Merge branch 'master' into master

pull/373/head
Marc 2021-01-31 19:32:56 +00:00 committed by GitHub
commit 1aab5e3962
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 2118 additions and 471 deletions

6
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,6 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"

126
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,126 @@
name: Continuous integration
on: [push, pull_request]
jobs:
linux:
name: Build (Linux, GCC)
runs-on: ubuntu-16.04
steps:
- name: Checkout
uses: actions/checkout@v2.3.4
with:
submodules: recursive
- name: Set up Python (for SCons)
uses: actions/setup-python@v2
with:
python-version: '3.9.1'
- name: Install dependencies
run: |
sudo apt-get update -qq
sudo apt-get install -qqq build-essential pkg-config
python -m pip install scons
- name: Build godot-cpp
run: |
scons target=release generate_bindings=yes -j $(nproc)
- name: Upload artifact
uses: actions/upload-artifact@v2.2.1
with:
name: godot-cpp-linux-glibc2.23-x86_64-release
path: bin/libgodot-cpp.linux.release.64.a
if-no-files-found: error
windows-msvc:
name: Build (Windows, MSVC)
runs-on: windows-2019
steps:
- name: Checkout
uses: actions/checkout@v2.3.4
with:
submodules: recursive
- name: Set up Python (for SCons)
uses: actions/setup-python@v2
with:
python-version: '3.9.1'
- name: Install dependencies
run: |
python -m pip install scons
- name: Build godot-cpp
run: |
scons target=release generate_bindings=yes -j $env:NUMBER_OF_PROCESSORS
- name: Upload artifact
uses: actions/upload-artifact@v2.2.1
with:
name: godot-cpp-windows-msvc2019-x86_64-release
path: bin/libgodot-cpp.windows.release.64.lib
if-no-files-found: error
windows-mingw:
name: Build (Windows, MinGW)
runs-on: windows-2019
steps:
- name: Checkout
uses: actions/checkout@v2.3.4
with:
submodules: recursive
- name: Set up Python (for SCons)
uses: actions/setup-python@v2
with:
python-version: '3.9.1'
- name: Install dependencies
run: |
python -m pip install scons
- name: Build godot-cpp
# Install GCC from Scoop as the default supplied GCC doesn't work ("Error 1").
run: |
Invoke-Expression (New-Object System.Net.WebClient).DownloadString('https://get.scoop.sh')
scoop install gcc
g++ --version
gcc --version
scons target=release generate_bindings=yes use_mingw=yes -j $env:NUMBER_OF_PROCESSORS
- name: Upload artifact
uses: actions/upload-artifact@v2.2.1
with:
name: godot-cpp-linux-mingw-x86_64-release
path: bin/libgodot-cpp.windows.release.64.a
if-no-files-found: error
macos:
name: Build (macOS, Clang)
runs-on: macos-11.0
steps:
- name: Checkout
uses: actions/checkout@v2.3.4
with:
submodules: recursive
- name: Set up Python (for SCons)
uses: actions/setup-python@v2
with:
python-version: '3.9.1'
- name: Install dependencies
run: |
python -m pip install scons
- name: Build godot-cpp
run: |
scons target=release generate_bindings=yes -j $(sysctl -n hw.logicalcpu)
- name: Upload artifact
uses: actions/upload-artifact@v2.2.1
with:
name: godot-cpp-macos-x86_64-release
path: bin/libgodot-cpp.osx.release.64.a
if-no-files-found: error

156
.gitignore vendored
View File

