From 1c0043e045525b7f9f221faa3e2fe41728e9bb95 Mon Sep 17 00:00:00 2001 From: Vit3V Date: Wed, 18 Nov 2026 01:28:04 +0200 Subject: [PATCH] Add iOS and tvOS platform support --- CMakeLists.txt | 22 ++ CMakeOptions.txt | 5 +- README.md | 2 +- cmake/AppleXCFramework.cmake | 52 +++ cmake/InstallConfigurations.cmake | 3 + cmake/LibraryConfigurations.cmake | 18 + examples/CMakeLists.txt | 9 + projects/CMake/AppleApp.cmake | 37 ++ projects/CMake/CMakeLists.txt | 20 +- projects/CMake/README.md | 45 +++ projects/CMake/apple_entry.c | 16 + projects/CMake/apple_info.plist | 38 ++ src/CMakeLists.txt | 19 +- src/Makefile | 9 + src/Makefile.Apple | 64 ++++ src/platforms/rcore_apple.c | 292 ++++++++++++++++ src/platforms/rcore_apple.h | 67 ++++ src/platforms/rcore_apple.m | 556 ++++++++++++++++++++++++++++++ src/raylib_apple.h | 32 ++ src/rcore.c | 45 ++- src/rlgl.h | 65 +++- 21 files changed, 1396 insertions(+), 20 deletions(-) create mode 100644 cmake/AppleXCFramework.cmake create mode 100644 projects/CMake/AppleApp.cmake create mode 100644 projects/CMake/apple_entry.c create mode 100644 projects/CMake/apple_info.plist create mode 100644 src/Makefile.Apple create mode 100644 src/platforms/rcore_apple.c create mode 100644 src/platforms/rcore_apple.h create mode 100644 src/platforms/rcore_apple.m create mode 100644 src/raylib_apple.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 637927400d19..f0672a88560a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,12 @@ cmake_minimum_required(VERSION 3.22) + +if (PLATFORM MATCHES "^(iOS|tvOS)$" AND NOT DEFINED CMAKE_SYSTEM_NAME AND NOT CMAKE_TOOLCHAIN_FILE) + set(CMAKE_SYSTEM_NAME "${PLATFORM}") +endif () +if (CMAKE_SYSTEM_NAME MATCHES "^(iOS|tvOS)$" AND NOT DEFINED CMAKE_OSX_DEPLOYMENT_TARGET) + set(CMAKE_OSX_DEPLOYMENT_TARGET "17.0" CACHE STRING "Minimum Apple OS version") +endif () + project(raylib) # Avoid excessive expansion of variables in conditionals. In particular, if @@ -37,6 +45,20 @@ endif() # Main sources directory (the second parameter sets the output directory name to raylib) add_subdirectory(src raylib) +if (PROJECT_IS_TOP_LEVEL AND CMAKE_HOST_APPLE AND CMAKE_SYSTEM_NAME STREQUAL "Darwin") + add_custom_target(raylib_xcframework + COMMAND ${CMAKE_COMMAND} + "-DRAYLIB_APPLE_SOURCE=${CMAKE_CURRENT_SOURCE_DIR}" + "-DRAYLIB_APPLE_OUTPUT=${CMAKE_CURRENT_BINARY_DIR}/apple/$" + "-DRAYLIB_APPLE_CONFIG=$" + "-DRAYLIB_APPLE_AUDIO=${SUPPORT_MODULE_RAUDIO}" + "-DRAYLIB_APPLE_MODELS=${SUPPORT_MODULE_RMODELS}" + -P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/AppleXCFramework.cmake" + USES_TERMINAL + VERBATIM + ) +endif () + # Uninstall target, only create when building raylib by itself # Avoid conflicting target names when using raylib with other libraries if(NOT TARGET uninstall AND PROJECT_IS_TOP_LEVEL) diff --git a/CMakeOptions.txt b/CMakeOptions.txt index 9e253dc55f87..dd157be37be3 100644 --- a/CMakeOptions.txt +++ b/CMakeOptions.txt @@ -6,7 +6,10 @@ if(EMSCRIPTEN) # When configuring web builds with "emcmake cmake -B build -S .", set PLATFORM to Web by default SET(PLATFORM Web CACHE STRING "Platform to build for.") endif() -enum_option(PLATFORM "Desktop;Win32;Web;WebRGFW;Android;Raspberry Pi;DRM;SDL;RGFW;Memory" "Platform to build for.") +if (CMAKE_SYSTEM_NAME MATCHES "^(iOS|tvOS)$" AND NOT DEFINED PLATFORM) + set(PLATFORM "${CMAKE_SYSTEM_NAME}" CACHE STRING "Platform to build for.") +endif () +enum_option(PLATFORM "Desktop;Win32;Web;WebRGFW;Android;iOS;tvOS;Raspberry Pi;DRM;SDL;RGFW;Memory" "Platform to build for.") enum_option(OPENGL_VERSION "OFF;4.3;3.3;2.1;1.1;ES 2.0;ES 3.0;Software" "Force a specific OpenGL Version?") diff --git a/README.md b/README.md index 49c11759cc44..5acb3a301cad 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ Ready to learn? Jump to [code examples!](https://www.raylib.com/examples.html) features -------- - **NO external dependencies**, all required libraries are [included in raylib](https://github.com/raysan5/raylib/tree/master/src/external) - - Multiple platforms supported: **Windows, Linux, MacOS, RPI, Android, HTML5... and more!** + - Multiple platforms supported: **Windows, Linux, macOS, iOS, iPadOS, tvOS, RPI, Android, HTML5... and more!** - Written in plain C code (C99) using PascalCase/camelCase notation - Hardware accelerated with OpenGL: **1.1, 2.1, 3.3, 4.3, ES 2.0, ES 3.0** - **Unique OpenGL abstraction layer** (usable as standalone module): [rlgl](https://github.com/raysan5/raylib/blob/master/src/rlgl.h) diff --git a/cmake/AppleXCFramework.cmake b/cmake/AppleXCFramework.cmake new file mode 100644 index 000000000000..e1fd1093eeac --- /dev/null +++ b/cmake/AppleXCFramework.cmake @@ -0,0 +1,52 @@ +# Build and package each Apple platform and simulator variant from the raylib sources +cmake_minimum_required(VERSION 3.22) +find_program(XCODEBUILD xcodebuild REQUIRED) + +set(xcframework_args) +foreach (sdk IN ITEMS macosx iphoneos iphonesimulator appletvos appletvsimulator) + set(platform Desktop) + set(system_args) + set(deployment_target 17.0) + set(architectures arm64) + if (sdk STREQUAL "macosx") + set(deployment_target 11.0) + elseif (sdk MATCHES "^iphone") + set(platform iOS) + set(system_args -DCMAKE_SYSTEM_NAME=iOS) + else () + set(platform tvOS) + set(system_args -DCMAKE_SYSTEM_NAME=tvOS) + endif () + if (sdk MATCHES "simulator$" OR sdk STREQUAL "macosx") + list(APPEND architectures x86_64) + endif () + + set(build_dir "${RAYLIB_APPLE_OUTPUT}/${sdk}") + set(install_dir "${build_dir}/install") + execute_process(COMMAND "${CMAKE_COMMAND}" -G "Unix Makefiles" + -S "${RAYLIB_APPLE_SOURCE}" -B "${build_dir}" + ${system_args} + "-DPLATFORM=${platform}" + "-DCMAKE_BUILD_TYPE=${RAYLIB_APPLE_CONFIG}" + "-DCMAKE_OSX_SYSROOT=${sdk}" + "-DCMAKE_OSX_DEPLOYMENT_TARGET=${deployment_target}" + "-DCMAKE_OSX_ARCHITECTURES=${architectures}" + -DCMAKE_INSTALL_LIBDIR=lib -DCMAKE_INSTALL_INCLUDEDIR=include + -DBUILD_EXAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DCUSTOMIZE_BUILD=ON + "-DSUPPORT_MODULE_RAUDIO=${RAYLIB_APPLE_AUDIO}" "-DSUPPORT_MODULE_RMODELS=${RAYLIB_APPLE_MODELS}" + COMMAND_ERROR_IS_FATAL ANY + ) + execute_process(COMMAND "${CMAKE_COMMAND}" --build "${build_dir}" --target raylib COMMAND_ERROR_IS_FATAL ANY) + execute_process(COMMAND "${CMAKE_COMMAND}" --install "${build_dir}" --prefix "${install_dir}" COMMAND_ERROR_IS_FATAL ANY) + list(APPEND xcframework_args -library "${install_dir}/lib/libraylib.a" -headers "${install_dir}/include") +endforeach () + +set(staging_dir "${RAYLIB_APPLE_OUTPUT}/staging") +set(output_dir "${RAYLIB_APPLE_OUTPUT}/raylib.xcframework") +file(REMOVE_RECURSE "${staging_dir}/raylib.xcframework") +execute_process(COMMAND "${XCODEBUILD}" -create-xcframework ${xcframework_args} + -output "${staging_dir}/raylib.xcframework" COMMAND_ERROR_IS_FATAL ANY +) +file(REMOVE_RECURSE "${output_dir}") +file(RENAME "${staging_dir}/raylib.xcframework" "${output_dir}") +message(STATUS "Created ${output_dir}") diff --git a/cmake/InstallConfigurations.cmake b/cmake/InstallConfigurations.cmake index 84caea2c003f..400656bb7196 100644 --- a/cmake/InstallConfigurations.cmake +++ b/cmake/InstallConfigurations.cmake @@ -11,6 +11,9 @@ if (NOT BUILD_SHARED_LIBS) include(LibraryPathToLinkerFlags) set(PKG_CONFIG_LIBS_PRIVATE ${GLFW_PKG_LIBS}) string(REPLACE ";" " " PKG_CONFIG_LIBS_PRIVATE "${PKG_CONFIG_LIBS_PRIVATE}") + foreach (framework IN LISTS RAYLIB_APPLE_FRAMEWORKS) + string(APPEND PKG_CONFIG_LIBS_PRIVATE " -framework ${framework}") + endforeach () elseif (BUILD_SHARED_LIBS) set(PKG_CONFIG_LIBS_EXTRA "") endif () diff --git a/cmake/LibraryConfigurations.cmake b/cmake/LibraryConfigurations.cmake index 262150be0d8a..6df781629f43 100644 --- a/cmake/LibraryConfigurations.cmake +++ b/cmake/LibraryConfigurations.cmake @@ -133,6 +133,24 @@ elseif (${PLATFORM} STREQUAL "Android") set(LIBS_PRIVATE log android EGL GLESv2 OpenSLES atomic c) set(LIBS_PUBLIC m) +elseif (PLATFORM MATCHES "^(iOS|tvOS)$") + if (NOT CMAKE_SYSTEM_NAME STREQUAL PLATFORM) + message(FATAL_ERROR "PLATFORM=${PLATFORM} requires the matching Apple SDK and CMAKE_SYSTEM_NAME.") + endif () + if (BUILD_SHARED_LIBS) + message(FATAL_ERROR "Build raylib as a static library for ${PLATFORM}.") + endif () + if (NOT OPENGL_VERSION MATCHES "^(OFF|ES 3\\.0)$") + message(FATAL_ERROR "${PLATFORM} uses OpenGL ES 3.0.") + endif () + + set(PLATFORM_CPP PLATFORM_APPLE_MOBILE) + set(GRAPHICS GRAPHICS_API_OPENGL_ES3) + set(RAYLIB_APPLE_FRAMEWORKS Foundation UIKit CoreGraphics QuartzCore OpenGLES GameController) + if (SUPPORT_MODULE_RAUDIO) + list(APPEND RAYLIB_APPLE_FRAMEWORKS AVFoundation AudioToolbox CoreFoundation) + endif () + elseif ("${PLATFORM}" STREQUAL "DRM") set(PLATFORM_CPP "PLATFORM_DRM") diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index f50f65ccd091..02dd947ae1b3 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -13,6 +13,15 @@ if (NOT DEFINED PLATFORM) set(PLATFORM "Desktop" CACHE STRING "Platform to build examples for") endif () +if (CMAKE_SYSTEM_NAME MATCHES "^(iOS|tvOS)$") + if (NOT TARGET raylib) + find_package(raylib REQUIRED) + endif () + include("${CMAKE_CURRENT_LIST_DIR}/../projects/CMake/AppleApp.cmake") + raylib_add_apple_app(core_basic_window "${CMAKE_CURRENT_SOURCE_DIR}/core/core_basic_window.c") + return() +endif () + # Directories that contain examples set(example_dirs audio diff --git a/projects/CMake/AppleApp.cmake b/projects/CMake/AppleApp.cmake new file mode 100644 index 000000000000..23044ee45983 --- /dev/null +++ b/projects/CMake/AppleApp.cmake @@ -0,0 +1,37 @@ +# Package an existing C game as a UIKit app +function(raylib_add_apple_app target game_source) + add_executable(${target} MACOSX_BUNDLE "${game_source}" "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/apple_entry.c") + set_property(SOURCE "${game_source}" APPEND PROPERTY COMPILE_DEFINITIONS main=RaylibGameMain) + target_link_libraries(${target} PRIVATE raylib) + + if (ARGC GREATER 2 AND IS_DIRECTORY "${ARGV2}") + file(GLOB_RECURSE app_resources CONFIGURE_DEPENDS "${ARGV2}/*") + foreach (resource IN LISTS app_resources) + file(RELATIVE_PATH relative_path "${ARGV2}" "${resource}") + get_filename_component(resource_dir "${relative_path}" DIRECTORY) + # A top-level Resources directory can be mistaken for a macOS bundle layout + set_source_files_properties("${resource}" PROPERTIES MACOSX_PACKAGE_LOCATION "Resources/raylib_resources/${resource_dir}") + endforeach () + target_sources(${target} PRIVATE ${app_resources}) + endif () + + string(REPLACE "_" "-" bundle_name "${target}") + if (CMAKE_SYSTEM_NAME STREQUAL "iOS") + set(device_family "1,2") + else () + set(device_family "3") + endif () + set_target_properties(${target} PROPERTIES + MACOSX_BUNDLE_INFO_PLIST "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/apple_info.plist" + MACOSX_BUNDLE_GUI_IDENTIFIER "org.raylib.${bundle_name}" + MACOSX_BUNDLE_BUNDLE_VERSION "1" + MACOSX_BUNDLE_SHORT_VERSION_STRING "1.0" + XCODE_ATTRIBUTE_TARGETED_DEVICE_FAMILY "${device_family}" + ) + if (CMAKE_GENERATOR STREQUAL "Xcode") + set_property(TARGET ${target} PROPERTY MACOSX_BUNDLE_GUI_IDENTIFIER "$(PRODUCT_BUNDLE_IDENTIFIER)") + if (NOT DEFINED CMAKE_XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER) + set_property(TARGET ${target} PROPERTY XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER "org.raylib.${bundle_name}") + endif () + endif () +endfunction() diff --git a/projects/CMake/CMakeLists.txt b/projects/CMake/CMakeLists.txt index 2124f6d5ff17..86481c2bb528 100644 --- a/projects/CMake/CMakeLists.txt +++ b/projects/CMake/CMakeLists.txt @@ -1,4 +1,10 @@ cmake_minimum_required(VERSION 3.11) # FetchContent is available in 3.11+ +if (CMAKE_SYSTEM_NAME MATCHES "^(iOS|tvOS)$") + cmake_minimum_required(VERSION 3.22) + if (NOT DEFINED CMAKE_OSX_DEPLOYMENT_TARGET) + set(CMAKE_OSX_DEPLOYMENT_TARGET "17.0" CACHE STRING "Minimum Apple OS version") + endif () +endif () project(example) # Generate compile_commands.json @@ -6,8 +12,13 @@ set(CMAKE_EXPORT_COMPILE_COMMANDS ON) # Dependencies set(RAYLIB_VERSION 6.0) -find_package(raylib ${RAYLIB_VERSION} QUIET) # QUIET or REQUIRED -if (NOT raylib_FOUND) # If there's none, fetch and build raylib +if (CMAKE_SYSTEM_NAME MATCHES "^(iOS|tvOS)$" AND + EXISTS "${CMAKE_CURRENT_LIST_DIR}/../../src/raylib_apple.h" AND NOT DEFINED raylib_DIR) + add_subdirectory(../.. raylib) +else () + find_package(raylib ${RAYLIB_VERSION} QUIET) # QUIET or REQUIRED +endif () +if (NOT TARGET raylib AND NOT raylib_FOUND) # If there's none, fetch and build raylib include(FetchContent) FetchContent_Declare( raylib @@ -22,6 +33,11 @@ if (NOT raylib_FOUND) # If there's none, fetch and build raylib endif() # Our Project +if (CMAKE_SYSTEM_NAME MATCHES "^(iOS|tvOS)$") + include("${CMAKE_CURRENT_LIST_DIR}/AppleApp.cmake") + raylib_add_apple_app(${PROJECT_NAME} "${CMAKE_CURRENT_SOURCE_DIR}/core_basic_window.c" "${CMAKE_CURRENT_SOURCE_DIR}/resources") + return() +endif () add_executable(${PROJECT_NAME} core_basic_window.c) #set(raylib_VERBOSE 1) diff --git a/projects/CMake/README.md b/projects/CMake/README.md index 01b5528c4823..2e0c3c7e685b 100644 --- a/projects/CMake/README.md +++ b/projects/CMake/README.md @@ -25,3 +25,48 @@ cd build emcmake cmake .. -DPLATFORM=Web -DCMAKE_BUILD_TYPE=Release -DCMAKE_EXECUTABLE_SUFFIX=".html" emmake make ``` + +### Apple platforms + +Apple builds require macOS, Xcode with the target SDK, and CMake 3.22 or newer. +iOS, iPadOS, and tvOS use UIKit and OpenGL ES 3.0. + +From the template directory, build the app for the iPhone or iPad simulator. + +```sh +cmake -S . -B build-ios -G Xcode -DCMAKE_SYSTEM_NAME=iOS \ + -DCMAKE_OSX_SYSROOT=iphonesimulator \ + -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=NO +cmake --build build-ios --config Debug --target example +``` + +The app is at `build-ios/Debug-iphonesimulator/example.app`. Open +`build-ios/example.xcodeproj` in Xcode and select a simulator to run it. + +Use a separate build directory for each SDK. For the Apple TV simulator, set +`CMAKE_SYSTEM_NAME=tvOS` and `CMAKE_OSX_SYSROOT=appletvsimulator`. For a physical +device, use `iphoneos` or `appletvos`, omit the flag that disables code signing, +and set your signing team and bundle identifier in Xcode. + +The template can use a raylib checkout or an installed static library for the +same SDK. Set `raylib_DIR` to the installed CMake package directory to select +that library. + +Replace the template's `core_basic_window.c` with a game using `int main(void)`. +Only that file is compiled with `main=RaylibGameMain`. The launcher calls +`RaylibRunAppleApp()` on the main thread and the game uses the normal raylib +window and drawing loop on the rendering thread. Keep graphics and input calls +on that thread and check `WindowShouldClose()` each frame. + +The template bundles files placed in its `resources/` directory as +`raylib_resources/`. The launcher exposes them at `resources/` relative to +the working directory. Write saves and screenshots elsewhere in the working +directory, which is Application Support on iOS and iPadOS and the system's +purgeable Caches directory on tvOS. +`InitWindow()` sets the logical canvas size. UIKit fits it to the drawable, whose +pixel dimensions are available through `GetRenderWidth()` and `GetRenderHeight()`. +iOS touch also drives the primary mouse button. On tvOS, the Siri Remote +directions, Select and Play/Pause map to arrow keys, Enter and Space. Back/Menu +follows system navigation. Extended gamepads supply axes and buttons. +Desktop window controls, clipboard, file drops, and gamepad mappings and +vibration are unavailable on the UIKit backend. diff --git a/projects/CMake/apple_entry.c b/projects/CMake/apple_entry.c new file mode 100644 index 000000000000..d73a51001464 --- /dev/null +++ b/projects/CMake/apple_entry.c @@ -0,0 +1,16 @@ +/********************************************************************************************** +* +* raylib - UIKit entry point for a C game +* +* This software is provided under the zlib/libpng license. See LICENSE for details. +* +**********************************************************************************************/ + +#include "raylib_apple.h" + +extern int RaylibGameMain(void); + +int main(int argc, char **argv) +{ + return RaylibRunAppleApp(argc, argv, RaylibGameMain); +} diff --git a/projects/CMake/apple_info.plist b/projects/CMake/apple_info.plist new file mode 100644 index 000000000000..40e862d182f3 --- /dev/null +++ b/projects/CMake/apple_info.plist @@ -0,0 +1,38 @@ + + + + + CFBundleExecutable + ${MACOSX_BUNDLE_EXECUTABLE_NAME} + CFBundleIdentifier + ${MACOSX_BUNDLE_GUI_IDENTIFIER} + CFBundleName + ${MACOSX_BUNDLE_EXECUTABLE_NAME} + CFBundlePackageType + APPL + CFBundleShortVersionString + ${MACOSX_BUNDLE_SHORT_VERSION_STRING} + CFBundleVersion + ${MACOSX_BUNDLE_BUNDLE_VERSION} + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + + UILaunchScreen + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 81bfe6f3053e..7b1028f63a11 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -47,7 +47,7 @@ if (NOT DEFINED SUPPORT_MODULE_RMODELS OR SUPPORT_MODULE_RMODELS) endif() # /cmake/GlfwImport.cmake handles the details around the inclusion of glfw -if (NOT ${PLATFORM} MATCHES "Web") +if (NOT PLATFORM MATCHES "Web|^(iOS|tvOS)$") include(GlfwImport) endif () @@ -56,6 +56,16 @@ endif () # Produces a variable LIBS_PRIVATE that will be used later include(LibraryConfigurations) +if (PLATFORM_CPP STREQUAL "PLATFORM_APPLE_MOBILE") + enable_language(OBJC) + list(APPEND raylib_sources platforms/rcore_apple.m) + list(APPEND raylib_public_headers raylib_apple.h) + set_source_files_properties(platforms/rcore_apple.m PROPERTIES COMPILE_OPTIONS "-fobjc-arc") + if (SUPPORT_MODULE_RAUDIO) + set_source_files_properties(raudio.c PROPERTIES LANGUAGE OBJC COMPILE_OPTIONS "-fno-objc-arc") + endif () +endif () + if (DEFINED SUPPORT_MODULE_RAUDIO AND NOT SUPPORT_MODULE_RAUDIO) MESSAGE(STATUS "Audio Backend: None (-DCUSTOMIZE_BUILD=ON -DSUPPORT_MODULE_RAUDIO=OFF)") else () @@ -64,6 +74,13 @@ endif () add_library(raylib ${raylib_sources} ${raylib_public_headers}) +if (PLATFORM_CPP STREQUAL "PLATFORM_APPLE_MOBILE") + target_compile_definitions(raylib PRIVATE GLES_SILENCE_DEPRECATION) + foreach (framework IN LISTS RAYLIB_APPLE_FRAMEWORKS) + target_link_options(raylib INTERFACE "SHELL:-framework ${framework}") + endforeach () +endif () + if (NOT BUILD_SHARED_LIBS) MESSAGE(STATUS "Building raylib static library") add_library(raylib_static ALIAS raylib) diff --git a/src/Makefile b/src/Makefile index fa9a3eee52fd..888e1ca4bb84 100644 --- a/src/Makefile +++ b/src/Makefile @@ -34,6 +34,8 @@ # - Embedded devices (with GPU) # > PLATFORM_ANDROID (native NDK): # - Android (ARM, ARM64) +# > PLATFORM_IOS / PLATFORM_TVOS (UIKit backend): +# - iOS, iPadOS and tvOS (device and simulator) # > PLATFORM_MEMORY # - Memory framebuffer output, using software renderer, no OS required # @@ -68,6 +70,11 @@ #------------------------------------------------------------------------------------------------ # Define target platform PLATFORM ?= PLATFORM_DESKTOP + +.DEFAULT_GOAL := all +include $(dir $(lastword $(MAKEFILE_LIST)))Makefile.Apple + +ifeq ($(filter $(PLATFORM),PLATFORM_IOS PLATFORM_TVOS),) ifeq ($(PLATFORM), PLATFORM_DESKTOP) TARGET_PLATFORM = PLATFORM_DESKTOP_GLFW else @@ -1002,3 +1009,5 @@ clean_shell_cmd: del lib$(RAYLIB_LIB_NAME)dll.a /s & \ del $(RAYLIB_LIB_NAME).dll /s & \ del raygui.c /s & \ + +endif # Non-UIKit platforms diff --git a/src/Makefile.Apple b/src/Makefile.Apple new file mode 100644 index 000000000000..27d094e0ef7f --- /dev/null +++ b/src/Makefile.Apple @@ -0,0 +1,64 @@ +# Apple SDK builds share the CMake platform configuration +CMAKE ?= cmake +APPLE_BUILD_DIR ?= ../build/apple +RAYLIB_LIBTYPE ?= STATIC +RAYLIB_BUILD_MODE ?= RELEASE +RAYLIB_MODULE_AUDIO ?= TRUE +RAYLIB_MODULE_MODELS ?= TRUE + +apple_build_type = $(if $(filter DEBUG,$(RAYLIB_BUILD_MODE)),Debug,Release) +apple_shared = $(if $(filter SHARED,$(RAYLIB_LIBTYPE)),ON,OFF) +apple_options = -DBUILD_EXAMPLES=OFF -DCMAKE_BUILD_TYPE=$(apple_build_type) \ + -DCUSTOMIZE_BUILD=ON -DSUPPORT_MODULE_RAUDIO=$(RAYLIB_MODULE_AUDIO) \ + -DSUPPORT_MODULE_RMODELS=$(RAYLIB_MODULE_MODELS) +apple_host_check = $(if $(filter Darwin,$(shell uname -s)),,$(error Apple SDK builds require macOS and Xcode)) + +.PHONY: apple-universal apple-xcframework +apple-universal: + $(apple_host_check) + $(CMAKE) -S .. -B "$(APPLE_BUILD_DIR)/macosx/$(apple_build_type)/$(RAYLIB_LIBTYPE)" $(apple_options) \ + -DPLATFORM=Desktop -DCMAKE_OSX_SYSROOT=macosx -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0 \ + "-DCMAKE_OSX_ARCHITECTURES=arm64;x86_64" -DBUILD_SHARED_LIBS=$(apple_shared) + $(CMAKE) --build "$(APPLE_BUILD_DIR)/macosx/$(apple_build_type)/$(RAYLIB_LIBTYPE)" --target raylib + +apple-xcframework: + $(apple_host_check) + $(CMAKE) -S .. -B "$(APPLE_BUILD_DIR)/xcframework/$(apple_build_type)" $(apple_options) -DPLATFORM=Desktop + $(CMAKE) --build "$(APPLE_BUILD_DIR)/xcframework/$(apple_build_type)" --target raylib_xcframework + +ifneq ($(filter $(PLATFORM),PLATFORM_IOS PLATFORM_TVOS),) + ifeq ($(PLATFORM),PLATFORM_IOS) + apple_platform = iOS + APPLE_SDK ?= iphoneos + apple_sdks = iphoneos iphonesimulator + else + apple_platform = tvOS + APPLE_SDK ?= appletvos + apple_sdks = appletvos appletvsimulator + endif + + APPLE_ARCHS ?= $(if $(filter %simulator,$(APPLE_SDK)),$(shell uname -m),arm64) + APPLE_DEPLOYMENT_TARGET ?= 17.0 + apple_sdk_build_dir = $(APPLE_BUILD_DIR)/$(APPLE_SDK)/$(apple_build_type) + apple_sdk_check = $(if $(filter $(APPLE_SDK),$(apple_sdks)),,$(error APPLE_SDK for $(PLATFORM) must be one of $(apple_sdks))) + + .PHONY: raylib + all: raylib + + raylib: + $(apple_host_check) + $(apple_sdk_check) + $(CMAKE) -S .. -B "$(apple_sdk_build_dir)" $(apple_options) \ + -DPLATFORM=$(apple_platform) -DCMAKE_OSX_SYSROOT=$(APPLE_SDK) \ + "-DCMAKE_OSX_ARCHITECTURES=$(APPLE_ARCHS)" -DCMAKE_OSX_DEPLOYMENT_TARGET=$(APPLE_DEPLOYMENT_TARGET) \ + -DBUILD_SHARED_LIBS=$(apple_shared) + $(CMAKE) --build "$(apple_sdk_build_dir)" --target raylib + ifdef RAYLIB_RELEASE_PATH + $(CMAKE) -E make_directory "$(RAYLIB_RELEASE_PATH)" + $(CMAKE) -E copy_if_different "$(apple_sdk_build_dir)/raylib/libraylib.a" "$(RAYLIB_RELEASE_PATH)/libraylib.a" + endif + + clean: + $(apple_sdk_check) + if [ -f "$(apple_sdk_build_dir)/CMakeCache.txt" ]; then $(CMAKE) --build "$(apple_sdk_build_dir)" --target clean; fi +endif diff --git a/src/platforms/rcore_apple.c b/src/platforms/rcore_apple.c new file mode 100644 index 000000000000..ceacc2694e36 --- /dev/null +++ b/src/platforms/rcore_apple.c @@ -0,0 +1,292 @@ +/********************************************************************************************** +* +* rcore_apple - Functions to manage the graphics device and inputs on iOS and tvOS +* +* This software is provided under the zlib/libpng license. See LICENSE for details. +* +**********************************************************************************************/ + +#include "rcore_apple.h" + +static AppleFrame appleFrame = { 0 }; +static bool appleNeedsFrame = false; + +static Size AppleViewportSize(void) +{ + return (Size){ CORE.Window.render.width - CORE.Window.renderOffset.x, + CORE.Window.render.height - CORE.Window.renderOffset.y }; +} + +static void AppleUpdateViewport(void) +{ + float scale = fminf((float)appleFrame.width/CORE.Window.screen.width, + (float)appleFrame.height/CORE.Window.screen.height); + int width = (int)fmaxf(1, roundf(CORE.Window.screen.width*scale)); + int height = (int)fmaxf(1, roundf(CORE.Window.screen.height*scale)); + CORE.Window.renderOffset = (Point){ appleFrame.width - width, appleFrame.height - height }; + CORE.Window.render = (Size){ appleFrame.width, appleFrame.height }; + CORE.Window.currentFbo = AppleViewportSize(); +} + +static void AppleUpdateTouch(AppleTouchEvent touch) +{ + int count = CORE.Input.Touch.pointCount; + int index = 0; + while ((index < count) && (CORE.Input.Touch.pointId[index] != touch.id)) index++; + if (index == count) + { + if ((touch.action != APPLE_TOUCH_DOWN) || (count >= MAX_TOUCH_POINTS)) return; + CORE.Input.Touch.pointId[index] = touch.id; + CORE.Input.Touch.currentTouchState[index] = 1; + count++; + CORE.Input.Touch.pointCount = count; + } + + Size viewport = AppleViewportSize(); + Vector2 position = { + (touch.x*appleFrame.width/appleFrame.pointWidth - CORE.Window.renderOffset.x/2)*CORE.Window.screen.width/viewport.width, + (touch.y*appleFrame.height/appleFrame.pointHeight - (CORE.Window.renderOffset.y + 1)/2)*CORE.Window.screen.height/viewport.height + }; + CORE.Input.Touch.position[index] = position; + if (index == 0) CORE.Input.Mouse.currentPosition = position; + +#if SUPPORT_GESTURES_SYSTEM + GestureEvent event = { .touchAction = touch.action, .pointCount = count }; + for (int i = 0; i < count; i++) + { + event.pointId[i] = CORE.Input.Touch.pointId[i]; + event.position[i] = (Vector2){ CORE.Input.Touch.position[i].x/CORE.Window.screen.width, + CORE.Input.Touch.position[i].y/CORE.Window.screen.height }; + } + ProcessGestureEvent(event); +#endif + + if ((touch.action == APPLE_TOUCH_UP) || (touch.action == APPLE_TOUCH_CANCEL)) + { + for (int i = index; i + 1 < count; i++) + { + CORE.Input.Touch.position[i] = CORE.Input.Touch.position[i + 1]; + CORE.Input.Touch.pointId[i] = CORE.Input.Touch.pointId[i + 1]; + } + CORE.Input.Touch.pointId[count - 1] = -1; + CORE.Input.Touch.currentTouchState[count - 1] = 0; + CORE.Input.Touch.pointCount--; + } + + CORE.Input.Mouse.currentButtonState[MOUSE_BUTTON_LEFT] = CORE.Input.Touch.pointCount > 0; + if (CORE.Input.Touch.pointCount > 0) CORE.Input.Mouse.currentPosition = CORE.Input.Touch.position[0]; +} + +void PollInputEvents(void) +{ +#if SUPPORT_GESTURES_SYSTEM + UpdateGestures(); +#endif + CORE.Input.Keyboard.keyPressedQueueCount = 0; + CORE.Input.Keyboard.charPressedQueueCount = 0; + CORE.Input.Gamepad.lastButtonPressed = GAMEPAD_BUTTON_UNKNOWN; + memcpy(CORE.Input.Keyboard.previousKeyState, CORE.Input.Keyboard.currentKeyState, sizeof(CORE.Input.Keyboard.currentKeyState)); + memcpy(CORE.Input.Mouse.previousButtonState, CORE.Input.Mouse.currentButtonState, sizeof(CORE.Input.Mouse.currentButtonState)); + memcpy(CORE.Input.Touch.previousTouchState, CORE.Input.Touch.currentTouchState, sizeof(CORE.Input.Touch.currentTouchState)); + memcpy(CORE.Input.Gamepad.previousButtonState, CORE.Input.Gamepad.currentButtonState, sizeof(CORE.Input.Gamepad.currentButtonState)); + CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition; + + if (appleFrame.resetInput) + { + memset(CORE.Input.Touch.currentTouchState, 0, sizeof(CORE.Input.Touch.currentTouchState)); + for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.pointId[i] = -1; + CORE.Input.Touch.pointCount = 0; + CORE.Input.Mouse.currentButtonState[MOUSE_BUTTON_LEFT] = 0; +#if SUPPORT_GESTURES_SYSTEM + ProcessGestureEvent((GestureEvent){ .touchAction = TOUCH_ACTION_CANCEL }); +#endif + appleFrame.resetInput = false; + } + + AppleTouchEvent touch = { 0 }; + while (AppleNextTouch(&touch)) AppleUpdateTouch(touch); + + const int remoteKeys[APPLE_REMOTE_KEYS] = { KEY_UP, KEY_RIGHT, KEY_DOWN, KEY_LEFT, KEY_ENTER, KEY_SPACE }; + for (int i = 0; i < APPLE_REMOTE_KEYS; i++) + { + int key = remoteKeys[i]; + CORE.Input.Keyboard.currentKeyState[key] = appleFrame.remoteKeys[i]; + if (CORE.Input.Keyboard.currentKeyState[key] && !CORE.Input.Keyboard.previousKeyState[key]) + { + if (CORE.Input.Keyboard.keyPressedQueueCount < MAX_KEY_PRESSED_QUEUE) + CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount++] = key; + if (key == CORE.Input.Keyboard.exitKey) CORE.Window.shouldClose = true; + } + } + + for (int i = 0; (i < APPLE_GAMEPADS) && (i < MAX_GAMEPADS); i++) + { + const AppleGamepad *gamepad = &appleFrame.gamepads[i]; + CORE.Input.Gamepad.ready[i] = gamepad->connected; + CORE.Input.Gamepad.axisCount[i] = gamepad->connected? ((APPLE_GAMEPAD_AXES < MAX_GAMEPAD_AXES)? APPLE_GAMEPAD_AXES : MAX_GAMEPAD_AXES) : 0; + snprintf(CORE.Input.Gamepad.name[i], MAX_GAMEPAD_NAME_LENGTH, "%s", gamepad->name); + for (int axis = 0; axis < CORE.Input.Gamepad.axisCount[i]; axis++) CORE.Input.Gamepad.axisState[i][axis] = gamepad->axes[axis]; + for (int button = 1; (button < APPLE_GAMEPAD_BUTTONS) && (button < MAX_GAMEPAD_BUTTONS); button++) + { + CORE.Input.Gamepad.currentButtonState[i][button] = gamepad->buttons[button]; + if (gamepad->buttons[button] && !CORE.Input.Gamepad.previousButtonState[i][button]) CORE.Input.Gamepad.lastButtonPressed = button; + } + } +} + +bool WindowShouldClose(void) +{ + if (!CORE.Window.ready || CORE.Window.shouldClose) return true; + if (appleNeedsFrame) + { + AppleFrame next = { 0 }; + if (!AppleWaitFrame(appleFrame.timestamp + CORE.Time.target, &next)) + { + CORE.Window.shouldClose = true; + return true; + } + + CORE.Window.resizedLastFrame = (next.width != appleFrame.width) || (next.height != appleFrame.height) || + (next.pointWidth != appleFrame.pointWidth) || (next.pointHeight != appleFrame.pointHeight); + CORE.Time.frame = next.interval; + appleFrame = next; + CORE.Window.display = (Size){ next.displayWidth, next.displayHeight }; + rlAppleDrawableFramebuffer = next.framebuffer; + if (CORE.Window.resizedLastFrame) + { + AppleUpdateViewport(); + SetupViewport(next.width, next.height); + rlSetFramebufferWidth(next.width); + rlSetFramebufferHeight(next.height); + } + appleNeedsFrame = false; +#if !SUPPORT_CUSTOM_FRAME_CONTROL + PollInputEvents(); +#endif + } + + return CORE.Window.shouldClose; +} + +void SwapScreenBuffer(void) +{ + ApplePresentFrame(); + appleNeedsFrame = true; +} + +double GetTime(void) +{ + return (double)(clock_gettime_nsec_np(CLOCK_MONOTONIC) - CORE.Time.base)*1e-9; +} + +int InitPlatform(void) +{ + if (!AppleWaitFrame(0.0, &appleFrame)) + { + TRACELOG(LOG_WARNING, "APPLE: Could not start an OpenGL ES frame. Launch the game with RaylibRunAppleApp()"); + return -1; + } + + if (CORE.Window.screen.width < 1) CORE.Window.screen.width = (int)appleFrame.pointWidth; + if (CORE.Window.screen.height < 1) CORE.Window.screen.height = (int)appleFrame.pointHeight; + CORE.Window.display = (Size){ appleFrame.displayWidth, appleFrame.displayHeight }; + CORE.Window.flags = FLAG_FULLSCREEN_MODE; + AppleUpdateViewport(); + rlAppleDrawableFramebuffer = appleFrame.framebuffer; + rlLoadExtensions(NULL); + CORE.Time.base = clock_gettime_nsec_np(CLOCK_MONOTONIC); + InitTimer(); + CORE.Storage.basePath = GetWorkingDirectory(); + CORE.Window.ready = true; + appleNeedsFrame = true; + for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.pointId[i] = -1; + return 0; +} + +void ClosePlatform(void) +{ + rlAppleDrawableFramebuffer = 0; + appleNeedsFrame = false; +} + +// UIKit and the system manage the native window +void ToggleFullscreen(void) { } +void ToggleBorderlessWindowed(void) { } +void MaximizeWindow(void) { } +void MinimizeWindow(void) { } +void RestoreWindow(void) { } +void SetWindowState(unsigned int flags) { (void)flags; } +void ClearWindowState(unsigned int flags) { (void)flags; } +void SetWindowIcon(Image image) { (void)image; } +void SetWindowIcons(Image *images, int count) { (void)images; (void)count; } +void SetWindowTitle(const char *title) { (void)title; } +void SetWindowPosition(int x, int y) { (void)x; (void)y; } +void SetWindowMonitor(int monitor) { (void)monitor; } +void SetWindowMinSize(int width, int height) { (void)width; (void)height; } +void SetWindowMaxSize(int width, int height) { (void)width; (void)height; } +void SetWindowOpacity(float opacity) { (void)opacity; } +void SetWindowFocused(void) { } +void *GetWindowHandle(void) { return appleFrame.window; } + +void SetWindowSize(int width, int height) +{ + if (!CORE.Window.ready || (width < 1) || (height < 1)) return; + CORE.Window.screen = (Size){ width, height }; + AppleUpdateViewport(); + SetupViewport(appleFrame.width, appleFrame.height); + CORE.Window.resizedLastFrame = true; +} + +int GetMonitorCount(void) { return CORE.Window.ready? 1 : 0; } +int GetCurrentMonitor(void) { return 0; } +Vector2 GetMonitorPosition(int monitor) { (void)monitor; return (Vector2){ 0 }; } +int GetMonitorWidth(int monitor) { return (monitor == 0)? appleFrame.displayWidth : 0; } +int GetMonitorHeight(int monitor) { return (monitor == 0)? appleFrame.displayHeight : 0; } +int GetMonitorPhysicalWidth(int monitor) { (void)monitor; return 0; } +int GetMonitorPhysicalHeight(int monitor) { (void)monitor; return 0; } +int GetMonitorRefreshRate(int monitor) { return (monitor == 0)? appleFrame.refreshRate : 0; } +const char *GetMonitorName(int monitor) { return (monitor == 0)? "Apple display" : ""; } +Vector2 GetWindowPosition(void) { return (Vector2){ 0 }; } + +Vector2 GetWindowScaleDPI(void) +{ + if (!CORE.Window.ready) return (Vector2){ 1.0f, 1.0f }; + Size viewport = AppleViewportSize(); + return (Vector2){ (float)viewport.width/CORE.Window.screen.width, (float)viewport.height/CORE.Window.screen.height }; +} + +void SetClipboardText(const char *text) { (void)text; } +const char *GetClipboardText(void) { return NULL; } +Image GetClipboardImage(void) { return (Image){ 0 }; } +void ShowCursor(void) { CORE.Input.Mouse.cursorHidden = false; } +void HideCursor(void) { CORE.Input.Mouse.cursorHidden = true; } +void EnableCursor(void) { ShowCursor(); } +void DisableCursor(void) { HideCursor(); } +void SetMouseCursor(int cursor) { (void)cursor; } + +void SetMousePosition(int x, int y) +{ + CORE.Input.Mouse.currentPosition = (Vector2){ x, y }; + CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition; +} + +const char *GetKeyName(int key) +{ + static char name[2] = { 0 }; + name[0] = ((key >= 32) && (key <= 126))? (char)key : '\0'; + return name; +} + +int SetGamepadMappings(const char *mappings) { (void)mappings; return 0; } +void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor, float duration) +{ + (void)gamepad; + (void)leftMotor; + (void)rightMotor; + (void)duration; +} + +void OpenURL(const char *url) +{ + if ((url != NULL) && ((strncmp(url, "https://", 8) == 0) || (strncmp(url, "http://", 7) == 0))) AppleOpenURL(url); +} diff --git a/src/platforms/rcore_apple.h b/src/platforms/rcore_apple.h new file mode 100644 index 000000000000..28ae25480e44 --- /dev/null +++ b/src/platforms/rcore_apple.h @@ -0,0 +1,67 @@ +/********************************************************************************************** +* +* rcore_apple - Interface between rcore and the UIKit application host +* +* This software is provided under the zlib/libpng license. See LICENSE for details. +* +**********************************************************************************************/ + +#ifndef RCORE_APPLE_H +#define RCORE_APPLE_H + +#include + +#include "raylib.h" + +enum { + APPLE_GAMEPADS = 4, + APPLE_GAMEPAD_BUTTONS = GAMEPAD_BUTTON_RIGHT_THUMB + 1, + APPLE_GAMEPAD_AXES = GAMEPAD_AXIS_RIGHT_TRIGGER + 1, + APPLE_REMOTE_KEYS = 6 +}; + +typedef struct AppleGamepad { + bool connected; + char name[128]; + bool buttons[APPLE_GAMEPAD_BUTTONS]; + float axes[APPLE_GAMEPAD_AXES]; +} AppleGamepad; + +typedef struct AppleFrame { + double timestamp; + double interval; + int width; + int height; + float pointWidth; + float pointHeight; + int displayWidth; + int displayHeight; + int refreshRate; + void *window; + unsigned int framebuffer; + bool resetInput; + bool remoteKeys[APPLE_REMOTE_KEYS]; + AppleGamepad gamepads[APPLE_GAMEPADS]; +} AppleFrame; + +typedef enum AppleTouchAction { + APPLE_TOUCH_UP = 0, + APPLE_TOUCH_DOWN, + APPLE_TOUCH_MOVE, + APPLE_TOUCH_CANCEL +} AppleTouchAction; + +typedef struct AppleTouchEvent { + AppleTouchAction action; + int id; + float x; + float y; +} AppleTouchEvent; + +// The following functions are called on the rendering thread +bool AppleWaitFrame(double minimumTimestamp, AppleFrame *frame); +void ApplePresentFrame(void); +bool AppleNextTouch(AppleTouchEvent *event); +void AppleOpenURL(const char *url); + +#endif // RCORE_APPLE_H diff --git a/src/platforms/rcore_apple.m b/src/platforms/rcore_apple.m new file mode 100644 index 000000000000..fe1a686a04f9 --- /dev/null +++ b/src/platforms/rcore_apple.m @@ -0,0 +1,556 @@ +/********************************************************************************************** +* +* rcore_apple - UIKit host for raylib's C game loop +* +* This software is provided under the zlib/libpng license. See LICENSE for details. +* +**********************************************************************************************/ + +#import +#import +#import +#import +#import +#include +#include +#include +#include + +#include "raylib_apple.h" +#include "rcore_apple.h" + +enum { APPLE_TOUCH_CAPACITY = 128 }; + +@interface RaylibAppleView : UIView +- (void)resetTouches; +@end + +@interface RaylibAppleHost : NSObject +- (void)attachView:(RaylibAppleView *)view; +- (void)detachView:(RaylibAppleView *)view; +- (void)setActive:(BOOL)active; +- (void)enqueueTouch:(AppleTouchEvent)touch; +- (BOOL)nextTouch:(AppleTouchEvent *)touch; +- (BOOL)waitFrame:(double)minimumTimestamp frame:(AppleFrame *)frame; +- (void)present; +@end + +static int (*appleGameMain)(void) = NULL; +static RaylibAppleHost *appleHost = nil; +static _Thread_local void *appleRenderHost = NULL; + +@implementation RaylibAppleView +{ + NSMapTable *_touches; + int _nextTouchId; +} + ++ (Class)layerClass { return [CAEAGLLayer class]; } + +- (void)resetTouches { [_touches removeAllObjects]; } + +#if TARGET_OS_IOS +- (void)forwardTouches:(NSSet *)touches action:(AppleTouchAction)action +{ + if (_touches == nil) _touches = [NSMapTable weakToStrongObjectsMapTable]; + for (UITouch *touch in touches) + { + NSNumber *identifier = [_touches objectForKey:touch]; + if (identifier == nil) + { + if (action != APPLE_TOUCH_DOWN) continue; + identifier = @(_nextTouchId); + _nextTouchId = (_nextTouchId == INT_MAX)? 0 : _nextTouchId + 1; + [_touches setObject:identifier forKey:touch]; + } + + CGPoint position = [touch locationInView:self]; + [appleHost enqueueTouch:(AppleTouchEvent){ .action = action, .id = identifier.intValue, .x = position.x, .y = position.y }]; + if ((action == APPLE_TOUCH_UP) || (action == APPLE_TOUCH_CANCEL)) [_touches removeObjectForKey:touch]; + } +} + +- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self forwardTouches:touches action:APPLE_TOUCH_DOWN]; } +- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [self forwardTouches:touches action:APPLE_TOUCH_MOVE]; } +- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [self forwardTouches:touches action:APPLE_TOUCH_UP]; } +- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { [self forwardTouches:touches action:APPLE_TOUCH_CANCEL]; } +#endif +@end + +@implementation RaylibAppleHost +{ + // The main thread owns the view and input producers. The condition guards the frame handoff + NSCondition *_condition; + RaylibAppleView *_view; + CADisplayLink *_link; + GCController *_controllers[APPLE_GAMEPADS]; + AppleFrame _pendingFrame; + CAEAGLLayer *_pendingLayer; + AppleTouchEvent _pendingTouches[APPLE_TOUCH_CAPACITY]; + int _pendingTouchCount; + BOOL _resetInput; + BOOL _active; + BOOL _hasFrame; + BOOL _parked; + BOOL _started; + BOOL _finished; + + // The rendering thread owns the OpenGL context and the current frame's input + CAEAGLLayer *_drawableLayer; + EAGLContext *_context; + GLuint _framebuffer; + GLuint _colorBuffer; + GLuint _depthBuffer; + int _allocatedWidth; + int _allocatedHeight; + int _drawableWidth; + int _drawableHeight; + double _lastTimestamp; + double _framePeriod; + double _nextDeadline; + AppleTouchEvent _frameTouches[APPLE_TOUCH_CAPACITY]; + int _touchIndex; + int _touchCount; +} + +- (instancetype)init +{ + self = [super init]; + if (self != nil) + { + _condition = [[NSCondition alloc] init]; + _parked = YES; + } + return self; +} + +- (void)attachView:(RaylibAppleView *)view +{ + [_condition lock]; + _view = view; + [_condition unlock]; + + CAEAGLLayer *layer = (CAEAGLLayer *)view.layer; + layer.opaque = YES; + layer.drawableProperties = @{ kEAGLDrawablePropertyColorFormat: kEAGLColorFormatRGBA8, + kEAGLDrawablePropertyRetainedBacking: @NO }; + _link = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayTick:)]; + _link.paused = YES; + [_link addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes]; +} + +- (void)detachView:(RaylibAppleView *)view +{ + if (_view != view) return; + [self setActive:NO]; + [_link invalidate]; + _link = nil; + + [_condition lock]; + _view = nil; + [_condition unlock]; +} + +- (void)setActive:(BOOL)active +{ + if (!active) [_view resetTouches]; + + [_condition lock]; + _active = active; + if (!active) + { + _hasFrame = NO; + _pendingLayer = nil; + _pendingTouchCount = 0; + _resetInput = YES; + [_condition broadcast]; + // Wait for the render thread to finish submitting GL commands before entering the background + while (!_parked && !_finished) [_condition wait]; + } + BOOL animate = active && !_finished; + [_condition unlock]; + + _link.paused = !animate; +} + +- (void)enqueueTouch:(AppleTouchEvent)touch +{ + [_condition lock]; + if (_active) + { + if (_pendingTouchCount == APPLE_TOUCH_CAPACITY) + { + _pendingTouchCount = 0; + _resetInput = YES; + } + _pendingTouches[_pendingTouchCount++] = touch; + } + [_condition unlock]; +} + +- (BOOL)nextTouch:(AppleTouchEvent *)touch +{ + if (_touchIndex >= _touchCount) return NO; + *touch = _frameTouches[_touchIndex++]; + return YES; +} + +- (void)sampleControllers:(AppleFrame *)frame +{ + NSArray *controllers = GCController.controllers; + for (int i = 0; i < APPLE_GAMEPADS; i++) + { + if ((_controllers[i] != nil) && ![controllers containsObject:_controllers[i]]) _controllers[i] = nil; + } + + for (GCController *controller in controllers) + { + GCExtendedGamepad *gamepad = controller.extendedGamepad; + if (gamepad == nil) + { +#if TARGET_OS_TV + GCMicroGamepad *remote = controller.microGamepad; + frame->remoteKeys[0] |= remote.dpad.up.isPressed; + frame->remoteKeys[1] |= remote.dpad.right.isPressed; + frame->remoteKeys[2] |= remote.dpad.down.isPressed; + frame->remoteKeys[3] |= remote.dpad.left.isPressed; + frame->remoteKeys[4] |= remote.buttonA.isPressed; + frame->remoteKeys[5] |= remote.buttonX.isPressed; +#endif + continue; + } + + int slot = 0; + while ((slot < APPLE_GAMEPADS) && (_controllers[slot] != controller)) slot++; + if (slot == APPLE_GAMEPADS) + { + slot = 0; + while ((slot < APPLE_GAMEPADS) && (_controllers[slot] != nil)) slot++; + if (slot == APPLE_GAMEPADS) continue; + _controllers[slot] = controller; + } + + AppleGamepad *input = &frame->gamepads[slot]; + *input = (AppleGamepad){ + .connected = true, + .buttons = { + [GAMEPAD_BUTTON_LEFT_FACE_UP] = gamepad.dpad.up.isPressed, + [GAMEPAD_BUTTON_LEFT_FACE_RIGHT] = gamepad.dpad.right.isPressed, + [GAMEPAD_BUTTON_LEFT_FACE_DOWN] = gamepad.dpad.down.isPressed, + [GAMEPAD_BUTTON_LEFT_FACE_LEFT] = gamepad.dpad.left.isPressed, + [GAMEPAD_BUTTON_RIGHT_FACE_UP] = gamepad.buttonY.isPressed, + [GAMEPAD_BUTTON_RIGHT_FACE_RIGHT] = gamepad.buttonB.isPressed, + [GAMEPAD_BUTTON_RIGHT_FACE_DOWN] = gamepad.buttonA.isPressed, + [GAMEPAD_BUTTON_RIGHT_FACE_LEFT] = gamepad.buttonX.isPressed, + [GAMEPAD_BUTTON_LEFT_TRIGGER_1] = gamepad.leftShoulder.isPressed, + [GAMEPAD_BUTTON_RIGHT_TRIGGER_1] = gamepad.rightShoulder.isPressed, + [GAMEPAD_BUTTON_LEFT_TRIGGER_2] = gamepad.leftTrigger.isPressed, + [GAMEPAD_BUTTON_RIGHT_TRIGGER_2] = gamepad.rightTrigger.isPressed, + [GAMEPAD_BUTTON_MIDDLE_LEFT] = gamepad.buttonOptions.isPressed, + [GAMEPAD_BUTTON_MIDDLE] = gamepad.buttonHome.isPressed, + [GAMEPAD_BUTTON_MIDDLE_RIGHT] = gamepad.buttonMenu.isPressed, + [GAMEPAD_BUTTON_LEFT_THUMB] = gamepad.leftThumbstickButton.isPressed, + [GAMEPAD_BUTTON_RIGHT_THUMB] = gamepad.rightThumbstickButton.isPressed + }, + .axes = { gamepad.leftThumbstick.xAxis.value, -gamepad.leftThumbstick.yAxis.value, + gamepad.rightThumbstick.xAxis.value, -gamepad.rightThumbstick.yAxis.value, + gamepad.leftTrigger.value*2.0f - 1.0f, gamepad.rightTrigger.value*2.0f - 1.0f } + }; + NSString *name = controller.vendorName ?: controller.productCategory; + snprintf(input->name, sizeof(input->name), "%s", name.UTF8String ?: "Apple game controller"); + } +} + +- (void)displayTick:(CADisplayLink *)link +{ + UIWindow *window = _view.window; + UIScreen *screen = window.windowScene.screen; + CGSize bounds = _view.bounds.size; + if ((screen == nil) || (bounds.width < 1) || (bounds.height < 1)) return; + + CGFloat scale = screen.scale; + CAEAGLLayer *layer = (CAEAGLLayer *)_view.layer; + if (_view.contentScaleFactor != scale) _view.contentScaleFactor = scale; + if (layer.contentsScale != scale) layer.contentsScale = scale; + AppleFrame frame = { + .timestamp = link.targetTimestamp, + .interval = link.targetTimestamp - link.timestamp, + .width = (int)lround(bounds.width*scale), + .height = (int)lround(bounds.height*scale), + .pointWidth = bounds.width, + .pointHeight = bounds.height, + .displayWidth = (int)screen.nativeBounds.size.width, + .displayHeight = (int)screen.nativeBounds.size.height, + .refreshRate = (int)screen.maximumFramesPerSecond, + .window = (__bridge void *)window + }; + [self sampleControllers:&frame]; + + [_condition lock]; + if (_active && !_finished) + { + _pendingFrame = frame; + _pendingLayer = layer; + _hasFrame = YES; + if (!_started) + { + _started = YES; + NSThread *thread = [[NSThread alloc] initWithBlock:^{ [self runGame]; }]; + thread.name = @"raylib rendering"; + [thread start]; + } + [_condition signal]; + } + [_condition unlock]; +} + +- (BOOL)bindDrawable:(CAEAGLLayer *)layer frame:(AppleFrame *)frame +{ + if (_context == nil) + { + _context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3]; + if ((_context == nil) || ![EAGLContext setCurrentContext:_context]) + { + _context = nil; + return NO; + } + + glGenFramebuffers(1, &_framebuffer); + glGenRenderbuffers(1, &_colorBuffer); + glGenRenderbuffers(1, &_depthBuffer); + } + glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer); + + if ((_drawableLayer != layer) || (_allocatedWidth != frame->width) || (_allocatedHeight != frame->height)) + { + glBindRenderbuffer(GL_RENDERBUFFER, _colorBuffer); + if (![_context renderbufferStorage:GL_RENDERBUFFER fromDrawable:layer]) return NO; + glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &_drawableWidth); + glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &_drawableHeight); + if ((_drawableWidth <= 0) || (_drawableHeight <= 0)) return NO; + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _colorBuffer); + + glBindRenderbuffer(GL_RENDERBUFFER, _depthBuffer); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, _drawableWidth, _drawableHeight); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthBuffer); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _depthBuffer); + if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) return NO; + + _drawableLayer = layer; + _allocatedWidth = frame->width; + _allocatedHeight = frame->height; + } + frame->width = _drawableWidth; + frame->height = _drawableHeight; + frame->framebuffer = _framebuffer; + return YES; +} + +- (BOOL)waitFrame:(double)minimumTimestamp frame:(AppleFrame *)frame +{ + @autoreleasepool + { + [_condition lock]; + while (true) + { + if (!_active && !_parked) + { + [_condition unlock]; + if (_context != nil) glFinish(); + _lastTimestamp = 0.0; + _nextDeadline = 0.0; + _allocatedWidth = 0; + [_condition lock]; + _parked = YES; + [_condition broadcast]; + } + + double period = (_lastTimestamp > 0.0)? fmax(0.0, minimumTimestamp - _lastTimestamp) : 0.0; + double deadline = (fabs(period - _framePeriod) < 0.000001)? _nextDeadline : minimumTimestamp; + if (period <= 0.0) deadline = 0.0; + if (_active && _hasFrame && (_pendingFrame.timestamp + _pendingFrame.interval*0.05 >= deadline)) + { + *frame = _pendingFrame; + if (_lastTimestamp > 0.0) frame->interval = frame->timestamp - _lastTimestamp; + _lastTimestamp = frame->timestamp; + _framePeriod = period; + _nextDeadline = (deadline + period > frame->timestamp)? deadline + period : frame->timestamp + period; + _hasFrame = NO; + _parked = NO; + + frame->resetInput = _resetInput; + _resetInput = NO; + _touchIndex = 0; + _touchCount = _pendingTouchCount; + memcpy(_frameTouches, _pendingTouches, _touchCount*sizeof(AppleTouchEvent)); + _pendingTouchCount = 0; + + CAEAGLLayer *layer = _pendingLayer; + [_condition unlock]; + return [self bindDrawable:layer frame:frame]; + } + + [_condition wait]; + } + } +} + +- (void)present +{ + [_condition lock]; + BOOL active = _active; + [_condition unlock]; + if (!active || (_context == nil)) return; + + glBindRenderbuffer(GL_RENDERBUFFER, _colorBuffer); + [_context presentRenderbuffer:GL_RENDERBUFFER]; +} + +- (BOOL)prepareWorkingDirectory +{ +#if TARGET_OS_TV + NSSearchPathDirectory directory = NSCachesDirectory; +#else + NSSearchPathDirectory directory = NSApplicationSupportDirectory; +#endif + NSFileManager *files = NSFileManager.defaultManager; + NSURL *work = [files URLForDirectory:directory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:NULL]; + if (work == nil) return NO; + + NSURL *resources = [NSBundle.mainBundle.resourceURL URLByAppendingPathComponent:@"raylib_resources" isDirectory:YES]; + if ([files fileExistsAtPath:resources.path]) + { + NSString *link = [work.path stringByAppendingPathComponent:@"resources"]; + NSString *destination = [files destinationOfSymbolicLinkAtPath:link error:NULL]; + if ((destination != nil) && ![destination isEqualToString:resources.path]) + { + if (![files removeItemAtPath:link error:NULL]) return NO; + } + if (![files fileExistsAtPath:link] && ![files createSymbolicLinkAtPath:link withDestinationPath:resources.path error:NULL]) return NO; + } + return chdir(work.fileSystemRepresentation) == 0; +} + +- (void)runGame +{ + @autoreleasepool + { + appleRenderHost = (__bridge void *)self; + int originalDirectory = open(".", O_RDONLY | O_CLOEXEC); + if ((originalDirectory >= 0) && [self prepareWorkingDirectory]) + { + int result = appleGameMain(); + if (IsWindowReady()) CloseWindow(); + if (result != 0) TraceLog(LOG_WARNING, "APPLE: Game returned %i", result); + } + else TraceLog(LOG_WARNING, "APPLE: Could not open the game working directory"); + + if (_context != nil) + { + glDeleteFramebuffers(1, &_framebuffer); + glDeleteRenderbuffers(1, &_colorBuffer); + glDeleteRenderbuffers(1, &_depthBuffer); + glFinish(); + [EAGLContext setCurrentContext:nil]; + _context = nil; + _drawableLayer = nil; + } + if (originalDirectory >= 0) + { + fchdir(originalDirectory); + close(originalDirectory); + } + appleRenderHost = NULL; + + [_condition lock]; + _finished = YES; + _parked = YES; + [_condition broadcast]; + [_condition unlock]; + dispatch_async(dispatch_get_main_queue(), ^{ self->_link.paused = YES; }); + } +} +@end + +@interface RaylibAppleSceneDelegate : UIResponder +@property (nonatomic, strong) UIWindow *window; +@end + +@implementation RaylibAppleSceneDelegate +- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)options +{ + UIWindow *window = [[UIWindow alloc] initWithWindowScene:(UIWindowScene *)scene]; + UIViewController *controller = [[UIViewController alloc] init]; + RaylibAppleView *view = [[RaylibAppleView alloc] initWithFrame:CGRectZero]; +#if TARGET_OS_IOS + view.multipleTouchEnabled = YES; +#endif + controller.view = view; + window.rootViewController = controller; + self.window = window; + [appleHost attachView:view]; + [window makeKeyAndVisible]; +} + +- (void)sceneDidBecomeActive:(UIScene *)scene { [appleHost setActive:YES]; } +- (void)sceneWillResignActive:(UIScene *)scene { [appleHost setActive:NO]; } + +- (void)sceneDidDisconnect:(UIScene *)scene +{ + [appleHost detachView:(RaylibAppleView *)self.window.rootViewController.view]; + self.window = nil; +} +@end + +@interface RaylibAppleAppDelegate : UIResponder +@end + +@implementation RaylibAppleAppDelegate +- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)session options:(UISceneConnectionOptions *)options +{ + UISceneConfiguration *config = [[UISceneConfiguration alloc] initWithName:nil sessionRole:session.role]; + config.sceneClass = [UIWindowScene class]; + config.delegateClass = [RaylibAppleSceneDelegate class]; + return config; +} +@end + +int RaylibRunAppleApp(int argc, char **argv, int (*gameMain)(void)) +{ + if ((gameMain == NULL) || !NSThread.isMainThread || (appleHost != nil)) return 1; + @autoreleasepool + { + appleGameMain = gameMain; + appleHost = [[RaylibAppleHost alloc] init]; + return UIApplicationMain(argc, argv, nil, NSStringFromClass([RaylibAppleAppDelegate class])); + } +} + +bool AppleWaitFrame(double minimumTimestamp, AppleFrame *frame) +{ + return [(__bridge RaylibAppleHost *)appleRenderHost waitFrame:minimumTimestamp frame:frame]; +} + +void ApplePresentFrame(void) +{ + [(__bridge RaylibAppleHost *)appleRenderHost present]; +} + +bool AppleNextTouch(AppleTouchEvent *touch) +{ + return [(__bridge RaylibAppleHost *)appleRenderHost nextTouch:touch]; +} + +void AppleOpenURL(const char *url) +{ +#if TARGET_OS_IOS + NSString *text = [NSString stringWithUTF8String:url]; + if (text == nil) return; + dispatch_async(dispatch_get_main_queue(), ^{ + NSURL *link = [NSURL URLWithString:text]; + if (link != nil) [UIApplication.sharedApplication openURL:link options:@{} completionHandler:nil]; + }); +#else + (void)url; +#endif +} diff --git a/src/raylib_apple.h b/src/raylib_apple.h new file mode 100644 index 000000000000..b8e4dc2927fb --- /dev/null +++ b/src/raylib_apple.h @@ -0,0 +1,32 @@ +/********************************************************************************************** +* +* raylib - UIKit application entry point for iOS, iPadOS and tvOS +* +* This software is provided under the zlib/libpng license. See LICENSE for details. +* +**********************************************************************************************/ + +#ifndef RAYLIB_APPLE_H +#define RAYLIB_APPLE_H + +#include "raylib.h" + +#if defined(__APPLE__) + #include + #if (TARGET_OS_IOS || TARGET_OS_TV) && !TARGET_OS_MACCATALYST + +#if defined(__cplusplus) +extern "C" { +#endif + +// Start UIKit from main() and run the C game on its rendering thread +RLAPI int RaylibRunAppleApp(int argc, char **argv, int (*gameMain)(void)); + +#if defined(__cplusplus) +} +#endif + + #endif +#endif + +#endif // RAYLIB_APPLE_H diff --git a/src/rcore.c b/src/rcore.c index cf90f225e33f..326303db9c5a 100644 --- a/src/rcore.c +++ b/src/rcore.c @@ -534,6 +534,8 @@ const char *TextFormat(const char *text, ...); // Formatting of text with variab #include "platforms/rcore_drm.c" #elif defined(PLATFORM_ANDROID) #include "platforms/rcore_android.c" +#elif defined(PLATFORM_APPLE_MOBILE) + #include "platforms/rcore_apple.c" #elif defined(PLATFORM_MEMORY) #include "platforms/rcore_memory.c" #else @@ -608,6 +610,8 @@ void InitWindow(int width, int height, const char *title) TRACELOG(LOG_INFO, "Platform backend: NATIVE DRM"); #elif defined(PLATFORM_ANDROID) TRACELOG(LOG_INFO, "Platform backend: ANDROID"); +#elif defined(PLATFORM_APPLE_MOBILE) + TRACELOG(LOG_INFO, "Platform backend: Apple UIKit"); #elif defined(PLATFORM_MEMORY) TRACELOG(LOG_INFO, "Platform backend: MEMORY (No OS)"); #else @@ -890,7 +894,7 @@ void EndDrawing(void) if (automationEventRecording) RecordAutomationEvent(); // Event recording #endif -#if !SUPPORT_CUSTOM_FRAME_CONTROL +#if !SUPPORT_CUSTOM_FRAME_CONTROL && !defined(PLATFORM_APPLE_MOBILE) SwapScreenBuffer(); // Copy back buffer to front buffer (screen) // Frame time control system @@ -923,6 +927,9 @@ void EndDrawing(void) } #endif +#if defined(PLATFORM_APPLE_MOBILE) && !SUPPORT_CUSTOM_FRAME_CONTROL + SwapScreenBuffer(); +#endif CORE.Time.frameCounter++; } @@ -1049,8 +1056,14 @@ void EndTextureMode(void) rlMultMatrixf(MatrixToFloat(CORE.Window.screenScale)); // Apply screen scaling if required // Reset current fbo to screen size +#if defined(PLATFORM_APPLE_MOBILE) + CORE.Window.currentFbo = AppleViewportSize(); + rlSetFramebufferWidth(CORE.Window.render.width); + rlSetFramebufferHeight(CORE.Window.render.height); +#else CORE.Window.currentFbo.width = CORE.Window.render.width; CORE.Window.currentFbo.height = CORE.Window.render.height; +#endif CORE.Window.usingFbo = false; } @@ -1087,7 +1100,16 @@ void BeginScissorMode(int x, int y, int width, int height) rlEnableScissorTest(); -#if defined(__APPLE__) +#if defined(PLATFORM_APPLE_MOBILE) + if (!CORE.Window.usingFbo) + { + Vector2 scale = GetWindowScaleDPI(); + Size viewport = AppleViewportSize(); + rlScissor(CORE.Window.renderOffset.x/2 + (int)(x*scale.x), + CORE.Window.renderOffset.y/2 + (int)(viewport.height - (y + height)*scale.y), + (int)(width*scale.x), (int)(height*scale.y)); + } +#elif defined(__APPLE__) if (!CORE.Window.usingFbo) { Vector2 scale = { 1.0f, 1.0f }; @@ -1825,9 +1847,19 @@ void TakeScreenshot(const char *fileName) // Security check to (partially) avoid malicious code if (strchr(fileName, '\'') != NULL) { TRACELOG(LOG_WARNING, "SYSTEM: Provided fileName could be potentially malicious, avoid [\'] character"); return; } +#if defined(PLATFORM_APPLE_MOBILE) + GLint previousReadFramebuffer = 0; + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &previousReadFramebuffer); + glBindFramebuffer(GL_READ_FRAMEBUFFER, rlAppleDrawableFramebuffer); +#endif + unsigned char *imgData = rlReadScreenPixels(CORE.Window.render.width, CORE.Window.render.height); Image image = { imgData, CORE.Window.render.width, CORE.Window.render.height, 1, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 }; +#if defined(PLATFORM_APPLE_MOBILE) + glBindFramebuffer(GL_READ_FRAMEBUFFER, (unsigned int)previousReadFramebuffer); +#endif + char path[MAX_FILEPATH_LENGTH] = { 0 }; if (!IsPathAbsolute(fileName)) snprintf(path, MAX_FILEPATH_LENGTH, "%s", TextFormat("%s/%s", CORE.Storage.basePath, fileName)); else snprintf(path, MAX_FILEPATH_LENGTH, "%s", fileName); @@ -4348,15 +4380,24 @@ void SetupViewport(int width, int height) CORE.Window.render.width = width; CORE.Window.render.height = height; +#if defined(PLATFORM_APPLE_MOBILE) + Size viewport = AppleViewportSize(); + rlViewport(CORE.Window.renderOffset.x/2, CORE.Window.renderOffset.y/2, viewport.width, viewport.height); +#else // Set viewport width and height rlViewport(CORE.Window.renderOffset.x/2, CORE.Window.renderOffset.y/2, CORE.Window.render.width, CORE.Window.render.height); +#endif rlMatrixMode(RL_PROJECTION); // Switch to projection matrix rlLoadIdentity(); // Reset current matrix (projection) // Set orthographic projection to current framebuffer size // NOTE: Configured top-left corner as (0, 0) +#if defined(PLATFORM_APPLE_MOBILE) + rlOrtho(0.0f, (float)CORE.Window.screen.width, (float)CORE.Window.screen.height, 0.0f, 0.0f, 1.0f); +#else rlOrtho(0.0f, (float)CORE.Window.render.width, (float)CORE.Window.render.height, 0.0f, 0.0f, 1.0f); +#endif rlMatrixMode(RL_MODELVIEW); // Switch back to modelview matrix rlLoadIdentity(); // Reset current matrix (modelview) diff --git a/src/rlgl.h b/src/rlgl.h index e322c576701f..34f5c969c3b5 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -880,9 +880,28 @@ RLAPI void rlLoadDrawQuad(void); // Load and draw a quad #endif #if defined(GRAPHICS_API_OPENGL_ES3) - #include // OpenGL ES 3.0 library - #define GL_GLEXT_PROTOTYPES - #include // OpenGL ES 2.0 extensions library + #if defined(PLATFORM_APPLE_MOBILE) + #include + #include + + // Apple's ES3 headers omit these extension aliases for core texture formats. + #ifndef GL_RED_EXT + #define GL_RED_EXT GL_RED + #endif + #ifndef GL_R32F_EXT + #define GL_R32F_EXT GL_R32F + #endif + #ifndef GL_RGB32F_EXT + #define GL_RGB32F_EXT GL_RGB32F + #endif + #ifndef GL_RGBA32F_EXT + #define GL_RGBA32F_EXT GL_RGBA32F + #endif + #else + #include // OpenGL ES 3.0 library + #define GL_GLEXT_PROTOTYPES + #include // OpenGL ES 2.0 extensions library + #endif #elif defined(GRAPHICS_API_OPENGL_ES2) // NOTE: OpenGL ES 2.0 can be enabled on Desktop platforms, // in that case, functions are loaded from a custom glad for OpenGL ES 2.0 @@ -1836,11 +1855,19 @@ void rlDisableShader(void) #endif } +// The UIKit drawable is backed by an application-owned framebuffer. +#if defined(PLATFORM_APPLE_MOBILE) +static unsigned int rlAppleDrawableFramebuffer = 0; +#define RLGL_DEFAULT_FRAMEBUFFER rlAppleDrawableFramebuffer +#else +#define RLGL_DEFAULT_FRAMEBUFFER 0 +#endif + // Enable rendering to texture (fbo) void rlEnableFramebuffer(unsigned int id) { #if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_SOFTWARE)) - glBindFramebuffer(GL_FRAMEBUFFER, id); + glBindFramebuffer(GL_FRAMEBUFFER, (id != 0)? id : RLGL_DEFAULT_FRAMEBUFFER); #endif } @@ -1851,14 +1878,14 @@ unsigned int rlGetActiveFramebuffer(void) #if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_SOFTWARE)) glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &fboId); #endif - return fboId; + return (fboId == (GLint)RLGL_DEFAULT_FRAMEBUFFER)? 0 : (unsigned int)fboId; } // Disable rendering to texture void rlDisableFramebuffer(void) { #if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_SOFTWARE)) - glBindFramebuffer(GL_FRAMEBUFFER, 0); + glBindFramebuffer(GL_FRAMEBUFFER, RLGL_DEFAULT_FRAMEBUFFER); #endif } @@ -1874,7 +1901,7 @@ void rlBlitFramebuffer(int srcX, int srcY, int srcWidth, int srcHeight, int dstX void rlBindFramebuffer(unsigned int target, unsigned int framebuffer) { #if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_SOFTWARE)) - glBindFramebuffer(target, framebuffer); + glBindFramebuffer(target, (framebuffer != 0)? framebuffer : RLGL_DEFAULT_FRAMEBUFFER); #endif } @@ -3415,7 +3442,7 @@ unsigned int rlLoadTextureDepth(int width, int height, bool useRenderBuffer) // Possible formats: GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT32 and GL_DEPTH_COMPONENT32F unsigned int glInternalFormat = GL_DEPTH_COMPONENT; -#if defined(GRAPHICS_API_OPENGL_ES2) +#if defined(GRAPHICS_API_OPENGL_ES2) && !defined(GRAPHICS_API_OPENGL_ES3) // WARNING: WebGL platform requires unsized internal format definition (GL_DEPTH_COMPONENT) // while other platforms using OpenGL ES 2.0 require/support sized internal formats depending on the GPU capabilities if (!RLGL.ExtSupported.texDepthWebGL || useRenderBuffer) @@ -3742,6 +3769,13 @@ void *rlReadTexturePixels(unsigned int id, int width, int height, int format) // 2 - Create an fbo, activate it, render quad with texture, glReadPixels() // Using Option 1, care for texture format on retrieval // NOTE: This behaviour could be conditioned by graphic driver... +#if defined(PLATFORM_APPLE_MOBILE) + GLint previousDrawFramebuffer = 0; + GLint previousReadFramebuffer = 0; + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &previousDrawFramebuffer); + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &previousReadFramebuffer); +#endif + unsigned int fboId = rlLoadFramebuffer(); glBindFramebuffer(GL_FRAMEBUFFER, fboId); @@ -3762,10 +3796,15 @@ void *rlReadTexturePixels(unsigned int id, int width, int height, int format) glReadPixels(0, 0, width, height, glFormat, glType, pixels); #endif - glBindFramebuffer(GL_FRAMEBUFFER, 0); + glBindFramebuffer(GL_FRAMEBUFFER, RLGL_DEFAULT_FRAMEBUFFER); // Clean up temporal fbo rlUnloadFramebuffer(fboId); + +#if defined(PLATFORM_APPLE_MOBILE) + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, (unsigned int)previousDrawFramebuffer); + glBindFramebuffer(GL_READ_FRAMEBUFFER, (unsigned int)previousReadFramebuffer); +#endif #endif return pixels; @@ -3841,7 +3880,7 @@ unsigned int rlLoadFramebuffer(void) #if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_SOFTWARE)) glGenFramebuffers(1, &fboId); // Create the framebuffer object - glBindFramebuffer(GL_FRAMEBUFFER, 0); // Unbind any framebuffer + glBindFramebuffer(GL_FRAMEBUFFER, RLGL_DEFAULT_FRAMEBUFFER); // Unbind any framebuffer #endif return fboId; @@ -3882,7 +3921,7 @@ void rlFramebufferAttach(unsigned int id, unsigned int texId, int attachType, in default: break; } - glBindFramebuffer(GL_FRAMEBUFFER, 0); + glBindFramebuffer(GL_FRAMEBUFFER, RLGL_DEFAULT_FRAMEBUFFER); #endif } @@ -3910,7 +3949,7 @@ bool rlFramebufferComplete(unsigned int id) } } - glBindFramebuffer(GL_FRAMEBUFFER, 0); + glBindFramebuffer(GL_FRAMEBUFFER, RLGL_DEFAULT_FRAMEBUFFER); result = (status == GL_FRAMEBUFFER_COMPLETE); #endif @@ -3940,7 +3979,7 @@ void rlUnloadFramebuffer(unsigned int id) // NOTE: If a texture object is deleted while its image is attached to the *currently bound* framebuffer, // the texture image is automatically detached from the currently bound framebuffer - glBindFramebuffer(GL_FRAMEBUFFER, 0); + glBindFramebuffer(GL_FRAMEBUFFER, RLGL_DEFAULT_FRAMEBUFFER); glDeleteFramebuffers(1, &id); TRACELOG(RL_LOG_INFO, "FBO: [ID %i] Unloaded framebuffer from VRAM (GPU)", id);