├── OnexOS
├── OnexKernel
├── OnexLang
├── android
├── onexapp
│ ├── src
│ │ └── main
│ │ │ ├── assets
│ │ │ ├── res
│ │ │ ├── xml
│ │ │ │ └── device_filter.xml
│ │ │ ├── drawable
│ │ │ │ ├── icon.png
│ │ │ │ └── icon1k.png
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ └── styles.xml
│ │ │ └── layout
│ │ │ │ ├── device_element.xml
│ │ │ │ └── device_list.xml
│ │ │ ├── java
│ │ │ └── android
│ │ │ │ └── network
│ │ │ │ └── object
│ │ │ │ └── onexapp
│ │ │ │ ├── AlarmReceiver.java
│ │ │ │ ├── EternalServiceJob.java
│ │ │ │ ├── BluetoothReceiver.java
│ │ │ │ ├── EternalServiceRestarter.java
│ │ │ │ ├── DeviceListActivity.java
│ │ │ │ ├── EternalService.java
│ │ │ │ └── OnexNativeActivity.java
│ │ │ └── AndroidManifest.xml
│ ├── build.gradle
│ └── CMakeLists.txt
├── settings.gradle
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── gradle.properties
├── build.gradle
└── gradlew
├── src
├── behaviours_2.c
├── display.h
├── calendar.h
├── ux-features.h
├── im-gui.h
├── gui.h
├── OnexAppBL.c
├── display.cpp
├── onex.cpp
└── ux-features.cpp
├── data
├── fonts
│ ├── OpenSans-Bold.ttf
│ ├── OpenSans-Light.ttf
│ ├── OpenSansEmoji.ttf
│ ├── OpenSans-Italic.ttf
│ ├── OpenSans-Regular.ttf
│ ├── OpenSans-BoldItalic.ttf
│ ├── OpenSans-ExtraBold.ttf
│ ├── OpenSans-SemiBold.ttf
│ ├── OpenSans-LightItalic.ttf
│ ├── OpenSans-ExtraBoldItalic.ttf
│ └── OpenSans-SemiBoldItalic.ttf
└── shaders
│ └── imgui
│ ├── ui.frag.spv
│ ├── ui.vert.spv
│ ├── ui.frag
│ └── ui.vert
├── gdb-commands-jlink.txt
├── .gitignore
├── sascha
├── CMakeLists.txt
├── VulkanDebug.h
├── VulkanTools.h
├── keycodes.hpp
├── VulkanBuffer.hpp
├── camera.hpp
├── VulkanAndroid.h
├── VulkanDebug.cpp
└── VulkanTools.cpp
├── .gitmodules
├── external
├── fonts
│ ├── noto_sans_numeric_60.h
│ ├── noto_sans_numeric_80.h
│ └── fonts_noto_sans_numeric_60.c
└── imgui
│ ├── LICENSE.txt
│ ├── LICENSE
│ └── imconfig.h
├── README.md
├── LICENSE
├── cmake
├── FindXCB.cmake
└── FindWayland.cmake
└── CMakeLists.txt
/OnexOS:
--------------------------------------------------------------------------------
1 | ../OnexOS
--------------------------------------------------------------------------------
/OnexKernel:
--------------------------------------------------------------------------------
1 | ../OnexKernel
--------------------------------------------------------------------------------
/OnexLang:
--------------------------------------------------------------------------------
1 | ../OnexLang
--------------------------------------------------------------------------------
/android/onexapp/src/main/assets:
--------------------------------------------------------------------------------
1 | ../../../../data
--------------------------------------------------------------------------------
/android/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':onexapp'
2 |
--------------------------------------------------------------------------------
/src/behaviours_2.c:
--------------------------------------------------------------------------------
1 | ../OnexKernel/src/onp/behaviours.c
--------------------------------------------------------------------------------
/src/display.h:
--------------------------------------------------------------------------------
1 |
2 | void draw_display(char* path, int16_t width, int16_t height);
3 |
4 |
--------------------------------------------------------------------------------
/android/onexapp/src/main/res/xml/device_filter.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/data/fonts/OpenSans-Bold.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DuncanCragg/OnexApp/HEAD/data/fonts/OpenSans-Bold.ttf
--------------------------------------------------------------------------------
/data/fonts/OpenSans-Light.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DuncanCragg/OnexApp/HEAD/data/fonts/OpenSans-Light.ttf
--------------------------------------------------------------------------------
/data/fonts/OpenSansEmoji.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DuncanCragg/OnexApp/HEAD/data/fonts/OpenSansEmoji.ttf
--------------------------------------------------------------------------------
/data/fonts/OpenSans-Italic.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DuncanCragg/OnexApp/HEAD/data/fonts/OpenSans-Italic.ttf
--------------------------------------------------------------------------------
/data/fonts/OpenSans-Regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DuncanCragg/OnexApp/HEAD/data/fonts/OpenSans-Regular.ttf
--------------------------------------------------------------------------------
/data/shaders/imgui/ui.frag.spv:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DuncanCragg/OnexApp/HEAD/data/shaders/imgui/ui.frag.spv
--------------------------------------------------------------------------------
/data/shaders/imgui/ui.vert.spv:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DuncanCragg/OnexApp/HEAD/data/shaders/imgui/ui.vert.spv
--------------------------------------------------------------------------------
/data/fonts/OpenSans-BoldItalic.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DuncanCragg/OnexApp/HEAD/data/fonts/OpenSans-BoldItalic.ttf
--------------------------------------------------------------------------------
/data/fonts/OpenSans-ExtraBold.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DuncanCragg/OnexApp/HEAD/data/fonts/OpenSans-ExtraBold.ttf
--------------------------------------------------------------------------------
/data/fonts/OpenSans-SemiBold.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DuncanCragg/OnexApp/HEAD/data/fonts/OpenSans-SemiBold.ttf
--------------------------------------------------------------------------------
/data/fonts/OpenSans-LightItalic.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DuncanCragg/OnexApp/HEAD/data/fonts/OpenSans-LightItalic.ttf
--------------------------------------------------------------------------------
/data/fonts/OpenSans-ExtraBoldItalic.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DuncanCragg/OnexApp/HEAD/data/fonts/OpenSans-ExtraBoldItalic.ttf
--------------------------------------------------------------------------------
/data/fonts/OpenSans-SemiBoldItalic.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DuncanCragg/OnexApp/HEAD/data/fonts/OpenSans-SemiBoldItalic.ttf
--------------------------------------------------------------------------------
/android/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DuncanCragg/OnexApp/HEAD/android/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/android/onexapp/src/main/res/drawable/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DuncanCragg/OnexApp/HEAD/android/onexapp/src/main/res/drawable/icon.png
--------------------------------------------------------------------------------
/android/onexapp/src/main/res/drawable/icon1k.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DuncanCragg/OnexApp/HEAD/android/onexapp/src/main/res/drawable/icon1k.png
--------------------------------------------------------------------------------
/src/calendar.h:
--------------------------------------------------------------------------------
1 |
2 | bool evaluate_event(object* o, void* d);
3 | void draw_calendar(char* path, int16_t width, int16_t height);
4 | void set_time_save_days();
5 |
6 |
--------------------------------------------------------------------------------
/gdb-commands-jlink.txt:
--------------------------------------------------------------------------------
1 | target extended-remote localhost:2331
2 | mon speed 10000
3 | mon flash download=1
4 | file _build/OnexOS.out
5 | set print pretty on
6 | break HardFault_Handler
7 | set unwindonsignal on
8 | mon reset 0
9 | continue
10 |
--------------------------------------------------------------------------------
/android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Oct 03 21:53:06 BST 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .*.sw?
2 | _build/
3 | sdk
4 | dfu.zip
5 | CMakeFiles/
6 | CMakeCache.txt
7 | Makefile
8 | cmake_install.cmake
9 | bin/
10 | doc/local
11 | android/doc
12 | ,*
13 | .gradle
14 | .idea
15 | *.iml
16 | build/
17 | .cxx/
18 | local.properties
19 | *.a
20 | *.o
21 | *.hex
22 | *.elf
23 |
--------------------------------------------------------------------------------
/data/shaders/imgui/ui.frag:
--------------------------------------------------------------------------------
1 | #version 450
2 |
3 | layout (binding = 0) uniform sampler2D fontSampler;
4 |
5 | layout (location = 0) in vec2 inUV;
6 | layout (location = 1) in vec4 inColor;
7 |
8 | layout (location = 0) out vec4 outColor;
9 |
10 | void main()
11 | {
12 | outColor = inColor * texture(fontSampler, inUV);
13 | }
--------------------------------------------------------------------------------
/android/gradle.properties:
--------------------------------------------------------------------------------
1 | org.gradle.jvmargs=-Xmx1536m
2 |
3 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
4 | org.gradle.parallel=true
5 |
6 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
7 | android.useAndroidX=true
8 | android.enableJetifier=true
9 |
10 |
--------------------------------------------------------------------------------
/sascha/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | file(GLOB SASCHA_SRC *.cpp)
2 | file(GLOB SASCHA_HEADERS *.hpp)
3 |
4 | if(WIN32)
5 | add_library(sascha STATIC ${SASCHA_SRC})
6 | target_link_libraries(sascha ${Vulkan_LIBRARY} ${WINLIBS})
7 | else(WIN32)
8 | add_library(sascha STATIC ${SASCHA_SRC})
9 | target_link_libraries(sascha)
10 | endif(WIN32)
11 |
12 |
--------------------------------------------------------------------------------
/android/onexapp/src/main/java/android/network/object/onexapp/AlarmReceiver.java:
--------------------------------------------------------------------------------
1 | package network.object.onexapp;
2 |
3 | import android.content.*;
4 | import android.app.*;
5 |
6 | public class AlarmReceiver extends BroadcastReceiver {
7 | @Override
8 | public void onReceive(Context context, Intent intent) {
9 | OnexNativeActivity.alarmReceived(context, intent);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "external/glm"]
2 | path = external/glm
3 | url = https://github.com/g-truc/glm
4 | [submodule "OnexKernel"]
5 | path = OnexKernel
6 | url = git@github.com:DuncanCragg/OnexKernel.git
7 | [submodule "OnexLang"]
8 | path = OnexLang
9 | url = git@github.com:DuncanCragg/OnexLang.git
10 | [submodule "external/lvgl"]
11 | path = external/lvgl
12 | url = git@github.com:littlevgl/lvgl.git
13 |
--------------------------------------------------------------------------------
/external/fonts/noto_sans_numeric_60.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2018 Koen Zandberg
3 | *
4 | * This file is subject to the terms and conditions of the GNU Lesser
5 | * General Public License v2.1. See the file LICENSE in the top level
6 | * directory for more details.
7 | */
8 |
9 | #ifndef _APP_FONTS_NOTO_SANS_NUMERIC_60_H
10 | #define _APP_FONTS_NOTO_SANS_NUMERIC_60_H
11 |
12 | #include "lvgl.h"
13 |
14 | #ifdef __cplusplus
15 | extern "C" {
16 | #endif
17 |
18 | extern lv_font_t noto_sans_numeric_60;
19 |
20 | #ifdef __cplusplus
21 | }
22 | #endif
23 | #endif
24 |
--------------------------------------------------------------------------------
/external/fonts/noto_sans_numeric_80.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2018 Koen Zandberg
3 | *
4 | * This file is subject to the terms and conditions of the GNU Lesser
5 | * General Public License v2.1. See the file LICENSE in the top level
6 | * directory for more details.
7 | */
8 |
9 | #ifndef _APP_FONTS_NOTO_SANS_NUMERIC_80_H
10 | #define _APP_FONTS_NOTO_SANS_NUMERIC_80_H
11 |
12 | #include "lvgl.h"
13 |
14 | #ifdef __cplusplus
15 | extern "C" {
16 | #endif
17 |
18 |
19 | extern lv_font_t noto_sans_numeric_80;
20 |
21 | #ifdef __cplusplus
22 | }
23 | #endif
24 | #endif
25 |
26 |
--------------------------------------------------------------------------------
/data/shaders/imgui/ui.vert:
--------------------------------------------------------------------------------
1 | #version 450
2 |
3 | layout (location = 0) in vec2 inPos;
4 | layout (location = 1) in vec2 inUV;
5 | layout (location = 2) in vec4 inColor;
6 |
7 | layout (push_constant) uniform PushConstants {
8 | vec2 scale;
9 | vec2 translate;
10 | } pushConstants;
11 |
12 | layout (location = 0) out vec2 outUV;
13 | layout (location = 1) out vec4 outColor;
14 |
15 | out gl_PerVertex
16 | {
17 | vec4 gl_Position;
18 | };
19 |
20 | void main()
21 | {
22 | outUV = inUV;
23 | outColor = inColor;
24 | gl_Position = vec4(inPos * pushConstants.scale + pushConstants.translate, 0.0, 1.0);
25 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Onex
3 |
4 | ### Quickstart:
5 |
6 | ```
7 | $ git clone --recursive git@github.com:DuncanCragg/OnexApp.git
8 | $ cd OnexApp/
9 | $ cmake .
10 | $ make
11 | $ cd bin; ./OnexApp
12 |
13 | $ cd android
14 | $ (copy your local.properties over)
15 | $ ./gradlew build --parallel
16 | $ adb -d uninstall network.object.onexapp && adb -d install ./onexapp/build/outputs/apk/onexapp-debug.apk
17 |
18 | $ adb logcat OnexApp:D \*:S
19 | $ adb logcat | grep -F "`adb shell ps | grep network.object.onexapp | cut -c10-15`"
20 | ```
21 |
22 |
23 | Read about the [initial plans for Onex here](http://object.network/onex-app.html).
24 |
25 |
26 |
--------------------------------------------------------------------------------
/android/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | google()
6 | mavenCentral()
7 | }
8 | dependencies {
9 | classpath 'com.android.tools.build:gradle:7.3.0'
10 | }
11 | }
12 |
13 | allprojects {
14 | repositories {
15 | google()
16 | mavenCentral()
17 | maven { url "https://jitpack.io" }
18 | }
19 | gradle.projectsEvaluated {
20 | tasks.withType(JavaCompile) {
21 | options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
22 | }
23 | }
24 | }
25 |
26 | task clean(type: Delete) {
27 | delete rootProject.buildDir
28 | }
29 |
30 |
--------------------------------------------------------------------------------
/src/ux-features.h:
--------------------------------------------------------------------------------
1 |
2 | extern char* dragPathId;
3 |
4 | void kill_drag();
5 | void track_drag(char* pathId, bool twodimensions);
6 | void set_drag_scroll(char* path);
7 |
8 |
9 | extern int linkDirection;
10 | extern char* linkFrom;
11 | extern char* linkTo;
12 | extern ImVec2 linkToPos;
13 | extern ImVec2 linkFromPos;
14 |
15 | void track_link(bool from, char* path, int width, int height);
16 | void draw_link();
17 |
18 |
19 | bool is_open(char* path);
20 | void toggle_open(char* path);
21 | void close_all_starting(char* prefix);
22 |
23 | void show_keyboard(float multy);
24 | void hide_keyboard();
25 |
26 | bool filter_auto_input_text(const char* id, char* buf, int buflen, ImGuiTextEditCallback fafn);
27 | int filter_and_autocomplete_calendar_tags(ImGuiTextEditCallbackData* data);
28 | int filter_and_autocomplete_default(ImGuiTextEditCallbackData* data);
29 | int filter_and_autocomplete_property_names(ImGuiTextEditCallbackData* data);
30 |
--------------------------------------------------------------------------------
/android/onexapp/src/main/java/android/network/object/onexapp/EternalServiceJob.java:
--------------------------------------------------------------------------------
1 | // THANKS to https://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android-gt-7
2 |
3 | package network.object.onexapp;
4 |
5 | import android.app.job.JobParameters;
6 | import android.content.*;
7 | import android.util.Log;
8 |
9 | public class EternalServiceJob extends android.app.job.JobService {
10 | private static String LOGNAME="Onex EternalServiceJob";
11 |
12 | @Override
13 | public boolean onStartJob(JobParameters jobParameters) {
14 | Log.d(LOGNAME, "*onStartJob");
15 |
16 | startForegroundService(new Intent(this, EternalService.class));
17 | return false;
18 | }
19 |
20 | @Override
21 | public boolean onStopJob(JobParameters jobParameters) {
22 | Log.d(LOGNAME, "*onStopJob");
23 |
24 | OnexNativeActivity.restartEternal();
25 |
26 | return false;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/android/onexapp/src/main/java/android/network/object/onexapp/BluetoothReceiver.java:
--------------------------------------------------------------------------------
1 | package network.object.onexapp;
2 |
3 | import android.util.Log;
4 | import android.content.BroadcastReceiver;
5 | import android.content.Context;
6 | import android.content.Intent;
7 | import android.bluetooth.BluetoothAdapter;
8 |
9 | public class BluetoothReceiver extends BroadcastReceiver {
10 | private static String LOGNAME="Onex BluetoothReceiver";
11 |
12 | @Override
13 | public void onReceive(Context context, Intent intent) {
14 | if(!BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) return;
15 | if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)==BluetoothAdapter.STATE_OFF){
16 | EternalService.bluetoothOff();
17 | }
18 | else
19 | if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)==BluetoothAdapter.STATE_ON){
20 | EternalService.bluetoothOn();
21 | }
22 | }
23 | }
24 |
25 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 Duncan Cragg
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/external/imgui/LICENSE.txt:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2014-2018 Omar Cornut
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/external/imgui/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2014-2015 Omar Cornut and ImGui contributors
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/android/onexapp/src/main/java/android/network/object/onexapp/EternalServiceRestarter.java:
--------------------------------------------------------------------------------
1 | // THANKS to https://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android-gt-7
2 |
3 | package network.object.onexapp;
4 |
5 | import android.content.BroadcastReceiver;
6 | import android.app.job.JobInfo;
7 | import android.app.job.JobScheduler;
8 | import android.content.*;
9 | import android.util.Log;
10 |
11 | import static android.content.Context.JOB_SCHEDULER_SERVICE;
12 |
13 | public class EternalServiceRestarter extends BroadcastReceiver {
14 | private static String LOGNAME="Onex EternalServiceRestarter";
15 |
16 | private static JobScheduler jobScheduler;
17 |
18 | @Override
19 | public void onReceive(final Context context, Intent intent) {
20 | Log.d(LOGNAME, "*onReceive");
21 | if(jobScheduler==null) jobScheduler=(JobScheduler)context.getSystemService(JOB_SCHEDULER_SERVICE);
22 | ComponentName componentName = new ComponentName(context, EternalServiceJob.class);
23 | JobInfo jobInfo = new JobInfo.Builder(1, componentName).setOverrideDeadline(0).setPersisted(true).build();
24 | jobScheduler.schedule(jobInfo);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/android/onexapp/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 |
5 | namespace "network.object.onexapp"
6 |
7 | compileSdkVersion 33
8 |
9 | defaultConfig {
10 | applicationId "network.object.onexapp"
11 | minSdkVersion 29
12 | targetSdkVersion 33
13 |
14 | ndk {
15 | abiFilters 'arm64-v8a'
16 | }
17 | externalNativeBuild {
18 | cmake {
19 | cppFlags "-std=c++14"
20 | arguments "-DANDROID_STL=c++_shared", '-DANDROID_TOOLCHAIN=clang'
21 | }
22 | }
23 | }
24 |
25 | buildTypes {
26 | release {
27 | minifyEnabled false
28 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
29 | }
30 | }
31 |
32 | externalNativeBuild {
33 | cmake {
34 | version "3.22.1"
35 | path "CMakeLists.txt"
36 | }
37 | }
38 |
39 | ndkVersion "25.2.9519653"
40 |
41 | sourceSets {
42 | main {
43 | }
44 | }
45 |
46 | lintOptions {
47 | abortOnError false
48 | }
49 |
50 | dependencies {
51 | implementation 'com.github.felHR85:UsbSerial:6.1.0'
52 | implementation 'androidx.core:core:1.10.1'
53 | }
54 |
55 | compileOptions {
56 | sourceCompatibility 1.8
57 | targetCompatibility 1.8
58 | }
59 | }
60 |
61 |
--------------------------------------------------------------------------------
/cmake/FindXCB.cmake:
--------------------------------------------------------------------------------
1 | # - FindXCB
2 | #
3 | # Copyright 2015 Valve Coporation
4 |
5 | find_package(PkgConfig)
6 |
7 | if(NOT XCB_FIND_COMPONENTS)
8 | set(XCB_FIND_COMPONENTS xcb)
9 | endif()
10 |
11 | include(FindPackageHandleStandardArgs)
12 | set(XCB_FOUND true)
13 | set(XCB_INCLUDE_DIRS "")
14 | set(XCB_LIBRARIES "")
15 | foreach(comp ${XCB_FIND_COMPONENTS})
16 | # component name
17 | string(TOUPPER ${comp} compname)
18 | string(REPLACE "-" "_" compname ${compname})
19 | # header name
20 | string(REPLACE "xcb-" "" headername xcb/${comp}.h)
21 | # library name
22 | set(libname ${comp})
23 |
24 | pkg_check_modules(PC_${comp} QUIET ${comp})
25 |
26 | find_path(${compname}_INCLUDE_DIR NAMES ${headername}
27 | HINTS
28 | ${PC_${comp}_INCLUDEDIR}
29 | ${PC_${comp}_INCLUDE_DIRS}
30 | )
31 |
32 | find_library(${compname}_LIBRARY NAMES ${libname}
33 | HINTS
34 | ${PC_${comp}_LIBDIR}
35 | ${PC_${comp}_LIBRARY_DIRS}
36 | )
37 |
38 | find_package_handle_standard_args(${comp}
39 | FOUND_VAR ${comp}_FOUND
40 | REQUIRED_VARS ${compname}_INCLUDE_DIR ${compname}_LIBRARY)
41 | mark_as_advanced(${compname}_INCLUDE_DIR ${compname}_LIBRARY)
42 |
43 | list(APPEND XCB_INCLUDE_DIRS ${${compname}_INCLUDE_DIR})
44 | list(APPEND XCB_LIBRARIES ${${compname}_LIBRARY})
45 |
46 | if(NOT ${comp}_FOUND)
47 | set(XCB_FOUND false)
48 | endif()
49 | endforeach()
50 |
51 | list(REMOVE_DUPLICATES XCB_INCLUDE_DIRS)
--------------------------------------------------------------------------------
/android/onexapp/CMakeLists.txt:
--------------------------------------------------------------------------------
1 |
2 | project(OnexApp)
3 |
4 | cmake_minimum_required(VERSION 3.19 FATAL_ERROR)
5 |
6 | set(TOP_DIR ../..)
7 | set(ONEX_KERNEL ../../../OnexKernel)
8 | set(ONEX_LANG ../../../OnexLang)
9 | set(EXTERNAL_DIR ../../external)
10 |
11 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -Wall -Werror -Wno-incompatible-pointer-types-discards-qualifiers -DVK_USE_PLATFORM_ANDROID_KHR -DVK_NO_PROTOTYPES")
12 |
13 | file(GLOB SOURCE_FILES "${ONEX_KERNEL}/src/onl/unix/channel-serial.c" "${ONEX_KERNEL}/src/onl/unix/mem.c" "${ONEX_KERNEL}/src/onl/unix/persistence.c" "${ONEX_KERNEL}/src/onl/unix/properties.c" "${ONEX_KERNEL}/src/onl/unix/random.c" "${ONEX_KERNEL}/src/onl/unix/serial.c" "${ONEX_KERNEL}/src/onl/unix/time.c" "${ONEX_KERNEL}/src/lib/lib.c" "${ONEX_KERNEL}/src/lib/list.c" "${ONEX_KERNEL}/src/lib/value.c" "${ONEX_KERNEL}/src/onn/*.c" "${ONEX_KERNEL}/src/onp/*.c" "${ONEX_LANG}/src/*.c" "${EXTERNAL_DIR}/imgui/*.cpp" "${TOP_DIR}/sascha/*.cpp" "${TOP_DIR}/src/*.cpp")
14 |
15 | add_library(native-lib SHARED ${SOURCE_FILES})
16 |
17 | add_library(native-app-glue STATIC ${ANDROID_NDK}/sources/android/native_app_glue/android_native_app_glue.c)
18 |
19 | #add_subdirectory(../base ${CMAKE_SOURCE_DIR}/../base)
20 |
21 | set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -u ANativeActivity_onCreate")
22 |
23 | include_directories(${EXTERNAL_DIR}/imgui)
24 | include_directories(${EXTERNAL_DIR}/glm)
25 | include_directories(${ONEX_KERNEL}/include)
26 | include_directories(${ONEX_KERNEL}/src)
27 | include_directories(${ONEX_KERNEL}/src/onn)
28 | include_directories(${ONEX_KERNEL}/src/onp)
29 | include_directories(${ONEX_LANG}/include)
30 | include_directories(${ANDROID_NDK}/sources/android/native_app_glue)
31 |
32 | target_link_libraries(
33 | native-lib
34 | native-app-glue
35 | android
36 | log
37 | z
38 | )
39 |
--------------------------------------------------------------------------------
/src/im-gui.h:
--------------------------------------------------------------------------------
1 |
2 | #include "gui.h"
3 |
4 | extern GUI* static_gui;
5 | extern VulkanBase* app;
6 | extern object* user;
7 | extern object* config;
8 | extern char* userUID;
9 |
10 |
11 | extern unsigned char* fontData;
12 | extern int texWidth, texHeight;
13 |
14 | extern bool keyboardCancelled;
15 |
16 | extern uint16_t buttonHeight;
17 | extern uint16_t paddingHeight;
18 | extern uint16_t objectHeight;
19 | extern uint16_t listHeight;
20 |
21 | extern uint16_t shorterValWidth;
22 | extern uint16_t buttonWidth;
23 | extern uint16_t smallButtonWidth;
24 | extern uint16_t rhsPadding;
25 |
26 | extern uint16_t workspace1Width;
27 | extern uint16_t workspace1Height;
28 | extern uint16_t workspace2Width;
29 | extern uint16_t workspace2Height;
30 |
31 | #if defined(__ANDROID__) || defined(TEST_ANDROID_KEYBOARD)
32 | extern uint16_t yOffsetTarget;
33 | extern uint16_t yOffset;
34 | extern uint16_t yOffsetCounter;
35 | #endif
36 |
37 | extern bool calendarView;
38 | extern bool tableView;
39 |
40 | extern ImVec4 actionColour;
41 | extern ImVec4 actionBackground;
42 | extern ImVec4 actionBackgroundActive;
43 |
44 | extern ImVec4 propertyColour;
45 | extern ImVec4 propertyBackground;
46 | extern ImVec4 propertyBackgroundActive;
47 |
48 | extern ImVec4 valueBackground;
49 | extern ImVec4 valueBackgroundActive;
50 |
51 | extern ImVec4 listBackground;
52 | extern ImVec4 listBackgroundDark;
53 |
54 | extern ImVec4 renderColour;
55 | extern ImVec4 renderColourSoft;
56 | extern ImVec4 renderBackground;
57 | extern ImVec4 renderBackgroundActive;
58 |
59 | extern ImVec4 ledOff;
60 | extern ImVec4 ledOn;
61 |
62 | extern ImVec4 btDisconnected;
63 | extern ImVec4 btConnected;
64 |
65 | extern ImVec4 schemeBrown;
66 | extern ImVec4 schemeYellow;
67 | extern ImVec4 schemeMauve;
68 | extern ImVec4 schemePurple;
69 | extern ImVec4 schemeGreen;
70 | extern ImVec4 schemeLightPurple;
71 | extern ImVec4 schemeDarkerPurple;
72 | extern ImVec4 schemePlum;
73 |
74 | void init_imgui(float width, float height);
75 | void get_font_info();
76 | void set_scaling();
77 |
78 | void invoke_single_set(char* uid, char* key, char* val);
79 | void invoke_single_add(char* uid, char* key, char* val);
80 |
81 |
--------------------------------------------------------------------------------
/android/onexapp/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
23 |
24 |
25 | Onxidium
26 | Onex Onxidium
27 |
28 | Onex devices
29 | Scan
30 | Cancel
31 | paired
32 | Select a device
33 | Scanning for devices...
34 | Bluetooth Low Energy not supported
35 |
36 |
37 |
--------------------------------------------------------------------------------
/src/gui.h:
--------------------------------------------------------------------------------
1 | #ifndef GUI_H
2 | #define GUI_H
3 |
4 | /*
5 | * Vulkan Example - imGui (https://github.com/ocornut/imgui)
6 | *
7 | * Copyright (C) 2017 by Sascha Willems - www.saschawillems.de
8 | *
9 | * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
10 | */
11 |
12 | #include
13 | #include
14 | #include
15 | extern void ImStrncpy(char* dst, const char* src, size_t count);
16 | #include
17 | #include
18 | #include
19 | #include
20 |
21 | extern "C" {
22 | #include
23 | #include
24 | #include
25 | #include
26 | }
27 |
28 | #include
29 | #include
30 |
31 | #include
32 | #include "../sascha/VulkanBase.h"
33 | #include "../sascha/VulkanDevice.hpp"
34 | #include "../sascha/VulkanBuffer.hpp"
35 |
36 | class GUI {
37 | public:
38 | VkSampler sampler;
39 | vks::Buffer vertexBuffer;
40 | vks::Buffer indexBuffer;
41 | int32_t vertexCount = 0;
42 | int32_t indexCount = 0;
43 | VkDeviceMemory fontMemory = VK_NULL_HANDLE;
44 | VkImage fontImage = VK_NULL_HANDLE;
45 | VkImageView fontView = VK_NULL_HANDLE;
46 | VkPipelineCache pipelineCache;
47 | VkPipelineLayout pipelineLayout;
48 | VkPipeline pipeline;
49 | VkDescriptorPool descriptorPool;
50 | VkDescriptorSetLayout descriptorSetLayout;
51 | VkDescriptorSet descriptorSet;
52 | vks::VulkanDevice *device;
53 |
54 | struct PushConstBlock {
55 | glm::vec2 scale;
56 | glm::vec2 translate;
57 | } pushConstBlock;
58 |
59 | GUI(VulkanBase *app);
60 |
61 | void prepare();
62 | void setUpKeyMap();
63 | void createFontImage();
64 | void setupImageBuffer(VkQueue copyQueue);
65 | void createSampler();
66 | void setupDescriptorPool();
67 | void setupDescriptorSetLayout();
68 | void setupDescriptorSets();
69 | void createPipelineCache();
70 | void createPipelines(VkRenderPass renderPass);
71 | void updateBuffers();
72 | void drawFrame(VkCommandBuffer commandBuffer);
73 | void buildCommandBuffers(int32_t i);
74 | void updateUniformBuffers(){}
75 | void addAnyKeySym();
76 | void keyPressed(int32_t keyCode, char32_t u32key);
77 | void keyReleased(int32_t keyCode);
78 | void render();
79 |
80 | ~GUI();
81 | };
82 |
83 | #endif
84 |
--------------------------------------------------------------------------------
/android/onexapp/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
23 |
24 |
25 |
29 |
36 |
37 |
38 |
41 |
42 | #FF000000
43 | #FFF2F2F2
44 |
45 |
46 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/android/onexapp/src/main/res/layout/device_element.xml:
--------------------------------------------------------------------------------
1 |
2 |
23 |
30 |
31 |
39 |
40 |
48 |
49 |
55 |
56 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/cmake/FindWayland.cmake:
--------------------------------------------------------------------------------
1 | # Try to find Wayland on a Unix system
2 | #
3 | # This will define:
4 | #
5 | # WAYLAND_FOUND - True if Wayland is found
6 | # WAYLAND_LIBRARIES - Link these to use Wayland
7 | # WAYLAND_INCLUDE_DIR - Include directory for Wayland
8 | # WAYLAND_DEFINITIONS - Compiler flags for using Wayland
9 | #
10 | # In addition the following more fine grained variables will be defined:
11 | #
12 | # WAYLAND_CLIENT_FOUND WAYLAND_CLIENT_INCLUDE_DIR WAYLAND_CLIENT_LIBRARIES
13 | # WAYLAND_SERVER_FOUND WAYLAND_SERVER_INCLUDE_DIR WAYLAND_SERVER_LIBRARIES
14 | # WAYLAND_EGL_FOUND WAYLAND_EGL_INCLUDE_DIR WAYLAND_EGL_LIBRARIES
15 | #
16 | # Copyright (c) 2013 Martin Gräßlin
17 | #
18 | # Redistribution and use is allowed according to the terms of the BSD license.
19 | # For details see the accompanying COPYING-CMAKE-SCRIPTS file.
20 |
21 | IF (NOT WIN32)
22 | IF (WAYLAND_INCLUDE_DIR AND WAYLAND_LIBRARIES)
23 | # In the cache already
24 | SET(WAYLAND_FIND_QUIETLY TRUE)
25 | ENDIF ()
26 |
27 | # Use pkg-config to get the directories and then use these values
28 | # in the FIND_PATH() and FIND_LIBRARY() calls
29 | FIND_PACKAGE(PkgConfig)
30 | PKG_CHECK_MODULES(PKG_WAYLAND QUIET wayland-client wayland-server wayland-egl wayland-cursor)
31 |
32 | SET(WAYLAND_DEFINITIONS ${PKG_WAYLAND_CFLAGS})
33 |
34 | FIND_PATH(WAYLAND_CLIENT_INCLUDE_DIR NAMES wayland-client.h HINTS ${PKG_WAYLAND_INCLUDE_DIRS})
35 | FIND_PATH(WAYLAND_SERVER_INCLUDE_DIR NAMES wayland-server.h HINTS ${PKG_WAYLAND_INCLUDE_DIRS})
36 | FIND_PATH(WAYLAND_EGL_INCLUDE_DIR NAMES wayland-egl.h HINTS ${PKG_WAYLAND_INCLUDE_DIRS})
37 | FIND_PATH(WAYLAND_CURSOR_INCLUDE_DIR NAMES wayland-cursor.h HINTS ${PKG_WAYLAND_INCLUDE_DIRS})
38 |
39 | FIND_LIBRARY(WAYLAND_CLIENT_LIBRARIES NAMES wayland-client HINTS ${PKG_WAYLAND_LIBRARY_DIRS})
40 | FIND_LIBRARY(WAYLAND_SERVER_LIBRARIES NAMES wayland-server HINTS ${PKG_WAYLAND_LIBRARY_DIRS})
41 | FIND_LIBRARY(WAYLAND_EGL_LIBRARIES NAMES wayland-egl HINTS ${PKG_WAYLAND_LIBRARY_DIRS})
42 | FIND_LIBRARY(WAYLAND_CURSOR_LIBRARIES NAMES wayland-cursor HINTS ${PKG_WAYLAND_LIBRARY_DIRS})
43 |
44 | set(WAYLAND_INCLUDE_DIR ${WAYLAND_CLIENT_INCLUDE_DIR} ${WAYLAND_SERVER_INCLUDE_DIR} ${WAYLAND_EGL_INCLUDE_DIR} ${WAYLAND_CURSOR_INCLUDE_DIR})
45 |
46 | set(WAYLAND_LIBRARIES ${WAYLAND_CLIENT_LIBRARIES} ${WAYLAND_SERVER_LIBRARIES} ${WAYLAND_EGL_LIBRARIES} ${WAYLAND_CURSOR_LIBRARIES})
47 |
48 | list(REMOVE_DUPLICATES WAYLAND_INCLUDE_DIR)
49 |
50 | include(FindPackageHandleStandardArgs)
51 |
52 | FIND_PACKAGE_HANDLE_STANDARD_ARGS(WAYLAND_CLIENT DEFAULT_MSG WAYLAND_CLIENT_LIBRARIES WAYLAND_CLIENT_INCLUDE_DIR)
53 | FIND_PACKAGE_HANDLE_STANDARD_ARGS(WAYLAND_SERVER DEFAULT_MSG WAYLAND_SERVER_LIBRARIES WAYLAND_SERVER_INCLUDE_DIR)
54 | FIND_PACKAGE_HANDLE_STANDARD_ARGS(WAYLAND_EGL DEFAULT_MSG WAYLAND_EGL_LIBRARIES WAYLAND_EGL_INCLUDE_DIR)
55 | FIND_PACKAGE_HANDLE_STANDARD_ARGS(WAYLAND_CURSOR DEFAULT_MSG WAYLAND_CURSOR_LIBRARIES WAYLAND_CURSOR_INCLUDE_DIR)
56 | FIND_PACKAGE_HANDLE_STANDARD_ARGS(WAYLAND DEFAULT_MSG WAYLAND_LIBRARIES WAYLAND_INCLUDE_DIR)
57 |
58 | MARK_AS_ADVANCED(
59 | WAYLAND_INCLUDE_DIR WAYLAND_LIBRARIES
60 | WAYLAND_CLIENT_INCLUDE_DIR WAYLAND_CLIENT_LIBRARIES
61 | WAYLAND_SERVER_INCLUDE_DIR WAYLAND_SERVER_LIBRARIES
62 | WAYLAND_EGL_INCLUDE_DIR WAYLAND_EGL_LIBRARIES
63 | WAYLAND_CURSOR_INCLUDE_DIR WAYLAND_CURSOR_LIBRARIES
64 | )
65 |
66 | ENDIF ()
67 |
--------------------------------------------------------------------------------
/android/onexapp/src/main/res/layout/device_list.xml:
--------------------------------------------------------------------------------
1 |
2 |
23 |
24 |
28 |
29 |
33 |
34 |
44 |
45 |
52 |
53 |
54 |
55 |
58 |
64 |
65 |
73 |
74 |
79 |
80 |
81 |
82 |
--------------------------------------------------------------------------------
/external/imgui/imconfig.h:
--------------------------------------------------------------------------------
1 | //-----------------------------------------------------------------------------
2 | // COMPILE-TIME OPTIONS FOR DEAR IMGUI
3 | // Most options (memory allocation, clipboard callbacks, etc.) can be set at runtime via the ImGuiIO structure - ImGui::GetIO().
4 | //-----------------------------------------------------------------------------
5 | // A) You may edit imconfig.h (and not overwrite it when updating imgui, or maintain a patch/branch with your modifications to imconfig.h)
6 | // B) or add configuration directives in your own file and compile with #define IMGUI_USER_CONFIG "myfilename.h"
7 | // Note that options such as IMGUI_API, IM_VEC2_CLASS_EXTRA or ImDrawIdx needs to be defined consistently everywhere you include imgui.h, not only for the imgui*.cpp compilation units.
8 | //-----------------------------------------------------------------------------
9 |
10 | #pragma once
11 |
12 | //---- Define assertion handler. Defaults to calling assert().
13 | //#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
14 |
15 | //---- Define attributes of all API symbols declarations, e.g. for DLL under Windows.
16 | //#define IMGUI_API __declspec( dllexport )
17 | //#define IMGUI_API __declspec( dllimport )
18 |
19 | //---- Don't define obsolete functions names. Consider enabling from time to time or when updating to reduce likelihood of using already obsolete function/names
20 | //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
21 |
22 | //---- Don't implement default handlers for Windows (so as not to link with certain functions)
23 | //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // Don't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc.
24 | //#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // Don't use and link with ImmGetContext/ImmSetCompositionWindow.
25 |
26 | //---- Don't implement demo windows functionality (ShowDemoWindow()/ShowStyleEditor()/ShowUserGuide() methods will be empty)
27 | //---- It is very strongly recommended to NOT disable the demo windows. Please read the comment at the top of imgui_demo.cpp.
28 | //#define IMGUI_DISABLE_DEMO_WINDOWS
29 |
30 | //---- Don't implement ImFormatString(), ImFormatStringV() so you can reimplement them yourself.
31 | //#define IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
32 |
33 | //---- Include imgui_user.h at the end of imgui.h as a convenience
34 | //#define IMGUI_INCLUDE_IMGUI_USER_H
35 |
36 | //---- Pack colors to BGRA8 instead of RGBA8 (if you needed to convert from one to another anyway)
37 | //#define IMGUI_USE_BGRA_PACKED_COLOR
38 |
39 | //---- Implement STB libraries in a namespace to avoid linkage conflicts (defaults to global namespace)
40 | //#define IMGUI_STB_NAMESPACE ImGuiStb
41 |
42 | //---- Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4.
43 | // This will be inlined as part of ImVec2 and ImVec4 class declarations.
44 | /*
45 | #define IM_VEC2_CLASS_EXTRA \
46 | ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \
47 | operator MyVec2() const { return MyVec2(x,y); }
48 |
49 | #define IM_VEC4_CLASS_EXTRA \
50 | ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \
51 | operator MyVec4() const { return MyVec4(x,y,z,w); }
52 | */
53 |
54 | //---- Use 32-bit vertex indices (instead of default 16-bit) to allow meshes with more than 64K vertices. Render function needs to support it.
55 | //#define ImDrawIdx unsigned int
56 |
57 | //---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files.
58 | /*
59 | namespace ImGui
60 | {
61 | void MyFunction(const char* name, const MyMatrix44& v);
62 | }
63 | */
64 |
65 | #define IMGUI_TEXT_ESCAPE_SKIP() \
66 | if (c == '\033' && s[1] && s[2] && s[3] && s[4]) \
67 | { \
68 | s += 5; \
69 | continue; \
70 | }
71 |
72 | #define IMGUI_TEXT_ESCAPE_RENDER() \
73 | if (c == '\033' && s[1] && s[2] && s[3] && s[4]) \
74 | { \
75 | const unsigned char *us = (const unsigned char *)s; \
76 | col = IM_COL32(us[1], us[2], us[3], us[4]); \
77 | s += 5; \
78 | continue; \
79 | }
80 |
--------------------------------------------------------------------------------
/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
2 | cmake_policy(VERSION 2.8)
3 | cmake_policy(SET CMP0015 NEW)
4 | set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake")
5 |
6 | set(NAME vulkanApp)
7 | set(APP_NAME OnexApp)
8 |
9 | project(${NAME})
10 |
11 | include_directories(external)
12 | include_directories(external/glm)
13 | include_directories(external/imgui)
14 | include_directories(sascha)
15 |
16 | include_directories(../OnexKernel/include)
17 | include_directories(../OnexLang/include)
18 |
19 | link_directories(../OnexKernel)
20 | link_directories(../OnexLang)
21 |
22 | OPTION(USE_D2D_WSI "Build the project using Direct to Display swapchain" OFF)
23 | OPTION(USE_WAYLAND_WSI "Build the project using Wayland swapchain" OFF)
24 |
25 | # Use FindVulkan module added with CMAKE 3.7
26 | if (NOT CMAKE_VERSION VERSION_LESS 3.7.0)
27 | message(STATUS "Using module to find Vulkan")
28 | find_package(Vulkan)
29 | endif()
30 |
31 | IF(WIN32)
32 | IF (NOT Vulkan_FOUND)
33 | find_library(Vulkan_LIBRARY NAMES vulkan-1 vulkan PATHS ${CMAKE_SOURCE_DIR}/libs/vulkan)
34 | IF (Vulkan_LIBRARY)
35 | set(Vulkan_FOUND ON)
36 | MESSAGE("Using bundled Vulkan library version")
37 | ENDIF()
38 | ENDIF()
39 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DVK_USE_PLATFORM_WIN32_KHR")
40 | ELSE(WIN32)
41 | IF (NOT Vulkan_FOUND)
42 | find_library(Vulkan_LIBRARY NAMES vulkan HINTS "$ENV{VULKAN_SDK}/lib" "${CMAKE_SOURCE_DIR}/libs/vulkan" REQUIRED)
43 | IF (Vulkan_LIBRARY)
44 | set(Vulkan_FOUND ON)
45 | MESSAGE("Using bundled Vulkan library version")
46 | ENDIF()
47 | ENDIF()
48 | find_package(Threads REQUIRED)
49 | IF(USE_D2D_WSI)
50 | MESSAGE("Using direct to display extension...")
51 | add_definitions(-D_DIRECT2DISPLAY)
52 | ELSEIF(USE_WAYLAND_WSI)
53 | find_package(Wayland REQUIRED)
54 | if (NOT WAYLAND_FOUND)
55 | message(FATAL_ERROR "Wayland development package not found")
56 | endif ()
57 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DVK_USE_PLATFORM_WAYLAND_KHR")
58 | include_directories(${WAYLAND_INCLUDE_DIR})
59 | ELSE(USE_D2D_WSI)
60 | find_package(XCB REQUIRED COMPONENTS xcb xkbcommon)
61 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DVK_USE_PLATFORM_XCB_KHR")
62 | ENDIF(USE_D2D_WSI)
63 | # Todo : android?
64 | ENDIF(WIN32)
65 |
66 | IF (NOT Vulkan_FOUND)
67 | message(FATAL_ERROR "Could not find Vulkan library!")
68 | ELSE()
69 | message(STATUS ${Vulkan_LIBRARY})
70 | ENDIF()
71 |
72 | # Set preprocessor defines
73 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DNOMINMAX -D_USE_MATH_DEFINES -Wno-write-strings")
74 |
75 | # Clang specific stuff
76 | if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
77 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-switch-enum")
78 | endif()
79 |
80 | # Debug flags
81 | set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall")
82 | if(CMAKE_COMPILER_IS_GNUCXX)
83 | set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wextra -Wundef")
84 | endif(CMAKE_COMPILER_IS_GNUCXX)
85 |
86 | add_definitions(-D_CRT_SECURE_NO_WARNINGS)
87 | add_definitions(-std=c++11)
88 |
89 | function(buildExample SRC)
90 | file(GLOB SOURCE *.cpp ${SRC}/*.cpp)
91 | SET(MAIN_CPP ${SRC}/${APP_NAME}.cpp)
92 | file(GLOB ADD_SOURCE external/imgui/*.cpp)
93 | SET(SOURCE ${SOURCE} ${ADD_SOURCE})
94 | if(WIN32)
95 | add_executable(${APP_NAME} WIN32 ${MAIN_CPP} ${SOURCE})
96 | target_link_libraries(${APP_NAME} sascha ${Vulkan_LIBRARY} ${WINLIBS})
97 | else(WIN32)
98 | add_executable(${APP_NAME} ${MAIN_CPP} ${SOURCE})
99 | target_link_libraries(${APP_NAME} sascha onex-kernel-xcb onex-lang-x86)
100 | endif(WIN32)
101 | endfunction(buildExample)
102 |
103 | function(buildExamples)
104 | foreach(SRC ${SOURCES})
105 | buildExample(${SRC})
106 | endforeach(SRC)
107 | endfunction(buildExamples)
108 |
109 | # Compiler specific stuff
110 | IF(MSVC)
111 | SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /EHsc")
112 | ENDIF(MSVC)
113 |
114 | IF(WIN32)
115 | # Nothing here (yet)
116 | ELSE(WIN32)
117 | link_libraries(${XCB_LIBRARIES} ${Vulkan_LIBRARY} ${WAYLAND_CLIENT_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT})
118 | ENDIF(WIN32)
119 |
120 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/")
121 |
122 | add_subdirectory(sascha)
123 |
124 | set(SOURCES src)
125 |
126 | buildExamples()
127 |
--------------------------------------------------------------------------------
/src/OnexAppBL.c:
--------------------------------------------------------------------------------
1 |
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #if defined(BOARD_PINETIME)
9 | #include
10 | #include
11 | #endif
12 | #include
13 | #include
14 | #include
15 |
16 | object* button;
17 | object* light;
18 | char* buttonuid;
19 | char* lightuid;
20 |
21 | static void button_changed(uint8_t pin, uint8_t type);
22 |
23 | #if defined(BOARD_PINETIME)
24 | static touch_info_t ti;
25 | static bool new_touch_info=false;
26 |
27 | void touched(touch_info_t touchinfo)
28 | {
29 | ti=touchinfo;
30 | new_touch_info=true;
31 | }
32 | #endif
33 |
34 | bool evaluate_button_io(object* button, void* pressed);
35 | bool evaluate_light_io(object* light, void* d);
36 |
37 | void* x;
38 | #define WHERESTHEHEAP(s) x = malloc(1); log_write("heap after %s: %x\n", s, x);
39 |
40 | int main()
41 | {
42 | properties* config = properties_new(32);
43 | properties_set(config, "channels", list_vals_new_from_fixed("radio serial"));
44 |
45 | log_init(config);
46 | time_init();
47 | gpio_init();
48 | random_init();
49 | serial_init(0,0,0);
50 |
51 | #if defined(BOARD_PINETIME)
52 | gfx_init();
53 | gfx_screen_colour(0xC618);
54 | gfx_text_colour(0x001F);
55 | gfx_screen_fill();
56 | touch_init(touched);
57 | #endif
58 |
59 | onex_init(config);
60 |
61 | #if defined(BOARD_PCA10059)
62 | gpio_mode_cb(BUTTON_1, INPUT_PULLUP, RISING_AND_FALLING, button_changed);
63 | gpio_mode(LED1_G, OUTPUT);
64 | gpio_mode(LED2_B, OUTPUT);
65 | #elif defined(BOARD_PINETIME)
66 | gpio_mode_cb(BUTTON_1, INPUT_PULLDOWN, RISING_AND_FALLING, button_changed);
67 | gpio_mode( BUTTON_ENABLE, OUTPUT);
68 | gpio_set( BUTTON_ENABLE, 1);
69 | gpio_mode(LCD_BACKLIGHT_HIGH, OUTPUT);
70 | #endif
71 |
72 | onex_set_evaluators("eval_button", evaluate_edit_rule, evaluate_button_io, 0);
73 | onex_set_evaluators("eval_light", evaluate_edit_rule, evaluate_light_logic, evaluate_light_io, 0);
74 |
75 | button=object_new(0, "eval_button", "editable button", 4);
76 | light =object_new(0, "eval_light", "editable light", 4);
77 |
78 | buttonuid=object_property(button, "UID");
79 | lightuid=object_property(light, "UID");
80 |
81 | object_property_set(button, "name", "£€§");
82 |
83 | object_property_set(light, "light", "off");
84 |
85 | object_property_add(onex_device_object, (char*)"io", buttonuid);
86 | object_property_add(onex_device_object, (char*)"io", lightuid);
87 |
88 | onex_run_evaluators(lightuid, 0);
89 |
90 | #if defined(BOARD_PCA10059)
91 | gpio_set(LED1_G, LEDS_ACTIVE_STATE);
92 | gpio_set(LED2_B, !LEDS_ACTIVE_STATE);
93 | #elif defined(BOARD_PINETIME)
94 | gfx_pos(10, 10);
95 | gfx_text("OnexOS");
96 | gpio_set(LCD_BACKLIGHT_HIGH, LEDS_ACTIVE_STATE);
97 | #endif
98 |
99 | while(1){
100 | onex_loop();
101 | #if defined(BOARD_PINETIME)
102 | if(new_touch_info){
103 | new_touch_info=false;
104 | if(ti.gesture==TOUCH_GESTURE_TAP_LONG){
105 | gpio_set(LCD_BACKLIGHT_HIGH, !LEDS_ACTIVE_STATE);
106 | }
107 | else {
108 | gpio_set(LCD_BACKLIGHT_HIGH, LEDS_ACTIVE_STATE);
109 | }
110 | button_changed(ti.action==TOUCH_ACTION_CONTACT);
111 | }
112 | #endif
113 | }
114 | }
115 |
116 | static void button_changed(uint8_t pin, uint8_t type){
117 | bool button_pressed=(gpio_get(pin)==BUTTONS_ACTIVE_STATE);
118 | #if defined(BOARD_PINETIME)
119 | gfx_pos(10, 110);
120 | gfx_text(button_pressed? "X": "O");
121 | #endif
122 | onex_run_evaluators(buttonuid, (void*)(bool)button_pressed);
123 | }
124 |
125 | bool evaluate_button_io(object* button, void* pressed)
126 | {
127 | char* s=(char*)(pressed? "down": "up");
128 | object_property_set(button, "state", s);
129 | return true;
130 | }
131 |
132 | bool evaluate_light_io(object* light, void* d)
133 | {
134 | if(object_property_is(light, "light", "on")){
135 | #if defined(BOARD_PCA10059)
136 | gpio_set(LED2_B, LEDS_ACTIVE_STATE);
137 | #elif defined(BOARD_PINETIME)
138 | gfx_pos(10, 60);
139 | gfx_text("ON");
140 | #endif
141 | } else {
142 | #if defined(BOARD_PCA10059)
143 | gpio_set(LED2_B, !LEDS_ACTIVE_STATE);
144 | #elif defined(BOARD_PINETIME)
145 | gfx_pos(10, 60);
146 | gfx_text("OFF");
147 | #endif
148 | }
149 | return true;
150 | }
151 |
152 |
--------------------------------------------------------------------------------
/android/onexapp/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
28 |
29 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
51 |
52 |
53 |
54 |
57 |
58 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
70 |
71 |
72 |
73 |
74 |
75 |
82 |
83 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
99 |
100 |
101 |
102 |
--------------------------------------------------------------------------------
/sascha/VulkanDebug.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #include "vulkan/vulkan.h"
3 |
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 | #ifdef _WIN32
14 | #include
15 | #include
16 | #include
17 | #endif
18 | #ifdef __ANDROID__
19 | #include "VulkanAndroid.h"
20 | #endif
21 | #define GLM_FORCE_RADIANS
22 | #define GLM_FORCE_DEPTH_ZERO_TO_ONE
23 | #include
24 |
25 | namespace vks
26 | {
27 | namespace debug
28 | {
29 | // Default validation layers
30 | extern int validationLayerCount;
31 | extern const char *validationLayerNames[];
32 |
33 | // Default debug callback
34 | VkBool32 messageCallback(
35 | VkDebugReportFlagsEXT flags,
36 | VkDebugReportObjectTypeEXT objType,
37 | uint64_t srcObject,
38 | size_t location,
39 | int32_t msgCode,
40 | const char* pLayerPrefix,
41 | const char* pMsg,
42 | void* pUserData);
43 |
44 | // Load debug function pointers and set debug callback
45 | // if callBack is NULL, default message callback will be used
46 | void setupDebugging(
47 | VkInstance instance,
48 | VkDebugReportFlagsEXT flags,
49 | VkDebugReportCallbackEXT callBack);
50 | // Clear debug callback
51 | void freeDebugCallback(VkInstance instance);
52 | }
53 |
54 | // Setup and functions for the VK_EXT_debug_marker_extension
55 | // Extension spec can be found at https://github.com/KhronosGroup/Vulkan-Docs/blob/1.0-VK_EXT_debug_marker/doc/specs/vulkan/appendices/VK_EXT_debug_marker.txt
56 | // Note that the extension will only be present if run from an offline debugging application
57 | // The actual check for extension presence and enabling it on the device is done in the example base class
58 | // See VulkanBase::createInstance and VulkanBase::createDevice (VulkanBase.cpp)
59 | namespace debugmarker
60 | {
61 | // Set to true if function pointer for the debug marker are available
62 | extern bool active;
63 |
64 | // Get function pointers for the debug report extensions from the device
65 | void setup(VkDevice device);
66 |
67 | // Sets the debug name of an object
68 | // All Objects in Vulkan are represented by their 64-bit handles which are passed into this function
69 | // along with the object type
70 | void setObjectName(VkDevice device, uint64_t object, VkDebugReportObjectTypeEXT objectType, const char *name);
71 |
72 | // Set the tag for an object
73 | void setObjectTag(VkDevice device, uint64_t object, VkDebugReportObjectTypeEXT objectType, uint64_t name, size_t tagSize, const void* tag);
74 |
75 | // Start a new debug marker region
76 | void beginRegion(VkCommandBuffer cmdbuffer, const char* pMarkerName, glm::vec4 color);
77 |
78 | // Insert a new debug marker into the command buffer
79 | void insert(VkCommandBuffer cmdbuffer, std::string markerName, glm::vec4 color);
80 |
81 | // End the current debug marker region
82 | void endRegion(VkCommandBuffer cmdBuffer);
83 |
84 | // Object specific naming functions
85 | void setCommandBufferName(VkDevice device, VkCommandBuffer cmdBuffer, const char * name);
86 | void setQueueName(VkDevice device, VkQueue queue, const char * name);
87 | void setImageName(VkDevice device, VkImage image, const char * name);
88 | void setSamplerName(VkDevice device, VkSampler sampler, const char * name);
89 | void setBufferName(VkDevice device, VkBuffer buffer, const char * name);
90 | void setDeviceMemoryName(VkDevice device, VkDeviceMemory memory, const char * name);
91 | void setShaderModuleName(VkDevice device, VkShaderModule shaderModule, const char * name);
92 | void setPipelineName(VkDevice device, VkPipeline pipeline, const char * name);
93 | void setPipelineLayoutName(VkDevice device, VkPipelineLayout pipelineLayout, const char * name);
94 | void setRenderPassName(VkDevice device, VkRenderPass renderPass, const char * name);
95 | void setFramebufferName(VkDevice device, VkFramebuffer framebuffer, const char * name);
96 | void setDescriptorSetLayoutName(VkDevice device, VkDescriptorSetLayout descriptorSetLayout, const char * name);
97 | void setDescriptorSetName(VkDevice device, VkDescriptorSet descriptorSet, const char * name);
98 | void setSemaphoreName(VkDevice device, VkSemaphore semaphore, const char * name);
99 | void setFenceName(VkDevice device, VkFence fence, const char * name);
100 | void setEventName(VkDevice device, VkEvent _event, const char * name);
101 | };
102 | }
103 |
--------------------------------------------------------------------------------
/sascha/VulkanTools.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Assorted Vulkan helper functions
3 | *
4 | * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de
5 | *
6 | * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
7 | */
8 |
9 | #pragma once
10 |
11 | #include "vulkan/vulkan.h"
12 | #include "VulkanInitializers.hpp"
13 |
14 | #include
15 | #include
16 | #include
17 | #include
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #if defined(_WIN32)
26 | #include
27 | #include
28 | #include
29 | #elif defined(__ANDROID__)
30 | #include "VulkanAndroid.h"
31 | #include
32 | #endif
33 |
34 | // Custom define for better code readability
35 | #define VK_FLAGS_NONE 0
36 | // Default fence timeout in nanoseconds
37 | #define DEFAULT_FENCE_TIMEOUT 100000000000
38 |
39 | // Macro to check and display Vulkan return results
40 | #if defined(__ANDROID__)
41 | #define VK_CHECK_RESULT(f) \
42 | { \
43 | VkResult res = (f); \
44 | if (res != VK_SUCCESS) \
45 | { \
46 | LOGE("Fatal : VkResult is \" %s \" in %s at line %d", vks::tools::errorString(res).c_str(), __FILE__, __LINE__); \
47 | assert(res == VK_SUCCESS); \
48 | } \
49 | }
50 | #else
51 | #define VK_CHECK_RESULT(f) \
52 | { \
53 | VkResult res = (f); \
54 | if (res != VK_SUCCESS) \
55 | { \
56 | std::cout << "Fatal : VkResult is \"" << vks::tools::errorString(res) << "\" in " << __FILE__ << " at line " << __LINE__ << std::endl; \
57 | assert(res == VK_SUCCESS); \
58 | } \
59 | }
60 | #endif
61 |
62 | #if defined(__ANDROID__)
63 | #define ASSET_PATH ""
64 | #else
65 | #define ASSET_PATH "./../data/"
66 | #endif
67 |
68 | namespace vks
69 | {
70 | namespace tools
71 | {
72 | /** @brief Returns an error code as a string */
73 | std::string errorString(VkResult errorCode);
74 |
75 | /** @brief Returns the device type as a string */
76 | std::string physicalDeviceTypeString(VkPhysicalDeviceType type);
77 |
78 | // Selected a suitable supported depth format starting with 32 bit down to 16 bit
79 | // Returns false if none of the depth formats in the list is supported by the device
80 | VkBool32 getSupportedDepthFormat(VkPhysicalDevice physicalDevice, VkFormat *depthFormat);
81 |
82 | // Put an image memory barrier for setting an image layout on the sub resource into the given command buffer
83 | void setImageLayout(
84 | VkCommandBuffer cmdbuffer,
85 | VkImage image,
86 | VkImageLayout oldImageLayout,
87 | VkImageLayout newImageLayout,
88 | VkImageSubresourceRange subresourceRange,
89 | VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
90 | VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
91 | // Uses a fixed sub resource layout with first mip level and layer
92 | void setImageLayout(
93 | VkCommandBuffer cmdbuffer,
94 | VkImage image,
95 | VkImageAspectFlags aspectMask,
96 | VkImageLayout oldImageLayout,
97 | VkImageLayout newImageLayout,
98 | VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
99 | VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
100 |
101 | /** @brief Inser an image memory barrier into the command buffer */
102 | void insertImageMemoryBarrier(
103 | VkCommandBuffer cmdbuffer,
104 | VkImage image,
105 | VkAccessFlags srcAccessMask,
106 | VkAccessFlags dstAccessMask,
107 | VkImageLayout oldImageLayout,
108 | VkImageLayout newImageLayout,
109 | VkPipelineStageFlags srcStageMask,
110 | VkPipelineStageFlags dstStageMask,
111 | VkImageSubresourceRange subresourceRange);
112 |
113 | // Display error message and exit on fatal error
114 | void exitFatal(std::string message, std::string caption, bool silent = false);
115 |
116 | // Load a SPIR-V shader (binary)
117 | #if defined(__ANDROID__)
118 | VkShaderModule loadShader(AAssetManager* assetManager, const char *fileName, VkDevice device);
119 | #else
120 | VkShaderModule loadShader(const char *fileName, VkDevice device);
121 | #endif
122 |
123 | // Load a GLSL shader (text)
124 | // Note: GLSL support requires vendor-specific extensions to be enabled and is not a core-feature of Vulkan
125 | VkShaderModule loadShaderGLSL(const char *fileName, VkDevice device, VkShaderStageFlagBits stage);
126 |
127 | /** @brief Checks if a file exists */
128 | bool fileExists(const std::string &filename);
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/sascha/keycodes.hpp:
--------------------------------------------------------------------------------
1 | /*
2 | * Key codes for multiple platforms
3 | *
4 | * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de
5 | *
6 | * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
7 | */
8 |
9 | #pragma once
10 |
11 | #if defined(_WIN32)
12 | #define KEY_ESCAPE VK_ESCAPE
13 | #define KEY_F1 VK_F1
14 | #define KEY_F2 VK_F2
15 | #define KEY_F3 VK_F3
16 | #define KEY_F4 VK_F4
17 | #define KEY_F5 VK_F5
18 | #define KEY_W 0x57
19 | #define KEY_A 0x41
20 | #define KEY_S 0x53
21 | #define KEY_D 0x44
22 | #define KEY_P 0x50
23 | #define KEY_SPACE 0x20
24 | #define KEY_KPADD 0x6B
25 | #define KEY_KPSUB 0x6D
26 | #define KEY_B 0x42
27 | #define KEY_F 0x46
28 | #define KEY_L 0x4C
29 | #define KEY_N 0x4E
30 | #define KEY_O 0x4F
31 | #define KEY_T 0x54
32 | #elif defined(__ANDROID__)
33 | #define KEY_BACKSPACE 0x43
34 | #define KEY_ENTER 0x42
35 | #define KEY_SPACE 0x3e
36 | #define KEY_ESCAPE 0x0
37 | #define KEY_F1 0x0
38 | #define KEY_F2 0x0
39 | #define KEY_F3 0x0
40 | #define KEY_F4 0x0
41 | #define KEY_W 0x0
42 | #define KEY_A 0x0
43 | #define KEY_S 0x0
44 | #define KEY_D 0x0
45 | #define KEY_P 0x0
46 | #define KEY_KPADD 0x0
47 | #define KEY_KPSUB 0x0
48 | #define KEY_B 0x0
49 | #define KEY_F 0x0
50 | #define KEY_G 0x0
51 | #define KEY_H 0x0
52 | #define KEY_J 0x0
53 | #define KEY_K 0x0
54 | #define KEY_L 0x0
55 | #define KEY_N 0x0
56 | #define KEY_O 0x0
57 | #define KEY_T 0x0
58 | #define KEY_CTRL_LEFT 0x0
59 | #define KEY_CTRL_RIGHT 0x0
60 | #define KEY_SHIFT_LEFT 0x0
61 | #define KEY_SHIFT_RIGHT 0x0
62 | #define KEY_ALT_LEFT 0x0
63 | #define KEY_ALT_RIGHT 0x0
64 | #define KEY_SUPER_LEFT 0x0
65 | #define KEY_SUPER_RIGHT 0x0
66 | #define KEY_TAB 0x0
67 | #define KEY_LEFT_ARROW 0x0
68 | #define KEY_RIGHT_ARROW 0x0
69 | #define KEY_UP_ARROW 0x0
70 | #define KEY_DOWN_ARROW 0x0
71 | #define KEY_HOME 0x0
72 | #define KEY_END 0x0
73 | #define KEY_DELETE 0x0
74 | #define KEY_Y 0x0
75 | #define KEY_Z 0x0
76 | #define KEY_X 0x0
77 | #define KEY_C 0x0
78 | #define KEY_V 0x0
79 |
80 | #elif defined(VK_USE_PLATFORM_IOS_MVK)
81 | // Use numeric keys instead of function keys.
82 | // Use main keyboard plus/minus instead of keypad plus/minus
83 | // Use Delete key instead of Escape key.
84 | #define KEY_ESCAPE 0x33
85 | #define KEY_F1 '1'
86 | #define KEY_F2 '2'
87 | #define KEY_F3 '3'
88 | #define KEY_F4 '4'
89 | #define KEY_W 'w'
90 | #define KEY_A 'a'
91 | #define KEY_S 's'
92 | #define KEY_D 'd'
93 | #define KEY_P 'p'
94 | #define KEY_SPACE ' '
95 | #define KEY_KPADD '+'
96 | #define KEY_KPSUB '-'
97 | #define KEY_B 'b'
98 | #define KEY_F 'f'
99 | #define KEY_L 'l'
100 | #define KEY_N 'n'
101 | #define KEY_O 'o'
102 | #define KEY_T 't'
103 |
104 | #elif defined(VK_USE_PLATFORM_MACOS_MVK)
105 | // For compatibility with iOS UX and absent keypad on MacBook:
106 | // - Use numeric keys instead of function keys
107 | // - Use main keyboard plus/minus instead of keypad plus/minus
108 | // - Use Delete key instead of Escape key
109 | #define KEY_ESCAPE 0x33
110 | #define KEY_F1 0x12
111 | #define KEY_F2 0x13
112 | #define KEY_F3 0x14
113 | #define KEY_F4 0x15
114 | #define KEY_W 0x0D
115 | #define KEY_A 0x00
116 | #define KEY_S 0x01
117 | #define KEY_D 0x02
118 | #define KEY_P 0x23
119 | #define KEY_SPACE 0x31
120 | #define KEY_KPADD 0x18
121 | #define KEY_KPSUB 0x1B
122 | #define KEY_B 0x0B
123 | #define KEY_F 0x03
124 | #define KEY_L 0x25
125 | #define KEY_N 0x2D
126 | #define KEY_O 0x1F
127 | #define KEY_T 0x11
128 |
129 | #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
130 | #include
131 |
132 | // todo: hack for bloom example
133 | #define KEY_KPADD KEY_KPPLUS
134 | #define KEY_KPSUB KEY_KPMINUS
135 |
136 | #elif defined(__linux__)
137 | #define KEY_CTRL_LEFT 0x25
138 | #define KEY_CTRL_RIGHT 0x25
139 | #define KEY_SHIFT_LEFT 0x32
140 | #define KEY_SHIFT_RIGHT 0x3e
141 | #define KEY_ALT_LEFT 0x40
142 | #define KEY_ALT_RIGHT 0x6c
143 | #define KEY_SUPER_LEFT 0x85
144 | #define KEY_SUPER_RIGHT 0x86
145 | #define KEY_TAB 0x17
146 | #define KEY_LEFT_ARROW 0x71
147 | #define KEY_RIGHT_ARROW 0x72
148 | #define KEY_UP_ARROW 0x6F
149 | #define KEY_DOWN_ARROW 0x74
150 | #define KEY_HOME 0x0
151 | #define KEY_END 0x0
152 | #define KEY_DELETE 0x0
153 | #define KEY_BACKSPACE 0x16
154 | #define KEY_ENTER 0x24
155 | #define KEY_ESCAPE 0x9
156 | #define KEY_SPACE 0x41
157 | #define KEY_KPADD 0x56
158 | #define KEY_KPSUB 0x52
159 | #define KEY_F1 0x43
160 | #define KEY_F2 0x44
161 | #define KEY_F3 0x45
162 | #define KEY_F4 0x46
163 | #define KEY_W 0x19
164 | #define KEY_A 0x26
165 | #define KEY_S 0x27
166 | #define KEY_D 0x28
167 | #define KEY_F 0x29
168 | #define KEY_G 0x2A
169 | #define KEY_H 0x2B
170 | #define KEY_J 0x2C
171 | #define KEY_K 0x2D
172 | #define KEY_L 0x2E
173 | #define KEY_P 0x21
174 | #define KEY_Y 0x1D
175 | #define KEY_Z 0x34
176 | #define KEY_X 0x35
177 | #define KEY_C 0x36
178 | #define KEY_V 0x37
179 | #define KEY_B 0x38
180 | #define KEY_N 0x39
181 | #define KEY_O 0x20
182 | #define KEY_T 0x1C
183 | #endif
184 |
185 | // todo: Android gamepad keycodes outside of define for now
186 | #define GAMEPAD_BUTTON_A 0x1000
187 | #define GAMEPAD_BUTTON_B 0x1001
188 | #define GAMEPAD_BUTTON_X 0x1002
189 | #define GAMEPAD_BUTTON_Y 0x1003
190 | #define GAMEPAD_BUTTON_L1 0x1004
191 | #define GAMEPAD_BUTTON_R1 0x1005
192 | #define GAMEPAD_BUTTON_START 0x1006
193 | #define TOUCH_DOUBLE_TAP 0x1100
194 | #define BACK_BUTTON 0x100A
195 |
196 |
--------------------------------------------------------------------------------
/sascha/VulkanBuffer.hpp:
--------------------------------------------------------------------------------
1 | /*
2 | * Vulkan buffer class
3 | *
4 | * Encapsulates a Vulkan buffer
5 | *
6 | * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de
7 | *
8 | * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
9 | */
10 |
11 | #pragma once
12 |
13 | #include
14 |
15 | #include "vulkan/vulkan.h"
16 | #include "VulkanTools.h"
17 |
18 | namespace vks
19 | {
20 | /**
21 | * @brief Encapsulates access to a Vulkan buffer backed up by device memory
22 | * @note To be filled by an external source like the VulkanDevice
23 | */
24 | struct Buffer
25 | {
26 | VkDevice device;
27 | VkBuffer buffer = VK_NULL_HANDLE;
28 | VkDeviceMemory memory = VK_NULL_HANDLE;
29 | VkDescriptorBufferInfo descriptor;
30 | VkDeviceSize size = 0;
31 | VkDeviceSize alignment = 0;
32 | void* mapped = nullptr;
33 |
34 | /** @brief Usage flags to be filled by external source at buffer creation (to query at some later point) */
35 | VkBufferUsageFlags usageFlags;
36 | /** @brief Memory propertys flags to be filled by external source at buffer creation (to query at some later point) */
37 | VkMemoryPropertyFlags memoryPropertyFlags;
38 |
39 | /**
40 | * Map a memory range of this buffer. If successful, mapped points to the specified buffer range.
41 | *
42 | * @param size (Optional) Size of the memory range to map. Pass VK_WHOLE_SIZE to map the complete buffer range.
43 | * @param offset (Optional) Byte offset from beginning
44 | *
45 | * @return VkResult of the buffer mapping call
46 | */
47 | VkResult map(VkDeviceSize size = VK_WHOLE_SIZE, VkDeviceSize offset = 0)
48 | {
49 | return vkMapMemory(device, memory, offset, size, 0, &mapped);
50 | }
51 |
52 | /**
53 | * Unmap a mapped memory range
54 | *
55 | * @note Does not return a result as vkUnmapMemory can't fail
56 | */
57 | void unmap()
58 | {
59 | if (mapped)
60 | {
61 | vkUnmapMemory(device, memory);
62 | mapped = nullptr;
63 | }
64 | }
65 |
66 | /**
67 | * Attach the allocated memory block to the buffer
68 | *
69 | * @param offset (Optional) Byte offset (from the beginning) for the memory region to bind
70 | *
71 | * @return VkResult of the bindBufferMemory call
72 | */
73 | VkResult bind(VkDeviceSize offset = 0)
74 | {
75 | return vkBindBufferMemory(device, buffer, memory, offset);
76 | }
77 |
78 | /**
79 | * Setup the default descriptor for this buffer
80 | *
81 | * @param size (Optional) Size of the memory range of the descriptor
82 | * @param offset (Optional) Byte offset from beginning
83 | *
84 | */
85 | void setupDescriptor(VkDeviceSize size = VK_WHOLE_SIZE, VkDeviceSize offset = 0)
86 | {
87 | descriptor.offset = offset;
88 | descriptor.buffer = buffer;
89 | descriptor.range = size;
90 | }
91 |
92 | /**
93 | * Copies the specified data to the mapped buffer
94 | *
95 | * @param data Pointer to the data to copy
96 | * @param size Size of the data to copy in machine units
97 | *
98 | */
99 | void copyTo(void* data, VkDeviceSize size)
100 | {
101 | assert(mapped);
102 | memcpy(mapped, data, size);
103 | }
104 |
105 | /**
106 | * Flush a memory range of the buffer to make it visible to the device
107 | *
108 | * @note Only required for non-coherent memory
109 | *
110 | * @param size (Optional) Size of the memory range to flush. Pass VK_WHOLE_SIZE to flush the complete buffer range.
111 | * @param offset (Optional) Byte offset from beginning
112 | *
113 | * @return VkResult of the flush call
114 | */
115 | VkResult flush(VkDeviceSize size = VK_WHOLE_SIZE, VkDeviceSize offset = 0)
116 | {
117 | VkMappedMemoryRange mappedRange = {};
118 | mappedRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
119 | mappedRange.memory = memory;
120 | mappedRange.offset = offset;
121 | mappedRange.size = size;
122 | return vkFlushMappedMemoryRanges(device, 1, &mappedRange);
123 | }
124 |
125 | /**
126 | * Invalidate a memory range of the buffer to make it visible to the host
127 | *
128 | * @note Only required for non-coherent memory
129 | *
130 | * @param size (Optional) Size of the memory range to invalidate. Pass VK_WHOLE_SIZE to invalidate the complete buffer range.
131 | * @param offset (Optional) Byte offset from beginning
132 | *
133 | * @return VkResult of the invalidate call
134 | */
135 | VkResult invalidate(VkDeviceSize size = VK_WHOLE_SIZE, VkDeviceSize offset = 0)
136 | {
137 | VkMappedMemoryRange mappedRange = {};
138 | mappedRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
139 | mappedRange.memory = memory;
140 | mappedRange.offset = offset;
141 | mappedRange.size = size;
142 | return vkInvalidateMappedMemoryRanges(device, 1, &mappedRange);
143 | }
144 |
145 | /**
146 | * Release all Vulkan resources held by this buffer
147 | */
148 | void destroy()
149 | {
150 | if (buffer)
151 | {
152 | vkDestroyBuffer(device, buffer, nullptr);
153 | }
154 | if (memory)
155 | {
156 | vkFreeMemory(device, memory, nullptr);
157 | }
158 | }
159 |
160 | };
161 | }
162 |
--------------------------------------------------------------------------------
/android/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/sascha/camera.hpp:
--------------------------------------------------------------------------------
1 | /*
2 | * Basic camera class
3 | *
4 | * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de
5 | *
6 | * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
7 | */
8 |
9 | #define GLM_FORCE_RADIANS
10 | #define GLM_FORCE_DEPTH_ZERO_TO_ONE
11 | #include
12 | #include
13 | #include
14 |
15 | class Camera
16 | {
17 | private:
18 | float fov;
19 | float znear, zfar;
20 |
21 | void updateViewMatrix()
22 | {
23 | glm::mat4 rotM = glm::mat4(1.0f);
24 | glm::mat4 transM;
25 |
26 | rotM = glm::rotate(rotM, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
27 | rotM = glm::rotate(rotM, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
28 | rotM = glm::rotate(rotM, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f));
29 |
30 | transM = glm::translate(glm::mat4(1.0f), position);
31 |
32 | if (type == CameraType::firstperson)
33 | {
34 | matrices.view = rotM * transM;
35 | }
36 | else
37 | {
38 | matrices.view = transM * rotM;
39 | }
40 | };
41 | public:
42 | enum CameraType { lookat, firstperson };
43 | CameraType type = CameraType::lookat;
44 |
45 | glm::vec3 rotation = glm::vec3();
46 | glm::vec3 position = glm::vec3();
47 |
48 | float rotationSpeed = 1.0f;
49 | float movementSpeed = 1.0f;
50 |
51 | struct
52 | {
53 | glm::mat4 perspective;
54 | glm::mat4 view;
55 | } matrices;
56 |
57 | struct
58 | {
59 | bool left = false;
60 | bool right = false;
61 | bool up = false;
62 | bool down = false;
63 | } keys;
64 |
65 | bool moving()
66 | {
67 | return keys.left || keys.right || keys.up || keys.down;
68 | }
69 |
70 | void setPerspective(float fov, float aspect, float znear, float zfar)
71 | {
72 | this->fov = fov;
73 | this->znear = znear;
74 | this->zfar = zfar;
75 | matrices.perspective = glm::perspective(glm::radians(fov), aspect, znear, zfar);
76 | };
77 |
78 | void updateAspectRatio(float aspect)
79 | {
80 | matrices.perspective = glm::perspective(glm::radians(fov), aspect, znear, zfar);
81 | }
82 |
83 | void setPosition(glm::vec3 position)
84 | {
85 | this->position = position;
86 | updateViewMatrix();
87 | }
88 |
89 | void setRotation(glm::vec3 rotation)
90 | {
91 | this->rotation = rotation;
92 | updateViewMatrix();
93 | };
94 |
95 | void rotate(glm::vec3 delta)
96 | {
97 | this->rotation += delta;
98 | updateViewMatrix();
99 | }
100 |
101 | void setTranslation(glm::vec3 translation)
102 | {
103 | this->position = translation;
104 | updateViewMatrix();
105 | };
106 |
107 | void translate(glm::vec3 delta)
108 | {
109 | this->position += delta;
110 | updateViewMatrix();
111 | }
112 |
113 | void update(float deltaTime)
114 | {
115 | if (type == CameraType::firstperson)
116 | {
117 | if (moving())
118 | {
119 | glm::vec3 camFront;
120 | camFront.x = -cos(glm::radians(rotation.x)) * sin(glm::radians(rotation.y));
121 | camFront.y = sin(glm::radians(rotation.x));
122 | camFront.z = cos(glm::radians(rotation.x)) * cos(glm::radians(rotation.y));
123 | camFront = glm::normalize(camFront);
124 |
125 | float moveSpeed = deltaTime * movementSpeed;
126 |
127 | if (keys.up)
128 | position += camFront * moveSpeed;
129 | if (keys.down)
130 | position -= camFront * moveSpeed;
131 | if (keys.left)
132 | position -= glm::normalize(glm::cross(camFront, glm::vec3(0.0f, 1.0f, 0.0f))) * moveSpeed;
133 | if (keys.right)
134 | position += glm::normalize(glm::cross(camFront, glm::vec3(0.0f, 1.0f, 0.0f))) * moveSpeed;
135 |
136 | updateViewMatrix();
137 | }
138 | }
139 | };
140 |
141 | // Update camera passing separate axis data (gamepad)
142 | // Returns true if view or position has been changed
143 | bool updatePad(glm::vec2 axisLeft, glm::vec2 axisRight, float deltaTime)
144 | {
145 | bool retVal = false;
146 |
147 | if (type == CameraType::firstperson)
148 | {
149 | // Use the common console thumbstick layout
150 | // Left = view, right = move
151 |
152 | const float deadZone = 0.0015f;
153 | const float range = 1.0f - deadZone;
154 |
155 | glm::vec3 camFront;
156 | camFront.x = -cos(glm::radians(rotation.x)) * sin(glm::radians(rotation.y));
157 | camFront.y = sin(glm::radians(rotation.x));
158 | camFront.z = cos(glm::radians(rotation.x)) * cos(glm::radians(rotation.y));
159 | camFront = glm::normalize(camFront);
160 |
161 | float moveSpeed = deltaTime * movementSpeed * 2.0f;
162 | float rotSpeed = deltaTime * rotationSpeed * 50.0f;
163 |
164 | // Move
165 | if (fabsf(axisLeft.y) > deadZone)
166 | {
167 | float pos = (fabsf(axisLeft.y) - deadZone) / range;
168 | position -= camFront * pos * ((axisLeft.y < 0.0f) ? -1.0f : 1.0f) * moveSpeed;
169 | retVal = true;
170 | }
171 | if (fabsf(axisLeft.x) > deadZone)
172 | {
173 | float pos = (fabsf(axisLeft.x) - deadZone) / range;
174 | position += glm::normalize(glm::cross(camFront, glm::vec3(0.0f, 1.0f, 0.0f))) * pos * ((axisLeft.x < 0.0f) ? -1.0f : 1.0f) * moveSpeed;
175 | retVal = true;
176 | }
177 |
178 | // Rotate
179 | if (fabsf(axisRight.x) > deadZone)
180 | {
181 | float pos = (fabsf(axisRight.x) - deadZone) / range;
182 | rotation.y += pos * ((axisRight.x < 0.0f) ? -1.0f : 1.0f) * rotSpeed;
183 | retVal = true;
184 | }
185 | if (fabsf(axisRight.y) > deadZone)
186 | {
187 | float pos = (fabsf(axisRight.y) - deadZone) / range;
188 | rotation.x -= pos * ((axisRight.y < 0.0f) ? -1.0f : 1.0f) * rotSpeed;
189 | retVal = true;
190 | }
191 | }
192 | else
193 | {
194 | // todo: move code from example base class for look-at
195 | }
196 |
197 | if (retVal)
198 | {
199 | updateViewMatrix();
200 | }
201 |
202 | return retVal;
203 | }
204 |
205 | };
206 |
--------------------------------------------------------------------------------
/src/display.cpp:
--------------------------------------------------------------------------------
1 |
2 | extern "C" {
3 | #include
4 | }
5 |
6 | #include
7 |
8 | #define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR)))
9 |
10 | #include "im-gui.h"
11 | #include "ux-features.h"
12 | #include "display.h"
13 |
14 | #define OUTER_PADDING 20
15 |
16 | extern void draw_padding(char* path, int16_t width, int16_t height, int8_t depth);
17 | extern void set_new_value(char* path, char* buf, bool single);
18 |
19 | void draw_light(char* path, int16_t width)
20 | {
21 | char pathlight[128]; snprintf(pathlight, 128, "%s:light", path);
22 | char pathname[128]; snprintf(pathname, 128, "%s:name", path);
23 | char* state=object_property(user, pathlight);
24 | char* name=object_property_values(user, pathname);
25 | char childName[128]; memcpy(childName, path, strlen(path)+1);
26 | ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0.0f, 0.0f, 0.0f, 0.0f));
27 | ImGui::PushStyleColor(ImGuiCol_BorderShadow, ImVec4(0.0f, 0.0f, 0.0f, 0.0f));
28 | ImGui::BeginChild(childName, ImVec2(width,200), true);
29 | {
30 | if(state && !strcmp(state, "off")){
31 | ImGui::PushStyleColor(ImGuiCol_Border, ledOff);
32 | ImGui::PushStyleColor(ImGuiCol_Button, ledOff);
33 | ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ledOff);
34 | ImGui::PushStyleColor(ImGuiCol_ButtonActive, ledOff);
35 | }
36 | else
37 | if(state && !strcmp(state, "on")){
38 | ImGui::PushStyleColor(ImGuiCol_Border, ledOff);
39 | ImGui::PushStyleColor(ImGuiCol_Button, ledOn);
40 | ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ledOn);
41 | ImGui::PushStyleColor(ImGuiCol_ButtonActive, ledOn);
42 | }
43 | else {
44 | ImGui::PushStyleColor(ImGuiCol_Border, valueBackgroundActive);
45 | ImGui::PushStyleColor(ImGuiCol_Button, valueBackground);
46 | ImGui::PushStyleColor(ImGuiCol_ButtonHovered, valueBackground);
47 | ImGui::PushStyleColor(ImGuiCol_ButtonActive, valueBackground);
48 | }
49 | char keyId[256]; snprintf(keyId, 256, "%s ## light %s", name? name: "light", path);
50 | if(ImGui::Button(keyId, ImVec2(200, 200-OUTER_PADDING*2))){
51 | set_new_value(pathlight, (char*)"on", true);
52 | }
53 | ImGui::PopStyleColor(4);
54 | }
55 | ImGui::SameLine();
56 | ImGui::EndChild();
57 | ImGui::PopStyleColor(2);
58 | }
59 |
60 | void draw_bluetooth(char* path, int16_t width)
61 | {
62 | char pathstate[128]; snprintf(pathstate, 128, "%s:state", path);
63 | char pathmac[128]; snprintf(pathmac, 128, "%s:mac", path);
64 |
65 | bool connected=object_property_contains(user, pathstate, (char*)"connected");
66 |
67 | char* mac=object_property(user, pathmac);
68 |
69 | char childName[128]; memcpy(childName, path, strlen(path)+1);
70 | ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0.0f, 0.0f, 0.0f, 0.0f));
71 | ImGui::PushStyleColor(ImGuiCol_BorderShadow, ImVec4(0.0f, 0.0f, 0.0f, 0.0f));
72 | ImGui::BeginChild(childName, ImVec2(width,200), true);
73 | {
74 | if(!connected){
75 | ImGui::PushStyleColor(ImGuiCol_Border, btDisconnected);
76 | ImGui::PushStyleColor(ImGuiCol_Button, btDisconnected);
77 | ImGui::PushStyleColor(ImGuiCol_ButtonHovered, btDisconnected);
78 | ImGui::PushStyleColor(ImGuiCol_ButtonActive, btDisconnected);
79 | }
80 | else{
81 | ImGui::PushStyleColor(ImGuiCol_Border, btDisconnected);
82 | ImGui::PushStyleColor(ImGuiCol_Button, btConnected);
83 | ImGui::PushStyleColor(ImGuiCol_ButtonHovered, btConnected);
84 | ImGui::PushStyleColor(ImGuiCol_ButtonActive, btConnected);
85 | }
86 | char keyId[256]; snprintf(keyId, 256, "%s ## bluetooth %s", mac? mac: "Bluetooth", path);
87 | if(ImGui::Button(keyId, ImVec2(300, 200-OUTER_PADDING*2))){
88 | set_new_value(pathstate, (char*)"BLE reconnecting", true);
89 | }
90 | ImGui::PopStyleColor(4);
91 | }
92 | ImGui::SameLine();
93 | ImGui::EndChild();
94 | ImGui::PopStyleColor(2);
95 | }
96 |
97 | char* buttonDown;
98 |
99 | void draw_button(char* path, int16_t width)
100 | {
101 | char pathstate[128]; snprintf(pathstate, 128, "%s:state", path);
102 | char pathname[128]; snprintf(pathname, 128, "%s:name", path);
103 | char* state=object_property(user, pathstate);
104 | char* name=object_property_values(user, pathname);
105 | char childName[128]; memcpy(childName, path, strlen(path)+1);
106 | ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0.0f, 0.0f, 0.0f, 0.0f));
107 | ImGui::PushStyleColor(ImGuiCol_BorderShadow, ImVec4(0.0f, 0.0f, 0.0f, 0.0f));
108 | ImGui::BeginChild(childName, ImVec2(width,100), true);
109 | {
110 | if(state && !strcmp(state, "up")){
111 | ImGui::PushStyleColor(ImGuiCol_Border, renderColourSoft);
112 | ImGui::PushStyleColor(ImGuiCol_Button, propertyBackground);
113 | ImGui::PushStyleColor(ImGuiCol_ButtonHovered, propertyBackground);
114 | ImGui::PushStyleColor(ImGuiCol_ButtonActive, propertyBackgroundActive);
115 | }
116 | else
117 | if(state && !strcmp(state, "down")){
118 | ImGui::PushStyleColor(ImGuiCol_Border, renderColourSoft);
119 | ImGui::PushStyleColor(ImGuiCol_Button, propertyBackgroundActive);
120 | ImGui::PushStyleColor(ImGuiCol_ButtonHovered, propertyBackgroundActive);
121 | ImGui::PushStyleColor(ImGuiCol_ButtonActive, propertyBackgroundActive);
122 | }
123 | else {
124 | ImGui::PushStyleColor(ImGuiCol_Border, valueBackgroundActive);
125 | ImGui::PushStyleColor(ImGuiCol_Button, valueBackground);
126 | ImGui::PushStyleColor(ImGuiCol_ButtonHovered, valueBackground);
127 | ImGui::PushStyleColor(ImGuiCol_ButtonActive, valueBackground);
128 | }
129 | char keyId[256]; snprintf(keyId, 256, "%s ## button %s", name? name: "button", path);
130 | ImGui::Button(keyId, ImVec2(300, 100-OUTER_PADDING*2));
131 | if(ImGui::IsItemActive()){
132 | if(!buttonDown){
133 | buttonDown=strdup(keyId);
134 | char* uid=object_property(user, path);
135 | invoke_single_set(uid, (char*)"state", (char*)"down");
136 | }
137 | }
138 | else{
139 | if(buttonDown && !strcmp(buttonDown, keyId)){
140 | free(buttonDown); buttonDown=0;
141 | char* uid=object_property(user, path);
142 | invoke_single_set(uid, (char*)"state", (char*)"up");
143 | }
144 | }
145 | ImGui::PopStyleColor(4);
146 | }
147 | ImGui::SameLine();
148 | ImGui::EndChild();
149 | ImGui::PopStyleColor(2);
150 | }
151 |
152 | void draw_display(char* path, int16_t width, int16_t height)
153 | {
154 | ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(OUTER_PADDING,OUTER_PADDING));
155 | uint16_t ln = object_property_length(user, path);
156 | size_t l=strlen(path);
157 | int j; for(j=1; j<=ln; j++){
158 | if(!is_uid(object_property_get_n(user, path, j))) continue;
159 | snprintf(path+l, 128-l, ":%d", j); // oops, not 128 long! (see im-gui.cpp)
160 | char pathis[128]; snprintf(pathis, 128, "%s:is", path);
161 | if(object_property_contains(user, pathis, (char*)"light")) draw_light(path, width);
162 | if(object_property_contains(user, pathis, (char*)"button")) draw_button(path, width);
163 | if(object_property_contains(user, pathis, (char*)"bluetooth")) draw_bluetooth(path, width);
164 | path[l] = 0;
165 | }
166 | ImGui::PopStyleVar();
167 | }
168 |
169 |
--------------------------------------------------------------------------------
/sascha/VulkanAndroid.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Android Vulkan function pointer prototypes
3 | *
4 | * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de
5 | *
6 | * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
7 | */
8 |
9 | #pragma once
10 |
11 | #ifndef VULKANANDROID_H
12 | #define VULKANANDROID_H
13 |
14 | // Vulkan needs to be loaded dynamically on android
15 |
16 | #pragma once
17 |
18 | #ifndef VULKANANDROID_HPP
19 | #define VULKANANDROID_HPP
20 |
21 | #include "vulkan/vulkan.h"
22 |
23 | #if defined(__ANDROID__)
24 |
25 | #include
26 | #include
27 | #include
28 | #include
29 |
30 | // Missing from the NDK
31 | namespace std
32 | {
33 | template
34 | std::unique_ptr make_unique(Args&&... args)
35 | {
36 | return std::unique_ptr(new T(std::forward(args)...));
37 | }
38 | }
39 |
40 | // Global reference to android application object
41 | extern android_app* androidApp;
42 |
43 | #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "vulkanApp", __VA_ARGS__))
44 | #define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "vulkanApp", __VA_ARGS__))
45 | #define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, "vulkanApp", __VA_ARGS__))
46 | #define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "vulkanApp", __VA_ARGS__))
47 |
48 | // Function pointer prototypes
49 | // Not complete, just the functions used in the caps viewer!
50 | extern PFN_vkCreateInstance vkCreateInstance;
51 | extern PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr;
52 | extern PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr;
53 | extern PFN_vkCreateDevice vkCreateDevice;
54 | extern PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices;
55 | extern PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties;
56 | extern PFN_vkEnumerateDeviceExtensionProperties vkEnumerateDeviceExtensionProperties;
57 | extern PFN_vkEnumerateDeviceLayerProperties vkEnumerateDeviceLayerProperties;
58 | extern PFN_vkGetPhysicalDeviceFormatProperties vkGetPhysicalDeviceFormatProperties;
59 | extern PFN_vkGetPhysicalDeviceFeatures vkGetPhysicalDeviceFeatures;
60 | extern PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties;
61 | extern PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties;
62 | extern PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties;
63 | extern PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties;
64 | extern PFN_vkCmdPipelineBarrier vkCmdPipelineBarrier;
65 | extern PFN_vkCreateShaderModule vkCreateShaderModule;
66 | extern PFN_vkCreateBuffer vkCreateBuffer;
67 | extern PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements;
68 | extern PFN_vkMapMemory vkMapMemory;
69 | extern PFN_vkUnmapMemory vkUnmapMemory;
70 | extern PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges;
71 | extern PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges;
72 | extern PFN_vkBindBufferMemory vkBindBufferMemory;
73 | extern PFN_vkDestroyBuffer vkDestroyBuffer;
74 | extern PFN_vkAllocateMemory vkAllocateMemory;
75 | extern PFN_vkBindImageMemory vkBindImageMemory;
76 | extern PFN_vkGetImageSubresourceLayout vkGetImageSubresourceLayout;
77 | extern PFN_vkCmdCopyBuffer vkCmdCopyBuffer;
78 | extern PFN_vkCmdCopyBufferToImage vkCmdCopyBufferToImage;
79 | extern PFN_vkCmdCopyImage vkCmdCopyImage;
80 | extern PFN_vkCmdBlitImage vkCmdBlitImage;
81 | extern PFN_vkCmdClearAttachments vkCmdClearAttachments;
82 | extern PFN_vkCreateSampler vkCreateSampler;
83 | extern PFN_vkDestroySampler vkDestroySampler;
84 | extern PFN_vkDestroyImage vkDestroyImage;
85 | extern PFN_vkFreeMemory vkFreeMemory;
86 | extern PFN_vkCreateRenderPass vkCreateRenderPass;
87 | extern PFN_vkCmdBeginRenderPass vkCmdBeginRenderPass;
88 | extern PFN_vkCmdEndRenderPass vkCmdEndRenderPass;
89 | extern PFN_vkCmdNextSubpass vkCmdNextSubpass;
90 | extern PFN_vkCmdExecuteCommands vkCmdExecuteCommands;
91 | extern PFN_vkCreateImage vkCreateImage;
92 | extern PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements;
93 | extern PFN_vkCreateImageView vkCreateImageView;
94 | extern PFN_vkDestroyImageView vkDestroyImageView;
95 | extern PFN_vkCreateSemaphore vkCreateSemaphore;
96 | extern PFN_vkDestroySemaphore vkDestroySemaphore;
97 | extern PFN_vkCreateFence vkCreateFence;
98 | extern PFN_vkDestroyFence vkDestroyFence;
99 | extern PFN_vkWaitForFences vkWaitForFences;
100 | extern PFN_vkResetFences vkResetFences;
101 | extern PFN_vkCreateCommandPool vkCreateCommandPool;
102 | extern PFN_vkDestroyCommandPool vkDestroyCommandPool;
103 | extern PFN_vkAllocateCommandBuffers vkAllocateCommandBuffers;
104 | extern PFN_vkBeginCommandBuffer vkBeginCommandBuffer;
105 | extern PFN_vkEndCommandBuffer vkEndCommandBuffer;
106 | extern PFN_vkGetDeviceQueue vkGetDeviceQueue;
107 | extern PFN_vkQueueSubmit vkQueueSubmit;
108 | extern PFN_vkQueueWaitIdle vkQueueWaitIdle;
109 | extern PFN_vkDeviceWaitIdle vkDeviceWaitIdle;
110 | extern PFN_vkCreateFramebuffer vkCreateFramebuffer;
111 | extern PFN_vkCreatePipelineCache vkCreatePipelineCache;
112 | extern PFN_vkCreatePipelineLayout vkCreatePipelineLayout;
113 | extern PFN_vkCreateGraphicsPipelines vkCreateGraphicsPipelines;
114 | extern PFN_vkCreateComputePipelines vkCreateComputePipelines;
115 | extern PFN_vkCreateDescriptorPool vkCreateDescriptorPool;
116 | extern PFN_vkCreateDescriptorSetLayout vkCreateDescriptorSetLayout;
117 | extern PFN_vkAllocateDescriptorSets vkAllocateDescriptorSets;
118 | extern PFN_vkUpdateDescriptorSets vkUpdateDescriptorSets;
119 | extern PFN_vkCmdBindDescriptorSets vkCmdBindDescriptorSets;
120 | extern PFN_vkCmdBindPipeline vkCmdBindPipeline;
121 | extern PFN_vkCmdBindVertexBuffers vkCmdBindVertexBuffers;
122 | extern PFN_vkCmdBindIndexBuffer vkCmdBindIndexBuffer;
123 | extern PFN_vkCmdSetViewport vkCmdSetViewport;
124 | extern PFN_vkCmdSetScissor vkCmdSetScissor;
125 | extern PFN_vkCmdSetLineWidth vkCmdSetLineWidth;
126 | extern PFN_vkCmdSetDepthBias vkCmdSetDepthBias;
127 | extern PFN_vkCmdPushConstants vkCmdPushConstants;
128 | extern PFN_vkCmdDrawIndexed vkCmdDrawIndexed;
129 | extern PFN_vkCmdDraw vkCmdDraw;
130 | extern PFN_vkCmdDrawIndexedIndirect vkCmdDrawIndexedIndirect;
131 | extern PFN_vkCmdDrawIndirect vkCmdDrawIndirect;
132 | extern PFN_vkCmdDispatch vkCmdDispatch;
133 | extern PFN_vkDestroyPipeline vkDestroyPipeline;
134 | extern PFN_vkDestroyPipelineLayout vkDestroyPipelineLayout;
135 | extern PFN_vkDestroyDescriptorSetLayout vkDestroyDescriptorSetLayout;
136 | extern PFN_vkDestroyDevice vkDestroyDevice;
137 | extern PFN_vkDestroyInstance vkDestroyInstance;
138 | extern PFN_vkDestroyDescriptorPool vkDestroyDescriptorPool;
139 | extern PFN_vkFreeCommandBuffers vkFreeCommandBuffers;
140 | extern PFN_vkDestroyRenderPass vkDestroyRenderPass;
141 | extern PFN_vkDestroyFramebuffer vkDestroyFramebuffer;
142 | extern PFN_vkDestroyShaderModule vkDestroyShaderModule;
143 | extern PFN_vkDestroyPipelineCache vkDestroyPipelineCache;
144 | extern PFN_vkCreateQueryPool vkCreateQueryPool;
145 | extern PFN_vkDestroyQueryPool vkDestroyQueryPool;
146 | extern PFN_vkGetQueryPoolResults vkGetQueryPoolResults;
147 | extern PFN_vkCmdBeginQuery vkCmdBeginQuery;
148 | extern PFN_vkCmdEndQuery vkCmdEndQuery;
149 | extern PFN_vkCmdResetQueryPool vkCmdResetQueryPool;
150 | extern PFN_vkCmdCopyQueryPoolResults vkCmdCopyQueryPoolResults;
151 |
152 | extern PFN_vkCreateAndroidSurfaceKHR vkCreateAndroidSurfaceKHR;
153 | extern PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR;
154 |
155 | namespace vks
156 | {
157 | namespace android
158 | {
159 | /* @brief Touch control thresholds from Android NDK samples */
160 | const int32_t DOUBLE_TAP_TIMEOUT = 300 * 1000000;
161 | const int32_t DOUBLE_TAP_SLOP = 100;
162 |
163 | /** @brief Density of the device screen (in DPI) */
164 | extern int32_t screenDensity;
165 |
166 | bool loadVulkanLibrary();
167 | void loadVulkanFunctions(VkInstance instance);
168 | void freeVulkanLibrary();
169 | void getDeviceConfig();
170 | }
171 | }
172 |
173 | #endif
174 |
175 | #endif // VULKANANDROID_HPP
176 |
177 |
178 | #endif // VULKANANDROID_H
179 |
180 |
--------------------------------------------------------------------------------
/src/onex.cpp:
--------------------------------------------------------------------------------
1 |
2 | #include
3 | #include
4 |
5 | extern "C" {
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 | }
13 |
14 | object* config;
15 |
16 | object* user;
17 | object* responses;
18 | object* bluetooth;
19 | object* taglookup;
20 |
21 | char* userUID=0;
22 | char* responsesUID=0;
23 | char* homeUID=0;
24 | char* clockUID=0;
25 | char* bluetoothUID=0;
26 | char* buttonUID=0;
27 | char* taglookupUID;
28 |
29 | extern bool evaluate_default(object* o, void* d);
30 | extern bool evaluate_user(object* o, void* d);
31 | extern bool evaluate_event(object* o, void* d);
32 | static bool evaluate_bluetooth_in(object* o, void* d);
33 | static bool evaluate_bluetooth_out(object* o, void* d);
34 |
35 | static void every_second(void*){ onex_run_evaluators(clockUID, 0); }
36 |
37 | extern "C" void sprintExternalStorageDirectory(char* buf, int buflen, const char* format);
38 | extern "C" void ensureBluetoothConnecting();
39 |
40 | static char* ble_state=0;
41 | static char* ble_mac=0;
42 |
43 | char* init_onex(const int argc, const char *argv[]) {
44 |
45 | #if defined(__ANDROID__)
46 | properties* conf = properties_new(32);
47 | char dbpath[128];
48 | sprintExternalStorageDirectory(dbpath, 128, "%s/Onex/onex.ondb");
49 | properties_set(conf, (char*)"dbpath", value_new(dbpath));
50 | #else
51 | properties* conf = get_config(argc, (char**)argv, "Onex/onex", "log-onp");
52 | if(!conf) return 0;
53 | #endif
54 | log_init(conf);
55 | onex_init(conf);
56 |
57 | onex_set_evaluators((char*)"eval_editable", evaluate_edit_rule, 0);
58 | onex_set_evaluators((char*)"eval_default", evaluate_edit_rule, evaluate_default, 0);
59 | onex_set_evaluators((char*)"eval_user", evaluate_user, 0);
60 | onex_set_evaluators((char*)"eval_clock", evaluate_edit_rule, /* evaluate_clock, */ 0);
61 | onex_set_evaluators((char*)"eval_event", evaluate_edit_rule, evaluate_event, 0);
62 | onex_set_evaluators((char*)"eval_light", evaluate_edit_rule, /* evaluate_light_logic, */ 0);
63 | onex_set_evaluators((char*)"eval_bluetooth", evaluate_bluetooth_in, evaluate_edit_rule, evaluate_bluetooth_out, 0);
64 |
65 | config=onex_get_from_cache((char*)"uid-0");
66 |
67 | if(!config){
68 | // UTF-8 hex: "\xF0\x9F\x98\x83 \xF0\x9F\x93\xA6"
69 |
70 | object* tagbirth=object_new_from((char*)"is: tag title: birthday icon: 📦 colour: red", 5);
71 | object* tagparty=object_new_from((char*)"is: tag title: party icon: 🎉 colour: yellow", 5);
72 | object* tagtrain=object_new_from((char*)"is: tag title: train icon: 🚆 colour: blue", 5);
73 | object* tagceleb=object_new_from((char*)"is: tag title: celebrate icon: 🎉 colour: red", 5);
74 | object* taglove =object_new_from((char*)"is: tag title: love icon: 😍 colour: red", 5);
75 |
76 | taglookup=object_new_from((char*)"is: tag lookup", 100);
77 | object_property_set(taglookup, (char*)"birthday", object_property(tagbirth, (char*)"UID"));
78 | object_property_set(taglookup, (char*)"party", object_property(tagparty, (char*)"UID"));
79 | object_property_set(taglookup, (char*)"train", object_property(tagtrain, (char*)"UID"));
80 | object_property_set(taglookup, (char*)"celebrate", object_property(tagceleb, (char*)"UID"));
81 | object_property_set(taglookup, (char*)"love", object_property(taglove, (char*)"UID"));
82 | taglookupUID=object_property(taglookup, (char*)"UID");
83 | /*
84 | object* links=object_new(0, (char*)"eval_default", (char*)"links list", 4);
85 | object_property_set(links, (char*)"list", object_property(taglookup, (char*)"UID"));
86 | */
87 | user=object_new(0, (char*)"eval_user", (char*)"user", 8);
88 | userUID=object_property(user, (char*)"UID");
89 |
90 | responses=object_new(0, (char*)"eval_default", (char*)"user responses", 12);
91 | char* responsesUID=object_property(responses, (char*)"UID");
92 |
93 | object* home=object_new(0, (char*)"eval_editable", (char*)"list editable", 4);
94 | homeUID=object_property(home, (char*)"UID");
95 |
96 | object* oclock=object_new(0, (char*)"eval_clock", (char*)"clock event", 12);
97 | object_property_set(oclock, (char*)"title", (char*)"OnexApp Clock");
98 | clockUID=object_property(oclock, (char*)"UID");
99 | object_set_persist(oclock, (char*)"none");
100 |
101 | bluetooth=object_new(0, (char*)"eval_bluetooth", (char*)"bluetooth", 6);
102 | object_property_set(bluetooth, (char*)"state", (char*)"BLE disconnected");
103 | bluetoothUID=object_property(bluetooth, (char*)"UID");
104 |
105 | object* button=object_new(0, (char*)"eval_editable", (char*)"button editable", 6);
106 | object_property_set(button, (char*)"state", (char*)"up");
107 | buttonUID=object_property(button, (char*)"UID");
108 |
109 | char* deviceUID=object_property(onex_device_object, (char*)"UID");
110 |
111 | object_property_add(onex_device_object, (char*)"name", (char*)"OnexApp");
112 |
113 | object_property_add(onex_device_object, (char*)"user", userUID);
114 | object_property_add(onex_device_object, (char*)"io", clockUID);
115 | object_property_add(onex_device_object, (char*)"io", bluetoothUID);
116 | object_property_add(onex_device_object, (char*)"io", buttonUID);
117 |
118 | object_property_set(user, (char*)"responses", responsesUID);
119 |
120 | config=object_new((char*)"uid-0", 0, (char*)"config", 10);
121 | object_property_set(config, (char*)"user", userUID);
122 | object_property_set(config, (char*)"responses", responsesUID);
123 | object_property_set(config, (char*)"clock", clockUID);
124 | object_property_set(config, (char*)"bluetooth", bluetoothUID);
125 | object_property_set(config, (char*)"taglookup", taglookupUID);
126 |
127 | object_property_add(home, (char*)"list", clockUID);
128 | object_property_add(home, (char*)"list", userUID);
129 | object_property_add(home, (char*)"list", deviceUID);
130 |
131 | object_property_set(user, (char*)"viewing-l", homeUID);
132 | }
133 | else{
134 | userUID= object_property(config, (char*)"user");
135 | responsesUID=object_property(config, (char*)"responses");
136 | clockUID= object_property(config, (char*)"clock");
137 | bluetoothUID=object_property(config, (char*)"bluetooth");
138 | taglookupUID=object_property(config, (char*)"taglookup");
139 |
140 | user =onex_get_from_cache(userUID);
141 | responses=onex_get_from_cache(responsesUID);
142 | bluetooth=onex_get_from_cache(bluetoothUID);
143 | taglookup=onex_get_from_cache(taglookupUID);
144 |
145 | ble_mac=mem_strdup(object_property(bluetooth, (char*)"mac"));
146 | }
147 | time_ticker(every_second, 0, 1000);
148 |
149 | return ble_mac;
150 | }
151 |
152 | void loop_onex()
153 | {
154 | while(true){
155 | if(!onex_loop()){
156 | time_delay_ms(5);
157 | }
158 | }
159 | }
160 |
161 | void on_alarm_recv(char* uid)
162 | {
163 | onex_run_evaluators(uid, 0);
164 | }
165 |
166 | void connection_state(char* st)
167 | {
168 | mem_free(ble_state);
169 | ble_state=mem_strdup(st);
170 | log_write("connection state=%s\n", ble_state);
171 | onex_run_evaluators(bluetoothUID, 0);
172 | }
173 |
174 | void set_ble_mac(char* bm)
175 | {
176 | mem_free(ble_mac);
177 | ble_mac=mem_strdup(bm);
178 | onex_run_evaluators(bluetoothUID, 0);
179 | }
180 |
181 | bool evaluate_bluetooth_in(object* o, void* d)
182 | {
183 | if(ble_state) object_property_set(bluetooth, (char*)"state", ble_state);
184 | if(ble_mac) object_property_set(bluetooth, (char*)"mac", ble_mac);
185 | return true;
186 | }
187 |
188 | bool evaluate_bluetooth_out(object* o, void* d)
189 | {
190 | #if defined(__ANDROID__)
191 | if(object_property_is(bluetooth, (char*)"state:2", (char*)"reconnecting")){
192 | mem_free(ble_state);
193 | ble_state=mem_strdup("BLE reconnecting");
194 | ensureBluetoothConnecting();
195 | }
196 | #endif
197 | return true;
198 | }
199 |
200 |
--------------------------------------------------------------------------------
/android/onexapp/src/main/java/android/network/object/onexapp/DeviceListActivity.java:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | * Copyright (c) 2015, Nordic Semiconductor
4 | * All rights reserved.
5 | *
6 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
7 | *
8 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
9 | *
10 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
11 | * documentation and/or other materials provided with the distribution.
12 | *
13 | * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
14 | * software without specific prior written permission.
15 | *
16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
18 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
19 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
20 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
21 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22 | */
23 | package network.object.onexapp;
24 |
25 | import java.util.ArrayList;
26 | import java.util.HashMap;
27 | import java.util.List;
28 | import java.util.Map;
29 |
30 | import android.app.Activity;
31 | import android.bluetooth.BluetoothAdapter;
32 | import android.bluetooth.BluetoothDevice;
33 | import android.bluetooth.BluetoothManager;
34 | import android.bluetooth.le.*;
35 | import android.content.Context;
36 | import android.content.Intent;
37 | import android.content.IntentFilter;
38 | import android.content.ServiceConnection;
39 | import android.content.pm.PackageManager;
40 | import android.graphics.Color;
41 | import android.os.Bundle;
42 | import android.os.Handler;
43 | import android.util.Log;
44 | import android.view.Gravity;
45 | import android.view.LayoutInflater;
46 | import android.view.View;
47 | import android.view.View.OnClickListener;
48 | import android.view.ViewGroup;
49 | import android.widget.AdapterView;
50 | import android.widget.AdapterView.OnItemClickListener;
51 | import android.widget.BaseAdapter;
52 | import android.widget.Button;
53 | import android.widget.ListView;
54 | import android.widget.TextView;
55 | import android.widget.Toast;
56 |
57 | public class DeviceListActivity extends Activity {
58 | private BluetoothAdapter bluetoothAdapter;
59 |
60 | private TextView emptyList;
61 | public static final String LOGNAME = "Onex DeviceListActivity";
62 |
63 | List deviceList;
64 | private DeviceAdapter deviceAdapter;
65 | Map devRssiValues;
66 | private static final long SCAN_PERIOD = 10000;
67 | private Handler handler;
68 | private boolean scanning;
69 |
70 | @Override
71 | protected void onCreate(Bundle savedInstanceState) {
72 | super.onCreate(savedInstanceState);
73 | setContentView(R.layout.device_list);
74 | android.view.WindowManager.LayoutParams layoutParams = this.getWindow().getAttributes();
75 | layoutParams.gravity=Gravity.TOP;
76 | layoutParams.y = 200;
77 | handler = new Handler();
78 |
79 | // Use this check to determine whether BLE is supported on the device. Then you can
80 | // selectively disable BLE-related features.
81 | if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
82 | Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
83 | finish();
84 | }
85 |
86 | // Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
87 | // BluetoothAdapter through BluetoothManager.
88 | final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
89 | bluetoothAdapter = bluetoothManager.getAdapter();
90 | if (bluetoothAdapter == null) {
91 | Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
92 | finish();
93 | return;
94 | }
95 |
96 | populateList();
97 |
98 | emptyList = (TextView) findViewById(R.id.empty);
99 |
100 | Button cancelButton = (Button) findViewById(R.id.btn_cancel);
101 | cancelButton.setOnClickListener(new OnClickListener() {
102 | @Override
103 | public void onClick(View v) {
104 | if (scanning==false) scanLeDevice(true);
105 | else finishWith("00:00:00:00:00:00");
106 | }
107 | });
108 |
109 | scanLeDevice(true);
110 | }
111 |
112 | private void populateList() {
113 | deviceList = new ArrayList();
114 | deviceAdapter = new DeviceAdapter(this, deviceList);
115 | devRssiValues = new HashMap();
116 |
117 | ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
118 | newDevicesListView.setAdapter(deviceAdapter);
119 | newDevicesListView.setOnItemClickListener(deviceClickListener);
120 | }
121 |
122 | private void scanLeDevice(final boolean enable) {
123 | final Button cancelButton = (Button) findViewById(R.id.btn_cancel);
124 | if (enable) {
125 | handler.postDelayed(new Runnable() {
126 | @Override
127 | public void run() {
128 | scanning = false;
129 | BluetoothLeScanner s=bluetoothAdapter.getBluetoothLeScanner();
130 | if(s!=null) s.stopScan(leScanCallback);
131 | cancelButton.setText(R.string.scan);
132 | }
133 | }, SCAN_PERIOD);
134 |
135 | scanning = true;
136 | bluetoothAdapter.getBluetoothLeScanner().startScan(leScanCallback);
137 | cancelButton.setText(R.string.cancel);
138 | } else {
139 | scanning = false;
140 | bluetoothAdapter.getBluetoothLeScanner().stopScan(leScanCallback);
141 | cancelButton.setText(R.string.scan);
142 | }
143 | }
144 |
145 | private ScanCallback leScanCallback = new ScanCallback() {
146 | @Override
147 | public void onScanResult(int callbackType, final ScanResult result) {
148 | super.onScanResult(callbackType, result);
149 | final BluetoothDevice device=result.getDevice();
150 | if(device.getName()==null || !device.getName().contains("Onex")) return;
151 | runOnUiThread(new Runnable() {
152 | @Override
153 | public void run() { addDevice(device, result.getRssi()); }
154 | });
155 | }
156 |
157 | @Override
158 | public void onBatchScanResults(List results) {
159 | super.onBatchScanResults(results);
160 | }
161 |
162 | @Override
163 | public void onScanFailed(int errorCode) {
164 | super.onScanFailed(errorCode);
165 | }
166 | };
167 |
168 | private void addDevice(BluetoothDevice device, int rssi) {
169 | boolean deviceFound = false;
170 |
171 | for (BluetoothDevice listDev : deviceList) {
172 | if (listDev.getAddress().equals(device.getAddress())) {
173 | deviceFound = true;
174 | break;
175 | }
176 | }
177 |
178 | devRssiValues.put(device.getAddress(), rssi);
179 |
180 | if (!deviceFound) {
181 | deviceList.add(device);
182 | emptyList.setVisibility(View.GONE);
183 | deviceAdapter.notifyDataSetChanged();
184 | }
185 | }
186 |
187 | @Override
188 | public void onStart() {
189 | super.onStart();
190 |
191 | IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
192 | filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
193 | filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
194 | }
195 |
196 | @Override
197 | public void onStop() {
198 | super.onStop();
199 | bluetoothAdapter.getBluetoothLeScanner().stopScan(leScanCallback);
200 | }
201 |
202 | @Override
203 | protected void onDestroy() {
204 | super.onDestroy();
205 | bluetoothAdapter.getBluetoothLeScanner().stopScan(leScanCallback);
206 | }
207 |
208 | private OnItemClickListener deviceClickListener = new OnItemClickListener() {
209 | @Override
210 | public void onItemClick(AdapterView> parent, View view, int position, long id) {
211 | bluetoothAdapter.getBluetoothLeScanner().stopScan(leScanCallback);
212 | finishWith(deviceList.get(position).getAddress());
213 | }
214 | };
215 |
216 | private void finishWith(String address){
217 | Bundle b = new Bundle();
218 | b.putString(BluetoothDevice.EXTRA_DEVICE, address);
219 | Intent result = new Intent();
220 | result.putExtras(b);
221 | setResult(Activity.RESULT_OK, result);
222 | finish();
223 | }
224 |
225 | protected void onPause() {
226 | super.onPause();
227 | scanLeDevice(false);
228 | }
229 |
230 | class DeviceAdapter extends BaseAdapter {
231 | Context context;
232 | List devices;
233 | LayoutInflater inflater;
234 |
235 | public DeviceAdapter(Context context, List devices) {
236 | this.context = context;
237 | inflater = LayoutInflater.from(context);
238 | this.devices = devices;
239 | }
240 |
241 | @Override
242 | public int getCount() {
243 | return devices.size();
244 | }
245 |
246 | @Override
247 | public Object getItem(int position) {
248 | return devices.get(position);
249 | }
250 |
251 | @Override
252 | public long getItemId(int position) {
253 | return position;
254 | }
255 |
256 | @Override
257 | public View getView(int position, View convertView, ViewGroup parent) {
258 | ViewGroup vg;
259 |
260 | if (convertView != null) {
261 | vg = (ViewGroup) convertView;
262 | } else {
263 | vg = (ViewGroup) inflater.inflate(R.layout.device_element, null);
264 | }
265 |
266 | BluetoothDevice device = devices.get(position);
267 | final TextView tvadd = ((TextView) vg.findViewById(R.id.address));
268 | final TextView tvname = ((TextView) vg.findViewById(R.id.name));
269 | final TextView tvpaired = (TextView) vg.findViewById(R.id.paired);
270 | final TextView tvrssi = (TextView) vg.findViewById(R.id.rssi);
271 |
272 | tvrssi.setVisibility(View.VISIBLE);
273 | byte rssival = (byte) devRssiValues.get(device.getAddress()).intValue();
274 | if (rssival != 0) {
275 | tvrssi.setText(String.valueOf(rssival));
276 | }
277 |
278 | tvname.setText(device.getName());
279 | tvadd.setText(device.getAddress());
280 | if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
281 | Log.i(LOGNAME, "device::"+device.getName());
282 | tvname.setTextColor(Color.WHITE);
283 | tvadd.setTextColor(Color.WHITE);
284 | tvpaired.setTextColor(Color.GRAY);
285 | tvpaired.setVisibility(View.VISIBLE);
286 | tvpaired.setText(R.string.paired);
287 | tvrssi.setVisibility(View.VISIBLE);
288 | tvrssi.setTextColor(Color.WHITE);
289 |
290 | } else {
291 | tvname.setTextColor(Color.WHITE);
292 | tvadd.setTextColor(Color.WHITE);
293 | tvpaired.setVisibility(View.GONE);
294 | tvrssi.setVisibility(View.VISIBLE);
295 | tvrssi.setTextColor(Color.WHITE);
296 | }
297 | return vg;
298 | }
299 | }
300 |
301 | private void showMessage(String msg) {
302 | Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
303 | }
304 | }
305 |
--------------------------------------------------------------------------------
/src/ux-features.cpp:
--------------------------------------------------------------------------------
1 |
2 | #include
3 |
4 | #define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR)))
5 |
6 | #include "im-gui.h"
7 | #include "calendar.h"
8 | #include "ux-features.h"
9 |
10 | #define DRAG_THRESHOLD 30.0f
11 | #define START_DRIFT_THRESHOLD 10.0f
12 | #define END_DRIFT_THRESHOLD 0.01f
13 | #define DRIFT_DAMPING 0.5f
14 |
15 | static ImVec2 startpoint(0,0);
16 | char* dragPathId=0;
17 | static float delta_x=0.0f;
18 | static float delta_y=0.0f;
19 | static bool drag_handled = true;
20 | static float drift_threshold = START_DRIFT_THRESHOLD;
21 |
22 | #define MOVING_DELTA(x,y,d) (((x)*(x)+(y)*(y)) >= (d))
23 |
24 | void kill_drag()
25 | {
26 | free(dragPathId);
27 | dragPathId=0;
28 | delta_x = 0.0f;
29 | delta_y = 0.0f;
30 | drag_handled=true;
31 | drift_threshold = START_DRIFT_THRESHOLD;
32 | startpoint=ImVec2(0,0);
33 | }
34 |
35 | void track_drag(char* pathId, bool twodimensions)
36 | {
37 | if(ImGui::IsItemActive() && !ImGui::IsMouseDragging() && dragPathId && strcmp(pathId, dragPathId)){
38 | kill_drag();
39 | }
40 | else
41 | if(ImGui::IsItemActive() && ImGui::IsMouseDragging()){
42 | if(!dragPathId){
43 | if(!startpoint.x && !startpoint.y) startpoint=ImGui::GetIO().MousePos;
44 | ImVec2 mp=ImGui::GetIO().MousePos;
45 | float dx=mp.x-startpoint.x;
46 | float dy=mp.y-startpoint.y;
47 | if(!twodimensions){ dx=0; dy*=0.5; }
48 | float distancemoved=sqrtf(dx*dx+dy*dy);
49 | if(distancemoved > DRAG_THRESHOLD) dragPathId=strdup(pathId);
50 | }
51 | else{
52 | ImVec2 mouse_delta = ImGui::GetIO().MouseDelta;
53 | delta_x=mouse_delta.x;
54 | delta_y=mouse_delta.y;
55 | drag_handled=false;
56 | }
57 | }
58 | else
59 | if(!ImGui::IsMouseDown(0) && MOVING_DELTA(delta_x, delta_y, drift_threshold) && dragPathId && !strcmp(pathId, dragPathId)){
60 | int msperframe = (int)(1000.0f/ImGui::GetIO().Framerate);
61 | delta_x *= (1.0f-(DRIFT_DAMPING*msperframe)/100);
62 | delta_y *= (1.0f-(DRIFT_DAMPING*msperframe)/100);
63 | drag_handled=false;
64 | drift_threshold = END_DRIFT_THRESHOLD;
65 | }
66 | else
67 | if(!ImGui::IsMouseDragging() && dragPathId && !strcmp(pathId, dragPathId)){
68 | kill_drag();
69 | }
70 | }
71 |
72 | void set_drag_scroll(char* path)
73 | {
74 | if(!dragPathId) return;
75 | char* dragPathPath=strstr(dragPathId, "viewing-l");
76 | if(!dragPathPath) dragPathPath=strstr(dragPathId, "viewing-r");
77 | if(!dragPathPath) return;
78 | if(!strncmp(dragPathPath, path, strlen(path)) && strcmp(dragPathPath, path) && !drag_handled && MOVING_DELTA(delta_x,delta_y,0.1f)){
79 | ImGui::SetScrollX(ImGui::GetScrollX() - delta_x);
80 | ImGui::SetScrollY(ImGui::GetScrollY() - delta_y);
81 | drag_handled=true;
82 | }
83 | }
84 |
85 |
86 |
87 |
88 | #define LINK_THRESHOLD 20.0f
89 | #define LINK_FROM 1
90 | #define LINK_TO 2
91 |
92 | int linkDirection=0;
93 | char* linkFrom=0;
94 | char* linkTo=0;
95 | ImVec2 linkToPos=ImVec2(0,0);
96 | ImVec2 linkFromPos=ImVec2(0,0);
97 |
98 | void best_prop_name(char* newpropname, int proplen, object* from, char* touid)
99 | {
100 | if(object_property_contains(from, (char*)"is", (char*)"list")){
101 | ImStrncpy(newpropname, "list", proplen);
102 | }
103 | else{
104 | object* to=onex_get_from_cache(touid);
105 | char* is=object_property_values(to, (char*)"is");
106 | size_t edlen=strlen("editable ");
107 | if(!strncmp(is, "editable ", edlen)){
108 | ImStrncpy(newpropname, is+edlen, proplen);
109 | }
110 | else ImStrncpy(newpropname, is, proplen);
111 | for(char* p=newpropname; *p; p++) if(*p==' ') *p='-';
112 | }
113 | }
114 |
115 | void make_link()
116 | {
117 | if(linkTo && linkFrom){
118 | char* lastcolon=strrchr(linkFrom,':');
119 | char* fromuid=0;
120 | char* propname;
121 | if(lastcolon){
122 | propname=lastcolon+1;
123 | int n; if(!sscanf(propname, "%u", &n)){
124 | *lastcolon=0;
125 | fromuid=object_property(user, linkFrom);
126 | *lastcolon=':';
127 | }
128 | }
129 | if(!fromuid){
130 | fromuid=object_property(user, linkFrom);
131 | propname=0;
132 | }
133 | object* objectEditing = onex_get_from_cache(fromuid);
134 | char* touid=object_property(user, linkTo);
135 | if(objectEditing && touid){
136 | char newpropname[128];
137 | if(!propname){ best_prop_name(newpropname, IM_ARRAYSIZE(newpropname), objectEditing, touid); propname=newpropname; }
138 | if(object_property_is(objectEditing, propname, (char*)"--")){
139 | invoke_single_set(fromuid, propname, touid);
140 | }
141 | else invoke_single_add(fromuid, propname, touid);
142 | }
143 | }
144 | if(linkFrom) free(linkFrom); linkFrom=0;
145 | if(linkTo) free(linkTo); linkTo=0;
146 | linkToPos=ImVec2(0,0);
147 | linkFromPos=ImVec2(0,0);
148 | linkDirection=0;
149 | }
150 |
151 | void track_link(bool from, char* path, int width, int height)
152 | {
153 | if(ImGui::IsItemActive() && ImGui::IsMouseDragging() && !dragPathId){
154 | char*& linkEnd =from? linkFrom: linkTo;
155 | ImVec2& linkEndPos=from? linkFromPos: linkToPos;
156 | ImVec2 mp=ImGui::GetIO().MousePos;
157 | if(!linkEndPos.x && !linkEndPos.y) linkEndPos=mp;
158 | if(!linkEnd){
159 | float dx=linkEndPos.x-mp.x;
160 | float dy=linkEndPos.y-mp.y;
161 | dx=dx>=0? dx: -dx;
162 | dy=dy>=0? dy: -dy;
163 | if(dx>LINK_THRESHOLD && dycp.x-width && mp.xcp.y && mp.yPushClipRectFullScreen();
204 | float arrowAngle=0.38;
205 | float arrowLength=25;
206 | float dx=to.x-from.x;
207 | float dy=to.y-from.y;
208 | float dv=sqrtf(dx*dx+dy*dy);
209 | dx=arrowLength*dx/dv; dy=arrowLength*dy/dv; dv=arrowLength;
210 | float dv2=dv/cos(arrowAngle);
211 | float a=acos(dy/dv);
212 | float dx2=dv2*sin(a-arrowAngle);
213 | float dy2=dv2*cos(a-arrowAngle);
214 | float dx3=dv2*sin(a+arrowAngle);
215 | float dy3=dv2*cos(a+arrowAngle);
216 | ImVec2 t1(dx>0? to.x-dx3: to.x+dx3, to.y-dy3);
217 | ImVec2 t2(dx>0? to.x-dx2: to.x+dx2, to.y-dy2);
218 | draw_list->AddCircleFilled(from, 10.0f, ImColor(actionColour));
219 | draw_list->AddTriangleFilled(to, t1, t2, ImColor(actionColour));
220 | draw_list->AddLine(to, from, ImColor(actionColour), 4.0f);
221 | draw_list->PopClipRect();
222 | }
223 | ImGui::EndChild();
224 | ImGui::PopStyleColor();
225 | }
226 | }
227 |
228 |
229 |
230 |
231 | #define MAX_OPEN 64
232 | static char* open[MAX_OPEN];
233 |
234 | bool is_open(char* path)
235 | {
236 | for(int i=0; iEventFlag==ImGuiInputTextFlags_CallbackCharFilter){
295 | autocompletenext=true;
296 | return enforcer ? (enforcer(data)? 0: 1) : 0;
297 | }
298 | if(data->EventFlag==ImGuiInputTextFlags_CallbackAlways && autocompletenext){
299 | autocompletenext=false;
300 | int p=data->BufTextLen;
301 | if(p){
302 | int i;
303 | for(i=0; iBuf, autoCompleteChoices[i], p)){
305 | data->DeleteChars(0, p);
306 | data->InsertChars(0, autoCompleteChoices[i]);
307 | ss=p;
308 | se=strlen(autoCompleteChoices[i]);
309 | data->BufDirty=true;
310 | break;
311 | }
312 | }
313 | if(i==autoCompleteChoicesSize){
314 | ss=-1;
315 | se=-1;
316 | }
317 | }
318 | }
319 | if(data->EventFlag==ImGuiInputTextFlags_CallbackAlways){
320 | if(ss!=-1) data->CursorPos=ss;
321 | if(ss!=-1) data->SelectionStart=ss;
322 | if(se!=-1) data->SelectionEnd=se;
323 | return 0;
324 | }
325 | return 0;
326 | }
327 |
328 | bool filter_auto_input_text(const char* id, char* buf, int buflen, ImGuiTextEditCallback fafn)
329 | {
330 | int flags=ImGuiInputTextFlags_CallbackCharFilter|ImGuiInputTextFlags_CallbackAlways|ImGuiInputTextFlags_EnterReturnsTrue;
331 | bool done=ImGui::InputText(id, buf, buflen, flags, fafn, buf);
332 | if(done){ ss= -1; se= -1; }
333 | return done;
334 | }
335 |
336 | static bool enforcePropertyName(ImGuiTextEditCallbackData* data)
337 | {
338 | ImWchar ch = data->EventChar;
339 | if(ch >=256) return false;
340 | if(!strlen((char*)(data->UserData)) && !isalpha(ch)) return false;
341 | if(ch == ' '){ data->EventChar = '-'; return true; }
342 | if(ch == '-') return true;
343 | if(!isalnum(ch)) return false;
344 | data->EventChar = tolower(ch);
345 | return true;
346 | }
347 |
348 | int filter_and_autocomplete_calendar_tags(ImGuiTextEditCallbackData* data)
349 | {
350 | int tls=object_property_size(config, (char*)"taglookup");
351 | char* calendarTags[tls-1];
352 | for(int t=2; t<=tls; t++){
353 | calendarTags[t-2]=object_property_key(config, (char*)"taglookup", t);
354 | }
355 | return filter_and_autocomplete(data, enforcePropertyName, calendarTags, tls-1);
356 | }
357 |
358 | int filter_and_autocomplete_default(ImGuiTextEditCallbackData* data)
359 | {
360 | return filter_and_autocomplete(data, 0, 0, 0);
361 | }
362 |
363 | static const char* propertyNameChoices[] = {
364 | "is",
365 | "Timer",
366 | "title",
367 | "description",
368 | "text",
369 | "name",
370 | "list",
371 | "date",
372 | "time",
373 | "end-time",
374 | "end-date",
375 | "every",
376 | "tags",
377 | "cost",
378 | "total",
379 | "Rules",
380 | "Timer",
381 | "Notifying"
382 | };
383 |
384 | int filter_and_autocomplete_property_names(ImGuiTextEditCallbackData* data)
385 | {
386 | return filter_and_autocomplete(data, enforcePropertyName, (char**)propertyNameChoices, IM_ARRAYSIZE(propertyNameChoices));
387 | }
388 |
--------------------------------------------------------------------------------
/sascha/VulkanDebug.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * Vulkan examples debug wrapper
3 | *
4 | * Appendix for VK_EXT_Debug_Report can be found at https://github.com/KhronosGroup/Vulkan-Docs/blob/1.0-VK_EXT_debug_report/doc/specs/vulkan/appendices/debug_report.txt
5 | *
6 | * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de
7 | *
8 | * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
9 | */
10 |
11 | #include "VulkanDebug.h"
12 | #include
13 |
14 | namespace vks
15 | {
16 | namespace debug
17 | {
18 | #if !defined(__ANDROID__)
19 | // On desktop the LunarG loaders exposes a meta layer that contains all layers
20 | int32_t validationLayerCount = 1;
21 | const char *validationLayerNames[] = {
22 | "VK_LAYER_LUNARG_standard_validation"
23 | };
24 | #else
25 | // On Android we need to explicitly select all layers
26 | int32_t validationLayerCount = 6;
27 | const char *validationLayerNames[] = {
28 | "VK_LAYER_GOOGLE_threading",
29 | "VK_LAYER_LUNARG_parameter_validation",
30 | "VK_LAYER_LUNARG_object_tracker",
31 | "VK_LAYER_LUNARG_core_validation",
32 | "VK_LAYER_LUNARG_swapchain",
33 | "VK_LAYER_GOOGLE_unique_objects"
34 | };
35 | #endif
36 |
37 | PFN_vkCreateDebugReportCallbackEXT CreateDebugReportCallback = VK_NULL_HANDLE;
38 | PFN_vkDestroyDebugReportCallbackEXT DestroyDebugReportCallback = VK_NULL_HANDLE;
39 | PFN_vkDebugReportMessageEXT dbgBreakCallback = VK_NULL_HANDLE;
40 |
41 | VkDebugReportCallbackEXT msgCallback;
42 |
43 | VkBool32 messageCallback(
44 | VkDebugReportFlagsEXT flags,
45 | VkDebugReportObjectTypeEXT objType,
46 | uint64_t srcObject,
47 | size_t location,
48 | int32_t msgCode,
49 | const char* pLayerPrefix,
50 | const char* pMsg,
51 | void* pUserData)
52 | {
53 | // Select prefix depending on flags passed to the callback
54 | // Note that multiple flags may be set for a single validation message
55 | std::string prefix("");
56 |
57 | // Error that may result in undefined behaviour
58 | if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)
59 | {
60 | prefix += "ERROR:";
61 | };
62 | // Warnings may hint at unexpected / non-spec API usage
63 | if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT)
64 | {
65 | prefix += "WARNING:";
66 | };
67 | // May indicate sub-optimal usage of the API
68 | if (flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT)
69 | {
70 | prefix += "PERFORMANCE:";
71 | };
72 | // Informal messages that may become handy during debugging
73 | if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT)
74 | {
75 | prefix += "INFO:";
76 | }
77 | // Diagnostic info from the Vulkan loader and layers
78 | // Usually not helpful in terms of API usage, but may help to debug layer and loader problems
79 | if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT)
80 | {
81 | prefix += "DEBUG:";
82 | }
83 |
84 | // Display message to default output (console/logcat)
85 | std::stringstream debugMessage;
86 | debugMessage << prefix << " [" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg;
87 |
88 | #if defined(__ANDROID__)
89 | if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
90 | LOGE("%s", debugMessage.str().c_str());
91 | }
92 | else {
93 | LOGD("%s", debugMessage.str().c_str());
94 | }
95 | #else
96 | if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
97 | std::cerr << debugMessage.str() << "\n";
98 | }
99 | else {
100 | std::cout << debugMessage.str() << "\n";
101 | }
102 | #endif
103 |
104 | fflush(stdout);
105 |
106 | // The return value of this callback controls wether the Vulkan call that caused
107 | // the validation message will be aborted or not
108 | // We return VK_FALSE as we DON'T want Vulkan calls that cause a validation message
109 | // (and return a VkResult) to abort
110 | // If you instead want to have calls abort, pass in VK_TRUE and the function will
111 | // return VK_ERROR_VALIDATION_FAILED_EXT
112 | return VK_FALSE;
113 | }
114 |
115 | void setupDebugging(VkInstance instance, VkDebugReportFlagsEXT flags, VkDebugReportCallbackEXT callBack)
116 | {
117 | CreateDebugReportCallback = reinterpret_cast(vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT"));
118 | DestroyDebugReportCallback = reinterpret_cast(vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"));
119 | dbgBreakCallback = reinterpret_cast(vkGetInstanceProcAddr(instance, "vkDebugReportMessageEXT"));
120 |
121 | VkDebugReportCallbackCreateInfoEXT dbgCreateInfo = {};
122 | dbgCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
123 | dbgCreateInfo.pfnCallback = (PFN_vkDebugReportCallbackEXT)messageCallback;
124 | dbgCreateInfo.flags = flags;
125 |
126 | CreateDebugReportCallback(
127 | instance,
128 | &dbgCreateInfo,
129 | nullptr,
130 | (callBack != VK_NULL_HANDLE) ? &callBack : &msgCallback);
131 | }
132 |
133 | void freeDebugCallback(VkInstance instance)
134 | {
135 | if (msgCallback != VK_NULL_HANDLE)
136 | {
137 | DestroyDebugReportCallback(instance, msgCallback, nullptr);
138 | }
139 | }
140 | }
141 |
142 | namespace debugmarker
143 | {
144 | bool active = false;
145 |
146 | PFN_vkDebugMarkerSetObjectTagEXT pfnDebugMarkerSetObjectTag = VK_NULL_HANDLE;
147 | PFN_vkDebugMarkerSetObjectNameEXT pfnDebugMarkerSetObjectName = VK_NULL_HANDLE;
148 | PFN_vkCmdDebugMarkerBeginEXT pfnCmdDebugMarkerBegin = VK_NULL_HANDLE;
149 | PFN_vkCmdDebugMarkerEndEXT pfnCmdDebugMarkerEnd = VK_NULL_HANDLE;
150 | PFN_vkCmdDebugMarkerInsertEXT pfnCmdDebugMarkerInsert = VK_NULL_HANDLE;
151 |
152 | void setup(VkDevice device)
153 | {
154 | pfnDebugMarkerSetObjectTag = reinterpret_cast(vkGetDeviceProcAddr(device, "vkDebugMarkerSetObjectTagEXT"));
155 | pfnDebugMarkerSetObjectName = reinterpret_cast(vkGetDeviceProcAddr(device, "vkDebugMarkerSetObjectNameEXT"));
156 | pfnCmdDebugMarkerBegin = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdDebugMarkerBeginEXT"));
157 | pfnCmdDebugMarkerEnd = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdDebugMarkerEndEXT"));
158 | pfnCmdDebugMarkerInsert = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdDebugMarkerInsertEXT"));
159 |
160 | // Set flag if at least one function pointer is present
161 | active = (pfnDebugMarkerSetObjectName != VK_NULL_HANDLE);
162 | }
163 |
164 | void setObjectName(VkDevice device, uint64_t object, VkDebugReportObjectTypeEXT objectType, const char *name)
165 | {
166 | // Check for valid function pointer (may not be present if not running in a debugging application)
167 | if (pfnDebugMarkerSetObjectName)
168 | {
169 | VkDebugMarkerObjectNameInfoEXT nameInfo = {};
170 | nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT;
171 | nameInfo.objectType = objectType;
172 | nameInfo.object = object;
173 | nameInfo.pObjectName = name;
174 | pfnDebugMarkerSetObjectName(device, &nameInfo);
175 | }
176 | }
177 |
178 | void setObjectTag(VkDevice device, uint64_t object, VkDebugReportObjectTypeEXT objectType, uint64_t name, size_t tagSize, const void* tag)
179 | {
180 | // Check for valid function pointer (may not be present if not running in a debugging application)
181 | if (pfnDebugMarkerSetObjectTag)
182 | {
183 | VkDebugMarkerObjectTagInfoEXT tagInfo = {};
184 | tagInfo.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_TAG_INFO_EXT;
185 | tagInfo.objectType = objectType;
186 | tagInfo.object = object;
187 | tagInfo.tagName = name;
188 | tagInfo.tagSize = tagSize;
189 | tagInfo.pTag = tag;
190 | pfnDebugMarkerSetObjectTag(device, &tagInfo);
191 | }
192 | }
193 |
194 | void beginRegion(VkCommandBuffer cmdbuffer, const char* pMarkerName, glm::vec4 color)
195 | {
196 | // Check for valid function pointer (may not be present if not running in a debugging application)
197 | if (pfnCmdDebugMarkerBegin)
198 | {
199 | VkDebugMarkerMarkerInfoEXT markerInfo = {};
200 | markerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT;
201 | memcpy(markerInfo.color, &color[0], sizeof(float) * 4);
202 | markerInfo.pMarkerName = pMarkerName;
203 | pfnCmdDebugMarkerBegin(cmdbuffer, &markerInfo);
204 | }
205 | }
206 |
207 | void insert(VkCommandBuffer cmdbuffer, std::string markerName, glm::vec4 color)
208 | {
209 | // Check for valid function pointer (may not be present if not running in a debugging application)
210 | if (pfnCmdDebugMarkerInsert)
211 | {
212 | VkDebugMarkerMarkerInfoEXT markerInfo = {};
213 | markerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT;
214 | memcpy(markerInfo.color, &color[0], sizeof(float) * 4);
215 | markerInfo.pMarkerName = markerName.c_str();
216 | pfnCmdDebugMarkerInsert(cmdbuffer, &markerInfo);
217 | }
218 | }
219 |
220 | void endRegion(VkCommandBuffer cmdBuffer)
221 | {
222 | // Check for valid function (may not be present if not runnin in a debugging application)
223 | if (pfnCmdDebugMarkerEnd)
224 | {
225 | pfnCmdDebugMarkerEnd(cmdBuffer);
226 | }
227 | }
228 |
229 | void setCommandBufferName(VkDevice device, VkCommandBuffer cmdBuffer, const char * name)
230 | {
231 | setObjectName(device, (uint64_t)cmdBuffer, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, name);
232 | }
233 |
234 | void setQueueName(VkDevice device, VkQueue queue, const char * name)
235 | {
236 | setObjectName(device, (uint64_t)queue, VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT, name);
237 | }
238 |
239 | void setImageName(VkDevice device, VkImage image, const char * name)
240 | {
241 | setObjectName(device, (uint64_t)image, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, name);
242 | }
243 |
244 | void setSamplerName(VkDevice device, VkSampler sampler, const char * name)
245 | {
246 | setObjectName(device, (uint64_t)sampler, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT, name);
247 | }
248 |
249 | void setBufferName(VkDevice device, VkBuffer buffer, const char * name)
250 | {
251 | setObjectName(device, (uint64_t)buffer, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, name);
252 | }
253 |
254 | void setDeviceMemoryName(VkDevice device, VkDeviceMemory memory, const char * name)
255 | {
256 | setObjectName(device, (uint64_t)memory, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, name);
257 | }
258 |
259 | void setShaderModuleName(VkDevice device, VkShaderModule shaderModule, const char * name)
260 | {
261 | setObjectName(device, (uint64_t)shaderModule, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT, name);
262 | }
263 |
264 | void setPipelineName(VkDevice device, VkPipeline pipeline, const char * name)
265 | {
266 | setObjectName(device, (uint64_t)pipeline, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, name);
267 | }
268 |
269 | void setPipelineLayoutName(VkDevice device, VkPipelineLayout pipelineLayout, const char * name)
270 | {
271 | setObjectName(device, (uint64_t)pipelineLayout, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT, name);
272 | }
273 |
274 | void setRenderPassName(VkDevice device, VkRenderPass renderPass, const char * name)
275 | {
276 | setObjectName(device, (uint64_t)renderPass, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, name);
277 | }
278 |
279 | void setFramebufferName(VkDevice device, VkFramebuffer framebuffer, const char * name)
280 | {
281 | setObjectName(device, (uint64_t)framebuffer, VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT, name);
282 | }
283 |
284 | void setDescriptorSetLayoutName(VkDevice device, VkDescriptorSetLayout descriptorSetLayout, const char * name)
285 | {
286 | setObjectName(device, (uint64_t)descriptorSetLayout, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT, name);
287 | }
288 |
289 | void setDescriptorSetName(VkDevice device, VkDescriptorSet descriptorSet, const char * name)
290 | {
291 | setObjectName(device, (uint64_t)descriptorSet, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, name);
292 | }
293 |
294 | void setSemaphoreName(VkDevice device, VkSemaphore semaphore, const char * name)
295 | {
296 | setObjectName(device, (uint64_t)semaphore, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT, name);
297 | }
298 |
299 | void setFenceName(VkDevice device, VkFence fence, const char * name)
300 | {
301 | setObjectName(device, (uint64_t)fence, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT, name);
302 | }
303 |
304 | void setEventName(VkDevice device, VkEvent _event, const char * name)
305 | {
306 | setObjectName(device, (uint64_t)_event, VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT, name);
307 | }
308 | };
309 | }
310 |
311 |
--------------------------------------------------------------------------------
/android/onexapp/src/main/java/android/network/object/onexapp/EternalService.java:
--------------------------------------------------------------------------------
1 | // THANKS to https://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android-gt-7
2 |
3 | package network.object.onexapp;
4 |
5 | import java.io.ByteArrayOutputStream;
6 |
7 | import android.os.*;
8 | import android.view.inputmethod.*;
9 | import android.view.ViewGroup.LayoutParams;
10 | import android.view.KeyEvent;
11 | import android.widget.*;
12 | import android.text.*;
13 | import android.app.NativeActivity;
14 | import android.hardware.usb.*;
15 | import android.content.*;
16 | import android.util.Log;
17 | import android.app.*;
18 |
19 | import com.felhr.usbserial.UsbSerialInterface;
20 | import com.felhr.usbserial.UsbSerialDevice;
21 |
22 | public class EternalService extends Service {
23 | private static String LOGNAME = "Onex EternalService";
24 | public static final boolean logReadWrite = true;
25 |
26 | static private EternalService self=null;
27 |
28 | static public void delay(int ms){ try{ Thread.sleep(ms); }catch(Exception e){}; }
29 |
30 | @Override
31 | public IBinder onBind(Intent intent) {
32 | Log.d(LOGNAME, "*onBind");
33 | return null;
34 | }
35 |
36 | static private boolean initialised=false;
37 |
38 | static private boolean connecting=false;
39 | static private boolean reconnecting=false;
40 |
41 | static private String blemac=null;
42 |
43 | static public native String initOnex();
44 | static public native void loopOnex();
45 | static public native void setBLEMac(String blemac);
46 | static public native void connectionState(String state);
47 |
48 | @Override
49 | public void onCreate() {
50 | super.onCreate();
51 | Log.d(LOGNAME, "*onCreate");
52 |
53 | String CHANNEL_ID = "onex-activity";
54 |
55 | NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Onex Activity", NotificationManager.IMPORTANCE_DEFAULT);
56 | ((NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
57 |
58 | Intent intent = new Intent(this, OnexNativeActivity.class);
59 | PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
60 |
61 | Notification.Builder notifbuilder = new Notification.Builder(this, CHANNEL_ID);
62 | notifbuilder.setSmallIcon(R.drawable.icon)
63 | .setContentTitle("Onex is running")
64 | .setContentText("(long press for notif settings)")
65 | .setContentIntent(pendingIntent)
66 | .setAutoCancel(true);
67 | startForeground(54321, notifbuilder.build());
68 | }
69 |
70 | // onStartCommand may be called many times
71 | @Override
72 | public int onStartCommand(Intent intent, int flags, int startId) {
73 | super.onStartCommand(intent, flags, startId);
74 | Log.d(LOGNAME, "*onStartCommand");
75 |
76 | self=this;
77 |
78 | if(!initialised){
79 |
80 | System.loadLibrary("native-lib");
81 |
82 | new Thread(){
83 | @Override
84 | public void run(){
85 | Log.d(LOGNAME, "============== calling initOnex()");
86 | blemac=initOnex();
87 | Log.d(LOGNAME, "============== initOnex() returned "+blemac);
88 |
89 | bindToNUSService();
90 |
91 | Log.d(LOGNAME, "============== calling loopOnex()");
92 | loopOnex();
93 | }
94 | }.start();
95 | initialised=true;
96 | }
97 | return START_STICKY;
98 | }
99 |
100 | private NUSService nusService = null;
101 |
102 | private void bindToNUSService() {
103 | Log.d(LOGNAME, "bindToNUSService()");
104 |
105 | Intent bindIntent = new Intent(this, NUSService.class);
106 | bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
107 |
108 | IntentFilter intentFilter = new IntentFilter();
109 | intentFilter.addAction(NUSService.ACTION_GATT_CONNECTING);
110 | intentFilter.addAction(NUSService.ACTION_GATT_CONNECTED);
111 | intentFilter.addAction(NUSService.ACTION_GATT_SERVICES_DISCOVERED);
112 | intentFilter.addAction(NUSService.ACTION_NUS_CONNECTED);
113 | intentFilter.addAction(NUSService.ACTION_DATA_AVAILABLE);
114 | intentFilter.addAction(NUSService.ACTION_GATT_DISCONNECTED);
115 | registerReceiver(NUSStatusChangeReceiver, intentFilter);
116 | }
117 |
118 | private ServiceConnection serviceConnection = new ServiceConnection() {
119 | public void onServiceConnected(ComponentName className, IBinder rawBinder) {
120 | if(nusService !=null){
121 | Log.d(LOGNAME, "onServiceConnected(): attempt to set nusService on top of existing");
122 | return;
123 | }
124 |
125 | nusService = ((NUSService.LocalBinder)rawBinder).getService();
126 |
127 | if(!nusService.initialize()){
128 | Log.e(LOGNAME, "onServiceConnected(): Unable to initialize NUS service");
129 | return;
130 | }
131 | Log.d(LOGNAME, "onServiceConnected(): OK");
132 |
133 | connectBLEMac();
134 | }
135 |
136 | public void onServiceDisconnected(ComponentName classname) {
137 | Log.d(LOGNAME, "onServiceDisconnected()");
138 | connecting=false;
139 | reconnecting=false;
140 | nusService = null;
141 | recvBuff.reset();
142 | }
143 | };
144 |
145 | static public void connectBLEMac(boolean success){
146 | if(success) self.connectBLEMac();
147 | else connectionState("BLE disconnected");
148 | }
149 |
150 | private void connectBLEMac(){
151 | Log.d(LOGNAME, "connectBLEMac["+nusService+", "+blemac+"]");
152 | if(nusService==null || blemac==null) return;
153 | if(!nusService.connect(blemac)) Log.d(LOGNAME, "nusService.connect failed");
154 | }
155 |
156 | static public void ensureBluetoothConnecting(){
157 | Log.d(LOGNAME, "ensureBluetoothConnecting() connecting="+connecting+" reconnecting="+reconnecting);
158 | if(reconnecting) return;
159 | reconnecting=true;
160 | blemac=null; setBLEMac("");
161 | if(self.nusService.disconnect()){
162 | Log.d(LOGNAME, "ensureBluetoothConnecting(): disconnecting..");
163 | if(connecting){
164 | delay(10);
165 | Log.d(LOGNAME, "ensureBluetoothConnecting(): already reconnecting; closing");
166 | self.nusService.close();
167 | connecting=false;
168 | connectionState("BLE selection");
169 | OnexNativeActivity.selectBLEMac();
170 | }
171 | }else{
172 | Log.d(LOGNAME, "ensureBluetoothConnecting(): not yet connected");
173 | connectionState("BLE selection");
174 | OnexNativeActivity.selectBLEMac();
175 | }
176 | }
177 |
178 | public static void onBLEMacSelected(String bm){
179 | Log.d(LOGNAME, "onBLEMacSelected("+bm+")");
180 | if(bm.equals("00:00:00:00:00:00")){
181 | connecting=false;
182 | reconnecting=false;
183 | blemac=null; setBLEMac("");
184 | connectionState("BLE disconnected");
185 | return;
186 | }
187 | blemac=bm; setBLEMac(blemac);
188 | connectBLEMac(true);
189 | }
190 |
191 | static public void bluetoothOff(){
192 | Log.d(LOGNAME, "BT off");
193 | if(self.nusService.disconnect()){
194 | delay(10);
195 | self.nusService.close();
196 | }
197 | connecting=false;
198 | reconnecting=false;
199 | connectionState("BLE disconnected");
200 | }
201 |
202 | static public void bluetoothOn(){
203 | Log.d(LOGNAME, "BT on");
204 | if(blemac!=null){
205 | connectionState("BLE rescanning");
206 | self.nusService.scanForBLEMAC(blemac);
207 | }
208 | }
209 |
210 | private final BroadcastReceiver NUSStatusChangeReceiver = new BroadcastReceiver() {
211 |
212 | public void onReceive(Context context, Intent intent) {
213 | String action = intent.getAction();
214 |
215 | if (action.equals(NUSService.ACTION_GATT_CONNECTING)) {
216 | Log.d(LOGNAME, "GATT connecting");
217 | connecting=true;
218 | connectionState("BLE connecting");
219 | }
220 |
221 | if (action.equals(NUSService.ACTION_GATT_CONNECTED)) {
222 | Log.d(LOGNAME, "GATT connected");
223 | connecting=false;
224 | reconnecting=false;
225 | connectionState("BLE connected");
226 | }
227 |
228 | if (action.equals(NUSService.ACTION_GATT_SERVICES_DISCOVERED)) {
229 | Log.d(LOGNAME, "GATT connected");
230 | connecting=false;
231 | reconnecting=false;
232 | connectionState("services connected");
233 | }
234 |
235 | if (action.equals(NUSService.ACTION_NUS_CONNECTED)) {
236 | Log.d(LOGNAME, "NUS connected");
237 | connecting=false;
238 | reconnecting=false;
239 | connectionState("Onex connected");
240 | asyncConnected();
241 | }
242 |
243 | if (action.equals(NUSService.ACTION_DATA_AVAILABLE)) {
244 | try {
245 | byte[] data = intent.getByteArrayExtra(NUSService.EXTRA_DATA);
246 | dataRecv(data);
247 | } catch (Exception e) {
248 | Log.e(LOGNAME, e.toString());
249 | }
250 | }
251 |
252 | if (action.equals(NUSService.ACTION_GATT_DISCONNECTED)) {
253 | Log.d(LOGNAME, "GATT disconnected");
254 | recvBuff.reset();
255 | if(reconnecting) self.nusService.close();
256 | if(blemac==null){
257 | connectionState("BLE selection");
258 | OnexNativeActivity.selectBLEMac();
259 | }
260 | else connectBLEMac();
261 | }
262 | }
263 | };
264 |
265 | // -----------------------------------------------------------
266 |
267 | private static UsbSerialDevice serialPort = null;
268 |
269 | static public void onUSBAttached(Intent intent){
270 | UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
271 | UsbManager usbManager = self.getSystemService(UsbManager.class);
272 | final UsbDeviceConnection connection = usbManager.openDevice(device);
273 | UsbInterface interf = device.getInterface(0);
274 | connection.claimInterface(interf, true);
275 | serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
276 | if(serialPort == null) { Log.e(LOGNAME, "No serial port!"); return; }
277 | if(!serialPort.open()) { Log.e(LOGNAME, "Could not open serial port!"); return; }
278 | serialPort.setBaudRate(9600);
279 | serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
280 | serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
281 | serialPort.setParity(UsbSerialInterface.PARITY_NONE);
282 | serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
283 | serialPort.read(recvCB);
284 | asyncConnected();
285 | }
286 |
287 | static public UsbSerialInterface.UsbReadCallback recvCB = new UsbSerialInterface.UsbReadCallback() {
288 | @Override
289 | public void onReceivedData(byte[] data) { dataRecv(data); }
290 | };
291 |
292 | // -----------------------------------------------------------
293 |
294 | static public native void serialOnRecv(String b);
295 |
296 | static public void asyncConnected(){
297 | new Thread(){ public void run(){ serialOnRecv(null); }}.start();
298 | }
299 |
300 | static private ByteArrayOutputStream recvBuff = new ByteArrayOutputStream();
301 |
302 | static private void dataRecv(byte[] data) {
303 | try{
304 | recvBuff.write(data);
305 | String chars = recvBuff.toString("UTF-8");
306 | int x = chars.lastIndexOf('\n');
307 | if(x == -1) return;
308 | String newChars = chars.substring(0,x+1);
309 | recvBuff.reset();
310 | recvBuff.write(chars.substring(x+1).getBytes());
311 | if(logReadWrite) Log.d(LOGNAME, "read (" + newChars + ")" );
312 | serialOnRecv(newChars);
313 | }catch(Exception e){}
314 | }
315 |
316 | static public void serialSend(String chars){
317 | if(logReadWrite) Log.d(LOGNAME, "write (" + chars + ")");
318 | try {
319 | if (self.nusService!=null){
320 | self.nusService.write(chars.getBytes("UTF-8"));
321 | }
322 | if(self.serialPort!=null){
323 | self.serialPort.write(chars.getBytes("UTF-8"));
324 | }
325 | }catch(Exception e){
326 | e.printStackTrace();
327 | }
328 | }
329 |
330 | // -----------------------------------------------------------
331 |
332 | @Override
333 | public void onDestroy() {
334 | super.onDestroy();
335 | Log.d(LOGNAME, "*onDestroy");
336 |
337 | OnexNativeActivity.restartEternal();
338 |
339 | try {
340 | unregisterReceiver(NUSStatusChangeReceiver);
341 | } catch (Exception e) {
342 | e.printStackTrace();
343 | }
344 | unbindService(serviceConnection);
345 | nusService.stopSelf();
346 | nusService= null;
347 | }
348 |
349 | @Override
350 | public void onTaskRemoved(Intent rootIntent) {
351 | super.onTaskRemoved(rootIntent);
352 | Log.d(LOGNAME, "*onTaskRemoved");
353 |
354 | OnexNativeActivity.restartEternal();
355 | }
356 | }
357 |
--------------------------------------------------------------------------------
/external/fonts/fonts_noto_sans_numeric_60.c:
--------------------------------------------------------------------------------
1 | /**
2 | * Generated by https://littlevgl.com/ttf-font-to-c-array from NotoSans-regular
3 | */
4 |
5 | #include "lvgl.h"
6 |
7 | /*******************************************************************************
8 | * Size: 60 px
9 | * Bpp: 1
10 | * Opts:
11 | ******************************************************************************/
12 |
13 | #ifndef NOTO_SANS_60
14 | #define NOTO_SANS_60 1
15 | #endif
16 |
17 | #if NOTO_SANS_60
18 |
19 | /*-----------------
20 | * BITMAPS
21 | *----------------*/
22 |
23 | /*Store the image of the glyphs*/
24 | static LV_ATTRIBUTE_LARGE_CONST const uint8_t gylph_bitmap[] = {
25 | /* U+30 "0" */
26 | 0x0, 0x0, 0x0, 0x0, 0xf, 0xfe, 0x0, 0x1,
27 | 0xff, 0xf8, 0x0, 0x7f, 0xff, 0xc0, 0xf, 0xff,
28 | 0xfe, 0x0, 0xfc, 0x3, 0xf0, 0x1f, 0x80, 0x1f,
29 | 0x81, 0xf0, 0x0, 0xf8, 0x3e, 0x0, 0x7, 0xc3,
30 | 0xe0, 0x0, 0x7c, 0x7c, 0x0, 0x7, 0xc7, 0xc0,
31 | 0x0, 0x3e, 0x7c, 0x0, 0x3, 0xe7, 0xc0, 0x0,
32 | 0x3e, 0x7c, 0x0, 0x3, 0xef, 0x80, 0x0, 0x1f,
33 | 0xf8, 0x0, 0x1, 0xff, 0x80, 0x0, 0x1f, 0xf8,
34 | 0x0, 0x1, 0xff, 0x80, 0x0, 0x1f, 0xf8, 0x0,
35 | 0x1, 0xff, 0x80, 0x0, 0x1f, 0xf8, 0x0, 0x1,
36 | 0xff, 0x80, 0x0, 0x1f, 0xf8, 0x0, 0x1, 0xff,
37 | 0x80, 0x0, 0x1f, 0xf8, 0x0, 0x1, 0xff, 0x80,
38 | 0x0, 0x1f, 0xf8, 0x0, 0x1, 0xff, 0x80, 0x0,
39 | 0x1f, 0x7c, 0x0, 0x3, 0xe7, 0xc0, 0x0, 0x3e,
40 | 0x7c, 0x0, 0x3, 0xe7, 0xc0, 0x0, 0x3e, 0x3c,
41 | 0x0, 0x7, 0xe3, 0xe0, 0x0, 0x7c, 0x3e, 0x0,
42 | 0x7, 0xc1, 0xf0, 0x0, 0xf8, 0x1f, 0x80, 0x1f,
43 | 0x80, 0xfc, 0x3, 0xf0, 0x7, 0xff, 0xfe, 0x0,
44 | 0x3f, 0xff, 0xc0, 0x1, 0xff, 0xf8, 0x0, 0x7,
45 | 0xfe, 0x0, 0x0, 0x0, 0x0, 0x0,
46 |
47 | /* U+31 "1" */
48 | 0x0, 0x1f, 0x0, 0x3f, 0x0, 0xff, 0x1, 0xff,
49 | 0x3, 0xff, 0x7, 0xff, 0x1f, 0xdf, 0x3f, 0x9f,
50 | 0x7f, 0x1f, 0xfe, 0x1f, 0x78, 0x1f, 0x30, 0x1f,
51 | 0x0, 0x1f, 0x0, 0x1f, 0x0, 0x1f, 0x0, 0x1f,
52 | 0x0, 0x1f, 0x0, 0x1f, 0x0, 0x1f, 0x0, 0x1f,
53 | 0x0, 0x1f, 0x0, 0x1f, 0x0, 0x1f, 0x0, 0x1f,
54 | 0x0, 0x1f, 0x0, 0x1f, 0x0, 0x1f, 0x0, 0x1f,
55 | 0x0, 0x1f, 0x0, 0x1f, 0x0, 0x1f, 0x0, 0x1f,
56 | 0x0, 0x1f, 0x0, 0x1f, 0x0, 0x1f, 0x0, 0x1f,
57 | 0x0, 0x1f, 0x0, 0x1f, 0x0, 0x1f, 0x0, 0x1f,
58 | 0x0, 0x1f, 0x0, 0x1f, 0x0, 0x1f,
59 |
60 | /* U+32 "2" */
61 | 0x0, 0x0, 0x0, 0x0, 0x1f, 0xfe, 0x0, 0x7,
62 | 0xff, 0xf8, 0x1, 0xff, 0xff, 0xe0, 0x7f, 0xff,
63 | 0xff, 0x7, 0xf0, 0x3, 0xf0, 0x3c, 0x0, 0x1f,
64 | 0x83, 0x80, 0x0, 0xf8, 0x0, 0x0, 0xf, 0xc0,
65 | 0x0, 0x0, 0x7c, 0x0, 0x0, 0x7, 0xc0, 0x0,
66 | 0x0, 0x7c, 0x0, 0x0, 0x7, 0xc0, 0x0, 0x0,
67 | 0x7c, 0x0, 0x0, 0x7, 0xc0, 0x0, 0x0, 0xfc,
68 | 0x0, 0x0, 0xf, 0x80, 0x0, 0x0, 0xf8, 0x0,
69 | 0x0, 0x1f, 0x80, 0x0, 0x1, 0xf0, 0x0, 0x0,
70 | 0x3e, 0x0, 0x0, 0x7, 0xe0, 0x0, 0x0, 0xfc,
71 | 0x0, 0x0, 0x1f, 0x80, 0x0, 0x3, 0xf8, 0x0,
72 | 0x0, 0x3f, 0x0, 0x0, 0x7, 0xe0, 0x0, 0x0,
73 | 0xfc, 0x0, 0x0, 0x1f, 0x80, 0x0, 0x3, 0xf0,
74 | 0x0, 0x0, 0x7e, 0x0, 0x0, 0xf, 0xc0, 0x0,
75 | 0x1, 0xf8, 0x0, 0x0, 0x3f, 0x0, 0x0, 0x7,
76 | 0xe0, 0x0, 0x0, 0xfc, 0x0, 0x0, 0x1f, 0x80,
77 | 0x0, 0x3, 0xf0, 0x0, 0x0, 0x7e, 0x0, 0x0,
78 | 0xf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
79 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
80 | 0xff, 0xff,
81 |
82 | /* U+33 "3" */
83 | 0x0, 0x0, 0x0, 0x0, 0x1f, 0xff, 0x0, 0xf,
84 | 0xff, 0xfc, 0x3, 0xff, 0xff, 0xf0, 0x7f, 0xff,
85 | 0xff, 0x87, 0xf8, 0x1, 0xf8, 0x3c, 0x0, 0xf,
86 | 0xc1, 0x80, 0x0, 0x7c, 0x0, 0x0, 0x7, 0xe0,
87 | 0x0, 0x0, 0x3e, 0x0, 0x0, 0x3, 0xe0, 0x0,
88 | 0x0, 0x3e, 0x0, 0x0, 0x3, 0xe0, 0x0, 0x0,
89 | 0x3e, 0x0, 0x0, 0x7, 0xe0, 0x0, 0x0, 0x7c,
90 | 0x0, 0x0, 0xf, 0xc0, 0x0, 0x1, 0xf8, 0x0,
91 | 0x0, 0x3f, 0x0, 0x0, 0x1f, 0xe0, 0x1, 0xff,
92 | 0xfc, 0x0, 0x1f, 0xfe, 0x0, 0x1, 0xff, 0xfc,
93 | 0x0, 0x1f, 0xff, 0xf0, 0x0, 0x0, 0xff, 0x80,
94 | 0x0, 0x1, 0xfc, 0x0, 0x0, 0x7, 0xe0, 0x0,
95 | 0x0, 0x3e, 0x0, 0x0, 0x3, 0xf0, 0x0, 0x0,
96 | 0x1f, 0x0, 0x0, 0x1, 0xf0, 0x0, 0x0, 0x1f,
97 | 0x0, 0x0, 0x1, 0xf0, 0x0, 0x0, 0x1f, 0x0,
98 | 0x0, 0x1, 0xf0, 0x0, 0x0, 0x3f, 0x0, 0x0,
99 | 0x3, 0xe0, 0x0, 0x0, 0x7e, 0xe0, 0x0, 0xf,
100 | 0xcf, 0x80, 0x3, 0xfc, 0xff, 0xff, 0xff, 0x8f,
101 | 0xff, 0xff, 0xe0, 0x7f, 0xff, 0xfc, 0x1, 0xff,
102 | 0xfe, 0x0, 0x0, 0x0, 0x0, 0x0,
103 |
104 | /* U+34 "4" */
105 | 0x0, 0x0, 0xf, 0xc0, 0x0, 0x0, 0xf, 0xc0,
106 | 0x0, 0x0, 0x1f, 0xc0, 0x0, 0x0, 0x3f, 0xc0,
107 | 0x0, 0x0, 0x7f, 0xc0, 0x0, 0x0, 0x7f, 0xc0,
108 | 0x0, 0x0, 0xf7, 0xc0, 0x0, 0x1, 0xf7, 0xc0,
109 | 0x0, 0x3, 0xe7, 0xc0, 0x0, 0x3, 0xe7, 0xc0,
110 | 0x0, 0x7, 0xc7, 0xc0, 0x0, 0xf, 0x87, 0xc0,
111 | 0x0, 0x1f, 0x7, 0xc0, 0x0, 0x1f, 0x7, 0xc0,
112 | 0x0, 0x3e, 0x7, 0xc0, 0x0, 0x7c, 0x7, 0xc0,
113 | 0x0, 0x7c, 0x7, 0xc0, 0x0, 0xf8, 0x7, 0xc0,
114 | 0x1, 0xf0, 0x7, 0xc0, 0x3, 0xe0, 0x7, 0xc0,
115 | 0x3, 0xe0, 0x7, 0xc0, 0x7, 0xc0, 0x7, 0xc0,
116 | 0xf, 0x80, 0x7, 0xc0, 0x1f, 0x80, 0x7, 0xc0,
117 | 0x1f, 0x0, 0x7, 0xc0, 0x3e, 0x0, 0x7, 0xc0,
118 | 0x7c, 0x0, 0x7, 0xc0, 0x7c, 0x0, 0x7, 0xc0,
119 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
120 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
121 | 0xff, 0xff, 0xff, 0xff, 0x0, 0x0, 0x7, 0xc0,
122 | 0x0, 0x0, 0x7, 0xc0, 0x0, 0x0, 0x7, 0xc0,
123 | 0x0, 0x0, 0x7, 0xc0, 0x0, 0x0, 0x7, 0xc0,
124 | 0x0, 0x0, 0x7, 0xc0, 0x0, 0x0, 0x7, 0xc0,
125 | 0x0, 0x0, 0x7, 0xc0, 0x0, 0x0, 0x7, 0xc0,
126 | 0x0, 0x0, 0x7, 0xc0,
127 |
128 | /* U+35 "5" */
129 | 0x1f, 0xff, 0xff, 0x3, 0xff, 0xff, 0xe0, 0x7f,
130 | 0xff, 0xfc, 0xf, 0xff, 0xff, 0x81, 0xff, 0xff,
131 | 0xf0, 0x3e, 0x0, 0x0, 0x7, 0x80, 0x0, 0x0,
132 | 0xf0, 0x0, 0x0, 0x3e, 0x0, 0x0, 0x7, 0xc0,
133 | 0x0, 0x0, 0xf8, 0x0, 0x0, 0x1f, 0x0, 0x0,
134 | 0x3, 0xe0, 0x0, 0x0, 0x7c, 0x0, 0x0, 0xf,
135 | 0x80, 0x0, 0x1, 0xf0, 0x0, 0x0, 0x3e, 0x0,
136 | 0x0, 0x7, 0xff, 0xf8, 0x0, 0xff, 0xff, 0xc0,
137 | 0x1f, 0xff, 0xfe, 0x3, 0xff, 0xff, 0xe0, 0x38,
138 | 0x1, 0xfe, 0x0, 0x0, 0xf, 0xe0, 0x0, 0x0,
139 | 0x7e, 0x0, 0x0, 0xf, 0xc0, 0x0, 0x0, 0xf8,
140 | 0x0, 0x0, 0x1f, 0x80, 0x0, 0x1, 0xf0, 0x0,
141 | 0x0, 0x3e, 0x0, 0x0, 0x7, 0xc0, 0x0, 0x0,
142 | 0xf8, 0x0, 0x0, 0x1f, 0x0, 0x0, 0x3, 0xe0,
143 | 0x0, 0x0, 0x7c, 0x0, 0x0, 0x1f, 0x0, 0x0,
144 | 0x3, 0xe0, 0x0, 0x0, 0xf9, 0x80, 0x0, 0x3f,
145 | 0x3e, 0x0, 0x1f, 0xc7, 0xff, 0xff, 0xf0, 0xff,
146 | 0xff, 0xfc, 0xf, 0xff, 0xfe, 0x0, 0x7f, 0xff,
147 | 0x0, 0x0, 0x0, 0x0, 0x0,
148 |
149 | /* U+36 "6" */
150 | 0x0, 0x0, 0x0, 0x0, 0x0, 0xff, 0xf8, 0x0,
151 | 0x3f, 0xff, 0x80, 0xf, 0xff, 0xf8, 0x1, 0xff,
152 | 0xff, 0x80, 0x3f, 0x80, 0x0, 0x7, 0xe0, 0x0,
153 | 0x0, 0xfc, 0x0, 0x0, 0xf, 0x80, 0x0, 0x1,
154 | 0xf0, 0x0, 0x0, 0x1f, 0x0, 0x0, 0x3, 0xe0,
155 | 0x0, 0x0, 0x3e, 0x0, 0x0, 0x3, 0xc0, 0x0,
156 | 0x0, 0x7c, 0x0, 0x0, 0x7, 0xc0, 0x0, 0x0,
157 | 0x78, 0x0, 0x0, 0x7, 0x80, 0xff, 0x0, 0xf8,
158 | 0x7f, 0xfc, 0xf, 0x8f, 0xff, 0xf0, 0xf9, 0xff,
159 | 0xff, 0x8f, 0xbe, 0x3, 0xfc, 0xff, 0x80, 0xf,
160 | 0xcf, 0xf0, 0x0, 0x7e, 0xfe, 0x0, 0x3, 0xef,
161 | 0xc0, 0x0, 0x3e, 0xfc, 0x0, 0x3, 0xff, 0x80,
162 | 0x0, 0x1f, 0xf8, 0x0, 0x1, 0xff, 0x80, 0x0,
163 | 0x1f, 0xf8, 0x0, 0x1, 0xff, 0x80, 0x0, 0x1f,
164 | 0x78, 0x0, 0x1, 0xf7, 0xc0, 0x0, 0x1f, 0x7c,
165 | 0x0, 0x3, 0xf3, 0xe0, 0x0, 0x3e, 0x3e, 0x0,
166 | 0x3, 0xe1, 0xf0, 0x0, 0x7c, 0x1f, 0x80, 0xf,
167 | 0xc0, 0xfc, 0x1, 0xf8, 0x7, 0xff, 0xff, 0x0,
168 | 0x3f, 0xff, 0xe0, 0x1, 0xff, 0xfc, 0x0, 0x7,
169 | 0xff, 0x0, 0x0, 0x0, 0x0, 0x0,
170 |
171 | /* U+37 "7" */
172 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
173 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
174 | 0xff, 0xff, 0x80, 0x0, 0x0, 0xf8, 0x0, 0x0,
175 | 0x7, 0xc0, 0x0, 0x0, 0x7e, 0x0, 0x0, 0x3,
176 | 0xe0, 0x0, 0x0, 0x3f, 0x0, 0x0, 0x1, 0xf0,
177 | 0x0, 0x0, 0x1f, 0x80, 0x0, 0x0, 0xf8, 0x0,
178 | 0x0, 0xf, 0xc0, 0x0, 0x0, 0x7c, 0x0, 0x0,
179 | 0x7, 0xe0, 0x0, 0x0, 0x3e, 0x0, 0x0, 0x3,
180 | 0xf0, 0x0, 0x0, 0x1f, 0x80, 0x0, 0x0, 0xf8,
181 | 0x0, 0x0, 0xf, 0xc0, 0x0, 0x0, 0x7c, 0x0,
182 | 0x0, 0x7, 0xe0, 0x0, 0x0, 0x3e, 0x0, 0x0,
183 | 0x3, 0xf0, 0x0, 0x0, 0x1f, 0x0, 0x0, 0x1,
184 | 0xf8, 0x0, 0x0, 0xf, 0x80, 0x0, 0x0, 0xfc,
185 | 0x0, 0x0, 0x7, 0xe0, 0x0, 0x0, 0x7e, 0x0,
186 | 0x0, 0x3, 0xf0, 0x0, 0x0, 0x3f, 0x0, 0x0,
187 | 0x1, 0xf8, 0x0, 0x0, 0xf, 0x80, 0x0, 0x0,
188 | 0xfc, 0x0, 0x0, 0x7, 0xc0, 0x0, 0x0, 0x7e,
189 | 0x0, 0x0, 0x3, 0xe0, 0x0, 0x0, 0x3f, 0x0,
190 | 0x0, 0x1, 0xf8, 0x0, 0x0, 0x1f, 0x80, 0x0,
191 | 0x0, 0xfc, 0x0, 0x0,
192 |
193 | /* U+38 "8" */
194 | 0x0, 0x0, 0x0, 0x0, 0xf, 0xff, 0x0, 0x3,
195 | 0xff, 0xfc, 0x0, 0xff, 0xff, 0xf0, 0x1f, 0xff,
196 | 0xff, 0x83, 0xf8, 0x1, 0xfc, 0x3f, 0x0, 0xf,
197 | 0xc7, 0xe0, 0x0, 0x7e, 0x7c, 0x0, 0x3, 0xe7,
198 | 0xc0, 0x0, 0x3e, 0x7c, 0x0, 0x3, 0xe7, 0xc0,
199 | 0x0, 0x3e, 0x7c, 0x0, 0x3, 0xe7, 0xe0, 0x0,
200 | 0x7e, 0x3e, 0x0, 0x7, 0xc3, 0xf0, 0x0, 0xfc,
201 | 0x1f, 0x80, 0x1f, 0x81, 0xfe, 0x3, 0xf0, 0xf,
202 | 0xf8, 0xfe, 0x0, 0x3f, 0xff, 0xc0, 0x1, 0xff,
203 | 0xf0, 0x0, 0xf, 0xff, 0x0, 0x1, 0xff, 0xf8,
204 | 0x0, 0x7f, 0xff, 0xe0, 0xf, 0xe1, 0xff, 0x1,
205 | 0xfc, 0x7, 0xf8, 0x3f, 0x0, 0x1f, 0xc7, 0xe0,
206 | 0x0, 0xfe, 0x7c, 0x0, 0x7, 0xef, 0xc0, 0x0,
207 | 0x3f, 0xf8, 0x0, 0x1, 0xff, 0x80, 0x0, 0x1f,
208 | 0xf8, 0x0, 0x1, 0xff, 0x80, 0x0, 0x1f, 0xf8,
209 | 0x0, 0x1, 0xff, 0x80, 0x0, 0x1f, 0xfc, 0x0,
210 | 0x3, 0xe7, 0xc0, 0x0, 0x3e, 0x7e, 0x0, 0x7,
211 | 0xe3, 0xf8, 0x1, 0xfc, 0x1f, 0xff, 0xff, 0x80,
212 | 0xff, 0xff, 0xf0, 0x7, 0xff, 0xfe, 0x0, 0x1f,
213 | 0xff, 0x0, 0x0, 0x0, 0x0, 0x0,
214 |
215 | /* U+39 "9" */
216 | 0x0, 0x0, 0x0, 0x0, 0xf, 0xfe, 0x0, 0x3,
217 | 0xff, 0xf8, 0x0, 0x7f, 0xff, 0xc0, 0xf, 0xff,
218 | 0xfe, 0x1, 0xf8, 0x3, 0xf0, 0x3f, 0x0, 0x1f,
219 | 0x83, 0xe0, 0x0, 0xf8, 0x7c, 0x0, 0x7, 0xc7,
220 | 0xc0, 0x0, 0x7c, 0xfc, 0x0, 0x3, 0xef, 0x80,
221 | 0x0, 0x3e, 0xf8, 0x0, 0x1, 0xef, 0x80, 0x0,
222 | 0x1f, 0xf8, 0x0, 0x1, 0xff, 0x80, 0x0, 0x1f,
223 | 0xf8, 0x0, 0x1, 0xff, 0x80, 0x0, 0x1f, 0xf8,
224 | 0x0, 0x3, 0xf7, 0xc0, 0x0, 0x3f, 0x7c, 0x0,
225 | 0x7, 0xf7, 0xe0, 0x0, 0xff, 0x3f, 0x0, 0x1f,
226 | 0xf3, 0xfc, 0x7, 0xdf, 0x1f, 0xff, 0xfd, 0xf0,
227 | 0xff, 0xff, 0x1f, 0x3, 0xff, 0xe1, 0xe0, 0xf,
228 | 0xf0, 0x1e, 0x0, 0x0, 0x1, 0xe0, 0x0, 0x0,
229 | 0x3e, 0x0, 0x0, 0x3, 0xe0, 0x0, 0x0, 0x3c,
230 | 0x0, 0x0, 0x7, 0xc0, 0x0, 0x0, 0x7c, 0x0,
231 | 0x0, 0xf, 0x80, 0x0, 0x0, 0xf8, 0x0, 0x0,
232 | 0x1f, 0x0, 0x0, 0x3, 0xf0, 0x0, 0x0, 0x7e,
233 | 0x0, 0x0, 0x1f, 0xc0, 0x1f, 0xff, 0xf8, 0x1,
234 | 0xff, 0xff, 0x0, 0x1f, 0xff, 0xc0, 0x1, 0xff,
235 | 0xf0, 0x0, 0x0, 0x0, 0x0, 0x0,
236 |
237 | /* U+3A ":" */
238 | 0x0, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xbe, 0x0,
239 | 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
240 | 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0xf7,
241 | 0xff, 0xff, 0xff, 0xff, 0x7c, 0x0
242 | };
243 |
244 |
245 | /*---------------------
246 | * GLYPH DESCRIPTION
247 | *--------------------*/
248 |
249 | static const lv_font_fmt_txt_glyph_dsc_t glyph_dsc[] = {
250 | {.bitmap_index = 0, .adv_w = 0, .box_w = 0, .box_h = 0, .ofs_x = 0, .ofs_y = 0} /* id = 0 reserved */,
251 | {.bitmap_index = 0, .adv_w = 549, .box_w = 28, .box_h = 45, .ofs_x = 3, .ofs_y = -1},
252 | {.bitmap_index = 158, .adv_w = 549, .box_w = 16, .box_h = 43, .ofs_x = 5, .ofs_y = 0},
253 | {.bitmap_index = 244, .adv_w = 549, .box_w = 28, .box_h = 44, .ofs_x = 3, .ofs_y = 0},
254 | {.bitmap_index = 398, .adv_w = 549, .box_w = 28, .box_h = 45, .ofs_x = 2, .ofs_y = -1},
255 | {.bitmap_index = 556, .adv_w = 549, .box_w = 32, .box_h = 43, .ofs_x = 1, .ofs_y = 0},
256 | {.bitmap_index = 728, .adv_w = 549, .box_w = 27, .box_h = 44, .ofs_x = 3, .ofs_y = -1},
257 | {.bitmap_index = 877, .adv_w = 549, .box_w = 28, .box_h = 45, .ofs_x = 3, .ofs_y = -1},
258 | {.bitmap_index = 1035, .adv_w = 549, .box_w = 29, .box_h = 43, .ofs_x = 3, .ofs_y = 0},
259 | {.bitmap_index = 1191, .adv_w = 549, .box_w = 28, .box_h = 45, .ofs_x = 3, .ofs_y = -1},
260 | {.bitmap_index = 1349, .adv_w = 549, .box_w = 28, .box_h = 45, .ofs_x = 3, .ofs_y = -1},
261 | {.bitmap_index = 1507, .adv_w = 257, .box_w = 7, .box_h = 34, .ofs_x = 4, .ofs_y = -1}
262 | };
263 |
264 | /*---------------------
265 | * CHARACTER MAPPING
266 | *--------------------*/
267 |
268 |
269 |
270 | /*Collect the unicode lists and glyph_id offsets*/
271 | static const lv_font_fmt_txt_cmap_t cmaps[] =
272 | {
273 | {
274 | .range_start = 48, .range_length = 11, .glyph_id_start = 1,
275 | .unicode_list = NULL, .glyph_id_ofs_list = NULL, .list_length = 0, .type = LV_FONT_FMT_TXT_CMAP_FORMAT0_TINY
276 | }
277 | };
278 |
279 |
280 |
281 | /*--------------------
282 | * ALL CUSTOM DATA
283 | *--------------------*/
284 |
285 | /*Store all the custom data of the font*/
286 | static lv_font_fmt_txt_dsc_t font_dsc = {
287 | .glyph_bitmap = gylph_bitmap,
288 | .glyph_dsc = glyph_dsc,
289 | .cmaps = cmaps,
290 | .kern_dsc = NULL,
291 | .kern_scale = 0,
292 | .cmap_num = 1,
293 | .bpp = 1,
294 | .kern_classes = 0,
295 | .bitmap_format = 0
296 | };
297 |
298 |
299 | /*-----------------
300 | * PUBLIC FONT
301 | *----------------*/
302 |
303 | /*Initialize a public general font descriptor*/
304 | lv_font_t noto_sans_numeric_60 = {
305 | .get_glyph_dsc = lv_font_get_glyph_dsc_fmt_txt, /*Function pointer to get glyph's data*/
306 | .get_glyph_bitmap = lv_font_get_bitmap_fmt_txt, /*Function pointer to get glyph's bitmap*/
307 | .line_height = 45, /*The maximum line height required by the font*/
308 | .base_line = 1, /*Baseline measured from the bottom of the line*/
309 | #if !(LVGL_VERSION_MAJOR == 6 && LVGL_VERSION_MINOR == 0)
310 | .subpx = LV_FONT_SUBPX_NONE,
311 | #endif
312 | .dsc = &font_dsc /*The custom font data. Will be accessed by `get_glyph_bitmap/dsc` */
313 | };
314 |
315 | #endif /*#if NOTO_SANS_60*/
316 |
317 |
--------------------------------------------------------------------------------
/sascha/VulkanTools.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * Assorted commonly used Vulkan helper functions
3 | *
4 | * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de
5 | *
6 | * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
7 | */
8 |
9 | #include "VulkanTools.h"
10 |
11 | namespace vks
12 | {
13 | namespace tools
14 | {
15 | std::string errorString(VkResult errorCode)
16 | {
17 | switch (errorCode)
18 | {
19 | #define STR(r) case VK_ ##r: return #r
20 | STR(NOT_READY);
21 | STR(TIMEOUT);
22 | STR(EVENT_SET);
23 | STR(EVENT_RESET);
24 | STR(INCOMPLETE);
25 | STR(ERROR_OUT_OF_HOST_MEMORY);
26 | STR(ERROR_OUT_OF_DEVICE_MEMORY);
27 | STR(ERROR_INITIALIZATION_FAILED);
28 | STR(ERROR_DEVICE_LOST);
29 | STR(ERROR_MEMORY_MAP_FAILED);
30 | STR(ERROR_LAYER_NOT_PRESENT);
31 | STR(ERROR_EXTENSION_NOT_PRESENT);
32 | STR(ERROR_FEATURE_NOT_PRESENT);
33 | STR(ERROR_INCOMPATIBLE_DRIVER);
34 | STR(ERROR_TOO_MANY_OBJECTS);
35 | STR(ERROR_FORMAT_NOT_SUPPORTED);
36 | STR(ERROR_SURFACE_LOST_KHR);
37 | STR(ERROR_NATIVE_WINDOW_IN_USE_KHR);
38 | STR(SUBOPTIMAL_KHR);
39 | STR(ERROR_OUT_OF_DATE_KHR);
40 | STR(ERROR_INCOMPATIBLE_DISPLAY_KHR);
41 | STR(ERROR_VALIDATION_FAILED_EXT);
42 | STR(ERROR_INVALID_SHADER_NV);
43 | #undef STR
44 | default:
45 | return "UNKNOWN_ERROR";
46 | }
47 | }
48 |
49 | std::string physicalDeviceTypeString(VkPhysicalDeviceType type)
50 | {
51 | switch (type)
52 | {
53 | #define STR(r) case VK_PHYSICAL_DEVICE_TYPE_ ##r: return #r
54 | STR(OTHER);
55 | STR(INTEGRATED_GPU);
56 | STR(DISCRETE_GPU);
57 | STR(VIRTUAL_GPU);
58 | #undef STR
59 | default: return "UNKNOWN_DEVICE_TYPE";
60 | }
61 | }
62 |
63 | VkBool32 getSupportedDepthFormat(VkPhysicalDevice physicalDevice, VkFormat *depthFormat)
64 | {
65 | // Since all depth formats may be optional, we need to find a suitable depth format to use
66 | // Start with the highest precision packed format
67 | std::vector depthFormats = {
68 | VK_FORMAT_D32_SFLOAT_S8_UINT,
69 | VK_FORMAT_D32_SFLOAT,
70 | VK_FORMAT_D24_UNORM_S8_UINT,
71 | VK_FORMAT_D16_UNORM_S8_UINT,
72 | VK_FORMAT_D16_UNORM
73 | };
74 |
75 | for (auto& format : depthFormats)
76 | {
77 | VkFormatProperties formatProps;
78 | vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &formatProps);
79 | // Format must support depth stencil attachment for optimal tiling
80 | if (formatProps.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)
81 | {
82 | *depthFormat = format;
83 | return true;
84 | }
85 | }
86 |
87 | return false;
88 | }
89 |
90 | // Create an image memory barrier for changing the layout of
91 | // an image and put it into an active command buffer
92 | // See chapter 11.4 "Image Layout" for details
93 |
94 | void setImageLayout(
95 | VkCommandBuffer cmdbuffer,
96 | VkImage image,
97 | VkImageLayout oldImageLayout,
98 | VkImageLayout newImageLayout,
99 | VkImageSubresourceRange subresourceRange,
100 | VkPipelineStageFlags srcStageMask,
101 | VkPipelineStageFlags dstStageMask)
102 | {
103 | // Create an image barrier object
104 | VkImageMemoryBarrier imageMemoryBarrier = vks::initializers::imageMemoryBarrier();
105 | imageMemoryBarrier.oldLayout = oldImageLayout;
106 | imageMemoryBarrier.newLayout = newImageLayout;
107 | imageMemoryBarrier.image = image;
108 | imageMemoryBarrier.subresourceRange = subresourceRange;
109 |
110 | // Source layouts (old)
111 | // Source access mask controls actions that have to be finished on the old layout
112 | // before it will be transitioned to the new layout
113 | switch (oldImageLayout)
114 | {
115 | case VK_IMAGE_LAYOUT_UNDEFINED:
116 | // Image layout is undefined (or does not matter)
117 | // Only valid as initial layout
118 | // No flags required, listed only for completeness
119 | imageMemoryBarrier.srcAccessMask = 0;
120 | break;
121 |
122 | case VK_IMAGE_LAYOUT_PREINITIALIZED:
123 | // Image is preinitialized
124 | // Only valid as initial layout for linear images, preserves memory contents
125 | // Make sure host writes have been finished
126 | imageMemoryBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
127 | break;
128 |
129 | case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
130 | // Image is a color attachment
131 | // Make sure any writes to the color buffer have been finished
132 | imageMemoryBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
133 | break;
134 |
135 | case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
136 | // Image is a depth/stencil attachment
137 | // Make sure any writes to the depth/stencil buffer have been finished
138 | imageMemoryBarrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
139 | break;
140 |
141 | case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
142 | // Image is a transfer source
143 | // Make sure any reads from the image have been finished
144 | imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
145 | break;
146 |
147 | case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
148 | // Image is a transfer destination
149 | // Make sure any writes to the image have been finished
150 | imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
151 | break;
152 |
153 | case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
154 | // Image is read by a shader
155 | // Make sure any shader reads from the image have been finished
156 | imageMemoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
157 | break;
158 | default:
159 | // Other source layouts aren't handled (yet)
160 | break;
161 | }
162 |
163 | // Target layouts (new)
164 | // Destination access mask controls the dependency for the new image layout
165 | switch (newImageLayout)
166 | {
167 | case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
168 | // Image will be used as a transfer destination
169 | // Make sure any writes to the image have been finished
170 | imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
171 | break;
172 |
173 | case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
174 | // Image will be used as a transfer source
175 | // Make sure any reads from the image have been finished
176 | imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
177 | break;
178 |
179 | case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
180 | // Image will be used as a color attachment
181 | // Make sure any writes to the color buffer have been finished
182 | imageMemoryBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
183 | break;
184 |
185 | case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
186 | // Image layout will be used as a depth/stencil attachment
187 | // Make sure any writes to depth/stencil buffer have been finished
188 | imageMemoryBarrier.dstAccessMask = imageMemoryBarrier.dstAccessMask | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
189 | break;
190 |
191 | case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
192 | // Image will be read in a shader (sampler, input attachment)
193 | // Make sure any writes to the image have been finished
194 | if (imageMemoryBarrier.srcAccessMask == 0)
195 | {
196 | imageMemoryBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
197 | }
198 | imageMemoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
199 | break;
200 | default:
201 | // Other source layouts aren't handled (yet)
202 | break;
203 | }
204 |
205 | // Put barrier inside setup command buffer
206 | vkCmdPipelineBarrier(
207 | cmdbuffer,
208 | srcStageMask,
209 | dstStageMask,
210 | 0,
211 | 0, nullptr,
212 | 0, nullptr,
213 | 1, &imageMemoryBarrier);
214 | }
215 |
216 | // Fixed sub resource on first mip level and layer
217 | void setImageLayout(
218 | VkCommandBuffer cmdbuffer,
219 | VkImage image,
220 | VkImageAspectFlags aspectMask,
221 | VkImageLayout oldImageLayout,
222 | VkImageLayout newImageLayout,
223 | VkPipelineStageFlags srcStageMask,
224 | VkPipelineStageFlags dstStageMask)
225 | {
226 | VkImageSubresourceRange subresourceRange = {};
227 | subresourceRange.aspectMask = aspectMask;
228 | subresourceRange.baseMipLevel = 0;
229 | subresourceRange.levelCount = 1;
230 | subresourceRange.layerCount = 1;
231 | setImageLayout(cmdbuffer, image, oldImageLayout, newImageLayout, subresourceRange, srcStageMask, dstStageMask);
232 | }
233 |
234 | void insertImageMemoryBarrier(
235 | VkCommandBuffer cmdbuffer,
236 | VkImage image,
237 | VkAccessFlags srcAccessMask,
238 | VkAccessFlags dstAccessMask,
239 | VkImageLayout oldImageLayout,
240 | VkImageLayout newImageLayout,
241 | VkPipelineStageFlags srcStageMask,
242 | VkPipelineStageFlags dstStageMask,
243 | VkImageSubresourceRange subresourceRange)
244 | {
245 | VkImageMemoryBarrier imageMemoryBarrier = vks::initializers::imageMemoryBarrier();
246 | imageMemoryBarrier.srcAccessMask = srcAccessMask;
247 | imageMemoryBarrier.dstAccessMask = dstAccessMask;
248 | imageMemoryBarrier.oldLayout = oldImageLayout;
249 | imageMemoryBarrier.newLayout = newImageLayout;
250 | imageMemoryBarrier.image = image;
251 | imageMemoryBarrier.subresourceRange = subresourceRange;
252 |
253 | vkCmdPipelineBarrier(
254 | cmdbuffer,
255 | srcStageMask,
256 | dstStageMask,
257 | 0,
258 | 0, nullptr,
259 | 0, nullptr,
260 | 1, &imageMemoryBarrier);
261 | }
262 |
263 | void exitFatal(std::string message, std::string caption, bool silent)
264 | {
265 | #if defined(_WIN32)
266 | if (!silent) {
267 | MessageBox(NULL, message.c_str(), caption.c_str(), MB_OK | MB_ICONERROR);
268 | }
269 | #elif defined(__ANDROID__)
270 | LOGE("Fatal error: %s", message.c_str());
271 | #endif
272 | std::cerr << message << "\n";
273 | exit(1);
274 | }
275 |
276 | std::string readTextFile(const char *fileName)
277 | {
278 | std::string fileContent;
279 | std::ifstream fileStream(fileName, std::ios::in);
280 | if (!fileStream.is_open()) {
281 | printf("File %s not found\n", fileName);
282 | return "";
283 | }
284 | std::string line = "";
285 | while (!fileStream.eof()) {
286 | getline(fileStream, line);
287 | fileContent.append(line + "\n");
288 | }
289 | fileStream.close();
290 | return fileContent;
291 | }
292 |
293 | #if defined(__ANDROID__)
294 | // Android shaders are stored as assets in the apk
295 | // So they need to be loaded via the asset manager
296 | VkShaderModule loadShader(AAssetManager* assetManager, const char *fileName, VkDevice device)
297 | {
298 | // Load shader from compressed asset
299 | AAsset* asset = AAssetManager_open(assetManager, fileName, AASSET_MODE_STREAMING);
300 | assert(asset);
301 | size_t size = AAsset_getLength(asset);
302 | assert(size > 0);
303 |
304 | char *shaderCode = new char[size];
305 | AAsset_read(asset, shaderCode, size);
306 | AAsset_close(asset);
307 |
308 | VkShaderModule shaderModule;
309 | VkShaderModuleCreateInfo moduleCreateInfo;
310 | moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
311 | moduleCreateInfo.pNext = NULL;
312 | moduleCreateInfo.codeSize = size;
313 | moduleCreateInfo.pCode = (uint32_t*)shaderCode;
314 | moduleCreateInfo.flags = 0;
315 |
316 | VK_CHECK_RESULT(vkCreateShaderModule(device, &moduleCreateInfo, NULL, &shaderModule));
317 |
318 | delete[] shaderCode;
319 |
320 | return shaderModule;
321 | }
322 | #else
323 | VkShaderModule loadShader(const char *fileName, VkDevice device)
324 | {
325 | std::ifstream is(fileName, std::ios::binary | std::ios::in | std::ios::ate);
326 |
327 | if (is.is_open())
328 | {
329 | size_t size = is.tellg();
330 | is.seekg(0, std::ios::beg);
331 | char* shaderCode = new char[size];
332 | is.read(shaderCode, size);
333 | is.close();
334 |
335 | assert(size > 0);
336 |
337 | VkShaderModule shaderModule;
338 | VkShaderModuleCreateInfo moduleCreateInfo{};
339 | moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
340 | moduleCreateInfo.codeSize = size;
341 | moduleCreateInfo.pCode = (uint32_t*)shaderCode;
342 |
343 | VK_CHECK_RESULT(vkCreateShaderModule(device, &moduleCreateInfo, NULL, &shaderModule));
344 |
345 | delete[] shaderCode;
346 |
347 | return shaderModule;
348 | }
349 | else
350 | {
351 | std::cerr << "Error: Could not open shader file \"" << fileName << "\"" << std::endl;
352 | return VK_NULL_HANDLE;
353 | }
354 | }
355 | #endif
356 |
357 | VkShaderModule loadShaderGLSL(const char *fileName, VkDevice device, VkShaderStageFlagBits stage)
358 | {
359 | std::string shaderSrc = readTextFile(fileName);
360 | const char *shaderCode = shaderSrc.c_str();
361 | size_t size = strlen(shaderCode);
362 | assert(size > 0);
363 |
364 | VkShaderModule shaderModule;
365 | VkShaderModuleCreateInfo moduleCreateInfo;
366 | moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
367 | moduleCreateInfo.pNext = NULL;
368 | moduleCreateInfo.codeSize = 3 * sizeof(uint32_t) + size + 1;
369 | moduleCreateInfo.pCode = (uint32_t*)malloc(moduleCreateInfo.codeSize);
370 | moduleCreateInfo.flags = 0;
371 |
372 | // Magic SPV number
373 | ((uint32_t *)moduleCreateInfo.pCode)[0] = 0x07230203;
374 | ((uint32_t *)moduleCreateInfo.pCode)[1] = 0;
375 | ((uint32_t *)moduleCreateInfo.pCode)[2] = stage;
376 | memcpy(((uint32_t *)moduleCreateInfo.pCode + 3), shaderCode, size + 1);
377 |
378 | VK_CHECK_RESULT(vkCreateShaderModule(device, &moduleCreateInfo, NULL, &shaderModule));
379 |
380 | return shaderModule;
381 | }
382 |
383 | bool fileExists(const std::string &filename)
384 | {
385 | std::ifstream f(filename.c_str());
386 | return !f.fail();
387 | }
388 | }
389 | }
390 |
--------------------------------------------------------------------------------
/android/onexapp/src/main/java/android/network/object/onexapp/OnexNativeActivity.java:
--------------------------------------------------------------------------------
1 |
2 | package network.object.onexapp;
3 |
4 | import java.util.List;
5 |
6 | import android.Manifest;
7 | import android.os.*;
8 | import android.net.Uri;
9 | import android.view.inputmethod.*;
10 | import android.view.ViewGroup.LayoutParams;
11 | import android.view.KeyEvent;
12 | import android.widget.*;
13 | import android.text.*;
14 | import android.content.*;
15 | import android.content.pm.*;
16 | import android.provider.Settings;
17 | import android.app.NativeActivity;
18 | import android.util.Log;
19 | import android.app.*;
20 |
21 | import androidx.core.content.ContextCompat;
22 | import androidx.core.app.ActivityCompat;
23 |
24 | import android.bluetooth.BluetoothAdapter;
25 | import android.bluetooth.BluetoothDevice;
26 |
27 | /** NativeActivity wrapper to offer Java API functions not available in JNI land.
28 | */
29 | public class OnexNativeActivity extends NativeActivity implements KeyEvent.Callback {
30 |
31 | static OnexNativeActivity self=null;
32 |
33 | public static final String LOGNAME = "Onex OnexNativeActivity";
34 |
35 | private static final int REQUEST_SELECT_DEVICE = 1;
36 | private static final int REQUEST_ENABLE_BT = 2;
37 |
38 | @Override
39 | public void onCreate(Bundle savedInstanceState){
40 | super.onCreate(savedInstanceState); Log.d(LOGNAME, "onCreate");
41 | self=this;
42 | setUpKeyboardView();
43 | }
44 |
45 | @Override
46 | public void onNewIntent(Intent intent){
47 | super.onNewIntent(intent);
48 | Log.d(LOGNAME, "onNewIntent("+intent.getAction()+")");
49 | if(!"android.hardware.usb.action.USB_DEVICE_ATTACHED".equalsIgnoreCase(intent.getAction())) return;
50 | EternalService.onUSBAttached(intent);
51 | }
52 |
53 | @Override
54 | public void onRestart(){
55 | super.onRestart(); Log.d(LOGNAME, "onRestart");
56 | }
57 |
58 | @Override
59 | public void onStart(){
60 | super.onStart(); Log.d(LOGNAME, "onStart");
61 | }
62 |
63 | static private int fileRWPerms = 0; // 0 waiting, 1 approved, -1 denied
64 |
65 | private void checkAndRequestFileRWPermission() {
66 |
67 | if(Build.VERSION.SDK_INT >= 30) {
68 |
69 | if(Environment.isExternalStorageManager()){
70 | Log.d(LOGNAME, "API 30+ has file RW permission");
71 | fileRWPerms=1;
72 | return;
73 | }
74 | try {
75 | Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
76 | intent.addCategory("android.intent.category.DEFAULT");
77 | intent.setData(Uri.parse(String.format("package:%s",getApplicationContext().getPackageName())));
78 | startActivityForResult(intent, 5544);
79 |
80 | } catch (Exception e) {
81 | Intent intent = new Intent();
82 | intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
83 | startActivityForResult(intent, 5544);
84 | }
85 |
86 | } else {
87 |
88 | int readext = ContextCompat.checkSelfPermission(OnexNativeActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE);
89 | int writext = ContextCompat.checkSelfPermission(OnexNativeActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
90 |
91 | if(readext==PackageManager.PERMISSION_GRANTED &&
92 | writext==PackageManager.PERMISSION_GRANTED ){
93 |
94 | Log.d(LOGNAME, "API 29 has file RW permission");
95 | fileRWPerms=1;
96 | return;
97 | }
98 | ActivityCompat.requestPermissions(OnexNativeActivity.this, new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 5544);
99 | }
100 | }
101 |
102 | @Override
103 | public void onResume(){
104 | super.onResume(); Log.d(LOGNAME, "onResume");
105 |
106 | // relies on an onResume from the finishing of the file RW permissions dialogues
107 |
108 | if(fileRWPerms==0) checkAndRequestFileRWPermission();
109 |
110 | restartEternal();
111 | }
112 |
113 | @Override
114 | public void onPause(){
115 | super.onPause(); Log.d(LOGNAME, "onPause");
116 | }
117 |
118 | @Override
119 | public void onStop(){
120 | super.onStop(); Log.d(LOGNAME, "onStop");
121 | }
122 |
123 | @Override
124 | public void onDestroy(){
125 | super.onDestroy(); Log.d(LOGNAME, "onDestroy");
126 | self=null;
127 | }
128 |
129 | static public void restartEternal(){
130 | if(self==null){
131 | Log.d(LOGNAME, "calling restartEternal without a running activity");
132 | return;
133 | }
134 | if(fileRWPerms!=1){
135 | Log.d(LOGNAME, "calling restartEternal without file RW permissions");
136 | return;
137 | }
138 | Intent intent = new Intent("network.object.onexapp.eternal.restart").setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
139 | PackageManager packageManager = self.getPackageManager();
140 | List broadcastReceivers = packageManager.queryBroadcastReceivers(intent, 0);
141 | for(ResolveInfo broadcastReceiver: broadcastReceivers) {
142 | ComponentName cn = new ComponentName(broadcastReceiver.activityInfo.packageName, broadcastReceiver.activityInfo.name);
143 | Log.d(LOGNAME, "restartEternal on "+cn);
144 | intent.setComponent(cn);
145 | self.sendBroadcast(intent);
146 | }
147 | }
148 |
149 | // -----------------------------------------------------------
150 |
151 | static private BluetoothAdapter bluetoothAdapter = null;
152 |
153 | static public void selectBLEMac(){
154 | Log.d(LOGNAME, "selectBLEMac()");
155 | if(self==null){
156 | Log.d(LOGNAME, "calling selectBLEMac without a running activity");
157 | return;
158 | }
159 | bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
160 | if (bluetoothAdapter == null) {
161 | Toast.makeText(self, "Bluetooth is not available", Toast.LENGTH_LONG).show();
162 | return;
163 | }
164 | if (!bluetoothAdapter.isEnabled()) {
165 | Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
166 | self.startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
167 | }
168 | else {
169 | Intent newIntent = new Intent(self, DeviceListActivity.class);
170 | self.startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
171 | }
172 | }
173 |
174 | @Override
175 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
176 | if(requestCode==5544){
177 | fileRWPerms= -1;
178 | if (grantResults.length >= 1) {
179 |
180 | int readext = grantResults[0];
181 | int writext = grantResults[1];
182 |
183 | if(readext==PackageManager.PERMISSION_GRANTED &&
184 | writext==PackageManager.PERMISSION_GRANTED ){
185 |
186 | Log.d(LOGNAME, "API 29 file RW permission granted");
187 | fileRWPerms=1;
188 | }
189 | }
190 | }
191 | }
192 |
193 | @Override
194 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
195 |
196 | super.onActivityResult(requestCode, resultCode, data);
197 |
198 | Log.d(LOGNAME, "onActivityResult()");
199 |
200 | if(requestCode==5544) {
201 | fileRWPerms= -1;
202 | if(Build.VERSION.SDK_INT >= 30) {
203 | if(Environment.isExternalStorageManager()) {
204 | Log.d(LOGNAME, "API 30+ file RW permission granted");
205 | fileRWPerms=1;
206 | }
207 | }
208 | return;
209 | }
210 |
211 | switch (requestCode) {
212 | case REQUEST_ENABLE_BT:
213 | if (resultCode == Activity.RESULT_OK) {
214 | Toast.makeText(this, "Bluetooth enabled", Toast.LENGTH_SHORT).show();
215 | Intent newIntent = new Intent(this, DeviceListActivity.class);
216 | startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
217 | } else {
218 | Log.d(LOGNAME, "Bluetooth not enabled");
219 | Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_SHORT).show();
220 | }
221 | break;
222 | case REQUEST_SELECT_DEVICE:
223 | if (resultCode == Activity.RESULT_OK && data != null) {
224 | String blemac = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
225 | Log.d(LOGNAME, "onActivityResult() select device OK: "+blemac);
226 | EternalService.onBLEMacSelected(blemac);
227 | }
228 | else {
229 | Log.d(LOGNAME, "onActivityResult() select device not OK");
230 | EternalService.onBLEMacSelected("00:00:00:00:00:00");
231 | }
232 | break;
233 | default:
234 | Log.e(LOGNAME, "wrong request code");
235 | break;
236 | }
237 | }
238 |
239 | // -----------------------------------------------------------
240 |
241 | public static final int KEY_BACKSPACE=0x0043;
242 | public static final int KEY_ENTER =0x0042;
243 | public static final int KEY_BACK =0x100a;
244 |
245 | private int keyboardType = InputType.TYPE_CLASS_TEXT;
246 | private boolean keyboardUp=false;
247 |
248 | public class KeyboardView extends EditText {
249 | public String prevText="";
250 | public KeyboardView(Context context) { super(context); }
251 | @Override
252 | public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
253 | if(!keyboardUp){
254 | InputMethodManager imm=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
255 | imm.hideSoftInputFromWindow(kbdView.getWindowToken(), 0);
256 | return null;
257 | }
258 | InputConnection inputConnection = super.onCreateInputConnection(outAttrs);
259 | outAttrs.inputType |= keyboardType; // | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
260 | return inputConnection;
261 | }
262 | @Override
263 | public boolean onKeyPreIme(int keyCode, KeyEvent event) {
264 | boolean r=super.onKeyPreIme(keyCode, event);
265 | if(keyboardUp && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
266 | if(event.getAction() == KeyEvent.ACTION_DOWN){ onKeyPress(KEY_BACK, 0); return true; }
267 | if(event.getAction() == KeyEvent.ACTION_UP) { onKeyRelease(KEY_BACK); keyboardUp=false; return true; }
268 | }
269 | return r;
270 | }
271 | }
272 |
273 | private KeyboardView kbdView;
274 |
275 | public void setUpKeyboardView(){
276 | kbdView = new KeyboardView(this);
277 | kbdView.setImeOptions(EditorInfo.IME_FLAG_NO_FULLSCREEN);
278 | kbdView.addTextChangedListener(new TextWatcher(){
279 | public void onTextChanged(CharSequence cs, int start, int before, int count) {
280 | String currText=cs.toString();
281 | String prevText=kbdView.prevText;
282 | int i; for(i=0; i