diff --git a/.gitignore b/.gitignore index c3f9c0803..8cebb37a5 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,12 @@ compile_commands.json *~ *.log memcards/ + +# Android/Gradle +.gradle/ +local.properties +**/.cxx/ +*.apk +*.aar +captures/ +*.keystore diff --git a/CMakeLists.txt b/CMakeLists.txt index 8a9b03714..95d94ce4e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,11 @@ cmake_minimum_required(VERSION 3.20) project(CTR-Native C) include(CheckCCompilerFlag) -set(CTR_NATIVE_VERSION "0.1.0-beta.7.1") +file(STRINGS "${CMAKE_SOURCE_DIR}/VERSION" CTR_NATIVE_VERSION LIMIT_COUNT 1) +string(STRIP "${CTR_NATIVE_VERSION}" CTR_NATIVE_VERSION) +if(CTR_NATIVE_VERSION STREQUAL "") + message(FATAL_ERROR "VERSION must contain the CTR Native release version.") +endif() if(NOT CMAKE_SIZEOF_VOID_P EQUAL 4) message(FATAL_ERROR @@ -18,9 +22,11 @@ if(CMAKE_C_COMPILER_ID STREQUAL "MSVC" OR CMAKE_C_SIMULATE_ID STREQUAL "MSVC") set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") endif() -set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE NEVER) -set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER) -set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER) +if(NOT ANDROID) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER) +endif() execute_process( COMMAND git rev-parse --short=12 HEAD @@ -60,8 +66,13 @@ function(ctr_native_add_label_warning_if_supported target warning flag_check) endfunction() # SDL3 -set(SDL_SHARED OFF CACHE BOOL "" FORCE) -set(SDL_STATIC ON CACHE BOOL "" FORCE) +if(ANDROID) + set(SDL_SHARED ON CACHE BOOL "" FORCE) + set(SDL_STATIC OFF CACHE BOOL "" FORCE) +else() + set(SDL_SHARED OFF CACHE BOOL "" FORCE) + set(SDL_STATIC ON CACHE BOOL "" FORCE) +endif() set(SDL_TEST_LIBRARY OFF CACHE BOOL "" FORCE) set(SDL_TESTS OFF CACHE BOOL "" FORCE) set(SDL_EXAMPLES OFF CACHE BOOL "" FORCE) @@ -74,7 +85,7 @@ set(SDL_DIALOG OFF CACHE BOOL "" FORCE) set(SDL_TRAY OFF CACHE BOOL "" FORCE) set(SDL_POWER OFF CACHE BOOL "" FORCE) set(SDL_VULKAN OFF CACHE BOOL "" FORCE) -set(SDL_OPENGLES OFF CACHE BOOL "" FORCE) +set(SDL_OPENGLES ${ANDROID} CACHE BOOL "" FORCE) set(SDL_OFFSCREEN OFF CACHE BOOL "" FORCE) set(SDL_SNDIO OFF CACHE BOOL "" FORCE) set(SDL_SNDIO_SHARED OFF CACHE BOOL "" FORCE) @@ -83,13 +94,19 @@ set(SDL_X11_XTEST OFF CACHE BOOL "" FORCE) add_subdirectory(externals/SDL) # CTR Native -add_executable(ctr_native main.c) +if(ANDROID) + add_library(ctr_native SHARED main.c) +else() + add_executable(ctr_native main.c) +endif() set_target_properties(ctr_native PROPERTIES C_STANDARD 17 C_STANDARD_REQUIRED ON C_EXTENSIONS OFF - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" ) +if(NOT ANDROID) + set_target_properties(ctr_native PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") +endif() target_include_directories(ctr_native PRIVATE ${CMAKE_SOURCE_DIR}/include) target_compile_definitions(ctr_native PRIVATE CTR_NATIVE @@ -111,7 +128,6 @@ if(CTR_NATIVE_MSVC_FRONTEND) ) else() target_compile_options(ctr_native PRIVATE - -msse -Wenum-conversion -Wenum-compare -Wswitch-enum @@ -121,6 +137,18 @@ else() $<$:-g> ) + if(ANDROID) + # ARM defaults to unsigned plain char. Retail MIPS and the supported PC + # targets use signed char in game-owned fields and comparisons. + target_compile_options(ctr_native PRIVATE -fsigned-char) + + # Two ASM-verified retail calls use static nonliteral format strings. + # Keep those game call sites exact while satisfying the NDK defaults. + target_compile_options(ctr_native PRIVATE -Wno-format-security) + else() + target_compile_options(ctr_native PRIVATE -msse) + endif() + if(CMAKE_C_COMPILER_ID STREQUAL "GNU") target_compile_options(ctr_native PRIVATE -Wall -Wextra -Wstrict-aliasing=2) ctr_native_add_label_warning_if_supported(ctr_native -Wfree-labels CTR_HAS_WFREE_LABELS) @@ -129,6 +157,9 @@ else() endif() endif() target_link_libraries(ctr_native SDL3::SDL3) +if(ANDROID) + target_link_libraries(ctr_native log) +endif() if(CMAKE_C_COMPILER_ID STREQUAL "GNU") target_link_options(ctr_native PRIVATE -static-libgcc) endif() @@ -137,7 +168,7 @@ if(MINGW) endif() include(CTest) -if(BUILD_TESTING) +if(BUILD_TESTING AND NOT ANDROID) add_test(NAME ctr_native_version COMMAND $ --version) set_tests_properties(ctr_native_version PROPERTIES PASS_REGULAR_EXPRESSION "^CTR Native ") endif() diff --git a/README.md b/README.md index 4d7bb0599..cf1de43b1 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,6 @@ # CTR Native -A native PC port of Crash Team Racing (PS1, 1999), built on top of the [CTR-ModSDK](https://github.com/CTR-tools/CTR-ModSDK) decompilation project. - -## Philosophy - -- **No byte budget.** Game source lives in `game/` as our own copies. Edit freely. -- **No PSX toolchain.** Targets Windows and Linux with SDL3. No MIPS compiler needed. -- **Clean platform layer.** `main.c` owns process startup; host details stay in `platform/native_*`. -- **No build system nonsense.** Just `build.bat` / `build.sh`. -- **Fully static build.** Single executable, zero dependencies. SDL3 is compiled from vendored source and linked statically. +A native port of Crash Team Racing (PS1, 1999), built on top of the [CTR-ModSDK](https://github.com/CTR-tools/CTR-ModSDK) decompilation project. ## Directory Layout @@ -19,8 +11,10 @@ ctr_native/ build-msvc.bat Windows build (MSVC x86) build.bat Windows build (MinGW i686) build.sh Linux build + android/ Android Gradle project and launcher CMakePresets.json Shared CLion/command-line CMake configurations README.md This file + README_ANDROID.md Android build and setup guide game/ Our copies of all decompiled game source (943 files) game_unity.h Ordered unity include chain for all game source files include/ Project headers (structs, globals, declarations, platform facade) @@ -60,6 +54,11 @@ sudo apt install gcc-multilib sudo apt install libx11-dev libxext-dev libgl1-mesa-dev libasound2-dev libudev-dev libdbus-1-dev ``` +### Android + +See [README_ANDROID.md](README_ANDROID.md). Android currently builds 32-bit +`armeabi-v7a` and `x86` APKs and requires an OpenGL ES 3 capable device. + ## Building ``` @@ -69,6 +68,13 @@ chmod +x build.sh ./build.sh # Linux ``` +For Android: + +``` +cd android +./gradlew assembleDebug +``` + The shared CMake presets can also be used directly or selected as CLion CMake profiles: ``` @@ -84,6 +90,7 @@ Output: - MSVC: `build-msvc-x86/Release/ctr_native.exe` - MinGW: `build/ctr_native.exe` - Linux: `build/ctr_native` +- Android: `android/app/build/outputs/apk/debug/app-debug.apk` ### Clean build @@ -100,6 +107,9 @@ rm -rf build/ # Linux: delete cached libraries ## Running +Android users select their own raw NTSC-U BIN through the in-app setup screen; +the app copies it into app-owned storage. See [README_ANDROID.md](README_ANDROID.md). + ### Normal Setup If you downloaded a release build, you only need two things for normal play: @@ -197,4 +207,5 @@ main.c (entrypoint) - [CTR-ModSDK](https://github.com/CTR-tools/CTR-ModSDK) — the decompilation project this is built on - [PsyCross](https://github.com/OpenDriver2/PsyCross) — original PS1 compatibility code from which parts of CTR Native's owned platform layer and PsyQ facade headers are derived - [SDL3](https://github.com/libsdl-org/SDL) — cross-platform multimedia +- [Simon Butt](https://github.com/Simon358) — initial Android port contribution - Crash Team Racing is a trademark of Sony Computer Entertainment / Naughty Dog diff --git a/README_ANDROID.md b/README_ANDROID.md new file mode 100644 index 000000000..09bfe2c85 --- /dev/null +++ b/README_ANDROID.md @@ -0,0 +1,78 @@ +# CTR Native on Android + +CTR Native builds as a sideloadable Android APK. The Android target preserves +the same game code and PS1 VRAM model as the desktop builds while using SDL3 and +OpenGL ES 3 at the host boundary. + +## Requirements + +- JDK 17 +- Android SDK Platform 35 +- Android NDK `27.0.12077973` +- CMake 3.22.1 from the Android SDK +- An OpenGL ES 3 capable Android device +- An Android-recognized gamepad; there is currently no touch-control overlay +- Your own NTSC-U retail CTR disc image in raw MODE2/2352 BIN format + +The current native memory model is 32-bit, so the APK contains `armeabi-v7a` +and `x86` libraries only. It is intended for direct sideloading, not Play Store +distribution. + +## Build + +Install the required SDK, NDK, and CMake versions through Android Studio's SDK +Manager, then run: + +```sh +cd android +./gradlew assembleDebug +``` + +The Gradle wrapper downloads the pinned Gradle version automatically. From the +repository root, the APK is written to: + +```text +android/app/build/outputs/apk/debug/app-debug.apk +``` + +While still in the `android/` directory, install or update it with: + +```sh +adb install -r app/build/outputs/apk/debug/app-debug.apk +``` + +You can also open the `android/` directory as a project in Android Studio. + +## Disc Setup + +On first launch, select your own NTSC-U retail CTR BIN through the setup screen. +The image must be a single-track raw MODE2/2352 BIN whose data track begins at +byte zero. Cooked 2048-byte ISO images do not contain the XA/STR sector data the +game needs. + +The launcher validates the raw sector layout, streams the selected image into +app-owned storage, and starts the game. It does not modify the selected file and +does not request broad storage or network permission. Android removes the +imported copy when the app is uninstalled, so it must be selected again after a +fresh install. + +## Controllers + +CTR Native uses SDL's Gamepad API and supports up to four recognized gamepads. +Bluetooth controllers and USB controllers connected through USB host/OTG can +both work when Android exposes them as standard gamepad devices. Pair or connect +the controller through Android; the app does not scan for Bluetooth devices and +does not require Bluetooth or USB permission. + +SDL includes mappings for many common controllers. A device exposed only as an +unknown joystick, without an SDL gamepad mapping, will not be opened by the +current input path. Controllers can be connected or removed while the game is +running. + +## Logs + +Native output is mirrored to Logcat with the `CTR-Native` tag: + +```sh +adb logcat -s CTR-Native +``` diff --git a/VERSION b/VERSION new file mode 100644 index 000000000..584376d0a --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.1.0-beta.7.1 diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 000000000..b0b090603 --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,66 @@ +plugins { + id 'com.android.application' +} + +def ctrNativeVersion = rootProject.file('../VERSION').getText('UTF-8').trim() + +android { + namespace 'com.ctrnative' + compileSdk 35 + ndkVersion '27.0.12077973' + + defaultConfig { + applicationId 'com.ctrnative' + minSdk 21 + targetSdk 35 + versionCode 701 + versionName ctrNativeVersion + + ndk { + abiFilters 'armeabi-v7a', 'x86' + } + + externalNativeBuild { + cmake { + arguments '-DANDROID_STL=c++_static' + } + } + } + + buildTypes { + release { + minifyEnabled false + } + } + + externalNativeBuild { + cmake { + path file('../../CMakeLists.txt') + version '3.22.1' + } + } + + sourceSets { + main { + java.srcDirs = [ + 'src/main/java', + '../../externals/SDL/android-project/app/src/main/java' + ] + res.srcDirs = [ + 'src/main/res', + '../../externals/SDL/android-project/app/src/main/res' + ] + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + + lint { + // AGP 8.7 intentionally caps this project at API 35. + disable 'OldTargetApi' + lintConfig file('lint.xml') + } +} diff --git a/android/app/lint.xml b/android/app/lint.xml new file mode 100644 index 000000000..84f7e11c6 --- /dev/null +++ b/android/app/lint.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..87da36a01 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/com/ctrnative/CTRNativeActivity.java b/android/app/src/main/java/com/ctrnative/CTRNativeActivity.java new file mode 100644 index 000000000..685e86046 --- /dev/null +++ b/android/app/src/main/java/com/ctrnative/CTRNativeActivity.java @@ -0,0 +1,10 @@ +package com.ctrnative; + +import org.libsdl.app.SDLActivity; + +public final class CTRNativeActivity extends SDLActivity { + @Override + protected String[] getLibraries() { + return new String[] {"SDL3", "ctr_native"}; + } +} diff --git a/android/app/src/main/java/com/ctrnative/CTRNativeLauncherActivity.java b/android/app/src/main/java/com/ctrnative/CTRNativeLauncherActivity.java new file mode 100644 index 000000000..468a24c7f --- /dev/null +++ b/android/app/src/main/java/com/ctrnative/CTRNativeLauncherActivity.java @@ -0,0 +1,297 @@ +package com.ctrnative; + +import android.app.Activity; +import android.content.ContentResolver; +import android.content.Intent; +import android.database.Cursor; +import android.graphics.Color; +import android.net.Uri; +import android.os.Bundle; +import android.provider.OpenableColumns; +import android.view.Gravity; +import android.view.View; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.TextView; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.RandomAccessFile; + +public final class CTRNativeLauncherActivity extends Activity { + private static final int REQUEST_DISC_IMAGE = 1001; + private static final int COPY_BUFFER_SIZE = 1024 * 1024; + private static final int RAW_SECTOR_SIZE = 2352; + private static final int PVD_LBA = 16; + private static final int FORM1_DATA_OFFSET = 24; + + private Button importButton; + private ProgressBar importProgress; + private TextView statusText; + private boolean importInProgress; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + File discImage = getImportedDiscImage(); + if (isRetailDiscImage(discImage)) { + launchGame(); + return; + } + + buildImportView(discImage.exists()); + } + + private File getStorageRoot() { + File root = getExternalFilesDir(null); + return (root != null) ? root : getFilesDir(); + } + + private File getImportedDiscImage() { + return new File(new File(getStorageRoot(), "assets"), "ctr-u.bin"); + } + + private int dp(int value) { + return Math.round(value * getResources().getDisplayMetrics().density); + } + + private TextView makeText(String text, float size, int color) { + TextView view = new TextView(this); + view.setText(text); + view.setTextColor(color); + view.setTextSize(size); + view.setGravity(Gravity.CENTER); + view.setMaxWidth(dp(720)); + return view; + } + + private void buildImportView(boolean invalidExistingImage) { + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setGravity(Gravity.CENTER); + root.setPadding(dp(32), dp(24), dp(32), dp(24)); + root.setBackgroundColor(Color.rgb(18, 18, 18)); + + TextView title = makeText(getString(R.string.setup_title), 30.0f, Color.WHITE); + LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.WRAP_CONTENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + titleParams.bottomMargin = dp(18); + root.addView(title, titleParams); + + TextView instructions = makeText( + getString(R.string.setup_instructions), + 17.0f, + Color.LTGRAY); + LinearLayout.LayoutParams instructionsParams = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.WRAP_CONTENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + instructionsParams.bottomMargin = dp(20); + root.addView(instructions, instructionsParams); + + statusText = makeText( + getString(invalidExistingImage ? R.string.setup_invalid_disc : R.string.setup_no_disc), + 15.0f, + invalidExistingImage ? Color.rgb(255, 160, 122) : Color.LTGRAY); + LinearLayout.LayoutParams statusParams = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.WRAP_CONTENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + statusParams.bottomMargin = dp(16); + root.addView(statusText, statusParams); + + importProgress = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal); + importProgress.setMax(100); + importProgress.setVisibility(View.GONE); + LinearLayout.LayoutParams progressParams = new LinearLayout.LayoutParams(dp(420), dp(12)); + progressParams.bottomMargin = dp(18); + root.addView(importProgress, progressParams); + + importButton = new Button(this); + importButton.setText(invalidExistingImage ? R.string.setup_replace_disc : R.string.setup_select_disc); + importButton.setOnClickListener(view -> selectDiscImage()); + root.addView(importButton); + + setContentView(root); + } + + private void selectDiscImage() { + if (importInProgress) { + return; + } + + Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + intent.setType("*/*"); + intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + startActivityForResult(intent, REQUEST_DISC_IMAGE); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + + if ((requestCode != REQUEST_DISC_IMAGE) || (resultCode != RESULT_OK) || (data == null) || (data.getData() == null)) { + return; + } + + importDiscImage(data.getData()); + } + + private long querySourceSize(Uri uri) { + try (Cursor cursor = getContentResolver().query(uri, new String[] {OpenableColumns.SIZE}, null, null, null)) { + if ((cursor != null) && cursor.moveToFirst() && !cursor.isNull(0)) { + return cursor.getLong(0); + } + } catch (Exception exception) { + return -1; + } + + return -1; + } + + private void importDiscImage(Uri uri) { + importInProgress = true; + importButton.setEnabled(false); + + long sourceSize = querySourceSize(uri); + importProgress.setIndeterminate(sourceSize <= 0); + importProgress.setProgress(0); + importProgress.setVisibility(View.VISIBLE); + statusText.setText(R.string.setup_importing_disc); + statusText.setTextColor(Color.LTGRAY); + + Thread worker = new Thread(() -> copyDiscImage(uri, sourceSize), "CTR disc import"); + worker.start(); + } + + private void copyDiscImage(Uri uri, long sourceSize) { + File destination = getImportedDiscImage(); + File assetDirectory = destination.getParentFile(); + File temporary = new File(assetDirectory, "ctr-u.bin.importing"); + + try { + if (!assetDirectory.isDirectory() && !assetDirectory.mkdirs()) { + throw new IOException("Could not create the app asset directory"); + } + + if (temporary.exists() && !temporary.delete()) { + throw new IOException("Could not replace an incomplete import"); + } + + ContentResolver resolver = getContentResolver(); + try (InputStream input = resolver.openInputStream(uri); + FileOutputStream output = new FileOutputStream(temporary)) { + if (input == null) { + throw new IOException("The selected file could not be opened"); + } + + byte[] buffer = new byte[COPY_BUFFER_SIZE]; + long copied = 0; + int lastProgress = -1; + int read; + + while ((read = input.read(buffer)) != -1) { + if (read == 0) { + continue; + } + + output.write(buffer, 0, read); + copied += read; + + if (sourceSize > 0) { + int progress = (int)Math.min(100, copied * 100 / sourceSize); + if (progress != lastProgress) { + lastProgress = progress; + int displayProgress = progress; + runOnUiThread(() -> updateImportProgress(displayProgress)); + } + } + } + + output.getFD().sync(); + } + + if (!isRetailDiscImage(temporary)) { + throw new IOException("The selected file is not a supported raw NTSC-U BIN image"); + } + + if (destination.exists() && !destination.delete()) { + throw new IOException("Could not replace the previous disc image"); + } + + if (!temporary.renameTo(destination)) { + throw new IOException("Could not finish the disc image import"); + } + + runOnUiThread(() -> { + statusText.setText(R.string.setup_starting_game); + launchGame(); + }); + } catch (Exception exception) { + temporary.delete(); + String detail = exception.getMessage(); + if ((detail == null) || detail.isEmpty()) { + detail = exception.getClass().getSimpleName(); + } + + String error = detail; + runOnUiThread(() -> showImportError(error)); + } + } + + private void updateImportProgress(int progress) { + importProgress.setProgress(progress); + statusText.setText(getString(R.string.setup_import_progress, progress)); + } + + private void showImportError(String error) { + importInProgress = false; + importProgress.setVisibility(View.GONE); + importButton.setEnabled(true); + importButton.setText(R.string.setup_select_another_disc); + statusText.setText(error); + statusText.setTextColor(Color.rgb(255, 160, 122)); + } + + private boolean isRetailDiscImage(File image) { + if (!image.isFile() || (image.length() < (long)(PVD_LBA + 1) * RAW_SECTOR_SIZE) || ((image.length() % RAW_SECTOR_SIZE) != 0)) { + return false; + } + + byte[] sector = new byte[RAW_SECTOR_SIZE]; + try (RandomAccessFile file = new RandomAccessFile(image, "r")) { + file.seek((long)PVD_LBA * RAW_SECTOR_SIZE); + file.readFully(sector); + } catch (IOException exception) { + return false; + } + + if ((sector[0] != 0) || (sector[11] != 0) || (sector[15] != 2)) { + return false; + } + + for (int i = 1; i < 11; i++) { + if ((sector[i] & 0xff) != 0xff) { + return false; + } + } + + return (sector[FORM1_DATA_OFFSET] == 1) + && (sector[FORM1_DATA_OFFSET + 1] == 'C') + && (sector[FORM1_DATA_OFFSET + 2] == 'D') + && (sector[FORM1_DATA_OFFSET + 3] == '0') + && (sector[FORM1_DATA_OFFSET + 4] == '0') + && (sector[FORM1_DATA_OFFSET + 5] == '1') + && (sector[FORM1_DATA_OFFSET + 6] == 1); + } + + private void launchGame() { + Intent intent = new Intent(this, CTRNativeActivity.class); + startActivity(intent); + finish(); + } +} diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 000000000..542662f2a --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,13 @@ + + + CTR Native + Select your NTSC-U raw BIN disc image. It will be copied into CTR Native\'s app storage; the original file is not changed. + No disc image has been imported. + The imported disc image is not a supported raw NTSC-U image. + Select disc image + Replace disc image + Importing disc image… + Importing disc image: %1$d%% + Starting CTR Native… + Select another disc image + diff --git a/android/app/src/main/res/xml/data_extraction_rules.xml b/android/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 000000000..04e7f7f23 --- /dev/null +++ b/android/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 000000000..5b7ccba7c --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,3 @@ +plugins { + id 'com.android.application' version '8.7.3' apply false +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 000000000..1b32ab274 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8 +org.gradle.parallel=true +android.useAndroidX=false diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..2c3521197 Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..68e8816d7 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionSha256Sum=d725d707bfabd4dfdc958c624003b3c80accc03f7037b5122c4b1d0ef15cecab +distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100755 index 000000000..f5feea6d6 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 000000000..9d21a2183 --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 000000000..7e0c8a8c6 --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,18 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = 'CTRNative' +include ':app' diff --git a/main.c b/main.c index 04600c0c8..250ad1c9b 100644 --- a/main.c +++ b/main.c @@ -1,5 +1,7 @@ #define _CRT_SECURE_NO_WARNINGS +#if !defined(__ANDROID__) #define SDL_MAIN_HANDLED +#endif #include #include @@ -141,33 +143,39 @@ int main(int argc, char *argv[]) { if (NativeArg_IsVersion(argv[argIndex])) { - printf("CTR Native %s (%s)\n", CTR_NATIVE_VERSION, CTR_NATIVE_BUILD_ID); + Platform_Log("CTR Native %s (%s)\n", CTR_NATIVE_VERSION, CTR_NATIVE_BUILD_ID); return 0; } } - printf("[CTR Native] Starting...\n"); - fflush(stdout); + Platform_Log("[CTR Native] Starting...\n"); - const char *sdlBasePath = SDL_GetBasePath(); - printf("[CTR Native] SDL base path: %s\n", sdlBasePath ? sdlBasePath : "(null)"); - fflush(stdout); + const char *sdlBasePath; +#if defined(__ANDROID__) + sdlBasePath = SDL_GetAndroidExternalStoragePath(); + if (sdlBasePath == NULL) + { + sdlBasePath = SDL_GetAndroidInternalStoragePath(); + } +#else + sdlBasePath = SDL_GetBasePath(); +#endif + Platform_Log("[CTR Native] SDL base path: %s\n", sdlBasePath ? sdlBasePath : "(null)"); if (!NativeAssets_Init(sdlBasePath)) { - fprintf(stderr, "[CTR Native] Failed to initialize asset paths.\n"); + Platform_LogError("[CTR Native] Failed to initialize asset paths.\n"); return NativeConsole_Return(1); } - printf("[CTR Native] Version: %s (%s)\n", CTR_NATIVE_VERSION, CTR_NATIVE_BUILD_ID); - printf("[CTR Native] Built with: " CC "\n"); - printf("[CTR Native] Base: %s\n", NativeAssets_GetBaseDir()); - printf("[CTR Native] Assets: %s\n", NativeAssets_GetAssetDir()); - fflush(stdout); + Platform_Log("[CTR Native] Version: %s (%s)\n", CTR_NATIVE_VERSION, CTR_NATIVE_BUILD_ID); + Platform_Log("[CTR Native] Built with: " CC "\n"); + Platform_Log("[CTR Native] Base: %s\n", NativeAssets_GetBaseDir()); + Platform_Log("[CTR Native] Assets: %s\n", NativeAssets_GetAssetDir()); if (chdir(NativeAssets_GetBaseDir()) != 0) { - fprintf(stderr, "[CTR Native] Failed to enter base directory: %s\n", NativeAssets_GetBaseDir()); + Platform_LogError("[CTR Native] Failed to enter base directory: %s\n", NativeAssets_GetBaseDir()); return NativeConsole_Return(1); } @@ -184,10 +192,10 @@ int main(int argc, char *argv[]) #endif #ifdef USE_16BY9 - printf("[CTR Native] Widescreen\n"); + Platform_Log("[CTR Native] Widescreen\n"); Platform_Init("Crash Team Racing", 1280, 720); #else - printf("[CTR Native] 4:3\n"); + Platform_Log("[CTR Native] 4:3\n"); Platform_Init("Crash Team Racing", 800, 600); #endif diff --git a/platform/native_audio.c b/platform/native_audio.c index f9313c862..e78d6e058 100644 --- a/platform/native_audio.c +++ b/platform/native_audio.c @@ -1650,7 +1650,7 @@ internal int NativeAudio_RenderFramesNoLock(s16 *out, int frameCount); internal void NativeAudio_SelectDriverHint(void) { -#if defined(__linux__) +#if defined(__linux__) && !defined(__ANDROID__) if (SDL_GetHint(SDL_HINT_AUDIO_DRIVER) == NULL) { // NOTE(aalhendi): Keep native Linux playback on the SDL3 drivers that diff --git a/platform/native_glad.c b/platform/native_glad.c index 878d5b0cd..548fbc309 100644 --- a/platform/native_glad.c +++ b/platform/native_glad.c @@ -1976,6 +1976,23 @@ internal void load_GL_ES_VERSION_2_0(GLADloadproc load) glad_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)load("glVertexAttribPointer"); glad_glViewport = (PFNGLVIEWPORTPROC)load("glViewport"); } + +// NOTE(aalhendi): CTR's GLES 3 renderer only needs these core entry points +// beyond the generated GLES 2 table. Keep this narrow instead of regenerating +// GLAD and changing the desktop loader surface. +internal void load_GL_ES_VERSION_3_0_Ctr(GLADloadproc load) +{ + if (GLVersion.major < 3) + { + return; + } + + glad_glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)load("glBindVertexArray"); + glad_glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)load("glDeleteVertexArrays"); + glad_glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)load("glGenVertexArrays"); + glad_glGetStringi = (PFNGLGETSTRINGIPROC)load("glGetStringi"); +} + internal int find_extensionsGLES2(void) { if (!get_exts()) @@ -2026,7 +2043,12 @@ internal void find_coreGLES2(void) max_loaded_major = major; max_loaded_minor = minor; GLAD_GL_ES_VERSION_2_0 = (major == 2 && minor >= 0) || major > 2; - if (GLVersion.major > 2 || (GLVersion.major >= 2 && GLVersion.minor >= 0)) + if (GLVersion.major >= 3) + { + max_loaded_major = 3; + max_loaded_minor = 0; + } + else if (GLVersion.major >= 2) { max_loaded_major = 2; max_loaded_minor = 0; @@ -2048,6 +2070,11 @@ int gladLoadGLES2Loader(GLADloadproc load) } find_coreGLES2(); load_GL_ES_VERSION_2_0(load); + load_GL_ES_VERSION_3_0_Ctr(load); + if ((GLVersion.major >= 3) && (glad_glGetStringi == NULL)) + { + return 0; + } if (!find_extensionsGLES2()) { diff --git a/platform/native_log.c b/platform/native_log.c index e04862126..e2a6554f2 100644 --- a/platform/native_log.c +++ b/platform/native_log.c @@ -6,6 +6,17 @@ #include #include +#ifdef __ANDROID__ +#include +#define NATIVE_LOG_INFO ANDROID_LOG_INFO +#define NATIVE_LOG_WARN ANDROID_LOG_WARN +#define NATIVE_LOG_ERROR ANDROID_LOG_ERROR +#else +#define NATIVE_LOG_INFO 0 +#define NATIVE_LOG_WARN 0 +#define NATIVE_LOG_ERROR 0 +#endif + #ifdef _WIN32 #include "platform/native_win32.h" #endif @@ -13,10 +24,16 @@ global_variable FILE *s_logStream = NULL; global_variable char s_logPath[512]; // TODO(aalhendi): yeah this is an issue waiting to happen. w/e -internal void Platform_LogWrite(FILE *consoleStream, const char *text) +internal void Platform_LogWrite(FILE *consoleStream, int priority, const char *text) { FILE *stream = (consoleStream != NULL) ? consoleStream : stdout; +#ifdef __ANDROID__ + __android_log_write(priority, "CTR-Native", text); +#else + (void)priority; +#endif + #ifdef _WIN32 OutputDebugStringA(text); #endif @@ -30,7 +47,7 @@ internal void Platform_LogWrite(FILE *consoleStream, const char *text) } } -internal void Platform_LogV(FILE *consoleStream, const char *fmt, va_list args) +internal void Platform_LogV(FILE *consoleStream, int priority, const char *fmt, va_list args) { char text[4096]; int written = vsnprintf(text, sizeof(text), fmt, args); @@ -41,7 +58,7 @@ internal void Platform_LogV(FILE *consoleStream, const char *fmt, va_list args) } text[sizeof(text) - 1] = '\0'; - Platform_LogWrite(consoleStream, text); + Platform_LogWrite(consoleStream, priority, text); } int Platform_LogSetPath(const char *path) @@ -122,7 +139,7 @@ void Platform_Log(const char *fmt, ...) va_list args; va_start(args, fmt); - Platform_LogV(stdout, fmt, args); + Platform_LogV(stdout, NATIVE_LOG_INFO, fmt, args); va_end(args); } @@ -131,7 +148,7 @@ void Platform_LogWarn(const char *fmt, ...) va_list args; va_start(args, fmt); - Platform_LogV(stdout, fmt, args); + Platform_LogV(stdout, NATIVE_LOG_WARN, fmt, args); va_end(args); } @@ -140,6 +157,6 @@ void Platform_LogError(const char *fmt, ...) va_list args; va_start(args, fmt); - Platform_LogV(stderr, fmt, args); + Platform_LogV(stderr, NATIVE_LOG_ERROR, fmt, args); va_end(args); } diff --git a/platform/native_renderer.c b/platform/native_renderer.c index ada38200e..b4adc9cd5 100644 --- a/platform/native_renderer.c +++ b/platform/native_renderer.c @@ -15,6 +15,7 @@ #include "platform/native_renderer.h" #include +#include #include #ifdef _WIN32 @@ -96,6 +97,11 @@ struct NativeVramState global_variable struct NativeVramState s_vram; +#if defined(__ANDROID__) +global_variable u8 *s_vramReadbackScratch; +global_variable size_t s_vramReadbackScratchCapacity; +#endif + struct NativeRenderTarget { TextureID texture; @@ -173,12 +179,26 @@ global_variable GLuint s_glVramFramebuffer; internal int NativeRenderer_InitialiseGLContext(char *windowName, int fullscreen) { SDL_WindowFlags windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE; + int major_version = 3; +#if defined(__ANDROID__) + int minor_version = 0; + int profile = SDL_GL_CONTEXT_PROFILE_ES; +#else + int minor_version = 3; + int profile = SDL_GL_CONTEXT_PROFILE_CORE; +#endif if (fullscreen) { windowFlags |= SDL_WINDOW_FULLSCREEN; } +#if defined(__ANDROID__) + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major_version); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minor_version); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, profile); +#endif + g_window = SDL_CreateWindow(windowName, g_windowWidth, g_windowHeight, windowFlags); if (g_window == NULL) @@ -187,10 +207,6 @@ internal int NativeRenderer_InitialiseGLContext(char *windowName, int fullscreen return 0; } - int major_version = 3; - int minor_version = 3; - int profile = SDL_GL_CONTEXT_PROFILE_CORE; - // find best OpenGL version do { @@ -209,7 +225,11 @@ internal int NativeRenderer_InitialiseGLContext(char *windowName, int fullscreen if (minor_version == -1) { +#if defined(__ANDROID__) + NATIVE_RENDERER_ERROR("%s\n", "Failed to initialise - OpenGL ES 3.0 is not supported."); +#else NATIVE_RENDERER_ERROR("%s\n", "Failed to initialise - OpenGL 3.x is not supported. Please update video drivers."); +#endif return 0; } @@ -218,13 +238,25 @@ internal int NativeRenderer_InitialiseGLContext(char *windowName, int fullscreen internal int NativeRenderer_InitialiseGLExt(void) { +#if defined(__ANDROID__) + const int err = gladLoadGLES2Loader((GLADloadproc)SDL_GL_GetProcAddress); +#else GLenum err = gladLoadGL(); +#endif if (err == 0) { return 0; } +#if defined(__ANDROID__) + if ((glBindVertexArray == NULL) || (glDeleteVertexArrays == NULL) || (glGenVertexArrays == NULL)) + { + NATIVE_RENDERER_ERROR("%s\n", "OpenGL ES 3.0 vertex-array functions are unavailable."); + return 0; + } +#endif + const char *rend = (const char *)glGetString(GL_RENDERER); const char *vendor = (const char *)glGetString(GL_VENDOR); NATIVE_RENDERER_LOG("*Video adapter: %s by %s\n", rend, vendor); @@ -282,6 +314,12 @@ void NativeRenderer_Shutdown(void) glDeleteProgram(s_presentVramShader); glDeleteVertexArrays(1, &s_vramQuadVAO); glDeleteBuffers(1, &s_vramQuadVBO); + +#if defined(__ANDROID__) + free(s_vramReadbackScratch); + s_vramReadbackScratch = NULL; + s_vramReadbackScratchCapacity = 0; +#endif } #if defined(CTR_INTERNAL) @@ -295,10 +333,10 @@ internal void NativeRenderer_ResolveGpuMeasurements(b32 waitForResults) continue; } - GLint available = 0; + GLuint available = 0; if (!waitForResults) { - glGetQueryObjectiv(query->id, GL_QUERY_RESULT_AVAILABLE, &available); + glGetQueryObjectuiv(query->id, GL_QUERY_RESULT_AVAILABLE, &available); if (!available) { continue; @@ -920,6 +958,21 @@ internal int NativeRenderer_Shader_CheckProgramStatus(GLuint program) internal ShaderID NativeRenderer_Shader_Compile(const char *source, bool isPsxShader) { +#if defined(__ANDROID__) + const char *GLSL_HEADER_VERT = "#version 300 es\n" + "precision highp int;\n" + "precision highp float;\n" + "#define varying out\n" + "#define attribute in\n" + "#define texture2D texture\n"; + + const char *GLSL_HEADER_FRAG = "#version 300 es\n" + "precision highp int;\n" + "precision highp float;\n" + "#define varying in\n" + "#define texture2D texture\n" + "out vec4 fragColor;\n"; +#else const char *GLSL_HEADER_VERT = " #version 140\n" " precision lowp int;\n" " precision highp float;\n" @@ -933,6 +986,7 @@ internal ShaderID NativeRenderer_Shader_Compile(const char *source, bool isPsxSh " #define varying in\n" " #define texture2D texture\n" " out vec4 fragColor;\n"; +#endif char extra_vs_defines[1024]; char extra_fs_defines[1024]; @@ -1172,6 +1226,9 @@ int NativeRenderer_InitialisePSX(void) NativeRenderer_InitVRAMPipelines(); #if defined(CTR_INTERNAL) +#if defined(__ANDROID__) + s_gpuTimerSupported = false; +#else GLint glMajor = 0; GLint glMinor = 0; glGetIntegerv(GL_MAJOR_VERSION, &glMajor); @@ -1186,6 +1243,7 @@ int NativeRenderer_InitialisePSX(void) s_gpuTimerQueries[i].id = queryIds[i]; } } +#endif #endif glDepthFunc(GL_LEQUAL); @@ -1807,6 +1865,22 @@ internal void NativeRenderer_SyncGpuVRAMToCPU(int x, int y, int w, int h) // is read back, preserving PS1 VRAM command order in the split host mirror. NativeRenderer_UpdateVRAM(); +#if defined(__ANDROID__) + const size_t readbackSize = (size_t)readRect.w * readRect.h * 4; + if (readbackSize > s_vramReadbackScratchCapacity) + { + u8 *newScratch = realloc(s_vramReadbackScratch, readbackSize); + if (newScratch == NULL) + { + NATIVE_RENDERER_ERROR("Failed to allocate %zu-byte VRAM readback buffer\n", readbackSize); + return; + } + + s_vramReadbackScratch = newScratch; + s_vramReadbackScratchCapacity = readbackSize; + } +#endif + NativePerf_BeginScope(NATIVE_PERF_BUCKET_FRAMEBUFFER_READBACK); GLint previousReadFramebuffer; GLint previousPackRowLength; @@ -1816,10 +1890,27 @@ internal void NativeRenderer_SyncGpuVRAMToCPU(int x, int y, int w, int h) glGetIntegerv(GL_PACK_ALIGNMENT, &previousPackAlignment); glBindFramebuffer(GL_READ_FRAMEBUFFER, s_glVramFramebuffer); +#if defined(__ANDROID__) + glPixelStorei(GL_PACK_ROW_LENGTH, 0); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glReadPixels(readRect.x, readRect.y, readRect.w, readRect.h, GL_RGBA, GL_UNSIGNED_BYTE, s_vramReadbackScratch); + + for (int row = 0; row < readRect.h; row++) + { + const u8 *sourceRow = s_vramReadbackScratch + (size_t)row * readRect.w * 4; + u16 *destinationRow = s_vram.cpuPixels + (size_t)(readRect.y + row) * VRAM_WIDTH + readRect.x; + for (int column = 0; column < readRect.w; column++) + { + const u8 *sourcePixel = sourceRow + column * 4; + destinationRow[column] = (u16)(sourcePixel[0] | ((u16)sourcePixel[1] << 8)); + } + } +#else glPixelStorei(GL_PACK_ROW_LENGTH, VRAM_WIDTH); glPixelStorei(GL_PACK_ALIGNMENT, sizeof(u16)); glReadPixels(readRect.x, readRect.y, readRect.w, readRect.h, VRAM_FORMAT, GL_UNSIGNED_BYTE, s_vram.cpuPixels + (size_t)readRect.y * VRAM_WIDTH + readRect.x); +#endif for (int tileY = tileY0; tileY <= tileY1; tileY++) { @@ -2237,7 +2328,11 @@ internal void NativeRenderer_SetViewPort(int x, int y, int width, int height) internal void NativeRenderer_SetWireframe(int enable) { +#if defined(__ANDROID__) + (void)enable; +#else glPolygonMode(GL_FRONT_AND_BACK, enable ? GL_LINE : GL_FILL); +#endif } void NativeRenderer_UpdateVertexBuffer(const GrVertex *vertices, int num_vertices) @@ -2267,11 +2362,19 @@ void NativeRenderer_DrawTriangles(int start_vertex, int triangles) void NativeRenderer_PushDebugLabel(const char *label) { - if (!GLAD_GL_KHR_debug) + if (!GLAD_GL_KHR_debug || (label == NULL)) { return; } - glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 0x8000, strlen(label), label); + + if (glad_glPushDebugGroup != NULL) + { + glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 0x8000, strlen(label), label); + } + else if (glad_glPushDebugGroupKHR != NULL) + { + glPushDebugGroupKHR(GL_DEBUG_SOURCE_APPLICATION_KHR, 0x8000, strlen(label), label); + } } void NativeRenderer_PopDebugLabel(void) @@ -2280,5 +2383,12 @@ void NativeRenderer_PopDebugLabel(void) { return; } - glPopDebugGroup(); + if (glad_glPopDebugGroup != NULL) + { + glPopDebugGroup(); + } + else if (glad_glPopDebugGroupKHR != NULL) + { + glPopDebugGroupKHR(); + } }