@ -16,3 +16,159 @@ bin
*.creator.user
*.files
*.includes
# Gprof output
gmon.out
# Vim temp files
*.swo
*.swp
# Qt project files
*.config
*.creator
*.creator.*
*.files
*.includes
*.cflags
*.cxxflags
# Eclipse CDT files
.cproject
.settings/
# Geany/geany-plugins files
*.geany
.geanyprj
# Misc
.DS_Store
logs/
# for projects that use SCons for building: http://http://www.scons.org/
.sconf_temp
.sconsign.dblite
*.pyc
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.opendb
*.VC.VC.opendb
enc_temp_folder/
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# CodeLite project files
*.project
*.workspace
.codelite/
# Windows Azure Build Output
csx/
*.build.csdef
# Windows Store app package directory
AppPackages/
# Others
sql/
*.Cache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
__pycache__/
# KDE
.directory
#Kdevelop project files
*.kdev4
# xCode
xcuserdata
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
App_Data/*.mdf
App_Data/*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# =========================
# Windows detritus
# =========================
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
logo.h
*.autosave
# https://github.com/github/gitignore/blob/master/Global/Tags.gitignore
# Ignore tags created by etags, ctags, gtags (GNU global) and cscope
TAGS
!TAGS/
tags
*.tags
!tags/
gtags.files
GTAGS
GRTAGS
GPATH
cscope.files
cscope.out
cscope.in.out
cscope.po.out
godot.creator.*
# Visual Studio 2017 and Visual Studio Code workspace folder
/.vs
/.vscode
# Visual Studio Code workspace file
*.code-workspace
# Scons progress indicator
.scons_node_count
# ccls cache (https://github.com/MaskRay/ccls)
.ccls-cache/
# compile commands (https://clang.llvm.org/docs/JSONCompilationDatabase.html)
compile_commands.json

View File

@ -1,76 +0,0 @@
language: cpp
dist: xenial
osx_image: xcode10.1
env:
global:
- SCONS_CACHE="$HOME/.scons_cache"
- SCONS_CACHE_LIMIT=1024
cache:
directories:
- $SCONS_CACHE
matrix:
include:
- name: Linux Debug + Static Checks
os: linux
compiler: gcc
env: TARGET=debug STATIC_CHECKS=yes
addons:
apt:
sources:
- llvm-toolchain-xenial-6.0
packages:
[scons, pkg-config, build-essential, p7zip-full, clang-format-6.0]
- name: Linux Release
os: linux
compiler: gcc
addons:
apt:
packages:
[scons, pkg-config, build-essential, p7zip-full]
env: TARGET=release
- name: macOS Debug
os: osx
compiler: clang
env: TARGET=debug
- name: macOS Release
os: osx
compiler: clang
env: TARGET=release
- name: Windows MSVC Debug
os: windows
env: TARGET=debug
- name: Windows MSVC Release
os: windows
env: TARGET=release
install:
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then
brew update;
brew install scons p7zip;
fi
- if [[ "$TRAVIS_OS_NAME" == "windows" ]]; then
curl -LO https://downloads.sourceforge.net/project/scons/scons-local/3.0.5/scons-local-3.0.5.zip;
unzip scons-local-3.0.5.zip;
fi
script:
- if [[ "$TRAVIS_OS_NAME" == "windows" ]]; then
export SCONS="./scons.bat";
else
export SCONS="scons";
fi
- $SCONS target="$TARGET" bits=64 generate_bindings=yes $SCONS_FLAGS;
- if [[ "$STATIC_CHECKS" == "yes" ]]; then
sh ./misc/travis/clang-format.sh;
fi

302
README.md
View File

@ -1,5 +1,6 @@
# godot-cpp
C++ bindings for the Godot script API
**C++ bindings for the Godot script API.**
The instructions below feature the new NativeScript 1.1 class structure and will only work for modules created for Godot 3.1 and later. Use the following branches for older implementations:
@ -8,18 +9,22 @@ Version | Branch
**Godot 3.0 Nativescript 1.0** | [3.0](https://github.com/GodotNativeTools/godot-cpp/tree/3.0)
**Godot 3.1 Nativescript 1.0** | [nativescript-1.0](https://github.com/GodotNativeTools/godot-cpp/tree/nativescript-1.0)
Index:
- [**Contributing**](#contributing)
- [**Getting Started**](#getting-started)
- [**Creating a simple class**](#creating-a-simple-class)
## Table of contents
- [**Contributing**](#contributing)
- [**Getting Started**](#getting-started)
- [**Creating a simple class**](#creating-a-simple-class)
## Contributing
We greatly appreciate help in maintaining and extending this project.
If you wish to help out ensure you have an account on Github and create a "fork" of the this repo.
Rémi "Akien" Verschelde wrote an excellent bit of documentation for the main Godot project on this:
https://docs.godotengine.org/en/3.0/community/contributing/pr_workflow.html
It is advisible to also install clang-format and copy the files in `misc/hooks` into `.git/hooks` so format checking is done before your changes are submitted.
We greatly appreciate help in maintaining and extending this project. If you
wish to help out, ensure you have an account on GitHub and create a "fork" of
this repository. Rémi "Akien" Verschelde wrote an excellent bit of documentation
for the main Godot project on this:
[Pull request workflow](https://docs.godotengine.org/en/3.0/community/contributing/pr_workflow.html)
Please install clang-format and copy the files in `misc/hooks` into `.git/hooks`
so formatting is done before your changes are submitted.
## Getting Started
@ -28,29 +33,36 @@ It is advisible to also install clang-format and copy the files in `misc/hooks`
### Setting up a new project
We recommend using git for managing your project and the instructions below assume so. Alternatively you can download the source code directly from GitHub in which case you need to download both [godot-cpp](https://github.com/GodotNativeTools/godot-cpp) and [godot_headers](https://github.com/GodotNativeTools/godot_headers).
We recommend using Git for managing your project. The instructions below assume
you're using Git. Alternatively, you can download the source code directly from
GitHub. In this case, you need to download both
[godot-cpp](https://github.com/GodotNativeTools/godot-cpp) and
[godot_headers](https://github.com/GodotNativeTools/godot_headers).
```
$ mkdir SimpleLibrary
$ cd SimpleLibrary
$ mkdir bin
$ mkdir src
$ git clone --recursive https://github.com/GodotNativeTools/godot-cpp
```bash
mkdir SimpleLibrary
cd SimpleLibrary
mkdir bin
mkdir src
git clone --recursive https://github.com/GodotNativeTools/godot-cpp
```
Note that if you wish to use a specific branch, add the -b option to the clone command:
```
$ git clone --recursive https://github.com/GodotNativeTools/godot-cpp -b 3.0
If you wish to use a specific branch, add the -b option to the clone command:
```bash
git clone --recursive https://github.com/GodotNativeTools/godot-cpp -b 3.0
```
If your project is an existing repository, use git submodule instead:
```
$ git submodule add https://github.com/GodotNativeTools/godot-cpp
$ git submodule update --init --recursive
If your project is an existing repository, use a Git submodule instead:
```bash
git submodule add https://github.com/GodotNativeTools/godot-cpp
git submodule update --init --recursive
```
Right now our directory structure should look like this:
```
Right now, our directory structure should look like this:
```text
SimpleLibrary/
├─godot-cpp/
| └─godot_headers/
@ -58,46 +70,77 @@ SimpleLibrary/
└─src/
```
### Updating the api.json
Our api.json file contains meta data of all the classes that are part of the Godot core and are needed to generate the C++ binding classes for use in GDNative modules.
### Updating the `api.json` file
This file is supplied with our godot_headers repository for your convinience but if you are running a custom build of Godot and need access to classes that have recent changes a new api.json file must be generated. You do this by starting your Godot executable with the following parameters:
Our `api.json` file contains metadata for all the classes that are part of the
Godot core. This metadata is required to generate the C++ binding classes for
use in GDNative modules.
```
$ godot --gdnative-generate-json-api api.json
This file is supplied with our
[godot_headers](https://github.com/GodotNativeTools/godot_headers) repository
for your convenience. However, if you're running a custom build of Godot and
need access to classes that have recent changes, you must generate a new
`api.json` file. You do this by starting your Godot executable with the
following parameters:
```bash
godot --gdnative-generate-json-api api.json
```
Now copy the api.json file into your folder structure so its easy to access. **Note** the remark below for the extra ```custom_api_file``` command line parameter needed to tell scons where to find your file.
Now copy the `api.json` file into your folder structure to make it easier to
access.
### Compiling the cpp bindings library
The final step is to compile our cpp bindings library:
See the remark below for the extra ```custom_api_file``` SCons argument, which
is required to tell SCons where to find your file.
### Compiling the C++ bindings library
The final step is to compile our C++ bindings library:
```bash
cd godot-cpp
scons platform=<your platform> generate_bindings=yes
cd ..
```
$ cd godot-cpp
$ scons platform=<your platform> generate_bindings=yes
$ cd ..
Replace `<your platform>` with either `windows`, `linux`, `osx` or `android`. If
you leave out `platform`, the target platform will automatically be detected
from the host platform.
The resulting library will be created in `godot-cpp/bin/`, take note of its name
as it'll differ depending on the target platform.
#### Compiling for Android
Download the latest [Android NDK](https://developer.android.com/ndk/downloads)
and set the NDK path.
```bash
scons platform=android generate_bindings=yes ANDROID_NDK_ROOT="/PATH-TO-ANDROID-NDK/" android_arch=<arch>
```
For android:
Download the latest [Android NDK](https://developer.android.com/ndk/downloads) from the official website and set NDK path.
```
$ scons platform=android generate_bindings=yes ANDROID_NDK_ROOT="/PATH-TO-ANDROID-NDK/" android_arch=< >
```
`android_arch` can be `armv7, arm64v8, x86, x86_64`.
`ANDROID_NDK_ROOT` can also be set in the environment variables of your computer if you do not want to include it in your Scons call.
The value of `android_arch` can be `armv7, arm64v8, x86, x86_64`. Most Android
devices in use nowadays use an ARM architecture, so compiling for `armv7` and
`arm64v8` is often enough when distributing an application.
> Replace `<your platform>` with either `windows`, `linux`, `osx` or `android`.
`ANDROID_NDK_ROOT` can also be set in the environment variables of your PC if
you don't want to include it in your SCons call.
> Include `use_llvm=yes` for using clang++
#### Compilation options
> Include `target=runtime` to build a runtime build (windows only at the moment)
You can optionally add the following options to the SCons command line:
> The resulting library will be created in `godot-cpp/bin/`, take note of its name as it will be different depending on platform.
> If you want to use an alternative api.json file add `use_custom_api_file=yes custom_api_file=../api.json`, be sure to specify the correct location of where you placed your file.
- When targeting Linux, add `use_llvm=yes` to use Clang instead of GCC.
- When targeting Windows, add `use_mingw=yes` to use MinGW instead of MSVC.
- When targeting Windows, include `target=runtime` to build a runtime build.
- To use an alternative `api.json` file, add `use_custom_api_file=yes
custom_api_file=../api.json`. Be sure to specify the correct location where
you placed your file (it can be a relative or absolute path).
## Creating a simple class
Create `init.cpp` under `SimpleLibrary/src/` and add the following code
Create `init.cpp` under `SimpleLibrary/src/` and add the following code:
```cpp
#include <Godot.hpp>
#include <Reference.hpp>
@ -109,7 +152,7 @@ class SimpleClass : public Reference {
public:
SimpleClass() { }
/* _init must exist as it is called by Godot */
/** `_init` must exist as it is called by Godot. */
void _init() { }
void test_void_method() {
@ -127,15 +170,15 @@ public:
register_method("method", &SimpleClass::method);
/**
* How to register exports like gdscript
* export var _name = "SimpleClass"
* The line below is equivalent to the following GDScript export:
* export var _name = "SimpleClass"
**/
register_property<SimpleClass, String>("base/name", &SimpleClass::_name, String("SimpleClass"));
/* or alternatively with getter and setter methods */
/** Alternatively, with getter and setter methods: */
register_property<SimpleClass, int>("base/value", &SimpleClass::set_value, &SimpleClass::get_value, 0);
/** For registering signal **/
/** Registering a signal: **/
// register_signal<SimpleClass>("signal_name");
// register_signal<SimpleClass>("signal_name", "string_argument", GODOT_VARIANT_TYPE_STRING)
}
@ -170,52 +213,137 @@ extern "C" void GDN_EXPORT godot_nativescript_init(void *handle) {
}
```
### Compiling
### Compiling the GDNative library
*Linux*
Once you've compiled the GDNative C++ bindings (see above), you can compile the GDNative library we've just created.
#### Linux
```bash
cd SimpleLibrary
clang++ -fPIC -o src/init.o -c src/init.cpp -g -O3 -std=c++14 -Igodot-cpp/include -Igodot-cpp/include/core -Igodot-cpp/include/gen -Igodot-cpp/godot_headers
clang++ -o bin/libtest.so -shared src/init.o -Lgodot-cpp/bin -l<name of the godot-cpp>
```
$ cd SimpleLibrary
$ clang -fPIC -o src/init.os -c src/init.cpp -g -O3 -std=c++14 -Igodot-cpp/include -Igodot-cpp/include/core -Igodot-cpp/include/gen -Igodot-cpp/godot_headers
$ clang -o bin/libtest.so -shared src/init.os -Lgodot-cpp/bin -l<name of the godot-cpp>
You'll need to replace `<name of the godot-cpp>` with the file that was created in [**Compiling the cpp bindings library**](#compiling-the-cpp-bindings-library).
This creates the file `libtest.so` in your `SimpleLibrary/bin` directory.
#### Windows
```bash
cd SimpleLibrary
cl /Fosrc/init.obj /c src/init.cpp /nologo -EHsc -DNDEBUG /MDd /Igodot-cpp\include /Igodot-cpp\include\core /Igodot-cpp\include\gen /Igodot-cpp\godot_headers
link /nologo /dll /out:bin\libtest.dll /implib:bin\libsimple.lib src\init.obj godot-cpp\bin\<name of the godot-cpp>
```
> This creates the file `libtest.so` in your `SimpleLibrary/bin` directory.
> You will need to replace `<name of the godot-cpp>` with the file that was created in [**Compiling the cpp bindings library**](#compiling-the-cpp-bindings-library)
You'll need to replace `<name of the godot-cpp>` with the file that was created
in [**Compiling the cpp bindingslibrary**](#compiling-the-cpp-bindings-library).
Replace `/MDd` with `/MD` to create a release build, which will run faster and
be smaller.
*Windows*
This creates the file `libtest.dll` in your `SimpleLibrary/bin` directory.
#### macOS
For macOS, you'll need to find out which compiler flags need to be used. These
are likely similar to Linux when using Clang, but may not be identical.
If you find suitable compiler flags for this example library, feel free to
submit a pull request :slightly_smiling_face:
#### Android
```bash
cd SimpleLibrary
aarch64-linux-android29-clang++ -fPIC -o src/init.o -c src/init.cpp -g -O3 -std=c++14 -Igodot-cpp/include -Igodot-cpp/include/core -Igodot-cpp/include/gen -Igodot-cpp/godot_headers
aarch64-linux-android29-clang++ -o bin/libtest.so -shared src/init.o -Lgodot-cpp/bin -l<name of the godot-cpp>
```
$ cd SimpleLibrary
$ cl /Fosrc/init.obj /c src/init.cpp /nologo -EHsc -DNDEBUG /MDd /Igodot-cpp\include /Igodot-cpp\include\core /Igodot-cpp\include\gen /Igodot-cpp\godot_headers
$ link /nologo /dll /out:bin\libtest.dll /implib:bin\libsimple.lib src\init.obj godot-cpp\bin\<name of the godot-cpp>
```
> This creates the file `libtest.dll` in your `SimpleLibrary/bin` directory.
> You will need to replace `<name of the godot-cpp>` with the file that was created in [**Compiling the cpp bindings library**](#compiling-the-cpp-bindings-library)
You'll need to replace `<name of the godot-cpp>` with the file that was created in [**Compiling the cpp bindings library**](#compiling-the-cpp-bindings-library). The command above targets `arm64v8`. To target `armv7`, use `armv7a-linux-androideabi29-clang++` instead of `aarch64-linux-android29-clang++`.
> Finally replace `/MDd` with `/MD` if you're generated a runtime build.
This creates the file `libtest.so` in your `SimpleLibrary/bin` directory.
*macOS*
For OSX you need to find out what compiler flags need to be used.
#### iOS
*Android*
```
$ cd SimpleLibrary
$ aarch64-linux-android29-clang -fPIC -o src/init.os -c src/init.cpp -g -O3 -std=c++14 -Igodot-cpp/include -Igodot-cpp/include/core -Igodot-cpp/include/gen -Igodot-cpp/godot_headers
$ aarch64-linux-android29-clang -o bin/libtest.so -shared src/init.os -Lgodot-cpp/bin -l<name of the godot-cpp>
```
> use `armv7a-linux-androideabi29-clang` for 32 bit armeabi-v7a library
GDNative isn't supported on iOS yet. This is because iOS only allows linking
static libraries, not dynamic libraries. In theory, it would be possible to link
a GDNative library statically, but some of GDNative's convenience would be lost
in the process as one would have to recompile the engine on every change. See
[issue #30](https://github.com/GodotNativeTools/godot_headers/issues/30) in the
Godot headers repository for more information.
> This creates the file `libtest.so` in your `SimpleLibrary/bin` directory.
> You will need to replace `<name of the godot-cpp>` with the file that was created in [**Compiling the cpp bindings library**](#compiling-the-cpp-bindings-library)
#### HTML5
GDNative isn't supported on the HTML5 platform yet. Support is being tracked on
[issue #12243](https://github.com/godotengine/godot/issues/12243) in the main
Godot repository.
### Creating `.gdnlib` and `.gdns` files
follow [godot_header/README.md](https://github.com/GodotNativeTools/godot_headers/blob/master/README.md#how-do-i-use-native-scripts-from-the-editor) to create the `.gdns`
### Implementing with gdscript
Follow the instructions in
[godot_header/README.md](https://github.com/GodotNativeTools/godot_headers/blob/master/README.md#how-do-i-use-native-scripts-from-the-editor)
to create the `.gdns` file. This file contains paths to GDNative libraries for
various platforms. This makes the library usable from Godot in a
platform-independent manner.
### Implementing with GDScript
Once your GDNative library is compiled and referenced in a `.gdns` file, you can use it in GDScript or C#. Here's an example with GDScript:
```gdscript
var simpleclass = load("res://simpleclass.gdns").new();
simpleclass.method("Test argument");
var simpleclass = load("res://simpleclass.gdns").new()
simpleclass.method("Test argument")
```
### Using Godot classes in C++
Godot expects you to manage its classes the same way the engine does. These rules apply to all Godot classes, including your NativeScripts, but not to any normal C++ classes used in your library.
- Instantiate Objects using `_new()`, not C++'s `new` operator.
```cpp
Sprite *sprite = Sprite::_new();
```
- Destroy Nodes using `queue_free()`, not C++'s `delete` operator.
```cpp
some_old_node->queue_free();
```
- Wrap References in `Ref` instead of passing around raw pointers. They are reference-counted and don't need to be freed manually.
```cpp
Ref<Texture> texture = resource_loader->load("res://icon.png");
```
- Pass core types that do *not* inherit Object by value. The containers (Array, Dictionary, PoolArray, String) manage their own memory and do not need to be explicitly initialized or freed.
```cpp
Array ints;
ints.append(123);
return ints;
```
- Initialize your NativeScript classes in their `_init()` method, not their constructor. The constructor can't access the base class's methods.
- Cast objects using `Object::cast_to`, not unsafe C-style casts or `static_cast`.
```cpp
MeshInstance *m = Object::cast_to<MeshInstance>(get_node("ChildNode"));
// `m` will be null if it's not a MeshInstance
if (m) { ... }
```
- **Never** use Godot types in static or global variables. The Godot API isn't loaded until after their constructors are called.
```cpp
String s; // crashes
class SomeClass {
static Dictionary d; // crashes
static Node *node_a = NULL; // fine, it's just a pointer
static Node *node_b = Node::_new(); // crashes
};
```

View File

@ -68,6 +68,17 @@ else:
'platform=<platform>'
)
env = Environment(ENV = os.environ)
is64 = sys.maxsize > 2**32
if (
env['TARGET_ARCH'] == 'amd64' or
env['TARGET_ARCH'] == 'emt64' or
env['TARGET_ARCH'] == 'x86_64' or
env['TARGET_ARCH'] == 'arm64-v8a'
):
is64 = True
opts = Variables([], ARGUMENTS)
opts.Add(EnumVariable(
'platform',
@ -79,8 +90,8 @@ opts.Add(EnumVariable(
opts.Add(EnumVariable(
'bits',
'Target platform bits',
'default',
('default', '32', '64')
'64' if is64 else '32',
('32', '64')
))
opts.Add(BoolVariable(
'use_llvm',
@ -144,23 +155,15 @@ opts.Add(
'Path to your Android NDK installation. By default, uses ANDROID_NDK_ROOT from your defined environment variables.',
os.environ.get("ANDROID_NDK_ROOT", None)
)
opts.Add(BoolVariable(
'generate_template_get_node',
"Generate a template version of the Node class's get_node.",
True
))
env = Environment(ENV = os.environ)
opts.Update(env)
Help(opts.GenerateHelpText(env))
is64 = sys.maxsize > 2**32
if (
env['TARGET_ARCH'] == 'amd64' or
env['TARGET_ARCH'] == 'emt64' or
env['TARGET_ARCH'] == 'x86_64' or
env['TARGET_ARCH'] == 'arm64-v8a'
):
is64 = True
if env['bits'] == 'default':
env['bits'] = '64' if is64 else '32'
# This makes sure to keep the session environment variables on Windows.
# This way, you can run SCons in a Visual Studio 2017 prompt and it will find
# all the required tools
@ -176,11 +179,11 @@ if env['platform'] == 'linux':
if env['use_llvm']:
env['CXX'] = 'clang++'
env.Append(CCFLAGS=['-fPIC', '-g', '-std=c++14', '-Wwrite-strings'])
env.Append(CCFLAGS=['-fPIC', '-std=c++14', '-Wwrite-strings'])
env.Append(LINKFLAGS=["-Wl,-R,'$$ORIGIN'"])
if env['target'] == 'debug':
env.Append(CCFLAGS=['-Og'])
env.Append(CCFLAGS=['-Og', '-g'])
elif env['target'] == 'release':
env.Append(CCFLAGS=['-O3'])
@ -200,7 +203,7 @@ elif env['platform'] == 'osx':
'Only 64-bit builds are supported for the macOS target.'
)
env.Append(CCFLAGS=['-g', '-std=c++14', '-arch', 'x86_64'])
env.Append(CCFLAGS=['-std=c++14', '-arch', 'x86_64'])
env.Append(LINKFLAGS=[
'-arch',
'x86_64',
@ -210,7 +213,7 @@ elif env['platform'] == 'osx':
])
if env['target'] == 'debug':
env.Append(CCFLAGS=['-Og'])
env.Append(CCFLAGS=['-Og', '-g'])
elif env['target'] == 'release':
env.Append(CCFLAGS=['-O3'])
@ -235,7 +238,7 @@ elif env['platform'] == 'ios':
env['AR'] = compiler_path + 'ar'
env['RANLIB'] = compiler_path + 'ranlib'
env.Append(CCFLAGS=['-g', '-std=c++14', '-arch', env['ios_arch'], '-isysroot', sdk_path])
env.Append(CCFLAGS=['-std=c++14', '-arch', env['ios_arch'], '-isysroot', sdk_path])
env.Append(LINKFLAGS=[
'-arch',
env['ios_arch'],
@ -247,7 +250,7 @@ elif env['platform'] == 'ios':
])
if env['target'] == 'debug':
env.Append(CCFLAGS=['-Og'])
env.Append(CCFLAGS=['-Og', '-g'])
elif env['target'] == 'release':
env.Append(CCFLAGS=['-O3'])
@ -278,13 +281,15 @@ elif env['platform'] == 'windows':
# Native or cross-compilation using MinGW
if host_platform == 'linux' or host_platform == 'osx' or env['use_mingw']:
env.Append(CCFLAGS=['-g', '-O3', '-std=c++14', '-Wwrite-strings'])
# These options are for a release build even using target=debug
env.Append(CCFLAGS=['-O3', '-std=c++14', '-Wwrite-strings'])
env.Append(LINKFLAGS=[
'--static',
'-Wl,--no-undefined',
'-static-libgcc',
'-static-libstdc++',
])
elif env['platform'] == 'android':
if host_platform == 'windows':
env = env.Clone(tools=['mingw'])
@ -356,13 +361,13 @@ json_api_file = ''
if 'custom_api_file' in env:
json_api_file = env['custom_api_file']
else:
json_api_file = os.path.join(os.getcwd(), 'godot_headers', 'api.json')
json_api_file = os.path.join(os.getcwd(), env['headers_dir'], 'api.json')
if env['generate_bindings']:
# Actually create the bindings here
import binding_generator
binding_generator.generate_bindings(json_api_file)
binding_generator.generate_bindings(json_api_file, env['generate_template_get_node'])
# Sources to compile
sources = []

View File

@ -4,9 +4,16 @@ import json
# comment.
# Convenience function for using template get_node
def correct_method_name(method_list):
for method in method_list:
if method["name"] == "get_node":
method["name"] = "get_node_internal"
classes = []
def generate_bindings(path):
def generate_bindings(path, use_template_get_node):
global classes
classes = json.load(open(path))
@ -16,10 +23,12 @@ def generate_bindings(path):
for c in classes:
# print c['name']
used_classes = get_used_classes(c)
if use_template_get_node and c["name"] == "Node":
correct_method_name(c["methods"])
header = generate_class_header(used_classes, c)
header = generate_class_header(used_classes, c, use_template_get_node)
impl = generate_class_implementation(icalls, used_classes, c)
impl = generate_class_implementation(icalls, used_classes, c, use_template_get_node)
header_file = open("include/gen/" + strip_name(c["name"]) + ".hpp", "w+")
header_file.write(header)
@ -46,11 +55,11 @@ def is_reference_type(t):
return True
return False
def make_gdnative_type(t):
def make_gdnative_type(t, ref_allowed):
if is_enum(t):
return remove_enum_prefix(t) + " "
elif is_class_type(t):
if is_reference_type(t):
if is_reference_type(t) and ref_allowed:
return "Ref<" + strip_name(t) + "> "
else:
return strip_name(t) + " *"
@ -62,7 +71,7 @@ def make_gdnative_type(t):
return strip_name(t) + " "
def generate_class_header(used_classes, c):
def generate_class_header(used_classes, c, use_template_get_node):
source = []
source.append("#ifndef GODOT_CPP_" + strip_name(c["name"]).upper() + "_HPP")
@ -83,8 +92,10 @@ def generate_class_header(used_classes, c):
# so don't include it here because it's not needed
if class_name != "Object" and class_name != "Reference":
source.append("#include <core/Ref.hpp>")
ref_allowed = True
else:
source.append("#include <core/TagDB.hpp>")
ref_allowed = False
included = []
@ -144,10 +155,14 @@ def generate_class_header(used_classes, c):
source.append("\t};")
source.append("\tstatic ___method_bindings ___mb;")
source.append("\tstatic void *_detail_class_tag;")
source.append("")
source.append("public:")
source.append("\tstatic void ___init_method_bindings();")
# class id from core engine for casting
source.append("\tinline static size_t ___get_id() { return (size_t)_detail_class_tag; }")
source.append("")
@ -163,8 +178,11 @@ def generate_class_header(used_classes, c):
# godot::api->godot_global_get_singleton((char *) \"" + strip_name(c["name"]) + "\");"
# ___get_class_name
# class name:
# Two versions needed needed because when the user implements a custom class,
# we want to override `___get_class_name` while `___get_godot_class_name` can keep returning the base name
source.append("\tstatic inline const char *___get_class_name() { return (const char *) \"" + strip_name(c["name"]) + "\"; }")
source.append("\tstatic inline const char *___get_godot_class_name() { return (const char *) \"" + strip_name(c["name"]) + "\"; }")
source.append("\tstatic inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; }")
@ -201,12 +219,11 @@ def generate_class_header(used_classes, c):
source.append("")
for method in c["methods"]:
method_signature = ""
# TODO decide what to do about virtual methods
# method_signature += "virtual " if method["is_virtual"] else ""
method_signature += make_gdnative_type(method["return_type"])
method_signature += make_gdnative_type(method["return_type"], ref_allowed)
method_name = escape_cpp(method["name"])
method_signature += method_name + "("
@ -215,7 +232,7 @@ def generate_class_header(used_classes, c):
method_arguments = ""
for i, argument in enumerate(method["arguments"]):
method_signature += "const " + make_gdnative_type(argument["type"])
method_signature += "const " + make_gdnative_type(argument["type"], ref_allowed)
argument_name = escape_cpp(argument["name"])
method_signature += argument_name
method_arguments += argument_name
@ -279,10 +296,26 @@ def generate_class_header(used_classes, c):
source.append("\t" + method_signature + ";")
source.append(vararg_templates)
source.append("};")
source.append("")
if use_template_get_node and class_name == "Node":
# Extra definition for template get_node that calls the renamed get_node_internal; has a default template parameter for backwards compatibility.
source.append("\ttemplate <class T = Node>")
source.append("\tT *get_node(const NodePath path) const {")
source.append("\t\treturn Object::cast_to<T>(get_node_internal(path));")
source.append("\t}")
source.append("};")
source.append("")
# ...And a specialized version so we don't unnecessarily cast when using the default.
source.append("template <>")
source.append("inline Node *Node::get_node<Node>(const NodePath path) const {")
source.append("\treturn get_node_internal(path);")
source.append("}")
source.append("")
else:
source.append("};")
source.append("")
source.append("}")
source.append("")
@ -296,8 +329,11 @@ def generate_class_header(used_classes, c):
def generate_class_implementation(icalls, used_classes, c):
def generate_class_implementation(icalls, used_classes, c, use_template_get_node):
class_name = strip_name(c["name"])
ref_allowed = class_name != "Object" and class_name != "Reference"
source = []
source.append("#include \"" + class_name + ".hpp\"")
source.append("")
@ -350,10 +386,18 @@ def generate_class_implementation(icalls, used_classes, c):
source.append(class_name + "::___method_bindings " + class_name + "::___mb = {};")
source.append("")
source.append("void *" + class_name + "::_detail_class_tag = nullptr;")
source.append("")
source.append("void " + class_name + "::___init_method_bindings() {")
for method in c["methods"]:
source.append("\t___mb.mb_" + method["name"] + " = godot::api->godot_method_bind_get_method(\"" + c["name"] + "\", \"" + method["name"] + "\");")
source.append("\t___mb.mb_" + method["name"] + " = godot::api->godot_method_bind_get_method(\"" + c["name"] + "\", \"" + ("get_node" if use_template_get_node and method["name"] == "get_node_internal" else method["name"]) + "\");")
source.append("\tgodot_string_name class_name;")
source.append("\tgodot::api->godot_string_name_new_data(&class_name, \"" + c["name"] + "\");")
source.append("\t_detail_class_tag = godot::core_1_2_api->godot_get_class_tag(&class_name);")
source.append("\tgodot::api->godot_string_name_destroy(&class_name);")
source.append("}")
source.append("")
@ -367,12 +411,11 @@ def generate_class_implementation(icalls, used_classes, c):
for method in c["methods"]:
method_signature = ""
method_signature += make_gdnative_type(method["return_type"])
method_signature += make_gdnative_type(method["return_type"], ref_allowed)
method_signature += strip_name(c["name"]) + "::" + escape_cpp(method["name"]) + "("
for i, argument in enumerate(method["arguments"]):
method_signature += "const " + make_gdnative_type(argument["type"])
method_signature += "const " + make_gdnative_type(argument["type"], ref_allowed)
method_signature += escape_cpp(argument["name"])
if i != len(method["arguments"]) - 1:
@ -396,13 +439,14 @@ def generate_class_implementation(icalls, used_classes, c):
continue
return_statement = ""
return_type_is_ref = is_reference_type(method["return_type"]) and ref_allowed
if method["return_type"] != "void":
if is_class_type(method["return_type"]):
if is_enum(method["return_type"]):
return_statement += "return (" + remove_enum_prefix(method["return_type"]) + ") "
elif is_reference_type(method["return_type"]):
return_statement += "return Ref<" + strip_name(method["return_type"]) + ">::__internal_constructor(";
elif return_type_is_ref:
return_statement += "return Ref<" + strip_name(method["return_type"]) + ">::__internal_constructor("
else:
return_statement += "return " + ("(" + strip_name(method["return_type"]) + " *) " if is_class_type(method["return_type"]) else "")
else:
@ -476,7 +520,7 @@ def generate_class_implementation(icalls, used_classes, c):
if method["return_type"] != "void":
cast = ""
if is_class_type(method["return_type"]):
if is_reference_type(method["return_type"]):
if return_type_is_ref:
cast += "Ref<" + strip_name(method["return_type"]) + ">::__internal_constructor(__result);"
else:
cast += "(" + strip_name(method["return_type"]) + " *) " + strip_name(method["return_type"] + "::___get_from_variant(") + "__result);"
@ -485,7 +529,6 @@ def generate_class_implementation(icalls, used_classes, c):
source.append("\treturn " + cast)
else:
args = []
@ -503,11 +546,15 @@ def generate_class_implementation(icalls, used_classes, c):
return_statement += icall_name + "(___mb.mb_" + method["name"] + ", (const Object *) " + core_object_name
for arg in method["arguments"]:
return_statement += ", " + escape_cpp(arg["name"]) + (".ptr()" if is_reference_type(arg["type"]) else "")
arg_is_ref = is_reference_type(arg["type"]) and ref_allowed
return_statement += ", " + escape_cpp(arg["name"]) + (".ptr()" if arg_is_ref else "")
return_statement += ")"
source.append("\t" + return_statement + (")" if is_reference_type(method["return_type"]) else "") + ";")
if return_type_is_ref:
return_statement += ")"
source.append("\t" + return_statement + ";")
source.append("}")
source.append("")
@ -672,8 +719,6 @@ def generate_init_method_bindings(classes):
source.append("{")
for c in classes:
class_name = strip_name(c["name"])
source.append("\t" + strip_name(c["name"]) + "::___init_method_bindings();")
source.append("}")
@ -709,7 +754,6 @@ def get_icall_name(sig):
def get_used_classes(c):
classes = []
for method in c["methods"]:
@ -725,9 +769,6 @@ def get_used_classes(c):
def strip_name(name):
if len(name) == 0:
return name

@ -1 +1 @@
Subproject commit ddf67cc7b8274c5fb77a71c828bab2991f1ee12a
Subproject commit f2122198d51f230d903f9585527248f6cf411494

View File

@ -57,6 +57,11 @@ class Object;
class Array {
godot_array _godot_array;
friend class Variant;
inline explicit Array(const godot_array &other) {
_godot_array = other;
}
public:
Array();
Array(const Array &other);

View File

@ -0,0 +1,103 @@
#ifndef CAMERA_MATRIX_H
#define CAMERA_MATRIX_H
#include "Defs.hpp"
#include "Plane.hpp"
#include "Rect2.hpp"
#include "Transform.hpp"
#include <vector>
namespace {
using namespace godot;
} // namespace
struct CameraMatrix {
enum Planes {
PLANE_NEAR,
PLANE_FAR,
PLANE_LEFT,
PLANE_TOP,
PLANE_RIGHT,
PLANE_BOTTOM
};
real_t matrix[4][4];
void set_identity();
void set_zero();
void set_light_bias();
void set_light_atlas_rect(const Rect2 &p_rect);
void set_perspective(real_t p_fovy_degrees, real_t p_aspect, real_t p_z_near, real_t p_z_far, bool p_flip_fov = false);
void set_perspective(real_t p_fovy_degrees, real_t p_aspect, real_t p_z_near, real_t p_z_far, bool p_flip_fov, int p_eye, real_t p_intraocular_dist, real_t p_convergence_dist);
void set_for_hmd(int p_eye, real_t p_aspect, real_t p_intraocular_dist, real_t p_display_width, real_t p_display_to_lens, real_t p_oversample, real_t p_z_near, real_t p_z_far);
void set_orthogonal(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_znear, real_t p_zfar);
void set_orthogonal(real_t p_size, real_t p_aspect, real_t p_znear, real_t p_zfar, bool p_flip_fov = false);
void set_frustum(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_near, real_t p_far);
void set_frustum(real_t p_size, real_t p_aspect, Vector2 p_offset, real_t p_near, real_t p_far, bool p_flip_fov = false);
static real_t get_fovy(real_t p_fovx, real_t p_aspect) {
return rad2deg(atan(p_aspect * tan(deg2rad(p_fovx) * 0.5)) * 2.0);
}
static inline double deg2rad(double p_y) { return p_y * Math_PI / 180.0; }
static inline float deg2rad(float p_y) { return p_y * Math_PI / 180.0; }
static inline double rad2deg(double p_y) { return p_y * 180.0 / Math_PI; }
static inline float rad2deg(float p_y) { return p_y * 180.0 / Math_PI; }
static inline double absd(double g) {
union {
double d;
uint64_t i;
} u;
u.d = g;
u.i &= (uint64_t)9223372036854775807ll;
return u.d;
}
real_t get_z_far() const;
real_t get_z_near() const;
real_t get_aspect() const;
real_t get_fov() const;
bool is_orthogonal() const;
std::vector<Plane> get_projection_planes(const Transform &p_transform) const;
bool get_endpoints(const Transform &p_transform, Vector3 *p_8points) const;
Vector2 get_viewport_half_extents() const;
void invert();
CameraMatrix inverse() const;
CameraMatrix operator*(const CameraMatrix &p_matrix) const;
Plane xform4(const Plane &p_vec4) const;
inline Vector3 xform(const Vector3 &p_vec3) const;
operator String() const;
void scale_translate_to_fit(const AABB &p_aabb);
void make_scale(const Vector3 &p_scale);
int get_pixels_per_meter(int p_for_pixel_width) const;
operator Transform() const;
CameraMatrix();
CameraMatrix(const Transform &p_transform);
~CameraMatrix();
};
Vector3 CameraMatrix::xform(const Vector3 &p_vec3) const {
Vector3 ret;
ret.x = matrix[0][0] * p_vec3.x + matrix[1][0] * p_vec3.y + matrix[2][0] * p_vec3.z + matrix[3][0];
ret.y = matrix[0][1] * p_vec3.x + matrix[1][1] * p_vec3.y + matrix[2][1] * p_vec3.z + matrix[3][1];
ret.z = matrix[0][2] * p_vec3.x + matrix[1][2] * p_vec3.y + matrix[2][2] * p_vec3.z + matrix[3][2];
real_t w = matrix[0][3] * p_vec3.x + matrix[1][3] * p_vec3.y + matrix[2][3] * p_vec3.z + matrix[3][3];
return ret / w;
}
#endif

View File

@ -5,6 +5,7 @@
#include <cmath>
#include "Defs.hpp"
#include "String.hpp"
namespace godot {
@ -73,6 +74,23 @@ public:
return components[idx];
}
Color operator+(const Color &p_color) const;
void operator+=(const Color &p_color);
Color operator-() const;
Color operator-(const Color &p_color) const;
void operator-=(const Color &p_color);
Color operator*(const Color &p_color) const;
Color operator*(const real_t &rvalue) const;
void operator*=(const Color &p_color);
void operator*=(const real_t &rvalue);
Color operator/(const Color &p_color) const;
Color operator/(const real_t &rvalue) const;
void operator/=(const Color &p_color);
void operator/=(const real_t &rvalue);
void invert();
void contrast();

View File

@ -61,11 +61,19 @@ enum class Error {
#include <GodotGlobal.hpp>
// alloca() is non-standard. When using MSVC, it's in malloc.h.
#if defined(__linux__) || defined(__APPLE__)
#include <alloca.h>
#else
#include <malloc.h>
#endif
typedef float real_t;
#define CMP_EPSILON 0.00001
#define CMP_EPSILON2 (CMP_EPSILON * CMP_EPSILON)
#define Math_PI 3.14159265358979323846
#define Math_TAU 6.2831853071795864769252867666
#define _PLANE_EQ_DOT_EPSILON 0.999
#define _PLANE_EQ_D_EPSILON 0.0001

View File

@ -12,6 +12,11 @@ namespace godot {
class Dictionary {
godot_dictionary _godot_dictionary;
friend Variant::operator Dictionary() const;
inline explicit Dictionary(const godot_dictionary &other) {
_godot_dictionary = other;
}
public:
Dictionary();
Dictionary(const Dictionary &other);

View File

@ -17,60 +17,113 @@
#include "GodotGlobal.hpp"
#include <GDNativeLibrary.hpp>
#include <NativeScript.hpp>
namespace godot {
namespace detail {
template <class T>
T *as(const Object *obj) {
return (obj) ? (T *)godot::nativescript_api->godot_nativescript_get_userdata(obj->_owner) : nullptr;
}
// Godot classes are wrapped by heap-allocated instances mimicking them through the C API.
// They all inherit `_Wrapped`.
template <class T>
T *get_wrapper(godot_object *obj) {
return (T *)godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, obj);
}
#define GODOT_CLASS(Name, Base) \
\
public: \
inline static const char *___get_type_name() { return static_cast<const char *>(#Name); } \
enum { ___CLASS_IS_SCRIPT = 1, \
}; \
inline static Name *_new() { \
godot::NativeScript *script = godot::NativeScript::_new(); \
script->set_library(godot::get_wrapper<godot::GDNativeLibrary>((godot_object *)godot::gdnlib)); \
script->set_class_name(#Name); \
Name *instance = godot::as<Name>(script->new_()); \
return instance; \
} \
inline static size_t ___get_id() { return typeid(Name).hash_code(); } \
inline static size_t ___get_base_id() { return typeid(Base).hash_code(); } \
inline static const char *___get_base_type_name() { return Base::___get_class_name(); } \
inline static Object *___get_from_variant(godot::Variant a) { return (godot::Object *)godot::as<Name>(godot::Object::___get_from_variant(a)); } \
\
// Custom class instances are not obtainable by just casting the pointer to the base class they inherit,
// partly because in Godot, scripts are not instances of the classes themselves, they are only attached to them.
// Yet we want to "fake" it as if they were the same entity.
template <class T>
T *get_custom_class_instance(const Object *obj) {
return (obj) ? (T *)godot::nativescript_api->godot_nativescript_get_userdata(obj->_owner) : nullptr;
}
template <class T>
inline T *create_custom_class_instance() {
// Usually, script instances hold a reference to their NativeScript resource.
// that resource is obtained from a `.gdns` file, which in turn exists because
// of the resource system of Godot. We can't cleanly hardcode that here,
// so the easiest for now (though not really clean) is to create new resource instances,
// individually attached to the script instances.
// We cannot use wrappers because of https://github.com/godotengine/godot/issues/39181
// godot::NativeScript *script = godot::NativeScript::_new();
// script->set_library(get_wrapper<godot::GDNativeLibrary>((godot_object *)godot::gdnlib));
// script->set_class_name(T::___get_class_name());
static_assert(T::___CLASS_IS_SCRIPT, "This function must only be used on custom classes");
// So we use the C API directly.
static godot_class_constructor script_constructor = godot::api->godot_get_class_constructor("NativeScript");
static godot_method_bind *mb_set_library = godot::api->godot_method_bind_get_method("NativeScript", "set_library");
static godot_method_bind *mb_set_class_name = godot::api->godot_method_bind_get_method("NativeScript", "set_class_name");
godot_object *script = script_constructor();
{
const void *args[] = { godot::gdnlib };
godot::api->godot_method_bind_ptrcall(mb_set_library, script, args, nullptr);
}
{
const String class_name = T::___get_class_name();
const void *args[] = { &class_name };
godot::api->godot_method_bind_ptrcall(mb_set_class_name, script, args, nullptr);
}
// Now to instanciate T, we initially did this, however in case of Reference it returns a variant with refcount
// already initialized, which woud cause inconsistent behavior compared to other classes (we still have to return a pointer).
//Variant instance_variant = script->new_();
//T *instance = godot::get_custom_class_instance<T>(instance_variant);
// So we should do this instead, however while convenient, it uses unnecessary wrapper objects.
// Object *base_obj = T::___new_godot_base();
// base_obj->set_script(script);
// return get_custom_class_instance<T>(base_obj);
// Again using the C API to do exactly what we have to do.
static godot_class_constructor base_constructor = godot::api->godot_get_class_constructor(T::___get_godot_class_name());
static godot_method_bind *mb_set_script = godot::api->godot_method_bind_get_method("Object", "set_script");
godot_object *base_obj = base_constructor();
{
const void *args[] = { script };
godot::api->godot_method_bind_ptrcall(mb_set_script, base_obj, args, nullptr);
}
return (T *)godot::nativescript_api->godot_nativescript_get_userdata(base_obj);
}
} // namespace detail
// Used in the definition of a custom class.
//
// Name: Name of your class, without namespace
// Base: Name of the direct base class, with namespace if necessary
//
// ___get_class_name: Name of the class
// ___get_godot_class_name: Name of the Godot base class this class inherits from (i.e not direct)
// _new: Creates a new instance of the class
// ___get_id: Gets the unique ID of the class. Godot and custom classes are both within that set.
// ___get_base_id: Gets the ID of the direct base class, as returned by ___get_id
// ___get_base_class_name: Name of the direct base class
// ___get_from_variant: Converts a Variant into an Object*. Will be non-null if the class matches.
#define GODOT_CLASS(Name, Base) \
\
public: \
inline static const char *___get_class_name() { return #Name; } \
enum { ___CLASS_IS_SCRIPT = 1 }; \
inline static const char *___get_godot_class_name() { \
return Base::___get_godot_class_name(); \
} \
inline static Name *_new() { \
return godot::detail::create_custom_class_instance<Name>(); \
} \
inline static size_t ___get_id() { return typeid(Name).hash_code(); } \
inline static size_t ___get_base_id() { return Base::___get_id(); } \
inline static const char *___get_base_class_name() { return Base::___get_class_name(); } \
inline static godot::Object *___get_from_variant(godot::Variant a) { \
return (godot::Object *)godot::detail::get_custom_class_instance<Name>( \
godot::Object::___get_from_variant(a)); \
} \
\
private:
#define GODOT_SUBCLASS(Name, Base) \
\
public: \
inline static const char *___get_type_name() { return static_cast<const char *>(#Name); } \
enum { ___CLASS_IS_SCRIPT = 1, \
}; \
inline static Name *_new() { \
godot::NativeScript *script = godot::NativeScript::_new(); \
script->set_library(godot::get_wrapper<godot::GDNativeLibrary>((godot_object *)godot::gdnlib)); \
script->set_class_name(#Name); \
Name *instance = godot::as<Name>(script->new_()); \
return instance; \
} \
inline static size_t ___get_id() { return typeid(Name).hash_code(); }; \
inline static size_t ___get_base_id() { return typeid(Base).hash_code(); }; \
inline static const char *___get_base_type_name() { return #Base; } \
inline static Object *___get_from_variant(godot::Variant a) { return (godot::Object *)godot::as<Name>(godot::Object::___get_from_variant(a)); } \
\
private:
// Legacy compatibility
#define GODOT_SUBCLASS(Name, Base) GODOT_CLASS(Name, Base)
template <class T>
struct _ArgCast {
@ -112,6 +165,8 @@ void _godot_class_destroy_func(godot_object * /*p*/, void * /*method_data*/, voi
template <class T>
void register_class() {
static_assert(T::___CLASS_IS_SCRIPT, "This function must only be used on custom classes");
godot_instance_create_func create = {};
create.create_func = _godot_class_instance_func<T>;
@ -120,13 +175,19 @@ void register_class() {
_TagDB::register_type(T::___get_id(), T::___get_base_id());
godot::nativescript_api->godot_nativescript_register_class(godot::_RegisterState::nativescript_handle, T::___get_type_name(), T::___get_base_type_name(), create, destroy);
godot::nativescript_1_1_api->godot_nativescript_set_type_tag(godot::_RegisterState::nativescript_handle, T::___get_type_name(), (const void *)typeid(T).hash_code());
godot::nativescript_api->godot_nativescript_register_class(godot::_RegisterState::nativescript_handle,
T::___get_class_name(), T::___get_base_class_name(), create, destroy);
godot::nativescript_1_1_api->godot_nativescript_set_type_tag(godot::_RegisterState::nativescript_handle,
T::___get_class_name(), (const void *)T::___get_id());
T::_register_methods();
}
template <class T>
void register_tool_class() {
static_assert(T::___CLASS_IS_SCRIPT, "This function must only be used on custom classes");
godot_instance_create_func create = {};
create.create_func = _godot_class_instance_func<T>;
@ -135,8 +196,12 @@ void register_tool_class() {
_TagDB::register_type(T::___get_id(), T::___get_base_id());
godot::nativescript_api->godot_nativescript_register_tool_class(godot::_RegisterState::nativescript_handle, T::___get_type_name(), T::___get_base_type_name(), create, destroy);
godot::nativescript_1_1_api->godot_nativescript_set_type_tag(godot::_RegisterState::nativescript_handle, T::___get_type_name(), (const void *)typeid(T).hash_code());
godot::nativescript_api->godot_nativescript_register_tool_class(godot::_RegisterState::nativescript_handle,
T::___get_class_name(), T::___get_base_class_name(), create, destroy);
godot::nativescript_1_1_api->godot_nativescript_set_type_tag(godot::_RegisterState::nativescript_handle,
T::___get_class_name(), (const void *)T::___get_id());
T::_register_methods();
}
@ -145,13 +210,15 @@ void register_tool_class() {
typedef godot_variant (*__godot_wrapper_method)(godot_object *, void *, void *, int, godot_variant **);
template <class T, class R, class... args>
const char *___get_method_class_name(R (T::* /*p*/)(args... a)) {
return T::___get_type_name();
const char *___get_method_class_name(R (T::*/*p*/)(args... a)) {
static_assert(T::___CLASS_IS_SCRIPT, "This function must only be used on custom classes");
return T::___get_class_name();
}
template <class T, class R, class... args>
const char *___get_method_class_name(R (T::* /*p*/)(args... a) const) {
return T::___get_type_name();
const char *___get_method_class_name(R (T::*/*p*/)(args... a) const) {
static_assert(T::___CLASS_IS_SCRIPT, "This function must only be used on custom classes");
return T::___get_class_name();
}
// Okay, time for some template magic.
@ -243,7 +310,17 @@ void register_method(const char *name, M method_ptr, godot_method_rpc_mode rpc_t
godot_method_attributes attr = {};
attr.rpc_type = rpc_type;
godot::nativescript_api->godot_nativescript_register_method(godot::_RegisterState::nativescript_handle, ___get_method_class_name(method_ptr), name, attr, method);
godot::nativescript_api->godot_nativescript_register_method(godot::_RegisterState::nativescript_handle,
___get_method_class_name(method_ptr), name, attr, method);
}
// User can specify a derived class D to register the method for, instead of it being inferred.
template <class D, class B, class R, class... As>
void register_method_explicit(const char *name, R (B::*method_ptr)(As...),
godot_method_rpc_mode rpc_type = GODOT_METHOD_RPC_MODE_DISABLED) {
static_assert(std::is_base_of<B, D>::value, "Explicit class must derive from method class");
register_method(name, static_cast<R (D::*)(As...)>(method_ptr), rpc_type);
}
template <class T, class P>
@ -310,13 +387,19 @@ struct _PropertyDefaultGetFunc {
};
template <class T, class P>
void register_property(const char *name, P(T::*var), P default_value, godot_method_rpc_mode rpc_mode = GODOT_METHOD_RPC_MODE_DISABLED, godot_property_usage_flags usage = GODOT_PROPERTY_USAGE_DEFAULT, godot_property_hint hint = GODOT_PROPERTY_HINT_NONE, String hint_string = "") {
void register_property(const char *name, P(T::*var), P default_value,
godot_method_rpc_mode rpc_mode = GODOT_METHOD_RPC_MODE_DISABLED,
godot_property_usage_flags usage = GODOT_PROPERTY_USAGE_DEFAULT,
godot_property_hint hint = GODOT_PROPERTY_HINT_NONE, String hint_string = "") {
static_assert(T::___CLASS_IS_SCRIPT, "This function must only be used on custom classes");
Variant def_val = default_value;
usage = (godot_property_usage_flags)((int)usage | GODOT_PROPERTY_USAGE_SCRIPT_VARIABLE);
if (def_val.get_type() == Variant::OBJECT) {
Object *o = get_wrapper<Object>(def_val.operator godot_object *());
Object *o = detail::get_wrapper<Object>(def_val.operator godot_object *());
if (o && o->is_class("Resource")) {
hint = (godot_property_hint)((int)hint | GODOT_PROPERTY_HINT_RESOURCE_TYPE);
hint_string = o->get_class();
@ -338,10 +421,12 @@ void register_property(const char *name, P(T::*var), P default_value, godot_meth
attr.usage = usage;
attr.hint_string = *_hint_string;
_PropertyDefaultSetFunc<T, P> *wrapped_set = (_PropertyDefaultSetFunc<T, P> *)godot::api->godot_alloc(sizeof(_PropertyDefaultSetFunc<T, P>));
_PropertyDefaultSetFunc<T, P> *wrapped_set =
(_PropertyDefaultSetFunc<T, P> *)godot::api->godot_alloc(sizeof(_PropertyDefaultSetFunc<T, P>));
wrapped_set->f = var;
_PropertyDefaultGetFunc<T, P> *wrapped_get = (_PropertyDefaultGetFunc<T, P> *)godot::api->godot_alloc(sizeof(_PropertyDefaultGetFunc<T, P>));
_PropertyDefaultGetFunc<T, P> *wrapped_get =
(_PropertyDefaultGetFunc<T, P> *)godot::api->godot_alloc(sizeof(_PropertyDefaultGetFunc<T, P>));
wrapped_get->f = var;
godot_property_set_func set_func = {};
@ -354,11 +439,18 @@ void register_property(const char *name, P(T::*var), P default_value, godot_meth
get_func.free_func = godot::api->godot_free;
get_func.get_func = &_PropertyDefaultGetFunc<T, P>::_wrapped_getter;
godot::nativescript_api->godot_nativescript_register_property(godot::_RegisterState::nativescript_handle, T::___get_type_name(), name, &attr, set_func, get_func);
godot::nativescript_api->godot_nativescript_register_property(godot::_RegisterState::nativescript_handle,
T::___get_class_name(), name, &attr, set_func, get_func);
}
template <class T, class P>
void register_property(const char *name, void (T::*setter)(P), P (T::*getter)(), P default_value, godot_method_rpc_mode rpc_mode = GODOT_METHOD_RPC_MODE_DISABLED, godot_property_usage_flags usage = GODOT_PROPERTY_USAGE_DEFAULT, godot_property_hint hint = GODOT_PROPERTY_HINT_NONE, String hint_string = "") {
void register_property(const char *name, void (T::*setter)(P), P (T::*getter)(), P default_value,
godot_method_rpc_mode rpc_mode = GODOT_METHOD_RPC_MODE_DISABLED,
godot_property_usage_flags usage = GODOT_PROPERTY_USAGE_DEFAULT,
godot_property_hint hint = GODOT_PROPERTY_HINT_NONE, String hint_string = "") {
static_assert(T::___CLASS_IS_SCRIPT, "This function must only be used on custom classes");
Variant def_val = default_value;
godot_string *_hint_string = (godot_string *)&hint_string;
@ -391,16 +483,23 @@ void register_property(const char *name, void (T::*setter)(P), P (T::*getter)(),
get_func.free_func = godot::api->godot_free;
get_func.get_func = &_PropertyGetFunc<T, P>::_wrapped_getter;
godot::nativescript_api->godot_nativescript_register_property(godot::_RegisterState::nativescript_handle, T::___get_type_name(), name, &attr, set_func, get_func);
godot::nativescript_api->godot_nativescript_register_property(godot::_RegisterState::nativescript_handle,
T::___get_class_name(), name, &attr, set_func, get_func);
}
template <class T, class P>
void register_property(const char *name, void (T::*setter)(P), P (T::*getter)() const, P default_value, godot_method_rpc_mode rpc_mode = GODOT_METHOD_RPC_MODE_DISABLED, godot_property_usage_flags usage = GODOT_PROPERTY_USAGE_DEFAULT, godot_property_hint hint = GODOT_PROPERTY_HINT_NONE, String hint_string = "") {
void register_property(const char *name, void (T::*setter)(P), P (T::*getter)() const, P default_value,
godot_method_rpc_mode rpc_mode = GODOT_METHOD_RPC_MODE_DISABLED,
godot_property_usage_flags usage = GODOT_PROPERTY_USAGE_DEFAULT,
godot_property_hint hint = GODOT_PROPERTY_HINT_NONE, String hint_string = "") {
register_property(name, setter, (P(T::*)())getter, default_value, rpc_mode, usage, hint, hint_string);
}
template <class T>
void register_signal(String name, Dictionary args = Dictionary()) {
static_assert(T::___CLASS_IS_SCRIPT, "This function must only be used on custom classes");
godot_signal signal = {};
signal.name = *(godot_string *)&name;
signal.num_args = args.size();
@ -425,7 +524,8 @@ void register_signal(String name, Dictionary args = Dictionary()) {
signal.args[i].type = args.values()[i];
}
godot::nativescript_api->godot_nativescript_register_signal(godot::_RegisterState::nativescript_handle, T::___get_type_name(), &signal);
godot::nativescript_api->godot_nativescript_register_signal(godot::_RegisterState::nativescript_handle,
T::___get_class_name(), &signal);
for (int i = 0; i < signal.num_args; i++) {
godot::api->godot_string_destroy(&signal.args[i].name);
@ -447,26 +547,31 @@ T *Object::cast_to(const Object *obj) {
if (!obj)
return nullptr;
size_t have_tag = (size_t)godot::nativescript_1_1_api->godot_nativescript_get_type_tag(obj->_owner);
if (T::___CLASS_IS_SCRIPT) {
size_t have_tag = (size_t)godot::nativescript_1_1_api->godot_nativescript_get_type_tag(obj->_owner);
if (have_tag) {
if (!godot::_TagDB::is_type_known((size_t)have_tag)) {
have_tag = 0;
}
}
if (have_tag) {
if (!godot::_TagDB::is_type_known((size_t)have_tag)) {
have_tag = 0;
if (!have_tag) {
have_tag = obj->_type_tag;
}
if (godot::_TagDB::is_type_compatible(T::___get_id(), have_tag)) {
return detail::get_custom_class_instance<T>(obj);
}
} else {
if (godot::core_1_2_api->godot_object_cast_to(obj->_owner, (void *)T::___get_id())) {
return (T *)obj;
}
}
if (!have_tag) {
have_tag = obj->_type_tag;
}
if (godot::_TagDB::is_type_compatible(typeid(T).hash_code(), have_tag)) {
return (T::___CLASS_IS_SCRIPT) ? godot::as<T>(obj) : (T *)obj;
} else {
return nullptr;
}
return nullptr;
}
#endif
} // namespace godot
#endif // GODOT_H
#endif // GODOT_HPP

250
include/core/Math.hpp Normal file
View File

@ -0,0 +1,250 @@
#ifndef GODOT_MATH_H
#define GODOT_MATH_H
#include "Defs.hpp"
#include <cmath>
namespace godot {
namespace Math {
// Functions reproduced as in Godot's source code `math_funcs.h`.
// Some are overloads to automatically support changing real_t into either double or float in the way Godot does.
inline double fmod(double p_x, double p_y) {
return ::fmod(p_x, p_y);
}
inline float fmod(float p_x, float p_y) {
return ::fmodf(p_x, p_y);
}
inline double floor(double p_x) {
return ::floor(p_x);
}
inline float floor(float p_x) {
return ::floorf(p_x);
}
inline double exp(double p_x) {
return ::exp(p_x);
}
inline float exp(float p_x) {
return ::expf(p_x);
}
inline double sin(double p_x) {
return ::sin(p_x);
}
inline float sin(float p_x) {
return ::sinf(p_x);
}
inline double cos(double p_x) {
return ::cos(p_x);
}
inline float cos(float p_x) {
return ::cosf(p_x);
}
inline double tan(double p_x) {
return ::tan(p_x);
}
inline float tan(float p_x) {
return ::tanf(p_x);
}
inline double atan2(double p_y, double p_x) {
return ::atan2(p_y, p_x);
}
inline float atan2(float p_y, float p_x) {
return ::atan2f(p_y, p_x);
}
inline double sqrt(double p_x) {
return ::sqrt(p_x);
}
inline float sqrt(float p_x) {
return ::sqrtf(p_x);
}
inline float lerp(float minv, float maxv, float t) {
return minv + t * (maxv - minv);
}
inline double lerp(double minv, double maxv, double t) {
return minv + t * (maxv - minv);
}
inline double lerp_angle(double p_from, double p_to, double p_weight) {
double difference = fmod(p_to - p_from, Math_TAU);
double distance = fmod(2.0 * difference, Math_TAU) - difference;
return p_from + distance * p_weight;
}
inline float lerp_angle(float p_from, float p_to, float p_weight) {
float difference = fmod(p_to - p_from, (float)Math_TAU);
float distance = fmod(2.0f * difference, (float)Math_TAU) - difference;
return p_from + distance * p_weight;
}
template <typename T>
inline T clamp(T x, T minv, T maxv) {
if (x < minv) {
return minv;
}
if (x > maxv) {
return maxv;
}
return x;
}
template <typename T>
inline T min(T a, T b) {
return a < b ? a : b;
}
template <typename T>
inline T max(T a, T b) {
return a > b ? a : b;
}
template <typename T>
inline T sign(T x) {
return x < 0 ? -1 : 1;
}
inline double deg2rad(double p_y) {
return p_y * Math_PI / 180.0;
}
inline float deg2rad(float p_y) {
return p_y * Math_PI / 180.0;
}
inline double rad2deg(double p_y) {
return p_y * 180.0 / Math_PI;
}
inline float rad2deg(float p_y) {
return p_y * 180.0 / Math_PI;
}
inline double inverse_lerp(double p_from, double p_to, double p_value) {
return (p_value - p_from) / (p_to - p_from);
}
inline float inverse_lerp(float p_from, float p_to, float p_value) {
return (p_value - p_from) / (p_to - p_from);
}
inline double range_lerp(double p_value, double p_istart, double p_istop, double p_ostart, double p_ostop) {
return Math::lerp(p_ostart, p_ostop, Math::inverse_lerp(p_istart, p_istop, p_value));
}
inline float range_lerp(float p_value, float p_istart, float p_istop, float p_ostart, float p_ostop) {
return Math::lerp(p_ostart, p_ostop, Math::inverse_lerp(p_istart, p_istop, p_value));
}
inline bool is_equal_approx(real_t a, real_t b) {
// Check for exact equality first, required to handle "infinity" values.
if (a == b) {
return true;
}
// Then check for approximate equality.
real_t tolerance = CMP_EPSILON * std::abs(a);
if (tolerance < CMP_EPSILON) {
tolerance = CMP_EPSILON;
}
return std::abs(a - b) < tolerance;
}
inline bool is_equal_approx(real_t a, real_t b, real_t tolerance) {
// Check for exact equality first, required to handle "infinity" values.
if (a == b) {
return true;
}
// Then check for approximate equality.
return std::abs(a - b) < tolerance;
}
inline bool is_zero_approx(real_t s) {
return std::abs(s) < CMP_EPSILON;
}
inline double smoothstep(double p_from, double p_to, double p_weight) {
if (is_equal_approx(p_from, p_to)) {
return p_from;
}
double x = clamp((p_weight - p_from) / (p_to - p_from), 0.0, 1.0);
return x * x * (3.0 - 2.0 * x);
}
inline float smoothstep(float p_from, float p_to, float p_weight) {
if (is_equal_approx(p_from, p_to)) {
return p_from;
}
float x = clamp((p_weight - p_from) / (p_to - p_from), 0.0f, 1.0f);
return x * x * (3.0f - 2.0f * x);
}
inline double move_toward(double p_from, double p_to, double p_delta) {
return std::abs(p_to - p_from) <= p_delta ? p_to : p_from + sign(p_to - p_from) * p_delta;
}
inline float move_toward(float p_from, float p_to, float p_delta) {
return std::abs(p_to - p_from) <= p_delta ? p_to : p_from + sign(p_to - p_from) * p_delta;
}
inline double linear2db(double p_linear) {
return log(p_linear) * 8.6858896380650365530225783783321;
}
inline float linear2db(float p_linear) {
return log(p_linear) * 8.6858896380650365530225783783321f;
}
inline double db2linear(double p_db) {
return exp(p_db * 0.11512925464970228420089957273422);
}
inline float db2linear(float p_db) {
return exp(p_db * 0.11512925464970228420089957273422f);
}
inline double round(double p_val) {
return (p_val >= 0) ? floor(p_val + 0.5) : -floor(-p_val + 0.5);
}
inline float round(float p_val) {
return (p_val >= 0) ? floor(p_val + 0.5) : -floor(-p_val + 0.5);
}
inline int64_t wrapi(int64_t value, int64_t min, int64_t max) {
int64_t range = max - min;
return range == 0 ? min : min + ((((value - min) % range) + range) % range);
}
inline double wrapf(double value, double min, double max) {
double range = max - min;
return is_zero_approx(range) ? min : value - (range * floor((value - min) / range));
}
inline float wrapf(float value, float min, float max) {
float range = max - min;
return is_zero_approx(range) ? min : value - (range * floor((value - min) / range));
}
inline real_t stepify(real_t p_value, real_t p_step) {
if (p_step != 0) {
p_value = floor(p_value / p_step + 0.5) * p_step;
}
return p_value;
}
inline unsigned int next_power_of_2(unsigned int x) {
if (x == 0)
return 0;
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return ++x;
}
} // namespace Math
} // namespace godot
#endif // GODOT_MATH_H

View File

@ -15,7 +15,9 @@ public:
RID(Object *p);
int32_t get_rid() const;
godot_rid _get_godot_rid() const;
int32_t get_id() const;
inline bool is_valid() const {
// is_valid() is not available in the C API...

View File

@ -29,6 +29,9 @@ public:
class String {
godot_string _godot_string;
String(godot_string contents) :
_godot_string(contents) {}
public:
String();
String(const char *contents);

View File

@ -5,7 +5,7 @@
#include "Defs.hpp"
#include <cmath>
#include <Math.hpp>
namespace godot {
@ -138,6 +138,12 @@ struct Vector2 {
return atan2(y - p_vector2.y, x - p_vector2.x);
}
inline Vector2 direction_to(const Vector2 &p_b) const {
Vector2 ret(p_b.x - x, p_b.y - y);
ret.normalize();
return ret;
}
inline real_t dot(const Vector2 &p_other) const {
return x * p_other.x + y * p_other.y;
}
@ -172,6 +178,13 @@ struct Vector2 {
Vector2 cubic_interpolate(const Vector2 &p_b, const Vector2 &p_pre_a, const Vector2 &p_post_b, real_t p_t) const;
Vector2 move_toward(const Vector2 &p_to, const real_t p_delta) const {
Vector2 v = *this;
Vector2 vd = p_to - v;
real_t len = vd.length();
return len <= p_delta || len < CMP_EPSILON ? p_to : v + vd / len * p_delta;
}
inline Vector2 slide(const Vector2 &p_vec) const {
return p_vec - *this * this->dot(p_vec);
}
@ -180,8 +193,8 @@ struct Vector2 {
return -reflect(p_normal);
}
inline Vector2 reflect(const Vector2 &p_vec) const {
return p_vec - *this * this->dot(p_vec) * 2.0;
inline Vector2 reflect(const Vector2 &p_normal) const {
return -(*this - p_normal * this->dot(p_normal) * 2.0);
}
inline real_t angle() const {
@ -209,13 +222,13 @@ struct Vector2 {
}
inline Vector2 floor() const {
return Vector2(::floor(x), ::floor(y));
return Vector2(Math::floor(x), Math::floor(y));
}
inline Vector2 snapped(const Vector2 &p_by) const {
return Vector2(
p_by.x != 0 ? ::floor(x / p_by.x + 0.5) * p_by.x : x,
p_by.y != 0 ? ::floor(y / p_by.y + 0.5) * p_by.y : y);
Math::stepify(x, p_by.x),
Math::stepify(y, p_by.y));
}
inline real_t aspect() const { return width / height; }
@ -227,6 +240,22 @@ inline Vector2 operator*(real_t p_scalar, const Vector2 &p_vec) {
return p_vec * p_scalar;
}
namespace Math {
// Convenience, since they exist in GDScript
inline Vector2 cartesian2polar(Vector2 v) {
return Vector2(Math::sqrt(v.x * v.x + v.y * v.y), Math::atan2(v.y, v.x));
}
inline Vector2 polar2cartesian(Vector2 v) {
// x == radius
// y == angle
return Vector2(v.x * Math::cos(v.y), v.x * Math::sin(v.y));
}
} // namespace Math
} // namespace godot
#endif // VECTOR2_H

View File

@ -7,7 +7,7 @@
#include "String.hpp"
#include <cmath>
#include <Math.hpp>
namespace godot {
@ -165,8 +165,20 @@ struct Vector3 {
z + (p_t * (p_b.z - z)));
}
inline Vector3 slerp(const Vector3 &p_b, real_t p_t) const {
real_t theta = angle_to(p_b);
return rotated(cross(p_b).normalized(), theta * p_t);
}
Vector3 cubic_interpolate(const Vector3 &b, const Vector3 &pre_a, const Vector3 &post_b, const real_t t) const;
Vector3 move_toward(const Vector3 &p_to, const real_t p_delta) const {
Vector3 v = *this;
Vector3 vd = p_to - v;
real_t len = vd.length();
return len <= p_delta || len < CMP_EPSILON ? p_to : v + vd / len * p_delta;
}
Vector3 bounce(const Vector3 &p_normal) const {
return -reflect(p_normal);
}
@ -199,10 +211,20 @@ struct Vector3 {
return x * b.x + y * b.y + z * b.z;
}
inline Vector3 project(const Vector3 &p_b) const {
return p_b * (dot(p_b) / p_b.length_squared());
}
inline real_t angle_to(const Vector3 &b) const {
return std::atan2(cross(b).length(), dot(b));
}
inline Vector3 direction_to(const Vector3 &p_b) const {
Vector3 ret(p_b.x - x, p_b.y - y, p_b.z - z);
ret.normalize();
return ret;
}
inline Vector3 floor() const {
return Vector3(::floor(x), ::floor(y), ::floor(z));
}
@ -238,8 +260,8 @@ struct Vector3 {
return v;
}
inline Vector3 reflect(const Vector3 &by) const {
return by - *this * this->dot(by) * 2.f;
inline Vector3 reflect(const Vector3 &p_normal) const {
return -(*this - p_normal * this->dot(p_normal) * 2.0);
}
inline Vector3 rotated(const Vector3 &axis, const real_t phi) const {
@ -251,7 +273,7 @@ struct Vector3 {
void rotate(const Vector3 &p_axis, real_t p_phi);
inline Vector3 slide(const Vector3 &by) const {
return by - *this * this->dot(by);
return *this - by * this->dot(by);
}
void snap(real_t p_val);

View File

@ -1,17 +1,25 @@
#!/bin/sh
CLANG_FORMAT=clang-format-6.0
CLANG_FORMAT=clang-format-8
if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
# Check the whole commit range against $TRAVIS_BRANCH, the base merge branch
# We could use $TRAVIS_COMMIT_RANGE but it doesn't play well with force pushes
RANGE="$(git rev-parse $TRAVIS_BRANCH) HEAD"
# Travis only clones the PR branch and uses its HEAD commit as detached HEAD,
# so it's problematic when we want an exact commit range for format checks.
# We fetch upstream to ensure that we have the proper references to resolve.
# Ideally we would use $TRAVIS_COMMIT_RANGE but it doesn't play well with PR
# updates, as it only includes changes since the previous state of the PR.
if [ -z "$(git remote | grep upstream)" ]; then
git remote add upstream https://github.com/godotengine/godot-cpp \
--no-tags -f -t $TRAVIS_BRANCH
fi
RANGE="upstream/$TRAVIS_BRANCH HEAD"
else
# Test only the last commit
# Test only the last commit, since $TRAVIS_COMMIT_RANGE wouldn't support
# force pushes.
RANGE=HEAD
fi
FILES=$(git diff-tree --no-commit-id --name-only -r $RANGE | grep -v thirdparty/ | grep -E "\.(c|h|cpp|hpp|cc|hh|cxx|m|mm|inc|java|glsl)$")
FILES=$(git diff-tree --no-commit-id --name-only -r $RANGE | grep -E "\.(c|h|cpp|hpp|cc|hh|cxx|m|mm|inc|java|glsl)$")
echo "Checking files:\n$FILES"
# create a random filename to store our generated patch

683
src/core/CameraMatrix.cpp Normal file
View File

@ -0,0 +1,683 @@
/*************************************************************************/
/* camera_matrix.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "CameraMatrix.hpp"
void CameraMatrix::set_identity() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
matrix[i][j] = (i == j) ? 1 : 0;
}
}
}
void CameraMatrix::set_zero() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
matrix[i][j] = 0;
}
}
}
Plane CameraMatrix::xform4(const Plane &p_vec4) const {
Plane ret;
ret.normal.x = matrix[0][0] * p_vec4.normal.x + matrix[1][0] * p_vec4.normal.y + matrix[2][0] * p_vec4.normal.z + matrix[3][0] * p_vec4.d;
ret.normal.y = matrix[0][1] * p_vec4.normal.x + matrix[1][1] * p_vec4.normal.y + matrix[2][1] * p_vec4.normal.z + matrix[3][1] * p_vec4.d;
ret.normal.z = matrix[0][2] * p_vec4.normal.x + matrix[1][2] * p_vec4.normal.y + matrix[2][2] * p_vec4.normal.z + matrix[3][2] * p_vec4.d;
ret.d = matrix[0][3] * p_vec4.normal.x + matrix[1][3] * p_vec4.normal.y + matrix[2][3] * p_vec4.normal.z + matrix[3][3] * p_vec4.d;
return ret;
}
void CameraMatrix::set_perspective(real_t p_fovy_degrees, real_t p_aspect, real_t p_z_near, real_t p_z_far, bool p_flip_fov) {
if (p_flip_fov) {
p_fovy_degrees = get_fovy(p_fovy_degrees, 1.0 / p_aspect);
}
real_t sine, cotangent, deltaZ;
real_t radians = p_fovy_degrees / 2.0 * Math_PI / 180.0;
deltaZ = p_z_far - p_z_near;
sine = sin(radians);
if ((deltaZ == 0) || (sine == 0) || (p_aspect == 0)) {
return;
}
cotangent = cos(radians) / sine;
set_identity();
matrix[0][0] = cotangent / p_aspect;
matrix[1][1] = cotangent;
matrix[2][2] = -(p_z_far + p_z_near) / deltaZ;
matrix[2][3] = -1;
matrix[3][2] = -2 * p_z_near * p_z_far / deltaZ;
matrix[3][3] = 0;
}
void CameraMatrix::set_perspective(real_t p_fovy_degrees, real_t p_aspect, real_t p_z_near, real_t p_z_far, bool p_flip_fov, int p_eye, real_t p_intraocular_dist, real_t p_convergence_dist) {
if (p_flip_fov) {
p_fovy_degrees = get_fovy(p_fovy_degrees, 1.0 / p_aspect);
}
real_t left, right, modeltranslation, ymax, xmax, frustumshift;
ymax = p_z_near * tan(p_fovy_degrees * Math_PI / 360.0f);
xmax = ymax * p_aspect;
frustumshift = (p_intraocular_dist / 2.0) * p_z_near / p_convergence_dist;
switch (p_eye) {
case 1: { // left eye
left = -xmax + frustumshift;
right = xmax + frustumshift;
modeltranslation = p_intraocular_dist / 2.0;
}; break;
case 2: { // right eye
left = -xmax - frustumshift;
right = xmax - frustumshift;
modeltranslation = -p_intraocular_dist / 2.0;
}; break;
default: { // mono, should give the same result as set_perspective(p_fovy_degrees,p_aspect,p_z_near,p_z_far,p_flip_fov)
left = -xmax;
right = xmax;
modeltranslation = 0.0;
}; break;
};
set_frustum(left, right, -ymax, ymax, p_z_near, p_z_far);
// translate matrix by (modeltranslation, 0.0, 0.0)
CameraMatrix cm;
cm.set_identity();
cm.matrix[3][0] = modeltranslation;
*this = *this * cm;
}
void CameraMatrix::set_for_hmd(int p_eye, real_t p_aspect, real_t p_intraocular_dist, real_t p_display_width, real_t p_display_to_lens, real_t p_oversample, real_t p_z_near, real_t p_z_far) {
// we first calculate our base frustum on our values without taking our lens magnification into account.
real_t f1 = (p_intraocular_dist * 0.5) / p_display_to_lens;
real_t f2 = ((p_display_width - p_intraocular_dist) * 0.5) / p_display_to_lens;
real_t f3 = (p_display_width / 4.0) / p_display_to_lens;
// now we apply our oversample factor to increase our FOV. how much we oversample is always a balance we strike between performance and how much
// we're willing to sacrifice in FOV.
real_t add = ((f1 + f2) * (p_oversample - 1.0)) / 2.0;
f1 += add;
f2 += add;
f3 *= p_oversample;
// always apply KEEP_WIDTH aspect ratio
f3 /= p_aspect;
switch (p_eye) {
case 1: { // left eye
set_frustum(-f2 * p_z_near, f1 * p_z_near, -f3 * p_z_near, f3 * p_z_near, p_z_near, p_z_far);
}; break;
case 2: { // right eye
set_frustum(-f1 * p_z_near, f2 * p_z_near, -f3 * p_z_near, f3 * p_z_near, p_z_near, p_z_far);
}; break;
default: { // mono, does not apply here!
}; break;
};
};
void CameraMatrix::set_orthogonal(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_znear, real_t p_zfar) {
set_identity();
matrix[0][0] = 2.0 / (p_right - p_left);
matrix[3][0] = -((p_right + p_left) / (p_right - p_left));
matrix[1][1] = 2.0 / (p_top - p_bottom);
matrix[3][1] = -((p_top + p_bottom) / (p_top - p_bottom));
matrix[2][2] = -2.0 / (p_zfar - p_znear);
matrix[3][2] = -((p_zfar + p_znear) / (p_zfar - p_znear));
matrix[3][3] = 1.0;
}
void CameraMatrix::set_orthogonal(real_t p_size, real_t p_aspect, real_t p_znear, real_t p_zfar, bool p_flip_fov) {
if (!p_flip_fov) {
p_size *= p_aspect;
}
set_orthogonal(-p_size / 2, +p_size / 2, -p_size / p_aspect / 2, +p_size / p_aspect / 2, p_znear, p_zfar);
}
void CameraMatrix::set_frustum(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_near, real_t p_far) {
ERR_FAIL_COND(p_right <= p_left);
ERR_FAIL_COND(p_top <= p_bottom);
ERR_FAIL_COND(p_far <= p_near);
real_t *te = &matrix[0][0];
real_t x = 2 * p_near / (p_right - p_left);
real_t y = 2 * p_near / (p_top - p_bottom);
real_t a = (p_right + p_left) / (p_right - p_left);
real_t b = (p_top + p_bottom) / (p_top - p_bottom);
real_t c = -(p_far + p_near) / (p_far - p_near);
real_t d = -2 * p_far * p_near / (p_far - p_near);
te[0] = x;
te[1] = 0;
te[2] = 0;
te[3] = 0;
te[4] = 0;
te[5] = y;
te[6] = 0;
te[7] = 0;
te[8] = a;
te[9] = b;
te[10] = c;
te[11] = -1;
te[12] = 0;
te[13] = 0;
te[14] = d;
te[15] = 0;
}
void CameraMatrix::set_frustum(real_t p_size, real_t p_aspect, Vector2 p_offset, real_t p_near, real_t p_far, bool p_flip_fov) {
if (!p_flip_fov) {
p_size *= p_aspect;
}
set_frustum(-p_size / 2 + p_offset.x, +p_size / 2 + p_offset.x, -p_size / p_aspect / 2 + p_offset.y, +p_size / p_aspect / 2 + p_offset.y, p_near, p_far);
}
real_t CameraMatrix::get_z_far() const {
const real_t *matrix = (const real_t *)this->matrix;
Plane new_plane = Plane(matrix[3] - matrix[2],
matrix[7] - matrix[6],
matrix[11] - matrix[10],
matrix[15] - matrix[14]);
new_plane.normal = -new_plane.normal;
new_plane.normalize();
return new_plane.d;
}
real_t CameraMatrix::get_z_near() const {
const real_t *matrix = (const real_t *)this->matrix;
Plane new_plane = Plane(matrix[3] + matrix[2],
matrix[7] + matrix[6],
matrix[11] + matrix[10],
-matrix[15] - matrix[14]);
new_plane.normalize();
return new_plane.d;
}
Vector2 CameraMatrix::get_viewport_half_extents() const {
const real_t *matrix = (const real_t *)this->matrix;
///////--- Near Plane ---///////
Plane near_plane = Plane(matrix[3] + matrix[2],
matrix[7] + matrix[6],
matrix[11] + matrix[10],
-matrix[15] - matrix[14]);
near_plane.normalize();
///////--- Right Plane ---///////
Plane right_plane = Plane(matrix[3] - matrix[0],
matrix[7] - matrix[4],
matrix[11] - matrix[8],
-matrix[15] + matrix[12]);
right_plane.normalize();
Plane top_plane = Plane(matrix[3] - matrix[1],
matrix[7] - matrix[5],
matrix[11] - matrix[9],
-matrix[15] + matrix[13]);
top_plane.normalize();
Vector3 res;
near_plane.intersect_3(right_plane, top_plane, &res);
return Vector2(res.x, res.y);
}
bool CameraMatrix::get_endpoints(const Transform &p_transform, Vector3 *p_8points) const {
std::vector<Plane> planes = get_projection_planes(Transform());
const Planes intersections[8][3] = {
{ PLANE_FAR, PLANE_LEFT, PLANE_TOP },
{ PLANE_FAR, PLANE_LEFT, PLANE_BOTTOM },
{ PLANE_FAR, PLANE_RIGHT, PLANE_TOP },
{ PLANE_FAR, PLANE_RIGHT, PLANE_BOTTOM },
{ PLANE_NEAR, PLANE_LEFT, PLANE_TOP },
{ PLANE_NEAR, PLANE_LEFT, PLANE_BOTTOM },
{ PLANE_NEAR, PLANE_RIGHT, PLANE_TOP },
{ PLANE_NEAR, PLANE_RIGHT, PLANE_BOTTOM },
};
for (int i = 0; i < 8; i++) {
Vector3 point;
bool res = planes[intersections[i][0]].intersect_3(planes[intersections[i][1]], planes[intersections[i][2]], &point);
ERR_FAIL_COND_V(!res, false);
p_8points[i] = p_transform.xform(point);
}
return true;
}
std::vector<Plane> CameraMatrix::get_projection_planes(const Transform &p_transform) const {
/** Fast Plane Extraction from combined modelview/projection matrices.
* References:
* https://web.archive.org/web/20011221205252/http://www.markmorley.com/opengl/frustumculling.html
* https://web.archive.org/web/20061020020112/http://www2.ravensoft.com/users/ggribb/plane%20extraction.pdf
*/
std::vector<Plane> planes;
const real_t *matrix = (const real_t *)this->matrix;
Plane new_plane;
///////--- Near Plane ---///////
new_plane = Plane(matrix[3] + matrix[2],
matrix[7] + matrix[6],
matrix[11] + matrix[10],
matrix[15] + matrix[14]);
new_plane.normal = -new_plane.normal;
new_plane.normalize();
planes.push_back(p_transform.xform(new_plane));
///////--- Far Plane ---///////
new_plane = Plane(matrix[3] - matrix[2],
matrix[7] - matrix[6],
matrix[11] - matrix[10],
matrix[15] - matrix[14]);
new_plane.normal = -new_plane.normal;
new_plane.normalize();
planes.push_back(p_transform.xform(new_plane));
///////--- Left Plane ---///////
new_plane = Plane(matrix[3] + matrix[0],
matrix[7] + matrix[4],
matrix[11] + matrix[8],
matrix[15] + matrix[12]);
new_plane.normal = -new_plane.normal;
new_plane.normalize();
planes.push_back(p_transform.xform(new_plane));
///////--- Top Plane ---///////
new_plane = Plane(matrix[3] - matrix[1],
matrix[7] - matrix[5],
matrix[11] - matrix[9],
matrix[15] - matrix[13]);
new_plane.normal = -new_plane.normal;
new_plane.normalize();
planes.push_back(p_transform.xform(new_plane));
///////--- Right Plane ---///////
new_plane = Plane(matrix[3] - matrix[0],
matrix[7] - matrix[4],
matrix[11] - matrix[8],
matrix[15] - matrix[12]);
new_plane.normal = -new_plane.normal;
new_plane.normalize();
planes.push_back(p_transform.xform(new_plane));
///////--- Bottom Plane ---///////
new_plane = Plane(matrix[3] + matrix[1],
matrix[7] + matrix[5],
matrix[11] + matrix[9],
matrix[15] + matrix[13]);
new_plane.normal = -new_plane.normal;
new_plane.normalize();
planes.push_back(p_transform.xform(new_plane));
return planes;
}
CameraMatrix CameraMatrix::inverse() const {
CameraMatrix cm = *this;
cm.invert();
return cm;
}
void CameraMatrix::invert() {
int i, j, k;
int pvt_i[4], pvt_j[4]; /* Locations of pivot matrix */
real_t pvt_val; /* Value of current pivot element */
real_t hold; /* Temporary storage */
real_t determinat; /* Determinant */
determinat = 1.0;
for (k = 0; k < 4; k++) {
/** Locate k'th pivot element **/
pvt_val = matrix[k][k]; /** Initialize for search **/
pvt_i[k] = k;
pvt_j[k] = k;
for (i = k; i < 4; i++) {
for (j = k; j < 4; j++) {
if (absd(matrix[i][j]) > absd(pvt_val)) {
pvt_i[k] = i;
pvt_j[k] = j;
pvt_val = matrix[i][j];
}
}
}
/** Product of pivots, gives determinant when finished **/
determinat *= pvt_val;
if (absd(determinat) < 1e-7) {
return; //(false); /** Matrix is singular (zero determinant). **/
}
/** "Interchange" rows (with sign change stuff) **/
i = pvt_i[k];
if (i != k) { /** If rows are different **/
for (j = 0; j < 4; j++) {
hold = -matrix[k][j];
matrix[k][j] = matrix[i][j];
matrix[i][j] = hold;
}
}
/** "Interchange" columns **/
j = pvt_j[k];
if (j != k) { /** If columns are different **/
for (i = 0; i < 4; i++) {
hold = -matrix[i][k];
matrix[i][k] = matrix[i][j];
matrix[i][j] = hold;
}
}
/** Divide column by minus pivot value **/
for (i = 0; i < 4; i++) {
if (i != k) matrix[i][k] /= (-pvt_val);
}
/** Reduce the matrix **/
for (i = 0; i < 4; i++) {
hold = matrix[i][k];
for (j = 0; j < 4; j++) {
if (i != k && j != k) matrix[i][j] += hold * matrix[k][j];
}
}
/** Divide row by pivot **/
for (j = 0; j < 4; j++) {
if (j != k) matrix[k][j] /= pvt_val;
}
/** Replace pivot by reciprocal (at last we can touch it). **/
matrix[k][k] = 1.0 / pvt_val;
}
/* That was most of the work, one final pass of row/column interchange */
/* to finish */
for (k = 4 - 2; k >= 0; k--) { /* Don't need to work with 1 by 1 corner*/
i = pvt_j[k]; /* Rows to swap correspond to pivot COLUMN */
if (i != k) { /* If rows are different */
for (j = 0; j < 4; j++) {
hold = matrix[k][j];
matrix[k][j] = -matrix[i][j];
matrix[i][j] = hold;
}
}
j = pvt_i[k]; /* Columns to swap correspond to pivot ROW */
if (j != k) /* If columns are different */
for (i = 0; i < 4; i++) {
hold = matrix[i][k];
matrix[i][k] = -matrix[i][j];
matrix[i][j] = hold;
}
}
}
CameraMatrix::CameraMatrix() {
set_identity();
}
CameraMatrix CameraMatrix::operator*(const CameraMatrix &p_matrix) const {
CameraMatrix new_matrix;
for (int j = 0; j < 4; j++) {
for (int i = 0; i < 4; i++) {
real_t ab = 0;
for (int k = 0; k < 4; k++)
ab += matrix[k][i] * p_matrix.matrix[j][k];
new_matrix.matrix[j][i] = ab;
}
}
return new_matrix;
}
void CameraMatrix::set_light_bias() {
real_t *m = &matrix[0][0];
m[0] = 0.5;
m[1] = 0.0;
m[2] = 0.0;
m[3] = 0.0;
m[4] = 0.0;
m[5] = 0.5;
m[6] = 0.0;
m[7] = 0.0;
m[8] = 0.0;
m[9] = 0.0;
m[10] = 0.5;
m[11] = 0.0;
m[12] = 0.5;
m[13] = 0.5;
m[14] = 0.5;
m[15] = 1.0;
}
void CameraMatrix::set_light_atlas_rect(const Rect2 &p_rect) {
real_t *m = &matrix[0][0];
m[0] = p_rect.size.width;
m[1] = 0.0;
m[2] = 0.0;
m[3] = 0.0;
m[4] = 0.0;
m[5] = p_rect.size.height;
m[6] = 0.0;
m[7] = 0.0;
m[8] = 0.0;
m[9] = 0.0;
m[10] = 1.0;
m[11] = 0.0;
m[12] = p_rect.position.x;
m[13] = p_rect.position.y;
m[14] = 0.0;
m[15] = 1.0;
}
CameraMatrix::operator String() const {
String str;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
str += String((j > 0) ? ", " : "\n") + String::num(matrix[i][j]);
return str;
}
real_t CameraMatrix::get_aspect() const {
Vector2 vp_he = get_viewport_half_extents();
return vp_he.x / vp_he.y;
}
int CameraMatrix::get_pixels_per_meter(int p_for_pixel_width) const {
Vector3 result = xform(Vector3(1, 0, -1));
return int((result.x * 0.5 + 0.5) * p_for_pixel_width);
}
bool CameraMatrix::is_orthogonal() const {
return matrix[3][3] == 1.0;
}
real_t CameraMatrix::get_fov() const {
const real_t *matrix = (const real_t *)this->matrix;
Plane right_plane = Plane(matrix[3] - matrix[0],
matrix[7] - matrix[4],
matrix[11] - matrix[8],
-matrix[15] + matrix[12]);
right_plane.normalize();
if ((matrix[8] == 0) && (matrix[9] == 0)) {
return rad2deg(acos(abs(right_plane.normal.x))) * 2.0;
} else {
// our frustum is asymmetrical need to calculate the left planes angle separately..
Plane left_plane = Plane(matrix[3] + matrix[0],
matrix[7] + matrix[4],
matrix[11] + matrix[8],
matrix[15] + matrix[12]);
left_plane.normalize();
return rad2deg(acos(abs(left_plane.normal.x))) + rad2deg(acos(abs(right_plane.normal.x)));
}
}
void CameraMatrix::make_scale(const Vector3 &p_scale) {
set_identity();
matrix[0][0] = p_scale.x;
matrix[1][1] = p_scale.y;
matrix[2][2] = p_scale.z;
}
void CameraMatrix::scale_translate_to_fit(const AABB &p_aabb) {
Vector3 min = p_aabb.position;
Vector3 max = p_aabb.position + p_aabb.size;
matrix[0][0] = 2 / (max.x - min.x);
matrix[1][0] = 0;
matrix[2][0] = 0;
matrix[3][0] = -(max.x + min.x) / (max.x - min.x);
matrix[0][1] = 0;
matrix[1][1] = 2 / (max.y - min.y);
matrix[2][1] = 0;
matrix[3][1] = -(max.y + min.y) / (max.y - min.y);
matrix[0][2] = 0;
matrix[1][2] = 0;
matrix[2][2] = 2 / (max.z - min.z);
matrix[3][2] = -(max.z + min.z) / (max.z - min.z);
matrix[0][3] = 0;
matrix[1][3] = 0;
matrix[2][3] = 0;
matrix[3][3] = 1;
}
CameraMatrix::operator Transform() const {
Transform tr;
const real_t *m = &matrix[0][0];
tr.basis.elements[0][0] = m[0];
tr.basis.elements[1][0] = m[1];
tr.basis.elements[2][0] = m[2];
tr.basis.elements[0][1] = m[4];
tr.basis.elements[1][1] = m[5];
tr.basis.elements[2][1] = m[6];
tr.basis.elements[0][2] = m[8];
tr.basis.elements[1][2] = m[9];
tr.basis.elements[2][2] = m[10];
tr.origin.x = m[12];
tr.origin.y = m[13];
tr.origin.z = m[14];
return tr;
}
CameraMatrix::CameraMatrix(const Transform &p_transform) {
const Transform &tr = p_transform;
real_t *m = &matrix[0][0];
m[0] = tr.basis.elements[0][0];
m[1] = tr.basis.elements[1][0];
m[2] = tr.basis.elements[2][0];
m[3] = 0.0;
m[4] = tr.basis.elements[0][1];
m[5] = tr.basis.elements[1][1];
m[6] = tr.basis.elements[2][1];
m[7] = 0.0;
m[8] = tr.basis.elements[0][2];
m[9] = tr.basis.elements[1][2];
m[10] = tr.basis.elements[2][2];
m[11] = 0.0;
m[12] = tr.origin.x;
m[13] = tr.origin.y;
m[14] = tr.origin.z;
m[15] = 1.0;
}
CameraMatrix::~CameraMatrix() {
}

View File

@ -527,4 +527,122 @@ bool Color::operator<(const Color &p_color) const {
return r < p_color.r;
}
Color Color::operator+(const Color &p_color) const {
return Color(
r + p_color.r,
g + p_color.g,
b + p_color.b,
a + p_color.a);
}
void Color::operator+=(const Color &p_color) {
r = r + p_color.r;
g = g + p_color.g;
b = b + p_color.b;
a = a + p_color.a;
}
Color Color::operator-(const Color &p_color) const {
return Color(
r - p_color.r,
g - p_color.g,
b - p_color.b,
a - p_color.a);
}
void Color::operator-=(const Color &p_color) {
r = r - p_color.r;
g = g - p_color.g;
b = b - p_color.b;
a = a - p_color.a;
}
Color Color::operator*(const Color &p_color) const {
return Color(
r * p_color.r,
g * p_color.g,
b * p_color.b,
a * p_color.a);
}
Color Color::operator*(const real_t &rvalue) const {
return Color(
r * rvalue,
g * rvalue,
b * rvalue,
a * rvalue);
}
void Color::operator*=(const Color &p_color) {
r = r * p_color.r;
g = g * p_color.g;
b = b * p_color.b;
a = a * p_color.a;
}
void Color::operator*=(const real_t &rvalue) {
r = r * rvalue;
g = g * rvalue;
b = b * rvalue;
a = a * rvalue;
}
Color Color::operator/(const Color &p_color) const {
return Color(
r / p_color.r,
g / p_color.g,
b / p_color.b,
a / p_color.a);
}
Color Color::operator/(const real_t &rvalue) const {
return Color(
r / rvalue,
g / rvalue,
b / rvalue,
a / rvalue);
}
void Color::operator/=(const Color &p_color) {
r = r / p_color.r;
g = g / p_color.g;
b = b / p_color.b;
a = a / p_color.a;
}
void Color::operator/=(const real_t &rvalue) {
if (rvalue == 0) {
r = 1.0;
g = 1.0;
b = 1.0;
a = 1.0;
} else {
r = r / rvalue;
g = g / rvalue;
b = b / rvalue;
a = a / rvalue;
}
}
Color Color::operator-() const {
return Color(
1.0 - r,
1.0 - g,
1.0 - b,
1.0 - a);
}
} // namespace godot

View File

@ -140,6 +140,13 @@ void Godot::gdnative_init(godot_gdnative_init_options *options) {
}
}
// Initialize the `language_index` here since `__register_types()` makes use of it.
godot_instance_binding_functions binding_funcs = {};
binding_funcs.alloc_instance_binding_data = wrapper_create;
binding_funcs.free_instance_binding_data = wrapper_destroy;
godot::_RegisterState::language_index = godot::nativescript_1_1_api->godot_nativescript_register_instance_binding_data_functions(binding_funcs);
// register these now
___register_types();
___init_method_bindings();
@ -155,12 +162,6 @@ void Godot::gdnative_profiling_add_data(const char *p_signature, uint64_t p_time
void Godot::nativescript_init(void *handle) {
godot::_RegisterState::nativescript_handle = handle;
godot_instance_binding_functions binding_funcs = {};
binding_funcs.alloc_instance_binding_data = wrapper_create;
binding_funcs.free_instance_binding_data = wrapper_destroy;
godot::_RegisterState::language_index = godot::nativescript_1_1_api->godot_nativescript_register_instance_binding_data_functions(binding_funcs);
}
void Godot::nativescript_terminate(void *handle) {

View File

@ -14,7 +14,11 @@ RID::RID(Object *p) {
godot::api->godot_rid_new_with_resource(&_godot_rid, (const godot_object *)p);
}
int32_t RID::get_rid() const {
godot_rid RID::_get_godot_rid() const {
return _godot_rid;
}
int32_t RID::get_id() const {
return godot::api->godot_rid_get_id(&_godot_rid);
}

View File

@ -25,52 +25,31 @@ const char *godot::CharString::get_data() const {
}
String String::num(double p_num, int p_decimals) {
String new_string;
new_string._godot_string = godot::api->godot_string_num_with_decimals(p_num, p_decimals);
return new_string;
return String(godot::api->godot_string_num_with_decimals(p_num, p_decimals));
}
String String::num_scientific(double p_num) {
String new_string;
new_string._godot_string = godot::api->godot_string_num_scientific(p_num);
return new_string;
return String(godot::api->godot_string_num_scientific(p_num));
}
String String::num_real(double p_num) {
String new_string;
new_string._godot_string = godot::api->godot_string_num_real(p_num);
return new_string;
return String(godot::api->godot_string_num_real(p_num));
}
String String::num_int64(int64_t p_num, int base, bool capitalize_hex) {
String new_string;
new_string._godot_string = godot::api->godot_string_num_int64_capitalized(p_num, base, capitalize_hex);
return new_string;
return String(godot::api->godot_string_num_int64_capitalized(p_num, base, capitalize_hex));
}
String String::chr(godot_char_type p_char) {
String new_string;
new_string._godot_string = godot::api->godot_string_chr(p_char);
return new_string;
return String(godot::api->godot_string_chr(p_char));
}
String String::md5(const uint8_t *p_md5) {
String new_string;
new_string._godot_string = godot::api->godot_string_md5(p_md5);
return new_string;
return String(godot::api->godot_string_md5(p_md5));
}
String String::hex_encode_buffer(const uint8_t *p_buffer, int p_len) {
String new_string;
new_string._godot_string = godot::api->godot_string_hex_encode_buffer(p_buffer, p_len);
return new_string;
return String(godot::api->godot_string_hex_encode_buffer(p_buffer, p_len));
}
godot::String::String() {
@ -124,18 +103,16 @@ bool String::operator!=(const String &s) const {
}
String String::operator+(const String &s) const {
String new_string;
new_string._godot_string = godot::api->godot_string_operator_plus(&_godot_string, &s._godot_string);
return new_string;
return String(godot::api->godot_string_operator_plus(&_godot_string, &s._godot_string));
}
void String::operator+=(const String &s) {
_godot_string = godot::api->godot_string_operator_plus(&_godot_string, &s._godot_string);
*this = String(godot::api->godot_string_operator_plus(&_godot_string, &s._godot_string));
}
void String::operator+=(const wchar_t /*c*/) {
// @Todo
void String::operator+=(const wchar_t c) {
String _to_be_added = String(c);
*this = String(godot::api->godot_string_operator_plus(&_godot_string, &_to_be_added._godot_string));
}
bool String::operator<(const String &s) const {
@ -223,24 +200,15 @@ PoolStringArray String::bigrams() const {
}
String String::c_escape() const {
String new_string;
new_string._godot_string = godot::api->godot_string_c_escape(&_godot_string);
return new_string;
return String(godot::api->godot_string_c_escape(&_godot_string));
}
String String::c_unescape() const {
String new_string;
new_string._godot_string = godot::api->godot_string_c_unescape(&_godot_string);
return new_string;
return String(godot::api->godot_string_c_unescape(&_godot_string));
}
String String::capitalize() const {
String new_string;
new_string._godot_string = godot::api->godot_string_capitalize(&_godot_string);
return new_string;
return String(godot::api->godot_string_capitalize(&_godot_string));
}
bool String::empty() const {
@ -268,41 +236,31 @@ int String::findn(String p_what, int p_from) const {
}
String String::format(Variant values) const {
String new_string;
new_string._godot_string = godot::api->godot_string_format(&_godot_string, (godot_variant *)&values);
return new_string;
return String(godot::api->godot_string_format(&_godot_string, (godot_variant *)&values));
}
String String::format(Variant values, String placeholder) const {
String new_string;
godot_char_string contents = godot::api->godot_string_utf8(&placeholder._godot_string);
new_string._godot_string = godot::api->godot_string_format_with_custom_placeholder(&_godot_string, (godot_variant *)&values, godot::api->godot_char_string_get_data(&contents));
String new_string(godot::api->godot_string_format_with_custom_placeholder(&_godot_string, (godot_variant *)&values, godot::api->godot_char_string_get_data(&contents)));
godot::api->godot_char_string_destroy(&contents);
return new_string;
}
String String::get_base_dir() const {
String new_string;
new_string._godot_string = godot::api->godot_string_get_base_dir(&_godot_string);
return new_string;
return String(godot::api->godot_string_get_base_dir(&_godot_string));
}
String String::get_basename() const {
godot_string new_string = godot::api->godot_string_get_basename(&_godot_string);
return *(String *)&new_string;
return String(godot::api->godot_string_get_basename(&_godot_string));
}
String String::get_extension() const {
godot_string new_string = godot::api->godot_string_get_extension(&_godot_string);
return *(String *)&new_string;
return String(godot::api->godot_string_get_extension(&_godot_string));
}
String String::get_file() const {
godot_string new_string = godot::api->godot_string_get_file(&_godot_string);
return *(String *)&new_string;
return String(godot::api->godot_string_get_file(&_godot_string));
}
int String::hash() const {
@ -314,10 +272,7 @@ int String::hex_to_int() const {
}
String String::insert(int position, String what) const {
String new_string;
new_string._godot_string = godot::api->godot_string_insert(&_godot_string, position, what._godot_string);
return new_string;
return String(godot::api->godot_string_insert(&_godot_string, position, what._godot_string));
}
bool String::is_abs_path() const {
@ -357,17 +312,11 @@ bool String::is_valid_ip_address() const {
}
String String::json_escape() const {
String new_string;
new_string._godot_string = godot::api->godot_string_json_escape(&_godot_string);
return new_string;
return String(godot::api->godot_string_json_escape(&_godot_string));
}
String String::left(int position) const {
String new_string;
new_string._godot_string = godot::api->godot_string_left(&_godot_string, position);
return new_string;
return String(godot::api->godot_string_left(&_godot_string, position));
}
bool String::match(String expr) const {
@ -384,10 +333,7 @@ PoolByteArray String::md5_buffer() const {
}
String String::md5_text() const {
String new_string;
new_string._godot_string = godot::api->godot_string_md5_text(&_godot_string);
return new_string;
return String(godot::api->godot_string_md5_text(&_godot_string));
}
int String::ord_at(int at) const {
@ -395,52 +341,31 @@ int String::ord_at(int at) const {
}
String String::pad_decimals(int digits) const {
String new_string;
new_string._godot_string = godot::api->godot_string_pad_decimals(&_godot_string, digits);
return new_string;
return String(godot::api->godot_string_pad_decimals(&_godot_string, digits));
}
String String::pad_zeros(int digits) const {
String new_string;
new_string._godot_string = godot::api->godot_string_pad_zeros(&_godot_string, digits);
return new_string;
return String(godot::api->godot_string_pad_zeros(&_godot_string, digits));
}
String String::percent_decode() const {
String new_string;
new_string._godot_string = godot::api->godot_string_percent_decode(&_godot_string);
return new_string;
return String(godot::api->godot_string_percent_decode(&_godot_string));
}
String String::percent_encode() const {
String new_string;
new_string._godot_string = godot::api->godot_string_percent_encode(&_godot_string);
return new_string;
return String(godot::api->godot_string_percent_encode(&_godot_string));
}
String String::plus_file(String file) const {
String new_string;
new_string._godot_string = godot::api->godot_string_plus_file(&_godot_string, &file._godot_string);
return new_string;
return String(godot::api->godot_string_plus_file(&_godot_string, &file._godot_string));
}
String String::replace(String p_key, String p_with) const {
String new_string;
new_string._godot_string = godot::api->godot_string_replace(&_godot_string, p_key._godot_string, p_with._godot_string);
return new_string;
return String(godot::api->godot_string_replace(&_godot_string, p_key._godot_string, p_with._godot_string));
}
String String::replacen(String what, String forwhat) const {
String new_string;
new_string._godot_string = godot::api->godot_string_replacen(&_godot_string, what._godot_string, forwhat._godot_string);
return new_string;
return String(godot::api->godot_string_replacen(&_godot_string, what._godot_string, forwhat._godot_string));
}
int String::rfind(String p_what, int p_from) const {
@ -452,10 +377,7 @@ int String::rfindn(String p_what, int p_from) const {
}
String String::right(int position) const {
String new_string;
new_string._godot_string = godot::api->godot_string_right(&_godot_string, position);
return new_string;
return String(godot::api->godot_string_right(&_godot_string, position));
}
PoolByteArray String::sha256_buffer() const {
@ -465,28 +387,28 @@ PoolByteArray String::sha256_buffer() const {
}
String String::sha256_text() const {
String new_string;
new_string._godot_string = godot::api->godot_string_sha256_text(&_godot_string);
return new_string;
return String(godot::api->godot_string_sha256_text(&_godot_string));
}
float String::similarity(String text) const {
return godot::api->godot_string_similarity(&_godot_string, &text._godot_string);
}
// TODO Suport allow_empty
PoolStringArray String::split(String divisor, bool /*allow_empty*/) const {
godot_array arr = godot::api->godot_string_split(&_godot_string, &divisor._godot_string);
return *(Array *)&arr;
}
// TODO Suport allow_empty
PoolIntArray String::split_ints(String divisor, bool /*allow_empty*/) const {
godot_array arr = godot::api->godot_string_split_floats(&_godot_string, &divisor._godot_string);
return *(Array *)&arr;
}
// TODO Suport allow_empty
PoolRealArray String::split_floats(String divisor, bool /*allow_empty*/) const {
godot_array arr = godot::api->godot_string_split_floats(&_godot_string, &divisor._godot_string);
@ -494,17 +416,11 @@ PoolRealArray String::split_floats(String divisor, bool /*allow_empty*/) const {
}
String String::strip_edges(bool left, bool right) const {
String new_string;
new_string._godot_string = godot::api->godot_string_strip_edges(&_godot_string, left, right);
return new_string;
return String(godot::api->godot_string_strip_edges(&_godot_string, left, right));
}
String String::substr(int from, int len) const {
String new_string;
new_string._godot_string = godot::api->godot_string_substr(&_godot_string, from, len);
return new_string;
return String(godot::api->godot_string_substr(&_godot_string, from, len));
}
float String::to_float() const {
@ -516,31 +432,19 @@ int64_t String::to_int() const {
}
String String::to_lower() const {
String new_string;
new_string._godot_string = godot::api->godot_string_to_lower(&_godot_string);
return new_string;
return String(godot::api->godot_string_to_lower(&_godot_string));
}
String String::to_upper() const {
String new_string;
new_string._godot_string = godot::api->godot_string_to_upper(&_godot_string);
return new_string;
return String(godot::api->godot_string_to_upper(&_godot_string));
}
String String::xml_escape() const {
String new_string;
new_string._godot_string = godot::api->godot_string_xml_escape(&_godot_string);
return new_string;
return String(godot::api->godot_string_xml_escape(&_godot_string));
}
String String::xml_unescape() const {
String new_string;
new_string._godot_string = godot::api->godot_string_xml_unescape(&_godot_string);
return new_string;
return String(godot::api->godot_string_xml_unescape(&_godot_string));
}
signed char String::casecmp_to(String p_str) const {

View File

@ -261,14 +261,12 @@ Variant::operator RID() const {
}
Variant::operator Dictionary() const {
Dictionary ret;
*(godot_dictionary *)&ret = godot::api->godot_variant_as_dictionary(&_godot_variant);
Dictionary ret(godot::api->godot_variant_as_dictionary(&_godot_variant));
return ret;
}
Variant::operator Array() const {
Array ret;
*(godot_array *)&ret = godot::api->godot_variant_as_array(&_godot_variant);
Array ret(godot::api->godot_variant_as_array(&_godot_variant));
return ret;
}

View File

@ -67,17 +67,12 @@ void Vector3::rotate(const Vector3 &p_axis, real_t p_phi) {
*this = Basis(p_axis, p_phi).xform(*this);
}
// this is ugly as well, but hey, I'm a simple man
#define _ugly_stepify(val, step) (step != 0 ? ::floor(val / step + 0.5) * step : val)
void Vector3::snap(real_t p_val) {
x = _ugly_stepify(x, p_val);
y = _ugly_stepify(y, p_val);
z = _ugly_stepify(z, p_val);
x = Math::stepify(x, p_val);
y = Math::stepify(y, p_val);
z = Math::stepify(z, p_val);
}
#undef _ugly_stepify
Vector3::operator String() const {
return String::num(x) + ", " + String::num(y) + ", " + String::num(z);
}