Merge pull request #33 from maplibre/android-demo

Add Android Gradle project and a demo
This commit is contained in:
Max Ammann 2022-04-24 12:26:44 +02:00 committed by GitHub
commit 021b87eaa8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
68 changed files with 1115 additions and 260 deletions

View File

@ -7,12 +7,18 @@ runs:
- uses: extractions/setup-just@v1
- name: Install nightly toolchain
shell: bash
run: just nightly-toolchain
run: just nightly-toolchain-android
- uses: Swatinem/rust-cache@v1
- name: Build
shell: bash
run: just build-apk
run: just build-android
- name: Check x86_64
shell: bash
run: just check maplibre-android x86_64-linux-android
- name: Check aarch64
shell: bash
run: just check maplibre-android aarch64-linux-android
- uses: actions/upload-artifact@v2
with:
name: maplibre-rs.apk
path: target/debug/apk/maplibre-rs-demo.apk
path: target/debug/apk/maplibre-rs-linux-demo.apk

View File

@ -1,5 +1,5 @@
name: desktop
description: Build for desktop
name: macOS
description: Build for macOS
runs:
using: "composite"
@ -9,9 +9,16 @@ runs:
shell: bash
run: just default-toolchain
- uses: Swatinem/rust-cache@v1
- name: Build xcframework
- name: Build
shell: bash
run: just xcodebuild-xcframework
- name: Check x86_64 darwin
shell: bash
run: just check apple x86_64-apple-darwin
- name: Check aarch64 darwin
shell: bash
run: just check apple aarch64-apple-darwin
# TODO: Additional clippy checks for iOS
- name: Build Example
shell: bash
run: cd apple/xcode && xcodebuild -scheme "example (iOS)" -arch arm64 -sdk iphoneos build CODE_SIGNING_ALLOWED=NO

17
.github/actions/benchmarks/action.yml vendored Normal file
View File

@ -0,0 +1,17 @@
name: benchmarks
description: Run benchmarks
runs:
using: "composite"
steps:
- uses: extractions/setup-just@v1
- name: Install toolchain
shell: bash
run: just default-toolchain
- uses: Swatinem/rust-cache@v1
- name: Install Dependencies
shell: bash
run: sudo apt-get install -y libwayland-dev libxkbcommon-dev # Required for winit
- name: Check
shell: bash
run: just check benchmarks x86_64-unknown-linux-gnu

View File

@ -12,9 +12,3 @@ runs:
- name: Format
shell: bash
run: just fmt-check
- name: Install Dependencies
shell: bash
run: sudo apt-get install -y libwayland-dev libxkbcommon-dev # Required for winit
- name: Clippy
shell: bash
run: just clippy

View File

@ -1,5 +1,5 @@
name: desktop
description: Build for desktop
name: linux-demo
description: Build linux-demo for linux
runs:
using: "composite"
@ -15,6 +15,9 @@ runs:
- name: Build
shell: bash
run: cargo build -p maplibre-demo
- name: Check
shell: bash
run: just check maplibre-demo x86_64-unknown-linux-gnu
- uses: actions/upload-artifact@v2
with:
name: maplibre-rs

View File

@ -12,3 +12,6 @@ runs:
- name: Build
shell: bash
run: just webpack-webgl-production
- name: Check
shell: bash
run: just check web wasm32-unknown-unknown

View File

@ -12,3 +12,6 @@ runs:
- name: Build
shell: bash
run: just webpack-production
- name: Check
shell: bash
run: just check web wasm32-unknown-unknown

View File

@ -12,11 +12,16 @@ jobs:
steps:
- uses: actions/checkout@v2
- uses: ./.github/actions/check
build-desktop:
run-benchmarks:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: ./.github/actions/desktop
- uses: ./.github/actions/benchmarks
build-linux-demo:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: ./.github/actions/linux-demo
build-android:
runs-on: ubuntu-20.04
steps:
@ -29,7 +34,7 @@ jobs:
- uses: ./.github/actions/webgpu
- uses: ./.github/actions/deploy
with:
source: web/web/dist/demo/.
source: web/web/dist/linux-demo/.
destination: webgpu
key: ${{ secrets.SSH_KEY_MAXAMMANN_ORG }}
build-deploy-webgl:
@ -39,7 +44,7 @@ jobs:
- uses: ./.github/actions/webgl
- uses: ./.github/actions/deploy
with:
source: web/web/dist/demo/.
source: web/web/dist/linux-demo/.
destination: webgl
key: ${{ secrets.SSH_KEY_MAXAMMANN_ORG }}
build-deploy-docs:

