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
[](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).

## 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


================================================
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