Repository: stackotter/delta-client Branch: main Commit: 70cd0ed48c67 Files: 754 Total size: 1.6 MB Directory structure: gitextract_hv9a6jeo/ ├── .editorconfig ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.md │ │ └── feature_request.md │ ├── pull_request_template.md │ └── workflows/ │ ├── build.yml │ ├── swiftlint.yml │ └── test.yml ├── .gitignore ├── .swift-format ├── .swiftlint.yml ├── AppIcon.icns ├── Bundler.toml ├── Contributing.md ├── LICENSE ├── Notes/ │ ├── Caching.md │ ├── ChunkPreparation.md │ ├── DebuggingDeadlocks.md │ ├── GUIRendering.md │ ├── PluginSystem.md │ ├── Readme.md │ └── RenderPipeline.md ├── Package.resolved ├── Package.swift ├── Readme.md ├── Roadmap.md ├── Security.md ├── Sources/ │ ├── Client/ │ │ ├── CommandLineArguments.swift │ │ ├── Components/ │ │ │ ├── AddressField.swift │ │ │ ├── ButtonStyles/ │ │ │ │ ├── DisabledButtonStyle.swift │ │ │ │ ├── PrimaryButtonStyle.swift │ │ │ │ └── SecondaryButtonStyle.swift │ │ │ ├── EditableList/ │ │ │ │ ├── EditableList.swift │ │ │ │ └── EditorView.swift │ │ │ ├── EmailField.swift │ │ │ ├── IconButton.swift │ │ │ ├── LegacyFormattedTextView.swift │ │ │ ├── OptionalNumberField.swift │ │ │ ├── PingIndicator.swift │ │ │ └── PixellatedBorder.swift │ │ ├── Config/ │ │ │ ├── Config.swift │ │ │ ├── ConfigError.swift │ │ │ └── ManagedConfig.swift │ │ ├── DeltaClientApp.swift │ │ ├── Discord/ │ │ │ ├── DiscordManager.swift │ │ │ └── DiscordPresenceState.swift │ │ ├── Extensions/ │ │ │ ├── Binding+onChange.swift │ │ │ ├── Box+ObservableObject.swift │ │ │ ├── TaskProgress+ObservableObject.swift │ │ │ └── View.swift │ │ ├── GitHub/ │ │ │ ├── GitHubBranch.swift │ │ │ ├── GitHubCommit.swift │ │ │ ├── GitHubComparison.swift │ │ │ └── GitHubReleasesAPIResponse.swift │ │ ├── Input/ │ │ │ ├── Controller.swift │ │ │ ├── ControllerHub.swift │ │ │ └── InputMethod.swift │ │ ├── Logger.swift │ │ ├── Modal.swift │ │ ├── State/ │ │ │ ├── AppState.swift │ │ │ └── StateWrapper.swift │ │ ├── StorageDirectory.swift │ │ ├── Utility/ │ │ │ ├── Clipboard.swift │ │ │ ├── Updater.swift │ │ │ └── Utils.swift │ │ ├── Views/ │ │ │ ├── Play/ │ │ │ │ ├── DirectConnectView.swift │ │ │ │ ├── GameView.swift │ │ │ │ ├── InGameMenu.swift │ │ │ │ ├── InputView.swift │ │ │ │ ├── JoinServerAndThen.swift │ │ │ │ ├── MetalView.swift │ │ │ │ ├── PlayView.swift │ │ │ │ ├── SelectAccountAndThen.swift │ │ │ │ ├── SelectInputMethodAndThen.swift │ │ │ │ ├── SelectOption.swift │ │ │ │ ├── WithController.swift │ │ │ │ ├── WithRenderCoordinator.swift │ │ │ │ └── WithSelectedAccount.swift │ │ │ ├── RouterView.swift │ │ │ ├── ServerList/ │ │ │ │ ├── LANServerList.swift │ │ │ │ ├── ServerDetail.swift │ │ │ │ ├── ServerListItem.swift │ │ │ │ └── ServerListView.swift │ │ │ ├── Settings/ │ │ │ │ ├── Account/ │ │ │ │ │ ├── AccountLoginView.swift │ │ │ │ │ ├── AccountSettingsView.swift │ │ │ │ │ ├── MicrosoftLoginView.swift │ │ │ │ │ ├── MojangLoginView.swift │ │ │ │ │ └── OfflineLoginView.swift │ │ │ │ ├── ControlsSettingsView.swift │ │ │ │ ├── KeymapEditorView.swift │ │ │ │ ├── PluginSettingsView.swift │ │ │ │ ├── Server/ │ │ │ │ │ ├── EditServerListView.swift │ │ │ │ │ └── ServerEditorView.swift │ │ │ │ ├── SettingsView.swift │ │ │ │ ├── TroubleShootingView.swift │ │ │ │ ├── UpdateView.swift │ │ │ │ └── VideoSettingsView.swift │ │ │ └── Startup/ │ │ │ ├── LoadAndThen.swift │ │ │ ├── ProgressLoadingView.swift │ │ │ └── StartupStep.swift │ │ └── main.swift │ ├── ClientGtk/ │ │ ├── ChatView.swift │ │ ├── DeltaClientApp.swift │ │ ├── GameView.swift │ │ ├── ServerListView.swift │ │ ├── Settings/ │ │ │ ├── AccountInspectionView.swift │ │ │ ├── AccountListView.swift │ │ │ ├── MicrosoftLoginView.swift │ │ │ ├── OfflineLoginView.swift │ │ │ └── SettingsView.swift │ │ └── Storage/ │ │ ├── Config.swift │ │ ├── ConfigError.swift │ │ ├── ConfigManager.swift │ │ └── StorageManager.swift │ ├── Core/ │ │ ├── Logger/ │ │ │ └── Logger.swift │ │ ├── Package.resolved │ │ ├── Package.swift │ │ ├── Renderer/ │ │ │ ├── Camera/ │ │ │ │ ├── Camera.swift │ │ │ │ └── Frustum.swift │ │ │ ├── CameraUniforms.swift │ │ │ ├── CaptureState.swift │ │ │ ├── CelestialBodyUniforms.swift │ │ │ ├── ChunkUniforms.swift │ │ │ ├── EndSkyUniforms.swift │ │ │ ├── EndSkyVertex.swift │ │ │ ├── Entity/ │ │ │ │ ├── EntityRenderer.swift │ │ │ │ └── EntityVertex.swift │ │ │ ├── EntityUniforms.swift │ │ │ ├── FogUniforms.swift │ │ │ ├── GUI/ │ │ │ │ ├── GUIContext.swift │ │ │ │ ├── GUIElementMesh.swift │ │ │ │ ├── GUIElementMeshArray.swift │ │ │ │ ├── GUIElementUniforms.swift │ │ │ │ ├── GUIQuad.swift │ │ │ │ ├── GUIRenderer.swift │ │ │ │ ├── GUIRendererError.swift │ │ │ │ ├── GUIUniforms.swift │ │ │ │ ├── GUIVertex.swift │ │ │ │ ├── GUIVertexStorage.swift │ │ │ │ ├── TextMeshBuilder.swift │ │ │ │ └── TextMeshBuilderError.swift │ │ │ ├── Logger.swift │ │ │ ├── Mesh/ │ │ │ │ ├── BlockMeshBuilder.swift │ │ │ │ ├── BlockNeighbour.swift │ │ │ │ ├── ChunkSectionMesh.swift │ │ │ │ ├── ChunkSectionMeshBuilder.swift │ │ │ │ ├── CubeGeometry.swift │ │ │ │ ├── EntityMeshBuilder.swift │ │ │ │ ├── FluidMeshBuilder.swift │ │ │ │ ├── Geometry.swift │ │ │ │ ├── Mesh.swift │ │ │ │ ├── SortableMesh.swift │ │ │ │ └── SortableMeshElement.swift │ │ │ ├── RenderCoordinator.swift │ │ │ ├── RenderError.swift │ │ │ ├── Renderer.swift │ │ │ ├── RenderingMeasurement.swift │ │ │ ├── Resources/ │ │ │ │ ├── Font+Metal.swift │ │ │ │ └── MetalTexturePalette.swift │ │ │ ├── ScreenRenderer.swift │ │ │ ├── Shader/ │ │ │ │ ├── ChunkOITShaders.metal │ │ │ │ ├── ChunkShaders.metal │ │ │ │ ├── ChunkTypes.metal │ │ │ │ ├── EntityShaders.metal │ │ │ │ ├── GUIShaders.metal │ │ │ │ ├── GUITypes.metal │ │ │ │ ├── ScreenShaders.metal │ │ │ │ └── SkyShaders.metal │ │ │ ├── SkyBoxRenderer.swift │ │ │ ├── SkyPlaneUniforms.swift │ │ │ ├── StarUniforms.swift │ │ │ ├── SunriseDiscUniforms.swift │ │ │ ├── Util/ │ │ │ │ └── MetalUtil.swift │ │ │ └── World/ │ │ │ ├── BlockVertex.swift │ │ │ ├── LightMap.swift │ │ │ ├── Visibility/ │ │ │ │ ├── ChunkSectionFace.swift │ │ │ │ ├── ChunkSectionFaceConnectivity.swift │ │ │ │ ├── ChunkSectionVoxelGraph.swift │ │ │ │ ├── VisibilityGraph+SearchQueueEntry.swift │ │ │ │ └── VisibilityGraph.swift │ │ │ ├── WorldMesh.swift │ │ │ ├── WorldMeshWorker+Job.swift │ │ │ ├── WorldMeshWorker.swift │ │ │ └── WorldRenderer.swift │ │ ├── Sources/ │ │ │ ├── Account/ │ │ │ │ ├── Account.swift │ │ │ │ ├── Microsoft/ │ │ │ │ │ ├── MicrosoftAPI.swift │ │ │ │ │ ├── MicrosoftAccessToken.swift │ │ │ │ │ ├── MicrosoftAccount.swift │ │ │ │ │ ├── Request/ │ │ │ │ │ │ ├── MinecraftXboxAuthenticationRequest.swift │ │ │ │ │ │ ├── XSTSAuthenticationRequest.swift │ │ │ │ │ │ └── XboxLiveAuthenticationRequest.swift │ │ │ │ │ ├── Response/ │ │ │ │ │ │ ├── GameOwnershipResponse.swift │ │ │ │ │ │ ├── MicrosoftAccessTokenResponse.swift │ │ │ │ │ │ ├── MicrosoftDeviceAuthorizationResponse.swift │ │ │ │ │ │ ├── MicrosoftMinecraftProfileResponse.swift │ │ │ │ │ │ ├── MinecraftXboxAuthenticationResponse.swift │ │ │ │ │ │ ├── XSTSAuthenticationError.swift │ │ │ │ │ │ ├── XSTSAuthenticationResponse.swift │ │ │ │ │ │ └── XboxLiveAuthenticationResponse.swift │ │ │ │ │ └── XboxLiveToken.swift │ │ │ │ ├── MinecraftAccessToken.swift │ │ │ │ ├── Mojang/ │ │ │ │ │ ├── MojangAPI.swift │ │ │ │ │ ├── MojangAccount.swift │ │ │ │ │ ├── Request/ │ │ │ │ │ │ ├── MojangAuthenticationRequest.swift │ │ │ │ │ │ ├── MojangJoinRequest.swift │ │ │ │ │ │ └── MojangRefreshTokenRequest.swift │ │ │ │ │ └── Response/ │ │ │ │ │ ├── MojangAuthenticationResponse.swift │ │ │ │ │ └── MojangRefreshTokenResponse.swift │ │ │ │ ├── OfflineAccount.swift │ │ │ │ └── OnlineAccount.swift │ │ │ ├── Cache/ │ │ │ │ ├── BinaryCacheable.swift │ │ │ │ ├── BinarySerialization.swift │ │ │ │ ├── BlockModelPalette+BinaryCacheable.swift │ │ │ │ ├── Cacheable.swift │ │ │ │ ├── FontPalette+BinaryCacheable.swift │ │ │ │ ├── ItemModelPalette+BinaryCacheable.swift │ │ │ │ ├── Registry/ │ │ │ │ │ ├── BiomeRegistry+JSONCacheable.swift │ │ │ │ │ ├── BlockRegistry+BinaryCacheable.swift │ │ │ │ │ ├── EntityRegistry+JSONCacheable.swift │ │ │ │ │ ├── FluidRegistry+JSONCacheable.swift │ │ │ │ │ ├── ItemRegistry+JSONCacheable.swift │ │ │ │ │ └── JSONCacheable.swift │ │ │ │ └── TexturePalette+BinaryCacheable.swift │ │ │ ├── Chat/ │ │ │ │ ├── Chat.swift │ │ │ │ ├── ChatComponent/ │ │ │ │ │ ├── ChatComponent.swift │ │ │ │ │ ├── ChatComponentColor.swift │ │ │ │ │ ├── ChatComponentContent.swift │ │ │ │ │ ├── ChatComponentError.swift │ │ │ │ │ ├── ChatComponentLocalizedContent.swift │ │ │ │ │ ├── ChatComponentScoreContent.swift │ │ │ │ │ └── ChatComponentStyle.swift │ │ │ │ ├── ChatMessage.swift │ │ │ │ └── LegacyFormattedText/ │ │ │ │ ├── LegacyFormattedText.swift │ │ │ │ ├── LegacyFormattedTextColor.swift │ │ │ │ ├── LegacyFormattedTextError.swift │ │ │ │ ├── LegacyFormattedTextFormattingCode.swift │ │ │ │ ├── LegacyFormattedTextStyle.swift │ │ │ │ └── LegacyFormattedTextToken.swift │ │ │ ├── Client.swift │ │ │ ├── ClientConfiguration.swift │ │ │ ├── Constants.swift │ │ │ ├── Datatypes/ │ │ │ │ ├── Axis.swift │ │ │ │ ├── BlockPosition.swift │ │ │ │ ├── CardinalDirection.swift │ │ │ │ ├── Difficulty.swift │ │ │ │ ├── Direction.swift │ │ │ │ ├── DirectionSet.swift │ │ │ │ ├── DominantHand.swift │ │ │ │ ├── Equipment.swift │ │ │ │ ├── Gamemode.swift │ │ │ │ ├── Hand.swift │ │ │ │ ├── Identifier.swift │ │ │ │ ├── IdentifierError.swift │ │ │ │ ├── ItemStack.swift │ │ │ │ ├── NBT/ │ │ │ │ │ ├── NBT.swift │ │ │ │ │ ├── NBTCompound.swift │ │ │ │ │ ├── NBTList.swift │ │ │ │ │ ├── NBTTag.swift │ │ │ │ │ └── NBTTagType.swift │ │ │ │ ├── PlayerEntityAction.swift │ │ │ │ ├── PlayerFlags.swift │ │ │ │ ├── Slot.swift │ │ │ │ ├── Statistic.swift │ │ │ │ └── UUID.swift │ │ │ ├── Duration.swift │ │ │ ├── ECS/ │ │ │ │ ├── BlockEntity.swift │ │ │ │ ├── Components/ │ │ │ │ │ ├── EnderDragonParts.swift │ │ │ │ │ ├── EntityAcceleration.swift │ │ │ │ │ ├── EntityAttributes.swift │ │ │ │ │ ├── EntityCamera.swift │ │ │ │ │ ├── EntityExperience.swift │ │ │ │ │ ├── EntityFlying.swift │ │ │ │ │ ├── EntityHeadYaw.swift │ │ │ │ │ ├── EntityHealth.swift │ │ │ │ │ ├── EntityHitBox.swift │ │ │ │ │ ├── EntityId.swift │ │ │ │ │ ├── EntityKindId.swift │ │ │ │ │ ├── EntityLerpState.swift │ │ │ │ │ ├── EntityMetadata.swift │ │ │ │ │ ├── EntityNutrition.swift │ │ │ │ │ ├── EntityOnGround.swift │ │ │ │ │ ├── EntityPosition.swift │ │ │ │ │ ├── EntityRotation.swift │ │ │ │ │ ├── EntitySneaking.swift │ │ │ │ │ ├── EntitySprinting.swift │ │ │ │ │ ├── EntityUUID.swift │ │ │ │ │ ├── EntityVelocity.swift │ │ │ │ │ ├── Marker/ │ │ │ │ │ │ ├── ClientPlayerEntity.swift │ │ │ │ │ │ ├── LivingEntity.swift │ │ │ │ │ │ ├── NonLivingEntity.swift │ │ │ │ │ │ └── PlayerEntity.swift │ │ │ │ │ ├── ObjectData.swift │ │ │ │ │ ├── ObjectUUID.swift │ │ │ │ │ ├── PlayerAttributes.swift │ │ │ │ │ ├── PlayerCollisionState.swift │ │ │ │ │ ├── PlayerFOV.swift │ │ │ │ │ ├── PlayerGamemode.swift │ │ │ │ │ └── PlayerInventory.swift │ │ │ │ ├── Singles/ │ │ │ │ │ ├── ClientboundEntityPacketStore.swift │ │ │ │ │ ├── GUIStateStorage.swift │ │ │ │ │ └── InputState.swift │ │ │ │ └── Systems/ │ │ │ │ ├── EntityMovementSystem.swift │ │ │ │ ├── EntitySmoothingSystem.swift │ │ │ │ ├── PacketHandlingSystem.swift │ │ │ │ ├── PlayerAccelerationSystem.swift │ │ │ │ ├── PlayerBlockBreakingSystem.swift │ │ │ │ ├── PlayerClimbSystem.swift │ │ │ │ ├── PlayerCollisionSystem.swift │ │ │ │ ├── PlayerFOVSystem.swift │ │ │ │ ├── PlayerFlightSystem.swift │ │ │ │ ├── PlayerFrictionSystem.swift │ │ │ │ ├── PlayerGravitySystem.swift │ │ │ │ ├── PlayerInputSystem.swift │ │ │ │ ├── PlayerJumpSystem.swift │ │ │ │ ├── PlayerPacketSystem.swift │ │ │ │ ├── PlayerPositionSystem.swift │ │ │ │ ├── PlayerSmoothingSystem.swift │ │ │ │ ├── PlayerVelocitySystem.swift │ │ │ │ └── System.swift │ │ │ ├── FileSystem.swift │ │ │ ├── GUI/ │ │ │ │ ├── BossBar.swift │ │ │ │ ├── Constraints.swift │ │ │ │ ├── GUIBuilder.swift │ │ │ │ ├── GUIElement.swift │ │ │ │ ├── GUISprite.swift │ │ │ │ ├── GUISpriteDescriptor.swift │ │ │ │ ├── HorizontalConstraint.swift │ │ │ │ ├── HorizontalOffset.swift │ │ │ │ ├── InGameGUI.swift │ │ │ │ ├── RenderStatistics.swift │ │ │ │ ├── VerticalConstraint.swift │ │ │ │ ├── VerticalOffset.swift │ │ │ │ ├── Window.swift │ │ │ │ ├── WindowArea.swift │ │ │ │ └── WindowType.swift │ │ │ ├── GUIState.swift │ │ │ ├── Game.swift │ │ │ ├── Input/ │ │ │ │ ├── Input.swift │ │ │ │ ├── Key.swift │ │ │ │ ├── Keymap.swift │ │ │ │ └── ModifierKey.swift │ │ │ ├── Logger.swift │ │ │ ├── Network/ │ │ │ │ ├── Cipher.swift │ │ │ │ ├── ConnectionState.swift │ │ │ │ ├── Endianness.swift │ │ │ │ ├── LANServerEnumerator.swift │ │ │ │ ├── Protocol/ │ │ │ │ │ ├── Buffer.swift │ │ │ │ │ ├── BufferError.swift │ │ │ │ │ ├── PacketRegistry.swift │ │ │ │ │ ├── PacketState.swift │ │ │ │ │ ├── Packets/ │ │ │ │ │ │ ├── ClientboundEntityPacket.swift │ │ │ │ │ │ ├── ClientboundPacket.swift │ │ │ │ │ │ ├── Handshaking/ │ │ │ │ │ │ │ └── Serverbound/ │ │ │ │ │ │ │ └── HandshakePacket.swift │ │ │ │ │ │ ├── Login/ │ │ │ │ │ │ │ ├── Clientbound/ │ │ │ │ │ │ │ │ ├── EncryptionRequestPacket.swift │ │ │ │ │ │ │ │ ├── LoginDisconnectPacket.swift │ │ │ │ │ │ │ │ ├── LoginPluginRequestPacket.swift │ │ │ │ │ │ │ │ ├── LoginSuccessPacket.swift │ │ │ │ │ │ │ │ └── SetCompressionPacket.swift │ │ │ │ │ │ │ └── Serverbound/ │ │ │ │ │ │ │ ├── EncryptionResponsePacket.swift │ │ │ │ │ │ │ ├── LoginPluginResponsePacket.swift │ │ │ │ │ │ │ └── LoginStartPacket.swift │ │ │ │ │ │ ├── PacketReader.swift │ │ │ │ │ │ ├── PacketReaderError.swift │ │ │ │ │ │ ├── PacketWriter.swift │ │ │ │ │ │ ├── Play/ │ │ │ │ │ │ │ ├── Clientbound/ │ │ │ │ │ │ │ │ ├── AcknowledgePlayerDiggingPacket.swift │ │ │ │ │ │ │ │ ├── AdvancementsPacket.swift │ │ │ │ │ │ │ │ ├── AttachEntityPacket.swift │ │ │ │ │ │ │ │ ├── BlockActionPacket.swift │ │ │ │ │ │ │ │ ├── BlockBreakAnimationPacket.swift │ │ │ │ │ │ │ │ ├── BlockChangePacket.swift │ │ │ │ │ │ │ │ ├── BlockEntityDataPacket.swift │ │ │ │ │ │ │ │ ├── BossBarPacket.swift │ │ │ │ │ │ │ │ ├── CameraPacket.swift │ │ │ │ │ │ │ │ ├── ChangeGameStatePacket.swift │ │ │ │ │ │ │ │ ├── ChatMessageClientboundPacket.swift │ │ │ │ │ │ │ │ ├── ChunkDataPacket.swift │ │ │ │ │ │ │ │ ├── CloseWindowClientboundPacket.swift │ │ │ │ │ │ │ │ ├── CollectItemPacket.swift │ │ │ │ │ │ │ │ ├── CombatEventPacket.swift │ │ │ │ │ │ │ │ ├── CraftRecipeResponsePacket.swift │ │ │ │ │ │ │ │ ├── DeclareCommandsPacket.swift │ │ │ │ │ │ │ │ ├── DeclareRecipesPacket.swift │ │ │ │ │ │ │ │ ├── DestroyEntitiesPacket.swift │ │ │ │ │ │ │ │ ├── DisplayScoreboardPacket.swift │ │ │ │ │ │ │ │ ├── EffectPacket.swift │ │ │ │ │ │ │ │ ├── EntityAnimationPacket.swift │ │ │ │ │ │ │ │ ├── EntityAttributesPacket.swift │ │ │ │ │ │ │ │ ├── EntityEffectPacket.swift │ │ │ │ │ │ │ │ ├── EntityEquipmentPacket.swift │ │ │ │ │ │ │ │ ├── EntityHeadLookPacket.swift │ │ │ │ │ │ │ │ ├── EntityMetadataPacket.swift │ │ │ │ │ │ │ │ ├── EntityMovementPacket.swift │ │ │ │ │ │ │ │ ├── EntityPositionAndRotationPacket.swift │ │ │ │ │ │ │ │ ├── EntityPositionPacket.swift │ │ │ │ │ │ │ │ ├── EntityRotationPacket.swift │ │ │ │ │ │ │ │ ├── EntitySoundEffectPacket.swift │ │ │ │ │ │ │ │ ├── EntityStatusPacket.swift │ │ │ │ │ │ │ │ ├── EntityTeleportPacket.swift │ │ │ │ │ │ │ │ ├── EntityVelocityPacket.swift │ │ │ │ │ │ │ │ ├── ExplosionPacket.swift │ │ │ │ │ │ │ │ ├── FacePlayerPacket.swift │ │ │ │ │ │ │ │ ├── HeldItemChangePacket.swift │ │ │ │ │ │ │ │ ├── JoinGamePacket.swift │ │ │ │ │ │ │ │ ├── KeepAliveClientboundPacket.swift │ │ │ │ │ │ │ │ ├── MapDataPacket.swift │ │ │ │ │ │ │ │ ├── MultiBlockUpdatePacket.swift │ │ │ │ │ │ │ │ ├── NBTQueryResponsePacket.swift │ │ │ │ │ │ │ │ ├── NamedSoundEffectPacket.swift │ │ │ │ │ │ │ │ ├── OpenBookPacket.swift │ │ │ │ │ │ │ │ ├── OpenHorseWindowPacket.swift │ │ │ │ │ │ │ │ ├── OpenSignEditorPacket.swift │ │ │ │ │ │ │ │ ├── OpenWindowPacket.swift │ │ │ │ │ │ │ │ ├── ParticlePacket.swift │ │ │ │ │ │ │ │ ├── PlayDisconnectPacket.swift │ │ │ │ │ │ │ │ ├── PlayerAbilitiesPacket.swift │ │ │ │ │ │ │ │ ├── PlayerInfoPacket.swift │ │ │ │ │ │ │ │ ├── PlayerListHeaderAndFooterPacket.swift │ │ │ │ │ │ │ │ ├── PlayerPositionAndLookClientboundPacket.swift │ │ │ │ │ │ │ │ ├── PluginMessagePacket.swift │ │ │ │ │ │ │ │ ├── RemoveEntityEffectPacket.swift │ │ │ │ │ │ │ │ ├── ResourcePackSendPacket.swift │ │ │ │ │ │ │ │ ├── RespawnPacket.swift │ │ │ │ │ │ │ │ ├── ScoreboardObjectivePacket.swift │ │ │ │ │ │ │ │ ├── SelectAdvancementTabPacket.swift │ │ │ │ │ │ │ │ ├── ServerDifficultyPacket.swift │ │ │ │ │ │ │ │ ├── SetCooldownPacket.swift │ │ │ │ │ │ │ │ ├── SetExperiencePacket.swift │ │ │ │ │ │ │ │ ├── SetPassengersPacket.swift │ │ │ │ │ │ │ │ ├── SetSlotPacket.swift │ │ │ │ │ │ │ │ ├── SoundEffectPacket.swift │ │ │ │ │ │ │ │ ├── SpawnEntityPacket.swift │ │ │ │ │ │ │ │ ├── SpawnExperienceOrbPacket.swift │ │ │ │ │ │ │ │ ├── SpawnLivingEntityPacket.swift │ │ │ │ │ │ │ │ ├── SpawnPaintingPacket.swift │ │ │ │ │ │ │ │ ├── SpawnPlayerPacket.swift │ │ │ │ │ │ │ │ ├── SpawnPositionPacket.swift │ │ │ │ │ │ │ │ ├── StatisticsPacket.swift │ │ │ │ │ │ │ │ ├── StopSoundPacket.swift │ │ │ │ │ │ │ │ ├── TabCompleteClientboundPacket.swift │ │ │ │ │ │ │ │ ├── TagsPacket.swift │ │ │ │ │ │ │ │ ├── TeamsPacket.swift │ │ │ │ │ │ │ │ ├── TimeUpdatePacket.swift │ │ │ │ │ │ │ │ ├── TitlePacket.swift │ │ │ │ │ │ │ │ ├── TradeListPacket.swift │ │ │ │ │ │ │ │ ├── UnloadChunkPacket.swift │ │ │ │ │ │ │ │ ├── UnlockRecipesPacket.swift │ │ │ │ │ │ │ │ ├── UpdateHealthPacket.swift │ │ │ │ │ │ │ │ ├── UpdateLightPacket.swift │ │ │ │ │ │ │ │ ├── UpdateScorePacket.swift │ │ │ │ │ │ │ │ ├── UpdateViewDistancePacket.swift │ │ │ │ │ │ │ │ ├── UpdateViewPositionPacket.swift │ │ │ │ │ │ │ │ ├── VehicleMoveClientboundPacket.swift │ │ │ │ │ │ │ │ ├── WindowConfirmationClientboundPacket.swift │ │ │ │ │ │ │ │ ├── WindowItemsPacket.swift │ │ │ │ │ │ │ │ ├── WindowPropertyPacket.swift │ │ │ │ │ │ │ │ └── WorldBorderPacket.swift │ │ │ │ │ │ │ └── Serverbound/ │ │ │ │ │ │ │ ├── AdvancementTabPacket.swift │ │ │ │ │ │ │ ├── AnimationServerboundPacket.swift │ │ │ │ │ │ │ ├── ChatMessageServerboundPacket.swift │ │ │ │ │ │ │ ├── ClickWindowButtonPacket.swift │ │ │ │ │ │ │ ├── ClickWindowPacket.swift │ │ │ │ │ │ │ ├── ClientSettingsPacket.swift │ │ │ │ │ │ │ ├── ClientStatusPacket.swift │ │ │ │ │ │ │ ├── CloseWindowServerboundPacket.swift │ │ │ │ │ │ │ ├── CraftRecipeRequestPacket.swift │ │ │ │ │ │ │ ├── CreativeInventoryActionPacket.swift │ │ │ │ │ │ │ ├── EditBookPacket.swift │ │ │ │ │ │ │ ├── EntityActionPacket.swift │ │ │ │ │ │ │ ├── GenerateStructurePacket.swift │ │ │ │ │ │ │ ├── HeldItemChangeServerboundPacket.swift │ │ │ │ │ │ │ ├── InteractEntityPacket.swift │ │ │ │ │ │ │ ├── KeepAliveServerboundPacket.swift │ │ │ │ │ │ │ ├── LockDifficultyPacket.swift │ │ │ │ │ │ │ ├── NameItemPacket.swift │ │ │ │ │ │ │ ├── PickItemPacket.swift │ │ │ │ │ │ │ ├── PlayerAbilitiesServerboundPacket.swift │ │ │ │ │ │ │ ├── PlayerBlockPlacementPacket.swift │ │ │ │ │ │ │ ├── PlayerDiggingPacket.swift │ │ │ │ │ │ │ ├── PlayerMovementPacket.swift │ │ │ │ │ │ │ ├── PlayerPositionAndRotationServerboundPacket.swift │ │ │ │ │ │ │ ├── PlayerPositionPacket.swift │ │ │ │ │ │ │ ├── PlayerRotationPacket.swift │ │ │ │ │ │ │ ├── PluginMessageServerboundPacket.swift │ │ │ │ │ │ │ ├── QueryBlockNBTPacket.swift │ │ │ │ │ │ │ ├── QueryEntityNBTPacket.swift │ │ │ │ │ │ │ ├── RecipeBookDataPacket.swift │ │ │ │ │ │ │ ├── ResourcePackStatusPacket.swift │ │ │ │ │ │ │ ├── SelectTradePacket.swift │ │ │ │ │ │ │ ├── SetBeaconEffectPacket.swift │ │ │ │ │ │ │ ├── SetDifficultyPacket.swift │ │ │ │ │ │ │ ├── SpectatePacket.swift │ │ │ │ │ │ │ ├── SteerBoatPacket.swift │ │ │ │ │ │ │ ├── SteerVehiclePacket.swift │ │ │ │ │ │ │ ├── TabCompleteServerboundPacket.swift │ │ │ │ │ │ │ ├── TeleportConfirmPacket.swift │ │ │ │ │ │ │ ├── UpdateCommandBlockMinecartPacket.swift │ │ │ │ │ │ │ ├── UpdateCommandBlockPacket.swift │ │ │ │ │ │ │ ├── UpdateJigsawBlockPacket.swift │ │ │ │ │ │ │ ├── UpdateSignPacket.swift │ │ │ │ │ │ │ ├── UpdateStructureBlockPacket.swift │ │ │ │ │ │ │ ├── UseItemPacket.swift │ │ │ │ │ │ │ ├── VehicleMoveServerboundPacket.swift │ │ │ │ │ │ │ └── WindowConfirmationServerboundPacket.swift │ │ │ │ │ │ ├── ServerboundPacket.swift │ │ │ │ │ │ └── Status/ │ │ │ │ │ │ ├── Clientbound/ │ │ │ │ │ │ │ ├── PongPacket.swift │ │ │ │ │ │ │ └── StatusResponsePacket.swift │ │ │ │ │ │ └── Serverbound/ │ │ │ │ │ │ ├── PingPacket.swift │ │ │ │ │ │ └── StatusRequestPacket.swift │ │ │ │ │ └── ProtocolVersion.swift │ │ │ │ ├── ServerConnection.swift │ │ │ │ ├── Socket+Darwin.swift │ │ │ │ ├── Socket+Glibc.swift │ │ │ │ ├── Socket.swift │ │ │ │ ├── SocketError.swift │ │ │ │ ├── SocketOption.swift │ │ │ │ └── Stack/ │ │ │ │ ├── Layers/ │ │ │ │ │ ├── CompressionLayer.swift │ │ │ │ │ ├── EncryptionLayer.swift │ │ │ │ │ ├── PacketLayer.swift │ │ │ │ │ └── SocketLayer.swift │ │ │ │ └── NetworkStack.swift │ │ │ ├── Physics/ │ │ │ │ ├── AxisAlignedBoundingBox.swift │ │ │ │ ├── CompoundBoundingBox.swift │ │ │ │ ├── PhysicsConstants.swift │ │ │ │ ├── Ray.swift │ │ │ │ └── VoxelRay.swift │ │ │ ├── Player/ │ │ │ │ ├── Player.swift │ │ │ │ ├── PlayerInfo.swift │ │ │ │ └── PlayerProperty.swift │ │ │ ├── Plugin/ │ │ │ │ ├── Event/ │ │ │ │ │ ├── CaptureCursorEvent.swift │ │ │ │ │ ├── ChatMessageReceivedEvent.swift │ │ │ │ │ ├── Connection/ │ │ │ │ │ │ ├── ConnectionFailedEvent.swift │ │ │ │ │ │ ├── ConnectionReadyEvent.swift │ │ │ │ │ │ ├── LoginDisconnectEvent.swift │ │ │ │ │ │ ├── LoginStartEvent.swift │ │ │ │ │ │ ├── LoginSuccessEvent.swift │ │ │ │ │ │ ├── PacketDecodingErrorEvent.swift │ │ │ │ │ │ ├── PacketHandlingErrorEvent.swift │ │ │ │ │ │ └── PlayDisconnectEvent.swift │ │ │ │ │ ├── ErrorEvent.swift │ │ │ │ │ ├── Event.swift │ │ │ │ │ ├── EventBus.swift │ │ │ │ │ ├── Input/ │ │ │ │ │ │ ├── KeyPressEvent.swift │ │ │ │ │ │ ├── KeyReleaseEvent.swift │ │ │ │ │ │ ├── OpenInGameMenuEvent.swift │ │ │ │ │ │ └── ReleaseCursorEvent.swift │ │ │ │ │ ├── Render/ │ │ │ │ │ │ └── FinishFrameCaptureEvent.swift │ │ │ │ │ └── World/ │ │ │ │ │ ├── AddChunk.swift │ │ │ │ │ ├── JoinWorldEvent.swift │ │ │ │ │ ├── MultiBlockUpdate.swift │ │ │ │ │ ├── RemoveChunk.swift │ │ │ │ │ ├── SingleBlockUpdate.swift │ │ │ │ │ ├── TerrainDownloadCompletionEvent.swift │ │ │ │ │ ├── TimeUpdate.swift │ │ │ │ │ ├── UpdateChunk.swift │ │ │ │ │ ├── UpdateChunkLighting.swift │ │ │ │ │ └── WorldEvent.swift │ │ │ │ ├── Plugin.swift │ │ │ │ ├── PluginBuilder.swift │ │ │ │ ├── PluginEnvironment.swift │ │ │ │ ├── PluginLoadingError.swift │ │ │ │ └── PluginManifest.swift │ │ │ ├── Recipe/ │ │ │ │ ├── BlastingRecipe.swift │ │ │ │ ├── CampfireCookingRecipe.swift │ │ │ │ ├── CraftingRecipe.swift │ │ │ │ ├── CraftingShaped.swift │ │ │ │ ├── CraftingShapeless.swift │ │ │ │ ├── HeatRecipe.swift │ │ │ │ ├── Ingredient.swift │ │ │ │ ├── RecipeItem.swift │ │ │ │ ├── RecipeRegistry.swift │ │ │ │ ├── SmeltingRecipe.swift │ │ │ │ ├── SmithingRecipe.swift │ │ │ │ ├── SmokingRecipe.swift │ │ │ │ ├── SpecialCrafting/ │ │ │ │ │ ├── ArmorDyeRecipe.swift │ │ │ │ │ ├── BannerAddPatternRecipe.swift │ │ │ │ │ ├── BannerDuplicateRecipe.swift │ │ │ │ │ ├── BookCloningRecipe.swift │ │ │ │ │ ├── FireworkRocketRecipe.swift │ │ │ │ │ ├── FireworkStarFadeRecipe.swift │ │ │ │ │ ├── FireworkStarRecipe.swift │ │ │ │ │ ├── MapCloningRecipe.swift │ │ │ │ │ ├── MapExtendingRecipe.swift │ │ │ │ │ ├── RepairItemRecipe.swift │ │ │ │ │ ├── ShieldDecorationRecipe.swift │ │ │ │ │ ├── ShulkerBoxColouringRecipe.swift │ │ │ │ │ ├── SpecialRecipe.swift │ │ │ │ │ ├── SuspiciousStewRecipe.swift │ │ │ │ │ └── TippedArrowRecipe.swift │ │ │ │ └── StonecuttingRecipe.swift │ │ │ ├── Registry/ │ │ │ │ ├── Biome/ │ │ │ │ │ ├── Biome.swift │ │ │ │ │ ├── BiomeCategory.swift │ │ │ │ │ ├── BiomeCriteria.swift │ │ │ │ │ ├── BiomeModifiers.swift │ │ │ │ │ └── BiomePrecipitationType.swift │ │ │ │ ├── BiomeRegistry.swift │ │ │ │ ├── Block/ │ │ │ │ │ ├── Block.swift │ │ │ │ │ ├── BlockLightMaterial.swift │ │ │ │ │ ├── BlockOffset.swift │ │ │ │ │ ├── BlockPhysicalMaterial.swift │ │ │ │ │ ├── BlockShape.swift │ │ │ │ │ ├── BlockSoundMaterial.swift │ │ │ │ │ ├── BlockStateProperties.swift │ │ │ │ │ └── BlockTint.swift │ │ │ │ ├── BlockRegistry.swift │ │ │ │ ├── Entity/ │ │ │ │ │ ├── EntityAttributeKey.swift │ │ │ │ │ ├── EntityAttributeModifier.swift │ │ │ │ │ ├── EntityAttributeValue.swift │ │ │ │ │ └── EntityKind.swift │ │ │ │ ├── EntityRegistry.swift │ │ │ │ ├── Fluid/ │ │ │ │ │ ├── Fluid.swift │ │ │ │ │ └── FluidState.swift │ │ │ │ ├── FluidRegistry.swift │ │ │ │ ├── Item/ │ │ │ │ │ ├── Item.swift │ │ │ │ │ └── ItemRarity.swift │ │ │ │ ├── ItemRegistry.swift │ │ │ │ ├── Pixlyzer/ │ │ │ │ │ ├── PixlyzerAABB.swift │ │ │ │ │ ├── PixlyzerBiome.swift │ │ │ │ │ ├── PixlyzerBlock.swift │ │ │ │ │ ├── PixlyzerBlockModelDescriptor.swift │ │ │ │ │ ├── PixlyzerBlockState.swift │ │ │ │ │ ├── PixlyzerEntity.swift │ │ │ │ │ ├── PixlyzerFluid.swift │ │ │ │ │ ├── PixlyzerFormatter.swift │ │ │ │ │ ├── PixlyzerItem.swift │ │ │ │ │ ├── PixlyzerShapeRegistry.swift │ │ │ │ │ └── SingleOrMultiple.swift │ │ │ │ └── RegistryStore.swift │ │ │ ├── RenderConfiguration.swift │ │ │ ├── RenderMode.swift │ │ │ ├── Resources/ │ │ │ │ ├── Biome/ │ │ │ │ │ ├── BiomeColorMap.swift │ │ │ │ │ └── BiomeColors.swift │ │ │ │ ├── Font/ │ │ │ │ │ ├── BitmapFontProvider.swift │ │ │ │ │ ├── CharacterDescriptor.swift │ │ │ │ │ ├── Font.swift │ │ │ │ │ ├── FontManifest.swift │ │ │ │ │ ├── FontPalette.swift │ │ │ │ │ ├── FontProvider.swift │ │ │ │ │ ├── LegacyUnicodeFontProvider.swift │ │ │ │ │ └── TrueTypeFontProvider.swift │ │ │ │ ├── GUI/ │ │ │ │ │ ├── GUITexturePalette.swift │ │ │ │ │ └── GUITextureSlice.swift │ │ │ │ ├── Locale/ │ │ │ │ │ ├── LocalizationFormatter.swift │ │ │ │ │ └── MinecraftLocale.swift │ │ │ │ ├── MCMeta/ │ │ │ │ │ ├── AnimationMCMeta.swift │ │ │ │ │ └── PackMCMeta.swift │ │ │ │ ├── Manifest/ │ │ │ │ │ ├── VersionManifest.swift │ │ │ │ │ └── VersionsManifest.swift │ │ │ │ ├── Model/ │ │ │ │ │ ├── Block/ │ │ │ │ │ │ ├── BlockModel.swift │ │ │ │ │ │ ├── BlockModelElement.swift │ │ │ │ │ │ ├── BlockModelFace.swift │ │ │ │ │ │ ├── BlockModelPalette.swift │ │ │ │ │ │ ├── BlockModelPaletteError.swift │ │ │ │ │ │ ├── BlockModelPart.swift │ │ │ │ │ │ ├── BlockModelRenderDescriptor.swift │ │ │ │ │ │ ├── Intermediate/ │ │ │ │ │ │ │ ├── IntermediateBlockModel.swift │ │ │ │ │ │ │ ├── IntermediateBlockModelElement.swift │ │ │ │ │ │ │ ├── IntermediateBlockModelElementRotation.swift │ │ │ │ │ │ │ ├── IntermediateBlockModelFace.swift │ │ │ │ │ │ │ └── IntermediateBlockModelPalette.swift │ │ │ │ │ │ └── JSON/ │ │ │ │ │ │ ├── JSONBlockModel.swift │ │ │ │ │ │ ├── JSONBlockModelAxis.swift │ │ │ │ │ │ ├── JSONBlockModelElement.swift │ │ │ │ │ │ ├── JSONBlockModelElementRotation.swift │ │ │ │ │ │ ├── JSONBlockModelFace.swift │ │ │ │ │ │ └── JSONBlockModelFaceName.swift │ │ │ │ │ ├── Entity/ │ │ │ │ │ │ ├── EntityModelPalette.swift │ │ │ │ │ │ └── JSON/ │ │ │ │ │ │ └── JSONEntityModel.swift │ │ │ │ │ ├── Item/ │ │ │ │ │ │ ├── ItemModel.swift │ │ │ │ │ │ ├── ItemModelPalette.swift │ │ │ │ │ │ ├── ItemModelPaletteError.swift │ │ │ │ │ │ ├── ItemModelTexture.swift │ │ │ │ │ │ └── JSON/ │ │ │ │ │ │ ├── JSONItemModel.swift │ │ │ │ │ │ ├── JSONItemModelGUILight.swift │ │ │ │ │ │ └── JSONItemModelOverride.swift │ │ │ │ │ ├── JSON/ │ │ │ │ │ │ ├── JSONModelDisplayTransforms.swift │ │ │ │ │ │ └── JSONModelTransform.swift │ │ │ │ │ └── ModelDisplayTransforms.swift │ │ │ │ ├── ResourcePack.swift │ │ │ │ ├── Resources.swift │ │ │ │ └── Texture/ │ │ │ │ ├── ColorMap.swift │ │ │ │ ├── Texture.swift │ │ │ │ ├── TextureAnimation.swift │ │ │ │ ├── TextureAnimationState.swift │ │ │ │ ├── TexturePalette.swift │ │ │ │ ├── TexturePaletteAnimationState.swift │ │ │ │ └── TextureType.swift │ │ │ ├── Server/ │ │ │ │ ├── Ping/ │ │ │ │ │ ├── PingError.swift │ │ │ │ │ ├── Pinger.swift │ │ │ │ │ └── StatusResponse.swift │ │ │ │ ├── ServerDescriptor.swift │ │ │ │ └── TabList.swift │ │ │ ├── Util/ │ │ │ │ ├── Array.swift │ │ │ │ ├── ArrayBinding.swift │ │ │ │ ├── BinaryFloatingPoint.swift │ │ │ │ ├── BinaryUtil.swift │ │ │ │ ├── Box.swift │ │ │ │ ├── Character.swift │ │ │ │ ├── ColorUtil.swift │ │ │ │ ├── CompressionUtil.swift │ │ │ │ ├── ContentType.swift │ │ │ │ ├── CryptoUtil.swift │ │ │ │ ├── CustomJSONDecoder.swift │ │ │ │ ├── Dictionary.swift │ │ │ │ ├── Either.swift │ │ │ │ ├── FileManager.swift │ │ │ │ ├── FontUtil.swift │ │ │ │ ├── FunctionalProgramming.swift │ │ │ │ ├── Image.swift │ │ │ │ ├── Int.swift │ │ │ │ ├── MathUtil.swift │ │ │ │ ├── Matrix.swift │ │ │ │ ├── MatrixUtil.swift │ │ │ │ ├── Profiler.swift │ │ │ │ ├── RGBColor.swift │ │ │ │ ├── Random.swift │ │ │ │ ├── ReadWriteLock.swift │ │ │ │ ├── Request.swift │ │ │ │ ├── RequestMethod.swift │ │ │ │ ├── RequestUtil.swift │ │ │ │ ├── RichError.swift │ │ │ │ ├── SIMD.swift │ │ │ │ ├── Stopwatch.swift │ │ │ │ ├── Task/ │ │ │ │ │ ├── TaskProgress.swift │ │ │ │ │ └── TaskStep.swift │ │ │ │ ├── ThreadUtil.swift │ │ │ │ ├── TickScheduler.swift │ │ │ │ ├── URL.swift │ │ │ │ └── Vector.swift │ │ │ └── World/ │ │ │ ├── BreakingBlock.swift │ │ │ ├── Chunk/ │ │ │ │ ├── Chunk.swift │ │ │ │ ├── ChunkNeighbours.swift │ │ │ │ ├── ChunkPosition.swift │ │ │ │ ├── ChunkSection.swift │ │ │ │ ├── ChunkSectionPosition.swift │ │ │ │ └── HeightMap.swift │ │ │ ├── DaylightCyclePhase.swift │ │ │ ├── Dimension/ │ │ │ │ └── Dimension.swift │ │ │ ├── Fog.swift │ │ │ ├── Light/ │ │ │ │ ├── ChunkLighting.swift │ │ │ │ ├── ChunkLightingUpdateData.swift │ │ │ │ ├── LightLevel.swift │ │ │ │ └── LightingEngine.swift │ │ │ ├── Targeted.swift │ │ │ ├── Thing.swift │ │ │ └── World.swift │ │ └── Tests/ │ │ └── DeltaCoreUnitTests/ │ │ ├── BufferTests.swift │ │ ├── ChatComponentTests.swift │ │ ├── IdentifierTests.swift │ │ ├── LegacyFormattedTextTests.swift │ │ └── LocalizationFormatterTests.swift │ └── Exporters/ │ ├── DynamicShim/ │ │ └── Exports.swift │ └── StaticShim/ │ └── Exports.swift ├── build.sh └── lint.sh ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ root = true [*] indent_style = space indent_size = 2 ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: stackotter ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug report about: Create a report to help us improve title: '' labels: bug assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Logs** If applicable, obtain the logs at `~/Library/Application Support/dev.stackotter.delta-client/logs/delta-client.log` and attach the relevant part here (probably the last few lines). This is made easy by the `View > Logs` menu bar item. **Screenshots** If applicable, add screenshots to help explain your problem. **Extra information (please complete the following information** - OS: [e.g. macOS 11.5.1] - Hardware: [e.g. M1 MacBook Air] - Build: [e.g. commit 060e29e or Snapshot 9] **Additional context** Add any other context about the problem here. ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Suggest an idea for this project title: '' labels: enhancement assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. ================================================ FILE: .github/pull_request_template.md ================================================ # Description Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. Fixes # (issue) (delete if these changes aren't for fixing an issue) ## Type of change Please delete options that are not relevant. - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] This change requires a documentation update # Checklist: - [ ] My code follows the style guidelines of this project - [ ] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation comments - [ ] My changes generate no new warnings ================================================ FILE: .github/workflows/build.yml ================================================ name: Build on: push: pull_request: workflow_dispatch: jobs: build-macos: runs-on: macOS-15 steps: - name: Checkout uses: actions/checkout@v6 - name: List Xcodes run: ls /Applications - name: Force Xcode 16.4 run: sudo xcode-select -switch /Applications/Xcode_16.4.app - name: Version run: swift --version - name: Cache swift-bundler id: cache-swift-bundler uses: actions/cache@v5 with: path: sbun key: ${{ runner.os }}-swift-bundler - name: Build swift-bundler if: steps.cache-swift-bundler.outputs.cache-hit != 'true' run: | git clone https://github.com/moreSwift/swift-bundler cd swift-bundler git checkout 6d72c4f442cc2c57c2559f3df21b3777b1d0a917 swift build --product swift-bundler cp .build/debug/swift-bundler ../sbun - name: Build arm64 run: | ./sbun bundle -c release --arch arm64 mv "$(./sbun bundle --show-bundle-path)" DeltaClient-arm64.app - name: Build x86 run: | ./sbun bundle -c release --arch x86_64 mv "$(./sbun bundle --show-bundle-path)" DeltaClient-x86_64.app - name: Zip .app (arm64) run: zip -r DeltaClient-arm64.zip DeltaClient-arm64.app - name: Zip .app (x86_64) run: zip -r DeltaClient-x86_64.zip DeltaClient-x86_64.app - name: Upload artifact (arm64) uses: actions/upload-artifact@v7 with: name: DeltaClient-arm64 path: ./DeltaClient-arm64.zip - name: Upload artifact (x86_64) uses: actions/upload-artifact@v7 with: name: DeltaClient-x86_64 path: ./DeltaClient-x86_64.zip build-linux: runs-on: ubuntu-latest steps: - name: Setup Swift uses: SwiftyLab/setup-swift@latest with: swift-version: "5.9" - name: Checkout uses: actions/checkout@v6 - name: Build run: | cd Sources/Core swift build ================================================ FILE: .github/workflows/swiftlint.yml ================================================ name: Lint on: push: pull_request: workflow_dispatch: jobs: swift-lint: runs-on: macOS-latest steps: - name: Checkout uses: actions/checkout@v6 - name: Lint run: | URL="https://github.com/realm/SwiftLint/releases/download/0.50.3/portable_swiftlint.zip" curl -LO "$URL" unzip portable_swiftlint -d ./swiftlint rm -rf portable_swiftlint.zip echo "Linting with swiftlint $(./swiftlint/swiftlint version)" ./swiftlint/swiftlint lint --reporter github-actions-logging shell: bash ================================================ FILE: .github/workflows/test.yml ================================================ name: Test on: push: pull_request: workflow_dispatch: jobs: test-macos: runs-on: macOS-15 steps: - name: Checkout uses: actions/checkout@v6 - name: Force Xcode 16.4 run: sudo xcode-select -switch /Applications/Xcode_16.4.app - name: Version run: swift --version - name: Test run: | cd Sources/Core swift test test-linux: runs-on: ubuntu-latest steps: - name: Setup Swift uses: SwiftyLab/setup-swift@latest with: swift-version: "5.9" - name: Checkout uses: actions/checkout@v6 - name: Test run: | cd Sources/Core swift test ================================================ FILE: .gitignore ================================================ .DS_Store .build .docc-build /Packages *.xcodeproj xcuserdata/ *.xcworkspace /DeltaClient.app /.swiftpm /.vscode .swiftpm /assets /cache /registry ================================================ FILE: .swift-format ================================================ { "version": 1, "indentation": { "spaces": 2 }, "indentSwitchCaseLabels": true } ================================================ FILE: .swiftlint.yml ================================================ excluded: - "**/.build" - "Sources/Core/Sources/Cache/Protobuf/Generated/BlockRegistry.pb.swift" - "Sources/Core/Sources/Cache/Protobuf/Generated/BlockModelPalette.pb.swift" # TODO: Reexclude once swiftlint github action is updated to support globs # - "**/*.pb.swift" disabled_rules: - switch_case_alignment - trailing_whitespace - identifier_name - opening_brace # Has false positives in the code base # TODO: Re-enable these rules later once more warnings are fixed - nesting - todo line_length: 160 type_body_length: 300 function_parameter_count: 8 file_length: 500 function_body_length: 50 cyclomatic_complexity: error: 40 # TODO: reset once more occurrences are fixed # Custom rules custom_rules: comments_space: # from https://github.com/brandenr/swiftlintconfig name: "Space After Comment" regex: '(^ *//\w+)' message: "There should be a space after //" severity: error # TODO: Once there are less warnings and violations, make the rules stricter and add some opt in ones ================================================ FILE: Bundler.toml ================================================ format_version = 2 [apps.DeltaClient] product = 'DeltaClient' version = 'v0.1.0-alpha.1' identifier = 'dev.stackotter.delta-client' category = 'public.app-category.games' icon = 'AppIcon.icns' [apps.DeltaClient.plist] # Append the current commit hash to the user-facing version string CFBundleShortVersionString = "$(VERSION), commit: $(COMMIT_HASH)" GCSupportsControllerUserInteraction = "True" MetalCaptureEnabled = true ================================================ FILE: Contributing.md ================================================ # Contributing Delta Client is completely open source and I welcome contributions of all kinds. If you're interested in contributing, you can checkout the [delta client issues](https://github.com/stackotter/delta-client/issues) and [delta client website issues](https://github.com/stackotter/delta-website) ( on GitHub for some tasks. Some of the tasks don't even require Swift! But before you get too excited, make sure that you've read the contributing guidelines, and make sure that your contributions follow them. If you need any help with a contribution, feel free to join the [Discord](https://discord.gg/xZPyDbmR6k) and chat :) Note: when you've decided on an issue to work on, please leave a comment on it so that everyone else knows not to work on it. ## Guidelines If your contributions follow these guidelines, they'll be much more likely to get accepted first try :thumbsup: 1. Make sure your indent size matches the repository (in the case of delta-client that's 2 spaces). 2. Be conscious of copyright and don't include any files distributed by Mojang in these repositories. 3. Be concise, only make changes that are required to achieve your end goal. The smaller your pull request, the faster I'll get around to reviewing it. 7. Add documentation comments for any methods or properties you create unless their usage is completely self-evident. Be sure to also document potentially unexpected side-effects or non-obvious requirements of methods. 4. Remove file headers from all files you create, they're unnecessary. `swift-bundler` will automatically remove them for you whenever you build. 5. Use `log` for logging (not just print statements everywhere). 6. If in doubt, consult [Google's Swift style guide](https://google.github.io/swift/#function-declarations) because that's the one I try to follow. ## Getting setup ### Delta Client **Important**: Only Xcode 14+ is supported, Xcode 12 builds don't work because Delta Client uses new automatic `Codable` conformance and there are some weird discrepancies between Xcode 12's swift compiler and Xcode 14+'s swift compiler. Xcode 13 isn't supported because it causes some weird memory corruption issues. [Delta Client](https://github.com/stackotter/delta-client) uses the [swift-bundler](https://github.com/stackotter/swift-bundler) build system so make sure you install that. You can use any ide you want to work on Delta Client (vscode and xcode are the best supported), but you'll need Xcode installed anyway because sadly that's currently the only way to get Metal and SwiftUI build support. Next, fork Delta Client and then clone it. ```sh git clone [url of your delta-client fork] cd delta-client ``` To run Delta Client, you can run `swift bundler run -c release`. If you are working on the UI you can leave out the `-c release`, it is only required when working with computationally intense parts of the client such as rendering, because without optimizations those parts of the client are unusable. See the [swift-bundler repo](https://github.com/stackotter/swift-bundler) for more commands and options. If you are using Xcode as your IDE run `swift bundler generate-xcode-support` and then open Package.swift with Xcode (`open Package.swift` should work unless you've changed your default program for opening swift files). **Make sure to choose the `DeltaClient` target in the top bar instead of the `DeltaClient-Package` target.** **Note: Xcode puts DeltaCore in the dependencies section of the file navigator instead of at its physical location in the directory structure. This is due to the way the plugin system had to be implemented.** You can now make changes and when you're done, just open a pull request on GitHub. ### Website The [website](https://delta.stackotter.dev) is built with svelte. Just follow these steps to get started; 1. Fork and clone [delta-website](https://github.com/stackotter/delta-website) 2. Run `npm i` 3. Run `npm run dev` to start a development server. Whenever you save changes to a file, the page will almost instantly reload with the changes, and most of the time it'll retain its state too (pretty cool) ================================================ FILE: LICENSE ================================================ ### GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. ### Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. ### TERMS AND CONDITIONS #### 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. #### 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. #### 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. #### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. #### 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. #### 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: - a) The work must carry prominent notices stating that you modified it, and giving a relevant date. - b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". - c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. - d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. #### 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: - a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. - b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. - c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. - d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. - e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. #### 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: - a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or - b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or - c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or - d) Limiting the use for publicity purposes of names of licensors or authors of the material; or - e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or - f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. #### 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. #### 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. #### 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. #### 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. #### 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. #### 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. #### 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. #### 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. #### 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #### 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS ### How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands \`show w' and \`show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: Notes/Caching.md ================================================ # Caching Delta Client uses caching to speed up launches by orders of magnitude. The only thing I cache at the moment are block models because these can take up to 30 seconds to load from the JSON model descriptors with my current method (optimisation attempts are very welcome). To decide which serialization technique to use I created a test project and implemented multiple methods of caching the vanilla block model palette. Below is my interpretation of the [results](#the-numbers); The first implementation was made using [Flatbuffers](https://github.com/google/flatbuffers) and the other was made using [Protobuf](https://github.com/protocolbuffers/protobuf). In release builds, Flatbuffers was faster at deserialization but slower than serialization. In this use case, deserialization performance is really the only thing we care about. To an end user only release build performance matters but when I'm developing the client, debug build performance greatly affects development speed. Interestingly, in debug builds, the fastest at serialization was Flatbuffers (by quite a bit), and Protobuf was over 3 times faster than Flatbuffers at deserialization. Now that I understood how Flatbuffers worked, I created an implementation that took a similar approach to my neater Protobuf-base implementation. This new Flatbuffers-based implementation was close enough to Protobuf deserialization speed in debug builds, and the serialization speed was pretty much the same as the original Flatbuffers-based implementation. However, in release builds deserialization speeds were now almost twice as slow as Protobuf and serialization speeds were also the slowest out of all three. Somehow, a change that almost doubled debug build performance significantly slowed down release performance? I have also previously tried out FastBinaryEncoding but it was quite a bit slower at deserialization (more like 2 seconds in release builds). To its credit, it did manage to encode it all into only 13mb which is pretty impressive. But that matters less than performance to me. ## The verdict For now I will be using Protobufs for caching because they are nicer to use and their performance is more consistent between debug and release builds. They also have the fastest debug build deserialization speed which is what I really care about right now, and the release build serialization speed wasn't too far off the fastest solution in the grand scheme of things. It also has the fastest release build serialization by far. It's only main downfall is that its debug build serialization speed is dismal. Oh, and It also had the smallest serialized size as an added bonus. ## The numbers ### Flatbuffers (with messy code) Serialized size: 21601644 bytes | Operation | Debug | Release | | ----------- | ------- | ------- | | Serialize | 17676ms | 2185ms | | Deserialize | 23190ms | 368ms | ### Flatbuffers, cleaner code Serialized size: 21601644 bytes | Operation | Debug | Release | | ----------- | ------- | ------- | | Serialize | 18661ms | 2601ms | | Deserialize | 11760ms | 972ms | ### Protobuf Serialized size: 16630993 bytes | Operation | Debug | Release | | ----------- | ------- | ------- | | Serialize | 29436ms | 1219ms | | Deserialize | 7490ms | 551ms | ## Sticky encoding [Sticky encoding](https://github.com/stickytools/sticky-encoding) looks quite enticing too so I tried it out. All it requires is adding Codable conformance to the types that need to be serialized. However, I tried it out and it's awfully slow (likely because of limitations of Swift's Codable implementation). In debug builds, both serialize and deserialize took over 50 seconds, and in release builds, serialize took around 14 seconds and deserialize took around 12 seconds. It would be nice to use such a nice solution, but it just can't meet our performance requirements. ## Custom binary serialization As an experiment, I have started implementing a custom serialization and deserialization API that uses the Minecraft network protocol's binary format behind the scenes. The initial implementation with no optimization was quite promisingsd. Given that I've gotten a new laptop and the block model format has changed a lot, here are the initial results including the new Protobuf and Flatbuffer times. I've removed `Flatbuffers (with messy code)` because it would've been too much work to reimplement it for the newer block model palette format, and realistically it's not how I would implement it in Delta Client because it's just too difficult to maintain. I will also not be testing debug build performance because that's not important to me anymore now that my laptop can demolish release builds and run debug builds at a reasonable speed. | Method & Operation | Release | | --------------------------- | ----------- | | Flatbuffers serialization | 470.42799ms | | Flatbuffers deserialization | 341.62700ms | | Protobuf serialization | 342.27204ms | | Protobuf deserialization | 181.43606ms | | Custom serialization | 54.83699ms | | Custom deserialization | 516.13605ms | The serialization speed is almost 7x faster than Protobuf! The order of magnitude difference between serialization and deserialization tells me that deserialization should have some pretty easy optimizations to make. | Method | Serialized size | | ----------- | --------------- | | Flatbuffers | 21472396 bytes | | Protobuf | 15105882 bytes | | Custom | 22136216 bytes | As you can see, the new custom method takes significantly more storage than Protobuf, and a tiny bit more than Flatbuffers, but this isn't very important to me because it's still only 22ish megabytes which is completely acceptable for a cache. ### Optimizing custom serialization and deserialization Using Xcode instruments, I found that the `uvs` property of `BlockModelFace` is the most expensive part of deserializing the block model palette. Optimizing the float decoding code path (which uses the fixed length integer decoding code path of `Buffer`) by rearranging code to avoid a call to `Array.reversed` managed to speed up deserialization by 1.7x (to 294.46900ms). Because `uvs` is so performance critical, I ended up using some unsafe pointer stuff to avoid unnecessary copies and byte reordering (caused by MC protocol). I basically just store the Float array's raw bytes in the cache directly because it's a fixed length array. This increased the deserialization speed by 2.09x (to 140.65397ms). This change also decreased the serialized size to 20229880 bytes (almost a 9% decrease). After some further optimization of `Buffer.readInteger(size:endianness:)` I managed to get another 2x deserialization speed improvement (down to 69.15092ms). I ended up deviating from the Minecraft protocol for integers to allow the use of unsafe pointers to decode them which gave another 1.23x increase in deserialization speed (down to 56.47790ms). Essentially I just store integers by copying their raw bytes so that while deserializing I can just get a pointer into the reader's buffer and cast it to a pointer to an integer. The next optimization gave a massive improvement by greatly simplifying the serialization and deserialization process for bitwise copyable types. These types can simply just have their raw bytes copied into the output and subsequently these bytes can be copied out as that type when deserializing (using unsafe pointer tricks). This gave another 1.52x improvement in deserialization speed (down to 37.13298ms). It also gave us our first big improvement in serialization speed of 1.3x (down to 38.87498ms). Given that `BlockModelFace` is the most performance critical part of serializing/deserializing the block model palette and it's technically a fixed amount of data, I decided to try making it a bitwise copyable type. All this involved was converting the fixed length array of `uvs` to a tuple-equivalent `struct`. I wasn't able to use a tuple because I needed `uvs` to be `Equatable` and tuples can't conform to protocols (how silly). After removing all use of indirection from `BlockModelFace` I was able to improve deserialization times by a factor of around 4.5 (to around 8.6ms). At this point, a large majority of the serialization time is allocations and appending to arrays. I tried using `Array.init(unsafeUninitializedCapacity:initializingWith:)` to avoid unnecessary allocations and append operations, however this ended up making the code slower. Either way, 8ms is definitely fast enough for this application :sweat_smile:. ### Results | Method & Operation | Release | | --------------------------- | ----------- | | Flatbuffers serialization | 470.42799ms | | Flatbuffers deserialization | 341.62700ms | | Protobuf serialization | 343.40799ms | | Protobuf deserialization | 181.43606ms | | Custom serialization | 50.11296ms | | Custom deserialization | 8.18300ms | Somewhere along the way I managed to reverse a majority of the progress that I made on serialization performance, but this is fine for my caching needs because cache generation shouldn't happen very often at all. | Method | Serialized size | | ----------- | --------------- | | Flatbuffers | 21472396 bytes | | Protobuf | 15105882 bytes | | Custom | 18839177 bytes | I'm not quite sure exactly what optimizations ended up decreasing the serialized so much for the custom serializer, but I guess it's a pleasant side effect! ### Conclusion I managed to create a custom binary serialization solution that is 22.2x faster at deserialization than Protobuf, 6.85x faster at serialization than Protobuf, and way more maintainable than an equivalent Protobuf-based caching system. Although I started out with the plan to use the Minecraft network protocol binary format to store the cache, I quickly realised that the Minecraft network protocol just isn't built for high performance serialization and deserialization. That's why I ended up just creating an approach that is essentially a fancy memdump that can handle indirection and complicated data structures. ### Aftermath I've implemented binary caching for the item model palette, block registry, font palette, and texture palettes (almost all of the expensive things to load). Overall this amounted to a 4x faster app launch time which is pretty amazing. The caching code is also way nicer than the old Protobuf stuff, and any optimization of BinarySerializable will basically have an effect on all of the expensive start up tasks making it a very appealing target. However, startup time is now 160ms (when files have been cached in memory by previous launches; it's around 200ms when they haven't been), so I don't think I need to put in any more work for now :sweat_smile:. ================================================ FILE: Notes/ChunkPreparation.md ================================================ # Chunk preparation optimisation Chunk mesh preparation is one of the prime areas of focus for optimisation efforts. Fast chunk loading is extremely important for that snappy feeling. There a few ideas for optimising chunk preparation that I have and here they are; ## Initial benchmarks I have created a swiftpm executable that can download specified chunks from a server and then save them to allow repeated consistent tests. This is what I will be evaluating performance gains with. I have gathered data on the time spent in each of the main high level tasks required when meshing each block and ordered them by which requires more attention (which ones take the longest). Initial measurements were of delta-core commit c9f0d1c6dab773802fd69bedf3675d0255fadf13. The chunk section being prepared is section -20 0 -14 in seed -6243685378508790499. 1. getCullingNeighbours: 0.0178ms, the longest task by far 2. getBlockModels: 0.0026ms, this one is surprising given it's just a quick lookup, perhaps this is why getCullingNeighbours is so slow 3. getNeighbourLightLevels: 0.0025ms 4. adding the block models to the mesh: 0.0010ms Total time: 102.8528ms ## Improving getCullingNeighbours getBlockModels was the main issue in this case, accessing the resources of a resource pack was super slow because of the use of a computed property called `vanillaResources` that took a stupidly large amount of time. First I tried changing the block models storage to use an array instead of a dictionary but there was no noticable performance difference. Fixing this issue made getCullingNeighbours 5x faster. 1. getCullingNeighbours: 0.0038ms, still the longest task 2. getNeighbourLightLevels: 0.0026ms 3. adding the block models to the mesh: 0.0011ms 4. getBlockModels: 0.0002ms, that's more like it New total time: 28.0777ms (3.7x faster than original) ## Improving getNeighbourLightLevels and getCullingNeighbours The second biggest bottleneck was calculating neighbour indices, lots of branching could be eliminated from this function I think but it would greatly complicate the logic of the function and make it massive. So instead of optimising the function I just calculate neighbour indices once instead of twice and pass them to both functions that require them. 1. getCullingNeighbours: 0.0025ms 2. getNeighbourLightLevels: 0.0016ms 3. getNeighbourIndices: 0.0012ms 4. add block models: 0.0010ms New total time: 22.8666ms (4.5x faster than original) ## Improving getNeighbourIndices Reserve capacity was the big winner here. Reserving a capacity of 6 won 0.0007ms (more than 2x faster). I also tried wrapping arithmetic (unchecked), but that didn't seem to make a noticable difference. Probably because the function is mostly bottlenecked by branching and collection operations. 1. getCullingNeighbours: 0.00253ms 2. getNeighbourLightLevels: 0.00160ms 3. getNeighbourIndices: 0.00055ms (more than 2x faster) 4. add block models: 0.00092ms ## Improving getNeighbourLightLevels I tried reserve capacity for this getting light levels and culling faces too and it made light levels more than 2x faster as well! Not such a big gain for getCullingNeighbours, but still like a 20% reduction. 1. getCullingNeighbours: 0.00208ms 2. add block models: 0.00096ms 3. getNeighbourLightLevels: 0.00084ms 4. getNeighbourIndices: 0.00053ms New total time: 15.8036 (6.5x faster than original, 1.45x faster than previous total time measurement) ## Improving getNeighbourBlockStates and adding block models I also added reserve capacity to getNeighbourBlockStates which made getCullingNeighbours 1.6x faster. I then fixed the way texture info was accessed (same issue as getting block models had before). This made adding block models 1.8x faster. 1. getCullingNeighbours: 0.00129ms, 1.6x faster than before 2. getNeighbourLightLevels: 0.00080ms 3. add block models: 0.00051ms, 1.8x faster than before 4. getNeighbourIndices: 0.00049ms New total time: 11.6262 (8.8x faster than original, 1.35x faster than previous) ## Improving everything I moved some work from mesh preparation to resource pack loading time, just flattened some information and added a list of cullable and noncullable faces too. This information also makes it easier to detect that a block isn't visible earlier. I also now only do light level lookups for required faces From now on times will be as total time spent in that task over the course of preparing the whole section because the flow of what tasks are done for each block is more complex now. There will be discrepancies between the sum of the measurements and the 'New total time' because the timer has some overhead. 1. calculate face visibility: 7.65150ms 2. get block models: 1.37812ms 3. get neighbour indices: 1.01480ms 4. add block models: 0.46374ms New total time: 7.5382ms (13.4x faster than original, 1.54x faster than previous) ## Improving face visibility calculation I added two ifs to early exit the calculation for most blocks, and use arrays and iteration instead of a dictionary for neighbour indices. 1. get culling neighbours: 4.48527ms 2. get block models: 1.41321ms 3. calculate face visibility: 0.98564ms 4. get neighbour indices: 0.86533ms New total time: 5.7885ms ## Improving block model getting I now store block models in an array instead of a dictionary because dictionaries are slow. 1. get culling neighbours: 4.12294ms 2. calculate face visibility: 1.03458ms 3. get neighbour indices: 0.96912ms 4. get block models: 0.87172ms 5. add block models: 0.49894ms New total time: 4.9672ms It now takes 8-9 seconds to prepare all chunks within 10 render distance. ## Replacing Set with DirectionSet (a bitset-based implementation) This is just overall a much better data structure for the situation. It also ended up improving the block model cache loading time by a bit over 20% because the data structure is much better suited to binary caching (fixed size and just a single integer). Original total time: 6.03ms (not sure whether my computer was slower or the mesh builder slowly got slower) New total time: 3.35ms (1.8x faster than with Set) ================================================ FILE: Notes/DebuggingDeadlocks.md ================================================ # Debugging deadlocks The more high performance parts of Delta Client use locks to ensure threadsafety (instead of higher level and slower concepts such as dispatch queues). This is all well and good until a subtle bug causes a deadlock and ruins your day. This document will hopefully help you find the cause faster. ## The basics Where applicable, many methods have an `acquireLock` parameter to allow callers to have more control over how locking occurs. The most common use case for this is calling a locking function from within another locking function. If either of the functions requires a write lock, you're in trouble, and the easiest way to avoid this issue is to call the inner function with `acquireLock: false`. Make sure that the outer function acquires a lock that is at least as permissive as the inner function requires. For example, if the inner function normally acquires a write lock, the outer function must acquire a write lock too. ## Pay attention to lock levels Often locks are arranged into levels, `World` has `terrainLock` for accessing chunks from the chunk storage, and then `Chunk` has `lock` for accessing its stored information. If some code has a chunk lock and wants to acquire a terrain lock, but some other code already has a terrain lock and is waiting for a chunk lock, you will get a deadlock. This can be a lot more subtle than a regular deadlock. The rule of thumb here is to only get more and more specific locks when locking and avoid having a specific lock while getting a general lock. If impossible (or tedious) to obey this rule in a certain bit of code, it is also possible to use caution and carefully ensure that one of the offending bits of code only takes one lock at a time (as seen in commit [17fb74bc36ad5b6619d6a6066ebf47073ff22659](https://github.com/stackotter/delta-client/commit/17fb74bc36ad5b6619d6a6066ebf47073ff22659)). ## `ClientboundEntityPacket`'s When implementing the `handle` method of a `ClientboundEntityPacket`, ensure that you do not attempt to acquire any locks on the ECS nexus. This is because these packets are handled in the `EntityPacketSystem` which is run during the game tick, and the tick scheduler always acquires a write lock on the nexus before running any systems. ## Finding the offending code (in trickier cases) If you are struggling to identify a deadlock cause, try defining the `DEBUG_LOCKS` flag. This enabled the `lastLockedBy` property on `ReadWriteLock` which stores the file, line and column where the lock was most recently acquired. Use the [`swiftSettings`](https://github.com/apple/swift-package-manager/blob/11ae0a7bbfaab580c5695eea2c76db9ab092b8a4/Documentation/PackageDescription.md#methods-9) property of the Swift package target you are building to define the flag. After defining the `DEBUG_LOCKS` flag, run the program under lldb or the Xcode debugger and wait for the deadlock to occur. Find a thread that is stuck waiting for a lock and inspect the lock's `lastLockedBy` property. This will hopefully help you find the code path that either forgot to unlock the lock or is acquiring a lock twice. ================================================ FILE: Notes/GUIRendering.md ================================================ # GUI rendering ## Optimisation GUI rendering should be a relatively cheap operation in the Delta Client pipeline, but at the moment it isn't (at least compared to what it should be). It takes close to 4ms per frame on my Intel MacBook Air (on a superflat world on low render distance that's 8 times higher than world rendering). If GUI rendering were put on a scale of optimisability, it would probably be pretty high because most GUI elements don't change from frame to frame. The main source of slow downs is that no mesh buffers are being reused at all. A new buffer is created for each mesh each frame. ### Avoid updating uniforms unless they have changed This made almost no difference to CPU or GPU time, but it's good practice. ### Combine meshes that use the same array texture where possible The only measurement that is affected by this improvement is `gui.encode`. The differences in other measurements are just due to external factors. Overall it seems to be a pretty fair comparison: some measurements that should be constant are slightly more and some are slightly less by they seem to be relatively consistent. This improvement gave a 2.36x reduction in encode time which is pretty great. This improvement isn't foolproof, it should be conservative enough to always retain ordering when required, but it doesn't seem to always combine meshes when they can be combined. This can be worked around by refactoring mesh generation to group by array texture when possible. I had to do this with `GUIList`'s row background generation (by putting all the backgrounds first) and it worked a charm. I don't quite know why it doesn't manage to combine the meshes in these cases, the text is probably overlapping in the transparent parts or something. This could be investigated by adding a mesh bounding box rendering feature to the GUI. ``` waitForRenderPassDescriptor 8.21971ms updateCamera 0.01754ms createRenderCommandEncoder 0.07330ms world 0.53691ms entities 0.06140ms gui 3.30120ms updateUniforms 0.03868ms updateContent 0.52186ms createMeshes 1.07536ms encode 1.63316ms commitToGPU 0.07620ms ``` Figure 1: *before* ``` === Start profiler summary === waitForRenderPassDescriptor 13.06693ms updateCamera 0.02092ms createRenderCommandEncoder 0.07628ms world 0.60788ms entities 0.03953ms gui 2.37221ms updateUniforms 0.03809ms updateContent 0.64521ms createMeshes 0.95568ms encode 0.69374ms commitToGPU 0.05965ms === End profiler summary === ``` Figure 2: *after* ### Reuse vertex buffers This was implemented simply by keeping an array of previous meshes and then when rendering a mesh, use the previous mesh at the same index if one exists. This means that in general a mesh will mostly reuse itself meaning that the size should be similar and the creation of a new vertex buffer can be avoided. This also means that as long as there aren't more meshes than there were in a previous frame (true most of the time), no uniforms buffers need to be created. Vertex buffers are created with enough head room to fit 20 more quads which reduced the number of new buffers created by my repeatable GUI test from 91 to 17 (the minimum possible being 10 which is the number of meshes the GUI uses with chat open, the number of items in the hotbar of the account I was using and the debug overlay activated). This cut down the `gui.encode` measurement by 2.5x (for a total 6x improvement so far). ``` === Start profiler summary === waitForRenderPassDescriptor 13.51036ms updateCamera 0.01717ms createRenderCommandEncoder 0.07296ms world 0.57931ms entities 0.04536ms gui 2.22940ms updateUniforms 0.04108ms updateContent 0.81972ms createMeshes 1.07331ms encode 0.27231ms commitToGPU 0.06338ms === End profiler summary === ``` Figure 3: *after* ### Micro optimization time At the moment I can't spot any other obvious causes for slow down so I just opened up Instruments and started optimizing slow codepaths. By using some unsafe pointers, smarter algorithms and tuples instead of arrays when size is fixed I managed to get quite a big improvement. I think this performance is finally getting pretty reasonable. Total CPU time for GUI rendering is now 2.5x lower than before I started optimizing. ``` === Start profiler summary === waitForRenderPassDescriptor 14.55348ms updateCamera 0.01872ms createRenderCommandEncoder 0.07736ms world 0.66486ms entities 0.03725ms gui 1.35770ms updateUniforms 0.03743ms updateContent 0.43399ms createMeshes 0.51876ms encode 0.34344ms commitToGPU 0.05536ms === End profiler summary === ``` ================================================ FILE: Notes/PluginSystem.md ================================================ # Plugin System This document explains how the plugin system is designed and implemented. ## `PluginEnvironment` The `PluginEnvironment` manages loading, unloading and reloading of plugins. All errors to do with plugin loading are added to `PluginEnvironment.errors` so that they can be accessed at a later time (e.g. in the plugin settings view). `PluginEnvironment` also has a method called `addEventBus` which is used to add all loaded plugins to an event bus as listeners. And a method `handleWillJoinServer` which should be replaced by an event at a later date when the events part is cleaned up. ## Dynamic linking All of a plugin's code is contained within a dynamic library (`libPlugin.dylib`). The dynamic library exposes a function called `buildPlugin` (exported using `@_cdecl("buildPlugin")`) which is called by the client to get a reference to a `PluginBuilder`. The plugin builder is then used to create an instance of the plugin and the plugin is installed into the main `PluginEnvironment` (`DeltaClientApp.pluginEnvironment`). For typecasting to work correctly in plugins, both the client and the plugin have to be using the same copies of types. This means that both the client and plugin have to be dynamically linked against `DeltaCore` (which contains the common code that both plugins and the client have access to). Due to limitations of Swift Package Manager, this means that `DeltaCore` has to be its own swift package which has a dynamic library product (see `Sources/Core/Package.swift`). The root swift package includes `Sources/Core` as a package dependency and the `DeltaClient` target in the root package has this as a dependency. To allow use of `DeltaCore` outside of `DeltaClient` (i.e. in plugins), the root package exposes two products: `DynamicShim` and `StaticShim`. `DynamicShim` re-exports the `DeltaCore` dynamic library for use in plugins (which must dynamically link to `DeltaCore`). However, not all projects require `DeltaCore` to be dynamically link (e.g. a simple bot client), therefore the `StaticShim` product was also exposed which re-exports a statically linked version of `DeltaCore`. ## Loading order If a feature only supports one plugin using it at a time (such as custom render coordinators), the client will use the first plugin that uses the feature. Until proper sorting support is added this can be worked around by unloading all and manually loading the plugins in the order you want (will not persist across launches). ## Manifest files A plugin's manifest file is just a JSON file containing basic information about the client such as its identifier, description and display name. The identifier is used to uniquely identify each plugin. ## Directory structure Plugins are just directories with the `deltaplugin` extension. They currently only contain a `manifest.json` and a `libPlugin.dylib`. ================================================ FILE: Notes/Readme.md ================================================ # Notes In this directory I will be documenting the reasoning behind certain design decisions. I will also be documenting the results of investigations I identify the most efficient solutions to certain bottlenecking problems. Hopefully this documentation will help you understand the design of Delta Core/Client and make better contributions. ================================================ FILE: Notes/RenderPipeline.md ================================================ # Render pipeline optimisation The CPU usage of the render pipeline is currently bottlenecking fps much more than the actual GPU usage. This document will contain my findings as I try to optimise the CPU part of the render pipeline. All measurements of pipeline performance will be measured at -312 140 -216 with yaw 0 and pitch 90 (looking straight down) in seed -6243685378508790499 with render distance 5. It will always be measured in full screen on my laptop's screen not my monitor's. ## Initial measurements - WorldRenderer.draw: ~25ms Just did a bunch of cleanup and now it's a bunch faster somehow; - WorldRenderer.draw: ~7ms I don't quite believe that it sped up that much so i probably measured it incorrectly ================================================ FILE: Package.resolved ================================================ { "pins" : [ { "identity" : "asn1parser", "kind" : "remoteSourceControl", "location" : "https://github.com/stackotter/ASN1Parser", "state" : { "branch" : "main", "revision" : "f92a5b26f5c92d38ae858a5a77048e9af82331a3" } }, { "identity" : "async-http-client", "kind" : "remoteSourceControl", "location" : "https://github.com/swift-server/async-http-client.git", "state" : { "revision" : "037b70291941fe43de668066eb6fb802c5e181d2", "version" : "1.1.1" } }, { "identity" : "bigint", "kind" : "remoteSourceControl", "location" : "https://github.com/attaswift/BigInt.git", "state" : { "revision" : "e07e00fa1fd435143a2dcf8b7eec9a7710b2fdfe", "version" : "5.7.0" } }, { "identity" : "bluesocket", "kind" : "remoteSourceControl", "location" : "https://github.com/stackotter/BlueSocket.git", "state" : { "branch" : "master", "revision" : "31e92ab743a9ffc2a4a6e7e2f1043f5fe1d97e80" } }, { "identity" : "circuitbreaker", "kind" : "remoteSourceControl", "location" : "https://github.com/Kitura/CircuitBreaker.git", "state" : { "revision" : "bd4255762e48cc3748a448d197f1297a4ba705f7", "version" : "5.1.0" } }, { "identity" : "cryptoswift", "kind" : "remoteSourceControl", "location" : "https://github.com/krzyzanowskim/CryptoSwift", "state" : { "revision" : "e45a26384239e028ec87fbcc788f513b67e10d8f", "version" : "1.9.0" } }, { "identity" : "ecs", "kind" : "remoteSourceControl", "location" : "https://github.com/stackotter/ecs.git", "state" : { "branch" : "master", "revision" : "c7660bcd24e31ef2fc3457f56a2bf4a58c3ad6ee" } }, { "identity" : "fireblade-math", "kind" : "remoteSourceControl", "location" : "https://github.com/stackotter/fireblade-math.git", "state" : { "branch" : "matrix2x2", "revision" : "750239647673b07457bea80b39438a6db52198f1" } }, { "identity" : "jjliso8601dateformatter", "kind" : "remoteSourceControl", "location" : "https://github.com/michaeleisel/JJLISO8601DateFormatter", "state" : { "revision" : "50d5ea26ffd3f82e3db8516d939d80b745e168cf", "version" : "0.2.0" } }, { "identity" : "jpeg", "kind" : "remoteSourceControl", "location" : "https://github.com/stackotter/jpeg", "state" : { "revision" : "a27e47f49479993b2541bc5f5c95d9354ed567a0", "version" : "1.0.2" } }, { "identity" : "libpng", "kind" : "remoteSourceControl", "location" : "https://github.com/the-swift-collective/libpng", "state" : { "revision" : "0eff23aca92a086b7892831f5cb4f58e15be9449", "version" : "1.6.45" } }, { "identity" : "libwebp", "kind" : "remoteSourceControl", "location" : "https://github.com/the-swift-collective/libwebp", "state" : { "revision" : "5f745a17b9a5c2a4283f17c2cde4517610ab5f99", "version" : "1.4.1" } }, { "identity" : "loggerapi", "kind" : "remoteSourceControl", "location" : "https://github.com/Kitura/LoggerAPI.git", "state" : { "revision" : "e82d34eab3f0b05391082b11ea07d3b70d2f65bb", "version" : "1.9.200" } }, { "identity" : "opencombine", "kind" : "remoteSourceControl", "location" : "https://github.com/OpenCombine/OpenCombine.git", "state" : { "revision" : "8576f0d579b27020beccbccc3ea6844f3ddfc2c2", "version" : "0.14.0" } }, { "identity" : "puppy", "kind" : "remoteSourceControl", "location" : "https://github.com/sushichop/Puppy", "state" : { "revision" : "80ebe6ab25fb7050904647cb96f6ad7bee77bad6", "version" : "0.9.0" } }, { "identity" : "rainbow", "kind" : "remoteSourceControl", "location" : "https://github.com/onevcat/Rainbow", "state" : { "revision" : "cdf146ae671b2624917648b61c908d1244b98ca1", "version" : "4.2.1" } }, { "identity" : "swift-algorithms", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-algorithms.git", "state" : { "revision" : "87e50f483c54e6efd60e885f7f5aa946cee68023", "version" : "1.2.1" } }, { "identity" : "swift-argument-parser", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-argument-parser", "state" : { "revision" : "626b5b7b2f45e1b0b1c6f4a309296d1d21d7311b", "version" : "1.7.1" } }, { "identity" : "swift-asn1", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-asn1.git", "state" : { "revision" : "9f542610331815e29cc3821d3b6f488db8715517", "version" : "1.6.0" } }, { "identity" : "swift-async-algorithms", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-async-algorithms.git", "state" : { "revision" : "9d349bcc328ac3c31ce40e746b5882742a0d1272", "version" : "1.1.3" } }, { "identity" : "swift-async-dns-resolver", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-async-dns-resolver.git", "state" : { "revision" : "36eedf108f9eda4feeaf47f3dfce657a88ef19aa", "version" : "0.6.0" } }, { "identity" : "swift-atomics", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-atomics.git", "state" : { "revision" : "b601256eab081c0f92f059e12818ac1d4f178ff7", "version" : "1.3.0" } }, { "identity" : "swift-case-paths", "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-case-paths", "state" : { "revision" : "206cbce3882b4de9aee19ce62ac5b7306cadd45b", "version" : "1.7.3" } }, { "identity" : "swift-certificates", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-certificates.git", "state" : { "revision" : "24ccdeeeed4dfaae7955fcac9dbf5489ed4f1a25", "version" : "1.18.0" } }, { "identity" : "swift-collections", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-collections.git", "state" : { "revision" : "6675bc0ff86e61436e615df6fc5174e043e57924", "version" : "1.4.1" } }, { "identity" : "swift-cross-ui", "kind" : "remoteSourceControl", "location" : "https://github.com/stackotter/swift-cross-ui", "state" : { "revision" : "835c9ea90a3b1d2dc20436eb2c87b00037b4eb9c", "version" : "0.4.0" } }, { "identity" : "swift-crypto", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-crypto.git", "state" : { "revision" : "bb4ba815dab96d4edc1e0b86d7b9acf9ff973a84", "version" : "4.3.1" } }, { "identity" : "swift-cwinrt", "kind" : "remoteSourceControl", "location" : "https://github.com/moreSwift/swift-cwinrt", "state" : { "revision" : "601287a2a89e8e56e8aa53782b6054db8be0bce8", "version" : "0.1.2" } }, { "identity" : "swift-http-structured-headers", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-http-structured-headers.git", "state" : { "revision" : "76d7627bd88b47bf5a0f8497dd244885960dde0b", "version" : "1.6.0" } }, { "identity" : "swift-http-types", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-http-types.git", "state" : { "revision" : "45eb0224913ea070ec4fba17291b9e7ecf4749ca", "version" : "1.5.1" } }, { "identity" : "swift-image", "kind" : "remoteSourceControl", "location" : "https://github.com/stackotter/swift-image.git", "state" : { "branch" : "master", "revision" : "7160e2d8799f8b182498ab699aa695cb66cf4ea6" } }, { "identity" : "swift-image-formats", "kind" : "remoteSourceControl", "location" : "https://github.com/stackotter/swift-image-formats", "state" : { "revision" : "2e5dc1ead747afab9fd517d81316d961969e3610", "version" : "0.3.3" } }, { "identity" : "swift-log", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-log.git", "state" : { "revision" : "ce592ae52f982c847a4efc0dd881cc9eb32d29f2", "version" : "1.6.4" } }, { "identity" : "swift-macro-toolkit", "kind" : "remoteSourceControl", "location" : "https://github.com/stackotter/swift-macro-toolkit", "state" : { "revision" : "d319bcc2586f7dbc6a09c05792105078263f1ed3", "version" : "0.7.2" } }, { "identity" : "swift-mutex", "kind" : "remoteSourceControl", "location" : "https://github.com/swhitty/swift-mutex", "state" : { "revision" : "1770152df756b54c28ef1787df1e957d93cc62d5", "version" : "0.0.6" } }, { "identity" : "swift-nio", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-nio.git", "state" : { "revision" : "558f24a4647193b5a0e2104031b71c55d31ff83a", "version" : "2.97.1" } }, { "identity" : "swift-nio-extras", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-nio-extras.git", "state" : { "revision" : "abcf5312eb8ed2fb11916078aef7c46b06f20813", "version" : "1.33.0" } }, { "identity" : "swift-nio-http2", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-nio-http2.git", "state" : { "revision" : "6d8d596f0a9bfebb925733003731fe2d749b7e02", "version" : "1.42.0" } }, { "identity" : "swift-nio-ssl", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-nio-ssl.git", "state" : { "revision" : "df9c3406028e3297246e6e7081977a167318b692", "version" : "2.36.1" } }, { "identity" : "swift-numerics", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-numerics.git", "state" : { "revision" : "0c0290ff6b24942dadb83a929ffaaa1481df04a2", "version" : "1.1.1" } }, { "identity" : "swift-package-zlib", "kind" : "remoteSourceControl", "location" : "https://github.com/fourplusone/swift-package-zlib", "state" : { "revision" : "03ecd41814d8929362f7439529f9682536a8de13", "version" : "1.2.11" } }, { "identity" : "swift-parsing", "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-parsing", "state" : { "revision" : "3432cb81164dd3d69a75d0d63205be5fbae2c34b", "version" : "0.14.1" } }, { "identity" : "swift-png", "kind" : "remoteSourceControl", "location" : "https://github.com/stackotter/swift-png", "state" : { "revision" : "b68a5662ef9887c8f375854720b3621f772bf8c5" } }, { "identity" : "swift-service-lifecycle", "kind" : "remoteSourceControl", "location" : "https://github.com/swift-server/swift-service-lifecycle.git", "state" : { "revision" : "9829955b385e5bb88128b73f1b8389e9b9c3191a", "version" : "2.11.0" } }, { "identity" : "swift-syntax", "kind" : "remoteSourceControl", "location" : "https://github.com/swiftlang/swift-syntax.git", "state" : { "revision" : "f99ae8aa18f0cf0d53481901f88a0991dc3bd4a2", "version" : "601.0.1" } }, { "identity" : "swift-system", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-system.git", "state" : { "revision" : "7c6ad0fc39d0763e0b699210e4124afd5041c5df", "version" : "1.6.4" } }, { "identity" : "swift-uwp", "kind" : "remoteSourceControl", "location" : "https://github.com/moreSwift/swift-uwp", "state" : { "revision" : "a0a86467514eaa63272eae848c70d49e6874ede4", "version" : "0.1.0" } }, { "identity" : "swift-webview2core", "kind" : "remoteSourceControl", "location" : "https://github.com/moreSwift/swift-webview2core", "state" : { "revision" : "a8ed52a57f6d81ee06c8db692f8ee0431174379a", "version" : "0.1.0" } }, { "identity" : "swift-windowsappsdk", "kind" : "remoteSourceControl", "location" : "https://github.com/moreSwift/swift-windowsappsdk", "state" : { "revision" : "3c06cb36da9711e24a76c35861e0b97702448015", "version" : "0.1.1" } }, { "identity" : "swift-windowsfoundation", "kind" : "remoteSourceControl", "location" : "https://github.com/moreSwift/swift-windowsfoundation", "state" : { "revision" : "94d56a5aea472672bc5d041c091f6cdf72e3cc44", "version" : "0.1.0" } }, { "identity" : "swift-winui", "kind" : "remoteSourceControl", "location" : "https://github.com/moreSwift/swift-winui", "state" : { "revision" : "73d5d19c39c523c92355027dd13aee445fc627a7", "version" : "0.1.1" } }, { "identity" : "swiftcpudetect", "kind" : "remoteSourceControl", "location" : "https://github.com/JWhitmore1/SwiftCPUDetect", "state" : { "branch" : "main", "revision" : "5ca694c6ad7eef1199d69463fa956c24c202465f" } }, { "identity" : "swiftpackagesbase", "kind" : "remoteSourceControl", "location" : "https://github.com/ITzTravelInTime/SwiftPackagesBase", "state" : { "revision" : "79477622b5dbacc3722d485c5060c46a90740016", "version" : "0.0.23" } }, { "identity" : "swiftyrequest", "kind" : "remoteSourceControl", "location" : "https://github.com/Kitura/SwiftyRequest.git", "state" : { "revision" : "2c543777a5088bed811503a68551a4b4eceac198", "version" : "3.2.200" } }, { "identity" : "swordrpc", "kind" : "remoteSourceControl", "location" : "https://github.com/stackotter/SwordRPC", "state" : { "revision" : "3ddf125eeb3d83cb17a6e4cda685f9c80e0d4bed" } }, { "identity" : "xctest-dynamic-overlay", "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/xctest-dynamic-overlay", "state" : { "revision" : "dfd70507def84cb5fb821278448a262c6ff2bbad", "version" : "1.9.0" } }, { "identity" : "zipfoundation", "kind" : "remoteSourceControl", "location" : "https://github.com/weichsel/ZIPFoundation.git", "state" : { "revision" : "22787ffb59de99e5dc1fbfe80b19c97a904ad48d", "version" : "0.9.20" } }, { "identity" : "zippyjson", "kind" : "remoteSourceControl", "location" : "https://github.com/michaeleisel/ZippyJSON", "state" : { "revision" : "ddbbc024ba5a826f9676035a0a090a0bc2d40755", "version" : "1.2.15" } }, { "identity" : "zippyjsoncfamily", "kind" : "remoteSourceControl", "location" : "https://github.com/michaeleisel/ZippyJSONCFamily", "state" : { "revision" : "c1c0f88977359ea85b81e128b2d988e8250dfdae", "version" : "1.2.14" } }, { "identity" : "zlib", "kind" : "remoteSourceControl", "location" : "https://github.com/the-swift-collective/zlib.git", "state" : { "revision" : "f1d153b90420f9fcc6ef916cd67ea96f0e68d137", "version" : "1.3.2" } } ], "version" : 2 } ================================================ FILE: Package.swift ================================================ // swift-tools-version:5.9 import PackageDescription var products: [Product] = [ .executable( name: "DeltaClientGtk", targets: ["DeltaClientGtk"] ), // Importing DynamicShim as a dependency in your own project will in effect just import // DeltaCore using dynamic linking .library( name: "DynamicShim", targets: ["DynamicShim"] ), // Importing StaticShim as a dependency in your own project will just import DeltaCore // using static linking .library( name: "StaticShim", targets: ["StaticShim"] ), ] #if canImport(Darwin) products.append( .executable( name: "DeltaClient", targets: ["DeltaClient"] ) ) #endif var targets: [Target] = [ .executableTarget( name: "DeltaClientGtk", dependencies: [ .product(name: "DeltaCore", package: "DeltaCore"), .product(name: "SwiftCrossUI", package: "swift-cross-ui"), .product(name: "GtkBackend", package: "swift-cross-ui"), ], path: "Sources/ClientGtk" ), .target( name: "DynamicShim", dependencies: [ .product(name: "DeltaCore", package: "DeltaCore") ], path: "Sources/Exporters/DynamicShim" ), .target( name: "StaticShim", dependencies: [ .product(name: "StaticDeltaCore", package: "DeltaCore") ], path: "Sources/Exporters/StaticShim" ), ] #if canImport(Darwin) targets.append( .executableTarget( name: "DeltaClient", dependencies: [ "DynamicShim", .product(name: "SwordRPC", package: "SwordRPC", condition: .when(platforms: [.macOS])), .product(name: "ArgumentParser", package: "swift-argument-parser"), ], path: "Sources/Client" ) ) #endif let package = Package( name: "DeltaClient", platforms: [.macOS(.v11), .iOS(.v15), .tvOS(.v15)], products: products, dependencies: [ // See Notes/PluginSystem.md for more details on the architecture of the project in regards to dependencies, targets and linking // In short, the dependencies for DeltaCore can be found in Sources/Core/Package.swift .package(name: "DeltaCore", path: "./Sources/Core"), .package(url: "https://github.com/apple/swift-argument-parser", from: "1.0.0"), .package( url: "https://github.com/stackotter/SwordRPC", revision: "3ddf125eeb3d83cb17a6e4cda685f9c80e0d4bed" ), .package( url: "https://github.com/stackotter/swift-cross-ui", .upToNextMinor(from: "0.4.0") ), ], targets: targets ) ================================================ FILE: Readme.md ================================================ # Delta Client - Changing the meaning of speed [![Discord](https://img.shields.io/discord/851058836776419368.svg?label=&logo=discord&logoColor=ffffff&color=5C5C5C&labelColor=6A7EC2)](https://deltaclient.app/discord) An open source rewrite of the *Minecraft: Java Edition* client, written in Swift for macOS and iOS (experimental). Currently Delta Client only supports connecting to **1.16.1** servers. ## Disclaimers This client is not finished yet. If you're looking for a client to use to play Minecraft today, then this is not for you. **I am NOT responsible for anti-cheat bans, the client has not been thoroughly tested yet and is still deep in development.** **This software is not affiliated with Mojang AB, the original developer of Minecraft.** ## Overview The main focus of this project is to create a highly efficient Java Edition compatible client written in Swift for macOS. The client also has experimental support for iOS, and is in the process of getting ported to Linux using SwiftCrossUI and eventually Kinzoku (once it is ready). If you want to have a say in the development of the client or have any questions, feel free to join the community on [Discord](https://deltaclient.app/discord). ![Playing with Delta Client in a Hypixel lobby](Screenshots/hypixel-3.png) ## Performance One of the biggest advantages of Delta Client is its performance. Epic comparison graphs are in progress, but for now have some dot-points. - Start-up time: - M2 MacBook Air: 0.9 seconds (vanilla takes 43 seconds) - i5 MacBook Air: 2.7 seconds (vanilla takes ~60 seconds) - FPS on 10 render distance in the mountains (bad for fps): - M2 MacBook Air (on 1080p monitor): ~120 fps (vanilla gets ~75 fps) - i5 MacBook Air: ~70 fps (vanilla gets ~35fps) ## Installation ### Prebuilt 1. Visit [Delta Client's downloads page](https://delta.stackotter.dev/downloads) and download the latest build from the `main` branch. 2. Unzip the downloaded zip archive and open the app inside 3. You will get a security alert, click ok 4. Right click the app in finder and select open 5. You should get another pop-up, click 'Open' 6. Delta Client will now open and start downloading the required assets (this only has to happen once and should take around 40s with a mediocre internet speed) 7. You can move Delta Client to your Applications folder for ease of use if you want To view application logs, click `View > Logs` in the menu bar while Delta Client is open. ### Building from source To build Delta Client you'll first need to install Xcode 14+ and the latest version of [Swift Bundler](https://github.com/stackotter/swift-bundler). Please note that using Xcode 13 is ok but you may run into some weird memory corruption issues, so test with Xcode 14+ before assuming that it's a Delta Client bug. Once you've installed the requirements, run the following commands in terminal; ```sh # Clone Delta Client git clone https://github.com/stackotter/delta-client cd delta-client # Perform a release build and output the bundled app to the current directory sh ./build.sh # If you want to develop Delta Client using Xcode, run the following command swift bundler generate-xcode-support # And then open Package.swift with Xcode and you'll be able to build it from Xcode too ``` ## Minecraft version support At the moment the client only supports joining **1.16.1** servers. In the future I plan to support more versions. Not every version will be perfectly supported but I will try and have the most polished support for the following versions; - 1.8.9 - the latest speedrunning version (currently 1.16.1) - the latest stable version ## Features - [x] Networking - [x] Basic networking - [x] Server list ping - [x] Encryption (for non-offline mode servers) - [x] Mojang accounts - [x] Microsoft accounts - [x] LAN server detection - [x] Basic config system - [x] Multi-accounting - [ ] Rendering - [x] World - [x] Basic block rendering - [x] Basic chunk rendering - [x] Block culling - [x] Block models - [x] Multipart structures (e.g. fences) - [x] Multiple chunks - [x] Lighting - [x] Animated textures (e.g. lava) - [x] Translucency - [x] Fluids (lava and water) - [x] Chunk frustum culling - [x] Biome blending (mostly) - [x] [Sky box](https://github.com/stackotter/delta-client/pull/188) - [ ] Entities - [x] Basic entity rendering (just coloured cubes) - [x] Render entity models - [ ] Block entities (e.g. chests) - [ ] Item entities - [ ] Entity animations - [ ] GUI - [x] Chat - [x] F3-style stuff - [x] Bossbars - [ ] Scoreboard - [x] Tab list - [x] Health, hunger and experience - [x] Hotbar - [ ] Inventory - [x] Basic inventory - [x] Basic crafting - [x] Inventory actions - [ ] Using recipe blocks (like crafting tables and stuff) - [ ] Creative inventory - [ ] Sound - [ ] Basic sounds system - [x] Physics - [x] Physics loop - [x] Input system - [x] Collision system - [x] Interaction - [x] Block placing - [x] Block breaking - [x] Block entity interaction - [x] Entity interaction - [ ] Particles - [ ] Basic particle system - [ ] Block break particles - [ ] Ambient particles - [ ] Hit particles - [ ] Particles from server ## Contributing First, please check out the [contributing guidelines](Contributing.md). Then you can checkout the [issues](https://github.com/stackotter/delta-client/issues) for a place to get started. Make sure to leave a comment on the issue you choose so that people know that someone's already working on it. ## Servers We now have an official testing server (`play.deltaclient.app`)! However, if you want to mess around to your hearts content you can run a server on your computer for full control (see below). To start a test server, download a 1.16.1 server jar from [here](https://mcversions.net/download/1.16.1). Then in Terminal type `java -jar ` and then drag the downloaded .jar file onto the terminal window and then hit enter. Wait for the server to start up. Now add a new server with the address `localhost` in Delta Client and you should be able to connect to it. Keep in mind the server may use a significant amount of resources and slow down Delta Client. ## More screenshots ![Delta Client being used to view a survival world from a vantage point on a mountain](Screenshots/survival.png) ![Delta Client's server selection UI](Screenshots/ui.png) ================================================ FILE: Roadmap.md ================================================ # **This is outdated, please ignore for now** # Demo Versions The demo versions are just proof-of-concepts. ## Demo 1 - Efficient Launch, Basic Rendering & All Networking *(Released)* ### Features - smooth first launch flow (downloading assets and creating default config and stuff) - login flow for mojang accounts - fast subsequent startups - rendering player's current chunk - the view can be moved around using ```tp``` commands from another player - basic config screens (account settings and server settings) ### Todo - [x] refactor networking - [x] add compression support - [x] add encryption support - [x] basic config system - [x] sign in screen on first launch - [x] config screen for changing account details (used a logout button for now instead) - [x] remove need for minecraft to be already installed - [x] add basic way to exit game and get back to server list - [x] prettyprint config json - [x] way to re-order servers - [x] move some things to menu bar instead of tool bar (like account stuff) ## Demo 2 - Critical Bug Fixes for Demo 1 *(Released)* ### New Features - none, just fixes some critical bugs from demo 1 ### Todo - [x] refresh access token before each server join - [x] fix first time server join # Alpha Versions The demo versions were just proof-of-concepts. The alpha versions will still be far from complete but will be looking a lot more promising. ## Alpha 1 - Basically Spectator Mode *(WIP)* ### New Features - rendering - proper lighting - multipart structures (e.g. fences) - random block rotations - multichunk rendering - complete redesigned rendering system - animated textures - frustum culling - mip maps - proper tints (redstone, leaves, water and grass etc.) - fluids - proper transparency and translucency rendering - movements - basic input system - basic spectator mode movement (freecam) - ui - cleaner ui and ui code - edit server list screen - accounts screen - multi-accounting (allow easily switching between accounts) - improved memory usage ### Todo - [x] multipart structure reading (from pixlyzer) - [x] multipart structure rendering - [x] parallelise generating chunk meshes - [x] order chunks based on distance from player when generating meshes - [x] order chunks based off frustum as well - [x] basic shading (face normal based) (bake light levels into block models) - [x] mip maps - [x] rewrite block model loading system - [x] lighting - [x] animated textures - [x] fix gpu ram usage (clear buffers when not being used, possibly use private mode buffers, possibly use a big default size buffer and transfer things through that) - [x] fix indices (either use 6 vertices to a face or do the fancy shader thing from before (adjusting the vertex indices)) - [x] optimise chunk mesh preparation - [x] proper transparent and translucent rendering - [x] non-transparent leaves for now (better performance) - [x] reduce cpu time for frames (gpu frame time is well below 16ms, cpu is taking up the majority of the time each frame) - [x] possibly use section based rendering instead of chunk based - [x] basic multichunk rendering - [x] fix hypixel chunk loading - [x] fix grass block sides - [x] implement rescale - [x] random block variants (that match vanilla) - [x] frustum culling for chunks - [x] create an input system - [x] keyboard - [x] mouse - [x] create a physics loop - [x] make a loop that runs at a consistent interval - [x] add basic physics simulation - [x] add basis for multi-accounting - [x] config - [x] login code - [x] add offline account support - [x] ui for switching accounts - [x] fix memory usage errors (when leaving a server or starting the app for the first time a lot of memory doesn't get freed for some reason) - [x] fluids - [x] waterlogging - [x] block id refactor (issue #25) ## Alpha 2 - Creative Mode Without Inventory ### New Features - collision system - auto-jump - gravity ### Todo - [x] load hitboxes - [x] wireframe hitboxes - [x] detect player-block collisions - [x] handle collisions - [ ] auto-jump - [x] add gravity to physics ## Alpha 3 - Basic Survival Mode ### New Features - Basic HUD & Inventory - f3 - hotbar - health - xp bar - bubbles (the indicator for drowning stuff) - basic inventory view ### Todo - [x] font rendering - [x] modular hud system - [x] bars - [x] health - [x] hunger - [x] xp - [ ] bubbles - [x] item rendering - [x] hotbar - [x] basic inventory (just for viewing) ================================================ FILE: Security.md ================================================ # Security Policy ## Supported Versions Only bugs present in the latest commit on a branch will be acted on (because all others have clearly been fixed). However, if there's a security bug in one of the GitHub releases, a security advisory will be added to release's description. And if it's the latest release, a new release will be made once the bug is fixed. ## Reporting a Vulnerability Create an issue for the vulnerability unless publicising the issue before it is fixed would put users at risk. In the case that creating a public GitHub issue is not sensible, contact me directly on Discord (stackotter#3100). If the bug does turn out to be serious after further investigation, it will be prioritised and fixed as soon as possible. If it's not serious, it will have the same priority as any other issue. ================================================ FILE: Sources/Client/CommandLineArguments.swift ================================================ import ArgumentParser import Foundation import Logging /// An error thrown while parsing ``CommandLineArguments``. enum CommandLineArgumentsError: LocalizedError { case invalidLogLevel(String) var errorDescription: String? { switch self { case .invalidLogLevel(let level): return "Invalid log level '\(level)'. Must be one of \(Logger.Level.allCases.map(\.rawValue))" } } } /// The command line arguments for Delta Client. struct CommandLineArguments: ParsableCommand { static let configuration = CommandConfiguration(commandName: "DeltaClient") /// A replacement for the default plugins directory. @Option( name: .customLong("plugins-dir"), help: "A directory to load plugins from instead of the default plugins directory.", transform: URL.init(fileURLWithPath:)) var pluginsDirectory: URL? /// The minimum log level to output to stdout. @Option( help: "The minimum log level to output to stdout.", transform: { string in switch string { case "trace": return .trace case "verbose": return .verbose case "debug": return .debug case "info": return .info case "notice": return .notice case "warning": return .warning case "error": return .error case "critical": return .critical default: throw CommandLineArgumentsError.invalidLogLevel(string) } }) var logLevel = LogLevel.info /// Xcode passes the `-NSDocumentRevisionsDebugMode` flag when running applications (no clue why). /// It needs to be defined here because otherwise it throws an error due to strict parsing. @Option( name: .customLong("NSDocumentRevisionsDebugMode", withSingleDash: true), help: .init("Ignore this, just Xcode being weird.", visibility: .hidden)) var nsDocumentRevisionsDebugMode: String? } ================================================ FILE: Sources/Client/Components/AddressField.swift ================================================ import SwiftUI import Combine struct AddressField: View { // swiftlint:disable:next force_try static private let ipRegex = try! NSRegularExpression( pattern: "^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)(\\.(?!$)|$)){4}$" ) // swiftlint:disable:next force_try static private let domainRegex = try! NSRegularExpression( pattern: "^[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*$" ) let title: String @State private var string: String @Binding private var host: String @Binding private var port: UInt16? @Binding private var isValid: Bool init(_ title: String, host: Binding, port: Binding, isValid: Binding) { self.title = title _host = host _port = port if let port = port.wrappedValue { _string = State(initialValue: "\(host.wrappedValue):\(port)") } else { _string = State(initialValue: host.wrappedValue) } _isValid = isValid } private func update(_ newValue: String) { let components = newValue.split(separator: ":") if components.count == 0 { log.trace("Invalid ip, empty string") isValid = false } else if components.count > 2 { log.trace("Invalid ip, too many components: '\(newValue)'") isValid = false } else if newValue.hasSuffix(":") { log.trace("Invalid ip, empty port: '\(newValue)'") isValid = false } // Check host component if components.count > 0 { let hostString = String(components[0]) let range = NSRange(location: 0, length: hostString.utf16.count) let isIp = Self.ipRegex.firstMatch(in: hostString, options: [], range: range) != nil let isDomain = Self.domainRegex.firstMatch(in: hostString, options: [], range: range) != nil if isIp || isDomain { host = hostString isValid = true } else { log.trace("Invalid host component: '\(hostString)'") isValid = false } } // Check port component if components.count == 2 { let portString = components[1] if let port = UInt16(portString) { self.port = port isValid = true } else { log.trace("Invalid port component: '\(portString)'") isValid = false } } else { port = nil } } var body: some View { TextField(title, text: $string) .onReceive(Just(string), perform: update) .onAppear { update(string) } } } ================================================ FILE: Sources/Client/Components/ButtonStyles/DisabledButtonStyle.swift ================================================ import SwiftUI struct DisabledButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { HStack { Spacer() configuration.label.foregroundColor(.gray) Spacer() } .padding(6) .background(Color.secondary.brightness(-0.4).cornerRadius(4)) } } ================================================ FILE: Sources/Client/Components/ButtonStyles/PrimaryButtonStyle.swift ================================================ import SwiftUI #if os(tvOS) typealias PrimaryButtonStyle = DefaultButtonStyle #else struct PrimaryButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { HStack { Spacer() configuration.label.foregroundColor(.white) Spacer() } .padding(6) .background(Color.accentColor.brightness(configuration.isPressed ? 0.15 : 0).cornerRadius(4)) } } #endif ================================================ FILE: Sources/Client/Components/ButtonStyles/SecondaryButtonStyle.swift ================================================ import SwiftUI #if os(tvOS) typealias SecondaryButtonStyle = DefaultButtonStyle #else struct SecondaryButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { HStack { Spacer() configuration.label.foregroundColor(.white) Spacer() } .padding(6) .background(Color.secondary.brightness(configuration.isPressed ? 0 : -0.15).cornerRadius(4)) } } #endif ================================================ FILE: Sources/Client/Components/EditableList/EditableList.swift ================================================ import SwiftUI enum EditableListAction { case delete case edit case moveUp case moveDown case select } enum EditableListState { case list case addItem case editItem(Int) } struct EditableList: View { @State var state: EditableListState = .list #if os(tvOS) @Namespace var focusNamespace #endif @Binding var items: [ItemEditor.Item] @Binding var selected: Int? let itemEditor: ItemEditor.Type let row: ( _ item: ItemEditor.Item, _ selected: Bool, _ isFirst: Bool, _ isLast: Bool, _ handler: @escaping (EditableListAction) -> Void ) -> Row let save: (() -> Void)? let cancel: (() -> Void)? /// Message to display when the list is empty. let emptyMessage: String init( _ items: Binding<[ItemEditor.Item]>, selected: Binding = Binding(get: { nil }, set: { _ in }), itemEditor: ItemEditor.Type, @ViewBuilder row: @escaping ( _ item: ItemEditor.Item, _ selected: Bool, _ isFirst: Bool, _ isLast: Bool, _ handler: @escaping (EditableListAction) -> Void ) -> Row, saveAction: (() -> Void)?, cancelAction: (() -> Void)?, emptyMessage: String = "No items", forceShowCreation: Bool = false ) { self._items = items self._selected = selected self.itemEditor = itemEditor self.row = row self.emptyMessage = emptyMessage save = saveAction cancel = cancelAction if forceShowCreation { _state = State(wrappedValue: .addItem) } } func handleItemEditableListAction(_ index: Int, _ action: EditableListAction) { switch action { case .delete: if selected == index { if items.count == 1 { selected = nil } else { selected = 0 } } else if let selectedIndex = selected, selectedIndex > index { selected = selectedIndex - 1 } items.remove(at: index) case .edit: state = .editItem(index) case .moveUp: if index != 0 { let item = items.remove(at: index) items.insert(item, at: index - 1) } case .moveDown: if index != items.count - 1 { let item = items.remove(at: index) items.insert(item, at: index + 1) } case .select: selected = index } } var body: some View { Group { switch state { case .list: VStack(alignment: .center, spacing: 16) { if items.count == 0 { Text(emptyMessage).italic() } ScrollView(showsIndicators: true) { ForEach(items.indices, id: \.self) { index in VStack(alignment: .leading) { Divider() let isFirst = index == 0 let isLast = index == items.count - 1 row(items[index], selected == index, isFirst, isLast, { action in handleItemEditableListAction(index, action) }) if index == items.count - 1 { Divider() } } } } #if os(tvOS) .focusSection() #endif VStack { Button("Add") { state = .addItem } #if os(tvOS) .prefersDefaultFocus(in: focusNamespace) #endif .buttonStyle(SecondaryButtonStyle()) if save != nil || cancel != nil { HStack { if let cancel = cancel { Button("Cancel", action: cancel) .buttonStyle(SecondaryButtonStyle()) } if let save = save { Button("Save", action: save) .buttonStyle(PrimaryButtonStyle()) } } } } #if !os(tvOS) .frame(width: 200) #else .focusSection() #endif } #if os(tvOS) .focusSection() #endif case .addItem: itemEditor.init(nil, completion: { newItem in items.append(newItem) selected = items.count - 1 state = .list }, cancelation: { state = .list }) case let .editItem(index): itemEditor.init(items[index], completion: { editedItem in items[index] = editedItem state = .list }, cancelation: { state = .list }) } } #if !os(tvOS) .frame(width: 400) #else .focusScope(focusNamespace) #endif } } ================================================ FILE: Sources/Client/Components/EditableList/EditorView.swift ================================================ import SwiftUI protocol EditorView: View { associatedtype Item init(_ item: Item?, completion: @escaping (Item) -> Void, cancelation: (() -> Void)?) } ================================================ FILE: Sources/Client/Components/EmailField.swift ================================================ import SwiftUI import Combine struct EmailField: View { // swiftlint:disable:next force_try static private let regex = try! NSRegularExpression( pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" ) private let title: String @Binding private var email: String @Binding private var isValid: Bool init( _ title: String, email: Binding, isValid: Binding = Binding(get: { false }, set: { _ in }) ) { self.title = title _email = email _isValid = isValid } private func validate(_ email: String) { let range = NSRange(location: 0, length: email.utf16.count) isValid = Self.regex.firstMatch(in: email, options: [], range: range) != nil } var body: some View { TextField(title, text: $email) .onReceive(Just(email), perform: validate) .onAppear { validate(email) } } } ================================================ FILE: Sources/Client/Components/IconButton.swift ================================================ import SwiftUI struct IconButton: View { let icon: String let isDisabled: Bool let action: () -> Void init(_ icon: String, isDisabled: Bool = false, action: @escaping () -> Void) { self.icon = icon self.isDisabled = isDisabled self.action = action } var body: some View { Button(action: action, label: { Image(systemName: icon) }) #if !os(tvOS) .buttonStyle(BorderlessButtonStyle()) #endif .disabled(isDisabled) } } ================================================ FILE: Sources/Client/Components/LegacyFormattedTextView.swift ================================================ import Foundation import DeltaCore import SwiftUI /// SwiftUI view for displaying text that is formatted using Legacy formatting codes. /// /// See ``LegacyTextFormatter``. struct LegacyFormattedTextView: View { /// The legacy formatted string. var string: String /// The formatted text. var attributedString = NSAttributedString(string: "") /// The font size. var fontSize: CGFloat /// The alignment of the text. var alignment: NSTextAlignment = .center init(legacyString: String, fontSize: CGFloat, alignment: NSTextAlignment = .center) { self.string = legacyString self.attributedString = LegacyFormattedText(legacyString).attributedString(fontSize: fontSize) self.fontSize = fontSize self.alignment = alignment } var body: some View { #if os(tvOS) Text(attributedString.string) #else NSAttributedTextView( attributedString: attributedString, alignment: alignment ).frame(width: attributedString.size().width) #endif } } #if canImport(AppKit) struct NSAttributedTextView: NSViewRepresentable { var attributedString: NSAttributedString var alignment: NSTextAlignment func makeNSView(context: Context) -> some NSView { let label = NSTextField() label.backgroundColor = .clear label.isBezeled = false label.isEditable = false return label } func updateNSView(_ nsView: NSViewType, context: Context) { guard let label = nsView as? NSTextField else { return } label.attributedStringValue = attributedString label.alignment = .left } } #elseif canImport(UIKit) struct NSAttributedTextView: UIViewRepresentable { var attributedString: NSAttributedString var alignment: NSTextAlignment func makeUIView(context: Context) -> some UIView { let label = UILabel() label.backgroundColor = .clear label.autoresizingMask = [.flexibleWidth, .flexibleHeight] return label } func updateUIView(_ uiView: UIViewType, context: Context) { guard let label = uiView as? UILabel else { return } label.attributedText = attributedString } } #else #error("Unsupported platform, no NSAttributedTextView") #endif ================================================ FILE: Sources/Client/Components/OptionalNumberField.swift ================================================ import SwiftUI import Combine struct OptionalNumberField: View { let title: String @State private var string: String @Binding private var number: Number? @Binding private var isValid: Bool init(_ title: String, number: Binding, isValid: Binding) { self.title = title _number = number _string = State(initialValue: number.wrappedValue?.description ?? "") _isValid = isValid } var body: some View { TextField(title, text: $string) .onReceive(Just(string)) { newValue in if newValue == "" { number = nil isValid = false } if let number = Number(newValue) { self.number = number isValid = true } else { isValid = false } } } } ================================================ FILE: Sources/Client/Components/PingIndicator.swift ================================================ import SwiftUI struct PingIndicator: View { let color: Color var body: some View { Circle() .foregroundColor(color) .fixedSize() } } ================================================ FILE: Sources/Client/Components/PixellatedBorder.swift ================================================ import SwiftUI struct PixellatedBorder: InsettableShape { public var insetAmount: CGFloat = 0 private let borderCorner: CGFloat = 4 func path(in rect: CGRect) -> Path { var path = Path() // Top path.move(to: CGPoint(x: borderCorner + insetAmount, y: borderCorner / 2 + insetAmount)) path.addLine(to: CGPoint(x: rect.width - borderCorner - insetAmount, y: borderCorner / 2 + insetAmount)) // Right path.move(to: CGPoint(x: rect.width - borderCorner / 2 - insetAmount, y: borderCorner + insetAmount)) path.addLine(to: CGPoint(x: rect.width - borderCorner/2 - insetAmount, y: rect.height - borderCorner - insetAmount)) // Bottom path.move(to: CGPoint(x: rect.width - borderCorner - insetAmount, y: rect.height - borderCorner / 2 - insetAmount)) path.addLine(to: CGPoint(x: borderCorner + insetAmount, y: rect.height - borderCorner / 2 - insetAmount)) // Left path.move(to: CGPoint(x: borderCorner / 2 + insetAmount, y: rect.height - borderCorner - insetAmount)) path.addLine(to: CGPoint(x: borderCorner / 2 + insetAmount, y: borderCorner + insetAmount)) return path } func inset(by amount: CGFloat) -> some InsettableShape { var border = self border.insetAmount += amount return border } } ================================================ FILE: Sources/Client/Config/Config.swift ================================================ import Foundation import DeltaCore import OrderedCollections /// The client's configuration. Usually stored in a JSON file. struct Config: Codable, ClientConfiguration { /// The current config version used by the client. static let currentVersion: Float = 0 /// The config format version. Used to detect outdated config files (and maybe /// in future to migrate them). Completely independent from the actual Delta /// Client version. var version: Float = currentVersion /// The random token used to identify ourselves to Mojang's API var clientToken = UUID().uuidString /// The id of the currently selected account. var selectedAccountId: String? /// The dictionary containing all of the user's accounts. var accounts: [String: Account] = [:] /// The user's server list. var servers: [ServerDescriptor] = [] /// Rendering related configuration. var render = RenderConfiguration(enableOrderIndependentTransparency: true) /// Plugins that the user has explicitly unloaded. var unloadedPlugins: [String] = [] /// The user's keymap. var keymap = Keymap.default /// Whether to use the sprint key as a toggle. var toggleSprint = false /// Whether to use the sneak key as a toggle. var toggleSneak = false /// The in game mouse sensitivity var mouseSensitivity: Float = 1 /// The user's accounts, ordered by username. var orderedAccounts: [Account] { accounts.values.sorted { $0.username <= $1.username } } /// The account the user has currently selected. var selectedAccount: Account? { if let id = selectedAccountId { return accounts[id] } else { return nil } } /// Creates the default config. init() {} /// Loads a configuration from a JSON configuration file. static func load(from file: URL) throws -> Config { let data = try Data(contentsOf: file) let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] guard let version = json?["version"] as? Float else { throw ConfigError.missingVersion } guard version == currentVersion else { throw ConfigError.unsupportedVersion(version) } return try JSONDecoder().decode(Self.self, from: data) } /// Saves the configuration to a JSON file. func save(to file: URL) throws { let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] let data = try encoder.encode(self) try data.write(to: file) } /// Adds an account to the configuration. If an account with the same id already /// exists, it gets replaced. mutating func addAccount(_ account: Account) { accounts[account.id] = account } /// Sets the selected account id. If the `id` is `nil`, then no account is selected. mutating func selectAccount(withId id: String?) { selectedAccountId = id } /// Adds a collection of accounts to the configuration. Any existing accounts with /// overlapping ids are replaced. mutating func addAccounts(_ accounts: [Account]) { for account in accounts { addAccount(account) } } } ================================================ FILE: Sources/Client/Config/ConfigError.swift ================================================ import Foundation public enum ConfigError: LocalizedError { /// The config file is missing a version. case missingVersion /// The config file is using an unsupported version. case unsupportedVersion(Float) /// The account in question is of an invalid type. case invalidAccountType /// No account exists with the given id. case invalidAccountId /// The currently selected account is of an invalid type. case invalidSelectedAccountType /// Failed to refresh an account. case accountRefreshFailed /// Not account has been selected. case noAccountSelected public var errorDescription: String? { switch self { case .missingVersion: return "Your config file is missing a 'version' field." case let .unsupportedVersion(version): return "Your config file version (\(version)) is unsupported. " + "\(Config.currentVersion) is the current supported version." case .invalidAccountType: return "The account in question is of an invalid type." case .invalidAccountId: return "No such account." case .invalidSelectedAccountType: return "The currently selected account is of an invalid type." case .accountRefreshFailed: return "Failed to refresh the given account." case .noAccountSelected: return "No account has been selected." } } } ================================================ FILE: Sources/Client/Config/ManagedConfig.swift ================================================ import Foundation import DeltaCore /// Manages the config stored in a config file. @dynamicMemberLookup final class ManagedConfig: ObservableObject { /// The current config. var config: Config { willSet { objectWillChange.send() } didSet { do { // TODO: Reduce the number of writes to disk, perhaps by asynchronously // debouncing. Often multiple config changes will happen in very quick // succession. try config.save(to: file) } catch { saveErrorHandler?(error) } } } subscript(dynamicMember member: WritableKeyPath) -> T { get { config[keyPath: member] } set { config[keyPath: member] = newValue } } /// The file the configuration is stored in. let file: URL /// A handler for errors which occur when attempting to save the configuration /// to disk in the background. let saveErrorHandler: ((any Error) -> Void)? /// Manages a configuration backed by a given file. init(_ config: Config, backedBy file: URL, saveErrorHandler: ((any Error) -> Void)?) { self.file = file self.config = config self.saveErrorHandler = saveErrorHandler } /// Resets the configuration to defaults. func reset() throws { config = Config() } /// Refreshes the specified account if necessary, saves it, and returns it (if /// an account exists with the given id). func refreshAccount(withId id: String) async throws -> Account { // Takes an id instead of a whole account to make it clear that it's // operating in-place on the config (taking an account would make it // unclear whether the account must be in the underlying config and // whether it gets saved after getting refreshed). guard let account = config.accounts[id] else { throw ConfigError.invalidAccountId.with("Id", id) } guard account.online?.accessToken.hasExpired == true else { return account } do { let refreshedAccount = try await account.refreshed(withClientToken: config.clientToken) config.addAccount(refreshedAccount) return refreshedAccount } catch { throw ConfigError.accountRefreshFailed .with("Username", account.username) .becauseOf(error) } } /// Gets the currently selected account (throws if no account is selected), /// and refreshes the account if necessary. May seem like the function is /// doing too much, but it's beneficial for usage of this to be concise. func selectedAccountRefreshedIfNecessary() async throws -> Account { guard let account = config.selectedAccount else { throw ConfigError.noAccountSelected } return try await refreshAccount(withId: account.id) } // TODO: Maybe we just shouldn't even refresh at app start, we could just refresh at time of // use. /// Refreshes all accounts which are close to expiring or have expired. /// - Returns: Any errors which occurred during account refreshing. func refreshAccounts() async -> [any Error] { var errors: [any Error] = [] for account in config.accounts.values { do { _ = try await refreshAccount(withId: account.id) } catch { errors.append(error) } } return errors } } extension ManagedConfig: ClientConfiguration { var render: RenderConfiguration { get { config.render } set { config.render = newValue } } var keymap: Keymap { get { config.keymap } set { config.keymap = newValue } } var toggleSprint: Bool { get { config.toggleSprint } set { config.toggleSprint = newValue } } var toggleSneak: Bool { get { config.toggleSneak } set { config.toggleSneak = newValue } } } ================================================ FILE: Sources/Client/DeltaClientApp.swift ================================================ import SwiftUI import DeltaCore /// The entry-point for Delta Client. struct DeltaClientApp: App { @StateObject var appState = StateWrapper(initial: .serverList) @StateObject var pluginEnvironment = PluginEnvironment() @StateObject var modal = Modal() @StateObject var controllerHub = ControllerHub() @State var storage: StorageDirectory? @State var hasLoaded = false let arguments: CommandLineArguments /// A Delta Client version. enum Version { /// A version such as `1.0.0`. case semantic(String) /// A nightly build's version (e.g. `ae348f8...`). case commit(String) } /// Gets the current client's version. `nil` if the app doesn't have an `Info.plist` or /// the `CFBundleShortVersionString` key is missing. static var version: Version? { guard let versionString = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String else { return nil } if versionString.hasPrefix("commit: ") { return .commit(String(versionString.dropFirst("commit: ".count))) } else { return .semantic(versionString) } } init() { arguments = CommandLineArguments.parseOrExit() setConsoleLogLevel(arguments.logLevel) DiscordManager.shared.updateRichPresence(to: .menu) } var body: some Scene { WindowGroup { LoadAndThen(arguments, $hasLoaded, $storage) { managedConfig, resourcePack, pluginEnvironment in RouterView() .environmentObject(resourcePack) .environmentObject(pluginEnvironment) .environmentObject(managedConfig) .onAppear { // TODO: Make a nice clean onboarding experience if managedConfig.selectedAccountId == nil { appState.update(to: .login) } } } .environment(\.storage, storage ?? StorageDirectoryEnvironmentKey.defaultValue) .environmentObject(modal) .environmentObject(appState) .environmentObject(controllerHub) .frame(maxWidth: .infinity, maxHeight: .infinity) .navigationTitle("Delta Client") .alert(isPresented: modal.isPresented) { Alert(title: Text("Error"), message: (modal.content?.message).map(Text.init), dismissButton: Alert.Button.default(Text("OK"))) } } #if os(macOS) .commands { // Add preferences menu item and shortcut (cmd+,) CommandGroup(after: .appSettings, addition: { Button("Preferences") { guard hasLoaded, modal.content == nil else { return } switch appState.current { case .serverList, .editServerList, .accounts, .login, .directConnect: appState.update(to: .settings(nil)) case .playServer, .settings: break } } .keyboardShortcut(KeyboardShortcut(KeyEquivalent(","), modifiers: [.command])) }) CommandGroup(after: .toolbar, addition: { Button("Logs") { guard let file = storage?.currentLogFile else { modal.error("File logging not enabled yet") return } NSWorkspace.shared.open(file) } }) CommandGroup(after: .windowSize, addition: { Button("Toggle Full Screen") { NSApp?.windows.first?.toggleFullScreen(nil) } .keyboardShortcut(KeyboardShortcut(KeyEquivalent("f"), modifiers: [.control, .command])) }) } #endif } } ================================================ FILE: Sources/Client/Discord/DiscordManager.swift ================================================ import Foundation #if os(macOS) import SwordRPC #endif /// Manages discord interactions final class DiscordManager { /// ``DiscordManager`` shared instance. public static let shared = DiscordManager() /// The discord rich presence currently being displayed on the user's profile. private var currentPresenceState: RichPresenceState? #if os(macOS) /// Manages discord rich presence. private let richPresenceManager = SwordRPC(appId: "907736809990148107") #endif private init() { #if os(macOS) _ = richPresenceManager.connect() #endif } /// Updates the user's discord rich presence state for Delta Client if the current OS is supported. /// - Parameter state: the preset to be used to configure the rich presence. public func updateRichPresence(to state: RichPresenceState) { #if os(macOS) guard currentPresenceState != state else { return } var presence = RichPresence() presence.assets.largeImage = "dark" presence.details = state.title presence.state = state.subtitle presence.timestamps.start = Date() richPresenceManager.setPresence(presence) currentPresenceState = state #endif } } ================================================ FILE: Sources/Client/Discord/DiscordPresenceState.swift ================================================ import Foundation extension DiscordManager { /// State of Discord rich presence. enum RichPresenceState: Equatable { /// The user is not currently connected to a server. case menu /// The user is playing on a server. case game(server: String?) /// Shown as the state of the game in Discord. Displayed under the name 'Delta Client'. var title: String { switch self { case .menu: return "Main menu" case .game: return "In game" } } /// Shown under `title` by Discord. var subtitle: String? { switch self { case .menu: return nil case .game(let server): if let server = server { return "Playing on '\(server)'" } return nil } } } } ================================================ FILE: Sources/Client/Extensions/Binding+onChange.swift ================================================ import Foundation import SwiftUI // This excellent solution is from https://www.hackingwithswift.com/quick-start/swiftui/how-to-run-some-code-when-state-changes-using-onchange extension Binding { func onChange(_ handler: @escaping (Value) -> Void) -> Binding { Binding( get: { self.wrappedValue }, set: { newValue in self.wrappedValue = newValue handler(newValue) } ) } } ================================================ FILE: Sources/Client/Extensions/Box+ObservableObject.swift ================================================ import Combine import DeltaCore extension Box: ObservableObject { public var objectWillChange: ObservableObjectPublisher { ObservableObjectPublisher() } } ================================================ FILE: Sources/Client/Extensions/TaskProgress+ObservableObject.swift ================================================ import Combine import DeltaCore extension TaskProgress: ObservableObject { public var objectWillChange: ObservableObjectPublisher { let publisher = ObservableObjectPublisher() onChange { _ in ThreadUtil.runInMain { publisher.send() } } return publisher } } ================================================ FILE: Sources/Client/Extensions/View.swift ================================================ import SwiftUI extension View { /// Returns a copy of self with the specified property set to the given value. /// Useful for implementing custom view modifiers. func with(_ keyPath: WritableKeyPath, _ value: T) -> Self { var view = self view[keyPath: keyPath] = value return view } /// Appends an action to an action stored property. Useful for implementing custom /// view modifiers such as `onClick` etc. Allows the modifier to be called multiple /// times without overwriting previous actions. If the stored action is nil, the /// given action becomes the stored action, otherwise the new action is appended to /// the existing action. func appendingAction( to keyPath: WritableKeyPath Void)?>, _ action: @escaping (T) -> Void ) -> Self { with(keyPath) { argument in self[keyPath: keyPath]?(argument) action(argument) } } /// Appends an action to an action stored property. Useful for implementing custom /// view modifiers such as `onClick` etc. Allows the modifier to be called multiple /// times without overwriting previous actions. If the stored action is nil, the /// given action becomes the stored action, otherwise the new action is appended to /// the existing action. func appendingAction( to keyPath: WritableKeyPath Void)?>, _ action: @escaping (T, U) -> Void ) -> Self { with(keyPath) { argument1, argument2 in self[keyPath: keyPath]?(argument1, argument2) action(argument1, argument2) } } /// Appends an action to an action stored property. Useful for implementing custom /// view modifiers such as `onClick` etc. Allows the modifier to be called multiple /// times without overwriting previous actions. If the stored action is nil, the /// given action becomes the stored action, otherwise the new action is appended to /// the existing action. func appendingAction( to keyPath: WritableKeyPath Void)?>, _ action: @escaping (T, U, V) -> Void ) -> Self { with(keyPath) { argument1, argument2, argument3 in self[keyPath: keyPath]?(argument1, argument2, argument3) action(argument1, argument2, argument3) } } /// Appends an action to an action stored property. Useful for implementing custom /// view modifiers such as `onClick` etc. Allows the modifier to be called multiple /// times without overwriting previous actions. If the stored action is nil, the /// given action becomes the stored action, otherwise the new action is appended to /// the existing action. func appendingAction( to keyPath: WritableKeyPath Void)?>, _ action: @escaping (T, U, V, W) -> Void ) -> Self { with(keyPath) { argument1, argument2, argument3, argument4 in self[keyPath: keyPath]?(argument1, argument2, argument3, argument4) action(argument1, argument2, argument3, argument4) } } } ================================================ FILE: Sources/Client/GitHub/GitHubBranch.swift ================================================ import Foundation struct GitHubBranch: Decodable { var name: String var commit: GitHubCommit } ================================================ FILE: Sources/Client/GitHub/GitHubCommit.swift ================================================ import Foundation struct GitHubCommit: Decodable { var sha: String var url: String } ================================================ FILE: Sources/Client/GitHub/GitHubComparison.swift ================================================ import Foundation /// Represents a comparison between GitHub branches and/or commits struct GitHubComparison: Decodable { /// The position difference between the compared objects in the tree enum Status: String, Decodable { case diverged case ahead case behind case identical } var status: Status } ================================================ FILE: Sources/Client/GitHub/GitHubReleasesAPIResponse.swift ================================================ import Foundation struct GitHubReleasesAPIResponse: Codable { var tagName: String var assets: [Asset] struct Asset: Codable { var browserDownloadURL: String enum CodingKeys: String, CodingKey { case browserDownloadURL = "browserDownloadUrl" } } } ================================================ FILE: Sources/Client/Input/Controller.swift ================================================ import GameController import Combine /// A control on a controller (a button, a thumbstick, a trigger, etc). protocol Control { associatedtype Element: GCControllerElement mutating func update(with element: Element) } /// A game controller (e.g. a PlayStation 5 controller). class Controller: ObservableObject { /// A display name for the controller. var name: String { var name = gcController.productCategory if gcController.playerIndex != GCControllerPlayerIndex.indexUnset { name = "\(name) (player \(gcController.playerIndex.rawValue + 1))" } return name } /// The underlying controller getting wrapped. I usually wouldn't prefix /// a property like that to match its type, but ``ControllerHub`` was getting /// so confusing with the two different types of controllers both getting /// referred to as `controller` and `controller.controller` and stuff. let gcController: GCController /// A publisher for subscribing to controller input events. var eventPublisher: AnyPublisher { eventSubject.eraseToAnyPublisher() } /// The states of all buttons, indexed by ``Button/rawValue``. Assumes that the /// raw values form a contiguous range starting from 0. private var buttonStates = Array(repeating: false, count: Button.allCases.count) /// The states of all thumbsticks, indexed by ``Thumbstick/rawValue``. Assumes that the /// raw values form a contiguous range starting from 0. private var thumbstickStates = Array( repeating: ThumbstickState(), count: Thumbstick.allCases.count ) /// Private to prevent users from publishing their own events and messing things up. private var eventSubject = PassthroughSubject() /// Wraps a controller to make it easily observable. Returns `nil` if the /// controller isn't supported (doesn't have an extended gamepad). init?(for gcController: GCController) { guard let pad = gcController.extendedGamepad else { return nil } self.gcController = gcController pad.valueChangedHandler = { [weak self] pad, element in guard let self = self else { return } // We could use `element` to skip buttons which haven't been updated, // but that wouldn't work for the dpad buttons, because in that case // the element is the dpad instead of the invidual dpad button that // changed. for button in Button.allCases { // Get the button's new state, skipping buttons which the controller doesn't have. let newState: Bool switch button.keyPath { case let .required(keyPath): newState = pad[keyPath: keyPath].isPressed case let .optional(keyPath): guard let buttonElement = pad[keyPath: keyPath] else { continue } newState = buttonElement.isPressed } // Some buttons set multiple updates when changing states because they're // analog (like the triggers on the PS5 controller), so we need to filter // those updates out. guard newState != self.buttonStates[button.rawValue] else { continue } self.buttonStates[button.rawValue] = newState if newState { self.eventSubject.send(.buttonPressed(button)) } else { self.eventSubject.send(.buttonReleased(button)) } } for thumbstick in Thumbstick.allCases { let thumbstickElement = pad[keyPath: thumbstick.keyPath] // Ignore updates which don't affect this thumbstick guard thumbstickElement == element else { continue } let x = thumbstickElement.xAxis.value let y = thumbstickElement.yAxis.value self.thumbstickStates[thumbstick.rawValue].x = x self.thumbstickStates[thumbstick.rawValue].y = y self.eventSubject.send(.thumbstickMoved(thumbstick, x: x, y: y)) } } NotificationCenter.default.addObserver( self, selector: #selector(handlePossibleDisconnect), name: NSNotification.Name.GCControllerDidDisconnect, object: nil ) } /// Due to how vague the NotificationCenter observation API is, we just know /// that *a* controller was disconnected. If it was this one, do something /// about it. @objc private func handlePossibleDisconnect() { guard !GCController.controllers().contains(gcController) else { // We survive another day, do nothing return } // TODO: Do something when a controller disconnects } } extension Controller { enum Event { /// A specific button was pressed. case buttonPressed(Button) /// A specific button was released. case buttonReleased(Button) /// The thumbstick moved to a new position `(x, y)`. case thumbstickMoved(Thumbstick, x: Float, y: Float) } /// `GCControllerButtonInput`s are sometimes optional, but we want to treat /// them all the same way so we need an enum. enum GCControllerButtonKeyPath { case required(KeyPath) case optional(KeyPath) } /// A controller button (includes triggers, shoulders, thumbstick buttons, etc). The /// raw value is used as an index when storing buttons in arrays. enum Button: Int, CaseIterable { case leftTrigger case rightTrigger case leftShoulder case rightShoulder case leftThumbstickButton case rightThumbstickButton case buttonA case buttonB case buttonX case buttonY case dpadUp case dpadDown case dpadLeft case dpadRight var keyPath: GCControllerButtonKeyPath { switch self { case .leftTrigger: return .required(\.leftTrigger) case .rightTrigger: return .required(\.rightTrigger) case .leftShoulder: return .required(\.leftShoulder) case .rightShoulder: return .required(\.rightShoulder) case .leftThumbstickButton: return .optional(\.leftThumbstickButton) case .rightThumbstickButton: return .optional(\.rightThumbstickButton) case .buttonA: return .required(\.buttonA) case .buttonB: return .required(\.buttonB) case .buttonX: return .required(\.buttonX) case .buttonY: return .required(\.buttonY) case .dpadUp: return .required(\.dpad.up) case .dpadDown: return .required(\.dpad.down) case .dpadLeft: return .required(\.dpad.left) case .dpadRight: return .required(\.dpad.right) } } } /// A controller thumbstick (often called a joystick). The raw value is used as /// an index when storing thumbsticks in arrays. enum Thumbstick: Int, CaseIterable { case left case right var keyPath: KeyPath { switch self { case .left: return \.leftThumbstick case .right: return \.rightThumbstick } } } /// The current state of a thumbstick. struct ThumbstickState { var x: Float = 0 var y: Float = 0 } } extension Controller: Equatable { static func ==(_ lhs: Controller, _ rhs: Controller) -> Bool { lhs.gcController == rhs.gcController } } extension Controller: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(gcController)) } } ================================================ FILE: Sources/Client/Input/ControllerHub.swift ================================================ import GameController import DeltaCore class ControllerHub: ObservableObject { @Published var controllers: [Controller] = [] @Published var currentController: Controller? init() { // Register notification observers. observe(NSNotification.Name.GCControllerDidConnect) observe(NSNotification.Name.GCControllerDidDisconnect) observe(NSNotification.Name.GCControllerDidBecomeCurrent) observe(NSNotification.Name.GCControllerDidStopBeingCurrent) // Check for controllers that might already be connected. updateControllers() } /// Registers an observer to update all controllers when a given event occurs. private func observe(_ event: NSNotification.Name) { NotificationCenter.default.addObserver( self, selector: #selector(updateControllers), name: event, object: nil ) } @objc private func updateControllers() { // If we jump to the main thread synchronously then some sort of internal GCController // lock never gets dropped and `GCController.current` causes a deadlock (strange). DispatchQueue.main.async { let gcControllers = GCController.controllers() // Handle newly connected controllers for gcController in gcControllers { guard !self.controllers.contains(where: { $0.gcController == gcController }), let controller = Controller(for: gcController) else { continue } gcController.playerIndex = GCControllerPlayerIndex(rawValue: self.controllers.count) ?? .indexUnset self.controllers.append(controller) log.info("Connected \(controller.name) controller") } // Handle newly disconnected controllers for (i, controller) in self.controllers.enumerated() { if !gcControllers.contains(controller.gcController) { self.controllers.remove(at: i) log.info("Disconnected \(controller.name) controller") } } // Update the current controller (last used) var current: Controller? = nil for controller in self.controllers { if controller.gcController == GCController.current { current = controller } } if self.currentController != current { self.currentController = current } } } } ================================================ FILE: Sources/Client/Input/InputMethod.swift ================================================ enum InputMethod: Hashable { case keyboardAndMouse case controller(Controller) var name: String { switch self { case .keyboardAndMouse: return "Keyboard and mouse" case let .controller(controller): return controller.gcController.productCategory } } var detail: String? { switch self { case .keyboardAndMouse: return nil case let .controller(controller): let player = controller.gcController.playerIndex if player != .indexUnset { return "player \(player.rawValue + 1)" } else { return nil } } } var isController: Bool { switch self { case .keyboardAndMouse: return false case .controller: return true } } var controller: Controller? { switch self { case .keyboardAndMouse: return nil case let .controller(controller): return controller } } } ================================================ FILE: Sources/Client/Logger.swift ================================================ @_exported import DeltaLogger ================================================ FILE: Sources/Client/Modal.swift ================================================ import DeltaCore import SwiftUI class Modal: ObservableObject { enum Content { case warning(String) case errorMessage(String) case error(Error) var message: String { switch self { case let .warning(message): return message case let .errorMessage(message): return message case let .error(error): if let richError = error as? RichError { return richError.richDescription } else { return error.localizedDescription } } } } var isPresented: Binding { Binding { self.content != nil } set: { newValue in if !newValue { self.content = nil self.dismissHandler?() } } } @Published var content: Content? private var dismissHandler: (() -> Void)? /// Handlers to call when an error occurs. Guaranteed to be called on the /// main thread. private var errorHandlers: [(Error) -> Void] = [] func onError(_ action: @escaping (Error) -> Void) { errorHandlers.append(action) } func warning(_ message: String, onDismiss dismissHandler: (() -> Void)? = nil) { log.warning(message) ThreadUtil.runInMain { content = .warning(message) self.dismissHandler = dismissHandler } } func error(_ message: String, onDismiss dismissHandler: (() -> Void)? = nil) { log.error(message) ThreadUtil.runInMain { content = .errorMessage(message) self.dismissHandler = dismissHandler for errorHandler in errorHandlers { errorHandler(RichError(message)) } } } func error(_ error: Error, onDismiss dismissHandler: (() -> Void)? = nil) { log.error(error.localizedDescription) ThreadUtil.runInMain { content = .error(error) self.dismissHandler = dismissHandler for errorHandler in errorHandlers { errorHandler(error) } } } } ================================================ FILE: Sources/Client/State/AppState.swift ================================================ import Foundation import DeltaCore /// App states indirect enum AppState: Equatable { case serverList case editServerList case accounts case login case directConnect case playServer(ServerDescriptor, paneCount: Int) case settings(SettingsState?) } ================================================ FILE: Sources/Client/State/StateWrapper.swift ================================================ import Foundation import DeltaCore /// An observable wrapper around a state enum for use with SwiftUI final class StateWrapper: ObservableObject { @Published private(set) var current: State private var history: [State] = [] /// Create a new state wrapper with the specified initial state init(initial: State) { current = initial } /// Update the app state to the state specified, on the main thread. func update(to newState: State) { ThreadUtil.runInMain { // Update state let current = self.current self.current = newState // Simplify state history if let index = history.firstIndex(where: { name(of: $0) == name(of: current) }) { history.removeLast(history.count - index) } if let index = history.firstIndex(where: { name(of: $0) == name(of: newState) }) { history.removeLast(history.count - index) } // Update state history history.append(current) } } /// Return to the previous app state func pop() { ThreadUtil.runInMain { if !history.isEmpty { let previousState = history.removeLast() update(to: previousState) } else { log.warning("failed to pop app state, no previous state to return to") } } } private func name(of state: State) -> String { return String(describing: state) } } ================================================ FILE: Sources/Client/StorageDirectory.swift ================================================ import Foundation import SwiftUI import DeltaCore /// An error thrown by ``StorageDirectory``. enum StorageDirectoryError: LocalizedError { case failedToCreateBackup var errorDescription: String? { switch self { case .failedToCreateBackup: return "Failed to create backup of storage directory." } } } struct StorageDirectoryEnvironmentKey: EnvironmentKey { static let defaultValue: StorageDirectory = StorageDirectory(URL(fileURLWithPath: ".")) } extension EnvironmentValues { var storage: StorageDirectory { get { self[StorageDirectoryEnvironmentKey.self] } set { self[StorageDirectoryEnvironmentKey.self] = newValue } } } // TODO: Find if there's a way to just have this as a struct (it's just immutable data, but needs // to be a class). /// A wrapper around Delta Client's storage directory URL. Used to define a consistent structure, /// and house useful helper methods. Never guarantees that the described directories exist. struct StorageDirectory { /// The default storage directory for the current platform. static var platformDefault: StorageDirectory? { #if os(macOS) || os(iOS) let options = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask) let base = options.first?.appendingPathComponent("dev.stackotter.delta-client") return base.map(StorageDirectory.init) #elseif os(tvOS) let base = FileManager.default.temporaryDirectory.appendingPathComponent("dev.stackotter.delta-client") try? FileManager.default.createDirectory(at: base, withIntermediateDirectories: true) return StorageDirectory(base) #elseif os(Linux) #error("Linux storage directory not implemented") #endif } /// The root of the storage directory. private(set) var baseDirectory: URL /// A custom plugin directory which overrides the default plugin directory /// location. Set to `nil` for ``StorageDirectory/pluginDirectory`` to go /// back to the default. var pluginDirectoryOverride: URL? /// The directory for assets (e.g. the vanilla resource pack). var assetDirectory: URL { baseDirectory.appendingPathComponent("assets") } /// The directory for registries (e.g. the block registry and item registry). var registryDirectory: URL { baseDirectory.appendingPathComponent("registries") } /// The directory for user-installed plugins. var pluginDirectory: URL { pluginDirectoryOverride ?? baseDirectory.appendingPathComponent("plugins") } /// The directory for performance-enhancing caches. var cacheDirectory: URL { baseDirectory.appendingPathComponent("cache") } /// The directory for GPU captures (traces). var gpuCaptureDirectory: URL { baseDirectory.appendingPathComponent("captures") } /// The directory to store log files. var logDirectory: URL { baseDirectory.appendingPathComponent("logs") } /// The current log file. var currentLogFile: URL { logDirectory.appendingPathComponent("delta-client.log") } /// The client configuration file. var configFile: URL { baseDirectory.appendingPathComponent("config.json") } /// Initializes a storage directory (without guaranteeing that it exists). init(_ base: URL) { baseDirectory = base } /// Creates a unique GPU capture output file path of the form /// `capture_dd-MM-yyyy_HH-mm-ss.gputrace`. func uniqueGPUCaptureFile() -> URL { let date = Date() let formatter = DateFormatter() formatter.dateFormat = "dd-MM-yyyy_HH-mm-ss" let fileName = "capture_\(formatter.string(from: date)).gputrace" return gpuCaptureDirectory.appendingPathComponent(fileName) } /// Creates the storage directory if it doesn't already exist. func ensureCreated() throws { guard !FileSystem.itemExists(baseDirectory) else { return } try FileSystem.createDirectory(baseDirectory) } /// Gets the location of the resource pack cache for the pack with the given name. func cache(forResourcePackNamed name: String) -> URL { cacheDirectory.appendingPathComponent("\(name).rpcache") } /// Gets the URL to a file with the given name in the storage directory. func file(_ name: String) -> URL { baseDirectory.appendingPathComponent(name) } /// Creates a backup of the storage directory. If an output file isn't supplied, a /// filename is autogenerated from the current datetime, and the backup is stored /// in the base of the storage directory. /// /// If `zipFile` is provided, and the file already exists, its existing contents /// get overwritten. func backup(to zipFile: URL? = nil) throws { let backupFile: URL if let zipFile = zipFile { backupFile = zipFile } else { let date = Date() let formatter = DateFormatter() formatter.dateFormat = "dd-MM-yyyy_HH-mm-ss" let backupName = "backup_\(formatter.string(from: date))" backupFile = file("\(backupName).zip") } do { try FileManager.default.zipItem(at: baseDirectory, to: backupFile) } catch { throw StorageDirectoryError.failedToCreateBackup.becauseOf(error) } } /// Resets the contents of the storage directory. If `keepBackups` is true, then /// any files which begin with `backup` won't get deleted. func reset(keepBackups: Bool = true) throws { let contents = try FileSystem.children(of: baseDirectory) for item in contents { // Remove item if it is not a backup if !(keepBackups && item.lastPathComponent.hasPrefix("backup")) { try FileSystem.remove(item) } } } /// Removes all caches from the storage directory. func removeCache() throws { try FileSystem.remove(cacheDirectory) } } ================================================ FILE: Sources/Client/Utility/Clipboard.swift ================================================ #if canImport(AppKit) import AppKit #elseif canImport(UIKit) import UIKit #endif /// A simple helper for managing the user's clipboard. enum Clipboard { /// Sets the contents of the user's clipboard to a given string. static func copy(_ contents: String) { #if canImport(AppKit) NSPasteboard.general.clearContents() NSPasteboard.general.setString(contents, forType: .string) #elseif os(iOS) UIPasteboard.general.string = contents #elseif os(tvOS) #warning("Remove dependence on copy on tvOS") #else #error("Unsupported platform, unknown clipboard implementation") #endif } } ================================================ FILE: Sources/Client/Utility/Updater.swift ================================================ #if os(macOS) import SwiftUI import DeltaCore /// An error thrown by ``Updater``. enum UpdaterError: LocalizedError { case failedToGetDownloadURL case failedToGetDownloadURLFromGitHubReleases case alreadyUpToDate case failedToGetBranches case failedToGetGitHubAPIResponse case failedToDownloadUpdate case failedToSaveDownload case failedToUnzipUpdate case failedToDeleteCache case invalidReleaseURL case invalidNightlyURL case invalidGitHubComparisonURL var errorDescription: String? { switch self { case .failedToGetDownloadURL: return "Failed to get download URL." case .failedToGetDownloadURLFromGitHubReleases: return "Failed to get download URL from GitHub Releases." case .alreadyUpToDate: return "You are already up to date." case .failedToGetBranches: return "Failed to get branches." case .failedToGetGitHubAPIResponse: return "Failed to get GitHub API response." case .failedToDownloadUpdate: return "Failed to download update." case .failedToSaveDownload: return "Failed to save download to disk." case .failedToUnzipUpdate: return "Failed to unzip update." case .failedToDeleteCache: return "Failed to delete cache." case .invalidReleaseURL: return "Invalid release URL." case .invalidNightlyURL: return "Invalid nightly URL." case .invalidGitHubComparisonURL: return "Invalid GitHub comparison URL." } } } /// An update to perform. enum Update { /// Update from GitHub releases. case latestRelease /// Update from latest CI build. case nightly(branch: String) /// Whether the update is nightly or not. var isNightly: Bool { switch self { case .latestRelease: return false case .nightly: return true } } } /// A download for an update. struct Download { /// The download's URL. var url: URL /// The version to display. var version: String } /// Used to update the client to either the latest successful CI build or the latest GitHub release. enum Updater { /// A step in an update. Used to track progress. enum UpdateStep: TaskStep { case downloadUpdate case unzipUpdate case unzipUpdateSecondLayer case deleteCache case tMinus3 case tMinus2 case tMinus1 var message: String { switch self { case .downloadUpdate: return "Downloading update" case .unzipUpdate: return "Unzipping update" case .unzipUpdateSecondLayer: return "Unzipping second layer of update" case .deleteCache: return "Deleting cache" case .tMinus3: return "Restarting app in 3" case .tMinus2: return "Restarting app in 2" case .tMinus1: return "Restarting app in 1" } } var relativeDuration: Double { switch self { case .downloadUpdate: return 10 case .unzipUpdate: return 2 case .unzipUpdateSecondLayer: return 2 case .deleteCache: return 1 case .tMinus3: return 1 case .tMinus2: return 1 case .tMinus1: return 1 } } } /// Performs a given update. Once the update's version string is known, `displayVersion` /// is updated (allowing a UI to display the version before the update has finished). /// `storage` is used to delete the cache before restarting the app. /// /// Never returns (unless an error occurs) because it restarts the app to allow the /// update to take effect. static func performUpdate(download: Download, isNightly: Bool, storage: StorageDirectory, progress: TaskProgress? = nil) async throws -> Never { let progress = progress ?? TaskProgress() // Download the release let data = try await progress.perform(.downloadUpdate) { observeStepProgress in try await withCheckedThrowingContinuation { continuation in let task = URLSession.shared.dataTask(with: download.url) { data, response, error in if let data = data { continuation.resume(returning: data) } else { var richError: any LocalizedError = UpdaterError.failedToDownloadUpdate if let error = error { richError = richError.becauseOf(error) } continuation.resume(throwing: richError) } } observeStepProgress(task.progress) task.resume() } } try Task.checkCancellation() let temp = FileManager.default.temporaryDirectory let zipFile = temp.appendingPathComponent("DeltaClient.zip") let outputDirectory = temp.appendingPathComponent("DeltaClient-\(UUID().uuidString)") do { try data.write(to: zipFile) } catch { throw UpdaterError.failedToSaveDownload.becauseOf(error) } try Task.checkCancellation() try await progress.perform(.unzipUpdate) { observeStepProgress in do { let progress = Progress() observeStepProgress(progress) try FileManager.default.unzipItem(at: zipFile, to: outputDirectory, skipCRC32: true, progress: progress) } catch { throw UpdaterError.failedToUnzipUpdate.becauseOf(error) } } try Task.checkCancellation() // Nightly builds have two layers of zip for whatever reason try await progress.perform(.unzipUpdateSecondLayer, if: isNightly) { observeStepProgress in let progress = Progress() observeStepProgress(progress) try FileManager.default.unzipItem( at: outputDirectory.appendingPathComponent("DeltaClient.zip"), to: outputDirectory, skipCRC32: true, progress: progress ) } try Task.checkCancellation() // Delete the cache to avoid common issues which can occur after updating try progress.perform(.deleteCache) { do { try FileSystem.remove(storage.cacheDirectory) } catch { throw UpdaterError.failedToDeleteCache.becauseOf(error) } } try Task.checkCancellation() progress.update(to: .tMinus3) try await Task.sleep(nanoseconds: 1_000_000_000) try Task.checkCancellation() progress.update(to: .tMinus2) try await Task.sleep(nanoseconds: 1_000_000_000) try Task.checkCancellation() progress.update(to: .tMinus1) try await Task.sleep(nanoseconds: 1_000_000_000) try Task.checkCancellation() // Create a background task to replace the app and relaunch let newApp = outputDirectory .appendingPathComponent("DeltaClient.app").path .replacingOccurrences(of: " ", with: "\\ ") let currentApp = Bundle.main.bundlePath.replacingOccurrences(of: " ", with: "\\ ") let logFile = storage.baseDirectory .appendingPathComponent("output.log").path .replacingOccurrences(of: " ", with: "\\ ") // TODO: Refactor to avoid potential for command injection attacks (relatively low impact anyway, // Delta Client doesn't run with elevated privileges, and this requires user interaction). Utils.shell( #"nohup sh -c 'sleep 3; rm -rf \#(currentApp); mv \#(newApp) \#(currentApp); open \#(currentApp); open \#(currentApp)' >\#(logFile) 2>&1 &"# ) Foundation.exit(0) } /// Gets the download for a given update. static func getDownload(for update: Update) throws -> Download { switch update { case .latestRelease: return try getLatestReleaseDownload() case .nightly(let branch): return try getLatestNightlyDownload(branch: branch) } } /// Gets the download for the latest GitHub release. static func getLatestReleaseDownload() throws -> Download { var decoder = CustomJSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let apiURL = URL(string: "https://api.github.com/repos/stackotter/delta-client/releases")! let data: Data let response: [GitHubReleasesAPIResponse] do { data = try Data(contentsOf: apiURL) response = try decoder.decode([GitHubReleasesAPIResponse].self, from: data) } catch { throw UpdaterError.failedToGetGitHubAPIResponse.becauseOf(error) } guard let tagName = response.first?.tagName, let downloadURL = response.first?.assets.first?.browserDownloadURL else { throw UpdaterError.failedToGetDownloadURLFromGitHubReleases } guard let url = URL(string: downloadURL) else { throw UpdaterError.invalidReleaseURL.with("URL", downloadURL) } return Download(url: url, version: tagName) } /// Gets the download for the artifact uploaded by the latest successful GitHub action run /// on a given branch. static func getLatestNightlyDownload(branch: String) throws -> Download { let branches = try getBranches() guard let commit = (branches.filter { $0.name == branch }.first?.commit) else { throw UpdaterError.failedToGetDownloadURL.with("Reason", "Branch '\(branch)' doesn't exist.") } if case let .commit(currentCommit) = DeltaClientApp.version { guard currentCommit != commit.sha else { throw UpdaterError.alreadyUpToDate.with("Current commit", currentCommit) } } let hash = commit.sha.prefix(7) let url = "https://backend.deltaclient.app/download/\(branch)/latest/DeltaClient.app.zip" guard let url = URL(string: url) else { throw UpdaterError.invalidNightlyURL.with("URL", url) } return Download(url: url, version: "commit \(hash) (latest)") } /// Gets basic information about all branches of the Delta Client GitHub repository. static func getBranches() throws -> [GitHubBranch] { let url = URL(string: "https://api.github.com/repos/stackotter/delta-client/branches")! do { let data = try Data(contentsOf: url) let response = try CustomJSONDecoder().decode([GitHubBranch].self, from: data) return response } catch { throw UpdaterError.failedToGetBranches.becauseOf(error) } } /// Compares two gitrefs in the Delta Client GitHub repository. static func compareGitRefs(_ first: String, _ second: String) throws -> GitHubComparison.Status { let url = "https://api.github.com/repos/stackotter/delta-client/compare/\(first)...\(second)" guard let url = URL(string: url) else { throw UpdaterError.invalidGitHubComparisonURL.with("URL", url) } let data = try Data(contentsOf: url) return try CustomJSONDecoder().decode(GitHubComparison.self, from: data).status } /// Checks if the user is on the main branch and a newer commit is available. static func isUpdateAvailable() throws -> Bool { guard case let .commit(commit) = DeltaClientApp.version else { return false } // TODO: When releases are supported again, check for newer releases if the user if on a release build. let status = try compareGitRefs(commit, "main") return status == .behind } } #endif ================================================ FILE: Sources/Client/Utility/Utils.swift ================================================ import Foundation enum Utils { #if os(macOS) /// Runs a shell command. static func shell(_ command: String) { let task = Process() task.arguments = ["-c", command] task.launchPath = "/bin/bash" task.launch() } /// Relaunches the application. static func relaunch() { log.info("Relaunching Delta Client") let url = URL(fileURLWithPath: Bundle.main.resourcePath!) let path = url.deletingLastPathComponent().deletingLastPathComponent().absoluteString let task = Process() task.launchPath = "/usr/bin/open" task.arguments = [path] task.launch() exit(0) } #endif } ================================================ FILE: Sources/Client/Views/Play/DirectConnectView.swift ================================================ import SwiftUI import DeltaCore struct DirectConnectView: View { @EnvironmentObject var appState: StateWrapper @State var host: String = "" @State var port: UInt16? = nil @State var errorMessage: String? = nil @State var isAddressValid = false private func verify() -> Bool { if !isAddressValid { errorMessage = "Invalid IP" } else { return true } return false } var body: some View { VStack { AddressField("Server address", host: $host, port: $port, isValid: $isAddressValid) if let message = errorMessage { Text(message) .bold() } HStack { Button("Cancel") { appState.update(to: .serverList) } .buttonStyle(SecondaryButtonStyle()) Button("Connect") { if verify() { let descriptor = ServerDescriptor(name: "Direct Connect", host: host, port: port) appState.update(to: .playServer(descriptor, paneCount: 1)) } } .buttonStyle(PrimaryButtonStyle()) } .padding(.top, 16) } #if !os(tvOS) .frame(width: 200) #endif #if !os(iOS) .onExitCommand { appState.update(to: .serverList) } #endif } } ================================================ FILE: Sources/Client/Views/Play/GameView.swift ================================================ import SwiftUI import DeltaCore import DeltaRenderer import Combine /// Where the real Minecraft stuff happens. This renders the actual game itself and /// also handles user input. struct GameView: View { enum GameState { case playing case gpuFrameCaptureComplete(file: URL) } @EnvironmentObject var appState: StateWrapper @EnvironmentObject var managedConfig: ManagedConfig @EnvironmentObject var modal: Modal @Environment(\.storage) var storage: StorageDirectory @State var state: GameState = .playing @State var inputCaptured = true @State var cursorCaptured = true @Binding var inGameMenuPresented: Bool var serverDescriptor: ServerDescriptor var account: Account var controller: Controller? var controllerOnly: Bool init( connectingTo serverDescriptor: ServerDescriptor, with account: Account, controller: Controller?, controllerOnly: Bool, inGameMenuPresented: Binding ) { self.serverDescriptor = serverDescriptor self.account = account self.controller = controller self.controllerOnly = controllerOnly _inGameMenuPresented = inGameMenuPresented } var body: some View { JoinServerAndThen(serverDescriptor, with: account) { client in WithRenderCoordinator(for: client) { renderCoordinator in VStack { switch state { case .playing: ZStack { WithController(controller, listening: $inputCaptured) { if controllerOnly { gameView(client: client, renderCoordinator: renderCoordinator) } else { InputView(listening: $inputCaptured, cursorCaptured: !inGameMenuPresented && cursorCaptured) { gameView(client: client, renderCoordinator: renderCoordinator) } .onKeyPress { [weak client] key, characters in client?.press(key, characters) } .onKeyRelease { [weak client] key in client?.release(key) } .onMouseMove { [weak client] x, y, deltaX, deltaY in // TODO: Formalise this adjustment factor somewhere let sensitivityAdjustmentFactor: Float = 0.004 let sensitivity = sensitivityAdjustmentFactor * managedConfig.mouseSensitivity client?.moveMouse(x: x, y: y, deltaX: sensitivity * deltaX, deltaY: sensitivity * deltaY) } .passthroughClicks(!cursorCaptured) } } .onButtonPress { [weak client] button in guard let input = input(for: button) else { return } client?.press(input) } .onButtonRelease { [weak client] button in guard let input = input(for: button) else { return } client?.release(input) } .onThumbstickMove { [weak client] thumbstick, x, y in switch thumbstick { case .left: client?.moveLeftThumbstick(x, y) case .right: client?.moveRightThumbstick(x, y) } } #if os(tvOS) .focusable(!inGameMenuPresented) .onExitCommand { inGameMenuPresented = true } #endif } case .gpuFrameCaptureComplete(let file): frameCaptureResult(file) .onAppear { cursorCaptured = false inputCaptured = false } } } .onAppear { modal.onError { [weak client] _ in client?.game.tickScheduler.cancel() cursorCaptured = false inputCaptured = false } registerEventHandler(client, renderCoordinator) } } cancellationHandler: { appState.update(to: .serverList) } } cancellationHandler: { appState.update(to: .serverList) } .onChange(of: inGameMenuPresented) { presented in if presented { cursorCaptured = false inputCaptured = false } else { cursorCaptured = true inputCaptured = true } } } func registerEventHandler(_ client: Client, _ renderCoordinator: RenderCoordinator) { client.eventBus.registerHandler { event in switch event { case _ as OpenInGameMenuEvent: inGameMenuPresented = true client.releaseAllInputs() case _ as ReleaseCursorEvent: cursorCaptured = false case _ as CaptureCursorEvent: cursorCaptured = true case let event as KeyPressEvent where event.input == .performGPUFrameCapture: let outputFile = storage.uniqueGPUCaptureFile() do { try renderCoordinator.captureFrames(count: 10, to: outputFile) } catch { modal.error(RichError("Failed to start frame capture").becauseOf(error)) } case let event as FinishFrameCaptureEvent: ThreadUtil.runInMain { state = .gpuFrameCaptureComplete(file: event.file) } default: break } } } func gameView(client: Client, renderCoordinator: RenderCoordinator) -> some View { ZStack { if #available(macOS 13, iOS 16, *) { MetalView(renderCoordinator: renderCoordinator) .onAppear { cursorCaptured = true inputCaptured = true } } else { MetalViewClass(renderCoordinator: renderCoordinator) .onAppear { cursorCaptured = true inputCaptured = true } } #if os(iOS) movementControls(client) #endif } } /// Gets the input associated with a particular controller button. func input(for button: Controller.Button) -> Input? { switch button { case .buttonA: return .jump case .leftTrigger: return .place case .rightTrigger: return .destroy case .leftShoulder: return .previousSlot case .rightShoulder: return .nextSlot case .leftThumbstickButton: return .sprint case .buttonB: return .sneak case .dpadUp: return .changePerspective case .dpadRight: return .openChat default: return nil } } func frameCaptureResult(_ file: URL) -> some View { VStack { Text("GPU frame capture complete") Group { #if os(macOS) Button("Show in finder") { NSWorkspace.shared.activateFileViewerSelecting([file]) }.buttonStyle(SecondaryButtonStyle()) #else // TODO: Add a file sharing menu for iOS and tvOS Text("I have no clue how to get hold of the file") #endif Button("OK") { state = .playing }.buttonStyle(PrimaryButtonStyle()) }.frame(width: 200) } } #if os(iOS) func movementControls(_ client: Client) -> some View { VStack { Spacer() HStack { HStack(alignment: .bottom) { movementControl("a", .strafeLeft, client) VStack { movementControl("w", .moveForward, client) movementControl("s", .moveBackward, client) } movementControl("d", .strafeRight, client) } Spacer() VStack { movementControl("*", .jump, client) movementControl("_", .sneak, client) } } } } func movementControl(_ label: String, _ input: Input, _ client: Client) -> some View { return ZStack { Color.blue.frame(width: 50, height: 50) Text(label) }.onLongPressGesture( minimumDuration: 100000000000, maximumDistance: 50, perform: { return }, onPressingChanged: { [weak client] isPressing in if isPressing { client?.press(input) } else { client?.release(input) } } ) } #endif } ================================================ FILE: Sources/Client/Views/Play/InGameMenu.swift ================================================ import SwiftUI struct InGameMenu: View { enum InGameMenuState { case menu case settings } @EnvironmentObject var appState: StateWrapper @Binding var presented: Bool @State var state: InGameMenuState = .menu #if os(tvOS) @FocusState var focusState: FocusElements? func moveFocus(_ direction: MoveCommandDirection) { if let focusState = focusState { let step: Int switch direction { case .down: step = 1 case .up: step = -1 case .left, .right: return } let count = FocusElements.allCases.count // Add an extra count before taking the modulo cause Swift's mod operator isn't // the real mathematical modulo. let index = (focusState.rawValue + step + count) % count self.focusState = FocusElements.allCases[index] } } enum FocusElements: Int, CaseIterable { case backToGame case settings case disconnect } #endif init(presented: Binding) { _presented = presented } var body: some View { if presented { GeometryReader { geometry in VStack { switch state { case .menu: VStack { Button("Back to game") { presented = false } #if os(tvOS) .focused($focusState, equals: .backToGame) #else .buttonStyle(PrimaryButtonStyle()) .keyboardShortcut(.escape, modifiers: []) #endif Button("Settings") { state = .settings } #if os(tvOS) .focused($focusState, equals: .settings) #endif .buttonStyle(SecondaryButtonStyle()) Button("Disconnect") { appState.update(to: .serverList) } #if os(tvOS) .focused($focusState, equals: .disconnect) #endif .buttonStyle(SecondaryButtonStyle()) } #if !os(tvOS) .frame(width: 200) #endif case .settings: SettingsView(isInGame: true) { state = .menu } } } .frame(width: geometry.size.width, height: geometry.size.height) .background(Color.black.opacity(0.702), alignment: .center) #if os(tvOS) .onAppear { focusState = .backToGame } .focusSection() #endif } } } } ================================================ FILE: Sources/Client/Views/Play/InputView.swift ================================================ import SwiftUI import DeltaCore import DeltaRenderer struct InputView: View { @EnvironmentObject var modal: Modal @EnvironmentObject var appState: StateWrapper @State var monitorsAdded = false @State var scrollWheelDeltaY: Float = 0 #if os(macOS) @State var previousModifierFlags: NSEvent.ModifierFlags? #endif @Binding var listening: Bool private var content: () -> Content private var handleKeyRelease: ((Key) -> Void)? private var handleKeyPress: ((Key, [Character]) -> Void)? private var handleMouseMove: (( _ x: Float, _ y: Float, _ deltaX: Float, _ deltaY: Float ) -> Void)? private var handleScroll: ((_ deltaY: Float) -> Void)? private var shouldPassthroughClicks = false private var shouldAvoidGeometryReader = false init( listening: Binding, cursorCaptured: Bool, @ViewBuilder _ content: @escaping () -> Content ) { _listening = listening self.content = content if cursorCaptured { Self.captureCursor() } else { Self.releaseCursor() } } /// Captures the cursor (locks it in place and makes it invisible). private static func captureCursor() { #if os(macOS) CGAssociateMouseAndMouseCursorPosition(0) NSCursor.hide() #endif } /// Releases the cursor, making it visible and able to move around. private static func releaseCursor() { #if os(macOS) CGAssociateMouseAndMouseCursorPosition(1) NSCursor.unhide() #endif } /// If listening, the view will still process clicks, but the click will /// get passed through for the underlying view to process as well. func passthroughClicks(_ passthroughClicks: Bool = true) -> Self { with(\.shouldPassthroughClicks, passthroughClicks) } /// When `true`, `GeometryReader` won't be used, but mouse movements /// won't be tracked. This can be used when mouse movements aren't /// required but the `GeometryReader` is messing with layouts. func avoidGeometryReader(_ avoidGeometryReader: Bool = true) -> Self { with(\.shouldAvoidGeometryReader, avoidGeometryReader) } /// Adds an action to run when a key is released. func onKeyRelease(_ action: @escaping (Key) -> Void) -> Self { appendingAction(to: \.handleKeyRelease, action) } /// Adds an action to run when a key is pressed. func onKeyPress(_ action: @escaping (Key, [Character]) -> Void) -> Self { appendingAction(to: \.handleKeyPress, action) } /// Adds an action to run when the mouse is moved. func onMouseMove(_ action: @escaping (_ x: Float, _ y: Float, _ deltaX: Float, _ deltaY: Float) -> Void) -> Self { appendingAction(to: \.handleMouseMove, action) } /// Adds an action to run when scrolling occurs. func onScroll(_ action: @escaping (_ deltaY: Float) -> Void) -> Self { appendingAction(to: \.handleScroll, action) } #if os(macOS) func mousePositionInView(with geometry: GeometryProxy) -> (x: Float, y: Float)? { // This assumes that there's only one window and that this is only called once // the view's body has been evaluated at least once. guard let window = NSApplication.shared.orderedWindows.first else { return nil } let viewFrame = geometry.frame(in: .global) let x = (NSEvent.mouseLocation.x - window.frame.minX) - viewFrame.minX let y = window.frame.maxY - NSEvent.mouseLocation.y - viewFrame.minY // AppKit gives us the position scaled by the screen's scaling factor, so we // adjust it back to get the position in terms of true pixels. let scalingFactor = CGFloat(GUIRenderer.screenScalingFactor()) return (Float(x * scalingFactor), Float(y * scalingFactor)) } #endif var body: some View { VStack { if shouldAvoidGeometryReader { contentWithEventListeners() } else { GeometryReader { geometry in contentWithEventListeners(geometry) } } } } func contentWithEventListeners(_ geometry: GeometryProxy? = nil) -> some View { // Make sure that the latest position is known to any observers (e.g. if // listening was disabled and now isn't, observers won't have been told // about any changes that occured during the period in which listening // was disabled). #if os(macOS) if let geometry = geometry { if let mousePosition = mousePositionInView(with: geometry) { handleMouseMove?(mousePosition.x, mousePosition.y, 0, 0) } else { modal.error("Failed to get mouse position (on demand)") { appState.update(to: .serverList) } } } #endif return content() #if os(iOS) .gesture(TapGesture(count: 2).onEnded { _ in handleKeyPress?(.escape, []) }) .gesture(LongPressGesture(minimumDuration: 2, maximumDistance: 9).onEnded { _ in handleKeyPress?(.f3, []) }) .gesture(DragGesture(minimumDistance: 0, coordinateSpace: .global).onChanged { value in // TODO: Implement absolute handleMouseMove?( Float(value.location.x), Float(value.location.y), Float(value.translation.width), Float(value.translation.height) ) }) #endif #if os(macOS) .onDisappear { Self.releaseCursor() } .onAppear { if !monitorsAdded { NSEvent.addLocalMonitorForEvents(matching: [.mouseMoved, .leftMouseDragged, .rightMouseDragged, .otherMouseDragged], handler: { event in guard listening, let geometry = geometry else { return event } guard let mousePosition = mousePositionInView(with: geometry) else { modal.error("Failed to get mouse position") { appState.update(to: .serverList) } return event } let x = mousePosition.x let y = mousePosition.y let deltaX = Float(event.deltaX) let deltaY = Float(event.deltaY) handleMouseMove?(x, y, deltaX, deltaY) return event }) NSEvent.addLocalMonitorForEvents(matching: [.scrollWheel], handler: { event in if !listening { return event } let deltaY = Float(event.scrollingDeltaY) handleScroll?(deltaY) scrollWheelDeltaY += deltaY // TODO: Implement a scroll wheel sensitivity setting let threshold: Float = 0.5 let key: Key if scrollWheelDeltaY >= threshold { key = .scrollUp } else if deltaY <= -threshold { key = .scrollDown } else { return nil } scrollWheelDeltaY = 0 handleKeyPress?(key, []) handleKeyRelease?(key) return nil }) NSEvent.addLocalMonitorForEvents(matching: [.rightMouseDown, .leftMouseDown, .otherMouseDown], handler: { event in if !listening { return event } if event.associatedEventsMask.contains(.leftMouseDown) { handleKeyPress?(.leftMouseButton, []) } if event.associatedEventsMask.contains(.rightMouseDown) { handleKeyPress?(.rightMouseButton, []) } if event.associatedEventsMask.contains(.otherMouseDown) { handleKeyPress?(.otherMouseButton(event.buttonNumber), []) } return shouldPassthroughClicks ? event : nil }) NSEvent.addLocalMonitorForEvents(matching: [.rightMouseUp, .leftMouseUp, .otherMouseUp], handler: { event in if !listening { return event } if event.associatedEventsMask.contains(.leftMouseUp) { handleKeyRelease?(.leftMouseButton) } if event.associatedEventsMask.contains(.rightMouseUp) { handleKeyRelease?(.rightMouseButton) } if event.associatedEventsMask.contains(.otherMouseUp) { handleKeyRelease?(.otherMouseButton(event.buttonNumber)) } return shouldPassthroughClicks ? event : nil }) NSEvent.addLocalMonitorForEvents(matching: [.keyDown], handler: { event in if !listening { return event } if let key = Key(keyCode: event.keyCode) { handleKeyPress?(key, Array(event.characters ?? "")) if key == .q && event.modifierFlags.contains(.command) { // Pass through quit command return event } if key == .f && event.modifierFlags.contains(.command) && event.modifierFlags.contains(.control) { // Pass through full screen command return event } } return nil }) NSEvent.addLocalMonitorForEvents(matching: [.keyUp], handler: { event in if !listening { return event } if let key = Key(keyCode: event.keyCode) { handleKeyRelease?(key) } return event }) NSEvent.addLocalMonitorForEvents(matching: [.flagsChanged], handler: { event in if !listening { return event } let raw = Int32(event.modifierFlags.rawValue) let previousRaw = Int32(previousModifierFlags?.rawValue ?? 0) func check(_ key: Key, mask: Int32) { if raw & mask != 0 && previousRaw & mask == 0 { handleKeyPress?(key, []) } else if raw & mask == 0 && previousRaw & mask != 0 { handleKeyRelease?(key) } } check(.leftOption, mask: NX_DEVICELALTKEYMASK) check(.leftCommand, mask: NX_DEVICELCMDKEYMASK) check(.leftControl, mask: NX_DEVICELCTLKEYMASK) check(.leftShift, mask: NX_DEVICELSHIFTKEYMASK) check(.rightOption, mask: NX_DEVICERALTKEYMASK) check(.rightCommand, mask: NX_DEVICERCMDKEYMASK) check(.rightControl, mask: NX_DEVICERCTLKEYMASK) check(.rightShift, mask: NX_DEVICERSHIFTKEYMASK) previousModifierFlags = event.modifierFlags return event }) } monitorsAdded = true } #endif } } ================================================ FILE: Sources/Client/Views/Play/JoinServerAndThen.swift ================================================ import SwiftUI import DeltaCore enum ServerJoinState { case connecting case loggingIn case downloadingChunks(received: Int, total: Int) case joined var message: String { switch self { case .connecting: return "Establishing connection..." case .loggingIn: return "Logging in..." case .downloadingChunks: return "Downloading terrain..." case .joined: return "Joined successfully" } } } enum ServerJoinError: LocalizedError { case failedToRefreshAccount case failedToSendJoinServerRequest var errorDescription: String? { switch self { case .failedToRefreshAccount: return "Failed to refresh account." case .failedToSendJoinServerRequest: return "Failed to send join server request." } } } struct JoinServerAndThen: View { @EnvironmentObject var resourcePack: Box @EnvironmentObject var pluginEnvironment: PluginEnvironment @EnvironmentObject var managedConfig: ManagedConfig @EnvironmentObject var modal: Modal @State var state: ServerJoinState = .connecting @State var client: Client? /// Both `timeReceived` and `terrainDownloaded` must be true for us /// to be considered joined. This prevents annoying visual flashes caused /// by the time changing shortly after rendering begins. @State var timeReceived = false @State var terrainDownloaded = false var serverDescriptor: ServerDescriptor /// Beware that this account may be outdated once the server has been /// joined, as the account may have been refreshed. It should only be /// used to join once (or only for its id and username). var account: Account var content: (Client) -> Content var cancel: () -> Void init( _ serverDescriptor: ServerDescriptor, with account: Account, @ViewBuilder content: @escaping (Client) -> Content, cancellationHandler cancel: @escaping () -> Void ) { self.serverDescriptor = serverDescriptor self.account = account self.content = content self.cancel = cancel } var body: some View { VStack { switch state { case .connecting, .loggingIn, .downloadingChunks: Text(state.message) if case let .downloadingChunks(received, total) = state { HStack { ProgressView(value: Double(received) / Double(total)) Text("\(received) of \(total)") } #if !os(tvOS) .frame(maxWidth: 200) #endif } Button("Cancel", action: cancel) .buttonStyle(SecondaryButtonStyle()) #if !os(tvOS) .frame(width: 150) #endif case .joined: if let client = client { content(client) } else { Text("Loading...").onAppear { modal.error(RichError("UI entered invalid state while joining server.")) { cancel() } } } } } .onAppear { let client = Client( resourcePack: resourcePack.value, configuration: managedConfig ) pluginEnvironment.addEventBus(client.eventBus) pluginEnvironment.handleWillJoinServer(server: serverDescriptor, client: client) Task { do { try await joinServer(serverDescriptor, with: account, client: client) } catch { modal.error(error) cancel() } } // An internal state variable used to reduce the number of state updates performed // when downloading chunks (otherwise it lags SwiftUI). var received = 0 client.eventBus.registerHandler { [weak client] event in guard let client = client else { return } handleEvent(&received, client, event) } self.client = client } .onDisappear { client?.disconnect() } } func handleEvent(_ received: inout Int, _ client: Client, _ event: Event) { // TODO: Clean up Events API (there should probably just be one error event, see what the Discord // server reckons) switch event { case _ as LoginStartEvent: ThreadUtil.runInMain { state = .loggingIn } case let connectionFailedEvent as ConnectionFailedEvent: modal.error( RichError("Connection to \(serverDescriptor) failed.") .becauseOf(connectionFailedEvent.networkError) ) { cancel() } case _ as JoinWorldEvent: // Approximation of the number of chunks the server will send (used in progress indicator) let totalChunksToReceieve = Int(Foundation.pow(Double(client.game.maxViewDistance * 2 + 3), 2)) state = .downloadingChunks(received: 0, total: totalChunksToReceieve) case _ as World.Event.AddChunk: ThreadUtil.runInMain { if case let .downloadingChunks(_, total) = state { // An intermediate variable is used to reduce the number of SwiftUI updates generated by downloading chunks received += 1 if received % 50 == 0 { state = .downloadingChunks(received: received, total: total) } } } case _ as TerrainDownloadCompletionEvent: terrainDownloaded = true if timeReceived { state = .joined } case _ as World.Event.TimeUpdate: timeReceived = true if terrainDownloaded { state = .joined } case let disconnectEvent as LoginDisconnectEvent: modal.error( RichError("Disconnected from server during login.").with("Reason", disconnectEvent.reason) ) { cancel() } case let packetError as PacketHandlingErrorEvent: modal.error( RichError("Failed to handle packet with id \(packetError.packetId.hexWithPrefix).") .with("Reason", packetError.error) ) { cancel() } case let packetError as PacketDecodingErrorEvent: modal.error( RichError("Failed to decode packet with id \(packetError.packetId.hexWithPrefix).") .with("Reason", packetError.error) ) { cancel() } case let generalError as ErrorEvent: modal.error(RichError(generalError.message ?? "Client error.").becauseOf(generalError.error)) { cancel() } default: break } } func joinServer( _ descriptor: ServerDescriptor, with account: Account, client: Client ) async throws { // Refresh the account (if it's an online account) and then join the server let refreshedAccount: Account do { refreshedAccount = try await managedConfig.refreshAccount(withId: account.id) } catch { throw ServerJoinError.failedToRefreshAccount .with("Username", account.username) .becauseOf(error) } do { try await client.joinServer( describedBy: descriptor, with: refreshedAccount ) } catch { throw ServerJoinError.failedToSendJoinServerRequest.becauseOf(error) } } } ================================================ FILE: Sources/Client/Views/Play/MetalView.swift ================================================ import Foundation import DeltaCore import DeltaRenderer import MetalKit import SwiftUI @available(macOS 13, *) @available(iOS 16, *) struct MetalView { var renderCoordinator: RenderCoordinator init(renderCoordinator: RenderCoordinator) { self.renderCoordinator = renderCoordinator } func makeCoordinator() -> RenderCoordinator { return renderCoordinator } func makeMTKView(renderCoordinator: RenderCoordinator) -> MTKView { let mtkView = MTKView() if let metalDevice = MTLCreateSystemDefaultDevice() { mtkView.device = metalDevice } mtkView.delegate = renderCoordinator mtkView.preferredFramesPerSecond = 10000 mtkView.framebufferOnly = true mtkView.clearColor = MTLClearColorMake(0, 0, 0, 1) mtkView.drawableSize = mtkView.frame.size mtkView.depthStencilPixelFormat = .depth32Float // Accept input mtkView.becomeFirstResponder() return mtkView } } @available(macOS, deprecated: 13, renamed: "MetalView") @available(iOS, deprecated: 16, renamed: "MetalView") final class MetalViewClass { var renderCoordinator: RenderCoordinator init(renderCoordinator: RenderCoordinator) { self.renderCoordinator = renderCoordinator } func makeCoordinator() -> RenderCoordinator { return renderCoordinator } func makeMTKView(renderCoordinator: RenderCoordinator) -> MTKView { let mtkView = MTKView() if let metalDevice = MTLCreateSystemDefaultDevice() { mtkView.device = metalDevice } mtkView.delegate = renderCoordinator mtkView.preferredFramesPerSecond = 10000 mtkView.framebufferOnly = true mtkView.clearColor = MTLClearColorMake(0, 0, 0, 1) mtkView.drawableSize = mtkView.frame.size mtkView.depthStencilPixelFormat = .depth32Float mtkView.clearDepth = 1.0 // Accept input mtkView.becomeFirstResponder() return mtkView } } #if canImport(AppKit) @available(macOS 13, *) extension MetalView: NSViewRepresentable { func makeNSView(context: Context) -> some NSView { return makeMTKView(renderCoordinator: context.coordinator) } func updateNSView(_ view: NSViewType, context: Context) {} } extension MetalViewClass: NSViewRepresentable { func makeNSView(context: Context) -> some NSView { return makeMTKView(renderCoordinator: context.coordinator) } func updateNSView(_ view: NSViewType, context: Context) {} } #elseif canImport(UIKit) @available(iOS 16, *) extension MetalView: UIViewRepresentable { func makeUIView(context: Context) -> some UIView { return makeMTKView(renderCoordinator: context.coordinator) } func updateUIView(_ view: UIViewType, context: Context) {} } extension MetalViewClass: UIViewRepresentable { func makeUIView(context: Context) -> some UIView { return makeMTKView(renderCoordinator: context.coordinator) } func updateUIView(_ view: UIViewType, context: Context) {} } #else #error("Unsupported platform, no MetalView SwiftUI compatibility") #endif ================================================ FILE: Sources/Client/Views/Play/PlayView.swift ================================================ import SwiftUI import DeltaCore struct PlayView: View { @EnvironmentObject var appState: StateWrapper @EnvironmentObject var controllerHub: ControllerHub @State var inGameMenuPresented = false @State var readyCount = 0 @State var takenAccounts: [Account] = [] @State var takenInputMethods: [InputMethod] = [] var server: ServerDescriptor var paneCount: Int init(_ server: ServerDescriptor, paneCount: Int = 1) { self.server = server self.paneCount = paneCount } var body: some View { ZStack { if paneCount == 1 { WithSelectedAccount { account in GameView( connectingTo: server, with: account, controller: controllerHub.currentController, controllerOnly: false, inGameMenuPresented: $inGameMenuPresented ) } } else { HStack(spacing: 0) { ForEach(Array(0.. some View { SelectAccountAndThen(excluding: takenAccounts) { account in SelectInputMethodAndThen(excluding: takenInputMethods) { inputMethod in // When all player choose controllers, player one gets keyboard and mouse as well to // be able to do things such as opening the shared in-game menu. let controllerOnly = allPlayersChoseControllers ? playerIndex != 0 : inputMethod.isController VStack { if readyCount == paneCount { GameView( connectingTo: server, with: account, controller: inputMethod.controller, controllerOnly: controllerOnly, inGameMenuPresented: $inGameMenuPresented ) } else { Text("Ready") } } .onAppear { readyCount += 1 takenInputMethods.append(inputMethod) } } cancellationHandler: { appState.update(to: .serverList) } .onAppear { takenAccounts.append(account) } } cancellationHandler: { appState.update(to: .serverList) } .frame(maxWidth: .infinity) } } ================================================ FILE: Sources/Client/Views/Play/SelectAccountAndThen.swift ================================================ import SwiftUI import DeltaCore struct SelectAccountAndThen: View { @EnvironmentObject var managedConfig: ManagedConfig var excludedAccounts: [Account] var content: (Account) -> Content var cancellationHandler: () -> Void init( excluding excludedAccounts: [Account] = [], @ViewBuilder content: @escaping (Account) -> Content, cancellationHandler: @escaping () -> Void ) { self.excludedAccounts = excludedAccounts self.content = content self.cancellationHandler = cancellationHandler } var body: some View { SelectOption( from: managedConfig.config.orderedAccounts, excluding: excludedAccounts, title: "Select an account" ) { account in HStack { Text(account.username) Text(account.type) .foregroundColor(.gray) } } andThen: { account in content(account) } cancellationHandler: { cancellationHandler() } } } ================================================ FILE: Sources/Client/Views/Play/SelectInputMethodAndThen.swift ================================================ import SwiftUI struct SelectInputMethodAndThen: View { @EnvironmentObject var controllerHub: ControllerHub var excludedMethods: [InputMethod] var content: (InputMethod) -> Content var cancellationHandler: () -> Void var inputMethods: [InputMethod] { [.keyboardAndMouse] + controllerHub.controllers.map(InputMethod.controller) } init( excluding excludedMethods: [InputMethod] = [], @ViewBuilder content: @escaping (InputMethod) -> Content, cancellationHandler: @escaping () -> Void ) { self.excludedMethods = excludedMethods self.content = content self.cancellationHandler = cancellationHandler } var body: some View { SelectOption( from: inputMethods, excluding: excludedMethods, title: "Select an input method" ) { method in HStack { Text(method.name) if let detail = method.detail { Text(detail) .foregroundColor(.gray) } } } andThen: { method in content(method) } cancellationHandler: { cancellationHandler() } } } ================================================ FILE: Sources/Client/Views/Play/SelectOption.swift ================================================ import SwiftUI // TODO: The init is starting to get a bit bloated, perhaps a sign that this // view is doing too much, or maybe that some things could be moved to // view modifiers? (e.g. the title) struct SelectOption: View { @State var selectedOption: Option? var options: [Option] var excludedOptions: [Option] var title: String var row: (Option) -> Row var content: (Option) -> Content var cancellationHandler: () -> Void init( from options: [Option], excluding excludedOptions: [Option] = [], title: String, @ViewBuilder row: @escaping (Option) -> Row, andThen content: @escaping (Option) -> Content, cancellationHandler: @escaping () -> Void ) { self.options = options self.excludedOptions = excludedOptions self.title = title self.row = row self.content = content self.cancellationHandler = cancellationHandler } var body: some View { if let selectedOption = selectedOption { content(selectedOption) } else { VStack { Text(title) .font(.title) VStack { Divider() ForEach(options, id: \.self) { option in #if !os(tvOS) HStack { row(option) Spacer() Image(systemName: "chevron.right") } .contentShape(Rectangle()) #if !os(tvOS) .onTapGesture { guard !excludedOptions.contains(option) else { return } selectedOption = option } #endif .padding(.top, 0.3) .foregroundColor(excludedOptions.contains(option) ? .gray : .primary) Divider() #else Button { selectedOption = option } label: { row(option) } .disabled(excludedOptions.contains(option)) #endif } Button("Cancel", action: cancellationHandler) .buttonStyle(SecondaryButtonStyle()) .frame(width: 150) } .padding(.bottom, 10) } #if !os(tvOS) .frame(width: 300) #endif } } } ================================================ FILE: Sources/Client/Views/Play/WithController.swift ================================================ import SwiftUI import Combine struct WithController: View { @State var cancellable: AnyCancellable? /// If `false`, events aren't passed on to registered listeners. @Binding var listening: Bool var controller: Controller? var content: () -> Content private var onButtonPress: ((Controller.Button) -> Void)? private var onButtonRelease: ((Controller.Button) -> Void)? private var onThumbstickMove: ((Controller.Thumbstick, _ x: Float, _ y: Float) -> Void)? init( _ controller: Controller?, listening: Binding, @ViewBuilder content: @escaping () -> Content ) { self.controller = controller _listening = listening self.content = content } func onButtonPress(_ action: @escaping (Controller.Button) -> Void) -> Self { appendingAction(to: \.onButtonPress, action) } func onButtonRelease(_ action: @escaping (Controller.Button) -> Void) -> Self { appendingAction(to: \.onButtonRelease, action) } func onThumbstickMove( _ action: @escaping (Controller.Thumbstick, _ x: Float, _ y: Float) -> Void ) -> Self { appendingAction(to: \.onThumbstickMove, action) } var body: some View { content() .onAppear { observe(controller) } .onChange(of: controller) { controller in observe(controller) } } func observe(_ controller: Controller?) { guard let controller = controller else { cancellable = nil return } cancellable = controller.eventPublisher.sink { event in guard listening else { return } switch event { case let .buttonPressed(button): onButtonPress?(button) case let .buttonReleased(button): onButtonRelease?(button) case let .thumbstickMoved(thumbstick, x, y): onThumbstickMove?(thumbstick, x, y) } } } } ================================================ FILE: Sources/Client/Views/Play/WithRenderCoordinator.swift ================================================ import SwiftUI import DeltaCore import DeltaRenderer /// A helper view which can be used to create a render coordinator for a client /// without having to introduce additional loading states into views. struct WithRenderCoordinator: View { var client: Client var content: (RenderCoordinator) -> Content var cancel: () -> Void init(for client: Client, @ViewBuilder content: @escaping (RenderCoordinator) -> Content, cancellationHandler cancel: @escaping () -> Void) { self.client = client self.content = content self.cancel = cancel } @State var renderCoordinator: RenderCoordinator? @State var renderCoordinatorError: RendererError? var body: some View { VStack { if let renderCoordinator = renderCoordinator { content(renderCoordinator) } else { if let error = renderCoordinatorError { Text(error.localizedDescription) Button("Done", action: cancel) .buttonStyle(SecondaryButtonStyle()) .frame(width: 150) } else { Text("Creating render coordinator") } } } .onAppear { do { renderCoordinator = try RenderCoordinator(client) } catch let error as RendererError { renderCoordinatorError = error } catch { renderCoordinatorError = RendererError.unknown(error) } } } } ================================================ FILE: Sources/Client/Views/Play/WithSelectedAccount.swift ================================================ import SwiftUI import DeltaCore /// Gets the currently selected account, or redirects the user to settings to select an /// account. struct WithSelectedAccount: View { @EnvironmentObject var appState: StateWrapper @EnvironmentObject var modal: Modal @EnvironmentObject var managedConfig: ManagedConfig var content: (Account) -> Content init(@ViewBuilder content: @escaping (Account) -> Content) { self.content = content } var body: some View { if let account = managedConfig.config.selectedAccount { content(account) } else { Text("Loading account...") .onAppear { modal.error("You must select an account.") { // TODO: Have an inline account selector instead of redirecting to settings. appState.update(to: .settings(.accounts)) } } } } } ================================================ FILE: Sources/Client/Views/RouterView.swift ================================================ import SwiftUI import DeltaCore struct RouterView: View { @EnvironmentObject var appState: StateWrapper @EnvironmentObject var managedConfig: ManagedConfig @EnvironmentObject var controllerHub: ControllerHub var body: some View { VStack { switch appState.current { case .serverList: ServerListView() case .editServerList: EditServerListView() case .login: AccountLoginView(completion: { account in managedConfig.config.addAccount(account) if managedConfig.config.accounts.count == 1 { managedConfig.config.selectAccount(withId: account.id) } appState.update(to: .serverList) }, cancelation: nil) case .accounts: AccountSettingsView(saveAction: { appState.update(to: .serverList) }).padding() case .directConnect: DirectConnectView() case let .playServer(server, paneCount): PlayView(server, paneCount: paneCount) case let .settings(landingPage): SettingsView(isInGame: false, landingPage: landingPage, onDone: { appState.pop() }) } } .onChange(of: appState.current) { newValue in // Update Discord rich presence based on the current app state switch newValue { case .serverList: DiscordManager.shared.updateRichPresence(to: .menu) case .playServer(let descriptor, _): DiscordManager.shared.updateRichPresence(to: .game(server: descriptor.name)) default: break } } } } ================================================ FILE: Sources/Client/Views/ServerList/LANServerList.swift ================================================ import SwiftUI import DeltaCore struct LANServerList: View { @ObservedObject var lanServerEnumerator: LANServerEnumerator var body: some View { if !lanServerEnumerator.pingers.isEmpty { ForEach(lanServerEnumerator.pingers, id: \.self) { pinger in NavigationLink(destination: ServerDetail(pinger: pinger)) { ServerListItem(pinger: pinger) } } } else { Text(lanServerEnumerator.hasErrored ? "LAN scan failed" : "scanning LAN...").italic() } } } ================================================ FILE: Sources/Client/Views/ServerList/ServerDetail.swift ================================================ import SwiftUI import DeltaCore struct ServerDetail: View { @EnvironmentObject var appState: StateWrapper @ObservedObject var pinger: Pinger var body: some View { let descriptor = pinger.descriptor VStack(alignment: .leading) { Text(descriptor.name) .font(.title) Text(descriptor.description) .padding(.bottom, 8) if let result = pinger.response { switch result { case let .success(response): LegacyFormattedTextView( legacyString: "\(response.description.text)", fontSize: FontUtil.systemFontSize(for: .regular), alignment: .right ).padding(.bottom, 8) Text(verbatim: "\(response.players.online)/\(response.players.max) online") LegacyFormattedTextView( legacyString: "Version: \(response.version.name) \(response.version.protocolVersion == Constants.protocolVersion ? "" : "(incompatible)")", fontSize: FontUtil.systemFontSize(for: .regular), alignment: .center ).padding(.bottom, 8) Button("Play") { appState.update(to: .playServer(descriptor, paneCount: 1)) } .buttonStyle(PrimaryButtonStyle()) #if !os(tvOS) .frame(width: 150) #endif Button("Play splitscreen") { appState.update(to: .playServer(descriptor, paneCount: 2)) } .buttonStyle(SecondaryButtonStyle()) #if !os(tvOS) .frame(width: 150) #endif case let .failure(error): Text(error.localizedDescription) .padding(.bottom, 8) Button("Play") {} .buttonStyle(DisabledButtonStyle()) .frame(width: 150) .disabled(true) Button("Play splitscreen") {} .buttonStyle(SecondaryButtonStyle()) .frame(width: 150) .disabled(true) } } else { Text("Pinging..") .padding(.bottom, 8) Button("Play") { } .buttonStyle(DisabledButtonStyle()) .frame(width: 150) .disabled(true) } } } } ================================================ FILE: Sources/Client/Views/ServerList/ServerListItem.swift ================================================ import SwiftUI import DeltaCore struct ServerListItem: View { @StateObject var pinger: Pinger var indicatorColor: SwiftUI.Color { let color: SwiftUI.Color if let result = pinger.response { switch result { case let .success(response): // Ping succeeded let isCompatible = response.version.protocolVersion == Constants.protocolVersion color = isCompatible ? .green : .yellow case .failure: // Connection failed color = .red } } else { // In the process of pinging color = .red } return color } var body: some View { HStack { Text(pinger.descriptor.name) Spacer() PingIndicator(color: indicatorColor) } } } ================================================ FILE: Sources/Client/Views/ServerList/ServerListView.swift ================================================ import SwiftUI import DeltaCore struct ServerListView: View { @EnvironmentObject var appState: StateWrapper @EnvironmentObject var managedConfig: ManagedConfig @EnvironmentObject var modal: Modal @State var pingers: [Pinger] = [] @State var lanServerEnumerator: LANServerEnumerator? @State var updateAvailable = false var body: some View { NavigationView { List { // Server list if !pingers.isEmpty { ForEach(pingers, id: \.self) { pinger in NavigationLink(destination: ServerDetail(pinger: pinger)) { ServerListItem(pinger: pinger) } } } else { Text("no servers").italic() } #if !os(tvOS) Divider() #endif if let lanServerEnumerator = lanServerEnumerator { LANServerList(lanServerEnumerator: lanServerEnumerator) } else { Text("LAN scan failed").italic() } #if os(tvOS) Divider() Button("Edit servers") { appState.update(to: .editServerList) } Button("Refresh servers") { refresh() } Button("Direct connect") { appState.update(to: .directConnect) } Button("Settings") { appState.update(to: .settings(nil)) } #else HStack { // Edit server list IconButton("square.and.pencil") { appState.update(to: .editServerList) } // Refresh server list (ping all servers) and discovered LAN servers IconButton("arrow.clockwise") { refresh() } // Direct connect IconButton("personalhotspot") { appState.update(to: .directConnect) } #if os(iOS) || os(tvOS) // Settings IconButton("gear") { appState.update(to: .settings(nil)) } #endif } #endif if (updateAvailable) { Button("Update") { appState.update(to: .settings(.update)) }.padding(.top, 5) } } #if !os(tvOS) // TODO: Does this even do anything? .listStyle(SidebarListStyle()) #endif } .onAppear { // Check for updates Task { await checkForUpdates() } // Create server pingers let servers = managedConfig.config.servers pingers = servers.map { server in Pinger(server) } refresh() // TODO: The whole EventBus architecture is pretty unwieldy at the moment, // all this code just to create and start a lan server enumerator? // Create LAN server enumerator let eventBus = EventBus() lanServerEnumerator = LANServerEnumerator(eventBus: eventBus) eventBus.registerHandler { event in switch event { case let event as ErrorEvent: log.warning("\(event.message ?? "Error"): \(event.error)") default: break } } do { try lanServerEnumerator?.start() } catch { modal.error(RichError("Failed to start LAN server enumerator.").becauseOf(error)) } } .onDisappear { lanServerEnumerator?.stop() } } // Check if any Delta Client updates are available. Does nothing if not on macOS. func checkForUpdates() async { #if os(macOS) do { let result = try Updater.isUpdateAvailable() await MainActor.run { updateAvailable = result } } catch { modal.error(RichError("Failed to check for updates").becauseOf(error)) } #endif } /// Ping all servers and clear discovered LAN servers. func refresh() { for pinger in pingers { Task { try? await pinger.ping() } } lanServerEnumerator?.clear() } } ================================================ FILE: Sources/Client/Views/Settings/Account/AccountLoginView.swift ================================================ import SwiftUI import DeltaCore enum LoginViewState { case chooseAccountType case loginMicrosoft case loginMojang case loginOffline } struct AccountLoginView: EditorView { typealias Item = Account @State var state: LoginViewState = .chooseAccountType let completionHandler: (Item) -> Void let cancelationHandler: (() -> Void)? /// Ignores `item` because this view is only ever used for logging into account not editing them. init(_ item: Item? = nil, completion: @escaping (Item) -> Void, cancelation: (() -> Void)?) { completionHandler = completion cancelationHandler = cancelation } var body: some View { switch state { case .chooseAccountType: VStack { Text("Choose account type") Button("Microsoft") { state = .loginMicrosoft }.buttonStyle(PrimaryButtonStyle()) Button("Mojang") { state = .loginMojang }.buttonStyle(PrimaryButtonStyle()) Button("Offline") { state = .loginOffline }.buttonStyle(PrimaryButtonStyle()) Spacer().frame(height: 32) Button("Cancel") { cancelationHandler?() }.buttonStyle(SecondaryButtonStyle()) } .navigationTitle("Account Login") #if !os(iOS) .onExitCommand { cancelationHandler?() } #endif #if !os(tvOS) .frame(width: 200) #endif case .loginMicrosoft: MicrosoftLoginView(loginViewState: $state, completionHandler: completionHandler) case .loginMojang: MojangLoginView(loginViewState: $state, completionHandler: completionHandler) case .loginOffline: OfflineLoginView(loginViewState: $state, completionHandler: completionHandler) } } } ================================================ FILE: Sources/Client/Views/Settings/Account/AccountSettingsView.swift ================================================ import SwiftUI import DeltaCore // TODO: Use Config.orderedAccounts to ensure that account ordering is at least consistent struct AccountSettingsView: View { @EnvironmentObject var managedConfig: ManagedConfig @State var accounts: [Account] = [] @State var selectedIndex: Int? = nil let saveAction: (() -> Void)? init(saveAction: (() -> Void)? = nil) { self.saveAction = saveAction } var body: some View { VStack { EditableList( $accounts.onChange(save), selected: $selectedIndex.onChange(saveSelected), itemEditor: AccountLoginView.self, row: row, saveAction: saveAction, cancelAction: nil, emptyMessage: "No accounts", forceShowCreation: managedConfig.accounts.isEmpty ) } .navigationTitle("Accounts") .onAppear { accounts = Array(managedConfig.accounts.values) selectedIndex = getSelectedIndex() } } func row( item: Account, selected: Bool, isFirst: Bool, isLast: Bool, handler: @escaping (EditableListAction) -> Void ) -> some View { HStack { Image(systemName: "chevron.right") .opacity(selected ? 1 : 0) VStack(alignment: .leading) { Text(item.username) .font(.headline) Text(item.type) .font(.subheadline) } Spacer() Button("Select") { handler(.select) } .disabled(selected) #if !os(tvOS) .buttonStyle(BorderlessButtonStyle()) #endif IconButton("xmark") { handler(.delete) } #if os(tvOS) .padding(.trailing, 20) #endif } } /// Saves the given accounts to the config file. func save(_ accounts: [Account]) { let accountId = getSelectedAccount()?.id // Filter out duplicate accounts var uniqueAccounts: [Account] = [] for account in accounts { if !uniqueAccounts.contains(where: { $0.id == account.id }) { uniqueAccounts.append(account) } } selectedIndex = uniqueAccounts.firstIndex { $0.id == accountId } if accounts.count != uniqueAccounts.count { self.accounts = uniqueAccounts return // Updating accounts will run this function again so we just stop here } managedConfig.accounts = [:] managedConfig.config.addAccounts(uniqueAccounts) managedConfig.config.selectAccount(withId: accountId) } /// Updates the selected account in the config file. func saveSelected(_ index: Int?) { guard let index = index else { managedConfig.config.selectAccount(withId: nil) return } managedConfig.config.selectAccount(withId: accounts[index].id) } /// Returns the currently selected account if any. func getSelectedAccount() -> Account? { guard let selectedIndex = selectedIndex else { return nil } guard selectedIndex >= 0 && selectedIndex < accounts.count else { self.selectedIndex = nil return nil } return accounts[selectedIndex] } /// Returns the index of the currently selected account according to the current configuration. func getSelectedIndex() -> Int? { guard let selectedAccountId = managedConfig.selectedAccountId else { return nil } return accounts.firstIndex { account in account.id == selectedAccountId } } } ================================================ FILE: Sources/Client/Views/Settings/Account/MicrosoftLoginView.swift ================================================ import SwiftUI import DeltaCore enum MicrosoftLoginViewError: LocalizedError { case failedToAuthorizeDevice case failedToAuthenticate var errorDescription: String? { switch self { case .failedToAuthorizeDevice: return "Failed to authorize device." case .failedToAuthenticate: return "Failed to authenticate Microsoft account." } } } struct MicrosoftLoginView: View { enum MicrosoftState { case authorizingDevice case login(MicrosoftDeviceAuthorizationResponse) case authenticatingUser } #if os(tvOS) @Namespace var focusNamespace #endif @EnvironmentObject var modal: Modal @EnvironmentObject var appState: StateWrapper @State var state: MicrosoftState = .authorizingDevice @Binding var loginViewState: LoginViewState #if os(tvOS) @Environment(\.resetFocus) var resetFocus #endif var completionHandler: (Account) -> Void var body: some View { VStack { switch state { case .authorizingDevice: Text("Fetching device authorization code") case .login(let response): Text(response.message) #if !os(tvOS) Link("Open in browser", destination: response.verificationURI) .padding(10) Button("Copy code") { Clipboard.copy(response.userCode) } .buttonStyle(PrimaryButtonStyle()) .frame(width: 200) .padding(.bottom, 26) #endif Button("Done") { state = .authenticatingUser authenticate(with: response.deviceCode) } .buttonStyle(PrimaryButtonStyle()) #if !os(tvOS) .frame(width: 200) #else .onAppear { resetFocus(in: focusNamespace) } #endif case .authenticatingUser: Text("Authenticating...") } Button("Cancel") { loginViewState = .chooseAccountType } .buttonStyle(SecondaryButtonStyle()) #if !os(tvOS) .frame(width: 200) #endif } .onAppear { authorizeDevice() } #if os(tvOS) .focusScope(focusNamespace) #endif } func authorizeDevice() { Task { do { let response = try await MicrosoftAPI.authorizeDevice() state = .login(response) } catch { modal.error(MicrosoftLoginViewError.failedToAuthorizeDevice.becauseOf(error)) { appState.update(to: .serverList) } } } } func authenticate(with deviceCode: String) { Task { do { let accessToken = try await MicrosoftAPI.getMicrosoftAccessToken(deviceCode) let account = try await MicrosoftAPI.getMinecraftAccount(accessToken) completionHandler(.microsoft(account)) } catch { // We can trust MicrosoftAPIError's messages to be suitably human readable let modalError: Error if let error = error as? MicrosoftAPIError { modalError = error } else { modalError = MicrosoftLoginViewError.failedToAuthenticate.becauseOf(error) } modal.error(modalError) { appState.update(to: .serverList) } } } } } ================================================ FILE: Sources/Client/Views/Settings/Account/MojangLoginView.swift ================================================ import SwiftUI import DeltaCore struct MojangLoginView: View { @EnvironmentObject var managedConfig: ManagedConfig @State var isEmailValid = false @State var email = "" @State var password = "" @State var errorMessage: String? @State var authenticating = false @Binding var loginViewState: LoginViewState var completionHandler: (Account) -> Void var body: some View { VStack { if authenticating { Text("Authenticating...") } else { if let errorMessage = errorMessage { Text(errorMessage) .foregroundColor(.red) } EmailField("Email", email: $email, isValid: $isEmailValid) SecureField("Password", text: $password) HStack { Button("Back") { loginViewState = .chooseAccountType }.buttonStyle(SecondaryButtonStyle()) Button("Login") { login() }.buttonStyle(PrimaryButtonStyle()) } } } #if !os(tvOS) .frame(width: 200) #endif } func login() { guard isEmailValid else { displayError("Please enter a valid email address") return } authenticating = true let email = email let password = password let clientToken = managedConfig.clientToken Task { do { let account = try await MojangAPI.login(email: email, password: password, clientToken: clientToken) completionHandler(account) } catch { displayError("Failed to authenticate: \(error)") } } } func displayError(_ message: String) { ThreadUtil.runInMain { errorMessage = message authenticating = false } } } ================================================ FILE: Sources/Client/Views/Settings/Account/OfflineLoginView.swift ================================================ import SwiftUI import DeltaCore struct OfflineLoginView: View { @State private var username = "" @State private var errorMessage: String? @Binding var loginViewState: LoginViewState var completionHandler: (Account) -> Void var body: some View { VStack { if let errorMessage = errorMessage { Text(errorMessage) .foregroundColor(.red) } TextField("Username", text: $username) HStack { Button("Back") { loginViewState = .chooseAccountType }.buttonStyle(SecondaryButtonStyle()) Button("Login") { login() }.buttonStyle(PrimaryButtonStyle()) } } #if !os(tvOS) .frame(width: 200) #endif } func login() { guard !username.isEmpty else { displayError("Please provide a username") return } let account = Account.offline(OfflineAccount(username: username)) completionHandler(account) } func displayError(_ message: String) { ThreadUtil.runInMain { errorMessage = message } } } ================================================ FILE: Sources/Client/Views/Settings/ControlsSettingsView.swift ================================================ import SwiftUI #if !os(tvOS) struct ControlsSettingsView: View { @EnvironmentObject var managedConfig: ManagedConfig @State var sensitivity: Float = 0 @State var toggleSprint = false @State var toggleSneak = false var body: some View { ScrollView { HStack { Text("Sensitivity: \(Self.formatSensitivity(sensitivity))") .frame(width: 150) Slider(value: $sensitivity, in: 0...10, onEditingChanged: { isEditing in if !isEditing { sensitivity = Self.roundSensitivity(sensitivity) managedConfig.mouseSensitivity = sensitivity } }) } .frame(width: 450) HStack { Text("Toggle sprint").frame(width: 150) Spacer() Toggle( "Toggle sprint", isOn: $toggleSprint.onChange { newValue in managedConfig.toggleSprint = newValue } ) .labelsHidden() .toggleStyle(.switch) Spacer() } .frame(width: 400) HStack { Text("Toggle sneak").frame(width: 150) Spacer() Toggle( "Toggle sneak", isOn: $toggleSneak.onChange { newValue in managedConfig.toggleSneak = newValue } ) .labelsHidden() .toggleStyle(.switch) Spacer() } .frame(width: 400) Text("Bindings") .font(.title) .padding(.top, 16) KeymapEditorView() } .onAppear { sensitivity = managedConfig.mouseSensitivity toggleSprint = managedConfig.toggleSprint toggleSneak = managedConfig.toggleSneak } } /// Rounds mouse sensitivity to the nearest even number percentage. private static func roundSensitivity(_ sensitivity: Float) -> Float { if abs(100 - sensitivity * 100) <= 3 { return 1 } return Float(Int(round(sensitivity * 100 / 2)) * 2) / 100 } /// Formats mouse sensitivity as a rounded percentage. private static func formatSensitivity(_ sensitivity: Float) -> String { return "\(Int(roundSensitivity(sensitivity) * 100))%" } } #endif ================================================ FILE: Sources/Client/Views/Settings/KeymapEditorView.swift ================================================ import SwiftUI import DeltaCore struct KeymapEditorView: View { @EnvironmentObject var managedConfig: ManagedConfig /// Whether key inputs are being captured by the view. @State var inputCaptured = false /// The input currently selected for rebinding. @State var selectedInput: Input? var body: some View { InputView(listening: $inputCaptured, cursorCaptured: false) { ForEach(Input.allCases.filter(\.isBindable), id: \.self) { (input: Input) in let bindings = managedConfig.keymap.bindings let key = bindings[input] let isUnique = key == nil ? true : bindings.values.filter({ $0 == key }).count == 1 let isBound = bindings[input] != nil let isSelected = selectedInput == input let labelColor = Self.labelColor(isUnique: isUnique, isBound: isBound, isSelected: isSelected) HStack { // Input name (e.g. 'Sneak') Text(input.humanReadableLabel) .frame(width: 150) // Button to set a new binding let keyName = bindings[input]?.description ?? "Unbound" Button(action: { if isSelected { managedConfig.keymap.bindings[input] = .leftMouseButton selectedInput = nil inputCaptured = false } else { selectedInput = input inputCaptured = true } }, label: { Text(isSelected ? "> Press key <" : keyName) .foregroundColor(labelColor) }) .buttonStyle(SecondaryButtonStyle()) .disabled(isSelected) // Button to unbind an input IconButton("xmark", isDisabled: !isBound || isSelected) { managedConfig.keymap.bindings.removeValue(forKey: input) } } .frame(width: 400) } } .passthroughClicks() .avoidGeometryReader() .onKeyPress { key, _ in guard let selectedInput = selectedInput else { return } if key == .escape { managedConfig.keymap.bindings.removeValue(forKey: selectedInput) } else { managedConfig.keymap.bindings[selectedInput] = key } self.selectedInput = nil } .onKeyRelease { key in inputCaptured = false } Button("Reset bindings to defaults") { managedConfig.keymap.bindings = Keymap.default.bindings } .buttonStyle(SecondaryButtonStyle()) .frame(width: 250) .padding(.top, 10) } static func labelColor(isUnique: Bool, isBound: Bool, isSelected: Bool) -> Color { if isSelected { return .white } else if !isBound { return .yellow } else if !isUnique { return .red } else { return .white } } } ================================================ FILE: Sources/Client/Views/Settings/PluginSettingsView.swift ================================================ import SwiftUI import DeltaCore #if os(macOS) enum PluginSettingsViewError: LocalizedError { case failedToLoadPlugin(identifier: String) var errorDescription: String? { switch self { case let .failedToLoadPlugin(identifier): return "Failed to load plugin '\(identifier)'" } } } struct PluginSettingsView: View { @EnvironmentObject var pluginEnvironment: PluginEnvironment @EnvironmentObject var modal: Modal @EnvironmentObject var managedConfig: ManagedConfig @Environment(\.storage) var storage: StorageDirectory func updateConfig() { managedConfig.unloadedPlugins = Array(pluginEnvironment.unloadedPlugins.keys) } var body: some View { VStack { HStack { // Loaded plugins VStack { Text("Loaded").font(.title2) ScrollView { ForEach(Array(pluginEnvironment.plugins), id: \.key) { (identifier, plugin) in HStack { Text(plugin.manifest.name) Button("Unload") { pluginEnvironment.unloadPlugin(identifier) updateConfig() } } } if pluginEnvironment.plugins.isEmpty { Text("no loaded plugins").italic() } } }.frame(maxWidth: .infinity) // Unloaded plugins VStack { Text("Unloaded").font(.title2) ScrollView { ForEach(Array(pluginEnvironment.unloadedPlugins), id: \.key) { (identifier, plugin) in HStack { Text(plugin.manifest.name) Button("Load") { do { try pluginEnvironment.loadPlugin(from: plugin.bundle) updateConfig() } catch { modal.error(PluginSettingsViewError.failedToLoadPlugin(identifier: identifier).becauseOf(error)) } } } } if pluginEnvironment.unloadedPlugins.isEmpty { Text("no unloaded plugins").italic() } } }.frame(maxWidth: .infinity) // Errors if !pluginEnvironment.errors.isEmpty { VStack { HStack { Text("Errors").font(.title2) Button("Clear") { pluginEnvironment.errors = [] } } ScrollView { VStack(alignment: .leading) { ForEach(Array(pluginEnvironment.errors.enumerated()), id: \.0) { (_, error) in Text("\(error.bundle):").font(.title) Text(String("\(error.underlyingError)")) } } } }.frame(maxWidth: .infinity) } } // Global actions HStack { Button("Unload all") { pluginEnvironment.unloadAll() updateConfig() } Button("Reload all") { pluginEnvironment.reloadAll(storage.pluginDirectory) updateConfig() } Button("Open plugins directory") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: storage.pluginDirectory.path) } } } } } #endif ================================================ FILE: Sources/Client/Views/Settings/Server/EditServerListView.swift ================================================ import SwiftUI import DeltaCore import Combine struct EditServerListView: View { @EnvironmentObject var appState: StateWrapper @EnvironmentObject var managedConfig: ManagedConfig @State var servers: [ServerDescriptor] = [] var body: some View { VStack { EditableList( $managedConfig.servers, itemEditor: ServerEditorView.self, row: { item, selected, isFirst, isLast, handler in HStack { #if !os(tvOS) VStack { IconButton("chevron.up", isDisabled: isFirst) { handler(.moveUp) } IconButton("chevron.down", isDisabled: isLast) { handler(.moveDown) } } #endif VStack(alignment: .leading) { Text(item.name) .font(.headline) Text(item.description) .font(.subheadline) } Spacer() HStack { IconButton("square.and.pencil") { handler(.edit) } IconButton("xmark") { handler(.delete) } #if os(tvOS) .padding(.trailing, 20) #endif } } }, saveAction: appState.pop, cancelAction: appState.pop, // TODO: There is no cancel anymore emptyMessage: "No servers") } .padding() .navigationTitle("Edit Servers") } } ================================================ FILE: Sources/Client/Views/Settings/Server/ServerEditorView.swift ================================================ import SwiftUI import DeltaCore struct ServerEditorView: EditorView { @State var descriptor: ServerDescriptor @State var errorMessage: String? var completionHandler: (ServerDescriptor) -> Void var cancelationHandler: (() -> Void)? @State var isAddressValid = false /// True if this is editing an existing server. let isEditor: Bool init(_ item: ServerDescriptor?, completion: @escaping (ServerDescriptor) -> Void, cancelation: (() -> Void)?) { completionHandler = completion cancelationHandler = cancelation isEditor = item != nil _descriptor = State(initialValue: item ?? ServerDescriptor(name: "", host: "", port: nil)) } private func verify() -> Bool { if !isAddressValid { errorMessage = "Invalid IP" } else { return true } return false } var body: some View { VStack { TextField("Server name", text: $descriptor.name) AddressField("Server address", host: $descriptor.host, port: $descriptor.port, isValid: $isAddressValid) if let message = errorMessage { Text(message) .bold() } HStack { if let cancel = cancelationHandler { Button("Cancel", action: cancel) .buttonStyle(SecondaryButtonStyle()) } Button(isEditor ? "Save" : "Add") { if verify() { completionHandler(descriptor) } } .buttonStyle(PrimaryButtonStyle()) } .padding(.top, 8) } #if !os(tvOS) .frame(width: 200) #endif } } ================================================ FILE: Sources/Client/Views/Settings/SettingsView.swift ================================================ import SwiftUI import DeltaCore enum SettingsState: CaseIterable { case video case controls case accounts case update case plugins case troubleshooting } struct SettingsView: View { var isInGame: Bool var done: () -> Void @State private var currentPage: SettingsState? init( isInGame: Bool, landingPage: SettingsState? = nil, onDone done: @escaping () -> Void ) { self.isInGame = isInGame self.done = done #if os(iOS) || os(tvOS) // On iOS, the navigation isn't a split view, so we should show the settings page selection // view first instead of auto-selecting the first page. self._currentPage = State(initialValue: landingPage) #else self._currentPage = State(initialValue: landingPage ?? SettingsState.allCases[0]) #endif } var body: some View { NavigationView { List { NavigationLink( "Video", destination: VideoSettingsView().padding(), tag: SettingsState.video, selection: $currentPage ) #if !os(tvOS) NavigationLink( "Controls", destination: ControlsSettingsView().padding(), tag: SettingsState.controls, selection: $currentPage ) #endif if !isInGame { NavigationLink( "Accounts", destination: AccountSettingsView().padding(), tag: SettingsState.accounts, selection: $currentPage ) #if os(macOS) NavigationLink( "Update", destination: UpdateView().padding(), tag: SettingsState.update, selection: $currentPage ) NavigationLink( "Plugins", destination: PluginSettingsView().padding(), tag: SettingsState.plugins, selection: $currentPage ) #endif NavigationLink( "Troubleshooting", destination: TroubleshootingView().padding(), tag: SettingsState.troubleshooting, selection: $currentPage ) } Button("Done", action: { withAnimation(nil) { done() } }) #if !os(tvOS) .buttonStyle(BorderlessButtonStyle()) .keyboardShortcut(.escape, modifiers: []) #endif } #if !os(tvOS) .listStyle(SidebarListStyle()) #endif } .navigationTitle("Settings") } } ================================================ FILE: Sources/Client/Views/Settings/TroubleShootingView.swift ================================================ import SwiftUI import DeltaCore /// An error which can occur during troubleshooting; how ironic. enum TroubleshootingError: LocalizedError { case failedToDeleteCache case failedToResetConfig case failedToPerformFreshInstall var errorDescription: String? { switch self { case .failedToDeleteCache: return "Failed to delete cache directory." case .failedToResetConfig: return "Failed to reset configuration to defaults." case .failedToPerformFreshInstall: return "Failed to perform fresh install." } } } /// A collection of useful troubleshooting actions. Optionally displays a cause for /// troubleshooting (in case the user was forcefully sent here). struct TroubleshootingView: View { @EnvironmentObject var appState: StateWrapper @EnvironmentObject var modal: Modal @EnvironmentObject var managedConfig: ManagedConfig @Environment(\.storage) var storage: StorageDirectory @State private var message: String? = nil /// Content for a never-disappearing error message displayed above the option buttons. private let error: (any Error)? /// The error message to show if any. var errorMessage: String? { guard let error = error else { return nil } if let error = error as? RichError { return error.richDescription } else { return "\(error)" } } /// Creates a troubleshooting view with an optional cause for troubleshooting. init(error: (any Error)? = nil) { self.error = error } var body: some View { VStack { if let errorMessage = errorMessage { Text(errorMessage) .padding(.bottom, 10) } Button("Clear cache") { // Clear cache perform( "Clearing cache", "Cleared cache successfully", action: storage.removeCache, error: TroubleshootingError.failedToDeleteCache ) { message = nil } }.buttonStyle(SecondaryButtonStyle()) Button("Reset config") { // Reset config perform( "Resetting config", "Reset config successfully", action: managedConfig.reset, error: TroubleshootingError.failedToResetConfig ) { message = nil } }.buttonStyle(SecondaryButtonStyle()) Button("Perform fresh install") { perform( "Performing fresh install", action: { try storage.backup() try storage.reset() #if os(macOS) message = "Relaunching..." try await delay(seconds: 1) Utils.relaunch() #else message = "Please relaunch app to complete fresh install." #endif }, error: TroubleshootingError.failedToPerformFreshInstall ) { message = nil } }.buttonStyle(SecondaryButtonStyle()) #if os(macOS) Button("View logs") { NSWorkspace.shared.open(storage.currentLogFile) }.buttonStyle(SecondaryButtonStyle()) #endif if let message = message { Text(message) .padding(.top, 10) } } #if !os(tvOS) .frame(width: 200) #endif } private func perform( _ taskName: String, _ successMessage: String? = nil, action: @escaping () async throws -> Void, error baseError: TroubleshootingError, onErrorDismissed errorDismissedHandler: (() -> Void)? = nil ) { Task { let initialMessage = "\(taskName)..." message = initialMessage do { try await delay(seconds: 0.5) try await action() if let successMessage = successMessage, message == initialMessage { message = successMessage } } catch { modal.error(baseError.becauseOf(error)) { errorDismissedHandler?() } } } } private func delay(seconds: Double) async throws { try await Task.sleep(nanoseconds: UInt64(Duration.seconds(seconds).nanoseconds)) } } ================================================ FILE: Sources/Client/Views/Settings/UpdateView.swift ================================================ import SwiftUI import ZIPFoundation import DeltaCore #if os(macOS) struct UpdateView: View { enum UpdateViewState { case loadingBranches case selectBranch(branches: [String]) case updating } @EnvironmentObject var appState: StateWrapper @EnvironmentObject var modal: Modal @Environment(\.storage) var storage: StorageDirectory @StateObject var progress = TaskProgress() @State var state: UpdateViewState = .loadingBranches @State var branch: String? @State var updateVersion: String? init() {} var body: some View { switch state { case .loadingBranches: Text("Loading branches...") .onAppear { Task { do { let branches = try Updater.getBranches().map(\.name) ThreadUtil.runInMain { state = .selectBranch(branches: branches) } } catch { modal.error(error) { appState.update(to: .serverList) } } } } case let .selectBranch(branches): VStack { Menu { ForEach(branches, id: \.self) { branch in Button(branch) { self.branch = branch } } } label: { if let branch = branch { Text("Branch: \(branch)") } else { Text("Select a branch") } } if let branch = branch { Button("Update to latest commit") { state = .updating Task { do { let download = try Updater.getDownload(for: .nightly(branch: branch)) updateVersion = download.version try await Updater.performUpdate( download: download, isNightly: true, storage: storage, progress: progress ) } catch { modal.error(error) { appState.update(to: .serverList) } } } } .buttonStyle(SecondaryButtonStyle()) } else { Button("Update to latest commit") {} .disabled(true) .buttonStyle(SecondaryButtonStyle()) } } .frame(width: 200) .padding(.vertical) case .updating: // Shows the progress of an update VStack(alignment: .leading, spacing: 16) { Group { if let version = updateVersion { Text("Updating to \(version)") } else { Text("Fetching update information") } } .font(.title) ProgressView(value: progress.progress) { Text(progress.message) } Button("Cancel") { state = .loadingBranches } .buttonStyle(SecondaryButtonStyle()) .frame(width: 200) } .frame(maxWidth: 500) } } } #endif ================================================ FILE: Sources/Client/Views/Settings/VideoSettingsView.swift ================================================ import SwiftUI import DeltaCore struct VideoSettingsView: View { @EnvironmentObject var managedConfig: ManagedConfig var body: some View { ScrollView { HStack { Text("Render distance: \(managedConfig.render.renderDistance)") #if os(tvOS) ProgressView(value: Double(managedConfig.render.renderDistance) / 32) #else Slider( value: Binding { Float(managedConfig.render.renderDistance) } set: { newValue in managedConfig.render.renderDistance = Int(newValue.rounded()) }, in: 0...32, step: 1 ) .frame(width: 220) #endif } #if os(tvOS) .focusable() .onMoveCommand { direction in switch direction { case .left: managedConfig.render.renderDistance -= 1 case .right: managedConfig.render.renderDistance += 1 default: break } } #endif #if !os(tvOS) HStack { Text("FOV: \(Int(managedConfig.render.fovY.rounded()))") Spacer() Slider( value: Binding { managedConfig.render.fovY } set: { newValue in managedConfig.render.fovY = newValue.rounded() }, in: 30...110 ) .frame(width: 220) } #endif HStack { Text("Render mode") Spacer() Picker("Render mode", selection: $managedConfig.render.mode) { ForEach(RenderMode.allCases) { mode in Text(mode.rawValue.capitalized) } } #if os(macOS) .pickerStyle(RadioGroupPickerStyle()) #elseif os(iOS) || os(tvOS) .pickerStyle(DefaultPickerStyle()) #endif #if !os(tvOS) .frame(width: 220) #endif } // Order independent transparency doesn't work on tvOS yet (our implementation uses a Metal // feature which isn't supported on tvOS). #if !os(tvOS) HStack { Text("Order independent transparency") Spacer() Toggle( "Order independent transparency", isOn: $managedConfig.render.enableOrderIndependentTransparency ) .labelsHidden() .toggleStyle(.switch) .frame(width: 220) } #endif } #if !os(tvOS) .frame(width: 450) #endif .navigationTitle("Video") } } ================================================ FILE: Sources/Client/Views/Startup/LoadAndThen.swift ================================================ import Combine import DeltaCore import SwiftUI struct LoadResult { var managedConfig: ManagedConfig var resourcePack: Box var pluginEnvironment: PluginEnvironment } struct LoadAndThen: View { @EnvironmentObject var modal: Modal @StateObject var startup = TaskProgress() @State var loadResult: LoadResult? @Binding var hasLoaded: Bool @Binding var storage: StorageDirectory? let arguments: CommandLineArguments var content: (ManagedConfig, Box, PluginEnvironment) -> Content init( _ arguments: CommandLineArguments, _ hasLoaded: Binding, _ storage: Binding, content: @escaping (ManagedConfig, Box, PluginEnvironment) -> Content ) { self.arguments = arguments _hasLoaded = hasLoaded _storage = storage self.content = content } func load() throws { var previousStep: StartupStep? startup.onChange { progress in if progress.currentStep != previousStep { let percentage = String(format: "%.01f", progress.progress * 100) log.info("\(progress.message) (\(percentage)%)") } previousStep = progress.currentStep } let stopwatch = Stopwatch() guard var storage = StorageDirectory.platformDefault else { throw RichError("Failed to get storage directory") } try storage.ensureCreated() storage.pluginDirectoryOverride = arguments.pluginsDirectory self.storage = storage // Load configuration, replacing it with defaults if it can't be read let config: Config do { config = try Config.load(from: storage.configFile) } catch { modal.error(RichError("Failed to load config, using defaults").becauseOf(error)) config = Config() // Don't save the new config (wait until the user makes changes). This means that // the user can quit the client and attempt to fix their config without having to // start their config all over again. } let managedConfig = ManagedConfig(config, backedBy: storage.configFile) { error in modal.error(RichError("Failed to save config").becauseOf(error)) } // Enable file logging as there isn't really a better place to put this. Despite // not being part of loading per-say, it needs to be enabled as early as possible // to be maximally useful, so we can't exactly wait till a better time. do { try enableFileLogger(loggingTo: storage.currentLogFile) } catch { modal.warning("Failed to enable file logger") } Task { let errors = await managedConfig.refreshAccounts() if errors.isEmpty { return } var richError = RichError("Failed to refresh accounts.") if errors.count > 1 { for (i, error) in errors.enumerated() { richError = richError.with("Reason \(i + 1)", error) } } else if let reason = errors.first { if let reason = reason as? RichError { richError = reason } else { richError = richError.becauseOf(reason) } } modal.error(richError) } let pluginEnvironment = PluginEnvironment() startup.perform(.loadPlugins) { try pluginEnvironment.loadPlugins( from: storage.pluginDirectory, excluding: config.unloadedPlugins ) } handleError: { error in modal.error("Error occurred during plugin loading, no plugins will be available: \(error)") } // This check encompasses both missing entity models and missing assets. let invalidateAssets = !FileSystem.directoryExists( storage.assetDirectory.appendingPathComponent("minecraft/models/entity") ) try startup.perform(.downloadAssets, if: invalidateAssets) { progress in try? FileManager.default.removeItem(at: storage.assetDirectory) try ResourcePack.downloadVanillaAssets( forVersion: Constants.versionString, to: storage.assetDirectory, progress: progress ) } try startup.perform(.loadRegistries) { progress in try RegistryStore.populateShared(storage.registryDirectory, progress: progress) } // TODO: Track resource pack loading progress to improve loading screen granularity // Load resource pack and cache it if necessary let resourcePack = try startup.perform(.loadResourcePacks) { let packCache = storage.cache(forResourcePackNamed: "vanilla") let resourcePack = try ResourcePack.load( from: storage.assetDirectory, cacheDirectory: invalidateAssets ? nil : packCache ) if !FileSystem.directoryExists(packCache) || invalidateAssets { do { try resourcePack.cache(to: packCache) } catch { modal.warning("Failed to cache vanilla resource pack") } } return resourcePack } log.info("Finished loading (\(stopwatch.elapsed))") ThreadUtil.runInMain { loadResult = LoadResult( managedConfig: managedConfig, resourcePack: Box(resourcePack), pluginEnvironment: pluginEnvironment ) hasLoaded = true } } var body: some View { VStack { if let loadResult = loadResult { content(loadResult.managedConfig, loadResult.resourcePack, loadResult.pluginEnvironment) } else { ProgressLoadingView(progress: startup.progress, message: startup.message) } } .onAppear { DispatchQueue(label: "app-loading").async { do { try load() } catch { let richError: RichError if let error = error as? RichError { richError = error } else { richError = RichError("Failed to load.").becauseOf(error) } modal.error(richError) { Foundation.exit(1) } } } } } } ================================================ FILE: Sources/Client/Views/Startup/ProgressLoadingView.swift ================================================ import SwiftUI import DeltaCore struct ProgressLoadingView: View { // MARK: Public properties /// Loader progress public var progress: Double /// Loading message public let message: String // MARK: Private properties /// Loader bar border height private let loaderHeight: CGFloat = 20 /// Loader bar border width private let loaderSize: CGFloat = 4 /// Bar inset private let inset: CGFloat = 6 /// Progress bar width percentage @State private var animatedProgress: Double = 0 // MARK: Init /// Creates a new progress bar view. /// - Parameters: /// - progress: The progress from 0 to 1. /// - message: A description for the current task. init(progress: Double, message: String) { if progress < 0 || progress > 1 { log.error("Progress out of range: \(progress)") } self.progress = progress self.message = message } // MARK: View var body: some View { GeometryReader { proxy in let parentWidth = proxy.size.width let loaderWidth = parentWidth * 0.6 let progressBarWidth = loaderWidth - 2 * inset VStack(alignment: .center) { Text(message) HStack(alignment: .center) { Color.white .frame(width: progressBarWidth * animatedProgress) .frame(maxHeight: .infinity, alignment: .leading) Spacer() } .padding(.horizontal, inset) .padding(.vertical, inset) .frame(width: loaderWidth, height: loaderHeight) .overlay( PixellatedBorder() .stroke(Color.white, lineWidth: loaderSize) ) } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center) .background(Color.black) } .onChange(of: progress) { newProgress in ThreadUtil.runInMain { withAnimation(.easeInOut(duration: 1)) { animatedProgress = newProgress } } } .onAppear { withAnimation(.easeInOut(duration: 1)) { animatedProgress = progress } } } } ================================================ FILE: Sources/Client/Views/Startup/StartupStep.swift ================================================ import Foundation import DeltaCore /// All major startup steps in order. enum StartupStep: CaseIterable, TaskStep { case loadPlugins case downloadAssets case loadRegistries case loadResourcePacks /// The task description. var message: String { switch self { case .loadPlugins: return "Loading plugins" case .downloadAssets: return "Downloading vanilla assets (might take a little while)" case .loadRegistries: return "Loading registries" case .loadResourcePacks: return "Loading resource pack" } } /// The task's expected duration relative to the total. var relativeDuration: Double { switch self { case .loadPlugins: return 3 case .downloadAssets: return 15 case .loadRegistries: return 3 case .loadResourcePacks: return 15 } } } ================================================ FILE: Sources/Client/main.swift ================================================ // Start the main SwiftUI loop DeltaClientApp.main() ================================================ FILE: Sources/ClientGtk/ChatView.swift ================================================ import DeltaCore import SwiftCrossUI class ChatViewState: Observable { @Observed var error: String? @Observed var messages: [String] = [] @Observed var message = "" } struct ChatView: View { var client: Client var state = ChatViewState() init(_ client: Client) { self.client = client client.eventBus.registerHandler(handleEvent) } func handleEvent(_ event: Event) { switch event { case let event as ChatMessageReceivedEvent: state.messages.append( event.message.content.toText(with: client.resourcePack.getDefaultLocale()) ) default: break } } var body: some View { if let error = state.error { Text(error) } TextField("Message", state.$message) Button("Send") { guard !state.message.isEmpty else { return } // TODO: Create api for sending chat messages do { try client.sendPacket(ChatMessageServerboundPacket(state.message)) } catch { state.error = "Failed to send message: \(error)" } state.message = "" } ForEach(state.messages.reversed()) { message in Text(message) } .frame(minHeight: 200) .padding(.top, 10) } } ================================================ FILE: Sources/ClientGtk/DeltaClientApp.swift ================================================ import DefaultBackend import DeltaCore import Dispatch import Foundation import SwiftCrossUI @main struct DeltaClientApp: App { enum DeltaClientState { case loading(message: String) case selectServer case settings case play(ServerDescriptor, ResourcePack) } class StateStorage: Observable { @Observed var state = DeltaClientState.loading(message: "Loading") var resourcePack: ResourcePack? } var identifier = "dev.stackotter.DeltaClientApp" var state = StateStorage() public init() { load() } func load() { DispatchQueue(label: "loading").asyncAfter(deadline: .now().advanced(by: .milliseconds(100))) { let assetsDirectory = URL(fileURLWithPath: "assets") let registryDirectory = URL(fileURLWithPath: "registry") let cacheDirectory = URL(fileURLWithPath: "cache") do { // Download vanilla assets if they haven't already been downloaded if !StorageManager.directoryExists(at: assetsDirectory) { loading("Downloading assets") try ResourcePack.downloadVanillaAssets( forVersion: Constants.versionString, to: assetsDirectory, progress: nil ) } // Load registries loading("Loading registries") try RegistryStore.populateShared(registryDirectory, progress: nil) // Load resource pack and cache it if necessary loading("Loading resource pack") let packCache = cacheDirectory.appendingPathComponent("vanilla.rpcache/") var cacheExists = StorageManager.directoryExists(at: packCache) state.resourcePack = try ResourcePack.load( from: assetsDirectory, cacheDirectory: cacheExists ? packCache : nil ) cacheExists = StorageManager.directoryExists(at: packCache) if !cacheExists { do { if let resourcePack = state.resourcePack { try resourcePack.cache(to: packCache) } } catch { log.warning("Failed to cache vanilla resource pack") } } self.state.state = .selectServer } catch { loading("Failed to load: \(error.localizedDescription) (\(error))") } } } func loading(_ message: String) { self.state.state = .loading(message: message) } var body: some Scene { WindowGroup("Delta Client") { VStack { switch state.state { case .loading(let message): Text(message) case .selectServer: ServerListView { server in if let resourcePack = state.resourcePack { state.state = .play(server, resourcePack) } } openSettings: { state.state = .settings } case .settings: SettingsView { state.state = .selectServer } case .play(let server, let resourcePack): GameView(server, resourcePack) { state.state = .selectServer } } } .padding(10) } .defaultSize(width: 400, height: 200) } } ================================================ FILE: Sources/ClientGtk/GameView.swift ================================================ import DeltaCore import Dispatch import SwiftCrossUI class GameViewState: Observable { enum State { case error(String) case connecting case connected } var server: ServerDescriptor var client: Client @Observed var state = State.connecting init(_ server: ServerDescriptor, _ resourcePack: ResourcePack) { self.server = server client = Client( resourcePack: resourcePack, configuration: ConfigManager.default.coreConfiguration) client.eventBus.registerHandler { [weak self] event in guard let self = self else { return } self.handleClientEvent(event) } // TODO: Use structured concurrency to get join server to wait until login is finished so that // errors can be handled inline if let account = ConfigManager.default.config.selectedAccount { Task { do { try await client.joinServer(describedBy: server, with: account) } catch { state = .error("Failed to join server: \(error.localizedDescription)") } } } else { state = .error("Please select an account") } } func handleClientEvent(_ event: Event) { switch event { // TODO: This is absolutely ridiculous just for error handling. Unify all errors into a single // error event case let event as ConnectionFailedEvent: state = .error("Connection failed: \(event.networkError)") case is JoinWorldEvent: state = .connected case let event as LoginDisconnectEvent: state = .error("Disconnected from server during login:\n\n\(event.reason)") case let event as PlayDisconnectEvent: state = .error("Disconnected from server during play:\n\n\(event.reason)") case let packetError as PacketHandlingErrorEvent: let id = String(packetError.packetId, radix: 16) state = .error("Failed to handle packet with id 0x\(id):\n\n\(packetError.error)") case let packetError as PacketDecodingErrorEvent: let id = String(packetError.packetId, radix: 16) state = .error("Failed to decode packet with id 0x\(id):\n\n\(packetError.error)") case let event as ErrorEvent: if let message = event.message { state = .error("\(message): \(event.error)") } else { state = .error("\(event.error)") } default: break } } } struct GameView: View { var state: GameViewState var completionHandler: () -> Void init( _ server: ServerDescriptor, _ resourcePack: ResourcePack, _ completionHandler: @escaping () -> Void ) { state = GameViewState(server, resourcePack) self.completionHandler = completionHandler } var body: some View { switch state.state { case .error(let message): Text(message) Button("Back") { completionHandler() } case .connecting: Text("Connecting...") case .connected: ChatView(state.client) Button("Disconnect") { state.client.disconnect() completionHandler() } } } } ================================================ FILE: Sources/ClientGtk/ServerListView.swift ================================================ import DeltaCore import SwiftCrossUI indirect enum DetailState { case server(_ index: Int) case adding case editing(_ index: Int) case error(_ message: String, returnState: DetailState) } class ServerListViewState: Observable { @Observed var servers: [ServerDescriptor] = ConfigManager.default.config.servers @Observed var detailState = DetailState.adding @Observed var name = "" @Observed var address = "" } struct ServerListView: View { var joinServer: (ServerDescriptor) -> Void var openSettings: () -> Void var state = ServerListViewState() var body: some View { NavigationSplitView { VStack { Button("Add server") { state.detailState = .adding } Button("Settings") { openSettings() } ScrollView { ForEach(state.servers.indices) { index in Button(state.servers[index].name) { state.detailState = .server(index) } .padding(.bottom, 5) } } } .frame(minWidth: 100) .padding(.trailing, 10) } detail: { VStack { switch state.detailState { case .server(let index): serverView(index) case .adding: addingView() case .editing(let index): editingView(index) case .error(let message, let returnState): Text("Error: \(message)") Button("Back") { state.detailState = returnState } } } .padding(.leading, 10) } } func serverView(_ index: Int) -> some View { let server = state.servers[index] return VStack { Text(server.name) Text(server.description) Button("Connect") { joinServer(server) } Button("Edit") { state.name = server.name state.address = server.description state.detailState = .editing(index) } } } func addingView() -> some View { return VStack { Text("Add server") TextField("Name", state.$name) TextField("Address", state.$address) Button("Add") { do { let (host, port) = try Self.parseAddress(state.address) state.servers.append(ServerDescriptor(name: state.name, host: host, port: port)) save() state.detailState = .server(state.servers.count - 1) state.name = "" state.address = "" } catch AddressParsingError.invalidPort { state.detailState = .error("Invalid port", returnState: .adding) } catch { state.detailState = .error("Invalid address", returnState: .adding) } } } } func editingView(_ index: Int) -> some View { return VStack { Text("Edit server") TextField("Name", state.$name) TextField("Address", state.$address) Button("Apply") { do { let (host, port) = try Self.parseAddress(state.address) state.servers[index] = ServerDescriptor(name: state.name, host: host, port: port) save() state.detailState = .server(index) state.name = "" state.address = "" } catch AddressParsingError.invalidPort { state.detailState = .error("Invalid port", returnState: .editing(index)) } catch { state.detailState = .error("Invalid address", returnState: .editing(index)) } } Button("Remove") { state.servers.remove(at: index) save() state.name = "" state.address = "" if state.servers.count > 0 { state.detailState = .server(0) } else { state.detailState = .adding } } } } private enum AddressParsingError: Error { case invalidColonAmount case invalidPort } private static func parseAddress(_ address: String) throws -> (host: String, port: UInt16?) { let parts = address.split(separator: ":") guard parts.count > 0, parts.count <= 2 else { throw AddressParsingError.invalidColonAmount } let host = String(parts[0]) var port: UInt16? if parts.count == 2 { guard let parsed = UInt16(parts[1]) else { throw AddressParsingError.invalidPort } port = parsed } return (host, port) } private func save() { var config = ConfigManager.default.config config.servers = state.servers ConfigManager.default.setConfig(to: config) } } ================================================ FILE: Sources/ClientGtk/Settings/AccountInspectionView.swift ================================================ import DeltaCore import SwiftCrossUI struct AccountInspectorView: View { var account: Account var selectAccount: () -> Void var removeAccount: () -> Void public init( account: Account, selectAccount: @escaping () -> Void, removeAccount: @escaping () -> Void ) { self.account = account self.selectAccount = selectAccount self.removeAccount = removeAccount } var body: some View { VStack { Text("Username: \(account.username)") Text("Type: \(account.type)") Button("Select account") { selectAccount() } Button("Remove account") { removeAccount() } } } } ================================================ FILE: Sources/ClientGtk/Settings/AccountListView.swift ================================================ import DeltaCore import SwiftCrossUI struct AccountListView: View { var inspectAccount: (Account) -> Void var offlineLogin: () -> Void var microsoftLogin: () -> Void var body: some View { VStack { Button("Add offline account") { offlineLogin() } Button("Add Microsoft account") { microsoftLogin() } Text("Selected account: \(ConfigManager.default.config.selectedAccount?.username ?? "none")") ScrollView { ForEach(Array(ConfigManager.default.config.accounts.values)) { account in Button(account.username) { inspectAccount(account) } .padding(.bottom, 5) } } } } } ================================================ FILE: Sources/ClientGtk/Settings/MicrosoftLoginView.swift ================================================ import DeltaCore import SwiftCrossUI enum MicrosoftState { case authorizingDevice case login(MicrosoftDeviceAuthorizationResponse) case authenticatingUser case error(String) } class MicrosoftLoginViewState: Observable { @Observed var state = MicrosoftState.authorizingDevice } struct MicrosoftLoginView: View { var completionHandler: (Account) -> Void var state = MicrosoftLoginViewState() public init(_ completionHandler: @escaping (Account) -> Void) { self.completionHandler = completionHandler authorizeDevice() } var body: some View { VStack { switch state.state { case .authorizingDevice: Text("Fetching device authorization code") case .login(let response): Text(response.message) Button("Done") { state.state = .authenticatingUser authenticate(with: response) } case .authenticatingUser: Text("Authenticating...") case .error(let message): Text(message) } } } func authorizeDevice() { Task { do { let response = try await MicrosoftAPI.authorizeDevice() state.state = .login(response) } catch { state.state = .error("Failed to authorize device: \(error)") } } } func authenticate(with response: MicrosoftDeviceAuthorizationResponse) { Task { let account: MicrosoftAccount do { let accessToken = try await MicrosoftAPI.getMicrosoftAccessToken(response.deviceCode) account = try await MicrosoftAPI.getMinecraftAccount(accessToken) } catch { state.state = .error( "Failed to authenticate Microsoft account: \(error.localizedDescription)" ) return } completionHandler(Account.microsoft(account)) } } } ================================================ FILE: Sources/ClientGtk/Settings/OfflineLoginView.swift ================================================ import DeltaCore import SwiftCrossUI class OfflineLoginViewState: Observable { @Observed var username = "" @Observed var error: String? } struct OfflineLoginView: View { var completionHandler: (Account) -> Void var state = OfflineLoginViewState() var body: some View { VStack { TextField("Username", state.$username) if let error = state.error { Text(error) } Button("Add account") { guard !state.username.isEmpty else { state.error = "Please provide a username" return } completionHandler(Account.offline(OfflineAccount(username: state.username))) } } } } ================================================ FILE: Sources/ClientGtk/Settings/SettingsView.swift ================================================ import DeltaCore import SwiftCrossUI enum SettingsPage { case accountList case inspectAccount(Account) case offlineLogin case microsoftLogin } class SettingsViewState: Observable { @Observed var page = SettingsPage.accountList } struct SettingsView: View { var returnToServerList: () -> Void var state = SettingsViewState() var body: some View { NavigationSplitView { VStack { Button("Accounts") { state.page = .accountList } Button("Close") { returnToServerList() } } .padding(.trailing, 10) } detail: { VStack { switch state.page { case .accountList: AccountListView { account in state.page = .inspectAccount(account) } offlineLogin: { state.page = .offlineLogin } microsoftLogin: { state.page = .microsoftLogin } case .inspectAccount(let account): AccountInspectorView(account: account) { ConfigManager.default.selectAccount(account.id) state.page = .accountList } removeAccount: { var accounts = ConfigManager.default.config.accounts accounts.removeValue(forKey: account.id) if ConfigManager.default.config.selectedAccountId == account.id { ConfigManager.default.setAccounts(Array(accounts.values), selected: nil) } else { ConfigManager.default.setAccounts( Array(accounts.values), selected: ConfigManager.default.config.selectedAccountId) } state.page = .accountList } case .offlineLogin: OfflineLoginView { account in ConfigManager.default.addAccount(account) state.page = .accountList } case .microsoftLogin: MicrosoftLoginView { account in ConfigManager.default.addAccount(account) state.page = .accountList } } } .padding(.leading, 10) } } } ================================================ FILE: Sources/ClientGtk/Storage/Config.swift ================================================ import Foundation import DeltaCore public struct Config: Codable { /// The random token used to identify ourselves to Mojang's API public var clientToken: String = UUID().uuidString /// The id of the currently selected account. public var selectedAccountId: String? /// The dictionary containing all of the user's accounts. public var accounts: [String: Account] = [:] /// The user's server list. public var servers: [ServerDescriptor] = [] /// Rendering related configuration. public var render: RenderConfiguration = RenderConfiguration() /// Plugins that the user has explicitly unloaded. public var unloadedPlugins: [String] = [] /// The user's keymap. public var keymap: Keymap = Keymap.default /// Whether to use the sprint key as a toggle. public var toggleSprint: Bool = false /// Whether to use the sneak key as a toggle. public var toggleSneak: Bool = false /// The in game mouse sensitivity public var mouseSensitivity: Float = 1 /// The account the user has currently selected. public var selectedAccount: Account? { if let id = selectedAccountId { return accounts[id] } else { return nil } } } ================================================ FILE: Sources/ClientGtk/Storage/ConfigError.swift ================================================ import Foundation public enum ConfigError: LocalizedError { /// The account in question is of an invalid type. case invalidAccountType /// No account is selected. case noAccountSelected /// The currently selected account is of an invalid type. case invalidSelectedAccountType /// Failed to refresh the given account. case accountRefreshFailed(Error) public var errorDescription: String? { switch self { case .invalidAccountType: return "The account in question is of an invalid type." case .noAccountSelected: return "No account is selected." case .invalidSelectedAccountType: return "The currently selected account is of an invalid type." case .accountRefreshFailed(let error): return """ Failed to refresh the given account. Reason: \(error.localizedDescription). """ } } } ================================================ FILE: Sources/ClientGtk/Storage/ConfigManager.swift ================================================ import DeltaCore import Foundation /// Manages the config stored in a config file. public final class ConfigManager { /// The manager for the default config file. public static var `default` = ConfigManager( for: StorageManager.default.absoluteFromRelative("config.json") ) /// The current config (thread-safe). public private(set) var config: Config { get { lock.acquireReadLock() defer { lock.unlock() } return _config } set(newValue) { lock.acquireWriteLock() defer { lock.unlock() } _config = newValue } } /// The implementation of ClientConfiguration that allows DeltaCore to access required config values. let coreConfiguration: CoreConfiguration /// The non-threadsafe storage for ``config``. private var _config: Config /// The file to store config in. private let configFile: URL /// A queue to ensure that writing to the config file always happens serially. private let queue = DispatchQueue(label: "dev.stackotter.delta-client.ConfigManager") /// The lock used to synchronise access to ``ConfigManager/_config``. private let lock = ReadWriteLock() /// Creates a manager for the specified config file. Creates default config if required. private init(for configFile: URL) { self.configFile = configFile // Create default config if no config file exists guard StorageManager.fileExists(at: configFile) else { _config = Config() coreConfiguration = CoreConfiguration(_config) let data: Data do { data = try JSONEncoder().encode(_config) FileManager.default.createFile(atPath: configFile.path, contents: data, attributes: nil) } catch { // TODO: Proper error handling for ConfigManager fatalError("Failed to encode config: \(error)") } return } // Read the current config from the config file do { let data = try Data(contentsOf: configFile) _config = try CustomJSONDecoder().decode(Config.self, from: data) } catch { // Existing config is corrupted, overwrite it with defaults log.error("Invalid config.json, overwriting with defaults") _config = Config() let data: Data do { data = try JSONEncoder().encode(_config) FileManager.default.createFile(atPath: configFile.path, contents: data, attributes: nil) } catch { fatalError("Failed to encode config: \(error)") } } coreConfiguration = CoreConfiguration(_config) } /// Commits the given account to the config file. /// - Parameters: /// - account: The account to add. /// - shouldSelect: Whether to select the account or not. public func addAccount(_ account: Account, shouldSelect: Bool = false) { config.accounts[account.id] = account if shouldSelect { config.selectedAccountId = account.id } try? commitConfig() } /// Selects the given account. /// - Parameter id: The id of the account as received from the authentication servers (or generated from the username if offline). public func selectAccount(_ id: String?) { config.selectedAccountId = id try? commitConfig() } /// Commits the given array of user accounts to the config file replacing any existing accounts. /// - Parameters: /// - accounts: The user's accounts. /// - selected: Decides which account will be selected. public func setAccounts(_ accounts: [Account], selected: String?) { config.accounts = [:] for account in accounts { config.accounts[account.id] = account } config.selectedAccountId = selected try? commitConfig() } /// Updates the config and writes it to the config file. /// - Parameter config: The config to write. /// - Parameter saveToFile: Whether to write to the file or just update internal references. public func setConfig(to config: Config, saveToFile: Bool = true) { self.config = config do { try commitConfig(saveToFile: saveToFile) } catch { log.error("Failed to write config to file: \(error)") } } /// Resets the configuration to defaults. public func resetConfig() throws { log.info("Resetting config.json") config = Config() try commitConfig() } /// Commits the current config to this manager's config file. /// - Parameter saveToFile: Whether to write to the file or just update internal references. private func commitConfig(saveToFile: Bool = true) throws { coreConfiguration.config = config if saveToFile { try queue.sync { let data = try JSONEncoder().encode(self.config) try data.write(to: self.configFile) } } } } /// Enables DeltaCore to access required configuration values. /// This is passed to the Client constructor. class CoreConfiguration: ClientConfiguration { var config: Config init(_ config: Config) { self.config = config } public var render: RenderConfiguration { return config.render } public var keymap: Keymap { return config.keymap } public var toggleSprint: Bool { return config.toggleSprint } public var toggleSneak: Bool { return config.toggleSneak } } ================================================ FILE: Sources/ClientGtk/Storage/StorageManager.swift ================================================ import DeltaCore import Foundation final class StorageManager { static var `default` = StorageManager() public var storageDirectory: URL public var assetsDirectory: URL public var registryDirectory: URL public var cacheDirectory: URL private init() { if let applicationSupport = FileManager.default.urls( for: .applicationSupportDirectory, in: .userDomainMask ).first { storageDirectory = applicationSupport.appendingPathComponent("delta-client") } else { log.warning("Failed to get application support directory, using temporary directory instead") let fallback = FileManager.default.temporaryDirectory.appendingPathComponent( "delta-client.fallback") storageDirectory = fallback } assetsDirectory = storageDirectory.appendingPathComponent("assets") registryDirectory = storageDirectory.appendingPathComponent("registries") cacheDirectory = storageDirectory.appendingPathComponent("cache") log.trace("Using \(storageDirectory.path) as storage directory") if !Self.directoryExists(at: storageDirectory) { do { log.info("Creating storage directory") try? FileManager.default.removeItem(at: storageDirectory) try Self.createDirectory(at: storageDirectory) } catch { fatalError("Failed to create storage directory") } } } // MARK: Static shortenings of FileManager methods /// Checks if a file or directory exists at the given url. static func itemExists(at url: URL) -> Bool { return FileManager.default.fileExists(atPath: url.path) } /// Checks if a file or directory exists at the given url updating isDirectory. static func itemExists(at url: URL, isDirectory: inout ObjCBool) -> Bool { return FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory) } /// Checks if a file exists at the given url. static func fileExists(at url: URL) -> Bool { var isDirectory: ObjCBool = false return itemExists(at: url, isDirectory: &isDirectory) && !isDirectory.boolValue } /// Checks if a directory exists at the given url. static func directoryExists(at url: URL) -> Bool { var isDirectory: ObjCBool = false return itemExists(at: url, isDirectory: &isDirectory) && isDirectory.boolValue } /// Creates a directory at the given url with intermediate directories. /// Replaces any existing item at the url with an empty directory. static func createDirectory(at url: URL) throws { try? FileManager.default.removeItem(at: url) try FileManager.default.createDirectory( at: url, withIntermediateDirectories: true, attributes: nil) } /// Returns the contents of a directory at the given URL. static func contentsOfDirectory(at url: URL) throws -> [URL] { return try FileManager.default.contentsOfDirectory( at: url, includingPropertiesForKeys: nil, options: [] ) } /// Copies the specified item to the destination directory. static func copyItem(at item: URL, to destination: URL) throws { try FileManager.default.copyItem(at: item, to: destination) } // MARK: Delta Client specific methods /// Returns the absolute URL of a path relative to the storage directory. public func absoluteFromRelative(_ relativePath: String) -> URL { return storageDirectory.appendingPathComponent(relativePath) } } ================================================ FILE: Sources/Core/Logger/Logger.swift ================================================ import Puppy import Foundation import Rainbow @_exported import enum Puppy.LogLevel struct ConsoleLogFormatter: LogFormattable { func formatMessage( _ level: LogLevel, message: String, tag: String, function: String, file: String, line: UInt, swiftLogInfo: [String : String], label: String, date: Date, threadID: UInt64 ) -> String { let levelString: String switch level { case .trace: levelString = "TRACE".lightWhite case .verbose: levelString = "VERBO".magenta case.debug: levelString = "DEBUG".green case .info: levelString = "INFO ".lightBlue case .notice: levelString = "NOTE ".lightYellow case .warning: levelString = "WARN ".yellow.bold case .error: levelString = "ERROR".red.bold case .critical: levelString = "CRIT ".red.bold } return "[\(levelString)] \(message)" } } struct FileLogFormatter: LogFormattable { let dateFormatter = DateFormatter() func formatMessage( _ level: LogLevel, message: String, tag: String, function: String, file: String, line: UInt, swiftLogInfo: [String : String], label: String, date: Date, threadID: UInt64 ) -> String { let date = dateFormatter.string(from: date) let moduleName = moduleName(file) return "[\(date)] [\(moduleName)] [\(level)] \(message)" } } var consoleLogger = ConsoleLogger( "dev.stackotter.delta-client.ConsoleLogger", logLevel: .debug, logFormat: ConsoleLogFormatter() ) func createLogger() -> Puppy { Rainbow.enabled = ProcessInfo.processInfo.environment.keys.contains("__XCODE_BUILT_PRODUCTS_DIR_PATHS") ? false : Rainbow.enabled var log = Puppy() log.add(consoleLogger) return log } public var log = createLogger() public func setConsoleLogLevel(_ logLevel: LogLevel) { log.remove(consoleLogger) consoleLogger = ConsoleLogger( "dev.stackotter.delta-client.ConsoleLogger", logLevel: logLevel, logFormat: ConsoleLogFormatter() ) log.add(consoleLogger) } public func enableFileLogger(loggingTo file: URL) throws { let rotationConfig = RotationConfig( suffixExtension: .date_uuid, maxFileSize: 5 * 1024 * 1024, maxArchivedFilesCount: 3 ) let fileLogger = try FileRotationLogger( "dev.stackotter.delta-client.FileRotationLogger", logLevel: .debug, logFormat: FileLogFormatter(), fileURL: file.absoluteURL, rotationConfig: rotationConfig ) log.add(fileLogger) } ================================================ FILE: Sources/Core/Package.resolved ================================================ { "pins" : [ { "identity" : "asn1parser", "kind" : "remoteSourceControl", "location" : "https://github.com/stackotter/ASN1Parser", "state" : { "branch" : "main", "revision" : "f92a5b26f5c92d38ae858a5a77048e9af82331a3" } }, { "identity" : "async-http-client", "kind" : "remoteSourceControl", "location" : "https://github.com/swift-server/async-http-client.git", "state" : { "revision" : "037b70291941fe43de668066eb6fb802c5e181d2", "version" : "1.1.1" } }, { "identity" : "bigint", "kind" : "remoteSourceControl", "location" : "https://github.com/attaswift/BigInt.git", "state" : { "revision" : "e07e00fa1fd435143a2dcf8b7eec9a7710b2fdfe", "version" : "5.7.0" } }, { "identity" : "circuitbreaker", "kind" : "remoteSourceControl", "location" : "https://github.com/Kitura/CircuitBreaker.git", "state" : { "revision" : "bd4255762e48cc3748a448d197f1297a4ba705f7", "version" : "5.1.0" } }, { "identity" : "cryptoswift", "kind" : "remoteSourceControl", "location" : "https://github.com/krzyzanowskim/CryptoSwift", "state" : { "revision" : "e45a26384239e028ec87fbcc788f513b67e10d8f", "version" : "1.9.0" } }, { "identity" : "ecs", "kind" : "remoteSourceControl", "location" : "https://github.com/stackotter/ecs.git", "state" : { "branch" : "master", "revision" : "c7660bcd24e31ef2fc3457f56a2bf4a58c3ad6ee" } }, { "identity" : "fireblade-math", "kind" : "remoteSourceControl", "location" : "https://github.com/stackotter/fireblade-math.git", "state" : { "branch" : "matrix2x2", "revision" : "750239647673b07457bea80b39438a6db52198f1" } }, { "identity" : "jjliso8601dateformatter", "kind" : "remoteSourceControl", "location" : "https://github.com/michaeleisel/JJLISO8601DateFormatter", "state" : { "revision" : "50d5ea26ffd3f82e3db8516d939d80b745e168cf", "version" : "0.2.0" } }, { "identity" : "loggerapi", "kind" : "remoteSourceControl", "location" : "https://github.com/Kitura/LoggerAPI.git", "state" : { "revision" : "e82d34eab3f0b05391082b11ea07d3b70d2f65bb", "version" : "1.9.200" } }, { "identity" : "opencombine", "kind" : "remoteSourceControl", "location" : "https://github.com/OpenCombine/OpenCombine.git", "state" : { "revision" : "8576f0d579b27020beccbccc3ea6844f3ddfc2c2", "version" : "0.14.0" } }, { "identity" : "puppy", "kind" : "remoteSourceControl", "location" : "https://github.com/sushichop/Puppy", "state" : { "revision" : "80ebe6ab25fb7050904647cb96f6ad7bee77bad6", "version" : "0.9.0" } }, { "identity" : "rainbow", "kind" : "remoteSourceControl", "location" : "https://github.com/onevcat/Rainbow", "state" : { "revision" : "cdf146ae671b2624917648b61c908d1244b98ca1", "version" : "4.2.1" } }, { "identity" : "swift-algorithms", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-algorithms.git", "state" : { "revision" : "87e50f483c54e6efd60e885f7f5aa946cee68023", "version" : "1.2.1" } }, { "identity" : "swift-asn1", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-asn1.git", "state" : { "revision" : "9f542610331815e29cc3821d3b6f488db8715517", "version" : "1.6.0" } }, { "identity" : "swift-async-algorithms", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-async-algorithms.git", "state" : { "revision" : "9d349bcc328ac3c31ce40e746b5882742a0d1272", "version" : "1.1.3" } }, { "identity" : "swift-async-dns-resolver", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-async-dns-resolver.git", "state" : { "revision" : "36eedf108f9eda4feeaf47f3dfce657a88ef19aa", "version" : "0.6.0" } }, { "identity" : "swift-atomics", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-atomics.git", "state" : { "revision" : "b601256eab081c0f92f059e12818ac1d4f178ff7", "version" : "1.3.0" } }, { "identity" : "swift-case-paths", "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-case-paths", "state" : { "revision" : "206cbce3882b4de9aee19ce62ac5b7306cadd45b", "version" : "1.7.3" } }, { "identity" : "swift-certificates", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-certificates.git", "state" : { "revision" : "24ccdeeeed4dfaae7955fcac9dbf5489ed4f1a25", "version" : "1.18.0" } }, { "identity" : "swift-collections", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-collections.git", "state" : { "revision" : "6675bc0ff86e61436e615df6fc5174e043e57924", "version" : "1.4.1" } }, { "identity" : "swift-crypto", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-crypto.git", "state" : { "revision" : "bb4ba815dab96d4edc1e0b86d7b9acf9ff973a84", "version" : "4.3.1" } }, { "identity" : "swift-http-structured-headers", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-http-structured-headers.git", "state" : { "revision" : "76d7627bd88b47bf5a0f8497dd244885960dde0b", "version" : "1.6.0" } }, { "identity" : "swift-http-types", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-http-types.git", "state" : { "revision" : "45eb0224913ea070ec4fba17291b9e7ecf4749ca", "version" : "1.5.1" } }, { "identity" : "swift-image", "kind" : "remoteSourceControl", "location" : "https://github.com/stackotter/swift-image.git", "state" : { "branch" : "master", "revision" : "7160e2d8799f8b182498ab699aa695cb66cf4ea6" } }, { "identity" : "swift-log", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-log.git", "state" : { "revision" : "ce592ae52f982c847a4efc0dd881cc9eb32d29f2", "version" : "1.6.4" } }, { "identity" : "swift-nio", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-nio.git", "state" : { "revision" : "558f24a4647193b5a0e2104031b71c55d31ff83a", "version" : "2.97.1" } }, { "identity" : "swift-nio-extras", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-nio-extras.git", "state" : { "revision" : "abcf5312eb8ed2fb11916078aef7c46b06f20813", "version" : "1.33.0" } }, { "identity" : "swift-nio-http2", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-nio-http2.git", "state" : { "revision" : "6d8d596f0a9bfebb925733003731fe2d749b7e02", "version" : "1.42.0" } }, { "identity" : "swift-nio-ssl", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-nio-ssl.git", "state" : { "revision" : "df9c3406028e3297246e6e7081977a167318b692", "version" : "2.36.1" } }, { "identity" : "swift-numerics", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-numerics.git", "state" : { "revision" : "0c0290ff6b24942dadb83a929ffaaa1481df04a2", "version" : "1.1.1" } }, { "identity" : "swift-package-zlib", "kind" : "remoteSourceControl", "location" : "https://github.com/fourplusone/swift-package-zlib", "state" : { "revision" : "03ecd41814d8929362f7439529f9682536a8de13", "version" : "1.2.11" } }, { "identity" : "swift-parsing", "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-parsing", "state" : { "revision" : "3432cb81164dd3d69a75d0d63205be5fbae2c34b", "version" : "0.14.1" } }, { "identity" : "swift-png", "kind" : "remoteSourceControl", "location" : "https://github.com/stackotter/swift-png", "state" : { "revision" : "b68a5662ef9887c8f375854720b3621f772bf8c5" } }, { "identity" : "swift-service-lifecycle", "kind" : "remoteSourceControl", "location" : "https://github.com/swift-server/swift-service-lifecycle.git", "state" : { "revision" : "9829955b385e5bb88128b73f1b8389e9b9c3191a", "version" : "2.11.0" } }, { "identity" : "swift-syntax", "kind" : "remoteSourceControl", "location" : "https://github.com/swiftlang/swift-syntax", "state" : { "revision" : "2b59c0c741e9184ab057fd22950b491076d42e91", "version" : "603.0.0" } }, { "identity" : "swift-system", "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-system.git", "state" : { "revision" : "7c6ad0fc39d0763e0b699210e4124afd5041c5df", "version" : "1.6.4" } }, { "identity" : "swiftcpudetect", "kind" : "remoteSourceControl", "location" : "https://github.com/JWhitmore1/SwiftCPUDetect", "state" : { "branch" : "main", "revision" : "5ca694c6ad7eef1199d69463fa956c24c202465f" } }, { "identity" : "swiftpackagesbase", "kind" : "remoteSourceControl", "location" : "https://github.com/ITzTravelInTime/SwiftPackagesBase", "state" : { "revision" : "79477622b5dbacc3722d485c5060c46a90740016", "version" : "0.0.23" } }, { "identity" : "swiftyrequest", "kind" : "remoteSourceControl", "location" : "https://github.com/Kitura/SwiftyRequest.git", "state" : { "revision" : "2c543777a5088bed811503a68551a4b4eceac198", "version" : "3.2.200" } }, { "identity" : "xctest-dynamic-overlay", "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/xctest-dynamic-overlay", "state" : { "revision" : "dfd70507def84cb5fb821278448a262c6ff2bbad", "version" : "1.9.0" } }, { "identity" : "zipfoundation", "kind" : "remoteSourceControl", "location" : "https://github.com/weichsel/ZIPFoundation.git", "state" : { "revision" : "22787ffb59de99e5dc1fbfe80b19c97a904ad48d", "version" : "0.9.20" } }, { "identity" : "zippyjson", "kind" : "remoteSourceControl", "location" : "https://github.com/michaeleisel/ZippyJSON", "state" : { "revision" : "ddbbc024ba5a826f9676035a0a090a0bc2d40755", "version" : "1.2.15" } }, { "identity" : "zippyjsoncfamily", "kind" : "remoteSourceControl", "location" : "https://github.com/michaeleisel/ZippyJSONCFamily", "state" : { "revision" : "c1c0f88977359ea85b81e128b2d988e8250dfdae", "version" : "1.2.14" } } ], "version" : 2 } ================================================ FILE: Sources/Core/Package.swift ================================================ // swift-tools-version:5.9 import PackageDescription let debugLocks = false // MARK: Products var productTargets = ["DeltaCore", "DeltaLogger"] #if canImport(Metal) productTargets.append("DeltaRenderer") #endif // MARK: Targets var targets: [Target] = [ .target( name: "DeltaCore", dependencies: [ "DeltaLogger", "ZIPFoundation", "ASN1Parser", "CryptoSwift", "SwiftCPUDetect", .product(name: "FirebladeECS", package: "ecs"), .product( name: "SwiftyRequest", package: "SwiftyRequest", condition: .when(platforms: [.linux])), .product(name: "OpenCombine", package: "OpenCombine", condition: .when(platforms: [.linux])), .product(name: "Atomics", package: "swift-atomics"), .product( name: "ZippyJSON", package: "ZippyJSON", condition: .when(platforms: [.macOS, .iOS, .tvOS])), .product(name: "Parsing", package: "swift-parsing"), .product(name: "Collections", package: "swift-collections"), .product(name: "OrderedCollections", package: "swift-collections"), .product(name: "FirebladeMath", package: "fireblade-math"), .product(name: "AsyncDNSResolver", package: "swift-async-dns-resolver"), .product(name: "Z", package: "swift-package-zlib"), .product(name: "SwiftImage", package: "swift-image"), .product(name: "PNG", package: "swift-png"), ], path: "Sources", swiftSettings: debugLocks ? [.define("DEBUG_LOCKS")] : [] ), .target( name: "DeltaLogger", dependencies: [ "Puppy", "Rainbow", ], path: "Logger" ), .testTarget( name: "DeltaCoreUnitTests", dependencies: ["DeltaCore"] ), ] #if canImport(Metal) targets.append( .target( name: "DeltaRenderer", dependencies: [ "DeltaCore" ], path: "Renderer", resources: [ .process("Shader/") ] ) ) #endif let package = Package( name: "DeltaCore", platforms: [.macOS(.v11), .iOS(.v14)], products: [ .library(name: "DeltaCore", type: .dynamic, targets: productTargets), .library(name: "StaticDeltaCore", type: .static, targets: productTargets), ], dependencies: [ .package(url: "https://github.com/weichsel/ZIPFoundation.git", from: "0.9.20"), .package(url: "https://github.com/apple/swift-collections.git", from: "1.0.3"), .package(url: "https://github.com/apple/swift-atomics.git", from: "1.0.2"), .package(url: "https://github.com/stackotter/ecs.git", branch: "master"), .package(url: "https://github.com/michaeleisel/ZippyJSON", from: "1.2.4"), .package(url: "https://github.com/pointfreeco/swift-parsing", from: "0.12.1"), .package(url: "https://github.com/stackotter/fireblade-math.git", branch: "matrix2x2"), .package(url: "https://github.com/apple/swift-async-dns-resolver.git", from: "0.4.0"), .package(url: "https://github.com/fourplusone/swift-package-zlib", from: "1.2.11"), .package(url: "https://github.com/stackotter/swift-image.git", branch: "master"), .package(url: "https://github.com/OpenCombine/OpenCombine.git", from: "0.13.0"), .package( url: "https://github.com/stackotter/swift-png", revision: "b68a5662ef9887c8f375854720b3621f772bf8c5" ), .package(url: "https://github.com/stackotter/ASN1Parser", branch: "main"), .package(url: "https://github.com/krzyzanowskim/CryptoSwift", from: "1.6.0"), .package(url: "https://github.com/Kitura/SwiftyRequest.git", from: "3.1.0"), .package(url: "https://github.com/JWhitmore1/SwiftCPUDetect", branch: "main"), .package(url: "https://github.com/sushichop/Puppy", .upToNextMinor(from: "0.9.0")), .package(url: "https://github.com/onevcat/Rainbow", from: "4.0.1"), ], targets: targets ) ================================================ FILE: Sources/Core/Renderer/Camera/Camera.swift ================================================ import Foundation import Metal import FirebladeMath import DeltaCore /// Holds information about a camera to render from. public struct Camera { /// The vertical FOV in radians. public private(set) var fovY: Float = 0.5 * .pi // 90deg /// The near clipping plane. public private(set) var nearDistance: Float = 0.04 /// The far clipping plant. public private(set) var farDistance: Float = 800 /// The aspect ratio. public private(set) var aspect: Float = 1 /// The camera's position. public private(set) var position: Vec3f = [0, 0, 0] // TODO: Rename xRot and yRot to pitch and yaw when refactoring Camera /// The camera's rotation around the x axis (pitch). -pi/2 radians is straight up, /// 0 is straight ahead, and pi/2 radians is straight down. public private(set) var xRot: Float = 0 /// The camera's rotation around the y axis measured counter-clockwise from the /// positive z axis when looking down from above (yaw). public private(set) var yRot: Float = 0 /// The ray defining the camera's position and the direction it faces. public var ray: Ray { Ray(from: position, pitch: xRot, yaw: yRot) } // TODO: Rename these matrices to translation, rotation, and projection. Could // even replace translation and rotation with a single combined `framing` // matrix if no code ever uses them separately. /// A translation matrix from world-space to player-centered coordinates. public var worldToPlayer: Mat4x4f { MatrixUtil.translationMatrix(-position) } /// A rotation matrix from player-centered coordinates to camera-space. public var playerToCamera: Mat4x4f { MatrixUtil.rotationMatrix(y: -(Float.pi + yRot)) * MatrixUtil.rotationMatrix(x: -xRot) } /// The projection matrix from camera-space to clip-space. public var cameraToClip: Mat4x4f { MatrixUtil.projectionMatrix( near: nearDistance, far: farDistance, aspect: aspect, fieldOfViewY: fovY ) } /// The camera's position as an entity position. public var entityPosition: EntityPosition { return EntityPosition(Vec3d(position)) } /// The direction that the camera is pointing. public var directionVector: Vec3f { let rotationMatrix = MatrixUtil.rotationMatrix(y: Float.pi + yRot) * MatrixUtil.rotationMatrix(x: xRot) let unitVector = Vec4f(0, 0, 1, 0) return (unitVector * rotationMatrix).xyz } private var frustum: Frustum? private var uniformsBuffers: [MTLBuffer] = [] private var uniformsIndex = 0 private var uniformsCount = 6 public init(_ device: MTLDevice) throws { // TODO: Multiple-buffering should be implemented separately from the camera. I reckon the // camera shouldn't have to know about Metal at all, or throw any errors. for i in 0...stride, options: .storageModeShared ) else { throw RenderError.failedtoCreateWorldUniformBuffers } buffer.label = "Camera.uniforms-\(i)" uniformsBuffers.append(buffer) } } /// Update a buffer to contain the current world to clip uniforms. public mutating func getUniformsBuffer() -> MTLBuffer { let buffer = uniformsBuffers[uniformsIndex] uniformsIndex = (uniformsIndex + 1) % uniformsCount var uniforms = getUniforms() buffer.contents().copyMemory( from: &uniforms, byteCount: MemoryLayout.stride ) return buffer } /// Get the world to clip uniforms. public mutating func getUniforms() -> CameraUniforms { return CameraUniforms( framing: worldToPlayer * playerToCamera, projection: cameraToClip ) } /// Sets this camera's vertical FOV. Horizontal FOV is calculated from vertical FOV and aspect ratio. public mutating func setFovY(_ fovY: Float) { self.fovY = fovY frustum = nil } /// Sets this camera's clipping planes. public mutating func setClippingPlanes(near: Float, far: Float) { nearDistance = near farDistance = far frustum = nil } /// Sets this camera's aspect ratio. public mutating func setAspect(_ aspect: Float) { self.aspect = aspect frustum = nil } /// Sets this camera's position in world coordinates. public mutating func setPosition(_ position: Vec3f) { self.position = position frustum = nil } /// Sets the rotation of this camera in radians. public mutating func setRotation(xRot: Float, yRot: Float) { self.xRot = xRot self.yRot = yRot frustum = nil } /// Calculates the camera's frustum from its parameters. public func calculateFrustum() -> Frustum { let worldToClip = getWorldToClipMatrix() return Frustum(worldToClip: worldToClip) } /// Faces this camera in the direction of an entity's rotation. public mutating func setRotation(playerLook: EntityRotation) { xRot = playerLook.pitch yRot = playerLook.yaw } // TODO: Make this a computed property /// Returns this camera's world-space to clip-space transformation matrix. public func getWorldToClipMatrix() -> Mat4x4f { return worldToPlayer * playerToCamera * cameraToClip } // TODO: This whole frustum caching thing seems weird. It can probably just be moved to the usage // site. i.e. just call computeFrustum once to get the frustum. /// Calculates the camera's frustum and saves it. Cached frustum can be fetched via ``getFrustum()``. public mutating func cacheFrustum() { self.frustum = calculateFrustum() } public func getFrustum() -> Frustum { return frustum ?? calculateFrustum() } /// Determine if the specified chunk is visible from this camera. public func isChunkVisible(at chunkPosition: ChunkPosition) -> Bool { let frustum = getFrustum() return frustum.approximatelyContains(chunkPosition.axisAlignedBoundingBox) } /// Determine if the specified chunk section is visible from this camera. public func isChunkSectionVisible(at chunkSectionPosition: ChunkSectionPosition) -> Bool { let frustum = getFrustum() return frustum.approximatelyContains(chunkSectionPosition.axisAlignedBoundingBox) } } ================================================ FILE: Sources/Core/Renderer/Camera/Frustum.swift ================================================ import Foundation import FirebladeMath import DeltaCore // method from: http://web.archive.org/web/20120531231005/http://crazyjoke.free.fr/doc/3D/plane%20extraction.pdf public struct Frustum { public var worldToClip: Mat4x4f public var left: Vec4d public var right: Vec4d public var top: Vec4d public var bottom: Vec4d public var near: Vec4d public var far: Vec4d public init(worldToClip: Mat4x4f) { self.worldToClip = worldToClip let columns = worldToClip.columns left = Vec4d(columns.3 + columns.0) right = Vec4d(columns.3 - columns.0) bottom = Vec4d(columns.3 + columns.1) top = Vec4d(columns.3 - columns.1) near = Vec4d(columns.2) far = Vec4d(columns.3 - columns.2) } public func approximatelyContains(_ boundingBox: AxisAlignedBoundingBox) -> Bool { let homogenousVertices = boundingBox.getHomogenousVertices() let planeVectors = [left, right, near, bottom, top] for planeVector in planeVectors { var boundingBoxLiesOutside = true for vertex in homogenousVertices { if dot(vertex, planeVector) > 0 { boundingBoxLiesOutside = false break } } if boundingBoxLiesOutside { return false } } // the bounding box does not lie completely outside any of the frustum planes // although it may still be outside the frustum (hence approximate) return true } } ================================================ FILE: Sources/Core/Renderer/CameraUniforms.swift ================================================ import FirebladeMath public struct CameraUniforms { /// Translation and rotation (sets up the camera's framing). public var framing: Mat4x4f /// The projection converting camera-space coordinates to clip-space coordinates. public var projection: Mat4x4f public init(framing: Mat4x4f, projection: Mat4x4f) { self.framing = framing self.projection = projection } } ================================================ FILE: Sources/Core/Renderer/CaptureState.swift ================================================ import Foundation extension RenderCoordinator { /// The state of a GPU frame capture. struct CaptureState { /// The number of frames remaining. var framesRemaining: Int /// The file that the capture will be outputted to. var outputFile: URL } } ================================================ FILE: Sources/Core/Renderer/CelestialBodyUniforms.swift ================================================ import FirebladeMath public struct CelestialBodyUniforms { public var transformation: Mat4x4f public var textureIndex: UInt16 public var uvPosition: Vec2f public var uvSize: Vec2f public var type: CelestialBodyType public enum CelestialBodyType: UInt8 { case sun = 0 case moon = 1 } } ================================================ FILE: Sources/Core/Renderer/ChunkUniforms.swift ================================================ import DeltaCore import FirebladeMath public struct ChunkUniforms { /// The translation to convert chunk-space coordinates (with origin at the /// lowest, Northmost, Eastmost block of the chunk) to world-space coordinates. public var transformation: Mat4x4f public init(transformation: Mat4x4f) { self.transformation = transformation } public init() { transformation = MatrixUtil.identity } } ================================================ FILE: Sources/Core/Renderer/EndSkyUniforms.swift ================================================ import FirebladeMath struct EndSkyUniforms { var transformation: Mat4x4f var textureIndex: UInt16 } ================================================ FILE: Sources/Core/Renderer/EndSkyVertex.swift ================================================ import FirebladeMath struct EndSkyVertex { var position: Vec3f var uv: Vec2f } ================================================ FILE: Sources/Core/Renderer/Entity/EntityRenderer.swift ================================================ import DeltaCore import FirebladeECS import FirebladeMath import Foundation import MetalKit /// Renders all entities in the world the client is currently connected to. public struct EntityRenderer: Renderer { /// The color to render hit boxes as. Defaults to 0xe3c28d (light cream colour). public static let hitBoxColor = DeltaCore.RGBColor(hexCode: 0xe3c28d) /// The render pipeline state for rendering entities. Does not have blending enabled. private var renderPipelineState: MTLRenderPipelineState /// The render pipeline state for rendering block entities and block item entities. private var blockRenderPipelineState: MTLRenderPipelineState /// The buffer containing the uniforms for all rendered entities. private var instanceUniformsBuffer: MTLBuffer? private var entityTexturePalette: MetalTexturePalette private var blockTexturePalette: MetalTexturePalette private var entityModelPalette: EntityModelPalette private var itemModelPalette: ItemModelPalette private var blockModelPalette: BlockModelPalette /// The client that entities will be renderer for. private var client: Client /// The device that will be used to render. private var device: MTLDevice /// The command queue used to perform operations outside of the main render loop. private var commandQueue: MTLCommandQueue private var profiler: Profiler /// Should get updated each frame via `setVisibleChunks`. private var visibleChunks: Set = [] /// Creates a new entity renderer. public init( client: Client, device: MTLDevice, commandQueue: MTLCommandQueue, profiler: Profiler, blockTexturePalette: MetalTexturePalette ) throws { self.client = client self.device = device self.commandQueue = commandQueue self.profiler = profiler self.blockTexturePalette = blockTexturePalette // Load library // TODO: Avoid loading library again and again let library = try MetalUtil.loadDefaultLibrary(device) let vertexFunction = try MetalUtil.loadFunction("entityVertexShader", from: library) let fragmentFunction = try MetalUtil.loadFunction("entityFragmentShader", from: library) let blockVertexFunction = try MetalUtil.loadFunction("chunkVertexShader", from: library) let blockFragmentFunction = try MetalUtil.loadFunction("chunkFragmentShader", from: library) // Create render pipeline state renderPipelineState = try MetalUtil.makeRenderPipelineState( device: device, label: "EntityRenderer.renderPipelineState", vertexFunction: vertexFunction, fragmentFunction: fragmentFunction, blendingEnabled: false ) // TODO: Consider supporting OIT here too? Probably not of much use cause most block item // entities aren't translucent, and there should never be many instances of them since // item entities merge. blockRenderPipelineState = try MetalUtil.makeRenderPipelineState( device: device, label: "EntityRenderer.blockRenderPipelineState", vertexFunction: blockVertexFunction, fragmentFunction: blockFragmentFunction, blendingEnabled: true ) entityTexturePalette = try MetalTexturePalette( palette: client.resourcePack.vanillaResources.entityTexturePalette, device: device, commandQueue: commandQueue ) entityModelPalette = client.resourcePack.vanillaResources.entityModelPalette itemModelPalette = client.resourcePack.vanillaResources.itemModelPalette blockModelPalette = client.resourcePack.vanillaResources.blockModelPalette } /// Renders all entity hit boxes using instancing. public mutating func render( view: MTKView, encoder: MTLRenderCommandEncoder, commandBuffer: MTLCommandBuffer, worldToClipUniformsBuffer: MTLBuffer, camera: Camera ) throws { var isFirstPerson = false client.game.accessPlayer { player in isFirstPerson = player.camera.perspective == .firstPerson } // Get all renderable entities var geometry = Geometry() var blockGeometry = Geometry() var translucentBlockGeometry = SortableMesh(uniforms: ChunkUniforms()) client.game.accessNexus { nexus in // If the player is in first person view we don't render them profiler.push(.getEntities) let entities: Family> if isFirstPerson { entities = nexus.family( requiresAll: EntityPosition.self, EntityRotation.self, EntityHitBox.self, EntityKindId.self, excludesAll: ClientPlayerEntity.self ) } else { entities = nexus.family( requiresAll: EntityPosition.self, EntityRotation.self, EntityHitBox.self, EntityKindId.self ) } profiler.pop() let renderDistance = client.configuration.render.renderDistance let cameraChunk = camera.entityPosition.chunk // Create uniforms for each entity profiler.push(.createRegularEntityMeshes) for (entity, position, rotation, hitbox, kindId) in entities.entityAndComponents { // Don't render entities that are outside of the render distance let chunkPosition = position.chunk if !chunkPosition.isWithinRenderDistance(renderDistance, of: cameraChunk) { continue } guard var kindIdentifier = kindId.entityKind?.identifier else { log.warning("Unknown entity kind '\(kindId.id)'") continue } if kindIdentifier == Identifier(name: "ender_dragon") { kindIdentifier = Identifier(name: "dragon") } let lightLevel = client.game.world.getLightLevel(at: position.block) buildEntityMesh( entity: entity, entityKindIdentifier: kindIdentifier, position: Vec3f(position.smoothVector), pitch: rotation.smoothPitch, yaw: rotation.smoothYaw, hitbox: hitbox.aabb(at: position.smoothVector), lightLevel: lightLevel, into: &geometry, blockGeometry: &blockGeometry, translucentBlockGeometry: &translucentBlockGeometry ) } profiler.pop() profiler.push(.createBlockEntityMeshes) for chunkPosition in visibleChunks { guard let chunk = client.game.world.chunk(at: chunkPosition) else { continue } for blockEntity in chunk.getBlockEntities() { let position = blockEntity.position.floatVector + Vec3f(0.5, 0, 0.5) let block = chunk.getBlock(at: blockEntity.position.relativeToChunk) let direction = block.stateProperties.facing ?? .south let lightLevel = client.game.world.getLightLevel(at: blockEntity.position) buildEntityMesh( entity: nil, entityKindIdentifier: blockEntity.identifier, position: position, pitch: 0, yaw: Self.blockEntityYaw(toFace: direction), hitbox: AxisAlignedBoundingBox(position: .zero, size: Vec3d(1, 1, 1)), lightLevel: lightLevel, into: &geometry, blockGeometry: &blockGeometry, translucentBlockGeometry: &translucentBlockGeometry ) } } profiler.pop() } profiler.push(.encodeEntities) if !geometry.isEmpty { encoder.setRenderPipelineState(renderPipelineState) encoder.setFragmentTexture(entityTexturePalette.arrayTexture, index: 0) var mesh = Mesh(geometry, uniforms: ()) try mesh.render(into: encoder, with: device, commandQueue: commandQueue) } if !blockGeometry.isEmpty || !translucentBlockGeometry.isEmpty { encoder.setRenderPipelineState(blockRenderPipelineState) encoder.setVertexBuffer(blockTexturePalette.textureStatesBuffer, offset: 0, index: 3) encoder.setFragmentTexture(blockTexturePalette.arrayTexture, index: 0) if !blockGeometry.isEmpty { var blockMesh = Mesh(blockGeometry, uniforms: ChunkUniforms()) try blockMesh.render(into: encoder, with: device, commandQueue: commandQueue) } if !translucentBlockGeometry.isEmpty { try translucentBlockGeometry.render( viewedFrom: camera.position, sort: true, encoder: encoder, device: device, commandQueue: commandQueue ) } } profiler.pop() } private func buildEntityMesh( entity: Entity? = nil, entityKindIdentifier: Identifier, position: Vec3f, pitch: Float, yaw: Float, hitbox: AxisAlignedBoundingBox, lightLevel: LightLevel, into geometry: inout Geometry, blockGeometry: inout Geometry, translucentBlockGeometry: inout SortableMesh ) { var translucentBlockElement = SortableMeshElement() EntityMeshBuilder( entity: entity, entityKind: entityKindIdentifier, position: position, pitch: pitch, yaw: yaw, entityModelPalette: entityModelPalette, itemModelPalette: itemModelPalette, blockModelPalette: blockModelPalette, entityTexturePalette: entityTexturePalette.palette, blockTexturePalette: blockTexturePalette.palette, hitbox: hitbox, lightLevel: lightLevel ).build( into: &geometry, blockGeometry: &blockGeometry, translucentBlockGeometry: &translucentBlockElement ) translucentBlockGeometry.add(translucentBlockElement) } /// Computes the yaw required for a block entity to face a given direction. private static func blockEntityYaw(toFace direction: Direction) -> Float { switch direction { case .south, .up, .down: return 0 case .west: return .pi / 2 case .north: return .pi case .east: return -.pi / 2 } } /// Sets the chunks that block entities should be rendered from. public mutating func setVisibleChunks(_ visibleChunks: Set) { self.visibleChunks = visibleChunks } } ================================================ FILE: Sources/Core/Renderer/Entity/EntityVertex.swift ================================================ /// The vertex format used by the entity shader. public struct EntityVertex { public var x: Float public var y: Float public var z: Float public var r: Float public var g: Float public var b: Float public var u: Float public var v: Float public var skyLightLevel: UInt8 public var blockLightLevel: UInt8 /// ``UInt16/max`` indicates that no texture is to be used. I would usually use /// an optional to model that, but this type needs to be compatible with C as we /// pass it off to the shaders for rendering. public var textureIndex: UInt16 public init( x: Float, y: Float, z: Float, r: Float, g: Float, b: Float, u: Float, v: Float, skyLightLevel: UInt8, blockLightLevel: UInt8, textureIndex: UInt16? ) { self.x = x self.y = y self.z = z self.r = r self.g = g self.b = b self.u = u self.v = v self.skyLightLevel = skyLightLevel self.blockLightLevel = blockLightLevel self.textureIndex = textureIndex ?? .max } } ================================================ FILE: Sources/Core/Renderer/EntityUniforms.swift ================================================ import FirebladeMath public struct EntityUniforms { /// The transformation for an instance of the generic entity hitbox. Scales and /// translates the hitbox to the correct size and world-space position. public var transformation: Mat4x4f public init(transformation: Mat4x4f) { self.transformation = transformation } } ================================================ FILE: Sources/Core/Renderer/FogUniforms.swift ================================================ import FirebladeMath /// Uniforms used to render distance fog. struct FogUniforms { var fogColor: Vec3f var fogStart: Float var fogEnd: Float var fogDensity: Float var isLinear: Bool } ================================================ FILE: Sources/Core/Renderer/GUI/GUIContext.swift ================================================ import Metal import DeltaCore struct GUIContext { var font: Font var fontArrayTexture: MTLTexture var guiTexturePalette: GUITexturePalette var guiArrayTexture: MTLTexture var itemTexturePalette: TexturePalette var itemArrayTexture: MTLTexture var itemModelPalette: ItemModelPalette var blockArrayTexture: MTLTexture var blockModelPalette: BlockModelPalette var blockTexturePalette: TexturePalette } ================================================ FILE: Sources/Core/Renderer/GUI/GUIElementMesh.swift ================================================ import MetalKit import FirebladeMath import DeltaCore /// A generic texture-backed GUI element. struct GUIElementMesh { /// The amount of extra room to allocate when creating a vertex buffer to avoid needing to create /// a new one too soon. Currently set to leave enough room for 20 extra quads. This measurably /// cuts down the number of new vertex buffers created. private static let vertexBufferHeadroom = 80 * MemoryLayout.stride /// The element's position. var position: Vec2i = .zero /// The unscaled size. var size: Vec2i /// The vertices making up the element grouped by quad as an optimisation for converting arrays of /// quads to meshes. var vertices: GUIVertexStorage /// The array texture used to render this element. var arrayTexture: MTLTexture? /// The buffer containing ``vertices``. var vertexBuffer: MTLBuffer? /// The mesh's uniforms. var uniformsBuffer: MTLBuffer? /// The minimum size that the vertex buffer must be. var requiredVertexBufferSize: Int { return vertices.count * MemoryLayout.stride } /// Creates a mesh from a collection of quads. init(size: Vec2i, arrayTexture: MTLTexture?, quads: [GUIQuad]) { self.size = size self.arrayTexture = arrayTexture // Basically just a fancy Array.map (it's measurably faster than using flatmap in this case and // this is performance critical, otherwise I would never use this code) let quadCount = quads.count vertices = .tuples(Array(unsafeUninitializedCapacity: quadCount) { buffer, count in quads.withUnsafeBufferPointer { quadsPointer in for i in 0...stride, options: [] ) self.uniformsBuffer = uniformsBuffer } // Assume that the buffers are outdated vertices.withUnsafeMutableVertexBufferPointer { buffer in vertexBuffer.contents().copyMemory( from: buffer.baseAddress!, byteCount: vertexCount * MemoryLayout.stride ) } uniformsBuffer.contents().copyMemory( from: &uniforms, byteCount: MemoryLayout.stride ) encoder.setVertexBuffer(vertexBuffer, offset: 0, index: 1) encoder.setVertexBuffer(uniformsBuffer, offset: 0, index: 2) encoder.setFragmentTexture(arrayTexture, index: 0) encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: vertexCount / 4 * 6) } } ================================================ FILE: Sources/Core/Renderer/GUI/GUIElementMeshArray.swift ================================================ import FirebladeMath extension Array where Element == GUIElementMesh { mutating func translate(amount: Vec2i) { for i in 0.. Vec2i { var iterator = makeIterator() guard let first = iterator.next() else { return [0, 0] } var minX = first.position.x var maxX = minX + first.size.x var minY = first.position.y var maxY = minY + first.size.y while let mesh = iterator.next() { let position = mesh.position let size = mesh.size let meshMaxX = position.x + size.x let meshMaxY = position.y + size.y if meshMaxX > maxX { maxX = meshMaxX } if position.x < minX { minX = position.x } if meshMaxY > maxY { maxY = meshMaxY } if position.y < minY { minY = position.y } } return [maxX - minX, maxY - minY] } } ================================================ FILE: Sources/Core/Renderer/GUI/GUIElementUniforms.swift ================================================ import FirebladeMath /// The uniforms for a GUI element. struct GUIElementUniforms { /// The element's position. var position: Vec2f } ================================================ FILE: Sources/Core/Renderer/GUI/GUIQuad.swift ================================================ import Metal import FirebladeMath import DeltaCore /// A convenient way to construct the vertices for a GUI quad. struct GUIQuad { static let vertices: [(position: Vec2f, uv: Vec2f)] = [ (position: [0, 0], uv: [0, 0]), (position: [1, 0], uv: [1, 0]), (position: [1, 1], uv: [1, 1]), (position: [0, 1], uv: [0, 1]) ] private static let verticesBuffer = vertices.withUnsafeBufferPointer { $0 } var position: Vec2f var size: Vec2f var uvMin: Vec2f var uvSize: Vec2f var textureIndex: UInt16 var tint: Vec4f init( position: Vec2f, size: Vec2f, uvMin: Vec2f, uvSize: Vec2f, textureIndex: UInt16, tint: Vec4f = [1, 1, 1, 1] ) { self.position = position self.size = size self.uvMin = uvMin self.uvSize = uvSize self.textureIndex = textureIndex self.tint = tint } /// Creates a quad instance for a solid color rectangle. init( position: Vec2f, size: Vec2f, color: Vec4f ) { self.position = position self.size = size self.tint = color self.uvMin = .zero self.uvSize = .zero self.textureIndex = UInt16.max } /// Creates a quad instance for the given sprite. init( for sprite: GUISpriteDescriptor, guiTexturePalette: GUITexturePalette, guiArrayTexture: MTLTexture, position: Vec2i = .zero ) { let textureSize: Vec2f = [ Float(guiArrayTexture.width), Float(guiArrayTexture.height) ] self.position = Vec2f(position) size = Vec2f(sprite.size) uvMin = Vec2f(sprite.position) / textureSize uvSize = self.size / textureSize textureIndex = UInt16(guiTexturePalette.textureIndex(for: sprite.slice)) tint = [1, 1, 1, 1] } /// Gets the vertices of the quad as an array. func toVertices() -> [GUIVertex] { // Basically just creating an array containing four vertices but fancilly to make it faster (I'm // only doing it this way because it measurably speeds up some other parts of the code). return Array(unsafeUninitializedCapacity: 4) { buffer, count in let tuple = toVertexTuple() buffer[0] = tuple.0 buffer[1] = tuple.1 buffer[2] = tuple.2 buffer[3] = tuple.3 count = 4 } } /// An alternative to ``toVertices()`` that can be used in performance critical situations. func toVertexTuple() -> (GUIVertex, GUIVertex, GUIVertex, GUIVertex) { // swiftlint:disable:this large_tuple ( GUIVertex( position: Self.verticesBuffer[0].position * size + position, uv: Self.verticesBuffer[0].uv * uvSize + uvMin, tint: tint, textureIndex: textureIndex ), GUIVertex( position: Self.verticesBuffer[1].position * size + position, uv: Self.verticesBuffer[1].uv * uvSize + uvMin, tint: tint, textureIndex: textureIndex ), GUIVertex( position: Self.verticesBuffer[2].position * size + position, uv: Self.verticesBuffer[2].uv * uvSize + uvMin, tint: tint, textureIndex: textureIndex ), GUIVertex( position: Self.verticesBuffer[3].position * size + position, uv: Self.verticesBuffer[3].uv * uvSize + uvMin, tint: tint, textureIndex: textureIndex ) ) } /// Translates the quad by the given amount. /// - Parameter amount: The amount of pixels to translate by along each axis. mutating func translate(amount: Vec2f) { self.position += amount } } ================================================ FILE: Sources/Core/Renderer/GUI/GUIRenderer.swift ================================================ import DeltaCore import FirebladeMath import MetalKit #if canImport(UIKit) import UIKit #endif /// The renderer for the GUI (chat, f3, scoreboard etc.). public final class GUIRenderer: Renderer { static let scale: Float = 2 var device: MTLDevice var font: Font var locale: MinecraftLocale var uniformsBuffer: MTLBuffer var pipelineState: MTLRenderPipelineState var profiler: Profiler var previousUniforms: GUIUniforms? var client: Client var fontArrayTexture: MTLTexture var guiTexturePalette: GUITexturePalette var guiArrayTexture: MTLTexture var itemTexturePalette: TexturePalette var itemArrayTexture: MTLTexture var itemModelPalette: ItemModelPalette var blockArrayTexture: MTLTexture var blockModelPalette: BlockModelPalette var blockTexturePalette: TexturePalette var entityArrayTexture: MTLTexture var entityTexturePalette: TexturePalette var entityModelPalette: EntityModelPalette var cache: [GUIElementMesh] = [] public init( client: Client, device: MTLDevice, commandQueue: MTLCommandQueue, profiler: Profiler ) throws { self.client = client self.device = device self.profiler = profiler // Create array texture font = client.resourcePack.vanillaResources.fontPalette.defaultFont locale = client.resourcePack.getDefaultLocale() let resources = client.resourcePack.vanillaResources let font = resources.fontPalette.defaultFont fontArrayTexture = try font.createArrayTexture( device: device, commandQueue: commandQueue ) fontArrayTexture.label = "fontArrayTexture" guiTexturePalette = try GUITexturePalette(resources.guiTexturePalette) guiArrayTexture = try MetalTexturePalette.createArrayTexture( for: resources.guiTexturePalette, device: device, commandQueue: commandQueue, includeAnimations: false ) guiArrayTexture.label = "guiArrayTexture" itemTexturePalette = resources.itemTexturePalette itemArrayTexture = try MetalTexturePalette.createArrayTexture( for: resources.itemTexturePalette, device: device, commandQueue: commandQueue, includeAnimations: false ) itemArrayTexture.label = "itemArrayTexture" itemModelPalette = resources.itemModelPalette blockTexturePalette = resources.blockTexturePalette blockArrayTexture = try MetalTexturePalette.createArrayTexture( for: resources.blockTexturePalette, device: device, commandQueue: commandQueue, includeAnimations: false ) blockArrayTexture.label = "blockArrayTexture" blockModelPalette = resources.blockModelPalette entityTexturePalette = resources.entityTexturePalette entityArrayTexture = try MetalTexturePalette.createArrayTexture( for: resources.entityTexturePalette, device: device, commandQueue: commandQueue, includeAnimations: false ) entityArrayTexture.label = "entityArrayTexture" entityModelPalette = resources.entityModelPalette // Create uniforms buffer uniformsBuffer = try MetalUtil.makeBuffer( device, length: MemoryLayout.stride, options: [] ) // Create pipeline state let library = try MetalUtil.loadDefaultLibrary(device) pipelineState = try MetalUtil.makeRenderPipelineState( device: device, label: "GUIRenderer", vertexFunction: try MetalUtil.loadFunction("guiVertex", from: library), fragmentFunction: try MetalUtil.loadFunction("guiFragment", from: library), blendingEnabled: true ) } public func render( view: MTKView, encoder: MTLRenderCommandEncoder, commandBuffer: MTLCommandBuffer, worldToClipUniformsBuffer: MTLBuffer, camera: Camera ) throws { // Construct uniforms profiler.push(.updateUniforms) let drawableSize = view.drawableSize let width = Float(drawableSize.width) let height = Float(drawableSize.height) let scalingFactor = Self.scale * Self.screenScalingFactor() // Adjust scale per screen scale factor var uniforms = createUniforms(width, height, scalingFactor) if uniforms != previousUniforms || true { uniformsBuffer.contents().copyMemory( from: &uniforms, byteCount: MemoryLayout.size ) previousUniforms = uniforms } profiler.pop() // Create meshes let effectiveDrawableSize = Vec2i( Int(width / scalingFactor), Int(height / scalingFactor) ) client.game.mutateGUIState { guiState in guiState.drawableSize = effectiveDrawableSize guiState.drawableScalingFactor = scalingFactor } let renderable = client.game.compileGUI(withFont: font, locale: locale, connection: nil) let meshes = try meshes(for: renderable) profiler.push(.encode) // Set vertex buffers encoder.setVertexBuffer(uniformsBuffer, offset: 0, index: 0) // Set pipeline encoder.setRenderPipelineState(pipelineState) let optimizedMeshes = try Self.optimizeMeshes(meshes) for (i, var mesh) in optimizedMeshes.enumerated() { if i < cache.count { let previousMesh = cache[i] if (previousMesh.vertexBuffer?.length ?? 0) >= mesh.requiredVertexBufferSize { mesh.vertexBuffer = previousMesh.vertexBuffer mesh.uniformsBuffer = previousMesh.uniformsBuffer } else { mesh.uniformsBuffer = previousMesh.uniformsBuffer } try mesh.render(into: encoder, with: device) cache[i] = mesh } else { try mesh.render(into: encoder, with: device) cache.append(mesh) } } profiler.pop() } func meshes(for renderable: GUIElement.GUIRenderable) throws -> [GUIElementMesh] { var meshes: [GUIElementMesh] switch renderable.content { case let .text(wrappedLines, hangingIndent, color): let builder = TextMeshBuilder(font: font) meshes = try wrappedLines.compactMap { (line: String) in do { return try builder.build( line, fontArrayTexture: fontArrayTexture, color: color ) } catch let error as LocalizedError { throw error.with("Text", line) } } for i in meshes.indices where i != 0 { meshes[i].position.x += hangingIndent meshes[i].position.y += Font.defaultCharacterHeight + 1 } case let .sprite(descriptor): meshes = try [ GUIElementMesh( sprite: descriptor, guiTexturePalette: guiTexturePalette, guiArrayTexture: guiArrayTexture ) ] case let .item(itemId): meshes = try self.meshes(forItemWithId: itemId) case nil, .interactable, .background: if case let .background(color) = renderable.content { meshes = [ GUIElementMesh(size: renderable.size, color: color) ] } else { meshes = [] } meshes += try renderable.children.flatMap(meshes(for:)) } meshes.translate(amount: renderable.relativePosition) return meshes } func meshes(forItemWithId itemId: Int) throws -> [GUIElementMesh] { guard let model = itemModelPalette.model(for: itemId) else { throw GUIRendererError.invalidItemId(itemId) } switch model { case let .layered(textures, _): return textures.map { texture in switch texture { case let .block(index): return GUIElementMesh(slice: index, texture: blockArrayTexture) case let .item(index): return GUIElementMesh(slice: index, texture: itemArrayTexture) } } case let .blockModel(modelId): guard let model = blockModelPalette.model(for: modelId, at: nil) else { log.warning("Missing block model of id \(modelId) (for item)") return [] } // TODO: Use this assumption to just lift all the display transforms when loading the // block model palette. // Get the block's transformation assuming that each block model part has the same // associated gui transformation (I don't see why this wouldn't always be true). var transformation: Mat4x4f if let transformsIndex = model.parts.first?.displayTransformsIndex { transformation = blockModelPalette.displayTransforms[transformsIndex].gui } else { transformation = MatrixUtil.identity } transformation *= MatrixUtil.translationMatrix([-0.5, -0.5, -0.5]) * MatrixUtil.rotationMatrix(x: .pi) * MatrixUtil.rotationMatrix(y: -.pi / 4) * MatrixUtil.rotationMatrix(x: -.pi / 6) * MatrixUtil.scalingMatrix(9.76) * MatrixUtil.translationMatrix([8, 8, 8]) var geometry = Geometry() var translucentGeometry = SortableMeshElement() BlockMeshBuilder( model: model, position: BlockPosition(x: 0, y: 0, z: 0), modelToWorld: transformation, culledFaces: [], lightLevel: LightLevel(sky: 15, block: 15), neighbourLightLevels: [:], tintColor: [1, 1, 1], blockTexturePalette: blockTexturePalette ).build(into: &geometry, translucentGeometry: &translucentGeometry) var vertices: [GUIVertex] = [] vertices.reserveCapacity(geometry.vertices.count) for vertex in geometry.vertices + translucentGeometry.vertices { vertices.append( GUIVertex( position: [vertex.x, vertex.y], uv: [vertex.u, vertex.v], tint: [vertex.r, vertex.g, vertex.b, 1], textureIndex: vertex.textureIndex ) ) } var mesh = GUIElementMesh( size: [16, 16], arrayTexture: blockArrayTexture, vertices: .flatArray(vertices) ) mesh.position = [0, 0] return [mesh] case let .entity(identifier, transforms): var entityIdentifier = identifier entityIdentifier.name = entityIdentifier.name.replacingOccurrences(of: "item/", with: "") // Dummy meshes, we don't handle rendering inventory entities which themselves // contain block item entities cause that doesn't happen (famous last words...) var blockGeometry = Geometry() var translucentBlockGeometry = SortableMeshElement() var geometry = Geometry() EntityMeshBuilder( entity: nil, entityKind: entityIdentifier, position: .zero, pitch: 0, yaw: 0, entityModelPalette: entityModelPalette, itemModelPalette: itemModelPalette, blockModelPalette: blockModelPalette, entityTexturePalette: entityTexturePalette, blockTexturePalette: blockTexturePalette, hitbox: AxisAlignedBoundingBox(position: .zero, size: Vec3d(1, 1, 1)), lightLevel: .default // Doesn't matter cause the GUI doesn't use light levels ).build( into: &geometry, blockGeometry: &blockGeometry, translucentBlockGeometry: &translucentBlockGeometry ) let transformation: Mat4x4f = MatrixUtil.translationMatrix(Vec3f(0, -0.5, 0)) * MatrixUtil.rotationMatrix(y: .pi / 2) * transforms.gui * MatrixUtil.scalingMatrix(Vec3f(-1, -1, 1)) * MatrixUtil.scalingMatrix(16) * MatrixUtil.translationMatrix([8, 8, 0]) var vertices: [GUIVertex] = [] vertices.reserveCapacity(geometry.vertices.count) for vertex in geometry.vertices { let position = (Vec4f(vertex.x, vertex.y, vertex.z, 1) * transformation).xyz vertices.append( GUIVertex( position: [position.x, position.y], uv: [vertex.u, vertex.v], tint: [vertex.r, vertex.g, vertex.b, 1], textureIndex: vertex.textureIndex ) ) } var mesh = GUIElementMesh( size: [16, 16], arrayTexture: entityArrayTexture, vertices: .flatArray(vertices) ) mesh.position = [0, 0] return [mesh] case .empty: return [] } } static func optimizeMeshes(_ meshes: [GUIElementMesh]) throws -> [GUIElementMesh] { var textureToIndex: [String: Int] = [:] var boxes: [[(position: Vec2i, size: Vec2i)]] = [] var combinedMeshes: [GUIElementMesh] = [] for mesh in meshes { var texture = "textureless" if let arrayTexture = mesh.arrayTexture { guard let label = arrayTexture.label else { throw GUIRendererError.textureMissingLabel } texture = label } // If the mesh's texture's current layer is below a layer that this mesh overlaps with, then // force a new layer to be created let box = (position: mesh.position, size: mesh.size) if let index = textureToIndex[texture] { let higherLayers = textureToIndex.values.filter { $0 > index } var done = false for layer in higherLayers { if doIntersect(mesh, combinedMeshes[layer]) { for otherBox in boxes[layer] { if doIntersect(box, otherBox) { textureToIndex[texture] = nil done = true break } } if done { break } } } } if let index = textureToIndex[texture] { combine(&combinedMeshes[index], mesh) boxes[index].append(box) } else { textureToIndex[texture] = combinedMeshes.count combinedMeshes.append(mesh) boxes.append([box]) } } return combinedMeshes } static func doIntersect(_ mesh: GUIElementMesh, _ other: GUIElementMesh) -> Bool { doIntersect( (position: mesh.position, size: mesh.size), (position: other.position, size: other.size) ) } static func doIntersect( _ box: (position: Vec2i, size: Vec2i), _ other: (position: Vec2i, size: Vec2i) ) -> Bool { let pos1 = box.position let size1 = box.size let pos2 = other.position let size2 = other.size let overlapsX = abs((pos1.x + size1.x / 2) - (pos2.x + size2.x / 2)) * 2 < (size1.x + size2.x) let overlapsY = abs((pos1.y + size1.y / 2) - (pos2.y + size2.y / 2)) * 2 < (size1.y + size2.y) return overlapsX && overlapsY } static func combine(_ mesh: inout GUIElementMesh, _ other: GUIElementMesh) { var other = other normalizeMeshPosition(&mesh) normalizeMeshPosition(&other) mesh.vertices.append(contentsOf: other.vertices) mesh.size = Vec2i( max(mesh.size.x, other.size.x), max(mesh.size.y, other.size.y) ) } /// Moves the mesh's vertices so that its position can be the origin. static func normalizeMeshPosition(_ mesh: inout GUIElementMesh) { if mesh.position == .zero { return } let position = Vec2f(mesh.position) mesh.vertices.mutateEach { vertex in vertex.position += position } mesh.position = .zero mesh.size &+= Vec2i(position) } /// Gets the scaling factor of the screen that Delta Client's currently getting rendered for. public static func screenScalingFactor() -> Float { // Higher density displays have higher scaling factors to keep content a similar real world // size across screens. #if canImport(AppKit) let screenScalingFactor = Float(NSApp.windows.first?.screen?.backingScaleFactor ?? 1) #elseif canImport(UIKit) let screenScalingFactor = Float(UIScreen.main.scale) #else #error("Unsupported platform, unknown screen scale factor") #endif return screenScalingFactor } func createUniforms(_ width: Float, _ height: Float, _ scale: Float) -> GUIUniforms { let transformation = Mat3x3f([ [2 / width, 0, -1], [0, -2 / height, 1], [0, 0, 1], ]) return GUIUniforms(screenSpaceToNormalized: transformation, scale: scale) } } ================================================ FILE: Sources/Core/Renderer/GUI/GUIRendererError.swift ================================================ import Foundation /// An error thrown by ``GUIRenderer``. enum GUIRendererError: LocalizedError { case failedToCreateVertexBuffer case failedToCreateIndexBuffer case failedToCreateUniformsBuffer case failedToCreateCharacterUniformsBuffer case emptyText case invalidCharacter(Character) case invalidItemId(Int) case missingItemTexture(Int) case failedToCreateTextMeshBuffer case textureMissingLabel var errorDescription: String? { switch self { case .failedToCreateVertexBuffer: return "Failed to create vertex buffer" case .failedToCreateIndexBuffer: return "Failed to create index buffer" case .failedToCreateUniformsBuffer: return "Failed to create uniforms buffer" case .failedToCreateCharacterUniformsBuffer: return "Failed to create character uniforms buffer" case .emptyText: return "Text was empty" case .invalidCharacter(let character): return "The selected font does not include '\(character)'" case .invalidItemId(let id): return "No item exists with id \(id)" case .missingItemTexture(let id): return "Missing texture for item with id \(id)" case .failedToCreateTextMeshBuffer: return "Failed to create text mesh buffer" case .textureMissingLabel: return "Failed to combine GUI meshes because texture was missing label" } } } ================================================ FILE: Sources/Core/Renderer/GUI/GUIUniforms.swift ================================================ import FirebladeMath /// The GUI's uniforms. public struct GUIUniforms: Equatable { /// The transformation to convert screen space coordinates to normalized device coordinates. var screenSpaceToNormalized: Mat3x3f /// The GUI scale. var scale: Float } ================================================ FILE: Sources/Core/Renderer/GUI/GUIVertex.swift ================================================ import FirebladeMath /// A vertex in the GUI. struct GUIVertex: Equatable { /// The position. var position: Vec2f /// The uv coordinate. var uv: Vec2f /// The color to tint the vertex. var tint: Vec4f /// The index of the texture in the array texture. If equal to ``UInt16/max``, no texture is /// sampled and the fragment color will be equal to the tint. var textureIndex: UInt16 } ================================================ FILE: Sources/Core/Renderer/GUI/GUIVertexStorage.swift ================================================ /// Vertices are stored in tuples as an optimisation. typealias GUIQuadVertices = (GUIVertex, GUIVertex, GUIVertex, GUIVertex) // swiftlint:disable:this large_tuple /// Specialized storage for GUI vertices that can work with two different storage formats (with /// identical memory layouts, but different types). This is useful because using tuples that group /// vertices into groups of four is faster when generating the vertices for lots of quads, but some /// code still generates vertices in the `flatArray` format. enum GUIVertexStorage { case tuples([GUIQuadVertices]) // TODO: Refactor block mesh generation to generate vertices in tuples so that this type can be // removed. Doing so should hopefully also improve block mesh generation performance. case flatArray([GUIVertex]) } extension GUIVertexStorage { static let empty = GUIVertexStorage.tuples([]) var count: Int { switch self { case .tuples(let tuples): return tuples.count * 4 case .flatArray(let array): return array.count } } @discardableResult mutating func withUnsafeMutableRawPointer(_ action: (UnsafeMutableRawPointer) -> Return) -> Return { switch self { case .tuples(var tuples): return action(&tuples) case .flatArray(var array): return action(&array) } } @discardableResult mutating func withUnsafeMutableVertexBufferPointer(_ action: (UnsafeMutableBufferPointer) -> Return) -> Return { switch self { case .tuples(var tuples): return tuples.withUnsafeMutableBufferPointer { pointer in return pointer.withMemoryRebound(to: GUIVertex.self) { buffer in return action(buffer) } } case .flatArray(var array): return array.withUnsafeMutableBufferPointer { pointer in return action(pointer) } } } mutating func mutateEach(_ action: (inout GUIVertex) -> Void) { switch self { case .tuples(var tuples): self = .tuples([]) // Avoid copy caused by CoW by making `tuples` uniquely referenced for i in 0.. [GUIQuadVertices] { switch self { case .tuples(let tuples): return tuples case .flatArray(let array): // This should never trigger becaues if the length of this array is not a multiple of 4 it // would mess up the rendering code anyway (which assumes quads made up of 4 vertices each). precondition( array.count % 4 == 0, "Flat array of GUI vertices must have a length which is a multiple of 4" ) return array.withUnsafeBufferPointer { pointer in return pointer.withMemoryRebound(to: GUIQuadVertices.self) { buffer in return Array(buffer) } } } } private func toFlatArray() -> [GUIVertex] { switch self { case .tuples(let tuples): return tuples.withUnsafeBufferPointer { pointer in return pointer.withMemoryRebound(to: GUIVertex.self) { buffer in return Array(buffer) } } case .flatArray(let array): return array } } } ================================================ FILE: Sources/Core/Renderer/GUI/TextMeshBuilder.swift ================================================ import Metal import FirebladeMath import DeltaCore struct TextMeshBuilder { var font: Font func descriptor(for character: Character) throws -> CharacterDescriptor { guard let descriptor = font.descriptor(for: character) else { guard let descriptor = font.descriptor(for: "�") else { log.warning("Failed to replace invalid character '\(character)' with placeholder '�'.") throw TextMeshBuilderError.invalidCharacter(character) } return descriptor } return descriptor } /// `indent` must be less than `maximumWidth` and `maximumWidth` must greater than the width of /// each individual character in the string. func wrap(_ text: String, maximumWidth: Int, indent: Int) -> [String] { assert(indent < maximumWidth, "indent must be smaller than maximumWidth") if text == "" { return [""] } var wrapIndex: String.Index? = nil var latestSpace: String.Index? = nil var width = 0 for i in text.indices { let character = text[i] // TODO: Figure out how to load the rest of the characters (such as stars) from the font to // fix chat rendering on Hypixel let descriptor: CharacterDescriptor do { descriptor = try self.descriptor(for: character) } catch { continue } assert( descriptor.renderedWidth < maximumWidth, "maximumWidth must be greater than every individual character in the string" ) width += descriptor.renderedWidth if i != text.startIndex { width += 1 // character spacing } // TODO: wrap on other characters such as '-' as well if character == " " { latestSpace = i } if width > maximumWidth { if let spaceIndex = latestSpace { wrapIndex = spaceIndex } else { wrapIndex = i } break } } var lines: [String] = [] if let wrapIndex = wrapIndex { lines = [String(text[text.startIndex.. GUIElementMesh? { if text.isEmpty { return nil } var currentX = 0 let currentY = 0 let spacing = 1 var quads: [GUIQuad] = [] quads.reserveCapacity(text.count) for character in text { let descriptor: CharacterDescriptor do { descriptor = try self.descriptor(for: character) } catch { continue } var quad = try Self.build( descriptor, fontArrayTexture: fontArrayTexture, color: color ) quad.translate(amount: Vec2f( Float(currentX), Float(currentY) )) quads.append(quad) currentX += Int(quad.size.x) + spacing } guard !quads.isEmpty else { throw GUIRendererError.emptyText } // Create outline if let outlineColor = outlineColor { var outlineQuads: [GUIQuad] = [] let outlineTranslations: [Vec2f] = [ [-1, 0], [1, 0], [0, -1], [0, 1] ] for translation in outlineTranslations { for var quad in quads { quad.translate(amount: translation) quad.tint = outlineColor outlineQuads.append(quad) } } // Outline is rendered before the actual text quads = outlineQuads + quads } let width = currentX - spacing let height = Font.defaultCharacterHeight return GUIElementMesh(size: [width, height], arrayTexture: fontArrayTexture, quads: quads) } /// Creates a quad instance for the given character. private static func build( _ character: CharacterDescriptor, fontArrayTexture: MTLTexture, color: Vec4f ) throws -> GUIQuad { let arrayTextureWidth = Float(fontArrayTexture.width) let arrayTextureHeight = Float(fontArrayTexture.height) let position = Vec2f( 0, Float(Font.defaultCharacterHeight - character.renderedHeight - character.verticalOffset) ) let size = Vec2f( Float(character.renderedWidth), Float(character.renderedHeight) ) let uvMin = Vec2f( Float(character.x) / arrayTextureWidth, Float(character.y) / arrayTextureHeight ) let uvSize = Vec2f( Float(character.width) / arrayTextureWidth, Float(character.height) / arrayTextureHeight ) return GUIQuad( position: position, size: size, uvMin: uvMin, uvSize: uvSize, textureIndex: UInt16(character.texture), tint: color ) } } ================================================ FILE: Sources/Core/Renderer/GUI/TextMeshBuilderError.swift ================================================ import Foundation enum TextMeshBuilderError: Error { case invalidCharacter(Character) } ================================================ FILE: Sources/Core/Renderer/Logger.swift ================================================ @_exported import DeltaLogger ================================================ FILE: Sources/Core/Renderer/Mesh/BlockMeshBuilder.swift ================================================ import DeltaCore import FirebladeMath /// Builds the mesh for a single block. struct BlockMeshBuilder { let model: BlockModel let position: BlockPosition let modelToWorld: Mat4x4f let culledFaces: DirectionSet let lightLevel: LightLevel let neighbourLightLevels: [Direction: LightLevel] // TODO: Convert to array for faster access let tintColor: Vec3f let blockTexturePalette: TexturePalette // TODO: Remove when texture type is baked into block models func build( into geometry: inout Geometry, translucentGeometry: inout SortableMeshElement ) { var translucentGeometryParts: [(size: Float, geometry: Geometry)] = [] for part in model.parts { buildPart( part, into: &geometry, translucentGeometry: &translucentGeometryParts ) } translucentGeometry = Self.mergeTranslucentGeometry( translucentGeometryParts, position: position ) } func buildPart( _ part: BlockModelPart, into geometry: inout Geometry, translucentGeometry: inout [(size: Float, geometry: Geometry)] ) { for element in part.elements { var elementTranslucentGeometry = Geometry() buildElement( element, into: &geometry, translucentGeometry: &elementTranslucentGeometry ) if !elementTranslucentGeometry.isEmpty { // Calculate a size used for sorting nested translucent elements (required for blocks such // as honey blocks and slime blocks). let minimum = (Vec4f(0, 0, 0, 1) * element.transformation * modelToWorld).xyz let maximum = (Vec4f(1, 1, 1, 1) * element.transformation * modelToWorld).xyz let size = (maximum - minimum).magnitude translucentGeometry.append((size: size, geometry: elementTranslucentGeometry)) } } } func buildElement( _ element: BlockModelElement, into geometry: inout Geometry, translucentGeometry: inout Geometry ) { let vertexToWorld = element.transformation * modelToWorld for face in element.faces { if let cullface = face.cullface, culledFaces.contains(cullface) { continue } let faceLightLevel = LightLevel.max( neighbourLightLevels[face.actualDirection] ?? .default, lightLevel ) buildFace( face, transformedBy: vertexToWorld, into: &geometry, translucentGeometry: &translucentGeometry, faceLightLevel: faceLightLevel, shouldShade: element.shade ) } } func buildFace( _ face: BlockModelFace, transformedBy vertexToWorld: Mat4x4f, into geometry: inout Geometry, translucentGeometry: inout Geometry, faceLightLevel: LightLevel, shouldShade: Bool ) { // TODO: Bake texture type into block model let textureType = blockTexturePalette.textures[face.texture].type if textureType == .translucent { buildFace( face, transformedBy: vertexToWorld, into: &translucentGeometry, faceLightLevel: faceLightLevel, shouldShade: shouldShade, textureType: textureType ) } else { buildFace( face, transformedBy: vertexToWorld, into: &geometry, faceLightLevel: faceLightLevel, shouldShade: shouldShade, textureType: textureType ) } } func buildFace( _ face: BlockModelFace, transformedBy vertexToWorld: Mat4x4f, into geometry: inout Geometry, faceLightLevel: LightLevel, shouldShade: Bool, textureType: TextureType ) { // Add face winding let offset = UInt32(geometry.vertices.count) // The index of the first vertex of this face for index in CubeGeometry.faceWinding { geometry.indices.append(index &+ offset) } let faceVertexPositions = CubeGeometry.faceVertices[face.direction.rawValue] // Calculate shade of face let faceDirection = face.actualDirection.rawValue let shade = shouldShade ? CubeGeometry.shades[faceDirection] : 1 // Calculate the tint color to apply to the face let tint: Vec3f if face.isTinted { tint = tintColor * shade } else { tint = Vec3f(repeating: shade) } let textureIndex = UInt16(face.texture) let isTransparent = textureType == .transparent // Add vertices to mesh for (uvIndex, vertexPosition) in faceVertexPositions.enumerated() { let position = (Vec4f(vertexPosition, 1) * vertexToWorld).xyz let uv = face.uvs[uvIndex] let vertex = BlockVertex( x: position.x, y: position.y, z: position.z, u: uv.x, v: uv.y, r: tint.x, g: tint.y, b: tint.z, a: 1, skyLightLevel: UInt8(faceLightLevel.sky), blockLightLevel: UInt8(faceLightLevel.block), textureIndex: textureIndex, isTransparent: isTransparent ) geometry.vertices.append(vertex) } } /// Sort the geometry assuming that smaller translucent elements are always inside of bigger /// elements in the same block (e.g. honey block, slime block). The geometry is then combined /// into a single element to add to the final mesh to reduce sorting calculations while /// rendering. private static func mergeTranslucentGeometry( _ geometries: [(size: Float, geometry: Geometry)], position: BlockPosition ) -> SortableMeshElement { var geometries = geometries // TODO: This may cause an unnecessary copy geometries.sort { first, second in return second.size > first.size } // Counts used to reserve a suitable amount of capacity var vertexCount = 0 var indexCount = 0 for (_, geometry) in geometries { vertexCount += geometry.vertices.count indexCount += geometry.indices.count } var vertices: [BlockVertex] = [] var indices: [UInt32] = [] vertices.reserveCapacity(vertexCount) indices.reserveCapacity(indexCount) for (_, geometry) in geometries { let startingIndex = UInt32(vertices.count) vertices.append(contentsOf: geometry.vertices) indices.append( contentsOf: geometry.indices.map { index in return index + startingIndex } ) } let geometry = Geometry(vertices: vertices, indices: indices) return SortableMeshElement( geometry: geometry, centerPosition: position.floatVector + Vec3f(0.5, 0.5, 0.5) ) } } ================================================ FILE: Sources/Core/Renderer/Mesh/BlockNeighbour.swift ================================================ import DeltaCore /// A representation of a neighbouring block that can be used efficiently when generating meshes. struct BlockNeighbour { /// The direction that the neighbouring block is located compared to the block. let direction: Direction /// If the neighbour is in another chunk, /// the direction of the chunk containing the neighbour. let chunkDirection: CardinalDirection? /// The index of the neighbour block in its chunk. let index: Int /// Gets the locations of all blocks neighbouring a given block. /// - Parameters: /// - index: Block index relative the block's chunk section. /// - sectionIndex: The index of the section that the block is in. /// - Returns: The block's neighbours. static func neighbours( ofBlockAt index: Int, inSection sectionIndex: Int ) -> [BlockNeighbour] { let indexInChunk = index &+ sectionIndex &* Chunk.Section.numBlocks var neighbours: [BlockNeighbour] = [] neighbours.reserveCapacity(6) let indexInLayer = indexInChunk % Chunk.blocksPerLayer if indexInLayer >= Chunk.width { neighbours.append(BlockNeighbour( direction: .north, chunkDirection: nil, index: indexInChunk &- Chunk.width )) } else { neighbours.append(BlockNeighbour( direction: .north, chunkDirection: .north, index: indexInChunk + Chunk.blocksPerLayer - Chunk.width )) } if indexInLayer < Chunk.blocksPerLayer &- Chunk.width { neighbours.append(BlockNeighbour( direction: .south, chunkDirection: nil, index: indexInChunk &+ Chunk.width )) } else { neighbours.append(BlockNeighbour( direction: .south, chunkDirection: .south, index: indexInChunk - Chunk.blocksPerLayer + Chunk.width )) } let indexInRow = indexInChunk % Chunk.width if indexInRow != Chunk.width &- 1 { neighbours.append(BlockNeighbour( direction: .east, chunkDirection: nil, index: indexInChunk &+ 1 )) } else { neighbours.append(BlockNeighbour( direction: .east, chunkDirection: .east, index: indexInChunk &- 15 )) } if indexInRow != 0 { neighbours.append(BlockNeighbour( direction: .west, chunkDirection: nil, index: indexInChunk &- 1 )) } else { neighbours.append(BlockNeighbour( direction: .west, chunkDirection: .west, index: indexInChunk &+ 15 )) } if indexInChunk < Chunk.numBlocks &- Chunk.blocksPerLayer { neighbours.append(BlockNeighbour( direction: .up, chunkDirection: nil, index: indexInChunk &+ Chunk.blocksPerLayer )) if indexInChunk >= Chunk.blocksPerLayer { neighbours.append(BlockNeighbour( direction: .down, chunkDirection: nil, index: indexInChunk &- Chunk.blocksPerLayer )) } } return neighbours } } ================================================ FILE: Sources/Core/Renderer/Mesh/ChunkSectionMesh.swift ================================================ import FirebladeMath import Foundation import MetalKit /// A renderable mesh of a chunk section. public struct ChunkSectionMesh { /// The mesh containing transparent and opaque blocks only. Doesn't need sorting. public var transparentAndOpaqueMesh: Mesh /// The mesh containing translucent blocks. Requires sorting when the player moves (clever stuff is done to minimise sorts in ``WorldRenderer``). public var translucentMesh: SortableMesh /// Whether the mesh contains fluids or not. public var containsFluids = false public var isEmpty: Bool { return transparentAndOpaqueMesh.isEmpty && translucentMesh.isEmpty } /// Create a new chunk section mesh. public init(_ uniforms: ChunkUniforms) { transparentAndOpaqueMesh = Mesh(uniforms: uniforms) translucentMesh = SortableMesh(uniforms: uniforms) } /// Clear the mesh's geometry and invalidate its buffers. Leaves GPU buffers intact for reuse. public mutating func clearGeometry() { transparentAndOpaqueMesh.clearGeometry() translucentMesh.clear() } /// Encode the render commands for transparent and opaque mesh of this chunk section. /// - Parameters: /// - renderEncoder: Encoder for rendering geometry. /// - device: The device to use. /// - commandQueue: The command queue to use for creating buffers. public mutating func renderTransparentAndOpaque( renderEncoder: MTLRenderCommandEncoder, device: MTLDevice, commandQueue: MTLCommandQueue ) throws { try transparentAndOpaqueMesh.render( into: renderEncoder, with: device, commandQueue: commandQueue) } /// Encode the render commands for translucent mesh of this chunk section. /// - Parameters: /// - position: Position the mesh is viewed from. Used for sorting. /// - sortTranslucent: Indicates whether sorting should be enabled for translucent mesh rendering. /// - renderEncoder: Encoder for rendering geometry. /// - device: The device to use. /// - commandQueue: The command queue to use for creating buffers. public mutating func renderTranslucent( viewedFrom position: Vec3f, sortTranslucent: Bool, renderEncoder: MTLRenderCommandEncoder, device: MTLDevice, commandQueue: MTLCommandQueue ) throws { try translucentMesh.render( viewedFrom: position, sort: sortTranslucent, encoder: renderEncoder, device: device, commandQueue: commandQueue ) } } ================================================ FILE: Sources/Core/Renderer/Mesh/ChunkSectionMeshBuilder.swift ================================================ import DeltaCore import FirebladeMath import Foundation import MetalKit /// Builds renderable meshes from chunk sections. /// /// Assumes that all relevant chunks have already been locked. public struct ChunkSectionMeshBuilder { // TODO: Bring docs up to date /// A lookup to quickly convert block index to block position. private static let indexToPosition = generateIndexLookup() /// A lookup tp quickly get the block indices for blocks' neighbours. private static let blockNeighboursLookup = (0.. ChunkSectionMesh? { // Create uniforms let position = Vec3f( Float(sectionPosition.sectionX) * 16, Float(sectionPosition.sectionY) * 16, Float(sectionPosition.sectionZ) * 16 ) let modelToWorldMatrix = MatrixUtil.translationMatrix(position) let uniforms = ChunkUniforms(transformation: modelToWorldMatrix) var mesh = existingMesh ?? ChunkSectionMesh(uniforms) mesh.clearGeometry() // Populate mesh with geometry let section = chunk.getSections(acquireLock: false)[sectionPosition.sectionY] let indexToNeighbours = Self.blockNeighboursLookup[sectionPosition.sectionY] let xOffset = sectionPosition.sectionX * Chunk.Section.width let yOffset = sectionPosition.sectionY * Chunk.Section.height let zOffset = sectionPosition.sectionZ * Chunk.Section.depth if section.blockCount != 0 { var transparentAndOpaqueGeometry = Geometry() for blockIndex in 0.., translucentMesh: inout SortableMesh, indexToNeighbours: [[BlockNeighbour]], containsFluids: inout Bool ) { // Get block model guard let blockModel = resources.blockModelPalette.model(for: blockId, at: position) else { log.warning("Skipping block with no block models") return } // Get block guard let block = RegistryStore.shared.blockRegistry.block(withId: blockId) else { log.warning( "Skipping block with non-existent state id \(blockId), failed to get block information" ) return } // Render fluid if present if let fluidState = block.fluidState { containsFluids = true addFluid( at: position, atBlockIndex: blockIndex, with: blockId, translucentMesh: &translucentMesh, indexToNeighbours: indexToNeighbours ) if !fluidState.isWaterlogged { return } } // Return early if block model is empty (such as air) if blockModel.cullableFaces.isEmpty && blockModel.nonCullableFaces.isEmpty { return } // Get block indices of neighbouring blocks let neighbours = indexToNeighbours[blockIndex] // Calculate face visibility let culledFaces = getCullingNeighbours(at: position, blockId: blockId, neighbours: neighbours) // Return early if there can't possibly be any visible faces if blockModel.cullableFaces == DirectionSet.all && culledFaces == DirectionSet.all && blockModel.nonCullableFaces.isEmpty { return } // Find the cullable faces which are visible var visibleFaces = blockModel.cullableFaces.subtracting(culledFaces) // Return early if there are no always visible faces and no non-culled faces if blockModel.nonCullableFaces.isEmpty && visibleFaces.isEmpty { return } // Add non cullable faces to the visible faces set (they are always rendered) if !blockModel.nonCullableFaces.isEmpty { visibleFaces = visibleFaces.union(blockModel.nonCullableFaces) // Return early if no faces are visible if visibleFaces.isEmpty { return } } // Get lighting let positionRelativeToChunkSection = position.relativeToChunkSection let lightLevel = chunk.getLighting(acquireLock: false).getLightLevel( at: positionRelativeToChunkSection, inSectionAt: sectionPosition.sectionY ) let neighbourLightLevels = getNeighbouringLightLevels( neighbours: neighbours, visibleFaces: visibleFaces ) // Get tint color guard let biome = chunk.biome(at: position.relativeToChunk, acquireLock: false) else { let biomeId = chunk.biomeId(at: position, acquireLock: false).map(String.init) ?? "unknown" log.warning("Block at \(position) has invalid biome with id \(biomeId)") return } let tintColor = resources.biomeColors.color(for: block, at: position, in: biome) // Create model to world transformation matrix let offset = block.getModelOffset(at: position) let modelToWorld = MatrixUtil.translationMatrix( positionRelativeToChunkSection.floatVector + offset ) // Add block model to mesh addBlockModel( blockModel, to: &transparentAndOpaqueGeometry, translucentMesh: &translucentMesh, position: position, modelToWorld: modelToWorld, culledFaces: culledFaces, lightLevel: lightLevel, neighbourLightLevels: neighbourLightLevels, tintColor: tintColor?.floatVector ?? [1, 1, 1] ) } private func addBlockModel( _ model: BlockModel, to transparentAndOpaqueGeometry: inout Geometry, translucentMesh: inout SortableMesh, position: BlockPosition, modelToWorld: Mat4x4f, culledFaces: DirectionSet, lightLevel: LightLevel, neighbourLightLevels: [Direction: LightLevel], tintColor: Vec3f ) { var translucentGeometry = SortableMeshElement(centerPosition: [0, 0, 0]) BlockMeshBuilder( model: model, position: position, modelToWorld: modelToWorld, culledFaces: culledFaces, lightLevel: lightLevel, neighbourLightLevels: neighbourLightLevels, tintColor: tintColor, blockTexturePalette: resources.blockTexturePalette ).build( into: &transparentAndOpaqueGeometry, translucentGeometry: &translucentGeometry ) if !translucentGeometry.isEmpty { translucentMesh.add(translucentGeometry) } } /// Adds a fluid block to the mesh. /// - Parameters: /// - position: The position of the block in world coordinates. /// - blockIndex: The index of the block in the chunk section. /// - blockId: The block's id. /// - translucentMesh: The mesh to add the fluid to. /// - indexToNeighbours: The lookup table used to find the neighbours of a block quickly. private func addFluid( at position: BlockPosition, atBlockIndex blockIndex: Int, with blockId: Int, translucentMesh: inout SortableMesh, indexToNeighbours: [[BlockNeighbour]] ) { guard let block = RegistryStore.shared.blockRegistry.block(withId: blockId), let fluid = block.fluidState?.fluid else { log.warning("Failed to get fluid block with block id \(blockId)") return } let neighbouringBlockIds = getNeighbouringBlockIds(neighbours: indexToNeighbours[blockIndex]) let cullingNeighbours = getCullingNeighbours( at: position.relativeToChunkSection, forFluid: fluid, blockId: blockId, neighbouringBlocks: neighbouringBlockIds ) var neighbouringBlocks = [Direction: Block](minimumCapacity: 6) for (direction, neighbourBlockId) in neighbouringBlockIds { let neighbourBlock = RegistryStore.shared.blockRegistry.block(withId: neighbourBlockId) neighbouringBlocks[direction] = neighbourBlock } let lightLevel = chunk .getLighting(acquireLock: false) .getLightLevel(atIndex: blockIndex, inSectionAt: sectionPosition.sectionY) let neighbouringLightLevels = getNeighbouringLightLevels( neighbours: indexToNeighbours[blockIndex], visibleFaces: [.up, .down, .north, .east, .south, .west] ) let builder = FluidMeshBuilder( position: position, blockIndex: blockIndex, block: block, fluid: fluid, chunk: chunk, cullingNeighbours: cullingNeighbours, neighbouringBlocks: neighbouringBlocks, lightLevel: lightLevel, neighbouringLightLevels: neighbouringLightLevels, blockTexturePalette: resources.blockTexturePalette, world: world ) builder.build(into: &translucentMesh) } // MARK: Helper /// Gets the chunk that contains the given neighbour block. /// - Parameter neighbourBlock: The neighbour block. /// - Returns: The chunk containing the block. func getChunk(for neighbourBlock: BlockNeighbour) -> Chunk { if let direction = neighbourBlock.chunkDirection { return neighbourChunks.neighbour(in: direction) } else { return chunk } } /// Gets the block id of each block neighbouring a block using the given neighbour indices. /// /// Blocks in neighbouring chunks are also included. Neighbours in cardinal directions will /// always be returned. If the block at `sectionIndex` is at y-level 0 or 255 the down or up neighbours /// will be omitted respectively (as there will be none). Otherwise, all neighbours are included. /// - Returns: A mapping from each possible direction to a corresponding block id. func getNeighbouringBlockIds(neighbours: [BlockNeighbour]) -> [(Direction, Int)] { // Convert a section relative index to a chunk relative index var neighbouringBlocks: [(Direction, Int)] = [] neighbouringBlocks.reserveCapacity(6) for neighbour in neighbours { let blockId = getChunk(for: neighbour).getBlockId(at: neighbour.index, acquireLock: false) neighbouringBlocks.append((neighbour.direction, blockId)) } return neighbouringBlocks } /// Gets the light levels of the blocks surrounding a block. /// - Parameters: /// - neighbours: The neighbours to get the light levels of. /// - visibleFaces: The set of faces to get the light levels of. /// - Returns: A dictionary of face direction to light level for all faces in `visibleFaces`. func getNeighbouringLightLevels( neighbours: [BlockNeighbour], visibleFaces: DirectionSet ) -> [Direction: LightLevel] { var lightLevels = [Direction: LightLevel](minimumCapacity: 6) for neighbour in neighbours { if visibleFaces.contains(neighbour.direction) { let lightLevel = getChunk(for: neighbour) .getLighting(acquireLock: false) .getLightLevel(at: neighbour.index) lightLevels[neighbour.direction] = lightLevel } } return lightLevels } /// Gets an array of the direction of all blocks neighbouring the block at `position` that have /// full faces facing the block at `position`. /// - Parameters: /// - position: The position of the block relative to the section. /// - blockId: The id of the block at the given position. /// - neighbourIndices: The neighbour indices lookup table to use. /// - Returns: The set of directions of neighbours that can possibly cull a face. func getCullingNeighbours( at position: BlockPosition, forFluid fluid: Fluid? = nil, blockId: Int, neighbours: [BlockNeighbour] ) -> DirectionSet { let neighbouringBlocks = getNeighbouringBlockIds(neighbours: neighbours) return getCullingNeighbours( at: position, forFluid: fluid, blockId: blockId, neighbouringBlocks: neighbouringBlocks ) } /// Gets an array of the direction of all blocks neighbouring the block at `position` that have /// full faces facing the block at `position`. /// - Parameters: /// - position: The position of the block relative to `sectionPosition`. /// - blockId: The id of the block at the given position. /// - neighbouringBlocks: The block ids of neighbouring blocks. /// - Returns: The set of directions of neighbours that can possibly cull a face. func getCullingNeighbours( at position: BlockPosition, forFluid fluid: Fluid? = nil, blockId: Int, neighbouringBlocks: [(Direction, Int)] ) -> DirectionSet { // TODO: Skip directions that the block can't be culled from if possible var cullingNeighbours = DirectionSet() let blockCullsSameKind = RegistryStore.shared.blockRegistry.selfCullingBlocks.contains(blockId) for (direction, neighbourBlockId) in neighbouringBlocks where neighbourBlockId != 0 { // We assume that block model variants always have the same culling faces as eachother, so // no position is passed to getModel. guard let blockModel = resources.blockModelPalette.model(for: neighbourBlockId, at: nil) else { log.debug("Skipping neighbour with no block models.") continue } let culledByOwnKind = blockCullsSameKind && blockId == neighbourBlockId if blockModel.cullingFaces.contains(direction.opposite) || culledByOwnKind { cullingNeighbours.insert(direction) } else if let fluid = fluid { guard let neighbourBlock = RegistryStore.shared.blockRegistry.block(withId: neighbourBlockId) else { continue } if neighbourBlock.fluidId == fluid.id { cullingNeighbours.insert(direction) } } } return cullingNeighbours } // MARK: Lookup table generation /// Generates a lookup table to quickly convert from section block index to block position. private static func generateIndexLookup() -> [BlockPosition] { var lookup: [BlockPosition] = [] lookup.reserveCapacity(Chunk.Section.numBlocks) for y in 0.. [[BlockNeighbour]] { var neighbours: [[BlockNeighbour]] = [] for i in 0.. [Vec3f] { let vertexIndices = faceVertexIndices[face.rawValue] let vertices = vertexIndices.map { index in return cubeVertices[index] } return vertices } } ================================================ FILE: Sources/Core/Renderer/Mesh/EntityMeshBuilder.swift ================================================ import CoreFoundation import DeltaCore import FirebladeECS import Foundation public struct EntityMeshBuilder { /// Associates entity kinds with hardcoded entity texture identifiers. Used to manually /// instruct Delta Client where to find certain textures that aren't in the standard /// locations. public static let hardcodedTextureIdentifiers: [Identifier: Identifier] = [ Identifier(name: "player"): Identifier(name: "entity/steve"), Identifier(name: "dragon"): Identifier(name: "entity/enderdragon/dragon"), Identifier(name: "chest"): Identifier(name: "entity/chest/normal"), ] /// Used to get extra metadata for rendering item entities and the Ender Dragon. Not required if just /// rendering an entity for things such as block entity items. public let entity: Entity? public let entityKind: Identifier public let position: Vec3f public let pitch: Float public let yaw: Float public let entityModelPalette: EntityModelPalette public let itemModelPalette: ItemModelPalette public let blockModelPalette: BlockModelPalette public let entityTexturePalette: TexturePalette public let blockTexturePalette: TexturePalette public let hitbox: AxisAlignedBoundingBox public let lightLevel: LightLevel static let colors: [Vec3f] = [ [1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0], [1, 0, 1], [0, 1, 1], [0, 0, 0], [1, 1, 1], ] // TODO: Propagate all warnings as errors and then handle them and emit them as warnings in EntityRenderer instead /// `blockGeometry` and `translucentBlockGeometry` are used to render block entities and block item entities. func build( into geometry: inout Geometry, blockGeometry: inout Geometry, translucentBlockGeometry: inout SortableMeshElement ) { if let model = entityModelPalette.models[entityKind] { buildModel(model, into: &geometry) } else if let itemMetadata = entity?.get(component: EntityMetadata.self)?.itemMetadata { guard let itemStack = itemMetadata.slot.stack else { // If there's no stack, then we're still waiting for the server to send // the item's metadata so don't render anything yet (to avoid seeing the // 'missing entity' hitbox for a split second whenever a new item entity // spawns in). return } guard let itemModel = itemModelPalette.model(for: itemStack.itemId) else { buildAABB(hitbox, into: &geometry) return } // TODO: Figure out why these bobbing constants and hardcoded translations are so weird // (they're even still slightly off vanilla, there must be a different order of transformations // that makes these numbers nice or something). let time = CFAbsoluteTimeGetCurrent() * TickScheduler.defaultTicksPerSecond let phaseOffset = Double(itemMetadata.bobbingPhaseOffset) let verticalOffset = Float(Foundation.sin(time / 10 + phaseOffset)) / 8 * 3 let spinAngle = -Float((time / 20 + phaseOffset).remainder(dividingBy: 2 * .pi)) let bob = MatrixUtil.translationMatrix(Vec3f(0, verticalOffset, 0)) * MatrixUtil.rotationMatrix(y: spinAngle) switch itemModel { case let .entity(identifier, transforms): // Remove identifier prefix (entity model palette doesn't have any `item/` or `entity/` prefixes). var entityIdentifier = identifier entityIdentifier.name = entityIdentifier.name.replacingOccurrences(of: "item/", with: "") guard let entityModel = entityModelPalette.models[entityIdentifier] else { log.warning("Missing entity model for entity with '\(entityIdentifier)' (as item)") return } let transformation = bob * transforms.ground * MatrixUtil.translationMatrix(Vec3f(0, 11.0 / 64, 0)) buildModel( entityModel, textureIdentifier: entityIdentifier, transformation: transformation, into: &geometry ) case let .blockModel(id): guard let blockModel = blockModelPalette.model(for: id, at: nil) else { log.warning( "Missing block model for item entity (block id: \(id), item id: \(itemStack.itemId))" ) return } var neighbourLightLevels: [Direction: LightLevel] = [:] for direction in Direction.allDirections { neighbourLightLevels[direction] = lightLevel } // TODO: Try using the transformation code from the GUIRenderer and see if that cleans things up a bit. let transformation = MatrixUtil.translationMatrix(Vec3f(-0.5, 0, -0.5)) * bob * MatrixUtil.scalingMatrix(0.25) * MatrixUtil.translationMatrix(Vec3f(0, 7.0 / 32.0, 0)) * MatrixUtil.rotationMatrix(y: yaw + .pi) * MatrixUtil.translationMatrix(position) let builder = BlockMeshBuilder( model: blockModel, position: .zero, modelToWorld: transformation, culledFaces: [], lightLevel: lightLevel, neighbourLightLevels: neighbourLightLevels, tintColor: Vec3f(1, 1, 1), blockTexturePalette: blockTexturePalette ) builder.build(into: &blockGeometry, translucentGeometry: &translucentBlockGeometry) case .layered: buildAABB(hitbox, into: &geometry) case .empty: break } } else { buildAABB(hitbox, into: &geometry) } if let dragonParts = entity?.get(component: EnderDragonParts.self) { for part in dragonParts.parts { let aabb = part.aabb(withParentPosition: Vec3d(position)) buildAABB(aabb, into: &geometry) } } } func buildAABB(_ aabb: AxisAlignedBoundingBox, into geometry: inout Geometry) { let transformation = MatrixUtil.scalingMatrix(Vec3f(aabb.size)) * MatrixUtil.translationMatrix(Vec3f(aabb.position)) for direction in Direction.allDirections { let offset = UInt32(geometry.vertices.count) for index in CubeGeometry.faceWinding { geometry.indices.append(index &+ offset) } let faceVertexPositions = CubeGeometry.faceVertices[direction.rawValue] for vertexPosition in faceVertexPositions { let position = (Vec4f(vertexPosition, 1) * transformation).xyz let color = EntityRenderer.hitBoxColor.floatVector let vertex = EntityVertex( x: position.x, y: position.y, z: position.z, r: color.x, g: color.y, b: color.z, u: 0, v: 0, skyLightLevel: UInt8(lightLevel.sky), blockLightLevel: UInt8(lightLevel.block), textureIndex: nil ) geometry.vertices.append(vertex) } } } /// The unit of `transformation` is blocks. func buildModel( _ model: JSONEntityModel, textureIdentifier: Identifier? = nil, transformation: Mat4x4f = MatrixUtil.identity, into geometry: inout Geometry ) { let baseTextureIdentifier = textureIdentifier ?? entityKind let texture: Int? if let identifier = Self.hardcodedTextureIdentifiers[baseTextureIdentifier] { texture = entityTexturePalette.textureIndex(for: identifier) } else { // Entity textures can be in all sorts of structures so we just have a few // educated guesses for now. let textureIdentifier = Identifier( namespace: baseTextureIdentifier.namespace, name: "entity/\(baseTextureIdentifier.name)" ) let nestedTextureIdentifier = Identifier( namespace: baseTextureIdentifier.namespace, name: "entity/\(baseTextureIdentifier.name)/\(baseTextureIdentifier.name)" ) texture = entityTexturePalette.textureIndex(for: textureIdentifier) ?? entityTexturePalette.textureIndex(for: nestedTextureIdentifier) } for (index, submodel) in model.models.enumerated() { buildSubmodel( submodel, index: index, textureIndex: texture, transformation: transformation, into: &geometry ) } } /// The unit of `transformation` is blocks. func buildSubmodel( _ submodel: JSONEntityModel.Submodel, index: Int, textureIndex: Int?, transformation: Mat4x4f = MatrixUtil.identity, into geometry: inout Geometry ) { var transformation = transformation if let rotation = submodel.rotate { let translation = submodel.translate ?? .zero transformation = MatrixUtil.rotationMatrix(-MathUtil.radians(from: rotation)) * MatrixUtil.translationMatrix(translation / 16) * transformation } for box in submodel.boxes ?? [] { buildBox( box, color: index < Self.colors.count ? Self.colors[index] : [0.5, 0.5, 0.5], transformation: transformation, textureIndex: textureIndex, // We already invert 'y' and 'z' invertedAxes: [ submodel.invertAxis?.contains("x") == true, submodel.invertAxis?.contains("y") != true, submodel.invertAxis?.contains("z") != true, ], into: &geometry ) } for (nestedIndex, nestedSubmodel) in (submodel.submodels ?? []).enumerated() { buildSubmodel( nestedSubmodel, index: nestedIndex, textureIndex: textureIndex, transformation: transformation, into: &geometry ) } } /// The unit of `transformation` is 16 units per block. func buildBox( _ box: JSONEntityModel.Box, color: Vec3f, transformation: Mat4x4f, textureIndex: Int?, invertedAxes: [Bool], into geometry: inout Geometry ) { var boxPosition = Vec3f( box.coordinates[0], box.coordinates[1], box.coordinates[2] ) var boxSize = Vec3f( box.coordinates[3], box.coordinates[4], box.coordinates[5] ) let textureOffset = Vec2f(box.textureOffset ?? .zero) let baseBoxSize = boxSize if let additionalSize = box.sizeAdd { let growth = Vec3f(repeating: additionalSize) boxPosition -= growth boxSize += 2 * growth } for direction in Direction.allDirections { // The index of the first vertex of this face let offset = UInt32(geometry.vertices.count) for index in CubeGeometry.faceWinding { geometry.indices.append(index &+ offset) } var uvOrigin: Vec2f var uvSize: Vec2f let verticalAxis: Axis let horizontalAxis: Axis switch direction { case .east: uvOrigin = textureOffset + Vec2f(0, baseBoxSize.z) uvSize = Vec2f(baseBoxSize.z, baseBoxSize.y) verticalAxis = .y horizontalAxis = .z case .north: uvOrigin = textureOffset + Vec2f(baseBoxSize.z, baseBoxSize.z) uvSize = Vec2f(baseBoxSize.x, baseBoxSize.y) verticalAxis = .y horizontalAxis = .x case .west: uvOrigin = textureOffset + Vec2f(baseBoxSize.z + baseBoxSize.x, baseBoxSize.z) uvSize = Vec2f(baseBoxSize.z, baseBoxSize.y) verticalAxis = .y horizontalAxis = .z case .south: uvOrigin = textureOffset + Vec2f(baseBoxSize.z * 2 + baseBoxSize.x, baseBoxSize.z) uvSize = Vec2f(baseBoxSize.x, baseBoxSize.y) verticalAxis = .y horizontalAxis = .x case .up: uvOrigin = textureOffset + Vec2f(baseBoxSize.z, 0) uvSize = Vec2f(baseBoxSize.x, baseBoxSize.z) verticalAxis = .z horizontalAxis = .x case .down: uvOrigin = textureOffset + Vec2f(baseBoxSize.z + baseBoxSize.x, 0) uvSize = Vec2f(baseBoxSize.x, baseBoxSize.z) verticalAxis = .z horizontalAxis = .x } if invertedAxes[horizontalAxis.index] { uvOrigin.x += uvSize.x uvSize.x *= -1 } if invertedAxes[verticalAxis.index] { uvOrigin.y += uvSize.y uvSize.y *= -1 } let textureSize = Vec2f( Float(entityTexturePalette.width), Float(entityTexturePalette.height) ) let uvs = [ uvOrigin, uvOrigin + Vec2f(0, uvSize.y), uvOrigin + Vec2f(uvSize.x, uvSize.y), uvOrigin + Vec2f(uvSize.x, 0), ].map { pixelUV in pixelUV / textureSize } let faceVertexPositions = CubeGeometry.faceVertices[direction.rawValue] for (uv, vertexPosition) in zip(uvs, faceVertexPositions) { var position = vertexPosition * boxSize + boxPosition position /= 16 position = (Vec4f(position, 1) * transformation * MatrixUtil.rotationMatrix(y: yaw + .pi)) .xyz position += self.position let vertex = EntityVertex( x: position.x, y: position.y, z: position.z, r: textureIndex == nil ? color.x : 1, g: textureIndex == nil ? color.y : 1, b: textureIndex == nil ? color.z : 1, u: uv.x, v: uv.y, skyLightLevel: UInt8(lightLevel.sky), blockLightLevel: UInt8(lightLevel.block), textureIndex: textureIndex.map(UInt16.init) ) geometry.vertices.append(vertex) } } } } ================================================ FILE: Sources/Core/Renderer/Mesh/FluidMeshBuilder.swift ================================================ import DeltaCore import FirebladeMath /// Builds the fluid mesh for a block. struct FluidMeshBuilder { // TODO: Make fluid meshes look more like they do in vanilla /// The UVs for the top of a fluid when flowing. static let flowingUVs: [Vec2f] = [ [0.75, 0.25], [0.25, 0.25], [0.25, 0.75], [0.75, 0.75], ] /// The UVs for the top of a fluid when still. static let stillUVs: [Vec2f] = [ [1, 0], [0, 0], [0, 1], [1, 1], ] /// The component directions of the direction to each corner. The index of each is used as the /// corner's index in arrays. private static let cornerToDirections: [[Direction]] = [ [.north, .east], [.north, .west], [.south, .west], [.south, .east], ] /// Maps directions to the indices of the corners connected to that edge. private static let directionToCorners: [Direction: [Int]] = [ .north: [0, 1], .west: [1, 2], .south: [2, 3], .east: [3, 0], ] let position: BlockPosition // Take index as well as position to avoid duplicate calculation let blockIndex: Int let block: Block let fluid: Fluid let chunk: Chunk let cullingNeighbours: DirectionSet let neighbouringBlocks: [Direction: Block] let lightLevel: LightLevel let neighbouringLightLevels: [Direction: LightLevel] let blockTexturePalette: TexturePalette let world: World func build(into translucentMesh: inout SortableMesh) { // If block is surrounded by the same fluid on all sides, don't render anything. if neighbouringBlocks.count == 6 { let neighbourFluids = Set(neighbouringBlocks.values.map { $0.fluidId }) if neighbourFluids.count == 1 && neighbourFluids.contains(fluid.id) { return } } var tint = Vec3f(1, 1, 1) if block.fluidState?.fluid.identifier.name == "water" { guard let tintColor = chunk.biome( at: position.relativeToChunk, acquireLock: false )?.waterColor.floatVector else { // TODO: use a fallback color instead log.warning("Failed to get water tint") return } tint = tintColor } let heights = calculateHeights() let isFlowing = Set(heights).count > 1 // If the corners aren't all the same height, it's flowing let topCornerPositions = calculatePositions(heights) // Get textures guard let flowingTextureIndex = blockTexturePalette.textureIndex(for: fluid.flowingTexture), let stillTextureIndex = blockTexturePalette.textureIndex(for: fluid.stillTexture) else { log.warning("Failed to get textures for fluid") return } let flowingTexture = UInt16(flowingTextureIndex) let stillTexture = UInt16(stillTextureIndex) build( into: &translucentMesh, topCornerPositions: topCornerPositions, heights: heights, flowingTexture: flowingTexture, stillTexture: stillTexture, isFlowing: isFlowing, tint: tint ) } func build( into translucentMesh: inout SortableMesh, topCornerPositions: [Vec3f], heights: [Float], flowingTexture: UInt16, stillTexture: UInt16, isFlowing: Bool, tint: Vec3f ) { let basePosition = position.relativeToChunkSection.floatVector + Vec3f(0.5, 0, 0.5) // Make cullingNeighbours mutable and prevent top face culling when covered by non-liquids var cullingNeighbours = cullingNeighbours if neighbouringBlocks[.up]?.fluidId != fluid.id { cullingNeighbours.remove(.up) } // Iterate through all visible faces for direction in Direction.allDirections where !cullingNeighbours.contains(direction) { let shade = CubeGeometry.shades[direction.rawValue] let tint = tint * shade var geometry = Geometry() switch direction { case .up: buildTopFace( into: &geometry, isFlowing: isFlowing, heights: heights, topCornerPositions: topCornerPositions, tint: tint, stillTexture: stillTexture, flowingTexture: flowingTexture ) case .north, .east, .south, .west: buildSideFace( direction, into: &geometry, heights: heights, topCornerPositions: topCornerPositions, basePosition: basePosition, flowingTexture: flowingTexture, tint: tint ) case .down: buildBottomFace( into: &geometry, basePosition: basePosition, topCornerPositions: topCornerPositions, stillTexture: stillTexture, tint: tint ) } geometry.indices.append(contentsOf: CubeGeometry.faceWinding) translucentMesh.add( SortableMeshElement( geometry: geometry, centerPosition: position.floatVector + Vec3f(0.5, 0.5, 0.5) ) ) } } private func buildTopFace( into geometry: inout Geometry, isFlowing: Bool, heights: [Float], topCornerPositions: [Vec3f], tint: Vec3f, stillTexture: UInt16, flowingTexture: UInt16 ) { var positions: [Vec3f] let uvs: [Vec2f] let texture: UInt16 if isFlowing { texture = flowingTexture let (lowestCornersCount, lowestCornerIndex) = countLowestCorners(heights) uvs = generateFlowingTopFaceUVs(lowestCornersCount: lowestCornersCount) // Rotate corner positions so that the lowest and the opposite from the lowest are on both triangles positions = [] for i in 0..<4 { positions.append(topCornerPositions[(i + lowestCornerIndex) & 0x3]) // & 0x3 performs mod 4 } } else { positions = topCornerPositions uvs = Self.stillUVs texture = stillTexture } addVertices(to: &geometry, at: positions.reversed(), uvs: uvs, texture: texture, tint: tint) } private func buildSideFace( _ direction: Direction, into geometry: inout Geometry, heights: [Float], topCornerPositions: [Vec3f], basePosition: Vec3f, flowingTexture: UInt16, tint: Vec3f ) { // The lookup will never be nil because directionToCorners contains values for north, east, south and west // swiftlint:disable force_unwrapping let cornerIndices = Self.directionToCorners[direction]! // swiftlint:enable force_unwrapping var uvs = Self.flowingUVs uvs[0][1] += (1 - heights[cornerIndices[0]]) / 2 uvs[1][1] += (1 - heights[cornerIndices[1]]) / 2 var positions = cornerIndices.map { topCornerPositions[$0] } let offsets = cornerIndices.map { Self.cornerToDirections[$0] }.reversed() for offset in offsets { positions.append(basePosition + offset[0].vector / 2 + offset[1].vector / 2) } addVertices(to: &geometry, at: positions, uvs: uvs, texture: flowingTexture, tint: tint) } private func buildBottomFace( into geometry: inout Geometry, basePosition: Vec3f, topCornerPositions: [Vec3f], stillTexture: UInt16, tint: Vec3f ) { let uvs = [Vec2f](Self.stillUVs.reversed()) var positions: [Vec3f] = [] positions.reserveCapacity(4) for i in 0..<4 { var position = topCornerPositions[(i - 1) & 0x3] // & 0x3 is mod 4 position.y = basePosition.y positions.append(position) } addVertices(to: &geometry, at: positions, uvs: uvs, texture: stillTexture, tint: tint) } /// Convert corner heights to corner positions relative to the current chunk section. private func calculatePositions(_ heights: [Float]) -> [Vec3f] { let basePosition = position.relativeToChunkSection.floatVector + Vec3f(0.5, 0, 0.5) var positions: [Vec3f] = [] for (index, height) in heights.enumerated() { let directions = Self.cornerToDirections[index] var position = basePosition for direction in directions { position += direction.vector / 2 } position.y += height positions.append(position) } return positions } /// Calculate the height of each corner of a fluid. private func calculateHeights() -> [Float] { // If under a fluid block of the same type, all corners are 1 if neighbouringBlocks[.up]?.fluidId == block.fluidId { return [1, 1, 1, 1] } // Begin with all corners as the height of the current fluid let height = getFluidLevel(block) var heights = [height, height, height, height] // Loop through corners for (index, directions) in Self.cornerToDirections.enumerated() { if heights[index] == 1 { continue } // Get positions of blocks surrounding the current corner let zOffset = directions[0].intVector let xOffset = directions[1].intVector let positions: [BlockPosition] = [ position + xOffset, position + zOffset, position + xOffset + zOffset, ] // Get the highest fluid level around the corner var maxHeight = height for neighbourPosition in positions { // If any of the surrounding blocks have the fluid above them, this corner should have a height of 1 let upperNeighbourBlock = world.getBlock( at: neighbourPosition + Direction.up.intVector, acquireLock: false ) if block.fluidId == upperNeighbourBlock.fluidId { maxHeight = 1 break } let neighbourBlock = world.getBlock(at: neighbourPosition, acquireLock: false) if block.fluidId == neighbourBlock.fluidId { let neighbourHeight = getFluidLevel(neighbourBlock) if neighbourHeight > maxHeight { maxHeight = neighbourHeight } } } heights[index] = maxHeight } return heights } /// Returns the height of a fluid from 0 to 1. /// - Parameter block: Block containing the fluid. /// - Returns: A height. private func getFluidLevel(_ block: Block) -> Float { if let height = block.fluidState?.height { return 0.9 - Float(7 - height) / 8 } else { return 0.8125 } } private func countLowestCorners(_ heights: [Float]) -> (count: Int, index: Int) { var lowestCornerHeight: Float = 1 var lowestCornerIndex = 0 var lowestCornersCount = 0 // The number of corners at the lowest height for (index, height) in heights.enumerated() { if height < lowestCornerHeight { lowestCornersCount = 1 lowestCornerHeight = height lowestCornerIndex = index } else if height == lowestCornerHeight { lowestCornersCount += 1 } } let previousCornerIndex = (lowestCornerIndex - 1) & 0x3 if lowestCornersCount == 2 { // If there are two lowest corners next to eachother, take the first (when going anticlockwise) if heights[previousCornerIndex] == lowestCornerHeight { lowestCornerIndex = previousCornerIndex } } else if lowestCornersCount == 3 { // If there are three lowest corners, take the last (when going anticlockwise) let nextCornerIndex = (lowestCornerIndex + 1) & 0x3 if heights[previousCornerIndex] == lowestCornerHeight && heights[nextCornerIndex] == lowestCornerHeight { lowestCornerIndex = nextCornerIndex } else if heights[nextCornerIndex] == lowestCornerHeight { lowestCornerIndex = (lowestCornerIndex + 2) & 0x3 } } return (count: lowestCornersCount, index: lowestCornerIndex) } private func generateFlowingTopFaceUVs(lowestCornersCount: Int) -> [Vec2f] { var uvs = Self.flowingUVs // Rotate UVs 45 degrees if flowing diagonally if lowestCornersCount == 1 || lowestCornersCount == 3 { let uvRotation = MatrixUtil.rotationMatrix2d( lowestCornersCount == 1 ? Float.pi / 4 : 3 * Float.pi / 4) let center = Vec2f(repeating: 0.5) for (index, uv) in uvs.enumerated() { uvs[index] = (uv - center) * uvRotation + center } } return uvs } private func addVertices( to geometry: inout Geometry, at positions: Positions, uvs: [Vec2f], texture: UInt16, tint: Vec3f ) where Positions.Element == Vec3f { var index = 0 for position in positions { let vertex = BlockVertex( x: position.x, y: position.y, z: position.z, u: uvs[index].x, v: uvs[index].y, r: tint.x, g: tint.y, b: tint.z, a: 1, skyLightLevel: UInt8(lightLevel.sky), blockLightLevel: UInt8(lightLevel.block), textureIndex: texture, isTransparent: false ) geometry.vertices.append(vertex) index += 1 } } } ================================================ FILE: Sources/Core/Renderer/Mesh/Geometry.swift ================================================ import Foundation /// The simplest representation of renderable geometry data. Just vertices and vertex winding. public struct Geometry { /// Vertex data. var vertices: [Vertex] = [] /// Vertex windings. var indices: [UInt32] = [] public var isEmpty: Bool { return vertices.isEmpty || indices.isEmpty } public init(vertices: [Vertex] = [], indices: [UInt32] = []) { self.vertices = vertices self.indices = indices } } ================================================ FILE: Sources/Core/Renderer/Mesh/Mesh.swift ================================================ import Foundation import Metal public enum MeshError: LocalizedError { case failedToCreateBuffer public var errorDescription: String? { switch self { case .failedToCreateBuffer: return "Failed to create buffer." } } } /// Holds and renders geometry data. public struct Mesh { /// The vertices in the mesh. public var vertices: [Vertex] /// The vertex windings. public var indices: [UInt32] /// The mesh's uniforms. public var uniforms: Uniforms /// A GPU buffer containing the vertices. public var vertexBuffer: MTLBuffer? /// A GPU buffer containing the vertex windings. public var indexBuffer: MTLBuffer? /// A GPU buffer containing the model to world transformation matrix. public var uniformsBuffer: MTLBuffer? /// If `false`, ``vertexBuffer`` will be recreated next time ``render(into:with:commandQueue:)`` is called. public var vertexBufferIsValid = false /// If `false`, ``indexBuffer`` will be recreated next time ``render(into:with:commandQueue:)`` is called. public var indexBufferIsValid = false /// If `false`, ``uniformsBuffer`` will be recreated next time ``render(into:with:commandQueue:)`` is called. public var uniformsBufferIsValid = false /// `true` if the mesh contains no geometry. public var isEmpty: Bool { return vertices.isEmpty || indices.isEmpty } /// Create a new populated mesh. public init(vertices: [Vertex], indices: [UInt32], uniforms: Uniforms) { self.vertices = vertices self.indices = indices self.uniforms = uniforms } /// Create a new mesh with geometry. public init(_ geometry: Geometry? = nil, uniforms: Uniforms) { self.init( vertices: geometry?.vertices ?? [], indices: geometry?.indices ?? [], uniforms: uniforms ) } /// Encodes the draw commands to render this mesh into a render encoder. Creates buffers if necessary. /// - Parameters: /// - encoder: Render encode to encode commands into. /// - device: Device to use. /// - commandQueue: Command queue used to create buffers if not created already. public mutating func render( into encoder: MTLRenderCommandEncoder, with device: MTLDevice, commandQueue: MTLCommandQueue ) throws { if isEmpty { return } // Get buffers. If the buffer is valid and not nil, it is used. If the buffer is invalid and not nil, // it is repopulated with the new data (if big enough, otherwise a new buffer is created). If the // buffer is nil, a new one is created. let vertexBuffer = try ((vertexBufferIsValid ? vertexBuffer : nil) ?? MetalUtil.createPrivateBuffer( labelled: "vertexBuffer", containing: vertices, reusing: vertexBuffer, device: device, commandQueue: commandQueue )) let indexBuffer = try ((indexBufferIsValid ? indexBuffer : nil) ?? MetalUtil.createPrivateBuffer( labelled: "indexBuffer", containing: indices, reusing: indexBuffer, device: device, commandQueue: commandQueue )) let uniformsBuffer = try ((uniformsBufferIsValid ? uniformsBuffer : nil) ?? MetalUtil.createPrivateBuffer( labelled: "uniformsBuffer", containing: [uniforms], reusing: uniformsBuffer, device: device, commandQueue: commandQueue )) // Update cached buffers. Unnecessary assignments won't affect performance because `MTLBuffer`s // are just descriptors, not the actual data self.vertexBuffer = vertexBuffer self.indexBuffer = indexBuffer self.uniformsBuffer = uniformsBuffer // Buffers are now all valid vertexBufferIsValid = true indexBufferIsValid = true uniformsBufferIsValid = true // Encode draw call encoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0) encoder.setVertexBuffer(uniformsBuffer, offset: 0, index: 2) encoder.drawIndexedPrimitives( type: .triangle, indexCount: indices.count, indexType: .uint32, indexBuffer: indexBuffer, indexBufferOffset: 0 ) } /// Force buffers to be recreated on next call to ``render(into:for:commandQueue:)``. /// /// The underlying private buffer may be reused, but it will be repopulated with the new data. /// /// - Parameters: /// - keepVertexBuffer: If `true`, the vertex buffer is not invalidated. /// - keepIndexBuffer: If `true`, the index buffer is not invalidated. /// - keepUniformsBuffer: If `true`, the uniforms buffer is not invalidated. public mutating func invalidateBuffers( keepVertexBuffer: Bool = false, keepIndexBuffer: Bool = false, keepUniformsBuffer: Bool = false ) { vertexBufferIsValid = keepVertexBuffer indexBufferIsValid = keepIndexBuffer uniformsBufferIsValid = keepUniformsBuffer } /// Clears the mesh's geometry and invalidates its buffers. public mutating func clearGeometry() { vertices = [] indices = [] invalidateBuffers(keepUniformsBuffer: true) } } ================================================ FILE: Sources/Core/Renderer/Mesh/SortableMesh.swift ================================================ import FirebladeMath import Foundation import MetalKit /// A mesh that can be sorted after the initial preparation. /// /// Use for translucent meshes. Only really designed for grid-aligned objects. public struct SortableMesh { /// Distinct mesh elements that should be rendered in order of distance. public var elements: [SortableMeshElement] = [] /// The mesh may be empty even if this is false if all of the elements contain no geometry. public var isEmpty: Bool { return elements.isEmpty } /// The mesh that is updated each time this mesh is sorted. public var underlyingMesh: Mesh /// Creates a new sortable mesh. /// - Parameters: /// - elements: Distinct mesh elements that should be rendered in order of distance. /// - uniforms: The mesh's uniforms. public init(_ elements: [SortableMeshElement] = [], uniforms: ChunkUniforms) { self.elements = elements underlyingMesh = Mesh(uniforms: uniforms) } /// Removes all elements from the mesh. public mutating func clear() { elements = [] underlyingMesh.clearGeometry() underlyingMesh.invalidateBuffers(keepUniformsBuffer: true) } /// Add an element to the mesh. Updates the element's id. public mutating func add(_ element: SortableMeshElement) { var element = element element.id = elements.count elements.append(element) } /// Encode the render commands for this mesh. /// - Parameters: /// - position: The position to sort from. /// - sort: If `false`, the mesh will not be sorted and the previous one will be rendered (unless no previous mesh has been rendered). /// - encoder: The encoder to encode the render commands into. /// - device: The device to use. /// - commandQueue: The command queue to use when creating buffers. public mutating func render( viewedFrom position: Vec3f, sort: Bool, encoder: MTLRenderCommandEncoder, device: MTLDevice, commandQueue: MTLCommandQueue ) throws { if underlyingMesh.isEmpty && elements.isEmpty { return } if sort || underlyingMesh.isEmpty { // TODO: reuse vertices from mesh and just recreate winding // Sort elements by distance in descending order. let newElements = elements.sorted(by: { let squaredDistance1 = distance_squared(position, $0.centerPosition) let squaredDistance2 = distance_squared(position, $1.centerPosition) return squaredDistance1 > squaredDistance2 }) if underlyingMesh.isEmpty || newElements != elements { elements = newElements underlyingMesh.clearGeometry() for element in elements { let windingOffset = UInt32(underlyingMesh.vertices.count) underlyingMesh.vertices.append(contentsOf: element.vertices) for index in element.indices { underlyingMesh.indices.append(index + windingOffset) } } } } // Could be reached if all elements contain no geometry if underlyingMesh.isEmpty { return } try underlyingMesh.render(into: encoder, with: device, commandQueue: commandQueue) } } ================================================ FILE: Sources/Core/Renderer/Mesh/SortableMeshElement.swift ================================================ import FirebladeMath import Foundation /// An element of a ``SortableMesh``. public struct SortableMeshElement { /// The element's unique id within its mesh. public var id: Int /// The vertex data. public var vertices: [BlockVertex] = [] /// The vertex windings. public var indices: [UInt32] = [] /// The position of the center of the mesh. public var centerPosition: Vec3f /// Whether the element contains any geometry or not. public var isEmpty: Bool { return indices.isEmpty } /// Create a new element. public init( id: Int = 0, vertices: [BlockVertex] = [], indices: [UInt32] = [], centerPosition: Vec3f = [0, 0, 0] ) { self.id = id self.vertices = vertices self.indices = indices self.centerPosition = centerPosition } /// Create a new element with geometry. /// - Parameters: /// - geometry: The element's geometry /// - centerPosition: The position of the center of the element. public init(id: Int = 0, geometry: Geometry, centerPosition: Vec3f) { self.init( id: id, vertices: geometry.vertices, indices: geometry.indices, centerPosition: centerPosition ) } } extension SortableMeshElement: Equatable { public static func == (lhs: SortableMeshElement, rhs: SortableMeshElement) -> Bool { return lhs.id == rhs.id } } ================================================ FILE: Sources/Core/Renderer/RenderCoordinator.swift ================================================ import Foundation import FirebladeMath import MetalKit import DeltaCore public enum RendererError: LocalizedError { case getMetalDevice case makeRenderCommandQueue case camera(Error) case skyBoxRenderer(Error) case worldRenderer(Error) case guiRenderer(Error) case screenRenderer(Error) case depthState(Error) case unknown(Error) public var errorDescription: String? { switch self { case .getMetalDevice: return "Failed to get metal device" case .makeRenderCommandQueue: return "Failed to make render command queue" case .camera(let cameraError): return "Failed to create camera: \(cameraError.labeledLocalizedDescription)" case .skyBoxRenderer(let skyBoxError): return "Failed to create sky box renderer: \(skyBoxError.labeledLocalizedDescription)" case .worldRenderer(let worldError): return "Failed to create world renderer: \(worldError.labeledLocalizedDescription)" case .guiRenderer(let guiError): return "Failed to create GUI renderer: \(guiError.labeledLocalizedDescription)" case .screenRenderer(let screenError): return "Failed to create Screen renderer: \(screenError.labeledLocalizedDescription)" case .depthState(let depthError): return "Failed to create depth state: \(depthError.labeledLocalizedDescription)" case .unknown(let error): return "Failed with an unknown error \(error.labeledLocalizedDescription)" } } } extension Error { public var labeledLocalizedDescription: String? { "\(String(describing: self)) - \(self.localizedDescription)" } } /// Coordinates the rendering of the game (e.g. blocks and entities). public final class RenderCoordinator: NSObject, MTKViewDelegate { // MARK: Public properties /// Statistics that measure the renderer's current performance. public var statistics: RenderStatistics // MARK: Private properties /// The client to render. private var client: Client /// The renderer for the world's sky box. private var skyBoxRenderer: SkyBoxRenderer /// The renderer for the current world. Only renders blocks. private var worldRenderer: WorldRenderer /// The renderer for rendering the GUI. private var guiRenderer: GUIRenderer /// The renderer for rendering on screen. Can perform upscaling. private var screenRenderer: ScreenRenderer /// The camera that is rendered from. private var camera: Camera /// The device used to render. private var device: MTLDevice /// The depth stencil state. It's the same for every renderer so it's just made once here. private var depthState: MTLDepthStencilState /// The command queue. private var commandQueue: MTLCommandQueue /// The time that the cpu started encoding the previous frame. private var previousFrameStartTime: Double = 0 /// The current frame capture state (`nil` if no capture is in progress). private var captureState: CaptureState? /// The renderer profiler. private var profiler = Profiler("Rendering") /// The number of frames rendered so far. private var frameCount = 0 /// The longest a frame has taken to encode so far. private var longestFrame: Double = 0 // MARK: Init /// Creates a render coordinator. /// - Parameter client: The client to render for. public required init(_ client: Client) throws { guard let device = MTLCreateSystemDefaultDevice() else { throw RendererError.getMetalDevice } guard let commandQueue = device.makeCommandQueue() else { throw RendererError.makeRenderCommandQueue } self.client = client self.device = device self.commandQueue = commandQueue // Setup camera do { camera = try Camera(device) } catch { throw RendererError.camera(error) } do { skyBoxRenderer = try SkyBoxRenderer( client: client, device: device, commandQueue: commandQueue ) } catch { throw RendererError.skyBoxRenderer(error) } do { worldRenderer = try WorldRenderer( client: client, device: device, commandQueue: commandQueue, profiler: profiler ) } catch { throw RendererError.worldRenderer(error) } do { guiRenderer = try GUIRenderer( client: client, device: device, commandQueue: commandQueue, profiler: profiler ) } catch { throw RendererError.guiRenderer(error) } do { screenRenderer = try ScreenRenderer( client: client, device: device, profiler: profiler ) } catch { throw RendererError.screenRenderer(error) } // Create depth stencil state do { depthState = try MetalUtil.createDepthState(device: device) } catch { throw RendererError.depthState(error) } statistics = RenderStatistics(gpuCountersEnabled: false) super.init() } // MARK: Render public func draw(in view: MTKView) { let time = CFAbsoluteTimeGetCurrent() let frameTime = time - previousFrameStartTime previousFrameStartTime = time profiler.push(.updateRenderTarget) do { try screenRenderer.updateRenderTarget(for: view) } catch { log.error("Failed to update render target: \(error)") client.eventBus.dispatch(ErrorEvent(error: error, message: "Failed to update render target")) return } profiler.pop() // Fetch offscreen render pass descriptor from ScreenRenderer let renderPassDescriptor = screenRenderer.renderDescriptor // The CPU start time if vsync was disabled let cpuStartTime = CFAbsoluteTimeGetCurrent() profiler.push(.updateCamera) // Create world to clip uniforms buffer let uniformsBuffer = getCameraUniforms(view) profiler.pop() // When the render distance is above 2, move the fog 1 chunk closer to conceal // more of the world edge. let renderDistance = max(client.configuration.render.renderDistance - 1, 2) let fogColor = client.game.world.getFogColor( forViewerWithRay: camera.ray, withRenderDistance: renderDistance ) renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor( red: Double(fogColor.x), green: Double(fogColor.y), blue: Double(fogColor.z), alpha: 1 ) profiler.push(.createRenderCommandEncoder) // Create command buffer guard let commandBuffer = commandQueue.makeCommandBuffer() else { log.error("Failed to create command buffer") client.eventBus.dispatch(ErrorEvent( error: RenderError.failedToCreateCommandBuffer, message: "RenderCoordinator failed to create command buffer" )) return } // Create render encoder guard let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) else { log.error("Failed to create render encoder") client.eventBus.dispatch(ErrorEvent( error: RenderError.failedToCreateRenderEncoder, message: "RenderCoordinator failed to create render encoder" )) return } profiler.pop() profiler.push(.skyBox) do { try skyBoxRenderer.render( view: view, encoder: renderEncoder, commandBuffer: commandBuffer, worldToClipUniformsBuffer: uniformsBuffer, camera: camera ) } catch { log.error("Failed to render sky box: \(error)") client.eventBus.dispatch(ErrorEvent(error: error, message: "Failed to render sky box")) return } profiler.pop() // Configure the render encoder renderEncoder.setDepthStencilState(depthState) renderEncoder.setFrontFacing(.counterClockwise) renderEncoder.setVertexBuffer(uniformsBuffer, offset: 0, index: 1) switch client.configuration.render.mode { case .normal: renderEncoder.setCullMode(.front) case .wireframe: renderEncoder.setCullMode(.none) renderEncoder.setTriangleFillMode(.lines) } profiler.push(.world) do { try worldRenderer.render( view: view, encoder: renderEncoder, commandBuffer: commandBuffer, worldToClipUniformsBuffer: uniformsBuffer, camera: camera ) } catch { log.error("Failed to render world: \(error)") client.eventBus.dispatch(ErrorEvent(error: error, message: "Failed to render world")) return } profiler.pop() profiler.push(.gui) do { try guiRenderer.render( view: view, encoder: renderEncoder, commandBuffer: commandBuffer, worldToClipUniformsBuffer: uniformsBuffer, camera: camera ) } catch { log.error("Failed to render GUI: \(error)") client.eventBus.dispatch(ErrorEvent(error: error, message: "Failed to render GUI")) return } profiler.pop() profiler.push(.commitToGPU) // Finish measurements for render statistics let cpuFinishTime = CFAbsoluteTimeGetCurrent() // Finish encoding the frame guard let drawable = view.currentDrawable else { log.warning("Failed to get current drawable") return } renderEncoder.endEncoding() profiler.push(.waitForRenderPassDescriptor) // Get current render pass descriptor guard let renderPassDescriptor = view.currentRenderPassDescriptor else { log.error("Failed to get the current render pass descriptor") client.eventBus.dispatch(ErrorEvent( error: RenderError.failedToGetCurrentRenderPassDescriptor, message: "RenderCoordinator failed to get the current render pass descriptor" )) return } profiler.pop() guard let quadRenderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) else { log.error("Failed to create quad render encoder") client.eventBus.dispatch(ErrorEvent( error: RenderError.failedToCreateRenderEncoder, message: "RenderCoordinator failed to create render encoder" )) return } profiler.push(.renderOnScreen) do { try screenRenderer.render( view: view, encoder: quadRenderEncoder, commandBuffer: commandBuffer, worldToClipUniformsBuffer: uniformsBuffer, camera: camera ) } catch { log.error("Failed to perform on-screen rendering: \(error)") client.eventBus.dispatch(ErrorEvent(error: error, message: "Failed to perform on-screen rendering pass.")) return } profiler.pop() quadRenderEncoder.endEncoding() commandBuffer.present(drawable) let cpuElapsed = cpuFinishTime - cpuStartTime statistics.addMeasurement( frameTime: frameTime, cpuTime: cpuElapsed, gpuTime: nil ) // Update statistics in gui client.game.updateRenderStatistics(to: statistics) commandBuffer.commit() profiler.pop() // Update frame capture state and stop current capture if necessary captureState?.framesRemaining -= 1 if let captureState = captureState, captureState.framesRemaining == 0 { let captureManager = MTLCaptureManager.shared() captureManager.stopCapture() client.eventBus.dispatch(FinishFrameCaptureEvent(file: captureState.outputFile)) self.captureState = nil } frameCount += 1 profiler.endTrial() if frameCount % 60 == 0 { longestFrame = cpuElapsed // profiler.printSummary() profiler.clear() } } /// Captures the specified number of frames into a GPU trace file. public func captureFrames(count: Int, to file: URL) throws { let captureManager = MTLCaptureManager.shared() guard captureManager.supportsDestination(.gpuTraceDocument) else { throw RenderError.gpuTraceNotSupported } let captureDescriptor = MTLCaptureDescriptor() captureDescriptor.captureObject = device captureDescriptor.destination = .gpuTraceDocument captureDescriptor.outputURL = file do { try captureManager.startCapture(with: captureDescriptor) } catch { throw RenderError.failedToStartCapture(error) } captureState = CaptureState(framesRemaining: count, outputFile: file) } // MARK: Helper public func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { } /// Gets the camera uniforms for the current frame. /// - Parameter view: The view that is being rendered to. Used to get aspect ratio. /// - Returns: A buffer containing the uniforms. private func getCameraUniforms(_ view: MTKView) -> MTLBuffer { let aspect = Float(view.drawableSize.width / view.drawableSize.height) camera.setAspect(aspect) let effectiveFovY = client.configuration.render.fovY * client.game.fovMultiplier() camera.setFovY(MathUtil.radians(from: effectiveFovY)) client.game.accessPlayer { player in var eyePosition = Vec3f(player.position.smoothVector) eyePosition.y += 1.625 // TODO: don't hardcode this, use the player's eye height var cameraPosition = Vec3f(repeating: 0) var pitch = player.rotation.smoothPitch var yaw = player.rotation.smoothYaw switch player.camera.perspective { case .thirdPersonRear: cameraPosition.z += 3 cameraPosition = (Vec4f(cameraPosition, 1) * MatrixUtil.rotationMatrix(x: pitch) * MatrixUtil.rotationMatrix(y: Float.pi + yaw)).xyz cameraPosition += eyePosition case .thirdPersonFront: pitch = -pitch yaw += Float.pi cameraPosition.z += 3 cameraPosition = (Vec4f(cameraPosition, 1) * MatrixUtil.rotationMatrix(x: pitch) * MatrixUtil.rotationMatrix(y: Float.pi + yaw)).xyz cameraPosition += eyePosition case .firstPerson: cameraPosition = eyePosition } camera.setPosition(cameraPosition) camera.setRotation(xRot: pitch, yRot: yaw) } camera.cacheFrustum() return camera.getUniformsBuffer() } } ================================================ FILE: Sources/Core/Renderer/RenderError.swift ================================================ import DeltaCore import Foundation public enum RenderError: LocalizedError { /// Failed to create a metal array texture. case failedToCreateArrayTexture /// Failed to create a private metal array texture. case failedToCreatePrivateArrayTexture /// Failed to get the Delta Core bundle. case failedToGetBundle /// Failed to find default.metallib in the bundle. case failedToLocateMetallib /// Failed to create a metal library from `default.metallib`. case failedToCreateMetallib(Error) /// Failed to load the shaders from the metallib. case failedToLoadShaders /// Failed to create the buffers that hold the world uniforms. case failedtoCreateWorldUniformBuffers /// Failed to create the render pipeline state for the world renderer. case failedToCreateWorldRenderPipelineState(Error) /// Failed to create the depth stencil state for the world renderer. case failedToCreateWorldDepthStencilState /// Failed to create the render pipeline state for a renderer. case failedToCreateRenderPipelineState(Error, label: String) /// Failed to create the depth stencil state for the entity renderer. case failedToCreateEntityDepthStencilState /// Failed to create the block texture array. case failedToCreateBlockTextureArray(Error) /// Failed to create the render encoder. case failedToCreateRenderEncoder /// Failed to create the command buffer. case failedToCreateCommandBuffer /// Failed to create geometry buffers for the entity renderer. case failedToCreateEntityGeometryBuffers /// Failed to create a metal buffer. case failedToCreateBuffer(label: String?) /// Failed to get the current render pass descriptor for a frame. case failedToGetCurrentRenderPassDescriptor /// Failed to create an event for the gpu timer. case failedToCreateTimerEvent /// Failed to get the specified counter set (it is likely not supported by the selected device). case failedToGetCounterSet(_ rawValue: String) /// Failed to create the buffer used for sampling GPU counters. case failedToMakeCounterSampleBuffer(Error) /// Failed to sample the GPU counters used to calculate FPS. case failedToSampleCounters /// The current device does not support capturing a gpu trace and outputting to a file. case gpuTraceNotSupported /// Failed to start GPU frame capture. case failedToStartCapture(Error) /// Failed to update render target textures case failedToUpdateRenderTargetSize /// Failed to create blit command encoder. case failedToCreateBlitCommandEncoder /// A required texture is missing. case missingTexture(Identifier) public var errorDescription: String? { switch self { case .failedToUpdateRenderTargetSize: return "Failed to update render target texture size." case .failedToCreateArrayTexture: return "Failed to create an array texture." case .failedToCreatePrivateArrayTexture: return "Failed to create a private array texture." case .failedToGetBundle: return "Failed to get the Delta Core bundle.." case .failedToLocateMetallib: return "Failed to find default.metallib in the bundle." case .failedToCreateMetallib(let error): return """ Failed to create a metal library from `default.metallib`. Reason: \(error.localizedDescription) """ case .failedToLoadShaders: return "Failed to load the shaders from the metallib." case .failedtoCreateWorldUniformBuffers: return "Failed to create the buffers that hold the world uniforms." case .failedToCreateWorldRenderPipelineState(let error): return """ Failed to create the render pipeline state for the world renderer. Reason: \(error.localizedDescription) """ case .failedToCreateWorldDepthStencilState: return "Failed to create the depth stencil state for the entity renderer." case .failedToCreateRenderPipelineState(let error, let label): return """ Failed to create render pipeline state. Reason: \(error.localizedDescription) Label: \(label) """ case .failedToCreateEntityDepthStencilState: return " Failed to create the depth stencil state for the entity renderer." case .failedToCreateBlockTextureArray(let error): return """ Failed to create the block texture array. Reason: \(error.localizedDescription) """ case .failedToCreateRenderEncoder: return "Failed to create the render encoder." case .failedToCreateCommandBuffer: return "Failed to create the command buffer." case .failedToCreateEntityGeometryBuffers: return "Failed to create geometry buffers for the entity renderer." case .failedToCreateBuffer(let label): return "Failed to create a buffer with label: \(label ?? "no label provided")." case .failedToGetCurrentRenderPassDescriptor: return "Failed to get the current render pass descriptor for a frame." case .failedToCreateTimerEvent: return "Failed to get the specified counter set (it is likely not supported by the selected device)." case .failedToGetCounterSet(let rawValue): return """ Failed to get the specified counter set (it is likely not supported by the selected device). Raw value: \(rawValue) """ case .failedToMakeCounterSampleBuffer(let error): return """ Failed to create the buffer used for sampling GPU counters. Reason: \(error.localizedDescription) """ case .failedToSampleCounters: return "Failed to sample the GPU counters used to calculate FPS." case .gpuTraceNotSupported: return "The current device does not support capturing a gpu trace and outputting to a file." case .failedToStartCapture(let error): return """ Failed to start GPU frame capture. Reason: \(error.localizedDescription) """ case .failedToCreateBlitCommandEncoder: return "Failed to create blit command encoder." case .missingTexture(let identifier): return "The required '\(identifier)' texture is missing." } } } ================================================ FILE: Sources/Core/Renderer/Renderer.swift ================================================ import Metal import MetalKit /// A protocol that renderers should conform to. public protocol Renderer { /// Renders a frame. /// /// Should not call `renderEncoder.endEncoding()` or `commandBuffer.commit()`. /// A render coordinator should will manage the encoder and command buffer. mutating func render( view: MTKView, encoder: MTLRenderCommandEncoder, commandBuffer: MTLCommandBuffer, worldToClipUniformsBuffer: MTLBuffer, camera: Camera ) throws } ================================================ FILE: Sources/Core/Renderer/RenderingMeasurement.swift ================================================ public enum RenderingMeasurement: String, Hashable { case waitForRenderPassDescriptor case updateCamera case createRenderCommandEncoder case skyBox case world case updateWorldMesh case updateAnimatedTextures case updateLightMap case updateFogUniforms case encodeOpaque case encodeBlockOutline case encodeTranslucent case entities case getEntities case createRegularEntityMeshes case createBlockEntityMeshes case encodeEntities case gui case updateUniforms case updateContent case createMeshes case renderOnScreen case updateRenderTarget case encodeUpscale case encode case commitToGPU } ================================================ FILE: Sources/Core/Renderer/Resources/Font+Metal.swift ================================================ import MetalKit import DeltaCore extension Font { /// Creates an array texture containing the font's atlases. /// - Parameters: /// - device: The device to create the texture with. /// - commandQueue: The command queue to use for blit operations. /// - Returns: An array texture containing the textures in ``textures``. public func createArrayTexture( device: MTLDevice, commandQueue: MTLCommandQueue ) throws -> MTLTexture { guard !textures.isEmpty else { throw FontError.emptyFont } // Calculate minimum dimensions to fit all textures. guard let width = textures.map({ texture in return texture.width }).max() else { throw FontError.failedToGetArrayTextureWidth } guard let height = textures.map({ texture in return texture.height }).max() else { throw FontError.failedToGetArrayTextureHeight } // Create texture descriptor let textureDescriptor = MTLTextureDescriptor() textureDescriptor.width = width textureDescriptor.height = height textureDescriptor.arrayLength = textures.count textureDescriptor.pixelFormat = .bgra8Unorm textureDescriptor.textureType = .type2DArray #if os(macOS) textureDescriptor.storageMode = .managed #elseif os(iOS) || os(tvOS) textureDescriptor.storageMode = .shared #else #error("Unsupported platform, can't determine storageMode for texture") #endif guard let arrayTexture = device.makeTexture(descriptor: textureDescriptor) else { throw FontError.failedToCreateArrayTexture } // Populate texture let bytesPerPixel = 4 for (index, texture) in textures.enumerated() { let bytesPerRow = bytesPerPixel * texture.width let byteCount = bytesPerRow * texture.height texture.image.withUnsafeBytes { pointer in arrayTexture.replace( region: MTLRegion( origin: MTLOrigin(x: 0, y: 0, z: 0), size: MTLSize( width: texture.width, height: texture.height, depth: 1 ) ), mipmapLevel: 0, slice: index, withBytes: pointer.baseAddress!, bytesPerRow: bytesPerRow, bytesPerImage: byteCount ) } } guard let commandBuffer = commandQueue.makeCommandBuffer(), let blitCommandEncoder = commandBuffer.makeBlitCommandEncoder() else { throw RenderError.failedToCreateBlitCommandEncoder } textureDescriptor.storageMode = .private guard let privateArrayTexture = device.makeTexture(descriptor: textureDescriptor) else { throw RenderError.failedToCreatePrivateArrayTexture } blitCommandEncoder.copy(from: arrayTexture, to: privateArrayTexture) blitCommandEncoder.endEncoding() commandBuffer.commit() return privateArrayTexture } } ================================================ FILE: Sources/Core/Renderer/Resources/MetalTexturePalette.swift ================================================ import Metal import DeltaCore /// An error thrown by ``MetalTexturePalette``. public enum MetalTexturePaletteError: LocalizedError { case failedToCreateCommandBuffer case failedToCreateBlitCommandEncoder public var errorDescription: String? { switch self { case .failedToCreateCommandBuffer: return "Failed to create command buffer for mipmap generation." case .failedToCreateBlitCommandEncoder: return "Failed to create blit command encoder for mipmap generation." } } } /// A Metal-specific wrapper for ``TexturePalette``. Handles animation-related buffers, and the /// palette's static array texture. public struct MetalTexturePalette { /// The underlying texture palette. public var palette: TexturePalette /// The texture palette's animation state. public var animationState: TexturePalette.AnimationState /// The underlying array texture. public var arrayTexture: MTLTexture /// The buffer storing texture states. public var textureStatesBuffer: MTLBuffer? /// The small buffer containing only the current time (we cannot just use the GPU's concept of /// time instead because the GPU does not use the same timebase as the CPU). public var timeBuffer: MTLBuffer? /// The global device to use for creating textures etc. public let device: MTLDevice /// The global command queue to use for creating textures etc. public let commandQueue: MTLCommandQueue /// For each texture there is a node that points to the previous animation frame and the next /// animation frame (in the array texture). public var textureStates: [TextureState] /// The time at which the palette was created measured in `CFAbsoluteTime`. public var creationTime: Double /// Maps a texture index to the index of its first frame (in the palette's array texture). public var textureIndexToFirstFrameIndex: [Int] /// The animation state of a texture in a format that is useful on the GPU. public struct TextureState { /// The array texture index of the texture's current animation frame. public var currentFrameIndex: UInt16 /// The array texture index of the texture's next animation frame. `65535` indicates that the value /// is not present. Usually this would be represented using `Optional`, however that does not /// lend itself well to being copied to and interpreted by the GPU. public var nextFrameIndex: UInt16 /// The time at which the previous update occured. Used for interpolation. Measured in ticks. public var previousUpdate: UInt32 /// The time at which the next frame index will become the current frame index. Used for /// interpolation. Measured in ticks. public var nextUpdate: UInt32 } /// Creates a new Metal wrapper for the given texture palette. public init( palette: TexturePalette, device: MTLDevice, commandQueue: MTLCommandQueue ) throws { self.palette = palette self.device = device self.commandQueue = commandQueue arrayTexture = try Self.createArrayTexture( for: palette, device: device, commandQueue: commandQueue ) animationState = palette.defaultAnimationState var frameIndex = 0 textureIndexToFirstFrameIndex = [] textureStates = [] creationTime = CFAbsoluteTimeGetCurrent() for texture in palette.textures { textureIndexToFirstFrameIndex.append(frameIndex) let frameTicks = texture.animation?.frames.first?.time ?? 0 textureStates.append(TextureState( currentFrameIndex: UInt16(frameIndex), nextFrameIndex: 65535, previousUpdate: UInt32(0), nextUpdate: UInt32(frameTicks) )) frameIndex += texture.frameCount } textureStatesBuffer = device.makeBuffer( bytes: &textureStates, length: MemoryLayout.stride * textureStates.count ) textureStatesBuffer?.label = "MetalTexturePalette.textureStatesBuffer" var tick: Float = 0 timeBuffer = device.makeBuffer(bytes: &tick, length: MemoryLayout.stride) timeBuffer?.label = "MetalTexturePalette.timeBuffer" } /// Gets the index of the texture referred to by the given identifier if any. public func textureIndex(for identifier: Identifier) -> Int? { palette.textureIndex(for: identifier) } /// Returns a metal array texture containing all textures (including each individual animation /// frame of each texture if `includeAnimations` is set to `true`). public static func createArrayTexture( for palette: TexturePalette, device: MTLDevice, commandQueue: MTLCommandQueue, includeAnimations: Bool = true ) throws -> MTLTexture { let count: Int if includeAnimations { count = palette.textures.map{ texture in return texture.frameCount }.reduce(0, +) } else { count = palette.textures.count } let width = palette.width let height = palette.height let textureDescriptor = MTLTextureDescriptor() textureDescriptor.width = width textureDescriptor.height = height textureDescriptor.pixelFormat = .bgra8Unorm textureDescriptor.textureType = .type2DArray textureDescriptor.arrayLength = count #if os(macOS) textureDescriptor.storageMode = .managed #elseif os(iOS) || os(tvOS) textureDescriptor.storageMode = .shared #else #error("Unsupported platform, can't determine storageMode for texture") #endif textureDescriptor.mipmapLevelCount = 1 + Int(Foundation.log2(Double(width)).rounded(.down)) guard let arrayTexture = device.makeTexture(descriptor: textureDescriptor) else { throw RenderError.failedToCreateArrayTexture } arrayTexture.label = "arrayTexture" let bytesPerPixel = 4 var frameIndex = 0 for texture in palette.textures { let frameWidth = texture.width let frameCount = texture.frameCount let frameHeight = texture.height / frameCount let bytesPerRow = bytesPerPixel * frameWidth let bytesPerFrame = bytesPerRow * frameHeight guard frameHeight <= height else { frameIndex += frameCount continue } for frame in 0...stride) let tick = Int(time.rounded(.down)) let updatedTextures = animationState.update(tick: tick) guard !updatedTextures.isEmpty else { return } for (textureIndex, latestUpdateTick) in updatedTextures { let texture = palette.textures[textureIndex] guard let animation = texture.animation else { continue } let frameIndex = animationState.frame(forTextureAt: textureIndex) let frame = animation.frames[frameIndex] let firstFrameIndex = textureIndexToFirstFrameIndex[textureIndex] let nextFrameIndex = (frameIndex + 1) % animation.frames.count textureStates[textureIndex] = TextureState( currentFrameIndex: UInt16(firstFrameIndex + frameIndex), nextFrameIndex: animation.interpolate ? UInt16(firstFrameIndex + nextFrameIndex) : 65535, previousUpdate: UInt32(latestUpdateTick), nextUpdate: UInt32(latestUpdateTick + frame.time) ) } textureStatesBuffer?.contents().copyMemory( from: &textureStates, byteCount: MemoryLayout.stride * textureStates.count ) } } ================================================ FILE: Sources/Core/Renderer/ScreenRenderer.swift ================================================ import Foundation import MetalKit import DeltaCore import FirebladeMath /// The renderer managing offscreen rendering and displaying final result in view. public final class ScreenRenderer: Renderer { /// The device used to render. private var device: MTLDevice /// Renderer's own pipeline state (for drawing on-screen) private var pipelineState: MTLRenderPipelineState /// Offscreen render pass descriptor used to perform rendering into renderer's internal textures private var offScreenRenderPassDescriptor: MTLRenderPassDescriptor! /// Renderer's profiler private var profiler: Profiler /// Render target texture into which offscreen rendering is performed private var renderTargetTexture: MTLTexture? /// Render target depth texture private var renderTargetDepthTexture: MTLTexture? /// The accumulation texture used for rendering of order independent transparency. private var transparencyAccumulationTexture: MTLTexture? /// The revealage texture used for rendering of order independent transparency. private var transparencyRevealageTexture: MTLTexture? /// Client for which rendering is performed private var client: Client public init( client: Client, device: MTLDevice, profiler: Profiler ) throws { self.device = device self.client = client self.profiler = profiler // Create pipeline state let library = try MetalUtil.loadDefaultLibrary(device) pipelineState = try MetalUtil.makeRenderPipelineState( device: device, label: "ScreenRenderer", vertexFunction: try MetalUtil.loadFunction("screenVertexFunction", from: library), fragmentFunction: try MetalUtil.loadFunction("screenFragmentFunction", from: library), blendingEnabled: false, isOffScreenPass: false ) } public var renderDescriptor: MTLRenderPassDescriptor { return offScreenRenderPassDescriptor } public func updateRenderTarget(for view: MTKView) throws { let drawableSize = view.drawableSize let width = Int(drawableSize.width) let height = Int(drawableSize.height) if let texture = renderTargetTexture { if texture.width == width && texture.height == height { // No updates necessary, early exit return } } renderTargetTexture = try MetalUtil.createTexture( device: device, width: width, height: height, pixelFormat: view.colorPixelFormat ) { descriptor in descriptor.storageMode = .private } renderTargetDepthTexture = try MetalUtil.createTexture( device: device, width: width, height: height, pixelFormat: .depth32Float ) { descriptor in descriptor.storageMode = .private } // Create accumulation texture for order independent transparency transparencyAccumulationTexture = try MetalUtil.createTexture( device: device, width: width, height: height, pixelFormat: .bgra8Unorm ) // Create revealage texture for order independent transparency transparencyRevealageTexture = try MetalUtil.createTexture( device: device, width: width, height: height, pixelFormat: .r8Unorm ) // Update render pass descriptor. Set clear colour to sky colour let passDescriptor = MetalUtil.createRenderPassDescriptor( device, targetRenderTexture: renderTargetTexture!, targetDepthTexture: renderTargetDepthTexture! ) let accumulationClearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 0) passDescriptor.colorAttachments[1].texture = transparencyAccumulationTexture passDescriptor.colorAttachments[1].clearColor = accumulationClearColor passDescriptor.colorAttachments[1].loadAction = MTLLoadAction.clear passDescriptor.colorAttachments[1].storeAction = MTLStoreAction.store let revealageClearColor = MTLClearColor(red: 1, green: 0, blue: 0, alpha: 0) passDescriptor.colorAttachments[2].texture = transparencyRevealageTexture passDescriptor.colorAttachments[2].clearColor = revealageClearColor passDescriptor.colorAttachments[2].loadAction = MTLLoadAction.clear passDescriptor.colorAttachments[2].storeAction = MTLStoreAction.store offScreenRenderPassDescriptor = passDescriptor } public func render( view: MTKView, encoder: MTLRenderCommandEncoder, commandBuffer: MTLCommandBuffer, worldToClipUniformsBuffer: MTLBuffer, camera: Camera ) throws { // TODO: Investigate using a blit operation instead. profiler.push(.encode) // Set pipeline for rendering on-screen encoder.setRenderPipelineState(pipelineState) // Use texture from offscreen rendering as fragment shader source to draw contents on-screen encoder.setFragmentTexture(self.renderTargetTexture, index: 0) encoder.setFragmentTexture(self.renderTargetDepthTexture, index: 1) // A quad with total of 6 vertices (2 overlapping triangles) is drawn to present // rendering results on-screen. The geometry is defined within the shader (hard-coded). encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 6) profiler.pop() } } ================================================ FILE: Sources/Core/Renderer/Shader/ChunkOITShaders.metal ================================================ #include #include "ChunkTypes.metal" using namespace metal; // These shaders are used in the order independent transparency pipeline based off this blog // article: https://casual-effects.blogspot.com/2015/03/implemented-weighted-blended-order.html?m=1 // The vertex shader used in this pipeline is just the regular one in ChunkShaders.metal // Compositing is performed using chunkOITCompositingVertexShader and chunkOITFragmentShader struct FragmentOut { float4 accumulation [[ color(1) ]]; float revealage [[ color(2) ]]; }; constexpr sampler textureSampler (mag_filter::nearest, min_filter::nearest, mip_filter::linear); constant float precomputedWeight = 0.286819249; fragment FragmentOut chunkOITFragmentShader(RasterizerData in [[stage_in]], texture2d_array textureArray [[texture(0)]], constant uint8_t *lightMap [[buffer(0)]], constant float &time [[buffer(1)]], constant FogUniforms &fogUniforms [[buffer(2)]]) { // Sample the relevant texture slice FragmentOut out; float4 color = textureArray.sample(textureSampler, in.uv, in.textureState.currentFrameIndex); if (in.textureState.nextFrameIndex != 65535) { float start = (float)in.textureState.previousUpdate; float end = (float)in.textureState.nextUpdate; float progress = (time - start) / (end - start); float4 nextColor = textureArray.sample(textureSampler, in.uv, in.textureState.nextFrameIndex); color = mix(color, nextColor, progress); } // Apply light level int index = in.skyLightLevel * 16 + in.blockLightLevel; float4 brightness; brightness.r = (float)lightMap[index * 4]; brightness.g = (float)lightMap[index * 4 + 1]; brightness.b = (float)lightMap[index * 4 + 2]; brightness.a = 255; color *= brightness / 255.0; color *= in.tint; // Apply distance fog float distance = length(in.cameraSpacePosition); float linearFogIntensity = smoothstep(fogUniforms.fogStart, fogUniforms.fogEnd, distance); float exponentialFogIntensity = clamp(1.0 - exp(-fogUniforms.fogDensity * distance), 0.0, 1.0); float fogIntensity = linearFogIntensity * fogUniforms.isLinear + exponentialFogIntensity * !fogUniforms.isLinear; color.rgb = color.rgb * (1.0 - fogIntensity) + fogUniforms.fogColor * fogIntensity; // As the fog approaches an intensity of 1.0, the alpha of the fragment has to increase to 1.0 // as well so that the fragment disappears into the fog. Otherwise the fragment is still visible // even once everything around it has disappeared into the fog (some weirdness with additive blending // during the compositing step). Cubing the intensity to curve it a bit more makes it look a bit // more correct (still looks a bit odd though). float fogAlphaIntensity = fogIntensity * fogIntensity * fogIntensity * fogIntensity; color.a = color.a * (1.0 - fogAlphaIntensity) + fogAlphaIntensity; // Premultiply alpha color.rgb *= color.a; // Order independent transparency code adapted from https://casual-effects.blogspot.com/2015/03/implemented-weighted-blended-order.html?m=1 // I have changed the maths a lot to get it working well at all. I've hardcoded the depth for now // and it seems to be working quite well. // This code was used to calculate z which was used in weight calculations. This had super weird // artifacts and it turns out that just hardcoding the depth to 16 works way better than any depth // weighting algorithms I have tried. The precomputedWeight is calculated using Equation 7 from // the 2013 paper by Morgan mcGuire and Louis Bavoil of NVIDIA: https://jcgt.org/published/0002/02/09/ // // float d = in.position.z; // float far = 400; // float near = 0.04; // float z = (far * near) / (d * (far - near) - far) + 32; // // constant float z = 16; // constant float zCubed = z * z * z; // constant float precomputedWeight = max(1e-2, min(3e3, 10 / (1e-5 + zCubed / 125 + zCubed * zCubed / 8e6))); float w = color.a * precomputedWeight; out.accumulation = color * w; out.revealage = color.a; return out; } // You're welcome for the alignment constant float4 screenCorners[6] = { float4( 1, 1, 0, 1), float4( 1, -1, 0, 1), float4(-1, 1, 0, 1), float4( 1, -1, 0, 1), float4(-1, -1, 0, 1), float4(-1, 1, 0, 1) }; vertex OITCompositingRasterizerData chunkOITCompositingVertexShader(uint vertexId [[vertex_id]]) { OITCompositingRasterizerData out; out.position = screenCorners[vertexId]; return out; } fragment float4 chunkOITCompositingFragmentShader(OITCompositingRasterizerData in [[stage_in]], float4 accumulation [[color(1)]], float revealage [[color(2)]]) { return float4(accumulation.rgb / max(min(accumulation.a, 5e4), 1e-4), 1 - revealage); } ================================================ FILE: Sources/Core/Renderer/Shader/ChunkShaders.metal ================================================ #include #include "ChunkTypes.metal" using namespace metal; constexpr sampler textureSampler (mag_filter::nearest, min_filter::nearest, mip_filter::linear); vertex RasterizerData chunkVertexShader(uint vertexId [[vertex_id]], uint instanceId [[instance_id]], constant Vertex *vertices [[buffer(0)]], constant CameraUniforms &cameraUniforms [[buffer(1)]], constant ChunkUniforms &chunkUniforms [[buffer(2)]], constant TextureState *textureStates [[buffer(3)]]) { Vertex in = vertices[vertexId]; RasterizerData out; float4 cameraSpacePosition = float4(in.x, in.y, in.z, 1.0) * chunkUniforms.transformation * cameraUniforms.framing; out.position = cameraSpacePosition * cameraUniforms.projection; out.cameraSpacePosition = float3(cameraSpacePosition / cameraSpacePosition.w); out.uv = float2(in.u, in.v); out.hasTexture = in.textureIndex != 65535; if (out.hasTexture) { out.textureState = textureStates[in.textureIndex]; } out.isTransparent = in.isTransparent; out.tint = float4(in.r, in.g, in.b, in.a); out.skyLightLevel = in.skyLightLevel; out.blockLightLevel = in.blockLightLevel; return out; } fragment float4 chunkFragmentShader(RasterizerData in [[stage_in]], texture2d_array textureArray [[texture(0)]], constant uint8_t *lightMap [[buffer(0)]], constant float &time [[buffer(1)]], constant FogUniforms &fogUniforms [[buffer(2)]]) { // Sample the relevant texture slice float4 color; if (in.hasTexture) { color = textureArray.sample(textureSampler, in.uv, in.textureState.currentFrameIndex); // If the texture is animated and requires interpolation, interpolate between the current // frame and the next. if (in.textureState.nextFrameIndex != 65535) { float start = (float)in.textureState.previousUpdate; float end = (float)in.textureState.nextUpdate; float progress = (time - start) / (end - start); float4 nextColor = textureArray.sample(textureSampler, in.uv, in.textureState.nextFrameIndex); color = mix(color, nextColor, progress); } } else { color = float4(1, 1, 1, 1); } // Discard transparent fragments if (in.isTransparent && color.a < 0.33) { discard_fragment(); } // Apply light level int index = in.skyLightLevel * 16 + in.blockLightLevel; float4 brightness; brightness.r = (float)lightMap[index * 4]; brightness.g = (float)lightMap[index * 4 + 1]; brightness.b = (float)lightMap[index * 4 + 2]; brightness.a = 255; color *= brightness / 255.0; // A bit of branchless programming for you color = color * in.tint; // TODO: Rename isTransparent to isTranslucent (which would require inverting its value) // Here transparent means opaque or fully transparent (basically just 'not-translucent') color.w = color.w * !in.isTransparent // If not transparent, take the original alpha + in.isTransparent; // If transparent, make alpha 1 float distance = length(in.cameraSpacePosition); float linearFogIntensity = smoothstep(fogUniforms.fogStart, fogUniforms.fogEnd, distance); float exponentialFogIntensity = clamp(1.0 - exp(-fogUniforms.fogDensity * distance), 0.0, 1.0); float fogIntensity = linearFogIntensity * fogUniforms.isLinear + exponentialFogIntensity * !fogUniforms.isLinear; color.rgb = color.rgb * (1.0 - fogIntensity) + fogUniforms.fogColor.rgb * fogIntensity; return color; } ================================================ FILE: Sources/Core/Renderer/Shader/ChunkTypes.metal ================================================ #include using namespace metal; struct TextureState { uint16_t currentFrameIndex; uint16_t nextFrameIndex; uint32_t previousUpdate; uint32_t nextUpdate; }; struct Vertex { float x; float y; float z; float u; float v; float r; float g; float b; float a; uint8_t skyLightLevel; // TODO: pack sky and block light into a single uint8 to reduce size of vertex uint8_t blockLightLevel; uint16_t textureIndex; bool isTransparent; }; struct RasterizerData { float4 position [[position]]; float3 cameraSpacePosition; float2 uv; float4 tint; TextureState textureState; bool hasTexture; bool isTransparent; uint8_t skyLightLevel; uint8_t blockLightLevel; }; struct CameraUniforms { float4x4 framing; float4x4 projection; }; struct ChunkUniforms { float4x4 transformation; }; struct OITCompositingRasterizerData { float4 position [[position]]; }; struct FogUniforms { float3 fogColor; float fogStart; float fogEnd; float fogDensity; bool isLinear; }; ================================================ FILE: Sources/Core/Renderer/Shader/EntityShaders.metal ================================================ #include #include "ChunkTypes.metal" using namespace metal; struct EntityVertex { float x; float y; float z; float r; float g; float b; float u; float v; uint8_t skyLightLevel; uint8_t blockLightLevel; uint16_t textureIndex; }; struct EntityRasterizerData { float4 position [[position]]; float4 color; float2 uv; uint8_t skyLightLevel; uint8_t blockLightLevel; uint16_t textureIndex; }; vertex EntityRasterizerData entityVertexShader(constant EntityVertex *vertices [[buffer(0)]], constant CameraUniforms &cameraUniforms [[buffer(1)]], uint vertexId [[vertex_id]]) { EntityVertex in = vertices[vertexId]; EntityRasterizerData out; out.position = float4(in.x, in.y, in.z, 1.0) * cameraUniforms.framing * cameraUniforms.projection; out.color = float4(in.r, in.g, in.b, 1.0); out.uv = float2(in.u, in.v); out.textureIndex = in.textureIndex; out.skyLightLevel = in.skyLightLevel; out.blockLightLevel = in.blockLightLevel; return out; } constexpr sampler textureSampler (mag_filter::nearest, min_filter::nearest, mip_filter::linear); fragment float4 entityFragmentShader(EntityRasterizerData in [[stage_in]], texture2d_array textureArray [[texture(0)]], constant uint8_t *lightMap [[buffer(0)]]) { float4 color; if (in.textureIndex == 65535) { color = in.color; } else { color = textureArray.sample(textureSampler, in.uv, in.textureIndex); } if (color.a < 0.3) { discard_fragment(); } int index = in.skyLightLevel * 16 + in.blockLightLevel; float4 brightness; brightness.r = (float)lightMap[index * 4]; brightness.g = (float)lightMap[index * 4 + 1]; brightness.b = (float)lightMap[index * 4 + 2]; brightness.a = 255; color *= brightness / 255.0; return color; } ================================================ FILE: Sources/Core/Renderer/Shader/GUIShaders.metal ================================================ #include #include "GUITypes.metal" using namespace metal; constant const uint vertexIndexLookup[] = {0, 1, 2, 2, 3, 0}; vertex FragmentInput guiVertex(constant GUIUniforms &uniforms [[buffer(0)]], constant GUIVertex *vertices [[buffer(1)]], constant GUIElementUniforms &elementUniforms [[buffer(2)]], uint vertexId [[vertex_id]], uint instanceId [[instance_id]]) { uint index = vertexIndexLookup[vertexId % 6] + vertexId / 6 * 4; GUIVertex in = vertices[index]; FragmentInput out; float2 position = in.position; position += elementUniforms.position; position *= uniforms.scale; float3 transformed = float3(position, 1) * uniforms.screenSpaceToNormalized; out.position = float4(transformed.xy, 0, transformed.z); out.uv = in.uv; out.tint = in.tint; out.textureIndex = in.textureIndex; return out; } constexpr sampler textureSampler (mag_filter::nearest, min_filter::nearest, mip_filter::linear); fragment float4 guiFragment(FragmentInput in [[stage_in]], texture2d_array textureArray [[texture(0)]]) { float4 color; if (in.textureIndex == 65535) { color = in.tint; } else { color = textureArray.sample(textureSampler, in.uv, in.textureIndex); if (color.a < 0.33) { discard_fragment(); } color *= in.tint; } return color; } ================================================ FILE: Sources/Core/Renderer/Shader/GUITypes.metal ================================================ #include using namespace metal; struct GUIVertex { float2 position; float2 uv; float4 tint; uint16_t textureIndex; }; struct GUIUniforms { float3x3 screenSpaceToNormalized; float scale; }; struct GUIElementUniforms { float2 position; }; struct FragmentInput { float4 position [[position]]; float2 uv; uint16_t textureIndex; float4 tint; }; ================================================ FILE: Sources/Core/Renderer/Shader/ScreenShaders.metal ================================================ #include using namespace metal; constant float2 quadVertices[] = { float2(-1.0, 1.0), float2(-1.0, -1.0), float2( 1.0, -1.0), float2(-1.0, 1.0), float2( 1.0, 1.0), float2( 1.0, -1.0) }; struct QuadVertex { float4 position [[position]]; float2 uv; }; vertex QuadVertex screenVertexFunction(uint id [[vertex_id]]) { auto quadVertex = quadVertices[id]; return { .position = float4(quadVertex, 1.0, 1.0), .uv = quadVertex * float2(0.5, -0.5) + 0.5, }; } fragment float4 screenFragmentFunction(QuadVertex vert [[stage_in]], texture2d offscreenResult [[texture(0)]], depth2d offscreenResultDepth [[texture(1)]], constant struct FogUniforms &fogUniforms [[buffer(0)]]) { constexpr sampler smplr(coord::normalized); float4 color = offscreenResult.sample(smplr, vert.uv); return color; }; ================================================ FILE: Sources/Core/Renderer/Shader/SkyShaders.metal ================================================ #include using namespace metal; struct SkyPlaneVertex { float4 transformedPosition [[position]]; // The position in the world's coordinate system but centered on the player. float3 playerSpacePosition; }; struct SkyPlaneUniforms { float4 skyColor; float4 fogColor; float fogStart; float fogEnd; float size; float verticalOffset; float4x4 playerToClip; }; vertex SkyPlaneVertex skyPlaneVertex(uint id [[vertex_id]], constant float3 *vertices [[buffer(0)]], constant struct SkyPlaneUniforms &uniforms [[buffer(1)]]) { float3 position = vertices[id]; position *= uniforms.size / 2; position += float3(0, uniforms.verticalOffset, 0); return { .transformedPosition = float4(position, 1.0) * uniforms.playerToClip, .playerSpacePosition = position }; } fragment float4 skyPlaneFragment(SkyPlaneVertex vert [[stage_in]], constant struct SkyPlaneUniforms &uniforms [[buffer(0)]]) { float distance = length(vert.playerSpacePosition); float fogIntensity = smoothstep(uniforms.fogStart, uniforms.fogEnd, distance); return uniforms.skyColor * (1.0 - fogIntensity) + uniforms.fogColor * fogIntensity; } struct SunriseDiscVertex { float4 position [[position]]; float4 color; }; struct SunriseDiscUniforms { float4 color; float4x4 transformation; }; vertex SunriseDiscVertex sunriseDiscVertex(uint id [[vertex_id]], constant float3 *vertices [[buffer(0)]], constant struct SunriseDiscUniforms &uniforms [[buffer(1)]]) { float3 inPosition = vertices[id]; float4 color = uniforms.color; // Modify disc tilt based on color alpha inPosition.y *= uniforms.color.a; // Set the ring vertices' alphas to 0 color.a *= id == 0; float4 outPosition = float4(inPosition, 1.0) * uniforms.transformation; return { .position = outPosition, .color = color }; } fragment float4 sunriseDiscFragment(SunriseDiscVertex vert [[stage_in]]) { return vert.color; } struct CelestialBodyVertex { float4 position [[position]]; float2 uv; uint16_t index; }; struct CelestialBodyUniforms { float4x4 transformation; uint16_t textureIndex; float2 uvPosition; float2 uvSize; uint8_t type; }; #define SUN_TYPE 0 #define MOON_TYPE 1 constexpr sampler textureSampler (mag_filter::nearest, min_filter::nearest, mip_filter::linear); vertex CelestialBodyVertex celestialBodyVertex(uint id [[vertex_id]], constant float3 *vertices [[buffer(0)]], constant struct CelestialBodyUniforms &uniforms [[buffer(1)]]) { float3 position = vertices[id]; // The quad goes from -1 to 1 along the x and z axes, simply shift the xz coordinates to get the uvs. float2 uv = position.xz / 2.0 + float2(0.5, 0.5); uv *= uniforms.uvSize; uv += uniforms.uvPosition; return { .position = float4(position, 1.0) * uniforms.transformation, .uv = uv, .index = uniforms.textureIndex }; } fragment float4 celestialBodyFragment(CelestialBodyVertex in [[stage_in]], texture2d_array textureArray [[texture(0)]]) { return textureArray.sample(textureSampler, in.uv, in.index); } struct StarVertex { float4 position [[position]]; }; struct StarUniforms { float4x4 transformation; float brightness; }; vertex StarVertex starVertex(uint id [[vertex_id]], constant float3 *vertices [[buffer(0)]], constant struct StarUniforms &uniforms [[buffer(1)]]) { float3 position = vertices[id]; return { .position = float4(position, 1.0) * uniforms.transformation, }; } fragment float4 starFragment(StarVertex in [[stage_in]], constant struct StarUniforms &uniforms [[buffer(0)]]) { return float4(uniforms.brightness); } struct EndSkyInVertex { float3 position; float2 uv; }; struct EndSkyVertex { float4 position [[position]]; float2 uv; }; struct EndSkyUniforms { float4x4 transformation; uint16_t textureIndex; }; vertex EndSkyVertex endSkyVertex(uint id [[vertex_id]], constant struct EndSkyInVertex *vertices [[buffer(0)]], constant struct EndSkyUniforms &uniforms [[buffer(1)]]) { struct EndSkyInVertex in = vertices[id]; return { .position = float4(in.position, 1.0) * uniforms.transformation, .uv = in.uv }; } constexpr sampler endSkyTextureSampler (mag_filter::nearest, min_filter::nearest, mip_filter::linear, address::repeat); fragment float4 endSkyFragment(struct EndSkyVertex in [[stage_in]], texture2d_array textureArray [[texture(0)]], constant struct EndSkyUniforms &uniforms [[buffer(0)]]) { // The end sky is half the size of the texture palette and tiles 16 times across each face. // This is achieved by some UV maths and using fmod (I love fmod). float2 uv = fmod(in.uv * 16 / 2, 0.5); float4 color = textureArray.sample(endSkyTextureSampler, uv, uniforms.textureIndex); return color * (float4(40.0, 40.0, 40.0, 255.0) / 255.0); } ================================================ FILE: Sources/Core/Renderer/SkyBoxRenderer.swift ================================================ import MetalKit import DeltaCore /// The sky box consists of a sky plane (above the player), and a void plane /// (below the player if the player is below the void plane visibility threshold). /// It also includes distance fog cast on the planes which is what creates the /// smooth transition from the fog color at the horizon to the sky color overhead. public final class SkyBoxRenderer: Renderer { private let client: Client private let skyPlaneRenderPipelineState: MTLRenderPipelineState private let sunriseDiscRenderPipelineState: MTLRenderPipelineState private let celestialBodyRenderPipelineState: MTLRenderPipelineState private let starRenderPipelineState: MTLRenderPipelineState private let endSkyRenderPipelineState: MTLRenderPipelineState private let quadVertexBuffer: MTLBuffer private let quadIndexBuffer: MTLBuffer private var skyPlaneUniformsBuffer: MTLBuffer private var voidPlaneUniformsBuffer: MTLBuffer private let sunriseDiscVertexBuffer: MTLBuffer private let sunriseDiscIndexBuffer: MTLBuffer private var sunriseDiscUniformsBuffer: MTLBuffer private let sunUniformsBuffer: MTLBuffer private let moonUniformsBuffer: MTLBuffer private let starVertexBuffer: MTLBuffer private let starIndexBuffer: MTLBuffer private let starUniformsBuffer: MTLBuffer private let endSkyVertexBuffer: MTLBuffer private let endSkyIndexBuffer: MTLBuffer private let endSkyUniformsBuffer: MTLBuffer private let environmentTexturePalette: MetalTexturePalette /// The vertices for the sky plane quad (also used for the void plane). private static var quadVertices: [Vec3f] = [ Vec3f(-1, 0, 1), Vec3f(1, 0, 1), Vec3f(1, 0, -1), Vec3f(-1, 0, -1) ] /// The indices for the sky plane, void plane, sun, or moon quad. private static var quadIndices: [UInt32] = [0, 1, 2, 2, 3, 0] /// The vertical offset of the sky plane relative to the camera. private static let skyPlaneOffset: Float = 16 /// The sky plane's size in blocks. private static let skyPlaneSize: Float = 768 /// The void plane's size in blocks. private static let voidPlaneSize: Float = 768 /// The vertical offset of the void plane relative to the camera. private static let voidPlaneOffset: Float = -4 /// The sun's size in blocks. private static let sunSize: Float = 60 /// The sun's distance from the camera. private static let sunDistance: Float = 100 /// The moon's size in blocks. private static let moonSize: Float = 40 /// The moon's distance from the camera. private static let moonDistance: Float = 100 /// The y-level at which the void plane becomes visible in superflat worlds. private static let superFlatVoidPlaneVisibilityThreshold: Float = 1 /// The y-level at which the void plane becomes visible in all worlds other than /// superflat worlds. private static let defaultVoidPlaneVisibilityThreshold: Float = 63 public init(client: Client, device: MTLDevice, commandQueue: MTLCommandQueue) throws { self.client = client let library = try MetalUtil.loadDefaultLibrary(device) skyPlaneRenderPipelineState = try MetalUtil.makeRenderPipelineState( device: device, label: "SkyBoxRenderer.skyPlane", vertexFunction: try MetalUtil.loadFunction("skyPlaneVertex", from: library), fragmentFunction: try MetalUtil.loadFunction("skyPlaneFragment", from: library), blendingEnabled: false ) sunriseDiscRenderPipelineState = try MetalUtil.makeRenderPipelineState( device: device, label: "SkyBoxRenderer.sunriseDisc", vertexFunction: try MetalUtil.loadFunction("sunriseDiscVertex", from: library), fragmentFunction: try MetalUtil.loadFunction("sunriseDiscFragment", from: library), blendingEnabled: true ) celestialBodyRenderPipelineState = try MetalUtil.makeRenderPipelineState( device: device, label: "SkyBoxRenderer.celestialBody", vertexFunction: try MetalUtil.loadFunction("celestialBodyVertex", from: library), fragmentFunction: try MetalUtil.loadFunction("celestialBodyFragment", from: library), blendingEnabled: true ) { descriptor in // The sun and moon textures just have their alpha set to one so they require // different blending to usual. descriptor.colorAttachments[0].destinationRGBBlendFactor = .one } starRenderPipelineState = try MetalUtil.makeRenderPipelineState( device: device, label: "SkyBoxRenderer.stars", vertexFunction: try MetalUtil.loadFunction("starVertex", from: library), fragmentFunction: try MetalUtil.loadFunction("starFragment", from: library), blendingEnabled: true ) { descriptor in // The stars are rendered similarly to the sun and moon. They add // to the color instead of linearly blending with the colour because // they're shining through from behind instead of overlayed on top. descriptor.colorAttachments[0].destinationRGBBlendFactor = .one } endSkyRenderPipelineState = try MetalUtil.makeRenderPipelineState( device: device, label: "SkyBoxRenderer.endSky", vertexFunction: try MetalUtil.loadFunction("endSkyVertex", from: library), fragmentFunction: try MetalUtil.loadFunction("endSkyFragment", from: library), blendingEnabled: false ) // TODO: Make these both private (storage mode) once that's simpler to do (after MetalUtil // rewrite/replacement) quadVertexBuffer = try MetalUtil.makeBuffer( device, bytes: &Self.quadVertices, length: Self.quadVertices.count * MemoryLayout.stride, options: .storageModeShared, label: "quadVertexBuffer" ) quadIndexBuffer = try MetalUtil.makeBuffer( device, bytes: &Self.quadIndices, length: Self.quadIndices.count * MemoryLayout.stride, options: .storageModeShared, label: "quadIndexBuffer" ) skyPlaneUniformsBuffer = try MetalUtil.makeBuffer( device, length: MemoryLayout.stride, options: .storageModeShared, label: "skyPlaneUniformsBuffer" ) voidPlaneUniformsBuffer = try MetalUtil.makeBuffer( device, length: MemoryLayout.stride, options: .storageModeShared, label: "skyPlaneUniformsBuffer" ) var sunriseDiscVertices = Self.generateSunriseDiscVertices() sunriseDiscVertexBuffer = try MetalUtil.makeBuffer( device, bytes: &sunriseDiscVertices, length: sunriseDiscVertices.count * MemoryLayout.stride, options: .storageModeShared, label: "sunriseDiscVertexBuffer" ) var sunriseDiscIndices = Self.generateSunriseDiscIndices() sunriseDiscIndexBuffer = try MetalUtil.makeBuffer( device, bytes: &sunriseDiscIndices, length: sunriseDiscIndices.count * MemoryLayout.stride, options: .storageModeShared, label: "sunriseDiscIndexBuffer" ) sunriseDiscUniformsBuffer = try MetalUtil.makeBuffer( device, length: MemoryLayout.stride, options: .storageModeShared, label: "sunriseDiscUniformsBuffer" ) sunUniformsBuffer = try MetalUtil.makeBuffer( device, length: MemoryLayout.stride, options: .storageModeShared, label: "sunUniformsBuffer" ) moonUniformsBuffer = try MetalUtil.makeBuffer( device, length: MemoryLayout.stride, options: .storageModeShared, label: "moonUniformsBuffer" ) environmentTexturePalette = try MetalTexturePalette( palette: client.resourcePack.vanillaResources.environmentTexturePalette, device: device, commandQueue: commandQueue ) var starVertices = Self.generateStarVertices() starVertexBuffer = try MetalUtil.makeBuffer( device, bytes: &starVertices, length: starVertices.count * MemoryLayout.stride, options: .storageModeShared, label: "starVertexBuffer" ) var starIndices = Self.generateStarIndices(starCount: starVertices.count / 4) starIndexBuffer = try MetalUtil.makeBuffer( device, bytes: &starIndices, length: starIndices.count * MemoryLayout.stride, options: .storageModeShared, label: "starIndexBuffer" ) starUniformsBuffer = try MetalUtil.makeBuffer( device, length: MemoryLayout.stride, options: .storageModeShared, label: "starUniformsBuffer" ) var endSkyVertices = Self.generateEndSkyVertices() endSkyVertexBuffer = try MetalUtil.makeBuffer( device, bytes: &endSkyVertices, length: endSkyVertices.count * MemoryLayout.stride, options: .storageModeShared, label: "endSkyVertexBuffer" ) var endSkyIndices = Self.generateEndSkyIndices() endSkyIndexBuffer = try MetalUtil.makeBuffer( device, bytes: &endSkyIndices, length: endSkyIndices.count * MemoryLayout.stride, options: .storageModeShared, label: "endSkyIndexBuffer" ) endSkyUniformsBuffer = try MetalUtil.makeBuffer( device, length: MemoryLayout.stride, options: .storageModeShared, label: "endSkyUniformsBuffer" ) } public func render( view: MTKView, encoder: MTLRenderCommandEncoder, commandBuffer: MTLCommandBuffer, worldToClipUniformsBuffer: MTLBuffer, camera: Camera ) throws { if client.game.world.dimension.isEnd { let texturePalette = client.resourcePack.vanillaResources.environmentTexturePalette let identifier = Identifier(name: "environment/end_sky") guard let textureIndex = texturePalette.textureIndex(for: identifier) else { throw RenderError.missingTexture(identifier) } var endSkyUniforms = EndSkyUniforms( transformation: camera.playerToCamera * camera.cameraToClip, textureIndex: UInt16(textureIndex) ) endSkyUniformsBuffer.contents().copyMemory( from: &endSkyUniforms, byteCount: MemoryLayout.stride ) encoder.setRenderPipelineState(endSkyRenderPipelineState) encoder.setCullMode(.none) encoder.setVertexBuffer(endSkyVertexBuffer, offset: 0, index: 0) encoder.setVertexBuffer(endSkyUniformsBuffer, offset: 0, index: 1) encoder.setFragmentBuffer(endSkyUniformsBuffer, offset: 0, index: 0) encoder.setFragmentTexture(environmentTexturePalette.arrayTexture, index: 0) encoder.drawIndexedPrimitives( type: .triangle, indexCount: endSkyIndexBuffer.length / MemoryLayout.stride, indexType: .uint32, indexBuffer: endSkyIndexBuffer, indexBufferOffset: 0 ) return } // Only the overworld has a sky plane. guard client.game.world.dimension.isOverworld else { return } // Below 4 render distance the sky plane, void plane, and sunrises/sunsets // don't get rendered anymore. guard client.configuration.render.renderDistance >= 4 else { return } let playerToClip = camera.playerToCamera * camera.cameraToClip // When the render distance is above 2, move the fog 1 chunk closer to conceal // more of the world edge. let renderDistance = max(client.configuration.render.renderDistance - 1, 2) let position = camera.ray.origin let blockPosition = BlockPosition(x: Int(position.x), y: Int(position.y), z: Int(position.z)) let skyColor = client.game.world.getSkyColor(at: blockPosition) let fogColor = client.game.world.getFogColor( forViewerWithRay: camera.ray, withRenderDistance: renderDistance ) // Render the sky plane. var skyPlaneUniforms = SkyPlaneUniforms( skyColor: Vec4f(skyColor, 1), fogColor: Vec4f(fogColor, 1), fogStart: 0, fogEnd: Float(renderDistance * Chunk.width), size: Self.skyPlaneSize, verticalOffset: Self.skyPlaneOffset, playerToClip: playerToClip ) skyPlaneUniformsBuffer.contents().copyMemory( from: &skyPlaneUniforms, byteCount: MemoryLayout.stride ) encoder.setRenderPipelineState(skyPlaneRenderPipelineState) encoder.setVertexBuffer(quadVertexBuffer, offset: 0, index: 0) encoder.setVertexBuffer(skyPlaneUniformsBuffer, offset: 0, index: 1) encoder.setFragmentBuffer(skyPlaneUniformsBuffer, offset: 0, index: 0) encoder.drawIndexedPrimitives( type: .triangle, indexCount: Self.quadIndices.count, indexType: .uint32, indexBuffer: quadIndexBuffer, indexBufferOffset: 0 ) // Render the sunrise/sunset disc if applicable. let daylightCyclePhase = client.game.world.getDaylightCyclePhase() switch daylightCyclePhase { case let .sunrise(color), let .sunset(color): let rotation: Mat4x4f if daylightCyclePhase.isSunrise { rotation = MatrixUtil.identity } else { rotation = MatrixUtil.rotationMatrix(.pi, around: .y) } let transformation = rotation * camera.playerToCamera * camera.cameraToClip var sunriseDiscUniforms = SunriseDiscUniforms( color: color, transformation: transformation ) sunriseDiscUniformsBuffer.contents().copyMemory( from: &sunriseDiscUniforms, byteCount: MemoryLayout.stride ) encoder.setRenderPipelineState(sunriseDiscRenderPipelineState) encoder.setVertexBuffer(sunriseDiscVertexBuffer, offset: 0, index: 0) encoder.setVertexBuffer(sunriseDiscUniformsBuffer, offset: 0, index: 1) encoder.drawIndexedPrimitives( type: .triangle, indexCount: sunriseDiscIndexBuffer.length / MemoryLayout.stride, indexType: .uint32, indexBuffer: sunriseDiscIndexBuffer, indexBufferOffset: 0 ) case .day, .night: break } // TODO: Make a similar system to the GUITexturePalette system where certain // textures are guaranteed to be present. Also have a way to get UV bounds // for specific 'sprites'. // Render the sun let sunTextureIndex = UInt16( environmentTexturePalette.textureIndex( for: Identifier(name: "environment/sun") )! ) var sunUniforms = CelestialBodyUniforms( transformation: MatrixUtil.scalingMatrix(Self.sunSize / 2) * MatrixUtil.translationMatrix(Vec3f(0, Self.sunDistance, 0)) * MatrixUtil.rotationMatrix(-.pi / 2, around: .y) * MatrixUtil.rotationMatrix(client.game.world.getSunAngleRadians(), around: .z) * playerToClip, textureIndex: sunTextureIndex, uvPosition: Vec2f(0, 0), uvSize: Vec2f(1/8, 1/8), type: .sun ) sunUniformsBuffer.contents().copyMemory( from: &sunUniforms, byteCount: MemoryLayout.stride ) encoder.setRenderPipelineState(celestialBodyRenderPipelineState) encoder.setVertexBuffer(quadVertexBuffer, offset: 0, index: 0) encoder.setVertexBuffer(sunUniformsBuffer, offset: 0, index: 1) encoder.setFragmentTexture(environmentTexturePalette.arrayTexture, index: 0) encoder.drawIndexedPrimitives( type: .triangle, indexCount: Self.quadIndices.count, indexType: .uint32, indexBuffer: quadIndexBuffer, indexBufferOffset: 0 ) // Render the moon let moonPhase = client.game.world.getMoonPhase() let moonUVPosition = Vec2f( Float(moonPhase % 4) * 1/8, Float(moonPhase / 4) * 1/8 ) let moonTextureIndex = UInt16( environmentTexturePalette.textureIndex( for: Identifier(name: "environment/moon_phases") )! ) var moonUniforms = CelestialBodyUniforms( transformation: MatrixUtil.scalingMatrix(Self.moonSize / 2) * MatrixUtil.translationMatrix(Vec3f(0, Self.moonDistance, 0)) * MatrixUtil.rotationMatrix(-.pi / 2, around: .y) * MatrixUtil.rotationMatrix(client.game.world.getSunAngleRadians() + .pi, around: .z) * playerToClip, textureIndex: moonTextureIndex, uvPosition: moonUVPosition, uvSize: Vec2f(1/8, 1/8), type: .sun ) moonUniformsBuffer.contents().copyMemory( from: &moonUniforms, byteCount: MemoryLayout.stride ) encoder.setVertexBuffer(moonUniformsBuffer, offset: 0, index: 1) encoder.drawIndexedPrimitives( type: .triangle, indexCount: Self.quadIndices.count, indexType: .uint32, indexBuffer: quadIndexBuffer, indexBufferOffset: 0 ) let starBrightness = client.game.world.getStarBrightness() if starBrightness > 0 { var starUniforms = StarUniforms( transformation: MatrixUtil.rotationMatrix(-.pi / 2, around: .y) * MatrixUtil.rotationMatrix(client.game.world.getSunAngleRadians(), around: .z) * playerToClip, brightness: starBrightness ) starUniformsBuffer.contents().copyMemory( from: &starUniforms, byteCount: MemoryLayout.stride ) encoder.setRenderPipelineState(starRenderPipelineState) encoder.setVertexBuffer(starVertexBuffer, offset: 0, index: 0) encoder.setVertexBuffer(starUniformsBuffer, offset: 0, index: 1) encoder.setFragmentBuffer(starUniformsBuffer, offset: 0, index: 0) encoder.drawIndexedPrimitives( type: .triangle, indexCount: starIndexBuffer.length / MemoryLayout.stride, indexType: .uint32, indexBuffer: starIndexBuffer, indexBufferOffset: 0 ) } // Render the void plane if visible. let voidPlaneVisibilityThreshold = client.game.world.isFlat ? Self.superFlatVoidPlaneVisibilityThreshold : Self.defaultVoidPlaneVisibilityThreshold if position.y <= voidPlaneVisibilityThreshold { var voidPlaneUniforms = SkyPlaneUniforms( skyColor: Vec4f(0, 0, 0, 1), fogColor: Vec4f(fogColor, 1), fogStart: 0, fogEnd: Float(renderDistance * Chunk.width), size: Self.voidPlaneSize, verticalOffset: Self.voidPlaneOffset, playerToClip: playerToClip ) voidPlaneUniformsBuffer.contents().copyMemory( from: &voidPlaneUniforms, byteCount: MemoryLayout.stride ) encoder.setRenderPipelineState(skyPlaneRenderPipelineState) encoder.setVertexBuffer(quadVertexBuffer, offset: 0, index: 0) encoder.setVertexBuffer(voidPlaneUniformsBuffer, offset: 0, index: 1) encoder.setFragmentBuffer(voidPlaneUniformsBuffer, offset: 0, index: 0) encoder.drawIndexedPrimitives( type: .triangle, indexCount: Self.quadIndices.count, indexType: .uint32, indexBuffer: quadIndexBuffer, indexBufferOffset: 0 ) } } /// Generates the vertices for a triangle fan. Think of it like a pizza, which /// has a single central vertex which is touched by one corner of every slice. /// The triangle fan generated has 16 slices, with the central vertex being /// vertex 0, and the next 16 vertices forming a clockwise ring. static func generateSunriseDiscVertices() -> [Vec3f] { var vertices: [Vec3f] = [Vec3f(100, 0, 0)] for i in 0..<16 { let t = Float(i) / 16 * 2 * .pi vertices.append(Vec3f( 120 * Foundation.cos(t), 40 * Foundation.cos(t), 120 * Foundation.sin(t) )) } return vertices } /// Generates the indices for a triangle fan. Think of it like a pizza, which /// has a single central vertex which is touched by one corner of every slice. /// The triangle fan is assumed to have 16 slices, with the central vertex /// being vertex 0, and the next 16 vertices forming a clockwise ring. static func generateSunriseDiscIndices() -> [UInt32] { var indices: [UInt32] = [] for i in 0..<16 { indices.append(contentsOf: [ 0, UInt32(i) + 1, ((UInt32(i) + 1) % 16) + 1 ]) } return indices } /// Generates the vertices for the star mesh. static func generateStarVertices() -> [Vec3f] { let baseVertices: [Vec4f] = [ Vec4f(-1, 0, -1, 1), Vec4f(1, 0, -1, 1), Vec4f(1, 0, 1, 1), Vec4f(-1, 0, 1, 1) ] var vertices: [Vec3f] = [] var random = Random(10842) for _ in 0..<1500 { let direction = Vec3f( random.nextFloat(), random.nextFloat(), random.nextFloat() ) * 2 - 1 // Generate the size before skipping the iteration because otherwise // the random number generator gets out of sync with what it would be // for Vanilla let starSize = 0.15 + random.nextFloat() * 0.1 let magnitude = direction.magnitude guard magnitude > 0.0001, magnitude < 1 else { continue } let yaw = -Foundation.atan2(direction.x, direction.z) let horizontalMagnitude = Foundation.sqrt( direction.x * direction.x + direction.z * direction.z ) let pitch = Foundation.atan2(horizontalMagnitude, direction.y) // Using `nextDouble` to have the same behaviour as Vanilla (it matters because of the // random number generator). let starRotation = Float(random.nextDouble() * 2 * .pi) let transformation = MatrixUtil.scalingMatrix(starSize) * MatrixUtil.rotationMatrix(-starRotation, around: .y) * MatrixUtil.translationMatrix(Vec3f(0, 100, 0)) * MatrixUtil.rotationMatrix(pitch, around: .x) * MatrixUtil.rotationMatrix(yaw, around: .y) vertices.append(contentsOf: baseVertices.map { vertex in let position = vertex * transformation return Vec3f( position.x, position.y, position.z ) / position.w }) } return vertices } /// Generates the indices for the star mesh. static func generateStarIndices(starCount: Int) -> [UInt32] { var indices: [UInt32] = [] for i in 0.. [EndSkyVertex] { return [ // North EndSkyVertex(position: Vec3f(-100, 100, -100), uv: Vec2f(0, 0)), EndSkyVertex(position: Vec3f(100, 100, -100), uv: Vec2f(1, 0)), EndSkyVertex(position: Vec3f(100, -100, -100), uv: Vec2f(1, 1)), EndSkyVertex(position: Vec3f(-100, -100, -100), uv: Vec2f(0, 1)), // South EndSkyVertex(position: Vec3f(-100, -100, 100), uv: Vec2f(0, 0)), EndSkyVertex(position: Vec3f(100, -100, 100), uv: Vec2f(1, 0)), EndSkyVertex(position: Vec3f(100, 100, 100), uv: Vec2f(1, 1)), EndSkyVertex(position: Vec3f(-100, 100, 100), uv: Vec2f(0, 1)), // East EndSkyVertex(position: Vec3f(100, -100, -100), uv: Vec2f(0, 0)), EndSkyVertex(position: Vec3f(100, 100, -100), uv: Vec2f(1, 0)), EndSkyVertex(position: Vec3f(100, 100, 100), uv: Vec2f(1, 1)), EndSkyVertex(position: Vec3f(100, -100, 100), uv: Vec2f(0, 1)), // West EndSkyVertex(position: Vec3f(-100, 100, -100), uv: Vec2f(0, 0)), EndSkyVertex(position: Vec3f(-100, -100, -100), uv: Vec2f(1, 0)), EndSkyVertex(position: Vec3f(-100, -100, 100), uv: Vec2f(1, 1)), EndSkyVertex(position: Vec3f(-100, 100, 100), uv: Vec2f(0, 1)), // Above EndSkyVertex(position: Vec3f(100, 100, 100), uv: Vec2f(0, 0)), EndSkyVertex(position: Vec3f(-100, 100, 100), uv: Vec2f(1, 0)), EndSkyVertex(position: Vec3f(-100, 100, -100), uv: Vec2f(1, 1)), EndSkyVertex(position: Vec3f(100, 100, -100), uv: Vec2f(0, 1)), // Before EndSkyVertex(position: Vec3f(-100, -100, -100), uv: Vec2f(0, 0)), EndSkyVertex(position: Vec3f(100, -100, -100), uv: Vec2f(1, 0)), EndSkyVertex(position: Vec3f(100, -100, 100), uv: Vec2f(1, 1)), EndSkyVertex(position: Vec3f(-100, -100, 100), uv: Vec2f(0, 1)), ] } static func generateEndSkyIndices() -> [UInt32] { var indices: [UInt32] = [] for i in 0..<6 { indices.append(contentsOf: [ 0, 1, 2, 2, 3, 0 ].map { UInt32($0 + i * 4) }) } return indices } } ================================================ FILE: Sources/Core/Renderer/SkyPlaneUniforms.swift ================================================ import FirebladeMath public struct SkyPlaneUniforms { public var skyColor: Vec4f public var fogColor: Vec4f public var fogStart: Float public var fogEnd: Float public var size: Float public var verticalOffset: Float public var playerToClip: Mat4x4f } ================================================ FILE: Sources/Core/Renderer/StarUniforms.swift ================================================ import FirebladeMath /// Uniforms for the star mesh rendered at night. public struct StarUniforms { public var transformation: Mat4x4f public var brightness: Float } ================================================ FILE: Sources/Core/Renderer/SunriseDiscUniforms.swift ================================================ import FirebladeMath // TODO: Maybe to be more clear that it's not just sunrise, but sunset too, the // sunrise disc could be named more technically, like the RayleighScatteringDisc // or something (I don't like that one though, it loses clarity in other ways). /// The uniforms for the sunrise/sunset disc. public struct SunriseDiscUniforms { public var color: Vec4f public var transformation: Mat4x4f } ================================================ FILE: Sources/Core/Renderer/Util/MetalUtil.swift ================================================ import Metal public enum MetalUtil { /// Makes a render pipeline state with the given properties. public static func makeRenderPipelineState( device: MTLDevice, label: String, vertexFunction: MTLFunction, fragmentFunction: MTLFunction, blendingEnabled: Bool, editDescriptor: ((MTLRenderPipelineDescriptor) -> Void)? = nil, isOffScreenPass: Bool = true ) throws -> MTLRenderPipelineState { let descriptor = MTLRenderPipelineDescriptor() descriptor.label = label descriptor.vertexFunction = vertexFunction descriptor.fragmentFunction = fragmentFunction descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm descriptor.depthAttachmentPixelFormat = .depth32Float // Optionally include accumulation and revealage buffers for order independent transparency if isOffScreenPass { descriptor.colorAttachments[1].pixelFormat = .bgra8Unorm descriptor.colorAttachments[2].pixelFormat = .r8Unorm } if blendingEnabled { descriptor.colorAttachments[0].isBlendingEnabled = true descriptor.colorAttachments[0].rgbBlendOperation = .add descriptor.colorAttachments[0].alphaBlendOperation = .add descriptor.colorAttachments[0].sourceRGBBlendFactor = .sourceAlpha descriptor.colorAttachments[0].sourceAlphaBlendFactor = .zero descriptor.colorAttachments[0].destinationRGBBlendFactor = .oneMinusSourceAlpha descriptor.colorAttachments[0].destinationAlphaBlendFactor = .zero } editDescriptor?(descriptor) do { return try device.makeRenderPipelineState(descriptor: descriptor) } catch { throw RenderError.failedToCreateRenderPipelineState(error, label: label) } } /// Loads the default metal library from the app bundle. /// /// The default library is at `DeltaClient.app/Contents/Resources/DeltaCore_DeltaCore.bundle/Resources/default.metallib`. public static func loadDefaultLibrary(_ device: MTLDevice) throws -> MTLLibrary { #if os(macOS) let bundlePath = "Contents/Resources/DeltaCore_DeltaRenderer.bundle" #elseif os(iOS) || os(tvOS) let bundlePath = "DeltaCore_DeltaRenderer.bundle" #else #error("Unsupported platform, unknown DeltaCore bundle location") #endif guard let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent(bundlePath)) else { throw RenderError.failedToGetBundle } guard let libraryURL = bundle.url(forResource: "default", withExtension: "metallib") else { throw RenderError.failedToLocateMetallib } do { return try device.makeLibrary(URL: libraryURL) } catch { throw RenderError.failedToCreateMetallib(error) } } /// Loads a metal function from the given library. /// - Parameters: /// - name: Name of the function. /// - library: Library containing the function. /// - Returns: The function. public static func loadFunction(_ name: String, from library: MTLLibrary) throws -> MTLFunction { guard let function = library.makeFunction(name: name) else { log.warning("Failed to load shader: '\(name)'") throw RenderError.failedToLoadShaders } return function } /// Creates a populated buffer. /// - Parameters: /// - device: Device to create the buffer with. /// - bytes: Bytes to populate the buffer with. /// - length: Length of the buffer. /// - options: Resource options for the buffer /// - label: Label to give the buffer. /// - Returns: A new buffer. public static func makeBuffer( _ device: MTLDevice, bytes: UnsafeRawPointer, length: Int, options: MTLResourceOptions, label: String? = nil ) throws -> MTLBuffer { guard let buffer = device.makeBuffer(bytes: bytes, length: length, options: options) else { throw RenderError.failedToCreateBuffer(label: label) } buffer.label = label return buffer } /// Creates a buffer for sampling the requested set of counters. /// - Parameters: /// - device: The device that sampling will be performed on. /// - commonCounterSet: The counter set that the buffer will be used to sample. /// - sampleCount: The size of sampling buffer to create. /// - Returns: A buffer for storing counter samples. public static func makeCounterSampleBuffer( _ device: MTLDevice, counterSet commonCounterSet: MTLCommonCounterSet, sampleCount: Int ) throws -> MTLCounterSampleBuffer { var counterSet: MTLCounterSet? for deviceCounterSet in device.counterSets ?? [] { if deviceCounterSet.name.caseInsensitiveCompare(commonCounterSet.rawValue) == .orderedSame { counterSet = deviceCounterSet break } } guard let counterSet = counterSet else { throw RenderError.failedToGetCounterSet(commonCounterSet.rawValue) } let descriptor = MTLCounterSampleBufferDescriptor() descriptor.counterSet = counterSet descriptor.storageMode = .shared descriptor.sampleCount = sampleCount do { return try device.makeCounterSampleBuffer(descriptor: descriptor) } catch { throw RenderError.failedToMakeCounterSampleBuffer(error) } } /// Creates an empty buffer. /// - Parameters: /// - device: Device to create the buffer with. /// - length: Length of the buffer. /// - options: Resource options for the buffer. /// - label: Label to give the buffer. /// - Returns: An empty buffer. public static func makeBuffer( _ device: MTLDevice, length: Int, options: MTLResourceOptions, label: String? = nil ) throws -> MTLBuffer { guard let buffer = device.makeBuffer(length: length, options: options) else { throw RenderError.failedToCreateBuffer(label: label) } buffer.label = label return buffer } /// Creates a simple depth stencil state. /// - Parameters: /// - device: Device to create the state with. /// - readOnly: If `true`, the depth texture will not be written to. /// - Returns: A depth stencil state. public static func createDepthState( device: MTLDevice, readOnly: Bool = false ) throws -> MTLDepthStencilState { let depthDescriptor = MTLDepthStencilDescriptor() depthDescriptor.depthCompareFunction = .lessEqual depthDescriptor.isDepthWriteEnabled = !readOnly guard let depthState = device.makeDepthStencilState(descriptor: depthDescriptor) else { throw RenderError.failedToCreateWorldDepthStencilState } return depthState } /// Creates a custom render pass descriptor with default clear / store actions. /// - Parameter device: Device to create the descriptor with. /// - Returns: A render pass descriptor with custom render targets. public static func createRenderPassDescriptor( _ device: MTLDevice, targetRenderTexture: MTLTexture, targetDepthTexture: MTLTexture, clearColour: MTLClearColor = MTLClearColor(red: 1, green: 1, blue: 1, alpha: 1) ) -> MTLRenderPassDescriptor { let renderPassDescriptor = MTLRenderPassDescriptor() renderPassDescriptor.colorAttachments[0].texture = targetRenderTexture renderPassDescriptor.colorAttachments[0].clearColor = clearColour renderPassDescriptor.colorAttachments[0].loadAction = MTLLoadAction.clear renderPassDescriptor.colorAttachments[0].storeAction = MTLStoreAction.store renderPassDescriptor.depthAttachment.texture = targetDepthTexture renderPassDescriptor.depthAttachment.loadAction = MTLLoadAction.clear renderPassDescriptor.depthAttachment.storeAction = MTLStoreAction.store return renderPassDescriptor } public static func createTexture( device: MTLDevice, width: Int, height: Int, pixelFormat: MTLPixelFormat, editDescriptor: ((MTLTextureDescriptor) -> Void)? = nil ) throws -> MTLTexture { let descriptor = MTLTextureDescriptor() descriptor.usage = [.shaderRead, .renderTarget] descriptor.width = width descriptor.height = height descriptor.pixelFormat = pixelFormat editDescriptor?(descriptor) guard let texture = device.makeTexture(descriptor: descriptor) else { throw RenderError.failedToUpdateRenderTargetSize } return texture } /// Creates a buffer on the GPU containing a given array. Reuses the supplied private buffer if it's big enough. /// - Returns: A new private buffer. public static func createPrivateBuffer( labelled label: String = "buffer", containing items: [T], reusing existingBuffer: MTLBuffer? = nil, device: MTLDevice, commandQueue: MTLCommandQueue ) throws -> MTLBuffer { precondition( existingBuffer?.storageMode == .private || existingBuffer == nil, "existingBuffer must have a storageMode of private" ) // First copy the array to a scratch buffer (accessible from both CPU and GPU) let bufferSize = MemoryLayout.stride * items.count guard let sharedBuffer = device.makeBuffer( bytes: items, length: bufferSize, options: [.storageModeShared] ) else { throw RenderError.failedToCreateBuffer(label: label) } // Create a private buffer (only accessible from GPU) or reuse the existing buffer if possible let privateBuffer: MTLBuffer if let existingBuffer = existingBuffer, existingBuffer.length >= bufferSize { privateBuffer = existingBuffer } else { guard let buffer = device.makeBuffer(length: bufferSize, options: [.storageModePrivate]) else { throw RenderError.failedToCreateBuffer(label: label) } privateBuffer = buffer } privateBuffer.label = label guard let commandBuffer = commandQueue.makeCommandBuffer(), let encoder = commandBuffer.makeBlitCommandEncoder() else { throw RenderError.failedToCreateBlitCommandEncoder } // Encode and commit a blit operation to copy the contents of the scratch buffer into the private buffer encoder.copy( from: sharedBuffer, sourceOffset: 0, to: privateBuffer, destinationOffset: 0, size: bufferSize ) encoder.endEncoding() commandBuffer.commit() return privateBuffer } } ================================================ FILE: Sources/Core/Renderer/World/BlockVertex.swift ================================================ import Foundation /// The vertex format used by the chunk block shader. public struct BlockVertex { var x: Float var y: Float var z: Float var u: Float var v: Float var r: Float var g: Float var b: Float var a: Float var skyLightLevel: UInt8 var blockLightLevel: UInt8 var textureIndex: UInt16 var isTransparent: Bool } ================================================ FILE: Sources/Core/Renderer/World/LightMap.swift ================================================ import Foundation import Metal import FirebladeMath // TODO: Move Vec3 and extensions of FirebladeMath into FirebladeMath to avoid this unnecessary import import DeltaCore // TODO: Make LightMap an ECS singleton struct LightMap { static let gamma: Double = 0 var pixels: [Vec3] var blockFlicker: Double = 1 var ambientLight: Double var baseLevels: [Double] var lastFlickerUpdateTick: Int? var hasChanged = true init(ambientLight: Double) { baseLevels = Self.generateBaseLevels(ambientLight) self.ambientLight = ambientLight pixels = [] for _ in 0..(pixel) } } } mutating func updateBlockFlicker(_ tick: Int) { let updateCount: Int if let lastFlickerUpdateTick = lastFlickerUpdateTick { updateCount = tick - lastFlickerUpdateTick } else { updateCount = 1 } guard updateCount != 0 else { return } var rng = Random() for _ in 0.. MTLBuffer { defer { hasChanged = false } let byteCount = LightLevel.levelCount * LightLevel.levelCount * MemoryLayout>.stride if let previousBuffer = previousBuffer { if hasChanged { previousBuffer.contents().copyMemory(from: &pixels, byteCount: byteCount) } return previousBuffer } else { return try MetalUtil.makeBuffer( device, bytes: &pixels, length: byteCount, options: .storageModeShared, label: "lightMap" ) } } static func index(_ skyLightLevel: Int, _ blockLightLevel: Int) -> Int { return skyLightLevel * LightLevel.levelCount + blockLightLevel } static func inverseGamma(_ value: Double) -> Double { let value = 1 - value return 1 - value * value * value * value } static func generateBaseLevels(_ ambientLight: Double) -> [Double] { var levels: [Double] = [] for i in 0.. Double { // TODO: Implement the effect of rain and thunder on sun brightness var brightness = Double(Foundation.cos(sunAngleRadians) * 2 + 0.2) brightness = MathUtil.clamp(brightness, 0, 1) return brightness * 0.8 + 0.2 } } ================================================ FILE: Sources/Core/Renderer/World/Visibility/ChunkSectionFace.swift ================================================ import DeltaCore /// Used by ``ChunkSectionFaceConnectivity`` to efficiently identify pairs of faces. /// /// If the values of any two faces are added together, the result is a unique integer /// that represents that pair of faces. /// /// ``ChunkSectionFaceConnectivity`` uses this property to efficiently store/access /// whether a given pair of faces is connected. A bit field is used where the value /// for each pair is the offset of a bit representing whether those two faces are /// connected. /// /// Its cases are in the same order as ``DirectionSet``. public enum ChunkSectionFace: Int, CaseIterable { case north = 0 case south = 1 case east = 2 case west = 4 case up = 7 case down = 12 public static var faces: [ChunkSectionFace] = [ .north, .south, .east, .west, .up, .down] public static func forDirection(_ direction: Direction) -> ChunkSectionFace { switch direction { case .down: return .down case .up: return .up case .north: return .north case .south: return .south case .west: return .west case .east: return .east } } } ================================================ FILE: Sources/Core/Renderer/World/Visibility/ChunkSectionFaceConnectivity.swift ================================================ import DeltaCore /// Stores which pairs faces in a chunk section are connected to each other. Not threadsafe. /// /// ``setConnected(_:_:)`` and ``setDisconnected(_:_:)`` are separate functions because this allows /// branching to be eliminated and in most cases the parameter specifying whether they are connected /// or not would be hardcoded anyway. /// /// The efficiency of this storage method comes from using a bit field as the underlying storage and /// using ``ChunkSectionFace``'s raw values to efficiently identify each pair of faces. See /// ``ChunkSectionFace`` for a more detailed explanation. public struct ChunkSectionFaceConnectivity: Equatable { // MARK: Public properties /// The connectivity for a fully connected chunk section. public static let fullyConnected = ChunkSectionFaceConnectivity(bitField: 0xffffffff) // MARK: Private properties /// The underlying storage for the connectivity information. private var bitField: UInt32 = 0 // MARK: Init /// Creates an empty connectivity graph where none of the faces are connected. public init() {} /// Only use if you know what you're doing. /// - Parameter bitField: Initial value of the underlying bitfield. private init(bitField: UInt32) { self.bitField = bitField } // MARK: Public methods /// Marks a pair of faces as connected. /// - Parameters: /// - firstFace: The first face. /// - secondFace: The seconds face. public mutating func setConnected(_ firstFace: ChunkSectionFace, _ secondFace: ChunkSectionFace) { let hashValue = firstFace.rawValue + secondFace.rawValue bitField |= 1 << hashValue } /// Marks a pair of faces as disconnected. /// - Parameters: /// - firstFace: The first face. /// - secondFace: The second face. public mutating func setDisconnected(_ firstFace: ChunkSectionFace, _ secondFace: ChunkSectionFace) { let hashValue = firstFace.rawValue + secondFace.rawValue bitField ^= ~(1 << hashValue) } /// Gets whether a pair of faces are connected or not. /// - Parameters: /// - firstFace: The first face. /// - secondFace: The second face. /// - Returns: Whether the faces are connected or not. public func areConnected(_ firstFace: ChunkSectionFace, _ secondFace: ChunkSectionFace) -> Bool { let hashValue = firstFace.rawValue + secondFace.rawValue return bitField & (1 << hashValue) != 0 } } ================================================ FILE: Sources/Core/Renderer/World/Visibility/ChunkSectionVoxelGraph.swift ================================================ import DeltaCore /// A 3d data structure used for flood filling chunk sections. Each 'voxel' is represented by an integer. /// /// The graph is initialised with `true` representing voxels that cannot be seen through whatsoever and `false` representing all other voxels. /// ``calculateConnectivity()`` figures out which faces are connected. When faces aren't connected it means that a ray cannot be created /// that enters through one of the faces and out the other. When faces are connected it doesn't necessarily mean such a ray exists, only that it might exist. /// /// Flood fills fill connected volumes of `false` with `true` and record which faces the fill reached. If two faces are reached by the /// same fill, they are counted as connected. public struct ChunkSectionVoxelGraph { /// The width, height and depth of the image (they're all equal to this number). public let dimension: Int /// The number of voxels per layer of the graph (``dimension`` squared). public let voxelsPerLayer: Int /// The initial number of voxels that weren't set to 0. private var initialVoxelCount: Int /// Stores the image's voxels. Indexed by `y * voxelsPerLayer + z * dimension + x`. private var voxels: [Bool] /// Used to efficiently set voxels values in ``voxels``. Will be invalid in copies of the graph (because it's a struct). private var mutableVoxelsPointer: UnsafeMutableBufferPointer // MARK: Private methods /// Creates a new graph of the section for figuring out face connectivity. /// - Parameter section: Section to create graph for. /// - Parameter blockModelPalette: Used to determine which blocks are solid. public init(for section: Chunk.Section, blockModelPalette: BlockModelPalette) { assert( Chunk.Section.width == Chunk.Section.height && Chunk.Section.height == Chunk.Section.depth, "Attempted to create a ChunkSectionVoxelGraph from non-cubic chunk section") dimension = Chunk.Section.width voxelsPerLayer = dimension * dimension assert(dimension.isPowerOfTwo, "Attempted to initialise a ChunkSectionVoxelGraph with a dimension that isn't a power of two.") initialVoxelCount = 0 voxels = [] voxels.reserveCapacity(section.blocks.count) for block in section.blocks { let isFullyOpaque = blockModelPalette.isBlockFullyOpaque(Int(block)) voxels.append(isFullyOpaque) if isFullyOpaque { initialVoxelCount += 1 } } mutableVoxelsPointer = self.voxels.withUnsafeMutableBufferPointer { $0 } assert( dimension * dimension * dimension == voxels.count, "Attempted to initialise a ChunkSectionVoxelGraph with an invalid number of voxels for its dimension (dimension=\(dimension), voxel_count=\(voxels.count)" ) } // MARK: Public methods /// Gets information about the connectivity of the section's faces. See ``ChunkSectionVoxelGraph``. /// - Returns: Information about which pairs of faces are connected. public mutating func calculateConnectivity() -> ChunkSectionFaceConnectivity { if initialVoxelCount == 0 { return ChunkSectionFaceConnectivity.fullyConnected } var connectivity = ChunkSectionFaceConnectivity() // Make sure that the pointer is still valid mutableVoxelsPointer = voxels.withUnsafeMutableBufferPointer { $0 } let emptyVoxelCoordinates = emptyVoxelCoordinates() var nextEmptyVoxel = 0 outerLoop: while true { var seedX: Int? var seedY: Int? var seedZ: Int? // Find the next voxel that hasn't been filled yet while true { if nextEmptyVoxel == emptyVoxelCoordinates.count { break outerLoop } let (x, y, z) = emptyVoxelCoordinates[nextEmptyVoxel] nextEmptyVoxel += 1 if getVoxel(x: x, y: y, z: z) == false { seedX = x seedY = y seedZ = z break } } // Flood fill the section (starting at the seed voxel) and update the connectivity // of the section depending on which faces the fill reached. if let seedX = seedX, let seedY = seedY, let seedZ = seedZ { var group = DirectionSet() iterativeFloodFill(x: seedX, y: seedY, z: seedZ, group: &group) for i in 0..<5 { for j in (i+1)..<6 { let first = Direction.allDirections[i] let second = Direction.allDirections[j] if group.contains(first) && group.contains(second) { let first = ChunkSectionFace.allCases[i] let second = ChunkSectionFace.allCases[j] connectivity.setConnected(first, second) } } } } else { break } } return connectivity } /// Gets the value of the given voxel. /// /// Does not validate the position. Behaviour is undefined if the position is not inside the chunk. /// - Parameters: /// - x: x coordinate of the voxel. /// - y: y coordinate of the voxel. /// - z: z coordinate of the voxel. /// - Returns: Current value of the voxel. private func getVoxel(x: Int, y: Int, z: Int) -> Bool { return voxels.withUnsafeBufferPointer { $0[(y &* dimension &+ z) &* dimension &+ x] } } /// Sets the value of the given voxel. /// - Parameters: /// - x: x coordinate of the voxel. /// - y: y coordinate of the voxel. /// - z: z coordiante of the voxel. /// - value: New value for the voxel. private mutating func setVoxel(x: Int, y: Int, z: Int, to value: Bool) { mutableVoxelsPointer[(y &* dimension &+ z) &* dimension &+ x] = value } /// Iteratively flood fills all voxels connected to the seed voxel that are set to `false`. /// - Parameters: /// - x: x coordinate of the seed voxel. /// - y: y coordinate of the seed voxel. /// - z: z coordinate of the seed voxel. /// - group: Stores which faces the flood fill has reached. Should be empty to start off. private mutating func iterativeFloodFill(x: Int, y: Int, z: Int, group: inout DirectionSet) { var stack: [(Int, Int, Int)] = [(x, y, z)] // 256 is just a rough estimate of how deep the stack might get. In reality the stack actually // varies from under 80 to over 20000 depending on the chunk section. stack.reserveCapacity(256) while let position = stack.popLast() { let x = position.0 let y = position.1 let z = position.2 if isInBounds(x: x, y: y, z: z) && getVoxel(x: x, y: y, z: z) == false { if x == 0 { group.insert(.west) } else if x == dimension &- 1 { group.insert(.east) } if y == 0 { group.insert(.down) } else if y == dimension &- 1 { group.insert(.up) } if z == 0 { group.insert(.north) } else if z == dimension &- 1 { group.insert(.south) } setVoxel(x: x, y: y, z: z, to: true) stack.append((x &+ 1, y, z)) stack.append((x &- 1, y, z)) stack.append((x, y &+ 1, z)) stack.append((x, y &- 1, z)) stack.append((x, y, z &+ 1)) stack.append((x, y, z &- 1)) } } } /// Only works if ``dimension`` is a power of two. /// - Parameters: /// - x: x coordinate of point to check. /// - y: y coordinate of point to check. /// - z: z coordinate of point to check. /// - Returns: Whether the point is inside the bounds of the image or not. private func isInBounds(x: Int, y: Int, z: Int) -> Bool { return (x | y | z) >= 0 && (x | y | z) < dimension } /// - Returns: The coordinates of all voxels set to 0. private func emptyVoxelCoordinates() -> [(Int, Int, Int)] { var coordinates: [(Int, Int, Int)] = Array() coordinates.reserveCapacity(voxels.count / 2) // TODO: determine a better initial capacity for y in 0.. = [] /// Block model palette used to determine whether blocks are see through or not. private let blockModelPalette: BlockModelPalette /// The x coordinate of the west-most chunk in the graph. private var minimumX = 0 /// The x coordinate of the east-most chunk in the graph. private var maximumX = 0 /// The z coordinate of the north-most chunk in the graph. private var minimumZ = 0 /// The z coordinate of the south-most chunk in the graph. private var maximumZ = 0 // MARK: Init /// Creates an empty visibility graph. /// - Parameter blockModelPalette: Used to determine whether blocks are see through or not. public init(blockModelPalette: BlockModelPalette) { self.blockModelPalette = blockModelPalette } // MARK: Public methods /// Adds a chunk to the visibility graph. /// - Parameters: /// - chunk: Chunk to add. /// - position: Position of chunk. public mutating func addChunk(_ chunk: Chunk, at position: ChunkPosition) { lock.acquireWriteLock() defer { lock.unlock() } let isFirstChunk = chunks.isEmpty chunks.insert(position) // Update the bounding box of the visibility graph if isFirstChunk { minimumX = position.chunkX minimumZ = position.chunkZ maximumX = position.chunkX maximumZ = position.chunkZ } else { if position.chunkX < minimumX { minimumX = position.chunkX } else if position.chunkX > maximumX { maximumX = position.chunkX } if position.chunkZ < minimumZ { minimumZ = position.chunkZ } else if position.chunkZ > maximumZ { maximumZ = position.chunkZ } } // Calculate connectivity for (sectionY, section) in chunk.getSections().enumerated() { let sectionPosition = ChunkSectionPosition(position, sectionY: sectionY) var connectivityGraph = ChunkSectionVoxelGraph(for: section, blockModelPalette: blockModelPalette) sections[sectionPosition] = (connectivity: connectivityGraph.calculateConnectivity(), isEmpty: section.isEmpty) } } /// Removes the given chunk from the visibility graph. /// - Parameter position: The position of the chunk to remove. public mutating func removeChunk(at position: ChunkPosition) { lock.acquireWriteLock() defer { lock.unlock() } chunks.remove(position) // Update the bounds of the graph if necessary if chunks.isEmpty { minimumX = 0 minimumZ = 0 maximumX = 0 maximumZ = 0 } else { if position.chunkX == minimumX { minimumX = Int.max for chunk in chunks where chunk.chunkX < minimumX { minimumX = chunk.chunkX } } else if position.chunkX == maximumX { maximumX = Int.min for chunk in chunks where chunk.chunkX > maximumX { maximumX = chunk.chunkX } } if position.chunkZ == minimumZ { minimumZ = Int.max for chunk in chunks where chunk.chunkZ < minimumZ { minimumZ = chunk.chunkZ } } else if position.chunkZ == maximumZ { maximumZ = Int.min for chunk in chunks where chunk.chunkZ > maximumZ { maximumZ = chunk.chunkZ } } } // Remove the chunk's sections from the graph. for y in 0.. Bool { lock.acquireReadLock() defer { lock.unlock() } return chunks.contains(position) } /// Recomputes the connectivity of the given section. /// - Parameters: /// - position: The position of the section. /// - chunk: The chunk that the section is in. public mutating func updateSection(at position: ChunkSectionPosition, in chunk: Chunk) { lock.acquireWriteLock() defer { lock.unlock() } guard let section = chunk.getSection(at: position.sectionY) else { return } var connectivityGraph = ChunkSectionVoxelGraph(for: section, blockModelPalette: blockModelPalette) sections[position] = (connectivity: connectivityGraph.calculateConnectivity(), isEmpty: section.isEmpty) } /// Gets whether a ray could possibly pass through the given chunk section, entering through a given face and exiting out another given face. /// - Parameters: /// - entryFace: Face to enter through. /// - exitFace: Face to exit through. /// - section: Section to check for. /// - acquireLock: Whether to acquire a read lock or not. Only set to `false` if you know what you're doing. /// - Returns: Whether is it possibly to see through the section looking through `entryFace` and out `exitFace`. public func canPass(from entryFace: Direction, to exitFace: Direction, through section: ChunkSectionPosition, acquireLock: Bool = true) -> Bool { if acquireLock { lock.acquireReadLock() } defer { if acquireLock { lock.unlock() } } let first = ChunkSectionFace.forDirection(entryFace) let second = ChunkSectionFace.forDirection(exitFace) if let connectivity = sections[section] { return connectivity.connectivity.areConnected(first, second) } else { return isWithinPaddedBounds(section) } } /// Gets whether the given section is within the bounds of the visibility graph, including 1 section of padding around the entire graph. /// - Parameter section: The position of the section. /// - Returns: `true` if the section is within the bounds of this graph. public func isWithinPaddedBounds(_ section: ChunkSectionPosition) -> Bool { return section.sectionX >= minimumX - 1 && section.sectionX <= maximumX + 1 && section.sectionY >= -1 && section.sectionY <= Chunk.numSections + 1 && section.sectionZ >= minimumZ - 1 && section.sectionZ <= maximumZ + 1 } /// Gets the positions of all chunk sections that are possibly visible from the given chunk. /// - Parameter position: Position of the chunk section that the world is being viewed from. /// - Parameter camera: Used for frustum culling. /// - Returns: The positions of all possibly visible chunk sections. Does not include empty sections. public func chunkSectionsVisible(from camera: Camera, renderDistance: Int) -> [ChunkSectionPosition] { lock.acquireReadLock() defer { lock.unlock() } // Get the camera's position and swap it for an equivalent position to minimise the number of empty sections traversed if possible. let position = simplifyCameraPosition(camera.entityPosition.chunkSection) let cameraChunk = camera.entityPosition.chunk // Traverse the graph to find all potentially visible sections var visible: [ChunkSectionPosition] = [] visible.reserveCapacity(sectionCount) if sections[position]?.isEmpty == false && position.isValid { visible.append(position) } var visited = Set(minimumCapacity: sectionCount) var queue: Deque = [SearchQueueEntry(position: position, entryFace: nil, directions: [])] while let current = queue.popFirst() { let entryFace = current.entryFace let position = current.position for exitFace in Direction.allDirections where exitFace != entryFace { let neighbourPosition = position.neighbour(inDirection: exitFace) // Avoids doubling back. If a chunk has been exited from the top face, any chunks after that shouldn't be exited from the bottom face. if current.directions.contains(exitFace.opposite) { continue } // Chunks outside render distance aren't visible let neighbourChunk = neighbourPosition.chunk if !neighbourChunk.isWithinRenderDistance(renderDistance, of: cameraChunk) { continue } // Don't visit the same section twice guard !visited.contains(neighbourPosition) else { continue } if let entryFace = entryFace, !canPass(from: entryFace, to: exitFace, through: position, acquireLock: false) { continue } // Frustum culling if !camera.isChunkSectionVisible(at: neighbourPosition) { continue } visited.insert(neighbourPosition) var directions = current.directions directions.insert(exitFace) queue.append(SearchQueueEntry( position: neighbourPosition, entryFace: exitFace.opposite, directions: directions )) if sections[neighbourPosition]?.isEmpty == false && neighbourPosition.isValid { visible.append(neighbourPosition) } } } return visible } /// Moves the camera to an equivalent position which requires less traversing of empty chunk sections. /// /// If the camera is within the bounding box containing all non-empty chunks, it isn't moved. Otherwise, /// the camera is moved to be in a chunk adjacent to the bounding box (including diagonally adjacent). private func simplifyCameraPosition(_ position: ChunkSectionPosition) -> ChunkSectionPosition { var position = position if position.sectionX < minimumX - 1 { position.sectionX = minimumX - 1 } else if position.sectionX > maximumX + 1 { position.sectionX = maximumX + 1 } if position.sectionY < -1 { position.sectionY = -1 } else if position.sectionY > Chunk.numSections + 1 { position.sectionY = Chunk.numSections + 1 } if position.sectionZ < minimumZ - 1 { position.sectionZ = minimumZ - 1 } else if position.sectionZ > maximumZ + 1 { position.sectionZ = maximumZ + 1 } return position } } ================================================ FILE: Sources/Core/Renderer/World/WorldMesh.swift ================================================ import DeltaCore /// Holds all the meshes for a world. Completely threadsafe. public struct WorldMesh { // MARK: Private properties /// The world this mesh is for. private var world: World /// Used to determine which chunk sections should be rendered. private var visibilityGraph: VisibilityGraph /// A lock used to make the mesh threadsafe. private var lock = ReadWriteLock() /// A worker that handles the preparation and updating of meshes. private var meshWorker: WorldMeshWorker /// All chunk section meshes. private var meshes: [ChunkSectionPosition: ChunkSectionMesh] = [:] /// Positions of all chunk sections that need to have their meshes prepared again when they next become visible. private var chunkSectionsToPrepare: Set = [] /// Positions of all currently visible chunk sections (updated when ``update(_:camera:)`` is called. private var visibleSections: [ChunkSectionPosition] = [] /// The maximum number of chunk section preparation jobs that will be queued at any given time. /// /// This allows sections to be prepared in a more sensible order because they are prepared closer /// to the time they were queued which means that the ordering is more likely to be valid. For example, /// if the size of the job queue was not limited and the player turns around while sections are being /// prepared, all of the sections that were previously visible would be prepared before the ones that /// were actually visible. private var maximumQueuedJobCount = 8 // MARK: Init /// Creates a new world mesh. Prepares any chunks already loaded in the world. public init(_ world: World, resources: ResourcePack.Resources) { self.world = world meshWorker = WorldMeshWorker(world: world, resources: resources) visibilityGraph = VisibilityGraph(blockModelPalette: resources.blockModelPalette) let chunks = world.loadedChunkPositions for position in chunks { addChunk(at: position) } } // MARK: Public methods /// Adds a chunk to the mesh. /// - Parameter position: Position of the newly added chunk. public mutating func addChunk(at position: ChunkPosition) { lock.acquireWriteLock() defer { lock.unlock() } guard world.isChunkComplete(at: position) else { return } // The chunks required to prepare this chunk is the same as the chunks that require this chunk to prepare. // Adding this chunk may have made some of the chunks that require it preparable so here we check if any of // those can now by prepared. `chunksRequiredToPrepare` includes the chunk itself as well. for position in Self.chunksRequiredToPrepare(chunkAt: position) { if !visibilityGraph.containsChunk(at: position) && canPrepareChunk(at: position) { if let chunk = world.chunk(at: position) { visibilityGraph.addChunk(chunk, at: position) // Mark any non-empty sections of the chunk for preparation. for (y, section) in chunk.getSections().enumerated() where !section.isEmpty { let sectionPosition = ChunkSectionPosition(position, sectionY: y) chunkSectionsToPrepare.insert(sectionPosition) } } } } } /// Removes the given chunk from the mesh. /// /// This method has an issue where any chunk already queued to be prepared will still be prepared and stored. /// However, it will not be rendered, so this isn't much of an issue. And it probably won't happen often anyway. /// - Parameter position: The position of the chunk to remove. public mutating func removeChunk(at position: ChunkPosition) { lock.acquireWriteLock() defer { lock.unlock() } for position in Self.chunksRequiredToPrepare(chunkAt: position) { visibilityGraph.removeChunk(at: position) for y in 0.. Void ) rethrows { lock.acquireWriteLock() defer { lock.unlock() } let updatedMeshes = meshWorker.getUpdatedMeshes() for (position, mesh) in updatedMeshes { meshes[position] = mesh } let sections = shouldReverseOrder ? visibleSections.reversed() : visibleSections for position in sections { if meshes[position] != nil { // It was done this way to prevent copies // swiftlint:disable force_unwrapping try action(position, &meshes[position]!) // swiftlint:enable force_unwrapping } } } /// Gets an array containing the position of each section affected by the update (including the section itself). /// /// This function shouldn't need to be `mutating`, but it causes crashes if it is not. /// - Parameter position: The position of the chunk section. /// - Parameter onlyLighting: If true, the update will be treated as if only lighting has changed. /// - Returns: The affected chunk sections. public mutating func sectionsAffectedBySectionUpdate(at position: ChunkSectionPosition, onlyLighting: Bool = false) -> [ChunkSectionPosition] { lock.acquireReadLock() defer { lock.unlock() } var sections = [ position, position.validNeighbour(inDirection: .north), position.validNeighbour(inDirection: .south), position.validNeighbour(inDirection: .east), position.validNeighbour(inDirection: .west), position.validNeighbour(inDirection: .up), position.validNeighbour(inDirection: .down) ].compactMap { $0 } if onlyLighting { return sections } // The following sections are only affected if they contain fluids let potentiallyAffected = [ position.validNeighbour(inDirection: .north)?.validNeighbour(inDirection: .east), position.validNeighbour(inDirection: .north)?.validNeighbour(inDirection: .east)?.validNeighbour(inDirection: .down), position.validNeighbour(inDirection: .north)?.validNeighbour(inDirection: .west), position.validNeighbour(inDirection: .north)?.validNeighbour(inDirection: .west)?.validNeighbour(inDirection: .down), position.validNeighbour(inDirection: .south)?.validNeighbour(inDirection: .west), position.validNeighbour(inDirection: .south)?.validNeighbour(inDirection: .west)?.validNeighbour(inDirection: .down), position.validNeighbour(inDirection: .south)?.validNeighbour(inDirection: .west), position.validNeighbour(inDirection: .south)?.validNeighbour(inDirection: .west)?.validNeighbour(inDirection: .down), position.validNeighbour(inDirection: .north)?.validNeighbour(inDirection: .down), position.validNeighbour(inDirection: .east)?.validNeighbour(inDirection: .down), position.validNeighbour(inDirection: .south)?.validNeighbour(inDirection: .down), position.validNeighbour(inDirection: .west)?.validNeighbour(inDirection: .down) ].compactMap { $0 } for section in potentiallyAffected { if let mesh = meshes[section] { if mesh.containsFluids { sections.append(section) } } } return sections } /// Gets the list of chunks that must be present to prepare a chunk, including the chunk itself. /// - Parameter position: Chunk to get dependencies of. /// - Returns: Chunks that must be present to prepare the given chunk, including the chunk itself. public static func chunksRequiredToPrepare(chunkAt position: ChunkPosition) -> [ChunkPosition] { return [ position, position.neighbour(inDirection: .north), position.neighbour(inDirection: .north).neighbour(inDirection: .east), position.neighbour(inDirection: .east), position.neighbour(inDirection: .south).neighbour(inDirection: .east), position.neighbour(inDirection: .south), position.neighbour(inDirection: .south).neighbour(inDirection: .west), position.neighbour(inDirection: .west), position.neighbour(inDirection: .north).neighbour(inDirection: .west) ] } // MARK: Private methods /// Prepares the mesh for a chunk section. Threadsafe. /// - Parameters: /// - position: The position of the section to prepare. /// - acquireWriteLock: If false, a write lock for `lock` must be acquired prior to calling this method. private mutating func prepareChunkSection(at position: ChunkSectionPosition, acquireWriteLock: Bool) { if acquireWriteLock { lock.acquireWriteLock() } defer { if acquireWriteLock { lock.unlock() } } let chunkPosition = position.chunk chunkSectionsToPrepare.remove(position) // TODO: This should possibly throw an error instead of failing silently guard let chunk = world.chunk(at: chunkPosition), let neighbours = world.allNeighbours(ofChunkAt: chunkPosition) else { log.warning("Failed to get chunk and neighbours of section at \(position)") visibilityGraph.removeChunk(at: chunkPosition) return } meshWorker.createMeshAsync( at: position, in: chunk, neighbours: neighbours ) } /// Checks whether a chunk section should be prepared when it next becomes visible. /// /// Does not perform any locking (isn't threadsafe). /// - Parameter position: The position of the chunk section to check. /// - Returns: Whether the chunk section should be prepared or not. private func shouldPrepareChunkSection(at position: ChunkSectionPosition) -> Bool { return chunkSectionsToPrepare.contains(position) } /// Checks whether a chunk has all the neighbours required to prepare it (including lighting). /// /// Does not perform any locking (isn't threadsafe). /// - Parameter position: The position of the chunk to check. /// - Returns: Whether the chunk can be prepared or not. private func canPrepareChunk(at position: ChunkPosition) -> Bool { for position in Self.chunksRequiredToPrepare(chunkAt: position) { if !world.isChunkComplete(at: position) { return false } } return true } } ================================================ FILE: Sources/Core/Renderer/World/WorldMeshWorker+Job.swift ================================================ import Collections import DeltaCore extension WorldMeshWorker { /// A chunk section mesh creation job. struct Job { /// The chunk that the section is in. var chunk: Chunk /// The position of the section to prepare. var position: ChunkSectionPosition /// The neighbouring chunks of ``chunk``. var neighbours: ChunkNeighbours } /// Handles queueing jobs and prioritisation. Completely threadsafe. struct JobQueue { /// The number of jobs currently in the queue. public var count: Int { lock.acquireReadLock() defer { lock.unlock() } return jobs.count } /// The queue of current jobs. private var jobs: Deque = [] /// A lock used to make the job queue threadsafe. private var lock = ReadWriteLock() /// Creates an empty job queue. init() {} /// Adds a job to the queue. mutating func add(_ job: Job) { lock.acquireWriteLock() defer { lock.unlock() } jobs.append(job) } /// Returns the next job to complete. mutating func next() -> Job? { lock.acquireWriteLock() defer { lock.unlock() } if !jobs.isEmpty { return jobs.removeFirst() } else { return nil } } } } ================================================ FILE: Sources/Core/Renderer/World/WorldMeshWorker.swift ================================================ import Foundation import Atomics import Metal import DeltaCore /// A multi-threaded worker that creates and updates the world's meshes. Completely threadsafe. public class WorldMeshWorker { // MARK: Public properties /// The number of jobs currently queued. public var jobCount: Int { jobQueue.count } // MARK: Private properties /// World that chunks are in. private var world: World /// Resources to prepare chunks with. private let resources: ResourcePack.Resources /// A lock used to make the worker threadsafe. private var lock = ReadWriteLock() /// Meshes that the worker has created or updated and the ``WorldRenderer`` hasn't taken back yet. private var updatedMeshes: [ChunkSectionPosition: ChunkSectionMesh] = [:] /// Mesh creation jobs. private var jobQueue = JobQueue() /// Serial dispatch queue for executing jobs on. private var executionQueue = DispatchQueue(label: "dev.stackotter.delta-client.WorldMeshWorker", attributes: [.concurrent]) /// Whether the execution loop is currently running or not. private var executingThreadsCount = ManagedAtomic(0) /// The maximum number of execution loops allowed to run at once (for performance reasons). private let maxExecutingThreadsCount = 1 // TODO: Scale max threads and executionQueue qos with size of job queue // MARK: Init /// Creates a new world mesh worker. public init(world: World, resources: ResourcePack.Resources) { self.world = world self.resources = resources } // MARK: Public methods /// Creates a new mesh for the specified chunk section. public func createMeshAsync( at position: ChunkSectionPosition, in chunk: Chunk, neighbours: ChunkNeighbours ) { let job = Job( chunk: chunk, position: position, neighbours: neighbours) jobQueue.add(job) startExecutionLoop() } /// Gets the meshes that have been updated since the last call to this function. /// - Returns: The updated meshes and their positions. public func getUpdatedMeshes() -> [ChunkSectionPosition: ChunkSectionMesh] { lock.acquireWriteLock() defer { updatedMeshes = [:] lock.unlock() } return updatedMeshes } // MARK: Private methods /// Starts an asynchronous loop that executes all jobs on the queue until there are none left. private func startExecutionLoop() { if executingThreadsCount.load(ordering: .relaxed) >= maxExecutingThreadsCount { return } executingThreadsCount.wrappingIncrement(ordering: .relaxed) executionQueue.async { while true { let jobWasExecuted = self.executeNextJob() // If no job was executed, the job queue is empty and this execution loop can stop if !jobWasExecuted { if self.executingThreadsCount.wrappingDecrementThenLoad(ordering: .relaxed) < 0 { log.warning("Error in WorldMeshWorker thread management, number of executing threads is below 0") } return } } } } /// Executes the next job. /// - Returns: `false` if there were no jobs to execute. private func executeNextJob() -> Bool { guard let job = jobQueue.next() else { return false } var affectedChunks: [Chunk] = [] for position in WorldMesh.chunksRequiredToPrepare(chunkAt: job.position.chunk) { if let chunk = world.chunk(at: position) { chunk.acquireReadLock() affectedChunks.append(chunk) } } let meshBuilder = ChunkSectionMeshBuilder( forSectionAt: job.position, in: job.chunk, withNeighbours: job.neighbours, world: world, resources: resources ) // TODO: implement buffer recycling let mesh = meshBuilder.build() for chunk in affectedChunks { chunk.unlock() } lock.acquireWriteLock() updatedMeshes[job.position] = mesh lock.unlock() return true } } ================================================ FILE: Sources/Core/Renderer/World/WorldRenderer.swift ================================================ import DeltaCore import FirebladeMath import Foundation import MetalKit /// A renderer that renders a `World` along with its associated entities (from `Game.nexus`). public final class WorldRenderer: Renderer { // MARK: Private properties /// Internal renderer for rendering entities. private var entityRenderer: EntityRenderer /// Render pipeline used for rendering world geometry. private var renderPipelineState: MTLRenderPipelineState #if !os(tvOS) /// Render pipeline used for rendering translucent world geometry. private var transparencyRenderPipelineState: MTLRenderPipelineState /// Render pipeline used for compositing translucent geometry onto the screen buffer. private var compositingRenderPipelineState: MTLRenderPipelineState #endif /// The device used for rendering. private var device: MTLDevice /// The resources to use for rendering blocks. private var resources: ResourcePack.Resources /// The command queue used for rendering. private var commandQueue: MTLCommandQueue /// The Metal texture palette containing the array-texture and animation-related buffers. private var texturePalette: MetalTexturePalette /// The light map texture used to calculate rendered brightness. private var lightMap: LightMap /// The client to render for. private var client: Client /// Manages the world's meshes. private var worldMesh: WorldMesh /// The rendering profiler. private var profiler: Profiler /// A buffer containing uniforms containing the identity matrix (no-op). private var identityUniformsBuffer: MTLBuffer /// A buffer containing vertices for a block outline. private let blockOutlineVertexBuffer: MTLBuffer /// A buffer containing indices for a block outline. private let blockOutlineIndexBuffer: MTLBuffer /// A buffer containing the light map (updated each frame). private var lightMapBuffer: MTLBuffer? #if !os(tvOS) /// The depth stencil state used for order independent transparency (which requires read-only /// depth). private let readOnlyDepthState: MTLDepthStencilState #endif /// The depth stencil state used when order independent transparency is disabled. private let depthState: MTLDepthStencilState /// The buffer for the uniforms used to render distance fog. private let fogUniformsBuffer: MTLBuffer private let destroyOverlayRenderPipelineState: MTLRenderPipelineState // MARK: Init /// Creates a new world renderer. public init( client: Client, device: MTLDevice, commandQueue: MTLCommandQueue, profiler: Profiler ) throws { self.client = client self.device = device self.commandQueue = commandQueue self.profiler = profiler // Load shaders let library = try MetalUtil.loadDefaultLibrary(device) let vertexFunction = try MetalUtil.loadFunction("chunkVertexShader", from: library) let fragmentFunction = try MetalUtil.loadFunction("chunkFragmentShader", from: library) let transparentFragmentFunction = try MetalUtil.loadFunction( "chunkOITFragmentShader", from: library ) let transparentCompositingVertexFunction = try MetalUtil.loadFunction( "chunkOITCompositingVertexShader", from: library ) let transparentCompositingFragmentFunction = try MetalUtil.loadFunction( "chunkOITCompositingFragmentShader", from: library ) // Create block palette array texture. resources = client.resourcePack.vanillaResources texturePalette = try MetalTexturePalette( palette: resources.blockTexturePalette, device: device, commandQueue: commandQueue ) // Create light map lightMap = LightMap(ambientLight: Double(client.game.world.dimension.ambientLight)) // TODO: Have another copy of this pipeline without blending enabled (to use when OIT is enabled) // Create opaque pipeline (which also handles translucent geometry when OIT is disabled) renderPipelineState = try MetalUtil.makeRenderPipelineState( device: device, label: "WorldRenderer.renderPipelineState", vertexFunction: vertexFunction, fragmentFunction: fragmentFunction, blendingEnabled: true ) destroyOverlayRenderPipelineState = try MetalUtil.makeRenderPipelineState( device: device, label: "WorldRenderer.destroyOverlayRenderPipelineState", vertexFunction: vertexFunction, fragmentFunction: fragmentFunction, blendingEnabled: true, editDescriptor: { descriptor in descriptor.colorAttachments[0].sourceRGBBlendFactor = .destinationColor descriptor.colorAttachments[0].sourceAlphaBlendFactor = .one descriptor.colorAttachments[0].destinationRGBBlendFactor = .sourceColor descriptor.colorAttachments[0].destinationAlphaBlendFactor = .zero } ) #if !os(tvOS) // Create OIT pipeline transparencyRenderPipelineState = try MetalUtil.makeRenderPipelineState( device: device, label: "WorldRenderer.oit", vertexFunction: vertexFunction, fragmentFunction: transparentFragmentFunction, blendingEnabled: true, editDescriptor: { (descriptor: MTLRenderPipelineDescriptor) in // Accumulation texture descriptor.colorAttachments[1].isBlendingEnabled = true descriptor.colorAttachments[1].rgbBlendOperation = .add descriptor.colorAttachments[1].alphaBlendOperation = .add descriptor.colorAttachments[1].sourceRGBBlendFactor = .one descriptor.colorAttachments[1].sourceAlphaBlendFactor = .one descriptor.colorAttachments[1].destinationRGBBlendFactor = .one descriptor.colorAttachments[1].destinationAlphaBlendFactor = .one // Revealage texture descriptor.colorAttachments[2].isBlendingEnabled = true descriptor.colorAttachments[2].rgbBlendOperation = .add descriptor.colorAttachments[2].alphaBlendOperation = .add descriptor.colorAttachments[2].sourceRGBBlendFactor = .zero descriptor.colorAttachments[2].sourceAlphaBlendFactor = .zero descriptor.colorAttachments[2].destinationRGBBlendFactor = .oneMinusSourceColor descriptor.colorAttachments[2].destinationAlphaBlendFactor = .oneMinusSourceAlpha } ) // Create OIT compositing pipeline compositingRenderPipelineState = try MetalUtil.makeRenderPipelineState( device: device, label: "WorldRenderer.compositing", vertexFunction: transparentCompositingVertexFunction, fragmentFunction: transparentCompositingFragmentFunction, blendingEnabled: true ) // Create the depth state used for order independent transparency readOnlyDepthState = try MetalUtil.createDepthState(device: device, readOnly: true) #endif // Create the regular depth state. // TODO: Is this meant to be read only? I would assume not depthState = try MetalUtil.createDepthState(device: device, readOnly: true) // Create entity renderer entityRenderer = try EntityRenderer( client: client, device: device, commandQueue: commandQueue, profiler: profiler, blockTexturePalette: texturePalette ) // Create world mesh worldMesh = WorldMesh(client.game.world, resources: resources) // TODO: Improve storage mode selection #if os(macOS) let storageMode = MTLResourceOptions.storageModeManaged #elseif os(iOS) || os(tvOS) let storageMode = MTLResourceOptions.storageModeShared #else #error("Unsupported platform") #endif var identityUniforms = ChunkUniforms() identityUniformsBuffer = try MetalUtil.makeBuffer( device, bytes: &identityUniforms, length: MemoryLayout.stride, options: storageMode ) let maxOutlinePartCount = RegistryStore.shared.blockRegistry.blocks.map { block in return block.shape.outlineShape.aabbs.count }.max() ?? 1 let geometry = Self.generateOutlineGeometry(position: .zero, size: [1, 1, 1], baseIndex: 0) blockOutlineIndexBuffer = try MetalUtil.makeBuffer( device, length: MemoryLayout.stride * geometry.indices.count * maxOutlinePartCount, options: storageMode, label: "blockOutlineIndexBuffer" ) blockOutlineVertexBuffer = try MetalUtil.makeBuffer( device, length: MemoryLayout.stride * geometry.vertices.count * maxOutlinePartCount, options: storageMode, label: "blockOutlineVertexBuffer" ) fogUniformsBuffer = try MetalUtil.makeBuffer( device, length: MemoryLayout.stride, options: storageMode, label: "fogUniformsBuffer" ) // Register event handler client.eventBus.registerHandler { [weak self] event in guard let self = self else { return } self.handle(event) } } // MARK: Public methods /// Renders the world's blocks. public func render( view: MTKView, encoder: MTLRenderCommandEncoder, commandBuffer: MTLCommandBuffer, worldToClipUniformsBuffer: MTLBuffer, camera: Camera ) throws { // Update world mesh profiler.push(.updateWorldMesh) worldMesh.update( camera: camera, renderDistance: client.configuration.render.renderDistance ) profiler.pop() // Update animated textures profiler.push(.updateAnimatedTextures) texturePalette.update() profiler.pop() // Get light map buffer profiler.push(.updateLightMap) lightMap.update( tick: client.game.tickScheduler.tickNumber, sunAngleRadians: client.game.world.getSunAngleRadians(), ambientLight: Double(client.game.world.dimension.ambientLight), dimensionHasSkyLight: client.game.world.dimension.hasSkyLight ) lightMapBuffer = try lightMap.getBuffer(device, reusing: lightMapBuffer) profiler.pop() profiler.push(.updateFogUniforms) var fogUniforms = Self.fogUniforms(client: client, camera: camera) fogUniformsBuffer.contents().copyMemory( from: &fogUniforms, byteCount: MemoryLayout.stride ) profiler.pop() // Setup render pass. The instance uniforms (vertex buffer index 3) are set to the identity // matrix because this phase of the renderer doesn't use instancing although the chunk shader // does support it. encoder.setRenderPipelineState(renderPipelineState) encoder.setVertexBuffer(texturePalette.textureStatesBuffer, offset: 0, index: 3) encoder.setFragmentTexture(texturePalette.arrayTexture, index: 0) encoder.setFragmentBuffer(lightMapBuffer, offset: 0, index: 0) encoder.setFragmentBuffer(texturePalette.timeBuffer, offset: 0, index: 1) encoder.setFragmentBuffer(fogUniformsBuffer, offset: 0, index: 2) // Render transparent and opaque geometry profiler.push(.encodeOpaque) var visibleChunks: Set = [] try worldMesh.mutateVisibleMeshes { position, mesh in visibleChunks.insert(position.chunk) try mesh.renderTransparentAndOpaque( renderEncoder: encoder, device: device, commandQueue: commandQueue ) } profiler.pop() if client.game.currentGamemode() != .spectator { // Render selected block outline profiler.push(.encodeBlockOutline) if let targetedBlock = client.game.targetedBlock() { let targetedBlockPosition = targetedBlock.target var indices: [UInt32] = [] var vertices: [BlockVertex] = [] let block = client.game.world.getBlock(at: targetedBlockPosition) let boundingBox = block.shape.outlineShape.offset(by: targetedBlockPosition.doubleVector) if !boundingBox.aabbs.isEmpty { for aabb in boundingBox.aabbs { let geometry = Self.generateOutlineGeometry( position: Vec3f(aabb.position), size: Vec3f(aabb.size), baseIndex: UInt32(indices.count) ) indices.append(contentsOf: geometry.indices) vertices.append(contentsOf: geometry.vertices) } blockOutlineVertexBuffer.contents().copyMemory( from: &vertices, byteCount: MemoryLayout.stride * vertices.count ) blockOutlineIndexBuffer.contents().copyMemory( from: &indices, byteCount: MemoryLayout.stride * indices.count ) encoder.setVertexBuffer(blockOutlineVertexBuffer, offset: 0, index: 0) encoder.setVertexBuffer(identityUniformsBuffer, offset: 0, index: 2) encoder.drawIndexedPrimitives( type: .triangle, indexCount: indices.count, indexType: .uint32, indexBuffer: blockOutlineIndexBuffer, indexBufferOffset: 0 ) } } profiler.pop() } for breakingBlock in client.game.world.getBreakingBlocks() { guard let stage = breakingBlock.stage else { continue } let block = client.game.world.getBlock(at: breakingBlock.position) if var model = resources.blockModelPalette.model(for: block.id, at: breakingBlock.position) { let textureId = client.resourcePack.vanillaResources.blockTexturePalette.textureIndex( for: Identifier(namespace: "minecraft", name: "block/destroy_stage_\(stage)"))! for (i, part) in model.parts.enumerated() { for (j, element) in part.elements.enumerated() { model.parts[i].elements[j].shade = false for k in 0..() var geometry = SortableMeshElement() builder.build(into: &dummyGeometry, translucentGeometry: &geometry) for i in 0...stride * geometry.vertices.count) guard let indexBuffer = device.makeBuffer( bytes: &geometry.indices, length: MemoryLayout.stride * geometry.indices.count) else { // No geometry to render continue } encoder.setRenderPipelineState(destroyOverlayRenderPipelineState) encoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0) encoder.setVertexBuffer(identityUniformsBuffer, offset: 0, index: 2) encoder.drawIndexedPrimitives( type: .triangle, indexCount: geometry.indices.count, indexType: .uint32, indexBuffer: indexBuffer, indexBufferOffset: 0 ) } } // Entities are rendered before translucent geometry for correct alpha blending behaviour. profiler.push(.entities) entityRenderer.setVisibleChunks(visibleChunks) try entityRenderer.render( view: view, encoder: encoder, commandBuffer: commandBuffer, worldToClipUniformsBuffer: worldToClipUniformsBuffer, camera: camera ) profiler.pop() // Setup render pass for encoding translucent geometry after entity rendering pass #if os(tvOS) encoder.setRenderPipelineState(renderPipelineState) #else if client.configuration.render.enableOrderIndependentTransparency { encoder.setRenderPipelineState(transparencyRenderPipelineState) encoder.setDepthStencilState(readOnlyDepthState) } else { encoder.setRenderPipelineState(renderPipelineState) } #endif encoder.setVertexBuffer(texturePalette.textureStatesBuffer, offset: 0, index: 3) encoder.setFragmentTexture(texturePalette.arrayTexture, index: 0) encoder.setFragmentBuffer(lightMapBuffer, offset: 0, index: 0) encoder.setFragmentBuffer(texturePalette.timeBuffer, offset: 0, index: 1) // Render translucent geometry profiler.push(.encodeTranslucent) try worldMesh.mutateVisibleMeshes(fromBackToFront: true) { _, mesh in try mesh.renderTranslucent( viewedFrom: camera.position, sortTranslucent: !client.configuration.render.enableOrderIndependentTransparency, renderEncoder: encoder, device: device, commandQueue: commandQueue ) } #if !os(tvOS) // Composite translucent geometry onto the screen buffer. No vertices need to be supplied, the // shader has the screen's corners hardcoded for simplicity. if client.configuration.render.enableOrderIndependentTransparency { encoder.setRenderPipelineState(compositingRenderPipelineState) encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 6) encoder.setDepthStencilState(depthState) } #endif profiler.pop() } // MARK: Private methods private func handle(_ event: Event) { // TODO: Optimize this the section updating algorithms to minimise unnecessary updates switch event { case let event as World.Event.AddChunk: worldMesh.addChunk(at: event.position) case let event as World.Event.RemoveChunk: worldMesh.removeChunk(at: event.position) case let event as World.Event.UpdateChunkLighting: let updatedSections = event.data.updatedSections var affectedSections: Set = [] for y in updatedSections { let position = ChunkSectionPosition(event.position, sectionY: y) let affected = worldMesh.sectionsAffectedBySectionUpdate(at: position, onlyLighting: true) affectedSections.formUnion(affected) } worldMesh.updateSections(at: Array(affectedSections)) case let event as World.Event.SingleBlockUpdate: let affectedSections = worldMesh.sectionsAffectedBySectionUpdate( at: event.position.chunkSection) worldMesh.updateSections(at: Array(affectedSections)) case let event as World.Event.MultiBlockUpdate: var affectedSections: Set = [] for update in event.updates { affectedSections.formUnion( worldMesh.sectionsAffectedBySectionUpdate(at: update.position.chunkSection)) } worldMesh.updateSections(at: Array(affectedSections)) case let event as World.Event.UpdateChunk: var affectedSections: Set = [] for sectionY in event.updatedSections { let position = ChunkSectionPosition(event.position, sectionY: sectionY) affectedSections.formUnion(worldMesh.sectionsAffectedBySectionUpdate(at: position)) } worldMesh.updateSections(at: Array(affectedSections)) case _ as JoinWorldEvent: // TODO: this has the possibility to cause crashes worldMesh = WorldMesh(client.game.world, resources: resources) default: return } } static func fogUniforms(client: Client, camera: Camera) -> FogUniforms { // When the render distance is above 2, move the fog 1 chunk closer to conceal // more of the world edge. let renderDistance = max(client.configuration.render.renderDistance - 1, 2) let fog = client.game.world.getFog( forViewerWithRay: camera.ray, withRenderDistance: renderDistance ) let isLinear: Bool let fogDensity: Float let fogStart: Float let fogEnd: Float switch fog.style { case let .exponential(density): isLinear = false fogDensity = density // Start and end are ignored by exponential fog fogStart = 0 fogEnd = 0 case let .linear(start, end): isLinear = true // Density is ignored by linear fog fogDensity = 0 fogStart = start fogEnd = end } return FogUniforms( fogColor: fog.color, fogStart: fogStart, fogEnd: fogEnd, fogDensity: fogDensity, isLinear: isLinear ) } private static func generateOutlineGeometry( position: Vec3f, size: Vec3f, baseIndex: UInt32 ) -> Geometry { let thickness: Float = 0.004 let padding: Float = -thickness + 0.001 // swiftlint:disable:next large_tuple var boxes: [(position: Vec3f, size: Vec3f, axis: Axis, faces: [Direction])] = [] for side: Direction in [.north, .east, .south, .west] { // Create up-right edge between this side and the next let adjacentSide = side.rotated(1, clockwiseFacing: .down) var position = side.vector + adjacentSide.vector position *= size / 2 + Vec3f(padding + thickness / 2, 0, padding + thickness / 2) position += Vec3f(size.x - thickness, 0, size.z - thickness) / 2 position.y -= padding boxes.append( ( position: position, size: [thickness, size.component(along: .y) + padding * 2, thickness], axis: .y, faces: [side, adjacentSide] )) // Create the edges above and below this side for direction: Direction in [.up, .down] { let edgeDirection = adjacentSide.axis.positiveDirection.vector var edgeSize = size.component(along: adjacentSide.axis) + (padding + thickness) * 2 if adjacentSide.axis == .x { edgeSize -= thickness * 2 } let edge = abs(adjacentSide.vector * edgeSize) var position = position if direction == .up { position.y += size.component(along: .y) + padding * 2 } else { position.y -= thickness } if position.component(along: adjacentSide.axis) > 0 { if adjacentSide.axis == .x { position.x -= size.component(along: .x) + padding * 2 } else { position.z -= size.component(along: .z) + padding * 2 + thickness } } else if adjacentSide.axis == .x { position.x += thickness } var faces = [side, direction] if adjacentSide.axis != .x { faces.append(contentsOf: [adjacentSide, adjacentSide.opposite]) } boxes.append( ( position: position, size: (Vec3f(1, 1, 1) - edgeDirection) * thickness + edge, axis: adjacentSide.axis, faces: faces )) } } var blockOutlineVertices: [BlockVertex] = [] var blockOutlineIndices: [UInt32] = [] let translation = MatrixUtil.translationMatrix(position) for box in boxes { for face in box.faces { let offset = UInt32(blockOutlineVertices.count) + baseIndex let winding = CubeGeometry.faceWinding.map { index in return index + offset } // Render both front and back faces blockOutlineIndices.append(contentsOf: winding) blockOutlineIndices.append(contentsOf: winding.reversed()) let transformation = MatrixUtil.scalingMatrix(box.size) * MatrixUtil.translationMatrix(box.position) * translation for vertex in CubeGeometry.faceVertices[face.rawValue] { let vertexPosition = (Vec4f(vertex, 1) * transformation).xyz blockOutlineVertices.append( BlockVertex( x: vertexPosition.x, y: vertexPosition.y, z: vertexPosition.z, u: 0, v: 0, r: 0, g: 0, b: 0, a: 0.6, skyLightLevel: UInt8(LightLevel.maximumLightLevel), blockLightLevel: 0, textureIndex: UInt16.max, isTransparent: false )) } } } return Geometry(vertices: blockOutlineVertices, indices: blockOutlineIndices) } } ================================================ FILE: Sources/Core/Sources/Account/Account.swift ================================================ import Foundation /// An account which can be a Microsoft, Mojang or offline account. public enum Account: Codable, Identifiable, Hashable { case microsoft(MicrosoftAccount) case mojang(MojangAccount) case offline(OfflineAccount) /// The account's id. public var id: String { switch self { case .microsoft(let account as OnlineAccount), .mojang(let account as OnlineAccount): return account.id case .offline(let account): return account.id } } /// The account type to display to users. public var type: String { switch self { case .microsoft: return "Microsoft" case .mojang: return "Mojang" case .offline: return "Offline" } } /// The account's username. public var username: String { switch self { case .microsoft(let account as OnlineAccount), .mojang(let account as OnlineAccount): return account.username case .offline(let account): return account.username } } /// The online version of this account if the account supports online mode. public var online: OnlineAccount? { switch self { case .microsoft(let account as OnlineAccount), .mojang(let account as OnlineAccount): return account case .offline: return nil } } /// The offline version of this account. public var offline: OfflineAccount { switch self { case .microsoft(let account as OnlineAccount), .mojang(let account as OnlineAccount): return OfflineAccount(username: account.username) case .offline(let account): return account } } /// Refreshes the account's access token (if it has one). /// - Parameter clientToken: The client token to use when refreshing the account. public func refreshed(withClientToken clientToken: String) async throws -> Self { switch self { case .microsoft(let account): let account = try await MicrosoftAPI.refreshMinecraftAccount(account) return .microsoft(account) case .mojang(let account): let account = try await MojangAPI.refresh(account, with: clientToken) return .mojang(account) case .offline: return self } } /// Refreshes the account's access token in place (if it has one). /// - Parameter clientToken: The client token to use when refreshing the account. public mutating func refresh(withClientToken clientToken: String) async throws { self = try await refreshed(withClientToken: clientToken) } } ================================================ FILE: Sources/Core/Sources/Account/Microsoft/MicrosoftAPI.swift ================================================ import Foundation public enum MicrosoftAPIError: LocalizedError { case noUserHashInResponse case failedToDeserializeResponse case xstsAuthenticationFailed case expiredAccessToken case failedToGetXboxLiveToken case failedToGetXSTSToken case failedToGetMinecraftAccessToken case failedToGetAttachedLicenses case accountDoesntOwnMinecraft case failedToGetMinecraftAccount public var errorDescription: String? { switch self { case .noUserHashInResponse: return "No user hash in response." case .failedToDeserializeResponse: return "Failed to deserialize response." case .xstsAuthenticationFailed: return "XSTS authentication failed." case .expiredAccessToken: return "Expired access token." case .failedToGetXboxLiveToken: return "Failed to get Xbox Live token." case .failedToGetXSTSToken: return "Failed to get XSTS token." case .failedToGetMinecraftAccessToken: return "Failed to get Minecraft access token." case .failedToGetAttachedLicenses: return "Failed to get attached licenses." case .accountDoesntOwnMinecraft: return "Account doesnt own Minecraft." case .failedToGetMinecraftAccount: return "Failed to get Minecraft account." } } } /// A utility for interacting with the Microsoft authentication API. /// /// ## Overview /// /// First, device authorization is obtained via ``authorizeDevice()``. The user must then visit the /// verification url provided in the ``MicrosoftDeviceAuthorizationResponse`` and enter the /// `userCode` also provided in the response. /// /// Once the user has completed the interactive part of logging in, ``getMicrosoftAccessToken(_:)`` /// is used to convert the device code into a Microsoft access token. /// /// ``getMinecraftAccount(_:)`` can then be called with the access token, resulting in an /// authenticated Microsoft-based Minecraft account. public enum MicrosoftAPI { // swiftlint:disable force_unwrapping /// The client id used for Microsoft authentication. public static let clientId = "e5c1b05f-4e94-4747-90bf-3e9d40f830f1" private static let xstsSandboxId = "RETAIL" private static let xstsRelyingParty = "rp://api.minecraftservices.com/" private static let authorizationURL = URL(string: "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode")! private static let authenticationURL = URL(string: "https://login.microsoftonline.com/consumers/oauth2/v2.0/token")! private static let xboxLiveAuthenticationURL = URL(string: "https://user.auth.xboxlive.com/user/authenticate")! private static let xstsAuthenticationURL = URL(string: "https://xsts.auth.xboxlive.com/xsts/authorize")! private static let minecraftXboxAuthenticationURL = URL(string: "https://api.minecraftservices.com/authentication/login_with_xbox")! private static let gameOwnershipURL = URL(string: "https://api.minecraftservices.com/entitlements/mcstore")! private static let minecraftProfileURL = URL(string: "https://api.minecraftservices.com/minecraft/profile")! // swiftlint:enable force_unwrapping // MARK: Public methods /// Authorizes this device (metaphorically). This is the first step in authenticating a user. /// - Returns: A device authorization response. public static func authorizeDevice() async throws -> MicrosoftDeviceAuthorizationResponse { let (_, data) = try await RequestUtil.performFormRequest( url: authorizationURL, body: [ "client_id": clientId, "scope": "XboxLive.signin offline_access" ], method: .post ) let response: MicrosoftDeviceAuthorizationResponse = try decodeResponse(data) // TODO: extract the error type if the response isn't a valid access token response return response } /// Fetches an access token for the user after they have completed the interactive login process. /// - Parameter deviceCode: The device code used during authentication. /// - Returns: An authenticated Microsoft access token. public static func getMicrosoftAccessToken(_ deviceCode: String) async throws -> MicrosoftAccessToken { let (_, data) = try await RequestUtil.performFormRequest( url: authenticationURL, body: [ "tenant": "consumers", "grant_type": "urn:ietf:params:oauth:grant-type:device_code", "client_id": clientId, "device_code": deviceCode ], method: .post ) let response: MicrosoftAccessTokenResponse = try decodeResponse(data) // TODO: extract the error type if the response isn't a valid access token response let accessToken = MicrosoftAccessToken( token: response.accessToken, expiresIn: response.expiresIn, refreshToken: response.refreshToken ) return accessToken } /// Gets the user's Minecraft account. /// - Parameters: /// - minecraftAccessToken: The user's Minecraft access token. /// - microsoftAccessToken: The user's Microsoft access token. /// - Returns: The user's Minecraft account. public static func getMinecraftAccount( _ minecraftAccessToken: MinecraftAccessToken, _ microsoftAccessToken: MicrosoftAccessToken ) async throws -> MicrosoftAccount { var request = Request(minecraftProfileURL) request.method = .get request.headers["Authorization"] = "Bearer \(minecraftAccessToken.token)" let (_, data) = try await RequestUtil.performRequest(request) let response: MicrosoftMinecraftProfileResponse = try decodeResponse(data) return MicrosoftAccount( id: response.id, username: response.name, minecraftAccessToken: minecraftAccessToken, microsoftAccessToken: microsoftAccessToken ) } /// Gets the user's Microsoft-based Minecraft account from their Microsoft access token. /// - Parameter microsoftAccessToken: The user's Microsoft access token with suitable scope /// `XboxLive.signin` and `offline_access`. /// - Returns: An authenticated and authorized Microsoft-based Minecraft account. public static func getMinecraftAccount(_ microsoftAccessToken: MicrosoftAccessToken) async throws -> MicrosoftAccount { // Get Xbox live token let xboxLiveToken: XboxLiveToken do { xboxLiveToken = try await MicrosoftAPI.getXBoxLiveToken(microsoftAccessToken) } catch { throw MicrosoftAPIError.failedToGetXboxLiveToken.becauseOf(error) } // Get XSTS token let xstsToken: String do { xstsToken = try await MicrosoftAPI.getXSTSToken(xboxLiveToken) } catch { throw MicrosoftAPIError.failedToGetXSTSToken.becauseOf(error) } // Get Minecraft access token let minecraftAccessToken: MinecraftAccessToken do { minecraftAccessToken = try await MicrosoftAPI.getMinecraftAccessToken(xstsToken, xboxLiveToken) } catch { throw MicrosoftAPIError.failedToGetMinecraftAccessToken.becauseOf(error) } // Get a list of the user's licenses let licenses: [GameOwnershipResponse.License] do { licenses = try await MicrosoftAPI.getAttachedLicenses(minecraftAccessToken) } catch { throw MicrosoftAPIError.failedToGetAttachedLicenses.becauseOf(error) } if licenses.isEmpty { throw MicrosoftAPIError.accountDoesntOwnMinecraft } // Get the user's account let account: MicrosoftAccount do { account = try await MicrosoftAPI.getMinecraftAccount(minecraftAccessToken, microsoftAccessToken) } catch { throw MicrosoftAPIError.failedToGetMinecraftAccount.becauseOf(error) } return account } /// Refreshes a Minecraft account which is attached to a Microsoft account. /// - Parameter account: The account to refresh. /// - Returns: The refreshed account. public static func refreshMinecraftAccount(_ account: MicrosoftAccount) async throws -> MicrosoftAccount { log.debug("Start refresh microsoft account") var account = account if account.microsoftAccessToken.hasExpired { account.microsoftAccessToken = try await MicrosoftAPI.refreshMicrosoftAccessToken(account.microsoftAccessToken) } account = try await MicrosoftAPI.getMinecraftAccount(account.microsoftAccessToken) log.debug("Finish refresh microsoft account") return account } // MARK: Private methods /// Acquires a new access token for the user's account using an existing refresh token. /// - Parameter token: The access token to refresh. /// - Returns: The refreshed access token. private static func refreshMicrosoftAccessToken(_ token: MicrosoftAccessToken) async throws -> MicrosoftAccessToken { let formData = [ "client_id": clientId, "refresh_token": token.refreshToken, "grant_type": "refresh_token", "scope": "service::user.auth.xboxlive.com::MBI_SSL" ] let (_, data) = try await RequestUtil.performFormRequest( url: authenticationURL, body: formData, method: .post ) let response: MicrosoftAccessTokenResponse = try decodeResponse(data) let accessToken = MicrosoftAccessToken( token: response.accessToken, expiresIn: response.expiresIn, refreshToken: response.refreshToken ) return accessToken } /// Gets the user's Xbox Live token from their Microsoft access token. /// - Parameters: /// - accessToken: The user's Microsoft access token. /// - Returns: The user's Xbox Live token. private static func getXBoxLiveToken(_ accessToken: MicrosoftAccessToken) async throws -> XboxLiveToken { guard !accessToken.hasExpired else { throw MicrosoftAPIError.expiredAccessToken } let payload = XboxLiveAuthenticationRequest( properties: XboxLiveAuthenticationRequest.Properties( authMethod: "RPS", siteName: "user.auth.xboxlive.com", accessToken: "d=\(accessToken.token)" ), relyingParty: "http://auth.xboxlive.com", tokenType: "JWT" ) let (_, data) = try await RequestUtil.performJSONRequest( url: xboxLiveAuthenticationURL, body: payload, method: .post ) let response: XboxLiveAuthenticationResponse = try decodeResponse(data) guard let userHash = response.displayClaims.xui.first?.userHash else { throw MicrosoftAPIError.noUserHashInResponse } return XboxLiveToken(token: response.token, userHash: userHash) } /// Gets the user's XSTS token from their Xbox Live token. /// - Parameters: /// - xboxLiveToken: The user's Xbox Live token. /// - Returns: The user's XSTS token. private static func getXSTSToken(_ xboxLiveToken: XboxLiveToken) async throws -> String { let payload = XSTSAuthenticationRequest( properties: XSTSAuthenticationRequest.Properties( sandboxId: xstsSandboxId, userTokens: [xboxLiveToken.token] ), relyingParty: xstsRelyingParty, tokenType: "JWT" ) let (_, data) = try await RequestUtil.performJSONRequest( url: xstsAuthenticationURL, body: payload, method: .post ) guard let response: XSTSAuthenticationResponse = try? decodeResponse(data) else { let error: XSTSAuthenticationError do { error = try decodeResponse(data) } catch { throw MicrosoftAPIError.failedToDeserializeResponse .with("Content", String(decoding: data, as: UTF8.self)) .becauseOf(error) } // Decode Microsoft's cryptic error codes let message: String switch error.code { case 2148916233: message = "This Microsoft account does not have an attached Xbox Live account (\(error.redirect))" case 2148916238: message = "Child accounts must first be added to a family (\(error.redirect))" default: message = error.message } throw MicrosoftAPIError.xstsAuthenticationFailed .with("Reason", message) .with("Code", error.code) .with("Identity", error.identity) } return response.token } /// Gets the Minecraft access token from the user's XSTS token. /// - Parameters: /// - xstsToken: The user's XSTS token. /// - xboxLiveToken: The user's Xbox Live token. /// - Returns: The user's Minecraft access token. private static func getMinecraftAccessToken(_ xstsToken: String, _ xboxLiveToken: XboxLiveToken) async throws -> MinecraftAccessToken { let payload = MinecraftXboxAuthenticationRequest( identityToken: "XBL3.0 x=\(xboxLiveToken.userHash);\(xstsToken)" ) let (_, data) = try await RequestUtil.performJSONRequest( url: minecraftXboxAuthenticationURL, body: payload, method: .post ) let response: MinecraftXboxAuthenticationResponse = try decodeResponse(data) let token = MinecraftAccessToken( token: response.accessToken, expiresIn: response.expiresIn ) return token } /// Gets the license attached to an account. /// - Parameters: /// - accessToken: The user's Minecraft access token. /// - Returns: The licenses attached to the user's Microsoft account. private static func getAttachedLicenses(_ accessToken: MinecraftAccessToken) async throws -> [GameOwnershipResponse.License] { var request = Request(gameOwnershipURL) request.method = .get request.headers["Authorization"] = "Bearer \(accessToken.token)" let (_, data) = try await RequestUtil.performRequest(request) let response: GameOwnershipResponse = try decodeResponse(data) return response.items } /// A helper function for decoding JSON responses. /// - Parameter data: The JSON data. /// - Returns: The decoded response. private static func decodeResponse(_ data: Data) throws -> Response { do { return try CustomJSONDecoder().decode(Response.self, from: data) } catch { throw MicrosoftAPIError.failedToDeserializeResponse .with("Content", String(decoding: data, as: UTF8.self)) .becauseOf(error) } } } ================================================ FILE: Sources/Core/Sources/Account/Microsoft/MicrosoftAccessToken.swift ================================================ import Foundation import CoreFoundation /// An access token used for refreshing Minecraft access tokens attached to Microsoft accounts. public struct MicrosoftAccessToken: Codable, Hashable { /// The access token. public var token: String /// The time that the token will expire at in system absolute time. public var expiry: Int /// The token used to acquire a new access token when it expires. public var refreshToken: String /// Whether the access token has expired or not. Includes a leeway of 10 seconds. public var hasExpired: Bool { return Int(CFAbsoluteTimeGetCurrent()) > expiry - 10 } /// Creates a new access token with the given properties. /// - Parameters: /// - token: The access token. /// - expiry: The time that the access token will expire at in system absolute time. /// - refreshToken: The refresh token. public init(token: String, expiry: Int, refreshToken: String) { self.token = token self.expiry = expiry self.refreshToken = refreshToken } /// Creates a new access token with the given properties. /// - Parameters: /// - token: The access token. /// - secondsToLive: The number of seconds until the access token expires. /// - refreshToken: The refresh token. public init(token: String, expiresIn secondsToLive: Int, refreshToken: String) { self.token = token self.expiry = Int(CFAbsoluteTimeGetCurrent()) + secondsToLive self.refreshToken = refreshToken } } ================================================ FILE: Sources/Core/Sources/Account/Microsoft/MicrosoftAccount.swift ================================================ import Foundation /// A user account that authenticates using the new Microsoft method. public struct MicrosoftAccount: Codable, OnlineAccount, Hashable { /// The account's id as a uuid. public var id: String /// The account's username. public var username: String /// The access token used to connect to servers. public var accessToken: MinecraftAccessToken /// The Microsoft access token and refresh token pair. public var microsoftAccessToken: MicrosoftAccessToken /// Creates an account with the given properties. public init( id: String, username: String, minecraftAccessToken: MinecraftAccessToken, microsoftAccessToken: MicrosoftAccessToken ) { self.id = id self.username = username accessToken = minecraftAccessToken self.microsoftAccessToken = microsoftAccessToken } } ================================================ FILE: Sources/Core/Sources/Account/Microsoft/Request/MinecraftXboxAuthenticationRequest.swift ================================================ import Foundation struct MinecraftXboxAuthenticationRequest: Codable { var identityToken: String } ================================================ FILE: Sources/Core/Sources/Account/Microsoft/Request/XSTSAuthenticationRequest.swift ================================================ import Foundation struct XSTSAuthenticationRequest: Codable { struct Properties: Codable { var sandboxId: String var userTokens: [String] // swiftlint:disable nesting enum CodingKeys: String, CodingKey { case sandboxId = "SandboxId" case userTokens = "UserTokens" } // swiftlint:enable nesting } var properties: Properties var relyingParty: String var tokenType: String enum CodingKeys: String, CodingKey { case properties = "Properties" case relyingParty = "RelyingParty" case tokenType = "TokenType" } } ================================================ FILE: Sources/Core/Sources/Account/Microsoft/Request/XboxLiveAuthenticationRequest.swift ================================================ import Foundation struct XboxLiveAuthenticationRequest: Codable { struct Properties: Codable { var authMethod: String var siteName: String var accessToken: String // swiftlint:disable nesting enum CodingKeys: String, CodingKey { case authMethod = "AuthMethod" case siteName = "SiteName" case accessToken = "RpsTicket" } // swiftlint:enable nesting } var properties: Properties var relyingParty: String var tokenType: String enum CodingKeys: String, CodingKey { case properties = "Properties" case relyingParty = "RelyingParty" case tokenType = "TokenType" } } ================================================ FILE: Sources/Core/Sources/Account/Microsoft/Response/GameOwnershipResponse.swift ================================================ import Foundation struct GameOwnershipResponse: Codable { struct License: Codable { var name: String var signature: String } var items: [License] var signature: String var keyId: String } ================================================ FILE: Sources/Core/Sources/Account/Microsoft/Response/MicrosoftAccessTokenResponse.swift ================================================ import Foundation struct MicrosoftAccessTokenResponse: Decodable { var tokenType: String var expiresIn: Int var scope: String var accessToken: String var refreshToken: String enum CodingKeys: String, CodingKey { case tokenType = "token_type" case expiresIn = "expires_in" case scope case accessToken = "access_token" case refreshToken = "refresh_token" } } ================================================ FILE: Sources/Core/Sources/Account/Microsoft/Response/MicrosoftDeviceAuthorizationResponse.swift ================================================ import Foundation public struct MicrosoftDeviceAuthorizationResponse: Decodable { public var deviceCode: String public var userCode: String public var verificationURI: URL public var expiresIn: Int public var interval: Int public var message: String private enum CodingKeys: String, CodingKey { case deviceCode = "device_code" case userCode = "user_code" case verificationURI = "verification_uri" case expiresIn = "expires_in" case interval case message = "message" } } ================================================ FILE: Sources/Core/Sources/Account/Microsoft/Response/MicrosoftMinecraftProfileResponse.swift ================================================ import Foundation struct MicrosoftMinecraftProfileResponse: Decodable { var id: String var name: String var skins: [Skin] var capes: [Cape]? struct Skin: Decodable { var id: String var state: String var url: URL var variant: String var alias: String? } struct Cape: Decodable { var id: String var state: String var url: URL var alias: String? } } ================================================ FILE: Sources/Core/Sources/Account/Microsoft/Response/MinecraftXboxAuthenticationResponse.swift ================================================ import Foundation struct MinecraftXboxAuthenticationResponse: Codable { var username: String var roles: [String] var accessToken: String var tokenType: String var expiresIn: Int enum CodingKeys: String, CodingKey { case username case roles case accessToken = "access_token" case tokenType = "token_type" case expiresIn = "expires_in" } } ================================================ FILE: Sources/Core/Sources/Account/Microsoft/Response/XSTSAuthenticationError.swift ================================================ import Foundation public struct XSTSAuthenticationError: Codable { public let identity: String public let code: Int public let message: String public let redirect: String enum CodingKeys: String, CodingKey { case identity = "Identity" case code = "XErr" case message = "Message" case redirect = "Redirect" } } ================================================ FILE: Sources/Core/Sources/Account/Microsoft/Response/XSTSAuthenticationResponse.swift ================================================ import Foundation struct XSTSAuthenticationResponse: Codable { struct Claims: Codable { var xui: [XUIClaim] } struct XUIClaim: Codable { var userHash: String private enum CodingKeys: String, CodingKey { case userHash = "uhs" } } var issueInstant: String var notAfter: String var token: String var displayClaims: Claims enum CodingKeys: String, CodingKey { case issueInstant = "IssueInstant" case notAfter = "NotAfter" case token = "Token" case displayClaims = "DisplayClaims" } } ================================================ FILE: Sources/Core/Sources/Account/Microsoft/Response/XboxLiveAuthenticationResponse.swift ================================================ import Foundation struct XboxLiveAuthenticationResponse: Codable { struct Claims: Codable { var xui: [XUIClaim] } struct XUIClaim: Codable { var userHash: String // swiftlint:disable nesting enum CodingKeys: String, CodingKey { case userHash = "uhs" } // swiftlint:enable nesting } var issueInstant: String var notAfter: String var token: String var displayClaims: Claims enum CodingKeys: String, CodingKey { case issueInstant = "IssueInstant" case notAfter = "NotAfter" case token = "Token" case displayClaims = "DisplayClaims" } } ================================================ FILE: Sources/Core/Sources/Account/Microsoft/XboxLiveToken.swift ================================================ struct XboxLiveToken { var token: String var userHash: String init(token: String, userHash: String) { self.token = token self.userHash = userHash } } ================================================ FILE: Sources/Core/Sources/Account/MinecraftAccessToken.swift ================================================ import Foundation import CoreFoundation /// An access token attached to an online account. Used for connecting to online-mode servers. public struct MinecraftAccessToken: Codable, Hashable { /// The access token. public var token: String /// The time that the token will expire at in system absolute time. If `nil`, the token won't expire. public var expiry: Int? /// Whether the access token has expired of not. The access token is valid for 10 more seconds after this changes to `true`. public var hasExpired: Bool { guard let expiry = expiry else { return false } return Int(CFAbsoluteTimeGetCurrent()) > expiry - 10 } /// Creates a new access token with the given properties. /// - Parameters: /// - token: The access token. /// - expiry: The time that the access token will expire at in system absolute time. public init(token: String, expiry: Int?) { self.token = token self.expiry = expiry } /// Creates a new access token with the given properties. /// - Parameters: /// - token: The access token. /// - secondsToLive: The number of seconds that the access token is valid for. public init(token: String, expiresIn secondsToLive: Int) { self.token = token self.expiry = Int(CFAbsoluteTimeGetCurrent()) + secondsToLive } } ================================================ FILE: Sources/Core/Sources/Account/Mojang/MojangAPI.swift ================================================ import Foundation public enum MojangAPIError: LocalizedError { case failedToDeserializeResponse(String) public var errorDescription: String? { switch self { case .failedToDeserializeResponse(let string): return """ Failed to deserialize response. Data: \(string) """ } } } /// Used to interface with Mojang's authentication API. public enum MojangAPI { // swiftlint:disable force_unwrapping private static let authenticationURL = URL(string: "https://authserver.mojang.com/authenticate")! private static let joinServerURL = URL(string: "https://sessionserver.mojang.com/session/minecraft/join")! private static let refreshURL = URL(string: "https://authserver.mojang.com/refresh")! // swiftlint:enable force_unwrapping /// Log into a Mojang account using an email and password. /// - Parameters: /// - email: User's email. /// - password: User's password. /// - clientToken: The client's unique token (different for each user). public static func login( email: String, password: String, clientToken: String ) async throws -> Account { let payload = MojangAuthenticationRequest( username: email, password: password, clientToken: clientToken, requestUser: true) let (_, data) = try await RequestUtil.performJSONRequest(url: authenticationURL, body: payload, method: .post) guard let response = try? CustomJSONDecoder().decode(MojangAuthenticationResponse.self, from: data) else { throw MojangAPIError.failedToDeserializeResponse(String(decoding: data, as: UTF8.self)) } let accessToken = MinecraftAccessToken( token: response.accessToken, expiry: nil) let selectedProfile = response.selectedProfile let account = MojangAccount( id: selectedProfile.id, username: response.selectedProfile.name, accessToken: accessToken) return Account.mojang(account) } /// Contacts the Mojang auth servers as part of the join game handshake. /// - Parameters: /// - accessToken: User's access token. /// - selectedProfile: UUID of the user's selected profile (one account can have multiple profiles). /// - serverHash: The hash received from the server that is being joined. public static func join( accessToken: String, selectedProfile: String, serverHash: String ) async throws { let payload = MojangJoinRequest( accessToken: accessToken, selectedProfile: selectedProfile, serverId: serverHash) _ = try await RequestUtil.performJSONRequest(url: joinServerURL, body: payload, method: .post) } /// Refreshes the access token of a Mojang account. /// - Parameters: /// - account: The account to refresh. /// - clientToken: The client's 'unique' token (Delta Client just uses Mojang's). public static func refresh( _ account: MojangAccount, with clientToken: String ) async throws -> MojangAccount { let accessToken = String(account.accessToken.token.split(separator: ".")[1]) let payload = MojangRefreshTokenRequest( accessToken: accessToken, clientToken: clientToken) let (_, data) = try await RequestUtil.performJSONRequest(url: refreshURL, body: payload, method: .post) guard let response = try? CustomJSONDecoder().decode(MojangRefreshTokenResponse.self, from: data) else { throw MojangAPIError.failedToDeserializeResponse(String(decoding: data, as: UTF8.self)) } var refreshedAccount = account refreshedAccount.accessToken = MinecraftAccessToken(token: response.accessToken, expiry: nil) return refreshedAccount } } ================================================ FILE: Sources/Core/Sources/Account/Mojang/MojangAccount.swift ================================================ import Foundation /// A user account that authenticates using the old Mojang method. public struct MojangAccount: Codable, OnlineAccount, Hashable { public var id: String public var username: String public var accessToken: MinecraftAccessToken public init( id: String, username: String, accessToken: MinecraftAccessToken ) { self.id = id self.username = username self.accessToken = accessToken } } ================================================ FILE: Sources/Core/Sources/Account/Mojang/Request/MojangAuthenticationRequest.swift ================================================ import Foundation struct MojangAuthenticationRequest: Encodable { struct MojangAgent: Codable { var name = "Minecraft" var version = 1 } var agent = MojangAgent() var username: String var password: String var clientToken: String var requestUser: Bool } ================================================ FILE: Sources/Core/Sources/Account/Mojang/Request/MojangJoinRequest.swift ================================================ import Foundation struct MojangJoinRequest: Codable { var accessToken: String var selectedProfile: String var serverId: String } ================================================ FILE: Sources/Core/Sources/Account/Mojang/Request/MojangRefreshTokenRequest.swift ================================================ import Foundation struct MojangRefreshTokenRequest: Codable { var accessToken: String var clientToken: String } ================================================ FILE: Sources/Core/Sources/Account/Mojang/Response/MojangAuthenticationResponse.swift ================================================ import Foundation struct MojangAuthenticationResponse: Decodable { struct MojangUser: Codable { var id: String var username: String } struct MojangProfile: Codable { var name: String var id: String } var user: MojangUser var clientToken: String var accessToken: String var selectedProfile: MojangProfile var availableProfiles: [MojangProfile] } ================================================ FILE: Sources/Core/Sources/Account/Mojang/Response/MojangRefreshTokenResponse.swift ================================================ import Foundation struct MojangRefreshTokenResponse: Codable { var accessToken: String } ================================================ FILE: Sources/Core/Sources/Account/OfflineAccount.swift ================================================ import Foundation /// A user account that can only connect to offline mode servers. public struct OfflineAccount: Codable, Hashable { public var id: String public var username: String /// Creates an offline account. /// /// The account's UUID is generated based on the username. /// - Parameter username: The username for the account. public init(username: String) { self.username = username let generatedUUID = UUID.fromString("OfflinePlayer: \(username)")?.uuidString id = generatedUUID ?? UUID().uuidString } } ================================================ FILE: Sources/Core/Sources/Account/OnlineAccount.swift ================================================ /// An account that can be used to join online servers. public protocol OnlineAccount { /// The account id (a UUID). var id: String { get } /// The username. var username: String { get } /// The access token for joining servers. var accessToken: MinecraftAccessToken { get } } ================================================ FILE: Sources/Core/Sources/Cache/BinaryCacheable.swift ================================================ import Foundation /// Allows values of conforming types to easily be cached. public protocol BinaryCacheable: Cacheable, RootBinarySerializable {} /// An error thrown by a type conforming to ``BinaryCacheable``. public enum BinaryCacheableError: LocalizedError { /// Failed to load a value from a binary cache file. case failedToLoadFromCache(BinaryCacheable.Type, Error) /// Failed to cache a value to a binary cache file. case failedToCache(BinaryCacheable.Type, Error) public var errorDescription: String? { switch self { case .failedToLoadFromCache(let type, let error): return """ Failed to load a value from a binary cache file. Type: \(String(describing: type)) Reason: \(error.localizedDescription) """ case .failedToCache(let type, let error): return """ Failed to cache a value to a binary cache file. Type: \(String(describing: type)) Reason: \(error.localizedDescription) """ } } } public extension BinaryCacheable { static func loadCached(from file: URL) throws -> Self { do { return try deserialize(fromFile: file) } catch { throw BinaryCacheableError.failedToLoadFromCache(Self.self, error) } } func cache(to file: URL) throws { do { try serialize(toFile: file) } catch { throw BinaryCacheableError.failedToCache(Self.self, error) } } } ================================================ FILE: Sources/Core/Sources/Cache/BinarySerialization.swift ================================================ import Foundation /// An error thrown during serialization implemented via ``BinarySerializable``. public enum BinarySerializationError: LocalizedError { case invalidSerializationFormatVersion(Int, expectedVersion: Int) case invalidCaseId(Int, type: String) public var errorDescription: String? { switch self { case .invalidSerializationFormatVersion(let version, expectedVersion: let expectedVersion): return """ Invalid serialization format version. Expected: \(expectedVersion) Received: \(version) """ case .invalidCaseId(let id, let type): return """ Invalid enum case id. Id: \(id) Enum: \(type) """ } } } /// An error thrown during deserialization implemented via ``BinarySerializable``. public enum DeserializationError: LocalizedError { case invalidRawValue public var errorDescription: String? { switch self { case .invalidRawValue: return "Encountered an invalid raw value while deserializing a RawRepresentable value." } } } /// A conforming type is able to be serialized and deserialized using Delta Client's custom binary /// caching mechanism. public protocol BinarySerializable { /// Serializes the value into a byte buffer. func serialize(into buffer: inout Buffer) /// Deserializes a value from a byte buffer. static func deserialize(from buffer: inout Buffer) throws -> Self } public extension BinarySerializable { /// Serializes the value into a byte buffer. func serialize() -> Buffer { var buffer = Buffer() serialize(into: &buffer) return buffer } /// Deserializes a value from a byte buffer. static func deserialize(from buffer: Buffer) throws -> Self { var buffer = buffer return try deserialize(from: &buffer) } } /// A conforming type is intended to be the root type of a binary cache and includes a validated /// format version that should be bumped after each change that would effect the format of the cache. public protocol RootBinarySerializable: BinarySerializable { static var serializationFormatVersion: Int { get } } public extension RootBinarySerializable { /// Serializes the value into a byte buffer prefixed by its format version. func serialize() -> Buffer { var buffer = Buffer() Self.serializationFormatVersion.serialize(into: &buffer) serialize(into: &buffer) return buffer } /// Deserializes a value from a byte buffer and verifies that it has the correct format version /// before continuing. static func deserialize(from buffer: Buffer) throws -> Self { var buffer = buffer let incomingVersion = try Int.deserialize(from: &buffer) guard incomingVersion == serializationFormatVersion else { throw BinarySerializationError.invalidSerializationFormatVersion(incomingVersion, expectedVersion: serializationFormatVersion) } return try deserialize(from: &buffer) } /// Serializes this value into a file. func serialize(toFile file: URL) throws { let buffer = serialize() try Data(buffer.bytes).write(to: file) } /// Deserializes a value from a file. static func deserialize(fromFile file: URL) throws -> Self { let data = try Data(contentsOf: file) return try deserialize(from: Buffer([UInt8](data))) } } /// A bitwise copyable type is one that is a value type that takes up contiguous memory with no /// indirection (i.e. doesn't include properties that are arrays, strings, etc.). For your safety, a /// runtime check is performed that ensures that conforming types are actually bitwise copyable /// types (a.k.a. a plain ol' datatypes, see [_isPOD](https://github.com/apple/swift/blob/5a7b8c7922348179cc6dbc7281108e59d94ccecb/stdlib/public/core/Builtin.swift#L709)) /// /// The ``BinarySerializable`` implementation provided by conforming to this marker protocol essentially /// just copies the raw bytes of a type into the output for serialization, and reverses the process /// extremely efficiently when deserializing using unsafe pointers. Bitwise copyable types are the /// fastest types to serialize and deserialize. public protocol BitwiseCopyable: BinarySerializable {} public extension BitwiseCopyable { @inline(__always) func serialize(into buffer: inout Buffer) { precondition(_isPOD(Self.self), "\(type(of: self)) must be a bitwise copyable datatype to conform to BitwiseCopyable") var value = self withUnsafeBytes(of: &value) { bufferPointer in let pointer = bufferPointer.assumingMemoryBound(to: UInt8.self).baseAddress! for i in 0...size { buffer.writeByte(pointer.advanced(by: i).pointee) } if MemoryLayout.size == MemoryLayout.stride { return } // Padding with zeroes is required to avoid segfaults that would occur if the last type // serialized into a buffer was a type that had mismatching size and stride and the length of // the buffer happened to be aligned with the end of a page. Using a for loop seems to be the // fastest way to do this with Swift's array API. There would definitely be faster ways in C. for _ in MemoryLayout.size...stride { buffer.writeByte(0) } } } @inline(__always) static func deserialize(from buffer: inout Buffer) throws -> Self { precondition(_isPOD(Self.self), "\(type(of: self)) must be a bitwise copyable datatype to conform to BitwiseCopyable") let index = buffer.index buffer.index += MemoryLayout.stride return buffer.bytes.withUnsafeBytes { pointer in return pointer.loadUnaligned(fromByteOffset: index, as: Self.self) } } } extension Bool: BitwiseCopyable {} extension Int: BitwiseCopyable {} extension UInt: BitwiseCopyable {} extension Int64: BitwiseCopyable {} extension UInt64: BitwiseCopyable {} extension Int32: BitwiseCopyable {} extension UInt32: BitwiseCopyable {} extension Int16: BitwiseCopyable {} extension UInt16: BitwiseCopyable {} extension Int8: BitwiseCopyable {} extension UInt8: BitwiseCopyable {} extension Float: BitwiseCopyable {} extension Double: BitwiseCopyable {} extension Matrix2x2: BitwiseCopyable, BinarySerializable {} extension Matrix3x3: BitwiseCopyable, BinarySerializable {} extension Matrix4x4: BitwiseCopyable, BinarySerializable {} extension SIMD2: BitwiseCopyable, BinarySerializable {} extension SIMD3: BitwiseCopyable, BinarySerializable {} extension SIMD4: BitwiseCopyable, BinarySerializable {} extension SIMD8: BitwiseCopyable, BinarySerializable {} extension SIMD16: BitwiseCopyable, BinarySerializable {} extension SIMD32: BitwiseCopyable, BinarySerializable {} extension SIMD64: BitwiseCopyable, BinarySerializable {} extension String: BinarySerializable { public func serialize(into buffer: inout Buffer) { count.serialize(into: &buffer) buffer.writeString(self) } public static func deserialize(from buffer: inout Buffer) throws -> Self { let count = try Int.deserialize(from: &buffer) return try buffer.readString(length: count) } } extension Character: BinarySerializable { public func serialize(into buffer: inout Buffer) { self.utf8.count.serialize(into: &buffer) buffer.writeBytes([UInt8](self.utf8)) } public static func deserialize(from buffer: inout Buffer) throws -> Self { let count = try Int.deserialize(from: &buffer) let bytes = try buffer.readBytes(count) guard let string = String(bytes: bytes, encoding: .utf8) else { throw BufferError.invalidByteInUTF8String } return Character(string) } } public extension BinarySerializable where Self: RawRepresentable, RawValue: BinarySerializable { func serialize(into buffer: inout Buffer) { rawValue.serialize(into: &buffer) } static func deserialize(from buffer: inout Buffer) throws -> Self { guard let value = Self(rawValue: try .deserialize(from: &buffer)) else { throw DeserializationError.invalidRawValue } return value } } extension Array: BinarySerializable where Element: BinarySerializable { public func serialize(into buffer: inout Buffer) { count.serialize(into: &buffer) for element in self { element.serialize(into: &buffer) } } public static func deserialize(from buffer: inout Buffer) throws -> [Element] { let count = try Int.deserialize(from: &buffer) var array: [Element] = [] array.reserveCapacity(count) for _ in 0.. Set { let count = try Int.deserialize(from: &buffer) var set: Set = [] set.reserveCapacity(count) for _ in 0.. Wrapped? { let isPresent = try Bool.deserialize(from: &buffer) if isPresent { return try Wrapped.deserialize(from: &buffer) } else { return nil } } } extension Dictionary: BinarySerializable where Key: BinarySerializable, Value: BinarySerializable { public func serialize(into buffer: inout Buffer) { count.serialize(into: &buffer) for (key, value) in self { key.serialize(into: &buffer) value.serialize(into: &buffer) } } public static func deserialize(from buffer: inout Buffer) throws -> Dictionary { let count = try Int.deserialize(from: &buffer) var dictionary: [Key: Value] = [:] dictionary.reserveCapacity(count) for _ in 0.. BlockModelPalette { return BlockModelPalette( models: try .deserialize(from: &buffer), displayTransforms: try .deserialize(from: &buffer), identifierToIndex: try .deserialize(from: &buffer), fullyOpaqueBlocks: try [Bool].deserialize(from: &buffer) ) } } extension Identifier: BinarySerializable { public func serialize(into buffer: inout Buffer) { namespace.serialize(into: &buffer) name.serialize(into: &buffer) } public static func deserialize(from buffer: inout Buffer) throws -> Identifier { return Identifier( namespace: try .deserialize(from: &buffer), name: try .deserialize(from: &buffer) ) } } extension BlockModel: BinarySerializable { public func serialize(into buffer: inout Buffer) { parts.serialize(into: &buffer) cullingFaces.serialize(into: &buffer) cullableFaces.serialize(into: &buffer) nonCullableFaces.serialize(into: &buffer) textureType.serialize(into: &buffer) } public static func deserialize(from buffer: inout Buffer) throws -> BlockModel { return BlockModel( parts: try .deserialize(from: &buffer), cullingFaces: try .deserialize(from: &buffer), cullableFaces: try .deserialize(from: &buffer), nonCullableFaces: try .deserialize(from: &buffer), textureType: try .deserialize(from: &buffer) ) } } extension BlockModelPart: BinarySerializable { public func serialize(into buffer: inout Buffer) { ambientOcclusion.serialize(into: &buffer) displayTransformsIndex.serialize(into: &buffer) elements.serialize(into: &buffer) } public static func deserialize(from buffer: inout Buffer) throws -> BlockModelPart { return BlockModelPart( ambientOcclusion: try .deserialize(from: &buffer), displayTransformsIndex: try .deserialize(from: &buffer), elements: try .deserialize(from: &buffer) ) } } extension BlockModelElement: BinarySerializable { public func serialize(into buffer: inout Buffer) { transformation.serialize(into: &buffer) shade.serialize(into: &buffer) faces.serialize(into: &buffer) } public static func deserialize(from buffer: inout Buffer) throws -> BlockModelElement { return BlockModelElement( transformation: try .deserialize(from: &buffer), shade: try .deserialize(from: &buffer), faces: try .deserialize(from: &buffer) ) } } extension BlockModelFace: BitwiseCopyable {} ================================================ FILE: Sources/Core/Sources/Cache/Cacheable.swift ================================================ import Foundation /// Conforming types can be cached to disk with ease. public protocol Cacheable { /// The default cache file name for this type. Used for ``Cacheable/loadCached(fromDirectory:)`` /// and ``Cacheable/cache(toDirectory:)``. static var defaultCacheFileName: String { get } /// Loads a cached value from a cache directory. See ``cacheFileName`` for a type's default cache /// file name. static func loadCached(from file: URL) throws -> Self /// Caches this value to a cache directory. See ``cacheFileName`` for a type's default cache file /// name. func cache(to file: URL) throws } public extension Cacheable { static var defaultCacheFileName: String { let base = String(describing: Self.self) let fileType: String if (Self.self as? JSONCacheable.Type) != nil { fileType = "json" } else { fileType = "bin" } return "\(base).\(fileType)" } static func loadCached(fromDirectory directory: URL) throws -> Self { return try loadCached(from: directory.appendingPathComponent(defaultCacheFileName)) } func cache(toDirectory directory: URL) throws { try cache(to: directory.appendingPathComponent(Self.defaultCacheFileName)) } } ================================================ FILE: Sources/Core/Sources/Cache/FontPalette+BinaryCacheable.swift ================================================ extension FontPalette: BinaryCacheable { public static var serializationFormatVersion: Int { return 0 } public func serialize(into buffer: inout Buffer) { fonts.serialize(into: &buffer) } public static func deserialize(from buffer: inout Buffer) throws -> FontPalette { return FontPalette(try .deserialize(from: &buffer)) } } extension Font: BinarySerializable { public func serialize(into buffer: inout Buffer) { characters.serialize(into: &buffer) asciiCharacters.serialize(into: &buffer) textures.serialize(into: &buffer) } public static func deserialize(from buffer: inout Buffer) throws -> Font { return Font( characters: try .deserialize(from: &buffer), asciiCharacters: try .deserialize(from: &buffer), textures: try .deserialize(from: &buffer) ) } } extension CharacterDescriptor: BitwiseCopyable {} ================================================ FILE: Sources/Core/Sources/Cache/ItemModelPalette+BinaryCacheable.swift ================================================ extension ItemModelPalette: BinaryCacheable { public static var serializationFormatVersion: Int { return 0 } public func serialize(into buffer: inout Buffer) { models.serialize(into: &buffer) } public static func deserialize(from buffer: inout Buffer) throws -> ItemModelPalette { return ItemModelPalette( try .deserialize(from: &buffer) ) } } extension ItemModel: BinarySerializable { public func serialize(into buffer: inout Buffer) { switch self { case .layered(let textureIndices, let transforms): 0.serialize(into: &buffer) textureIndices.serialize(into: &buffer) transforms.serialize(into: &buffer) case .blockModel(let id): 1.serialize(into: &buffer) id.serialize(into: &buffer) case .entity(let identifier, let transforms): 2.serialize(into: &buffer) identifier.serialize(into: &buffer) transforms.serialize(into: &buffer) case .empty: 3.serialize(into: &buffer) } } public static func deserialize(from buffer: inout Buffer) throws -> ItemModel { let caseId = try Int.deserialize(from: &buffer) switch caseId { case 0: return .layered( textureIndices: try .deserialize(from: &buffer), transforms: try .deserialize(from: &buffer) ) case 1: return .blockModel(id: try .deserialize(from: &buffer)) case 2: return .entity( try .deserialize(from: &buffer), transforms: try .deserialize(from: &buffer) ) case 3: return .empty default: throw BinarySerializationError.invalidCaseId(caseId, type: String(describing: Self.self)) } } } extension ItemModelTexture: BitwiseCopyable {} ================================================ FILE: Sources/Core/Sources/Cache/Registry/BiomeRegistry+JSONCacheable.swift ================================================ extension BiomeRegistry: JSONCacheable {} ================================================ FILE: Sources/Core/Sources/Cache/Registry/BlockRegistry+BinaryCacheable.swift ================================================ extension Block.Tint: BitwiseCopyable {} extension Block.Offset: BitwiseCopyable {} extension Block.PhysicalMaterial: BitwiseCopyable {} extension Block.LightMaterial: BitwiseCopyable {} extension Block.SoundMaterial: BitwiseCopyable {} extension FluidState: BitwiseCopyable {} extension AxisAlignedBoundingBox: BitwiseCopyable {} extension Block.StateProperties: BitwiseCopyable {} extension BlockRegistry: BinaryCacheable { public static var serializationFormatVersion: Int { return 0 } public func serialize(into buffer: inout Buffer) { blocks.serialize(into: &buffer) renderDescriptors.serialize(into: &buffer) selfCullingBlocks.serialize(into: &buffer) airBlocks.serialize(into: &buffer) } public static func deserialize(from buffer: inout Buffer) throws -> BlockRegistry { return BlockRegistry( blocks: try .deserialize(from: &buffer), renderDescriptors: try .deserialize(from: &buffer), selfCullingBlocks: try .deserialize(from: &buffer), airBlocks: try .deserialize(from: &buffer) ) } } extension Block: BinarySerializable { public func serialize(into buffer: inout Buffer) { id.serialize(into: &buffer) vanillaParentBlockId.serialize(into: &buffer) identifier.serialize(into: &buffer) className.serialize(into: &buffer) fluidState.serialize(into: &buffer) tint.serialize(into: &buffer) offset.serialize(into: &buffer) vanillaMaterialIdentifier.serialize(into: &buffer) physicalMaterial.serialize(into: &buffer) lightMaterial.serialize(into: &buffer) soundMaterial.serialize(into: &buffer) shape.serialize(into: &buffer) stateProperties.serialize(into: &buffer) } public static func deserialize(from buffer: inout Buffer) throws -> Block { return Block( id: try .deserialize(from: &buffer), vanillaParentBlockId: try .deserialize(from: &buffer), identifier: try .deserialize(from: &buffer), className: try .deserialize(from: &buffer), fluidState: try .deserialize(from: &buffer), tint: try .deserialize(from: &buffer), offset: try .deserialize(from: &buffer), vanillaMaterialIdentifier: try .deserialize(from: &buffer), physicalMaterial: try .deserialize(from: &buffer), lightMaterial: try .deserialize(from: &buffer), soundMaterial: try .deserialize(from: &buffer), shape: try .deserialize(from: &buffer), stateProperties: try .deserialize(from: &buffer) ) } } extension Block.Shape: BinarySerializable { public func serialize(into buffer: inout Buffer) { isDynamic.serialize(into: &buffer) isLarge.serialize(into: &buffer) collisionShape.serialize(into: &buffer) outlineShape.serialize(into: &buffer) occlusionShapeIds.serialize(into: &buffer) isSturdy.serialize(into: &buffer) } public static func deserialize(from buffer: inout Buffer) throws -> Block.Shape { return Block.Shape( isDynamic: try .deserialize(from: &buffer), isLarge: try .deserialize(from: &buffer), collisionShape: try .deserialize(from: &buffer), outlineShape: try .deserialize(from: &buffer), occlusionShapeIds: try .deserialize(from: &buffer), isSturdy: try .deserialize(from: &buffer) ) } } extension CompoundBoundingBox: BinarySerializable { public func serialize(into buffer: inout Buffer) { aabbs.serialize(into: &buffer) } public static func deserialize(from buffer: inout Buffer) throws -> CompoundBoundingBox { return CompoundBoundingBox(try .deserialize(from: &buffer)) } } extension BlockModelRenderDescriptor: BinarySerializable { public func serialize(into buffer: inout Buffer) { model.serialize(into: &buffer) xRotationDegrees.serialize(into: &buffer) yRotationDegrees.serialize(into: &buffer) uvLock.serialize(into: &buffer) } public static func deserialize(from buffer: inout Buffer) throws -> BlockModelRenderDescriptor { return BlockModelRenderDescriptor( model: try .deserialize(from: &buffer), xRotationDegrees: try .deserialize(from: &buffer), yRotationDegrees: try .deserialize(from: &buffer), uvLock: try .deserialize(from: &buffer) ) } } ================================================ FILE: Sources/Core/Sources/Cache/Registry/EntityRegistry+JSONCacheable.swift ================================================ extension EntityRegistry: JSONCacheable {} ================================================ FILE: Sources/Core/Sources/Cache/Registry/FluidRegistry+JSONCacheable.swift ================================================ extension FluidRegistry: JSONCacheable {} ================================================ FILE: Sources/Core/Sources/Cache/Registry/ItemRegistry+JSONCacheable.swift ================================================ extension ItemRegistry: JSONCacheable {} ================================================ FILE: Sources/Core/Sources/Cache/Registry/JSONCacheable.swift ================================================ import Foundation /// Allows ``Codable`` types to easily conform to the ``Cacheable`` protocol. public protocol JSONCacheable: Cacheable, Codable {} public enum JSONCacheableError: LocalizedError { /// Failed to load a value from a JSON cache file. case failedToLoadFromCache(JSONCacheable.Type, Error) /// Failed to cache a value to a JSON cache file. case failedToCache(JSONCacheable.Type, Error) public var errorDescription: String? { switch self { case .failedToLoadFromCache(let type, let error): return """ Failed to load a value from a JSON cache file. Type: \(String(describing: type)) Reason: \(error.localizedDescription) """ case .failedToCache(let type, let error): return """ Failed to cache a value to a binary cache file. Type: \(String(describing: type)) Reason: \(error.localizedDescription) """ } } } public extension JSONCacheable { static func loadCached(from file: URL) throws -> Self { do { let data = try Data(contentsOf: file) return try CustomJSONDecoder().decode(Self.self, from: data) } catch { throw JSONCacheableError.failedToLoadFromCache(Self.self, error) } } func cache(to file: URL) throws { do { let data = try JSONEncoder().encode(self) try data.write(to: file) } catch { throw JSONCacheableError.failedToCache(Self.self, error) } } } ================================================ FILE: Sources/Core/Sources/Cache/TexturePalette+BinaryCacheable.swift ================================================ import SwiftImage extension TexturePalette: BinaryCacheable { public static var serializationFormatVersion: Int { return 0 } public func serialize(into buffer: inout Buffer) { textures.serialize(into: &buffer) width.serialize(into: &buffer) height.serialize(into: &buffer) identifierToIndex.serialize(into: &buffer) } public static func deserialize(from buffer: inout Buffer) throws -> TexturePalette { return TexturePalette( textures: try .deserialize(from: &buffer), width: try .deserialize(from: &buffer), height: try .deserialize(from: &buffer), identifierToIndex: try .deserialize(from: &buffer) ) } } extension Texture: BinarySerializable { public func serialize(into buffer: inout Buffer) { type.serialize(into: &buffer) image.serialize(into: &buffer) animation.serialize(into: &buffer) frameCount.serialize(into: &buffer) } public static func deserialize(from buffer: inout Buffer) throws -> Texture { return Texture( type: try .deserialize(from: &buffer), image: try .deserialize(from: &buffer), animation: try .deserialize(from: &buffer), frameCount: try .deserialize(from: &buffer) ) } } extension Texture.BGRA: BitwiseCopyable {} extension Image: BinarySerializable where Pixel: BinarySerializable { public func serialize(into buffer: inout Buffer) { width.serialize(into: &buffer) height.serialize(into: &buffer) (width * height).serialize(into: &buffer) // Simplifies deserialization self.withUnsafeBytes { pixelBuffer in let pointer = pixelBuffer.assumingMemoryBound(to: UInt8.self).baseAddress! for i in 0.. Self { return Self( width: try .deserialize(from: &buffer), height: try .deserialize(from: &buffer), pixels: try .deserialize(from: &buffer) ) } } extension Texture.Animation: BinarySerializable { public func serialize(into buffer: inout Buffer) { interpolate.serialize(into: &buffer) frames.serialize(into: &buffer) } public static func deserialize(from buffer: inout Buffer) throws -> Texture.Animation { return Texture.Animation( interpolate: try .deserialize(from: &buffer), frames: try .deserialize(from: &buffer) ) } } extension Texture.Animation.Frame: BitwiseCopyable {} ================================================ FILE: Sources/Core/Sources/Chat/Chat.swift ================================================ import Collections /// Storage for a game's chat. public struct Chat { public static let maximumScrollback = 200 /// All messages sent and received. public var messages: Deque = [] /// Creates an empty chat. public init() {} /// Add a message to the chat. /// - Parameter message: The message to add. public mutating func add(_ message: ChatMessage) { messages.append(message) if messages.count > Self.maximumScrollback { messages.removeFirst() } } } ================================================ FILE: Sources/Core/Sources/Chat/ChatComponent/ChatComponent.swift ================================================ /// A component of a chat message. public struct ChatComponent: Decodable, Equatable { /// The component's style. var style: Style /// The component's content. var content: Content /// The component's children (displayed directly after ``content``). var children: [ChatComponent] private enum CodingKeys: String, CodingKey { case children = "extra" case text case translationIdentifier = "translate" case translationContent = "with" case score case keybind } /// Creates a new chat component. /// - Parameters: /// - style: The component's style (inherited by children). /// - content: The component's content. /// - children: The component's children (dsplayed directly after ``content``). public init(style: Style, content: Content, children: [ChatComponent] = []) { self.style = style self.content = content self.children = children } public init(from decoder: Decoder) throws { let container: KeyedDecodingContainer do { container = try decoder.container(keyedBy: CodingKeys.self) } catch { let content = try decoder.singleValueContainer().decode(String.self) style = Style() self.content = Content.string(content) children = [] return } style = try Style(from: decoder) if container.contains(.children) { children = try container.decode([ChatComponent].self, forKey: .children) } else { children = [] } if container.contains(.text) { let string: String if let integer = try? container.decode(Int.self, forKey: .text) { string = String(integer) } else if let boolean = try? container.decode(Bool.self, forKey: .text) { string = String(boolean) } else { string = try container.decode(String.self, forKey: .text) } content = .string(string) } else if container.contains(.score) { let score = try container.decode(ScoreContent.self, forKey: .score) content = .score(score) } else if container.contains(.keybind) { let keybind = try container.decode(String.self, forKey: .keybind) content = .keybind(keybind) } else if container.contains(.translationIdentifier) { let identifier = try container.decode(String.self, forKey: .translationIdentifier) let translationContent: [ChatComponent] if container.contains(.translationContent) { translationContent = try container.decode([ChatComponent].self, forKey: .translationContent) } else { translationContent = [] } content = .translation(LocalizedContent(translateKey: identifier, content: translationContent)) } else { throw ChatComponentError.invalidChatComponentType } } /// Converts the chat component to plain text. /// - Parameter locale: The locale to use when resolving localized components. /// - Returns: The component's contents as plain text. public func toText(with locale: MinecraftLocale) -> String { var output = content.toText(with: locale) for child in children { output += child.toText(with: locale) } // Remove legacy formatted text style codes let legacy = LegacyFormattedText(output) return legacy.toString() } } ================================================ FILE: Sources/Core/Sources/Chat/ChatComponent/ChatComponentColor.swift ================================================ import Foundation extension ChatComponent { /// A component's color. public enum Color: String, Codable, Equatable { // TODO: handle hex code colors case white case black case gray case darkGray = "dark_gray" case red case darkRed = "dark_red" case gold case yellow case green case darkGreen = "dark_green" case aqua case darkAqua = "dark_aqua" case blue case darkBlue = "dark_blue" case purple = "light_purple" case darkPurple = "dark_purple" case reset } } ================================================ FILE: Sources/Core/Sources/Chat/ChatComponent/ChatComponentContent.swift ================================================ extension ChatComponent { /// The content of a chat component. public enum Content: Equatable { case string(String) case keybind(String) case score(ScoreContent) case translation(LocalizedContent) /// Converts the content to plain text. /// - Parameter locale: The locale to use when resolving localized content. /// - Returns: The content as plain text. public func toText(with locale: MinecraftLocale) -> String { switch self { case .string(let string): return string case .keybind(let keybind): // TODO: read the keybind's value from configuration return keybind case .score(let score): // TODO: load score value in `score.value` is nil return "\(score.name):\(score.objective):\(score.value ?? "unknown_value")" case .translation(let localizedContent): return locale.getTranslation(for: localizedContent.translateKey, with: localizedContent.content.map { component in return component.toText(with: locale) }) } } } } ================================================ FILE: Sources/Core/Sources/Chat/ChatComponent/ChatComponentError.swift ================================================ import Foundation /// An error thrown by ``ChatComponent`` and related types. public enum ChatComponentError: LocalizedError { case invalidChatComponentType public var errorDescription: String? { switch self { case .invalidChatComponentType: return "Invalid chat component type." } } } ================================================ FILE: Sources/Core/Sources/Chat/ChatComponent/ChatComponentLocalizedContent.swift ================================================ extension ChatComponent { /// The content of a localized component. public struct LocalizedContent: Equatable { /// The identifier of the localized template to use. public var translateKey: String /// Content to replace placeholders in the localized template with. public var content: [ChatComponent] } } ================================================ FILE: Sources/Core/Sources/Chat/ChatComponent/ChatComponentScoreContent.swift ================================================ import Foundation extension ChatComponent { /// The content of a score component. public struct ScoreContent: Codable, Equatable { /// The name of the user to display the score of. `*` indicates the current user. public var name: String /// The objective to display the score for. public var objective: String /// The score's value. If `nil`, the score value should be loaded from the world. public var value: String? } } ================================================ FILE: Sources/Core/Sources/Chat/ChatComponent/ChatComponentStyle.swift ================================================ import Foundation extension ChatComponent { public struct Style: Decodable, Equatable { /// If `true`, the text is **bold**. public var bold: Bool? /// If `true`, the text is *italic*. public var italic: Bool? /// If `true`, the text has an underline. public var underlined: Bool? /// If `true`, the text has a ~~line through the middle~~. public var strikethrough: Bool? /// If `true`, each character of the text cycles through characters of the same width to hide the message. public var obfuscated: Bool? /// The color of text. public var color: Color? private enum CodingKeys: String, CodingKey { case bold case italic case underlined case strikethrough case obfuscated case color } /// Creates a chat style. Defaults to white text with no decoration. public init( bold: Bool? = nil, italic: Bool? = nil, underlined: Bool? = nil, strikethrough: Bool? = nil, obfuscated: Bool? = nil, color: Color? = nil ) { self.bold = bold self.italic = italic self.underlined = underlined self.strikethrough = strikethrough self.obfuscated = obfuscated self.color = color } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) bold = (try? container.decode(Bool.self, forKey: .bold)) italic = (try? container.decode(Bool.self, forKey: .italic)) underlined = (try? container.decode(Bool.self, forKey: .underlined)) strikethrough = (try? container.decode(Bool.self, forKey: .strikethrough)) obfuscated = (try? container.decode(Bool.self, forKey: .obfuscated)) color = (try? container.decode(Color.self, forKey: .color)) } } } ================================================ FILE: Sources/Core/Sources/Chat/ChatMessage.swift ================================================ import Foundation import CoreFoundation /// A chat message. public struct ChatMessage { /// The content of the message. public var content: ChatComponent /// The uuid of the message's sender. public var sender: UUID /// The time at which the message was received. public var timeReceived: CFAbsoluteTime /// Creates a new chat message. /// - Parameters: /// - content: The message of the message (includes `` when received from /// vanilla server). /// - sender: The uuid of the message's sender. /// - timeReceived: The time at which the message was received. Defaults to the current time. public init( content: ChatComponent, sender: UUID, timeReceived: CFAbsoluteTime = CFAbsoluteTimeGetCurrent() ) { self.content = content self.sender = sender self.timeReceived = timeReceived } } ================================================ FILE: Sources/Core/Sources/Chat/LegacyFormattedText/LegacyFormattedText.swift ================================================ import Foundation #if canImport(AppKit) import AppKit #elseif canImport(UIKit) import CoreGraphics import UIKit #endif /// Text formatted using legacy formatting codes. /// /// [See the wiki for more information on legacy formatting codes](https://minecraft.fandom.com/wiki/Formatting_codes) public struct LegacyFormattedText { /// The styled tokens that form the text. public var tokens: [Token] /// Parses a string containing legacy formatting codes into styled tokens. public init(_ string: String) { // This will always succeed because lenient parsing doesn't throw any errors // swiftlint:disable force_try self = try! Self.parse(string, strict: false) // swiftlint:enable force_try } /// Creates legacy formatted text from tokens. public init(_ tokens: [Token]) { self.tokens = tokens } /// When `strict` is `true`, no errors are thrown. public static func parse(_ string: String, strict: Bool) throws -> LegacyFormattedText { var tokens: [Token] = [] var currentColor: Color? var currentStyle: Style? let parts = string.split(separator: "§", omittingEmptySubsequences: false) for (i, part) in parts.enumerated() { // First token always has no formatting code if i == 0 { guard part != "" else { continue } tokens.append(Token(string: String(part), color: nil, style: nil)) continue } // First character is formatting code guard let character = part.first else { if strict { throw LegacyFormattedTextError.missingFormattingCodeCharacter } continue } // Rest is content let content = String(part.dropFirst()) guard let code = FormattingCode(rawValue: character) else { if strict { throw LegacyFormattedTextError.invalidFormattingCodeCharacter(character) } tokens.append(Token(string: content, color: nil, style: nil)) continue } // Update formatting state switch code { case .style(.reset): currentStyle = nil currentColor = nil case let .color(color): currentColor = color // Using a color code resets the style in Java Edition currentStyle = nil case let .style(style): currentStyle = style } guard !content.isEmpty else { continue } tokens.append(Token(string: content, color: currentColor, style: currentStyle)) } return LegacyFormattedText(tokens) } /// - Returns: The string as plaintext (with styling removed) public func toString() -> String { return tokens.map(\.string).joined() } #if canImport(Darwin) /// Creates an attributed string representing the formatted text. /// - Parameter fontSize: The size of font to use. /// - Returns: The formatted string. public func attributedString(fontSize: CGFloat) -> NSAttributedString { let font = FontUtil.systemFont(ofSize: fontSize) let output = NSMutableAttributedString(string: "") for token in tokens { var attributes: [NSAttributedString.Key: Any] = [:] var font = font if let color = token.color { let color = ColorUtil.color(fromHexString: color.hex) attributes[.foregroundColor] = color attributes[.strikethroughColor] = color attributes[.underlineColor] = color } if let style = token.style { switch style { case .bold: font = font.bold() ?? font case .strikethrough: attributes[.strikethroughStyle] = NSUnderlineStyle.single.rawValue case .underline: attributes[.underlineStyle] = NSUnderlineStyle.single.rawValue case .italic: font = font.italics() ?? font case .reset: break } } attributes[.font] = font output.append(NSAttributedString( string: token.string, attributes: attributes )) } return output } #endif } ================================================ FILE: Sources/Core/Sources/Chat/LegacyFormattedText/LegacyFormattedTextColor.swift ================================================ extension LegacyFormattedText { /// A legacy text color formatting code. public enum Color: Character { case black = "0" case darkBlue = "1" case darkGreen = "2" case darkAqua = "3" case darkRed = "4" case darkPurple = "5" case gold = "6" case gray = "7" case darkGray = "8" case blue = "9" case green = "a" case aqua = "b" case red = "c" case lightPurple = "d" case yellow = "e" case white = "f" /// The hex value of the color. public var hex: String { switch self { case .black: return "#000000" case .darkBlue: return "#0000AA" case .darkGreen: return "#00AA00" case .darkAqua: return "#00AAAA" case .darkRed: return "#AA0000" case .darkPurple: return "#AA00AA" case .gold: return "#FFAA00" case .gray: return "#AAAAAA" case .darkGray: return "#555555" case .blue: return "#5555FF" case .green: return "#55FF55" case .aqua: return "#55FFFF" case .red: return "#FF5555" case .lightPurple: return "#FF55FF" case .yellow: return "#FFFF55" case .white: return "#FFFFFF" } } } } ================================================ FILE: Sources/Core/Sources/Chat/LegacyFormattedText/LegacyFormattedTextError.swift ================================================ import Foundation public enum LegacyFormattedTextError: Error { case missingFormattingCodeCharacter case invalidFormattingCodeCharacter(Character) } ================================================ FILE: Sources/Core/Sources/Chat/LegacyFormattedText/LegacyFormattedTextFormattingCode.swift ================================================ extension LegacyFormattedText { /// A legacy text formatting code. /// /// [Reference](https://minecraft.fandom.com/wiki/Formatting_codes) public enum FormattingCode: RawRepresentable { case color(Color) case style(Style) public var rawValue: Character { switch self { case let .color(color): return color.rawValue case let .style(style): return style.rawValue } } public init?(rawValue: Character) { if let color = Color(rawValue: rawValue) { self = .color(color) } else if let style = Style(rawValue: rawValue) { self = .style(style) } else { return nil } } } } ================================================ FILE: Sources/Core/Sources/Chat/LegacyFormattedText/LegacyFormattedTextStyle.swift ================================================ extension LegacyFormattedText { /// A legacy text style formatting code. public enum Style: Character { case bold = "l" case strikethrough = "m" case underline = "n" case italic = "o" case reset = "r" } } ================================================ FILE: Sources/Core/Sources/Chat/LegacyFormattedText/LegacyFormattedTextToken.swift ================================================ extension LegacyFormattedText { /// A formatted text token. public struct Token: Equatable { let string: String let color: Color? let style: Style? } } ================================================ FILE: Sources/Core/Sources/Client.swift ================================================ import Foundation // TODO: Make client actually Sendable /// A client creates and maintains a connection to a server and handles the received packets. public final class Client: @unchecked Sendable { // MARK: Public properties /// The resource pack to use. public var resourcePack: ResourcePack /// The account this client uses to join servers. public var account: Account? /// The game this client is playing in. public var game: Game /// The client's configuration. public let configuration: ClientConfiguration /// The connection to the current server. public var connection: ServerConnection? /// An event bus shared with ``game``. public var eventBus = EventBus() /// Whether the client has finished downloading terrain yet. public var hasFinishedDownloadingTerrain = false // MARK: Init /// Creates a new client instance. /// - Parameter resourcePack: The resources to use. /// - Parameter configuration: The clientside configuration. public init(resourcePack: ResourcePack, configuration: ClientConfiguration) { self.resourcePack = resourcePack self.configuration = configuration game = Game( eventBus: eventBus, configuration: configuration, font: resourcePack.vanillaResources.fontPalette.defaultFont, locale: resourcePack.getDefaultLocale() ) } deinit { game.tickScheduler.cancel() connection?.close() } // MARK: Connection lifecycle /// Join the specified server. Throws if the packets fail to send. public func joinServer( describedBy descriptor: ServerDescriptor, with account: Account ) async throws { self.account = account // Create a connection to the server let connection = try await ServerConnection( descriptor: descriptor, eventBus: eventBus ) connection.setPacketHandler { [weak self] packet in guard let self = self else { return } self.handlePacket(packet) } game.stopTickScheduler() game = Game( eventBus: eventBus, configuration: configuration, connection: connection, font: resourcePack.vanillaResources.fontPalette.defaultFont, locale: resourcePack.getDefaultLocale() ) hasFinishedDownloadingTerrain = false try connection.login(username: account.username) self.connection = connection } /// Disconnect from the currently connected server if any. public func disconnect() { // Close connection connection?.close() connection = nil // Reset chunk storage game.changeWorld(to: World(eventBus: eventBus)) // Stop ticking game.tickScheduler.cancel() } // MARK: Networking /// Send a packet to the server currently connected to (if any). public func sendPacket(_ packet: ServerboundPacket) throws { try connection?.sendPacket(packet) } /// The client's packet handler. public func handlePacket(_ packet: ClientboundPacket) { do { if let entityPacket = packet as? ClientboundEntityPacket { game.handleDuringTick(entityPacket, client: self) } else { try packet.handle(for: self) } } catch { disconnect() log.error("Failed to handle packet: \(error)") eventBus.dispatch(PacketHandlingErrorEvent(packetId: type(of: packet).id, error: "\(error)")) } } // MARK: Input /// Handles a key press. /// - Parameters: /// - key: The pressed key. /// - characters: The characters typed by pressing the key. public func press(_ key: Key, _ characters: [Character] = []) { let input = configuration.keymap.getInput(for: key) game.press(key: key, input: input, characters: characters) } /// Handles an input press. /// - Parameter input: The pressed input. public func press(_ input: Input) { game.press(key: nil, input: input) } /// Handles a key release. /// - Parameter key: The released key. public func release(_ key: Key) { let input = configuration.keymap.getInput(for: key) game.release(key: key, input: input) } /// Handles an input release. /// - Parameter input: The released input. public func release(_ input: Input) { game.release(key: nil, input: input) } /// Releases all inputs. public func releaseAllInputs() { game.releaseAllInputs() } /// Moves the mouse. /// /// `deltaX` and `deltaY` aren't just the difference between the current and /// previous values of `x` and `y` because there are ways for the mouse to /// appear at a new position without causing in-game movement (e.g. if the /// user opens the in-game menu, moves the mouse, and then closes the in-game /// menu). /// - Parameters: /// - x: The absolute mouse x (relative to the play area's top left corner). /// - y: The absolute mouse y (relative to the play area's top left corner). /// - deltaX: The change in mouse x. /// - deltaY: The change in mouse y. public func moveMouse(x: Float, y: Float, deltaX: Float, deltaY: Float) { // TODO: Update this API (and everything else reliant on it) so that DeltaCore // is the one that decides which input events to ignore (instead of InputView // (and similar) deciding whether an event should be given to Client or not). // This will allow the deltaX and deltaY parameters to be removed. game.moveMouse(x: x, y: y, deltaX: deltaX, deltaY: deltaY) } /// Moves the left thumbstick. /// - Parameters: /// - x: The x position. /// - y: The y position. public func moveLeftThumbstick(_ x: Float, _ y: Float) { game.moveLeftThumbstick(x, y) } /// Moves the right thumbstick. /// - Parameters: /// - x: The x position. /// - y: The y position. public func moveRightThumbstick(_ x: Float, _ y: Float) { game.moveRightThumbstick(x, y) } } ================================================ FILE: Sources/Core/Sources/ClientConfiguration.swift ================================================ /// Clientside configuration such as keymap and clientside render distance. /// Any package creating a Client instance should implement this protocol to allow DeltaCore to access configuration values. public protocol ClientConfiguration { /// The configuration related to rendering. var render: RenderConfiguration { get } /// The configured keymap. var keymap: Keymap { get } /// Whether to use the sprint key as a toggle. var toggleSprint: Bool { get } /// Whether to use the sneak key as a toggle. var toggleSneak: Bool { get } } ================================================ FILE: Sources/Core/Sources/Constants.swift ================================================ import Foundation public enum Constants { public static let protocolVersion = 736 public static let versionString = "1.16.1" public static let locale = "en_us" public static let textureSize = 16 public static let packFormatVersion = 5 } ================================================ FILE: Sources/Core/Sources/Datatypes/Axis.swift ================================================ import Foundation /// An axis public enum Axis: CaseIterable { case x case y case z /// The positive direction along this axis in Minecraft's coordinate system. public var positiveDirection: Direction { switch self { case .x: return .east case .y: return .up case .z: return .south } } /// The negative direction along this axis in Minecraft's coordinate system. public var negativeDirection: Direction { switch self { case .x: return .west case .y: return .down case .z: return .north } } /// The conventional indices assigned to the axis, i.e. x -> 0, y -> 1, z -> 2 public var index: Int { switch self { case .x: return 0 case .y: return 1 case .z: return 2 } } } ================================================ FILE: Sources/Core/Sources/Datatypes/BlockPosition.swift ================================================ import FirebladeMath import Foundation /// A block position. public struct BlockPosition { /// The origin. public static let zero = BlockPosition(x: 0, y: 0, z: 0) /// The x component. public var x: Int /// The y component. public var y: Int /// The z component. public var z: Int /// The position of the ``Chunk`` this position is in public var chunk: ChunkPosition { let chunkX = x >> 4 // divides by 16 and rounds down let chunkZ = z >> 4 return ChunkPosition(chunkX: chunkX, chunkZ: chunkZ) } /// The position of the ``Chunk/Section`` this position is in public var chunkSection: ChunkSectionPosition { let sectionX = x >> 4 // divides by 16 and rounds down let sectionY = y >> 4 let sectionZ = z >> 4 return ChunkSectionPosition(sectionX: sectionX, sectionY: sectionY, sectionZ: sectionZ) } /// This position relative to the ``Chunk`` it's in public var relativeToChunk: BlockPosition { let relativeX = x &- chunk.chunkX &* Chunk.Section.width let relativeZ = z &- chunk.chunkZ &* Chunk.Section.depth return BlockPosition(x: relativeX, y: y, z: relativeZ) } /// This position relative to the ``Chunk/Section`` it's in public var relativeToChunkSection: BlockPosition { let relativeX = x &- chunk.chunkX &* Chunk.Section.width let relativeZ = z &- chunk.chunkZ &* Chunk.Section.depth let relativeY = y &- sectionIndex &* Chunk.Section.height return BlockPosition(x: relativeX, y: relativeY, z: relativeZ) } /// This position as a vector of floats. public var floatVector: Vec3f { return Vec3f( Float(x), Float(y), Float(z) ) } /// This position as a vector of doubles. public var doubleVector: Vec3d { return Vec3d( Double(x), Double(y), Double(z) ) } /// This position as a vector of ints. public var intVector: Vec3i { return Vec3i(x, y, z) } /// The positions neighbouring this position. public var neighbours: [BlockPosition] { Direction.allDirections.map { self + $0.intVector } } /// The block index of the position. /// /// Block indices are in order of increasing x-coordinate, in rows of increasing /// z-coordinate, in layers of increasing y. If that doesn't make sense read the /// implementation. public var blockIndex: Int { return (y &* Chunk.depth &+ z) &* Chunk.width &+ x } /// The biomes index of the position. /// /// Biome indices are in order of increasing x-coordinate, in rows of increasing /// z-coordinate, in layers of increasing y. If that doesn't make sense read the /// implementation. Each biome is a 4x4x4 area, and that's the only reason that /// this calculation differs from ``blockIndex``. public var biomeIndex: Int { return (y / 4 &* Chunk.depth / 4 &+ z / 4) &* Chunk.width / 4 &+ x / 4 } /// The section Y of the section this position is in public var sectionIndex: Int { let index = y / Chunk.Section.height if y < 0 { return index - 1 } else { return index } } /// Create a new block position. /// /// Coordinates are not validated. /// - Parameters: /// - x: The x coordinate. /// - y: The y coordinate. /// - z: The z coordinate. public init(x: Int, y: Int, z: Int) { self.x = x self.y = y self.z = z } /// Component-wise addition of two block positions. public static func + (lhs: BlockPosition, rhs: Vec3i) -> BlockPosition { return BlockPosition(x: lhs.x &+ rhs.x, y: lhs.y &+ rhs.y, z: lhs.z &+ rhs.z) } /// Gets the position of the neighbouring block in the given direction. public func neighbour(_ direction: Direction) -> BlockPosition { return self + direction.intVector } } extension BlockPosition: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(x) hasher.combine(y) hasher.combine(z) } } ================================================ FILE: Sources/Core/Sources/Datatypes/CardinalDirection.swift ================================================ import Foundation /// An axis aligned compass direction (i.e. either North, East, South or West). public enum CardinalDirection: CaseIterable { case north case east case south case west /// The opposite direction. public var opposite: CardinalDirection { let oppositeMap: [CardinalDirection: CardinalDirection] = [ .north: .south, .south: .north, .east: .west, .west: .east] return oppositeMap[self]! } } ================================================ FILE: Sources/Core/Sources/Datatypes/Difficulty.swift ================================================ import Foundation public enum Difficulty: UInt8 { case peaceful = 0 case easy = 1 case normal = 2 case hard = 3 } ================================================ FILE: Sources/Core/Sources/Datatypes/Direction.swift ================================================ import FirebladeMath import Foundation /// A direction enum where the raw value is the same as in some of the Minecraft packets. public enum Direction: Int, CustomStringConvertible { case down = 0 case up = 1 case north = 2 case south = 3 case west = 4 case east = 5 /// The array of all directions. public static let allDirections: [Direction] = [ .north, .south, .east, .west, .up, .down, ] /// All directions excluding up and down. public static let sides: [Direction] = [ .north, .east, .south, .west, ] public var description: String { switch self { case .down: return "down" case .up: return "up" case .north: return "north" case .south: return "south" case .west: return "west" case .east: return "east" } } /// Returns the directions on the xz plane that are perpendicular to a direction. public var perpendicularXZ: [Direction] { switch self { case .north, .south: return [.east, .west] case .east, .west: return [.north, .south] case .up, .down: return [.north, .east, .south, .west] } } /// The axis this direction lies on. public var axis: Axis { switch self { case .west, .east: return .x case .up, .down: return .y case .north, .south: return .z } } /// Whether the direction is a positive direction in Minecraft's coordinate system or not. public var isPositive: Bool { switch self { case .up, .south, .east: return true case .down, .north, .west: return false } } /// The direction pointing the opposite direction to this one. public var opposite: Direction { switch self { case .down: return .up case .up: return .down case .north: return .south case .south: return .north case .east: return .west case .west: return .east } } /// Creates a direction from a string such as `"down"`. public init?(string: String) { switch string { case "down": self = .down case "up": self = .up case "north": self = .north case "south": self = .south case "west": self = .west case "east": self = .east default: return nil } } /// A normalized vector representing this direction. public var vector: Vec3f { Vec3f(intVector) } /// A normalized vector representing this direction. public var doubleVector: Vec3d { Vec3d(intVector) } /// A normalized vector representing this direction. public var intVector: Vec3i { switch self { case .down: return Vec3i(0, -1, 0) case .up: return Vec3i(0, 1, 0) case .north: return Vec3i(0, 0, -1) case .south: return Vec3i(0, 0, 1) case .west: return Vec3i(-1, 0, 0) case .east: return Vec3i(1, 0, 0) } } /// Returns the direction `n` 90 degree clockwise rotations around the axis while facing `referenceDirection`. public func rotated(_ n: Int, clockwiseFacing referenceDirection: Direction) -> Direction { // The three 'loops' of directions around the three axes. The directions are listed clockwise when looking in the negative direction along the axis. let loops: [Axis: [Direction]] = [ .x: [.up, .north, .down, .south], .y: [.north, .east, .south, .west], .z: [.up, .east, .down, .west], ] switch self { case referenceDirection, referenceDirection.opposite: return self default: // This is safe because all axes are defined in the dictionary let loop = loops[referenceDirection.axis]! // This is safe because all four directions that are handled by this case will be in the loop let index = loop.firstIndex(of: self)! var newIndex: Int if referenceDirection.isPositive { newIndex = index - n } else { newIndex = index + n } newIndex = MathUtil.mod(newIndex, loop.count) return loop[newIndex] } } } extension Direction: Codable { public init(from decoder: Decoder) throws { let string = try decoder.singleValueContainer().decode(String.self) guard let direction = Direction(string: string) else { throw DecodingError.dataCorrupted( .init( codingPath: decoder.codingPath, debugDescription: "Invalid direction '\(string)'" ) ) } self = direction } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(description) } } ================================================ FILE: Sources/Core/Sources/Datatypes/DirectionSet.swift ================================================ /// A set of directions. public struct DirectionSet: SetAlgebra, Equatable { public typealias Element = Direction public var rawValue: UInt8 public static let north = DirectionSet(containing: .north) public static let south = DirectionSet(containing: .south) public static let east = DirectionSet(containing: .east) public static let west = DirectionSet(containing: .west) public static let up = DirectionSet(containing: .up) public static let down = DirectionSet(containing: .down) /// The set of all directions. public static let all: DirectionSet = [ .north, .south, .east, .west, .up, .down ] public var isEmpty: Bool { return rawValue == 0 } public init() { rawValue = 0 } public init(rawValue: UInt8) { self.rawValue = rawValue } public init(containing direction: Direction) { rawValue = Self.directionMask(direction) } public init(_ sequence: S) where S.Element == Direction { self.init() for element in sequence { insert(element) } } private static func directionMask(_ direction: Direction) -> UInt8 { return 1 << direction.rawValue } public func contains(_ direction: Direction) -> Bool { return rawValue & Self.directionMask(direction) != 0 } @discardableResult public mutating func insert(_ direction: Direction) -> (inserted: Bool, memberAfterInsert: Direction) { let oldRawValue = rawValue rawValue |= Self.directionMask(direction) return (inserted: oldRawValue != rawValue, memberAfterInsert: direction) } @discardableResult public mutating func update(with direction: Direction) -> Direction? { let oldRawValue = rawValue rawValue |= Self.directionMask(direction) return oldRawValue == rawValue ? nil : direction } @discardableResult public mutating func remove(_ direction: Direction) -> Direction? { let oldRawValue = rawValue rawValue &= ~Self.directionMask(direction) return oldRawValue == rawValue ? nil : direction } public func union(_ other: DirectionSet) -> DirectionSet { return DirectionSet(rawValue: rawValue | other.rawValue) } public mutating func formUnion(_ other: DirectionSet) { rawValue |= other.rawValue } public func intersection(_ other: DirectionSet) -> DirectionSet { return DirectionSet(rawValue: rawValue & other.rawValue) } public mutating func formIntersection(_ other: DirectionSet) { rawValue &= other.rawValue } public func symmetricDifference(_ other: DirectionSet) -> DirectionSet { return DirectionSet(rawValue: rawValue ^ other.rawValue) } public mutating func formSymmetricDifference(_ other: DirectionSet) { rawValue ^= other.rawValue } public func isStrictSubset(of other: DirectionSet) -> Bool { return rawValue != other.rawValue && intersection(other).rawValue == rawValue } public func isStrictSuperset(of other: DirectionSet) -> Bool { return other.isStrictSubset(of: self) } public func isDisjoint(with other: DirectionSet) -> Bool { return subtracting(other).rawValue == rawValue } public func isSubset(of other: DirectionSet) -> Bool { return intersection(other).rawValue == rawValue } public func isSuperset(of other: DirectionSet) -> Bool { return other.isSubset(of: self) } public mutating func subtract(_ other: DirectionSet) { rawValue &= ~other.rawValue } public func subtracting(_ other: DirectionSet) -> DirectionSet { return DirectionSet(rawValue: rawValue & (~other.rawValue)) } } ================================================ FILE: Sources/Core/Sources/Datatypes/DominantHand.swift ================================================ import Foundation public enum DominantHand: Int32 { case left = 0 case right = 1 } ================================================ FILE: Sources/Core/Sources/Datatypes/Equipment.swift ================================================ import Foundation public struct Equipment { public var slot: UInt8 public var item: Slot } ================================================ FILE: Sources/Core/Sources/Datatypes/Gamemode.swift ================================================ import Foundation /// The player's gamemode. Each gamemode gives the player different abilities. public enum Gamemode: Int8 { case survival = 0 case creative = 1 case adventure = 2 case spectator = 3 /// Whether the player is always flying when in this gamemode. public var isAlwaysFlying: Bool { return self == .spectator } /// Whether the player collides with the world or not when in this gamemode. public var hasCollisions: Bool { return self != .spectator } /// Whether the gamemode has visible health. public var hasHealth: Bool { switch self { case .survival, .adventure: return true case .creative, .spectator: return false } } public var canBreakBlocks: Bool { switch self { case .survival, .creative: return true case .adventure, .spectator: return false } } public var canPlaceBlocks: Bool { switch self { case .survival, .creative: return true case .adventure, .spectator: return false } } /// The lowercase string representation of the gamemode. public var string: String { switch self { case .survival: return "survival" case .creative: return "creative" case .adventure: return "adventure" case .spectator: return "spectator" } } } ================================================ FILE: Sources/Core/Sources/Datatypes/Hand.swift ================================================ import Foundation public enum Hand: Int32 { case mainHand = 0 case offHand = 1 } ================================================ FILE: Sources/Core/Sources/Datatypes/Identifier.swift ================================================ import Foundation import Parsing /// An identifier consists of a namespace and a name, they are used by Mojang a lot. public struct Identifier: Hashable, Equatable, Codable, CustomStringConvertible { // MARK: Public properties /// The namespace of the identifier. public var namespace: String /// The name of the identifier. public var name: String /// The string representation of this identifier. public var description: String { return "\(namespace):\(name)" } // MARK: Private properties /// The set of characters allowed in an identifier namespace. private static let namespaceAllowedCharacters = Set("0123456789abcdefghijklmnopqrstuvwxyz-_") /// The set of characters allowed in an identifier name. private static let nameAllowedCharacters = Set("0123456789abcdefghijklmnopqrstuvwxyz-_./") /// The parser used to parse identifiers from strings. private static let identifierParser = OneOf { Parse { Prefix(1...) { namespaceAllowedCharacters.contains($0) } Optionally { ":" Prefix(1...) { nameAllowedCharacters.contains($0) } } End() }.map { tuple -> Identifier in if let name = tuple.1 { return Identifier(namespace: String(tuple.0), name: String(name)) } else { return Identifier(name: String(tuple.0)) } } // Required for the case where an identifier has no namespace and the name contains characters not allowed in a namespace Parse { Prefix { nameAllowedCharacters.contains($0) } End() }.map { name -> Identifier in return Identifier(name: String(name)) } } // MARK: Init /// Creates an identifier with the given name and namespace. /// - Parameters: /// - namespace: The namespace for the identifier. /// - name: The name for the identifier. public init(namespace: String, name: String) { self.namespace = namespace self.name = name } /// Creates an identifier with the given name and the `"minecraft"` namespace. /// /// This is separate from ``Identifier/init(namespace:name:)`` so that it can be used it expressions /// such as `["dirt", "wood"].map(Identifier.init(name:))` (which a single init with a default argument /// wouldn't enable). /// - Parameters: /// - name: The name for the identifier. public init(name: String) { self.namespace = "minecraft" self.name = name } /// Creates an identifier from the given string. Throws if the string is not a valid identifier. /// - Parameter string: String of the form `"namespace:name"` or `"name"`. public init(_ string: String) throws { do { let identifier = try Self.identifierParser.parse(string) name = identifier.name namespace = identifier.namespace } catch { throw IdentifierError.invalidIdentifier(string, error) } } public init(from decoder: Decoder) throws { do { // Decode identifiers in the form ["namespace", "name"] (it's a lot faster than string form) var container = try decoder.unkeyedContainer() let namespace = try container.decode(String.self) let name = try container.decode(String.self) self.init(namespace: namespace, name: name) } catch { // If the previous decoding method files the value is likely stored as a single string (of the form "namespace:name") let container = try decoder.singleValueContainer() let string = try container.decode(String.self) try self.init(string) } } // MARK: Public methods /// Hashes the identifier. public func hash(into hasher: inout Hasher) { hasher.combine(namespace) hasher.combine(name) } public static func == (lhs: Identifier, rhs: Identifier) -> Bool { return lhs.namespace == rhs.namespace && lhs.name == rhs.name } /// Encodes the identifier in the form `["namespace", "name"]` (because it's the most efficient way). public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(namespace) try container.encode(name) } } ================================================ FILE: Sources/Core/Sources/Datatypes/IdentifierError.swift ================================================ import Foundation public enum IdentifierError: LocalizedError { case invalidIdentifier(String, Error) public var errorDescription: String? { switch self { case .invalidIdentifier(let string, let error): return """ Invalid identifier for string: \(string). Reason: \(error.localizedDescription) """ } } } ================================================ FILE: Sources/Core/Sources/Datatypes/ItemStack.swift ================================================ import Foundation // TODO: Refactor item stacks and recipes /// A stack of items. public struct ItemStack { /// The item that is stacked. public var itemId: Int /// The number of items in the stack. public var count: Int /// Any extra properties the items have. public var nbt: NBT.Compound // TODO: refactor this away /// Creates a new item stack. public init(itemId: Int, itemCount: Int, nbt: NBT.Compound? = nil) { self.itemId = itemId self.count = itemCount self.nbt = nbt ?? NBT.Compound() } } ================================================ FILE: Sources/Core/Sources/Datatypes/NBT/NBT.swift ================================================ /// NBT is essentially Mojang's take on protocol buffers. /// /// It stands for 'Named Binary Tags' and is basically what it sounds like. /// In my NBT system it should be assumed all tags are big endian and signed /// unless a type name specifies otherwise. public enum NBT { } ================================================ FILE: Sources/Core/Sources/Datatypes/NBT/NBTCompound.swift ================================================ import Foundation public enum NBTError: LocalizedError { case emptyList case invalidListType case invalidTagType case rootTagNotCompound case failedToGetList(_ key: String) case failedToGetTag(_ key: String) case failedToOpenURL public var errorDescription: String? { switch self { case .emptyList: return "Empty list." case .invalidListType: return "Invalid list type." case .invalidTagType: return "Invalid tag type." case .rootTagNotCompound: return "Root tag not compound." case .failedToGetList(let key): return "Failed to get list for key: \(key)." case .failedToGetTag(let key): return "Failed to get tag for key: \(key)." case .failedToOpenURL: return "Failed to open URL." } } } // all tags are assumed to be big endian and signed unless otherwise specified // TODO: Clean up NBT decoder extension NBT { /// An container for NBT tags. A bit like an object in JSON. public struct Compound: CustomStringConvertible { public var buffer: Buffer public var tags: [String: Tag] = [:] public var name: String = "" public var numBytes = -1 public var isRoot: Bool public var description: String { return "\(tags)" } // MARK: Init public init(name: String = "", isRoot: Bool = false) { self.buffer = Buffer() self.isRoot = isRoot self.name = name } public init(fromBytes bytes: [UInt8], isRoot: Bool = true) throws { try self.init(fromBuffer: Buffer(bytes), isRoot: isRoot) } public init(fromBuffer buffer: Buffer, withName name: String = "", isRoot: Bool = true) throws { let initialBufferIndex = buffer.index self.buffer = buffer self.isRoot = isRoot self.name = name try unpack() if isRoot && !tags.isEmpty { let root: Compound = try get("") tags = root.tags self.name = root.name } let numBytesRead = self.buffer.index - initialBufferIndex numBytes = numBytesRead } public init(fromURL url: URL) throws { let data: Data do { data = try Data(contentsOf: url) } catch { throw NBTError.failedToOpenURL } let bytes = [UInt8](data) try self.init(fromBytes: bytes) } // MARK: Getters public func get(_ key: String) throws -> T { guard let value = tags[key]?.value, let tag = value as? T else { throw NBTError.failedToGetTag(key) } return tag } public func getList(_ key: String) throws -> T { guard let nbtList = tags[key]?.value as? List else { throw NBTError.failedToGetList(key) } guard let list = nbtList.list as? T else { throw NBTError.failedToGetList(key) } return list } // MARK: Unpacking public mutating func unpack() throws { var n = 0 while true { let typeId = try buffer.readByte() if let type = TagType(rawValue: typeId) { if type == .end { break } let nameLength = Int(try buffer.readShort(endianness: .big)) let name = try buffer.readString(length: nameLength) tags[name] = try readTag(ofType: type, withId: n, andName: name) } else { // type not valid throw NBTError.invalidTagType } // the root tag should only contain one command if isRoot { break } n += 1 } } private mutating func readTag(ofType type: TagType, withId id: Int = 0, andName name: String = "") throws -> Tag { var value: Any? switch type { case .end: break case .byte: value = try buffer.readSignedByte() case .short: value = try buffer.readSignedShort(endianness: .big) case .int: value = try buffer.readSignedInteger(endianness: .big) case .long: value = try buffer.readSignedLong(endianness: .big) case .float: value = try buffer.readFloat(endianness: .big) case .double: value = try buffer.readDouble(endianness: .big) case .byteArray: let length = Int(try buffer.readSignedInteger(endianness: .big)) value = try buffer.readSignedBytes(length) case .string: let length = Int(try buffer.readShort(endianness: .big)) value = try buffer.readString(length: length) case .list: let typeId = try buffer.readByte() if let listType = TagType(rawValue: typeId) { let length = try buffer.readSignedInteger(endianness: .big) if length < 0 { throw NBTError.emptyList } var list = List(type: listType) if length != 0 { for _ in 0.. [UInt8] { buffer = Buffer() let tags = self.tags.values if isRoot { buffer.writeByte(TagType.compound.rawValue) writeName(self.name) } for tag in tags { buffer.writeByte(tag.type.rawValue) writeName(tag.name!) writeTag(tag) } writeTag(Tag(id: 0, type: .end, value: nil)) return buffer.bytes } private mutating func writeName(_ name: String) { buffer.writeShort(UInt16(name.utf8.count), endianness: .big) buffer.writeString(name) } // TODO: Remove force casts // swiftlint:disable force_cast private mutating func writeTag(_ tag: Tag) { switch tag.type { case .end: buffer.writeByte(0) case .byte: buffer.writeSignedByte(tag.value as! Int8) case .short: buffer.writeSignedShort(tag.value as! Int16, endianness: .big) case .int: buffer.writeSignedInt(tag.value as! Int32, endianness: .big) case .long: buffer.writeSignedLong(tag.value as! Int64, endianness: .big) case .float: buffer.writeFloat(tag.value as! Float, endianness: .big) case .double: buffer.writeDouble(tag.value as! Double, endianness: .big) case .byteArray: buffer.writeBytes(tag.value as! [UInt8]) case .string: let string = tag.value as! String buffer.writeShort(UInt16(string.utf8.count), endianness: .big) buffer.writeString(string) case .list: let list = tag.value as! List let listType = list.type let listLength = list.count buffer.writeByte(listType.rawValue) buffer.writeSignedInt(Int32(listLength), endianness: .big) for elem in list.list { let value = Tag(id: 0, type: listType, value: elem) writeTag(value) } case .compound: var compound = tag.value as! Compound buffer.writeBytes(compound.pack()) case .intArray: let array = tag.value as! [Int32] let length = Int32(array.count) buffer.writeSignedInt(length, endianness: .big) for int in array { buffer.writeSignedInt(int, endianness: .big) } case .longArray: let array = tag.value as! [Int64] let length = Int32(array.count) buffer.writeSignedInt(length, endianness: .big) for int in array { buffer.writeSignedLong(int, endianness: .big) } } } // swiftlint:enable force_cast } } ================================================ FILE: Sources/Core/Sources/Datatypes/NBT/NBTList.swift ================================================ import Foundation // TODO: figure out how to not use Any extension NBT { /// An array of unnamed NBT tags of the same type. public struct List: CustomStringConvertible { public var type: TagType public var list: [Any] = [] public var description: String { return "\(list)" } public var count: Int { return list.count } public mutating func append(_ elem: Any) { list.append(elem) } } } ================================================ FILE: Sources/Core/Sources/Datatypes/NBT/NBTTag.swift ================================================ import Foundation extension NBT { /// An NBT tag holds a name (unless in an NBT list), a type, and a value. public struct Tag: CustomStringConvertible { public var id: Int public var name: String? public var type: TagType public var value: Any? public var description: String { if value != nil { if value is Compound { return "\(value!)" } return "\"\(value!)\"" } else { return "nil" } } } } ================================================ FILE: Sources/Core/Sources/Datatypes/NBT/NBTTagType.swift ================================================ import Foundation extension NBT { /// All possible NBT tag types public enum TagType: UInt8 { case end = 0 case byte = 1 case short = 2 case int = 3 case long = 4 case float = 5 case double = 6 case byteArray = 7 case string = 8 case list = 9 case compound = 10 case intArray = 11 case longArray = 12 } } ================================================ FILE: Sources/Core/Sources/Datatypes/PlayerEntityAction.swift ================================================ import Foundation public enum PlayerEntityAction: Int32 { case startSneaking = 0 case stopSneaking = 1 case leaveBed = 2 case startSprinting = 3 case stopSprinting = 4 case startHorseJump = 5 case stopHorseJump = 6 case openHorseInventory = 7 case startElytraFlying = 8 } ================================================ FILE: Sources/Core/Sources/Datatypes/PlayerFlags.swift ================================================ import Foundation public struct PlayerFlags: OptionSet { public let rawValue: UInt8 public init(rawValue: UInt8) { self.rawValue = rawValue } public static let invulnerable = PlayerFlags(rawValue: 0x01) public static let flying = PlayerFlags(rawValue: 0x02) public static let canFly = PlayerFlags(rawValue: 0x04) public static let instantBreak = PlayerFlags(rawValue: 0x08) } ================================================ FILE: Sources/Core/Sources/Datatypes/Slot.swift ================================================ /// An inventory slot. public struct Slot { /// The slot's content if any. public var stack: ItemStack? /// Creates a new slot. /// - Parameter stack: The slot's content. public init(_ stack: ItemStack? = nil) { self.stack = stack } } ================================================ FILE: Sources/Core/Sources/Datatypes/Statistic.swift ================================================ import Foundation public struct Statistic { public var categoryId: Int public var statisticId: Int public var value: Int } ================================================ FILE: Sources/Core/Sources/Datatypes/UUID.swift ================================================ import Foundation // adding a convenience method to more consistently get a UUID from a string (cause minecraft randomly gives you ones without hyphens) extension UUID { static func fromString(_ string: String) -> UUID? { let cleanedString: String var matches = string.range(of: "^[a-fA-F0-9]{8}-([a-fA-F0-9]{4}-){3}[a-fA-F0-9]{12}$", options: .regularExpression) if matches != nil { cleanedString = string } else { matches = string.range(of: "^[a-fA-F0-9]{32}", options: .regularExpression) if matches != nil { let tempString = NSMutableString(string: string) tempString.insert("-", at: 20) tempString.insert("-", at: 16) tempString.insert("-", at: 12) tempString.insert("-", at: 8) cleanedString = tempString as String } else { return nil } } return UUID(uuidString: cleanedString) } func toBytes() -> [UInt8] { let (u1, u2, u3, u4, u5, u6, u7, u8, u9, u10, u11, u12, u13, u14, u15, u16) = self.uuid return [u1, u2, u3, u4, u5, u6, u7, u8, u9, u10, u11, u12, u13, u14, u15, u16] } } ================================================ FILE: Sources/Core/Sources/Duration.swift ================================================ /// A duration of time. public struct Duration: CustomStringConvertible { /// The duration in seconds. public var seconds: Double /// The duration in milliseconds. public var milliseconds: Double { seconds * 1_000 } /// The duration in microseconds. public var microseconds: Double { seconds * 1_000_000 } /// The duration in nanoseconds. public var nanoseconds: Double { seconds * 1_000_000_000 } /// A description of the duration with units appropriate for its magnitude. public var description: String { if seconds >= 1 { return String(format: "%.04fs", seconds) } else if milliseconds >= 1 { return String(format: "%.04fms", milliseconds) } else if microseconds >= 1 { return String(format: "%.04fμs", microseconds) } else { return String(format: "%.04fns", nanoseconds) } } /// Creates a duration measured in seconds. public static func seconds(_ seconds: Double) -> Self { Self(seconds: seconds) } /// Creates a duration measured in milliseconds. public static func milliseconds(_ milliseconds: Double) -> Self { Self(seconds: milliseconds / 1_000) } /// Creates a duration measured in microseconds. public static func microseconds(_ microseconds: Double) -> Self { Self(seconds: microseconds / 1_000_000) } /// Creates a duration measured in nanoseconds. public static func nanoseconds(_ nanoseconds: Double) -> Self { Self(seconds: nanoseconds / 1_000_000_000) } } ================================================ FILE: Sources/Core/Sources/ECS/BlockEntity.swift ================================================ import Foundation /// Metadata about a block. public struct BlockEntity { /// The position of the block that this metadata applies to. public let position: BlockPosition /// Identifier of the block that this metadata is for. public let identifier: Identifier /// Metadata stored in the nbt format. public let nbt: NBT.Compound } ================================================ FILE: Sources/Core/Sources/ECS/Components/EnderDragonParts.swift ================================================ import FirebladeECS public class EnderDragonParts: Component { public var head = Part( .head, size: Vec2d(1, 1), entityIdOffset: 1, relativePosition: Vec3d(-0.5, 0, 1) ) public var neck = Part( .neck, size: Vec2d(3, 3), entityIdOffset: 2, relativePosition: Vec3d(-1.5, -1, -2) ) public var body = Part( .body, size: Vec2d(5, 3), entityIdOffset: 3, relativePosition: Vec3d(-2.5, -1, -4) ) // TODO: Verify the entity id offsets of these public var upperTail = Part( .tail, size: Vec2d(2, 2), entityIdOffset: 4, relativePosition: Vec3d(-1, -0.5, -5) ) public var midTail = Part( .tail, size: Vec2d(2, 2), entityIdOffset: 5, relativePosition: Vec3d(-1, -0.5, -6) ) public var lowerTail = Part( .tail, size: Vec2d(2, 2), entityIdOffset: 6, relativePosition: Vec3d(-1, -0.5, -7) ) public var leftWing = Part( .wing, size: Vec2d(4, 2), entityIdOffset: 7, relativePosition: Vec3d(2, 0, -4) ) public var rightWing = Part( .wing, size: Vec2d(4, 2), entityIdOffset: 8, relativePosition: Vec3d(-6, 0, -4) ) /// All parts. public var parts: [Part] { [head, neck, body, upperTail, midTail, lowerTail, leftWing, rightWing] } public init() {} public struct Part { /// Group that this part is a member of (e.g. tail). public var group: Group /// The size of the part's hitbox as a width (x and z) and a height (y). public var size: Vec2d /// The offset of this part's entity id from the parent entity's id. public var entityIdOffset: Int /// Position relative to parent entity. public var relativePosition: Vec3d public enum Group { case head case neck case body case tail case wing } public init( _ group: Group, size: Vec2d, entityIdOffset: Int, relativePosition: Vec3d ) { self.group = group self.size = size self.entityIdOffset = entityIdOffset self.relativePosition = relativePosition } public func aabb(withParentPosition parentPosition: Vec3d) -> AxisAlignedBoundingBox { AxisAlignedBoundingBox( position: parentPosition + relativePosition, size: Vec3d(size.x, size.y, size.x) ) } } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityAcceleration.swift ================================================ import FirebladeECS import FirebladeMath /// A component storing an entity's acceleration. public class EntityAcceleration: Component { // MARK: Public properties /// The vector representing this acceleration. public var vector: Vec3d /// x component in blocks per tick. public var x: Double { get { vector.x } set { vector.x = newValue } } /// y component in blocks per tick. public var y: Double { get { vector.y } set { vector.y = newValue } } /// z component in blocks per tick. public var z: Double { get { vector.z } set { vector.z = newValue } } // MARK: Init /// Creates an entity's acceleration. /// - Parameter vector: Vector representing the acceleration. public init(_ vector: Vec3d) { self.vector = vector } /// Creates an entity's acceleration. /// - Parameters: /// - x: x component. /// - y: y component. /// - z: z component. public convenience init(_ x: Double, _ y: Double, _ z: Double) { self.init(Vec3d(x, y, z)) } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityAttributes.swift ================================================ import FirebladeECS /// A component storing an entity's attributes. See ``EntityMetadata`` for a /// discussion on the difference between metadata and attributes. public class EntityAttributes: Component { /// The attributes as key-value pairs. private var attributes: [EntityAttributeKey: EntityAttributeValue] = [:] /// Creates a new component with the default value for each attribute. public init() {} /// Gets and sets the value of an attribute. If the attribute has no value, the default value is returned. public subscript(_ attribute: EntityAttributeKey) -> EntityAttributeValue { get { return attributes[attribute] ?? EntityAttributeValue(baseValue: attribute.defaultValue) } set(newValue) { attributes[attribute] = newValue } } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityCamera.swift ================================================ import FirebladeECS /// A component storing an entity's camera properties. public class EntityCamera: Component { /// A camera perspective. public enum Perspective: Int, Codable, CaseIterable { /// Rendered as if looking from the entity's eyes. case firstPerson /// Rendered from behind the entity's head, looking at the back of the entity's head. case thirdPersonRear /// Rendered in front of the entity's head, looking at the entity's face. case thirdPersonFront } /// The current perspective. public var perspective: Perspective /// Creates an entity's camera. /// - Parameter perspective: Defaults to ``Perspective-swift.enum/firstPerson``. public init(perspective: Perspective = .firstPerson) { self.perspective = perspective } /// Changes to the next perspective. public func cyclePerspective() { let index = (perspective.rawValue + 1) % Perspective.allCases.count perspective = Perspective.allCases[index] } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityExperience.swift ================================================ import FirebladeECS /// A component storing an entity's experience level. public class EntityExperience: Component { /// The entity's total xp. public var experience: Int /// The entity's xp level (displayed above the xp bar). public var experienceLevel: Int /// The entity's experience bar progress. public var experienceBarProgress: Float /// Creates an entity's xp state. /// - Parameters: /// - experience: Defaults to 0. /// - experienceLevel: Defaults to 0. /// - experienceBarProgress: Defaults to 0. public init(experience: Int = 0, experienceLevel: Int = 0, experienceBarProgress: Float = 0) { self.experience = experience self.experienceLevel = experienceLevel self.experienceBarProgress = experienceBarProgress } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityFlying.swift ================================================ import FirebladeECS /// A component storing whether an entity is flying. public class EntityFlying: Component { /// Whether the entity is flying or not. public var isFlying: Bool /// Creates an entity's flying state. /// - Parameter isFlying: Defaults to false. public init(_ isFlying: Bool = false) { self.isFlying = isFlying } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityHeadYaw.swift ================================================ import FirebladeECS /// A component storing the yaw of an entity's head. public class EntityHeadYaw: Component { /// The yaw of an entity's head (counter clockwise starting at the positive z axis). public var yaw: Float /// Creates a new entity head yaw component. public init(_ yaw: Float) { self.yaw = yaw } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityHealth.swift ================================================ import FirebladeECS /// A component storing an entity's health (hp). public class EntityHealth: Component { /// The entity's health measured in half hearts. public var health: Float /// Creates an entity's health value. /// - Parameter health: Defaults to 20 hp. public init(_ health: Float = 20) { self.health = health } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityHitBox.swift ================================================ import FirebladeECS import FirebladeMath /// A component storing an entity's hit box. /// /// Entity hit boxes are axis aligned and their width and depth are always equal (``width``). public class EntityHitBox: Component { /// The width (and depth) of the entity's hit box. public var width: Double /// The height of the entity's hit box. public var height: Double /// The size of the hit box as a vector. public var size: Vec3d { Vec3d(width, height, width) } /// Creates a new hit box component. public init(width: Double, height: Double) { self.width = width self.height = height } /// Creates a new hit box component. public init(width: Float, height: Float) { self.width = Double(width) self.height = Double(height) } /// The bounding box for this hitbox if it was at the given position. /// - Parameter position: The position of the hitbox. /// - Returns: A bounding box with the same size as the hitbox and the given position. public func aabb(at position: Vec3d) -> AxisAlignedBoundingBox { let position = position - 0.5 * Vec3d(size.x, 0, size.z) return AxisAlignedBoundingBox(position: position, size: size) } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityId.swift ================================================ import FirebladeECS /// A component storing an entity's id. public class EntityId: Component { public var id: Int public init(_ id: Int) { self.id = id } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityKindId.swift ================================================ import FirebladeECS /// A component storing the id of an entity's kind. public class EntityKindId: Component { public var id: Int public var entityKind: EntityKind? { RegistryStore.shared.entityRegistry.entity(withId: id) } public init(_ id: Int) { self.id = id } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityLerpState.swift ================================================ import CoreFoundation import FirebladeECS import FirebladeMath import Foundation /// A component storing the lerp (if any) that an entity is currently undergoing; lerp is short /// for linear interpolation. public class EntityLerpState: Component { public var currentLerp: Lerp? public struct Lerp { public var targetPosition: Vec3d public var targetPitch: Float public var targetYaw: Float public var ticksRemaining: Int public init( targetPosition: Vec3d, targetPitch: Float, targetYaw: Float, ticksRemaining: Int ) { self.targetPosition = targetPosition self.targetPitch = targetPitch self.targetYaw = targetYaw self.ticksRemaining = ticksRemaining } } public init() {} /// Initiate a lerp to the given position and rotation. /// - Parameters: /// - position: Target position. /// - pitch: Target pitch. /// - yaw: Target yaw. /// - duration: Lerp duration in ticks. public func lerp(to position: Vec3d, pitch: Float, yaw: Float, duration: Int) { currentLerp = Lerp( targetPosition: position, targetPitch: pitch, targetYaw: yaw, ticksRemaining: duration ) } /// Ticks an entities current lerp returning the entity's new position, pitch, and yaw. If there's no current /// lerp, then `nil` is returned. public func tick( position: Vec3d, pitch: Float, yaw: Float ) -> ( position: Vec3d, pitch: Float, yaw: Float )? { guard var lerp = currentLerp, lerp.ticksRemaining > 0 else { currentLerp = nil return nil } let progress = 1 / Double(lerp.ticksRemaining) lerp.ticksRemaining -= 1 if lerp.ticksRemaining == 0 { currentLerp = nil } else { currentLerp = lerp } let targetYaw: Float if yaw - lerp.targetYaw > .pi { targetYaw = lerp.targetYaw + 2 * .pi } else if yaw - lerp.targetYaw < -.pi { targetYaw = lerp.targetYaw - 2 * .pi } else { targetYaw = lerp.targetYaw } return ( MathUtil.lerp(from: position, to: lerp.targetPosition, progress: progress), MathUtil.lerp(from: pitch, to: lerp.targetPitch, progress: Float(progress)), MathUtil.lerp(from: yaw, to: targetYaw, progress: Float(progress)) ) } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityMetadata.swift ================================================ import FirebladeECS /// The distinction between entity metadata and entity attributes is that entity /// attributes are for properties that can have modifiers applied (e.g. speed, /// max health, etc). public class EntityMetadata: Component { /// Metadata specific to a certain kind of entity. public var specializedMetadata: SpecializedMetadata? public var itemMetadata: ItemMetadata? { switch specializedMetadata { case let .item(metadata): return metadata default: return nil } } public var mobMetadata: MobMetadata? { switch specializedMetadata { case let .mob(metadata): return metadata default: return nil } } public enum SpecializedMetadata { case item(ItemMetadata) case mob(MobMetadata) } public struct ItemMetadata { public var slot = Slot() /// The phase (in the periodic motion sense) of the item entity's bobbing animation. /// Not part of the vanilla entity metadata, this is just a sensible place to store /// this item entity property. public var bobbingPhaseOffset: Float public init() { bobbingPhaseOffset = Float.random(in: 0...1) * 2 * .pi } } public struct MobMetadata { /// If an entity doesn't have AI, we should ignore its velocity. For some reason the /// server still sends us the velocity even when the entity isn't moving. public var noAI = false } /// Creates a public init(inheritanceChain: [String]) { if inheritanceChain.contains("ItemEntity") { specializedMetadata = .item(ItemMetadata()) } else if inheritanceChain.contains("MobEntity") { specializedMetadata = .mob(MobMetadata()) } } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityNutrition.swift ================================================ import FirebladeECS /// A component storing an entity's food and saturation levels. public class EntityNutrition: Component { public var food: Int public var saturation: Float /// Creates an entity's nutrition with the provided values. /// - Parameters: /// - food: Defaults to 20. /// - saturation: Defaults to 0. public init(food: Int = 20, saturation: Float = 0) { self.food = food self.saturation = saturation } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityOnGround.swift ================================================ import FirebladeECS /// A component storing whether an entity is on the ground (walking or swimming) or not on the ground (jumping/falling). public class EntityOnGround: Component { /// Whether the entity is touching the ground or not. public var onGround: Bool /// The most recently saved value of ``onGround`` (see ``save()``). public var previousOnGround: Bool public init(_ onGround: Bool) { self.onGround = onGround previousOnGround = onGround } /// Saves the current value to ``previousOnGround``. public func save() { previousOnGround = onGround } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityPosition.swift ================================================ import Foundation import CoreFoundation import FirebladeECS import FirebladeMath /// A component storing an entity's position relative to the world. /// /// Use ``smoothVector`` to get a vector that changes smoothly (positions are usually only updated once per tick). public class EntityPosition: Component { // MARK: Public properties /// The underlying vector. public var vector: Vec3d /// The previous position. public var previousVector: Vec3d /// The amount of time taken (in seconds) for ``smoothVector`` to transition from one position to the next. public var smoothingAmount: Double /// A vector that smoothly interpolates from the previous position (set by calling ``save()``) /// to the next position in an amount of time described by ``smoothingAmount``. public var smoothVector: Vec3d { let delta = CFAbsoluteTimeGetCurrent() - lastUpdated let tickProgress = MathUtil.clamp(delta / smoothingAmount, 0, 1) return tickProgress * (vector - previousVector) + previousVector } /// The raw x component (not smoothed). public var x: Double { get { vector.x } set { vector.x = newValue } } /// The raw y component (not smoothed). public var y: Double { get { vector.y } set { vector.y = newValue } } /// The raw z component (not smoothed). public var z: Double { get { vector.z } set { vector.z = newValue } } /// The position of the chunk this position is in. public var chunk: ChunkPosition { return ChunkPosition( chunkX: Int((x / 16).rounded(.down)), chunkZ: Int((z / 16).rounded(.down)) ) } /// The position of the chunk section this position is in. public var chunkSection: ChunkSectionPosition { return ChunkSectionPosition( sectionX: Int((x / 16).rounded(.down)), sectionY: Int((y / 16).rounded(.down)), sectionZ: Int((z / 16).rounded(.down)) ) } /// The block at the entity position. public var block: BlockPosition { return BlockPosition( x: Int(x.rounded(.down)), y: Int(y.rounded(.down)), z: Int(z.rounded(.down)) ) } /// The block underneath the entity position. public var blockUnderneath: BlockPosition { return BlockPosition( x: Int(x.rounded(.down)), y: Int((y - 0.5).rounded(.down)), z: Int(z.rounded(.down)) ) } // MARK: Private properties /// The time the vector was last updated. Used for smoothing. private var lastUpdated: CFAbsoluteTime // MARK: Init /// Creates an entity position from a vector. /// - Parameters: /// - vector: A vector representing the position. /// - smoothingAmount: The amount of time (in seconds) for ``smoothVector`` to transition from one position to the next. Defaults to one 15th of a second. public init(_ vector: Vec3d, smoothingAmount: Double = 1/15) { self.vector = vector previousVector = vector lastUpdated = CFAbsoluteTimeGetCurrent() self.smoothingAmount = smoothingAmount } /// Creates an entity position from coordinates. /// - Parameters: /// - x: x coordinate. /// - y: y coordinate. /// - z: z coordinate. /// - smoothingAmount: The amount of time (in seconds) for ``smoothVector`` to transition from one position to the next. Defaults to one 15th of a second. public convenience init(_ x: Double, _ y: Double, _ z: Double, smoothingAmount: Double = 1/15) { self.init(Vec3d(x, y, z), smoothingAmount: smoothingAmount) } // MARK: Updating /// Moves the position to a new position. public func move(to position: EntityPosition) { vector = position.vector } /// Moves the position to a new position. public func move(to position: Vec3d) { vector = position } /// Offsets the position by a specified amount. public func move(by offset: Vec3d) { vector += offset } // MARK: Smoothing /// Saves the current value as the value to smooth from. public func save() { previousVector = smoothVector lastUpdated = CFAbsoluteTimeGetCurrent() } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityRotation.swift ================================================ import FirebladeECS import Foundation import CoreFoundation /// A component storing an entity's rotation in radians. public class EntityRotation: Component { /// The amount of time taken (in seconds) for ``smoothVector`` to transition from one position to the next. public var smoothingAmount: Float /// Pitch in radians. public var pitch: Float /// Yaw in radians. public var yaw: Float /// The previous pitch. public var previousPitch: Float /// The previous yaw. public var previousYaw: Float /// The smoothly interpolated pitch. public var smoothPitch: Float { let delta = Float(CFAbsoluteTimeGetCurrent() - lastUpdated) let progress = MathUtil.clamp(delta / smoothingAmount, 0, 1) return MathUtil.lerpAngle(from: previousPitch, to: pitch, progress: progress) } /// The smoothly interpolated yaw. public var smoothYaw: Float { let delta = Float(CFAbsoluteTimeGetCurrent() - lastUpdated) let progress = MathUtil.clamp(delta / smoothingAmount, 0, 1) return MathUtil.lerpAngle(from: previousYaw, to: yaw, progress: progress) } /// The compass heading. public var heading: Direction { let index = Int((yaw / (.pi / 2)).rounded()) % 4 return [.south, .west, .north, .east][index] } // MARK: Private properties /// The time that the rotation was last updated. Used for smoothing. Set by ``save()``. private var lastUpdated: CFAbsoluteTime // MARK: Init /// Creates an entity's rotation. /// - Parameters: /// - pitch: The pitch in radians. -pi/2 is straight up, 0 is straight ahead, and pi/2 is straight down. /// - yaw: The yaw in radians. Measured counterclockwise from the positive z axis. /// - smoothingAmount: The amount of time (in seconds) for ``smoothYaw`` and ``smoothPitch`` /// to transition from one position to the next. Defaults to 0 seconds. public init(pitch: Float, yaw: Float, smoothingAmount: Float = 0) { self.pitch = pitch self.yaw = yaw self.previousPitch = pitch self.previousYaw = yaw self.smoothingAmount = smoothingAmount lastUpdated = CFAbsoluteTimeGetCurrent() } // MARK: Public methods /// Saves the current pitch and yaw as the values to smooth from. public func save() { previousPitch = pitch previousYaw = yaw lastUpdated = CFAbsoluteTimeGetCurrent() } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntitySneaking.swift ================================================ import FirebladeECS /// A component storing whether an entity is sneaking or not. public class EntitySneaking: Component { /// Whether the entity is sneaking or not. public var isSneaking: Bool /// Creates an entity's sneaking state. /// - Parameter isSneaking: Defaults to false. public init(_ isSneaking: Bool = false) { self.isSneaking = isSneaking } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntitySprinting.swift ================================================ import FirebladeECS /// A component storing whether an entity is sprinting or not. public class EntitySprinting: Component { /// Whether the entity is sprinting or not. public var isSprinting: Bool /// Creates an entity's sprinting state. /// - Parameter isSprinting: Defaults to false. public init(_ isSprinting: Bool = false) { self.isSprinting = isSprinting } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityUUID.swift ================================================ import Foundation import FirebladeECS /// A component storing an entity's UUID. Not to be confused with ``EntityId``. public class EntityUUID: Component { public var uuid: UUID public init(_ uuid: UUID) { self.uuid = uuid } } ================================================ FILE: Sources/Core/Sources/ECS/Components/EntityVelocity.swift ================================================ import FirebladeECS import FirebladeMath /// A component storing an entity's velocity in blocks per tick. public class EntityVelocity: Component { // MARK: Public properties /// The vector representing this velocity. public var vector: Vec3d /// x component in blocks per tick. public var x: Double { get { vector.x } set { vector.x = newValue } } /// y component in blocks per tick. public var y: Double { get { vector.y } set { vector.y = newValue } } /// z component in blocks per tick. public var z: Double { get { vector.z } set { vector.z = newValue } } // MARK: Init /// Creates an entity's velocity. /// - Parameter vector: Vector representing the velocity. public init(_ vector: Vec3d) { self.vector = vector } /// Creates an entity's velocity. /// - Parameters: /// - x: x component. /// - y: y component. /// - z: z component. public convenience init(_ x: Double, _ y: Double, _ z: Double) { self.init(Vec3d(x, y, z)) } } ================================================ FILE: Sources/Core/Sources/ECS/Components/Marker/ClientPlayerEntity.swift ================================================ import FirebladeECS /// A marker component for the client's player's entity. public class ClientPlayerEntity: Component {} ================================================ FILE: Sources/Core/Sources/ECS/Components/Marker/LivingEntity.swift ================================================ import FirebladeECS /// A marker component for living entities. public class LivingEntity: Component {} ================================================ FILE: Sources/Core/Sources/ECS/Components/Marker/NonLivingEntity.swift ================================================ import FirebladeECS /// A marker component for non-living entities. public class NonLivingEntity: Component {} ================================================ FILE: Sources/Core/Sources/ECS/Components/Marker/PlayerEntity.swift ================================================ import FirebladeECS /// A marker component for player entities. public class PlayerEntity: Component {} ================================================ FILE: Sources/Core/Sources/ECS/Components/ObjectData.swift ================================================ import FirebladeECS /// A component storing an object's data value. public class ObjectData: Component { /// The object's data value (don't ask me what this does, I don't know yet). public var data: Int /// Creates an object data component. public init(_ data: Int) { self.data = data } } ================================================ FILE: Sources/Core/Sources/ECS/Components/ObjectUUID.swift ================================================ import Foundation import FirebladeECS /// A component storing an object's UUID. Not to be confused with. public class ObjectUUID: Component { /// An object's UUID. public var uuid: UUID /// Creates an object UUID component. public init(_ uuid: UUID) { self.uuid = uuid } } ================================================ FILE: Sources/Core/Sources/ECS/Components/PlayerAttributes.swift ================================================ import FirebladeECS /// A component storing attributes specific to the client's player. public class PlayerAttributes: Component { /// The player's spawn position. public var spawnPosition: BlockPosition /// The player's maximum flying speed (set by server). public var flyingSpeed: Float /// The player's current fov modifier. public var fovModifier: Float /// Whether the player is invulnerable to damage or not. In creative mode this is `true`. public var isInvulnerable: Bool /// Whether the player is allowed to fly or not. public var canFly: Bool /// Whether the player can instantly break blocks. public var canInstantBreak: Bool /// Whether the player is in hardcore mode or not. Affects respawn screen and rendering of hearts. public var isHardcore: Bool /// The player's previous gamemode. Likely used in vanilla by the F3+F4 gamemode switcher. public var previousGamemode: Gamemode? /// Creates the player's attributes. /// - Parameters: /// - spawnPosition: Defaults to (0, 0, 0). /// - flyingSpeed: Defaults to 0. /// - fovModifier: Defaults to 0. /// - isInvulnerable: Defaults to false. /// - canFly: Defaults to false. /// - canInstantBreak: Defaults to false. /// - isHardcore: Defaults to false. /// - previousGamemode: Defaults to `nil`. public init( spawnPosition: BlockPosition = BlockPosition(x: 0, y: 0, z: 0), flyingSpeed: Float = 0, fovModifier: Float = 0, isInvulnerable: Bool = false, canFly: Bool = false, canInstantBreak: Bool = false, isHardcore: Bool = false, previousGamemode: Gamemode? = nil ) { self.spawnPosition = spawnPosition self.flyingSpeed = flyingSpeed self.fovModifier = fovModifier self.isInvulnerable = isInvulnerable self.canFly = canFly self.canInstantBreak = canInstantBreak self.isHardcore = isHardcore self.previousGamemode = previousGamemode } } ================================================ FILE: Sources/Core/Sources/ECS/Components/PlayerCollisionState.swift ================================================ import FirebladeECS /// A component which stores the state of collisions from the latest tick. public class PlayerCollisionState: Component { public var collidingHorizontally = false public var collidingVertically = false public init() {} } ================================================ FILE: Sources/Core/Sources/ECS/Components/PlayerFOV.swift ================================================ import CoreFoundation import FirebladeECS import FirebladeMath /// A component storing the player's FOV. public class PlayerFOV: Component { /// The FOV multiplier from the previous tick. public var previousMultiplier: Float /// The FOV multiplier from the next tick. public var multiplier: Float /// The time at which the FOV multiplier was last calculated. public var lastUpdated: CFAbsoluteTime /// The FOV multiplier smoothed over the course of the current tick. Smooths from /// the latest value saved using ``PlayerFOV/save``. public var smoothMultiplier: Float { let delta = Float(CFAbsoluteTimeGetCurrent() - lastUpdated) let tickProgress = MathUtil.clamp(delta * Float(TickScheduler.defaultTicksPerSecond), 0, 1) return tickProgress * (multiplier - previousMultiplier) + previousMultiplier } /// Creates a player FOV multiplier component. public init(multiplier: Float = 1) { self.previousMultiplier = multiplier self.multiplier = multiplier lastUpdated = CFAbsoluteTimeGetCurrent() } /// Saves the current value as the value to smooth from. public func save() { previousMultiplier = multiplier lastUpdated = CFAbsoluteTimeGetCurrent() } } ================================================ FILE: Sources/Core/Sources/ECS/Components/PlayerGamemode.swift ================================================ import FirebladeECS /// A component storing a player's gamemode. public class PlayerGamemode: Component { /// The player's gamemode. public var gamemode: Gamemode /// Creates a player's gamemode. /// - Parameter gamemode: Defaults to survival. public init(gamemode: Gamemode = .survival) { self.gamemode = gamemode } } ================================================ FILE: Sources/Core/Sources/ECS/Components/PlayerInventory.swift ================================================ import FirebladeECS /// A component storing the player's inventory. Simply wraps a ``Window`` with some /// inventory-specific properties and helper methods. public class PlayerInventory: Component { /// The number of slots in a player inventory (including armor and off hand). public static let slotCount = 46 /// The player's inventory's window id. public static let windowId = 0 /// The index of the crafting result slot. public static let craftingResultIndex = craftingResultArea.startIndex /// The index of the player's off-hand slot. public static let offHandIndex = offHandArea.startIndex public static let mainArea = WindowArea( startIndex: 9, width: 9, height: 3, position: Vec2i(8, 84) ) public static let hotbarArea = WindowArea( startIndex: 36, width: 9, height: 1, position: Vec2i(8, 142) ) public static let craftingInputArea = WindowArea( startIndex: 1, width: 2, height: 2, position: Vec2i(98, 18), kind: .smallCraftingRecipeInput ) public static let craftingResultArea = WindowArea( startIndex: 0, width: 1, height: 1, position: Vec2i(154, 28), kind: .recipeResult ) public static let armorArea = WindowArea( startIndex: 5, width: 1, height: 4, position: Vec2i(8, 8), kind: .armor ) public static let offHandArea = WindowArea( startIndex: 45, width: 1, height: 1, position: Vec2i(77, 62) ) /// The inventory's window; contains the underlying slots. public var window: Window /// The player's currently selected hotbar slot. public var selectedHotbarSlot: Int /// The inventory's main 3 row 9 column area. public var mainArea: [[Slot]] { window.slots(for: Self.mainArea) } /// The inventory's crafting input slots. public var craftingInputs: [[Slot]] { window.slots(for: Self.craftingInputArea) } // TODO: Choose a casing for hotbar and stick to it (hotbar vs hotBar) /// The inventory's hotbar slots. public var hotbar: [Slot] { window.slots(for: Self.hotbarArea)[0] } /// The result slot of the inventory's crafting area. public var craftingResult: Slot { window.slots[Self.craftingResultIndex] } /// The armor slots. public var armorSlots: [Slot] { window.slots(for: Self.armorArea).map { row in row[0] } } /// The off-hand slot. public var offHand: Slot { window.slots[Self.offHandIndex] } /// The item in the currently selected hotbar slot, `nil` if the slot is empty /// or the item stack is invalid. public var mainHandItem: Item? { guard let stack = hotbar[selectedHotbarSlot].stack else { return nil } guard let item = RegistryStore.shared.itemRegistry.item(withId: stack.itemId) else { log.warning("Non-existent item with id \(stack.itemId) selected in hotbar") return nil } return item } /// Creates the player's inventory state. /// - Parameter selectedHotbarSlot: Defaults to 0 (the first slot from the left in the main hotbar). /// - Precondition: The length of `slots` must match ``PlayerInventory/slotCount``. public init(slots: [Slot]? = nil, selectedHotbarSlot: Int = 0) { window = Window( id: Self.windowId, type: .inventory, slots: slots ) self.selectedHotbarSlot = selectedHotbarSlot } } ================================================ FILE: Sources/Core/Sources/ECS/Singles/ClientboundEntityPacketStore.swift ================================================ import FirebladeECS /// Used to save entity-related packets until a tick occurs. Entity packets must be handled during /// the game tick. public final class ClientboundEntityPacketStore: SingleComponent { /// Packets are stored as closures to avoid systems needing access to the ``Client`` when running /// the packet handlers. public var packets: [() throws -> Void] /// Creates an empty store. public init() { packets = [] } /// Adds a packet to be handled during the next tick. public func add(_ packet: ClientboundEntityPacket, client: Client) { packets.append({ [weak client] in guard let client = client else { return } try packet.handle(for: client) }) } /// Handles all stored packets and removes them. public func handleAll() throws { for packet in packets { try packet() } packets = [] } } ================================================ FILE: Sources/Core/Sources/ECS/Singles/GUIStateStorage.swift ================================================ import FirebladeECS @dynamicMemberLookup public final class GUIStateStorage: SingleComponent { public var inner = GUIState() public init() {} subscript(dynamicMember member: WritableKeyPath) -> T { get { inner[keyPath: member] } set { inner[keyPath: member] = newValue } } subscript(dynamicMember member: KeyPath) -> T { inner[keyPath: member] } } ================================================ FILE: Sources/Core/Sources/ECS/Singles/InputState.swift ================================================ import FirebladeECS import FirebladeMath /// The game's input state. public final class InputState: SingleComponent { /// The maximum number of ticks between consecutive inputs to count as a /// double tap. public static let maximumDoubleTapDelay = 6 /// The newly pressed keys in the order that they were pressed. Only includes /// presses since last call to ``flushInputs()``. public private(set) var newlyPressed: [KeyPressEvent] = [] /// The newly released keys in the order that they were released. Only includes /// releases since last call to ``flushInputs()``. public private(set) var newlyReleased: [KeyReleaseEvent] = [] /// The currently pressed keys. public private(set) var keys: Set = [] /// The currently pressed inputs. public private(set) var inputs: Set = [] /// The current absolute mouse position relative to the play area's top left corner. /// Measured in true pixels (not scaled down by the screen's scaling factor). public private(set) var mousePosition: Vec2f = Vec2f(0, 0) /// The mouse delta since the last call to ``resetMouseDelta()``. public private(set) var mouseDelta: Vec2f = Vec2f(0, 0) /// The position of the left thumbstick. public private(set) var leftThumbstick: Vec2f = Vec2f(0, 0) /// The position of the right thumbstick. public private(set) var rightThumbstick: Vec2f = Vec2f(0, 0) /// The time since forwards last changed from not pressed to pressed. public private(set) var ticksSinceForwardsPressed: Int = 0 /// Whether the sprint was triggered by double tapping forwards. public private(set) var sprintIsFromDoubleTap: Bool = false /// The time since jump last changed from not pressed to pressed. public private(set) var ticksSinceJumpPressed: Int = 0 /// Whether sprint is currently toggled. Only used if toggle sprint is enabled. public private(set) var isSprintToggled: Bool = false /// Whether sneak is currently toggled. Only used if toggle sneak is enabled. public private(set) var isSneakToggled: Bool = false /// Creates an empty input state. public init() {} /// Presses an input. /// - Parameters: /// - key: The key pressed. /// - input: The input bound to the pressed key if any. /// - characters: Characters associated with the input. public func press(key: Key?, input: Input?, characters: [Character] = []) { newlyPressed.append(KeyPressEvent(key: key, input: input, characters: characters)) } /// Releases an input. /// - Parameters: /// - key: The key released. /// - input: The input released. public func release(key: Key?, input: Input?) { newlyReleased.append(KeyReleaseEvent(key: key, input: input)) } /// Releases all inputs. Doesn't clear ``newlyPressed``, so if used when disabling /// a certain set of (or all) inputs, wait to call this until after all relevant handlers /// know to ignore said inputs. public func releaseAll(clearNewlyPressed: Bool = true) { for key in keys { newlyReleased.append(KeyReleaseEvent(key: key, input: nil)) } for input in inputs { newlyReleased.append(KeyReleaseEvent(key: nil, input: input)) } } /// Clears ``newlyPressed`` and ``newlyReleased``. public func flushInputs() { newlyPressed = [] newlyReleased = [] } /// Updates the current mouse delta by adding the given delta. /// /// See ``Client/moveMouse(x:y:deltaX:deltaY:)`` for the reasoning behind /// having both absolute and relative parameters (it's currently necessary /// but could be fixed by cleaning up the input handling architecture). /// - Parameters: /// - x: The absolute mouse x (relative to the play area's top left corner). /// - y: The absolute mouse y (relative to the play area's top left corner). /// - deltaX: The change in mouse x. /// - deltaY: The change in mouse y. public func moveMouse(x: Float, y: Float, deltaX: Float, deltaY: Float) { mouseDelta += Vec2f(deltaX, deltaY) mousePosition = Vec2f(x, y) } /// Updates the current position of the left thumbstick. /// - Parameters: /// - x: The x position. /// - y: The y position. public func moveLeftThumbstick(_ x: Float, _ y: Float) { leftThumbstick = [x, y] } /// Updates the current position of the right thumbstick. /// - Parameters: /// - x: The x position. /// - y: The y position. public func moveRightThumbstick(_ x: Float, _ y: Float) { rightThumbstick = [x, y] } /// Resets the mouse delta to 0. public func resetMouseDelta() { mouseDelta = Vec2f(0, 0) } /// Ticks the input state by flushing ``newlyPressed`` into ``keys`` and ``inputs``, and clearing /// ``newlyReleased``. Also emits events to the given ``EventBus``. func tick(_ isInputSuppressed: [Bool], _ eventBus: EventBus, _ configuration: ClientConfiguration) { precondition(isInputSuppressed.count == newlyPressed.count, "`isInputSuppressed` should be the same length as `newlyPressed`") ticksSinceForwardsPressed += 1 ticksSinceJumpPressed += 1 // Reset toggles if they're disabled if (!configuration.toggleSprint && isSprintToggled) { inputs.remove(.sprint) isSprintToggled = false } if (!configuration.toggleSneak && isSneakToggled) { inputs.remove(.sneak) isSneakToggled = false } for (var event, suppressInput) in zip(newlyPressed, isInputSuppressed) { if suppressInput { event.input = nil } // Detect double pressing forwards (to activate sprint). if event.input == .moveForward && !inputs.contains(.moveForward) { // If the forwards key has been pressed within 6 ticks, press sprint. if !inputs.contains(.sprint) && ticksSinceForwardsPressed <= Self.maximumDoubleTapDelay { inputs.insert(.sprint) // Mark the sprint input for removal once forwards is pressed. sprintIsFromDoubleTap = true } ticksSinceForwardsPressed = 0 } // Detect double pressing jump (to fly). if event.input == .jump && !inputs.contains(.jump) { if ticksSinceJumpPressed <= Self.maximumDoubleTapDelay { inputs.insert(.fly) } ticksSinceJumpPressed = 0 } // Make sure that sprint isn't removed when forwards is released if it was pressed by the user. if event.input == .sprint { sprintIsFromDoubleTap = false } eventBus.dispatch(event) if let key = event.key { keys.insert(key) } if let input = event.input { // Toggle sprint if enabled if configuration.toggleSprint && input == .sprint { isSprintToggled = !isSprintToggled if !isSprintToggled { inputs.remove(input) continue } } // Toggle sneak if enabled if configuration.toggleSneak && input == .sneak { isSneakToggled = !isSneakToggled if !isSneakToggled { inputs.remove(input) continue } } inputs.insert(input) } } for event in newlyReleased { // Remove sprint if the forwards key is released and the sprint came from a double tap. if event.input == .moveForward && sprintIsFromDoubleTap { inputs.remove(.sprint) } // TODO: The release event of any inputs that were suppressed should probably also be suppressed eventBus.dispatch(event) // Don't remove sprint or sneak if toggling is enabled if (event.input == .sprint && configuration.toggleSprint) || (event.input == .sneak && configuration.toggleSneak) { continue } if let key = event.key { keys.remove(key) } if let input = event.input { inputs.remove(input) } } flushInputs() // `fly` is a synthetic input and is always immediately released. if inputs.contains(.fly) { release(key: nil, input: .fly) } } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/EntityMovementSystem.swift ================================================ import FirebladeECS /// Updates the position of each entity according to its velocity (excluding the player, /// because velocity for the player is handled by the ``PlayerVelocitySystem``). Also handles /// position/rotation lerping. public struct EntityMovementSystem: System { public func update(_ nexus: Nexus, _ world: World) { let physicsEntities = nexus.family( requiresAll: EntityPosition.self, EntityVelocity.self, EntityRotation.self, EntityLerpState.self, EntityMetadata.self, EntityKindId.self, EntityOnGround.self, excludesAll: ClientPlayerEntity.self ) for (position, velocity, rotation, lerpState, metadata, kind, onGround) in physicsEntities { guard let kind = RegistryStore.shared.entityRegistry.entity(withId: kind.id) else { log.warning("Unknown entity kind '\(kind.id)'") continue } if let (newPosition, newPitch, newYaw) = lerpState.tick( position: position.vector, pitch: rotation.pitch, yaw: rotation.yaw ) { position.vector = newPosition rotation.pitch = newPitch rotation.yaw = newYaw continue } velocity.vector *= 0.98 if onGround.onGround { velocity.vector.y = 0 } else { if kind.identifier == Identifier(name: "item") { velocity.vector.y *= 0.98 velocity.vector.y -= 0.04 } } if abs(velocity.vector.x) < 0.003 { velocity.vector.x = 0 } if abs(velocity.vector.y) < 0.003 { velocity.vector.y = 0 } if abs(velocity.vector.z) < 0.003 { velocity.vector.z = 0 } if metadata.mobMetadata?.noAI != true { position.move(by: velocity.vector) } } } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/EntitySmoothingSystem.swift ================================================ import FirebladeECS /// Saves the position of each entity before it is modified so that interpolation can be performed /// when rendering. public struct EntitySmoothingSystem: System { public func update(_ nexus: Nexus, _ world: World) { let physicsEntities = nexus.family( requiresAll: EntityPosition.self, EntityVelocity.self, excludesAll: ClientPlayerEntity.self ) for (position, _) in physicsEntities { position.save() } } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/PacketHandlingSystem.swift ================================================ import FirebladeECS /// Handles all packets in the ``ClientboundEntityPacketStore``. Mostly the packets in the store are /// entity movement packets. Handling them during the game tick helps position smoothing work /// better. public struct EntityPacketHandlingSystem: System { public func update(_ nexus: Nexus, _ world: World) throws { let packetStore = nexus.single(ClientboundEntityPacketStore.self).component do { try packetStore.handleAll() } catch { log.error("Failed to handle entity-related packets during tick: \(error)") throw error } } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/PlayerAccelerationSystem.swift ================================================ import Foundation import FirebladeECS import FirebladeMath public struct PlayerAccelerationSystem: System { static let sneakMultiplier: Double = 0.3 static let sprintingFoodLevel = 6 static let sprintingModifier = EntityAttributeModifier( uuid: UUID(uuidString: "662A6B8D-DA3E-4C1C-8813-96EA6097278D")!, amount: 0.3, operation: .addPercent ) public func update(_ nexus: Nexus, _ world: World) { let guiState = nexus.single(GUIStateStorage.self).component var family = nexus.family( requiresAll: EntityNutrition.self, EntityFlying.self, EntityOnGround.self, EntityRotation.self, EntityPosition.self, EntityAcceleration.self, EntitySprinting.self, EntitySneaking.self, PlayerAttributes.self, EntityAttributes.self, PlayerCollisionState.self, ClientPlayerEntity.self ).makeIterator() guard let ( nutrition, flying, onGround, rotation, position, acceleration, sprinting, sneaking, playerAttributes, entityAttributes, collisionState, _ ) = family.next() else { log.error("PlayerAccelerationSystem failed to get player to tick") return } // This should just act as an optimization, movement inputs shouldn't get here // in the first place when movement isn't allowed so this function would just // zero the acceleration anyway. guard guiState.movementAllowed else { acceleration.vector = .zero return } let inputState = nexus.single(InputState.self).component let inputs = Self.addControllerMovement(inputState.inputs, inputState.leftThumbstick) let forwardsImpulse: Double = inputs.contains(.moveForward) ? 1 : 0 let backwardsImpulse: Double = inputs.contains(.moveBackward) ? 1 : 0 let leftImpulse: Double = inputs.contains(.strafeLeft) ? 1 : 0 let rightImpulse: Double = inputs.contains(.strafeRight) ? 1 : 0 var impulse = Vec3d( leftImpulse - rightImpulse, 0, forwardsImpulse - backwardsImpulse ) if !flying.isFlying && inputs.contains(.sneak) { impulse *= Self.sneakMultiplier sneaking.isSneaking = true } else { sneaking.isSneaking = false } let canSprint = (nutrition.food > Self.sprintingFoodLevel || playerAttributes.canFly) if !sprinting.isSprinting && impulse.z >= 0.8 && canSprint && inputs.contains(.sprint) { sprinting.isSprinting = true } if sprinting.isSprinting { if !inputs.contains(.moveForward) || collisionState.collidingHorizontally { sprinting.isSprinting = false } } let hasModifier = entityAttributes[.movementSpeed].hasModifier(Self.sprintingModifier.uuid) if sprinting.isSprinting == true && !hasModifier { entityAttributes[.movementSpeed].apply(Self.sprintingModifier) } else if sprinting.isSprinting == false && hasModifier { entityAttributes[.movementSpeed].remove(Self.sprintingModifier.uuid) } if impulse.magnitude < 0.0000001 { impulse = .zero } else if impulse.magnitudeSquared > 1 { impulse = normalize(impulse) } impulse.x *= 0.98 impulse.z *= 0.98 let speed = Self.calculatePlayerSpeed( position.vector, world, entityAttributes[.movementSpeed].value, sprinting.isSprinting, onGround.onGround, flying.isFlying, playerAttributes.flyingSpeed ) impulse *= speed let rotationMatrix = MatrixUtil.rotationMatrix(y: Double(rotation.yaw)) impulse = (Vec4d(impulse, 1) * rotationMatrix).xyz acceleration.vector = impulse } private static func addControllerMovement( _ inputs: Set, _ thumbstick: Vec2f ) -> Set { let x = thumbstick.x let y = thumbstick.y guard x != 0 || y != 0 else { return inputs } var inputs = inputs let angle = FirebladeMath.atan2(y, x) let sector = Int((angle / (.pi / 4)).rounded()) if sector >= 1 && sector <= 3 { inputs.insert(.moveForward) } if sector >= -3 && sector <= -1 { inputs.insert(.moveBackward) } if sector == -4 || sector == -3 || sector == 3 || sector == 4 { inputs.insert(.strafeLeft) } if sector >= -1 && sector <= 1 { inputs.insert(.strafeRight) } return inputs } private static func calculatePlayerSpeed( _ position: Vec3d, _ world: World, _ movementSpeed: Double, _ isSprinting: Bool, _ onGround: Bool, _ isFlying: Bool, _ flightSpeed: Float ) -> Double { var speed: Double if onGround { // TODO: make get block below function once there is a Position protocol (and make vectors conform to it) let blockPosition = BlockPosition( x: Int(Foundation.floor(position.x)), y: Int(Foundation.floor(position.y - 0.5)), z: Int(Foundation.floor(position.z)) ) let block = world.getBlock(at: blockPosition) let slipperiness = block.physicalMaterial.slipperiness speed = movementSpeed * 0.216 / (slipperiness * slipperiness * slipperiness) } else if isFlying { speed = Double(flightSpeed) if isSprinting { speed *= 2 } } else { speed = 0.02 if isSprinting { speed += 0.006 } } return speed } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/PlayerBlockBreakingSystem.swift ================================================ import FirebladeECS public final class PlayerBlockBreakingSystem: System { var connection: ServerConnection? weak var game: Game? var lastDestroyCompletionTick: Int? public init(_ connection: ServerConnection?, _ game: Game) { self.connection = connection self.game = game } public func update(_ nexus: Nexus, _ world: World) throws { guard let game = game else { return } // TODO: Cancel digging when hotbar slot changes var family = nexus.family( requiresAll: PlayerInventory.self, PlayerGamemode.self, PlayerAttributes.self, EntityId.self, ClientPlayerEntity.self ).makeIterator() guard let (inventory, gamemode, attributes, playerEntityId, _) = family.next() else { log.error("PlayerInputSystem failed to get player to tick") return } guard gamemode.gamemode.canPlaceBlocks else { return } let guiState = nexus.single(GUIStateStorage.self).component guard guiState.movementAllowed else { return } // 5tick delay between successfully breaking a block and starting to break the next one. if let completionTick = lastDestroyCompletionTick, game.tickScheduler.tickNumber - completionTick <= 5 { return } let inputState = nexus.single(InputState.self).component guard let targetedBlock = game.targetedBlock(acquireLock: false) else { if let block = world.getBreakingBlocks().first(where: { $0.perpetratorEntityId == playerEntityId.id }) { world.endBlockBreaking(for: playerEntityId.id) try self.connection?.sendPacket(PlayerDiggingPacket( status: .cancelledDigging, location: block.position, face: .up // TODO: Figure out what value to use in this situation )) } return } let position = targetedBlock.target let notifyServer = { status in try self.connection?.sendPacket(PlayerDiggingPacket( status: status, location: position, face: targetedBlock.face )) } guard !attributes.canInstantBreak else { if inputState.newlyPressed.contains(where: { $0.input == .destroy }) { try notifyServer(.startedDigging) } return } let newlyReleased = inputState.newlyReleased.contains(where: { $0.input == .destroy }) if newlyReleased { world.endBlockBreaking(for: playerEntityId.id) try notifyServer(.cancelledDigging) } // Technically possible to release and press again within the same tick. if inputState.newlyPressed.contains(where: { $0.input == .destroy }) { world.startBreakingBlock(at: position, for: playerEntityId.id) try notifyServer(.startedDigging) } else if inputState.inputs.contains(.destroy) && !newlyReleased { let ourBreakingBlocks = world.getBreakingBlocks().filter { block in block.perpetratorEntityId == playerEntityId.id } var alreadyMiningTargetedBlock = false for block in ourBreakingBlocks { if block.position != position { world.endBlockBreaking(at: block.position) try notifyServer(.cancelledDigging) } else { alreadyMiningTargetedBlock = true } } if alreadyMiningTargetedBlock { // TODO: This may be off by one tick, worth double checking let block = world.getBlock(at: position) let heldItem = inventory.mainHandItem world.addBreakingProgress(Self.computeDestroyProgressDelta(block, heldItem), toBlockAt: position) let progress = world.getBlockBreakingProgress(at: position) ?? 0 if progress >= 1 { world.endBlockBreaking(for: playerEntityId.id) world.setBlockId(at: position, to: 0) try notifyServer(.finishedDigging) lastDestroyCompletionTick = game.tickScheduler.tickNumber } } else { world.startBreakingBlock(at: position, for: playerEntityId.id) try notifyServer(.startedDigging) } } } public static func computeDestroyProgressDelta(_ block: Block, _ heldItem: Item?) -> Double { let isBamboo = block.className == "BambooBlock" || block.className == "BambooSaplingBlock" let holdingSword = heldItem?.properties?.toolProperties?.kind == .sword if isBamboo && holdingSword { return 1 } else { let hardness = block.physicalMaterial.hardness // TODO: Sentinel values are gross, we could probably just make hardness an optional // (don't have to copy vanilla). I would do that right now but we need cache versioning // first cause I'm pretty sure that change is subtle enough that it might just crash cache // loading instead of forcing it to fail and retry from pixlyzer. guard hardness != -1 else { return 0 } let defaultSpeed = block.physicalMaterial.requiresTool ? 0.01 : (1 / 30) let toolSpeed = heldItem?.properties?.toolProperties?.destroySpeedMultiplier(for: block) ?? defaultSpeed return toolSpeed / hardness } } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/PlayerClimbSystem.swift ================================================ import FirebladeECS public struct PlayerClimbSystem: System { public func update(_ nexus: Nexus, _ world: World) { var family = nexus.family( requiresAll: EntityPosition.self, EntityVelocity.self, PlayerGamemode.self, PlayerCollisionState.self, ClientPlayerEntity.self ).makeIterator() guard let (position, velocity, gamemode, collisionState, _) = family.next() else { log.error("PlayerClimbSystem failed to get player to tick") return } let isOnLadder = Self.isOnLadder(position, world, gamemode.gamemode) guard isOnLadder else { return } let inputState = nexus.single(InputState.self).component // Limit horizontal velocity while on ladder. velocity.vector.x = MathUtil.clamp(velocity.vector.x, -0.15, 0.15) velocity.vector.z = MathUtil.clamp(velocity.vector.z, -0.15, 0.15) // Limit falling speed while on ladder. velocity.vector.y = max(velocity.vector.y, -0.15) // Ascending ladders takes precedence over sneaking on ladders. if collisionState.collidingHorizontally || inputState.inputs.contains(.jump) { velocity.vector.y = 0.2 } else if Self.isStoppedOnLadder(position, world, gamemode.gamemode, inputState, collisionState) { velocity.vector.y = 0 } } static func isOnLadder(_ position: EntityPosition, _ world: World, _ gamemode: Gamemode) -> Bool { guard gamemode != .spectator else { return false } let block = world.getBlock(at: position.block) if block.isClimbable { return true } else { // If the player is on an open trapdoor above a ladder then they're also counted as being on a ladder // as long as the ladder and trapdoor are facing the same way. let blockBelow = world.getBlock(at: position.block.neighbour(.down)) let blockIdentifierBelow = blockBelow.identifier let ladder = Identifier(name: "block/ladder") let onTrapdoorAboveLadder = block.className == "TrapdoorBlock" && blockIdentifierBelow == ladder let blocksFacingSameDirection = block.stateProperties.facing == blockBelow.stateProperties.facing let trapdoorIsOpen = block.stateProperties.isOpen == true return onTrapdoorAboveLadder && blocksFacingSameDirection && trapdoorIsOpen } } static func isStoppedOnLadder( _ position: EntityPosition, _ world: World, _ gamemode: Gamemode, _ inputState: InputState, _ collisionState: PlayerCollisionState ) -> Bool { let isClimbing = collisionState.collidingHorizontally || inputState.inputs.contains(.jump) return isOnLadder(position, world, gamemode) && !isClimbing && inputState.inputs.contains(.sneak) } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/PlayerCollisionSystem.swift ================================================ import FirebladeECS import FirebladeMath // TODO: Implement pushoutofblocks method (see decompiled vanilla sources) public struct PlayerCollisionSystem: System { static let stepHeight: Double = 0.6 public func update(_ nexus: Nexus, _ world: World) { var family = nexus.family( requiresAll: EntityPosition.self, EntityVelocity.self, EntityHitBox.self, EntityOnGround.self, PlayerGamemode.self, PlayerCollisionState.self, ClientPlayerEntity.self ).makeIterator() guard let (position, velocity, hitbox, onGround, gamemode, collisionState, _) = family.next() else { log.error("PlayerCollisionSystem failed to get player to tick") return } guard gamemode.gamemode.hasCollisions else { return } let original = velocity.vector let (adjustedVelocity, step) = Self.getAdjustedVelocityWithStepping( position.vector, velocity.vector, hitbox.aabb(at: position.vector), world, onGround.onGround ) velocity.vector = adjustedVelocity position.vector.y += step onGround.onGround = original.y < 0 && original.y != velocity.y collisionState.collidingVertically = original.y != velocity.y collisionState.collidingHorizontally = original.x != velocity.x || original.z != velocity.z } /// Adjusts the player's velocity to avoid collisions while automatically going up blocks under /// 0.5 tall (e.g. slabs or carpets). /// - Parameters: /// - position: The player's position. /// - velocity: The player's velocity. /// - aabb: The player's hitbox. /// - world: The world the player is colliding with. /// - Returns: The adjusted velocity, the magnitude will be between 0 and the magnitude of the original velocity. private static func getAdjustedVelocityWithStepping( _ position: Vec3d, _ velocity: Vec3d, _ aabb: AxisAlignedBoundingBox, _ world: World, _ onGround: Bool ) -> (velocity: Vec3d, step: Double) { // TODO: Rewrite to be more delta clienty perhaps (currently quite similar to vanilla's impl) let adjustedVelocity = getAdjustedVelocity(position, velocity, aabb, world) let willBeOnGround = adjustedVelocity.y != velocity.y && velocity.y < 0 let onGround = onGround || willBeOnGround let wasHorizontallyRestricted = adjustedVelocity.x != velocity.x || adjustedVelocity.z != velocity.z // Check if the player could step up to move further if onGround && wasHorizontallyRestricted { var velocityWithStep = getAdjustedVelocity( position, [velocity.x, Self.stepHeight, velocity.z], aabb, world ) let maximumVerticalVelocity = getAdjustedVelocity( position, [0, Self.stepHeight, 0], aabb.extend(by: [velocity.x, 0, velocity.z]), world ).y if maximumVerticalVelocity < Self.stepHeight { // If the player would hit their head while ascending a full stepHeight, check if stepping as // high as possible without hitting their head would avoid other collisions. let velocityWithSmallerStep = getAdjustedVelocity( position, [velocity.x, 0, velocity.z], aabb.offset(by: maximumVerticalVelocity, along: .y), world ) if velocityWithSmallerStep.horizontalMagnitude > velocityWithStep.horizontalMagnitude { velocityWithStep = velocityWithSmallerStep velocityWithStep.y = maximumVerticalVelocity } } if velocityWithStep.horizontalMagnitude > adjustedVelocity.horizontalMagnitude { // Recalculate the y velocity required to get up the 'step'. velocityWithStep += getAdjustedVelocity(position, [0, -Self.stepHeight, 0], aabb.offset(by: velocityWithStep), world) let step = velocityWithStep.y velocityWithStep.y = 0 return (velocity: velocityWithStep, step: step) } } return (velocity: adjustedVelocity, step: 0) } /// Adjusts the player's velocity to avoid collisions. /// - Parameters: /// - position: The player's position. /// - velocity: The player's velocity. /// - aabb: The player's hitbox. /// - world: The world the player is colliding with. /// - Returns: The adjusted velocity, the magnitude will be between 0 and the magnitude of the original velocity. private static func getAdjustedVelocity( _ position: Vec3d, _ velocity: Vec3d, _ aabb: AxisAlignedBoundingBox, _ world: World ) -> Vec3d { let collisionVolume = getCollisionVolume(position, velocity, aabb, world) var adjustedVelocity = velocity adjustedVelocity.y = adjustComponent(adjustedVelocity.y, onAxis: .y, collisionVolume: collisionVolume, aabb: aabb) var adjustedAABB = aabb.offset(by: adjustedVelocity.y, along: .y) let prioritizeZ = abs(velocity.z) > abs(velocity.x) if prioritizeZ { adjustedVelocity.z = adjustComponent(adjustedVelocity.z, onAxis: .z, collisionVolume: collisionVolume, aabb: adjustedAABB) adjustedAABB = adjustedAABB.offset(by: adjustedVelocity.z, along: .z) } adjustedVelocity.x = adjustComponent(adjustedVelocity.x, onAxis: .x, collisionVolume: collisionVolume, aabb: adjustedAABB) adjustedAABB = adjustedAABB.offset(by: adjustedVelocity.x, along: .x) if !prioritizeZ { adjustedVelocity.z = adjustComponent(adjustedVelocity.z, onAxis: .z, collisionVolume: collisionVolume, aabb: adjustedAABB) } if adjustedVelocity.magnitudeSquared > velocity.magnitudeSquared { adjustedVelocity = .zero } return adjustedVelocity } /// Adjusts the specified component of the player velocity to avoid any collisions along that axis. /// - Parameters: /// - value: The value of the velocity component. /// - axis: The axis the velocity component lies on. /// - collisionVolume: The volume to avoid collisions with. /// - aabb: The player aabb. /// - Returns: The adjusted velocity along the given axis. The adjusted value will be between 0 and the original velocity. private static func adjustComponent( _ value: Double, onAxis axis: Axis, collisionVolume: CompoundBoundingBox, aabb: AxisAlignedBoundingBox ) -> Double { if abs(value) < 0.0000001 { return 0 } var value = value for otherAABB in collisionVolume.aabbs { if !aabb.offset(by: value, along: axis).shrink(by: 0.001).intersects(with: otherAABB) { continue } let aabbMin = aabb.minimum.component(along: axis) let aabbMax = aabb.maximum.component(along: axis) let otherMin = otherAABB.minimum.component(along: axis) let otherMax = otherAABB.maximum.component(along: axis) if value > 0 && otherMin <= aabbMax + value { let newValue = otherMin - aabbMax if newValue >= -0.0000001 { value = min(newValue, value) } } else if value < 0 && otherMax >= aabbMin + value { let newValue = otherMax - aabbMin if newValue <= 0.0000001 { value = max(newValue, value) } } } return value } /// Gets a compound shape of all blocks the player could possibly be colliding with. /// /// It creates the smallest bounding box containing the current player AABB and the player AABB /// after adding the current velocity (pre-collisions). It then creates a compound bounding box /// containing all blocks within that volume. private static func getCollisionVolume( _ position: Vec3d, _ velocity: Vec3d, _ aabb: AxisAlignedBoundingBox, _ world: World ) -> CompoundBoundingBox { let nextAABB = aabb.offset(by: velocity) let minimum = MathUtil.min(aabb.minimum, nextAABB.minimum) let maximum = MathUtil.max(aabb.maximum, nextAABB.maximum) // Extend the AABB down one block to account for blocks such as fences let bigAABB = AxisAlignedBoundingBox(minimum: minimum, maximum: maximum).extend(.down, amount: 1) let blockPositions = bigAABB.blockPositions var collisionShape = CompoundBoundingBox() for blockPosition in blockPositions { guard world.isChunkComplete(at: blockPosition.chunk) else { continue } let block = world.getBlock(at: blockPosition) let blockShape = block.shape.collisionShape.offset(by: blockPosition.doubleVector) collisionShape.formUnion(blockShape) } return collisionShape } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/PlayerFOVSystem.swift ================================================ import Foundation import FirebladeECS public struct PlayerFOVSystem: System { public func update(_ nexus: Nexus, _ world: World) { var family = nexus.family( requiresAll: PlayerFOV.self, EntityAttributes.self, EntityFlying.self, ClientPlayerEntity.self ).makeIterator() guard let (fov, attributes, flying, _) = family.next() else { log.error("PlayerFOVSystem failed to get player to tick") return } // Save the current fov as the fov to smooth from over the course of the next tick. fov.save() let speedAttribute = attributes[EntityAttributeKey.movementSpeed] let speed = speedAttribute.value let baseSpeed = speedAttribute.baseValue var targetMultiplier: Float if baseSpeed != 0 && speed != 0 { targetMultiplier = Float((speed / baseSpeed + 1) / 2) if flying.isFlying { targetMultiplier *= 1.1 } } else { targetMultiplier = 1 } // The effective multiplier will creep up to the value of `targetMultiplier` over the // course of a few ticks. fov.multiplier += (targetMultiplier - fov.multiplier) / 2 if fov.multiplier > 1.5 { fov.multiplier = 1.5 } else if fov.multiplier < 0.1 { fov.multiplier = 0.1 } } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/PlayerFlightSystem.swift ================================================ import FirebladeECS public struct PlayerFlightSystem: System { public func update(_ nexus: Nexus, _ world: World) { var family = nexus.family( requiresAll: PlayerGamemode.self, EntityOnGround.self, EntityFlying.self, EntityVelocity.self, PlayerAttributes.self, ClientPlayerEntity.self ).makeIterator() guard let (gamemode, onGround, flying, velocity, attributes, _) = family.next() else { log.error("PlayerFlightSystem failed to get player to tick") return } let inputState = nexus.single(InputState.self).component if gamemode.gamemode.isAlwaysFlying { onGround.onGround = false flying.isFlying = true } else if onGround.onGround || !attributes.canFly { flying.isFlying = false } if inputState.inputs.contains(.fly) && !flying.isFlying && attributes.canFly { flying.isFlying = true } else if inputState.inputs.contains(.fly) && flying.isFlying && !gamemode.gamemode.isAlwaysFlying { flying.isFlying = false } if flying.isFlying { let sneakPressed = inputState.inputs.contains(.sneak) let jumpPressed = inputState.inputs.contains(.jump) if sneakPressed != jumpPressed { if sneakPressed { velocity.y -= Double(attributes.flyingSpeed * 3) } else { velocity.y += Double(attributes.flyingSpeed * 3) } } } } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/PlayerFrictionSystem.swift ================================================ import FirebladeECS public struct PlayerFrictionSystem: System { public func update(_ nexus: Nexus, _ world: World) { var family = nexus.family( requiresAll: EntityPosition.self, EntityVelocity.self, EntityOnGround.self, ClientPlayerEntity.self ).makeIterator() guard let (position, velocity, onGround, _) = family.next() else { log.error("PlayerFrictionSystem failed to get player to tick") return } var multiplier: Double = 0.91 if onGround.previousOnGround { let blockPosition = position.blockUnderneath let material = world.getBlock(at: blockPosition).physicalMaterial multiplier *= material.slipperiness } velocity.x *= multiplier velocity.y *= 0.98 velocity.z *= multiplier } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/PlayerGravitySystem.swift ================================================ import FirebladeECS import Foundation public struct PlayerGravitySystem: System { public func update(_ nexus: Nexus, _ world: World) { var family = nexus.family( requiresAll: EntityFlying.self, EntityVelocity.self, EntityPosition.self, PlayerGamemode.self, PlayerCollisionState.self, ClientPlayerEntity.self ).makeIterator() guard let (flying, velocity, position, gamemode, collisionState, _) = family.next() else { log.error("PlayerGravitySystem failed to get player to tick") return } let inputState = nexus.single(InputState.self).component guard !PlayerClimbSystem.isStoppedOnLadder(position, world, gamemode.gamemode, inputState, collisionState) else { return } guard !flying.isFlying else { return } if world.chunk(at: position.chunk) != nil { velocity.y -= 0.08 } velocity.y *= 0.98 } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/PlayerInputSystem.swift ================================================ import FirebladeECS #if os(macOS) // Used to access clipboard import AppKit #endif /// Handles all player input except for input related to player movement (see ``PlayerAccelerationSystem``). public final class PlayerInputSystem: System { var connection: ServerConnection? weak var game: Game? var eventBus: EventBus let configuration: ClientConfiguration let font: Font let locale: MinecraftLocale public init( _ connection: ServerConnection?, _ game: Game, _ eventBus: EventBus, _ configuration: ClientConfiguration, _ font: Font, _ locale: MinecraftLocale ) { self.connection = connection self.game = game self.eventBus = eventBus self.configuration = configuration self.font = font self.locale = locale } public func update(_ nexus: Nexus, _ world: World) throws { guard let game = game else { return } var family = nexus.family( requiresAll: EntityRotation.self, PlayerInventory.self, EntityCamera.self, PlayerGamemode.self, EntitySneaking.self, ClientPlayerEntity.self ).makeIterator() guard let (rotation, inventory, camera, gamemode, sneaking, _) = family.next() else { log.error("PlayerInputSystem failed to get player to tick") return } let inputState = nexus.single(InputState.self).component let guiState = nexus.single(GUIStateStorage.self).component let mousePosition = Vec2i(inputState.mousePosition / guiState.drawableScalingFactor) // Handle non-movement inputs var isInputSuppressed: [Bool] = [] for event in inputState.newlyPressed { var suppressInput = false // TODO: Formalize 'mouse targeted interactions are allowed', seems a bit hacky this way if !suppressInput && !guiState.movementAllowed { // Recompute the gui everytime that we get it to handle a new interaction because e.g. if previous // interactions within the same tick have closed the inventory and opened the chat, then the old // gui would still be handling the input for the inventory. That's a bit contrived, but I'm sure // other edge cases are possible, and recomputing the GUI is relatively cheap (and multiple inputs // within a single tick should be uncommon anyway). // Be careful not to acquire a nexus lock here (passing the guiState parameter ensures this) let gui = game.compileGUI( withFont: font, locale: locale, connection: connection, guiState: guiState ) suppressInput = gui.handleInteraction(.press(event), at: mousePosition) } if !suppressInput { suppressInput = try handleChat(event, inputState, guiState) } if !suppressInput { suppressInput = try handleInventory(event, inventory, guiState, eventBus, connection) } if !suppressInput { suppressInput = try handleWindow(event, guiState, eventBus, connection) } if !suppressInput { switch event.input { case .changePerspective: camera.cyclePerspective() case .toggleHUD: guiState.showHUD = !guiState.showHUD case .toggleDebugHUD: guiState.showDebugScreen = !guiState.showDebugScreen case .toggleInventory: // Closing the inventory is handled by `handleInventory` guiState.showInventory = true inputState.releaseAll() eventBus.dispatch(ReleaseCursorEvent()) case .slot1: inventory.selectedHotbarSlot = 0 case .slot2: inventory.selectedHotbarSlot = 1 case .slot3: inventory.selectedHotbarSlot = 2 case .slot4: inventory.selectedHotbarSlot = 3 case .slot5: inventory.selectedHotbarSlot = 4 case .slot6: inventory.selectedHotbarSlot = 5 case .slot7: inventory.selectedHotbarSlot = 6 case .slot8: inventory.selectedHotbarSlot = 7 case .slot9: inventory.selectedHotbarSlot = 8 case .nextSlot: inventory.selectedHotbarSlot = (inventory.selectedHotbarSlot + 1) % 9 case .previousSlot: inventory.selectedHotbarSlot = (inventory.selectedHotbarSlot + 8) % 9 case .dropItem: // TODO: Implement a similar check on other desktop platforms (Linux, Windows) #if os(macOS) let isQuitKeyboardShortcut = event.key == .q && (inputState.keys.contains(where: \.isCommand) || inputState.newlyPressed.contains { $0.key?.isCommand == true }) guard !isQuitKeyboardShortcut else { break } #endif let slotIndex = PlayerInventory.hotbarArea.startIndex + inventory.selectedHotbarSlot inventory.window.dropItemFromSlot( slotIndex, mouseItemStack: nil, connection: connection ) case .place: // Block breaking is handled by ``PlayerBlockBreakingSystem``, this just handles hand animation and // other non breaking things for the `.destroy` input (e.g. attacking) if inventory.hotbar[inventory.selectedHotbarSlot].stack != nil { try connection?.sendPacket(UseItemPacket(hand: .mainHand)) } guard let targetedThing = game.targetedThing(acquireLock: false) else { break } switch targetedThing.target { case let .block(blockPosition): let cursor = targetedThing.cursor try connection?.sendPacket( PlayerBlockPlacementPacket( hand: .mainHand, location: blockPosition, face: targetedThing.face, cursorPositionX: cursor.x, cursorPositionY: cursor.y, cursorPositionZ: cursor.z, insideBlock: targetedThing.distance < 0 ) ) if gamemode.gamemode.canPlaceBlocks { // TODO: Predict the result of block placement so that we're not relying on the server // (quite noticeable latency) } case let .entity(entityId): let targetedPosition = targetedThing.targetedPosition try connection?.sendPacket( InteractEntityPacket( entityId: Int32(entityId), interaction: .interactAt( targetX: targetedPosition.x, targetY: targetedPosition.y, targetZ: targetedPosition.z, hand: .mainHand, isSneaking: sneaking.isSneaking ) ) ) try connection?.sendPacket( InteractEntityPacket( entityId: Int32(entityId), interaction: .interact(hand: .mainHand, isSneaking: sneaking.isSneaking) ) ) } case .destroy: guard let targetedEntity = game.targetedEntity(acquireLock: false) else { try connection?.sendPacket(AnimationServerboundPacket(hand: .mainHand)) break } var entityId = targetedEntity.target if let dragonParts = game.accessComponent( entityId: targetedEntity.target, EnderDragonParts.self, acquireLock: false, action: identity ) { guard let dragonPosition = game.accessComponent( entityId: targetedEntity.target, EntityPosition.self, acquireLock: false, action: identity ) else { log.warning("Ender dragon missing position") break } let ray = game.accessPlayer(acquireLock: false, action: \.ray) var currentDistance: Float = Player.attackReach for part in dragonParts.parts { let aabb = part.aabb(withParentPosition: dragonPosition.vector) if let (distance, _) = aabb.intersectionDistanceAndFace(with: ray), distance < currentDistance { entityId = targetedEntity.target + part.entityIdOffset currentDistance = distance } } } try connection?.sendPacket( InteractEntityPacket( entityId: Int32(entityId), interaction: .attack(isSneaking: sneaking.isSneaking) ) ) default: break } if event.key == .escape { eventBus.dispatch(OpenInGameMenuEvent()) } } isInputSuppressed.append(suppressInput) } // Handle mouse input. if guiState.movementAllowed { updateRotation(inputState, rotation) } inputState.resetMouseDelta() inputState.tick(isInputSuppressed, eventBus, configuration) } /// - Returns: Whether to suppress the input associated with the event or not. `true` while user is typing. private func handleChat( _ event: KeyPressEvent, _ inputState: InputState, _ guiState: GUIStateStorage ) throws -> Bool { if var message = guiState.messageInput { var newCharacters: [Character] = [] if event.key == .enter { if !message.isEmpty { try connection?.sendPacket(ChatMessageServerboundPacket(message)) guiState.playerMessageHistory.append(message) guiState.currentMessageIndex = nil } guiState.messageInput = nil eventBus.dispatch(CaptureCursorEvent()) return true } else if event.key == .escape { guiState.messageInputCursor = 0 guiState.messageInput = nil guiState.currentMessageIndex = nil eventBus.dispatch(CaptureCursorEvent()) return true } else if event.key == .delete { if !message.isEmpty && guiState.messageInputCursor < guiState.messageInput?.count ?? 0 { guiState.messageInput?.remove(at: message.index(before: guiState.messageInputCursorIndex)) } } else if event.key == .upArrow { // If no message is selected, select the above message if let index = guiState.currentMessageIndex, index > 0 { guiState.currentMessageIndex = index - 1 guiState.messageInput = guiState.playerMessageHistory[index - 1] } else if guiState.currentMessageIndex == nil && !guiState.playerMessageHistory.isEmpty { guiState.stashedMessageInput = guiState.messageInput let index = guiState.playerMessageHistory.count - 1 guiState.currentMessageIndex = index guiState.messageInput = guiState.playerMessageHistory[index] } } else if event.key == .downArrow { // If there is a message selected, index down a message if let index = guiState.currentMessageIndex { if index < guiState.playerMessageHistory.count - 1 { guiState.currentMessageIndex = index + 1 guiState.messageInput = guiState.playerMessageHistory[index + 1] } else { // If there is no message to index down to, go back to what the user was typing originally guiState.currentMessageIndex = nil guiState.messageInput = guiState.stashedMessageInput ?? "" } } } else if event.key == .leftArrow && guiState.messageInput?.count ?? 0 > guiState.messageInputCursor { guiState.messageInputCursor += 1 } else if event.key == .rightArrow && guiState.messageInputCursor > 0 { guiState.messageInputCursor -= 1 } else { #if os(macOS) if event.key == .v && !inputState.keys.intersection([.leftCommand, .rightCommand]).isEmpty { // Handle paste keyboard shortcut if let content = NSPasteboard.general.string(forType: .string) { newCharacters = Array(content) } } else if message.utf8.count < InGameGUI.maximumMessageLength { newCharacters = event.characters } #else if message.utf8.count < InGameGUI.maximumMessageLength { newCharacters = event.characters } #endif // Ensure that the message doesn't exceed 256 bytes (including if multi-byte characters are entered). var count = 0 for character in newCharacters { guard character.isPrintable, character != "\t" else { // TODO: Make this check less restrictive, it's currently over-cautious continue } guard character.utf8.count + message.utf8.count <= InGameGUI.maximumMessageLength else { break } let index = message.index(guiState.messageInputCursorIndex, offsetBy: count) message.insert(character, at: index) count += 1 } guiState.messageInput = message } } else if event.input == .openChat { guiState.messageInput = "" // TODO: Refactor input handling to be a bit more declarative so that something like // issue #192 is less likely to happen again. Besides, this input handling code is // pretty spaghetti and could do with a makeover anyway. inputState.releaseAll() eventBus.dispatch(ReleaseCursorEvent()) } else if event.key == .forwardSlash { guiState.messageInput = "/" inputState.releaseAll() eventBus.dispatch(ReleaseCursorEvent()) } // Suppress inputs while the user is typing. return guiState.showChat } /// - Returns: Whether to suppress the input associated with the event or not. private func handleInventory( _ event: KeyPressEvent, _ inventory: PlayerInventory, _ guiState: GUIStateStorage, _ eventBus: EventBus, _ connection: ServerConnection? ) throws -> Bool { guard guiState.showInventory else { return false } if event.key == .escape || event.input == .toggleInventory { // Weirdly enough, the vanilla client sends a close window packet when closing the player's // inventory even though it never tells the server that it opened the inventory in the first // place. Likely just for the server to verify the slots and chuck out anything in the crafting // area. try inventory.window.close( mouseStack: &guiState.mouseItemStack, eventBus: eventBus, connection: connection ) guiState.showInventory = false } return true } /// - Returns: Whether to suppress the input associated with the event or not. private func handleWindow( _ event: KeyPressEvent, _ guiState: GUIStateStorage, _ eventBus: EventBus, _ connection: ServerConnection? ) throws -> Bool { guard let window = guiState.window else { return false } if event.key == .escape || event.input == .toggleInventory { try window.close( mouseStack: &guiState.mouseItemStack, eventBus: eventBus, connection: connection ) guiState.window = nil } return true } /// Updates the direction which the player is looking. /// - Parameters: /// - inputState: The current input state. /// - rotation: The player's rotation component. private func updateRotation(_ inputState: InputState, _ rotation: EntityRotation) { let thumbstickSensitivity: Float = 0.2 let stick = inputState.rightThumbstick * thumbstickSensitivity let mouseDelta = inputState.mouseDelta var yaw = rotation.yaw + mouseDelta.x + stick.x var pitch = rotation.pitch + mouseDelta.y - stick.y // Clamp pitch between -90 and 90 pitch = MathUtil.clamp(pitch, -.pi / 2, .pi / 2) // Wrap yaw to be between 0 and 360 let remainder = yaw.truncatingRemainder(dividingBy: .pi * 2) yaw = remainder < 0 ? .pi * 2 + remainder : remainder rotation.yaw = yaw rotation.pitch = pitch } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/PlayerJumpSystem.swift ================================================ import Foundation import FirebladeECS public struct PlayerJumpSystem: System { public func update(_ nexus: Nexus, _ world: World) { var family = nexus.family( requiresAll: EntityOnGround.self, EntitySprinting.self, EntityVelocity.self, EntityPosition.self, EntityRotation.self, ClientPlayerEntity.self ).makeIterator() guard let (onGround, sprinting, velocity, position, rotation, _) = family.next() else { log.error("PlayerJumpSystem failed to get player to tick") return } let inputState = nexus.single(InputState.self).component guard onGround.onGround && inputState.inputs.contains(.jump) else { return } let blockPosition = BlockPosition( x: Int(position.x.rounded(.down)), y: Int((position.y - 0.5).rounded(.down)), z: Int(position.z.rounded(.down)) ) let block = world.getBlock(at: blockPosition) let jumpPower = 0.42 * Double(block.physicalMaterial.jumpVelocityMultiplier) velocity.y = jumpPower // Add a bit of extra acceleration if the player is sprinting (this makes sprint jumping faster than sprinting) if sprinting.isSprinting { let yaw = Double(rotation.yaw) velocity.x -= Foundation.sin(yaw) * 0.2 velocity.z += Foundation.cos(yaw) * 0.2 } } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/PlayerPacketSystem.swift ================================================ import FirebladeECS import FirebladeMath /// Sends update packets to the server depending on which client and player properties have changed. /// Mostly sends movement packets. public struct PlayerPacketSystem: System { var connection: ServerConnection var state = State() class State { var previousHotbarSlot = -1 var wasSprinting = false var wasSneaking = false var wasFlying = false var ticksUntilForcedPositionUpdate = 20 var lastPositionSent = Vec3d.zero } public init(_ connection: ServerConnection) { self.connection = connection } public func update(_ nexus: Nexus, _ world: World) throws { guard connection.hasJoined else { return } var family = nexus.family( requiresAll: PlayerInventory.self, EntityId.self, EntitySprinting.self, EntitySneaking.self, EntityPosition.self, EntityRotation.self, EntityOnGround.self, EntityFlying.self, ClientPlayerEntity.self ).makeIterator() guard let (inventory, entityId, sprinting, sneaking, position, rotation, onGround, flying, _) = family.next() else { log.error("PlayerPacketSystem failed to get player to tick") return } // Send hotbar slot update if inventory.selectedHotbarSlot != state.previousHotbarSlot { try connection.sendPacket(HeldItemChangeServerboundPacket(slot: Int16(inventory.selectedHotbarSlot))) state.previousHotbarSlot = inventory.selectedHotbarSlot } // Send sprinting update let isSprinting = sprinting.isSprinting if isSprinting != state.wasSprinting { try connection.sendPacket(EntityActionPacket( entityId: Int32(entityId.id), action: isSprinting ? .startSprinting : .stopSprinting )) state.wasSprinting = isSprinting } // Send sneaking update let isSneaking = sneaking.isSneaking if isSneaking != state.wasSneaking { try connection.sendPacket(EntityActionPacket( entityId: Int32(entityId.id), action: isSneaking ? .startSneaking : .stopSneaking )) state.wasSneaking = isSneaking } // Send position update if player has moved fast enough let positionDelta = (position.vector - state.lastPositionSent).magnitudeSquared state.ticksUntilForcedPositionUpdate -= 1 let mustSendPositionUpdate = positionDelta > 0.0009 || state.ticksUntilForcedPositionUpdate == 0 let hasRotated = rotation.previousPitch != rotation.pitch || rotation.previousYaw != rotation.yaw var positionUpdateSent = true if mustSendPositionUpdate && hasRotated { try connection.sendPacket(PlayerPositionAndRotationServerboundPacket( position: position.vector, yaw: MathUtil.degrees(from: rotation.yaw), pitch: MathUtil.degrees(from: rotation.pitch), onGround: onGround.onGround )) } else if mustSendPositionUpdate { try connection.sendPacket(PlayerPositionPacket( position: position.vector, onGround: onGround.onGround )) } else if hasRotated { try connection.sendPacket(PlayerRotationPacket( yaw: MathUtil.degrees(from: rotation.yaw), pitch: MathUtil.degrees(from: rotation.pitch), onGround: onGround.onGround )) } else if onGround.onGround != onGround.previousOnGround { try connection.sendPacket(PlayerMovementPacket(onGround: onGround.onGround)) } else { positionUpdateSent = false } if flying.isFlying != state.wasFlying { state.wasFlying = flying.isFlying // TODO: Ensure other player flags are preserved try connection.sendPacket(PlayerAbilitiesServerboundPacket(flags: flying.isFlying ? [.flying] : [])) } if positionUpdateSent { state.ticksUntilForcedPositionUpdate = 20 state.lastPositionSent = position.vector } } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/PlayerPositionSystem.swift ================================================ import FirebladeECS public struct PlayerPositionSystem: System { public func update(_ nexus: Nexus, _ world: World) { var family = nexus.family( requiresAll: EntityPosition.self, EntityVelocity.self, EntityFlying.self, ClientPlayerEntity.self ).makeIterator() guard let (position, velocity, flying, _) = family.next() else { log.error("PlayerPositionSystem failed to get player to tick") return } position.vector += velocity.vector position.x = MathUtil.clamp(position.x, -29_999_999, 29_999_999) position.z = MathUtil.clamp(position.z, -29_999_999, 29_999_999) if flying.isFlying { velocity.y *= 0.6 } } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/PlayerSmoothingSystem.swift ================================================ import FirebladeECS public struct PlayerSmoothingSystem: System { public func update(_ nexus: Nexus, _ world: World) { var family = nexus.family( requiresAll: EntityPosition.self, EntityRotation.self, EntityOnGround.self, ClientPlayerEntity.self ).makeIterator() guard let (position, rotation, onGround, _) = family.next() else { log.error("PlayerSmoothingSystem failed to get player to tick") return } position.save() rotation.save() onGround.save() } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/PlayerVelocitySystem.swift ================================================ import FirebladeECS public struct PlayerVelocitySystem: System { public func update(_ nexus: Nexus, _ world: World) { var family = nexus.family( requiresAll: EntityPosition.self, EntityVelocity.self, EntityAcceleration.self, EntityOnGround.self, ClientPlayerEntity.self ).makeIterator() guard let (position, velocity, acceleration, onGround, _) = family.next() else { log.error("PlayerVelocitySystem failed to get player to tick") return } if abs(velocity.x) < 0.003 { velocity.x = 0 } if abs(velocity.y) < 0.003 { velocity.y = 0 } if abs(velocity.z) < 0.003 { velocity.z = 0 } velocity.vector += acceleration.vector if onGround.onGround { let blockPosition = BlockPosition( x: Int(position.x.rounded(.down)), y: Int((position.y - 0.5).rounded(.down)), z: Int(position.z.rounded(.down))) let material = world.getBlock(at: blockPosition).physicalMaterial velocity.x *= material.velocityMultiplier velocity.z *= material.velocityMultiplier } } } ================================================ FILE: Sources/Core/Sources/ECS/Systems/System.swift ================================================ import FirebladeECS public protocol System { func update(_ nexus: Nexus, _ world: World) throws } ================================================ FILE: Sources/Core/Sources/FileSystem.swift ================================================ import Foundation /// An interface to the file system (a better version of `FileManager.default` from `Foundation`). public enum FileSystem { /// Gets whether a file or directory exists at the specified URL. public static func itemExists(_ item: URL) -> Bool { return FileManager.default.fileExists(atPath: item.path) } /// Gets whether a given directory exists. public static func directoryExists(_ directory: URL) -> Bool { var isDirectory = ObjCBool(false) let itemExists = FileManager.default.fileExists(atPath: directory.path, isDirectory: &isDirectory) return itemExists && isDirectory.boolValue } /// Gets whether a given file exists (`false` if the URL points to a directory). public static func fileExists(_ file: URL) -> Bool { var isDirectory = ObjCBool(false) let itemExists = FileManager.default.fileExists(atPath: file.path, isDirectory: &isDirectory) return itemExists && !isDirectory.boolValue } /// Gets the direct descendants of a directory. public static func children(of directory: URL) throws -> [URL] { return try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) } /// Deletes the given file or directory. public static func remove(_ item: URL) throws { try FileManager.default.removeItem(at: item) } /// Creates a directory (including any required intermediate directories). public static func createDirectory(_ directory: URL) throws { try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) } } ================================================ FILE: Sources/Core/Sources/GUI/BossBar.swift ================================================ import Foundation public struct BossBar { public var id: UUID public var title: ChatComponent /// The boss's health as a value from 0 to 1. public var health: Float public var color: Color public var style: Style public var flags: Flags public enum Color: Int { case pink = 0 case blue = 1 case red = 2 case green = 3 case yellow = 4 case purple = 5 case white = 6 /// The background and foreground sprites used when rendering a boss bar of /// this color. public var sprites: (background: GUISprite, foreground: GUISprite) { switch self { case .pink: return (.pinkBossBarBackground, .pinkBossBarForeground) case .blue: return (.blueBossBarBackground, .blueBossBarForeground) case .red: return (.redBossBarBackground, .redBossBarForeground) case .green: return (.greenBossBarBackground, .greenBossBarForeground) case .yellow: return (.yellowBossBarBackground, .yellowBossBarForeground) case .purple: return (.purpleBossBarBackground, .purpleBossBarForeground) case .white: return (.whiteBossBarBackground, .whiteBossBarForeground) } } } public enum Style: Int { case noNotches = 0 case sixNotches = 1 case tenNotches = 2 case twelveNotches = 3 case twentyNotches = 4 /// The bar overlay sprite used when rendering a boss bar of this style. public var overlay: GUISprite { switch self { case .noNotches: return .bossBarNoNotchOverlay case .sixNotches: return .bossBarSixNotchOverlay case .tenNotches: return .bossBarTenNotchOverlay case .twelveNotches: return .bossBarTwelveNotchOverlay case .twentyNotches: return .bossBarTwentyNotchOverlay } } } public struct Flags { public var darkenSky: Bool public var createFog: Bool public var isEnderDragonHealthBar: Bool public init(darkenSky: Bool, createFog: Bool, isEnderDragonHealthBar: Bool) { self.darkenSky = darkenSky self.createFog = createFog self.isEnderDragonHealthBar = isEnderDragonHealthBar } } public init( id: UUID, title: ChatComponent, health: Float, color: BossBar.Color, style: BossBar.Style, flags: BossBar.Flags ) { self.id = id self.title = title self.health = health self.color = color self.style = style self.flags = flags } } ================================================ FILE: Sources/Core/Sources/GUI/Constraints.swift ================================================ import FirebladeMath public struct Constraints { public var vertical: VerticalConstraint public var horizontal: HorizontalConstraint public init(_ vertical: VerticalConstraint, _ horizontal: HorizontalConstraint) { self.vertical = vertical self.horizontal = horizontal } public static let center = Constraints(.center, .center) public static func position(_ x: Int, _ y: Int) -> Constraints { return Constraints(.top(y), .left(x)) } public func solve(innerSize: Vec2i, outerSize: Vec2i) -> Vec2i { let x: Int switch horizontal { case .left(let distance): x = distance case .center(let offset): x = (outerSize.x - innerSize.x) / 2 + (offset?.value ?? 0) case .right(let distance): x = outerSize.x - innerSize.x - distance } let y: Int switch vertical { case .top(let distance): y = distance case .center(let offset): y = (outerSize.y - innerSize.y) / 2 + (offset?.value ?? 0) case .bottom(let distance): y = outerSize.y - innerSize.y - distance } return [x, y] } } ================================================ FILE: Sources/Core/Sources/GUI/GUIBuilder.swift ================================================ @resultBuilder public struct GUIBuilder { public static func buildBlock(_ elements: GUIElement...) -> GUIElement { .list(spacing: 0, elements: elements) } public static func buildEither(first component: GUIElement) -> GUIElement { component } public static func buildEither(second component: GUIElement) -> GUIElement { component } public static func buildOptional(_ component: GUIElement?) -> GUIElement { if let component = component { return component } else { return .spacer(width: 0, height: 0) } } } ================================================ FILE: Sources/Core/Sources/GUI/GUIElement.swift ================================================ // TODO: Update container related modifier methods to avoid unnecessary nesting where possible, // e.g. `.expand().padding(2)` should only result in a single container being added instead of // two levels of nested containers. public indirect enum GUIElement { public enum Direction { case vertical case horizontal } public struct DirectionSet: ExpressibleByArrayLiteral, Equatable { public var horizontal: Bool public var vertical: Bool public static let both: Self = [.horizontal, .vertical] public static let neither: Self = [] public static let horizontal: Self = [.horizontal] public static let vertical: Self = [.vertical] public init(arrayLiteral elements: Direction...) { vertical = elements.contains(.vertical) horizontal = elements.contains(.horizontal) } } public enum Edge { case top case bottom case left case right } public struct EdgeSet: ExpressibleByArrayLiteral { public var edges: Set public static let top: Self = [.top] public static let bottom: Self = [.bottom] public static let left: Self = [.left] public static let right: Self = [.right] public static let vertical: Self = [.top, .bottom] public static let horizontal: Self = [.left, .right] public static let all: Self = [.top, .bottom, .left, .right] public init(arrayLiteral elements: Edge...) { edges = Set(elements) } public func contains(_ edge: Edge) -> Bool { edges.contains(edge) } } public struct Padding { public var top: Int public var bottom: Int public var left: Int public var right: Int /// The total padding along each axis. public var axisTotals: Vec2i { Vec2i( left + right, top + bottom ) } public static let zero: Self = Padding(top: 0, bottom: 0, left: 0, right: 0) public init(top: Int, bottom: Int, left: Int, right: Int) { self.top = top self.bottom = bottom self.left = left self.right = right } public init(edges: EdgeSet, amount: Int) { self.top = edges.contains(.top) ? amount : 0 self.bottom = edges.contains(.bottom) ? amount : 0 self.left = edges.contains(.left) ? amount : 0 self.right = edges.contains(.right) ? amount : 0 } } case text(_ content: String, wrap: Bool = false, color: Vec4f = Vec4f(1, 1, 1, 1)) case message(_ message: ChatComponent, wrap: Bool = true) case interactable(_ element: GUIElement, handleInteraction: (Interaction) -> Bool) case sprite(GUISprite) case customSprite(GUISpriteDescriptor) /// Stacks elements in the specified direction. Aligns elements to the top left by default. case list(direction: Direction = .vertical, spacing: Int, elements: [GUIElement]) /// Stacks elements in the z direction. Non-positioned elements default to the top-left corner. /// Elements appear on top of the elements that come before them. case stack(elements: [GUIElement]) case positioned(element: GUIElement, constraints: Constraints) case sized(element: GUIElement, width: Int?, height: Int?) case spacer(width: Int, height: Int) /// Wraps an element with a background. case container( element: GUIElement, background: Vec4f?, padding: Padding, paddingColor: Vec4f?, expandDirections: DirectionSet = .neither ) case floating(element: GUIElement) case item(id: Int) public var children: [GUIElement] { switch self { case let .list(_, _, elements), let .stack(elements): return elements case let .interactable(element, _), let .positioned(element, _), let .sized(element, _, _), let .container(element, _, _, _, _), let .floating(element): return [element] case .text, .message, .sprite, .customSprite, .spacer, .item: return [] } } public static let textWrapIndent: Int = 4 public static let lineSpacing: Int = 1 public static func list( direction: Direction = .vertical, spacing: Int, @GUIBuilder elements: () -> GUIElement ) -> GUIElement { .list(direction: direction, spacing: spacing, elements: elements().children) } public static func forEach( in values: S, direction: Direction = .vertical, spacing: Int, @GUIBuilder element: (S.Element) -> GUIElement ) -> GUIElement { let elements = values.map(element) return .list(direction: direction, spacing: spacing, elements: elements) } public static func stack(@GUIBuilder elements: () -> GUIElement) -> GUIElement { .stack(elements: elements().children) } public func center() -> GUIElement { .positioned(element: self, constraints: .center) } public func positionInParent(_ x: Int, _ y: Int) -> GUIElement { .positioned(element: self, constraints: .position(x, y)) } public func positionInParent(_ position: Vec2i) -> GUIElement { .positioned(element: self, constraints: .position(position.x, position.y)) } public func constraints( _ verticalConstraint: VerticalConstraint, _ horizontalConstraint: HorizontalConstraint ) -> GUIElement { .positioned(element: self, constraints: Constraints(verticalConstraint, horizontalConstraint)) } public func constraints(_ constraints: Constraints) -> GUIElement { .positioned(element: self, constraints: constraints) } /// `nil` indicates to use the natural width/height (the default). public func size(_ width: Int?, _ height: Int?) -> GUIElement { .sized(element: self, width: width, height: height) } public func size(_ size: Vec2i) -> GUIElement { .sized(element: self, width: size.x, height: size.y) } public func padding(_ amount: Int) -> GUIElement { self.padding(.all, amount) } public func padding(_ edges: EdgeSet, _ amount: Int) -> GUIElement { .container(element: self, background: nil, padding: Padding(edges: edges, amount: amount), paddingColor: nil) } public func border(_ amount: Int, _ color: Vec4f) -> GUIElement { self.border(.all, amount, color) } public func border(_ edges: EdgeSet, _ amount: Int, _ color: Vec4f) -> GUIElement { .container(element: self, background: nil, padding: Padding(edges: edges, amount: amount), paddingColor: color) } public func background(_ color: Vec4f) -> GUIElement { // Sometimes we can just update the element instead of adding another layer. switch self { case let .container(element, background, padding, paddingColor, expandDirections): if background == nil { return .container( element: element, background: color, padding: padding, paddingColor: paddingColor, expandDirections: expandDirections ) } default: break } return .container(element: self, background: color, padding: .zero, paddingColor: nil) } public func expand(_ directions: DirectionSet = .both) -> GUIElement { if case let .container(element, background, padding, paddingColor, .neither) = self { return .container( element: element, background: background, padding: padding, paddingColor: paddingColor, expandDirections: directions ) } return .container(element: self, background: .zero, padding: .zero, paddingColor: nil, expandDirections: directions) } public func onClick(_ action: @escaping () -> Void) -> GUIElement { onHoverKeyPress(matching: .leftMouseButton, action) } public func onRightClick(_ action: @escaping () -> Void) -> GUIElement { onHoverKeyPress(matching: .rightMouseButton, action) } public func onHoverKeyPress(matching key: Key, _ action: @escaping () -> Void) -> GUIElement { .interactable( self, handleInteraction: { interaction in switch interaction { case let .press(event): if event.key == key { action() return true } else { return false } case .release: return false } } ) } public func onHoverKeyPress(_ action: @escaping (KeyPressEvent) -> Bool) -> GUIElement { .interactable( self, handleInteraction: { interaction in switch interaction { case let .press(event): return action(event) case .release: return false } } ) } /// Sets an element's apparent size to zero so that it doesn't partake in layout. /// It will still get put exactly where it otherwise would, but for example if the /// element is in a list, all following elements will be positioned as if the element /// doesn't exist (except double spacing where the element would've been). /// /// Any constraints placed on an element after it has been floated will act as if the /// element is of zero size. This probably isn't the best and could be fixed without /// too much effort (by making element rendering logic understand floating instead of /// just pretending the size is zero). public func float() -> GUIElement { .floating(element: self) } public enum Interaction { case press(KeyPressEvent) case release(KeyReleaseEvent) } public struct GUIRenderable { public var relativePosition: Vec2i public var size: Vec2i public var content: Content? public var children: [GUIRenderable] public enum Content { case text(wrappedLines: [String], hangingIndent: Int, color: Vec4f) case interactable(handleInteraction: (Interaction) -> Bool) case sprite(GUISpriteDescriptor) /// Fills the renderable with the given background color. Goes behind /// any children that the renderable may have. case background(Vec4f) case item(id: Int) } // Returns true if the click was handled by the renderable or any of its children. public func handleInteraction(_ interaction: Interaction, at position: Vec2i) -> Bool { guard Self.isHit(position, inBoxAt: relativePosition, ofSize: size) else { return false } switch content { case let .interactable(handleInteraction): if handleInteraction(interaction) { return true } case .text, .sprite, .background, .item, nil: break } let relativeClickPosition = position &- relativePosition for renderable in children.reversed() { if renderable.handleInteraction(interaction, at: relativeClickPosition) { return true } } return false } private static func isHit( _ position: Vec2i, inBoxAt upperLeft: Vec2i, ofSize size: Vec2i ) -> Bool { return position.x > upperLeft.x && position.x < (upperLeft.x + size.x) && position.y > upperLeft.y && position.y < (upperLeft.y + size.y) } } public func resolveConstraints( availableSize: Vec2i, font: Font, locale: MinecraftLocale ) -> GUIRenderable { let relativePosition: Vec2i let size: Vec2i let content: GUIRenderable.Content? let children: [GUIRenderable] switch self { case let .text(text, wrap, color): // Wrap the lines, but if wrapping is disabled wrap to a width of Int.max (so that we can // still compute the width of the line). let lines = Self.wrap( text, maximumWidth: wrap ? availableSize.x : .max, indent: Self.textWrapIndent, font: font ) relativePosition = .zero size = Vec2i( lines.map(\.width).max() ?? 0, lines.count * Font.defaultCharacterHeight + (lines.count - 1) * Self.lineSpacing ) content = .text( wrappedLines: lines.map(\.line), hangingIndent: Self.textWrapIndent, color: color ) children = [] case let .message(message, wrap): let text = message.toText(with: locale) return GUIElement.text(text, wrap: wrap) .resolveConstraints(availableSize: availableSize, font: font, locale: locale) case let .interactable(label, handleInteraction): let child = label.resolveConstraints( availableSize: availableSize, font: font, locale: locale ) relativePosition = .zero size = child.size content = .interactable(handleInteraction: handleInteraction) children = [child] case let .sprite(sprite): let descriptor = sprite.descriptor relativePosition = .zero size = descriptor.size content = .sprite(descriptor) children = [] case let .customSprite(descriptor): relativePosition = .zero size = descriptor.size content = .sprite(descriptor) children = [] case let .list(direction, spacing, elements): var availableSize = availableSize var childPosition = Vec2i(0, 0) let axisComponent = direction == .vertical ? 1 : 0 children = elements.map { element in var renderable = element.resolveConstraints( availableSize: availableSize, font: font, locale: locale ) renderable.relativePosition[axisComponent] += childPosition[axisComponent] let rowSize = renderable.size[axisComponent] + spacing childPosition[axisComponent] += rowSize availableSize[axisComponent] -= rowSize return renderable } relativePosition = .zero let lengthAlongAxis = elements.isEmpty ? 0 : childPosition[axisComponent] - spacing switch direction { case .vertical: let width = children.map(\.size.x).max() ?? 0 size = Vec2i(width, lengthAlongAxis) case .horizontal: let height = children.map(\.size.y).max() ?? 0 size = Vec2i(lengthAlongAxis, height) } content = nil case let .stack(elements): children = elements.map { element in element.resolveConstraints( availableSize: availableSize, font: font, locale: locale ) } size = Vec2i( children.map { renderable in renderable.size.x + renderable.relativePosition.x }.max() ?? 0, children.map { renderable in renderable.size.y + renderable.relativePosition.y }.max() ?? 0 ) relativePosition = .zero content = nil case let .positioned(element, constraints): let child = element.resolveConstraints( availableSize: availableSize, font: font, locale: locale ) children = [child] relativePosition = constraints.solve( innerSize: child.size, outerSize: availableSize ) size = child.size content = nil case let .sized(element, width, height): let child = element.resolveConstraints( availableSize: Vec2i( width ?? availableSize.x, height ?? availableSize.y ), font: font, locale: locale ) children = [child] relativePosition = .zero size = Vec2i( width ?? child.size.x, height ?? child.size.y ) content = nil case let .spacer(width, height): children = [] relativePosition = .zero size = Vec2i(width, height) content = nil case let .container(element, background, padding, paddingColor, expandDirections): let paddingAxisTotals = padding.axisTotals var child = element.resolveConstraints( availableSize: availableSize &- paddingAxisTotals, font: font, locale: locale ) child.relativePosition &+= Vec2i(padding.left, padding.top) relativePosition = .zero size = Vec2i( expandDirections.horizontal ? availableSize.x : min(availableSize.x, child.size.x + paddingAxisTotals.x), expandDirections.vertical ? availableSize.y : min(availableSize.y, child.size.y + paddingAxisTotals.y) ) let expandedChildSize = size &- paddingAxisTotals if let paddingColor = paddingColor { // Something feels kinda dark about this variable name... var borderChildren: [GUIRenderable] = [] // https://open.spotify.com/track/5hM5arv9KDbCHS0k9uqwjr?si=58df9b2231e848b8 func addBorderLine(position: Vec2i, size: Vec2i) { borderChildren.append(GUIRenderable( relativePosition: position, size: size, content: .background(paddingColor), children: [] )) } if padding.left != 0 { addBorderLine( position: [0, 0], size: [padding.left, expandedChildSize.y + paddingAxisTotals.y] ) } if padding.right != 0 { addBorderLine( position: [padding.left + expandedChildSize.x, 0], size: [padding.right, expandedChildSize.y + paddingAxisTotals.y] ) } if padding.top != 0 { addBorderLine( position: [padding.left, 0], size: [expandedChildSize.x, padding.top] ) } if padding.bottom != 0 { addBorderLine( position: [padding.left, padding.top + expandedChildSize.y], size: [expandedChildSize.x, padding.bottom] ) } let backgroundChild: GUIRenderable? if let background = background { backgroundChild = GUIRenderable( relativePosition: Vec2i(padding.left, padding.top), size: child.size, content: .background(background), children: [] ) } else { backgroundChild = nil } children = borderChildren + [ backgroundChild, child ].compactMap(identity) content = nil } else { children = [child] content = background.map(GUIRenderable.Content.background) } case let .floating(element): let child = element.resolveConstraints( availableSize: availableSize, font: font, locale: locale ) children = [child] relativePosition = .zero size = .zero content = nil case let .item(id): children = [] relativePosition = .zero size = Vec2i(16, 16) content = .item(id: id) } return GUIRenderable( relativePosition: relativePosition, size: size, content: content, children: children ) } /// `indent` must be less than `maximumWidth` and `maximumWidth` must greater than the width of /// each individual character in the string. static func wrap(_ text: String, maximumWidth: Int, indent: Int, font: Font) -> [(line: String, width: Int)] { assert(indent < maximumWidth, "indent must be smaller than maximumWidth") if text == "" { return [(line: "", width: 0)] } var wrapIndex: String.Index? = nil var latestSpace: String.Index? = nil var width = 0 for i in text.indices { let character = text[i] guard let descriptor = Self.descriptor(for: character, from: font) else { continue } assert( descriptor.renderedWidth < maximumWidth, "maximumWidth must be greater than every individual character in the string" ) // Compute the width with the current character included var nextWidth = width + descriptor.renderedWidth if i != text.startIndex { nextWidth += 1 // character spacing } // TODO: wrap on other characters such as '-' as well if character == " " { latestSpace = i } // Break before the current character if it'd bring the text over the maximum width. // If it's the first character, never wrap because otherwise we enter an infinite loop. if nextWidth > maximumWidth && i != text.startIndex { if let spaceIndex = latestSpace { wrapIndex = spaceIndex } else { wrapIndex = i } break } else { width = nextWidth } } var lines: [(line: String, width: Int)] = [] if let wrapIndex = wrapIndex { lines = [ (line: String(text[text.startIndex.. CharacterDescriptor? { if let descriptor = font.descriptor(for: character) { return descriptor } else if let descriptor = font.descriptor(for: "�") { return descriptor } else { log.warning("Failed to replace invalid character '\(character)' with placeholder '�'.") return nil } } } ================================================ FILE: Sources/Core/Sources/GUI/GUISprite.swift ================================================ /// A sprite in the GUI texture palette. public enum GUISprite { case heartOutline case fullHeart case halfHeart case foodOutline case fullFood case halfFood case armorOutline case fullArmor case halfArmor case crossHair case hotbar case selectedHotbarSlot case xpBarBackground case xpBarForeground case inventory case craftingTable case furnace case blastFurnace case smoker case anvil case dispenser case beacon /// If positioned directly above ``GUISprite/genericInventory`` it forms /// the background for a single chest window. The way the texture is made forces /// these to be separate sprites. case genericInventory // Inventory for most interfaces, its a part of the sprite case generic9x1 case generic9x2 case generic9x3 case generic9x4 case generic9x5 case generic9x6 case pinkBossBarBackground case pinkBossBarForeground case blueBossBarBackground case blueBossBarForeground case redBossBarBackground case redBossBarForeground case greenBossBarBackground case greenBossBarForeground case yellowBossBarBackground case yellowBossBarForeground case purpleBossBarBackground case purpleBossBarForeground case whiteBossBarBackground case whiteBossBarForeground case bossBarNoNotchOverlay case bossBarSixNotchOverlay case bossBarTenNotchOverlay case bossBarTwelveNotchOverlay case bossBarTwentyNotchOverlay /// The sprite for a connection strength in the range `0...5`. case playerConnectionStrength(PlayerInfo.ConnectionStrength) /// The descriptor for the sprite. public var descriptor: GUISpriteDescriptor { switch self { case .heartOutline: return .icon(0, 0) case .fullHeart: return .icon(4, 0) case .halfHeart: return .icon(5, 0) case .foodOutline: return .icon(0, 3) case .fullFood: return .icon(4, 3) case .halfFood: return .icon(5, 3) case .armorOutline: return .icon(0, 1) case .fullArmor: return .icon(2, 1) case .halfArmor: return .icon(1, 1) case .crossHair: return GUISpriteDescriptor(slice: .icons, position: [3, 3], size: [9, 9]) case .hotbar: return GUISpriteDescriptor(slice: .widgets, position: [0, 0], size: [182, 22]) case .selectedHotbarSlot: return GUISpriteDescriptor(slice: .widgets, position: [0, 22], size: [24, 24]) case .xpBarBackground: return GUISpriteDescriptor(slice: .icons, position: [0, 64], size: [182, 5]) case .xpBarForeground: return GUISpriteDescriptor(slice: .icons, position: [0, 69], size: [182, 5]) case .inventory: return GUISpriteDescriptor(slice: .inventory, position: [0, 0], size: [176, 166]) case .craftingTable: return GUISpriteDescriptor(slice: .craftingTable, position: [0, 0], size: [176, 166]) case .furnace: return GUISpriteDescriptor(slice: .furnace, position: [0, 0], size: [176, 166]) case .blastFurnace: return GUISpriteDescriptor(slice: .blastFurnace, position: [0, 0], size: [176, 166]) case .smoker: return GUISpriteDescriptor(slice: .smoker, position: [0, 0], size: [176, 166]) case .anvil: return GUISpriteDescriptor(slice: .anvil, position: [0, 0], size: [176, 166]) case .dispenser: return GUISpriteDescriptor(slice: .dispenser, position: [0, 0], size: [176, 166]) case .beacon: return GUISpriteDescriptor(slice: .beacon, position: [0,0], size: [229, 218]) case .genericInventory: return GUISpriteDescriptor(slice: .genericContainer, position: [0, 125], size: [176, 97]) case .generic9x1: return GUISpriteDescriptor(slice: .genericContainer, position: [0, 0], size: [176, 35]) case .generic9x2: return GUISpriteDescriptor(slice: .genericContainer, position: [0, 0], size: [176, 53]) case .generic9x3: return GUISpriteDescriptor(slice: .genericContainer, position: [0, 0], size: [176, 71]) case .generic9x4: return GUISpriteDescriptor(slice: .genericContainer, position: [0, 0], size: [176, 89]) case .generic9x5: return GUISpriteDescriptor(slice: .genericContainer, position: [0, 0], size: [176, 107]) case .generic9x6: return GUISpriteDescriptor(slice: .genericContainer, position: [0, 0], size: [176, 222]) case .pinkBossBarBackground: return GUISpriteDescriptor(slice: .bars, position: [0, 0], size: [182, 5]) case .pinkBossBarForeground: return GUISpriteDescriptor(slice: .bars, position: [0, 5], size: [182, 5]) case .blueBossBarBackground: return GUISpriteDescriptor(slice: .bars, position: [0, 10], size: [182, 5]) case .blueBossBarForeground: return GUISpriteDescriptor(slice: .bars, position: [0, 15], size: [182, 5]) case .redBossBarBackground: return GUISpriteDescriptor(slice: .bars, position: [0, 20], size: [182, 5]) case .redBossBarForeground: return GUISpriteDescriptor(slice: .bars, position: [0, 25], size: [182, 5]) case .greenBossBarBackground: return GUISpriteDescriptor(slice: .bars, position: [0, 30], size: [182, 5]) case .greenBossBarForeground: return GUISpriteDescriptor(slice: .bars, position: [0, 35], size: [182, 5]) case .yellowBossBarBackground: return GUISpriteDescriptor(slice: .bars, position: [0, 40], size: [182, 5]) case .yellowBossBarForeground: return GUISpriteDescriptor(slice: .bars, position: [0, 45], size: [182, 5]) case .purpleBossBarBackground: return GUISpriteDescriptor(slice: .bars, position: [0, 50], size: [182, 5]) case .purpleBossBarForeground: return GUISpriteDescriptor(slice: .bars, position: [0, 55], size: [182, 5]) case .whiteBossBarBackground: return GUISpriteDescriptor(slice: .bars, position: [0, 60], size: [182, 5]) case .whiteBossBarForeground: return GUISpriteDescriptor(slice: .bars, position: [0, 65], size: [182, 5]) case .bossBarNoNotchOverlay: return GUISpriteDescriptor(slice: .bars, position: [0, 70], size: [182, 5]) case .bossBarSixNotchOverlay: return GUISpriteDescriptor(slice: .bars, position: [0, 80], size: [182, 5]) case .bossBarTenNotchOverlay: return GUISpriteDescriptor(slice: .bars, position: [0, 90], size: [182, 5]) case .bossBarTwelveNotchOverlay: return GUISpriteDescriptor(slice: .bars, position: [0, 100], size: [182, 5]) case .bossBarTwentyNotchOverlay: return GUISpriteDescriptor(slice: .bars, position: [0, 110], size: [182, 5]) case let .playerConnectionStrength(strength): let y = 16 + (5 - strength.rawValue) * 8 return GUISpriteDescriptor(slice: .icons, position: [0, y], size: [10, 7]) } } } ================================================ FILE: Sources/Core/Sources/GUI/GUISpriteDescriptor.swift ================================================ import FirebladeMath /// Describes how to render a specific sprite from a ``GUITexturePalette``. public struct GUISpriteDescriptor { /// The slice containing the sprite. public var slice: GUITextureSlice /// The position of the sprite in the texture. Origin is at the top left. public var position: Vec2i /// The size of the sprite. public var size: Vec2i /// Creates the descriptor for the specified icon. Icons start 16 pixels from the left of the /// texture and are arranged as a grid of 9x9 icons. /// - Parameters: /// - xIndex: The horizontal index of the sprite. /// - yIndex: The vertical index of the sprite. /// - Returns: A sprite descriptor for the icon. public static func icon(_ xIndex: Int, _ yIndex: Int) -> GUISpriteDescriptor { return GUISpriteDescriptor( slice: .icons, position: [xIndex * 9 + 16, yIndex * 9], size: [9, 9] ) } } ================================================ FILE: Sources/Core/Sources/GUI/HorizontalConstraint.swift ================================================ public enum HorizontalConstraint { case left(Int) case center(HorizontalOffset?) case right(Int) public static let center = Self.center(nil) } ================================================ FILE: Sources/Core/Sources/GUI/HorizontalOffset.swift ================================================ public enum HorizontalOffset { case left(Int) case right(Int) /// The offset value, negative for up, positive for down. public var value: Int { switch self { case .left(let offset): return -offset case .right(let offset): return offset } } } ================================================ FILE: Sources/Core/Sources/GUI/InGameGUI.swift ================================================ import Collections import CoreFoundation import SwiftCPUDetect /// Never acquires nexus locks. public class InGameGUI { // TODO: Figure out why anything greater than 252 breaks the protocol. Anything less than 256 should work afaict public static let maximumMessageLength = 252 /// The number of seconds until messages should be hidden from the regular GUI. static let messageHideDelay: Double = 10 /// The maximum number of messages displayed in the regular GUI. static let maximumDisplayedMessages = 10 /// The width of the chat history. static let chatHistoryWidth = 330 #if os(macOS) /// The system's CPU display name. static let cpuName = HWInfo.CPU.name() /// The system's CPU architecture. static let cpuArch = CpuArchitecture.current()?.rawValue /// The system's total memory. static let totalMem = (HWInfo.ramAmount() ?? 0) / (1024 * 1024 * 1024) /// A string containing information about the system's default GPU. static let gpuInfo = GPUDetection.mainMetalGPU()?.infoString() #endif static let xpLevelTextColor = Vec4f(126, 252, 31, 255) / 255 static let debugScreenRowBackgroundColor = Vec4f(80, 80, 80, 144) / 255 public init() {} /// Gets the GUI's content. Doesn't acquire any locks. public func content( game: Game, connection: ServerConnection?, state: GUIStateStorage ) -> GUIElement { let (gamemode, inventory, perspective) = game.accessPlayer(acquireLock: false) { player in (player.gamemode.gamemode, player.inventory, player.camera.perspective) } let inputState = game.accessInputState(acquireLock: false, action: identity) if state.showHUD { return GUIElement.stack { if gamemode != .spectator { GUIElement.stack { hotbarArea(game: game, gamemode: gamemode) if perspective == .firstPerson { GUIElement.sprite(.crossHair) .center() } } } GUIElement.forEach(in: state.bossBars, spacing: 3) { bossBar in self.bossBar(bossBar) } .constraints(.top(2), .center) if state.movementAllowed && inputState.keys.contains(.tab) { tabList(game.tabList) .constraints(.top(8), .center) } if state.showDebugScreen { debugScreen(game: game, state: state) } chat(state: state) if state.showInventory { window( window: inventory.window, game: game, connection: connection, state: state ) } else if let window = state.window { self.window( window: window, game: game, connection: connection, state: state ) } } } else { return GUIElement.spacer(width: 0, height: 0) } } public func bossBar(_ bossBar: BossBar) -> GUIElement { let (background, foreground) = bossBar.color.sprites return GUIElement.list(spacing: 1) { GUIElement.message(bossBar.title, wrap: false) .constraints(.top(0), .center) GUIElement.stack { continuousMeter(bossBar.health, background: background, foreground: foreground) // TODO: Render both the background and foreground overlays separately (instead of assuming // that they're both the same like they are in the vanilla resource pack) GUIElement.sprite(bossBar.style.overlay) } } .size(GUISprite.xpBarBackground.descriptor.size.x, nil) } public func tabList(_ tabList: TabList) -> GUIElement { // TODO: Resolve chat component content when building ui instead of when resolving it // (just too tricky to do stuff without knowing the chat component's content) // TODO: Handle teams (changes sorting I think) // TODO: Spectator players should go first, then sort by display name (with no-display-name players // coming first?) then sort by player name let sortedPlayers = tabList.players.values.sorted { left, right in // TODO: Sort by the name that's gonna be displayed (displayName ?? name), // requires the above TODO to be resolved first left.name < right.name } let borderColor = Vec4f(0, 0, 0, 0.8) // TODO: Render borders between rows (harder than it sounds lol, will require more advanced layout // controls in GUIElement). return GUIElement.list(direction: .horizontal, spacing: 0) { GUIElement.forEach(in: sortedPlayers, spacing: 0) { player in // TODO: Add text shadow when that's supported for chat components // TODO: Render spectator mode player names italic GUIElement.list(direction: .horizontal, spacing: 2) { if let displayName = player.displayName { GUIElement.message(displayName) } else { textWithShadow(player.name) } } } .padding(.bottom, -1) .background(Vec4f(0, 0, 0, 0.5)) GUIElement.forEach(in: sortedPlayers, spacing: 1) { player in GUIElement.sprite(.playerConnectionStrength(player.connectionStrength)) .padding([.top, .right], 1) .padding(.left, 2) } .background(Vec4f(0, 0, 0, 0.5)) } .border([.top, .left, .bottom], 1, borderColor) } public func chat(state: GUIStateStorage) -> GUIElement { // TODO: Implement scrollable chat history. // Limit number of messages shown. let index = max( state.chat.messages.startIndex, state.chat.messages.endIndex - Self.maximumDisplayedMessages ) let latestMessages = state.chat.messages[index...SubSequence if state.showChat { visibleMessages = latestMessages } else { let lastVisibleIndex = latestMessages.lastIndex { message in message.timeReceived < threshold }?.advanced(by: 1) ?? latestMessages.startIndex visibleMessages = latestMessages[lastVisibleIndex.. GUIElement { let messageBeforeCursor = String(content.prefix(upTo: cursorIndex)) let messageAfterCursor = String(content.suffix(from: cursorIndex)) return GUIElement.list(direction: .horizontal, spacing: 0) { textWithShadow(messageBeforeCursor) if Int(CFAbsoluteTimeGetCurrent() * 10 / 3) % 2 == 1 { if messageAfterCursor.isEmpty { textWithShadow("_") .positionInParent(messageBeforeCursor.isEmpty ? 0 : 1, 0) } else { GUIElement.spacer(width: 1, height: 11) .background(Vec4f(1, 1, 1, 1)) .positionInParent(0, -1) .float() } } textWithShadow(messageAfterCursor) } .size(nil, Font.defaultCharacterHeight + 1) .expand(.horizontal) .padding([.top, .left, .right], 2) .padding(.bottom, 1) .background(Vec4f(0, 0, 0, 0.5)) } /// Gets the contents of the hotbar (and nearby stats if in a gamemode with health). /// Doesn't acquire a nexus lock. public func hotbarArea(game: Game, gamemode: Gamemode) -> GUIElement { let (health, food, selectedSlot, xpBarProgress, xpLevel, hotbarSlots) = game.accessPlayer(acquireLock: false) { player in ( player.health.health, player.nutrition.food, player.inventory.selectedHotbarSlot, player.experience.experienceBarProgress, player.experience.experienceLevel, player.inventory.hotbar ) } return GUIElement.list(spacing: 0) { if gamemode.hasHealth { stats(health: health, food: food, xpBarProgress: xpBarProgress, xpLevel: xpLevel) } hotbar(slots: hotbarSlots, selectedSlot: selectedSlot) } .size(GUISprite.hotbar.descriptor.size.x + 2, nil) .constraints(.bottom(-1), .center) } public func hotbar(slots: [Slot], selectedSlot: Int) -> GUIElement { GUIElement.stack { GUIElement.sprite(.hotbar) .padding(1) GUIElement.sprite(.selectedHotbarSlot) .positionInParent(selectedSlot * 20, 0) GUIElement.forEach(in: slots, direction: .horizontal, spacing: 4) { slot in inventorySlot(slot) } .positionInParent(4, 4) } } public func window( window: Window, game: Game, connection: ServerConnection?, state: GUIStateStorage ) -> GUIElement { let mousePosition = game.accessInputState(acquireLock: false) { inputState in Vec2i(inputState.mousePosition / state.drawableScalingFactor) } return GUIElement.stack { GUIElement.spacer(width: 0, height: 0) .expand() .background(Vec4f(0, 0, 0, 0.702)) .onClick { window.dropStackFromMouse(&state.mouseItemStack, connection: connection) } .onRightClick { window.dropItemFromMouse(&state.mouseItemStack, connection: connection) } GUIElement.stack { // Has a dummy click handler to prevent clicks within the inventory from propagating to the background window.type.background.onHoverKeyPress { event in return event.key == .leftMouseButton || event.key == .rightMouseButton } GUIElement.stack( elements: window.type.areas.map { area in windowArea( area, window, game: game, connection: connection, state: state ) } ) } .center() if let mouseItemStack = state.mouseItemStack { inventorySlot(Slot(mouseItemStack)) .positionInParent(mousePosition &- Vec2i(8, 8)) } } } public func windowArea( _ area: WindowArea, _ window: Window, game: Game, connection: ServerConnection?, state: GUIStateStorage ) -> GUIElement { GUIElement.forEach(in: 0.. GUIElement { // TODO: Make if blocks layout transparent (their children should be treated as children of the parent block) if let stack = slot.stack { return GUIElement.stack { GUIElement.item(id: stack.itemId) if stack.count != 1 { textWithShadow("\(stack.count)") .constraints(.bottom(-2), .right(-1)) .float() } } .size(16, 16) } else { return GUIElement.spacer(width: 16, height: 16) } } public func textWithShadow( _ text: String, textColor: Vec4f = Vec4f(1, 1, 1, 1), shadowColor: Vec4f = Vec4f(62, 62, 62, 255) / 255 ) -> GUIElement { if !text.isEmpty { return GUIElement.stack { GUIElement.text(text, color: shadowColor) .positionInParent(1, 1) GUIElement.text(text, color: textColor) } } else { return GUIElement.spacer(width: 0, height: 0) } } public enum ReadingDirection { case leftToRight case rightToLeft } public func stats( health: Float, food: Int, xpBarProgress: Float, xpLevel: Int ) -> GUIElement { GUIElement.list(spacing: 0) { GUIElement.stack { discreteMeter( Int(health.rounded()), fullIcon: .fullHeart, halfIcon: .halfHeart, outlineIcon: .heartOutline ) discreteMeter( food, fullIcon: .fullFood, halfIcon: .halfFood, outlineIcon: .foodOutline, direction: .rightToLeft ) .constraints(.top(0), .right(0)) } .size(GUISprite.hotbar.descriptor.size.x, nil) .constraints(.top(0), .center) GUIElement.stack { continuousMeter( xpBarProgress, background: .xpBarBackground, foreground: .xpBarForeground ) .constraints(.top(0), .center) outlinedText("\(xpLevel)", textColor: Self.xpLevelTextColor) .constraints(.top(-7), .center) } .padding(1) .constraints(.top(0), .center) } } /// Gets the contents of the debug screen, doesn't acquire a nexus lock. public func debugScreen(game: Game, state: GUIStateStorage) -> GUIElement { var blockPosition = BlockPosition(x: 0, y: 0, z: 0) var chunkSectionPosition = ChunkSectionPosition(sectionX: 0, sectionY: 0, sectionZ: 0) var position: Vec3d = .zero var pitch: Float = 0 var yaw: Float = 0 var heading: Direction = .north var gamemode: Gamemode = .adventure game.accessPlayer(acquireLock: false) { player in position = player.position.vector blockPosition = player.position.blockUnderneath chunkSectionPosition = player.position.chunkSection pitch = MathUtil.degrees(from: player.rotation.pitch) yaw = MathUtil.degrees(from: player.rotation.yaw) heading = player.rotation.heading gamemode = player.gamemode.gamemode } blockPosition.y += 1 let x = String(format: "%.06f", position.x).prefix(7) let y = String(format: "%.06f", position.y).prefix(7) let z = String(format: "%.06f", position.z).prefix(7) let relativePosition = blockPosition.relativeToChunkSection let relativePositionString = "\(relativePosition.x) \(relativePosition.y) \(relativePosition.z)" let chunkSectionString = "\(chunkSectionPosition.sectionX) \(chunkSectionPosition.sectionY) \(chunkSectionPosition.sectionZ)" let yawString = String(format: "%.01f", yaw) let pitchString = String(format: "%.01f", pitch) let axisHeading = "\(heading.isPositive ? "positive" : "negative") \(heading.axis)" var lightPosition = blockPosition lightPosition.y += 1 let skyLightLevel = game.world.getSkyLightLevel(at: lightPosition) let blockLightLevel = game.world.getBlockLightLevel(at: lightPosition) let biome = game.world.getBiome(at: blockPosition) let targetedEntity = game.targetedEntity() let leftSections: [[String]] = [ [ "Minecraft \(Constants.versionString) (Delta Client)", renderStatisticsString(state.inner.debouncedRenderStatistics()), "Dimension: \(game.world.dimension.identifier)", ], [ "XYZ: \(x) / \(y) / \(z)", // Block under feet "Block: \(blockPosition.x) \(blockPosition.y) \(blockPosition.z)", "Chunk: \(relativePositionString) in \(chunkSectionString)", "Facing: \(heading) (Towards \(axisHeading)) (\(yawString) / \(pitchString))", // Lighting (at foot level) "Light: \(skyLightLevel) sky, \(blockLightLevel) block", "Biome: \(biome?.identifier.description ?? "not loaded")", "Gamemode: \(gamemode.string)", ], // Custom Delta Client info [ targetedEntity.map { "Targeted entity: \($0.target)" } ].compactMap(identity), ] #if os(macOS) let rightSections: [[String]] = [ [ "CPU: \(Self.cpuName ?? "unknown") (\(Self.cpuArch ?? "n/a"))", "Total mem: \(Self.totalMem)GB", "GPU: \(Self.gpuInfo ?? "unknown")", ] ] #else let rightSections: [[String]] = [] #endif return GUIElement.stack { debugScreenList(leftSections, side: .left) debugScreenList(rightSections, side: .right) } } public enum Alignment { case left case right } public func debugScreenList(_ sections: [[String]], side: Alignment) -> GUIElement { GUIElement.forEach(in: sections, spacing: 6) { section in GUIElement.forEach(in: section, spacing: 0) { line in GUIElement.text(line) .padding([.left, .top], 1) .padding([.right], 2) .background(Self.debugScreenRowBackgroundColor) .constraints(.top(0), side == .left ? .left(0) : .right(0)) } .padding(1) } } /// Converts the given render statistics into the format required by the debug screen; /// /// ``` /// XX fps (XX.XX theoretical) (XX.XXms cpu, XX.XXms gpu) /// ``` /// /// Theoretical FPS and GPU time are only included if being collected. public func renderStatisticsString(_ renderStatistics: RenderStatistics) -> String { let theoreticalFPSString = renderStatistics.averageTheoreticalFPS.map { theoreticalFPS in "(\(theoreticalFPS) theoretical)" } let gpuTimeString = renderStatistics.averageGPUTime.map { gpuTime in String(format: "%.02fms gpu", gpuTime * 1000) } let cpuTimeString = String(format: "%.02fms cpu", renderStatistics.averageCPUTime * 1000) let fpsString = String(format: "%.00f fps", renderStatistics.averageFPS) let timingsString = [cpuTimeString, gpuTimeString].compactMap(identity).joined(separator: ", ") return [fpsString, theoreticalFPSString, "(\(timingsString))"] .compactMap(identity) .joined(separator: " ") } public func outlinedText( _ text: String, textColor: Vec4f, outlineColor: Vec4f = Vec4f(0, 0, 0, 1) ) -> GUIElement { let outlineText = GUIElement.text(text, color: outlineColor) return GUIElement.stack { outlineText.constraints(.top(0), .left(1)) outlineText.constraints(.top(1), .left(0)) outlineText.constraints(.top(1), .left(2)) outlineText.constraints(.top(2), .left(1)) GUIElement.text(text, color: textColor) .constraints(.top(1), .left(1)) } } public func discreteMeter( _ value: Int, fullIcon: GUISprite, halfIcon: GUISprite, outlineIcon: GUISprite, direction: ReadingDirection = .leftToRight ) -> GUIElement { let fullIconCount = value / 2 let hasHalfIcon = value % 2 == 0 var range = Array(0..<10) if direction == .rightToLeft { range = range.reversed() } return GUIElement.forEach(in: range, direction: .horizontal, spacing: -1) { i in GUIElement.stack { GUIElement.sprite(outlineIcon) if i < fullIconCount { GUIElement.sprite(fullIcon) } else if hasHalfIcon && i == fullIconCount { GUIElement.sprite(halfIcon) } } } } public func continuousMeter( _ value: Float, background: GUISprite, foreground: GUISprite ) -> GUIElement { var croppedForeground = foreground.descriptor croppedForeground.size.x = Int(Float(croppedForeground.size.x) * value) return GUIElement.stack { GUIElement.sprite(background) GUIElement.customSprite(croppedForeground) } } } ================================================ FILE: Sources/Core/Sources/GUI/RenderStatistics.swift ================================================ /// Statistics related to a renderer's performance. public struct RenderStatistics { // MARK: Public properties /// The average CPU time including waiting for vsync. Measured as the time between starting two consecutive frames. public var averageFrameTime: Double { frameTimes.average() } /// The average CPU time excluding waiting for vsync. public var averageCPUTime: Double { cpuTimes.average() } /// The average GPU time. public var averageGPUTime: Double? { gpuCountersEnabled ? gpuTimes.average() : nil } /// The average FPS. public var averageFPS: Double { return averageFrameTime == 0 ? 0 : 1 / averageFrameTime } /// The theoretical FPS if vsync was disabled. public var averageTheoreticalFPS: Double? { if let averageGPUTime = averageGPUTime { let bottleneck = max(averageCPUTime, averageGPUTime) return bottleneck == 0 ? 0 : 1 / bottleneck } else { return nil } } public var gpuCountersEnabled: Bool // MARK: Private properties /// The most recent cpu times including waiting for vsync. Measured in seconds. private var frameTimes: [Double] = [] /// The most recent cpu times excluding waiting for vsync. Measured in seconds. private var cpuTimes: [Double] = [] /// The most recent gpu times. Measured in seconds. private var gpuTimes: [Double] = [] /// The number of samples for the rolling average. public let sampleSize = 20 // MARK: Init /// Creates a new group of render statistics. public init(gpuCountersEnabled: Bool = false) { self.gpuCountersEnabled = gpuCountersEnabled } // MARK: Public methods /// Updates the statistics with the measurements taken for a frame. /// - Parameters: /// - frameTime: The CPU time taken for the frame measured in seconds including waiting for vsync. /// - cpuTime: The CPU time taken for the frame measured in seconds excluding waiting for vsync. /// - gpuTime: The GPU time taken for the frame measured in seconds. public mutating func addMeasurement(frameTime: Double, cpuTime: Double, gpuTime: Double?) { frameTimes.append(frameTime) cpuTimes.append(cpuTime) if let gpuTime = gpuTime { gpuTimes.append(gpuTime) } if frameTimes.count > sampleSize { frameTimes.removeFirst() cpuTimes.removeFirst() if gpuTime != nil { gpuTimes.removeFirst() } } } } ================================================ FILE: Sources/Core/Sources/GUI/VerticalConstraint.swift ================================================ public enum VerticalConstraint { case top(Int) case center(VerticalOffset?) case bottom(Int) public static let center = Self.center(nil) } ================================================ FILE: Sources/Core/Sources/GUI/VerticalOffset.swift ================================================ public enum VerticalOffset { case up(Int) case down(Int) /// The offset value, negative for up, positive for down. public var value: Int { switch self { case .up(let offset): return -offset case .down(let offset): return offset } } } ================================================ FILE: Sources/Core/Sources/GUI/Window.swift ================================================ /// The slots behind a GUI window. Only a `class` because of the way it gets consumed by /// ``InGameGUI``, it gets too unergonomic short of wrapping it in a ``Box`` (which /// gets a little cumbersome sometimes, purely because we have to give inventory /// special treatment while also wanting to work generically over mutable references to /// windows). public class Window { public var id: Int public var type: WindowType public var slots: [Slot] /// The action id to use for the next action performed on the inventory (used when sending /// ``ClickWindowPacket``). private var nextActionId = 0 public init(id: Int, type: WindowType, slots: [Slot]? = nil) { if let count = slots?.count { precondition(count == type.slotCount) } self.id = id self.type = type self.slots = slots ?? Array(repeating: Slot(), count: type.slotCount) self.nextActionId = 0 } /// Returns a unique window action id (counts up from 0 like vanilla does). private func generateActionId() -> Int16 { let id = nextActionId nextActionId += 1 return Int16(id) } /// Gets the slots associated with a particular area of the window. /// - Returns: The rows of the area, e.g. ``PlayerInventory/hotbarArea`` results in a single row, and /// ``PlayerInventory/armorArea`` results in 4 rows containing 1 element each. public func slots(for area: WindowArea) -> [[Slot]] { var rows: [[Slot]] = [] for y in 0.. (area: WindowArea, position: Vec2i)? { for area in type.areas { guard let position = area.position(ofWindowSlot: slotIndex) else { continue } return (area, position) } return nil } public func leftClick( _ slotIndex: Int, mouseStack: inout ItemStack?, connection: ServerConnection? ) { guard let (area, slotPosition) = area(containing: slotIndex) else { log.warning( "No area of window of type '\(type.identifier)' contains the slot with index '\(slotIndex)'" ) return } let clickedItem = slots[slotIndex] if var slotStack = slots[slotIndex].stack, var mouseStackCopy = mouseStack, slotStack.itemId == mouseStackCopy.itemId { guard let item = RegistryStore.shared.itemRegistry.item(withId: slotStack.itemId) else { log.warning("Failed to get maximum stack size for item with id '\(slotStack.itemId)'") return } // If clicking on a recipe result, take result if possible. if area.kind == .recipeResult { // Only take if we can take the whole result if slotStack.count <= item.maximumStackSize - mouseStackCopy.count { slots[slotIndex].stack = nil mouseStackCopy.count += slotStack.count mouseStack = mouseStackCopy } } else { let total = slotStack.count + mouseStackCopy.count slotStack.count = min(total, item.maximumStackSize) slots[slotIndex].stack = slotStack if slotStack.count == total { mouseStack = nil } else { mouseStackCopy.count = total - slotStack.count mouseStack = mouseStackCopy } } } else if area.kind != .recipeResult { if area.kind == .armor, let mouseStackCopy = mouseStack { guard let item = RegistryStore.shared.itemRegistry.item(withId: mouseStackCopy.itemId) else { log.warning("Failed to get armor properties for item with id '\(mouseStackCopy.itemId)'") return } // TODO: Allow heads and carved pumpkings to be warn (should be easy, just need an exhaustive // list). // Ensure that armor of the correct kind (boots etc) can be put in an armor slot let isValid = item.properties?.armorProperties?.equipmentSlot.index == slotPosition.y if isValid { swap(&slots[slotIndex].stack, &mouseStack) } } else { swap(&slots[slotIndex].stack, &mouseStack) } } do { try connection?.sendPacket( ClickWindowPacket( windowId: UInt8(id), actionId: generateActionId(), action: .leftClick(slot: Int16(slotIndex)), clickedItem: clickedItem ) ) } catch { log.warning("Failed to send click window packet for inventory left click: \(error)") } } public func rightClick( _ slotIndex: Int, mouseStack: inout ItemStack?, connection: ServerConnection? ) { let clickedItem = slots[slotIndex] if var stack = slots[slotIndex].stack, mouseStack == nil { let total = stack.count var takenStack = stack stack.count = total / 2 takenStack.count = total - stack.count mouseStack = takenStack if stack.count == 0 { slots[slotIndex].stack = nil } else { slots[slotIndex].stack = stack } } else if var stack = mouseStack, slots[slotIndex].stack == nil { stack.count -= 1 slots[slotIndex].stack = ItemStack(itemId: stack.itemId, itemCount: 1) if stack.count == 0 { mouseStack = nil } else { mouseStack = stack } } else if let slotStack = slots[slotIndex].stack, slotStack.itemId == mouseStack?.itemId { slots[slotIndex].stack?.count += 1 mouseStack?.count -= 1 if mouseStack?.count == 0 { mouseStack = nil } } else { swap(&slots[slotIndex].stack, &mouseStack) } do { try connection?.sendPacket( ClickWindowPacket( windowId: UInt8(id), actionId: generateActionId(), action: .rightClick(slot: Int16(slotIndex)), clickedItem: clickedItem )) } catch { log.warning("Failed to send click window packet for inventory right click: \(error)") } } /// - Returns: `true` if the event was handled, otherwise `false` (indicating that the next relevant GUI /// element should given the event, and so on). public func pressKey( over slotIndex: Int, event: KeyPressEvent, mouseStack: inout ItemStack?, inputState: InputState, connection: ServerConnection? ) -> Bool { guard let input = event.input else { return false } let slotInputs: [Input] = [ .slot1, .slot2, .slot3, .slot4, .slot5, .slot6, .slot7, .slot8, .slot9, ] if input == .dropItem { let dropWholeStack = inputState.keys.contains(where: \.isControl) if dropWholeStack { dropStackFromSlot(slotIndex, mouseItemStack: mouseStack, connection: connection) } else { dropItemFromSlot(slotIndex, mouseItemStack: mouseStack, connection: connection) } } else if let hotBarSlot = slotInputs.firstIndex(of: input) { guard mouseStack == nil else { return true } let clickedItem = slots[slotIndex] let hotBarSlotslotIndex = PlayerInventory.hotbarArea.startIndex + hotBarSlot if hotBarSlotslotIndex != slotIndex { slots.swapAt(slotIndex, hotBarSlotslotIndex) } do { try connection?.sendPacket( ClickWindowPacket( windowId: UInt8(id), actionId: generateActionId(), action: .numberKey(slot: Int16(slotIndex), number: Int8(hotBarSlot)), clickedItem: clickedItem )) } catch { log.warning("Failed to send click window packet for inventory right click: \(error)") } } else { return false } return true } public func close(mouseStack: inout ItemStack?, eventBus: EventBus, connection: ServerConnection?) throws { mouseStack = nil eventBus.dispatch(CaptureCursorEvent()) try connection?.sendPacket(CloseWindowServerboundPacket(windowId: UInt8(id))) } public func dropItemFromSlot( _ slotIndex: Int, mouseItemStack: ItemStack?, connection: ServerConnection? ) { dropFromSlot( slotIndex, wholeStack: false, mouseItemStack: mouseItemStack, connection: connection) } public func dropStackFromSlot( _ slotIndex: Int, mouseItemStack: ItemStack?, connection: ServerConnection? ) { dropFromSlot( slotIndex, wholeStack: true, mouseItemStack: mouseItemStack, connection: connection) } public func dropItemFromMouse(_ mouseStack: inout ItemStack?, connection: ServerConnection?) { dropFromMouse(wholeStack: false, mouseItemStack: &mouseStack, connection: connection) } public func dropStackFromMouse(_ mouseStack: inout ItemStack?, connection: ServerConnection?) { dropFromMouse(wholeStack: true, mouseItemStack: &mouseStack, connection: connection) } public func dropFromMouse( wholeStack: Bool, mouseItemStack mouseStack: inout ItemStack?, connection: ServerConnection? ) { let slot = Slot(mouseStack) if wholeStack { mouseStack = nil } else if var stack = mouseStack { stack.count -= 1 if stack.count == 0 { mouseStack = nil } else { mouseStack = stack } } do { try connection?.sendPacket( ClickWindowPacket( windowId: UInt8(id), actionId: generateActionId(), action: wholeStack ? .leftClick(slot: nil) : .rightClick(slot: nil), clickedItem: slot )) } catch { log.warning("Failed to send click window packet for item drop: \(error)") } } private func dropFromSlot( _ slotIndex: Int, wholeStack: Bool, mouseItemStack: ItemStack?, connection: ServerConnection? ) { if mouseItemStack == nil { if wholeStack { slots[slotIndex].stack = nil } else if var stack = slots[slotIndex].stack { stack.count -= 1 if stack.count == 0 { slots[slotIndex].stack = nil } else { slots[slotIndex].stack = stack } } } do { try connection?.sendPacket( ClickWindowPacket( windowId: UInt8(id), actionId: generateActionId(), action: wholeStack ? .dropStack(slot: Int16(slotIndex)) : .dropOne(slot: Int16(slotIndex)), clickedItem: Slot(ItemStack(itemId: -1, itemCount: 1)) )) } catch { log.warning("Failed to send click window packet for item drop: \(error)") } } } ================================================ FILE: Sources/Core/Sources/GUI/WindowArea.swift ================================================ /// An area of a GUI window; a grid of slots. Only handles areas where the rows /// are stored one after another in the window's slot array. public struct WindowArea { /// Index of the first slot in the area. public var startIndex: Int /// Number of slots wide. public var width: Int /// Number of slots high. public var height: Int /// The position of the area within its window. public var position: Vec2i /// The kind of window area (determines its behaviour). public var kind: Kind? public init( startIndex: Int, width: Int, height: Int, position: Vec2i, kind: WindowArea.Kind? = nil ) { self.startIndex = startIndex self.width = width self.height = height self.position = position self.kind = kind } /// Gets the position of a slot (given as an index in the window's slots array) /// if it lies within this area. public func position(ofWindowSlot slotIndex: Int) -> Vec2i? { let endIndex = startIndex + width * height if slotIndex >= startIndex && slotIndex < endIndex { let position = Vec2i( (slotIndex - startIndex) % width, (slotIndex - startIndex) / width ) return position } return nil } public enum Kind { /// A 9x3 area synced with the player's inventory. case inventorySynced /// A 9x1 area synced with the player's hotbar. case hotbarSynced /// A full 3x3 crafting recipe input area. case fullCraftingRecipeInput /// A small 2x2 crafting recipe input area. case smallCraftingRecipeInput /// A 1x1 heat recipe (e.g. furnace recipe) input area. case heatRecipeInput /// A 1x1 recipe result output area. case recipeResult /// A 1x1 heat recipe fuel input area (e.g. furnace fuel slot). case heatRecipeFuel /// The 1x1 anvil input slot on the left. case firstAnvilInput /// The 1x1 anvil input slot on the right. case secondAnvilInput /// The 1x4 armor area in the player inventory. case armor } } ================================================ FILE: Sources/Core/Sources/GUI/WindowType.swift ================================================ /// A type of GUI window (e.g. inventory, crafting table, chest, etc). Defines the layout /// and which slots go where. public struct WindowType { public var id: Id public var identifier: Identifier public var background: GUIElement public var slotCount: Int public var areas: [WindowArea] public enum Id: Hashable, Equatable { case inventory case vanilla(Int) } /// The window types understood by vanilla. public static let types = [Id: Self]( values: [ inventory, craftingTable, anvil, furnace, blastFurnace, smoker, beacon, generic9x1, generic9x2, generic9x3, generic9x4, generic9x5, generic9x6, generic3x3, ], keyedBy: \.id ) /// The player's inventory. public static let inventory = WindowType( id: .inventory, identifier: Identifier(namespace: "minecraft", name: "inventory"), background: .sprite(.inventory), slotCount: 46, areas: [ PlayerInventory.mainArea, PlayerInventory.hotbarArea, PlayerInventory.craftingInputArea, PlayerInventory.craftingResultArea, PlayerInventory.armorArea, PlayerInventory.offHandArea, ] ) /// A 3x3 crafting table. public static let craftingTable = WindowType( id: .vanilla(11), identifier: Identifier(namespace: "minecraft", name: "crafting"), background: .sprite(.craftingTable), slotCount: 46, areas: [ WindowArea( startIndex: 0, width: 1, height: 1, position: Vec2i(124, 35), kind: .recipeResult ), WindowArea( startIndex: 1, width: 3, height: 3, position: Vec2i(30, 17), kind: .fullCraftingRecipeInput ), WindowArea( startIndex: 10, width: 9, height: 3, position: Vec2i(8, 84), kind: .inventorySynced ), WindowArea( startIndex: 37, width: 9, height: 1, position: Vec2i(8, 142), kind: .hotbarSynced ), ] ) /// An anvil. public static let anvil = WindowType( id: .vanilla(7), identifier: Identifier(namespace: "minecraft", name: "crafting"), background: .sprite(.anvil), slotCount: 39, areas: [ WindowArea( startIndex: 0, width: 1, height: 1, position: Vec2i(27, 47), kind: .firstAnvilInput ), WindowArea( startIndex: 1, width: 1, height: 1, position: Vec2i(76, 47), kind: .secondAnvilInput ), WindowArea( startIndex: 2, width: 1, height: 1, position: Vec2i(134, 47), kind: .recipeResult ), WindowArea( startIndex: 3, width: 9, height: 3, position: Vec2i(8, 84), kind: .inventorySynced ), WindowArea( startIndex: 30, width: 9, height: 1, position: Vec2i(8, 142), kind: .hotbarSynced ), ] ) /// The areas of a heat recipe window (e.g. furnace, smoker, etc). public static let heatRecipeWindowAreas: [WindowArea] = [ WindowArea( startIndex: 0, width: 1, height: 1, position: Vec2i(56, 17), kind: .heatRecipeInput ), WindowArea( startIndex: 1, width: 1, height: 1, position: Vec2i(56, 53), kind: .heatRecipeFuel ), WindowArea( startIndex: 2, width: 1, height: 1, position: Vec2i(112, 31), kind: .recipeResult ), WindowArea( startIndex: 3, width: 9, height: 3, position: Vec2i(8, 84), kind: .inventorySynced ), WindowArea( startIndex: 30, width: 9, height: 1, position: Vec2i(8, 142), kind: .hotbarSynced ), ] /// A regular furnace. public static let furnace = WindowType( id: .vanilla(13), identifier: Identifier(namespace: "minecraft", name: "furnace"), background: .sprite(.furnace), slotCount: 39, areas: heatRecipeWindowAreas ) /// A blast furnace. public static let blastFurnace = WindowType( id: .vanilla(9), identifier: Identifier(namespace: "minecraft", name: "blast_furnace"), background: .sprite(.blastFurnace), slotCount: 39, areas: heatRecipeWindowAreas ) /// A smoker. public static let smoker = WindowType( id: .vanilla(21), identifier: Identifier(namespace: "minecraft", name: "smoker"), background: .sprite(.smoker), slotCount: 39, areas: heatRecipeWindowAreas ) /// A beacon block interface. public static let beacon = WindowType( id: .vanilla(8), identifier: Identifier(namespace: "minecraft", name: "beacon"), background: .sprite(.beacon), slotCount: 37, areas: [ WindowArea( startIndex: 0, width: 1, height: 1, position: Vec2i(136, 110) ), WindowArea( startIndex: 1, width: 9, height: 3, position: Vec2i(36, 137), kind: .inventorySynced ), WindowArea( startIndex: 28, width: 9, height: 1, position: Vec2i(36, 196), kind: .hotbarSynced ), ] ) // A dispenser or dropper. public static let generic3x3 = WindowType( id: .vanilla(6), identifier: Identifier(namespace: "minecraft", name: "generic_3x3"), background: .sprite(.dispenser), slotCount: 45, areas: [ WindowArea( startIndex: 0, width: 3, height: 3, position: Vec2i(62, 17) ), WindowArea( startIndex: 9, width: 9, height: 3, position: Vec2i(8, 84), kind: .inventorySynced ), WindowArea( startIndex: 36, width: 9, height: 1, position: Vec2i(8, 142), kind: .hotbarSynced ), ] ) /// A 1-row container. public static let generic9x1 = WindowType( id: .vanilla(0), identifier: Identifier(namespace: "minecraft", name: "generic_9x1"), background: GUIElement.list(spacing: 0) { GUIElement.sprite(.generic9x1) GUIElement.sprite(.genericInventory) }, slotCount: 45, areas: [ WindowArea( startIndex: 0, width: 9, height: 1, position: Vec2i(8, 18) ), WindowArea( startIndex: 9, width: 9, height: 3, position: Vec2i(8, 50), kind: .inventorySynced ), WindowArea( startIndex: 36, width: 9, height: 1, position: Vec2i(8, 108), kind: .hotbarSynced ), ] ) /// A 2-row container. public static let generic9x2 = WindowType( id: .vanilla(1), identifier: Identifier(namespace: "minecraft", name: "generic_9x2"), background: GUIElement.list(spacing: 0) { GUIElement.sprite(.generic9x2) GUIElement.sprite(.genericInventory) }, slotCount: 54, areas: [ WindowArea( startIndex: 0, width: 9, height: 2, position: Vec2i(8, 18) ), WindowArea( startIndex: 18, width: 9, height: 3, position: Vec2i(8, 68), kind: .inventorySynced ), WindowArea( startIndex: 45, width: 9, height: 1, position: Vec2i(8, 126), kind: .hotbarSynced ), ] ) /// A 3-row container (e.g. a single chest). public static let generic9x3 = WindowType( id: .vanilla(2), identifier: Identifier(namespace: "minecraft", name: "generic_9x3"), background: GUIElement.list(spacing: 0) { GUIElement.sprite(.generic9x3) GUIElement.sprite(.genericInventory) }, slotCount: 63, areas: [ WindowArea( startIndex: 0, width: 9, height: 3, position: Vec2i(8, 18) ), WindowArea( startIndex: 27, width: 9, height: 3, position: Vec2i(8, 86), kind: .inventorySynced ), WindowArea( startIndex: 54, width: 9, height: 1, position: Vec2i(8, 144), kind: .hotbarSynced ), ] ) /// A 4-row container. public static let generic9x4 = WindowType( id: .vanilla(3), identifier: Identifier(namespace: "minecraft", name: "generic_9x4"), background: GUIElement.list(spacing: 0) { GUIElement.sprite(.generic9x4) GUIElement.sprite(.genericInventory) }, slotCount: 72, areas: [ WindowArea( startIndex: 0, width: 9, height: 4, position: Vec2i(8, 18) ), WindowArea( startIndex: 36, width: 9, height: 3, position: Vec2i(8, 104), kind: .inventorySynced ), WindowArea( startIndex: 63, width: 9, height: 1, position: Vec2i(8, 162), kind: .hotbarSynced ), ] ) /// A 4-row container. public static let generic9x5 = WindowType( id: .vanilla(4), identifier: Identifier(namespace: "minecraft", name: "generic_9x5"), background: GUIElement.list(spacing: 0) { GUIElement.sprite(.generic9x5) GUIElement.sprite(.genericInventory) }, slotCount: 81, areas: [ WindowArea( startIndex: 0, width: 9, height: 5, position: Vec2i(8, 18) ), WindowArea( startIndex: 45, width: 9, height: 3, position: Vec2i(8, 122), kind: .inventorySynced ), WindowArea( startIndex: 72, width: 9, height: 1, position: Vec2i(8, 180), kind: .hotbarSynced ), ] ) /// A 6-row container (e.g. a double chest). public static let generic9x6 = WindowType( id: .vanilla(5), identifier: Identifier(namespace: "minecraft", name: "generic_9x6"), background: GUIElement.list(spacing: 0) { GUIElement.sprite(.generic9x6) }, slotCount: 90, areas: [ WindowArea( startIndex: 0, width: 9, height: 6, position: Vec2i(8, 18) ), WindowArea( startIndex: 54, width: 9, height: 3, position: Vec2i(8, 140), kind: .inventorySynced ), WindowArea( startIndex: 81, width: 9, height: 1, position: Vec2i(8, 198), kind: .hotbarSynced ), ] ) } ================================================ FILE: Sources/Core/Sources/GUIState.swift ================================================ import CoreFoundation public struct GUIState { /// The interval between render statistics updates in the GUI. Used by /// ``GUIState/debouncedRenderStatistics()``. public static let renderStatisticsUpdateInterval = 0.4 /// Whether the HUD (health, hotbar, hunger, etc.) is visible or not. public var showHUD = true /// Whether the debug screen is visible or not. public var showDebugScreen = false /// Whether the inventory is open or not. public var showInventory = false /// The chat history including messages received from other players. public var chat = Chat() /// The current contents of the chat message input. Non-`nil` if and only if chat is open. public var messageInput: String? /// The message that the user was composing before they used the up arrow to replace it with /// a historical message. Allows users to return to their message by hitting the down arrow a /// sufficient number of times. public var stashedMessageInput: String? /// All messages that the player has sent. public var playerMessageHistory: [String] = [] /// The index of the currently selected historical message (changed by using the up /// and down arrow keys while composing a chat message). Indexes into ``playerMessageHistory``. public var currentMessageIndex: Int? /// A small default size would cause more text wrapping and slow down game /// ticks (even if not rendering). Haven't measured, just a hunch. Renderers /// must set this value to their drawable size to ensure that mouse interaction /// functions correctly. public var drawableSize = Vec2i(2000, 2000) /// The scaling factor from true pixels to drawable pixels. Should be set by /// renderers so that mouse coordinates can be correctly converted to drawable /// coordinates by GUI code. public var drawableScalingFactor: Float = 1 /// The cursor position in the message input. 0 is the end of the message, /// and the maximum value is the beginning of the message. public var messageInputCursor: Int = 0 /// Rendering statistics to display to the user. public var renderStatistics = RenderStatistics() /// The render statistics last returned by `debouncedRenderStatistics`. private var debouncedRenderStatisticsStorage = RenderStatistics() /// The last time that the debounced render statistics were updated at. private var lastDebouncedRenderStatisticsUpdate: CFAbsoluteTime = 0 /// The currently active GUI window (e.g. crafting table, chest, etc). Inventory is treated /// differently because it's always 'open' (in the eyes of the server, and in the sense that /// the client always remembers what items are in it). If the inventory is open, this should /// still be `nil`. public var window: Window? /// The item stack currently being moved by the mouse. public var mouseItemStack: ItemStack? /// Boss bars currently visible to the player. public var bossBars: [BossBar] = [] /// The chat input field cursor as an index into ``messageInput``. public var messageInputCursorIndex: String.Index { if let messageInput = messageInput { return messageInput.index(messageInput.endIndex, offsetBy: -messageInputCursor) } else { return "".endIndex } } /// Whether chat is open or not. public var showChat: Bool { return messageInput != nil } /// Whether the player is allowed to move, as opposed to being in a /// menu or having chat open. public var movementAllowed: Bool { return !showChat && !showInventory && window == nil } /// The render statistics but only updated every `Self.renderStatisticsUpdateInterval`. public mutating func debouncedRenderStatistics() -> RenderStatistics { let time = CFAbsoluteTimeGetCurrent() if time > lastDebouncedRenderStatisticsUpdate + Self.renderStatisticsUpdateInterval { debouncedRenderStatisticsStorage = renderStatistics lastDebouncedRenderStatisticsUpdate = time } return debouncedRenderStatisticsStorage } } ================================================ FILE: Sources/Core/Sources/Game.swift ================================================ import FirebladeECS import Foundation /// Stores all of the game data such as entities, chunks and chat messages. public final class Game: @unchecked Sendable { // MARK: Public properties /// The scheduler that runs the game's systems every 20th of a second (by default). public private(set) var tickScheduler: TickScheduler /// The event bus for emitting events. public private(set) var eventBus: EventBus /// Maps Vanilla entity Ids to identifiers of entities in the ``Nexus``. private var entityIdToEntityIdentifier: [Int: EntityIdentifier] = [:] /// The world the player is currently connected to. private(set) public var world: World /// The list of all players in the game. public var tabList = TabList() /// The names of all worlds in this game public var worldNames: [Identifier] = [] /// A structure holding information about all of the dimensions (sent by server). public var dimensions = [Dimension.overworld] /// Registry containing all recipes in this game (sent by server). public var recipeRegistry = RecipeRegistry() /// The render distance of the server. public var maxViewDistance = 0 /// The maximum number of players that can join the server. public var maxPlayers = 0 /// Whether the server sends reduced debug info or not. public var debugInfoReduced = false /// Whether the client should show the respawn screen on death. public var respawnScreenEnabled = true /// The difficulty of the server. public var difficulty = Difficulty.normal /// Whether the server is hardcode or not. public var isHardcore = false /// Whether the server's difficulty is locked for the player or not. public var isDifficultyLocked = true // MARK: Private properties #if DEBUG_LOCKS /// A locked for managing safe access of ``nexus``. public let nexusLock = ReadWriteLock() #else /// A locked for managing safe access of ``nexus``. private let nexusLock = ReadWriteLock() #endif /// The container for the game's entities. Strictly only contains what Minecraft counts as /// entities. Doesn't include block entities. private let nexus = Nexus() /// The player. private var player: Player /// The current input state (keyboard and mouse). private let inputState: InputState /// A lock for managing safe access of ``gui``. private let guiLock = ReadWriteLock() /// The current GUI state (f3 screen, inventory, etc). private let gui: InGameGUI /// Storage for the current GUI state. Protected by ``nexusLock`` since it's stored in the /// nexus. private let _guiState: GUIStateStorage // MARK: Init /// Creates a game with default properties. Creates the player. Starts the tick loop. public init( eventBus: EventBus, configuration: ClientConfiguration, connection: ServerConnection? = nil, font: Font, locale: MinecraftLocale ) { self.eventBus = eventBus world = World(eventBus: eventBus) tickScheduler = TickScheduler(nexus, nexusLock: nexusLock, world) inputState = nexus.single(InputState.self).component gui = InGameGUI() _guiState = nexus.single(GUIStateStorage.self).component player = Player() var player = player player.add(to: self) self.player = player // The order of the systems may seem weird, but it has to be this way so that the physics // behaves identically to vanilla tickScheduler.addSystem(PlayerFrictionSystem()) tickScheduler.addSystem(PlayerClimbSystem()) tickScheduler.addSystem(PlayerGravitySystem()) tickScheduler.addSystem(PlayerSmoothingSystem()) tickScheduler.addSystem(PlayerBlockBreakingSystem(connection, self)) // TODO: Make sure that font gets updated when resource pack gets updated, will likely // require significant refactoring if we wanna do it right (as in not just hacking it // together for the specific case of PlayerInputSystem); proper resource pack propagation // will probably take quite a bit of work. tickScheduler.addSystem( PlayerInputSystem(connection, self, eventBus, configuration, font, locale) ) tickScheduler.addSystem(PlayerFlightSystem()) tickScheduler.addSystem(PlayerAccelerationSystem()) tickScheduler.addSystem(PlayerJumpSystem()) tickScheduler.addSystem(PlayerVelocitySystem()) tickScheduler.addSystem(PlayerCollisionSystem()) tickScheduler.addSystem(PlayerPositionSystem()) tickScheduler.addSystem(PlayerFOVSystem()) tickScheduler.addSystem(EntitySmoothingSystem()) tickScheduler.addSystem(EntityPacketHandlingSystem()) tickScheduler.addSystem(EntityMovementSystem()) if let connection = connection { tickScheduler.addSystem(PlayerPacketSystem(connection)) } // Start tick loop tickScheduler.startTickLoop() } // MARK: Input /// Handles a key press. /// - Parameters: /// - key: The pressed key if any. /// - input: The pressed input if any. /// - characters: The characters typed by the pressed key. public func press(key: Key?, input: Input?, characters: [Character] = []) { // swiftlint:disable:this cyclomatic_complexity nexusLock.acquireWriteLock() defer { nexusLock.unlock() } inputState.press(key: key, input: input, characters: characters) } /// Handles a key release. /// - Parameters: /// - key: The released key if any. /// - input: The released input if any. public func release(key: Key?, input: Input?) { nexusLock.acquireWriteLock() defer { nexusLock.unlock() } inputState.release(key: key, input: input) } /// Releases all inputs. That includes keys. public func releaseAllInputs() { nexusLock.acquireWriteLock() defer { nexusLock.unlock() } inputState.releaseAll() } /// Moves the mouse. /// /// See ``Client/moveMouse(x:y:deltaX:deltaY:)`` for the reasoning behind /// having both absolute and relative parameters (it's currently necessary /// but could be fixed by cleaning up the input handling architecture). /// - Parameters: /// - x: The absolute mouse x (relative to the play area's top left corner). /// - y: The absolute mouse y (relative to the play area's top left corner). /// - deltaX: The change in mouse x. /// - deltaY: The change in mouse y. public func moveMouse(x: Float, y: Float, deltaX: Float, deltaY: Float) { nexusLock.acquireWriteLock() defer { nexusLock.unlock() } inputState.moveMouse(x: x, y: y, deltaX: deltaX, deltaY: deltaY) } /// Moves the left thumbstick. /// - Parameters: /// - x: The x positon. /// - y: The y position. public func moveLeftThumbstick(_ x: Float, _ y: Float) { nexusLock.acquireWriteLock() defer { nexusLock.unlock() } inputState.moveLeftThumbstick(x, y) } /// Moves the right thumbstick. /// - Parameters: /// - x: The x positon. /// - y: The y position. public func moveRightThumbstick(_ x: Float, _ y: Float) { nexusLock.acquireWriteLock() defer { nexusLock.unlock() } inputState.moveRightThumbstick(x, y) } public func accessInputState(acquireLock: Bool = true, action: (InputState) -> R) -> R { if acquireLock { nexusLock.acquireWriteLock() } defer { if acquireLock { nexusLock.unlock() } } return action(inputState) } /// Gets a copy of the current GUI state. /// - Returns: A copy of the current GUI state. public func guiState() -> GUIState { nexusLock.acquireReadLock() defer { nexusLock.unlock() } return _guiState.inner } /// Handles a received chat message. public func receiveChatMessage(acquireLock: Bool = true, _ message: ChatMessage) { if acquireLock { nexusLock.acquireWriteLock() } defer { if acquireLock { nexusLock.unlock() } } _guiState.chat.add(message) } /// Mutates the GUI state with a given action. public func mutateGUIState(acquireLock: Bool = true, action: (inout GUIState) throws -> R) rethrows -> R { if acquireLock { nexusLock.acquireWriteLock() } defer { if acquireLock { nexusLock.unlock() } } return try action(&_guiState.inner) } /// Updates the GUI's render statistics. public func updateRenderStatistics(acquireLock: Bool = true, to statistics: RenderStatistics) { mutateGUIState(acquireLock: false) { state in state.renderStatistics = statistics } } /// Compile the in-game GUI to a renderable. /// - acquireGUILock: If `false`, a GUI lock will not be acquired. Use with caution. /// - acquireNexusLock: If `false`, a GUI lock will not be acquired (otherwise a nexus lock will be /// acquired if guiState isn't supplied). Use with caution. /// - connection: Used to notify the server of window interactions and related operations. /// - font: Font to use when rendering, used to compute text sizing and wrapping. /// - locale: Locale used to resolve chat message content. /// - guiState: Avoids the need for this function to call out to the nexus redundantly if the caller already /// has a reference to the gui state. public func compileGUI( acquireGUILock: Bool = true, acquireNexusLock: Bool = true, withFont font: Font, locale: MinecraftLocale, connection: ServerConnection?, guiState: GUIStateStorage? = nil ) -> GUIElement.GUIRenderable { // Acquire the nexus lock first as that's the one that threads can be sitting inside of with `Game.accessNexus`. // If we get the GUI lock first then the renderer can be waiting for the nexus lock while PlayerInputSystem is // sitting with a nexus lock and waiting for a gui lock. // TODO: Formalize the idea of keeping a consistent 'topological' ordering for locks throughout the project. // I think that would prevent this class of deadlocks. var state: GUIStateStorage if let guiState = guiState { state = guiState } else { if acquireNexusLock { nexusLock.acquireWriteLock() } state = nexus.single(GUIStateStorage.self).component } if acquireGUILock { guiLock.acquireWriteLock() } defer { if acquireGUILock { guiLock.unlock() } } defer { if acquireNexusLock && guiState == nil { nexusLock.unlock() } } return gui.content(game: self, connection: connection, state: state) .resolveConstraints(availableSize: state.drawableSize, font: font, locale: locale) } // MARK: Entity /// A method for creating entities in a thread-safe manor. /// /// The builder can handle up to 20 components. This should be enough in most cases but if not, /// components can be added to the entity directly, this is just more convenient. The builder can /// only work for up to 20 components because of a limitation regarding result builders. /// - Parameters: /// - id: The id to create the entity with. /// - builder: The builder that creates the components for the entity. /// - action: An action to perform on the entity once it's created. public func createEntity( id: Int, @ComponentsBuilder using builder: () -> [Component], action: ((Entity) -> Void)? = nil ) { nexusLock.acquireWriteLock() defer { nexusLock.unlock() } let entity = nexus.createEntity(with: builder()) entityIdToEntityIdentifier[id] = entity.identifier action?(entity) } /// Allows thread safe access to a given entity. /// - Parameters: /// - id: The id of the entity to access. /// - action: The action to perform on the entity if it exists. public func accessEntity( id: Int, acquireLock: Bool = true, action: (Entity) throws -> R ) rethrows -> R? { if acquireLock { nexusLock.acquireWriteLock() } defer { if acquireLock { nexusLock.unlock() } } if let identifier = entityIdToEntityIdentifier[id] { return try action(nexus.entity(from: identifier)) } else { return nil } } /// Allows thread safe access to a given component. /// - Parameters: /// - entityId: The id of the entity with the component. /// - componentType: The type of component to access. /// - acquireLock: If `false`, no lock is acquired. Only use if you know what you're doing. /// - action: The action to perform on the component if the entity exists and contains that component. public func accessComponent( entityId: Int, _ componentType: T.Type, acquireLock: Bool = true, action: (T) throws -> R ) rethrows -> R? { if acquireLock { nexusLock.acquireWriteLock() } defer { if acquireLock { nexusLock.unlock() } } guard let identifier = entityIdToEntityIdentifier[entityId], let component = nexus.entity(from: identifier).get(component: T.self) else { return nil } return try action(component) } /// Removes the entity with the given vanilla id from the game if it exists. /// - Parameter id: The id of the entity to remove. public func removeEntity(acquireLock: Bool = true, id: Int) { if acquireLock { nexusLock.acquireWriteLock() } defer { if acquireLock { nexusLock.unlock() } } if let identifier = entityIdToEntityIdentifier[id] { nexus.destroy(entityId: identifier) } } /// Updates an entity's id if it exists. /// - Parameters: /// - id: The current id of the entity. /// - newId: The new id for the entity. public func updateEntityId(_ id: Int, to newId: Int) { nexusLock.acquireWriteLock() defer { nexusLock.unlock() } if let identifier = entityIdToEntityIdentifier.removeValue(forKey: id) { entityIdToEntityIdentifier[newId] = identifier if let component = nexus.entity(from: identifier).get(component: EntityId.self) { component.id = newId } } } /// Allows thread safe access to the nexus. /// - Parameter action: The action to perform on the nexus. public func accessNexus(action: (Nexus) -> Void) { nexusLock.acquireWriteLock() defer { nexusLock.unlock() } action(nexus) } /// Allows thread safe access to the player. /// - Parameters: /// - acquireLock: If `false`, no lock is acquired. Only use if you know what you're doing. /// - action: The action to perform on the player. public func accessPlayer(acquireLock: Bool = true, action: (Player) throws -> T) rethrows -> T { if acquireLock { nexusLock.acquireWriteLock() } defer { if acquireLock { nexusLock.unlock() } } return try action(player) } /// Queues handling of an entity-related packet to occur during the next game tick. /// - Parameters: /// - packet: The packet to queue. /// - client: The client to handle the packet for. public func handleDuringTick(_ packet: ClientboundEntityPacket, client: Client) { nexusLock.acquireWriteLock() defer { nexusLock.unlock() } let packetStore = nexus.single(ClientboundEntityPacketStore.self).component packetStore.add(packet, client: client) } // MARK: Player /// Gets the position of the block currently targeted by the player. /// - Parameters: /// - acquireLock: If `false`, no locks are acquired. Only use if you know what you're doing. public func targetedBlockIgnoringEntities(acquireLock: Bool = true) -> Targeted? { if acquireLock { nexusLock.acquireReadLock() } let ray = player.ray if acquireLock { nexusLock.unlock() } for position in VoxelRay(along: ray, count: 7) { let block = world.getBlock(at: position, acquireLock: acquireLock) let boundingBox = block.shape.outlineShape.offset(by: position.doubleVector) if let (distance, face) = boundingBox.intersectionDistanceAndFace(with: ray) { guard distance <= Player.buildingReach else { break } let targetedPosition = ray.direction * distance + ray.origin return Targeted( target: position, distance: distance, face: face, targetedPosition: targetedPosition ) } } return nil } public func targetedBlock(acquireLock: Bool = true) -> Targeted? { guard let targetedThing = targetedThing(acquireLock: acquireLock) else { return nil } guard case let .block(position) = targetedThing.target else { return nil } return targetedThing.map(constant(position)) } // TODO: Make a value type for entity ids so that this doesn't return a targeted integer (just feels confusing). /// - Returns: The id of the entity targeted by the player, if any. public func targetedEntityIgnoringBlocks(acquireLock: Bool = true) -> Targeted? { if acquireLock { nexusLock.acquireReadLock() } defer { if acquireLock { nexusLock.unlock() } } let playerPosition = player.position.vector let playerRay = player.ray let family = nexus.family( requiresAll: EntityId.self, EntityPosition.self, EntityHitBox.self, excludesAll: ClientPlayerEntity.self ) var candidate: Targeted? for (id, position, hitbox) in family { // Should be big enough radius not to accidentally exclude big entities such as the Ender Dragon? guard (playerPosition - position.vector).magnitude < 12 else { continue } let aabb = hitbox.aabb(at: position.vector) guard let (distance, face) = aabb.intersectionDistanceAndFace(with: playerRay), distance >= 0 || aabb.contains(Vec3d(playerRay.origin)), distance <= Player.attackReach else { continue } let newCandidate = Targeted( target: id.id, distance: distance, face: face, targetedPosition: playerRay.direction * distance + playerRay.origin ) if let currentCandidate = candidate { if distance < currentCandidate.distance { candidate = newCandidate } } else { candidate = newCandidate } } return candidate } public func targetedEntity(acquireLock: Bool = true) -> Targeted? { guard let targetedThing = targetedThing(acquireLock: acquireLock) else { return nil } guard case let .entity(id) = targetedThing.target else { return nil } return targetedThing.map(constant(id)) } /// - Returns: The closest thing targeted by the player. public func targetedThing(acquireLock: Bool = true) -> Targeted? { let targetedBlock = targetedBlockIgnoringEntities(acquireLock: acquireLock) let targetedEntity = targetedEntityIgnoringBlocks(acquireLock: acquireLock) if let block = targetedBlock, let entity = targetedEntity { if block.distance < entity.distance { return block.map(Thing.block) } else { return entity.map(Thing.entity) } } else if let block = targetedBlock { return block.map(Thing.block) } else if let entity = targetedEntity { return entity.map(Thing.entity) } else { return nil } } /// Gets current gamemode of the player. public func currentGamemode() -> Gamemode? { var gamemode: Gamemode? = nil accessPlayer { player in gamemode = player.gamemode.gamemode } return gamemode } /// Calculates the current fov multiplier from various factors such as movement speed /// and whether the player is flying. Emulates vanilla's behaviour. public func fovMultiplier() -> Float { return accessPlayer { player in return player.fov.smoothMultiplier } } // MARK: Lifecycle /// Sets the game's event bus. This is a method in case the game ever needs to listen to the event /// bus, this way means that the listener can be added again. public func setEventBus(_ eventBus: EventBus) { self.eventBus = eventBus self.world.eventBus = eventBus } /// Changes to a new world. /// - Parameter world: The new world. public func changeWorld(to newWorld: World) { // TODO: Make this threadsafe self.world = newWorld tickScheduler.setWorld(to: newWorld) nexusLock.acquireWriteLock() defer { nexusLock.unlock() } entityIdToEntityIdentifier = entityIdToEntityIdentifier.filter { (id, identifier) in let isClientPlayer = id == player.entityId.id if !isClientPlayer { nexus.destroy(entityId: identifier) } return isClientPlayer } } /// Stops the tick scheduler. public func stopTickScheduler() { tickScheduler.cancel() } } ================================================ FILE: Sources/Core/Sources/Input/Input.swift ================================================ import Foundation /// A player input. On a laptop or desktop, this represents a key press or mouse button press. public enum Input: String, Codable, CaseIterable { case place case destroy case moveForward case moveBackward case strafeLeft case strafeRight case jump case fly case sneak case sprint case toggleHUD case toggleDebugHUD case toggleInventory case changePerspective case performGPUFrameCapture case dropItem case slot1 case slot2 case slot3 case slot4 case slot5 case slot6 case slot7 case slot8 case slot9 case nextSlot case previousSlot case openChat public var isBindable: Bool { return self != .fly } public var humanReadableLabel: String { switch self { case .place: return "Use item/Place block" case .destroy: return "Attack/Destroy" case .moveForward: return "Move forward" case .moveBackward: return "Move backward" case .strafeLeft: return "Strafe left" case .strafeRight: return "Strafe right" case .jump: return "Jump" case .fly: return "Fly" case .sneak: return "Sneak" case .sprint: return "Sprint" case .toggleHUD: return "Toggle HUD" case .toggleDebugHUD: return "Toggle debug HUD" case .toggleInventory: return "Toggle Inventory" case .changePerspective: return "Change Perspective" case .performGPUFrameCapture: return "Perform GPU trace" case .dropItem: return "Drop Selected Item" case .slot1: return "Slot 1" case .slot2: return "Slot 2" case .slot3: return "Slot 3" case .slot4: return "Slot 4" case .slot5: return "Slot 5" case .slot6: return "Slot 6" case .slot7: return "Slot 7" case .slot8: return "Slot 8" case .slot9: return "Slot 9" case .nextSlot: return "Next slot" case .previousSlot: return "Previous slot" case .openChat: return "Open chat" } } } ================================================ FILE: Sources/Core/Sources/Input/Key.swift ================================================ import Foundation public enum Key: CustomStringConvertible, Hashable { case leftShift case rightShift case leftControl case rightControl case leftOption case rightOption case leftCommand case rightCommand case function case a case b case c case d case e case f case g case h case i case j case k case l case m case n case o case p case q case r case s case t case u case v case w case x case y case z case zero case one case two case three case four case five case six case seven case eight case nine case numberPad0 case numberPad1 case numberPad2 case numberPad3 case numberPad4 case numberPad5 case numberPad6 case numberPad7 case numberPad8 case numberPad9 case numberPadDecimal case numberPadPlus case numberPadMinus case numberPadEquals case numberPadAsterisk case numberPadForwardSlash case numberPadClear case numberPadEnter case dash case equals case backSlash case forwardSlash case openSquareBracket case closeSquareBracket case comma case period case backTick case semicolon case singleQuote case tab case insert case enter case space case delete case escape case f1 case f2 case f3 case f4 case f5 case f6 case f7 case f8 case f9 case f10 case f11 case f12 case f13 case f14 case f15 case f16 case f17 case f18 case f19 case f20 case home case end case pageUp case pageDown case forwardDelete case upArrow case downArrow case leftArrow case rightArrow case leftMouseButton case rightMouseButton case scrollUp case scrollDown case otherMouseButton(Int) /// Whether the key is a control key. public var isControl: Bool { self == .leftControl || self == .rightControl } /// Whether the key is a command key. public var isCommand: Bool { self == .leftCommand || self == .rightCommand } /// Whether the key is a shift key. public var isShift: Bool { self == .leftShift || self == .rightShift } /// Whether the key is an option key. public var isOption: Bool { self == .leftOption || self == .rightOption } /// The key's display name. public var description: String { name.display } /// The key's name including both the raw and display representations. public var name: (raw: String, display: String) { switch self { case .leftShift: return ("leftShift", "Left shift") case .rightShift: return ("rightShift", "Right shift") case .leftControl: return ("leftControl", "Left control") case .rightControl: return ("rightControl", "Right control") case .leftOption: return ("leftOption", "Left option") case .rightOption: return ("rightOption", "Right option") case .leftCommand: return ("leftCommand", "Left command") case .rightCommand: return ("rightCommand", "Right command") case .function: return ("function", "Function") case .a: return ("a", "A") case .b: return ("b", "B") case .c: return ("c", "C") case .d: return ("d", "D") case .e: return ("e", "E") case .f: return ("f", "F") case .g: return ("g", "G") case .h: return ("h", "H") case .i: return ("i", "I") case .j: return ("j", "J") case .k: return ("k", "K") case .l: return ("l", "L") case .m: return ("m", "M") case .n: return ("n", "N") case .o: return ("o", "O") case .p: return ("p", "P") case .q: return ("q", "Q") case .r: return ("r", "R") case .s: return ("s", "S") case .t: return ("t", "T") case .u: return ("u", "U") case .v: return ("v", "V") case .w: return ("w", "W") case .x: return ("x", "X") case .y: return ("y", "Y") case .z: return ("z", "Z") case .zero: return ("zero", "0") case .one: return ("one", "1") case .two: return ("two", "2") case .three: return ("three", "3") case .four: return ("four", "4") case .five: return ("five", "5") case .six: return ("six", "6") case .seven: return ("seven", "7") case .eight: return ("eight", "8") case .nine: return ("nine", "9") case .numberPad0: return ("numberPad0", "Numpad 0") case .numberPad1: return ("numberPad1", "Numpad 1") case .numberPad2: return ("numberPad2", "Numpad 2") case .numberPad3: return ("numberPad3", "Numpad 3") case .numberPad4: return ("numberPad4", "Numpad 4") case .numberPad5: return ("numberPad5", "Numpad 5") case .numberPad6: return ("numberPad6", "Numpad 6") case .numberPad7: return ("numberPad7", "Numpad 7") case .numberPad8: return ("numberPad8", "Numpad 8") case .numberPad9: return ("numberPad9", "Numpad 9") case .numberPadDecimal: return ("numberPadDecimal", "Numpad .") case .numberPadPlus: return ("numberPadPlus", "Numpad +") case .numberPadMinus: return ("numberPadMinus", "Numpad -") case .numberPadEquals: return ("numberPadEquals", "Numpad =") case .numberPadAsterisk: return ("numberPadAsterisk", "Numpad *") case .numberPadForwardSlash: return ("numberPadForwardSlash", "Numpad /") case .numberPadClear: return ("numberPadClear", "Numpad clear") case .numberPadEnter: return ("numberPadEnter", "Numpad enter") case .dash: return ("dash", "-") case .equals: return ("equals", "=") case .backSlash: return ("backSlash", "\\") case .forwardSlash: return ("forwardSlash", "/") case .openSquareBracket: return ("openSquareBracket", "[") case .closeSquareBracket: return ("closeSquareBracket", "]") case .comma: return ("comma", ",") case .period: return ("period", ".") case .backTick: return ("backTick", "`") case .semicolon: return ("semicolon", ";") case .singleQuote: return ("singleQuote", "'") case .tab: return ("tab", "Tab") case .insert: return ("insert", "Insert") case .enter: return ("enter", "Enter") case .space: return ("space", "Space") case .delete: return ("delete", "Delete") case .escape: return ("escape", "Escape") case .f1: return ("f1", "F1") case .f2: return ("f2", "F2") case .f3: return ("f3", "F3") case .f4: return ("f4", "F4") case .f5: return ("f5", "F5") case .f6: return ("f6", "F6") case .f7: return ("f7", "F7") case .f8: return ("f8", "F8") case .f9: return ("f9", "F9") case .f10: return ("f10", "F10") case .f11: return ("f11", "F11") case .f12: return ("f12", "F12") case .f13: return ("f13", "F13") case .f14: return ("f14", "F14") case .f15: return ("f15", "F15") case .f16: return ("f16", "F16") case .f17: return ("f17", "F17") case .f18: return ("f18", "F18") case .f19: return ("f19", "F19") case .f20: return ("f20", "F20") case .forwardDelete: return ("forwardDelete", "Forward delete") case .home: return ("home", "Home") case .end: return ("end", "End") case .pageUp: return ("pageUp", "Page up") case .pageDown: return ("pageDown", "Page down") case .upArrow: return ("upArrow", "Up arrow") case .downArrow: return ("downArrow", "Down arrow") case .leftArrow: return ("leftArrow", "Left arrow") case .rightArrow: return ("rightArrow", "Right arrow") case .leftMouseButton: return ("leftMouseButton", "Left click") case .rightMouseButton: return ("rightMouseButton", "Right click") case .scrollUp: return ("scrollUp", "Scroll up") case .scrollDown: return ("scrollDown", "Scroll down") case .otherMouseButton(let number): return ("mouseButton\(number)", "Mouse button \(number)") } } public init?(keyCode: UInt16) { if let key = Self.keyCodeToKey[keyCode] { self = key } else { return nil } } private static let keyCodeToKey: [UInt16: Key] = [ 0x00: .a, 0x01: .s, 0x02: .d, 0x03: .f, 0x04: .h, 0x05: .g, 0x06: .z, 0x07: .x, 0x08: .c, 0x09: .v, 0x0B: .b, 0x0C: .q, 0x0D: .w, 0x0E: .e, 0x0F: .r, 0x10: .y, 0x11: .t, 0x12: .one, 0x13: .two, 0x14: .three, 0x15: .four, 0x16: .six, 0x17: .five, 0x18: .equals, 0x19: .nine, 0x1A: .seven, 0x1B: .dash, 0x1C: .eight, 0x1D: .zero, 0x1E: .closeSquareBracket, 0x1F: .o, 0x20: .u, 0x21: .openSquareBracket, 0x22: .i, 0x23: .p, 0x25: .l, 0x26: .j, 0x27: .singleQuote, 0x28: .k, 0x29: .semicolon, 0x2A: .backSlash, 0x2B: .comma, 0x2C: .forwardSlash, 0x2D: .m, 0x2E: .m, 0x2F: .period, 0x32: .backTick, 0x41: .numberPadDecimal, 0x43: .numberPadAsterisk, 0x45: .numberPadPlus, 0x47: .numberPadClear, 0x4B: .numberPadForwardSlash, 0x4C: .numberPadEnter, 0x4E: .numberPadMinus, 0x51: .numberPadEquals, 0x52: .numberPad0, 0x53: .numberPad1, 0x54: .numberPad2, 0x55: .numberPad3, 0x56: .numberPad4, 0x57: .numberPad5, 0x58: .numberPad6, 0x59: .numberPad7, 0x5B: .numberPad8, 0x5C: .numberPad9, 0x24: .enter, 0x30: .tab, 0x31: .space, 0x33: .delete, 0x35: .escape, 0x40: .f17, 0x4F: .f18, 0x50: .f19, 0x5A: .f20, 0x60: .f5, 0x61: .f6, 0x62: .f7, 0x63: .f3, 0x64: .f8, 0x65: .f9, 0x67: .f11, 0x69: .f13, 0x6A: .f16, 0x6B: .f14, 0x6D: .f10, 0x6F: .f12, 0x71: .f15, 0x72: .insert, 0x73: .home, 0x74: .pageUp, 0x75: .forwardDelete, 0x76: .f4, 0x77: .end, 0x78: .f2, 0x79: .pageDown, 0x7A: .f1, 0x7B: .leftArrow, 0x7C: .rightArrow, 0x7D: .downArrow, 0x7E: .upArrow, ] } extension Key: RawRepresentable { /// The key's name in-code. More suitable for config files. public var rawValue: String { switch self { case let .otherMouseButton(number): return "mouseButton\(number)" default: return name.raw } } public init?(rawValue: String) { if rawValue.hasPrefix("mouseButton") { let number = rawValue.dropFirst("mouseButton".count) guard let number = Int(number) else { return nil } self = .otherMouseButton(number) } else { guard let key = Self.rawValueToKey[rawValue] else { return nil } self = key } } /// Used to convert raw values to keys. Works for all keys except /// ``Key/otherMouseButton`` which contains an associated value. private static let rawValueToKey: [String: Key] = [ "leftShift": .leftShift, "rightShift": .rightShift, "leftControl": .leftControl, "rightControl": .rightControl, "leftOption": .leftOption, "rightOption": .rightOption, "leftCommand": .leftCommand, "rightCommand": .rightCommand, "function": .function, "a": .a, "b": .b, "c": .c, "d": .d, "e": .e, "f": .f, "g": .g, "h": .h, "i": .i, "j": .j, "k": .k, "l": .l, "m": .m, "n": .n, "o": .o, "p": .p, "q": .q, "r": .r, "s": .s, "t": .t, "u": .u, "v": .v, "w": .w, "x": .x, "y": .y, "z": .z, "zero": .zero, "one": .one, "two": .two, "three": .three, "four": .four, "five": .five, "six": .six, "seven": .seven, "eight": .eight, "nine": .nine, "numberPad0": .numberPad0, "numberPad1": .numberPad1, "numberPad2": .numberPad2, "numberPad3": .numberPad3, "numberPad4": .numberPad4, "numberPad5": .numberPad5, "numberPad6": .numberPad6, "numberPad7": .numberPad7, "numberPad8": .numberPad8, "numberPad9": .numberPad9, "numberPadDecimal": .numberPadDecimal, "numberPadPlus": .numberPadPlus, "numberPadMinus": .numberPadMinus, "numberPadEquals": .numberPadEquals, "numberPadAsterisk": .numberPadAsterisk, "numberPadForwardSlash": .numberPadForwardSlash, "numberPadClear": .numberPadClear, "numberPadEnter": .numberPadEnter, "dash": .dash, "equals": .equals, "backSlash": .backSlash, "forwardSlash": .forwardSlash, "openSquareBracket": .openSquareBracket, "closeSquareBracket": .closeSquareBracket, "comma": .comma, "period": .period, "backTick": .backTick, "semicolon": .semicolon, "singleQuote": .singleQuote, "tab": .tab, "insert": .insert, "enter": .enter, "space": .space, "delete": .delete, "escape": .escape, "f1": .f1, "f2": .f2, "f3": .f3, "f4": .f4, "f5": .f5, "f6": .f6, "f7": .f7, "f8": .f8, "f9": .f9, "f10": .f10, "f11": .f11, "f12": .f12, "f13": .f13, "f14": .f14, "f15": .f15, "f16": .f16, "f17": .f17, "f18": .f18, "f19": .f19, "f20": .f20, "forwardDelete": .forwardDelete, "home": .home, "end": .end, "pageUp": .pageUp, "pageDown": .pageDown, "upArrow": .upArrow, "downArrow": .downArrow, "leftArrow": .leftArrow, "rightArrow": .rightArrow, "leftMouseButton": .leftMouseButton, "rightMouseButton": .rightMouseButton, "scrollUp": .scrollUp, "scrollDown": .scrollDown, ] } extension Key: Codable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let rawValue = try container.decode(String.self) guard let key = Key(rawValue: rawValue) else { throw RichError("No such key '\(rawValue)'") } self = key } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } ================================================ FILE: Sources/Core/Sources/Input/Keymap.swift ================================================ import Foundation /// A keymap stores the user's keybindings. public struct Keymap { /// The client's default key bindings. public static var `default` = Keymap(bindings: [ .place: .rightMouseButton, .destroy: .leftMouseButton, .moveForward: .w, .moveBackward: .s, .strafeLeft: .a, .strafeRight: .d, .jump: .space, .sneak: .leftShift, .sprint: .leftControl, .toggleHUD: .f1, .toggleDebugHUD: .f3, .toggleInventory: .e, .changePerspective: .f5, .dropItem: .q, .slot1: .one, .slot2: .two, .slot3: .three, .slot4: .four, .slot5: .five, .slot6: .six, .slot7: .seven, .slot8: .eight, .slot9: .nine, .nextSlot: .scrollUp, .previousSlot: .scrollDown, .openChat: .t ]) /// The user's keybindings. public var bindings: [Input: Key] /// Creates a new keymap. /// - Parameter bindings: Bindings for the new keymap. init(bindings: [Input: Key]) { self.bindings = bindings } /// - Returns: The input action for the given key if bound. public func getInput(for key: Key) -> Input? { for (input, inputKey) in bindings where key == inputKey { return input } return nil } } /// We implement `Codable` ourselves because the default codable works very strangely, /// with keys that aren't strings or integers. /// /// Here's a sample of what the default implementations do (wtf), /// /// ```json /// "bindings" : [ /// { /// "moveForward" : { /// /// } /// }, /// { /// "w" : { /// /// } /// }, /// { /// "previousSlot" : { /// /// } /// }, /// { /// "scrollDown" : { /// /// } /// }, /// ... /// ] /// ``` /// /// Each key value pair is actually just two consecutive objects in an array, with empty /// payloads. Here's the format we implement ourselves, /// /// ```json /// "bindings": { /// "moveForward": "w", /// "previousSlot": "scrollDown" /// } /// ``` extension Keymap: Codable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: Input.self) bindings = [:] for input in container.allKeys { bindings[input] = try container.decode(Key.self, forKey: input) } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: Input.self) for (input, key) in bindings { try container.encode(key, forKey: input) } } } extension Input: CodingKey { public var stringValue: String { rawValue } public var intValue: Int? { nil } public init?(stringValue: String) { self.init(rawValue: stringValue) } public init?(intValue: Int) { return nil } } ================================================ FILE: Sources/Core/Sources/Input/ModifierKey.swift ================================================ import Foundation public enum ModifierKey: Hashable, Codable { case leftShift case rightShift case leftControl case rightControl case leftOption case rightOption case leftCommand case rightCommand case function } ================================================ FILE: Sources/Core/Sources/Logger.swift ================================================ @_exported import DeltaLogger ================================================ FILE: Sources/Core/Sources/Network/Cipher.swift ================================================ import CryptoSwift /// An AES-128-CFB8 stream cipher used for encryption and decryption in the network protocol. public class Cipher { /// The operation that a cipher is made to perform. public enum Operation { case encrypt case decrypt } /// The cipher's mode of operation. public var operation: Operation /// The cipher's internal AES encryptor or decryptor. private var cryptor: Cryptor & Updatable /// Creates a new cipher. /// - Parameters: /// - key: The key. Must be at least 16 bytes. /// - iv: The initial vector. Must be at least 16 bytes. /// - Precondition: Key must be at least 16 bytes and iv must be at least 16 bytes. public init(_ operation: Operation, key: [UInt8], iv: [UInt8]) throws { precondition(key.count >= 16, "Key must be at least 16 bytes, was \(key.count)") precondition(iv.count >= 16, "IV must be at least 16 bytes, was \(iv.count)") self.operation = operation let aes = try AES( key: key, blockMode: CFB(iv: iv, segmentSize: .cfb8), padding: .noPadding ) switch operation { case .encrypt: cryptor = try aes.makeEncryptor() case .decrypt: cryptor = try aes.makeDecryptor() } } public func update(with bytes: [UInt8]) throws -> [UInt8] { let new = try cryptor.update(withBytes: bytes) return new } } ================================================ FILE: Sources/Core/Sources/Network/ConnectionState.swift ================================================ import Foundation extension ServerConnection { public enum State { case idle case connecting case handshaking case status case login case play case disconnected public var packetState: PacketState? { switch self { case .handshaking: return .handshaking case .status: return .status case .login: return .login case .play: return .play default: return nil } } } } ================================================ FILE: Sources/Core/Sources/Network/Endianness.swift ================================================ /// The endianness of some bytes. /// /// See [Wikipedia's entry on endianness](https://en.wikipedia.org/wiki/Endianness) for more information. public enum Endianness { case little case big } ================================================ FILE: Sources/Core/Sources/Network/LANServerEnumerator.swift ================================================ import Foundation import Parsing #if !canImport(Combine) import OpenCombine #endif /// An error that occured during LAN server enumeration. enum LANServerEnumeratorError: LocalizedError { /// Failed to create multicast receiving socket. case failedToCreateMulticastSocket(Error) /// Failed to read from multicast socket. case failedToReadFromSocket(Error) var errorDescription: String? { switch self { case .failedToCreateMulticastSocket(let error): return """ Failed to create multicast receiving socket for LAN server enumerator Reason: \(error.localizedDescription) """ case .failedToReadFromSocket(let error): return """ Failed to read from multicast socket for LAN server enumerator Reason: \(error.localizedDescription) """ } } } /// Used to discover LAN servers (servers on the same network as the client). /// /// LAN servers broadcast themselves through UDP multicast packets on the `224.0.2.60` multicast group /// and port `4445`. They send messages of the form `[MOTD]username - world name[/MOTD][AD]port[/AD]`. /// /// As well as discovering servers, the enumerator also pings them for more information (see ``pingers``). /// /// Make sure to call ``stop()`` before trying to create another enumerator. public class LANServerEnumerator: ObservableObject { // MARK: Static properties /// Used to prevent DoS attacks. 50 LAN servers at a time is definitely enough, in most cases there will be at most 2 or 3. public static let maximumServerCount = 50 // MARK: Public properties /// Pingers for all currently identified LAN servers. @Published public var pingers: [Pinger] = [] /// Whether the enumerator has errored or not. @Published public var hasErrored = false /// All currently identified servers. public var servers: [ServerDescriptor] = [] // MARK: Private properties /// Multicast socket for receiving packets. private var socket: Socket? /// Whether the enumerator is listening already or not. private var isListening = false /// Used to notify about errors. private let eventBus: EventBus /// Dispatch queue used for networking. private let queue = DispatchQueue(label: "LANServerEnumerator") // MARK: Init /// Creates a new LAN server enumerator. /// /// To start enumeration call `start`. /// - Parameter eventBus: Event bus to dispatch errors to. public init(eventBus: EventBus) { self.eventBus = eventBus } deinit { try? socket?.close() } /// Creates a new multicast socket for this instance to use for receiving broadcasts from servers /// on the local network.. public func createSocket() throws { do { let socket = try Socket(.ip4, .udp) try socket.setValue(true, for: BoolSocketOption.localAddressReuse) try socket.bind(to: Socket.Address.ip4("224.0.2.60", 4445)) try socket.setValue( try MembershipRequest( groupAddress: "224.0.2.60", localAddress: "0.0.0.0" ), for: MembershipRequestSocketOption.addMembership ) self.socket = socket } catch { throw LANServerEnumeratorError.failedToCreateMulticastSocket(error) } } /// An async read loop that receives and parses messages from servers on the local network. /// /// It is implemented recursively to prevent the method from creating a reference cycle /// (by dropping self temporarily each iteration). public func asyncSocketReadLoop() { queue.async { [weak self] in guard let self = self, let socket = self.socket else { return } do { let (content, sender) = try socket.recvFrom(atMost: 16384) self.handlePacket(sender: sender, content: content) } catch { ThreadUtil.runInMain { self.hasErrored = true } self.eventBus.dispatch( ErrorEvent( error: LANServerEnumeratorError.failedToReadFromSocket(error), message: "LAN server enumeration failed" ) ) return } self.asyncSocketReadLoop() } } // MARK: Public methods /// Starts listening for LAN servers announcing themselves. public func start() throws { if socket == nil { try createSocket() asyncSocketReadLoop() isListening = true } else { log.warning("Attempted to start LANServerEnumerator twice") } } /// Stops scanning for new LAN servers and closes the multicast socket. Any pings that are in progress will still be completed. public func stop() { if isListening { try? socket?.close() socket = nil } else { log.warning("Attempted to stop LANServerEnumerator while it wasn't started") } } /// Clears all currently discovered servers. public func clear() { servers = [] ThreadUtil.runInMain { pingers = [] } } // MARK: Private methods /// Parses LAN server multicast messages. /// /// They are expected to be of the form: `[MOTD]message of the day[/MOTD][AD]port[/AD]`. /// Apparently sometimes the entire address is included in the `AD` section so that is /// handled too. private func handlePacket(sender: Socket.Address, content: [UInt8]) { // Cap the maximum number of LAN servers that can be discovered guard servers.count < Self.maximumServerCount else { return } // Extract motd and port guard let content = String(bytes: content, encoding: .utf8), case let .ip4(host, _) = sender, let (motd, port) = parseMessage(content) else { log.error("Failed to parse LAN server broadcast message") return } let server = ServerDescriptor(name: motd, host: host, port: port) if servers.contains(server) { return } // Ping the server let pinger = Pinger(server) Task { try? await pinger.ping() } servers.append(server) ThreadUtil.runInMain { pingers.append(pinger) } log.trace("Received LAN server multicast packet: motd=`\(motd)`, address=`\(host):\(port)`") } /// Parses a message of the form `"[MOTD]motd[/MOTD][AD]port[/AD]"`. /// - Parameter message: The message to parse. /// - Returns: The motd and port. private func parseMessage(_ message: String) -> (String, UInt16)? { let portParser = OneOf { // Sometimes the port also includes a host ("host:port") so we must handle that case Parse { Prefix { $0 != ":" } ":" UInt16.parser() }.map { $0.1 } // Otherwise it's just a port UInt16.parser() } let packetParser = Parse { "[MOTD]" Prefix { $0 != "["} "[/MOTD][AD]" portParser "[/AD]" }.map { tuple -> (String, UInt16) in (String(tuple.0), tuple.1) } do { return try packetParser.parse(message) } catch { log.warning("Invalid LAN server broadcast message received: \"\(message)\", error: \(error)") return nil } } } ================================================ FILE: Sources/Core/Sources/Network/Protocol/Buffer.swift ================================================ import Foundation /// A byte buffer. /// /// All methods read unsigned values unless otherwise specified in their name. public struct Buffer { /// The buffer's underlying byte array. public private(set) var bytes: [UInt8] /// The current index of the read/write head. public var index = 0 /// The buffer's current length. public var length: Int { return self.bytes.count } /// The number of bytes remaining in the buffer. public var remaining: Int { return length - index } // MARK: Init /// Creates an empty buffer. public init() { self.bytes = [] } /// Creates a buffer with the given bytes. /// - Parameter bytes: The buffer's initial bytes. public init(_ bytes: [UInt8]) { self.bytes = bytes } // MARK: Reading /// Skips forward or backward over the specified number of bytes. /// - Parameter count: Number of bytes to skip (a negative number goes backwards). /// - Throws: ``BufferError/skippedOutOfBounds`` if the new index is out of bounds. public mutating func skip(_ count: Int) throws { index += count if remaining < 0 || index < 0 { throw BufferError.skippedOutOfBounds(length: length, index: index) } } /// Reads an unsigned integer with the specified number of bytes and the given endianness. /// - Parameters: /// - size: The size of the integer in bytes (must be at most 8). /// - endianness: The endianness of the integer. /// - Returns: The integer stored as a 64 bit unsigned integer. /// - Throws: ``BufferError/rangeOutOfBounds`` if the requested number of bytes can't be read. public mutating func readInteger(size: Int, endianness: Endianness) throws -> UInt64 { assert(size <= 8) // TODO: throw error if out of bounds and turn assert into an error too var bitPattern: UInt64 = 0 switch endianness { case .little: for index in 0.. UInt8 { guard remaining > 0 else { throw BufferError.outOfBounds(length: length, index: index) } let byte = bytes[index] index += 1 return byte } /// Reads the signed byte at ``index``. /// - Returns: The signed byte. /// - Throws: ``BufferError/outOfBounds`` if ``remaining`` is not positive. public mutating func readSignedByte() throws -> Int8 { let byte = Int8(bitPattern: try readByte()) return byte } /// Reads a specified number of bytes (starting from ``index``). /// - Returns: The bytes. /// - Throws: ``BufferError/rangeOutOfBounds`` if the requested number of bytes can't be read. public mutating func readBytes(_ count: Int) throws -> [UInt8] { guard remaining >= count else { throw BufferError.rangeOutOfBounds(length: length, start: index, end: count + index) } let byteArray = Array(bytes[index..<(index + count)]) index += count return byteArray } /// Reads a specified number of signed bytes (starting from ``index``). /// - Returns: The bytes. /// - Throws: ``BufferError/rangeOutOfBounds`` if the requested number of bytes can't be read. public mutating func readSignedBytes(_ count: Int) throws -> [Int8] { guard remaining >= count else { throw BufferError.rangeOutOfBounds(length: length, start: index, end: count + index) } let unsignedBytes = try readBytes(count) var signedBytes: [Int8] = [] for i in 0.. [UInt8] { let remainingBytes = (try? readBytes(remaining)) ?? [] index = length return remainingBytes } /// Reads an unsigned short (2 byte integer). /// - Parameter endianness: The endianness of the integer. /// - Returns: The unsigned short. /// - Throws: ``BufferError/outOfBounds`` if ``index`` is out of bounds. public mutating func readShort(endianness: Endianness) throws -> UInt16 { return UInt16(try readInteger(size: MemoryLayout.stride, endianness: endianness)) } /// Reads a signed short (2 byte integer). /// - Parameter endianness: The endianness of the integer. /// - Returns: The signed short. /// - Throws: ``BufferError/outOfBounds`` if ``index`` is out of bounds. public mutating func readSignedShort(endianness: Endianness) throws -> Int16 { return Int16(bitPattern: try readShort(endianness: endianness)) } /// Reads an unsigned integer (4 bytes). /// - Parameter endianness: The endianness of the integer. /// - Returns: The unsigned integer. /// - Throws: ``BufferError/outOfBounds`` if ``index`` is out of bounds. public mutating func readInteger(endianness: Endianness) throws -> UInt32 { return UInt32(try readInteger(size: MemoryLayout.stride, endianness: endianness)) } /// Reads a signed integer (4 bytes). /// - Parameter endianness: The endianness of the integer. /// - Returns: The signed integer. /// - Throws: ``BufferError/outOfBounds`` if ``index`` is out of bounds. public mutating func readSignedInteger(endianness: Endianness) throws -> Int32 { return Int32(bitPattern: try readInteger(endianness: endianness)) } /// Reads an unsigned long (8 bytes). /// - Parameter endianness: The endianness of the integer. /// - Returns: The unsigned long. /// - Throws: ``BufferError/outOfBounds`` if ``index`` is out of bounds. public mutating func readLong(endianness: Endianness) throws -> UInt64 { return try readInteger(size: MemoryLayout.stride, endianness: endianness) } /// Reads a signed long (8 bytes). /// - Parameter endianness: The endianness of the integer. /// - Returns: The signed long. /// - Throws: ``BufferError/outOfBounds`` if ``index`` is out of bounds. public mutating func readSignedLong(endianness: Endianness) throws -> Int64 { return Int64(bitPattern: try readLong(endianness: endianness)) } /// Reads a float (4 bytes). /// - Parameter endianness: The endianness of the float. /// - Returns: The float. /// - Throws: ``BufferError/outOfBounds`` if ``index`` is out of bounds. public mutating func readFloat(endianness: Endianness) throws -> Float { return Float(bitPattern: try readInteger(endianness: endianness)) } /// Reads a double (4 bytes). /// - Parameter endianness: The endianness of the double. /// - Returns: The double. /// - Throws: ``BufferError/outOfBounds`` if ``index`` is out of bounds. public mutating func readDouble(endianness: Endianness) throws -> Double { return Double(bitPattern: try readLong(endianness: endianness)) } /// Reads a variable length integer. /// - Parameter maximumSize: The maximum number of bytes after decoding (i.e. a maximum of 4 could /// require reading 5 bytes because only 7 bits are encoded per byte). /// - Returns: The integer stored as a 64 bit integer. /// - Throws: ``BufferError/outOfBounds`` if ``index`` is out of bounds. ``BufferError/variableIntegerTooLarge`` /// if the integer is larger than `maximumSize`. /// - Precondition: `maximumSize` is no more than 8 (the number of bytes in a `UInt64`). public mutating func readVariableLengthInteger(maximumSize: Int) throws -> UInt64 { precondition(maximumSize <= MemoryLayout.stride) let maximumBits = UInt64(maximumSize * 8) var bitCount: UInt64 = 0 var bitPattern: UInt64 = 0 while true { guard bitCount < maximumBits else { throw BufferError.variableIntegerTooLarge(maximum: maximumSize) } // Read byte and remove continuation bit let byte = try readByte() let newBits = UInt64(byte & 0x7f) // Ensure that the new bits would not overflow the integer let remainingBits: UInt64 = maximumBits - bitCount if remainingBits < 8 { // mask is 0b11...11 where the number of 1s is remainingBits let mask: UInt64 = (1 << remainingBits) - 1 guard newBits & mask == newBits else { throw BufferError.variableIntegerTooLarge(maximum: maximumSize) } } // Prepend bits to the bit pattern bitPattern += newBits << bitCount bitCount += 7 // Check for continuation bit (most significant bit) if byte & 0x80 != 0x80 { break } } return bitPattern } /// Reads a variable length integer (4 bytes, stored as up to 5 bytes). /// - Returns: The integer stored as a 64 bit integer. /// - Throws: ``BufferError/outOfBounds`` if ``index`` is out of bounds. ``BufferError/variableIntegerTooLarge`` /// if the integer is encoded as more than 5 bytes. public mutating func readVariableLengthInteger() throws -> Int32 { let int = try readVariableLengthInteger(maximumSize: MemoryLayout.stride) let bitPattern = UInt32(int) return Int32(bitPattern: bitPattern) } /// Reads a variable length long (8 bytes, stored as up to 10 bytes). /// - Returns: The integer stored as a 64 bit integer. /// - Throws: ``BufferError/outOfBounds`` if ``index`` is out of bounds. ``BufferError/variableIntegerTooLarge`` /// if the long is encoded as more than 10 bytes. public mutating func readVariableLengthLong() throws -> Int64 { let bitPattern = try readVariableLengthInteger(maximumSize: MemoryLayout.stride) return Int64(bitPattern: bitPattern) } /// Reads a string. /// - Parameter length: The length of the string in bytes. /// - Returns: The string. /// - Throws: ``BufferError/outOfBounds`` if ``index`` is out of bounds. ``BufferError/invalidByteInUTF8String`` /// if the bytes cannot be converted to a strig. public mutating func readString(length: Int) throws -> String { let stringBytes = try readBytes(length) guard let string = String(bytes: stringBytes, encoding: .utf8) else { throw BufferError.invalidByteInUTF8String } return string } // MARK: Writing public mutating func writeByte(_ byte: UInt8) { bytes.append(byte) } public mutating func writeSignedByte(_ signedByte: Int8) { writeByte(UInt8(bitPattern: signedByte)) } public mutating func writeBytes(_ byteArray: [UInt8]) { bytes.append(contentsOf: byteArray) } public mutating func writeSignedBytes(_ signedBytes: [Int8]) { for signedByte in signedBytes { bytes.append(UInt8(bitPattern: signedByte)) } } public mutating func writeBitPattern(_ bitPattern: UInt64, numBytes: Int, endianness: Endianness) { switch endianness { case .big: for i in 1...numBytes { let byte = UInt8((bitPattern >> ((numBytes - i) * 8)) & 0xff) writeByte(byte) } case .little: for i in 1...numBytes { let byte = UInt8((bitPattern >> ((numBytes - (numBytes - i)) * 8)) & 0xff) writeByte(byte) } } } public mutating func writeShort(_ short: UInt16, endianness: Endianness) { writeBitPattern(UInt64(short), numBytes: 2, endianness: endianness) } public mutating func writeSignedShort(_ signedShort: Int16, endianness: Endianness) { writeShort(UInt16(bitPattern: signedShort), endianness: endianness) } public mutating func writeInt(_ int: UInt32, endianness: Endianness) { writeBitPattern(UInt64(int), numBytes: 4, endianness: endianness) } public mutating func writeSignedInt(_ signedInt: Int32, endianness: Endianness) { writeInt(UInt32(bitPattern: signedInt), endianness: endianness) } public mutating func writeLong(_ long: UInt64, endianness: Endianness) { writeBitPattern(long, numBytes: 8, endianness: endianness) } public mutating func writeSignedLong(_ signedLong: Int64, endianness: Endianness) { writeLong(UInt64(bitPattern: signedLong), endianness: endianness) } public mutating func writeFloat(_ float: Float, endianness: Endianness) { writeBitPattern(UInt64(float.bitPattern), numBytes: 4, endianness: endianness) } public mutating func writeDouble(_ double: Double, endianness: Endianness) { writeBitPattern(double.bitPattern, numBytes: 8, endianness: endianness) } public mutating func writeVarBitPattern(_ varBitPattern: UInt64) { var bitPattern = varBitPattern repeat { var toWrite = bitPattern & 0x7f bitPattern >>= 7 if bitPattern != 0 { toWrite |= 0x80 } writeByte(UInt8(toWrite)) } while bitPattern != 0 } public mutating func writeVarInt(_ varInt: Int32) { let bitPattern = UInt32(bitPattern: varInt) writeVarBitPattern(UInt64(bitPattern)) } public mutating func writeVarLong(_ varLong: Int64) { let bitPattern = UInt64(bitPattern: varLong) writeVarBitPattern(bitPattern) } public mutating func writeString(_ string: String) { let stringBytes = [UInt8](string.utf8) writeBytes(stringBytes) } } ================================================ FILE: Sources/Core/Sources/Network/Protocol/BufferError.swift ================================================ import Foundation /// An error thrown by ``Buffer``. public enum BufferError: Error { case invalidByteInUTF8String case skippedOutOfBounds(length: Int, index: Int) case outOfBounds(length: Int, index: Int) case rangeOutOfBounds(length: Int, start: Int, end: Int) case variableIntegerTooLarge(maximum: Int) } ================================================ FILE: Sources/Core/Sources/Network/Protocol/PacketRegistry.swift ================================================ import Foundation /// Stores the clientbound packet types for a given protocol version and assigns them ids. /// /// Packets are also grouped by connection state. For example, packet 0x01 in the handshaking /// state is usually differnet to packet 0x01 in the status state. public struct PacketRegistry { /// The client bound packets of this protocol. public var clientboundPackets: [PacketState: [Int: ClientboundPacket.Type]] = [ .handshaking: [:], .status: [:], .login: [:], .play: [:] ] /// Creates an empty packet registry. public init() {} // swiftlint:disable function_body_length /// Creates the packet registry for the 1.16.1 protocol version. public static func create_1_16_1() -> PacketRegistry { var registry = PacketRegistry() registry.addClientboundPackets([ StatusResponsePacket.self, PongPacket.self ], toState: .status) registry.addClientboundPackets([ LoginDisconnectPacket.self, EncryptionRequestPacket.self, LoginSuccessPacket.self, SetCompressionPacket.self, LoginPluginRequestPacket.self, PlayDisconnectPacket.self ], toState: .login) registry.addClientboundPackets([ SpawnEntityPacket.self, SpawnExperienceOrbPacket.self, SpawnLivingEntityPacket.self, SpawnPaintingPacket.self, SpawnPlayerPacket.self, EntityAnimationPacket.self, StatisticsPacket.self, AcknowledgePlayerDiggingPacket.self, BlockBreakAnimationPacket.self, BlockEntityDataPacket.self, BlockActionPacket.self, BlockChangePacket.self, BossBarPacket.self, ServerDifficultyPacket.self, ChatMessageClientboundPacket.self, MultiBlockUpdatePacket.self, TabCompleteClientboundPacket.self, DeclareCommandsPacket.self, WindowConfirmationClientboundPacket.self, CloseWindowClientboundPacket.self, WindowItemsPacket.self, SetSlotPacket.self, SetCooldownPacket.self, PluginMessagePacket.self, NamedSoundEffectPacket.self, PlayDisconnectPacket.self, EntityStatusPacket.self, ExplosionPacket.self, UnloadChunkPacket.self, ChangeGameStatePacket.self, OpenHorseWindowPacket.self, KeepAliveClientboundPacket.self, ChunkDataPacket.self, EffectPacket.self, ParticlePacket.self, UpdateLightPacket.self, JoinGamePacket.self, MapDataPacket.self, TradeListPacket.self, EntityPositionPacket.self, EntityPositionAndRotationPacket.self, EntityRotationPacket.self, EntityMovementPacket.self, VehicleMoveClientboundPacket.self, OpenBookPacket.self, OpenWindowPacket.self, OpenSignEditorPacket.self, CraftRecipeResponsePacket.self, PlayerAbilitiesPacket.self, CombatEventPacket.self, PlayerInfoPacket.self, FacePlayerPacket.self, PlayerPositionAndLookClientboundPacket.self, UnlockRecipesPacket.self, DestroyEntitiesPacket.self, RemoveEntityEffectPacket.self, ResourcePackSendPacket.self, RespawnPacket.self, EntityHeadLookPacket.self, SelectAdvancementTabPacket.self, WorldBorderPacket.self, CameraPacket.self, HeldItemChangePacket.self, UpdateViewPositionPacket.self, UpdateViewDistancePacket.self, SpawnPositionPacket.self, DisplayScoreboardPacket.self, EntityMetadataPacket.self, AttachEntityPacket.self, EntityVelocityPacket.self, EntityEquipmentPacket.self, SetExperiencePacket.self, UpdateHealthPacket.self, ScoreboardObjectivePacket.self, SetPassengersPacket.self, TeamsPacket.self, UpdateScorePacket.self, TimeUpdatePacket.self, TitlePacket.self, EntitySoundEffectPacket.self, SoundEffectPacket.self, StopSoundPacket.self, PlayerListHeaderAndFooterPacket.self, NBTQueryResponsePacket.self, CollectItemPacket.self, EntityTeleportPacket.self, AdvancementsPacket.self, EntityAttributesPacket.self, EntityEffectPacket.self, DeclareRecipesPacket.self, TagsPacket.self, WindowPropertyPacket.self ], toState: .play) return registry } // swiftlint:enable function_body_length /// Adds an array of clientbound packets to the given connection state. Each packet is assigned the id which is stored as a static property on the type. public mutating func addClientboundPackets(_ packets: [ClientboundPacket.Type], toState state: PacketState) { for packet in packets { addClientboundPacket(packet, toState: state) } } /// Adds a clientbound packet to the given connection state. The packet is assigned the id which is stored in the static property `id`. public mutating func addClientboundPacket(_ packet: ClientboundPacket.Type, toState state: PacketState) { let id = packet.id if var packets = clientboundPackets[state] { packets[id] = packet clientboundPackets[state] = packets } else { clientboundPackets[state] = [id: packet] } } /// Gets the packet type for the requested packet id and connection state. public func getClientboundPacketType(withId id: Int, andState state: PacketState) -> ClientboundPacket.Type? { return clientboundPackets[state]?[id] } } ================================================ FILE: Sources/Core/Sources/Network/Protocol/PacketState.swift ================================================ import Foundation public enum PacketState { case handshaking case status case login case play } ================================================ FILE: Sources/Core/Sources/Network/Protocol/Packets/ClientboundEntityPacket.swift ================================================ /// A marker for packets that must be handled during the game tick. /// /// > Warning: Packets conforming to this must not acquire a nexus lock because this will cause /// > deadlocks. The tick scheduler will already have a lock by the time the packets are handled. public protocol ClientboundEntityPacket: ClientboundPacket {} ================================================ FILE: Sources/Core/Sources/Network/Protocol/Packets/ClientboundPacket.swift ================================================ import Foundation public enum ClientboundPacketError: LocalizedError { case invalidDifficulty case invalidGamemode(rawValue: Int8) case invalidServerId case invalidJSONString case invalidInventorySlotCount(Int) case invalidInventorySlotIndex(Int, windowId: Int) case invalidChangeGameStateReasonRawValue(ChangeGameStatePacket.Reason.RawValue) case invalidDimension(Identifier) case invalidBossBarActionId(Int) case invalidBossBarColorId(Int) case invalidBossBarStyleId(Int) case duplicateBossBar(UUID) case noSuchBossBar(UUID) case invalidPoseId(Int) case invalidEntityMetadataDatatypeId(Int) case incorrectEntityMetadataDatatype( property: String, expectedType: String, value: EntityMetadataPacket.Value ) public var errorDescription: String? { switch self { case .invalidDifficulty: return "Invalid difficulty." case let .invalidGamemode(rawValue): return """ Invalid gamemode. Raw value: \(rawValue) """ case .invalidServerId: return "Invalid server Id." case .invalidJSONString: return "Invalid JSON string." case let .invalidInventorySlotCount(slotCount): return """ Invalid inventory slot count. Slot count: \(slotCount) """ case let .invalidInventorySlotIndex(slotIndex, windowId): return """ Invalid inventory slot index. Slot index: \(slotIndex) Window Id: \(windowId) """ case let .invalidChangeGameStateReasonRawValue(rawValue): return """ Invalid change game state reason. Raw value: \(rawValue) """ case let .invalidDimension(identifier): return """ Invalid dimension. Identifier: \(identifier) """ case let .invalidBossBarActionId(actionId): return """ Invalid boss bar action id. Id: \(actionId) """ case let .invalidBossBarColorId(colorId): return """ Invalid boss bar color id. Id: \(colorId) """ case let .invalidBossBarStyleId(styleId): return """ Invalid boss bar style id. Id: \(styleId) """ case let .duplicateBossBar(uuid): return """ Received duplicate boss bar. UUID: \(uuid.uuidString) """ case let .noSuchBossBar(uuid): return """ Received update for non-existent boss bar. UUID: \(uuid) """ case let .invalidPoseId(poseId): return """ Received invalid pose id. Id: \(poseId) """ case let .invalidEntityMetadataDatatypeId(datatypeId): return """ Received invalid entity metadata datatype id. Id: \(datatypeId) """ case let .incorrectEntityMetadataDatatype(property, expectedType, value): return """ Received entity metadata property with invalid data type. Property name: \(property) Expected type: \(expectedType) Value: \(value) """ } } } public protocol ClientboundPacket { static var id: Int { get } init(from packetReader: inout PacketReader) throws func handle(for client: Client) throws func handle(for pinger: Pinger) throws } extension ClientboundPacket { public func handle(for client: Client) { return } public func handle(for pinger: Pinger) { return } } ================================================ FILE: Sources/Core/Sources/Network/Protocol/Packets/Handshaking/Serverbound/HandshakePacket.swift ================================================ import Foundation public struct HandshakePacket: ServerboundPacket { public static let id: Int = 0x00 public var protocolVersion: Int public var serverAddr: String public var serverPort: Int public var nextState: NextState public enum NextState: Int { case status = 1 case login = 2 } public func writePayload(to writer: inout PacketWriter) { writer.writeVarInt(Int32(protocolVersion)) writer.writeString(serverAddr) writer.writeUnsignedShort(UInt16(serverPort)) writer.writeVarInt(Int32(nextState.rawValue)) } } ================================================ FILE: Sources/Core/Sources/Network/Protocol/Packets/Login/Clientbound/EncryptionRequestPacket.swift ================================================ import Foundation public enum EncryptionRequestPacketError: LocalizedError { case incorrectAccountType public var errorDescription: String? { switch self { case .incorrectAccountType: return "Incorrect account type." } } } public struct EncryptionRequestPacket: ClientboundPacket, Sendable { public static let id: Int = 0x01 public let serverId: String public let publicKey: [UInt8] public let verifyToken: [UInt8] public init(from packetReader: inout PacketReader) throws { serverId = try packetReader.readString() let publicKeyLength = try packetReader.readVarInt() publicKey = try packetReader.readByteArray(length: publicKeyLength) let verifyTokenLength = try packetReader.readVarInt() verifyToken = try packetReader.readByteArray(length: verifyTokenLength) } public func handle(for client: Client) throws { client.eventBus.dispatch(LoginStartEvent()) let sharedSecret = try CryptoUtil.generateRandomBytes(16) guard let serverIdData = serverId.data(using: .ascii) else { throw ClientboundPacketError.invalidServerId } // Calculate the server hash let serverHash = try CryptoUtil.sha1MojangDigest([ serverIdData, Data(sharedSecret), Data(publicKey) ]) // TODO: Clean up EncryptionRequestPacket.handle // Request to join the server if let account = client.account?.online { let accessToken = account.accessToken let selectedProfile = account.id Task { do { try await MojangAPI.join( accessToken: accessToken.token, selectedProfile: selectedProfile, serverHash: serverHash ) } catch { log.error("Join request for online server failed: \(error)") client.eventBus.dispatch(PacketHandlingErrorEvent(packetId: Self.id, error: "Join request for online server failed: \(error)")) return } // block inbound thread until encryption is enabled client.connection?.networkStack.inboundThread.sync { do { let publicKeyData = Data(publicKey) // Send encryption response packet let encryptedSharedSecret = try CryptoUtil.encryptRSA( data: Data(sharedSecret), publicKeyDERData: publicKeyData) let encryptedVerifyToken = try CryptoUtil.encryptRSA( data: Data(verifyToken), publicKeyDERData: publicKeyData) let encryptionResponse = EncryptionResponsePacket( sharedSecret: [UInt8](encryptedSharedSecret), verifyToken: [UInt8](encryptedVerifyToken)) try client.sendPacket(encryptionResponse) // Wait for packet to send then enable encryption try client.connection?.networkStack.outboundThread.sync { try client.connection?.enableEncryption(sharedSecret: sharedSecret) } } catch { log.error("Failed to enable encryption: \(error)") } } } } else { log.error("Cannot join an online server with an offline account") throw EncryptionRequestPacketError.incorrectAccountType } } } ================================================ FILE: Sources/Core/Sources/Network/Protocol/Packets/Login/Clientbound/LoginDisconnectPacket.swift ================================================ import Foundation public struct LoginDisconnectPacket: ClientboundPacket { public static let id: Int = 0x00 public var reason: ChatComponent public init(from packetReader: inout PacketReader) throws { reason = try packetReader.readChat() } public func handle(for client: Client) { let locale = client.resourcePack.getDefaultLocale() let message = reason.toText(with: locale) log.trace("Disconnected from server: \(message)") client.eventBus.dispatch(LoginDisconnectEvent(reason: message)) } } ================================================ FILE: Sources/Core/Sources/Network/Protocol/Packets/Login/Clientbound/LoginPluginRequestPacket.swift ================================================ import Foundation public struct LoginPluginRequestPacket: ClientboundPacket { public static let id: Int = 0x04 public var messageId: Int public var channel: Identifier public var data: [UInt8] public init(from packetReader: inout PacketReader) throws { messageId = try packetReader.readVarInt() channel = try packetReader.readIdentifier() data = try packetReader.readByteArray(length: packetReader.remaining) } public func handle(for client: Client) throws { try client.sendPacket(LoginPluginResponsePacket( messageId: messageId, wasSuccess: false, data: [] )) } } ================================================ FILE: Sources/Core/Sources/Network/Protocol/Packets/Login/Clientbound/LoginSuccessPacket.swift ================================================ import Foundation public struct LoginSuccessPacket: ClientboundPacket { public static let id: Int = 0x02 public var uuid: UUID public var username: String public init(from packetReader: inout PacketReader) throws { uuid = try packetReader.readUUID() username = try packetReader.readString() } public func handle(for client: Client) throws { client.connection?.setState(.play) client.eventBus.dispatch(LoginSuccessEvent()) } } ================================================ FILE: Sources/Core/Sources/Network/Protocol/Packets/Login/Clientbound/SetCompressionPacket.swift ================================================ import Foundation public struct SetCompressionPacket: ClientboundPacket { public static let id: Int = 0x03 public var threshold: Int public init(from packetReader: inout PacketReader) throws { threshold = try packetReader.readVarInt() } public func handle(for client: Client) throws { client.connection?.setCompression(threshold: threshold) } } ================================================ FILE: Sources/Core/Sources/Network/Protocol/Packets/Login/Serverbound/EncryptionResponsePacket.swift ================================================ import Foundation public struct EncryptionResponsePacket: ServerboundPacket { public static let id: Int = 0x01 public var sharedSecret: [UInt8] public var verifyToken: [UInt8] public func writePayload(to writer: inout PacketWriter) { writer.writeVarInt(Int32(sharedSecret.count)) writer.writeByteArray(sharedSecret) writer.writeVarInt(Int32(verifyToken.count)) writer.writeByteArray(verifyToken) } } ================================================ FILE: Sources/Core/Sources/Network/Protocol/Packets/Login/Serverbound/LoginPluginResponsePacket.swift ================================================ import Foundation public struct LoginPluginResponsePacket: ServerboundPacket { public static let id: Int = 0x02 public var messageId: Int public var wasSuccess: Bool public var data: [UInt8] public func writePayload(to writer: inout PacketWriter) { writer.writeVarInt(Int32(messageId)) writer.writeBool(!data.isEmpty ? wasSuccess : false) writer.writeByteArray(data) } } ================================================ FILE: Sources/Core/Sources/Network/Protocol/Packets/Login/Serverbound/LoginStartPacket.swift ================================================ import Foundation public struct LoginStartPacket: ServerboundPacket { public static let id: Int = 0x00 public var username: String public func writePayload(to writer: inout PacketWriter) { writer.writeString(username) } } ================================================ FILE: Sources/Core/Sources/Network/Protocol/Packets/PacketReader.swift ================================================ import FirebladeMath import Foundation /// A wrapper around ``Buffer`` that is specialized for reading Minecraft packets. public struct PacketReader { /// The packet's id. public let packetId: Int /// The packet's bytes as a buffer. public var buffer: Buffer /// The number of bytes remaining in the packet's buffer. public var remaining: Int { return buffer.remaining } // MARK: Init /// Creates a new packet reader. /// /// Expects the start of the bytes to be a variable length integer encoding the packet's id. /// - Parameter bytes: The packet's bytes. /// - Throws: A ``BufferError`` if the packet's id cannot be read. public init(bytes: [UInt8]) throws { self.buffer = Buffer(bytes) self.packetId = Int(try buffer.readVariableLengthInteger()) } /// Creates a new packet reader. /// /// Expects the start of the buffer to be a variable length integer encoding the packet's id. /// - Parameter bytes: The packet's bytes as a buffer. Reading starts from the buffer's current index. /// - Throws: A ``BufferError`` if the packet's id cannot be read. public init(buffer: Buffer) throws { self.buffer = buffer self.packetId = Int(try self.buffer.readVariableLengthInteger()) } // MARK: Public methods /// Reads a boolean (1 byte). /// - Returns: A boolean. /// - Throws: A ``BufferError`` if out of bounds. public mutating func readBool() throws -> Bool { let byte = try buffer.readByte() let bool = byte == 1 return bool } /// Optionally reads a value (assuming that the value's presence is indicated by a boolean /// field directly preceding it). public mutating func readOptional(_ inner: (inout Self) throws -> T) throws -> T? { if try readBool() { return try inner(&self) } else { return nil } } /// Reads a direction (represented as a VarInt). public mutating func readDirection() throws -> Direction { let rawValue = try readVarInt() guard let direction = Direction(rawValue: rawValue) else { throw PacketReaderError.invalidDirection(rawValue) } return direction } /// Reads a signed byte. /// - Returns: A signed byte. /// - Throws: A ``BufferError`` if out of bounds. public mutating func readByte() throws -> Int8 { return try buffer.readSignedByte() } /// Reads an unsigned byte. /// - Returns: An unsigned byte. /// - Throws: A ``BufferError`` if out of bounds. public mutating func readUnsignedByte() throws -> UInt8 { return try buffer.readByte() } /// Reads a signed short (2 bytes). /// - Returns: A signed short. /// - Throws: A ``BufferError`` if out of bounds. public mutating func readShort() throws -> Int16 { return try buffer.readSignedShort(endianness: .big) } /// Reads an unsigned short (2 bytes). /// - Returns: An unsigned short. /// - Throws: A ``BufferError`` if out of bounds. public mutating func readUnsignedShort() throws -> UInt16 { return try buffer.readShort(endianness: .big) } /// Reads a signed integer (4 bytes). /// - Returns: A signed integer. /// - Throws: A ``BufferError`` if out of bounds. public mutating func readInt() throws -> Int { return Int(try buffer.readSignedInteger(endianness: .big)) } /// Reads a signed long (8 bytes). /// - Returns: A signed long. /// - Throws: A ``BufferError`` if out of bounds. public mutating func readLong() throws -> Int { return Int(try buffer.readSignedLong(endianness: .big)) } /// Reads a float (4 bytes). /// - Returns: A float. /// - Throws: A ``BufferError`` if out of bounds. public mutating func readFloat() throws -> Float { return try buffer.readFloat(endianness: .big) } /// Reads a double (8 bytes). /// - Returns: A double. /// - Throws: A ``BufferError`` if out of bounds. public mutating func readDouble() throws -> Double { return try buffer.readDouble(endianness: .big) } /// Reads a length prefixed string (length must be encoded as a variable length integer). /// - Returns: A string. /// - Throws: A ``BufferError`` if any reads go out of bounds. ``PacketReaderError/stringTooLong`` if the string is longer than 32767 (Minecraft's maximum string length). public mutating func readString() throws -> String { let length = Int(try buffer.readVariableLengthInteger()) guard length <= 32767 else { throw PacketReaderError.stringTooLong(length: length) } let string = try buffer.readString(length: length) return string } /// Reads a variable length integer (4 bytes, encoded as up to 5 bytes). /// - Returns: A signed integer. /// - Throws: A ``BufferError`` if any reads go out of bounds or the integer is encoded as more than 5 bytes. public mutating func readVarInt() throws -> Int { return Int(try buffer.readVariableLengthInteger()) } /// Reads a variable length long (8 bytes, encoded as up to 10 bytes). /// - Returns: A signed long. /// - Throws: A ``BufferError`` if any reads go out of bounds or the long is encoded as more than 10 bytes. public mutating func readVarLong() throws -> Int { return Int(try buffer.readVariableLengthLong()) } /// Reads and parses a JSON-encoded chat component. /// - Returns: A chat component. /// - Throws: A ``BufferError`` if any reads go out of bounds. A ``ChatComponentError`` if the component is invalid. public mutating func readChat() throws -> ChatComponent { let string = try readString() do { let data = Data(string.utf8) let chat = try JSONDecoder().decode(ChatComponent.self, from: data) return chat } catch { log.warning("Failed to decode chat message: '\(string)' with error '\(error)'") // TODO: Remove fallback once all chat components are handled return ChatComponent(style: .init(), content: .string(""), children: []) } } /// Reads and parses an identifier (e.g. `minecraft:block/dirt`). /// - Returns: An identifier. /// - Throws: A ``BufferError`` if any reads go out of bounds. ``PacketReaderError/invalidIdentifier`` if the identifier is invalid. public mutating func readIdentifier() throws -> Identifier { let string = try readString() do { let identifier = try Identifier(string) return identifier } catch { throw PacketReaderError.invalidIdentifier(string) } } /// Reads an item stack. /// - Returns: An item stack, or `nil` if the item stack is not present (in-game). /// - Throws: A ``BufferError`` if any reads go out of bounds. ``PacketReaderError/invalidNBT`` if the slot has invalid NBT data. public mutating func readSlot() throws -> Slot { let isPresent = try readBool() if isPresent { let itemId = try readVarInt() let itemCount = Int(try readByte()) let nbt = try readNBTCompound() return Slot(ItemStack(itemId: itemId, itemCount: itemCount, nbt: nbt)) } else { return Slot() } } /// Reads an NBT compound. /// - Returns: An NBT compound. /// - Throws: A ``BufferError`` if any reads go out of bounds. ``PacketReaderError/invalidNBT`` if the NBT is invalid. public mutating func readNBTCompound() throws -> NBT.Compound { do { let compound = try NBT.Compound(fromBuffer: buffer) try buffer.skip(compound.numBytes) return compound } catch { throw PacketReaderError.invalidNBT(error) } } /// Reads an angle (1 byte) and returns it as radians. /// - Returns: An angle in radians. /// - Throws: A ``BufferError`` if any reads go out of bounds. public mutating func readAngle() throws -> Float { let angle = try readUnsignedByte() return Float(angle) / 128 * .pi } /// Reads a UUID (16 bytes). /// - Returns: A UUID. /// - Throws: A ``BufferError`` if any reads go out of bounds. public mutating func readUUID() throws -> UUID { var bytes = try buffer.readBytes(16) let uuid = Data(bytes: &bytes, count: bytes.count).withUnsafeBytes { pointer in pointer.load(as: UUID.self) } return uuid } /// Reads a byte array. /// - Parameter length: The length of byte array to read. /// - Returns: A byte array. /// - Throws: A ``BufferError`` if any reads go out of bounds. public mutating func readByteArray(length: Int) throws -> [UInt8] { return try buffer.readBytes(length) } /// Reads a packed block position (8 bytes). /// /// The x and z coordinates take up 26 bits each and the y coordinate takes up 12 bits. /// - Returns: A block position. /// - Throws: A ``BufferError`` if any reads go out of bounds. public mutating func readBlockPosition() throws -> BlockPosition { let val = try buffer.readLong(endianness: .big) // Extract the bit patterns (in the order x, then z, then y) var x = UInt32(val >> 38) // x is 26 bit var z = UInt32((val << 26) >> 38) // z is 26 bit var y = UInt32(val & 0xfff) // y is 12 bit // x and z are 26-bit signed integers, y is a 12-bit signed integer let xSignBit = (x & (1 << 25)) >> 25 let ySignBit = (y & (1 << 11)) >> 11 let zSignBit = (z & (1 << 25)) >> 25 // Convert to 32 bit signed bit patterns if xSignBit == 1 { x |= 0b111111 << 26 } if ySignBit == 1 { y |= 0b1111_11111111_11111111 << 12 } if zSignBit == 1 { z |= 0b111111 << 26 } return BlockPosition( x: Int(Int32(bitPattern: x)), y: Int(Int32(bitPattern: y)), z: Int(Int32(bitPattern: z)) ) } /// Reads an entity rotation (2 bytes) and returns it in radians. /// /// Expects yaw to be before pitch unless `pitchFirst` is `true`. Every packet except one has yaw first, thanks Mojang. /// - Parameter pitchFirst: If `true`, pitch is read before yaw. /// - Returns: An entity rotation in radians. /// - Throws: A ``BufferError`` if any reads go out of bounds. public mutating func readEntityRotation(pitchFirst: Bool = false) throws -> ( pitch: Float, yaw: Float ) { var pitch: Float = 0 if pitchFirst { pitch = try readAngle() } let yaw = try readAngle() if !pitchFirst { pitch = try readAngle() } return (pitch: pitch, yaw: yaw) } /// Reads an entity position (24 bytes). /// - Returns: An entity position. /// - Throws: A ``BufferError`` if any reads go out of bounds. public mutating func readEntityPosition() throws -> Vec3d { let x = try readDouble() let y = try readDouble() let z = try readDouble() return Vec3d(x, y, z) } /// Reads an entity velocity (6 bytes). /// - Returns: An entity velocity. /// - Throws: A ``BufferError`` if any reads go out of bounds. public mutating func readEntityVelocity() throws -> Vec3d { let x = try Double(readShort()) / 8000 let y = try Double(readShort()) / 8000 let z = try Double(readShort()) / 8000 return Vec3d(x, y, z) } } ================================================ FILE: Sources/Core/Sources/Network/Protocol/Packets/PacketReaderError.swift ================================================ import Foundation /// An error thrown by ``PacketReader``. public enum PacketReaderError: Error { case stringTooLong(length: Int) case invalidNBT(Error) case invalidIdentifier(String) case invalidDirection(Int) } ================================================ FILE: Sources/Core/Sources/Network/Protocol/Packets/PacketWriter.swift ================================================ import Foundation import FirebladeMath // TODO: document packet writer public struct PacketWriter { public var buffer: Buffer public init() { buffer = Buffer([]) } // MARK: Basic datatypes public mutating func writeBool(_ bool: Bool) { let byte: UInt8 = bool ? 1 : 0 writeUnsignedByte(byte) } public mutating func writeByte(_ byte: Int8) { buffer.writeSignedByte(byte) } public mutating func writeUnsignedByte(_ unsignedByte: UInt8) { buffer.writeByte(unsignedByte) } public mutating func writeByteArray(_ byteArray: [UInt8]) { buffer.writeBytes(byteArray) } public mutating func writeShort(_ short: Int16) { buffer.writeSignedShort(short, endianness: .big) } public mutating func writeUnsignedShort(_ unsignedShort: UInt16) { buffer.writeShort(unsignedShort, endianness: .big) } public mutating func writeInt(_ int: Int32) { buffer.writeSignedInt(int, endianness: .big) } public mutating func writeLong(_ long: Int64) { buffer.writeSignedLong(long, endianness: .big) } public mutating func writeFloat(_ float: Float) { buffer.writeFloat(float, endianness: .big) } public mutating func writeDouble(_ double: Double) { buffer.writeDouble(double, endianness: .big) } public mutating func writeString(_ string: String) { let length = string.utf8.count precondition(length < 32767, "string too long to write") writeVarInt(Int32(length)) buffer.writeString(string) } public mutating func writeVarInt(_ varInt: Int32) { buffer.writeVarInt(varInt) } public mutating func writeVarLong(_ varLong: Int64) { buffer.writeVarLong(varLong) } public mutating func writeIdentifier(_ identifier: Identifier) { writeString(identifier.description) } // MARK: Complex datatypes // IMPLEMENT: Entity Metadata, Angle public mutating func writeSlot(_ slot: Slot) { if let itemStack = slot.stack { writeBool(true) writeVarInt(Int32(itemStack.itemId)) writeByte(Int8(itemStack.count)) writeNBT(itemStack.nbt) } else { writeBool(false) } } public mutating func writeNBT(_ nbtCompound: NBT.Compound) { var compound = nbtCompound buffer.writeBytes(compound.pack()) } public mutating func writeUUID(_ uuid: UUID) { let bytes = uuid.toBytes() buffer.writeBytes(bytes) } public mutating func writePosition(_ position: BlockPosition) { var val: UInt64 = (UInt64(bitPattern: Int64(position.x)) & 0x3FFFFFF) << 38 val |= (UInt64(bitPattern: Int64(position.z)) & 0x3FFFFFF) << 12 val |= UInt64(bitPattern: Int64(position.y)) & 0xFFF buffer.writeLong(val, endianness: .big) } public mutating func writeEntityPosition(_ position: Vec3d) { writeDouble(position.x) writeDouble(position.y) writeDouble(position.z) } } ================================================ FILE: Sources/Core/Sources/Network/Protocol/Packets/Play/Clientbound/AcknowledgePlayerDiggingPacket.swift ================================================ import Foundation public struct AcknowledgePlayerDiggingPacket: ClientboundPacket { public static let id: Int = 0x07 public var location: BlockPosition public var block: Int public var status: Int public var successful: Bool public init(from packetReader: inout PacketReader) throws { location = try packetReader.readBlockPosition() block = try packetReader.readVarInt() status = try packetReader.readVarInt() successful = try packetReader.readBool() } } ================================================ FILE: Sources/Core/Sources/Network/Protocol/Packets/Play/Clientbound/AdvancementsPacket.swift ================================================ import Foundation public struct AdvancementsPacket: ClientboundPacket { public static let id: Int = 0x57 public var shouldReset: Bool public var advancements: [Identifier: Advancement] public var advancementsToRemove: [Identifier] public var advancementProgresses: [Identifier: AdvancementProgress] public struct Advancement { public var hasParent: Bool public var parentId: Identifier? public var hasDisplay: Bool public var displayData: AdvancementDisplay? public var criteria: [Identifier] public var requirements: [[String]] } public struct AdvancementDisplay { public var title: ChatComponent public var description: ChatComponent public var icon: Slot public var frameType: Int public var flags: Int public var backgroundTexture: Identifier? public var xCoord: Float public var yCoord: Float } public struct AdvancementProgress { public var criteria: [Identifier: CriterionProgress] } public struct CriterionProgress { public var achieved: Bool public var dateOfAchieving: Int? } public init(from packetReader: inout PacketReader) throws { shouldReset = try packetReader.readBool() advancements = try Self.readAdvancements(from: &packetReader) advancementsToRemove = try Self.readAdvancementsToRemove(from: &packetReader) advancementProgresses = try Self.readAdvancementProgresses(from: &packetReader) } private static func readAdvancements(from packetReader: inout PacketReader) throws -> [Identifier: Advancement] { let mappingSize = try packetReader.readVarInt() var advancements: [Identifier: Advancement] = [:] for _ in 0..