View File

@ -12,11 +12,16 @@ jobs:
steps:
- uses: actions/checkout@v2
- uses: ./.github/actions/check
build-desktop:
run-benchmarks:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: ./.github/actions/desktop
- uses: ./.github/actions/benchmarks
build-linux-demo:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: ./.github/actions/linux-demo
build-android:
runs-on: ubuntu-20.04
steps:

View File

@ -113,7 +113,7 @@ cargo build
After that, you can run it on your desktop:
```bash
cargo run --example desktop --
cargo run -p maplibre-demo
```
More information about building for different platforms can be

View File

@ -9,9 +9,9 @@ publish = false
[dependencies]
maplibre = { path = "../maplibre" }
env_logger = "0.9"
[target.'cfg(target_os = "android")'.dependencies]
log = "0.4.16"
ndk-glue = "0.5.0" # version is required by winit
jni = "0.19.0"
[lib]
#name = "maplibre_android" Currently not supported: https://github.com/rust-windowing/android-ndk-rs/issues/136

View File

@ -18,4 +18,20 @@ gradle-app.setting
# Eclipse Core
.project
# JDT-specific (Eclipse Java Development Tools)
.classpath
.classpath
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties

8
android/gradle/.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

1
android/gradle/.idea/.name generated Normal file
View File

@ -0,0 +1 @@
maplibre-rs-android

6
android/gradle/.idea/compiler.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="11" />
</component>
</project>

22
android/gradle/.idea/gradle.xml generated Normal file
View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="delegatedBuild" value="true" />
<option name="testRunner" value="GRADLE" />
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="#JAVA_HOME" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/demo" />
<option value="$PROJECT_DIR$/lib" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>

25
android/gradle/.idea/jarRepositories.xml generated Normal file
View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="MavenRepo" />
<option name="name" value="MavenRepo" />
<option name="url" value="https://repo.maven.apache.org/maven2/" />
</remote-repository>
<remote-repository>
<option name="id" value="Google" />
<option name="name" value="Google" />
<option name="url" value="https://dl.google.com/dl/android/maven2/" />
</remote-repository>
</component>
</project>

12
android/gradle/.idea/misc.xml generated Normal file
View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DesignSurface">
<option name="filePathToZoomLevelMap">
<map>
<entry key="app/src/main/res/layout/activity_main.xml" value="0.296195652173913" />
</map>
</option>
</component>
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="11" project-jdk-type="JavaSDK" />
</project>

6
android/gradle/.idea/vcs.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
</component>
</project>

View File

