This commit is contained in:
Dante
2026-05-21 23:40:20 -07:00
parent 3e2915dff7
commit 877a69d844
5737 changed files with 29796 additions and 1589684 deletions

1
Kha/.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
* -text

View File

@ -0,0 +1,35 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Execution Environment:**
- Host system (where you compile your code):
- Target system (where you run your code):
- IDE used (if any):
- Kha revision:
- Kha build output (Using Kha...):
- Application output (if it runs):
**Additional context**
Add any other context about the problem here.

View File

@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

2
Kha/.github/funding.yml vendored Normal file
View File

@ -0,0 +1,2 @@
github: RobDangerous
patreon: RobDangerous

View File

@ -0,0 +1,29 @@
name: Android (OpenGL)
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'oracle'
java-version: '17'
- name: Get DLC
run: ./get_dlc
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Setup Node.js
run: nodejs_bin/copysysbin.sh
- name: Compile
run: nodejs_bin/node make.js android -g opengl --kha . --from Tests/Empty --arch arm64 --compile

View File

@ -0,0 +1,29 @@
name: Android (Vulkan)
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
distribution: 'oracle'
java-version: '17'
- name: Get DLC
run: ./get_dlc
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Setup Node.js
run: nodejs_bin/copysysbin.sh
- name: Compile
run: nodejs_bin/node make.js android -g vulkan --kha . --from Tests/Empty --arch arm64 --compile

52
Kha/.github/workflows/dox.yml vendored Normal file
View File

@ -0,0 +1,52 @@
name: dox
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: krdlab/setup-haxe@v1
with:
haxe-version: 4.2.3
- uses: actions/checkout@v1
- name: Install dox
run: haxelib install dox
- name: Get Submodules
run: git submodule update --init --recursive
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Setup Node.js
run: nodejs_bin/copysysbin.sh
- name: Create documentation
run: nodejs_bin/node make.js empty --kha . --from Tests/Empty
- name: Clone website
run: git clone -b gh-pages https://github.com/Kode/Kha.git Kha-pages
- name: Remove old documentation
run: rm -r Kha-pages/api
- name: Copy new documentation
run: cp -R build/pages Kha-pages/api
- name: Set name
run: git config --global user.name "Robbot"
- name: Set email
run: git config --global user.email "robbot2019@robdangero.us"
- name: Add documentation
run: git -C Kha-pages add .
- name: Commit documentation
id: commit
continue-on-error: true
run: git -C Kha-pages commit -m "Update documentation to $GITHUB_SHA."
- name: Push documentation
if: steps.commit.outcome == 'success'
continue-on-error: true
run: git -C Kha-pages push https://Kode-Robbot:$ROBBOT_PASS@github.com/Kode/Kha.git gh-pages
env:
ROBBOT_PASS: ${{ secrets.ROBBOT_PASS }}

25
Kha/.github/workflows/html5.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: HTML5
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Get DLC
run: ./get_dlc
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Setup Node.js
run: nodejs_bin/copysysbin.sh
- name: Compile
run: nodejs_bin/node make.js html5 --kha . --from Tests/Empty

25
Kha/.github/workflows/html5worker.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: HTML5 Worker
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Get DLC
run: ./get_dlc
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Setup Node.js
run: nodejs_bin/copysysbin.sh
- name: Compile
run: nodejs_bin/node make.js html5worker --kha . --from Tests/Empty

25
Kha/.github/workflows/ios-metal.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: iOS (Metal)
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: macOS-latest
steps:
- uses: actions/checkout@v1
- name: Get DLC
run: ./get_dlc
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Setup Node.js
run: nodejs_bin/copysysbin.sh
- name: Compile
run: nodejs_bin/node make.js ios -g metal --kha . --from Tests/Empty --nosigning --compile

25
Kha/.github/workflows/ios-opengl.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: iOS (OpenGL)
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: macOS-latest
steps:
- uses: actions/checkout@v1
- name: Get DLC
run: ./get_dlc
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Setup Node.js
run: nodejs_bin/copysysbin.sh
- name: Compile
run: nodejs_bin/node make.js ios -g opengl --kha . --from Tests/Empty --nosigning --compile

25
Kha/.github/workflows/java.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: Java
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Get DLC
run: ./get_dlc
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Setup Node.js
run: nodejs_bin/copysysbin.sh
- name: Compile
run: nodejs_bin/node make.js java --kha . --from Tests/Empty

25
Kha/.github/workflows/krom.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: Krom
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Get DLC
run: ./get_dlc
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Setup Node.js
run: nodejs_bin/copysysbin.sh
- name: Compile
run: nodejs_bin/node make.js krom --kha . --from Tests/Empty

View File

@ -0,0 +1,29 @@
name: Linux (HL, OpenGL)
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Apt Update
run: sudo apt-get update
- name: Apt Install
run: sudo apt-get install libasound2-dev libxinerama-dev libxrandr-dev libgl1-mesa-dev libxi-dev libxcursor-dev libudev-dev libwayland-dev wayland-protocols libxkbcommon-dev ninja-build --yes --quiet
- name: Get DLC
run: ./get_dlc
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Setup Node.js
run: nodejs_bin/copysysbin.sh
- name: Compile
run: nodejs_bin/node make.js linux-hl -g opengl --kha . --from Tests/Empty --compile

29
Kha/.github/workflows/linux-opengl.yml vendored Normal file
View File

@ -0,0 +1,29 @@
name: Linux (OpenGL)
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Apt Update
run: sudo apt-get update
- name: Apt Install
run: sudo apt-get install libasound2-dev libxinerama-dev libxrandr-dev libgl1-mesa-dev libxi-dev libxcursor-dev libudev-dev libwayland-dev wayland-protocols libxkbcommon-dev ninja-build --yes --quiet
- name: Get DLC
run: ./get_dlc
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Setup Node.js
run: nodejs_bin/copysysbin.sh
- name: Compile
run: nodejs_bin/node make.js -g opengl --kha . --from Tests/Empty --compile

33
Kha/.github/workflows/linux-vulkan.yml vendored Normal file
View File

@ -0,0 +1,33 @@
name: Linux (Vulkan)
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Get LunarG key
run: wget -qO- https://packages.lunarg.com/lunarg-signing-key-pub.asc | sudo tee /etc/apt/trusted.gpg.d/lunarg.asc
- name: Get LunarG apt sources
run: sudo wget -qO /etc/apt/sources.list.d/lunarg-vulkan-noble.list http://packages.lunarg.com/vulkan/lunarg-vulkan-noble.list
- name: Apt Update
run: sudo apt update
- name: Apt Install
run: sudo apt install libasound2-dev libxinerama-dev libxrandr-dev libgl1-mesa-dev libxi-dev libxcursor-dev libudev-dev vulkan-sdk libwayland-dev wayland-protocols libxkbcommon-dev ninja-build --yes --quiet
- name: Get DLC
run: ./get_dlc
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Setup Node.js
run: nodejs_bin/copysysbin.sh
- name: Compile
run: nodejs_bin/node make.js -g vulkan --kha . --from Tests/Empty --compile

View File

@ -0,0 +1,25 @@
name: macOS (HL, Metal)
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: macOS-latest
steps:
- uses: actions/checkout@v1
- name: Get DLC
run: ./get_dlc
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Setup Node.js
run: nodejs_bin/copysysbin.sh
- name: Compile
run: nodejs_bin/node make.js osx-hl -g metal --kha . --from Tests/Empty --compile

25
Kha/.github/workflows/macos-metal.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: macOS (Metal)
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: macOS-latest
steps:
- uses: actions/checkout@v1
- name: Get DLC
run: ./get_dlc
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Setup Node.js
run: nodejs_bin/copysysbin.sh
- name: Compile
run: nodejs_bin/node make.js -g metal --kha . --from Tests/Empty --compile

25
Kha/.github/workflows/macos-opengl.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: macOS (OpenGL)
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: macOS-latest
steps:
- uses: actions/checkout@v1
- name: Get DLC
run: ./get_dlc
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Setup Node.js
run: nodejs_bin/copysysbin.sh
- name: Compile
run: nodejs_bin/node make.js -g opengl --kha . --from Tests/Empty --compile

25
Kha/.github/workflows/node.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: Node.js
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Get DLC
run: ./get_dlc
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Setup Node.js
run: nodejs_bin/copysysbin.sh
- name: Compile
run: nodejs_bin/node make.js node --kha . --from Tests/Empty

23
Kha/.github/workflows/uwp.yml vendored Normal file
View File

@ -0,0 +1,23 @@
name: UWP
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v1
- name: Get DLC
run: .\get_dlc.bat
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Compile
run: .\nodejs_bin\node.exe make.js windowsapp -v vs2022 --kha . --from Tests/Empty --compile

View File

@ -0,0 +1,23 @@
name: Windows (Direct3D 11)
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v1
- name: Get DLC
run: .\get_dlc.bat
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Compile
run: .\nodejs_bin\node.exe make.js -v vs2022 -g direct3d11 --kha . --from Tests/Empty --compile

View File

@ -0,0 +1,23 @@
name: Windows (Direct3D 12)
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v1
- name: Get DLC
run: .\get_dlc.bat
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Compile
run: .\nodejs_bin\node.exe make.js -v vs2022 -g direct3d12 --kha . --from Tests/Empty --compile

View File

@ -0,0 +1,23 @@
name: Windows (HL, Direct3D 11)
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v1
- name: Get DLC
run: .\get_dlc.bat
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Compile
run: .\nodejs_bin\node.exe make.js windows-hl -v vs2022 -g direct3d11 --kha . --from Tests/Empty --compile

View File

@ -0,0 +1,23 @@
name: Windows (OpenGL)
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v1
- name: Get DLC
run: .\get_dlc.bat
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Compile
run: .\nodejs_bin\node.exe make.js -v vs2022 -g opengl --kha . --from Tests/Empty --compile

View File

@ -0,0 +1,30 @@
name: Windows (Vulkan)
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v1
- name: Setup Vulkan
run: |
Invoke-WebRequest -Uri "https://sdk.lunarg.com/sdk/download/1.3.275.0/windows/VulkanSDK-1.3.275.0-Installer.exe" -OutFile VulkanSDK.exe
$installer = Start-Process -FilePath VulkanSDK.exe -Wait -PassThru -ArgumentList @("--da", "--al", "-c", "in");
$installer.WaitForExit();
- name: Get DLC
run: .\get_dlc.bat
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Compile
run: .\nodejs_bin\node.exe make.js -v vs2022 -g vulkan --kha . --from Tests/Empty --compile
env:
VULKAN_SDK: C:\VulkanSDK\1.3.275.0

23
Kha/.github/workflows/wpf.yml vendored Normal file
View File

@ -0,0 +1,23 @@
name: WPF
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v1
- name: Get DLC
run: .\get_dlc.bat
- name: Get Node.js
run: git clone https://github.com/Kode/nodejs_bin.git --depth 1
- name: Compile
run: .\nodejs_bin\node.exe make.js wpf --kha . --from Tests/Empty

3
Kha/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
.DS_Store
/build
/Tests/Empty/korefile.js

37
Kha/.gitmodules vendored Normal file
View File

@ -0,0 +1,37 @@
[submodule "Tools/khamake"]
path = Tools/khamake
url = https://github.com/Kode/khamake.git
branch = main
[submodule "Backends/Kore-hxcpp/khacpp"]
path = Backends/Kore-hxcpp/khacpp
url = https://github.com/Kode/khacpp.git
branch = main
[submodule "Kore"]
path = Kore
url = https://github.com/Kode/Kore.git
branch = v2
[submodule "Tools/linux_x64"]
path = Tools/linux_x64
url = https://github.com/Kode/KhaTools_linux_x64.git
branch = main
shallow = true
[submodule "Tools/linux_arm64"]
path = Tools/linux_arm64
url = https://github.com/Kode/KhaTools_linux_arm64.git
branch = main
shallow = true
[submodule "Tools/windows_x64"]
path = Tools/windows_x64
url = https://github.com/Kode/KhaTools_windows_x64.git
branch = main
shallow = true
[submodule "Tools/macos_arm64"]
path = Tools/macos_arm64
url = https://github.com/Kode/KhaTools_macos_arm64.git
branch = main
shallow = true
[submodule "Tools/macos_x64"]
path = Tools/macos_x64
url = https://github.com/Kode/KhaTools_macos_x64.git
branch = main
shallow = true

View File

@ -0,0 +1,22 @@
package kha.graphics4;
import haxe.io.Bytes;
import kha.Blob;
class ComputeShader {
public function new(sources: Array<Blob>, files: Array<String>) {
}
public function delete(): Void {
}
public function getConstantLocation(name: String): ConstantLocation {
return null;
}
public function getTextureUnit(name: String): TextureUnit {
return null;
}
}

View File

@ -0,0 +1,24 @@
package kha.graphics4;
class ShaderStorageBuffer {
var data: Array<Int>;
var myCount: Int;
public function new(indexCount: Int, type: VertexData) {
myCount = indexCount;
data = new Array<Int>();
data[myCount - 1] = 0;
}
public function delete(): Void {}
public function lock(): Array<Int> {
return data;
}
public function unlock(): Void {}
public function count(): Int {
return myCount;
}
}

View File

@ -0,0 +1,22 @@
package kha.graphics4;
import haxe.io.Bytes;
import kha.Blob;
class ComputeShader {
public function new(sources: Array<Blob>, files: Array<String>) {
}
public function delete(): Void {
}
public function getConstantLocation(name: String): ConstantLocation {
return null;
}
public function getTextureUnit(name: String): TextureUnit {
return null;
}
}

View File

@ -0,0 +1,24 @@
package kha.graphics4;
class ShaderStorageBuffer {
var data: Array<Int>;
var myCount: Int;
public function new(indexCount: Int, type: VertexData) {
myCount = indexCount;
data = new Array<Int>();
data[myCount - 1] = 0;
}
public function delete(): Void {}
public function lock(): Array<Int> {
return data;
}
public function unlock(): Void {}
public function count(): Int {
return myCount;
}
}

View File

@ -2,9 +2,11 @@ package kha.html5worker;
import kha.arrays.Float32Array; import kha.arrays.Float32Array;
import kha.Canvas; import kha.Canvas;
import kha.graphics4.ComputeShader;
import kha.graphics4.IndexBuffer; import kha.graphics4.IndexBuffer;
import kha.graphics4.MipMapFilter; import kha.graphics4.MipMapFilter;
import kha.graphics4.PipelineState; import kha.graphics4.PipelineState;
import kha.graphics4.ShaderStorageBuffer;
import kha.graphics4.TextureAddressing; import kha.graphics4.TextureAddressing;
import kha.graphics4.TextureFilter; import kha.graphics4.TextureFilter;
import kha.graphics4.Usage; import kha.graphics4.Usage;
@ -342,4 +344,16 @@ class Graphics implements kha.graphics4.Graphics {
public function maxBoundTextures(): Int { public function maxBoundTextures(): Int {
return 16; return 16;
} }
public function setShaderStorageBuffer(buffer: ShaderStorageBuffer, index: Int) {
}
public function setComputeShader(shader: ComputeShader) {
}
public function compute(x: Int, y: Int, z: Int) {
}
} }

View File

@ -27,7 +27,7 @@ class CanvasImage extends Image {
var g2canvas: CanvasGraphics = null; var g2canvas: CanvasGraphics = null;
public static function init() { public static function init() {
var canvas: Dynamic = Browser.document.createElement("canvas"); final canvas = Browser.document.createCanvasElement();
if (canvas != null) { if (canvas != null) {
context = canvas.getContext("2d"); context = canvas.getContext("2d");
canvas.width = 2048; canvas.width = 2048;
@ -56,7 +56,7 @@ class CanvasImage extends Image {
override function get_g2(): kha.graphics2.Graphics { override function get_g2(): kha.graphics2.Graphics {
if (g2canvas == null) { if (g2canvas == null) {
var canvas: Dynamic = Browser.document.createElement("canvas"); final canvas = Browser.document.createCanvasElement();
image = canvas; image = canvas;
var context = canvas.getContext("2d"); var context = canvas.getContext("2d");
canvas.width = width; canvas.width = width;

View File

@ -66,7 +66,7 @@ class Display {
public var pixelsPerInch(get, never): Int; public var pixelsPerInch(get, never): Int;
function get_pixelsPerInch(): Int { function get_pixelsPerInch(): Int {
var dpiElement = Browser.document.createElement("div"); final dpiElement = Browser.document.createDivElement();
dpiElement.style.position = "absolute"; dpiElement.style.position = "absolute";
dpiElement.style.width = "1in"; dpiElement.style.width = "1in";
dpiElement.style.height = "1in"; dpiElement.style.height = "1in";

View File

@ -1,5 +1,6 @@
package kha; package kha;
import js.html.FileReader;
import haxe.io.Bytes; import haxe.io.Bytes;
import js.html.ImageElement; import js.html.ImageElement;
import js.html.CanvasElement; import js.html.CanvasElement;
@ -90,11 +91,29 @@ class Image implements Canvas implements Resource {
public static function fromEncodedBytes(bytes: Bytes, fileExtention: String, doneCallback: Image->Void, errorCallback: String->Void, public static function fromEncodedBytes(bytes: Bytes, fileExtention: String, doneCallback: Image->Void, errorCallback: String->Void,
readable: Bool = false): Void { readable: Bool = false): Void {
var dataUrl = "data:image;base64," + haxe.crypto.Base64.encode(bytes); final mime = switch fileExtention {
var imageElement = cast(js.Browser.document.createElement("img"), ImageElement); case "jpg": 'image/jpeg';
imageElement.onload = function() doneCallback(fromImage(imageElement, readable)); case ext: 'image/$ext';
imageElement.onerror = function() errorCallback("Image was not created"); }
imageElement.src = dataUrl; bufferToBase64(cast bytes.getData(), dataUrl -> {
final imageElement = js.Browser.document.createImageElement();
imageElement.onload = () -> doneCallback(fromImage(imageElement, readable));
imageElement.onerror = () -> errorCallback("Image was not created");
imageElement.src = 'data:$mime;base64,$dataUrl';
}, () -> {
errorCallback("Image was not created");
});
}
static function bufferToBase64(buffer:js.lib.Uint8Array, onLoad:(base64:String)->Void, onError:()->Void) {
final reader = new FileReader();
reader.onload = () -> {
final result:String = reader.result;
// remove the `data:application/octet-stream;base64,` part from the start
onLoad(result.substr(result.indexOf(',') + 1));
}
reader.onerror = () -> onError();
reader.readAsDataURL(new js.html.Blob([buffer]));
} }
public static function fromVideo(video: kha.Video): Image { public static function fromVideo(video: kha.Video): Image {

View File

@ -32,7 +32,7 @@ class LoaderImpl {
}, failed); }, failed);
} }
else { else {
var img: ImageElement = cast Browser.document.createElement("img"); final img = Browser.document.createImageElement();
img.onerror = function(event: Dynamic) failed({url: desc.files[0], error: event}); img.onerror = function(event: Dynamic) failed({url: desc.files[0], error: event});
img.onload = function(event: Dynamic) done(Image.fromImage(img, readable)); img.onload = function(event: Dynamic) done(Image.fromImage(img, readable));
img.crossOrigin = ""; img.crossOrigin = "";
@ -159,9 +159,9 @@ class LoaderImpl {
} }
public static function loadRemote(desc: Dynamic, done: Blob->Void, failed: AssetError->Void) { public static function loadRemote(desc: Dynamic, done: Blob->Void, failed: AssetError->Void) {
var request = untyped new XMLHttpRequest(); var request = new XMLHttpRequest();
request.open("GET", desc.files[0], true); request.open("GET", desc.files[0], true);
request.responseType = "arraybuffer"; request.responseType = ARRAYBUFFER;
request.onreadystatechange = function() { request.onreadystatechange = function() {
if (request.readyState != 4) if (request.readyState != 4)
@ -174,12 +174,6 @@ class LoaderImpl {
var byteArray: Dynamic = Syntax.code("new Uint8Array(arrayBuffer)"); var byteArray: Dynamic = Syntax.code("new Uint8Array(arrayBuffer)");
bytes = Bytes.ofData(byteArray); bytes = Bytes.ofData(byteArray);
} }
else if (request.responseBody != null) {
var data: Dynamic = untyped Syntax.code("VBArray(request.responseBody).toArray()");
bytes = Bytes.alloc(data.length);
for (i in 0...data.length)
bytes.set(i, data[i]);
}
else { else {
failed({url: desc.files[0]}); failed({url: desc.files[0]});
return; return;

View File

@ -6,8 +6,10 @@ import js.html.CanvasElement;
import js.html.ClipboardEvent; import js.html.ClipboardEvent;
import js.html.DeviceMotionEvent; import js.html.DeviceMotionEvent;
import js.html.DeviceOrientationEvent; import js.html.DeviceOrientationEvent;
import js.html.DragEvent;
import js.html.KeyboardEvent; import js.html.KeyboardEvent;
import js.html.MouseEvent; import js.html.MouseEvent;
import js.html.PointerEvent;
import js.html.Touch; import js.html.Touch;
import js.html.TouchEvent; import js.html.TouchEvent;
import js.html.WebSocket; import js.html.WebSocket;
@ -213,6 +215,7 @@ class SystemImpl {
} }
public static function vibrate(ms: Int): Void { public static function vibrate(ms: Int): Void {
if (Browser.navigator.vibrate == null) return;
Browser.navigator.vibrate(ms); Browser.navigator.vibrate(ms);
} }
@ -227,7 +230,7 @@ class SystemImpl {
} }
static inline var maxGamepads: Int = 4; static inline var maxGamepads: Int = 4;
public static var frame: Framebuffer; static var frame: Framebuffer;
static var keyboard: Keyboard = null; static var keyboard: Keyboard = null;
static var mouse: kha.input.Mouse; static var mouse: kha.input.Mouse;
static var surface: Surface; static var surface: Surface;
@ -311,14 +314,14 @@ class SystemImpl {
} }
public static function copyToClipboard(text: String) { public static function copyToClipboard(text: String) {
var textArea = Browser.document.createElement("textarea"); var textArea = Browser.document.createTextAreaElement();
untyped textArea.value = text; textArea.value = text;
textArea.style.top = "0"; textArea.style.top = "0";
textArea.style.left = "0"; textArea.style.left = "0";
textArea.style.position = "fixed"; textArea.style.position = "fixed";
Browser.document.body.appendChild(textArea); Browser.document.body.appendChild(textArea);
textArea.focus(); textArea.focus();
untyped textArea.select(); textArea.select();
try { try {
Browser.document.execCommand("copy"); Browser.document.execCommand("copy");
} }
@ -388,8 +391,7 @@ class SystemImpl {
{ {
alpha: false, alpha: false,
antialias: options.framebuffer.samplesPerPixel > 1, antialias: options.framebuffer.samplesPerPixel > 1,
stencil: true, stencil: true
xrCompatible: true
}); // preserveDrawingBuffer: true } ); Warning: preserveDrawingBuffer can cause huge performance issues on mobile browsers }); // preserveDrawingBuffer: true } ); Warning: preserveDrawingBuffer can cause huge performance issues on mobile browsers
SystemImpl.gl.pixelStorei(GL.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1); SystemImpl.gl.pixelStorei(GL.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
@ -418,8 +420,7 @@ class SystemImpl {
{ {
alpha: false, alpha: false,
antialias: options.framebuffer.samplesPerPixel > 1, antialias: options.framebuffer.samplesPerPixel > 1,
stencil: true, stencil: true
xrCompatible: true
}); // preserveDrawingBuffer: true } ); WARNING: preserveDrawingBuffer causes huge performance issues (on mobile browser)! }); // preserveDrawingBuffer: true } ); WARNING: preserveDrawingBuffer causes huge performance issues (on mobile browser)!
SystemImpl.gl.pixelStorei(GL.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1); SystemImpl.gl.pixelStorei(GL.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
SystemImpl.gl.getExtension("OES_texture_float"); SystemImpl.gl.getExtension("OES_texture_float");
@ -462,7 +463,7 @@ class SystemImpl {
} }
// canvas.getContext("2d").scale(transform, transform); // canvas.getContext("2d").scale(transform, transform);
if (!mobile && kha.audio2.Audio._init()) { if ((!mobile || options.audio.allowMobileWebAudio) && kha.audio2.Audio._init()) {
SystemImpl._hasWebAudio = true; SystemImpl._hasWebAudio = true;
kha.audio2.Audio1._init(); kha.audio2.Audio1._init();
} }
@ -482,7 +483,7 @@ class SystemImpl {
canvas.focus(); canvas.focus();
#if kha_disable_context_menu #if kha_disable_context_menu
canvas.oncontextmenu = function(event: Dynamic) { canvas.oncontextmenu = function(event: PointerEvent) {
event.stopPropagation(); event.stopPropagation();
event.preventDefault(); event.preventDefault();
} }
@ -505,12 +506,12 @@ class SystemImpl {
canvas.addEventListener("touchend", touchUp, false); canvas.addEventListener("touchend", touchUp, false);
canvas.addEventListener("touchmove", touchMove, false); canvas.addEventListener("touchmove", touchMove, false);
canvas.addEventListener("touchcancel", touchCancel, false); canvas.addEventListener("touchcancel", touchCancel, false);
// prevent dragging canvas like images in Firefox
canvas.addEventListener("dragstart", (e: DragEvent) -> e.preventDefault());
// prevent dropping local files on page and replacing page with them
Browser.document.addEventListener("dragover", (e: DragEvent) -> e.preventDefault());
Browser.document.addEventListener("dragover", function(event) { Browser.document.addEventListener("drop", function(event: DragEvent) {
event.preventDefault();
});
Browser.document.addEventListener("drop", function(event: js.html.DragEvent) {
event.preventDefault(); event.preventDefault();
if (event.dataTransfer != null && event.dataTransfer.files != null) { if (event.dataTransfer != null && event.dataTransfer.files != null) {
for (file in event.dataTransfer.files) { for (file in event.dataTransfer.files) {
@ -531,14 +532,7 @@ class SystemImpl {
static function initAnimate(callback: Window->Void) { static function initAnimate(callback: Window->Void) {
var canvas: CanvasElement = getCanvasElement(); var canvas: CanvasElement = getCanvasElement();
var window: Dynamic = Browser.window; final window = Browser.window;
var requestAnimationFrame = window.requestAnimationFrame;
if (requestAnimationFrame == null)
requestAnimationFrame = window.mozRequestAnimationFrame;
if (requestAnimationFrame == null)
requestAnimationFrame = window.webkitRequestAnimationFrame;
if (requestAnimationFrame == null)
requestAnimationFrame = window.msRequestAnimationFrame;
var isRefreshRateDetectionActive = false; var isRefreshRateDetectionActive = false;
var lastTimestamp = 0.0; var lastTimestamp = 0.0;
@ -549,16 +543,7 @@ class SystemImpl {
]; ];
function animate(timestamp) { function animate(timestamp) {
if (untyped Browser.window._khaSkipWindowRender == true) { window.requestAnimationFrame(animate);
if (requestAnimationFrame != null)
requestAnimationFrame(animate);
return;
}
if (requestAnimationFrame == null)
Browser.window.setTimeout(animate, 1000.0 / 60.0);
else
requestAnimationFrame(animate);
var sysGamepads = getGamepads(); var sysGamepads = getGamepads();
if (sysGamepads != null) { if (sysGamepads != null) {
@ -639,64 +624,38 @@ class SystemImpl {
}, 500); }, 500);
Scheduler.start(); Scheduler.start();
requestAnimationFrame(animate); window.requestAnimationFrame(animate);
callback(SystemImpl.window); callback(SystemImpl.window);
} }
public static function lockMouse(): Void { public static function lockMouse(): Void {
untyped if (SystemImpl.khanvas.requestPointerLock) { if (SystemImpl.khanvas.requestPointerLock != null) {
SystemImpl.khanvas.requestPointerLock(); SystemImpl.khanvas.requestPointerLock();
} }
else if (SystemImpl.khanvas.mozRequestPointerLock) {
SystemImpl.khanvas.mozRequestPointerLock();
}
else if (SystemImpl.khanvas.webkitRequestPointerLock) {
SystemImpl.khanvas.webkitRequestPointerLock();
}
} }
public static function unlockMouse(): Void { public static function unlockMouse(): Void {
untyped if (document.exitPointerLock) { if (Browser.document.exitPointerLock != null) {
document.exitPointerLock(); Browser.document.exitPointerLock();
}
else if (document.mozExitPointerLock) {
document.mozExitPointerLock();
}
else if (document.webkitExitPointerLock) {
document.webkitExitPointerLock();
} }
} }
public static function canLockMouse(): Bool { public static function canLockMouse(): Bool {
return Syntax.code("'pointerLockElement' in document || return Syntax.code("'pointerLockElement' in document");
'mozPointerLockElement' in document ||
'webkitPointerLockElement' in document");
} }
public static function isMouseLocked(): Bool { public static function isMouseLocked(): Bool {
return Syntax.code("document.pointerLockElement === kha_SystemImpl.khanvas || return Syntax.code("document.pointerLockElement === kha_SystemImpl.khanvas");
document.mozPointerLockElement === kha_SystemImpl.khanvas ||
document.webkitPointerLockElement === kha_SystemImpl.khanvas");
} }
public static function notifyOfMouseLockChange(func: Void->Void, error: Void->Void): Void { public static function notifyOfMouseLockChange(func: Void->Void, error: Void->Void): Void {
js.Browser.document.addEventListener("pointerlockchange", func, false); js.Browser.document.addEventListener("pointerlockchange", func, false);
js.Browser.document.addEventListener("mozpointerlockchange", func, false);
js.Browser.document.addEventListener("webkitpointerlockchange", func, false);
js.Browser.document.addEventListener("pointerlockerror", error, false); js.Browser.document.addEventListener("pointerlockerror", error, false);
js.Browser.document.addEventListener("mozpointerlockerror", error, false);
js.Browser.document.addEventListener("webkitpointerlockerror", error, false);
} }
public static function removeFromMouseLockChange(func: Void->Void, error: Void->Void): Void { public static function removeFromMouseLockChange(func: Void->Void, error: Void->Void): Void {
js.Browser.document.removeEventListener("pointerlockchange", func, false); js.Browser.document.removeEventListener("pointerlockchange", func, false);
js.Browser.document.removeEventListener("mozpointerlockchange", func, false);
js.Browser.document.removeEventListener("webkitpointerlockchange", func, false);
js.Browser.document.removeEventListener("pointerlockerror", error, false); js.Browser.document.removeEventListener("pointerlockerror", error, false);
js.Browser.document.removeEventListener("mozpointerlockerror", error, false);
js.Browser.document.removeEventListener("webkitpointerlockerror", error, false);
} }
static function setMouseXY(event: MouseEvent): Void { static function setMouseXY(event: MouseEvent): Void {
@ -902,13 +861,6 @@ class SystemImpl {
var movementX = event.movementX; var movementX = event.movementX;
var movementY = event.movementY; var movementY = event.movementY;
if (event.movementX == null) {
movementX = (untyped event.mozMovementX != null) ? untyped event.mozMovementX : ((untyped event.webkitMovementX != null) ? untyped event.webkitMovementX : (mouseX
- lastMouseX));
movementY = (untyped event.mozMovementY != null) ? untyped event.mozMovementY : ((untyped event.webkitMovementY != null) ? untyped event.webkitMovementY : (mouseY
- lastMouseY));
}
// this ensures same behaviour across browser until they fix it // this ensures same behaviour across browser until they fix it
if (firefox) { if (firefox) {
movementX = Std.int(movementX * Browser.window.devicePixelRatio); movementX = Std.int(movementX * Browser.window.devicePixelRatio);
@ -956,7 +908,9 @@ class SystemImpl {
} }
setTouchXY(touch); setTouchXY(touch);
if (!Surface.listenedEventsBefore) {
mouse.sendDownEvent(0, 0, touchX, touchY); mouse.sendDownEvent(0, 0, touchX, touchY);
}
surface.sendTouchStartEvent(id, touchX, touchY); surface.sendTouchStartEvent(id, touchX, touchY);
if (index == 0) { if (index == 0) {
lastFirstTouchX = touchX; lastFirstTouchX = touchX;
@ -979,7 +933,9 @@ class SystemImpl {
} }
setTouchXY(touch); setTouchXY(touch);
if (!Surface.listenedEventsBefore) {
mouse.sendUpEvent(0, 0, touchX, touchY); mouse.sendUpEvent(0, 0, touchX, touchY);
}
surface.sendTouchEndEvent(id, touchX, touchY); surface.sendTouchEndEvent(id, touchX, touchY);
} }
insideInputEvent = false; insideInputEvent = false;
@ -998,8 +954,10 @@ class SystemImpl {
lastFirstTouchX = touchX; lastFirstTouchX = touchX;
lastFirstTouchY = touchY; lastFirstTouchY = touchY;
if (!Surface.listenedEventsBefore) {
mouse.sendMoveEvent(0, touchX, touchY, movementX, movementY); mouse.sendMoveEvent(0, touchX, touchY, movementX, movementY);
} }
}
var id = touch.identifier; var id = touch.identifier;
if (ios) if (ios)
id = iosTouchs.indexOf(id); id = iosTouchs.indexOf(id);
@ -1020,7 +978,9 @@ class SystemImpl {
id = iosTouchs.indexOf(id); id = iosTouchs.indexOf(id);
setTouchXY(touch); setTouchXY(touch);
if (!Surface.listenedEventsBefore) {
mouse.sendUpEvent(0, 0, touchX, touchY); mouse.sendUpEvent(0, 0, touchX, touchY);
}
surface.sendTouchEndEvent(id, touchX, touchY); surface.sendTouchEndEvent(id, touchX, touchY);
} }
iosTouchs = []; iosTouchs = [];
@ -1311,15 +1271,45 @@ class SystemImpl {
return "unknown"; return "unknown";
} }
public static function setGamepadRumble(index: Int, leftAmount: Float, rightAmount: Float) {} public static function setGamepadRumble(index: Int, leftAmount: Float, rightAmount: Float): Void {
final sysGamepads = getGamepads();
if (sysGamepads == null || sysGamepads[index] == null) {
return;
}
final gamepad = sysGamepads[index];
final duration = 10000; // 10 seconds
if (untyped gamepad.vibrationActuator) {
if (leftAmount == 0 && rightAmount == 0) {
untyped gamepad.vibrationActuator.reset();
}
else {
untyped gamepad.vibrationActuator.playEffect('dual-rumble', {
duration: duration,
strongMagnitude: leftAmount,
weakMagnitude: rightAmount
});
}
}
else if (untyped gamepad.hapticActuators && untyped gamepad.hapticActuators.length > 0) {
final hapticActuator = untyped gamepad.hapticActuators[0];
if (leftAmount == 0 && rightAmount == 0) {
untyped gamepad.hapticActuators[0].pulse(0, 0);
}
else {
untyped gamepad.hapticActuators[0].pulse(leftAmount, duration);
}
}
}
static function getGamepads(): Array<js.html.Gamepad> { static function getGamepads(): Array<js.html.Gamepad> {
if (chrome && kha.vr.VrInterface.instance != null && kha.vr.VrInterface.instance.IsVrEnabled()) { if (chrome && kha.vr.VrInterface.instance != null && kha.vr.VrInterface.instance.IsVrEnabled()) {
return null; // Chrome crashes if navigator.getGamepads() is called when using VR return null; // Chrome crashes if navigator.getGamepads() is called when using VR
} }
if (untyped navigator.getGamepads) { if (Browser.navigator.getGamepads != null) {
return js.Browser.navigator.getGamepads(); return Browser.navigator.getGamepads();
} }
else { else {
return null; return null;

View File

@ -21,7 +21,6 @@ class Window {
this.defaultHeight = defaultHeight; this.defaultHeight = defaultHeight;
windows.push(this); windows.push(this);
resizeCallbacks[num] = []; resizeCallbacks[num] = [];
windows.push(this);
final observer: MutationObserver = new MutationObserver(function(mutations: Array<js.html.MutationRecord>, observer: MutationObserver) { final observer: MutationObserver = new MutationObserver(function(mutations: Array<js.html.MutationRecord>, observer: MutationObserver) {
var isResize = false; var isResize = false;
for (mutation in mutations) { for (mutation in mutations) {

View File

@ -1,14 +1,14 @@
package kha.audio2; package kha.audio2;
import js.Syntax;
import js.Browser; import js.Browser;
import js.Syntax;
import js.html.URL; import js.html.URL;
import js.html.audio.AudioContext; import js.html.audio.AudioContext;
import js.html.audio.AudioProcessingEvent; import js.html.audio.AudioProcessingEvent;
import js.html.audio.ScriptProcessorNode; import js.html.audio.ScriptProcessorNode;
import kha.Sound;
import kha.internal.IntBox; import kha.internal.IntBox;
import kha.js.AEAudioChannel; import kha.js.AEAudioChannel;
import kha.Sound;
class Audio { class Audio {
public static var disableGcInteractions = false; public static var disableGcInteractions = false;
@ -70,7 +70,7 @@ class Audio {
public static var samplesPerSecond: Int; public static var samplesPerSecond: Int;
public static var audioCallback: kha.internal.IntBox->Buffer->Void; public static var audioCallback: (outputBufferLength: IntBox, buffer: Buffer) -> Void;
static var virtualChannels: Array<VirtualStreamChannel> = []; static var virtualChannels: Array<VirtualStreamChannel> = [];

View File

@ -1,5 +1,6 @@
package kha.capture; package kha.capture;
import js.Browser.navigator;
import js.html.audio.AudioProcessingEvent; import js.html.audio.AudioProcessingEvent;
import kha.audio2.Buffer; import kha.audio2.Buffer;
@ -16,8 +17,8 @@ class AudioCapture {
return; return;
} }
var getUserMedia = untyped __js__("navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia"); final getUserMedia = (navigator : Dynamic).getUserMedia;
getUserMedia.call(js.Browser.navigator, {audio: true}, function(stream: Dynamic) { getUserMedia.call(navigator, {audio: true}, function(stream: Dynamic) {
input = kha.audio2.Audio._context.createMediaStreamSource(stream); input = kha.audio2.Audio._context.createMediaStreamSource(stream);
var bufferSize = 1024 * 2; var bufferSize = 1024 * 2;

View File

@ -1,12 +1,13 @@
package kha.capture; package kha.capture;
import js.Browser.navigator;
import js.Browser; import js.Browser;
class VideoCapture { class VideoCapture {
public static function init(initialized: kha.Video->Void, error: Void->Void): Void { public static function init(initialized: kha.Video->Void, error: Void->Void): Void {
var getUserMedia = untyped __js__("navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia"); final getUserMedia = (navigator : Dynamic).getUserMedia;
getUserMedia.call(js.Browser.navigator, {audio: true, video: true}, function(stream: Dynamic) { getUserMedia.call(navigator, {audio: true, video: true}, function(stream: Dynamic) {
var element: js.html.VideoElement = cast Browser.document.createElement("video"); final element = Browser.document.createVideoElement();
element.srcObject = stream; element.srcObject = stream;
element.onloadedmetadata = function(e) { element.onloadedmetadata = function(e) {
initialized(kha.js.Video.fromElement(element)); initialized(kha.js.Video.fromElement(element));

View File

@ -0,0 +1,22 @@
package kha.graphics4;
import haxe.io.Bytes;
import kha.Blob;
class ComputeShader {
public function new(sources: Array<Blob>, files: Array<String>) {
}
public function delete(): Void {
}
public function getConstantLocation(name: String): ConstantLocation {
return null;
}
public function getTextureUnit(name: String): TextureUnit {
return null;
}
}

View File

@ -0,0 +1,24 @@
package kha.graphics4;
class ShaderStorageBuffer {
var data: Array<Int>;
var myCount: Int;
public function new(indexCount: Int, type: VertexData) {
myCount = indexCount;
data = new Array<Int>();
data[myCount - 1] = 0;
}
public function delete(): Void {}
public function lock(): Array<Int> {
return data;
}
public function unlock(): Void {}
public function count(): Int {
return myCount;
}
}

View File

@ -105,18 +105,7 @@ class CanvasGraphics extends Graphics {
} }
override function set_imageScaleQuality(value: ImageScaleQuality): ImageScaleQuality { override function set_imageScaleQuality(value: ImageScaleQuality): ImageScaleQuality {
if (value == ImageScaleQuality.Low) { canvas.imageSmoothingEnabled = value == ImageScaleQuality.High;
untyped canvas.mozImageSmoothingEnabled = false;
untyped canvas.webkitImageSmoothingEnabled = false;
untyped canvas.msImageSmoothingEnabled = false;
canvas.imageSmoothingEnabled = false;
}
else {
untyped canvas.mozImageSmoothingEnabled = true;
untyped canvas.webkitImageSmoothingEnabled = true;
untyped canvas.msImageSmoothingEnabled = true;
canvas.imageSmoothingEnabled = true;
}
return scaleQuality = value; return scaleQuality = value;
} }

View File

@ -0,0 +1,28 @@
package kha.js;
import js.html.MessageChannel;
class Microtask {
static var messageChannel: MessageChannel;
static final callbacks: Array<() -> Void> = [];
static function init(): Void {
if (messageChannel != null) {
return;
}
messageChannel = new MessageChannel();
messageChannel.port1.onmessage = _ -> {
final copy = callbacks.copy();
callbacks.resize(0);
for (callback in copy) {
callback();
}
};
}
public static function queueMicrotask(callback: () -> Void): Void {
init();
callbacks.push(callback);
messageChannel.port2.postMessage(js.Lib.undefined);
}
}

View File

@ -32,7 +32,7 @@ class Video extends kha.Video {
video.done = done; video.done = done;
video.element = cast Browser.document.createElement("video"); video.element = Browser.document.createVideoElement();
video.filenames = []; video.filenames = [];
for (filename in filenames) { for (filename in filenames) {

View File

@ -91,7 +91,7 @@ class WebAudioSound extends kha.Sound {
var i = 0; var i = 0;
final lidx = len * 2; final lidx = len * 2;
function uncompressInner() { function uncompressInner() {
var chk_len = idx + 11025; var chk_len = idx + 44100;
var next_chk = chk_len > lidx ? lidx : chk_len; var next_chk = chk_len > lidx ? lidx : chk_len;
while (idx < next_chk) { while (idx < next_chk) {
uncompressedData[idx] = ch0[i]; uncompressedData[idx] = ch0[i];
@ -100,7 +100,7 @@ class WebAudioSound extends kha.Sound {
++i; ++i;
} }
if (idx < lidx) if (idx < lidx)
js.Browser.window.setTimeout(uncompressInner, 0); Microtask.queueMicrotask(uncompressInner);
else { else {
compressedData = null; compressedData = null;
done(); done();

View File

@ -8,11 +8,13 @@ import js.html.webgl.GL;
import kha.graphics4.BlendingFactor; import kha.graphics4.BlendingFactor;
import kha.graphics4.BlendingOperation; import kha.graphics4.BlendingOperation;
import kha.graphics4.CompareMode; import kha.graphics4.CompareMode;
import kha.graphics4.ComputeShader;
import kha.graphics4.CubeMap; import kha.graphics4.CubeMap;
import kha.graphics4.CullMode; import kha.graphics4.CullMode;
import kha.graphics4.IndexBuffer; import kha.graphics4.IndexBuffer;
import kha.graphics4.MipMapFilter; import kha.graphics4.MipMapFilter;
import kha.graphics4.PipelineState; import kha.graphics4.PipelineState;
import kha.graphics4.ShaderStorageBuffer;
import kha.graphics4.StencilAction; import kha.graphics4.StencilAction;
import kha.graphics4.TextureAddressing; import kha.graphics4.TextureAddressing;
import kha.graphics4.TextureFilter; import kha.graphics4.TextureFilter;
@ -47,7 +49,6 @@ class Graphics implements kha.graphics4.Graphics {
static var current: Graphics = null; static var current: Graphics = null;
static var useVertexAttributes: Int = 0; static var useVertexAttributes: Int = 0;
public static var vrFramebufferBound: Bool = false;
public function new(renderTarget: Canvas = null) { public function new(renderTarget: Canvas = null) {
this.renderTarget = renderTarget; this.renderTarget = renderTarget;
@ -90,11 +91,9 @@ class Graphics implements kha.graphics4.Graphics {
SystemImpl.gl.enable(GL.BLEND); SystemImpl.gl.enable(GL.BLEND);
SystemImpl.gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA); SystemImpl.gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA);
if (renderTarget == null) { if (renderTarget == null) {
if (!vrFramebufferBound) {
SystemImpl.gl.bindFramebuffer(GL.FRAMEBUFFER, null); SystemImpl.gl.bindFramebuffer(GL.FRAMEBUFFER, null);
SystemImpl.gl.viewport(0, 0, System.windowWidth(), System.windowHeight()); SystemImpl.gl.viewport(0, 0, System.windowWidth(), System.windowHeight());
} }
}
else { else {
SystemImpl.gl.bindFramebuffer(GL.FRAMEBUFFER, renderTargetFrameBuffer); SystemImpl.gl.bindFramebuffer(GL.FRAMEBUFFER, renderTargetFrameBuffer);
// if (isCubeMap) SystemImpl.gl.framebufferTexture(GL.FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.TEXTURE_CUBE_MAP, renderTargetTexture, 0); // Layered // if (isCubeMap) SystemImpl.gl.framebufferTexture(GL.FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.TEXTURE_CUBE_MAP, renderTargetTexture, 0); // Layered
@ -625,8 +624,8 @@ class Graphics implements kha.graphics4.Graphics {
SystemImpl.gl.uniform4f((cast location : ConstantLocation).value, value.x, value.y, value.z, value.w); SystemImpl.gl.uniform4f((cast location : ConstantLocation).value, value.x, value.y, value.z, value.w);
} }
static var matrixCache = new js.lib.Float32Array(16);
public inline function setMatrix(location: kha.graphics4.ConstantLocation, matrix: FastMatrix4): Void { public inline function setMatrix(location: kha.graphics4.ConstantLocation, matrix: FastMatrix4): Void {
static var matrixCache = new js.lib.Float32Array(16);
matrixCache[0] = matrix._00; matrixCache[0] = matrix._00;
matrixCache[1] = matrix._01; matrixCache[1] = matrix._01;
matrixCache[2] = matrix._02; matrixCache[2] = matrix._02;
@ -646,8 +645,8 @@ class Graphics implements kha.graphics4.Graphics {
SystemImpl.gl.uniformMatrix4fv((cast location : ConstantLocation).value, false, matrixCache); SystemImpl.gl.uniformMatrix4fv((cast location : ConstantLocation).value, false, matrixCache);
} }
static var matrix3Cache = new js.lib.Float32Array(9);
public inline function setMatrix3(location: kha.graphics4.ConstantLocation, matrix: FastMatrix3): Void { public inline function setMatrix3(location: kha.graphics4.ConstantLocation, matrix: FastMatrix3): Void {
static var matrix3Cache = new js.lib.Float32Array(9);
matrix3Cache[0] = matrix._00; matrix3Cache[0] = matrix._00;
matrix3Cache[1] = matrix._01; matrix3Cache[1] = matrix._01;
matrix3Cache[2] = matrix._02; matrix3Cache[2] = matrix._02;
@ -738,4 +737,16 @@ class Graphics implements kha.graphics4.Graphics {
public function instancedRenderingAvailable(): Bool { public function instancedRenderingAvailable(): Bool {
return instancedExtension; return instancedExtension;
} }
public function setShaderStorageBuffer(buffer: ShaderStorageBuffer, index: Int) {
}
public function setComputeShader(shader: ComputeShader) {
}
public function compute(x: Int, y: Int, z: Int) {
}
} }

View File

@ -13,29 +13,10 @@ import kha.SystemImpl;
class VrInterface extends kha.vr.VrInterface { class VrInterface extends kha.vr.VrInterface {
var vrEnabled: Bool = false; var vrEnabled: Bool = false;
var isWebXR: Bool = false;
var vrDisplay: Dynamic; var vrDisplay: Dynamic;
var frameData: Dynamic; var frameData: Dynamic;
var xrSession: Dynamic;
var xrRefSpace: Dynamic;
public var xrGLLayer: Dynamic;
public var currentFrame: Dynamic;
public var currentViews: Dynamic;
public var currentViewerPose: Dynamic;
public var currentInputSources: Dynamic;
var xrAnimationFrameHandle: Int = -1;
public var _glContext: Dynamic;
public var _leftViewport: Dynamic;
public var _rightViewport: Dynamic;
public var _cachedViewsLength: Int = 0;
var savedCanvasWidth: Int = 0;
var savedCanvasHeight: Int = 0;
var browserRAFId: Int = -1;
var leftProjectionMatrix: FastMatrix4 = FastMatrix4.identity(); var leftProjectionMatrix: FastMatrix4 = FastMatrix4.identity();
var rightProjectionMatrix: FastMatrix4 = FastMatrix4.identity(); var rightProjectionMatrix: FastMatrix4 = FastMatrix4.identity();
var leftViewMatrix: FastMatrix4 = FastMatrix4.identity(); var leftViewMatrix: FastMatrix4 = FastMatrix4.identity();
@ -49,29 +30,15 @@ class VrInterface extends kha.vr.VrInterface {
public function new() { public function new() {
super(); super();
#if kha_webvr #if kha_webvr
var webXREnabled: Bool = Syntax.code("navigator.xr");
if (webXREnabled) {
isWebXR = true;
vrEnabled = true;
trace("WebXR API detected");
}
else {
var displayEnabled: Bool = Syntax.code("navigator.getVRDisplays"); var displayEnabled: Bool = Syntax.code("navigator.getVRDisplays");
if (displayEnabled) {
isWebXR = false;
vrEnabled = true;
getVRDisplays();
trace("WebVR 1.1 API detected");
}
}
#else #else
var displayEnabled = false; var displayEnabled = false;
#end #end
//if (displayEnabled) { if (displayEnabled) {
// vrEnabled = true; vrEnabled = true;
// getVRDisplays(); getVRDisplays();
// trace("Display enabled."); trace("Display enabled.");
//} }
} }
function getVRDisplays() { function getVRDisplays() {
@ -97,10 +64,6 @@ class VrInterface extends kha.vr.VrInterface {
} }
public override function onVRRequestPresent() { public override function onVRRequestPresent() {
if (isWebXR) {
requestWebXRSession();
} else {
// WebVR 1.1
try { try {
vrDisplay.requestPresent([{source: SystemImpl.khanvas}]).then(function() { vrDisplay.requestPresent([{source: SystemImpl.khanvas}]).then(function() {
onResize(); onResize();
@ -108,466 +71,22 @@ class VrInterface extends kha.vr.VrInterface {
}); });
} }
catch (err:Dynamic) { catch (err:Dynamic) {
trace("Failed to requestPresent WebVR: " + err); trace("Failed to requestPresent.");
}
}
}
function requestWebXRSession() {
var vrScaleFactor = 1.0;
#if lnx_vr
vrScaleFactor = leenkx.renderpath.Inc.getSuperSampling();
trace("[VR] Using renderpath superSample as framebufferScaleFactor: " + vrScaleFactor);
#end
try {
Syntax.code("
let gl = null;
let canvas = null;
try {
if (typeof kha_SystemImpl !== 'undefined') {
gl = kha_SystemImpl.gl;
canvas = kha_SystemImpl.khanvas;
}
} catch (e) {
trace('kha_SystemImpl access failed: ' + e.message);
}
if (!canvas) {
canvas = document.querySelector('canvas');
}
if (canvas && !gl) {
const contextAttributes = { xrCompatible: true, antialias: true, alpha: false };
gl = canvas.getContext('webgl2', contextAttributes) ||
canvas.getContext('webgl', contextAttributes) ||
canvas.getContext('experimental-webgl', contextAttributes);
}
if (!canvas) {
canvas = document.getElementById('khanvas');
if (canvas && !gl) {
gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
}
}
if (!gl) {
return;
}
const self = this;
const glContext = gl;
self._glContext = glContext;
");
Syntax.code("
self._vrRenderCallback = function() {
self.vrRenderCallback();
};
const checkAndRequestSession = async () => {
try {
const supported = await navigator.xr.isSessionSupported('immersive-vr');
if (!supported) {
trace('immersive-vr session not supported');
}
} catch (e) {
trace('WARN: isSessionSupported failed: ' + e.message);
// Continue anyway as some browsers do not support the check itself
}
return await navigator.xr.requestSession('immersive-vr', {
optionalFeatures: ['local-floor', 'hand-tracking', 'bounded-floor']
});
};
checkAndRequestSession().then(async (session) => {
self.xrSession = session;
if (typeof window !== 'undefined') {
window._khaSkipWindowRender = true;
}
const contextAttributes = glContext.getContextAttributes();
if (!contextAttributes || !contextAttributes.xrCompatible) {
await glContext.makeXRCompatible();
}
self.xrGLLayer = new XRWebGLLayer(session, glContext, {
depth: true, // Essential for depth testing
stencil: false, // Not needed, wastes memory
alpha: false, // Not needed in VR wastes
antialias: true, // Smooth rendering
framebufferScaleFactor: {0} // VR resolution quality from renderpath
});
if (self.xrGLLayer.framebufferWidth === 0 || self.xrGLLayer.framebufferHeight === 0) {
trace('XRWebGLLayer framebuffer has invalid dimensions');
}
session.updateRenderState({
baseLayer: self.xrGLLayer
});
const handlers = {};
handlers.end = () => {
self.onSessionEnd();
};
session.addEventListener('end', handlers.end);
handlers.select = (event) => {
if (self.onSelect) self.onSelect(event);
};
session.addEventListener('select', handlers.select);
handlers.selectstart = (event) => {
if (self.onSelectStart) self.onSelectStart(event);
};
session.addEventListener('selectstart', handlers.selectstart);
handlers.selectend = (event) => {
if (self.onSelectEnd) self.onSelectEnd(event);
};
session.addEventListener('selectend', handlers.selectend);
handlers.squeeze = (event) => {
if (self.onSqueeze) self.onSqueeze(event);
};
session.addEventListener('squeeze', handlers.squeeze);
handlers.squeezestart = (event) => {
if (self.onSqueezeStart) self.onSqueezeStart(event);
};
session.addEventListener('squeezestart', handlers.squeezestart);
handlers.squeezeend = (event) => {
if (self.onSqueezeEnd) self.onSqueezeEnd(event);
};
session.addEventListener('squeezeend', handlers.squeezeend);
session.addEventListener('inputsourceschange', handlers.inputsourceschange);
handlers.visibilitychange = (event) => {
const state = event.session.visibilityState;
};
session.addEventListener('visibilitychange', handlers.visibilitychange);
self._eventHandlers = handlers;
const requestRefSpace = async () => {
const spaces = ['local-floor', 'local'];
for (const space of spaces) {
try {
const refSpace = await session.requestReferenceSpace(space);
return refSpace;
} catch (e) {
trace(space + ' not supported');
}
}
trace('No reference space supported');
};
requestRefSpace().then((refSpace) => {
self.xrRefSpace = refSpace;
if (canvas && canvas.width) {
self.savedCanvasWidth = canvas.width;
self.savedCanvasHeight = canvas.height;
} else {
const canvasFallback = document.querySelector('canvas');
if (canvasFallback) {
self.savedCanvasWidth = canvasFallback.width;
self.savedCanvasHeight = canvasFallback.height;
}
}
const onFrame = (time, frame) => {
try {
if (self.xrSession) {
self.xrAnimationFrameHandle = self.xrSession.requestAnimationFrame(onFrame);
}
if (!self._lastFrameTime) self._lastFrameTime = time;
const deltaTime = time - self._lastFrameTime;
self._lastFrameTime = time;
if (!window._xrFrameCount) window._xrFrameCount = 0;
window._xrFrameCount++;
if (glContext && self.xrSession && self.xrSession.renderState && self.xrSession.renderState.baseLayer) {
const layer = self.xrSession.renderState.baseLayer;
if (layer.framebuffer) {
const pose = frame.getViewerPose(self.xrRefSpace);
if (pose && pose.views && pose.views.length > 0) {
glContext.bindFramebuffer(glContext.FRAMEBUFFER, layer.framebuffer);
let bgR = 0, bgG = 0, bgB = 0;
if (typeof iron !== 'undefined' && iron.Scene && iron.Scene.active && iron.Scene.active.world && iron.Scene.active.world.raw) {
const bgColor = iron.Scene.active.world.raw.background_color;
if (bgColor !== undefined) {
bgR = ((bgColor >> 16) & 255) / 255;
bgG = ((bgColor >> 8) & 255) / 255;
bgB = (bgColor & 255) / 255;
}
}
for (const view of pose.views) {
const vp = layer.getViewport(view);
glContext.viewport(vp.x, vp.y, vp.width, vp.height);
glContext.scissor(vp.x, vp.y, vp.width, vp.height);
glContext.enable(glContext.SCISSOR_TEST);
glContext.clearColor(bgR, bgG, bgB, 1.0);
glContext.clear(glContext.COLOR_BUFFER_BIT | glContext.DEPTH_BUFFER_BIT);
}
glContext.disable(glContext.SCISSOR_TEST);
}
}
}
if (!self.xrSession) {
return;
}
const pose = frame.getViewerPose(self.xrRefSpace);
if (!pose) {
return;
}
if (pose.emulatedPosition && !self._emulatedPosLogged) {
self._emulatedPosLogged = true;
}
const views = pose.views;
if (!self.xrSession.renderState || !self.xrSession.renderState.baseLayer) {
if (!self._noRenderStateLogged) {
self._noRenderStateLogged = true;
}
return;
}
const glLayer = self.xrSession.renderState.baseLayer;
if (!views || views.length === 0) {
return;
}
if (self.xrSession.visibilityState === 'hidden') {
return;
}
self.currentFrame = frame;
self.currentViews = views;
self.currentViewerPose = pose;
if (self.xrSession && self.xrSession.inputSources) {
self.currentInputSources = self.xrSession.inputSources;
}
if (glContext.isContextLost()) {
return;
}
if (!glContext || !glLayer || !glLayer.framebuffer) {
return;
}
if (glContext.bindVertexArray) {
glContext.bindVertexArray(null);
}
while (glContext.getError() !== glContext.NO_ERROR) {
// Drain error queue
}
glContext.bindFramebuffer(glContext.FRAMEBUFFER, glLayer.framebuffer);
const bindError = glContext.getError();
if (bindError !== glContext.NO_ERROR && !self._bindErrorLogged) {
self._bindErrorLogged = true;
}
const fbStatus = glContext.checkFramebufferStatus(glContext.FRAMEBUFFER);
if (fbStatus !== glContext.FRAMEBUFFER_COMPLETE) {
return;
}
glContext.enable(glContext.DEPTH_TEST);
glContext.depthFunc(glContext.LEQUAL);
glContext.depthMask(true);
glContext.colorMask(true, true, true, true);
glContext.disable(glContext.BLEND);
glContext.enable(glContext.CULL_FACE);
glContext.cullFace(glContext.BACK);
glContext.frontFace(glContext.CCW);
glContext.disable(glContext.STENCIL_TEST);
glContext.disable(glContext.POLYGON_OFFSET_FILL);
if (!self._fbLogged && p) {
const depthTest = glContext.isEnabled(glContext.DEPTH_TEST);
const cullFace = glContext.isEnabled(glContext.CULL_FACE);
const blend = glContext.isEnabled(glContext.BLEND);
self._fbLogged = true;
}
if (views.length === 0) {
return;
}
if (views.length >= 1) {
try {
self._leftViewport = glLayer.getViewport(views[0]);
self._rightViewport = views.length >= 2 ? glLayer.getViewport(views[1]) : null;
self._cachedViewsLength = views.length;
if (!self._leftViewport) {
return;
}
} catch (e) {
return;
}
}
if (views.length >= 1) {
self.leftProjectionMatrix = self.createMatrixFromArray(views[0].projectionMatrix);
self.leftViewMatrix = self.createMatrixFromArray(views[0].transform.inverse.matrix);
}
if (views.length >= 2) {
self.rightProjectionMatrix = self.createMatrixFromArray(views[1].projectionMatrix);
self.rightViewMatrix = self.createMatrixFromArray(views[1].transform.inverse.matrix);
} else if (views.length === 1) {
self.rightProjectionMatrix = self.leftProjectionMatrix;
self.rightViewMatrix = self.leftViewMatrix;
}
if (self._vrRenderCallback) {
self._vrRenderCallback();
}
} catch (err) {
console.error('XR Frame Error:', err);
} finally {
self.currentFrame = null;
self.currentViews = null;
self.currentInputSources = null;
}
};
self.xrAnimationFrameHandle = session.requestAnimationFrame(onFrame);
}).catch((err) => {
trace('REF SPACE FAILED: ' + err.message );
});
}).catch((err) => {
trace('SESSION FAILED: ' + err);
});
", vrScaleFactor);
}
catch (err:Dynamic) {
trace("Failed to requestSession (WebXR).");
trace(err); trace(err);
} }
} }
function onSessionEnd() {
var canvas = SystemImpl.khanvas;
if (canvas == null) {
canvas = Syntax.code("document.querySelector('canvas')");
}
if (canvas != null && savedCanvasWidth > 0 && savedCanvasHeight > 0) {
canvas.width = savedCanvasWidth;
canvas.height = savedCanvasHeight;
}
if (xrSession != null) {
Syntax.code("
if (this.xrAnimationFrameHandle !== -1 && this.xrSession) {
this.xrSession.cancelAnimationFrame(this.xrAnimationFrameHandle);
this.xrAnimationFrameHandle = -1;
}
if (this._eventHandlers && this.xrSession) {
const handlers = this._eventHandlers;
const events = ['end', 'select', 'selectstart', 'selectend', 'squeeze', 'squeezestart', 'squeezeend', 'inputsourceschange', 'visibilitychange'];
for (const event of events) {
if (handlers[event]) {
this.xrSession.removeEventListener(event, handlers[event]);
}
}
this._eventHandlers = null;
}
");
}
Syntax.code("
const gl = this._glContext;
if (gl) {
gl.bindFramebuffer(gl.FRAMEBUFFER, null); // Restore default framebuffer
gl.disable(gl.SCISSOR_TEST);
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
}
if (typeof window !== 'undefined') {
window._khaSkipWindowRender = false;
}
this.xrSession = null;
this.xrRefSpace = null;
this.xrGLLayer = null;
this.currentFrame = null;
this.currentViews = null;
this.currentInputSources = null;
this._lastFrameTime = null;
if (typeof window !== 'undefined') {
delete window._xrFrameCount;
delete window._ironRenderCount;
delete window._slowFrameCount;
}
");
}
public override function onVRExitPresent() { public override function onVRExitPresent() {
if (isWebXR) {
try {
if (xrSession != null) {
Syntax.code("
if (this.xrSession) {
this.xrSession.end().then(() => {
trace('Session ended');
}).catch((err) => {
trace('Session.end() failed:', err);
});
}
");
xrSession = null;
xrRefSpace = null;
xrGLLayer = null;
}
}
catch (err:Dynamic) {
trace("Failed to exitPresent in WebXR");
trace(err);
}
}
else {
// WebVR 1.1
try { try {
vrDisplay.exitPresent([{source: SystemImpl.khanvas}]).then(function() { vrDisplay.exitPresent([{source: SystemImpl.khanvas}]).then(function() {
onResize(); onResize();
}); });
} }
catch (err:Dynamic) { catch (err:Dynamic) {
trace("Failed to exitPresent"); trace("Failed to exitPresent.");
trace(err); trace(err);
} }
} }
}
public override function onResetPose() { public override function onResetPose() {
try { try {
@ -597,25 +116,13 @@ class VrInterface extends kha.vr.VrInterface {
} }
function onResize() { function onResize() {
if (isWebXR) {
return;
}
else {
// WebVR 1.1
if (vrDisplay != null && vrDisplay.isPresenting) { if (vrDisplay != null && vrDisplay.isPresenting) {
var canvas = SystemImpl.khanvas; SystemImpl.khanvas.width = vrWidth;
if (canvas != null) { SystemImpl.khanvas.height = vrHeight;
canvas.width = vrWidth;
canvas.height = vrHeight;
}
} }
else { else {
var canvas = SystemImpl.khanvas; SystemImpl.khanvas.width = width;
if (canvas != null) { SystemImpl.khanvas.height = height;
canvas.width = width;
canvas.height = height;
}
}
} }
} }
@ -667,11 +174,9 @@ class VrInterface extends kha.vr.VrInterface {
} }
public override function IsPresenting(): Bool { public override function IsPresenting(): Bool {
var presenting = false; if (vrDisplay != null)
if (vrDisplay != null){ return vrDisplay.isPresenting;
presenting = vrDisplay.isPresenting; return false;
}
return presenting;
} }
public override function IsVrEnabled(): Bool { public override function IsVrEnabled(): Bool {
@ -702,10 +207,6 @@ class VrInterface extends kha.vr.VrInterface {
function createMatrixFromArray(array: Float32Array): FastMatrix4 { function createMatrixFromArray(array: Float32Array): FastMatrix4 {
var matrix: FastMatrix4 = FastMatrix4.identity(); var matrix: FastMatrix4 = FastMatrix4.identity();
if (array == null || array.length < 16) {
trace("Warning: Invalid matrix array, using identity");
return matrix;
}
matrix._00 = array[0]; matrix._00 = array[0];
matrix._01 = array[1]; matrix._01 = array[1];
matrix._02 = array[2]; matrix._02 = array[2];
@ -745,63 +246,4 @@ class VrInterface extends kha.vr.VrInterface {
} }
return quaternion; return quaternion;
} }
public function vrRenderCallback(): Void {
var g4 = kha.SystemImpl.frame != null ? kha.SystemImpl.frame.g4 : null;
if (g4 != null && iron.Scene.active != null && iron.RenderPath.active != null) {
if (untyped window._vrUpdateStarted == null) {
untyped window._vrUpdateStarted = true;
}
iron.system.Time.update();
iron.Scene.active.updateFrame();
js.Syntax.code("
const App = iron.App;
if (App) {
const frame = window._vrCallbackCount;
const inits = App.traitInits;
if (inits && inits.length > 0) {
for (let i = 0; i < inits.length; i++) {
inits[i]();
}
inits.length = 0;
}
const fixedUpdates = App.traitFixedUpdates;
if (fixedUpdates) {
for (let i = 0; i < fixedUpdates.length; i++) {
fixedUpdates[i]();
}
}
const updates = App.traitUpdates;
if (updates) {
for (let i = 0; i < updates.length; i++) {
updates[i]();
}
}
const lateUpdates = App.traitLateUpdates;
if (lateUpdates) {
for (let i = 0; i < lateUpdates.length; i++) {
lateUpdates[i]();
}
}
}
");
iron.Scene.active.renderFrame(g4);
}
else {
if (untyped window._vrSkipLogged == null) {
untyped window._vrSkipLogged = true;
}
}
}
} }

View File

@ -0,0 +1,22 @@
package kha.graphics4;
import haxe.io.Bytes;
import kha.Blob;
class ComputeShader {
public function new(sources: Array<Blob>, files: Array<String>) {
}
public function delete(): Void {
}
public function getConstantLocation(name: String): ConstantLocation {
return null;
}
public function getTextureUnit(name: String): TextureUnit {
return null;
}
}

View File

@ -0,0 +1,24 @@
package kha.graphics4;
class ShaderStorageBuffer {
var data: Array<Int>;
var myCount: Int;
public function new(indexCount: Int, type: VertexData) {
myCount = indexCount;
data = new Array<Int>();
data[myCount - 1] = 0;
}
public function delete(): Void {}
public function lock(): Array<Int> {
return data;
}
public function unlock(): Void {}
public function count(): Int {
return myCount;
}
}

View File

@ -1,268 +0,0 @@
/*
* Platform-specific and custom entropy polling functions
*
* Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#define _GNU_SOURCE
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_ENTROPY_C)
#include "mbedtls/entropy.h"
#include "mbedtls/entropy_poll.h"
#if defined(MBEDTLS_TIMING_C)
#include <string.h>
#include "mbedtls/timing.h"
#endif
#if defined(MBEDTLS_HAVEGE_C)
#include "mbedtls/havege.h"
#endif
#if defined(MBEDTLS_ENTROPY_NV_SEED)
#include "mbedtls/platform.h"
#endif
#if !defined(MBEDTLS_NO_PLATFORM_ENTROPY)
#if !defined(unix) && !defined(__unix__) && !defined(__unix) && \
!defined(__APPLE__) && !defined(_WIN32)
#error "Platform entropy sources only work on Unix and Windows, see MBEDTLS_NO_PLATFORM_ENTROPY in config.h"
#endif
#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
#if !defined(_WIN32_WINNT)
#define _WIN32_WINNT 0x0400
#endif
#include <windows.h>
#include <wincrypt.h>
int mbedtls_platform_entropy_poll( void *data, unsigned char *output, size_t len,
size_t *olen )
{
HCRYPTPROV provider;
((void) data);
*olen = 0;
if( CryptAcquireContext( &provider, NULL, NULL,
PROV_RSA_FULL, CRYPT_VERIFYCONTEXT ) == FALSE )
{
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
}
if( CryptGenRandom( provider, (DWORD) len, output ) == FALSE )
{
CryptReleaseContext( provider, 0 );
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
}
CryptReleaseContext( provider, 0 );
*olen = len;
return( 0 );
}
#else /* _WIN32 && !EFIX64 && !EFI32 */
/*
* Test for Linux getrandom() support.
* Since there is no wrapper in the libc yet, use the generic syscall wrapper
* available in GNU libc and compatible libc's (eg uClibc).
*/
#if defined(__linux__) && defined(__GLIBC__)
#include <unistd.h>
#include <sys/syscall.h>
#if defined(SYS_getrandom)
#define HAVE_GETRANDOM
static int getrandom_wrapper( void *buf, size_t buflen, unsigned int flags )
{
/* MemSan cannot understand that the syscall writes to the buffer */
#if defined(__has_feature)
#if __has_feature(memory_sanitizer)
memset( buf, 0, buflen );
#endif
#endif
return( syscall( SYS_getrandom, buf, buflen, flags ) );
}
#include <sys/utsname.h>
/* Check if version is at least 3.17.0 */
static int check_version_3_17_plus( void )
{
int minor;
struct utsname un;
const char *ver;
/* Get version information */
uname(&un);
ver = un.release;
/* Check major version; assume a single digit */
if( ver[0] < '3' || ver[0] > '9' || ver [1] != '.' )
return( -1 );
if( ver[0] - '0' > 3 )
return( 0 );
/* Ok, so now we know major == 3, check minor.
* Assume 1 or 2 digits. */
if( ver[2] < '0' || ver[2] > '9' )
return( -1 );
minor = ver[2] - '0';
if( ver[3] >= '0' && ver[3] <= '9' )
minor = 10 * minor + ver[3] - '0';
else if( ver [3] != '.' )
return( -1 );
if( minor < 17 )
return( -1 );
return( 0 );
}
static int has_getrandom = -1;
#endif /* SYS_getrandom */
#endif /* __linux__ */
#include <stdio.h>
int mbedtls_platform_entropy_poll( void *data,
unsigned char *output, size_t len, size_t *olen )
{
FILE *file;
size_t read_len;
((void) data);
#if defined(HAVE_GETRANDOM)
if( has_getrandom == -1 )
has_getrandom = ( check_version_3_17_plus() == 0 );
if( has_getrandom )
{
int ret;
if( ( ret = getrandom_wrapper( output, len, 0 ) ) < 0 )
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
*olen = ret;
return( 0 );
}
#endif /* HAVE_GETRANDOM */
*olen = 0;
file = fopen( "/dev/urandom", "rb" );
if( file == NULL )
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
read_len = fread( output, 1, len, file );
if( read_len != len )
{
fclose( file );
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
}
fclose( file );
*olen = len;
return( 0 );
}
#endif /* _WIN32 && !EFIX64 && !EFI32 */
#endif /* !MBEDTLS_NO_PLATFORM_ENTROPY */
#if defined(MBEDTLS_TEST_NULL_ENTROPY)
int mbedtls_null_entropy_poll( void *data,
unsigned char *output, size_t len, size_t *olen )
{
((void) data);
((void) output);
*olen = 0;
if( len < sizeof(unsigned char) )
return( 0 );
*olen = sizeof(unsigned char);
return( 0 );
}
#endif
#if defined(MBEDTLS_TIMING_C)
int mbedtls_hardclock_poll( void *data,
unsigned char *output, size_t len, size_t *olen )
{
unsigned long timer = mbedtls_timing_hardclock();
((void) data);
*olen = 0;
if( len < sizeof(unsigned long) )
return( 0 );
memcpy( output, &timer, sizeof(unsigned long) );
*olen = sizeof(unsigned long);
return( 0 );
}
#endif /* MBEDTLS_TIMING_C */
#if defined(MBEDTLS_HAVEGE_C)
int mbedtls_havege_poll( void *data,
unsigned char *output, size_t len, size_t *olen )
{
mbedtls_havege_state *hs = (mbedtls_havege_state *) data;
*olen = 0;
if( mbedtls_havege_random( hs, output, len ) != 0 )
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
*olen = len;
return( 0 );
}
#endif /* MBEDTLS_HAVEGE_C */
#if defined(MBEDTLS_ENTROPY_NV_SEED)
int mbedtls_nv_seed_poll( void *data,
unsigned char *output, size_t len, size_t *olen )
{
unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
size_t use_len = MBEDTLS_ENTROPY_BLOCK_SIZE;
((void) data);
memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
if( mbedtls_nv_seed_read( buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) < 0 )
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
if( len < use_len )
use_len = len;
memcpy( output, buf, use_len );
*olen = use_len;
return( 0 );
}
#endif /* MBEDTLS_ENTROPY_NV_SEED */
#endif /* MBEDTLS_ENTROPY_C */

View File

@ -1,31 +0,0 @@
let project = new Project('Kha', __dirname);
project.addFiles('kinc-bridge/**', 'hl/include/**', 'hl/src/std/**', 'hl/src/gc.c', 'hl/src/hl.h', 'hl/src/hlc.h', 'hl/src/hlmodule.h', 'hl/src/opcodes.h');
project.addExcludes('hl/src/std/unicase.c', 'hl/src/std/debug.c', 'hl/include/pcre/pcre2_jit_match.c', 'hl/include/pcre/pcre2_jit_misc.c');
project.addIncludeDirs('hl/src', 'hl/include/pcre', 'hl/include/mbedtls/include', 'hl/include/zlib');
project.addFiles('hl/include/mbedtls/library/**', 'hl/include/zlib/**', 'hl/libs/fmt/fmt.c', 'hl/libs/fmt/sha1.c', 'hl/libs/ssl/ssl.c');
if (platform == Platform.OSX) project.addDefine('KORE_DEBUGDIR="osx-hl"');
if (platform == Platform.iOS) project.addDefine('KORE_DEBUGDIR="ios-hl"');
if (platform !== Platform.Windows || audio !== AudioApi.DirectSound) {
project.addDefine('KORE_MULTITHREADED_AUDIO');
project.addDefine('KINC_MULTITHREADED_AUDIO');
}
project.addDefine('KORE');
project.addDefine('KOREC');
project.addDefine('ROTATE90');
project.addDefine('LIBHL_STATIC');
project.addDefine('PCRE2_CODE_UNIT_WIDTH=16');
project.addDefine('HAVE_CONFIG_H');
project.cStd = 'c11';
if (platform === Platform.Windows || platform === Platform.WindowsApp) {
project.addDefine('_WINSOCK_DEPRECATED_NO_WARNINGS');
}
if (platform === Platform.Windows) {
project.addLib('ws2_32');
project.addLib('Crypt32'); // SSL
}
resolve(project);

View File

@ -1,463 +0,0 @@
package kha;
import haxe.io.Bytes;
import haxe.io.BytesData;
import kha.korehl.graphics4.TextureUnit;
import kha.graphics4.TextureFormat;
import kha.graphics4.DepthStencilFormat;
import kha.graphics4.Usage;
class Image implements Canvas implements Resource {
public var _texture: Pointer;
public var _renderTarget: Pointer;
public var _textureArray: Pointer;
public var _textureArrayTextures: Pointer;
var myFormat: TextureFormat;
var readable: Bool;
var graphics1: kha.graphics1.Graphics;
var graphics2: kha.graphics2.Graphics;
var graphics4: kha.graphics4.Graphics;
public static function fromVideo(video: Video): Image {
var image = new Image(false);
image.myFormat = TextureFormat.RGBA32;
image.initVideo(cast(video, kha.korehl.Video));
return image;
}
public static function create(width: Int, height: Int, format: TextureFormat = null, usage: Usage = null, readable: Bool = false): Image {
return create2(width, height, format == null ? TextureFormat.RGBA32 : format, readable, false, NoDepthAndStencil);
}
public static function create3D(width: Int, height: Int, depth: Int, format: TextureFormat = null, usage: Usage = null, readable: Bool = false): Image {
return create3(width, height, depth, format == null ? TextureFormat.RGBA32 : format, readable, 0);
}
public static function createRenderTarget(width: Int, height: Int, format: TextureFormat = null, depthStencil: DepthStencilFormat = NoDepthAndStencil,
antiAliasingSamples: Int = 1): Image {
return create2(width, height, format == null ? TextureFormat.RGBA32 : format, false, true, depthStencil);
}
// public static function createArray(images: Array<Image>, format: TextureFormat = null): Image {
// var image = new Image(false);
// image.myFormat = (format == null) ? TextureFormat.RGBA32 : format;
// initArrayTexture(image, images);
// return image;
// }
public static function fromBytes(bytes: Bytes, width: Int, height: Int, format: TextureFormat = null, usage: Usage = null, readable: Bool = false): Image {
var image = new Image(readable);
image.myFormat = format;
image.initFromBytes(bytes.getData(), width, height, getTextureFormat(format));
return image;
}
function initFromBytes(bytes: BytesData, width: Int, height: Int, format: Int): Void {
_texture = kinc_texture_from_bytes(bytes.bytes, width, height, format, readable);
}
public static function fromBytes3D(bytes: Bytes, width: Int, height: Int, depth: Int, format: TextureFormat = null, usage: Usage = null,
readable: Bool = false): Image {
var image = new Image(readable);
image.myFormat = format;
image.initFromBytes3D(bytes.getData(), width, height, depth, getTextureFormat(format));
return image;
}
function initFromBytes3D(bytes: BytesData, width: Int, height: Int, depth: Int, format: Int): Void {
_texture = kinc_texture_from_bytes3d(bytes.bytes, width, height, depth, format, readable);
}
public static function fromEncodedBytes(bytes: Bytes, format: String, doneCallback: Image->Void, errorCallback: String->Void,
readable: Bool = false): Void {
var image = new Image(readable);
var isFloat = format == "hdr" || format == "HDR";
image.myFormat = isFloat ? TextureFormat.RGBA128 : TextureFormat.RGBA32;
image.initFromEncodedBytes(bytes.getData(), format);
doneCallback(image);
}
function initFromEncodedBytes(bytes: BytesData, format: String): Void {
_texture = kinc_texture_from_encoded_bytes(bytes.bytes, bytes.length, StringHelper.convert(format), readable);
}
function new(readable: Bool) {
this.readable = readable;
}
static function getRenderTargetFormat(format: TextureFormat): Int {
switch (format) {
case RGBA32: // Target32Bit
return 0;
case RGBA64: // Target64BitFloat
return 1;
case RGBA128: // Target128BitFloat
return 3;
case DEPTH16: // Target16BitDepth
return 4;
default:
return 0;
}
}
static function getDepthBufferBits(depthAndStencil: DepthStencilFormat): Int {
return switch (depthAndStencil) {
case NoDepthAndStencil: -1;
case DepthOnly: 24;
case DepthAutoStencilAuto: 24;
case Depth24Stencil8: 24;
case Depth32Stencil8: 32;
case Depth16: 16;
}
}
static function getStencilBufferBits(depthAndStencil: DepthStencilFormat): Int {
return switch (depthAndStencil) {
case NoDepthAndStencil: -1;
case DepthOnly: -1;
case DepthAutoStencilAuto: 8;
case Depth24Stencil8: 8;
case Depth32Stencil8: 8;
case Depth16: 0;
}
}
static function getTextureFormat(format: TextureFormat): Int {
switch (format) {
case RGBA32:
return 0;
case RGBA128:
return 3;
case RGBA64:
return 4;
case A32:
return 5;
case A16:
return 7;
default:
return 1; // Grey8
}
}
public static function create2(width: Int, height: Int, format: TextureFormat, readable: Bool, renderTarget: Bool,
depthStencil: DepthStencilFormat): Image {
var image = new Image(readable);
image.myFormat = format;
if (renderTarget)
image.initRenderTarget(width, height, getDepthBufferBits(depthStencil), getRenderTargetFormat(format), getStencilBufferBits(depthStencil));
else
image.init(width, height, format);
return image;
}
public static function create3(width: Int, height: Int, depth: Int, format: TextureFormat, readable: Bool, contextId: Int): Image {
var image = new Image(readable);
image.myFormat = format;
image.init3D(width, height, depth, getTextureFormat(format));
return image;
}
function initRenderTarget(width: Int, height: Int, depthBufferBits: Int, format: Int, stencilBufferBits: Int): Void {
_renderTarget = kinc_render_target_create(width, height, depthBufferBits, format, stencilBufferBits);
_texture = null;
}
function init(width: Int, height: Int, format: Int): Void {
_texture = kinc_texture_create(width, height, format, readable);
_renderTarget = null;
}
function init3D(width: Int, height: Int, depth: Int, format: Int): Void {
_texture = kinc_texture_create3d(width, height, depth, format, readable);
_renderTarget = null;
}
function initVideo(video: kha.korehl.Video): Void {
_texture = kinc_video_get_current_image(video._video);
_renderTarget = null;
}
public static function fromFile(filename: String, readable: Bool): Image {
var image = new Image(readable);
var isFloat = StringTools.endsWith(filename, ".hdr");
image.myFormat = isFloat ? TextureFormat.RGBA128 : TextureFormat.RGBA32;
image.initFromFile(filename);
if (image._texture == null) {
return null;
}
return image;
}
function initFromFile(filename: String): Void {
_texture = kinc_texture_create_from_file(StringHelper.convert(filename), readable);
_renderTarget = null;
}
public var g1(get, never): kha.graphics1.Graphics;
function get_g1(): kha.graphics1.Graphics {
if (graphics1 == null) {
graphics1 = new kha.graphics2.Graphics1(this);
}
return graphics1;
}
public var g2(get, never): kha.graphics2.Graphics;
function get_g2(): kha.graphics2.Graphics {
if (graphics2 == null) {
graphics2 = new kha.korehl.graphics4.Graphics2(this);
}
return graphics2;
}
public var g4(get, never): kha.graphics4.Graphics;
function get_g4(): kha.graphics4.Graphics {
if (graphics4 == null) {
graphics4 = new kha.korehl.graphics4.Graphics(this);
}
return graphics4;
}
public static var maxSize(get, never): Int;
static function get_maxSize(): Int {
return 4096;
}
public static var nonPow2Supported(get, never): Bool;
static function get_nonPow2Supported(): Bool {
return kinc_non_pow2_textures_supported();
}
public static function renderTargetsInvertedY(): Bool {
return kinc_graphics_render_targets_inverted_y();
}
public var width(get, never): Int;
function get_width(): Int {
return _texture != null ? kinc_texture_get_width(_texture) : kinc_render_target_get_width(_renderTarget);
}
public var height(get, never): Int;
function get_height(): Int {
return _texture != null ? kinc_texture_get_height(_texture) : kinc_render_target_get_height(_renderTarget);
}
public var depth(get, never): Int;
function get_depth(): Int {
return 1;
}
public var format(get, never): TextureFormat;
function get_format(): TextureFormat {
return myFormat;
}
public var realWidth(get, never): Int;
function get_realWidth(): Int {
return _texture != null ? kinc_texture_get_real_width(_texture) : kinc_render_target_get_real_width(_renderTarget);
}
public var realHeight(get, never): Int;
function get_realHeight(): Int {
return _texture != null ? kinc_texture_get_real_height(_texture) : kinc_render_target_get_real_height(_renderTarget);
}
public var stride(get, never): Int;
function get_stride(): Int {
return _texture != null ? kinc_texture_get_stride(_texture) : (formatByteSize(myFormat) * width);
}
public function isOpaque(x: Int, y: Int): Bool {
return atInternal(x, y) & 0xff != 0;
}
function atInternal(x: Int, y: Int): Int {
return kinc_texture_at(_texture, x, y);
}
public inline function at(x: Int, y: Int): Color {
return Color.fromValue(atInternal(x, y));
}
public function unload(): Void {
_texture != null ? kinc_texture_unload(_texture) : kinc_render_target_unload(_renderTarget);
}
var bytes: Bytes = null;
public function lock(level: Int = 0): Bytes {
bytes = Bytes.alloc(formatByteSize(myFormat) * width * height);
return bytes;
}
public function unlock(): Void {
kinc_texture_unlock(_texture, bytes.getData().bytes);
bytes = null;
}
var pixels: Bytes = null;
public function getPixels(): Bytes {
if (_renderTarget == null)
return null;
if (pixels == null) {
var size = formatByteSize(myFormat) * width * height;
pixels = Bytes.alloc(size);
}
kinc_render_target_get_pixels(_renderTarget, pixels.getData().bytes);
return pixels;
}
static function formatByteSize(format: TextureFormat): Int {
return switch (format) {
case RGBA32: 4;
case L8: 1;
case RGBA128: 16;
case DEPTH16: 2;
case RGBA64: 8;
case A32: 4;
case A16: 2;
default: 4;
}
}
public function generateMipmaps(levels: Int): Void {
_texture != null ? kinc_generate_mipmaps_texture(_texture, levels) : kinc_generate_mipmaps_target(_renderTarget, levels);
}
public function setMipmaps(mipmaps: Array<Image>): Void {
for (i in 0...mipmaps.length) {
var image = mipmaps[i];
var level = i + 1;
kinc_set_mipmap_texture(_texture, image._texture, level);
}
}
public function setDepthStencilFrom(image: Image): Void {
kinc_render_target_set_depth_stencil_from(_renderTarget, image._renderTarget);
}
public function clear(x: Int, y: Int, z: Int, width: Int, height: Int, depth: Int, color: Color): Void {
kinc_texture_clear(_texture, x, y, z, width, height, depth, color);
}
@:hlNative("std", "kinc_texture_create") static function kinc_texture_create(width: Int, height: Int, format: Int, readable: Bool): Pointer {
return null;
}
@:hlNative("std", "kinc_texture_create_from_file") static function kinc_texture_create_from_file(filename: hl.Bytes, readable: Bool): Pointer {
return null;
}
@:hlNative("std", "kinc_texture_create3d") static function kinc_texture_create3d(width: Int, height: Int, depth: Int, format: Int,
readable: Bool): Pointer {
return null;
}
@:hlNative("std", "kinc_video_get_current_image") static function kinc_video_get_current_image(video: Pointer): Pointer {
return null;
}
@:hlNative("std", "kinc_texture_from_bytes") static function kinc_texture_from_bytes(bytes: Pointer, width: Int, height: Int, format: Int,
readable: Bool): Pointer {
return null;
}
@:hlNative("std", "kinc_texture_from_bytes3d") static function kinc_texture_from_bytes3d(bytes: Pointer, width: Int, height: Int, depth: Int, format: Int,
readable: Bool): Pointer {
return null;
}
@:hlNative("std", "kinc_texture_from_encoded_bytes") static function kinc_texture_from_encoded_bytes(bytes: Pointer, length: Int, format: hl.Bytes,
readable: Bool): Pointer {
return null;
}
@:hlNative("std", "kinc_non_pow2_textures_supported") static function kinc_non_pow2_textures_supported(): Bool {
return false;
}
@:hlNative("std", "kinc_graphics_render_targets_inverted_y") static function kinc_graphics_render_targets_inverted_y(): Bool {
return false;
}
@:hlNative("std", "kinc_texture_get_width") static function kinc_texture_get_width(texture: Pointer): Int {
return 0;
}
@:hlNative("std", "kinc_texture_get_height") static function kinc_texture_get_height(texture: Pointer): Int {
return 0;
}
@:hlNative("std", "kinc_texture_get_real_width") static function kinc_texture_get_real_width(texture: Pointer): Int {
return 0;
}
@:hlNative("std", "kinc_texture_get_real_height") static function kinc_texture_get_real_height(texture: Pointer): Int {
return 0;
}
@:hlNative("std", "kinc_texture_get_stride") static function kinc_texture_get_stride(texture: Pointer): Int {
return 0;
}
@:hlNative("std", "kinc_texture_at") static function kinc_texture_at(texture: Pointer, x: Int, y: Int): Int {
return 0;
}
@:hlNative("std", "kinc_texture_unload") static function kinc_texture_unload(texture: Pointer): Void {}
@:hlNative("std", "kinc_render_target_unload") static function kinc_render_target_unload(renderTarget: Pointer): Void {}
@:hlNative("std", "kinc_render_target_create") static function kinc_render_target_create(width: Int, height: Int, depthBufferBits: Int, format: Int,
stencilBufferBits: Int): Pointer {
return null;
}
@:hlNative("std", "kinc_render_target_get_width") static function kinc_render_target_get_width(renderTarget: Pointer): Int {
return 0;
}
@:hlNative("std", "kinc_render_target_get_height") static function kinc_render_target_get_height(renderTarget: Pointer): Int {
return 0;
}
@:hlNative("std", "kinc_render_target_get_real_width") static function kinc_render_target_get_real_width(renderTarget: Pointer): Int {
return 0;
}
@:hlNative("std", "kinc_render_target_get_real_height") static function kinc_render_target_get_real_height(renderTarget: Pointer): Int {
return 0;
}
@:hlNative("std", "kinc_texture_unlock") static function kinc_texture_unlock(texture: Pointer, bytes: Pointer): Void {}
@:hlNative("std", "kinc_render_target_get_pixels") static function kinc_render_target_get_pixels(renderTarget: Pointer, pixels: Pointer): Void {}
@:hlNative("std", "kinc_generate_mipmaps_texture") static function kinc_generate_mipmaps_texture(texture: Pointer, levels: Int): Void {}
@:hlNative("std", "kinc_generate_mipmaps_target") static function kinc_generate_mipmaps_target(renderTarget: Pointer, levels: Int): Void {}
@:hlNative("std", "kinc_set_mipmap_texture") static function kinc_set_mipmap_texture(texture: Pointer, mipmap: Pointer, level: Int): Void {}
@:hlNative("std", "kinc_render_target_set_depth_stencil_from") static function kinc_render_target_set_depth_stencil_from(renderTarget: Pointer,
from: Pointer): Int {
return 0;
}
@:hlNative("std", "kinc_texture_clear") static function kinc_texture_clear(texture: Pointer, x: Int, y: Int, z: Int, width: Int, height: Int, depth: Int,
color: Color): Void {}
}

View File

@ -1,496 +0,0 @@
package kha;
import kha.graphics4.TextureFormat;
import kha.input.Gamepad;
import kha.input.KeyCode;
import kha.input.Keyboard;
import kha.input.Mouse;
import kha.input.MouseImpl;
import kha.input.Pen;
import kha.input.Surface;
import kha.System;
class SystemImpl {
static var framebuffer: Framebuffer;
static var keyboard: Keyboard;
static var mouse: kha.input.Mouse;
static var pen: kha.input.Pen;
static var gamepads: Array<Gamepad>;
static var surface: Surface;
static var mouseLockListeners: Array<Void->Void>;
public static function init(options: SystemOptions, callback: Window->Void): Void {
haxe.Log.trace = function(v: Dynamic, ?infos: haxe.PosInfos) {
var message = infos != null ? infos.className + ":" + infos.lineNumber + ": " + v : Std.string(v);
kinc_log(StringHelper.convert(message));
};
init_kore(StringHelper.convert(options.title), options.width, options.height, options.framebuffer.samplesPerPixel, options.framebuffer.verticalSync,
cast options.window.mode, options.window.windowFeatures);
new Window(0);
Scheduler.init();
Shaders.init();
var g4 = new kha.korehl.graphics4.Graphics();
framebuffer = new Framebuffer(0, null, null, g4);
framebuffer.init(new kha.graphics2.Graphics1(framebuffer), new kha.korehl.graphics4.Graphics2(framebuffer), g4);
final samplesRef: hl.Ref<Int> = kha.audio2.Audio.samplesPerSecond;
kinc_init_audio(kha.audio2.Audio._callCallback, kha.audio2.Audio._readSample, samplesRef);
kha.audio2.Audio.samplesPerSecond = samplesRef.get();
kha.audio1.Audio._init();
kha.audio2.Audio._init();
keyboard = new kha.input.Keyboard();
mouse = new kha.input.MouseImpl();
pen = new kha.input.Pen();
gamepads = new Array<Gamepad>();
for (i in 0...4) {
gamepads[i] = new kha.input.Gamepad(i);
gamepads[i].connected = kinc_gamepad_connected(i);
}
surface = new kha.input.Surface();
mouseLockListeners = new Array();
kinc_register_keyboard(keyDown, keyUp, keyPress);
kinc_register_mouse(mouseDown, mouseUp, mouseMove, mouseWheel);
kinc_register_pen(penDown, penUp, penMove);
kinc_register_gamepad(gamepadAxis, gamepadButton);
kinc_register_surface(touchStart, touchEnd, touchMove);
kinc_register_sensor(kha.input.Sensor._accelerometerChanged, kha.input.Sensor._gyroscopeChanged);
kinc_register_callbacks(foreground, resume, pause, background, shutdown);
kinc_register_dropfiles(dropFiles);
kinc_register_copycutpaste(copy, cut, paste);
Scheduler.start();
callback(Window.get(0));
run_kore();
}
public static function initEx(title: String, options: Array<WindowOptions>, windowCallback: Int->Void, callback: Void->Void): Void {}
@:keep
public static function frame(): Void {
Scheduler.executeFrame();
System.render([framebuffer]);
for (i in 0...4) {
if (gamepads[i].connected && !kinc_gamepad_connected(i)) {
Gamepad.sendDisconnectEvent(i);
}
else if (!gamepads[i].connected && kinc_gamepad_connected(i)) {
Gamepad.sendConnectEvent(i);
}
}
}
public static function getTime(): Float {
return kinc_get_time();
}
public static function windowWidth(windowId: Int): Int {
return kinc_get_window_width(windowId);
}
public static function windowHeight(windowId: Int): Int {
return kinc_get_window_height(windowId);
}
public static function getScreenRotation(): ScreenRotation {
return ScreenRotation.RotationNone;
}
public static function getSystemId(): String {
final b: hl.Bytes = kinc_get_system_id();
return @:privateAccess String.fromUTF8(b);
}
public static function vibrate(ms: Int): Void {
kinc_vibrate(ms);
}
public static function getLanguage(): String {
final b: hl.Bytes = kinc_get_language();
return @:privateAccess String.fromUTF8(b);
}
public static function requestShutdown(): Bool {
kinc_request_shutdown();
return true;
}
public static function getMouse(num: Int): Mouse {
if (num != 0)
return null;
return mouse;
}
public static function getPen(num: Int): Pen {
if (num != 0)
return null;
return pen;
}
public static function getKeyboard(num: Int): Keyboard {
if (num != 0)
return null;
return keyboard;
}
public static function lockMouse(windowId: Int = 0): Void {
if (!isMouseLocked()) {
kinc_mouse_lock(windowId);
for (listener in mouseLockListeners) {
listener();
}
}
}
public static function unlockMouse(windowId: Int = 0): Void {
if (isMouseLocked()) {
kinc_mouse_unlock(windowId);
for (listener in mouseLockListeners) {
listener();
}
}
}
public static function canLockMouse(windowId: Int = 0): Bool {
return kinc_can_lock_mouse(windowId);
}
public static function isMouseLocked(windowId: Int = 0): Bool {
return kinc_is_mouse_locked(windowId);
}
public static function notifyOfMouseLockChange(func: Void->Void, error: Void->Void): Void {
if (canLockMouse(0) && func != null) {
mouseLockListeners.push(func);
}
}
public static function removeFromMouseLockChange(func: Void->Void, error: Void->Void): Void {
if (canLockMouse(0) && func != null) {
mouseLockListeners.remove(func);
}
}
public static function hideSystemCursor(): Void {
kinc_show_mouse(false);
}
public static function showSystemCursor(): Void {
kinc_show_mouse(true);
}
public static function keyDown(code: KeyCode): Void {
keyboard.sendDownEvent(code);
}
public static function keyUp(code: KeyCode): Void {
keyboard.sendUpEvent(code);
}
public static function keyPress(char: Int): Void {
keyboard.sendPressEvent(String.fromCharCode(char));
}
public static function mouseDown(windowId: Int, button: Int, x: Int, y: Int): Void {
mouse.sendDownEvent(windowId, button, x, y);
}
public static function mouseUp(windowId: Int, button: Int, x: Int, y: Int): Void {
mouse.sendUpEvent(windowId, button, x, y);
}
public static function mouseMove(windowId: Int, x: Int, y: Int, movementX: Int, movementY: Int): Void {
mouse.sendMoveEvent(windowId, x, y, movementX, movementY);
}
public static function mouseWheel(windowId: Int, delta: Int): Void {
mouse.sendWheelEvent(windowId, delta);
}
public static function mouseLeave(windowId: Int): Void {
mouse.sendLeaveEvent(windowId);
}
public static function penDown(windowId: Int, x: Int, y: Int, pressure: Float): Void {
pen.sendDownEvent(windowId, x, y, pressure);
}
public static function penUp(windowId: Int, x: Int, y: Int, pressure: Float): Void {
pen.sendUpEvent(windowId, x, y, pressure);
}
public static function penMove(windowId: Int, x: Int, y: Int, pressure: Float): Void {
pen.sendMoveEvent(windowId, x, y, pressure);
}
public static function gamepadAxis(gamepad: Int, axis: Int, value: FastFloat): Void {
gamepads[gamepad].sendAxisEvent(axis, value);
}
public static function gamepadButton(gamepad: Int, button: Int, value: FastFloat): Void {
gamepads[gamepad].sendButtonEvent(button, value);
}
public static function touchStart(index: Int, x: Int, y: Int): Void {
surface.sendTouchStartEvent(index, x, y);
}
public static function touchEnd(index: Int, x: Int, y: Int): Void {
surface.sendTouchEndEvent(index, x, y);
}
public static function touchMove(index: Int, x: Int, y: Int): Void {
surface.sendMoveEvent(index, x, y);
}
public static function foreground(): Void {
System.foreground();
}
public static function resume(): Void {
System.resume();
}
public static function pause(): Void {
System.pause();
}
public static function background(): Void {
System.background();
}
public static function shutdown(): Void {
System.shutdown();
}
public static function dropFiles(filePath: String): Void {
System.dropFiles(filePath);
}
public static function copy(): hl.Bytes {
if (System.copyListener != null) {
final text = System.copyListener();
if (text == null)
return null;
return StringHelper.convert(text);
}
else {
return null;
}
}
public static function cut(): hl.Bytes {
if (System.cutListener != null) {
final text = System.cutListener();
if (text == null)
return null;
return StringHelper.convert(text);
}
else {
return null;
}
}
public static function paste(data: hl.Bytes): Void {
final text = @:privateAccess String.fromUTF8(data);
if (System.pasteListener != null) {
System.pasteListener(text);
}
}
static var fullscreenListeners: Array<Void->Void> = new Array();
static var previousWidth: Int = 0;
static var previousHeight: Int = 0;
public static function canSwitchFullscreen(): Bool {
return true;
}
public static function isFullscreen(): Bool {
return kinc_system_is_fullscreen();
}
public static function requestFullscreen(): Void {
if (!isFullscreen()) {
previousWidth = kinc_get_window_width(0);
previousHeight = kinc_get_window_height(0);
kinc_system_request_fullscreen();
for (listener in fullscreenListeners) {
listener();
}
}
}
public static function exitFullscreen(): Void {
if (isFullscreen()) {
if (previousWidth == 0 || previousHeight == 0) {
previousWidth = kinc_get_window_width(0);
previousHeight = kinc_get_window_height(0);
}
kinc_system_exit_fullscreen(previousWidth, previousHeight);
for (listener in fullscreenListeners) {
listener();
}
}
}
public static function notifyOfFullscreenChange(func: Void->Void, error: Void->Void): Void {
if (canSwitchFullscreen() && func != null) {
fullscreenListeners.push(func);
}
}
public static function removeFromFullscreenChange(func: Void->Void, error: Void->Void): Void {
if (canSwitchFullscreen() && func != null) {
fullscreenListeners.remove(func);
}
}
public static function changeResolution(width: Int, height: Int): Void {
kinc_system_change_resolution(width, height);
}
public static function setKeepScreenOn(on: Bool): Void {
kinc_system_set_keepscreenon(on);
}
public static function loadUrl(url: String): Void {
kinc_system_load_url(StringHelper.convert(url));
}
public static function getGamepadId(index: Int): String {
final b: hl.Bytes = kinc_get_gamepad_id(index);
return @:privateAccess String.fromUTF8(b);
}
public static function getGamepadVendor(index: Int): String {
final b: hl.Bytes = kinc_get_gamepad_vendor(index);
return @:privateAccess String.fromUTF8(b);
}
public static function setGamepadRumble(index: Int, leftAmount: Float, rightAmount: Float) {}
public static function safeZone(): Float {
return 1.0;
}
public static function login(): Void {}
public static function automaticSafeZone(): Bool {
return true;
}
public static function setSafeZone(value: Float): Void {}
public static function unlockAchievement(id: Int): Void {}
public static function waitingForLogin(): Bool {
return false;
}
public static function disallowUserChange(): Void {}
public static function allowUserChange(): Void {}
@:hlNative("std", "init_kore") static function init_kore(title: hl.Bytes, width: Int, height: Int, samplesPerPixel: Int, vSync: Bool, windowMode: Int,
windowFeatures: Int): Void {}
@:hlNative("std", "run_kore") static function run_kore(): Void {}
@:hlNative("std", "kinc_init_audio") static function kinc_init_audio(callCallback: Int->Void, readSample: Void->FastFloat,
outSamplesPerSecond: hl.Ref<Int>): Void {}
@:hlNative("std", "kinc_log") static function kinc_log(v: hl.Bytes): Void {}
@:hlNative("std", "kinc_get_time") static function kinc_get_time(): Float {
return 0;
}
@:hlNative("std", "kinc_get_window_width") static function kinc_get_window_width(window: Int): Int {
return 0;
}
@:hlNative("std", "kinc_get_window_height") static function kinc_get_window_height(window: Int): Int {
return 0;
}
@:hlNative("std", "kinc_get_system_id") static function kinc_get_system_id(): hl.Bytes {
return null;
}
@:hlNative("std", "kinc_vibrate") static function kinc_vibrate(ms: Int): Void {}
@:hlNative("std", "kinc_get_language") static function kinc_get_language(): hl.Bytes {
return null;
}
@:hlNative("std", "kinc_request_shutdown") static function kinc_request_shutdown(): Void {}
@:hlNative("std", "kinc_mouse_lock") static function kinc_mouse_lock(windowId: Int): Void {}
@:hlNative("std", "kinc_mouse_unlock") static function kinc_mouse_unlock(windowId: Int): Void {}
@:hlNative("std", "kinc_can_lock_mouse") static function kinc_can_lock_mouse(windowId: Int): Bool {
return false;
}
@:hlNative("std", "kinc_is_mouse_locked") static function kinc_is_mouse_locked(windowId: Int): Bool {
return false;
}
@:hlNative("std", "kinc_show_mouse") static function kinc_show_mouse(show: Bool): Void {}
@:hlNative("std", "kinc_system_is_fullscreen") static function kinc_system_is_fullscreen(): Bool {
return false;
}
@:hlNative("std", "kinc_system_request_fullscreen") static function kinc_system_request_fullscreen(): Void {}
@:hlNative("std", "kinc_system_exit_fullscreen") static function kinc_system_exit_fullscreen(previousWidth: Int, previousHeight: Int): Void {}
@:hlNative("std", "kinc_register_keyboard") static function kinc_register_keyboard(keyDown: KeyCode->Void, keyUp: KeyCode->Void,
keyPress: Int->Void): Void {}
@:hlNative("std", "kinc_register_mouse") static function kinc_register_mouse(mouseDown: Int->Int->Int->Int->Void, mouseUp: Int->Int->Int->Int->Void,
mouseMove: Int->Int->Int->Int->Int->Void, mouseWheel: Int->Int->Void): Void {}
@:hlNative("std", "kinc_register_pen") static function kinc_register_pen(penDown: Int->Int->Int->Float->Void, penUp: Int->Int->Int->Float->Void,
penMove: Int->Int->Int->Float->Void): Void {}
@:hlNative("std", "kinc_register_gamepad") static function kinc_register_gamepad(gamepadAxis: Int->Int->FastFloat->Void,
gamepadButton: Int->Int->FastFloat->Void): Void {}
@:hlNative("std", "kinc_register_surface") static function kinc_register_surface(touchStart: Int->Int->Int->Void, touchEnd: Int->Int->Int->Void,
touchMove: Int->Int->Int->Void): Void {}
@:hlNative("std", "kinc_register_sensor") static function kinc_register_sensor(accelerometerChanged: Float->Float->Float->Void,
gyroscopeChanged: Float->Float->Float->Void): Void {}
@:hlNative("std", "kinc_register_callbacks") static function kinc_register_callbacks(foreground: Void->Void, resume: Void->Void, pause: Void->Void,
background: Void->Void, shutdown: Void->Void): Void {}
@:hlNative("std", "kinc_register_dropfiles") static function kinc_register_dropfiles(dropFiles: String->Void): Void {}
@:hlNative("std", "kinc_register_copycutpaste") static function kinc_register_copycutpaste(copy: Void->hl.Bytes, cut: Void->hl.Bytes,
paste: hl.Bytes->Void): Void {}
@:hlNative("std", "kinc_system_change_resolution") static function kinc_system_change_resolution(width: Int, height: Int): Void {}
@:hlNative("std", "kinc_system_set_keepscreenon") static function kinc_system_set_keepscreenon(on: Bool): Void {}
@:hlNative("std", "kinc_system_load_url") static function kinc_system_load_url(url: hl.Bytes): Void {}
@:hlNative("std", "kinc_get_gamepad_id") static function kinc_get_gamepad_id(index: Int): hl.Bytes {
return null;
}
@:hlNative("std", "kinc_get_gamepad_vendor") static function kinc_get_gamepad_vendor(index: Int): hl.Bytes {
return null;
}
@:hlNative("std", "kinc_gamepad_connected") static function kinc_gamepad_connected(index: Int): Bool {
return false;
}
}

View File

@ -1,448 +0,0 @@
package kha.arrays;
class ByteArrayPrivate {
public var self: ByteBuffer;
public var byteArrayOffset: Int;
public var byteArrayLength: Int;
public inline function new(offset: Int, length: Int) {
this.byteArrayOffset = offset;
this.byteArrayLength = length;
}
}
abstract ByteArray(ByteArrayPrivate) {
public var buffer(get, never): ByteBuffer;
inline function get_buffer(): ByteBuffer {
return this.self;
}
public var byteLength(get, never): Int;
inline function get_byteLength(): Int {
return this.byteArrayLength;
}
public var byteOffset(get, never): Int;
inline function get_byteOffset(): Int {
return this.byteArrayOffset;
}
public inline function new(buffer: ByteBuffer, byteOffset: Int, byteLength: Int): Void {
this = new ByteArrayPrivate(byteOffset, byteLength);
this.self = buffer;
}
public static inline function make(byteLength: Int): ByteArray {
var buffer = ByteBuffer.create(byteLength);
return new ByteArray(buffer, 0, byteLength);
}
public inline function free() {
this.self.free();
}
public inline function getData(): Pointer {
return this.self;
}
// Get
public inline function getInt8(byteOffset: Int): Int {
return kinc_bytearray_getint8(this.self, this.byteArrayOffset + byteOffset);
}
public inline function getUint8(byteOffset: Int): Int {
return kinc_bytearray_getuint8(this.self, this.byteArrayOffset + byteOffset);
}
public inline function getInt16(byteOffset: Int): Int {
return kinc_bytearray_getint16(this.self, this.byteArrayOffset + byteOffset);
}
public inline function getUint16(byteOffset: Int): Int {
return kinc_bytearray_getuint16(this.self, this.byteArrayOffset + byteOffset);
}
public inline function getInt32(byteOffset: Int): Int {
return kinc_bytearray_getint32(this.self, this.byteArrayOffset + byteOffset);
}
public inline function getUint32(byteOffset: Int): Int {
return kinc_bytearray_getuint32(this.self, this.byteArrayOffset + byteOffset);
}
public inline function getFloat32(byteOffset: Int): FastFloat {
return kinc_bytearray_getfloat32(this.self, this.byteArrayOffset + byteOffset);
}
public inline function getFloat64(byteOffset: Int): Float {
return kinc_bytearray_getfloat64(this.self, this.byteArrayOffset + byteOffset);
}
// Set
public inline function setInt8(byteOffset: Int, value: Int): Void {
kinc_bytearray_setint8(this.self, this.byteArrayOffset + byteOffset, value);
}
public inline function setUint8(byteOffset: Int, value: Int): Void {
kinc_bytearray_setuint8(this.self, this.byteArrayOffset + byteOffset, value);
}
public inline function setInt16(byteOffset: Int, value: Int): Void {
kinc_bytearray_setint16(this.self, this.byteArrayOffset + byteOffset, value);
}
public inline function setUint16(byteOffset: Int, value: Int): Void {
kinc_bytearray_setuint16(this.self, this.byteArrayOffset + byteOffset, value);
}
public inline function setInt32(byteOffset: Int, value: Int): Void {
kinc_bytearray_setint32(this.self, this.byteArrayOffset + byteOffset, value);
}
public inline function setUint32(byteOffset: Int, value: hl.I64): Void {
kinc_bytearray_setuint32(this.self, this.byteArrayOffset + byteOffset, value);
}
public inline function setFloat32(byteOffset: Int, value: FastFloat): Void {
kinc_bytearray_setfloat32(this.self, this.byteArrayOffset + byteOffset, value);
}
public inline function setFloat64(byteOffset: Int, value: Float): Void {
kinc_bytearray_setfloat64(this.self, this.byteArrayOffset + byteOffset, value);
}
// Get (little endian)
public inline function getInt16LE(byteOffset: Int): Int {
#if !sys_bigendian
return getInt16(byteOffset);
#else
return kinc_bytearray_getint16_le(this.self, this.byteArrayOffset + byteOffset);
#end
}
public inline function getUint16LE(byteOffset: Int): Int {
#if !sys_bigendian
return getUint16(byteOffset);
#else
return kinc_bytearray_getuint16_le(this.self, this.byteArrayOffset + byteOffset);
#end
}
public inline function getInt32LE(byteOffset: Int): Int {
#if !sys_bigendian
return getInt32(byteOffset);
#else
return kinc_bytearray_getint32_le(this.self, this.byteArrayOffset + byteOffset);
#end
}
public inline function getUint32LE(byteOffset: Int): hl.I64 {
#if !sys_bigendian
return getUint32(byteOffset);
#else
return kinc_bytearray_getuint32_le(this.self, this.byteArrayOffset + byteOffset);
#end
}
public inline function getFloat32LE(byteOffset: Int): FastFloat {
#if !sys_bigendian
return getFloat32(byteOffset);
#else
return kinc_bytearray_getfloat32_le(this.self, this.byteArrayOffset + byteOffset);
#end
}
public inline function getFloat64LE(byteOffset: Int): Float {
#if !sys_bigendian
return getFloat64(byteOffset);
#else
return kinc_bytearray_getfloat64_le(this.self, this.byteArrayOffset + byteOffset);
#end
}
// Set (little endian)
public inline function setInt16LE(byteOffset: Int, value: Int): Void {
#if !sys_bigendian
setInt16(byteOffset, value);
#else
kinc_bytearray_setint16_le(this.self, this.byteArrayOffset + byteOffset, value);
#end
}
public inline function setUint16LE(byteOffset: Int, value: Int): Void {
#if !sys_bigendian
setUint16(byteOffset, value);
#else
kinc_bytearray_setuint16_le(this.self, this.byteArrayOffset + byteOffset, value);
#end
}
public inline function setInt32LE(byteOffset: Int, value: Int): Void {
#if !sys_bigendian
setInt32(byteOffset, value);
#else
kinc_bytearray_setint32_le(this.self, this.byteArrayOffset + byteOffset, value);
#end
}
public inline function setUint32LE(byteOffset: Int, value: hl.I64): Void {
#if !sys_bigendian
setUint32(byteOffset, value);
#else
kinc_bytearray_setuint32_le(this.self, this.byteArrayOffset + byteOffset, value);
#end
}
public inline function setFloat32LE(byteOffset: Int, value: FastFloat): Void {
#if !sys_bigendian
setFloat32(byteOffset, value);
#else
kinc_bytearray_setfloat32_le(this.self, this.byteArrayOffset + byteOffset, value);
#end
}
public inline function setFloat64LE(byteOffset: Int, value: Float): Void {
#if !sys_bigendian
setFloat64(byteOffset, value);
#else
kinc_bytearray_setfloat64_le(this.self, this.byteArrayOffset + byteOffset, value);
#end
}
// Get (big endian)
public inline function getInt16BE(byteOffset: Int): Int {
#if sys_bigendian
return getInt16(byteOffset);
#else
return kinc_bytearray_getint16_be(this.self, this.byteArrayOffset + byteOffset);
#end
}
public inline function getUint16BE(byteOffset: Int): Int {
#if sys_bigendian
return getUint16(byteOffset);
#else
return kinc_bytearray_getuint16_be(this.self, this.byteArrayOffset + byteOffset);
#end
}
public inline function getInt32BE(byteOffset: Int): Int {
#if sys_bigendian
return getInt32(byteOffset);
#else
return kinc_bytearray_getint32_be(this.self, this.byteArrayOffset + byteOffset);
#end
}
public inline function getUint32BE(byteOffset: Int): hl.I64 {
#if sys_bigendian
return getUint32(byteOffset);
#else
return kinc_bytearray_getuint32_be(this.self, this.byteArrayOffset + byteOffset);
#end
}
public inline function getFloat32BE(byteOffset: Int): FastFloat {
#if sys_bigendian
return getFloat32(byteOffset);
#else
return kinc_bytearray_getfloat32_be(this.self, this.byteArrayOffset + byteOffset);
#end
}
public inline function getFloat64BE(byteOffset: Int): Float {
#if sys_bigendian
return getFloat64(byteOffset);
#else
return kinc_bytearray_getfloat64_be(this.self, this.byteArrayOffset + byteOffset);
#end
}
// Set (big endian)
public inline function setInt16BE(byteOffset: Int, value: Int): Void {
#if sys_bigendian
setInt16(byteOffset, value);
#else
kinc_bytearray_setint16_be(this.self, this.byteArrayOffset + byteOffset, value);
#end
}
public inline function setUint16BE(byteOffset: Int, value: Int): Void {
#if sys_bigendian
setUint16(byteOffset, value);
#else
kinc_bytearray_setuint16_be(this.self, this.byteArrayOffset + byteOffset, value);
#end
}
public inline function setInt32BE(byteOffset: Int, value: Int): Void {
#if sys_bigendian
setInt32(byteOffset, value);
#else
kinc_bytearray_setint32_be(this.self, this.byteArrayOffset + byteOffset, value);
#end
}
public inline function setUint32BE(byteOffset: Int, value: hl.I64): Void {
#if sys_bigendian
setUint32(byteOffset, value);
#else
kinc_bytearray_setuint32_be(this.self, this.byteArrayOffset + byteOffset, value);
#end
}
public inline function setFloat32BE(byteOffset: Int, value: FastFloat): Void {
#if sys_bigendian
setFloat32(byteOffset, value);
#else
kinc_bytearray_setfloat32_be(this.self, this.byteArrayOffset + byteOffset, value);
#end
}
public inline function setFloat64BE(byteOffset: Int, value: Float): Void {
#if sys_bigendian
setFloat64(byteOffset, value);
#else
kinc_bytearray_setfloat64_be(this.self, this.byteArrayOffset + byteOffset, value);
#end
}
public function subarray(start: Int, ?end: Int): ByteArray {
var offset: Int = this.byteArrayOffset + start;
var length: Int = end == null ? this.byteArrayLength - start : end - start;
return new ByteArray(this.self, offset, length);
}
@:hlNative("std", "kinc_bytearray_getint8") static function kinc_bytearray_getint8(bytearray: Pointer, byteOffset: Int): Int {
return 0;
}
@:hlNative("std", "kinc_bytearray_getuint8") static function kinc_bytearray_getuint8(bytearray: Pointer, byteOffset: Int): Int {
return 0;
}
@:hlNative("std", "kinc_bytearray_getint16") static function kinc_bytearray_getint16(bytearray: Pointer, byteOffset: Int): Int {
return 0;
}
@:hlNative("std", "kinc_bytearray_getuint16") static function kinc_bytearray_getuint16(bytearray: Pointer, byteOffset: Int): Int {
return 0;
}
@:hlNative("std", "kinc_bytearray_getint32") static function kinc_bytearray_getint32(bytearray: Pointer, byteOffset: Int): Int {
return 0;
}
@:hlNative("std", "kinc_bytearray_getuint32") static function kinc_bytearray_getuint32(bytearray: Pointer, byteOffset: Int): hl.I64 {
return 0;
}
@:hlNative("std", "kinc_bytearray_getfloat32") static function kinc_bytearray_getfloat32(bytearray: Pointer, byteOffset: Int): FastFloat {
return 0;
}
@:hlNative("std", "kinc_bytearray_getfloat64") static function kinc_bytearray_getfloat64(bytearray: Pointer, byteOffset: Int): Float {
return 0;
}
@:hlNative("std", "kinc_bytearray_setint8") static function kinc_bytearray_setint8(bytearray: Pointer, byteOffset: Int, value: Int) {}
@:hlNative("std", "kinc_bytearray_setuint8") static function kinc_bytearray_setuint8(bytearray: Pointer, byteOffset: Int, value: Int) {}
@:hlNative("std", "kinc_bytearray_setint16") static function kinc_bytearray_setint16(bytearray: Pointer, byteOffset: Int, value: Int) {}
@:hlNative("std", "kinc_bytearray_setuint16") static function kinc_bytearray_setuint16(bytearray: Pointer, byteOffset: Int, value: Int) {}
@:hlNative("std", "kinc_bytearray_setint32") static function kinc_bytearray_setint32(bytearray: Pointer, byteOffset: Int, value: Int) {}
@:hlNative("std", "kinc_bytearray_setuint32") static function kinc_bytearray_setuint32(bytearray: Pointer, byteOffset: Int, value: hl.I64) {}
@:hlNative("std", "kinc_bytearray_setfloat32") static function kinc_bytearray_setfloat32(bytearray: Pointer, byteOffset: Int, value: FastFloat) {}
@:hlNative("std", "kinc_bytearray_setfloat64") static function kinc_bytearray_setfloat64(bytearray: Pointer, byteOffset: Int, value: Float) {}
// Variants for little endian on big endian system
@:hlNative("std", "kinc_bytearray_getint16_le") static function kinc_bytearray_getint16_le(bytearray: Pointer, byteOffset: Int): Int {
return 0;
}
@:hlNative("std", "kinc_bytearray_getuint16_le") static function kinc_bytearray_getuint16_le(bytearray: Pointer, byteOffset: Int): Int {
return 0;
}
@:hlNative("std", "kinc_bytearray_getint32_le") static function kinc_bytearray_getint32_le(bytearray: Pointer, byteOffset: Int): Int {
return 0;
}
@:hlNative("std", "kinc_bytearray_getuint32_le") static function kinc_bytearray_getuint32_le(bytearray: Pointer, byteOffset: Int): hl.I64 {
return 0;
}
@:hlNative("std", "kinc_bytearray_getfloat32_le") static function kinc_bytearray_getfloat32_le(bytearray: Pointer, byteOffset: Int): FastFloat {
return 0;
}
@:hlNative("std", "kinc_bytearray_getfloat64_le") static function kinc_bytearray_getfloat64_le(bytearray: Pointer, byteOffset: Int): Float {
return 0;
}
@:hlNative("std", "kinc_bytearray_setint16_le") static function kinc_bytearray_setint16_le(bytearray: Pointer, byteOffset: Int, value: Int) {}
@:hlNative("std", "kinc_bytearray_setuint16_le") static function kinc_bytearray_setuint16_le(bytearray: Pointer, byteOffset: Int, value: Int) {}
@:hlNative("std", "kinc_bytearray_setint32_le") static function kinc_bytearray_setint32_le(bytearray: Pointer, byteOffset: Int, value: Int) {}
@:hlNative("std", "kinc_bytearray_setuint32_le") static function kinc_bytearray_setuint32_le(bytearray: Pointer, byteOffset: Int, value: hl.I64) {}
@:hlNative("std", "kinc_bytearray_setfloat32_le") static function kinc_bytearray_setfloat32_le(bytearray: Pointer, byteOffset: Int, value: FastFloat) {}
@:hlNative("std", "kinc_bytearray_setfloat64_le") static function kinc_bytearray_setfloat64_le(bytearray: Pointer, byteOffset: Int, value: Float) {}
// Variants for big endian on little endian system
@:hlNative("std", "kinc_bytearray_getint16_be") static function kinc_bytearray_getint16_be(bytearray: Pointer, byteOffset: Int): Int {
return 0;
}
@:hlNative("std", "kinc_bytearray_getuint16_be") static function kinc_bytearray_getuint16_be(bytearray: Pointer, byteOffset: Int): Int {
return 0;
}
@:hlNative("std", "kinc_bytearray_getint32_be") static function kinc_bytearray_getint32_be(bytearray: Pointer, byteOffset: Int): Int {
return 0;
}
@:hlNative("std", "kinc_bytearray_getuint32_be") static function kinc_bytearray_getuint32_be(bytearray: Pointer, byteOffset: Int): hl.I64 {
return 0;
}
@:hlNative("std", "kinc_bytearray_getfloat32_be") static function kinc_bytearray_getfloat32_be(bytearray: Pointer, byteOffset: Int): FastFloat {
return 0;
}
@:hlNative("std", "kinc_bytearray_getfloat64_be") static function kinc_bytearray_getfloat64_be(bytearray: Pointer, byteOffset: Int): Float {
return 0;
}
@:hlNative("std", "kinc_bytearray_setint16_be") static function kinc_bytearray_setint16_be(bytearray: Pointer, byteOffset: Int, value: Int) {}
@:hlNative("std", "kinc_bytearray_setuint16_be") static function kinc_bytearray_setuint16_be(bytearray: Pointer, byteOffset: Int, value: Int) {}
@:hlNative("std", "kinc_bytearray_setint32_be") static function kinc_bytearray_setint32_be(bytearray: Pointer, byteOffset: Int, value: Int) {}
@:hlNative("std", "kinc_bytearray_setuint32_be") static function kinc_bytearray_setuint32_be(bytearray: Pointer, byteOffset: Int, value: hl.I64) {}
@:hlNative("std", "kinc_bytearray_setfloat32_be") static function kinc_bytearray_setfloat32_be(bytearray: Pointer, byteOffset: Int, value: FastFloat) {}
@:hlNative("std", "kinc_bytearray_setfloat64_be") static function kinc_bytearray_setfloat64_be(bytearray: Pointer, byteOffset: Int, value: Float) {}
}

View File

@ -1,171 +0,0 @@
package kha.compute;
import kha.arrays.Float32Array;
import kha.Image;
import kha.FastFloat;
import kha.math.FastMatrix3;
import kha.math.FastMatrix4;
import kha.math.FastVector2;
import kha.math.FastVector3;
import kha.math.FastVector4;
import kha.graphics4.CubeMap;
import kha.graphics4.TextureAddressing;
import kha.graphics4.TextureFilter;
import kha.graphics4.MipMapFilter;
class Compute {
public static function setBool(location: kha.compute.ConstantLocation, value: Bool): Void {
kinc_compute_set_bool(location._location, value);
}
public static function setInt(location: kha.compute.ConstantLocation, value: Int): Void {
kinc_compute_set_int(location._location, value);
}
public static function setFloat(location: kha.compute.ConstantLocation, value: FastFloat): Void {
kinc_compute_set_float(location._location, value);
}
public static function setFloat2(location: kha.compute.ConstantLocation, value1: FastFloat, value2: FastFloat): Void {
kinc_compute_set_float2(location._location, value1, value2);
}
public static function setFloat3(location: kha.compute.ConstantLocation, value1: FastFloat, value2: FastFloat, value3: FastFloat): Void {
kinc_compute_set_float3(location._location, value1, value2, value3);
}
public static function setFloat4(location: kha.compute.ConstantLocation, value1: FastFloat, value2: FastFloat, value3: FastFloat,
value4: FastFloat): Void {
kinc_compute_set_float4(location._location, value1, value2, value3, value4);
}
public static function setVector2(location: kha.compute.ConstantLocation, value: FastVector2): Void {
kinc_compute_set_float2(location._location, value.x, value.y);
}
public static function setVector3(location: kha.compute.ConstantLocation, value: FastVector3): Void {
kinc_compute_set_float3(location._location, value.x, value.y, value.z);
}
public static function setVector4(location: kha.compute.ConstantLocation, value: FastVector4): Void {
kinc_compute_set_float4(location._location, value.x, value.y, value.z, value.w);
}
public static function setFloats(location: kha.compute.ConstantLocation, values: Float32Array): Void {
kinc_compute_set_floats(location._location, values.getData(), values.length);
}
public static function setMatrix(location: kha.compute.ConstantLocation, matrix: FastMatrix4): Void {
kinc_compute_set_matrix(location._location, matrix._00, matrix._10, matrix._20, matrix._30, matrix._01, matrix._11, matrix._21, matrix._31,
matrix._02, matrix._12, matrix._22, matrix._32, matrix._03, matrix._13, matrix._23, matrix._33);
}
public static function setMatrix3(location: kha.compute.ConstantLocation, matrix: FastMatrix3): Void {
kinc_compute_set_matrix3(location._location, matrix._00, matrix._10, matrix._20, matrix._01, matrix._11, matrix._21, matrix._02, matrix._12,
matrix._22);
}
public static function setBuffer(buffer: ShaderStorageBuffer, index: Int) {
// Kore::Compute::setBuffer(buffer->buffer, index);
}
public static function setTexture(unit: TextureUnit, texture: Image, access: Access) {
if (texture._texture != null)
kinc_compute_set_texture(unit._unit, texture._texture, access);
else
kinc_compute_set_target(unit._unit, texture._renderTarget, access);
}
public static function setSampledTexture(unit: TextureUnit, texture: Image) {
if (texture._texture != null)
kinc_compute_set_sampled_texture(unit._unit, texture._texture);
else
kinc_compute_set_sampled_target(unit._unit, texture._renderTarget);
}
public static function setSampledDepthTexture(unit: TextureUnit, texture: Image) {
kinc_compute_set_sampled_depth_target(unit._unit, texture._renderTarget);
}
public static function setSampledCubeMap(unit: TextureUnit, cubeMap: CubeMap) {
if (cubeMap._texture != null)
kinc_compute_set_sampled_cubemap_texture(unit._unit, cubeMap._texture);
else
kinc_compute_set_sampled_cubemap_target(unit._unit, cubeMap._renderTarget);
}
public static function setSampledDepthCubeMap(unit: TextureUnit, cubeMap: CubeMap) {
kinc_compute_set_sampled_cubemap_depth_target(unit._unit, cubeMap._renderTarget);
}
public static function setTextureParameters(unit: TextureUnit, uAddressing: TextureAddressing, vAddressing: TextureAddressing,
minificationFilter: TextureFilter, magnificationFilter: TextureFilter, mipmapFilter: MipMapFilter): Void {
kinc_compute_set_texture_parameters(unit._unit, uAddressing, vAddressing, minificationFilter, magnificationFilter, mipmapFilter);
}
public static function setTexture3DParameters(unit: TextureUnit, uAddressing: TextureAddressing, vAddressing: TextureAddressing,
wAddressing: TextureAddressing, minificationFilter: TextureFilter, magnificationFilter: TextureFilter, mipmapFilter: MipMapFilter): Void {
kinc_compute_set_texture3d_parameters(unit._unit, uAddressing, vAddressing, wAddressing, minificationFilter, magnificationFilter, mipmapFilter);
}
public static function setShader(shader: Shader) {
kinc_compute_set_shader(shader._shader);
}
public static function compute(x: Int, y: Int, z: Int) {
kinc_compute_compute(x, y, z);
}
@:hlNative("std", "kinc_compute_set_bool") static function kinc_compute_set_bool(location: Pointer, value: Bool): Void {}
@:hlNative("std", "kinc_compute_set_int") static function kinc_compute_set_int(location: Pointer, value: Int): Void {}
@:hlNative("std", "kinc_compute_set_float") static function kinc_compute_set_float(location: Pointer, value: FastFloat): Void {}
@:hlNative("std", "kinc_compute_set_float2") static function kinc_compute_set_float2(location: Pointer, value1: FastFloat, value2: FastFloat): Void {}
@:hlNative("std", "kinc_compute_set_float3") static function kinc_compute_set_float3(location: Pointer, value1: FastFloat, value2: FastFloat,
value3: FastFloat): Void {}
@:hlNative("std", "kinc_compute_set_float4") static function kinc_compute_set_float4(location: Pointer, value1: FastFloat, value2: FastFloat,
value3: FastFloat, value4: FastFloat): Void {}
@:hlNative("std", "kinc_compute_set_floats") static function kinc_compute_set_floats(location: Pointer, values: Pointer, count: Int): Void {}
@:hlNative("std", "kinc_compute_set_matrix") static function kinc_compute_set_matrix(location: Pointer, _00: FastFloat, _10: FastFloat, _20: FastFloat,
_30: FastFloat, _01: FastFloat, _11: FastFloat, _21: FastFloat, _31: FastFloat, _02: FastFloat, _12: FastFloat, _22: FastFloat, _32: FastFloat,
_03: FastFloat, _13: FastFloat, _23: FastFloat, _33: FastFloat): Void {}
@:hlNative("std", "kinc_compute_set_matrix3") static function kinc_compute_set_matrix3(location: Pointer, _00: FastFloat, _10: FastFloat, _20: FastFloat,
_01: FastFloat, _11: FastFloat, _21: FastFloat, _02: FastFloat, _12: FastFloat, _22: FastFloat): Void {}
@:hlNative("std", "kinc_compute_set_texture") static function kinc_compute_set_texture(unit: Pointer, texture: Pointer, access: Int): Void {}
@:hlNative("std", "kinc_compute_set_target") static function kinc_compute_set_target(unit: Pointer, renderTarget: Pointer, access: Int): Void {}
@:hlNative("std", "kinc_compute_set_sampled_texture") static function kinc_compute_set_sampled_texture(unit: Pointer, texture: Pointer): Void {}
@:hlNative("std", "kinc_compute_set_sampled_target") static function kinc_compute_set_sampled_target(unit: Pointer, renderTarget: Pointer): Void {}
@:hlNative("std", "kinc_compute_set_sampled_depth_target") static function kinc_compute_set_sampled_depth_target(unit: Pointer,
renderTarget: Pointer): Void {}
@:hlNative("std", "kinc_compute_set_sampled_cubemap_texture") static function kinc_compute_set_sampled_cubemap_texture(unit: Pointer,
texture: Pointer): Void {}
@:hlNative("std", "kinc_compute_set_sampled_cubemap_target") static function kinc_compute_set_sampled_cubemap_target(unit: Pointer,
renderTarget: Pointer): Void {}
@:hlNative("std", "kinc_compute_set_sampled_cubemap_depth_target") static function kinc_compute_set_sampled_cubemap_depth_target(unit: Pointer,
renderTarget: Pointer): Void {}
@:hlNative("std", "kinc_compute_set_texture_parameters") static function kinc_compute_set_texture_parameters(unit: Pointer, uAddressing: Int,
vAddressing: Int, minificationFilter: Int, magnificationFilter: Int, mipmapFilter: Int): Void {}
@:hlNative("std", "kinc_compute_set_texture3d_parameters") static function kinc_compute_set_texture3d_parameters(unit: Pointer, uAddressing: Int,
vAddressing: Int, wAddressing: Int, minificationFilter: Int, magnificationFilter: Int, mipmapFilter: Int): Void {}
@:hlNative("std", "kinc_compute_set_shader") static function kinc_compute_set_shader(shader: Pointer): Void {}
@:hlNative("std", "kinc_compute_compute") static function kinc_compute_compute(x: Int, y: Int, z: Int): Void {}
}

View File

@ -1,9 +0,0 @@
package kha.compute;
class ConstantLocation {
public var _location: Pointer;
public function new(location: Pointer) {
_location = location;
}
}

View File

@ -1,37 +0,0 @@
package kha.compute;
import kha.Blob;
class Shader {
public var _shader: Pointer;
public function new(sources: Array<Blob>, files: Array<String>) {
_shader = kinc_compute_create_shader(sources[0].bytes.getData(), sources[0].bytes.getData().length);
}
public function delete(): Void {
kinc_compute_delete_shader(_shader);
}
public function getConstantLocation(name: String): ConstantLocation {
return new ConstantLocation(kinc_compute_get_constantlocation(_shader, StringHelper.convert(name)));
}
public function getTextureUnit(name: String): TextureUnit {
return new TextureUnit(kinc_compute_get_textureunit(_shader, StringHelper.convert(name)));
}
@:hlNative("std", "kinc_compute_create_shader") static function kinc_compute_create_shader(data: hl.Bytes, length: Int): Pointer {
return null;
}
@:hlNative("std", "kinc_compute_delete_shader") static function kinc_compute_delete_shader(shader: Pointer): Void {}
@:hlNative("std", "kinc_compute_get_constantlocation") static function kinc_compute_get_constantlocation(shader: Pointer, name: hl.Bytes): Pointer {
return null;
}
@:hlNative("std", "kinc_compute_get_textureunit") static function kinc_compute_get_textureunit(shader: Pointer, name: hl.Bytes): Pointer {
return null;
}
}

View File

@ -1,26 +0,0 @@
package kha.compute;
import kha.graphics4.VertexData;
class ShaderStorageBuffer {
public var _buffer: Pointer;
var data: Array<Int>;
var myCount: Int;
public function new(indexCount: Int, type: VertexData) {}
function init(indexCount: Int, type: VertexData) {}
public function delete(): Void {}
public function lock(): Array<Int> {
return data;
}
public function unlock(): Void {}
public function count(): Int {
return myCount;
}
}

View File

@ -1,9 +0,0 @@
package kha.compute;
class TextureUnit {
public var _unit: Pointer;
public function new(unit: Pointer) {
_unit = unit;
}
}

View File

@ -1,70 +0,0 @@
package kha.graphics4;
using StringTools;
import kha.Blob;
class FragmentShader {
public var _shader: Pointer;
public function new(sources: Array<Blob>, files: Array<String>) {
//initShader(sources[0]);
var shaderBlob: Blob = null;
var shaderFile: String = null;
#if kha_opengl
final expectedExtension = ".glsl";
#elseif kha_direct3d11
final expectedExtension = ".d3d11";
#elseif kha_direct3d12
final expectedExtension = ".d3d12";
#elseif kha_metal
final expectedExtension = ".metal";
#elseif kha_vulkan
final expectedExtension = ".spirv";
#else
final expectedExtension = ".glsl";
#end
if (sources != null && files != null) {
for (i in 0...files.length) {
if (files[i].endsWith(expectedExtension)) {
shaderBlob = sources[i];
shaderFile = files[i];
break;
}
}
}
if (shaderBlob == null && sources != null && sources.length > 0) {
trace('Warning: Could not find shader with extension ${expectedExtension}. Falling back to sources[0]: ${files != null && files.length > 0 ? files[0] : "Unknown"}');
shaderBlob = sources[0];
}
if (shaderBlob != null) {
initShader(shaderBlob);
} else {
trace('Error: No suitable fragment shader source found!');
}
}
function initShader(source: Blob): Void {
//_shader = kinc_create_fragmentshader(source.bytes.getData(), source.bytes.getData().length);
_shader = kinc_create_fragmentshader(source.bytes.getData(), source.length); // Use source.length here
}
public static function fromSource(source: String): FragmentShader {
var sh = new FragmentShader(null, null);
sh._shader = kinc_fragmentshader_from_source(StringHelper.convert(source));
return sh;
}
public function delete(): Void {}
@:hlNative("std", "kinc_create_fragmentshader") static function kinc_create_fragmentshader(data: hl.Bytes, length: Int): Pointer {
return null;
}
@:hlNative("std", "kinc_fragmentshader_from_source") static function kinc_fragmentshader_from_source(source: hl.Bytes): Pointer {
return null;
}
}

View File

@ -1,379 +0,0 @@
package kha.korehl.graphics4;
import kha.arrays.Float32Array;
import kha.graphics4.CubeMap;
import kha.graphics4.MipMapFilter;
import kha.graphics4.PipelineState;
import kha.graphics4.TextureAddressing;
import kha.graphics4.TextureFilter;
import kha.graphics4.Usage;
import kha.graphics4.VertexBuffer;
import kha.math.FastMatrix3;
import kha.math.FastMatrix4;
import kha.math.FastVector2;
import kha.math.FastVector3;
import kha.math.FastVector4;
import kha.Canvas;
import kha.Image;
import kha.Video;
import kha.Color;
class Graphics implements kha.graphics4.Graphics {
var target: Canvas;
public function new(target: Canvas = null) {
this.target = target;
}
public function vsynced(): Bool {
return kinc_graphics_vsynced();
}
public function refreshRate(): Int {
return kinc_graphics_refreshrate();
}
public function clear(?color: Color, ?z: FastFloat, ?stencil: Int): Void {
var flags: Int = 0;
if (color != null)
flags |= 1;
if (z != null)
flags |= 2;
if (stencil != null)
flags |= 4;
kinc_graphics_clear(flags, color == null ? 0 : color.value, z, stencil);
}
public function viewport(x: Int, y: Int, width: Int, height: Int): Void {
kinc_graphics_viewport(x, y, width, height);
}
public function setVertexBuffer(vertexBuffer: kha.graphics4.VertexBuffer): Void {
kinc_graphics_set_vertexbuffer(vertexBuffer._buffer);
}
public function setVertexBuffers(vertexBuffers: Array<kha.graphics4.VertexBuffer>): Void {
kinc_graphics_set_vertexbuffers(vertexBuffers.length > 0 ? vertexBuffers[0]._buffer : null,
vertexBuffers.length > 1 ? vertexBuffers[1]._buffer : null, vertexBuffers.length > 2 ? vertexBuffers[2]._buffer : null,
vertexBuffers.length > 3 ? vertexBuffers[3]._buffer : null, vertexBuffers.length);
}
public function setIndexBuffer(indexBuffer: kha.graphics4.IndexBuffer): Void {
kinc_graphics_set_indexbuffer(indexBuffer._buffer);
}
public function maxTextureSize(): Int {
return 4096;
}
public function supportsNonPow2Textures(): Bool {
return false;
}
public function setCubeMap(unit: kha.graphics4.TextureUnit, cubeMap: kha.graphics4.CubeMap): Void {
if (cubeMap == null)
return;
if (cubeMap._texture != null)
kinc_graphics_set_cubemap_texture(cast(unit, kha.korehl.graphics4.TextureUnit)._unit, cubeMap._texture);
else
kinc_graphics_set_cubemap_target(cast(unit, kha.korehl.graphics4.TextureUnit)._unit, cubeMap._renderTarget);
}
public function setCubeMapDepth(unit: kha.graphics4.TextureUnit, cubeMap: kha.graphics4.CubeMap): Void {
if (cubeMap == null)
return;
kinc_graphics_set_cubemap_depth(cast(unit, kha.korehl.graphics4.TextureUnit)._unit, cubeMap._renderTarget);
}
public function scissor(x: Int, y: Int, width: Int, height: Int): Void {
kinc_graphics_scissor(x, y, width, height);
}
public function disableScissor(): Void {
kinc_graphics_disable_scissor();
}
public function instancedRenderingAvailable(): Bool {
return true;
}
public function setTextureParameters(unit: kha.graphics4.TextureUnit, uAddressing: TextureAddressing, vAddressing: TextureAddressing,
minificationFilter: TextureFilter, magnificationFilter: TextureFilter, mipmapFilter: MipMapFilter): Void {
kinc_graphics_set_texture_parameters(cast(unit, kha.korehl.graphics4.TextureUnit)._unit, uAddressing, vAddressing, minificationFilter,
magnificationFilter, mipmapFilter);
}
public function setTexture3DParameters(unit: kha.graphics4.TextureUnit, uAddressing: TextureAddressing, vAddressing: TextureAddressing,
wAddressing: TextureAddressing, minificationFilter: TextureFilter, magnificationFilter: TextureFilter, mipmapFilter: MipMapFilter): Void {
kinc_graphics_set_texture3d_parameters(cast(unit, kha.korehl.graphics4.TextureUnit)._unit, uAddressing, vAddressing, wAddressing, minificationFilter,
magnificationFilter, mipmapFilter);
}
public function setTextureCompareMode(unit: kha.graphics4.TextureUnit, enabled: Bool) {
kinc_graphics_set_texture_compare_mode(cast(unit, kha.korehl.graphics4.TextureUnit)._unit, enabled);
}
public function setCubeMapCompareMode(unit: kha.graphics4.TextureUnit, enabled: Bool) {
kinc_graphics_set_cube_map_compare_mode(cast(unit, kha.korehl.graphics4.TextureUnit)._unit, enabled);
}
public function setTexture(unit: kha.graphics4.TextureUnit, texture: kha.Image): Void {
if (texture == null)
return;
if (texture._texture != null)
kinc_graphics_set_texture(cast(unit, kha.korehl.graphics4.TextureUnit)._unit, texture._texture);
else
kinc_graphics_set_render_target(cast(unit, kha.korehl.graphics4.TextureUnit)._unit, texture._renderTarget);
}
public function setTextureArray(unit: kha.graphics4.TextureUnit, texture: kha.Image): Void {
if (texture == null)
return;
kinc_graphics_set_texture_array(cast(unit, kha.korehl.graphics4.TextureUnit)._unit, texture._textureArray);
}
public function setTextureDepth(unit: kha.graphics4.TextureUnit, texture: kha.Image): Void {
if (texture == null)
return;
kinc_graphics_set_texture_depth(cast(unit, kha.korehl.graphics4.TextureUnit)._unit, texture._renderTarget);
}
public function setVideoTexture(unit: kha.graphics4.TextureUnit, texture: kha.Video): Void {
if (texture == null)
return;
kinc_graphics_set_texture(cast(unit, kha.korehl.graphics4.TextureUnit)._unit, Image.fromVideo(texture)._texture);
}
public function setImageTexture(unit: kha.graphics4.TextureUnit, texture: kha.Image): Void {
kinc_graphics_set_image_texture(cast(unit, kha.korehl.graphics4.TextureUnit)._unit, texture._texture);
}
public function maxBoundTextures(): Int {
return 8;
}
public function setPipeline(pipe: PipelineState): Void {
pipe.set();
}
public function setStencilReferenceValue(value: Int): Void {}
public function setBool(location: kha.graphics4.ConstantLocation, value: Bool): Void {
kinc_graphics_set_bool(cast(location, kha.korehl.graphics4.ConstantLocation)._location, value);
}
public function setInt(location: kha.graphics4.ConstantLocation, value: Int): Void {
kinc_graphics_set_int(cast(location, kha.korehl.graphics4.ConstantLocation)._location, value);
}
public function setInt2(location: kha.graphics4.ConstantLocation, value1: Int, value2: Int): Void {
kinc_graphics_set_int2(cast(location, kha.korehl.graphics4.ConstantLocation)._location, value1, value2);
}
public function setInt3(location: kha.graphics4.ConstantLocation, value1: Int, value2: Int, value3: Int): Void {
kinc_graphics_set_int3(cast(location, kha.korehl.graphics4.ConstantLocation)._location, value1, value2, value3);
}
public function setInt4(location: kha.graphics4.ConstantLocation, value1: Int, value2: Int, value3: Int, value4: Int): Void {
kinc_graphics_set_int4(cast(location, kha.korehl.graphics4.ConstantLocation)._location, value1, value2, value3, value4);
}
public function setInts(location: kha.graphics4.ConstantLocation, values: kha.arrays.Int32Array): Void {
kinc_graphics_set_ints(cast(location, kha.korehl.graphics4.ConstantLocation)._location, values.getData(), values.length);
}
public function setFloat(location: kha.graphics4.ConstantLocation, value: FastFloat): Void {
kinc_graphics_set_float(cast(location, kha.korehl.graphics4.ConstantLocation)._location, value);
}
public function setFloat2(location: kha.graphics4.ConstantLocation, value1: FastFloat, value2: FastFloat): Void {
kinc_graphics_set_float2(cast(location, kha.korehl.graphics4.ConstantLocation)._location, value1, value2);
}
public function setFloat3(location: kha.graphics4.ConstantLocation, value1: FastFloat, value2: FastFloat, value3: FastFloat): Void {
kinc_graphics_set_float3(cast(location, kha.korehl.graphics4.ConstantLocation)._location, value1, value2, value3);
}
public function setFloat4(location: kha.graphics4.ConstantLocation, value1: FastFloat, value2: FastFloat, value3: FastFloat, value4: FastFloat): Void {
kinc_graphics_set_float4(cast(location, kha.korehl.graphics4.ConstantLocation)._location, value1, value2, value3, value4);
}
public function setVector2(location: kha.graphics4.ConstantLocation, value: FastVector2): Void {
kinc_graphics_set_float2(cast(location, kha.korehl.graphics4.ConstantLocation)._location, value.x, value.y);
}
public function setVector3(location: kha.graphics4.ConstantLocation, value: FastVector3): Void {
kinc_graphics_set_float3(cast(location, kha.korehl.graphics4.ConstantLocation)._location, value.x, value.y, value.z);
}
public function setVector4(location: kha.graphics4.ConstantLocation, value: FastVector4): Void {
kinc_graphics_set_float4(cast(location, kha.korehl.graphics4.ConstantLocation)._location, value.x, value.y, value.z, value.w);
}
public function setFloats(location: kha.graphics4.ConstantLocation, values: Float32Array): Void {
kinc_graphics_set_floats(cast(location, kha.korehl.graphics4.ConstantLocation)._location, values.getData(), values.length);
}
public inline function setMatrix(location: kha.graphics4.ConstantLocation, matrix: FastMatrix4): Void {
kinc_graphics_set_matrix(cast(location, kha.korehl.graphics4.ConstantLocation)._location, matrix._00, matrix._10, matrix._20, matrix._30, matrix._01,
matrix._11, matrix._21, matrix._31, matrix._02, matrix._12, matrix._22, matrix._32, matrix._03, matrix._13, matrix._23, matrix._33);
}
public inline function setMatrix3(location: kha.graphics4.ConstantLocation, matrix: FastMatrix3): Void {
kinc_graphics_set_matrix3(cast(location, kha.korehl.graphics4.ConstantLocation)._location, matrix._00, matrix._10, matrix._20, matrix._01, matrix._11,
matrix._21, matrix._02, matrix._12, matrix._22);
}
public function drawIndexedVertices(start: Int = 0, count: Int = -1): Void {
if (count < 0)
kinc_graphics_draw_all_indexed_vertices();
else
kinc_graphics_draw_indexed_vertices(start, count);
}
public function drawIndexedVerticesInstanced(instanceCount: Int, start: Int = 0, count: Int = -1): Void {
if (count < 0)
kinc_graphics_draw_all_indexed_vertices_instanced(instanceCount);
else
kinc_graphics_draw_indexed_vertices_instanced(instanceCount, start, count);
}
function renderToTexture(additionalRenderTargets: Array<Canvas>): Void {
if (additionalRenderTargets != null) {
var len = additionalRenderTargets.length;
var rt0 = cast(target, Image)._renderTarget;
var rt1 = len > 0 ? cast(additionalRenderTargets[0], Image)._renderTarget : null;
var rt2 = len > 1 ? cast(additionalRenderTargets[1], Image)._renderTarget : null;
var rt3 = len > 2 ? cast(additionalRenderTargets[2], Image)._renderTarget : null;
var rt4 = len > 3 ? cast(additionalRenderTargets[3], Image)._renderTarget : null;
var rt5 = len > 4 ? cast(additionalRenderTargets[4], Image)._renderTarget : null;
var rt6 = len > 5 ? cast(additionalRenderTargets[5], Image)._renderTarget : null;
var rt7 = len > 6 ? cast(additionalRenderTargets[6], Image)._renderTarget : null;
kinc_graphics_render_to_textures(rt0, rt1, rt2, rt3, rt4, rt5, rt6, rt7, len + 1);
}
else {
kinc_graphics_render_to_texture(cast(target, Image)._renderTarget);
}
}
public function begin(additionalRenderTargets: Array<Canvas> = null): Void {
if (target == null)
kinc_graphics_restore_render_target();
else
renderToTexture(additionalRenderTargets);
}
public function beginFace(face: Int): Void {
kinc_graphics_render_to_face(cast(target, CubeMap)._renderTarget, face);
}
public function beginEye(eye: Int): Void {}
public function end(): Void {}
public function flush(): Void {
kinc_graphics_flush();
}
@:hlNative("std", "kinc_graphics_clear") static function kinc_graphics_clear(flags: Int, color: Int, z: FastFloat, stencil: Int): Void {}
@:hlNative("std", "kinc_graphics_vsynced") static function kinc_graphics_vsynced(): Bool {
return false;
}
@:hlNative("std", "kinc_graphics_refreshrate") static function kinc_graphics_refreshrate(): Int {
return 0;
}
@:hlNative("std", "kinc_graphics_viewport") static function kinc_graphics_viewport(x: Int, y: Int, width: Int, height: Int): Void {}
@:hlNative("std", "kinc_graphics_set_vertexbuffer") static function kinc_graphics_set_vertexbuffer(buffer: Pointer): Void {}
@:hlNative("std", "kinc_graphics_set_vertexbuffers") static function kinc_graphics_set_vertexbuffers(b0: Pointer, b1: Pointer, b2: Pointer, b3: Pointer,
count: Int): Void {}
@:hlNative("std", "kinc_graphics_set_indexbuffer") static function kinc_graphics_set_indexbuffer(buffer: Pointer): Void {}
@:hlNative("std", "kinc_graphics_scissor") static function kinc_graphics_scissor(x: Int, y: Int, width: Int, height: Int): Void {}
@:hlNative("std", "kinc_graphics_disable_scissor") static function kinc_graphics_disable_scissor(): Void {}
@:hlNative("std", "kinc_graphics_set_texture_parameters") static function kinc_graphics_set_texture_parameters(unit: Pointer, uAddressing: Int,
vAddressing: Int, minificationFilter: Int, magnificationFilter: Int, mipmapFilter: Int): Void {}
@:hlNative("std", "kinc_graphics_set_texture3d_parameters") static function kinc_graphics_set_texture3d_parameters(unit: Pointer, uAddressing: Int,
vAddressing: Int, wAddressing: Int, minificationFilter: Int, magnificationFilter: Int, mipmapFilter: Int): Void {}
@:hlNative("std", "kinc_graphics_set_texture_compare_mode") static function kinc_graphics_set_texture_compare_mode(unit: Pointer, enabled: Bool): Void {}
@:hlNative("std", "kinc_graphics_set_cube_map_compare_mode") static function kinc_graphics_set_cube_map_compare_mode(unit: Pointer, enabled: Bool): Void {}
@:hlNative("std", "kinc_graphics_set_texture") static function kinc_graphics_set_texture(unit: Pointer, texture: Pointer): Void {}
@:hlNative("std", "kinc_graphics_set_texture_depth") static function kinc_graphics_set_texture_depth(unit: Pointer, renderTarget: Pointer): Void {}
@:hlNative("std", "kinc_graphics_set_texture_array") static function kinc_graphics_set_texture_array(unit: Pointer, textureArray: Pointer): Void {}
@:hlNative("std", "kinc_graphics_set_render_target") static function kinc_graphics_set_render_target(unit: Pointer, renderTarget: Pointer): Void {}
@:hlNative("std", "kinc_graphics_set_cubemap_texture") static function kinc_graphics_set_cubemap_texture(unit: Pointer, texture: Pointer): Void {}
@:hlNative("std", "kinc_graphics_set_cubemap_target") static function kinc_graphics_set_cubemap_target(unit: Pointer, renderTarget: Pointer): Void {}
@:hlNative("std", "kinc_graphics_set_cubemap_depth") static function kinc_graphics_set_cubemap_depth(unit: Pointer, renderTarget: Pointer): Void {}
@:hlNative("std", "kinc_graphics_set_image_texture") static function kinc_graphics_set_image_texture(unit: Pointer, texture: Pointer): Void {}
@:hlNative("std", "kinc_graphics_set_bool") static function kinc_graphics_set_bool(location: Pointer, value: Bool): Void {}
@:hlNative("std", "kinc_graphics_set_int") static function kinc_graphics_set_int(location: Pointer, value: Int): Void {}
@:hlNative("std", "kinc_graphics_set_int2") static function kinc_graphics_set_int2(location: Pointer, value1: Int, value2: Int): Void {}
@:hlNative("std", "kinc_graphics_set_int3") static function kinc_graphics_set_int3(location: Pointer, value1: Int, value2: Int, value3: Int): Void {}
@:hlNative("std", "kinc_graphics_set_int4") static function kinc_graphics_set_int4(location: Pointer, value1: Int, value2: Int, value3: Int,
value4: Int): Void {}
@:hlNative("std", "kinc_graphics_set_ints") static function kinc_graphics_set_ints(location: Pointer, values: Pointer, count: Int): Void {}
@:hlNative("std", "kinc_graphics_set_float") static function kinc_graphics_set_float(location: Pointer, value: FastFloat): Void {}
@:hlNative("std", "kinc_graphics_set_float2") static function kinc_graphics_set_float2(location: Pointer, value1: FastFloat, value2: FastFloat): Void {}
@:hlNative("std", "kinc_graphics_set_float3") static function kinc_graphics_set_float3(location: Pointer, value1: FastFloat, value2: FastFloat,
value3: FastFloat): Void {}
@:hlNative("std", "kinc_graphics_set_float4") static function kinc_graphics_set_float4(location: Pointer, value1: FastFloat, value2: FastFloat,
value3: FastFloat, value4: FastFloat): Void {}
@:hlNative("std", "kinc_graphics_set_floats") static function kinc_graphics_set_floats(location: Pointer, values: Pointer, count: Int): Void {}
@:hlNative("std", "kinc_graphics_set_matrix") static function kinc_graphics_set_matrix(location: Pointer, _00: FastFloat, _10: FastFloat, _20: FastFloat,
_30: FastFloat, _01: FastFloat, _11: FastFloat, _21: FastFloat, _31: FastFloat, _02: FastFloat, _12: FastFloat, _22: FastFloat, _32: FastFloat,
_03: FastFloat, _13: FastFloat, _23: FastFloat, _33: FastFloat): Void {}
@:hlNative("std", "kinc_graphics_set_matrix3") static function kinc_graphics_set_matrix3(location: Pointer, _00: FastFloat, _10: FastFloat,
_20: FastFloat, _01: FastFloat, _11: FastFloat, _21: FastFloat, _02: FastFloat, _12: FastFloat, _22: FastFloat): Void {}
@:hlNative("std", "kinc_graphics_draw_all_indexed_vertices") static function kinc_graphics_draw_all_indexed_vertices(): Void {}
@:hlNative("std", "kinc_graphics_draw_indexed_vertices") static function kinc_graphics_draw_indexed_vertices(start: Int, count: Int): Void {}
@:hlNative("std",
"kinc_graphics_draw_all_indexed_vertices_instanced") static function kinc_graphics_draw_all_indexed_vertices_instanced(instanceCount: Int): Void {}
@:hlNative("std", "kinc_graphics_draw_indexed_vertices_instanced") static function kinc_graphics_draw_indexed_vertices_instanced(instanceCount: Int,
start: Int, count: Int): Void {}
@:hlNative("std", "kinc_graphics_restore_render_target") static function kinc_graphics_restore_render_target(): Void {}
@:hlNative("std", "kinc_graphics_render_to_texture") static function kinc_graphics_render_to_texture(renderTarget: Pointer): Void {}
@:hlNative("std", "kinc_graphics_render_to_textures") static function kinc_graphics_render_to_textures(rt0: Pointer, rt1: Pointer, rt2: Pointer,
rt3: Pointer, rt4: Pointer, rt5: Pointer, rt6: Pointer, rt7: Pointer, count: Int): Void {}
@:hlNative("std", "kinc_graphics_render_to_face") static function kinc_graphics_render_to_face(renderTarget: Pointer, face: Int): Void {}
@:hlNative("std", "kinc_graphics_flush") static function kinc_graphics_flush(): Void {}
}

View File

@ -1,38 +0,0 @@
#include <kinc/graphics4/compute.h>
#include <kinc/graphics4/texture.h>
#include <hl.h>
vbyte *hl_kinc_compute_create_shader(vbyte *data, int length) {
kinc_g4_compute_shader *shader = (kinc_g4_compute_shader *)malloc(sizeof(kinc_g4_compute_shader));
kinc_g4_compute_shader_init(shader, data, length);
return (vbyte *)shader;
}
void hl_kinc_compute_delete_shader(vbyte *shader) {
kinc_g4_compute_shader *sh = (kinc_g4_compute_shader *)shader;
kinc_g4_compute_shader_destroy(sh);
free(sh);
}
vbyte *hl_kinc_compute_get_constantlocation(vbyte *shader, vbyte *name) {
kinc_g4_compute_shader *sh = (kinc_g4_compute_shader *)shader;
kinc_g4_constant_location_t *location = (kinc_g4_constant_location_t *)malloc(sizeof(kinc_g4_constant_location_t));
*location = kinc_g4_compute_shader_get_constant_location(sh, (char *)name);
return (vbyte *)location;
}
vbyte *hl_kinc_compute_get_textureunit(vbyte *shader, vbyte *name) {
kinc_g4_compute_shader *sh = (kinc_g4_compute_shader *)shader;
kinc_g4_texture_unit_t *unit = (kinc_g4_texture_unit_t *)malloc(sizeof(kinc_g4_texture_unit_t));
*unit = kinc_g4_compute_shader_get_texture_unit(sh, (char *)name);
return (vbyte *)unit;
}
void hl_kinc_set_compute_shader(vbyte *shader) {
kinc_g4_set_compute_shader((kinc_g4_compute_shader *)shader);
}
void hl_kinc_compute(int x, int y, int z) {
kinc_g4_compute(x, y, z);
}

View File

@ -1,265 +0,0 @@
#include <kinc/graphics4/graphics.h>
#include <kinc/graphics4/pipeline.h>
#include <kinc/graphics4/shader.h>
#include <kinc/graphics4/vertexstructure.h>
#include <hl.h>
static kinc_g4_compare_mode_t convertCompareMode(int mode) {
switch (mode) {
case 0:
return KINC_G4_COMPARE_ALWAYS;
case 1:
return KINC_G4_COMPARE_NEVER;
case 2:
return KINC_G4_COMPARE_EQUAL;
case 3:
return KINC_G4_COMPARE_NOT_EQUAL;
case 4:
return KINC_G4_COMPARE_LESS;
case 5:
return KINC_G4_COMPARE_LESS_EQUAL;
case 6:
return KINC_G4_COMPARE_GREATER;
case 7:
default:
return KINC_G4_COMPARE_GREATER_EQUAL;
}
}
static kinc_g4_stencil_action_t convertStencilAction(int action) {
switch (action) {
case 0:
return KINC_G4_STENCIL_KEEP;
case 1:
return KINC_G4_STENCIL_ZERO;
case 2:
return KINC_G4_STENCIL_REPLACE;
case 3:
return KINC_G4_STENCIL_INCREMENT;
case 4:
return KINC_G4_STENCIL_INCREMENT_WRAP;
case 5:
return KINC_G4_STENCIL_DECREMENT;
case 6:
return KINC_G4_STENCIL_DECREMENT_WRAP;
case 7:
default:
return KINC_G4_STENCIL_INVERT;
}
}
static kinc_g4_render_target_format_t convertColorAttachment(int format) {
switch (format) {
case 0:
return KINC_G4_RENDER_TARGET_FORMAT_32BIT;
case 1:
return KINC_G4_RENDER_TARGET_FORMAT_8BIT_RED;
case 2:
return KINC_G4_RENDER_TARGET_FORMAT_128BIT_FLOAT;
case 3:
return KINC_G4_RENDER_TARGET_FORMAT_16BIT_DEPTH;
case 4:
return KINC_G4_RENDER_TARGET_FORMAT_64BIT_FLOAT;
case 5:
return KINC_G4_RENDER_TARGET_FORMAT_32BIT_RED_FLOAT;
case 6:
default:
return KINC_G4_RENDER_TARGET_FORMAT_16BIT_RED_FLOAT;
}
}
vbyte *hl_kinc_create_vertexshader(vbyte *data, int length) {
kinc_g4_shader_t *shader = (kinc_g4_shader_t *)malloc(sizeof(kinc_g4_shader_t));
kinc_g4_shader_init(shader, data, length, KINC_G4_SHADER_TYPE_VERTEX);
return (vbyte *)shader;
}
vbyte *hl_kinc_create_fragmentshader(vbyte *data, int length) {
kinc_g4_shader_t *shader = (kinc_g4_shader_t *)malloc(sizeof(kinc_g4_shader_t));
kinc_g4_shader_init(shader, data, length, KINC_G4_SHADER_TYPE_FRAGMENT);
return (vbyte *)shader;
}
vbyte *hl_kinc_create_geometryshader(vbyte *data, int length) {
kinc_g4_shader_t *shader = (kinc_g4_shader_t *)malloc(sizeof(kinc_g4_shader_t));
kinc_g4_shader_init(shader, data, length, KINC_G4_SHADER_TYPE_GEOMETRY);
return (vbyte *)shader;
}
vbyte *hl_kinc_create_tesscontrolshader(vbyte *data, int length) {
kinc_g4_shader_t *shader = (kinc_g4_shader_t *)malloc(sizeof(kinc_g4_shader_t));
kinc_g4_shader_init(shader, data, length, KINC_G4_SHADER_TYPE_TESSELLATION_CONTROL);
return (vbyte *)shader;
}
vbyte *hl_kinc_create_tessevalshader(vbyte *data, int length) {
kinc_g4_shader_t *shader = (kinc_g4_shader_t *)malloc(sizeof(kinc_g4_shader_t));
kinc_g4_shader_init(shader, data, length, KINC_G4_SHADER_TYPE_TESSELLATION_EVALUATION);
return (vbyte *)shader;
}
vbyte *hl_kinc_vertexshader_from_source(vbyte *source) {
kinc_g4_shader_t *shader = (kinc_g4_shader_t *)malloc(sizeof(kinc_g4_shader_t));
kinc_g4_shader_init_from_source(shader, (char *)source, KINC_G4_SHADER_TYPE_VERTEX);
return (vbyte *)shader;
}
vbyte *hl_kinc_fragmentshader_from_source(vbyte *source) {
kinc_g4_shader_t *shader = (kinc_g4_shader_t *)malloc(sizeof(kinc_g4_shader_t));
kinc_g4_shader_init_from_source(shader, (char *)source, KINC_G4_SHADER_TYPE_FRAGMENT);
return (vbyte *)shader;
}
vbyte *hl_kinc_geometryshader_from_source(vbyte *source) {
kinc_g4_shader_t *shader = (kinc_g4_shader_t *)malloc(sizeof(kinc_g4_shader_t));
kinc_g4_shader_init_from_source(shader, (char *)source, KINC_G4_SHADER_TYPE_GEOMETRY);
return (vbyte *)shader;
}
vbyte *hl_kinc_tesscontrolshader_from_source(vbyte *source) {
kinc_g4_shader_t *shader = (kinc_g4_shader_t *)malloc(sizeof(kinc_g4_shader_t));
kinc_g4_shader_init_from_source(shader, (char *)source, KINC_G4_SHADER_TYPE_TESSELLATION_CONTROL);
return (vbyte *)shader;
}
vbyte *hl_kinc_tessevalshader_from_source(vbyte *source) {
kinc_g4_shader_t *shader = (kinc_g4_shader_t *)malloc(sizeof(kinc_g4_shader_t));
kinc_g4_shader_init_from_source(shader, (char *)source, KINC_G4_SHADER_TYPE_TESSELLATION_EVALUATION);
return (vbyte *)shader;
}
vbyte *hl_kinc_create_pipeline() {
kinc_g4_pipeline_t *pipeline = (kinc_g4_pipeline_t *)malloc(sizeof(kinc_g4_pipeline_t));
kinc_g4_pipeline_init(pipeline);
return (vbyte *)pipeline;
}
void hl_kinc_delete_pipeline(vbyte *pipeline) {
kinc_g4_pipeline_t *pipe = (kinc_g4_pipeline_t *)pipeline;
kinc_g4_pipeline_destroy(pipe);
free(pipe);
}
void hl_kinc_pipeline_set_vertex_shader(vbyte *pipeline, vbyte *shader) {
kinc_g4_pipeline_t *pipe = (kinc_g4_pipeline_t *)pipeline;
kinc_g4_shader_t *sh = (kinc_g4_shader_t *)shader;
pipe->vertex_shader = sh;
}
void hl_kinc_pipeline_set_fragment_shader(vbyte *pipeline, vbyte *shader) {
kinc_g4_pipeline_t *pipe = (kinc_g4_pipeline_t *)pipeline;
kinc_g4_shader_t *sh = (kinc_g4_shader_t *)shader;
pipe->fragment_shader = sh;
}
void hl_kinc_pipeline_set_geometry_shader(vbyte *pipeline, vbyte *shader) {
kinc_g4_pipeline_t *pipe = (kinc_g4_pipeline_t *)pipeline;
kinc_g4_shader_t *sh = (kinc_g4_shader_t *)shader;
pipe->geometry_shader = sh;
}
void hl_kinc_pipeline_set_tesscontrol_shader(vbyte *pipeline, vbyte *shader) {
kinc_g4_pipeline_t *pipe = (kinc_g4_pipeline_t *)pipeline;
kinc_g4_shader_t *sh = (kinc_g4_shader_t *)shader;
pipe->tessellation_control_shader = sh;
}
void hl_kinc_pipeline_set_tesseval_shader(vbyte *pipeline, vbyte *shader) {
kinc_g4_pipeline_t *pipe = (kinc_g4_pipeline_t *)pipeline;
kinc_g4_shader_t *sh = (kinc_g4_shader_t *)shader;
pipe->tessellation_evaluation_shader = sh;
}
void hl_kinc_pipeline_compile(vbyte *pipeline, vbyte *structure0, vbyte *structure1, vbyte *structure2, vbyte *structure3) {
kinc_g4_pipeline_t *pipe = (kinc_g4_pipeline_t *)pipeline;
pipe->input_layout[0] = (kinc_g4_vertex_structure_t *)structure0;
pipe->input_layout[1] = (kinc_g4_vertex_structure_t *)structure1;
pipe->input_layout[2] = (kinc_g4_vertex_structure_t *)structure2;
pipe->input_layout[3] = (kinc_g4_vertex_structure_t *)structure3;
pipe->input_layout[4] = NULL;
kinc_g4_pipeline_compile(pipe);
}
void hl_kinc_pipeline_set_states(vbyte *pipeline, int cullMode, int depthMode, int stencilFrontMode, int stencilFrontBothPass, int stencilFrontDepthFail,
int stencilFrontFail, int stencilBackMode, int stencilBackBothPass, int stencilBackDepthFail, int stencilBackFail,
int blendSource, int blendDestination, int alphaBlendSource, int alphaBlendDestination, bool depthWrite,
int stencilReferenceValue, int stencilReadMask, int stencilWriteMask, bool colorWriteMaskRed, bool colorWriteMaskGreen,
bool colorWriteMaskBlue, bool colorWriteMaskAlpha, int colorAttachmentCount, int colorAttachment0, int colorAttachment1,
int colorAttachment2, int colorAttachment3, int colorAttachment4, int colorAttachment5, int colorAttachment6,
int colorAttachment7, int depthAttachmentBits, int stencilAttachmentBits, bool conservativeRasterization) {
kinc_g4_pipeline_t *pipe = (kinc_g4_pipeline_t *)pipeline;
switch (cullMode) {
case 0:
pipe->cull_mode = KINC_G4_CULL_CLOCKWISE;
break;
case 1:
pipe->cull_mode = KINC_G4_CULL_COUNTER_CLOCKWISE;
break;
case 2:
pipe->cull_mode = KINC_G4_CULL_NOTHING;
break;
}
pipe->depth_mode = convertCompareMode(depthMode);
pipe->depth_write = depthWrite;
pipe->stencil_front_mode = convertCompareMode(stencilFrontMode);
pipe->stencil_front_both_pass = convertStencilAction(stencilFrontBothPass);
pipe->stencil_front_depth_fail = convertStencilAction(stencilFrontDepthFail);
pipe->stencil_front_fail = convertStencilAction(stencilFrontFail);
pipe->stencil_back_mode = convertCompareMode(stencilBackMode);
pipe->stencil_back_both_pass = convertStencilAction(stencilBackBothPass);
pipe->stencil_back_depth_fail = convertStencilAction(stencilBackDepthFail);
pipe->stencil_back_fail = convertStencilAction(stencilBackFail);
pipe->stencil_reference_value = stencilReferenceValue;
pipe->stencil_read_mask = stencilReadMask;
pipe->stencil_write_mask = stencilWriteMask;
pipe->blend_source = (kinc_g4_blending_factor_t)blendSource;
pipe->blend_destination = (kinc_g4_blending_factor_t)blendDestination;
pipe->alpha_blend_source = (kinc_g4_blending_factor_t)alphaBlendSource;
pipe->alpha_blend_destination = (kinc_g4_blending_factor_t)alphaBlendDestination;
pipe->color_write_mask_red[0] = colorWriteMaskRed;
pipe->color_write_mask_green[0] = colorWriteMaskGreen;
pipe->color_write_mask_blue[0] = colorWriteMaskBlue;
pipe->color_write_mask_alpha[0] = colorWriteMaskAlpha;
pipe->color_attachment_count = colorAttachmentCount;
pipe->color_attachment[0] = convertColorAttachment(colorAttachment0);
pipe->color_attachment[1] = convertColorAttachment(colorAttachment1);
pipe->color_attachment[2] = convertColorAttachment(colorAttachment2);
pipe->color_attachment[3] = convertColorAttachment(colorAttachment3);
pipe->color_attachment[4] = convertColorAttachment(colorAttachment4);
pipe->color_attachment[5] = convertColorAttachment(colorAttachment5);
pipe->color_attachment[6] = convertColorAttachment(colorAttachment6);
pipe->color_attachment[7] = convertColorAttachment(colorAttachment7);
pipe->depth_attachment_bits = depthAttachmentBits;
pipe->stencil_attachment_bits = stencilAttachmentBits;
pipe->conservative_rasterization = conservativeRasterization;
}
void hl_kinc_pipeline_set(vbyte *pipeline) {
kinc_g4_pipeline_t *pipe = (kinc_g4_pipeline_t *)pipeline;
kinc_g4_set_pipeline(pipe);
}
vbyte *hl_kinc_pipeline_get_constantlocation(vbyte *pipeline, vbyte *name) {
kinc_g4_pipeline_t *pipe = (kinc_g4_pipeline_t *)pipeline;
kinc_g4_constant_location_t *location = (kinc_g4_constant_location_t *)malloc(sizeof(kinc_g4_constant_location_t));
*location = kinc_g4_pipeline_get_constant_location(pipe, (char *)name);
return (vbyte *)location;
}
vbyte *hl_kinc_pipeline_get_textureunit(vbyte *pipeline, vbyte *name) {
kinc_g4_pipeline_t *pipe = (kinc_g4_pipeline_t *)pipeline;
kinc_g4_texture_unit_t *unit = (kinc_g4_texture_unit_t *)malloc(sizeof(kinc_g4_texture_unit_t));
*unit = kinc_g4_pipeline_get_texture_unit(pipe, (char *)name);
return (vbyte *)unit;
}

View File

@ -1,201 +0,0 @@
#include <kinc/input/acceleration.h>
#include <kinc/input/gamepad.h>
#include <kinc/input/keyboard.h>
#include <kinc/input/mouse.h>
#include <kinc/input/pen.h>
#include <kinc/input/rotation.h>
#include <kinc/input/surface.h>
#include <kinc/log.h>
#include <kinc/system.h>
#include <kinc/video.h>
#include <kinc/window.h>
#include <hl.h>
void hl_kinc_log(vbyte *v) {
kinc_log(KINC_LOG_LEVEL_INFO, (char *)v);
}
double hl_kinc_get_time(void) {
return kinc_time();
}
int hl_kinc_get_window_width(int window) {
return kinc_window_width(window);
}
int hl_kinc_get_window_height(int window) {
return kinc_window_height(window);
}
vbyte *hl_kinc_get_system_id(void) {
return (vbyte *)kinc_system_id();
}
void hl_kinc_vibrate(int ms) {
kinc_vibrate(ms);
}
vbyte *hl_kinc_get_language(void) {
return (vbyte *)kinc_language();
}
void hl_kinc_request_shutdown(void) {
kinc_stop();
}
void hl_kinc_mouse_lock(int windowId) {
kinc_mouse_lock(windowId);
}
void hl_kinc_mouse_unlock(void) {
kinc_mouse_unlock();
}
bool hl_kinc_can_lock_mouse(void) {
return kinc_mouse_can_lock();
}
bool hl_kinc_is_mouse_locked(void) {
return kinc_mouse_is_locked();
}
void hl_kinc_show_mouse(bool show) {
if (show) {
kinc_mouse_show();
}
else {
kinc_mouse_hide();
}
}
bool hl_kinc_system_is_fullscreen(void) {
return false; // kinc_is_fullscreen();
}
void hl_kinc_system_request_fullscreen(void) {
// kinc_change_resolution(display_width(), display_height(), true);
}
void hl_kinc_system_exit_fullscreen(int previousWidth, int previousHeight) {
// kinc_change_resolution(previousWidth, previousHeight, false);
}
void hl_kinc_system_change_resolution(int width, int height) {
// kinc_change_resolution(width, height, false);
}
void hl_kinc_system_set_keepscreenon(bool on) {
kinc_set_keep_screen_on(on);
}
void hl_kinc_system_load_url(vbyte *url) {
kinc_load_url((char *)url);
}
vbyte *hl_kinc_get_gamepad_id(int index) {
return (vbyte *)kinc_gamepad_product_name(index);
}
vbyte *hl_kinc_get_gamepad_vendor(int index) {
return (vbyte *)kinc_gamepad_vendor(index);
}
bool hl_kinc_gamepad_connected(int index) {
return kinc_gamepad_connected(index);
}
typedef void (*FN_KEY_DOWN)(int, void *);
typedef void (*FN_KEY_UP)(int, void *);
typedef void (*FN_KEY_PRESS)(unsigned int, void *);
void hl_kinc_register_keyboard(vclosure *keyDown, vclosure *keyUp, vclosure *keyPress) {
kinc_keyboard_set_key_down_callback(*((FN_KEY_DOWN *)(&keyDown->fun)), NULL);
kinc_keyboard_set_key_up_callback(*((FN_KEY_UP *)(&keyUp->fun)), NULL);
kinc_keyboard_set_key_press_callback(*((FN_KEY_PRESS *)(&keyPress->fun)), NULL);
}
typedef void (*FN_MOUSE_DOWN)(int, int, int, int, void *);
typedef void (*FN_MOUSE_UP)(int, int, int, int, void *);
typedef void (*FN_MOUSE_MOVE)(int, int, int, int, int, void *);
typedef void (*FN_MOUSE_WHEEL)(int, int, void *);
void hl_kinc_register_mouse(vclosure *mouseDown, vclosure *mouseUp, vclosure *mouseMove, vclosure *mouseWheel) {
kinc_mouse_set_press_callback(*((FN_MOUSE_DOWN *)(&mouseDown->fun)), NULL);
kinc_mouse_set_release_callback(*((FN_MOUSE_UP *)(&mouseUp->fun)), NULL);
kinc_mouse_set_move_callback(*((FN_MOUSE_MOVE *)(&mouseMove->fun)), NULL);
kinc_mouse_set_scroll_callback(*((FN_MOUSE_WHEEL *)(&mouseWheel->fun)), NULL);
}
typedef void (*FN_PEN_DOWN)(int, int, int, float);
typedef void (*FN_PEN_UP)(int, int, int, float);
typedef void (*FN_PEN_MOVE)(int, int, int, float);
void hl_kinc_register_pen(vclosure *penDown, vclosure *penUp, vclosure *penMove) {
kinc_pen_set_press_callback(*((FN_PEN_DOWN *)(&penDown->fun)));
kinc_pen_set_release_callback(*((FN_PEN_UP *)(&penUp->fun)));
kinc_pen_set_move_callback(*((FN_PEN_MOVE *)(&penMove->fun)));
}
typedef void (*FN_GAMEPAD_AXIS)(int, int, float, void *);
typedef void (*FN_GAMEPAD_BUTTON)(int, int, float, void *);
void hl_kinc_register_gamepad(vclosure *gamepadAxis, vclosure *gamepadButton) {
kinc_gamepad_set_axis_callback(*((FN_GAMEPAD_AXIS *)(&gamepadAxis->fun)), NULL);
kinc_gamepad_set_button_callback(*((FN_GAMEPAD_BUTTON *)(&gamepadButton->fun)), NULL);
}
typedef void (*FN_TOUCH_START)(int, int, int);
typedef void (*FN_TOUCH_END)(int, int, int);
typedef void (*FN_TOUCH_MOVE)(int, int, int);
void hl_kinc_register_surface(vclosure *touchStart, vclosure *touchEnd, vclosure *touchMove) {
kinc_surface_set_touch_start_callback(*((FN_TOUCH_START *)(&touchStart->fun)));
kinc_surface_set_touch_end_callback(*((FN_TOUCH_END *)(&touchEnd->fun)));
kinc_surface_set_move_callback(*((FN_TOUCH_MOVE *)(&touchMove->fun)));
}
typedef void (*FN_SENSOR_ACCELEROMETER)(float, float, float);
typedef void (*FN_SENSOR_GYROSCOPE)(float, float, float);
void hl_kinc_register_sensor(vclosure *accelerometerChanged, vclosure *gyroscopeChanged) {
kinc_acceleration_set_callback(*((FN_SENSOR_ACCELEROMETER *)(&accelerometerChanged->fun)));
kinc_rotation_set_callback(*((FN_SENSOR_GYROSCOPE *)(&gyroscopeChanged->fun)));
}
// typedef void(*FN_CB_ORIENTATION)(int);
typedef void (*FN_CB_FOREGROUND)(void *);
typedef void (*FN_CB_RESUME)(void *);
typedef void (*FN_CB_PAUSE)(void *);
typedef void (*FN_CB_BACKGROUND)(void *);
typedef void (*FN_CB_SHUTDOWN)(void *);
void hl_kinc_register_callbacks(vclosure *foreground, vclosure *resume, vclosure *pause, vclosure *background, vclosure *shutdown) {
// kinc_set_orientation_callback(orientation);
kinc_set_foreground_callback(*((FN_CB_FOREGROUND *)(&foreground->fun)), NULL);
kinc_set_resume_callback(*((FN_CB_RESUME *)(&resume->fun)), NULL);
kinc_set_pause_callback(*((FN_CB_PAUSE *)(&pause->fun)), NULL);
kinc_set_background_callback(*((FN_CB_BACKGROUND *)(&background->fun)), NULL);
kinc_set_shutdown_callback(*((FN_CB_SHUTDOWN *)(&shutdown->fun)), NULL);
}
typedef void (*FN_CB_DROPFILES)(wchar_t *);
void hl_kinc_register_dropfiles(vclosure *dropFiles) {
// todo: string convert
// kinc_set_drop_files_callback(*((FN_CB_DROPFILES*)(&dropFiles->fun)));
}
typedef char *(*FN_CB_COPY)(void *);
typedef char *(*FN_CB_CUT)(void *);
typedef void (*FN_CB_PASTE)(char *, void *);
void hl_kinc_register_copycutpaste(vclosure *copy, vclosure *cut, vclosure *paste) {
kinc_set_copy_callback(*((FN_CB_COPY *)(&copy->fun)), NULL);
kinc_set_cut_callback(*((FN_CB_CUT *)(&cut->fun)), NULL);
kinc_set_paste_callback(*((FN_CB_PASTE *)(&paste->fun)), NULL);
}
const char *hl_kinc_video_format(void) {
return kinc_video_formats()[0];
}

View File

@ -1,327 +0,0 @@
#include <kinc/graphics4/graphics.h>
#include <kinc/image.h>
#include <kinc/video.h>
#include <hl.h>
#include <assert.h>
typedef struct tex_and_data {
kinc_g4_texture_t texture;
int width, height;
void *data;
} tex_and_data_t;
static kinc_image_format_t convertImageFormat(int format) {
switch (format) {
default:
case 0:
return KINC_IMAGE_FORMAT_RGBA32;
case 1:
return KINC_IMAGE_FORMAT_GREY8;
case 2:
return KINC_IMAGE_FORMAT_RGBA128;
case 4:
return KINC_IMAGE_FORMAT_RGBA64;
case 5:
return KINC_IMAGE_FORMAT_A32;
case 6:
return KINC_IMAGE_FORMAT_A16;
}
}
static int sizeOf(kinc_image_format_t format) {
switch (format) {
case KINC_IMAGE_FORMAT_RGBA128:
return 16;
case KINC_IMAGE_FORMAT_RGBA32:
case KINC_IMAGE_FORMAT_BGRA32:
return 4;
case KINC_IMAGE_FORMAT_RGBA64:
return 8;
case KINC_IMAGE_FORMAT_A32:
return 4;
case KINC_IMAGE_FORMAT_A16:
return 2;
case KINC_IMAGE_FORMAT_GREY8:
return 1;
case KINC_IMAGE_FORMAT_RGB24:
return 3;
}
assert(false);
return 0;
}
vbyte *hl_kinc_texture_create(int width, int height, int format, bool readable) {
tex_and_data_t *texture = (tex_and_data_t *)malloc(sizeof(tex_and_data_t));
kinc_image_format_t f = convertImageFormat(format);
kinc_g4_texture_init(&texture->texture, width, height, f);
texture->width = width;
texture->height = height;
if (readable) {
texture->data = malloc(width * height * sizeOf(f));
}
else {
texture->data = NULL;
}
return (vbyte *)texture;
}
vbyte *hl_kinc_texture_create_from_file(vbyte *filename, bool readable) {
size_t size = kinc_image_size_from_file((char *)filename);
if (size > 0) {
tex_and_data_t *texture = (tex_and_data_t *)malloc(sizeof(tex_and_data_t));
texture->data = malloc(size);
kinc_image_t image;
if (kinc_image_init_from_file(&image, texture->data, (char *)filename) != 0) {
kinc_g4_texture_init_from_image(&texture->texture, &image);
texture->width = image.width;
texture->height = image.height;
if (!readable) {
free(texture->data);
texture->data = NULL;
}
kinc_image_destroy(&image);
return (vbyte *)texture;
}
kinc_image_destroy(&image);
free(texture->data);
texture->data = NULL;
free(texture);
}
return NULL;
}
vbyte *hl_kinc_texture_create3d(int width, int height, int depth, int format, bool readable) {
tex_and_data_t *texture = (tex_and_data_t *)malloc(sizeof(tex_and_data_t));
kinc_image_format_t f = convertImageFormat(format);
kinc_g4_texture_init(&texture->texture, width, height, f);
texture->width = width;
texture->height = height;
if (readable) {
texture->data = malloc(width * height * depth * sizeOf(f));
}
else {
texture->data = NULL;
}
return (vbyte *)texture;
}
vbyte *hl_kinc_video_get_current_image(vbyte *video) {
kinc_video_t *v = (kinc_video_t *)video;
return (vbyte *)kinc_video_current_image(v);
}
vbyte *hl_kinc_texture_from_bytes(vbyte *bytes, int width, int height, int format, bool readable) {
kinc_image_format_t f = convertImageFormat(format);
kinc_image_t image;
kinc_image_init(&image, bytes, width, height, f);
tex_and_data_t *texture = (tex_and_data_t *)malloc(sizeof(tex_and_data_t));
kinc_g4_texture_init_from_image(&texture->texture, &image);
texture->width = width;
texture->height = height;
kinc_image_destroy(&image);
if (readable) {
size_t size = width * height * sizeOf(f);
texture->data = malloc(size);
memcpy(texture->data, bytes, size);
}
else {
texture->data = NULL;
}
return (vbyte *)texture;
}
vbyte *hl_kinc_texture_from_bytes3d(vbyte *bytes, int width, int height, int depth, int format, bool readable) {
kinc_image_format_t f = convertImageFormat(format);
kinc_image_t image;
kinc_image_init3d(&image, bytes, width, height, depth, f);
tex_and_data_t *texture = (tex_and_data_t *)malloc(sizeof(tex_and_data_t));
kinc_g4_texture_init_from_image3d(&texture->texture, &image);
texture->width = width;
texture->height = height;
kinc_image_destroy(&image);
if (readable) {
size_t size = width * height * depth * sizeOf(f);
texture->data = malloc(size);
memcpy(texture->data, bytes, size);
}
else {
texture->data = NULL;
}
return (vbyte *)texture;
}
vbyte *hl_kinc_texture_from_encoded_bytes(vbyte *bytes, int length, vbyte *format, bool readable) {
tex_and_data_t *texture = (tex_and_data_t *)malloc(sizeof(tex_and_data_t));
size_t size = kinc_image_size_from_encoded_bytes(bytes, length, (char *)format);
texture->data = malloc(size);
kinc_image_t image;
kinc_image_init_from_encoded_bytes(&image, texture->data, bytes, length, (char *)format);
kinc_g4_texture_init_from_image(&texture->texture, &image);
texture->width = image.width;
texture->height = image.height;
kinc_image_destroy(&image);
if (!readable) {
free(texture->data);
texture->data = NULL;
}
return (vbyte *)texture;
}
bool hl_kinc_non_pow2_textures_supported(void) {
return kinc_g4_supports_non_pow2_textures();
}
int hl_kinc_texture_get_width(vbyte *texture) {
tex_and_data_t *tex = (tex_and_data_t *)texture;
return tex->width;
}
int hl_kinc_texture_get_height(vbyte *texture) {
tex_and_data_t *tex = (tex_and_data_t *)texture;
return tex->height;
}
int hl_kinc_texture_get_real_width(vbyte *texture) {
kinc_g4_texture_t *tex = (kinc_g4_texture_t *)texture;
return tex->tex_width;
}
int hl_kinc_texture_get_real_height(vbyte *texture) {
kinc_g4_texture_t *tex = (kinc_g4_texture_t *)texture;
return tex->tex_height;
}
int hl_kinc_texture_get_stride(vbyte *texture) {
kinc_g4_texture_t *tex = (kinc_g4_texture_t *)texture;
return kinc_g4_texture_stride(tex);
}
int hl_kinc_texture_at(vbyte *texture, int x, int y) {
tex_and_data_t *tex = (tex_and_data_t *)texture;
assert(tex->data != NULL);
return *(int *)&((uint8_t *)tex->data)[tex->width * sizeOf(tex->texture.format) * y + x * sizeOf(tex->texture.format)];
}
void hl_kinc_texture_unload(vbyte *texture) {
tex_and_data_t *tex = (tex_and_data_t *)texture;
if (tex->data != NULL) {
free(tex->data);
tex->data = NULL;
}
kinc_g4_texture_destroy(&tex->texture);
free(tex);
}
void hl_kinc_render_target_unload(vbyte *renderTarget) {
kinc_g4_render_target_t *rt = (kinc_g4_render_target_t *)renderTarget;
kinc_g4_render_target_destroy(rt);
free(rt);
}
vbyte *hl_kinc_render_target_create(int width, int height, int depthBufferBits, int format, int stencilBufferBits) {
kinc_g4_render_target_t *rt = (kinc_g4_render_target_t *)malloc(sizeof(kinc_g4_render_target_t));
kinc_g4_render_target_init(rt, width, height, (kinc_g4_render_target_format_t)format, depthBufferBits, stencilBufferBits);
return (vbyte *)rt;
}
int hl_kinc_render_target_get_width(vbyte *renderTarget) {
kinc_g4_render_target_t *rt = (kinc_g4_render_target_t *)renderTarget;
return rt->width;
}
int hl_kinc_render_target_get_height(vbyte *renderTarget) {
kinc_g4_render_target_t *rt = (kinc_g4_render_target_t *)renderTarget;
return rt->height;
}
int hl_kinc_render_target_get_real_width(vbyte *renderTarget) {
kinc_g4_render_target_t *rt = (kinc_g4_render_target_t *)renderTarget;
return rt->texWidth;
}
int hl_kinc_render_target_get_real_height(vbyte *renderTarget) {
kinc_g4_render_target_t *rt = (kinc_g4_render_target_t *)renderTarget;
return rt->texHeight;
}
void hl_kinc_texture_unlock(vbyte *texture, vbyte *bytes) {
kinc_g4_texture_t *tex = (kinc_g4_texture_t *)texture;
uint8_t *b = (uint8_t *)bytes;
uint8_t *btex = kinc_g4_texture_lock(tex);
int size = sizeOf(tex->format);
int stride = kinc_g4_texture_stride(tex);
for (int y = 0; y < tex->tex_height; ++y) {
for (int x = 0; x < tex->tex_width; ++x) {
#ifdef KORE_DIRECT3D
if (tex->format == KINC_IMAGE_FORMAT_RGBA32) {
// RBGA->BGRA
btex[y * stride + x * size + 0] = b[(y * tex->tex_width + x) * size + 2];
btex[y * stride + x * size + 1] = b[(y * tex->tex_width + x) * size + 1];
btex[y * stride + x * size + 2] = b[(y * tex->tex_width + x) * size + 0];
btex[y * stride + x * size + 3] = b[(y * tex->tex_width + x) * size + 3];
}
else
#endif
{
for (int i = 0; i < size; ++i) {
btex[y * stride + x * size + i] = b[(y * tex->tex_width + x) * size + i];
}
}
}
}
kinc_g4_texture_unlock(tex);
}
void hl_kinc_render_target_get_pixels(vbyte *renderTarget, vbyte *pixels) {
kinc_g4_render_target_t *rt = (kinc_g4_render_target_t *)renderTarget;
kinc_g4_render_target_get_pixels(rt, pixels);
}
void hl_kinc_generate_mipmaps_texture(vbyte *texture, int levels) {
kinc_g4_texture_t *tex = (kinc_g4_texture_t *)texture;
kinc_g4_texture_generate_mipmaps(tex, levels);
}
void hl_kinc_generate_mipmaps_target(vbyte *renderTarget, int levels) {
kinc_g4_render_target_t *rt = (kinc_g4_render_target_t *)renderTarget;
kinc_g4_render_target_generate_mipmaps(rt, levels);
}
void hl_kinc_set_mipmap_texture(vbyte *texture, vbyte *mipmap, int level) {
kinc_g4_texture_t *tex = (kinc_g4_texture_t *)texture;
tex_and_data_t *miptex = (tex_and_data_t *)mipmap;
assert(miptex->data != NULL);
kinc_image_t mipimage;
kinc_image_init(&mipimage, miptex->data, miptex->width, miptex->height, miptex->texture.format);
kinc_g4_texture_set_mipmap(tex, &mipimage, level);
kinc_image_destroy(&mipimage);
}
void hl_kinc_render_target_set_depth_stencil_from(vbyte *renderTarget, vbyte *from) {
kinc_g4_render_target_t *rt = (kinc_g4_render_target_t *)renderTarget;
kinc_g4_render_target_t *rt2 = (kinc_g4_render_target_t *)from;
kinc_g4_render_target_set_depth_stencil_from(rt, rt2);
}
void hl_kinc_texture_clear(vbyte *texture, int x, int y, int z, int width, int height, int depth, int color) {
kinc_g4_texture_t *tex = (kinc_g4_texture_t *)texture;
kinc_g4_texture_clear(tex, x, y, z, width, height, depth, color);
}

View File

@ -1,154 +0,0 @@
let project = new Project('Kha');
const pcreVersion = '10.42';
const tlsVersion = '2.28.2';
const zlibVersion = '1.2.13';
project.addFiles('khacpp/src/**.h', 'khacpp/src/**.cpp', 'khacpp/include/**.h');
project.addFiles('khacpp/project/libs/common/**.h', 'khacpp/project/libs/common/**.cpp');
if (platform === Platform.Windows || platform === Platform.WindowsApp) project.addFiles('khacpp/project/libs/msvccompat/**.cpp');
if (platform === Platform.Linux) project.addFiles('khacpp/project/libs/linuxcompat/**.cpp');
project.addFiles('khacpp/project/libs/regexp/**.h', 'khacpp/project/libs/regexp/**.cpp', 'khacpp/project/libs/std/**.h', 'khacpp/project/libs/std/**.cpp');
project.addFiles('khacpp/project/thirdparty/pcre2-' + pcreVersion + '-8/src/**.h', 'khacpp/project/thirdparty/pcre2-' + pcreVersion + '-8/src/**.c');
project.addFiles('khacpp/project/thirdparty/pcre2-' + pcreVersion + '-16/src/**.h', 'khacpp/project/thirdparty/pcre2-' + pcreVersion + '-16/src/**.c');
const zlibFiles = [
'**.h',
'adler32.c',
'compress.c',
'crc32.c',
'gzio.c',
'uncompr.c',
'deflate.c',
'trees.c',
'zutil.c',
'inflate.c',
'infback.c',
'inftrees.c',
'inffast.c'
];
for (const file of zlibFiles) {
project.addFile('khacpp/project/thirdparty/zlib-' + zlibVersion + '/' + file);
}
project.addFiles('khacpp/project/thirdparty/mbedtls-' + tlsVersion + '/**');
project.addFiles('*.cpp', '*.c', 'Backends/Kore/*.h', '*.natvis');
project.addFiles('lib/**');
project.addIncludeDir('lib');
const pcreExcludes = [
'pcre2_dftables.c',
'pcre2_fuzzsupport.c',
'pcre2_printint.c',
'pcre2_jit_match.c',
'pcre2_jit_misc.c',
'pcre2_jit_test.c',
'pcre2_ucptables.c',
'pcre2demo.c',
'pcre2grep.c',
'pcre2posix.h',
'pcre2posix.c',
'pcre2posix_test.c',
'pcre2test.c',
'sljit/**'
];
for (const file of pcreExcludes) {
project.addExclude('khacpp/project/thirdparty/pcre2-' + pcreVersion + '-8/src/' + file);
project.addExclude('khacpp/project/thirdparty/pcre2-' + pcreVersion + '-16/src/' + file);
}
project.addExcludes('khacpp/src/ExampleMain.cpp', 'khacpp/src/hx/Scriptable.cpp', 'khacpp/src/hx/NoFiles.cpp', 'khacpp/src/hx/cppia/**');
project.addExcludes('khacpp/src/hx/Debugger.cpp', 'khacpp/src/hx/Profiler.cpp', 'khacpp/src/hx/Telemetry.cpp');
project.addExcludes('khacpp/src/hx/NekoAPI.cpp');
project.addExcludes('khacpp/src/hx/libs/sqlite/**');
project.addExcludes('khacpp/src/hx/libs/mysql/**');
project.addIncludeDirs('khacpp/include', 'khacpp/project/thirdparty/zlib-' + zlibVersion, 'khacpp/project/libs/nekoapi', 'khacpp/project/thirdparty/mbedtls-' + tlsVersion + '/include');
project.addIncludeDir('khacpp/src/hx/libs/ssl');
//if (options.vrApi == "rift") {
// out += "project.addIncludeDirs('C:/khaviar/LibOVRKernel/Src/');\n";
// out += "project.addIncludeDirs('C:/khaviar/LibOVR/Include/');\n";
//}
if (platform !== Platform.Android) {
project.addExcludes('khacpp/src/hx/AndroidCompat.cpp');
}
if (platform === Platform.Windows) {
project.addDefine('HX_WINDOWS');
project.addLib('Shlwapi');
project.addLib('Crypt32');
}
if (platform === Platform.WindowsApp) {
project.addDefine('HX_WINDOWS');
project.addDefine('HX_WINRT');
}
if (platform !== Platform.Windows || audio !== AudioApi.DirectSound) {
project.addDefine('KORE_MULTITHREADED_AUDIO');
}
if (platform === Platform.OSX) {
project.addDefine('HXCPP_M64');
project.addDefine('HX_MACOS');
}
if (platform === Platform.Linux) project.addDefine('HX_LINUX');
if (platform === Platform.iOS) {
project.addDefine('IPHONE');
project.addDefine('HX_IPHONE');
}
if (platform === Platform.tvOS) {
project.addDefine('APPLETV');
}
if (platform === Platform.Android) {
project.addDefine('ANDROID');
project.addDefine('_ANDROID');
project.addDefine('HX_ANDROID');
project.addDefine('HXCPP_ANDROID_PLATFORM=24');
}
if (platform === Platform.OSX) {
project.addDefine('KORE_DEBUGDIR="osx"');
project.addLib('Security');
}
if (platform === Platform.iOS) project.addDefine('KORE_DEBUGDIR="ios"');
// project:addDefine('HXCPP_SCRIPTABLE');
project.addDefine('STATIC_LINK');
project.addDefine('PCRE2_STATIC');
project.addDefine('HXCPP_VISIT_ALLOCS');
project.addDefine('KHA');
project.addDefine('KORE');
project.addDefine('ROTATE90');
project.addDefine('HAVE_CONFIG_H');
project.addDefine('SUPPORT_UTF');
project.addDefine('SUPPORT_UCP');
project.addDefine('SUPPORT_UNICODE');
project.addDefine('MBEDTLS_USER_CONFIG_FILE="mbedtls_config.h"');
project.addDefine('HX_SMART_STRINGS');
//if (Options.vrApi === "gearvr") {
// out += "project.addDefine('VR_GEAR_VR');\n";
//}
//else if (Options.vrApi === "cardboard") {
// out += "project.addDefine('VR_CARDBOARD');\n";
//}
//else if (Options.vrApi === "rift") {
// out += "project.addDefine('VR_RIFT');\n";
//}
//
//if (options.vrApi == "rift") {
// out += "project.addLib('C:/khaviar/LibOVRKernel/Lib/Windows/Win32/Release/VS2013/LibOVRKernel');\n";
// out += "project.addLib('C:/khaviar/LibOVR/Lib/Windows/Win32/Release/VS2013/LibOVR');\n";
//}
if (platform === Platform.Windows || platform === Platform.WindowsApp) {
project.addDefine('_WINSOCK_DEPRECATED_NO_WARNINGS');
}
if (platform === Platform.Windows) {
project.addLib('ws2_32');
}
resolve(project);

View File

@ -1,559 +0,0 @@
package kha;
import haxe.io.Bytes;
import haxe.io.BytesData;
import kha.kore.graphics4.TextureUnit;
import kha.graphics4.TextureFormat;
import kha.graphics4.DepthStencilFormat;
import kha.graphics4.Usage;
@:headerCode("
#include <kinc/graphics4/rendertarget.h>
#include <kinc/graphics4/texture.h>
#include <kinc/graphics4/texturearray.h>
#include <kinc/video.h>
#include <assert.h>
enum KhaImageType {
KhaImageTypeNone,
KhaImageTypeTexture,
KhaImageTypeRenderTarget,
KhaImageTypeTextureArray
};
")
@:headerClassCode("
KhaImageType imageType;
int originalWidth;
int originalHeight;
uint8_t *imageData;
bool ownsImageData;
kinc_g4_texture_t texture;
kinc_g4_render_target_t renderTarget;
kinc_g4_texture_array_t textureArray;
")
class Image implements Canvas implements Resource {
var myFormat: TextureFormat;
var readable: Bool;
var graphics1: kha.graphics1.Graphics;
var graphics2: kha.graphics2.Graphics;
var graphics4: kha.graphics4.Graphics;
public static function fromVideo(video: Video): Image {
var image = new Image(false, false);
image.myFormat = RGBA32;
image.initVideo(cast(video, kha.kore.Video));
return image;
}
public static function create(width: Int, height: Int, format: TextureFormat = null, usage: Usage = null, readable: Bool = false): Image {
return _create2(width, height, format == null ? TextureFormat.RGBA32 : format, readable, false, NoDepthAndStencil, 0);
}
public static function create3D(width: Int, height: Int, depth: Int, format: TextureFormat = null, usage: Usage = null, readable: Bool = false): Image {
return _create3(width, height, depth, format == null ? TextureFormat.RGBA32 : format, readable, 0);
}
public static function createRenderTarget(width: Int, height: Int, format: TextureFormat = null, depthStencil: DepthStencilFormat = NoDepthAndStencil,
antiAliasingSamples: Int = 1): Image {
return _create2(width, height, format == null ? TextureFormat.RGBA32 : format, false, true, depthStencil, antiAliasingSamples);
}
/**
* The provided images need to be readable.
*/
public static function createArray(images: Array<Image>, format: TextureFormat = null): Image {
var image = new Image(false);
image.myFormat = (format == null) ? TextureFormat.RGBA32 : format;
initArrayTexture(image, images);
return image;
}
@:functionCode("
kinc_image_t *kincImages = (kinc_image_t*)malloc(sizeof(kinc_image_t) * images->length);
for (unsigned i = 0; i < images->length; ++i) {
kinc_image_init(&kincImages[i], images->__get(i).StaticCast<::kha::Image>()->imageData, images->__get(i).StaticCast<::kha::Image>()->originalWidth, images->__get(i).StaticCast<::kha::Image>()->originalHeight, (kinc_image_format_t)getTextureFormat(images->__get(i).StaticCast<::kha::Image>()->myFormat));
}
kinc_g4_texture_array_init(&source->textureArray, kincImages, images->length);
for (unsigned i = 0; i < images->length; ++i) {
kinc_image_destroy(&kincImages[i]);
}
free(kincImages);
")
static function initArrayTexture(source: Image, images: Array<Image>): Void {}
public static function fromBytes(bytes: Bytes, width: Int, height: Int, format: TextureFormat = null, usage: Usage = null, readable: Bool = false): Image {
var image = new Image(readable);
image.myFormat = format;
image.initFromBytes(bytes.getData(), width, height, getTextureFormat(format));
return image;
}
@:functionCode("
kinc_image_t image;
kinc_image_init(&image, bytes.GetPtr()->GetBase(), width, height, (kinc_image_format_t)format);
kinc_g4_texture_init_from_image(&texture, &image);
if (readable) {
imageData = (uint8_t*)image.data;
}
kinc_image_destroy(&image);
imageType = KhaImageTypeTexture;
originalWidth = width;
originalHeight = height;
")
function initFromBytes(bytes: BytesData, width: Int, height: Int, format: Int): Void {}
public static function fromBytes3D(bytes: Bytes, width: Int, height: Int, depth: Int, format: TextureFormat = null, usage: Usage = null,
readable: Bool = false): Image {
var image = new Image(readable);
image.myFormat = format;
image.initFromBytes3D(bytes.getData(), width, height, depth, getTextureFormat(format));
return image;
}
@:functionCode("
kinc_image_t image;
kinc_image_init3d(&image, bytes.GetPtr()->GetBase(), width, height, depth, (kinc_image_format_t)format);
kinc_g4_texture_init_from_image3d(&texture, &image);
if (readable) {
imageData = (uint8_t*)image.data;
}
kinc_image_destroy(&image);
imageType = KhaImageTypeTexture;
originalWidth = width;
originalHeight = height;
")
function initFromBytes3D(bytes: BytesData, width: Int, height: Int, depth: Int, format: Int): Void {}
public static function fromEncodedBytes(bytes: Bytes, format: String, doneCallback: Image->Void, errorCallback: String->Void,
readable: Bool = false): Void {
var image = new Image(readable);
var isFloat = format == "hdr" || format == "HDR";
image.myFormat = isFloat ? TextureFormat.RGBA128 : TextureFormat.RGBA32;
image.initFromEncodedBytes(bytes.getData(), format);
doneCallback(image);
}
@:functionCode("
size_t size = kinc_image_size_from_encoded_bytes(bytes.GetPtr()->GetBase(), bytes.GetPtr()->length, format.c_str());
void* data = malloc(size);
kinc_image_t image;
kinc_image_init_from_encoded_bytes(&image, data, bytes.GetPtr()->GetBase(), bytes.GetPtr()->length, format.c_str());
originalWidth = image.width;
originalHeight = image.height;
kinc_g4_texture_init_from_image(&texture, &image);
if (readable) {
imageData = (uint8_t*)image.data;
}
kinc_image_destroy(&image);
if (!readable) {
free(data);
}
imageType = KhaImageTypeTexture;
")
function initFromEncodedBytes(bytes: BytesData, format: String): Void {}
function new(readable: Bool, ?dispose = true) {
this.readable = readable;
nullify();
if (dispose) {
cpp.vm.Gc.setFinalizer(this, cpp.Function.fromStaticFunction(finalize));
}
}
@:functionCode("
imageType = KhaImageTypeNone;
originalWidth = 0;
originalHeight = 0;
imageData = NULL;
ownsImageData = false;
")
function nullify() {}
@:functionCode("
if (image->imageType != KhaImageTypeNone) {
image->unload();
}
")
@:void static function finalize(image: Image): Void {}
static function getRenderTargetFormat(format: TextureFormat): Int {
switch (format) {
case RGBA32: // Target32Bit
return 0;
case RGBA64: // Target64BitFloat
return 1;
case A32: // Target32BitRedFloat
return 2;
case RGBA128: // Target128BitFloat
return 3;
case DEPTH16: // Target16BitDepth
return 4;
case L8:
return 5; // Target8BitRed
case A16:
return 6; // Target16BitRedFloat
default:
return 0;
}
}
static function getDepthBufferBits(depthAndStencil: DepthStencilFormat): Int {
return switch (depthAndStencil) {
case NoDepthAndStencil: -1;
case DepthOnly: 24;
case DepthAutoStencilAuto: 24;
case Depth24Stencil8: 24;
case Depth32Stencil8: 32;
case Depth16: 16;
}
}
static function getStencilBufferBits(depthAndStencil: DepthStencilFormat): Int {
return switch (depthAndStencil) {
case NoDepthAndStencil: -1;
case DepthOnly: -1;
case DepthAutoStencilAuto: 8;
case Depth24Stencil8: 8;
case Depth32Stencil8: 8;
case Depth16: 0;
}
}
static function getTextureFormat(format: TextureFormat): Int {
switch (format) {
case RGBA32:
return 0;
case RGBA128:
return 3;
case RGBA64:
return 4;
case A32:
return 5;
case A16:
return 7;
default:
return 1; // Grey8
}
}
@:noCompletion
public static function _create2(width: Int, height: Int, format: TextureFormat, readable: Bool, renderTarget: Bool, depthStencil: DepthStencilFormat,
samplesPerPixel: Int): Image {
var image = new Image(readable);
image.myFormat = format;
if (renderTarget)
image.initRenderTarget(width, height, getRenderTargetFormat(format), getDepthBufferBits(depthStencil), getStencilBufferBits(depthStencil),
samplesPerPixel);
else
image.init(width, height, getTextureFormat(format));
return image;
}
@:noCompletion
public static function _create3(width: Int, height: Int, depth: Int, format: TextureFormat, readable: Bool, contextId: Int): Image {
var image = new Image(readable);
image.myFormat = format;
image.init3D(width, height, depth, getTextureFormat(format));
return image;
}
@:functionCode("
kinc_g4_render_target_init_with_multisampling(&renderTarget, width, height, (kinc_g4_render_target_format_t)format, depthBufferBits, stencilBufferBits, samplesPerPixel);
imageType = KhaImageTypeRenderTarget;
originalWidth = width;
originalHeight = height;
")
function initRenderTarget(width: Int, height: Int, format: Int, depthBufferBits: Int, stencilBufferBits: Int, samplesPerPixel: Int): Void {}
@:functionCode("
kinc_g4_texture_init(&texture, width, height, (kinc_image_format_t)format);
imageType = KhaImageTypeTexture;
originalWidth = width;
originalHeight = height;
")
function init(width: Int, height: Int, format: Int): Void {}
@:functionCode("
kinc_g4_texture_init3d(&texture, width, height, depth, (kinc_image_format_t)format);
imageType = KhaImageTypeTexture;
originalWidth = width;
originalHeight = height;
")
function init3D(width: Int, height: Int, depth: Int, format: Int): Void {}
@:functionCode("
texture = *kinc_video_current_image(&video->video);
imageType = KhaImageTypeTexture;
")
function initVideo(video: kha.kore.Video): Void {}
public static function createEmpty(readable: Bool, floatFormat: Bool): Image {
var image = new Image(readable);
image.myFormat = floatFormat ? TextureFormat.RGBA128 : TextureFormat.RGBA32;
return image;
}
/*public static function fromFile(filename: String, readable: Bool): Image {
var image = new Image(readable);
var isFloat = StringTools.endsWith(filename, ".hdr");
image.format = isFloat ? TextureFormat.RGBA128 : TextureFormat.RGBA32;
image.initFromFile(filename);
return image;
}
@:functionCode('texture = new Kore::Graphics4::Texture(filename.c_str(), readable);')
private function initFromFile(filename: String): Void {
}*/
public var g1(get, never): kha.graphics1.Graphics;
function get_g1(): kha.graphics1.Graphics {
if (graphics1 == null) {
graphics1 = new kha.graphics2.Graphics1(this);
}
return graphics1;
}
public var g2(get, never): kha.graphics2.Graphics;
function get_g2(): kha.graphics2.Graphics {
if (graphics2 == null) {
graphics2 = new kha.kore.graphics4.Graphics2(this);
}
return graphics2;
}
public var g4(get, never): kha.graphics4.Graphics;
function get_g4(): kha.graphics4.Graphics {
if (graphics4 == null) {
graphics4 = new kha.kore.graphics4.Graphics(this);
}
return graphics4;
}
public static var maxSize(get, never): Int;
static function get_maxSize(): Int {
return 4096;
}
public static var nonPow2Supported(get, never): Bool;
@:functionCode("return kinc_g4_supports_non_pow2_textures();")
static function get_nonPow2Supported(): Bool {
return false;
}
@:functionCode("return kinc_g4_render_targets_inverted_y();")
public static function renderTargetsInvertedY(): Bool {
return false;
}
public var width(get, never): Int;
@:functionCode("return originalWidth;")
function get_width(): Int {
return 0;
}
public var height(get, never): Int;
@:functionCode("return originalHeight;")
function get_height(): Int {
return 0;
}
public var depth(get, never): Int;
@:functionCode("if (imageType == KhaImageTypeTexture) return texture.tex_depth; else return 0;")
function get_depth(): Int {
return 0;
}
public var format(get, never): TextureFormat;
@:functionCode("if (imageType == KhaImageTypeTexture) return texture.format; else return 0;")
function get_format(): TextureFormat {
return TextureFormat.RGBA32;
}
public var realWidth(get, never): Int;
@:functionCode("if (imageType == KhaImageTypeTexture) return texture.tex_width; else if (imageType == KhaImageTypeRenderTarget) return renderTarget.width; else return 0;")
function get_realWidth(): Int {
return 0;
}
public var realHeight(get, never): Int;
@:functionCode("if (imageType == KhaImageTypeTexture) return texture.tex_height; else if (imageType == KhaImageTypeRenderTarget) return renderTarget.height; else return 0;")
function get_realHeight(): Int {
return 0;
}
public function isOpaque(x: Int, y: Int): Bool {
return isOpaqueInternal(x, y, getTextureFormat(myFormat));
}
@:functionCode("
kinc_image_t image;
kinc_image_init(&image, imageData, originalWidth, originalHeight, (kinc_image_format_t)format);
bool opaque = (kinc_image_at(&image, x, y) & 0xff) != 0;
kinc_image_destroy(&image);
return opaque;
")
function isOpaqueInternal(x: Int, y: Int, format: Int): Bool {
return true;
}
public inline function at(x: Int, y: Int): Color {
return Color.fromValue(atInternal(x, y, getTextureFormat(myFormat)));
}
@:functionCode("
kinc_image_t image;
kinc_image_init(&image, imageData, originalWidth, originalHeight, (kinc_image_format_t)format);
int value = kinc_image_at(&image, x, y);
kinc_image_destroy(&image);
return value;
")
function atInternal(x: Int, y: Int, format: Int): Int {
return 0;
}
@:keep
@:functionCode("
if (imageType == KhaImageTypeTexture) {
kinc_g4_texture_destroy(&texture);
}
else if (imageType == KhaImageTypeRenderTarget) {
kinc_g4_render_target_destroy(&renderTarget);
}
else if (imageType == KhaImageTypeTextureArray) {
kinc_g4_texture_array_destroy(&textureArray);
}
else {
assert(false);
}
if (ownsImageData) {
free(imageData);
}
imageData = NULL;
imageType = KhaImageTypeNone;
")
public function unload(): Void {}
var bytes: Bytes = null;
@:functionCode("
int size = kinc_image_format_sizeof(texture.format) * originalWidth * originalHeight;
this->bytes = ::haxe::io::Bytes_obj::alloc(size);
return this->bytes;
")
public function lock(level: Int = 0): Bytes {
return null;
}
@:functionCode("
uint8_t *b = bytes->b->Pointer();
uint8_t *tex = kinc_g4_texture_lock(&texture);
int size = kinc_image_format_sizeof(texture.format);
int stride = kinc_g4_texture_stride(&texture);
for (int y = 0; y < texture.tex_height; ++y) {
for (int x = 0; x < texture.tex_width; ++x) {
#ifdef KORE_DIRECT3D
if (texture.format == KINC_IMAGE_FORMAT_RGBA32) {
//RBGA->BGRA
tex[y * stride + x * size + 0] = b[(y * originalWidth + x) * size + 2];
tex[y * stride + x * size + 1] = b[(y * originalWidth + x) * size + 1];
tex[y * stride + x * size + 2] = b[(y * originalWidth + x) * size + 0];
tex[y * stride + x * size + 3] = b[(y * originalWidth + x) * size + 3];
}
else
#endif
{
for (int i = 0; i < size; ++i) {
tex[y * stride + x * size + i] = b[(y * originalWidth + x) * size + i];
}
}
}
}
kinc_g4_texture_unlock(&texture);
")
public function unlock(): Void {
bytes = null;
}
@:ifFeature("kha.Image.getPixelsInternal")
var pixels: Bytes = null;
@:ifFeature("kha.Image.getPixelsInternal")
var pixelsAllocated: Bool = false;
@:functionCode("
if (imageType != KhaImageTypeRenderTarget) return NULL;
if (!this->pixelsAllocated) {
int size = formatSize * renderTarget.width * renderTarget.height;
this->pixels = ::haxe::io::Bytes_obj::alloc(size);
this->pixelsAllocated = true;
}
uint8_t *b = this->pixels->b->Pointer();
kinc_g4_render_target_get_pixels(&renderTarget, b);
return this->pixels;
")
function getPixelsInternal(formatSize: Int): Bytes {
return null;
}
public function getPixels(): Bytes {
return getPixelsInternal(formatByteSize(myFormat));
}
static function formatByteSize(format: TextureFormat): Int {
return switch (format) {
case RGBA32: 4;
case L8: 1;
case RGBA128: 16;
case DEPTH16: 2;
case RGBA64: 8;
case A32: 4;
case A16: 2;
default: 4;
}
}
public function generateMipmaps(levels: Int): Void {
untyped __cpp__("if (imageType == KhaImageTypeTexture) kinc_g4_texture_generate_mipmaps(&texture, levels); else if (imageType == KhaImageTypeRenderTarget) kinc_g4_render_target_generate_mipmaps(&renderTarget, levels)");
}
public function setMipmaps(mipmaps: Array<Image>): Void {
for (i in 0...mipmaps.length) {
var khaImage = mipmaps[i];
var level = i + 1;
var format = getTextureFormat(this.format);
untyped __cpp__("
kinc_image_t image;
kinc_image_init(&image, {0}->imageData, {0}->originalWidth, {0}->originalHeight, (kinc_image_format_t){2});
kinc_g4_texture_set_mipmap(&texture, &image, {1});
kinc_image_destroy(&image);
", khaImage, level, format);
}
}
public function setDepthStencilFrom(image: Image): Void {
untyped __cpp__("kinc_g4_render_target_set_depth_stencil_from(&renderTarget, &image->renderTarget)");
}
@:functionCode("if (imageType == KhaImageTypeTexture) kinc_g4_texture_clear(&texture, x, y, z, width, height, depth, color);")
public function clear(x: Int, y: Int, z: Int, width: Int, height: Int, depth: Int, color: Color): Void {}
public var stride(get, never): Int;
@:functionCode("if (imageType == KhaImageTypeTexture) return kinc_g4_texture_stride(&texture); else if (imageType == KhaImageTypeRenderTarget) return formatByteSize(myFormat) * renderTarget.width; else return 0;")
function get_stride(): Int {
return 0;
}
}

View File

@ -1,519 +0,0 @@
package kha;
import kha.input.Gamepad;
import kha.input.KeyCode;
import kha.input.Keyboard;
import kha.input.Mouse;
import kha.input.Pen;
import kha.input.Sensor;
import kha.input.SensorType;
import kha.input.Surface;
import kha.System;
import kha.graphics4.TextureFormat;
import kha.graphics4.DepthStencilFormat;
#if ANDROID
#if VR_CARDBOARD
import kha.kore.vr.CardboardVrInterface;
#end
#if !VR_CARDBOARD
import kha.kore.vr.VrInterface;
#end
#end
#if !ANDROID
#if VR_RIFT
import kha.kore.vr.VrInterfaceRift;
#end
#if !VR_RIFT
import kha.vr.VrInterfaceEmulated;
#end
#end
@:headerCode("
#include <kinc/system.h>
#include <kinc/input/gamepad.h>
#include <kinc/input/mouse.h>
#include <kinc/input/pen.h>
#include <kinc/display.h>
#include <kinc/window.h>
kinc_window_options_t convertWindowOptions(::kha::WindowOptions win);
kinc_framebuffer_options_t convertFramebufferOptions(::kha::FramebufferOptions frame);
void init_kinc(const char *name, int width, int height, kinc_window_options_t *win, kinc_framebuffer_options_t *frame);
void post_kinc_init();
void kha_kinc_init_audio(void);
void run_kinc();
const char *getGamepadId(int index);
const char *getGamepadVendor(int index);
void setGamepadRumble(int index, float left, float right);
")
@:keep
class SystemImpl {
public static var needs3d: Bool = false;
public static function getMouse(num: Int): Mouse {
if (num != 0)
return null;
return mouse;
}
public static function getPen(num: Int): Pen {
if (num != 0)
return null;
return pen;
}
public static function getKeyboard(num: Int): Keyboard {
if (num != 0)
return null;
return keyboard;
}
@:functionCode("return kinc_time();")
public static function getTime(): Float {
return 0;
}
public static function windowWidth(windowId: Int): Int {
return untyped __cpp__("kinc_window_width(windowId)");
}
public static function windowHeight(windowId: Int): Int {
return untyped __cpp__("kinc_window_height(windowId)");
}
public static function screenDpi(): Int {
return untyped __cpp__("kinc_display_current_mode(kinc_primary_display()).pixels_per_inch");
}
public static function getVsync(): Bool {
return true;
}
public static function getRefreshRate(): Int {
return 60;
}
public static function getScreenRotation(): ScreenRotation {
return ScreenRotation.RotationNone;
}
@:functionCode("return ::String(kinc_system_id());")
public static function getSystemId(): String {
return "";
}
public static function vibrate(ms: Int): Void {
untyped __cpp__("kinc_vibrate(ms)");
}
@:functionCode("return ::String(kinc_language());")
public static function getLanguage(): String {
return "en";
}
public static function requestShutdown(): Bool {
untyped __cpp__("kinc_stop()");
return true;
}
static var framebuffers: Array<Framebuffer> = new Array();
static var keyboard: Keyboard;
static var mouse: kha.input.Mouse;
static var pen: kha.input.Pen;
static var gamepads: Array<Gamepad>;
static var surface: Surface;
static var mouseLockListeners: Array<Void->Void>;
public static function init(options: SystemOptions, callback: Window->Void): Void {
initKinc(options.title, options.width, options.height, options.window, options.framebuffer);
Window._init();
kha.Worker._mainThread = sys.thread.Thread.current();
untyped __cpp__("post_kinc_init()");
Shaders.init();
#if (!VR_GEAR_VR && !VR_RIFT)
var g4 = new kha.kore.graphics4.Graphics();
g4.window = 0;
// var g5 = new kha.kore.graphics5.Graphics();
var framebuffer = new Framebuffer(0, null, null, g4 /*, g5*/);
framebuffer.init(new kha.graphics2.Graphics1(framebuffer), new kha.kore.graphics4.Graphics2(framebuffer), g4 /*, g5*/);
framebuffers.push(framebuffer);
#end
postInit(callback);
}
static function onWindowCreated(index: Int) {
var g4 = new kha.kore.graphics4.Graphics();
g4.window = index;
var framebuffer = new Framebuffer(index, null, null, g4);
framebuffer.init(new kha.graphics2.Graphics1(framebuffer), new kha.kore.graphics4.Graphics2(framebuffer), g4);
framebuffers.push(framebuffer);
}
static function postInit(callback: Window->Void) {
mouseLockListeners = new Array();
haxe.Timer.stamp();
Sensor.get(SensorType.Accelerometer); // force compilation
keyboard = new kha.kore.Keyboard();
mouse = new kha.input.MouseImpl();
pen = new kha.input.Pen();
gamepads = new Array<Gamepad>();
for (i in 0...4) {
gamepads[i] = new Gamepad(i);
gamepads[i].connected = checkGamepadConnected(i);
}
surface = new Surface();
kha.audio2.Audio._init();
kha.audio1.Audio._init();
untyped __cpp__("kha_kinc_init_audio()");
Scheduler.init();
loadFinished();
callback(Window.get(0));
untyped __cpp__("run_kinc()");
}
static function loadFinished() {
Scheduler.start();
/*
#if ANDROID
#if VR_GEAR_VR
kha.vr.VrInterface.instance = new kha.kore.vr.VrInterface();
#end
#if !VR_GEAR_VR
kha.vr.VrInterface.instance = new CardboardVrInterface();
#end
#end
#if !ANDROID
#if VR_RIFT
kha.vr.VrInterface.instance = new VrInterfaceRift();
#end
#if !VR_RIFT
kha.vr.VrInterface.instance = new kha.vr.VrInterfaceEmulated();
#end
#end
*/
// (DK) moved
/*Shaders.init();
#if (!VR_GEAR_VR && !VR_RIFT)
var g4 = new kha.kore.graphics4.Graphics();
framebuffers.push(new Framebuffer(null, null, g4));
framebuffers[0].init(new kha.graphics2.Graphics1(framebuffers[0]), new kha.kore.graphics4.Graphics2(framebuffers[0]), g4);
g4 = new kha.kore.graphics4.Graphics();
framebuffers.push(new Framebuffer(null, null, g4));
framebuffers[1].init(new kha.graphics2.Graphics1(framebuffers[1]), new kha.kore.graphics4.Graphics2(framebuffers[1]), g4);
#end
*/}
public static function lockMouse(windowId: Int = 0): Void {
if (!isMouseLocked()) {
untyped __cpp__("kinc_mouse_lock(windowId);");
for (listener in mouseLockListeners) {
listener();
}
}
}
public static function unlockMouse(windowId: Int = 0): Void {
if (isMouseLocked()) {
untyped __cpp__("kinc_mouse_unlock();");
for (listener in mouseLockListeners) {
listener();
}
}
}
public static function canLockMouse(windowId: Int = 0): Bool {
return untyped __cpp__("kinc_mouse_can_lock()");
}
public static function isMouseLocked(windowId: Int = 0): Bool {
return untyped __cpp__("kinc_mouse_is_locked()");
}
public static function notifyOfMouseLockChange(func: Void->Void, error: Void->Void, windowId: Int = 0): Void {
if (canLockMouse(windowId) && func != null) {
mouseLockListeners.push(func);
}
}
public static function removeFromMouseLockChange(func: Void->Void, error: Void->Void, windowId: Int = 0): Void {
if (canLockMouse(windowId) && func != null) {
mouseLockListeners.remove(func);
}
}
public static function hideSystemCursor(): Void {
untyped __cpp__("kinc_mouse_hide();");
}
public static function showSystemCursor(): Void {
untyped __cpp__("kinc_mouse_show();");
}
public static function setSystemCursor(cursor: Int): Void {
untyped __cpp__("kinc_mouse_set_cursor(cursor)");
}
public static function frame() {
/*
#if !ANDROID
#if !VR_RIFT
if (framebuffer == null) return;
var vrInterface: VrInterfaceEmulated = cast(VrInterface.instance, VrInterfaceEmulated);
vrInterface.framebuffer = framebuffer;
#end
#else
#if VR_CARDBOARD
var vrInterface: CardboardVrInterface = cast(VrInterface.instance, CardboardVrInterface);
vrInterface.framebuffer = framebuffer;
#end
#end
*/
LoaderImpl.tick();
Scheduler.executeFrame();
System.render(framebuffers);
if (kha.kore.graphics4.Graphics.lastWindow != -1) {
var win = kha.kore.graphics4.Graphics.lastWindow;
untyped __cpp__("kinc_g4_end({0})", win);
}
else {
untyped __cpp__("kinc_g4_begin(0)");
untyped __cpp__("kinc_g4_clear(KINC_G4_CLEAR_COLOR | KINC_G4_CLEAR_DEPTH | KINC_G4_CLEAR_STENCIL, 0, 0.0f, 0)");
untyped __cpp__("kinc_g4_end(0)");
}
kha.kore.graphics4.Graphics.lastWindow = -1;
for (i in 0...4) {
if (gamepads[i].connected && !checkGamepadConnected(i)) {
Gamepad.sendDisconnectEvent(i);
}
else if (!gamepads[i].connected && checkGamepadConnected(i)) {
Gamepad.sendConnectEvent(i);
}
}
}
@:functionCode("return kinc_gamepad_connected(i);")
static function checkGamepadConnected(i: Int): Bool {
return true;
}
public static function keyDown(code: KeyCode): Void {
keyboard.sendDownEvent(code);
}
public static function keyUp(code: KeyCode): Void {
keyboard.sendUpEvent(code);
}
public static function keyPress(char: Int): Void {
keyboard.sendPressEvent(String.fromCharCode(char));
}
public static var mouseX: Int;
public static var mouseY: Int;
public static function mouseDown(windowId: Int, button: Int, x: Int, y: Int): Void {
mouseX = x;
mouseY = y;
mouse.sendDownEvent(windowId, button, x, y);
}
public static function mouseUp(windowId: Int, button: Int, x: Int, y: Int): Void {
mouseX = x;
mouseY = y;
mouse.sendUpEvent(windowId, button, x, y);
}
public static function mouseMove(windowId: Int, x: Int, y: Int, movementX: Int, movementY: Int): Void {
// var movementX = x - mouseX;
// var movementY = y - mouseY;
mouseX = x;
mouseY = y;
mouse.sendMoveEvent(windowId, x, y, movementX, movementY);
}
public static function mouseWheel(windowId: Int, delta: Int): Void {
mouse.sendWheelEvent(windowId, delta);
}
public static function mouseLeave(windowId: Int): Void {
mouse.sendLeaveEvent(windowId);
}
public static function penDown(windowId: Int, x: Int, y: Int, pressure: Float): Void {
pen.sendDownEvent(windowId, x, y, pressure);
}
public static function penUp(windowId: Int, x: Int, y: Int, pressure: Float): Void {
pen.sendUpEvent(windowId, x, y, pressure);
}
public static function penMove(windowId: Int, x: Int, y: Int, pressure: Float): Void {
pen.sendMoveEvent(windowId, x, y, pressure);
}
public static function penEraserDown(windowId: Int, x: Int, y: Int, pressure: Float): Void {
pen.sendEraserDownEvent(windowId, x, y, pressure);
}
public static function penEraserUp(windowId: Int, x: Int, y: Int, pressure: Float): Void {
pen.sendEraserUpEvent(windowId, x, y, pressure);
}
public static function penEraserMove(windowId: Int, x: Int, y: Int, pressure: Float): Void {
pen.sendEraserMoveEvent(windowId, x, y, pressure);
}
public static function gamepadAxis(gamepad: Int, axis: Int, value: Float): Void {
gamepads[gamepad].sendAxisEvent(axis, value);
}
public static function gamepadButton(gamepad: Int, button: Int, value: Float): Void {
gamepads[gamepad].sendButtonEvent(button, value);
}
public static function touchStart(index: Int, x: Int, y: Int): Void {
surface.sendTouchStartEvent(index, x, y);
}
public static function touchEnd(index: Int, x: Int, y: Int): Void {
surface.sendTouchEndEvent(index, x, y);
}
public static function touchMove(index: Int, x: Int, y: Int): Void {
surface.sendMoveEvent(index, x, y);
}
public static function foreground(): Void {
System.foreground();
}
public static function resume(): Void {
System.resume();
}
public static function pause(): Void {
System.pause();
}
public static function background(): Void {
System.background();
}
public static function shutdown(): Void {
System.shutdown();
}
public static function dropFiles(filePath: String): Void {
System.dropFiles(filePath);
}
public static function copy(): String {
if (System.copyListener != null) {
return System.copyListener();
}
else {
return null;
}
}
public static function cut(): String {
if (System.cutListener != null) {
return System.cutListener();
}
else {
return null;
}
}
public static function paste(data: String): Void {
if (System.pasteListener != null) {
System.pasteListener(data);
}
}
@:functionCode("kinc_copy_to_clipboard(text.c_str());")
public static function copyToClipboard(text: String) {}
@:functionCode("kinc_login();")
public static function login(): Void {}
@:functionCode("return kinc_waiting_for_login();")
public static function waitingForLogin(): Bool {
return false;
}
@:functionCode("kinc_disallow_user_change();")
public static function disallowUserChange(): Void {}
@:functionCode("kinc_allow_user_change();")
public static function allowUserChange(): Void {}
public static function loginevent(): Void {
if (System.loginListener != null) {
System.loginListener();
}
}
public static function logoutevent(): Void {
if (System.logoutListener != null) {
System.logoutListener();
}
}
@:functionCode("
kinc_window_options_t window = convertWindowOptions(win);
kinc_framebuffer_options_t framebuffer = convertFramebufferOptions(frame);
init_kinc(name, width, height, &window, &framebuffer);
")
static function initKinc(name: String, width: Int, height: Int, win: WindowOptions, frame: FramebufferOptions): Void {}
public static function setKeepScreenOn(on: Bool): Void {
untyped __cpp__("kinc_set_keep_screen_on(on)");
}
public static function loadUrl(url: String): Void {
untyped __cpp__("kinc_load_url(url)");
}
@:functionCode("return ::String(::getGamepadId(index));")
public static function getGamepadId(index: Int): String {
return "unknown";
}
@:functionCode("return ::String(::getGamepadVendor(index));")
public static function getGamepadVendor(index: Int): String {
return "unknown";
}
public static function setGamepadRumble(index: Int, leftAmount: Float, rightAmount: Float): Void {
untyped __cpp__("::setGamepadRumble(index, leftAmount, rightAmount)");
}
public static function safeZone(): Float {
return untyped __cpp__("kinc_safe_zone()");
}
public static function automaticSafeZone(): Bool {
return untyped __cpp__("kinc_automatic_safe_zone()");
}
public static function setSafeZone(value: Float): Void {
untyped __cpp__("kinc_set_safe_zone(value)");
}
public static function unlockAchievement(id: Int): Void {
untyped __cpp__("kinc_unlock_achievement(id)");
}
}

View File

@ -1,176 +0,0 @@
package kha.compute;
import kha.arrays.Float32Array;
import kha.Image;
import kha.FastFloat;
import kha.math.FastMatrix3;
import kha.math.FastMatrix4;
import kha.math.FastVector2;
import kha.math.FastVector3;
import kha.math.FastVector4;
import kha.graphics4.CubeMap;
import kha.graphics4.TextureAddressing;
import kha.graphics4.TextureFilter;
import kha.graphics4.MipMapFilter;
@:headerCode("
#include <kinc/compute/compute.h>
")
class Compute {
public static function setBool(location: ConstantLocation, value: Bool) {
untyped __cpp__("kinc_compute_set_bool(location->location, value);");
}
public static function setInt(location: ConstantLocation, value: Int) {
untyped __cpp__("kinc_compute_set_int(location->location, value);");
}
public static function setFloat(location: ConstantLocation, value: FastFloat) {
untyped __cpp__("kinc_compute_set_float(location->location, value);");
}
public static function setFloat2(location: ConstantLocation, value1: FastFloat, value2: FastFloat) {
untyped __cpp__("kinc_compute_set_float2(location->location, value1, value2);");
}
public static function setFloat3(location: ConstantLocation, value1: FastFloat, value2: FastFloat, value3: FastFloat) {
untyped __cpp__("kinc_compute_set_float3(location->location, value1, value2, value3);");
}
public static function setFloat4(location: ConstantLocation, value1: FastFloat, value2: FastFloat, value3: FastFloat, value4: FastFloat) {
untyped __cpp__("kinc_compute_set_float4(location->location, value1, value2, value3, value4);");
}
public static function setFloats(location: ConstantLocation, values: Float32Array) {
untyped __cpp__("kinc_compute_set_floats(location->location, (float *)&values->self.data[values->byteArrayOffset], values->byteArrayLength);");
}
public static function setVector2(location: ConstantLocation, value: FastVector2): Void {
Compute.setFloat2(location, value.x, value.y);
}
public static function setVector3(location: ConstantLocation, value: FastVector3): Void {
Compute.setFloat3(location, value.x, value.y, value.z);
}
public static function setVector4(location: ConstantLocation, value: FastVector4): Void {
Compute.setFloat4(location, value.x, value.y, value.z, value.w);
}
public static function setMatrix(location: ConstantLocation, value: FastMatrix4): Void {
setMatrixPrivate(location, value);
}
public static function setMatrix3(location: ConstantLocation, value: FastMatrix3): Void {
setMatrix3Private(location, value);
}
@:functionCode("
kinc_matrix4x4_t value;
kinc_matrix4x4_set(&value, 0, 0, matrix->_00); kinc_matrix4x4_set(&value, 0, 1, matrix->_10); kinc_matrix4x4_set(&value, 0, 2, matrix->_20); kinc_matrix4x4_set(&value, 0, 3, matrix->_30);
kinc_matrix4x4_set(&value, 1, 0, matrix->_01); kinc_matrix4x4_set(&value, 1, 1, matrix->_11); kinc_matrix4x4_set(&value, 1, 2, matrix->_21); kinc_matrix4x4_set(&value, 1, 3, matrix->_31);
kinc_matrix4x4_set(&value, 2, 0, matrix->_02); kinc_matrix4x4_set(&value, 2, 1, matrix->_12); kinc_matrix4x4_set(&value, 2, 2, matrix->_22); kinc_matrix4x4_set(&value, 2, 3, matrix->_32);
kinc_matrix4x4_set(&value, 3, 0, matrix->_03); kinc_matrix4x4_set(&value, 3, 1, matrix->_13); kinc_matrix4x4_set(&value, 3, 2, matrix->_23); kinc_matrix4x4_set(&value, 3, 3, matrix->_33);
kinc_compute_set_matrix4(location->location, &value);
")
static function setMatrixPrivate(location: ConstantLocation, matrix: FastMatrix4): Void {}
@:functionCode("
kinc_matrix3x3_t value;
kinc_matrix3x3_set(&value, 0, 0, matrix->_00); kinc_matrix3x3_set(&value, 0, 1, matrix->_10); kinc_matrix3x3_set(&value, 0, 2, matrix->_20);
kinc_matrix3x3_set(&value, 1, 0, matrix->_01); kinc_matrix3x3_set(&value, 1, 1, matrix->_11); kinc_matrix3x3_set(&value, 1, 2, matrix->_21);
kinc_matrix3x3_set(&value, 2, 0, matrix->_02); kinc_matrix3x3_set(&value, 2, 1, matrix->_12); kinc_matrix3x3_set(&value, 2, 2, matrix->_22);
kinc_compute_set_matrix3(location->location, &value);
")
static function setMatrix3Private(location: ConstantLocation, matrix: FastMatrix3): Void {}
public static function setBuffer(buffer: ShaderStorageBuffer, index: Int) {
untyped __cpp__("
#ifdef KORE_OPENGL
kinc_compute_set_buffer(&buffer->buffer, index);
#endif
");
}
public static function setTexture(unit: TextureUnit, texture: Image, access: Access) {
setTexturePrivate(unit, texture, access);
}
@:functionCode("
if (texture->imageType == KhaImageTypeTexture) kinc_compute_set_texture(unit->unit, &texture->texture, (kinc_compute_access_t)access);
else if (texture->imageType == KhaImageTypeRenderTarget) kinc_compute_set_render_target(unit->unit, &texture->renderTarget, (kinc_compute_access_t)access);
")
static function setTexturePrivate(unit: TextureUnit, texture: Image, access: Int): Void {}
public static function setSampledTexture(unit: TextureUnit, texture: Image) {
setSampledTexturePrivate(unit, texture);
}
@:functionCode("
if (texture->imageType == KhaImageTypeTexture) kinc_compute_set_sampled_texture(unit->unit, &texture->texture);
else if (texture->imageType == KhaImageTypeRenderTarget) kinc_compute_set_sampled_render_target(unit->unit, &texture->renderTarget);
")
static function setSampledTexturePrivate(unit: TextureUnit, texture: Image): Void {}
public static function setSampledDepthTexture(unit: TextureUnit, texture: Image) {
untyped __cpp__("if (texture->imageType == KhaImageTypeRenderTarget) kinc_compute_set_sampled_depth_from_render_target(unit->unit, &texture->renderTarget);");
}
public static function setSampledCubeMap(unit: TextureUnit, cubeMap: CubeMap) {
setSampledCubeMapPrivate(unit, cubeMap);
}
@:functionCode("kinc_compute_set_sampled_render_target(unit->unit, &cubeMap->renderTarget);")
static function setSampledCubeMapPrivate(unit: TextureUnit, cubeMap: CubeMap): Void {}
public static function setSampledDepthCubeMap(unit: TextureUnit, cubeMap: CubeMap) {
untyped __cpp__("kinc_compute_set_sampled_depth_from_render_target(unit->unit, &cubeMap->renderTarget);");
}
@:functionCode("
kinc_compute_set_texture_addressing(unit->unit, KINC_G4_TEXTURE_DIRECTION_U, (kinc_g4_texture_addressing_t)uWrap);
kinc_compute_set_texture_addressing(unit->unit, KINC_G4_TEXTURE_DIRECTION_V, (kinc_g4_texture_addressing_t)vWrap);
")
static function setTextureWrapNative(unit: TextureUnit, uWrap: Int, vWrap: Int): Void {}
@:functionCode("
kinc_compute_set_texture3d_addressing(unit->unit, KINC_G4_TEXTURE_DIRECTION_U, (kinc_g4_texture_addressing_t)uWrap);
kinc_compute_set_texture3d_addressing(unit->unit, KINC_G4_TEXTURE_DIRECTION_V, (kinc_g4_texture_addressing_t)vWrap);
kinc_compute_set_texture3d_addressing(unit->unit, KINC_G4_TEXTURE_DIRECTION_W, (kinc_g4_texture_addressing_t)wWrap);
")
static function setTexture3DWrapNative(unit: TextureUnit, uWrap: Int, vWrap: Int, wWrap: Int): Void {}
@:functionCode("
kinc_compute_set_texture_minification_filter(unit->unit, (kinc_g4_texture_filter_t)minificationFilter);
kinc_compute_set_texture_magnification_filter(unit->unit, (kinc_g4_texture_filter_t)magnificationFilter);
kinc_compute_set_texture_mipmap_filter(unit->unit, (kinc_g4_mipmap_filter_t)mipMapFilter);
")
static function setTextureFiltersNative(unit: TextureUnit, minificationFilter: Int, magnificationFilter: Int, mipMapFilter: Int): Void {}
@:functionCode("
kinc_compute_set_texture3d_minification_filter(unit->unit, (kinc_g4_texture_filter_t)minificationFilter);
kinc_compute_set_texture3d_magnification_filter(unit->unit, (kinc_g4_texture_filter_t)magnificationFilter);
kinc_compute_set_texture3d_mipmap_filter(unit->unit, (kinc_g4_mipmap_filter_t)mipMapFilter);
")
static function setTexture3DFiltersNative(unit: TextureUnit, minificationFilter: Int, magnificationFilter: Int, mipMapFilter: Int): Void {}
public static function setTextureParameters(unit: TextureUnit, uAddressing: TextureAddressing, vAddressing: TextureAddressing,
minificationFilter: TextureFilter, magnificationFilter: TextureFilter, mipmapFilter: MipMapFilter): Void {
setTextureWrapNative(unit, uAddressing, vAddressing);
setTextureFiltersNative(unit, minificationFilter, magnificationFilter, mipmapFilter);
}
public static function setTexture3DParameters(unit: TextureUnit, uAddressing: TextureAddressing, vAddressing: TextureAddressing,
wAddressing: TextureAddressing, minificationFilter: TextureFilter, magnificationFilter: TextureFilter, mipmapFilter: MipMapFilter): Void {
setTexture3DWrapNative(unit, uAddressing, vAddressing, wAddressing);
setTexture3DFiltersNative(unit, minificationFilter, magnificationFilter, mipmapFilter);
}
public static function setShader(shader: Shader) {
untyped __cpp__("kinc_compute_set_shader(&shader->shader);");
}
public static function compute(x: Int, y: Int, z: Int) {
untyped __cpp__("kinc_compute(x, y, z);");
}
}

View File

@ -1,9 +0,0 @@
package kha.compute;
@:headerCode("
#include <kinc/compute/compute.h>
")
@:headerClassCode("kinc_compute_constant_location location;")
class ConstantLocation {
public function new() {}
}

View File

@ -1,45 +0,0 @@
package kha.compute;
import haxe.io.Bytes;
import kha.Blob;
@:headerCode("
#include <kinc/compute/compute.h>
")
@:headerClassCode("kinc_compute_shader shader;")
class Shader {
public function new(sources: Array<Blob>, files: Array<String>) {
init(sources[0], files[0]);
}
function init(source: Blob, file: String): Void {
untyped __cpp__("kinc_compute_shader_init(&shader, source->bytes->b->Pointer(), source->get_length());");
}
public function delete(): Void {
untyped __cpp__("kinc_compute_shader_destroy(&shader);");
}
public function getConstantLocation(name: String): ConstantLocation {
var location = new ConstantLocation();
initConstantLocation(location, name);
return location;
}
@:functionCode("location->location = kinc_compute_shader_get_constant_location(&shader, name.c_str());")
function initConstantLocation(location: ConstantLocation, name: String): Void {}
public function getTextureUnit(name: String): TextureUnit {
var unit = new TextureUnit();
initTextureUnit(unit, name);
return unit;
}
@:functionCode("unit->unit = kinc_compute_shader_get_texture_unit(&shader, name.c_str());")
function initTextureUnit(unit: TextureUnit, name: String): Void {}
@:keep
function _forceInclude(): Void {
Bytes.alloc(0);
}
}

View File

@ -1,77 +0,0 @@
package kha.compute;
import kha.graphics4.VertexData;
@:headerCode("
#include <kinc/compute/compute.h>
")
@:headerClassCode("
#ifdef KORE_OPENGL
kinc_shader_storage_buffer buffer;
#endif")
class ShaderStorageBuffer {
var data: Array<Int>;
var myCount: Int;
public function new(indexCount: Int, type: VertexData) {
myCount = indexCount;
data = new Array<Int>();
data[myCount - 1] = 0;
init(indexCount, type);
}
@:functionCode("
#ifdef KORE_OPENGL
kinc_g4_vertex_data type2;
switch (type) {
case 0:
type2 = KINC_G4_VERTEX_DATA_FLOAT1;
break;
case 1:
type2 = KINC_G4_VERTEX_DATA_FLOAT2;
break;
case 2:
type2 = KINC_G4_VERTEX_DATA_FLOAT3;
break;
case 3:
type2 = KINC_G4_VERTEX_DATA_FLOAT4;
break;
case 4:
type2 = KINC_G4_VERTEX_DATA_FLOAT4X4;
break;
}
kinc_shader_storage_buffer_init(&buffer, indexCount, type2);
#endif
")
function init(indexCount: Int, type: VertexData) {
myCount = indexCount;
data = new Array<Int>();
data[myCount - 1] = 0;
}
@:functionCode("
#ifdef KORE_OPENGL
kinc_shader_storage_buffer_destroy(&buffer);
#endif
")
public function delete(): Void {}
public function lock(): Array<Int> {
return data;
}
@:functionCode("
#ifdef KORE_OPENGL
int* indices = kinc_shader_storage_buffer_lock(&buffer);
for (int i = 0; i < myCount; ++i) {
indices[i] = data[i];
}
kinc_shader_storage_buffer_unlock(&buffer);
#endif
")
public function unlock(): Void {}
public function count(): Int {
return myCount;
}
}

View File

@ -1,9 +0,0 @@
package kha.compute;
@:headerCode("
#include <kinc/compute/compute.h>
")
@:headerClassCode("kinc_compute_texture_unit unit;")
class TextureUnit {
public function new() {}
}

View File

@ -1,503 +0,0 @@
package kha.kore.graphics4;
import kha.arrays.Float32Array;
import kha.Blob;
import kha.Canvas;
import kha.Color;
import kha.graphics4.CubeMap;
import kha.graphics4.CullMode;
import kha.graphics4.FragmentShader;
import kha.graphics4.BlendingFactor;
import kha.graphics4.BlendingOperation;
import kha.graphics4.CompareMode;
import kha.graphics4.MipMapFilter;
import kha.graphics4.PipelineState;
import kha.graphics4.StencilAction;
import kha.graphics4.TexDir;
import kha.graphics4.TextureAddressing;
import kha.graphics4.TextureFilter;
import kha.graphics4.TextureFormat;
import kha.graphics4.Usage;
import kha.graphics4.VertexBuffer;
import kha.graphics4.VertexShader;
import kha.graphics4.VertexStructure;
import kha.Image;
import kha.math.FastMatrix3;
import kha.math.FastMatrix4;
import kha.math.FastVector2;
import kha.math.FastVector3;
import kha.math.FastVector4;
import kha.math.Matrix4;
import kha.math.Vector2;
import kha.math.Vector3;
import kha.math.Vector4;
import kha.Video;
@:headerCode("
#include <kinc/display.h>
#include <kinc/graphics4/graphics.h>
#include <kinc/graphics4/rendertarget.h>
#include <kinc/window.h>
")
@:headerClassCode("kinc_g4_render_target_t *renderTarget = nullptr;")
class Graphics implements kha.graphics4.Graphics {
var target: Canvas;
public var window: Null<Int>;
public static var lastWindow: Int = -1;
static var current: Graphics = null;
public function new(target: Canvas = null) {
this.target = target;
init();
}
function init() {
if (target == null)
return;
if (Std.isOfType(target, CubeMap)) {
var cubeMap = cast(target, CubeMap);
untyped __cpp__("renderTarget = &{0}->renderTarget", cubeMap);
}
else {
var image = cast(target, Image);
untyped __cpp__("renderTarget = &{0}->renderTarget", image);
}
}
@:functionCode("return kinc_window_vsynced(0);")
public function vsynced(): Bool {
return true;
}
@:functionCode("return kinc_display_current_mode(kinc_primary_display()).frequency;")
public function refreshRate(): Int {
return 0;
}
public function clear(?color: Color, ?z: Float, ?stencil: Int): Void {
var flags: Int = 0;
if (color != null)
flags |= 1;
if (z != null)
flags |= 2;
if (stencil != null)
flags |= 4;
clear2(flags, color == null ? 0 : color.value, z, stencil);
}
@:functionCode("kinc_g4_viewport(x, y, width, height);")
public function viewport(x: Int, y: Int, width: Int, height: Int): Void {}
@:functionCode("kinc_g4_clear(flags, color, z, stencil);")
function clear2(flags: Int, color: Int, z: Float, stencil: Int): Void {}
// public function createVertexBuffer(vertexCount: Int, structure: VertexStructure, usage: Usage, canRead: Bool = false): kha.graphics4.VertexBuffer {
// return new VertexBuffer(vertexCount, structure);
// }
@:functionCode("kinc_g4_set_vertex_buffer(&vertexBuffer->buffer);")
public function setVertexBuffer(vertexBuffer: kha.graphics4.VertexBuffer): Void {}
@:functionCode("
kinc_g4_vertex_buffer_t* vertexBuffers[4] = {
vb0 == null() ? nullptr : &vb0->buffer,
vb1 == null() ? nullptr : &vb1->buffer,
vb2 == null() ? nullptr : &vb2->buffer,
vb3 == null() ? nullptr : &vb3->buffer
};
kinc_g4_set_vertex_buffers(vertexBuffers, count);
")
function setVertexBuffersInternal(vb0: VertexBuffer, vb1: VertexBuffer, vb2: VertexBuffer, vb3: VertexBuffer, count: Int): Void {}
public function setVertexBuffers(vertexBuffers: Array<kha.graphics4.VertexBuffer>): Void {
setVertexBuffersInternal(vertexBuffers.length > 0 ? vertexBuffers[0] : null, vertexBuffers.length > 1 ? vertexBuffers[1] : null,
vertexBuffers.length > 2 ? vertexBuffers[2] : null, vertexBuffers.length > 3 ? vertexBuffers[3] : null, vertexBuffers.length);
}
// public function createIndexBuffer(indexCount: Int, usage: Usage, canRead: Bool = false): kha.graphics.IndexBuffer {
// return new IndexBuffer(indexCount);
// }
@:functionCode("kinc_g4_set_index_buffer(&indexBuffer->buffer);")
public function setIndexBuffer(indexBuffer: kha.graphics4.IndexBuffer): Void {}
// public function createTexture(width: Int, height: Int, format: TextureFormat, usage: Usage, canRead: Bool = false, levels: Int = 1): Texture {
// return Image.create(width, height, format, canRead, false, false);
// }
// public function createRenderTargetTexture(width: Int, height: Int, format: TextureFormat, depthStencil: Bool, antiAliasingSamples: Int = 1): Texture {
// return Image.create(width, height, format, false, true, depthStencil);
// }
public function maxTextureSize(): Int {
return 4096;
}
public function supportsNonPow2Textures(): Bool {
return false;
}
public function setCubeMap(unit: kha.graphics4.TextureUnit, cubeMap: kha.graphics4.CubeMap): Void {
if (cubeMap == null)
return;
var koreUnit = cast(unit, kha.kore.graphics4.TextureUnit);
untyped __cpp__("kinc_g4_render_target_use_color_as_texture(&cubeMap->renderTarget, {0}->unit)", koreUnit);
}
public function setCubeMapDepth(unit: kha.graphics4.TextureUnit, cubeMap: kha.graphics4.CubeMap): Void {
if (cubeMap == null)
return;
var koreUnit = cast(unit, kha.kore.graphics4.TextureUnit);
untyped __cpp__("kinc_g4_render_target_use_depth_as_texture(&cubeMap->renderTarget, {0}->unit);", koreUnit);
}
@:functionCode("kinc_g4_scissor(x, y, width, height);")
public function scissor(x: Int, y: Int, width: Int, height: Int): Void {}
@:functionCode("kinc_g4_disable_scissor();")
public function disableScissor(): Void {}
public function instancedRenderingAvailable(): Bool {
return true;
}
@:functionCode("
kinc_g4_set_texture_addressing(unit->unit, KINC_G4_TEXTURE_DIRECTION_U, (kinc_g4_texture_addressing_t)uWrap);
kinc_g4_set_texture_addressing(unit->unit, KINC_G4_TEXTURE_DIRECTION_V, (kinc_g4_texture_addressing_t)vWrap);
")
function setTextureWrapNative(unit: TextureUnit, uWrap: Int, vWrap: Int): Void {}
@:functionCode("
kinc_g4_set_texture3d_addressing(unit->unit, KINC_G4_TEXTURE_DIRECTION_U, (kinc_g4_texture_addressing_t)uWrap);
kinc_g4_set_texture3d_addressing(unit->unit, KINC_G4_TEXTURE_DIRECTION_V, (kinc_g4_texture_addressing_t)vWrap);
kinc_g4_set_texture3d_addressing(unit->unit, KINC_G4_TEXTURE_DIRECTION_W, (kinc_g4_texture_addressing_t)wWrap);
")
function setTexture3DWrapNative(unit: TextureUnit, uWrap: Int, vWrap: Int, wWrap: Int): Void {}
@:functionCode("
kinc_g4_set_texture_minification_filter(unit->unit, (kinc_g4_texture_filter_t)minificationFilter);
kinc_g4_set_texture_magnification_filter(unit->unit, (kinc_g4_texture_filter_t)magnificationFilter);
kinc_g4_set_texture_mipmap_filter(unit->unit, (kinc_g4_mipmap_filter_t)mipMapFilter);
")
function setTextureFiltersNative(unit: TextureUnit, minificationFilter: Int, magnificationFilter: Int, mipMapFilter: Int): Void {}
@:functionCode("
kinc_g4_set_texture3d_minification_filter(unit->unit, (kinc_g4_texture_filter_t)minificationFilter);
kinc_g4_set_texture3d_magnification_filter(unit->unit, (kinc_g4_texture_filter_t)magnificationFilter);
kinc_g4_set_texture3d_mipmap_filter(unit->unit, (kinc_g4_mipmap_filter_t)mipMapFilter);
")
function setTexture3DFiltersNative(unit: TextureUnit, minificationFilter: Int, magnificationFilter: Int, mipMapFilter: Int): Void {}
public function setTextureParameters(texunit: kha.graphics4.TextureUnit, uAddressing: TextureAddressing, vAddressing: TextureAddressing,
minificationFilter: TextureFilter, magnificationFilter: TextureFilter, mipmapFilter: MipMapFilter): Void {
setTextureWrapNative(cast texunit, uAddressing, vAddressing);
setTextureFiltersNative(cast texunit, minificationFilter, magnificationFilter, mipmapFilter);
}
public function setTexture3DParameters(texunit: kha.graphics4.TextureUnit, uAddressing: TextureAddressing, vAddressing: TextureAddressing,
wAddressing: TextureAddressing, minificationFilter: TextureFilter, magnificationFilter: TextureFilter, mipmapFilter: MipMapFilter): Void {
setTexture3DWrapNative(cast texunit, uAddressing, vAddressing, wAddressing);
setTexture3DFiltersNative(cast texunit, minificationFilter, magnificationFilter, mipmapFilter);
}
public function setTextureCompareMode(texunit: kha.graphics4.TextureUnit, enabled: Bool) {
var koreUnit = cast(texunit, kha.kore.graphics4.TextureUnit);
untyped __cpp__("kinc_g4_set_texture_compare_mode({0}->unit, enabled);", koreUnit);
}
public function setCubeMapCompareMode(texunit: kha.graphics4.TextureUnit, enabled: Bool) {
var koreUnit = cast(texunit, kha.kore.graphics4.TextureUnit);
untyped __cpp__("kinc_g4_set_cubemap_compare_mode({0}->unit, enabled);", koreUnit);
}
@:functionCode("
if (texture->imageType == KhaImageTypeTexture) kinc_g4_set_texture(unit->unit, &texture->texture);
else if (texture->imageType == KhaImageTypeRenderTarget) kinc_g4_render_target_use_color_as_texture(&texture->renderTarget, unit->unit);
")
function setTextureInternal(unit: kha.kore.graphics4.TextureUnit, texture: kha.Image): Void {}
public function setTexture(unit: kha.graphics4.TextureUnit, texture: kha.Image): Void {
if (texture == null)
return;
setTextureInternal(cast unit, texture);
}
public function setTextureDepth(unit: kha.graphics4.TextureUnit, texture: kha.Image): Void {
if (texture == null)
return;
var koreUnit = cast(unit, kha.kore.graphics4.TextureUnit);
untyped __cpp__("kinc_g4_render_target_use_depth_as_texture(&texture->renderTarget, {0}->unit);", koreUnit);
}
public function setTextureArray(unit: kha.graphics4.TextureUnit, texture: kha.Image): Void {
if (texture == null)
return;
var koreUnit = cast(unit, kha.kore.graphics4.TextureUnit);
untyped __cpp__("if (texture->imageType == KhaImageTypeTextureArray) kinc_g4_set_texture_array({0}->unit, &texture->textureArray);", koreUnit);
}
public function setVideoTexture(unit: kha.graphics4.TextureUnit, texture: kha.Video): Void {
if (texture == null)
return;
setTextureInternal(cast unit, Image.fromVideo(texture));
}
@:functionCode("kinc_g4_set_image_texture(unit->unit, &texture->texture);")
function setImageTextureInternal(unit: kha.kore.graphics4.TextureUnit, texture: kha.Image): Void {}
public function setImageTexture(unit: kha.graphics4.TextureUnit, texture: kha.Image): Void {
if (texture == null)
return;
setImageTextureInternal(cast unit, texture);
}
@:functionCode("return kinc_g4_max_bound_textures();")
public function maxBoundTextures(): Int {
return 0;
}
// public function createVertexShader(source: Blob): VertexShader {
// return new Shader(source, ShaderType.VertexShader);
// }
// public function createFragmentShader(source: Blob): FragmentShader {
// return new Shader(source, ShaderType.FragmentShader);
// }
// public function createProgram(): kha.graphics4.Program {
// return new Program();
// }
public function setPipeline(pipe: PipelineState): Void {
pipe.set();
}
@:functionCode("kinc_g4_set_stencil_reference_value(value);")
public function setStencilReferenceValue(value: Int): Void {}
public function setBool(location: kha.graphics4.ConstantLocation, value: Bool): Void {
setBoolPrivate(cast location, value);
}
@:functionCode("kinc_g4_set_bool(location->location, value);")
function setBoolPrivate(location: kha.kore.graphics4.ConstantLocation, value: Bool): Void {}
public function setInt(location: kha.graphics4.ConstantLocation, value: Int): Void {
setIntPrivate(cast location, value);
}
@:functionCode("kinc_g4_set_int(location->location, value);")
function setIntPrivate(location: ConstantLocation, value: Int): Void {}
public function setInt2(location: kha.graphics4.ConstantLocation, value1: Int, value2: Int): Void {
setInt2Private(cast location, value1, value2);
}
@:functionCode("kinc_g4_set_int2(location->location, value1, value2);")
function setInt2Private(location: ConstantLocation, value1: Int, value2: Int): Void {}
public function setInt3(location: kha.graphics4.ConstantLocation, value1: Int, value2: Int, value3: Int): Void {
setInt3Private(cast location, value1, value2, value3);
}
@:functionCode("kinc_g4_set_int3(location->location, value1, value2, value3);")
function setInt3Private(location: ConstantLocation, value1: Int, value2: Int, value3: Int): Void {}
public function setInt4(location: kha.graphics4.ConstantLocation, value1: Int, value2: Int, value3: Int, value4: Int): Void {
setInt4Private(cast location, value1, value2, value3, value4);
}
@:functionCode("kinc_g4_set_int4(location->location, value1, value2, value3, value4);")
function setInt4Private(location: ConstantLocation, value1: Int, value2: Int, value3: Int, value4: Int): Void {}
public function setInts(location: kha.graphics4.ConstantLocation, values: kha.arrays.Int32Array): Void {
setIntsPrivate(cast location, values);
}
@:functionCode("kinc_g4_set_ints(location->location, (int*)values->self.data, values->byteArrayLength / 4);")
function setIntsPrivate(location: ConstantLocation, values: kha.arrays.Int32Array): Void {}
public function setFloat(location: kha.graphics4.ConstantLocation, value: FastFloat): Void {
setFloatPrivate(cast location, value);
}
@:functionCode("kinc_g4_set_float(location->location, value);")
function setFloatPrivate(location: ConstantLocation, value: FastFloat): Void {}
public function setFloat2(location: kha.graphics4.ConstantLocation, value1: FastFloat, value2: FastFloat): Void {
setFloat2Private(cast location, value1, value2);
}
@:functionCode("kinc_g4_set_float2(location->location, value1, value2);")
function setFloat2Private(location: ConstantLocation, value1: FastFloat, value2: FastFloat): Void {}
public function setFloat3(location: kha.graphics4.ConstantLocation, value1: FastFloat, value2: FastFloat, value3: FastFloat): Void {
setFloat3Private(cast location, value1, value2, value3);
}
@:functionCode("kinc_g4_set_float3(location->location, value1, value2, value3);")
function setFloat3Private(location: ConstantLocation, value1: FastFloat, value2: FastFloat, value3: FastFloat): Void {}
public function setFloat4(location: kha.graphics4.ConstantLocation, value1: FastFloat, value2: FastFloat, value3: FastFloat, value4: FastFloat): Void {
setFloat4Private(cast location, value1, value2, value3, value4);
}
@:functionCode("kinc_g4_set_float4(location->location, value1, value2, value3, value4);")
function setFloat4Private(location: ConstantLocation, value1: FastFloat, value2: FastFloat, value3: FastFloat, value4: FastFloat): Void {}
public function setVector2(location: kha.graphics4.ConstantLocation, value: FastVector2): Void {
setVector2Private(cast location, value.x, value.y);
}
@:functionCode("kinc_g4_set_float2(location->location, x, y);")
function setVector2Private(location: ConstantLocation, x: FastFloat, y: FastFloat): Void {}
public function setVector3(location: kha.graphics4.ConstantLocation, value: FastVector3): Void {
setVector3Private(cast location, value.x, value.y, value.z);
}
@:functionCode("kinc_g4_set_float3(location->location, x, y, z);")
function setVector3Private(location: ConstantLocation, x: FastFloat, y: FastFloat, z: FastFloat): Void {}
public function setVector4(location: kha.graphics4.ConstantLocation, value: FastVector4): Void {
setVector4Private(cast location, value.x, value.y, value.z, value.w);
}
@:functionCode("kinc_g4_set_float4(location->location, x, y, z, w);")
function setVector4Private(location: ConstantLocation, x: FastFloat, y: FastFloat, z: FastFloat, w: FastFloat): Void {}
public function setFloats(location: kha.graphics4.ConstantLocation, values: Float32Array): Void {
setFloatsPrivate(cast location, values);
}
@:functionCode("kinc_g4_set_floats(location->location, (float*)values->self.data, values->byteArrayLength / 4);")
function setFloatsPrivate(location: ConstantLocation, values: Float32Array): Void {}
public function setMatrix(location: kha.graphics4.ConstantLocation, matrix: FastMatrix4): Void {
setMatrixPrivate(cast location, matrix);
}
@:functionCode("
kinc_matrix4x4_t value;
kinc_matrix4x4_set(&value, 0, 0, matrix->_00); kinc_matrix4x4_set(&value, 1, 0, matrix->_10); kinc_matrix4x4_set(&value, 2, 0, matrix->_20); kinc_matrix4x4_set(&value, 3, 0, matrix->_30);
kinc_matrix4x4_set(&value, 0, 1, matrix->_01); kinc_matrix4x4_set(&value, 1, 1, matrix->_11); kinc_matrix4x4_set(&value, 2, 1, matrix->_21); kinc_matrix4x4_set(&value, 3, 1, matrix->_31);
kinc_matrix4x4_set(&value, 0, 2, matrix->_02); kinc_matrix4x4_set(&value, 1, 2, matrix->_12); kinc_matrix4x4_set(&value, 2, 2, matrix->_22); kinc_matrix4x4_set(&value, 3, 2, matrix->_32);
kinc_matrix4x4_set(&value, 0, 3, matrix->_03); kinc_matrix4x4_set(&value, 1, 3, matrix->_13); kinc_matrix4x4_set(&value, 2, 3, matrix->_23); kinc_matrix4x4_set(&value, 3, 3, matrix->_33);
kinc_g4_set_matrix4(location->location, &value);
")
function setMatrixPrivate(location: ConstantLocation, matrix: FastMatrix4): Void {}
public function setMatrix3(location: kha.graphics4.ConstantLocation, matrix: FastMatrix3): Void {
setMatrix3Private(cast location, matrix);
}
@:functionCode("
kinc_matrix3x3_t value;
kinc_matrix3x3_set(&value, 0, 0, matrix->_00); kinc_matrix3x3_set(&value, 1, 0, matrix->_10); kinc_matrix3x3_set(&value, 2, 0, matrix->_20);
kinc_matrix3x3_set(&value, 0, 1, matrix->_01); kinc_matrix3x3_set(&value, 1, 1, matrix->_11); kinc_matrix3x3_set(&value, 2, 1, matrix->_21);
kinc_matrix3x3_set(&value, 0, 2, matrix->_02); kinc_matrix3x3_set(&value, 1, 2, matrix->_12); kinc_matrix3x3_set(&value, 2, 2, matrix->_22);
kinc_g4_set_matrix3(location->location, &value);
")
function setMatrix3Private(location: ConstantLocation, matrix: FastMatrix3): Void {}
public function drawIndexedVertices(start: Int = 0, count: Int = -1): Void {
if (count < 0)
drawAllIndexedVertices();
else
drawSomeIndexedVertices(start, count);
}
@:functionCode("kinc_g4_draw_indexed_vertices();")
function drawAllIndexedVertices(): Void {}
@:functionCode("kinc_g4_draw_indexed_vertices_from_to(start, count);")
public function drawSomeIndexedVertices(start: Int, count: Int): Void {}
public function drawIndexedVerticesInstanced(instanceCount: Int, start: Int = 0, count: Int = -1): Void {
if (count < 0)
drawAllIndexedVerticesInstanced(instanceCount);
else
drawSomeIndexedVerticesInstanced(instanceCount, start, count);
}
@:functionCode("kinc_g4_draw_indexed_vertices_instanced(instanceCount);")
function drawAllIndexedVerticesInstanced(instanceCount: Int): Void {}
@:functionCode("kinc_g4_draw_indexed_vertices_instanced_from_to(instanceCount, start, count);")
function drawSomeIndexedVerticesInstanced(instanceCount: Int, start: Int, count: Int): Void {}
function renderToTexture(additionalRenderTargets: Array<Canvas>): Void {
if (additionalRenderTargets != null) {
var len = additionalRenderTargets.length;
var image1 = cast(additionalRenderTargets[0], Image);
var image2 = cast(additionalRenderTargets[1], Image);
var image3 = cast(additionalRenderTargets[2], Image);
var image4 = cast(additionalRenderTargets[3], Image);
var image5 = cast(additionalRenderTargets[4], Image);
var image6 = cast(additionalRenderTargets[5], Image);
var image7 = cast(additionalRenderTargets[6], Image);
untyped __cpp__("
kinc_g4_render_target_t *renderTargets[8] = { renderTarget, {1} == null() ? nullptr : &{1}->renderTarget, {2} == null() ? nullptr : &{2}->renderTarget, image3 == null() ? nullptr : &{3}->renderTarget, {4} == null() ? nullptr : &{4}->renderTarget, {5} == null() ? nullptr : &{5}->renderTarget, {6} == null() ? nullptr : &{6}->renderTarget, {7} == null() ? nullptr : &{7}->renderTarget };
kinc_g4_set_render_targets(renderTargets, {0} + 1);
", len, image1, image2, image3, image4, image5, image6, image7);
}
else {
untyped __cpp__("
kinc_g4_render_target_t *renderTargets[1] = { renderTarget };
kinc_g4_set_render_targets(renderTargets, 1)
");
}
}
@:functionCode("kinc_g4_restore_render_target();")
function renderToBackbuffer(): Void {}
public function begin(additionalRenderTargets: Array<Canvas> = null): Void {
if (current == null) {
current = this;
}
else {
throw "End before you begin";
}
var win: Int = window == null ? 0 : window;
if (win != lastWindow) {
if (lastWindow != -1) {
untyped __cpp__("kinc_g4_end(lastWindow);");
}
untyped __cpp__("kinc_g4_begin(win);");
lastWindow = win;
}
if (target == null) {
renderToBackbuffer();
}
else
renderToTexture(additionalRenderTargets);
}
public function beginFace(face: Int): Void {
if (current == null) {
current = this;
}
else {
throw "End before you begin";
}
untyped __cpp__("kinc_g4_set_render_target_face(renderTarget, face)");
}
public function beginEye(eye: Int): Void {}
public function end(): Void {
if (current == this) {
current = null;
}
else {
throw "Begin before you end";
}
}
@:functionCode("kinc_g4_flush();")
public function flush(): Void {}
}

View File

@ -1,2 +0,0 @@
DisableFormat: true
SortIncludes: false

View File

@ -1,650 +0,0 @@
4.3
------------------------------------------------------------
* Bug fixes
* Upgrade to 4.3 API
* Use PCRE v2
4.2
------------------------------------------------------------
* Update MIN_IOS_VERSION
* Bug fixes
* Upgrade to 4.2 API
* Fixed mysql_select_db failing for newer mariadb versions due to extra 0x00 byte after database
* Fixed mysql_close not sending COM_QUIT before closing socket
4.1.15
------------------------------------------------------------
* Added Arm64 suport on windows
* Fixed crash with zero-sized alloc and generational GC
* Fixed crash with generational GC when old objects come back to life
* Fixed compile error with @:fixed Anons and arrays (socket select)
* Fixed lastIndexOf
* Optimized some equality functions
4.1.1
------------------------------------------------------------
* Added functions for haxe 4.1 Api.
* Added HXCPP_DEBUG_LINK_AND_STRIP to preserve symbolic information when creating android release binaries.
* Added optional HXCPP_SIGNAL_THROW to convert memory errors to haxe exceptions without needing additional code
* Added string_hash_map_substr and __hxcpp_parse_substr_float/int to allow some substring processing without extra allocation
4.0.64
------------------------------------------------------------
* Upgrade buildserver to 4.01
* Better generational collection in high fragmentation case
* typeinfo include fix for MSVC
* Fix MySQL connections
* Fix bugs with HXCPP_GC_GENERATIONAL
* Add map.clear
* Better c++11 iOS support
4.0.19
------------------------------------------------------------
* Add Array.keyValueIterator
* General Utf16 string improvements
* Limit the amount of recursion in toString function
* Add float32 support to cppia
* Fix Gc race condition
* Throw exceptions according to the spec when casting
* Introduce hxcpp_smart_strings for unicode text
4.0.4
------------------------------------------------------------
* Compile Cppia against haxe 4.0 preview 4
4.0.2
------------------------------------------------------------
* Default Cppia to 64 bits on windows
4.0.1
------------------------------------------------------------
* More logic for determining the android NDK version
* Updated various opensource libraries (thanks robocoder)
* Updated version of zlib
* Updated version of sljit
* Updated version of pcre
* Updated version of sqlit3
* Updated version of mbedtls
* Some work on supporting utf16 strings (hx_smart_strings)
* Added process_kill
* Change root when calculating haxelib in build.xml files
* Fix cppia super calls across cpp boundary
* Add Array.resize
* Be consistent with mod in cppia
* Fix Sys.stderr
* Add 'embedName' file attribute to allow text to cpp conversion
* Updates for Msvc
* Updates for Xcode
3.4.188
------------------------------------------------------------
* Fix some threading crashes
3.4.185
------------------------------------------------------------
* Do not ship static libraries
* Use more lock-free structures in GC processing
* Added some documentation
* Added HXCPP_GC_SUMMARY option
* Added HXCPP_GC_GENERATIONAL option
* Added HXCPP_GC_DYNAMIC_SIZE option
* Some MSVC 2017 support
* Compile Cppia with JIT as an option by default
3.4.64
------------------------------------------------------------
* Fixed cppia native interface implementation
* Fixed debugger breakpoints
* More compatibility for inet_pton and inet_ntop
* Correct the order of thread housekeeping data
3.4.49
------------------------------------------------------------
* Fixed 2d-Arrays and unserialize
3.4.43
------------------------------------------------------------
* Added more options for code-size optimizations on android (thanks madrazo)
* Added version of stpcpy on android to allow building with platform > 21, and running on older devices
* Added some initial support for ipv6
* Experimental support for Cppia JIT
* Fixed issue with stale objects that use new pch files in cache
* Rethrowing exception now preserves stack correctly
3.4.2
------------------------------------------------------------
* Align float reads from memory for Arm architecture
* Removed some virtual functions not needed by newer versions of haxe
* Reworked the logic for compacting fragmented heaps with HXCPP_GC_MOVING
* Expose StackContext to allow inlining of allocation routine, and combine with Cppia context
* Fix some compare-with-dynamic issues
* Added WatchOs support
* Fixed for android NDK 13
* Fix Array closure equality
* Refactor the Cppia code
* Fix return codes for atomic decrease
* Fix some GC zone issues in the standard library
* Set minimum MacOS deployment target to 10.6
* Do not use typedefs for 'Int' and 'Bool' for newer api levels
* Added dll_link to create output dll
* Improved ObjC support
* Make Cppia order of operations of '+=' et al consistent with other targets
* Added NO_RECURSE flag to PCRE
* Fix bsd_signal undefines on android
* Add create/free abstract
3.3.49
------------------------------------------------------------
* Fix Dynamic != for haxe 3.2.1
* Fix Command line parsing on windows for triple quotes
3.3.45
------------------------------------------------------------
* Much better compile cache support
* Added tags to compiler flags to allow better targeting
* Added UCP support to regexp
* Added Array::fromData
* Added AtomicInt operations
* Added _hx_imod
* More improvements for tvos
* Fix blocking deque issue
* Improved native testing
* Added 'hxcpp run hxcpp cache ...' commands for managing cache
* Added cpp.Variant class for query of field values to avoid boxing
* Added more efficient version of finalizer
* Add non allocating version of __hxcpp_print
* More WinRT fixes
* Output 'HxcppConfig.h' with defines included for easier external integration
* Output list of output files if requested
* Add support functions for StdLib - alloc/free/sizeof
* Fix crash when marking stack names from GCRoots
* Add bitcode support for iOS
* Rename RegisterClass to avoid conflicts with windows
* Added 'VirtualArray' for arrays of unknown types
* Split Macros.tpl
* Added optional ShowParam to process_run
* Added inline functions for Int64 externs
* Add error check for allocating from a finalizer
* Fix null strings on Cffi Prime
* Use slow path if required for Win64 Tls
* Expand logic for detecting android toolchain from NDK name
* Remove the need for hxcpp binaries by compiling source directly into target
* Adjust the default verbosity level, and add HXCPP_VERBOSE/HXCPP_QUIET/HXCPP_SILENT
* Added some control options for copyFile directive
* Fix cppia decrement
* Add Array.removeRange, which does not require a return value
* Do not call setbuf(0) on stdin, since it messes with readLine
* Cppia now throws an error if loading fails
* Allocate EnumParam data inline to cut down on allocations
* Allow anonymous object data to be allocated inline to avoid allocations
* Add SSL library code
* Add NativeGen framework for interfaces
* Add macros to allow neater generated code
* Allow larger memory space with -D HXCPP_GC_BIG_BLOCKS
* Improve Array.join speed
3.2.205
------------------------------------------------------------
* Initial support for HXCPP_OPTIMIZE_FOR_SIZE
* Support HXCPP_DEBUG_LINK on more targets
* Support for cross compiling to windows from linux
* Added array removeAt
* Some telemety fixes (thanks Jeff)
* Check contents when comparing Dynamics with same pointer (Math.Nan!=Math.Nan)
* Numerous WinRT fixes (thanks madrazo)
* Fixed bug causing GC to crash marking constant strings (eg, resources)
* Updated default SDK for Tizen (thanks Joshua)
* Fixed command line args on linux (thanks Andy)
3.2.193
------------------------------------------------------------
* Some improvements for tvos
* Start on some GC defragging code
* Fix android thread access to GC structures
* Add socket socket_recv_from and socket_send_to
* Fixed memory leak in GC collection code
* Allow cross-compile to windows via MINGW
* Fix overflow error that meant GC would work with a too-small buffer in some cases
3.2.180
------------------------------------------------------------
* Initial support for tvos
* Change name of ObjectType to hxObjectType to avoid clashes with iOS
* Try to keep windows.h out of haxe-generated code
* Fix null access bug in array-of-array
* Create separate library for msvc 19
------------------------------------------------------------
* Try to get the pdb server working better for MSVS 2015
* So not export symbols on windows unless HXCPP_DLL_EXPORT is set (-D dll_export) - makes exe smaller
* Avoid dynamic-cast if possible when converting 2D arrays
* Some RPi fixes
* Some CFFI Prime fixes (thanks Joshua)
* Fix build tool for next version of neko
* Improve msvc cl.exe version checking for non-English environments
* Add more control over how much Gc memory is used
* Add faster(inline) thread local storage for Gc on windows.
* Add some Gc load balancing when marking large arrays with multiple threads
* Change the Gc memory layout to be a bit larger, but simpler. This allows most of the allocation to be simplified and inlined.
* Explicitly scan registers for Gc references because the stack scanning was missing them sometimes
* Some additions to Undefine.h for windows
* When static linking using MSVC 2015, compile the libraries directly into the exe to avoid compatibility issues
* Move standard libraries into their own build.xml files
* Make it easier to change the generated output filename
* Allow targets from one build.xml file to be merged into another
* Some more work on HXCPP_COMPILE_CACHE
* Allow automatic grouping of obj files into librarys to avoid linking all the symbols in all obj files
* Add implicit conversion to referenced type from cpp.Reference
* Allow build.xml files to be imported relative to importing file
* Allow '-' in command-line defines
* Fix warnings from Hash class
* Fix setsockopt for Mac
* Support to MSVC2015
* Fix for Blackberry 10.3
* Fix debug break by linenumber
* Better objc integration (thanks Caue)
* Increase number of variables captured in closures to 20
* Initial support for telemetry (thanks Jeff)
* Align allocations for better emscripten support
------------------------------------------------------------
* Fix gc_lock error in remove_dir
* Some cppia bug fixes - enum and resources overrides
* More android atof fixes
* Improved haxelib seek logic
Haxe 3.2.0
------------------------------------------------------------
* Improve testing
* Allow dll_load path to be set programatically and simplified the dll search sequence.
* Improved cffi_prime, and added String class
* Fixed static linking of mysql5
* Moved static link code in general to cpp.link package, not hxcpp package
* URL decode now does not need to performe reallocs
* Ensure HXCPP_API_LEVEL is always defined
* Added __hxcpp_unload_all_libraries to cleanly unload dlls
* Added some utc date functions
* Better support for non-console apps in windows XP 64
* Increased use of HXCPP_DEBUG_LINK for gcc based targets
* Class 'hasField' is now more consistent with other functions/targets
* 'haxelib run hxcpp test.cppia' will run Cppia on the specified file
* Add fast-select option for sockets
* Allow code to run without HXCPP_VISIT_ALLOCS defined
* Fix debugger thread deadlocks
* Allow up to 27 dynamic arguments
* Fixes for Emscripten - byte align access and disable threads
* Allow emscripten to generate 'executables' (.js/.html) and add options for specifying memory
* Allow spaces in exe names again
* Make cpp::Struct compare via memcmp, and mark correctly
* Fix catch block in cppia
* Treat '-debug' as an alias for "-Ddebug"
* Expose ArrayBase for use with some generic or external code
* Clarify the role of 'buffer' in cffi
------------------------------------------------------------
* Only put a minimal run.n in source-control, and use this to boot hxcpp.n
* Added cpp.Struct and cpp.Reference classes, which are handy for extern classes
* Moved Class to hx namespace
* Simplified 'main' logic
* Allow new android compilers to work for old devices (thanks google)
* Correctly read hxcpp_api_level from Build.xml
* Verbose logging prints which file is being compiled
* Handle undefining the INT_ constants differently to allow std::string to still compile
* Remove entries form Options.txt that do not influence the cpp build
* Add optional destination= command-line option to allow copying the result to named file
* Static libraries will be prefixed with 'lib' now
* val_is_buffer always returns false on neko
* Add val_iter_field_vals, which is like val_iter_fields but consistent with neko
* Remove NekoApi binaries
* Add Cppia binaries
* Add Windows64 binaries
* Make compares between Dynamic and numeric types false, unless the Dynamic is actaully numeric
------------------------------------------------------------
* Even more optimizations for hashes
* Some more optimizations for small hashes
* Fix for google changing inlining in platform21 headers (atof, rand, srand)
* Re-tuned Hash for small objects too (improves Anon object perforamce)
* Reverted change that automatically threw 'BadCast'. Now required HXCPP_STRICT_CASTS
------------------------------------------------------------
* Cached dynamic versions of small ints and 1-char-strings for speed
* Added support for weak hashes - needs latest haxe version
* Use internal hash structure for maps - now faster. New version of haxe makes it faster still.
* Changed the way development versions are bootstrapped to avoid committing binaries
* Improved mingw support
* Dont append -debug to dll name
* Reorder xml includes to allow early parts to correctly influence older parts
* Fix busy wait in semaphore lock
* Fixed GC issue when constructing exrernal primitive objects
* Added armv7s and arm64 targets for ios
* Some fixes for neko cffi - wstring and warning for neko_init
* Fix file read (and copy) from thread
------------------------------------------------------------
* Compile fix for blackberry
* Pass on haxe_api_level
* Add -nocolor flag
------------------------------------------------------------
* Add support for prelinker
* Cygwin toolchain fix
* Add HXCPP_NO_COLOUR and HXCPP_NO_M32
* Fix windows trace output
* Add initial support for GCWO compile
* Fix bug with losing GC references in Array.sort
* Fix bug with zombie marking
* Add support for optimised sort routines
* Add support for haxe.ds.Vector optimisation
* Add support for cpp.Pointer, cpp.NativeArray, cpp.NativeString
------------------------------------------------------------
* Add BlackBerry and Tizen binaries
* Fix issues when using names like ANDROID or IPHONE in an enum
* Added more info in verbose mode (setenv HXCPP_VERBOSE)
* Refactor build files to allow greater customisation
* Fix bug with 'lock' where some threads may not get released
* Add optimised arrays access
* Add optimised memory operations for arrays and haxe.io.Bytes
* Avoid blocking in gethostbyname
* Upgrade run tool output and layout
* Restore sys_time for windows
3.1.1
------------------------------------------------------------
* Fixed MSVC support for 64-bit targets (vc11, vc12)
* Initial work on cpp.Pointer (not fully functional)
* Fixed callstack when throwing from native function
3.1.0
------------------------------------------------------------
* VC 2013 support - used as default now
* Add winxp compatibility flags
* Allow cross-compiling from mac to linux
* Added NSString helper conversion
* Better auto-detection for android toolchain
* Allow foreign threads to easily attach and detach from GC system
* Weak references to closures keep object alive
* Added HXCPP_API_LEVEL define to allow for future compatibility
* Fixed clearing finalizers twice
* Int multiply and minus are performed with integers now
* Fix comparing +- infinities
* Use multiple threads in the mark phase of GC
* IOS now defaults cpp11 binary linkage
* Added HXCPP_VERBOSE environment var to enable extra output
* Fixed spin loop in pthread_cond_wait
* Added ability to link several .a files into a single .a file
* Removed dependence on STL runtime for supplied modules
* Renamed some directories to be more standard
* Moved some extra build files into obj directory
* Use sys.io.Process instead of Sys.command to avoid threading slowdown writing to console
* Add hxcpp.Builder to help with building multiple binaries
* Add android x86 support
* Drop pre-compiled support for everything excepth windows,mac,linux,ios and android
* Allow libraries and files to accumulated in the build.xml
* Supply pre-build lib files for static linking on supported platforms
* Support for static linking of all modules
* Support for hxcpp-debugger project
* Binaries have been removed from repo, and are built using a server
* Use build.n script to build all appropriate binaries
* Some initial support for mysql and sqlite databases
* Add free_abstract for safe releasing of data references
* Change process lauching to get better thread usage on mac
* Fix GC error in string resources
* Give obj files in libraries unique names
3.0.2
------------------------------------------------------------
* Fix Dynamic + Int logic
* Reverted linux compiler to older version
* Cast Array at call site if required
* Tweak Array.map return value
3.0.1
------------------------------------------------------------
* Added nekoapi for linux64
* Upgrade nekoapi to v2
* Added haxe vector support
* Added socket_set_fast_send
* Fixed android build
* Expanded native memory access methods
* Fix exception dump
* Added initial Emscriptm support
* Allow specification of ANDROID_HOST
* Inital work on auto-setup of win64
* Support call-site casting of Arrays
3.0.0
------------------------------------------------------------
* Support haxe3 syntax
* Added socket poll function
* Added some initial support for dll_import/dll_export
* Allow full path name when loading dynamic libraries
* Allow dynamic toString function
* Added initial support for Raspberry Pi
* Array sort now uses std::stable_sort
* Fixed Dynamic+null string output
* Fix splice size calculation
* Add object ids for use in maps
* Add map/filter functions to arrays
* GC will now collect more often when big arrays are used
* You can specify a number of args > 5 for cffi functions if you want
* Fix internal hash size variable
* Class static field list does not report super members now
* Fix casting of null to any object
* Do not read input twice in sys_getch
* Link in PCH generated obj data on msvs 2012
* Date is now consistent with UTC
* Hash 'remove' now returns correct value
* CPP native WeakRef now works, and has a 'set' function
* Fixed compile error when assigning to a base class
* Fixed compile error when using != and Dynamic
* Math/floor/ceil/trunc/min/max now pass unit tests
* More control over android sdk installation
* Regexp_match fix
* Fix val_callN CFFI
2.10.3
------------------------------------------------------------
* Added initial build support for WinRT
* Android toolchain improvements
* Minor compile fixes
* Other minor improvements
2.10.2
------------------------------------------------------------
* Fixes for BlackBerry 10 compatibility
* Fixes for iOS 6 compatibility
* CFFI improvements
* Minor Linux improvements
* Minor OS X improvements
2.10.1
------------------------------------------------------------
* Fix trace() output
* Clang options for OS X compiler
* Small fixes
2.10.0
------------------------------------------------------------
* GC upgrades - moving/defragging/releasing
* Built-in profiler
* Build-in debugger
* Fix mac ndll finding bug
* Add Int32 member functions
* Clang options for ios compiler
* Add a few pre-boxed constants
* Some general bug fixes
2.09.3
------------------------------------------------------------
* Fix Xml enum usage
2.09.2
------------------------------------------------------------
* Resolve library paths when launching Mac apps from Finder
* Compile fix for the BlackBerry toolchain
* Fix interface comparison
* Fix api_val_array_value for NekoApi
* Add workaround for optional Strings in interfaces
* Tweak the timing og the GC run
* Remove setProperty conditional compiles
* String charCodeAt only returns positive values
* Fix modulo for negative numbers
* Remove extra space from array output
* Treat '.' and '_' as literals in urlEncode
* Dynamically generated, 0 param, enum instances match the static version
2.09
------------------------------------------------------------
* Improved precision in random implementations
* Added some experimental support for float32
* Added some experimental support for generic getProcAddress
* String::fromCharCode generates single-byte strings
* Fix method compares
* Plug memory leak in finalizers
* Fix debug link flags
* Separate get/SetField from get/setProperty
* Added Null<T> for optional parameters
2.08.3
------------------------------------------------------------
* Actually add blackberry toolchain
2.08.2
------------------------------------------------------------
* Add blackberry support
* Add armv7 options
* Support new xcode layout
* Fix const qualifiers on interface functions
* Fix webOS obj directory
2.08.1
------------------------------------------------------------
* Fix Math.random returning 1.0 sometimes
* Std.is( 2.0, Int ) is now true
* Make static library building more separated - refactor defines to control this
* Do not use @files for linking on mac
* toString on Anon objects will now get called
* Fix fast memory access with --no-inline
* Android tool host now set to linux-x86
* Allow use of __compare as operator== overload
* Add toNativeInt
* Add weak references
* Implement some neko/cffi compatibility operations
* Fix mac deployment using environment variable
* Fix reentrant mutexes
* Do not explicitly specify version of g++
* Speedup some code by avoiding dynamic_cast if possible
* Some fixes to allow Android multi-threading in normal operation
2.08
------------------------------------------------------------
* Do not create a new class definition for each member function
* Allow 5 fast and up to 20 slow dynamic function arguments
* Support utf8 class
* Added "Fast Memory" API similar to flash
* Added support for webOS
* Fix uncompress buffers
* Added file to undefined pesky processor macros
* Setup default config in user area
* Auto-detect msvc and iphone version
* Force compilation for mac 10.5
* Some support for cygwin compilers
* Remove Boehm GC as an option
* Integrate properly now with Android ndk-r6
* Make Int32 pass haxe unit tests (shift/modulo)
* Fix bug in "join"
* Fix bug with marking the "this" pointer in closures
* Fix bug with returning NAN from parseFloat
* Fix linux link flags
* Fix bug where string of length 0 would be null
* Made String cca return value consistent
* Added control over @file syntax
* Removed need for nekoapi.ndll
* Allow for neko.so to end in ".0"
2.07
------------------------------------------------------------
* Added initial support for Mac64, Linux64, MinGW and GPH and refactored build tool.
* Return the count of traced objects
* Fix interface operator ==
* Initial work on msvc10 batch file
* Add bounds check on String.cca
* Build static libraries, if requrested
* Added exe stripping
* Added val_field_name, val_iter_fields
* Fixed nekoapi string length
* Fixed Sys.args
2.06.1
------------------------------------------------------------
* Close files if required in GC
* Added fix for File.write
* Fixed String UTF8 Encode
* Nekoapi is now a "ndll", not a "dso".
* Fix array compile issue on linux
* Fix stack setting on firced collect
2.06.0
------------------------------------------------------------
* Updates to match haxe 2.06 compiler features
* Numerous bug fixes
* Add additional context to GC collection process
* Swapped from wchar_t* to utf8 char*
* Added templated iterators
* Use strftime for Dates
* Fix socket select and "_s" members
* Seed Math.random
* Fixed dynamic integer compare
* Added __hxcpp_obj_id
* Added some Android support
2.05.1
------------------------------------------------------------
* Updated windows nekoapi.dll binary
* Added -m32 compile flags to force 32 bit
2.05.0
------------------------------------------------------------
* Default to IMMIX based internal garbage collection.
* Reorginised files - split big ones, and moved common ones out of "runtime".
* Put internal classes in "hx" namespace, or HX_ prefix for macros.
* Remove multiple-inheritance, and use delegation instead.
* Write "Options.txt" from compiler so dependency can be determined.
* Require -D HXCPP_MULTI_THREADED for multi-threaded classes - to avoid overhead if not required.
* Build thread code into executable for better control.
* Fix return values of parseINt/parseFloat.
* Added comprehensive list of reserved member names.
* Put if/else statements in blocks.
* Added assert, NULL, LITTLE_ENDIAN, BIG_ENDIAN as keywords.
* Added control over how fast-cffi routines are created by requiring cpp.rtti.FastIntergerLookup to be "implemented".
* Construct anonymous object fields in deterministic (as declared) order.
* Fix code generation for some complex inline cases.
* Added cpp.zip.Compress
* Change "Reflect" class to be more standard
* Use array of dynamics for StringBuf.
* Fix setting of attributes in XML nodes.
Build-tool:
* Allow multiple build threads (via setenv HXCPP_COMPILE_THREADS N) for faster building on multi-code boxes.
* Added FileGroup dependencies
* Added pre-compiled headers (windows only, at the moment since gcc seems buggy)
1.0.7
-----------------
Changelog starts.

View File

@ -1,15 +0,0 @@
* Copyright (c) 2008 by the contributors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following condition is met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* See individual source files for additional license information.
*
* THIS SOFTWARE IS PROVIDED BY THE HAXE PROJECT CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED.

View File

@ -1,30 +0,0 @@
# hxcpp
[![Build Status](https://dev.azure.com/HaxeFoundation/GitHubPublic/_apis/build/status/HaxeFoundation.hxcpp?branchName=master)](https://dev.azure.com/HaxeFoundation/GitHubPublic/_build/latest?definitionId=3&branchName=master)
hxcpp is the runtime support for the c++ backend of the [haxe](http://haxe.org/) compiler. This contains the headers, libraries and support code required to generate a fully compiled executable from haxe code.
# building the tools
```
REPO=$(pwd)
cd ${REPO}/tools/run
haxe compile.hxml
cd ${REPO}/tools/hxcpp
haxe compile.hxml
cd $REPO
```
# cppia
You first need to build the cppia host.
```
REPO=$(pwd)
cd ${REPO}/project
haxe compile-cppia.hxml
cd $REPO
```
Then you can do `haxelib run hxcpp file.cppia`.

View File

@ -1,42 +0,0 @@
variables:
- group: variables-haxe
- name: AZURE_PIPELINES_REPO_URL
value: $(Build.Repository.Uri)
- name: AZURE_PIPELINES_BRANCH
value: $(Build.SourceBranchName)
- name: HXCPP_COMPILE_CACHE
value: $(Agent.TempDirectory)/hxcache
stages:
- stage: StageTest
jobs:
- template: tools/azure-pipelines/build.yml
parameters:
name: Linux64
vmImage: ubuntu-20.04
platform: linux64
arch: 64
- template: tools/azure-pipelines/build.yml
parameters:
name: Linux32
vmImage: ubuntu-20.04
platform: linux64
arch: 32
- template: tools/azure-pipelines/build.yml
parameters:
name: Mac
vmImage: macOS-10.15
platform: mac
arch: 64
- template: tools/azure-pipelines/build.yml
parameters:
name: Windows64
vmImage: windows-2019
platform: windows
arch: 64
- template: tools/azure-pipelines/build.yml
parameters:
name: Windows32
vmImage: windows-2019
platform: windows
arch: 32

View File

@ -1,6 +0,0 @@
<xml>
<pragma once="true" />
<include name="toolchain/haxe-target.xml" />
</xml>

View File

@ -1,55 +0,0 @@
The Hxcpp Cache
---------------
The hxcpp compile cache is used to share object files between projects. This can alleviate the need to ship static libraries with external projects, since developers who use the library can compile the library just once, and then reuse it between projects.
The cache uses a hashing mechanism to tell if the contents of a file or its dependencies has changed, and combines this with the compiler version and flags to make specific object files for each change and each compiler congiguration. This also allows some common haxe runtime and haxe generated files to share their object files between projects, even if in different directories.
Additional benefits include keeping some files outside the source tree, and being able to remove these temp files easily.
### Setup
A directory needs to be set aside to enable the cache. If possible, this should be on fast storage, such as a SSD. This is most easily done with an entry in the .hxcpp_config.xml file:
```xml
<set name="HXCPP_COMPILE_CACHE" value="c:/hxcpp/cache" />
<set name="HXCPP_CACHE_MB" value="4000" />
```
Keeping the path short can help in some border-line cases with some compilers where command-line length can become an issue.
The cache size defaults to 1 Gig. For many cases, this is big enough. However, on large projects, with several architectures and lots of debug information, this default can lead to "cache churn" where some files are evicted from the cache, even though they are likely to be used again. Increasing the number of mega-bytes allocated to the cache can help here.
### Using The Cache
To use the cashe with your own libraries, the files group should have 'cache' entry to tell hxcpp that you have considered dependency issues when designing the group.
```xml
<cache value="true" project="name" asLibrary="true" />
```
- project = name of project used to manage and group object files in the cache
- asLibrary = link the objs into a .lib file.
When linking a file group 'asLibrary', the object files are compiled and then the library tool is used to make a library from these object files. This library is then added to the linker. This has a few implications:
- Object files that to not resolve any symbols directly are not added to the final executable
+ Can make final exe size smaller
+ If the object file only contains a handler that is self-registering via static constructor,
then the constructor may not get called, leading to bugs.
- Can help on some systems where the linker command-line length is an issue.
### Management
When compiling normally, hxcpp will check the cache size and evict the least used files to maintain the specified cache size.
Object files in the cache are grouped into "projects" to make management easier, and the hxcpp build tool can be used to explicitly manage the object files.
```
haxelib run hxcpp cache [command] [project]
Perform command on cache, either on specific project or all. commands:
clear -- remove all files from cache
days #days -- remove files older than "days"
resize #megabytes -- Only keep #megabytes MB
list -- list cache usage
details -- list cache usage, per file
```
Start with
```
haxelib run hxcpp cache list
```
To get an idea of cache usage.

View File

@ -1,152 +0,0 @@
Threads And Stacks
-------------------
### Conservative, co-operation
Hxcpp uses conservative stop-the-world GC, where the threads need to co-operate.
- Threads must not change GC pointers in the collection phase
- The thread stacks/registers must be scanned for GC pointers
- Threads must not block without letting the GC system know not to wait for them, otherwise GC blocks until end of block
+ call hx::GCEnterBlocking() / gc_enter_blocking() / (cpp.vm.Gc.enterGCFreeZone() from Haxe) before potentially blocking system call (fs, network, etc)
+ call hx::GCExitBlocking() / gc_exit_blocking() / (cpp.vm.Gc.exitGCFreeZone() from Haxe) before making more GC calls
+ Might need to pre-allocate buffers
+ Don't forget the exit blocking on error condition
### Foreign Threads
When you create a thread from haxe, it starts attached. Before a non-haxe created thread can interact with hxcpp, some care must be taken, since GC allocations are done using a GC context per thread, and all threads must respect the stopped world.
- Foreign threads must be attached-detached
- SetTopOfStack(int * inTop,bool inPush)
- *inTop* = pointer to top of stack to attach, or '0' to remove stack
- *inPush* = usually true. recursive attachment/detachment
- Must not change things when the world is stopped
- Must define their stack range for scanning
- If you are attached, you may need to enter/exit gc free zone
- Must release context when done, if no more calls are going to be made
- Make sure local variables are covered in stack
- compiler may reorder, so be careful
- Read documentation because some things, eg audio callbacks, happen on other threads
- You can use other techniques, eg
- create a haxe thread, which blocks waiting for signal
- foreign thread generates request and signals haxe thread
- haxe thread performs job and generates data then signals foreign thread
- foreign picks up data and carries on
### Top of Stack
- To understand how to handle threads, you need a mental picture of the c++ stack
- The stack usually goes "down". That is, if the first stack location is 10000, the next one will be 9999 etc.
- Historical, but consistent. Except for emscripten which goes up - but still use same terminology/picture, just change the less-thans to greater-thans in code.
Say the system starts each program stack at 10000, the stack might look like this, with local variables and arguments pushed on the stack:
```
10000
-----------------------------------------------
9996 startup temp variable
9992 startup temp variable
-- main function --
9988 main return address - order and details of this are ABI specific
9984 char ** argv
9980 int argc
```
Hxcpp then runs it main code, which starts with the macro HX_TOP_OF_STACK, which expands to something like:
```
int t0 = 99;
hx::SetTopOfStack(&t0,false);
...
__boot_all();
__hxcpp_main();
-- main function --
9988 main return address order and details of this are ABI specific
9984 char ** argv
9980 int argc
9976 int t0
-- hx::SetTopOfStack --
records '9976' as top of stack for this thread
```
Later, many generated functions deep, `__hxcpp_main` generates an allocation call which
triggers a collection
```
...
8100 Array<Bullet> bullets
-- alloc Enemy --
...
-- Call collect --
8050 int bottomOfStackTemp
MarkConservative(&bottomOfStackTemp, 9976) -> scans stack from 8050 -> 9976
MarkConservative(Capture registers)
```
Enter/exit use similar technique, where the registers are captured and the bottomOfStack is 'locked-in' when the "enter gc free zone" call is made.
```
8100 Array<Bullet> bullets
-- EnterGCFreeZone --
8088 int bottomOfStackTemp
thread->setBottomOfStack(&bottomOfStackTemp)
thread->captureRegisters()
return
* any changes here will not affect GC
```
Now, when another thread does a collection, the gc-free thread can be scanned from 8088 to 9976, regardless of any stuff happening lower dowsn the stack.
### Not Called From Main
Top of stack can be tricky to get right when a gui framework does not really have a "main".
```
10000
-----------------------------------------------
9996 startup temp variable
9992 startup temp variable
-- main function --
setupWindows(onReadyCallback)......
...
8000
-- onReadyCallback --
7976 int t0
SetTopOfStack(&t0,false) -> 7966
__hxcpp_main();
setOnFrameCallack(haxeOnFrame)
return;
```
Later, the haxeOnFrame callback is trigger, but not "below" `__hxcpp_main`
```
9800 -- haxeOnFrame ---
// Top of stack will be below bottom of stack.
```
Solutions:
- Make sure you get in at top of main
+ may scan too much?
- Ratchet up top-of-stack in callbacks, inForce = false
+ gc_set_top_of_stack(void * inTopOfStack,bool inForce);
- Detach main thread after hxcpp_main and reattach each callback
+ android solution because render callbacks happen on different threads
+ gc_set_top_of_stack(&base,true); // attach
+ gc_set_top_of_stack(0,true); // detach
### Debugging.
- in debug mode, hxcpp will check for calls from unattached threads
- hxcpp can log conservative ranges. With a native debugger you can check the address of
your local variables and ensure they are included.
- hxcpp will scan native objects on the stack, but will not follow non-haxe pointers to other objects, so additional GC roots may be required.

View File

@ -1,82 +0,0 @@
Compiler
--------
Compilers are run over each of the changed files in each of the filegroups in a target to create object files, which are then linked into the target. Modification dates or hashes are used to tell if files need recompiling, of if the object file can be reused.
- *flag* - Add single arg to command-line.
```xml
<flag value="value" tag="tag" />
```
+ value = text for flag added to command line
+ tag = optional filter to restrict flag to files with matching tag. See [Tags.md](Tags.md).
- *cflag/cppflag/objcflag/mmflag* - Add flag when compiling specific file types.
```xml
<cflag value="value" />
<cppflag value="value" />
<objcflag value="value" />
<mmflag value="value" />
```
+ cflag = only added to .c files
+ cppflag = only added to .cpp files
+ objcflag = only added to .objc files
+ mmflag = only added to .mm objc++ files
- *pchflag* - Add flag when compiling precompiled header .h files.
```xml
<pchflag value="value" />
```
+ pchflag = Usually `["-x", "c++-header"]` for apple to specify the "identity" of the header
- *pch* - Set the precompiled header style - "gcc" or "msvc".
```xml
<pch value="gcc|msvc" />
```
- *objdir* - set name of directory used to store object files. Should be unique for given set of compiler flags to avoid linking against wrong architecture.
```xml
<objdir value="obj/somewhere" />
```
+ value = usually built programmatically, like `obj/msvc${MSVC_VER}-rt${OBJEXT}${OBJCACHE}${XPOBJ}`
- *output* - Flag used to specifying compiler output name.
```xml
<outflag value="-flag" />
```
+ value = flag value. Note that it should contain a space character
if the actual name should be a separate argument, like "-o ", or "-o"/"-out:" if it does not.
- *exe* = Override the executable command specified in the compiler attribute.
```xml
<exe name="command" />
```
+ name = command. Usually you would use 'path' to add the directory, then this is just the filename part.
- *ext* - Specify the object file extension
```xml
<ext name=".obj" />
```
+ name = extension, including ".". Usually ".o" or ".obj".
- *getversion* - The command-line used to create text describing the version of the compiler.
This is used for working out if the compiler has changed, and therefore the objs need recompiling.
```xml
<getversion value="command" />
```
+ value = command to run. It defaults to `compiler --version` which is usual for gcc based compilers.
Setting it empty will disable caching.
- *section* - Group entries - usually sharing common condition
```xml
<section > </section>
```
- *include* - include compiler options from another file. Most compilers should include `<include name="toolchain/common-defines.xml" />` to add defines used by hxcpp.
```xml
<include name="filename" />
```

View File

@ -1,90 +0,0 @@
Defines
-------
There are a number of standard defines you can use to control the hxcpp build. Some of these are used by the haxe compiler, and affect then generated code. Others apply to the build tool and affect how the code is compiled.
Defines affecting how the code is generated. These need to be in the command line when calling haxe.
| Define | Meaning |
|-------------------------|--------------------|
| *HXCPP_DEBUGGER* | Add extra macros required by debugger. Usually added automatically be debugger haxelib |
| *HXCPP_GC_GENERATIONAL* | Enable experimental generational garbage collector |
| *annotate_source* | Add additional annotations to source code - useful for developing hxcpp |
| *dll_export* | Export hxcpp runtime symbols |
| *file_extension* | Set the extension (without the dot) of generated files. eg "-D file_extension=mm" for objc++ code |
| *force_native_property* | Make dynamic access of fields call property getters/setters where appropriate |
| *include_prefix* | Place all generated include files in a sub-directory, eg "-D include_prefix=hxinc". Useful for avoiding name clashes |
| *no-compilation* | Generate the code, but do not compile it |
| *no-debug* | Do not generate debug macros in code |
| *nocppiaast* | Use legacy cppia generation instead of new more recent changes |
| *objc* | Generate objective-c++ classes |
| *scriptable* | Enable extra runtime information required for scripting |
Defines affecting how the code is compiled. These can be on the command line when calling haxe, or added via the hxcpp build environment.
| Define | Meaning |
|-------------------------|--------------------|
| *HXCPP_GC_MOVING* | Allow garbage collector to move memory to reduce fragmentation |
| *HXCPP_GC_SUMMARY* | Print small profiling summary at end of program |
| *HXCPP_GC_DYNAMIC_SIZE* | Monitor GC times and expand memory working space if required |
| *HXCPP_GC_BIG_BLOCKS* | Allow working memory greater than 1 Gig |
| *HXCPP_GC_DEBUG_LEVEL* | Number 1-4 indicating additional debugging in GC |
| *HXCPP_DEBUG_LINK* | Add symbols to final binary, even in release mode. |
| *HXCPP_STACK_TRACE* | Have valid function-level stack traces, even in release mode. |
| *HXCPP_STACK_LINE* | Include line information in stack traces, even in release mode. |
| *HXCPP_CHECK_POINTER* | Add null-pointer checks,even in release mode. |
| *HXCPP_PROFILER* | Add profiler support |
| *HXCPP_TELEMETRY* | Add telemetry support |
| *HXCPP_CPP11* | Use c++11 features and link libraries |
| *exe_link* | Generate executable file (rather than dynamic library on android) |
| *static_link* | Generate static library |
| *dll_link* | Generate dynamic library |
Other defines:
| Define | Meaning |
|-------------------------|--------------------|
| *HXCPP_VERBOSE* | Print extra output from build tool. |
| *HXCPP_TIMES* | Show some basic profiling information |
| *HXCPP_NEKO_BUILDTOOL* | Force use of hxcpp.n, rather than compiled BuildTool.exe
| *HXCPP_NO_COLOR* | Do not add colour-codes to tool output |
| *HXCPP_KEEP_TEMP* | Does not delete the files created for file 'embedName' option |
Defines affecting target architecture.
| Define | Meaning |
|-------------------------|--------------------|
| *HXCPP_M32* | Force 32-bit compile for current desktop |
| *HXCPP_M64* | Force 64-bit compile for current desktop |
| *HXCPP_ARMV6* | Compile arm-based devices for armv6 |
| *HXCPP_ARM64* | Compile arm-based devices for 64 bits |
| *HXCPP_ARMV7* | Compile arm-based devices for armv7 |
| *HXCPP_ARMV7S* | Compile arm-based devices for armv7s |
| *HXCPP_LINUX_ARMV7* | Run on a linux ARMv7 device |
| *HXCPP_LINUX_ARM64* | Run on a linux ARM64 device |
| *winrt* | Compile for windowsRt/windows UWP |
| *android* | Compile for android |
| *PLATFORM* | Specify the android platform for NDK compilation |
| *ANDROID_NDK_ROOT* | Specify the location of the android NDK toolchain |
| *ANDROID_NDK_DIR* | Specify the search location for finding the android NDK toolchain |
| *HXCPP_X86* | Compile android for x86 architecture |
| *iphoneos* | Compile for iphone iOS |
| *iphonesim* | Compile for iphone simulator |
| *appletvos* | Compile for apple tvOS |
| *appletvsim* | Compile for apple tvOS simulator |
| *watchos* | Compile for apple watchOS |
| *watchsimulator* | Compile for apple watchOS simulator |
| *webos* | Compile for webOS |
| *tizen* | Compile for Tizen |
| *blackberry* | Compile for Blackberry |
| *emscripten* | Compile for Emscripten |
| *cygwin* | Compile for windows using cygwin |
| *linux* | (Cross) Compile for linux |
| *rpi* | (Cross) Compile for raspberry pi |
| *mingw* | Compile for windows using mingw |
| *HXCPP_MINGW* | Compile for windows using mingw |
| *NO_AUTO_MSVC* | Do not detect msvc location, use the one already in the executable path |
| *HXCPP_WINXP_COMPAT* | Remain compatible with Windows XP. Disables condition variables. No effect on ARM. |

View File

@ -1,94 +0,0 @@
Files
------
The files node defines a group of files that all share the same attributes, including relative directory, default compiler flags and dependencies. The node can be used to define a set of header files on which other files can depend, or a set of source files to be compiled and included in a target.
- *depend* - Declare that all files in the group depend on another file or another file group.
```xml
<depend name="filename" />
<depend files="filesId" />
```
+ name = If the named file changes then then all the files in the group need recompiling.
+ files = If any of the files in the named group changes then then all the files in the group need recompiling.
- *options* - Name of file containing compiler flags. When the cache is not used, Options.txt helps detect when the options have changed, and therefore whether files need recompiling.
```xml
<options name="Options.txt" />
```
- *config* - Name of file to generate that contains the #defines that were active when code was compiled.
```xml
<config name="outfile.h" />
```
- *tag* - Add a default compiler flags tag to all files in group. See [Tags.md](Tags.md).
```xml
<tag value="tag" />
```
- *addTwice* - When compiled to a library, add the library twice to the link line - once at the beginning and once at then end to satisfy linux selective linking.
```xml
<addTwice value="tue" />
```
- *cache* - Use compiler cache for files in group. See [compile cache](../CompileCache.md) for more details.
```xml
<cache value="true" project="name" asLibrary="true" />
```
+ project = name of project used to manage and group object files in the cache
+ asLibrary = link the objs into a .lib file, which can skip unneeded objs, but
will also skip things that rely on static initializers to register handlers, so be careful.
- *include* - Include an external file list
```xml
<include name="filename.xml" />
```
- *section* - Groups block of elements - usually ones that all respect the same if/unless condition.
```xml
<section name="id" /> </section>
```
- *compilerflag* - Add a compilerflag when compiling files in group.
```xml
<compilerflag name="name" value="value" />
<compilerflag value="value" />
```
+ name, value = add 2 flags when compiling
+ value = add 1 flag when compiling
- *nvcc* - This group is compiled with nvcc.
```xml
<nvcc />
```
- *objprefix* - An id prepended to generated obj name to allow alphabetical grouping of similar objs.
```xml
<objprefix value="prefix" />
```
- *precompiledheader* - Use a precompiledheader of given name when compiling group
```xml
<precompiledheader name="name" dir="directory" />
```
+ name = the include used when precompiling these files (without the .h)
+ directory = the location of this file
eg, for `#include <lib/Header.h>`
+ name = "lib/Header"
+ directory = "${haxelib:somelib}/include"
- *file* - Add file to group, with optional attributes
```xml
<file name="filename" tags="tag,tag1" filterout="define" embedName="embed" >
<depend name="filename1" />
<depend name="filename2" />
</file>
```
+ name = name of file - may be absolute or relative to files.dir
+ tags = optional override of group tags. See [Tags.md](Tags.md).
+ filterout = allows files to be skipped at compile-time if the named define exists.
This is useful when the define is set sometime after the file list is parsed.
+ depend name = filename of additional dependency
+ embed = causes the file to be embedded as an extern c++ 'const char *' string constant of the specified name

View File

@ -1,97 +0,0 @@
The Haxe Target
---------------
When compiling from haxe, via hxcpp, a "Build.xml" file is generated in the output directory. The file lists the generated files and dependencies and ultimately includes the "toolchain/haxe-target.xml" file, which describes how to combine these files.
### Include Order
There are a few complications when setting the order in which things are configured, since a particular build might want to:
- set the compiler
- override some compiler settings
- make decisions based on the compiler or settings
- set or use standard file prefixes/suffixes
### Example Sequence
You can see which files are included by setting the HXCPP_VERBOSE define when compiling. One example is for a hypothetical user 'Hugh' on a windows platform:
```
Using makefile: Build.xml
No specified toolchain
- Parsing include: C:/Users/Hugh/dev/hxcpp/toolchain/setup.xml
- Parsing include: C:\Users\Hugh\.hxcpp_config.xml (section "vars")
Using Windows compiler: MSVC
- Parsing include: C:/Users/Hugh/dev/hxcpp/toolchain/finish-setup.xml
- Parsing makefile: C:\Users\Hugh\test\proj\cpp\Build.xml
- Parsing include: C:/Users/Hugh/dev/hxcpp/build-tool/BuildCommon.xml
- Parsing include: C:/Users/Hugh/dev/hxcpp/toolchain/haxe-target.xml
- Parsing include: C:/Users/Hugh/dev/hxcpp/toolchain/msvc-toolchain.xml
- Parsing compiler: C:/Users/Hugh/dev/hxcpp/toolchain/common-defines.xml
- Parsing include: C:\Users\Hugh\.hxcpp_config.xml (section "exes")
```
- setup.xml is read because no custom toolchain is specified, and this just include hxcpp_config
- the 'vars' section of hxcpp_config is read - mainly to setup SDK locations
- the hxcpp build tool then uses internal logic based on host and defines to work out which compiler/toolchain to use
- finish-setup then sets a bunch of standard defines for file-extensions and linking flags based on
the type of toolchain being used.
- The provided buildfile (Build.xml) is then processed. It can use the standard defines from finish-setup.
- Build.xml imports the standard haxe-target buildfile, which adds standard runtime files
- The toolchain file is then parsed - making use of any settings from the main Build.xml and finish-setup.
- This file includes the "common-defines.xml" from the compiler to inject standard haxe compiler flags
- hxcpp_config "exe" is parsed. Historically to add libraries or build-paths to targets.
### Standard Environment
finish-setup.xml is where the conventions are set. These variables include:
- haxelink = dll|static_link|exe
- LIBPREFIX = lib|""
- LIBEXTRA =
+ .iphonesim-64
+ .iphonesim
+ .iphoneos
+ .iphoneos-v7
+ .iphoneos-v7s
+ .iphoneos-64
+ .appletvsim-64
+ .appletvsim
+ .watchos
+ .watchsimulator
+ -x86
+ -v7
+ -64
- HX_LINK_SUFFIX = LIBEXTRA | -19 (msvc 19)
- LIBEXT = .a|.lib
- DBG = ""|"-debug"
- OBJEXT = "-list-of-config-ids" depending on available options
These variables are used by haxe-target - you can use them too. Haxe then builds the "haxe" target, which uses some code like:
```xml
<set name="HAXE_OUTPUT_FILE" value="${LIBPREFIX}${HAXE_OUTPUT_PART}${DBG}" />
<target id="haxe" tool="linker" toolid="${haxelink}" output="${HAXE_OUTPUT_FILE}">
<ext value="${LIBEXTRA}.a" if="static_link" />
<!-- ... -->
<files id="__main__" unless="static_link" />
<files id="__lib__" if="static_link"/>
<files id="__resources__" />
<files id="__externs__" />
<files id="runtime" unless="dll_import" />
<files id="cppia" if="scriptable" />
<lib name="-lpthread" if="linux" unless="static_link" />
<lib name="-ldl" if="linux" unless="static_link" />
</target>
```
Here you can see the various file groups, which are enabled or not depending on the compiler mode, and some standard libraries that are needed for Linux.
### Experimenting With Hxcpp Generated Code/Build.xml
If you are using external cpp code, or using meta-data to inject xml into the build process, and you are getting a compile or link error, then it can be useful to run the hxcpp build tool without re-running haxe. This lets you hand-edit the build file or generated c++ code until you get things to work. Once you have solved the issues using this technique, then you can move the changes back into the injected/external code.
First, compile haxe with '-v' flag. This gives quite a bit of debug, but will include a line like this:
```
haxelib run hxcpp Build.xml haxe -Dhaxe3="1" -Dhaxe_ver="4.000" -Dhxcpp_api_level="332" -Dsource-header="Generated by Haxe 4.0.0" -I"" -I"C:/Users/Hugh/dev/haxe/std/cpp/_std/" -I"C:/Users/Hugh/dev/haxe/std/"
```
To use this, first change directories to your output directory. This will be the one you specified with the "-cpp" haxe compiler option. Then, cut and paste this command into a shell, cmd or batch file.

View File

@ -1,86 +0,0 @@
Linker
------
Generally one linker is run per target to build a static library, dynamic library or exe. The 'id' attribute of the linker specifies whch type of linking is performed.
- *exe* - Overwrite the exe command for this linker.
```xml
<exe name="command" />
```
- *flag* - Add a single link flag.
```xml
<flag value="flag"/>
```
- *ext* - Default extension for generated files - if not overridden by target.
```xml
<ext value=".ext"/>
```
+ value = extension, including "."
- *outflag* - Flag for specifying linker output name.
```xml
<outflag value="-o"/>
```
+ value = linker flag. Note that it should contain a space character
if the actual name should be a separate argument, like "-o ", or "-o"/"-out:" if it does not.
- *section* - Group items - usually sharing common condition
```xml
<section > </section>
```
- *libdir* - A temp directory name to build into. This will capture the extra files the compiler
generates, and then the desired file will be copied to the correct location.
```xml
<libdir name="name"/>
```
- *lib* - Add a library to the link line.
```xml
<lib (name|hxbase|base)="libName" />
```
+ name = the complete name is specified
+ base = the name without compiler-specific extension (.a/.lib) is specified
+ hxbase = the name without extension and architecture (-v7/.iphoinesim) is specified
- *prefix* - Prefix for generated files.
```xml
<prefix value="lib"/>
```
+ value = prefix. This will usually be "lib" or nothing.
- *ranlib* - Whether ranlib needs to be run, and what command to use. Usually only for unix-style static libraries
```xml
<ranlib name="ranlib command"/>
```
- *libpathflag* - Flag used for adding library paths to command line. It will be combined with *lib* entries.
```xml
<libpathflag value="-L"/>
```
- *recreate* - Whether to delete the target file before re-running link command.
The archive "ar" command likes to add obj files to existing archives, so deleting first can help.
```xml
<recreate value="true"/>
```
- *expandAr* - Whether to extract the individual obj files from an archive and add these, rather than
add the archive as a single library. Can solve some link-order and static-initialization issues,
but may make final exe bigger.
```xml
<expandAr value="true"/>
```
- *fromfile* - If the linker supports taking a list of objs in a file, then this is flag for specifying the file.
```xml
<fromfile value="flag" needsQuotes="true" />
```
+ value = flag for specifying file.
If the filename should be a separate argument, then the flag should end with a space.
Usually `@` or `-filelist `. Use empty to disable.
+ needsQuotes = is whether to quote the obj names in the file

View File

@ -1,79 +0,0 @@
Build.xml
----------
The hxcpp build.xml build system is designed to make compiling, cross-compiling and linking easy on a large variety of operating systems and devices. It was originally designed to build the haxe-generated c++ code but has evolved to replace the need for configuration tools in many open source libraries.
### Running
The source code for the tool lives in "tools/hxcpp" in this repo. When compiled, it can be run with the haxe 'haxelib' library tool. This is usually done automatically by the haxe compiler after the cpp code has been generated. It can be done manually like:
```
haxelib run hxcpp build.xml key=value .... [target]
```
### Configuration
The hxcpp build tool is configured using key-value pairs, or just using keys, known internally as 'defines'. These can be set in several ways:
- From system environment variables
- From the command-line, with key=value
- From haxe. Keys defined in haxe with '-D key[=value]' are passed to the build too, where they can influence the build. Certain defines need to be set on the haxe command line so that they can influence the generated code.
- From the the .hxcpp_config.xml file in the users home(profile) directory. This is a good place to set values the apply to the whole machine, like the location of SDKs etc.
- The defines can be manipulated logically from within the build files themselves.
See [Defines.md](Defines.md) for a list of standard defines.
### Format
The compiler specification and target lists all use the same format.
- uses xml parser
- mostly declarative list of files and flags
- order is important
+ overriding values is a valid technique
+ "commands" are run as they are parsed (eg, 'echo')
- conditions via "if" and "unless" node attributes
- substitution via '${VAR}' syntax
- need to define 'default' target
### Conditions/Substitution
Most of the xml nodes support 'if' and 'unless' attributes. These will enable or disable the whole node according the existence or non-existence of a define. These can be combined with a space for "and" or two pipes for "or".
Substitution is supported via the dollars-brace syntax, and does simple text substitution. In addition, there are a few dynamic variables that can be used:
- "${VAR}" - normal replacement
- "${removeQuotes:VAR}" - strips surrounding quotes from VAR, it any
- "${dospath:VAR}" - converts VAR to backwards-slash path
- "${dir:PathWithFilename}" - just the directory part of filename
- "${this_dir}" - the location of the containing build.xml file
### Example
The following code is saved in [example.xml](example.xml) in this directory
```xml
<xml>
<echo value="Hello ${WHO}" if="WHO" unless="SILENT" />
<echo value="You are in ${haxelib:hxcpp}" unless="WHO||SILENT"/>
<error value="Silent and who both specified" if="WHO SILENT"/>
<target id="default" />
</xml>
```
and some example uses:
```
unsetenv SILENT
haxelib run hxcpp example.xml
haxelib run hxcpp example.xml WHO=world default
setenv SILENT 1
haxelib run hxcpp example.xml
haxelib run hxcpp example.xml WHO=world
```
### Details
The build.xml file contains configuration, targets, compilers, linkers and files. The details can be found in this directory.
- [Top Level](TopLevel.md)
- [Files](Files.md)
- [Targets](Targets.md)
- [Compiler](Compiler.md)
- [Linker](Linker.md)
- [Stripper](Stripper.md)
When building from haxe, the "haxe" target is built. You can see the details in [HaxeTarget](HaxeTarget.md).
You can extend the generated Build.xml from haxe code using [Xml injection](XmlInjection.md).

View File

@ -1,15 +0,0 @@
Stripper
--------
A stripper is used to remove debug information in release builds on gcc-like systems. It may contain entries:
- *exe* - Override stripper command
```xml
<exe name="command"/>
```
- *flag* - Add flag to stripper command
```xml
<flag value="flag"/>
```

View File

@ -1,31 +0,0 @@
Tags
----
Tags are identifiers that link compiler flags with specific files. Usually, they are defined in a files group with the 'tags' attribute as a comma separated list, and with the 'tag' attribute on a compiler 'flag' node. Files are then compiled with all the flags that have matching tags.
By restricting tags to certain files, only a sub-set of files needs to be recompiled when conditions change, and files without the relevant tags can reuse their object files. This can save a lot of time, since some flags only apply to a few files.
Files can override the group tags by specifying their own 'tags' attribute. Groups can add tags with the 'tag' node.
Some tags have standard meanings when compiling haxe code:
- *haxe* - The haxe tag adds all the required compiler flags to get haxe-generated code to compile correctly, and should be added to files that depend directly or indirectly on hxcpp.h.
- *static* - This will add the STATIC_LINK define when appropriate, which is used for generating cffi glue. It should be added to cffi code that might generate static libraries.
- *gc* - These flags only affect the garbage-collection files
- *hxstring* - These flags only affect String.cpp
- *optimization tags* - each file is assumed to have exactly 1 optimization tags. If none is explicitly specified, then the default is used depending on whether it is a debug or release build. They are:
+ optim-std = alias for 'debug' or 'release' depending on build
+ debug
+ release
+ optim-none
+ optim-size
Setting one of these tags is useful for compiling your library in release mode, even if haxe has -debug. Some very big files are slow to compile in release mode, so using a less optimized mode can be faster.
The tags attribute can be added to a haxe-generated file using the `@:fileXml` meta, eg:
```haxe
@:fileXml("tags='haxe,optim-none'")
class MyClass { ...
```
Here, the class is compiled with the normal haxe flags, but has the optimizations disabled, which can lead to much faster compiler times in some circumstances.

View File

@ -1,82 +0,0 @@
Targets
-------
Targets are used to produce binaries, or to group other targets. When compiling exes or dynamic libraries, they provide the additional link libraries.
By default, hxcpp will try to compile the 'default' target, so it is easiest to define this one - perhaps by simply adding a dependence on your other targets(s).
The target is defined with a 'toolid' attribute; exe, static_link or dll. This defines which linker is run, but many of the target entries will be the same even if the linker is changed.
Targets can contain the following nodes:
- *subTargetName* - Build another target before building this one.
```xml
<target id="subTargetName" />
```
- *merge* - Combine fields from another target. This is useful if you want a target to function as static library or dll when compiled in its own, but also allow it to be used as a list of object files if another target wants to link in the object files directly.
```xml
<merge id="otherTargetName" />
```
- *files* - Add a named group of compiled files to target.
```xml
<files id="filesId"/>
```
- *section* - Group items - usually sharing common condition
```xml
<section > </section>
```
- *lib* - Add a library to the link line.
```xml
<lib (name|hxbase|base)="libName" />
```
+ name = the complete name is specified
+ base = the name without compiler-specific extension (.a/.lib) is specified
+ hxbase = the name without extension and architecture (-v7/.iphoinesim) is specified
- *flag* - Add a single link flag.
```xml
<flag value="flag"/>
```
- *vflag* - Add a pair of link flags.
```xml
<vflag name="flag1" value="flag2"/>
```
- *depend* - Target depends on given filename.
```xml
<depend name="filename"/>
```
- *dir* - Add a directory to the targets directory list. These directories will get removed then the target is cleaned.
```xml
<dir name="tempPath"/>
```
- *outdir* - Directory for build results - including "copyFile" targets
```xml
<outdir name="path"/>
```
- *ext* - Extension for generated files.
```xml
<ext name=".ext"/>
```
+ ext = extension - should contain "."
- *builddir* - The directory from which the targets build commands are run, and therefore the
relative base for some filenames, and destination for some compiler generated temps.
```xml
<builddir name="path"/>
```
- *libpath* Add library search path to build command
```xml
<libpath name="directory"/>
```
+ name = directory. The particular linker will add the required flags

View File

@ -1,139 +0,0 @@
Structure of the top-level
---------------------------
The top-level nodes live inside an "xml" node, and can be:
- *set* - Set a "define", define being a general variable.
```xml
<set name="name" value="1" />
```
- *setenv* - Sets an hxcpp define and an environment variable for child processes.
```xml
<setenv name="name" value="1" />
```
- *unset* - Unset a define. if="name" will no longer be true
```xml
<unset name="name" />
```
- *setup* - Used internally to call custom setup code to find SDKs etc.
```xml
<setup name="androidNdk|blackberry|msvc|pdbserver|mingw|emscripten|nvcc" />
```
- *echo* - Print value to console. Good for debugging.
```xml
<echo value="text" />
```
- *error* - Print value to console and force error. Good for checking prerequisites.
```xml
<error value="error message" />
```
- *pleaseUpdateHxcppTool* - Used to tell people updating git version that they need to recompile the build tool.
```xml
<pleaseUpdateHxcppTool version="1" />
```
- *path* - Add an directory to the exe search path.
```xml
<path name="directory_to_add" />
```
- *mkdir* - Create a directory.
```xml
<mkdir name="directory" />
```
- *section* - Groups block of elements - usually ones that all respect the same if/unless condition.
```xml
<section name="id" /> </section>
```
- *copy* - Copy file when node is parsed.
```xml
<copy to="destination" from="src" />
```
- *import*/*include* - Read xml from another file. 'import' resets the relative base to the new file, include does not.
```xml
<import name="filename" section="filter" noerror="true" />
<include name="filename" section="filter" noerror="true" />
```
+ noerror - setting the optional noerror allows the file to be missing
+ section - setting the optional section will only read the named section from the xml file. Used by hxcpp_config.xml.
- *pragma* - Only include build file once, even with multiple include statements.
```xml
<pragma once="true" />
```
- *nvccflag* - Add flag to all nvcc compiles.
```xml
<nvccflag name="?name" value="-IincludePath" />
```
- *nvcclinkflag* - Add flag when linking with nvcc code.
```xml
<nvcclinkflag name="?name" value="-arch=sm_30" />
```
- *files* - Define a file group, and set default tags.
```xml
<files dir="dir" name="name" tags="tag1,tag2,tag3" >
...
</files>
```
+ dir = directory to which the filenames in the group are relative
+ tags = comma separated list of flags tags
- *target* - Define a target, and set its toolid(link mode) and output name.
```xml
<target name="name" overwrite="true" append="true" tool="linker" toolid="${haxelink}" output="filename" >
...
</target>
```
- *copyFile* - Copy a file after given toolId is run into target output directory
```xml
<copyFile name="destination" from="src" allowMissing="true" overwrite="true" toolId="filter" >
```
- *magiclib* - Internal for replacing dlls with object files
```xml
<magiclib name="libname" replace="old dll" />
```
- *compiler* - Define a compiler.
```xml
<compiler id="id" exe="command" replace="true" >
...
</compiler>
```
+ Use optional 'replace' to overwrite, otherwise append
+ It is assumed only 1 compiler is active
+ exe can be overridden in the body of the definition
- *stripper* - Define a stripper, to remove debug information for release from gcc executables
```xml
<stripper exe="command" replace="true" > </stripper>
```
+ Use optional 'replace' to overwrite, otherwise append
- *linker* - Define a linker.
```xml
<linker id="id" exe="command" replace="true" > </linker>
```
+ Use optional 'replace' to overwrite, otherwise append
+ id could be 'static_link', 'dll' or 'exe'. Usually all 3 linkers are defined.
+ exe can be overridden in the body of the definition
- *prelinker* - Define a prelinker.
```xml
<prelinker name="id" replace="true" />
...
</prelinker>
```

View File

@ -1,23 +0,0 @@
Xml Injection
-------------
When using external code in hxcpp, it is often useful to add libraries, include paths or compiler flags to the build process. This can be done with the `@:buildXml` class meta-data. eg,
```haxe
@:buildXml("
<target id='haxe'>
<lib name='${haxelib:nme}/lib/${BINDIR}/libnme${LIBEXTRA}${LIBEXT}'/>
</target>
")
@:keep
class StaticNme
{
...
```
So, by referencing a given class (you just 'import' the class, no need to use it because it has the @:keep meta-data), the xml fragment is also included.
Here, the xml fragment is copied verbatim into the generated Build.xml immediately after the standard file lists. This example adds a library to the haxe target, but you could also add flags to files nodes, or files to another files node or target. Another possibility is to add an include command to pull in a whole external xml file. This can help avoid some syntax awkwardness needed when quoting strings in meta-data, and allows a normal xml editor to be used.
It is also possible to replace the `__main__` file group to skip the standard initialization code and use a custom bootstrap procedure.

View File

@ -1,6 +0,0 @@
<xml>
<echo value="Hello ${WHO}" if="WHO" unless="SILENT" />
<echo value="You are in ${haxelib:hxcpp}" unless="WHO||SILENT"/>
<error value="Silent and who both specified" if="WHO SILENT"/>
<target id="default" />
</xml>

View File

@ -1,14 +0,0 @@
{
"name": "hxcpp",
"url": "https://github.com/HaxeFoundation/hxcpp/",
"license": "BSD",
"tags": ["haxe", "hxcpp", "cpp"],
"description": "Hxcpp is the runtime support for the C++ backend of the Haxe compiler. This contains the headers, libraries and support code required to generate a fully compiled executable from Haxe code.",
"version": "4.3.0",
"releasenote": "See Changes.md",
"contributors": ["gamehaxe", "HaxeFoundation"],
"binaryversion": 48,
"dependencies": {
}
}

View File

@ -1,5 +0,0 @@
<project name="hxcpp" url="http://gamehaxe.com/" license="BSD">
<user name="gamehaxe"/>
<description>Hxcpp is the runtime support for the c++ backend of the haxe compiler. This release constains the headers, libraries and support code required to generate a fully compiled executable from haxe code.</description>
<version name="3.1.0">See Changes.txt</version>
</project>

Some files were not shown because too many files have changed in this diff Show More