@ -1,84 +1,3 @@
buildscript {
repositories {
google()
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "com.android.tools.build:gradle:7.1.3"
classpath 'org.mozilla.rust-android-gradle:plugin:0.9.2'
}
}
apply plugin: 'com.android.library'
apply plugin: 'org.mozilla.rust-android-gradle.rust-android'
android {
ndkVersion "23.1.7779620"
compileSdkVersion 27
defaultConfig {
minSdkVersion 21
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
cargo {
module = "../"
targets = ["arm64"]
libname = "maplibre"
features {
defaultAnd "foo", "bar"
noDefaultBut("foo", "bar")
all()
}
def ndkDir = android.ndkDirectory
exec = { spec, toolchain ->
spec.environment("TEST", "test")
// https://github.com/mozilla/rust-android-gradle/issues/91
if (toolchain.target == "aarch64-linux-android") {
spec.environment("AR_aarch64-linux-android", "$ndkDir/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-ar")
}
}
}
repositories {
google()
}
dependencies {
androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
implementation 'com.android.support:appcompat-v7:27.1.1'
testImplementation 'junit:junit:4.12'
}
afterEvaluate {
// The `cargoBuild` task isn't available until after evaluation.
android.libraryVariants.all { variant ->
def productFlavor = ""
variant.productFlavors.each {
productFlavor += "${it.name.capitalize()}"
}
def buildType = "${variant.buildType.name.capitalize()}"
tasks["generate${productFlavor}${buildType}Assets"].dependsOn(tasks["cargoBuild"])
}
task clean(type: Delete) {
delete rootProject.buildDir
}

1
android/gradle/demo/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build

View File

@ -0,0 +1,49 @@
plugins {
id 'com.android.application' version '7.0.4' apply true
id 'org.jetbrains.kotlin.android' version '1.6.21' apply true
}
android {
compileSdk 31
defaultConfig {
applicationId "com.example.demo"
minSdk 30
targetSdk 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
ndk {
// Specifies the ABI configurations of your native
// libraries Gradle should build and package with your app.
abiFilters 'x86_64', 'arm64-v8a'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation project(':lib')
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

21
android/gradle/demo/proguard-rules.pro vendored Normal file
View File

@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demo">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Demo">
<!-- This will take care of integrating with our NDK code. -->
<activity android:name="android.app.NativeActivity"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:exported="true">
<!-- Tell NativeActivity the name of our .so -->
<meta-data android:name="android.app.lib_name"
android:value="maplibre_android"/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".MainActivity" android:exported="true">
</activity>
</application>
</manifest>

View File

@ -0,0 +1,15 @@
package com.example.demo
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import org.maplibre_rs.MapLibreRs
// Currently not used. Instead the NativeActivity referenced in AndroidManifest.xml is used.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MapLibreRs.android_main()
}
}

View File

@ -0,0 +1,31 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:startY="49.59793"
android:startX="42.9492"
android:endY="92.4963"
android:endX="85.84757"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0"/>
<item
android:color="#00000000"
android:offset="1.0"/>
</gradient>
</aapt:attr>
</path>
<path
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:strokeWidth="1"
android:strokeColor="#00000000"/>
</vector>

View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="utf-8"?>
<vector
xmlns:android="http://schemas.android.com/apk/res/android"
android:height="108dp"
android:width="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z"/>
<path android:fillColor="#00000000" android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
<path android:fillColor="#00000000" android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF" android:strokeWidth="0.8"/>
</vector>

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 982 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

View File

@ -0,0 +1,16 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.Demo" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_200</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/black</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_200</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources>

View File

@ -0,0 +1,3 @@
<resources>
<string name="app_name">demo</string>
</resources>

View File

@ -0,0 +1,16 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.Demo" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>

View File

@ -0,0 +1,21 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app"s APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
android/gradle/gradlew vendored Executable file
View File

@ -0,0 +1,234 @@
#!/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.
#
##############################################################################
#
# 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/master/subprojects/plugins/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
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# 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"'
# 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
which java >/dev/null 2>&1 || 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
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
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
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# 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" "$@"

89
android/gradle/gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@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
@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=.
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%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
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%"=="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!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,88 @@
plugins {
id 'org.mozilla.rust-android-gradle.rust-android' version '0.9.2' apply true
id 'com.android.library' version '7.0.4' apply true
id 'org.jetbrains.kotlin.android' version '1.6.21' apply true
}
apply plugin: 'kotlin-android'
android {
ndkVersion "23.1.7779620"
compileSdkVersion 29
defaultConfig {
minSdkVersion 21
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
cargo {
module = "../../"
targets = ["arm64", "x86_64"]
libname = "maplibre_android"
targetDirectory = "${module}/../target"
profile = "debug"
features {
defaultAnd "foo", "bar"
noDefaultBut("foo", "bar")
all()
}
def ndkDir = android.ndkDirectory
exec = { spec, toolchain ->
spec.environment("TEST", "test")
// https://github.com/mozilla/rust-android-gradle/issues/91
if (toolchain.target == "x86_64-linux-android") {
spec.environment("AR_x86_64-linux-android", "$ndkDir/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-ar")
}
if (toolchain.target == "armv7-linux-androideabi") {
spec.environment("AR_armv7-linux-androideabi", "$ndkDir/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-ar")
}
if (toolchain.target == "aarch64-linux-android") {
spec.environment("AR_aarch64-linux-android", "$ndkDir/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-ar")
}
}
}
dependencies {
androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testImplementation 'junit:junit:4.13.2'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.6.21"
}
tasks.whenTaskAdded { task ->
if ((task.name == 'mergeDebugJniLibFolders' || task.name == 'mergeReleaseJniLibFolders')) {
task.dependsOn 'cargoBuild'
}
}
afterEvaluate {
// The `cargoBuild` task isn't available until after evaluation.
android.libraryVariants.all { variant ->
def productFlavor = ""
variant.productFlavors.each {
productFlavor += "${it.name.capitalize()}"
}
def buildType = "${variant.buildType.name.capitalize()}"
tasks["generate${productFlavor}${buildType}Assets"].dependsOn(tasks["cargoBuild"])
}
}

View File

@ -1,9 +1,8 @@
package org.maplibre-rs;
package org.maplibre_rs;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -21,6 +20,6 @@ public class ExampleInstrumentedTest {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.nishtahir.library.test", appContext.getPackageName());
assertEquals("org.maplibre_rs", appContext.getPackageName());
}
}

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest package="org.maplibre_rs" />

View File

@ -0,0 +1,9 @@
package org.maplibre_rs;
public class MapLibreRs {
public static native void android_main();
static {
System.loadLibrary("maplibre_android");
}
}

View File

@ -0,0 +1,21 @@
pluginManagement {
repositories {
google()
maven {
url 'maven-repo'
}
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "maplibre-rs-android"
include ':demo'
include ':lib'

View File

@ -1,10 +0,0 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.maplibre-rs">
<application android:allowBackup="true" android:label="@string/app_name"
android:supportsRtl="true">
</application>
</manifest>

View File

@ -1,3 +0,0 @@
<resources>
<string name="app_name">maplibre-rs</string>
</resources>

View File

@ -1,13 +1,16 @@
use jni::objects::JClass;
use jni::JNIEnv;
use log::Level;
use maplibre::window::FromWindow;
use maplibre::{MapBuilder, ScheduleMethod, TokioScheduleMethod};
use std::ffi::CString;
pub use std::time::Instant;
// TODO clippy
// #[cfg(not(target_os = "android"))]
// compile_error!("android works only on android.");
#[cfg(not(target_os = "android"))]
compile_error!("android works only on android.");
#[cfg_attr(target_os = "android", ndk_glue::main(backtrace = "on"))]
pub fn main() {
pub fn android_main() {
env_logger::init_from_env(env_logger::Env::default().default_filter_or("info"));
MapBuilder::from_window("A fantastic window!")
@ -15,3 +18,10 @@ pub fn main() {
.build()
.run_sync();
}
#[no_mangle]
pub extern "system" fn Java_org_maplibre_1rs_MapLibreRs_android_1main(env: JNIEnv, class: JClass) {
let tag = CString::new("maplibre").unwrap();
let message = CString::new("maplibre WOORKING").unwrap();
ndk_glue::android_log(Level::Warn, &tag, &message);
}

View File

@ -2,9 +2,8 @@ use maplibre::window::FromWindow;
use maplibre::{MapBuilder, ScheduleMethod, TokioScheduleMethod};
pub use std::time::Instant;
// TODO clippy
// #[cfg(not(any(target_os = "macos", target_os = "ios")))]
// compile_error!("apple works only on macOS and iOS.");
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
compile_error!("apple works only on macOS and iOS.");
#[no_mangle]
pub fn maplibre_apple_main() {

View File

@ -1,5 +1,5 @@
[package]
name = "maplibre-benchmark"
name = "benchmarks"
version = "0.1.0"
description = ""
categories = []

View File

@ -5,28 +5,22 @@
The setup normal desktop is very simple. You just have to run the following:
```bash
cargo run --example desktop --
cargo run -p maplibre-demo
```
## Android
First you have to install cargo-apk:
```bash
cargo install cargo-apk
```
Next, you should make sure that a recent Android NDK is installed. You will need to set the `ANDROID_NDK_ROOT` variable
You should make sure that a recent Android NDK is installed. You will need to set the `ANDROID_NDK_ROOT` variable
to something like this:
```bash
export ANDROID_NDK_ROOT=$HOME/android-sdk/ndk/23.1.7779620/
```
After that you can run the app on a connected device using:
After that you can run the build the library:
``bash
cargo apk run --lib
just build-android
``
## iOS
@ -41,8 +35,6 @@ In order to run this app on macOS you have to open the Xcode project at `./apple
You can then run the app on a macOS. During the Xcode build process cargo is used to build
a static library for the required architecture.
*Hint: Right now only arm64/aarch64 devices are supported*
## Web (WebGL, WebGPU)
If you have a browser which already supports a recent version of the WebGPU specification then you can start a

View File

@ -12,8 +12,8 @@ test:
install-clippy:
rustup component add clippy
clippy: install-clippy
cargo clippy --all-targets --all-features --no-deps
check PROJECT ARCH: install-clippy
cargo clippy --no-deps -p {{PROJECT}} --target {{ARCH}}
install-rustfmt:
rustup component add rustfmt
@ -33,6 +33,10 @@ nightly-toolchain:
rustup component add rust-src --toolchain $NIGHTLY_TOOLCHAIN
rustup override set $NIGHTLY_TOOLCHAIN
nightly-toolchain-android: nightly-toolchain
rustup target add --toolchain $NIGHTLY_TOOLCHAIN x86_64-linux-android
rustup target add --toolchain $NIGHTLY_TOOLCHAIN aarch64-linux-android
webpack-webgl-production: nightly-toolchain
cd web/web && npm install && npm run webgl-production-build
@ -68,14 +72,9 @@ webpack-production: nightly-toolchain
#profile-bench:
# cargo flamegraph --bench render -- --bench
install-cargo-apk:
cargo install cargo-apk
run-apk: print-android-env nightly-toolchain install-cargo-apk
cargo apk run -p maplibre-android --lib -Zbuild-std
build-apk: print-android-env nightly-toolchain install-cargo-apk
cargo apk build -p maplibre-android --lib -Zbuild-std
build-android: print-android-env
cd android/gradle && ./gradlew assembleDebug
# language=bash
print-android-env:

View File

@ -11,7 +11,7 @@ enable-tracing = ["maplibre/enable-tracing", "tracing-subscriber", "tracing-trac
[dependencies]
env_logger = "0.9"
maplibre = { path = "../maplibre" }
maplibre = { path = "../maplibre", version = "0.1.0" }
tracing = { version = "0.1" }
tracing-subscriber = { version = "0.3", optional = true }

View File

@ -83,4 +83,4 @@ csscolorparser = { version = "0.5", features = ["serde", "cint"]}
cint = "0.2"
[build-dependencies]
maplibre-build-tools = { path = "../maplibre-build-tools" }
maplibre-build-tools = { path = "../maplibre-build-tools", version = "0.1.0" }

View File

@ -31,7 +31,7 @@ pub struct MapState<W> {
camera: ChangeObserver<camera::Camera>,
perspective: camera::Perspective,
render_state: RenderState,
render_state: Option<RenderState>,
scheduler: Scheduler,
message_receiver: mpsc::Receiver<TessellateMessage>,
shared_thread_state: SharedThreadState,
@ -46,7 +46,7 @@ impl<W> MapState<W> {
pub fn new(
window: W,
window_size: WindowSize,
render_state: RenderState,
render_state: Option<RenderState>,
scheduler: Scheduler,
style: Style,
) -> Self {
@ -100,7 +100,7 @@ impl<W> MapState<W> {
self.prepare_render();
// Render buffers
let result = self.render_state.render();
let result = self.render_state_mut().render();
#[cfg(all(feature = "enable-tracing", not(target_arch = "wasm32")))]
tracy_client::finish_continuous_frame!();
@ -171,12 +171,15 @@ impl<W> MapState<W> {
if let Some(view_region) = &view_region {
self.render_state
.as_mut()
.expect("render state not yet initialized. Call reinitialize().")
.upload_tile_geometry(view_region, &self.style, &self.tile_cache);
self.render_state
.update_tile_view_pattern(view_region, &view_proj, self.zoom());
let zoom = self.zoom();
self.render_state_mut()
.update_tile_view_pattern(view_region, &view_proj, zoom);
self.render_state.update_metadata();
self.render_state_mut().update_metadata();
}
// TODO: Could we draw inspiration from StagingBelt (https://docs.rs/wgpu/latest/wgpu/util/struct.StagingBelt.html)?
@ -188,7 +191,7 @@ impl<W> MapState<W> {
self.try_failed = self.request_tiles_in_view(view_region);
}
self.render_state.update_globals(&view_proj, &self.camera);
self.render_state().update_globals(&view_proj, &self.camera);
}
self.camera.update_reference();
@ -253,7 +256,7 @@ impl<W> MapState<W> {
self.perspective.resize(width, height);
self.camera.resize(width, height);
self.render_state.resize(width, height)
self.render_state_mut().resize(width, height)
}
pub fn scheduler(&self) -> &Scheduler {
@ -289,11 +292,21 @@ impl<W> MapState<W> {
}
pub fn suspend(&mut self) {
self.render_state.suspend();
self.render_state_mut().suspend();
}
pub fn resume(&mut self) {
self.render_state.resume();
self.render_state_mut().resume();
}
pub fn render_state(&self) -> &RenderState {
self.render_state
.as_ref()
.expect("render state not yet initialized. Call reinitialize().")
}
pub fn render_state_mut(&mut self) -> &'_ mut RenderState {
self.render_state.as_mut().unwrap()
}
}
@ -302,6 +315,21 @@ where
W: raw_window_handle::HasRawWindowHandle,
{
pub fn recreate_surface(&mut self) {
self.render_state.recreate_surface(&self.window);
self.render_state
.as_mut()
.expect("render state not yet initialized. Call reinitialize().")
.recreate_surface(&self.window);
}
pub fn is_initialized(&self) -> bool {
self.render_state.is_some()
}
pub async fn reinitialize(&mut self) {
if self.render_state.is_none() {
let window_size = WindowSize::new(100, 100).unwrap(); // TODO get size
let render_state = RenderState::initialize(&self.window, window_size);
self.render_state = Some(render_state.await.unwrap())
}
}
}

View File

@ -68,11 +68,12 @@ impl RenderState {
pub async fn initialize<W: raw_window_handle::HasRawWindowHandle>(
window: &W,
window_size: WindowSize,
) -> Self {
) -> Option<Self> {
let sample_count = 4;
//let instance = wgpu::Instance::new(wgpu::Backends::GL);
let instance = wgpu::Instance::new(wgpu::Backends::all());
//let instance = wgpu::Instance::new(wgpu::Backends::all());
let instance = wgpu::Instance::new(wgpu::Backends::VULKAN);
let surface = unsafe { instance.create_surface(&window) };
let surface_config = wgpu::SurfaceConfiguration {
@ -101,7 +102,13 @@ impl RenderState {
} else if cfg!(target_os = "android") {
Limits {
max_storage_textures_per_shader_stage: 4,
..wgpu::Limits::default()
max_compute_workgroups_per_dimension: 0,
max_compute_workgroup_size_z: 0,
max_compute_workgroup_size_y: 0,
max_compute_workgroup_size_x: 0,
max_compute_workgroup_storage_size: 0,
max_compute_invocations_per_workgroup: 0,
..wgpu::Limits::downlevel_defaults()
}
} else {
Limits {
@ -126,7 +133,7 @@ impl RenderState {
None,
)
.await
.unwrap();
.ok()?;
surface.configure(&device, &surface_config);
@ -245,7 +252,7 @@ impl RenderState {
None
};
Self {
Some(Self {
instance,
surface,
device,
@ -270,7 +277,7 @@ impl RenderState {
tile_view_buffer,
TILE_VIEW_BUFFER_SIZE,
)),
}
})
}
pub fn recreate_surface<W: raw_window_handle::HasRawWindowHandle>(&mut self, window: &W) {

View File

@ -23,88 +23,102 @@ impl Runnable<winit::event_loop::EventLoop<()>> for MapState<winit::window::Wind
let mut input_controller = InputController::new(0.2, 100.0, 0.1);
event_loop.run(move |event, _, control_flow| {
match event {
Event::DeviceEvent {
ref event,
.. // We're not using device_id currently
} => {
input_controller.device_input(event);
}
Event::WindowEvent {
ref event,
window_id,
} if window_id == self.window().id() => {
if !input_controller.window_input(event) {
match event {
WindowEvent::CloseRequested
| WindowEvent::KeyboardInput {
input:
KeyboardInput {
state: ElementState::Pressed,
virtual_keycode: Some(VirtualKeyCode::Escape),
..
},
..
} => *control_flow = ControlFlow::Exit,
WindowEvent::Resized(physical_size) => {
self.resize(physical_size.width, physical_size.height);
}
WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
self.resize(new_inner_size.width, new_inner_size.height);
}
_ => {}
}
}
}
Event::RedrawRequested(_) => {
let _span_ = tracing::span!(tracing::Level::TRACE, "redraw requested").entered();
#[cfg(target_os = "android")]
if !self.is_initialized() && event == Event::Resumed {
use tokio::runtime::Handle;
use tokio::task;
let now = Instant::now();
let dt = now - last_render_time;
last_render_time = now;
let state = task::block_in_place(|| {
Handle::current().block_on(async {
self.reinitialize().await;
})
});
return;
}
input_controller.update_state(&mut self, dt);
match self.update_and_redraw() {
Ok(_) => {}
Err(wgpu::SurfaceError::Lost) => {
log::error!("Surface Lost");
},
// The system is out of memory, we should probably quit
Err(wgpu::SurfaceError::OutOfMemory) => {
log::error!("Out of Memory");
*control_flow = ControlFlow::Exit;
},
// All other errors (Outdated, Timeout) should be resolved by the next frame
Err(e) => eprintln!("{:?}", e),
};
if let Some(max_frames) = max_frames {
if current_frame >= max_frames {
log::info!("Exiting because maximum frames reached.");
*control_flow = ControlFlow::Exit;
}
current_frame += 1;
}
}
Event::Suspended => {
self.suspend();
}
Event::Resumed => {
self.recreate_surface();
let size = self.window().inner_size();
self.resize(size.width, size.height);// FIXME: Resumed is also called when the app launches for the first time. Instead of first using a "fake" inner_size() in State::new we should initialize with a proper size from the beginning
self.resume();
}
Event::MainEventsCleared => {
// RedrawRequested will only trigger once, unless we manually
// request it.
self.window().request_redraw();
}
_ => {}
match event {
Event::DeviceEvent {
ref event,
.. // We're not using device_id currently
} => {
input_controller.device_input(event);
}
Event::WindowEvent {
ref event,
window_id,
} if window_id == self.window().id() => {
if !input_controller.window_input(event) {
match event {
WindowEvent::CloseRequested
| WindowEvent::KeyboardInput {
input:
KeyboardInput {
state: ElementState::Pressed,
virtual_keycode: Some(VirtualKeyCode::Escape),
..
},
..
} => *control_flow = ControlFlow::Exit,
WindowEvent::Resized(physical_size) => {
self.resize(physical_size.width, physical_size.height);
}
WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
self.resize(new_inner_size.width, new_inner_size.height);
}
_ => {}
}
}
}
Event::RedrawRequested(_) => {
let _span_ = tracing::span!(tracing::Level::TRACE, "redraw requested").entered();
let now = Instant::now();
let dt = now - last_render_time;
last_render_time = now;
input_controller.update_state(&mut self, dt);
match self.update_and_redraw() {
Ok(_) => {}
Err(wgpu::SurfaceError::Lost) => {
log::error!("Surface Lost");
}
// The system is out of memory, we should probably quit
Err(wgpu::SurfaceError::OutOfMemory) => {
log::error!("Out of Memory");
*control_flow = ControlFlow::Exit;
}
// All other errors (Outdated, Timeout) should be resolved by the next frame
Err(e) => eprintln!("{:?}", e),
};
if let Some(max_frames) = max_frames {
if current_frame >= max_frames {
log::info!("Exiting because maximum frames reached.");
*control_flow = ControlFlow::Exit;
}
current_frame += 1;
}
}
Event::Suspended => {
self.suspend();
}
Event::Resumed => {
self.recreate_surface();
let size = self.window().inner_size();
self.resize(size.width, size.height);// FIXME: Resumed is also called when the app launches for the first time. Instead of first using a "fake" inner_size() in State::new we should initialize with a proper size from the beginning
self.resume();
}
Event::MainEventsCleared => {
// RedrawRequested will only trigger once, unless we manually
// request it.
self.window().request_redraw();
}
_ => {}
}
});
}
}
@ -119,11 +133,7 @@ impl FromWindow for MapBuilder<winit::window::Window, winit::event_loop::EventLo
.build(&event_loop)
.unwrap();
let size = window.inner_size();
(
window,
WindowSize::new(size.width, size.height).unwrap(),
event_loop,
)
(window, WindowSize::new(100, 100).unwrap(), event_loop)
}))
}
}

View File

@ -1,7 +1,7 @@
[toolchain]
channel = "1.60"
targets = [
"wasm32-unknown-unknown", "x86_64-unknown-linux-gnu", "aarch64-linux-android",
"wasm32-unknown-unknown", "x86_64-unknown-linux-gnu", "x86_64-linux-android", "aarch64-linux-android",
"x86_64-apple-darwin", "aarch64-apple-darwin", "x86_64-apple-ios", "aarch64-apple-ios", "aarch64-apple-ios-sim"
]
components = [ "rust-src" ] # rust-src is required for WASM and android builds which recompile the stdlib

View File

@ -1,5 +1,4 @@
pub use maplibre::*;
// TODO clippy
// #[cfg(not(target_arch = "wasm32"))]
// compile_error!("web works only on wasm32.");
#[cfg(not(target_arch = "wasm32"))]
compile_error!("web works only on wasm32.");