28 Commits

Author SHA1 Message Date
Kolyah35
a45c01d013 server compilable 2026-03-26 03:55:28 +03:00
Kolyah35
cbd81b47ce ADD: EpikIzCool to credits 2026-03-24 17:32:52 +03:00
Kolyah35
c146791845 Merge pull request 'Fix Whool and block variations n slabs n stuff' (#13) from EpikIzCool/minecraft-pe-0.6.1:main into main
Reviewed-on: https://192.168.0.2:3000/Kolyah35/minecraft-pe-0.6.1/pulls/13
2026-03-24 16:31:46 +02:00
EpikIzCool
a7c75d2ad2 Touch thingie 2026-03-24 00:29:52 +02:00
EpikIzCool
468ae4a211 Whool Fix part 1 2026-03-24 00:24:16 +02:00
mschiller890
9405e8daad FIXED: Scrolling with mouse wheel improved 2026-03-22 18:38:14 +01:00
mschiller890
bef09a3305 FIXED: sprinting now works when flying 2026-03-22 14:51:22 +01:00
Kolyah35
82f827af29 Merge remote-tracking branch 'refs/remotes/origin/main' 2026-03-22 02:12:46 +03:00
Kolyah35
4f8b18b735 FIX: Now we're using useTouchsceen() right way!!!! 2026-03-22 02:12:04 +03:00
InviseDivine
2acb57d051 revert all sht 2026-03-21 19:19:07 +02:00
InviseDivine
5251085752 i broke all 2026-03-21 19:09:11 +02:00
InviseDivine
a16f76f2b6 idk??? 2026-03-21 19:05:00 +02:00
InviseDivine
b088f39e52 emm 2026-03-21 18:54:51 +02:00
InviseDivine
13c624e07e hmmmmmmmmmm 2026-03-21 18:54:04 +02:00
InviseDivine
2bfa8f11f1 hmm 2026-03-21 18:39:08 +02:00
InviseDivine
98a05e5aa3 FIX: Keyboard on android 2026-03-21 18:25:42 +02:00
InviseDivine
3f6d9cdcb8 FIX: Armor display 2026-03-21 18:10:46 +02:00
InviseDivine
39186069cf Merge branch 'main' of https://gitea.sffempire.ru/Kolyah35/minecraft-pe-0.6.1 2026-03-21 16:22:50 +02:00
InviseDivine
b94c16b22a FIX: Bow release 2026-03-21 16:22:50 +02:00
Kolyah35
91ce365a26 Merge remote-tracking branch 'refs/remotes/origin/main' 2026-03-21 17:20:18 +03:00
Kolyah35
f114536463 FIX: improve web port 2026-03-21 17:19:46 +03:00
InviseDivine
6e0615c0bc FEAT: Auto jump in settings (again) 2026-03-21 16:03:51 +02:00
InviseDivine
fd3ee23e4e Merge branch 'main' of https://gitea.sffempire.ru/Kolyah35/minecraft-pe-0.6.1 2026-03-21 15:44:06 +02:00
InviseDivine
e9766ed2a1 FEAT: Option button in PauseScreen 2026-03-21 15:44:05 +02:00
Kolyah35
298451c290 USE_LIBPNG when compile web 2026-03-21 15:28:50 +03:00
Kolyah35
668fc9d16f oh i forgot data 2026-03-21 15:25:18 +03:00
Kolyah35
5717aeab24 ADD: Web action 2026-03-21 15:23:37 +03:00
Kolyah35
9af1496b9d FIX: windows CI build 2026-03-21 15:04:50 +03:00
119 changed files with 4064 additions and 8651 deletions

View File

@@ -18,7 +18,7 @@ permissions:
jobs:
build-windows:
name: Windows Build
name: Build Windows
runs-on: ubuntu-22.04
steps:
@@ -68,13 +68,12 @@ jobs:
name: mcpe-windows
path: |
${{github.workspace}}/build/MinecraftPE.exe
${{github.workspace}}/build/glfw3.dll
${{github.workspace}}/build/libpng16.dll
${{github.workspace}}/build/OpenAL32.dll
${{github.workspace}}/build/z.dll
${{github.workspace}}/build/libz.dll
build-linux:
name: Linux Build
name: Build Linux
runs-on: ubuntu-latest
steps:
@@ -120,7 +119,7 @@ jobs:
${{github.workspace}}/build/MinecraftPE-server
build-android: # pray to god
name: Build Android APK (${{ matrix.abi }})
name: Build Android (${{ matrix.abi }})
runs-on: ubuntu-latest
strategy:
@@ -215,10 +214,59 @@ jobs:
name: minecraftpe-apk-${{ matrix.abi }}
path: ${{ github.workspace }}/build-apk/minecraftpe-*-debug.apk
build-web:
name: Build Web
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup caches
uses: ./.github/actions/setup-cache
with:
host: linux
target: linux
- name: Setup Ninja
uses: ./.github/actions/setup-ninja
with:
host: linux
- name: Setup emsdk
uses: mymindstorm/setup-emsdk@v14
with:
version: 5.0.3
actions-cache-folder: 'emsdk-cache'
- name: Create Build Environment
# Some projects don't allow in-source building, so create a separate build directory
# We'll use this as our working directory for all subsequent commands
run: cmake -E make_directory ${{github.workspace}}/build
- name: Configure CMake
# Use a bash shell so we can use the same syntax for environment variable
# access regardless of the host operating system
shell: bash
working-directory: ${{github.workspace}}/build
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -G Ninja -DCMAKE_TOOLCHAIN_FILE="$GITHUB_WORKSPACE/emsdk-cache/emsdk-main/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake"
- name: Build
working-directory: ${{github.workspace}}/build
run: cmake --build . --config $BUILD_TYPE --target MinecraftPE --parallel
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: mcpe-web
path: |
${{github.workspace}}/build/MinecraftPE.js
${{github.workspace}}/build/MinecraftPE.wasm
${{github.workspace}}/build/MinecraftPE.data
publish:
name: Publish
runs-on: ubuntu-latest
needs: [ build-windows, build-linux, build-android ]
needs: [ build-windows, build-linux, build-android, build-web ]
if: github.ref == 'refs/heads/main'
steps:
- name: Checkout
@@ -236,13 +284,13 @@ jobs:
- name: Zip Windows Artifacts
uses: vimtor/action-zip@v1.2
with:
files: data mcpe-windows/MinecraftPE.exe mcpe-windows/glfw3.dll mcpe-windows/libpng16.dll mcpe-windows/OpenAL32.dll mcpe-windows/z.dll
files: mcpe-windows/MinecraftPE.exe mcpe-windows/libpng16.dll mcpe-windows/OpenAL32.dll mcpe-windows/libz.dll
dest: minecraftpe-${{ steps.ref.outputs.hash }}-windows.zip
- name: Zip Linux Artifacts
uses: vimtor/action-zip@v1.2
with:
files: data mcpe-linux/MinecraftPE
files: mcpe-linux/MinecraftPE
dest: minecraftpe-${{ steps.ref.outputs.hash }}-linux.zip
- name: Zip Linux Server Artifacts
@@ -263,6 +311,19 @@ jobs:
files: minecraftpe-apk-armeabi-v7a/minecraftpe-v7a-debug.apk
dest: minecraftpe-${{ steps.ref.outputs.hash }}-android-armeabi-v7a.zip
- name: Zip Web Artifact
uses: vimtor/action-zip@v1.2
with:
files: mcpe-web/MinecraftPE.js mcpe-web/MinecraftPE.wasm mcpe-web/MinecraftPE.data misc/web/index.html
dest: minecraftpe-${{ steps.ref.outputs.hash }}-web.zip
- name: Zip Data
uses: vimtor/action-zip@v1.2
with:
files: data
recursive: false
dest: data.zip
- name: Update Development Release
uses: andelf/nightly-release@main
env:
@@ -273,8 +334,10 @@ jobs:
body: |
MinecraftPE development release for commit ${{ github.sha }}.
files: |
./data.zip
./minecraftpe-${{ steps.ref.outputs.hash }}-windows.zip
./minecraftpe-${{ steps.ref.outputs.hash }}-linux.zip
./minecraftpe-server-${{ steps.ref.outputs.hash }}.zip
./minecraftpe-${{ steps.ref.outputs.hash }}-android-arm64-v8a.zip
./minecraftpe-${{ steps.ref.outputs.hash }}-android-armeabi-v7a.zip
./minecraftpe-${{ steps.ref.outputs.hash }}-web.zip

View File

@@ -7,10 +7,6 @@ set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
set(CMAKE_POLICY_VERSION_MINIMUM 3.10)
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
set(CMAKE_CXX_FLAGS "-Wno-c++11-narrowing -Wno-narrowing -Wno-invalid-source-encoding -Wno-reserved-user-defined-literal")
endif()
include(cmake/EnumOption.cmake)
if(EMSCRIPTEN)
@@ -26,6 +22,14 @@ find_package(OpenSSL)
if (${PLATFORM} STREQUAL "Desktop")
set(PLATFORM_CPP "PLATFORM_DESKTOP")
if (MINGW)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-libstdc++ -static-libgcc")
endif()
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-c++11-narrowing -Wno-narrowing -Wno-invalid-source-encoding -Wno-reserved-user-defined-literal")
endif()
if (WIN32)
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
include_directories(misc/windows)
@@ -35,6 +39,8 @@ if (${PLATFORM} STREQUAL "Desktop")
set(EXTRA_LIBS pthread m)
endif()
include_directories("glad/include")
elseif (${PLATFORM} STREQUAL "Web")
set(PLATFORM_CPP "PLATFORM_WEB")
set(EXTRA_LIBS "idbfs.js")
@@ -52,6 +58,7 @@ if(${PLATFORM} MATCHES "Web")
add_library(png INTERFACE IMPORTED)
set_target_properties(png PROPERTIES
INTERFACE_COMPILE_OPTIONS "-sUSE_LIBPNG=1"
INTERFACE_LINK_OPTIONS "-sUSE_LIBPNG=1"
)
@@ -102,39 +109,45 @@ CPMAddPackage(
"ALSOFT_UTILS OFF"
"LIBTYPE ${AL_LIBTYPE}"
"ALSOFT_ENABLE_MODULES OFF"
"ALSOFT_STATIC_STDCXX ON"
"ALSOFT_STATIC_LIBGCC ON"
)
# TODO: Clear this paths with *
file(GLOB SERVER_SOURCES
"project/lib_projects/raknet/jni/RaknetSources/*.cpp"
"src/NinecraftApp.cpp"
"src/Performance.cpp"
"src/SharedConstants.cpp"
"src/Minecraft.cpp"
"src/MinecraftServer.cpp"
"src/App.cpp"
"src/IPlatform.cpp"
"src/client/IConfigListener.cpp"
"src/client/Minecraft.cpp"
"src/client/OptionStrings.cpp"
"src/client/Option.cpp"
"src/client/Options.cpp"
"src/client/OptionsFile.cpp"
"src/client/ServerProfiler.cpp"
"src/client/gamemode/CreativeMode.cpp"
"src/client/gamemode/GameMode.cpp"
"src/client/gamemode/SurvivalMode.cpp"
# "src/client/IConfigListener.cpp"
# "src/client/Minecraft.cpp"
# "src/client/OptionStrings.cpp"
# "src/client/Option.cpp"
# "src/client/Options.cpp"
# "src/client/OptionsFile.cpp"
# "src/client/ServerProfiler.cpp"
"src/client/player/LocalPlayer.cpp"
"src/client/player/RemotePlayer.cpp"
"src/client/player/input/KeyboardInput.cpp"
# "src/client/gamemode/CreativeMode.cpp"
# "src/client/gamemode/GameMode.cpp"
# "src/client/gamemode/SurvivalMode.cpp"
# "src/client/player/LocalPlayer.cpp"
# "src/client/player/RemotePlayer.cpp"
# "src/client/player/input/KeyboardInput.cpp"
"src/gamemode/*.cpp"
"src/locale/I18n.cpp"
"src/main.cpp"
"src/main_dedicated.cpp"
"src/nbt/Tag.cpp"
"src/network/ClientSideNetworkHandler.cpp"
"src/network/NetEventCallback.cpp"
"src/network/Packet.cpp"
"src/network/RakNetInstance.cpp"
@@ -145,11 +158,7 @@ file(GLOB SERVER_SOURCES
"src/platform/HttpClient.cpp"
"src/platform/PngLoader.cpp"
"src/platform/time.cpp"
"src/platform/input/Controller.cpp"
"src/platform/input/Keyboard.cpp"
"src/platform/input/Mouse.cpp"
"src/platform/input/Multitouch.cpp"
"src/platform/server/PlatformServer.cpp"
"src/server/ArgumentsSettings.cpp"
"src/server/ServerLevel.cpp"
@@ -321,11 +330,11 @@ target_include_directories(${PROJECT_NAME} PUBLIC
if(${PLATFORM} MATCHES "Web")
set(CMAKE_CXX_STANDARD 11)
# uuuh i hate it
set(EM_FLAGS "-pthread -sUSE_PTHREADS=1 -sSHARED_MEMORY=1")
set(EM_FLAGS "-pthread -sUSE_PTHREADS=1 -sUSE_LIBPNG=1 -sSHARED_MEMORY=1")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EM_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EM_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${EM_FLAGS} --preload-file ${CMAKE_SOURCE_DIR}/data@/data -sPROXY_TO_PTHREAD")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${EM_FLAGS} --preload-file ${CMAKE_SOURCE_DIR}/data@/data")
target_compile_options(${PROJECT_NAME} PUBLIC
"-Os"
@@ -362,7 +371,7 @@ if(${PLATFORM} MATCHES "Web")
endif()
# Client
target_compile_definitions(${PROJECT_NAME} PUBLIC "OPENGL_ES" "NO_EGL" ${PLATFORM})
target_compile_definitions(${PROJECT_NAME} PUBLIC "OPENGL_ES" "NO_EGL" "${PLATFORM_CPP}")
target_link_libraries(${PROJECT_NAME} zlib ${PNG_LIB} OpenAL::OpenAL glfw ${EXTRA_LIBS})
if (OpenSSL_FOUND)

View File

@@ -153,7 +153,7 @@ options.group.tweaks=Tweaks
options.allowSprint=Allow sprint
options.barOnTop=HUD above inventory
options.rpiCursor=Show Raspberry PI cursor
options.autojump=Auto Jump
options.autoJump=Auto Jump
options.thirdperson=Third Person
options.servervisible=Server Visible
options.sensitivity=Sensitivity

View File

@@ -1,143 +1,46 @@
<!doctype html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Emscripten-Generated Code</title>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MCPE 0.6.1</title>
<style>
.emscripten { padding-right: 0; margin-left: auto; margin-right: auto; display: block; }
textarea.emscripten { font-family: monospace; width: 80%; }
div.emscripten { text-align: center; }
div.emscripten_border { border: 1px solid black; }
/* the canvas *must not* have any border or padding, or mouse coords will be wrong */
canvas.emscripten { border: 0px none; background-color: black; }
.spinner {
height: 50px;
width: 50px;
margin: 0px auto;
-webkit-animation: rotation .8s linear infinite;
-moz-animation: rotation .8s linear infinite;
-o-animation: rotation .8s linear infinite;
animation: rotation 0.8s linear infinite;
border-left: 10px solid rgb(0,150,240);
border-right: 10px solid rgb(0,150,240);
border-bottom: 10px solid rgb(0,150,240);
border-top: 10px solid rgb(100,0,200);
border-radius: 100%;
background-color: rgb(200,100,250);
}
@-webkit-keyframes rotation {
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(360deg);}
}
@-moz-keyframes rotation {
from {-moz-transform: rotate(0deg);}
to {-moz-transform: rotate(360deg);}
}
@-o-keyframes rotation {
from {-o-transform: rotate(0deg);}
to {-o-transform: rotate(360deg);}
}
@keyframes rotation {
from {transform: rotate(0deg);}
to {transform: rotate(360deg);}
html, body {
margin: 0;
padding: 0;
height: 100%;
background: black;
overflow: hidden;
}
#canvas {
width: 100vw;
height: 100vh;
display: block;
}
</style>
</head>
<body>
<hr/>
<figure style="overflow:visible;" id="spinner"><div class="spinner"></div><center style="margin-top:0.5em"><strong>emscripten</strong></center></figure>
<div class="emscripten" id="status">Downloading...</div>
<div class="emscripten">
<progress value="0" max="100" id="progress" hidden=1></progress>
</div>
<div class="emscripten_border">
<canvas class="emscripten" id="canvas" oncontextmenu="event.preventDefault()" tabindex=-1></canvas>
</div>
<hr/>
<div class="emscripten">
<input type="checkbox" id="resize">Resize canvas
<input type="checkbox" id="pointerLock" checked>Lock/hide mouse pointer
&nbsp;&nbsp;&nbsp;
<input type="button" value="Fullscreen" onclick="Module.requestFullscreen(document.getElementById('pointerLock').checked,
document.getElementById('resize').checked)">
</div>
</head>
<body>
<hr/>
<textarea class="emscripten" id="output" rows="8"></textarea>
<hr>
<script type='text/javascript'>
var statusElement = document.getElementById('status');
var progressElement = document.getElementById('progress');
var spinnerElement = document.getElementById('spinner');
var canvasElement = document.getElementById('canvas');
var outputElement = document.getElementById('output');
if (outputElement) outputElement.value = ''; // clear browser cache
// As a default initial behavior, pop up an alert when webgl context is lost. To make your
// application robust, you may want to override this behavior before shipping!
// See http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2
canvasElement.addEventListener("webglcontextlost", (e) => {
alert('WebGL context lost. You will need to reload the page.');
e.preventDefault();
}, false);
function setStatus(text) {
if (!setStatus.last) setStatus.last = { time: Date.now(), text: '' };
if (text === setStatus.last.text) return;
var m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/);
var now = Date.now();
if (m && now - setStatus.last.time < 30) return; // if this is a progress update, skip it if too soon
setStatus.last.time = now;
setStatus.last.text = text;
if (m) {
text = m[1];
progressElement.value = parseInt(m[2])*100;
progressElement.max = parseInt(m[4])*100;
progressElement.hidden = false;
spinnerElement.hidden = false;
} else {
progressElement.value = null;
progressElement.max = null;
progressElement.hidden = true;
if (!text) spinnerElement.hidden = true;
}
statusElement.innerHTML = text;
}
<canvas id="canvas"></canvas>
<script>
var Module = {
print(...args) {
// These replacements are necessary if you render to raw HTML
//text = text.replace(/&/g, "&amp;");
//text = text.replace(/</g, "&lt;");
//text = text.replace(/>/g, "&gt;");
//text = text.replace('\n', '<br>', 'g');
console.log(...args);
if (outputElement) {
var text = args.join(' ');
outputElement.value += text + "\n";
outputElement.scrollTop = outputElement.scrollHeight; // focus on bottom
canvas: document.getElementById('canvas'),
onRuntimeInitialized: function () { resizeCanvas() }
};
function resizeCanvas() {
const canvas = Module.canvas;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
},
canvas: canvasElement,
setStatus: setStatus,
totalDependencies: 0,
monitorRunDependencies(left) {
this.totalDependencies = Math.max(this.totalDependencies, left);
setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.');
}
};
setStatus('Downloading...');
window.onerror = () => {
setStatus('Exception thrown, see JavaScript console');
spinnerElement.style.display = 'none';
setStatus = (text) => {
if (text) console.error('[post-exception status] ' + text);
};
};
</script>
<script src="MinecraftPE.js"></script>
</body>
window.addEventListener('resize', resizeCanvas);
window.addEventListener('onunload', () => {
FS.syncfs(true, function (err) { console.log('Sync FS failed: ' + err) });
})
</script>
<script src="MinecraftPE.js"></script>
</body>
</html>

26
src/App.cpp Normal file
View File

@@ -0,0 +1,26 @@
#include "App.h"
#include "IPlatform.h"
#include "platform/server/PlatformServer.h"
#include "platform/glfw/PlatformGlfw.h"
std::unique_ptr<IPlatform> App::CreatePlatform() {
#if defined(STANDALONE_SERVER)
return std::make_unique<PlatformServer>();
#elif defined(PLATFORM_DESKTOP)
return std::make_unique<PlatformGlfw>();
#else
static_assert(false, "Unsupported platform!");
#endif
}
void App::run() {
init();
m_platform->runMainLoop(*this);
}
void App::swapBuffers() {
m_platform->swapBuffers();
}

View File

@@ -1,6 +1,6 @@
#ifndef APP_H__
#define APP_H__
#pragma once
#include <memory>
#ifdef __APPLE__
#define NO_EGL
#endif
@@ -8,47 +8,36 @@
#define NO_EGL
#endif
#include "AppPlatform.h"
#include <IPlatform.h>
#ifndef NO_EGL
#include <EGL/egl.h>
#endif
#include "platform/log.h"
typedef struct AppContext {
#ifndef NO_EGL
EGLDisplay display;
EGLContext context;
EGLSurface surface;
#endif
AppPlatform* platform;
bool doRender;
} AppContext;
class App
{
// typedef struct AppContext {
// #ifndef NO_EGL
// EGLDisplay display;
// EGLContext context;
// EGLSurface surface;
// #endif
// AppPlatform* platform;
// bool doRender;
// } AppContext;
class App {
protected:
std::unique_ptr<IPlatform> m_platform;
public:
App()
: _finished(false),
_inited(false)
{
_context.platform = 0;
}
static std::unique_ptr<IPlatform> CreatePlatform();
App(std::unique_ptr<IPlatform> platform) : m_platform(std::move(platform)), m_finished(false), m_inited(false) {}
App() = delete;
virtual ~App() {}
void init(AppContext& c) {
_context = c;
init();
_inited = true;
}
bool isInited() { return _inited; }
void run();
virtual AppPlatform* platform() { return _context.platform; }
void onGraphicsReset(AppContext& c) {
_context = c;
onGraphicsReset();
}
bool isInited() { return m_inited; }
virtual void audioEngineOn () {}
virtual void audioEngineOff() {}
@@ -58,30 +47,25 @@ public:
virtual void loadState(void* state, int stateSize) {}
virtual bool saveState(void** state, int* stateSize) { return false; }
void swapBuffers() {
#ifndef NO_EGL
if (_context.doRender)
eglSwapBuffers(_context.display, _context.surface);
#endif
}
void swapBuffers();
// {
// #ifndef NO_EGL
// if (_context.doRender)
// eglSwapBuffers(_context.display, _context.surface);
// #endif
// m_platform->swapBuffers();
// }
virtual void draw() {}
virtual void update() {};// = 0;
virtual void setSize(int width, int height) {}
virtual void update() = 0;
virtual void quit() { _finished = true; }
virtual bool wantToQuit() { return _finished; }
virtual void quit() { m_finished = true; }
virtual bool wantToQuit() { return m_finished; }
virtual bool handleBack(bool isDown) { return false; }
protected:
virtual void init() {}
//virtual void onGraphicsLost() = 0;
virtual void onGraphicsReset() = 0;
virtual void init() { m_inited = true;}
private:
bool _inited;
bool _finished;
AppContext _context;
bool m_inited = false;
bool m_finished = false;
};
#endif//APP_H__

View File

@@ -1,10 +0,0 @@
#ifndef _MINECRAFT_APPCONSTANTS_H_
#define _MINECRAFT_APPCONSTANTS_H_
#define APP_VERSION_STRING "Demo"
#define APP_NAME "Minecraft - Pocket Edition " APP_VERSION_STRING
#endif

View File

@@ -1,143 +0,0 @@
#ifndef APPPLATFORM_H__
#define APPPLATFORM_H__
#include <vector>
#include <string>
#include <cstring>
#include "client/renderer/TextureData.h"
typedef std::vector<std::string> StringVector;
/*
typedef struct UserInput
{
static const int STATUS_INVALID = -1;
static const int STATUS_NOTINITED = -2;
static const int STATUS_OK = 1;
static const int STATUS_CANCEL = 0;
UserInput(int id)
: _id(id),
status(STATUS_NOTINITED)
{}
UserInput(int id, int status)
: _id(id),
status(status)
{}
int getId() { return _id; }
int status;
private:
int _id;
} UserInput;
class UserInputStatus {
int _status;
public:
UserInputStatus(int status)
: _status(status)
{}
bool isAnswered() { return _status >= 0; }
bool isOk() { return _status == UserInput::STATUS_OK; }
bool isCancel() { return _status == UserInput::STATUS_CANCEL; }
};
*/
class BinaryBlob {
public:
BinaryBlob()
: data(NULL),
size(-1) {}
BinaryBlob(unsigned char* data, unsigned int size)
: data(data),
size(size) {}
unsigned char* data;
int size;
};
class PlatformStringVars {
public:
static const int DEVICE_BUILD_MODEL = 0;
};
class AppPlatform
{
public:
AppPlatform() : keyboardVisible(false) {}
virtual ~AppPlatform() {}
virtual void saveScreenshot(const std::string& filename, int glWidth, int glHeight) {}
virtual TextureData loadTexture(const std::string& filename_, bool textureFolder) { return TextureData(); }
virtual TextureData loadTextureFromMemory(const unsigned char* data, size_t size) { return TextureData(); }
virtual void playSound(const std::string& fn, float volume, float pitch) {}
virtual void hideCursor(bool hide) {}
virtual void showDialog(int dialogId) {}
virtual void createUserInput() {}
bool is_big_endian(void) {
union {
unsigned int i;
char c[4];
} bint = {0x01020304};
return bint.c[0] == 1;
}
void createUserInput(int dialogId)
{
showDialog(dialogId);
createUserInput();
}
virtual int getUserInputStatus() { return 0; }
virtual StringVector getUserInput() { return StringVector(); }
virtual std::string getDateString(int s) { return ""; }
//virtual void createUserInputScreen(const char* types) {}
virtual void uploadPlatformDependentData(int id, void* data) {}
virtual BinaryBlob readAssetFile(const std::string& filename) { return BinaryBlob(); }
virtual void _tick() {}
virtual int getScreenWidth() { return 854; }
virtual int getScreenHeight() { return 480; }
virtual float getPixelsPerMillimeter() { return 10; }
virtual bool isNetworkEnabled(bool onlyWifiAllowed) { return true; }
virtual bool isPowerVR() {
return false;
}
virtual int getKeyFromKeyCode(int keyCode, int metaState, int deviceId) {return 0;}
#ifdef __APPLE__
virtual bool isSuperFast() = 0;
#endif
virtual void openURL(const std::string& url) {}
virtual void finish() {}
virtual bool supportsTouchscreen() { return false; }
virtual void vibrate(int milliSeconds) {}
virtual std::string getPlatformStringVar(int stringId) {
return "<getPlatformStringVar NotImplemented>";
}
virtual void showKeyboard() {
keyboardVisible = true;
}
virtual void hideKeyboard() {
keyboardVisible = false;
}
virtual bool isKeyboardVisible() {return keyboardVisible;}
protected:
bool keyboardVisible;
};
#endif /*APPPLATFORM_H__*/

View File

@@ -1,12 +0,0 @@
#include "AppPlatform_glfw.h"
float AppPlatform_glfw::getPixelsPerMillimeter() {
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
int width_mm, height_mm;
glfwGetMonitorPhysicalSize(monitor, &width_mm, &height_mm);
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
return (float)mode->width / (float)width_mm;
}

View File

@@ -1,130 +0,0 @@
#ifndef APPPLATFORM_GLFW_H__
#define APPPLATFORM_GLFW_H__
#include "AppPlatform.h"
#include "platform/log.h"
#include "platform/HttpClient.h"
#include "platform/PngLoader.h"
#include "client/renderer/gles.h"
#include "world/level/storage/FolderMethods.h"
#include <png.h>
#include <cmath>
#include <fstream>
#include <sstream>
#include <GLFW/glfw3.h>
#include <ctime>
#include "util/StringUtils.h"
#ifdef _WIN32
#include <windows.h>
#include <shellapi.h>
#endif
static void png_funcReadFile(png_structp pngPtr, png_bytep data, png_size_t length) {
((std::istream*)png_get_io_ptr(pngPtr))->read((char*)data, length);
}
class AppPlatform_glfw: public AppPlatform
{
public:
AppPlatform_glfw()
{
}
BinaryBlob readAssetFile(const std::string& filename) override {
FILE* fp = fopen(("data/" + filename).c_str(), "r");
if (!fp)
return BinaryBlob();
int size = getRemainingFileSize(fp);
BinaryBlob blob;
blob.size = size;
blob.data = new unsigned char[size];
fread(blob.data, 1, size, fp);
fclose(fp);
return blob;
}
void saveScreenshot(const std::string& filename, int glWidth, int glHeight) override {
//@todo
}
__inline unsigned int rgbToBgr(unsigned int p) {
return (p & 0xff00ff00) | ((p >> 16) & 0xff) | ((p << 16) & 0xff0000);
}
TextureData loadTexture(const std::string& filename_, bool textureFolder) override
{
// Support fetching PNG textures via HTTP/HTTPS (for skins, etc)
if (Util::startsWith(filename_, "http://") || Util::startsWith(filename_, "https://")) {
std::vector<unsigned char> body;
if (HttpClient::download(filename_, body) && !body.empty()) {
return loadTextureFromMemory(body.data(), body.size());
}
return TextureData();
}
TextureData out;
std::string filename = textureFolder? "data/images/" + filename_
: filename_;
std::ifstream source(filename.c_str(), std::ios::binary);
if (!source) {
LOGI("Couldn't find file: %s\n", filename.c_str());
return out;
}
std::vector<unsigned char> fileData((std::istreambuf_iterator<char>(source)), std::istreambuf_iterator<char>());
source.close();
if (fileData.empty()) {
LOGI("Couldn't read file: %s\n", filename.c_str());
return out;
}
return loadTextureFromMemory(fileData.data(), fileData.size());
}
TextureData loadTextureFromMemory(const unsigned char* data, size_t size) override {
return loadPngFromMemory(data, size);
}
virtual std::string getDateString(int s) override {
time_t tm = s;
char mbstr[100];
std::strftime(mbstr, sizeof(mbstr), "%F %T", std::localtime(&tm));
return std::string(mbstr);
}
virtual int getScreenWidth() override { return 854; };
virtual int getScreenHeight() override { return 480; };
virtual float getPixelsPerMillimeter() override;
virtual bool supportsTouchscreen() override { return true; }
virtual void hideCursor(bool hide) override {
int isHide = hide ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_HIDDEN;
glfwSetInputMode(window, GLFW_CURSOR, isHide);
}
virtual void openURL(const std::string& url) override {
#ifdef _WIN32
ShellExecuteA(NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL);
#elif __linux__
std::string command = "xdg-open " + url;
system(command.c_str());
#endif
}
GLFWwindow* window;
private:
};
#endif /*APPPLATFORM_GLFW_H__*/

View File

@@ -1,13 +0,0 @@
#ifndef ERRORCODES_H__
#define ERRORCODES_H__
namespace ErrorCodes {
enum Enum {
Unknown,
ContainerRefStillExistsAfterDestruction
};
}
#endif /*ERRORCODES_H__*/

14
src/IPlatform.cpp Normal file
View File

@@ -0,0 +1,14 @@
#include <IPlatform.h>
#include <App.h>
#include <fstream>
void IPlatform::runMainLoop(App& app) {
while(!app.wantToQuit()) app.update();
}
ByteVector IPlatform::readAssetFile(const std::string& path) {
std::ifstream instream(path, std::ios::in | std::ios::binary);
std::vector<uint8_t> data((std::istreambuf_iterator<char>(instream)), std::istreambuf_iterator<char>());
return data;
}

81
src/IPlatform.h Executable file
View File

@@ -0,0 +1,81 @@
#pragma once
#include <vector>
#include <string>
#include "client/renderer/TextureData.h"
#include <cstdint>
typedef std::vector<std::string> StringVector;
typedef std::vector<uint8_t> ByteVector;
class App;
class IPlatform {
public:
IPlatform() : keyboardVisible(false), windowSizeChanged(false), m_targetFrametime(0.f) {}
virtual ~IPlatform() {}
virtual bool init() { return true; }
virtual void swapBuffers() {}
virtual void runMainLoop(App& app);
virtual ByteVector readAssetFile(const std::string& path);
// Mojang functions here
virtual TextureData loadTexture(const std::string& filename_, bool textureFolder) { return TextureData(); }
virtual TextureData loadTextureFromMemory(const unsigned char* data, size_t size) { return TextureData(); }
virtual void playSound(const std::string& fn, float volume, float pitch) {}
virtual void hideCursor(bool hide) {}
virtual std::string getDateString(int s) = 0;
virtual void uploadPlatformDependentData(int id, void* data) {}
// virtual BinaryBlob readAssetFile(const std::string& filename) { return BinaryBlob(); }
virtual void _tick() {}
virtual int getScreenWidth() { return 854; }
virtual int getScreenHeight() { return 480; }
virtual float getPixelsPerMillimeter() { return 10; }
virtual bool isNetworkEnabled(bool onlyWifiAllowed) { return true; }
virtual bool isPowerVR() {
return false;
}
virtual int getKeyFromKeyCode(int keyCode, int metaState, int deviceId) {return 0;}
#ifdef __APPLE__
virtual bool isSuperFast() = 0;
#endif
virtual void openURL(const std::string& url) {}
virtual void finish() {}
virtual bool supportsTouchscreen() { return false; }
virtual void vibrate(int milliSeconds) {}
virtual std::string getPlatformStringVar(int stringId) = 0;
virtual void showKeyboard() { keyboardVisible = true; }
virtual void hideKeyboard() { keyboardVisible = false; }
virtual bool isKeyboardVisible() { return keyboardVisible; }
virtual void setTargetFPS(int fps) { m_targetFrametime = 1.0 / fps; }
bool isWindowSizeChanged() { return windowSizeChanged; }
virtual void setVSync(bool on) { vsync = on; }
protected:
bool keyboardVisible;
bool windowSizeChanged;
bool vsync;
double m_targetFrametime;
};

502
src/Minecraft.cpp Executable file
View File

@@ -0,0 +1,502 @@
#include <Minecraft.h>
#include "gamemode/CreativeMode.h"
#include "gamemode/SurvivalMode.h"
#include "gamemode/CreatorMode.h"
#include "world/entity/player/Player.h"
#include "world/item/Item.h"
#include "world/item/ItemInstance.h"
#include "world/item/crafting/Recipes.h"
#include "world/level/Level.h"
#include "world/level/tile/entity/TileEntity.h"
#include <string>
#include <cstdlib>
#include "client/gui/Screen.h"
#include "world/level/storage/ExternalFileLevelStorageSource.h"
#if defined(APPLE_DEMO_PROMOTION)
#define NO_NETWORK
#endif
#if defined(RPI)
#define CREATORMODE
#endif
#include "network/RakNetInstance.h"
#include "network/ClientSideNetworkHandler.h"
#include "network/ServerSideNetworkHandler.h"
//#include "network/Packet.h"
#include "world/entity/player/Inventory.h"
#include "world/level/tile/Tile.h"
#include "world/level/storage/LevelStorageSource.h"
#include "world/level/storage/LevelStorage.h"
#include "world/level/chunk/ChunkSource.h"
#include "platform/CThread.h"
#include <IPlatform.h>
#include "util/PerfTimer.h"
#include "util/PerfRenderer.h"
#include "world/entity/MobFactory.h"
#include "world/level/MobSpawner.h"
#include "util/Mth.h"
#include "world/entity/MobCategory.h"
#include "server/ServerLevel.h"
#ifdef CREATORMODE
#include "server/CreatorLevel.h"
#endif
#include "network/command/CommandServer.h"
/*static*/
const char* Minecraft::progressMessages[] = {
"Locating server",
"Building terrain",
"Preparing",
"Saving chunks"
};
// int Minecraft::customDebugId = Minecraft::CDI_NONE;
bool Minecraft::_hasInitedStatics = false;
#if defined(_MSC_VER)
#pragma warning( disable : 4355 ) // 'this' pointer in initialization list which is perfectly legal
#endif
// Minecraft::Minecraft() :
// #ifdef __APPLE__
// _isSuperFast(false),
// #endif
// #if defined(NO_NETWORK)
// raknetInstance = new IRakNetInstance();
// #else
// raknetInstance = new RakNetInstance();
// #endif
// #ifndef STANDALONE_SERVER
// soundEngine = new SoundEngine(20.0f);
// soundEngine->init(this, &options);
// #endif
// //setupPieces();
// #if defined(ANDROID) || defined(__APPLE__) || defined(RPI)
// signal(SIGPIPE, SIG_IGN);
// #endif
// externalCacheStoragePath = '.';
// externalCacheStoragePath = '.';
// }
Minecraft::~Minecraft() {
delete netCallback;
delete raknetInstance;
delete gameMode;
if (level != NULL) {
level->saveGame();
if (level->getChunkSource())
level->getChunkSource()->saveAll(true);
delete level->getLevelStorage();
delete level;
level = NULL;
}
//delete player;
delete storageSource;
delete _commandServer;
MobFactory::clearStaticTestMobs();
// Note: Don't tear down statics if we run on Android
// (we might change this in the future)
#ifndef ANDROID
Biome::teardownBiomes();
Item ::teardownItems();
Tile ::teardownTiles();
Material::teardownMaterials();
Recipes ::teardownRecipes();
TileEntity::teardownTileEntities();
#endif
}
// Only called by server
void Minecraft::selectLevel( const std::string& levelId, const std::string& levelName, const LevelSettings& settings ) {
level = (Level*)new ServerLevel(
storageSource->selectLevel(levelId, false),
levelName,
settings,
SharedConstants::GeneratorVersion
);
// note: settings is useless beyond this point, since it's
// either copied to LevelData (or LevelData read from file)
setLevel(level, "Generating level");
setIsCreativeMode(level->getLevelData()->getGameType() == GameType::Creative);
_running = true;
}
void Minecraft::setLevel(Level* level, const std::string& message, Player* forceInsertPlayer) {
LOGI("Seed is %ld\n", level->getSeed());
if (level != NULL) {
level->raknetInstance = raknetInstance;
gameMode->initLevel(level);
this->level = level;
_hasSignaledGeneratingLevelFinished = false;
#ifdef STANDALONE_SERVER
const bool threadedLevelCreation = false;
#else
const bool threadedLevelCreation = true;
#endif
if (threadedLevelCreation) {
// Threaded
// "Lock"
isGeneratingLevel = true;
generateLevelThread = new CThread(Minecraft::prepareLevel_tspawn, this);
} else {
// Non-threaded
generateLevel("Currently not used", level);
}
}
this->lastTickTime = 0;
this->_running = true;
}
void Minecraft::prepareLevel(const std::string& title) {
LOGI("status: 1\n");
progressStageStatusId = 1;
Stopwatch A, B, C, D;
A.start();
Stopwatch L;
// Dont update lights if we load the level (ok, actually just with leveldata version=1.+(?))
if (!level->isNew())
level->setUpdateLights(false);
int Max = CHUNK_CACHE_WIDTH * CHUNK_CACHE_WIDTH;
int pp = 0;
for (int x = 8; x < (CHUNK_CACHE_WIDTH * CHUNK_WIDTH); x += CHUNK_WIDTH) {
for (int z = 8; z < (CHUNK_CACHE_WIDTH * CHUNK_WIDTH); z += CHUNK_WIDTH) {
progressStagePercentage = 100 * pp++ / Max;
//printf("level generation progress %d\n", progressStagePercentage);
B.start();
level->getTile(x, 64, z);
B.stop();
L.start();
if (level->isNew())
while (level->updateLights())
;
L.stop();
}
}
A.stop();
level->setUpdateLights(true);
C.start();
for (int x = 0; x < CHUNK_CACHE_WIDTH; x++)
{
for (int z = 0; z < CHUNK_CACHE_WIDTH; z++)
{
LevelChunk* chunk = level->getChunk(x, z);
if (chunk && !chunk->createdFromSave)
{
chunk->unsaved = false;
chunk->clearUpdateMap();
}
}
}
C.stop();
LOGI("status: 3\n");
progressStageStatusId = 3;
if (level->isNew()) {
level->setInitialSpawn(); // @note: should obviously be called from Level itself
level->saveLevelData();
level->getChunkSource()->saveAll(false);
level->saveGame();
} else {
level->saveLevelData();
level->loadEntities();
}
progressStagePercentage = -1;
progressStageStatusId = 2;
LOGI("status: 2\n");
D.start();
level->prepare();
D.stop();
A.print("Generate level: ");
L.print(" - light: ");
B.print(" - getTl: ");
C.print(" - clear: ");
D.print(" - prepr: ");
progressStageStatusId = 0;
}
void Minecraft::update() {
timer.advanceTime();
raknetInstance->runEvents(netCallback);
TIMER_PUSH("tick");
int toTick = timer.ticks;
timer.ticks = 0;
for (int i = 0; i < toTick; ++i, ++ticks) tick(i, toTick-1);
TIMER_POP_PUSH("updatelights");
{
if (level && !isGeneratingLevel) {
level->updateLights();
}
}
TIMER_POP();
// Restart the server if (our modded) RakNet reports an error
if (level && raknetInstance->isProbablyBroken() && raknetInstance->isServer()) {
restartServer();
}
}
void Minecraft::restartServer() {
if (!level) return;
raknetInstance->resetIsBroken();
hostMultiplayer();
if (netCallback) netCallback->levelGenerated(level);
}
void Minecraft::tick(int nTick, int maxTick) {
if (missTime > 0) missTime--;
TIMER_PUSH("gameMode");
if (level) {
gameMode->tick();
}
TIMER_POP_PUSH("commandServer");
if (level && _commandServer) {
_commandServer->tick();
}
//
// Ongoing level generation in a (perhaps) different thread. When it's
// ready, _levelGenerated() is called once and any threads are deleted.
//
if (isGeneratingLevel) {
return;
} else if (!_hasSignaledGeneratingLevelFinished) {
if (generateLevelThread) {
delete generateLevelThread;
generateLevelThread = NULL;
}
_levelGenerated();
}
//
// Normal game loop, run before or efter level generation
//
if (level != NULL) {
TIMER_POP_PUSH("level");
level->tickEntities();
level->tick();
}
TIMER_POP();
}
bool Minecraft::isOnlineClient() {
return false;
}
bool Minecraft::isOnline() {
return netCallback != NULL;
}
void Minecraft::init()
{
// WHY DO WE NEED THIS ON MODERN PLATFORMS :sob:
// Global initialization goes here
Mth::initMth();
if (raknetInstance != nullptr) {
delete raknetInstance;
}
raknetInstance = new RakNetInstance();
// If we're running Android, only initialize
// the first time class is instanced
#ifdef ANDROID
if (!_hasInitedStatics) {
_hasInitedStatics = true;
#endif
Material::initMaterials();
MobCategory::initMobCategories();
Tile::initTiles();
Item::initItems();
Biome::initBiomes();
TileEntity::initTileEntities();
#ifdef ANDROID
}
#endif
setIsCreativeMode(false); // false means it's Survival Mode
#if !defined(NO_STORAGE)
storageSource = new ExternalFileLevelStorageSource(externalStoragePath, externalCacheStoragePath);
#else
storageSource = new MemoryLevelStorageSource();
#endif
// Server-only featire @todo server class app
hostMultiplayer();
}
//
// Multiplayer
//
void Minecraft::hostMultiplayer(int port) {
// Tear down last instance
raknetInstance->disconnect();
delete netCallback;
netCallback = nullptr;
#if !defined(NO_NETWORK)
netCallback = new ServerSideNetworkHandler(this, raknetInstance);
#endif
}
//
// Level generation
//
/*static*/
void* Minecraft::prepareLevel_tspawn(void *p_param) {
Minecraft* mc = (Minecraft*) p_param;
mc->generateLevel("Currently not used", mc->level);
return 0;
}
void Minecraft::generateLevel( const std::string& message, Level* level ) {
Stopwatch s;
s.start();
prepareLevel(message);
s.stop();
s.print("Level generated: ");
// "Unlock"
isGeneratingLevel = false;
}
void Minecraft::_levelGenerated() {
level->validateSpawn();
if (raknetInstance->isServer())
raknetInstance->announceServer(getServerName());
if (netCallback) {
netCallback->levelGenerated(level);
}
_hasSignaledGeneratingLevelFinished = true;
}
Player* Minecraft::respawnPlayer(int playerId) {
for (unsigned int i = 0; i < level->players.size(); ++i) {
if (level->players[i]->entityId == playerId) {
resetPlayer(level->players[i]);
return level->players[i];
}
}
return NULL;
}
void Minecraft::resetPlayer(Player* player) {
level->validateSpawn();
player->reset();
Pos p;
if(player->hasRespawnPosition()) {
p = player->getRespawnPosition();
}
else {
p = level->getSharedSpawnPos();
}
player->setPos((float)p.x + 0.5f, (float)p.y + 1.0f, (float)p.z + 0.5f);
player->resetPos(true);
if (isCreativeMode())
player->inventory->clearInventoryWithDefault();
}
int Minecraft::getProgressStatusId() {
return progressStageStatusId;
}
const char* Minecraft::getProgressMessage()
{
return progressMessages[progressStageStatusId];
}
bool Minecraft::isLevelGenerated()
{
return level != NULL && !isGeneratingLevel;
}
LevelStorageSource* Minecraft::getLevelSource()
{
return storageSource;
}
void Minecraft::setIsCreativeMode(bool isCreative)
{
#ifdef CREATORMODE
delete gameMode;
gameMode = new CreatorMode(this);
_isCreativeMode = true;
#else
if (!gameMode || isCreative != _isCreativeMode)
{
delete gameMode;
if (isCreative) gameMode = new CreativeMode(*this);
else gameMode = new SurvivalMode(*this);
_isCreativeMode = isCreative;
}
#endif
}
bool Minecraft::isCreativeMode() {
return _isCreativeMode;
}
ICreator* Minecraft::getCreator()
{
#ifdef CREATORMODE
return ((CreatorMode*)gameMode)->getCreator();
#else
return NULL;
#endif
}
void Minecraft::optionUpdated(OptionId option, bool value ) {
if(netCallback != NULL && option == OPTIONS_SERVER_VISIBLE) {
ServerSideNetworkHandler* ss = (ServerSideNetworkHandler*) netCallback;
ss->allowIncomingConnections(value);
}
}
void Minecraft::optionUpdated(OptionId option, float value ) {}
void Minecraft::optionUpdated(OptionId option, int value ) {}

140
src/Minecraft.h Executable file
View File

@@ -0,0 +1,140 @@
#ifndef NET_MINECRAFT_CLIENT__Minecraft_H__
#define NET_MINECRAFT_CLIENT__Minecraft_H__
#include "client/Options.h"
#include "client/Timer.h"
//#include "../network/RakNetInstance.h"
#include "world/phys/HitResult.h"
#include "App.h"
#include <cstddef>
class Level;
class LocalPlayer;
class IInputHolder;
class Mob;
class Player;
class Entity;
class ICreator;
class GameMode;
class CThread;
class LevelStorageSource;
class BuildActionIntention;
class PerfRenderer;
class LevelSettings;
class IRakNetInstance;
class NetEventCallback;
class CommandServer;
struct PingedCompatibleServer;
class Minecraft: public App {
public:
using App::App;
virtual ~Minecraft();
virtual void init();
virtual void update();
virtual void restartServer();
virtual void tick(int nTick, int maxTick);
virtual bool isOnlineClient();
virtual bool isOnline();
virtual void setIsCreativeMode(bool isCreative);
virtual void optionUpdated(OptionId option, bool value);
virtual void optionUpdated(OptionId option, float value);
virtual void optionUpdated(OptionId option, int value);
/**
* @brief Get public name that will be listed in JoinGame menu
*/
virtual std::string getServerName() { return "Unknown"; }
void toggleDimension() {}
bool isCreativeMode();
virtual void selectLevel(const std::string& levelId, const std::string& levelName, const LevelSettings& settings);
virtual void setLevel(Level* level, const std::string& message = "", Player* forceInsertPlayer = NULL);
virtual void onBlockDestroyed(Player* player, int x, int y, int z, int face) {}
void generateLevel( const std::string& message, Level* level );
LevelStorageSource* getLevelSource();
virtual void hostMultiplayer(int port=19132);
Player* respawnPlayer(int playerId);
void respawnPlayer();
void resetPlayer(Player* player);
void doActuallyRespawnPlayer();
void prepareLevel(const std::string& message);
int getProgressStatusId();
const char* getProgressMessage();
ICreator* getCreator();
bool isLevelGenerated();
#ifdef __APPLE__
bool _isSuperFast = false;
bool isSuperFast() { return _isSuperFast; }
#endif
protected:
virtual void _levelGenerated();
private:
static void* prepareLevel_tspawn(void *p_param);
public:
Level* level = nullptr;
CommandServer* _commandServer = nullptr;
GameMode* gameMode = nullptr;
IRakNetInstance* raknetInstance = nullptr;
NetEventCallback* netCallback = nullptr;
int commandPort = 4711;
int lastTime = 0;
int lastTickTime = -1;
int missTime = 0;
int ticks = 0;
CThread* generateLevelThread = nullptr;
// static int customDebugId;
HitResult hitResult;
volatile int progressStagePercentage = 0;
// This field is initialized in main()
// It sets the base path to where worlds can be written (sdcard on android)
std::string externalStoragePath;
std::string externalCacheStoragePath;
protected:
Timer timer{20};
// @note @attn @warn: this is dangerous as fuck!
volatile bool isGeneratingLevel = false;
bool _hasSignaledGeneratingLevelFinished = true;
LevelStorageSource* storageSource;
bool _running;
protected:
volatile int progressStageStatusId = 0;
static const char* progressMessages[];
int _licenseId;
bool _isCreativeMode;
Player* _pendingRemovePlayer; // @attn @todo @fix: remove this shait and fix the respawn behaviour
// from NinecraftApp
bool _verbose = true;
int _lastTickMs = 0;
static bool _hasInitedStatics;
};
#endif /*NET_MINECRAFT_CLIENT__Minecraft_H__*/

1258
src/MinecraftClient.cpp Normal file

File diff suppressed because it is too large Load Diff

142
src/MinecraftClient.h Normal file
View File

@@ -0,0 +1,142 @@
#pragma once
#include "client/gui/Font.h"
#include "client/gui/Screen.h"
#include "client/particle/ParticleEngine.h"
#include "client/player/LocalPlayer.h"
#include "client/renderer/GameRenderer.h"
#include "client/renderer/Textures.h"
#include "client/sound/SoundEngine.h"
#include <Minecraft.h>
#include <client/MouseHandler.h>
#include <client/gui/Gui.h>
#include <client/gui/screens/ScreenChooser.h>
#include <client/PixelCalc.h>
#include <client/renderer/LevelRenderer.h>
class MinecraftClient : public Minecraft {
public:
using Minecraft::Minecraft;
~MinecraftClient();
void init() override;
void update() override;
void setSize(int width, int height);
void reloadOptions();
bool supportNonTouchScreen();
bool useTouchscreen();
void grabMouse();
void releaseMouse();
void setScreen(Screen*);
void leaveGame(bool renameLevel = false);
void setLevel(Level* level, const std::string& message = "", Player* forceInsertPlayer = NULL) override;
void updateStats();
void restartServer() override;
bool handleBack(bool isDown) override;
void onGraphicsReset();
void initGLStates();
void tick(int nTick, int maxTick) override;
void tickInput();
void handleBuildAction(BuildActionIntention* action);
bool isOnlineClient() override;
void pauseGame(bool isBackPaused);
void gameLostFocus();
void respawnPlayer();
void audioEngineOn() override;
void audioEngineOff() override;
void setIsCreativeMode(bool isCreative) override;
void optionUpdated(OptionId option, bool value) override;
void optionUpdated(OptionId option, float value) override;
void optionUpdated(OptionId option, int value) override;
LocalPlayer* getPlayer() { return player; }
Font* getFont() { return font; }
Textures& textures() { return m_textures; }
Options& options() { return m_options;}
Screen* getScreen() { return m_screen; }
Gui& gui() { return m_gui; }
ParticleEngine* getParticleEngine() {return particleEngine; }
int getScreenWidth() { return width; }
int getScreenHeigth() { return height; }
virtual void hostMultiplayer(int port) override;
bool isPowerVR() { return _powerVr; }
bool isKindleFire(int kindleVersion);
bool transformResolution(int* w, int* h);
virtual std::string getServerName() override;
void locateMultiplayer();
void cancelLocateMultiplayer();
bool joinMultiplayer(const PingedCompatibleServer& server);
bool joinMultiplayerFromString(const std::string& server);
void onBlockDestroyed(Player* player, int x, int y, int z, int face) override;
protected:
void _reloadInput();
void _levelGenerated() override;
int width = 1, height = 1;
Font* font = nullptr;
// @warn This is unsafe cuz Gui may call some MinecraftClient method while MinecraftClient is not ready
MouseHandler mouseHandler;
LevelRenderer* levelRenderer = nullptr;
GameRenderer* gameRenderer = nullptr;
ParticleEngine* particleEngine = nullptr;
SoundEngine* soundEngine = nullptr;
PerfRenderer* _perfRenderer = nullptr;
bool mouseGrabbed = false;
PixelCalc pixelCalc;
PixelCalc pixelCalcUi;
Screen* m_screen = nullptr;
bool screenMutex = false;
bool hasScheduledScreen = false;
Screen* scheduledScreen = nullptr;
int m_frames = 0;
volatile bool pause = false;
// @todo make static
LocalPlayer* player = nullptr;
IInputHolder* inputHolder = nullptr;
Mob* cameraTargetPlayer = nullptr;
bool _supportsNonTouchscreen = false;
bool isLookingForMultiplayer = false;
bool _powerVr = false;
Options m_options{*this};
Textures m_textures{m_options, *m_platform};
ScreenChooser screenChooser{*this};
Gui m_gui{*this};
};

15
src/MinecraftServer.cpp Normal file
View File

@@ -0,0 +1,15 @@
#include "MinecraftServer.h"
#include <Minecraft.h>
#include <network/RakNetInstance.h>
void MinecraftServer::hostMultiplayer(int port) {
Minecraft::hostMultiplayer(port);
raknetInstance->host("Server", port, 16);
}
std::string MinecraftServer::getServerName() {
// @todo read server name from config
return "Dedicated server 0.6.1";
}

10
src/MinecraftServer.h Normal file
View File

@@ -0,0 +1,10 @@
#pragma once
#include <Minecraft.h>
class MinecraftServer : public Minecraft {
public:
using Minecraft::Minecraft;
void hostMultiplayer(int port) override;
std::string getServerName() override;
};

View File

@@ -1,428 +0,0 @@
#include "NinecraftApp.h"
//#include <EGL/egl.h>
#ifdef RPI
//#define NO_STORAGE
#endif
#include <errno.h>
#include "platform/input/Mouse.h"
#include "platform/input/Multitouch.h"
#include "world/item/Item.h"
#include "world/level/Level.h"
#include "world/level/biome/Biome.h"
#include "world/level/material/Material.h"
#include "world/entity/MobCategory.h"
//#include "world/level/storage/FolderMethods.h"
#ifndef STANDALONE_SERVER
#include "client/gui/screens/StartMenuScreen.h"
#include "client/gui/screens/UsernameScreen.h"
#endif
#include "client/player/LocalPlayer.h"
#ifndef STANDALONE_SERVER
#include "client/renderer/gles.h"
#include "client/renderer/Chunk.h"
#include "client/renderer/LevelRenderer.h"
#include "client/renderer/Tesselator.h"
#endif
// sorry for raknet dependency, but I'm too lazy to find another getTime method
#include "raknet/GetTime.h"
#include "network/RakNetInstance.h"
#include "network/ClientSideNetworkHandler.h"
#include "client/gui/screens/ProgressScreen.h"
//#include "world/entity/player/Inventory2.h"
#if !defined(DEMO_MODE) && !defined(APPLE_DEMO_PROMOTION) && !defined(NO_STORAGE)
#include "world/level/storage/ExternalFileLevelStorageSource.h"
#else
#include "world/level/storage/MemoryLevelStorageSource.h"
#endif
#ifndef STANDALONE_SERVER
#include "client/renderer/Textures.h"
#include "client/renderer/entity/ItemRenderer.h"
#endif
#include "world/item/crafting/Recipes.h"
#include "world/level/tile/entity/TileEntity.h"
#ifndef STANDALONE_SERVER
#include "client/renderer/EntityTileRenderer.h"
#endif
bool NinecraftApp::_hasInitedStatics = false;
NinecraftApp::NinecraftApp()
: _verbose(true),
_lastTickMs(0),
_frames(0)
{
#if defined(ANDROID) || defined(__APPLE__) || defined(RPI)
signal(SIGPIPE, SIG_IGN);
#endif
}
NinecraftApp::~NinecraftApp()
{
teardown();
}
void NinecraftApp::init()
{
// Global initialization goes here
Mth::initMth();
//#ifdef DEMO_MODE
//writeDemoFile();
//#endif
// If we're running Android, only initialize
// the first time class is instanced
#ifdef ANDROID
if (!_hasInitedStatics) {
_hasInitedStatics = true;
#endif
Material::initMaterials();
MobCategory::initMobCategories();
Tile::initTiles();
Item::initItems();
Biome::initBiomes();
TileEntity::initTileEntities();
#ifdef ANDROID
}
#endif
#ifndef STANDALONE_SERVER
initGLStates();
Tesselator::instance.init();
I18n::loadLanguage(platform(), "en_US");
#endif
if (!externalStoragePath.empty()) {
options.setOptionsFilePath(externalStoragePath);
}
Minecraft::init();
#if !defined(DEMO_MODE) && !defined(APPLE_DEMO_PROMOTION) && !defined(NO_STORAGE)
storageSource = new ExternalFileLevelStorageSource(externalStoragePath, externalCacheStoragePath);
#else
storageSource = new MemoryLevelStorageSource();
#endif
_running = false;
#ifndef STANDALONE_SERVER
LOGI("This: %p\n", this);
screenChooser.setScreen(SCREEN_STARTMENU);
if (options.getBooleanValue(OPTIONS_FIRST_LAUNCH)) {
options.toggle(OPTIONS_FIRST_LAUNCH);
setScreen(new UsernameScreen());
}
#else
hostMultiplayer();
#endif
}
void NinecraftApp::teardown()
{
// Note: Don't tear down statics if we run on Android
// (we might change this in the future)
#ifndef ANDROID
Biome::teardownBiomes();
Item ::teardownItems();
Tile ::teardownTiles();
Material::teardownMaterials();
Recipes ::teardownRecipes();
TileEntity::teardownTileEntities();
#endif
#ifdef WIN32
ItemRenderer::teardown_static();
if (EntityTileRenderer::instance != NULL) {
delete EntityTileRenderer::instance;
EntityTileRenderer::instance = NULL;
}
TileEntityRenderDispatcher::destroy();
#endif
}
void NinecraftApp::update()
{
++_frames;
// Generate Multitouch active pointer list
Multitouch::commit();
#ifndef ANDROID_PUBLISH
//testCreationAndDestruction();
//testJoiningAndDestruction();
#endif /*ANDROID_PUBLISH*/
Minecraft::update();
swapBuffers();
Mouse::reset2();
// Restart the server if (our modded) RakNet reports an error
if (level && raknetInstance->isProbablyBroken() && raknetInstance->isServer()) {
restartServer();
}
#ifndef WIN32
updateStats();
#endif
}
void NinecraftApp::updateStats()
{
#ifndef STANDALONE_SERVER
if (Options::debugGl)
LOGI("--------------------------------------------\n");
//*
int now = getTimeMs();
//int since = now - _lastTickMs;
if (now >= lastTime + 1000)
{
if (player) {
LOGI("%d fps \t%3d chunk updates. (%.2f, %.2f, %.2f)\n",
_frames, Chunk::updates, player->x, player->y, player->z);
Chunk::resetUpdates();
//static int _n = 0;
//if (++_n % 5 == -1) { // @note: -1
// static char filename[256];
// sprintf(filename, "%s/games/com.mojang/img_%.4d.jpg", externalStoragePath.c_str(), _n/5);
// _context.platform->saveScreenshot(filename, width, height);
//}
LOGI("%s", levelRenderer->gatherStats1().c_str());
//printf("Texture swaps (this frame): %d\n", Textures::textureChanges);
} else {
LOGI("%d fps\n", _frames);
}
//const int* pointerIds;
//int pointerCount = Multitouch::getActivePointerIds(&pointerIds);
//if (pointerCount) {
// std::string s = "Pointers (";
// s += (char)(48 + pointerCount);
// s += ": ";
// for (int i = 0; i < pointerCount; ++i) {
// s += (char)(48 + pointerIds[i]);
// s += ", ";
// }
// LOGI("%s\n", s.c_str());
//}
lastTime = now;
_frames = 0;
#ifdef GLDEBUG
while (1) {
int error = glGetError();
if (error == GL_NO_ERROR) break;
LOGI("#################### GL-ERROR: %d\t#####################\n", error);
LOGI("#################### GL-ERROR: %d\t#####################\n", error);
LOGI("#################### GL-ERROR: %d\t#####################\n", error);
}
#endif
}
Textures::textureChanges = 0;
/**/
#endif /* STANDALONE_SERVER */
}
void NinecraftApp::initGLStates()
{
#ifndef STANDALONE_SERVER
//glShadeModel2(GL_SMOOTH);
//glClearDepthf(1.0f);
glEnable2(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glDepthRangef(0, 1);
glEnable2(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0.1f);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable2(GL_TEXTURE_2D);
#ifndef _EMSCRIPTEN_
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
#endif
// Both updates isPowerVR flag in java and returns if the graphics chip is PowerVR SGX or not
_powerVr = platform()->isPowerVR();
#ifdef __APPLE__
_isSuperFast = platform()->isSuperFast();
#endif
//glLineWidth(4);
#endif /* STANDALONE_SERVER */
}
void NinecraftApp::restartServer() {
if (!level) return;
for (int i = level->players.size()-1; i >= 0; --i) {
Player* p = level->players[i];
if (p != player)
level->removeEntity(p);
}
raknetInstance->resetIsBroken();
#ifndef STANDALONE_SERVER
gui.addMessage("This server has restarted!");
#endif
hostMultiplayer();
if (netCallback) netCallback->levelGenerated(level);
}
bool NinecraftApp::handleBack(bool isDown)
{
if (isGeneratingLevel)
{
return true;
}
if (level)
{
if (!isDown)
{
if (screen)
{
if (!screen->handleBackEvent(isDown))
{
if (player->containerMenu) player->closeContainer();
setScreen(NULL);
}
return true;
} else {
pauseGame(true);
}
//leaveGame();
return false;
}
return true;
}
else if (screen)
{
return screen->handleBackEvent(isDown);
}
return false;
}
void NinecraftApp::onGraphicsReset()
{
#ifndef STANDALONE_SERVER
initGLStates();
Tesselator::instance.init();
Minecraft::onGraphicsReset();
#endif
}
#ifndef ANDROID_PUBLISH
static int _state = -1;
static int _stateTicksLeft = 0;
void NinecraftApp::testCreationAndDestruction()
{
if (_state == -1) {
_stateTicksLeft = 100;
_state = 0;
}
if (_state == 0) {
if (--_stateTicksLeft <= 0)
_state = 1;
}
else if (_state == 1) {
getLevelSource()->deleteLevel("perf");
int seed = getEpochTimeS();
LOGI(">seed %d\n", seed);
selectLevel("perf", "perf", LevelSettings(seed, GameType::Creative));
hostMultiplayer();
#ifndef STANDALONE_SERVER
setScreen(new ProgressScreen());
#endif
_state = 2;
_stateTicksLeft = 1000;//25000;//00;
}
else if (_state == 2) {
if (isLevelGenerated()) {
if (--_stateTicksLeft <= 0) {
_state = 3;
}
}
} else if (_state == 3) {
leaveGame();
_state = 1;
}
}
void NinecraftApp::testJoiningAndDestruction()
{
if (_state == -1) {
//LightUpdate sz[2] = { LightUpdate(LightLayer::Block, 0, 0, 0, 1, 1, 1),
// LightUpdate(LightLayer::Sky, 0, 0, 0, 1, 1, 1) };
//LOGI("size of lightupdate: %lu == %d\n", sizeof(LightUpdate), (const char*)&sz[1] - (const char*)&sz[0]);
_stateTicksLeft = 100;
_state = 0;
}
if (_state == 0) {
if (--_stateTicksLeft <= 0) {
raknetInstance->clearServerList();
locateMultiplayer();
_state = 1;
}
}
else if (_state == 1) {
if (!raknetInstance->getServerList().empty()) {
PingedCompatibleServer s = raknetInstance->getServerList().at(0);
if (s.name.GetLength() > 0) {
joinMultiplayer(s);
#ifndef STANDALONE_SERVER
setScreen(new ProgressScreen());
#endif
_state = 2;
_stateTicksLeft = 80;//1000;
}
}
}
else if (_state == 2) {
if (isLevelGenerated()) {
if (--_stateTicksLeft <= 0) {
_state = 3;
}
}
} else if (_state == 3) {
leaveGame();
_stateTicksLeft = 50;
_state = 0;
}
}
#endif /*ANDROID_PUBLISH*/
/*
void NinecraftApp::writeDemoFile() {
std::string path = externalStoragePath + "/games";
if (createFolderIfNotExists(path.c_str())) {
path += "/com.mojang";
if (createFolderIfNotExists(path.c_str())) {
path += "/minecraftpe";
if (createFolderIfNotExists(path.c_str())) {
path += "/played_demo";
FILE* fp = fopen(path.c_str(), "w");
if (fp) fclose(fp);
}}}
}
bool NinecraftApp::hasPlayedDemo() {
std::string filename = externalStoragePath + "/games/com.mojang/minecraftpe/played_demo";
FILE* fp = fopen(filename.c_str(), "r");
if (!fp) return false;
fclose(fp);
return true;
}
*/

View File

@@ -1,52 +0,0 @@
#ifndef NINECRAFTAPP_H__
#define NINECRAFTAPP_H__
#include "world/Pos.h"
#include "App.h"
#include "client/Minecraft.h"
#include "world/level/storage/MemoryLevelStorage.h"
#include <string>
class Level;
class LocalPlayer;
class ExternalFileLevelStorageSource;
class NinecraftApp: public Minecraft
{
public:
NinecraftApp();
~NinecraftApp();
void init();
void teardown();
void update();
virtual bool handleBack(bool isDown);
protected:
void onGraphicsReset();
private:
void initGLStates();
void restartServer();
void updateStats();
//void writeDemoFile();
//bool hasPlayedDemo();
#ifndef ANDROID_PUBLISH
void testCreationAndDestruction();
void testJoiningAndDestruction();
#endif /*ANDROID_PUBLISH*/
bool _verbose;
int _frames;
int _lastTickMs;
static bool _hasInitedStatics;
};
#endif//NINECRAFTAPP_H__

File diff suppressed because it is too large Load Diff

View File

@@ -1,227 +0,0 @@
#ifndef NET_MINECRAFT_CLIENT__Minecraft_H__
#define NET_MINECRAFT_CLIENT__Minecraft_H__
#include "Options.h"
#ifndef STANDALONE_SERVER
#include "MouseHandler.h"
#include "gui/Gui.h"
#include "gui/screens/ScreenChooser.h"
#endif
#include "Timer.h"
//#include "../network/RakNetInstance.h"
#include "../world/phys/HitResult.h"
class Level;
class LocalPlayer;
class IInputHolder;
class Mob;
class Player;
class LevelRenderer;
class GameRenderer;
class ParticleEngine;
class Entity;
class ICreator;
class GameMode;
class Textures;
class CThread;
class SoundEngine;
class Screen;
class Font;
class LevelStorageSource;
class BuildActionIntention;
class PerfRenderer;
class LevelSettings;
class IRakNetInstance;
class NetEventCallback;
class CommandServer;
struct PingedCompatibleServer;
//class ExternalFileLevelStorageSource;
#include "../App.h"
#include "PixelCalc.h"
class AppPlatform;
class AppPlatform_android;
class Minecraft: public App
{
protected:
Minecraft();
public:
virtual ~Minecraft();
void init();
void setSize(int width, int height);
void reloadOptions();
bool supportNonTouchScreen();
bool useTouchscreen();
void grabMouse();
void releaseMouse();
void handleBuildAction(BuildActionIntention*);
void toggleDimension(){}
bool isCreativeMode();
void setIsCreativeMode(bool isCreative);
void setScreen(Screen*);
virtual void selectLevel(const std::string& levelId, const std::string& levelName, const LevelSettings& settings);
virtual void setLevel(Level* level, const std::string& message = "", LocalPlayer* forceInsertPlayer = NULL);
void generateLevel( const std::string& message, Level* level );
LevelStorageSource* getLevelSource();
bool isLookingForMultiplayer;
void locateMultiplayer();
void cancelLocateMultiplayer();
bool joinMultiplayer(const PingedCompatibleServer& server);
bool joinMultiplayerFromString(const std::string& server);
void hostMultiplayer(int port=19132);
Player* respawnPlayer(int playerId);
void respawnPlayer();
void resetPlayer(Player* player);
void doActuallyRespawnPlayer();
void update();
void tick(int nTick, int maxTick);
void tickInput();
bool isOnlineClient();
bool isOnline();
void pauseGame(bool isBackPaused);
void gameLostFocus();
void prepareLevel(const std::string& message);
void leaveGame(bool renameLevel = false);
int getProgressStatusId();
const char* getProgressMessage();
ICreator* getCreator();
// void onGraphicsLost() {}
void onGraphicsReset();
bool isLevelGenerated();
void audioEngineOn();
void audioEngineOff();
bool isPowerVR() { return _powerVr; }
bool isKindleFire(int kindleVersion);
bool transformResolution(int* w, int* h);
void optionUpdated(OptionId option, bool value);
void optionUpdated(OptionId option, float value);
void optionUpdated(OptionId option, int value);
#ifdef __APPLE__
bool _isSuperFast;
bool isSuperFast() { return _isSuperFast; }
#endif
protected:
void _levelGenerated();
private:
static void* prepareLevel_tspawn(void *p_param);
void _reloadInput();
public:
int width;
int height;
// Vars that the platform is allowed to use in the future
int commandPort;
int reserved_d1, reserved_d2;
float reserved_f1, reserved_f2;
Options options;
static bool useAmbientOcclusion;
//static bool threadInterrupt;
volatile bool pause;
LevelRenderer* levelRenderer;
GameRenderer* gameRenderer;
ParticleEngine* particleEngine;
SoundEngine* soundEngine;
GameMode* gameMode;
#ifndef STANDALONE_SERVER
Textures* textures;
ScreenChooser screenChooser;
Font* font;
#endif
IRakNetInstance* raknetInstance;
NetEventCallback* netCallback;
int lastTime;
int lastTickTime;
float ticksSinceLastUpdate;
Level* level;
LocalPlayer* player;
IInputHolder* inputHolder;
Mob* cameraTargetPlayer;
#ifndef STANDALONE_SERVER
Gui gui;
#endif
CThread* generateLevelThread;
Screen* screen;
static int customDebugId;
static const int CDI_NONE = 0;
static const int CDI_GRAPHICS = 1;
#ifndef STANDALONE_SERVER
MouseHandler mouseHandler;
#endif
bool mouseGrabbed;
PixelCalc pixelCalc;
PixelCalc pixelCalcUi;
HitResult hitResult;
volatile int progressStagePercentage;
// This field is initialized in main()
// It sets the base path to where worlds can be written (sdcard on android)
std::string externalStoragePath;
std::string externalCacheStoragePath;
protected:
Timer timer;
// @note @attn @warn: this is dangerous as fuck!
volatile bool isGeneratingLevel;
bool _hasSignaledGeneratingLevelFinished;
LevelStorageSource* storageSource;
bool _running;
bool _powerVr;
private:
volatile int progressStageStatusId;
static const char* progressMessages[];
int missTime;
int ticks;
bool screenMutex;
bool hasScheduledScreen;
Screen* scheduledScreen;
int _licenseId;
bool _supportsNonTouchscreen;
bool _isCreativeMode;
//int _respawnPlayerTicks;
Player* _pendingRemovePlayer; // @attn @todo @fix: remove this shait and fix the respawn behaviour
PerfRenderer* _perfRenderer;
CommandServer* _commandServer;
};
#endif /*NET_MINECRAFT_CLIENT__Minecraft_H__*/

View File

@@ -5,7 +5,7 @@
#include <SDL/SDL.h>
#endif
#ifdef PLATFORM_DESKTOP
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB)
#include <GLFW/glfw3.h>
#endif
@@ -34,7 +34,7 @@ void MouseHandler::grab() {
SDL_ShowCursor(0);
#endif
#ifdef PLATFORM_DESKTOP
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB)
glfwSetInputMode(glfwGetCurrentContext(), GLFW_CURSOR, GLFW_CURSOR_DISABLED);
#endif
}
@@ -46,7 +46,7 @@ void MouseHandler::release() {
SDL_ShowCursor(1);
#endif
#ifdef PLATFORM_DESKTOP
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB)
glfwSetInputMode(glfwGetCurrentContext(), GLFW_CURSOR, GLFW_CURSOR_NORMAL);
#endif
}

View File

@@ -1,11 +1,6 @@
#include "Options.h"
#include "OptionStrings.h"
#include "Minecraft.h"
#include "../platform/log.h"
#include "../world/Difficulty.h"
#include <cmath>
#include <memory>
#include <MinecraftClient.h>
bool Options::debugGl = false;
@@ -290,13 +285,13 @@ void Options::setOptionsFilePath(const std::string& path) {
}
void Options::notifyOptionUpdate(OptionId key, bool value) {
minecraft->optionUpdated(key, value);
minecraft.optionUpdated(key, value);
}
void Options::notifyOptionUpdate(OptionId key, float value) {
minecraft->optionUpdated(key, value);
minecraft.optionUpdated(key, value);
}
void Options::notifyOptionUpdate(OptionId key, int value) {
minecraft->optionUpdated(key, value);
minecraft.optionUpdated(key, value);
}

View File

@@ -15,9 +15,8 @@
//#include "locale/Language.h"
#include <string>
#include <cstdio>
#include "../platform/input/Keyboard.h"
#include "../util/StringUtils.h"
#include <platform/input/Keyboard.h>
#include <util/StringUtils.h>
#include "OptionsFile.h"
#include "Option.h"
#include <array>
@@ -88,7 +87,7 @@ enum OptionId {
OPTIONS_COUNT
};
class Minecraft;
class MinecraftClient;
typedef std::vector<std::string> StringVector;
class Options
@@ -96,7 +95,7 @@ class Options
public:
static bool debugGl;
Options(Minecraft* minecraft, const std::string& workingDirectory = "")
Options(MinecraftClient& minecraft, const std::string& workingDirectory = "")
: minecraft(minecraft) {
// elements werent initialized so i was getting a garbage pointer and a crash
m_options.fill(nullptr);
@@ -161,7 +160,7 @@ private:
std::array<Option*, OPTIONS_COUNT> m_options;
OptionsFile optionsFile;
Minecraft* minecraft;
MinecraftClient& minecraft;
};
#endif /*NET_MINECRAFT_CLIENT__Options_H__*/

View File

@@ -16,6 +16,8 @@ OptionsFile::OptionsFile() {
settingsPath = "./Documents/options.txt";
#elif defined(ANDROID)
settingsPath = "options.txt";
#elif defined(__EMSCRIPTEN__)
settingsPath = "/games/com.mojang/options.txt";
#else
settingsPath = "options.txt";
#endif

View File

@@ -1,69 +0,0 @@
#include "CreativeMode.h"
#include "../Minecraft.h"
#ifndef STANDALONE_SERVER
#include "../particle/ParticleEngine.h"
#endif
#include "../player/LocalPlayer.h"
#ifndef STANDALONE_SERVER
#include "../renderer/LevelRenderer.h"
#include "../sound/SoundEngine.h"
#endif
#include "../../world/level/Level.h"
//#include "../../network/Packet.h"
#include "../../network/packet/RemoveBlockPacket.h"
#include "../../world/entity/player/Abilities.h"
static const int DestructionTickDelay = 5;
CreativeMode::CreativeMode(Minecraft* minecraft)
: super(minecraft)
{
}
void CreativeMode::startDestroyBlock(int x, int y, int z, int face) {
if(minecraft->player->getCarriedItem() != NULL && minecraft->player->getCarriedItem()->id == Item::bow->id)
return;
creativeDestroyBlock(x, y, z, face);
destroyDelay = DestructionTickDelay;
}
void CreativeMode::creativeDestroyBlock(int x, int y, int z, int face) {
minecraft->level->extinguishFire(x, y, z, face);
destroyBlock(x, y, z, face);
}
void CreativeMode::continueDestroyBlock(int x, int y, int z, int face) {
destroyDelay--;
if (destroyDelay <= 0) {
destroyDelay = DestructionTickDelay;
creativeDestroyBlock(x, y, z, face);
}
}
void CreativeMode::stopDestroyBlock() {
destroyDelay = 0;
}
void CreativeMode::initAbilities( Abilities& abilities ) {
abilities.mayfly = true;
abilities.instabuild = true;
abilities.invulnerable = true;
}
bool CreativeMode::isCreativeType() {
return true;
}
void CreativeMode::releaseUsingItem( Player* player ) {
if(player->getCarriedItem() != NULL) {
int oldItemId = player->getCarriedItem()->id;
int oldAux = player->getAuxData();
super::releaseUsingItem(player);
if(player->getCarriedItem() != NULL && player->getCarriedItem()->id == oldItemId) {
player->getCarriedItem()->setAuxValue(oldAux);
}
} else {
super::releaseUsingItem(player);
}
}

View File

@@ -1,98 +0,0 @@
#include "SurvivalMode.h"
#include "../Minecraft.h"
#include "../player/LocalPlayer.h"
#ifndef STANDALONE_SERVER
#include "../particle/ParticleEngine.h"
#include "../sound/SoundEngine.h"
#endif
#include "../../world/level/Level.h"
#include "../../world/entity/player/Abilities.h"
SurvivalMode::SurvivalMode( Minecraft* minecraft )
: super(minecraft),
xDestroyBlock(-1),
yDestroyBlock(-1),
zDestroyBlock(-1)
{
}
void SurvivalMode::continueDestroyBlock( int x, int y, int z, int face ) {
if (destroyDelay > 0) {
destroyDelay--;
return;
}
if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) {
int t = minecraft->level->getTile(x, y, z);
if (t == 0) return;
Tile* tile = Tile::tiles[t];
destroyProgress += tile->getDestroyProgress(minecraft->player);
if ((++destroyTicks & 3) == 1) {
#ifndef STANDALONE_SERVER
if (tile != NULL) {
minecraft->soundEngine->play(tile->soundType->getStepSound(), x + 0.5f, y + 0.5f, z + 0.5f, (tile->soundType->getVolume() + 1) / 8, tile->soundType->getPitch() * 0.5f);
}
#endif
}
if (destroyProgress >= 1) {
destroyBlock(x, y, z, face);
destroyProgress = 0;
oDestroyProgress = 0;
destroyTicks = 0;
destroyDelay = 5;
}
} else {
destroyProgress = 0;
oDestroyProgress = 0;
destroyTicks = 0;
xDestroyBlock = x;
yDestroyBlock = y;
zDestroyBlock = z;
}
}
bool SurvivalMode::destroyBlock( int x, int y, int z, int face ) {
int t = minecraft->level->getTile(x, y, z);
int data = minecraft->level->getData(x, y, z);
bool changed = GameMode::destroyBlock(x, y, z, face);
bool couldDestroy = minecraft->player->canDestroy(Tile::tiles[t]);
ItemInstance* item = minecraft->player->inventory->getSelected();
if (item != NULL) {
item->mineBlock(t, x, y, z);
if (item->count == 0) {
//item->snap(minecraft->player);
minecraft->player->inventory->clearSlot(minecraft->player->inventory->selected);
}
}
if (changed && couldDestroy) {
ItemInstance instance(t, 1, data);
Tile::tiles[t]->playerDestroy(minecraft->level, minecraft->player, x, y, z, data);
}
return changed;
}
void SurvivalMode::stopDestroyBlock() {
destroyProgress = 0;
destroyDelay = 0;
}
void SurvivalMode::initAbilities( Abilities& abilities ) {
abilities.flying = false;
abilities.mayfly = false;
abilities.instabuild = false;
abilities.invulnerable = false;
}
void SurvivalMode::startDestroyBlock( int x, int y, int z, int face ) {
if(minecraft->player->getCarriedItem() != NULL && minecraft->player->getCarriedItem()->id == Item::bow->id)
return;
int t = minecraft->level->getTile(x, y, z);
if (t > 0 && destroyProgress == 0) Tile::tiles[t]->attack(minecraft->level, x, y, z, minecraft->player);
if (t > 0 && Tile::tiles[t]->getDestroyProgress(minecraft->player) >= 1)
destroyBlock(x, y, z, face);
}

View File

@@ -1,11 +1,12 @@
#include "Gui.h"
#include "Font.h"
#include "MinecraftClient.h"
#include "client/Options.h"
#include "platform/input/Keyboard.h"
#include "screens/IngameBlockSelectionScreen.h"
#include "screens/ChatScreen.h"
#include "screens/ConsoleScreen.h"
#include "../Minecraft.h"
#include <Minecraft.h>
#include "../player/LocalPlayer.h"
#include "../renderer/Tesselator.h"
#include "../renderer/TileRenderer.h"
@@ -29,38 +30,23 @@
#include <algorithm>
#include <sstream>
#define MAX_MESSAGE_WIDTH 240
float Gui::InvGuiScale = 1.0f / 3.0f;
float Gui::GuiScale = 1.0f / Gui::InvGuiScale;
const float Gui::DropTicks = 40.0f;
//#include <android/log.h>
Gui::Gui(Minecraft* minecraft)
: minecraft(minecraft),
tickCount(0),
progress(0),
overlayMessageTime(0),
animateOverlayMessageColor(false),
chatScrollOffset(0),
tbr(1),
_inventoryNeedsUpdate(true),
_flashSlotId(-1),
_flashSlotStartTime(-1),
_slotFont(NULL),
_numSlots(4),
_currentDropTicks(-1),
_currentDropSlot(-1),
MAX_MESSAGE_WIDTH(240),
itemNameOverlayTime(2)
{
// @todo virtual controlConfigurationChanged() when player switches from keyboard to touch for example
Gui::Gui(MinecraftClient& minecraft) : minecraft(minecraft), _openInventorySlot(minecraft.useTouchscreen()) {
glGenBuffers2(1, &_inventoryRc.vboId);
glGenBuffers2(1, &rcFeedbackInner.vboId);
glGenBuffers2(1, &rcFeedbackOuter.vboId);
//Gui::InvGuiScale = 1.0f / (int) (3 * Minecraft::width / 854);
}
Gui::~Gui()
{
Gui::~Gui() {
if (_slotFont)
delete _slotFont;
@@ -68,20 +54,16 @@ Gui::~Gui()
}
void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) {
if (!minecraft->level || !minecraft->player)
if (!minecraft.level || !minecraft.getPlayer())
return;
//minecraft->gameRenderer->setupGuiScreen();
Font* font = minecraft->font;
Font* font = minecraft.getFont();
#ifdef PLATFORM_DESKTOP
const bool isTouchInterface = false;
#else
const bool isTouchInterface = minecraft->useTouchscreen();
#endif
const int screenWidth = (int)(minecraft->width * InvGuiScale);
const int screenHeight = (int)(minecraft->height * InvGuiScale);
const bool isTouchInterface = minecraft.useTouchscreen();
const int screenWidth = (int)(minecraft.getScreenWidth() * InvGuiScale);
const int screenHeight = (int)(minecraft.getScreenHeigth() * InvGuiScale);
blitOffset = -90;
renderProgressIndicator(isTouchInterface, screenWidth, screenHeight, a);
@@ -93,9 +75,9 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) {
// F: 3
int ySlot = screenHeight - 16 - 3;
if (!minecraft->options.getBooleanValue(OPTIONS_HIDEGUI)) {
if (minecraft->gameMode->canHurtPlayer()) {
minecraft->textures->loadAndBindTexture("gui/icons.png");
if (!minecraft.options.getBooleanValue(OPTIONS_HIDEGUI)) {
if (minecraft.gameMode->canHurtPlayer()) {
minecraft.getTextures()->loadAndBindTexture("gui/icons.png");
Tesselator& t = Tesselator::instance;
t.beginOverride();
t.colorABGR(0xffffffff);
@@ -105,7 +87,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) {
}
}
if(minecraft->player->getSleepTimer() > 0) {
if(minecraft.getPlayer()->getSleepTimer() > 0) {
glDisable(GL_DEPTH_TEST);
glDisable(GL_ALPHA_TEST);
@@ -114,7 +96,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) {
glEnable(GL_ALPHA_TEST);
glEnable(GL_DEPTH_TEST);
}
if (!minecraft->options.getBooleanValue(OPTIONS_HIDEGUI)) {
if (!minecraft.options.getBooleanValue(OPTIONS_HIDEGUI)) {
renderToolBar(a, ySlot, screenWidth);
glEnable(GL_BLEND);
@@ -206,16 +188,10 @@ void Gui::handleClick(int button, int x, int y) {
if (button != MouseAction::ACTION_LEFT) return;
int slot = getSlotIdAt(x, y);
if (slot != -1)
{
#ifndef PLATFORM_DESKTOP
if (slot == (getNumSlots()-1))
{
if (slot != -1) {
if (_openInventorySlot && slot == (getNumSlots()-1)) {
minecraft->screenChooser.setScreen(SCREEN_BLOCKSELECTION);
}
else
#endif
{
} else {
minecraft->player->inventory->selectSlot(slot);
itemNameOverlayTime = 0;
}
@@ -349,7 +325,7 @@ void Gui::setNowPlaying(const std::string& string) {
void Gui::displayClientMessage(const std::string& messageId) {
//Language language = Language.getInstance();
//std::string languageString = language.getElement(messageId);
addMessage(std::string("Client message: ") + messageId);
addMessage(messageId);
}
void Gui::renderVignette(float br, int w, int h) {
@@ -537,11 +513,7 @@ void Gui::tickItemDrop()
static bool isCurrentlyActive = false;
isCurrentlyActive = false;
int slots = getNumSlots();
#ifndef PLATFORM_DESKTOP
slots--;
#endif
int slots = getNumSlots() - _openInventorySlot;
if (Mouse::isButtonDown(MouseAction::ACTION_LEFT)) {
int slot = getSlotIdAt(Mouse::getX(), Mouse::getY());
@@ -1083,13 +1055,7 @@ void Gui::renderToolBar( float a, int ySlot, const int screenWidth ) {
float x = baseItemX;
int slots = getNumSlots();
// TODO: if using touchscreen
#ifndef PLATFORM_DESKTOP
slots--;
#endif
int slots = getNumSlots() - _openInventorySlot;
for (int i = 0; i < slots; i++) {
renderSlot(i, (int)x, ySlot, a);
@@ -1097,9 +1063,10 @@ void Gui::renderToolBar( float a, int ySlot, const int screenWidth ) {
}
_inventoryNeedsUpdate = false;
#ifndef PLATFORM_DESKTOP
if (_openInventorySlot) {
blit(screenWidth / 2 + 10 * getNumSlots() - 20 + 4, ySlot + 6, 242, 252, 14, 4, 14, 4);
#endif
}
minecraft->textures->loadAndBindTexture("gui/gui_blocks.png");
t.endOverrideAndDraw();

View File

@@ -10,7 +10,7 @@
#include "../../util/Random.h"
#include "../IConfigListener.h"
class Minecraft;
class MinecraftClient;
class ItemInstance;
class Textures;
class Tesselator;
@@ -27,7 +27,7 @@ typedef std::vector<GuiMessage> GuiMessageList;
class Gui: public GuiComponent, IConfigListener
{
public:
Gui(Minecraft* minecraft);
Gui(MinecraftClient& minecraft);
~Gui();
int getSlotIdAt(int x, int y);
@@ -90,43 +90,44 @@ private:
void tickItemDrop();
float cubeSmoothStep(float percentage, float min, float max);
public:
float progress;
float progress = 0.f;
std::string selectedName;
static float InvGuiScale;
static float GuiScale;
private:
int MAX_MESSAGE_WIDTH;
//ItemRenderer itemRenderer;
GuiMessageList guiMessages;
int chatScrollOffset;
int chatScrollOffset = 0;
Random random;
Minecraft* minecraft;
int tickCount;
float itemNameOverlayTime;
MinecraftClient& minecraft;
int tickCount = 0;
float itemNameOverlayTime = 2;
std::string overlayMessageString;
int overlayMessageTime;
bool animateOverlayMessageColor;
int overlayMessageTime = 0;
bool animateOverlayMessageColor = false;
float tbr;
float tbr = 1.f;
RenderChunk _inventoryRc;
bool _inventoryNeedsUpdate;
bool _inventoryNeedsUpdate = true;
int _flashSlotId;
float _flashSlotStartTime;
int _flashSlotId = -1;
float _flashSlotStartTime = -1;
Font* _slotFont;
int _numSlots;
Font* _slotFont = nullptr;
int _numSlots = 4;
RenderChunk rcFeedbackOuter;
RenderChunk rcFeedbackInner;
// For dropping
static const float DropTicks;
float _currentDropTicks;
int _currentDropSlot;
float _currentDropTicks = -1;
int _currentDropSlot = -1;
bool _openInventorySlot;
};
#endif /*NET_MINECRAFT_CLIENT_GUI__Gui_H__*/

View File

@@ -1,7 +1,7 @@
#include "Screen.h"
#include "components/Button.h"
#include "components/TextBox.h"
#include "../Minecraft.h"
#include <Minecraft.h>
#include "../renderer/Tesselator.h"
#include "../sound/SoundEngine.h"
#include "../../platform/input/Keyboard.h"
@@ -177,9 +177,11 @@ void Screen::keyPressed( int eventKey )
textbox->keyPressed(minecraft, eventKey);
}
#ifdef TABBING
if (minecraft->useTouchscreen())
return;
// "Tabbing" the buttons (walking with keys)
const int tabButtonCount = tabButtons.size();
if (!tabButtonCount)
@@ -199,6 +201,7 @@ void Screen::keyPressed( int eventKey )
}
updateTabButtonSelection();
#endif
}
void Screen::charPressed(char inputChar) {
@@ -209,11 +212,13 @@ void Screen::charPressed(char inputChar) {
void Screen::updateTabButtonSelection()
{
#ifdef TABBING
if (minecraft->useTouchscreen())
return;
for (unsigned int i = 0; i < tabButtons.size(); ++i)
tabButtons[i]->selected = (i == tabButtonIndex);
#endif
}
void Screen::mouseClicked( int x, int y, int buttonNum )

View File

@@ -95,7 +95,7 @@ void Button::renderBg( Minecraft* minecraft, int xm, int ym )
}
bool Button::hovered(Minecraft* minecraft, int xm , int ym) {
return minecraft->useTouchscreen()? (_currentlyDown && isInside(xm, ym)) : false;
return minecraft->useTouchscreen()? (_currentlyDown && isInside(xm, ym)) : isInside(xm, ym);
}
bool Button::isInside( int xm, int ym ) {
@@ -143,7 +143,8 @@ TButton::TButton( int id, int x, int y, int w, int h, const std::string& msg )
void TButton::renderBg( Minecraft* minecraft, int xm, int ym )
{
bool hovered = active && (minecraft->useTouchscreen()? (_currentlyDown && xm >= x && ym >= y && xm < x + width && ym < y + height) : false);
bool hovered = active && (minecraft->useTouchscreen()? (_currentlyDown && xm >= x && ym >= y && xm < x + width && ym < y + height) : isInside(xm, ym));
// bool hovered = active && (_currentlyDown && isInside(xm, ym));
minecraft->textures->loadAndBindTexture("gui/touchgui.png");

View File

@@ -42,7 +42,7 @@ void ImageButton::render(Minecraft* minecraft, int xm, int ym) {
//minecraft->textures->loadAndBindTexture("gui/gui.png");
glColor4f2(1, 1, 1, 1);
bool hovered = active && (minecraft->useTouchscreen()? (_currentlyDown && xm >= x && ym >= y && xm < x + width && ym < y + height) : false);
bool hovered = active && (minecraft->useTouchscreen()? (_currentlyDown && xm >= x && ym >= y && xm < x + width && ym < y + height) : isInside(xm, ym));
bool IsSecondImage = isSecondImage(hovered);
//printf("ButtonId: %d - Hovered? %d (cause: %d, %d, %d, %d, <> %d, %d)\n", id, hovered, x, y, x+w, y+h, xm, ym);

View File

@@ -33,7 +33,7 @@ void LargeImageButton::render(Minecraft* minecraft, int xm, int ym) {
//minecraft->textures->loadAndBindTexture("gui/gui.png");
glColor4f2(1, 1, 1, 1);
bool hovered = active && (minecraft->useTouchscreen()? (_currentlyDown && xm >= x && ym >= y && xm < x + width && ym < y + height) : false);
bool hovered = active && (minecraft->useTouchscreen()? (_currentlyDown && xm >= x && ym >= y && xm < x + width && ym < y + height) : isInside(xm, ym));
//printf("ButtonId: %d - Hovered? %d (cause: %d, %d, %d, %d, <> %d, %d)\n", id, hovered, x, y, x+w, y+h, xm, ym);
//int yImage = getYImage(hovered || selected);

View File

@@ -1,14 +1,14 @@
#include "RolledSelectionListH.h"
#include "../../Minecraft.h"
#include "../../renderer/Tesselator.h"
#include "../../renderer/gles.h"
#include "../../../platform/input/Mouse.h"
#include "../../../platform/input/Multitouch.h"
#include "../../../util/Mth.h"
#include "../../renderer/Textures.h"
#include "MinecraftClient.h"
RolledSelectionListH::RolledSelectionListH( Minecraft* minecraft, int width, int height, int x0, int x1, int y0, int y1, int itemWidth )
RolledSelectionListH::RolledSelectionListH( MinecraftClient& minecraft, int width, int height, int x0, int x1, int y0, int y1, int itemWidth )
: minecraft(minecraft),
width(width),
height(height),
@@ -172,7 +172,7 @@ void RolledSelectionListH::render( int xm, int ym, float a )
//LOGI("x: %f\n", xo);
minecraft->textures->loadAndBindTexture("gui/background.png");
minecraft.textures().loadAndBindTexture("gui/background.png");
glColor4f2(1.0f, 1, 1, 1);
float s = 32;
t.begin();
@@ -280,7 +280,7 @@ void RolledSelectionListH::render( int xm, int ym, float a )
void RolledSelectionListH::renderHoleBackground( /*float x0, float x1,*/ float y0, float y1, int a0, int a1 )
{
Tesselator& t = Tesselator::instance;
minecraft->textures->loadAndBindTexture("gui/background.png");
minecraft.textures().loadAndBindTexture("gui/background.png");
glColor4f2(1.0f, 1, 1, 1);
float s = 32;
t.begin();

View File

@@ -2,7 +2,7 @@
#define NET_MINECRAFT_CLIENT_GUI_COMPONENTS__RolledSelectionListH_H__
#include "../GuiComponent.h"
class Minecraft;
class MinecraftClient;
class Tesselator;
@@ -12,7 +12,7 @@ class RolledSelectionListH : public GuiComponent
static const int DRAG_OUTSIDE = -2;
static const int DRAG_NORMAL = 0;
public:
RolledSelectionListH(Minecraft* minecraft, int width, int height, int x0, int x1, int y0, int y1, int itemWidth);
RolledSelectionListH(MinecraftClient& minecraft, int width, int height, int x0, int x1, int y0, int y1, int itemWidth);
virtual int getItemAtPosition(int x, int y);
@@ -45,7 +45,7 @@ protected:
virtual void clickedHeader(int headerMouseX, int headerMouseY) {}
int getItemAtXPositionRaw(int x);
protected:
Minecraft* minecraft;
MinecraftClient& minecraft;
float x0;
float x1;

View File

@@ -20,6 +20,9 @@ static const float kMinimumTrackingForDrag = 5;
static const float kMinIndicatorLength = 34.0f / 3;
static const float PKScrollIndicatorEndSize = 3;
static const float PKScrollIndicatorThickness = 7.0f /3;
static const float kWheelOverscrollMax = 80.0f;
static const float kWheelOverscrollDamping = 0.6f;
static const float kWheelOverscrollRestoreAlpha = 0.18f;
ScrollingPane::ScrollingPane(
int optionFlags,
@@ -70,13 +73,19 @@ ScrollingPane::ScrollingPane(
}
//LOGI("%d, %d :: %d\n", bbox.w, itemBbox.w, this->columns);
rows = 1 + (numItems-1) / this->columns,
rows = 1 + (numItems-1) / this->columns;
/*
if (columns * itemBbox.w <= bbox.w) flags |= SF_LockX;
if (rows * itemBbox.h <= bbox.h) flags |= SF_LockY;
*/
// initialize content bounds immediately
adjustContentSize();
minPoint.set((float)(this->size.w - this->adjustedContentSize.w), (float)(this->size.h - this->adjustedContentSize.h), 0);
this->snapContentOffsetToBounds(false);
dragDeltas.reserve(128);
te_moved = 0;
@@ -114,6 +123,34 @@ void ScrollingPane::tick() {
updateScrollFade(vScroll);
updateScrollFade(hScroll);
}
if (isNotSet(SF_HardLimits) && !Mouse::isButtonDown(MouseAction::ACTION_LEFT) && !dragging && !tracking && !decelerating) {
float targetX = _contentOffset.x;
float targetY = _contentOffset.y;
bool corrected = false;
if (targetX > 0.0f) {
targetX = Mth::lerp(targetX, 0.0f, kWheelOverscrollRestoreAlpha);
corrected = true;
} else if (targetX < minPoint.x) {
targetX = Mth::lerp(targetX, minPoint.x, kWheelOverscrollRestoreAlpha);
corrected = true;
}
if (targetY > 0.0f) {
targetY = Mth::lerp(targetY, 0.0f, kWheelOverscrollRestoreAlpha);
corrected = true;
} else if (targetY < minPoint.y) {
targetY = Mth::lerp(targetY, minPoint.y, kWheelOverscrollRestoreAlpha);
corrected = true;
}
if (corrected) {
if (Mth::abs(targetX - _contentOffset.x) < 0.25f) targetX = (targetX > 0.0f ? 0.0f : (targetX < minPoint.x ? minPoint.x : targetX));
if (Mth::abs(targetY - _contentOffset.y) < 0.25f) targetY = (targetY > 0.0f ? 0.0f : (targetY < minPoint.y ? minPoint.y : targetY));
setContentOffset(Vec3(targetX, targetY, 0));
}
}
}
bool ScrollingPane::getGridItemFor_slow(int itemIndex, GridItem& out) {
@@ -549,11 +586,39 @@ void ScrollingPane::stepThroughDecelerationAnimation(bool noAnimation) {
}
void ScrollingPane::scrollBy(float dx, float dy) {
// adjust the translation offsets fpx/fpy by the requested amount
float nfpx = fpx + dx;
float nfpy = fpy + dy;
// convert back to content offset (fpx = -contentOffset.x)
setContentOffset(Vec3(-nfpx, -nfpy, 0));
// compute target content offset from wheel delta (in screen-space w/ opposite sign)
float targetX = _contentOffset.x - dx;
float targetY = _contentOffset.y - dy;
if (isSet(SF_LockX)) targetX = _contentOffset.x;
if (isSet(SF_LockY)) targetY = _contentOffset.y;
if (isSet(SF_HardLimits)) {
targetX = Mth::clamp(targetX, minPoint.x, 0.0f);
targetY = Mth::clamp(targetY, minPoint.y, 0.0f);
} else {
if (targetX > 0.0f) {
float overshoot = targetX;
overshoot = Mth::Min(overshoot, kWheelOverscrollMax);
targetX = overshoot * kWheelOverscrollDamping;
} else if (targetX < minPoint.x) {
float overshoot = targetX - minPoint.x;
overshoot = Mth::Max(overshoot, -kWheelOverscrollMax);
targetX = minPoint.x + overshoot * kWheelOverscrollDamping;
}
if (targetY > 0.0f) {
float overshoot = targetY;
overshoot = Mth::Min(overshoot, kWheelOverscrollMax);
targetY = overshoot * kWheelOverscrollDamping;
} else if (targetY < minPoint.y) {
float overshoot = targetY - minPoint.y;
overshoot = Mth::Max(overshoot, -kWheelOverscrollMax);
targetY = minPoint.y + overshoot * kWheelOverscrollDamping;
}
}
setContentOffset(Vec3(targetX, targetY, 0));
}
void ScrollingPane::setContentOffset(float x, float y) {

View File

@@ -22,7 +22,7 @@
//static NinePatchLayer* guiPaneFrame = NULL;
static __inline void setIfNotSet(bool& ref, bool condition) {
static inline void setIfNotSet(bool& ref, bool condition) {
ref = (ref || condition);
}

View File

@@ -31,7 +31,7 @@ ConfirmScreen::~ConfirmScreen() {
void ConfirmScreen::init()
{
if (minecraft->useTouchscreen()) {
if (/* minecraft->useTouchscreen() */ true) {
yesButton = new Touch::TButton(0, 0, 0, yesButtonText),
noButton = new Touch::TButton(1, 0, 0, noButtonText);
} else {

View File

@@ -28,6 +28,7 @@ void CreditsScreen::init() {
buttons.push_back(bHeader);
buttons.push_back(btnBack);
// TODO: rewrite it
// prepare text lines
_lines.clear();
_lines.push_back("Minecraft: Pocket Edition");
@@ -39,6 +40,7 @@ void CreditsScreen::init() {
_lines.push_back("Kolyah35");
_lines.push_back("karson");
_lines.push_back("deepfriedwaffles");
_lines.push_back("EpikIzCool");
_lines.push_back("");
// avoid color tags around the URL so it isn't mangled by the parser please
_lines.push_back("Join our Discord server: https://discord.gg/c58YesBxve");

View File

@@ -23,7 +23,7 @@ DeathScreen::~DeathScreen()
void DeathScreen::init()
{
if (minecraft->useTouchscreen()) {
if (/* minecraft->useTouchscreen() */ true) {
bRespawn = new Touch::TButton(1, "Respawn!");
bTitle = new Touch::TButton(2, "Main menu");
} else {

View File

@@ -21,7 +21,7 @@ public:
}
void init() {
if (minecraft->useTouchscreen())
if (/* minecraft->useTouchscreen() */ true)
_back = new Touch::TButton(1, "Ok");
else
_back = new Button(1, "Ok");

View File

@@ -17,7 +17,7 @@ InBedScreen::~InBedScreen() {
}
void InBedScreen::init() {
if (minecraft->useTouchscreen()) {
if (/* minecraft->useTouchscreen() */ true) {
bWakeUp = new Touch::TButton(1, "Leave Bed");
} else {
bWakeUp = new Button(1, "Leave Bed");

View File

@@ -9,7 +9,7 @@
#include "../Gui.h"
#include "../../renderer/Textures.h"
#include "../../gamemode/GameMode.h"
#include <gamemode/GameMode.h>
#include "ArmorScreen.h"
#include "../components/Button.h"

View File

@@ -19,7 +19,6 @@ OptionsScreen::OptionsScreen()
}
OptionsScreen::~OptionsScreen() {
if (btnClose != NULL) {
delete btnClose;
btnClose = NULL;
@@ -53,7 +52,6 @@ OptionsScreen::~OptionsScreen() {
}
void OptionsScreen::init() {
bHeader = new Touch::THeader(0, "Options");
btnClose = new ImageButton(1, "");
@@ -89,7 +87,6 @@ void OptionsScreen::init() {
}
void OptionsScreen::setupPositions() {
int buttonHeight = btnClose->height;
btnClose->x = width - btnClose->width;
@@ -134,7 +131,6 @@ void OptionsScreen::setupPositions() {
void OptionsScreen::render(int xm, int ym, float a) {
renderBackground();
int xmm = xm * width / minecraft->width;
@@ -150,11 +146,14 @@ void OptionsScreen::removed() {
}
void OptionsScreen::buttonClicked(Button* button) {
if (button == btnClose) {
minecraft->options.save();
if (minecraft->screen != NULL) {
minecraft->setScreen(NULL);
} else {
minecraft->screenChooser.setScreen(SCREEN_STARTMENU);
}
}
else if (button->id > 1 && button->id < 7) {
int categoryButton = button->id - categoryButtons[0]->id;
selectCategory(categoryButton);
@@ -165,7 +164,6 @@ void OptionsScreen::buttonClicked(Button* button) {
}
void OptionsScreen::selectCategory(int index) {
int currentIndex = 0;
for (std::vector<Touch::TButton*>::iterator it = categoryButtons.begin(); it != categoryButtons.end(); ++it) {
@@ -209,7 +207,8 @@ void OptionsScreen::generateOptionScreens() {
// // Controls Pane
optionPanes[2]->addOptionItem(OPTIONS_INVERT_Y_MOUSE, minecraft)
.addOptionItem(OPTIONS_USE_TOUCHSCREEN, minecraft);
.addOptionItem(OPTIONS_USE_TOUCHSCREEN, minecraft)
.addOptionItem(OPTIONS_AUTOJUMP, minecraft);
for (int i = OPTIONS_KEY_FORWARD; i <= OPTIONS_KEY_USE; i++) {
optionPanes[2]->addOptionItem((OptionId)i, minecraft);
@@ -230,7 +229,6 @@ void OptionsScreen::generateOptionScreens() {
}
void OptionsScreen::mouseClicked(int x, int y, int buttonNum) {
if (currentOptionsGroup != NULL)
currentOptionsGroup->mouseClicked(minecraft, x, y, buttonNum);
@@ -238,7 +236,6 @@ void OptionsScreen::mouseClicked(int x, int y, int buttonNum) {
}
void OptionsScreen::mouseReleased(int x, int y, int buttonNum) {
if (currentOptionsGroup != NULL)
currentOptionsGroup->mouseReleased(minecraft, x, y, buttonNum);

View File

@@ -5,12 +5,16 @@
#include "../../../util/Mth.h"
#include "../../../network/RakNetInstance.h"
#include "../../../network/ServerSideNetworkHandler.h"
#include "client/Options.h"
#include "client/gui/components/Button.h"
#include "client/gui/screens/OptionsScreen.h"
PauseScreen::PauseScreen(bool wasBackPaused)
: saveStep(0),
visibleTime(0),
bContinue(0),
bQuit(0),
bOptions(0),
bQuitAndSaveLocally(0),
bServerVisibility(0),
// bThirdPerson(0),
@@ -39,18 +43,21 @@ PauseScreen::~PauseScreen() {
delete bQuit;
delete bQuitAndSaveLocally;
delete bServerVisibility;
delete bOptions;
// delete bThirdPerson;
}
void PauseScreen::init() {
if (minecraft->useTouchscreen()) {
if (/* minecraft->useTouchscreen() */ true) {
bContinue = new Touch::TButton(1, "Back to game");
bOptions = new Touch::TButton(5, "Options");
bQuit = new Touch::TButton(2, "Quit to title");
bQuitAndSaveLocally = new Touch::TButton(3, "Quit and copy map");
bServerVisibility = new Touch::TButton(4, "");
// bThirdPerson = new Touch::TButton(5, "Toggle 3:rd person view");
} else {
bContinue = new Button(1, "Back to game");
bOptions = new Button(5, "Options");
bQuit = new Button(2, "Quit to title");
bQuitAndSaveLocally = new Button(3, "Quit and copy map");
bServerVisibility = new Button(4, "");
@@ -59,7 +66,7 @@ void PauseScreen::init() {
buttons.push_back(bContinue);
buttons.push_back(bQuit);
buttons.push_back(bOptions);
// bSound.updateImage(&minecraft->options);
bThirdPerson.updateImage(&minecraft->options);
bHideGui.updateImage(&minecraft->options);
@@ -99,21 +106,24 @@ void PauseScreen::setupPositions() {
saveStep = 0;
int yBase = 16;
bContinue->width = bQuit->width = /*bThirdPerson->w =*/ 160;
bContinue->width = bOptions->width = bQuit->width = /*bThirdPerson->w =*/ 160;
bQuitAndSaveLocally->width = bServerVisibility->width = 160;
bContinue->x = (width - bContinue->width) / 2;
bContinue->y = yBase + 32 * 1;
bOptions->x = (width - bOptions->width) / 2;
bOptions->y = yBase + 32 * 2;
bQuit->x = (width - bQuit->width) / 2;
bQuit->y = yBase + 32 * 2;
bQuit->y = yBase + 32 * 3;
#if APPLE_DEMO_PROMOTION
bQuit->y += 16;
#endif
bQuitAndSaveLocally->x = bServerVisibility->x = (width - bQuitAndSaveLocally->width) / 2;
bQuitAndSaveLocally->y = bServerVisibility->y = yBase + 32 * 3;
bQuitAndSaveLocally->y = bServerVisibility->y = yBase + 32 * 4;
// bSound.y = bThirdPerson.y = 8;
// bSound.x = 4;
@@ -157,7 +167,9 @@ void PauseScreen::buttonClicked(Button* button) {
if (button->id == bQuitAndSaveLocally->id) {
minecraft->leaveGame(true);
}
if (button->id == bOptions->id) {
minecraft->setScreen(new OptionsScreen());
}
if (button->id == bServerVisibility->id) {
if (minecraft->raknetInstance && minecraft->netCallback && minecraft->raknetInstance->isServer()) {
ServerSideNetworkHandler* ss = (ServerSideNetworkHandler*) minecraft->netCallback;

View File

@@ -33,7 +33,9 @@ private:
Button* bQuit;
Button* bQuitAndSaveLocally;
Button* bServerVisibility;
// Button* bThirdPerson;
Button* bOptions;
// Button* bThirdPerson;
// OptionButton bSound;
OptionButton bThirdPerson;

View File

@@ -11,6 +11,8 @@ public:
void render(int xm, int ym, float a);
bool isInGameScreen();
virtual void keyPressed(int eventKey) {}
void tick();
private:
int ticks;

View File

@@ -1,55 +0,0 @@
#include "RenameMPLevelScreen.h"
#include "StartMenuScreen.h"
#include "DialogDefinitions.h"
#include "../Gui.h"
#include "../../Minecraft.h"
#include "../../../AppPlatform.h"
#include "../../../platform/log.h"
#include "../../../world/level/storage/LevelStorageSource.h"
static char ILLEGAL_FILE_CHARACTERS[] = {
'/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':'
};
RenameMPLevelScreen::RenameMPLevelScreen( const std::string& levelId )
: _levelId(levelId)
{
}
void RenameMPLevelScreen::init() {
minecraft->platform()->createUserInput(DialogDefinitions::DIALOG_RENAME_MP_WORLD);
}
void RenameMPLevelScreen::render(int xm, int ym, float a)
{
renderBackground();
#ifdef WIN32
minecraft->getLevelSource()->renameLevel(_levelId, "Save?Level");
minecraft->screenChooser.setScreen(SCREEN_STARTMENU);
#else
int status = minecraft->platform()->getUserInputStatus();
if (status > -1) {
if (status == 1) {
std::vector<std::string> v = minecraft->platform()->getUserInput();
if (!v.empty()) {
// Read the level name.
// 1) Trim name 2) Remove all bad chars -) We don't have to getUniqueLevelName, since renameLevel will do that
std::string levelId = v[0];
for (int i = 0; i < sizeof(ILLEGAL_FILE_CHARACTERS) / sizeof(char); ++i)
levelId = Util::stringReplace(levelId, std::string(1, ILLEGAL_FILE_CHARACTERS[i]), "");
if ((int)levelId.length() == 0) {
levelId = "saved_world";
}
minecraft->getLevelSource()->renameLevel(_levelId, levelId);
}
}
minecraft->screenChooser.setScreen(SCREEN_STARTMENU);
}
#endif
}

View File

@@ -1,18 +0,0 @@
#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__RenameMPLevelScreen_H__
#define NET_MINECRAFT_CLIENT_GUI_SCREENS__RenameMPLevelScreen_H__
#include "../Screen.h"
class RenameMPLevelScreen: public Screen
{
public:
RenameMPLevelScreen(const std::string& levelId);
virtual void init();
virtual void render(int xm, int ym, float a);
private:
std::string _levelId;
};
#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__RenameMPLevelScreen_H__*/

View File

@@ -1,5 +1,6 @@
#include "ScreenChooser.h"
#include "StartMenuScreen.h"
#include "MinecraftClient.h"
#include "SelectWorldScreen.h"
#include "JoinGameScreen.h"
#include "PauseScreen.h"
@@ -21,7 +22,7 @@ Screen* ScreenChooser::createScreen( ScreenId id )
Screen* screen = NULL;
// :sob:
if (_mc->useTouchscreen()) {
if (/* _mc->useTouchscreen() */ true) {
switch (id) {
case SCREEN_STARTMENU: screen = new Touch::StartMenuScreen(); break;
case SCREEN_SELECTWORLD: screen = new Touch::SelectWorldScreen();break;
@@ -58,6 +59,6 @@ Screen* ScreenChooser::createScreen( ScreenId id )
Screen* ScreenChooser::setScreen(ScreenId id)
{
Screen* screen = createScreen(id);
_mc->setScreen(screen);
_mc.setScreen(screen);
return screen;
}

View File

@@ -14,19 +14,17 @@ enum ScreenId {
};
class Screen;
class Minecraft;
class MinecraftClient;
class ScreenChooser
{
public:
ScreenChooser(Minecraft* mc)
: _mc(mc)
{}
ScreenChooser(MinecraftClient& mc) : _mc(mc) {}
Screen* createScreen(ScreenId id);
Screen* setScreen(ScreenId id);
private:
Minecraft* _mc;
MinecraftClient& _mc;
};
#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__ScreenChooser_H__*/

View File

@@ -1,4 +1,5 @@
#include "SelectWorldScreen.h"
#include "MinecraftClient.h"
#include "StartMenuScreen.h"
#include "ProgressScreen.h"
#include "DialogDefinitions.h"
@@ -22,7 +23,7 @@ static float Max(float a, float b) {
//
// World Selection List
//
WorldSelectionList::WorldSelectionList( Minecraft* minecraft, int width, int height )
WorldSelectionList::WorldSelectionList( MinecraftClient& minecraft, int width, int height )
: _height(height),
hasPickedLevel(false),
currentTick(0),

View File

@@ -5,11 +5,11 @@
#include "../TweenData.h"
#include "../components/Button.h"
#include "../components/RolledSelectionListH.h"
#include "../../Minecraft.h"
#include "../../../world/level/storage/LevelStorageSource.h"
class SelectWorldScreen;
class MinecraftClient;
//
// Scrolling World selection list
@@ -17,7 +17,7 @@ class SelectWorldScreen;
class WorldSelectionList : public RolledSelectionListH
{
public:
WorldSelectionList(Minecraft* _minecraft, int _width, int _height);
WorldSelectionList(MinecraftClient& _minecraft, int _width, int _height);
virtual void tick();
void stepLeft();
void stepRight();

View File

@@ -56,7 +56,7 @@ void SimpleChooseLevelScreen::init()
def.setSrc(IntRectangle(150, 0, (int)def.width, (int)def.height));
bBack->setImageDef(def, true);
}
if (minecraft->useTouchscreen()) {
if (/* minecraft->useTouchscreen() */ true) {
bGamemode = new Touch::TButton(1, "Survival mode");
bCheats = new Touch::TButton(4, "Cheats: Off");
bCreate = new Touch::TButton(3, "Create");

View File

@@ -41,7 +41,7 @@ public:
//fill(x+1, y+1, x+w-1, y+h-1, 0xff999999);
bool hovered = active && (minecraft->useTouchscreen()?
(_currentlyDown && xm >= x && ym >= y && xm < x + width && ym < y + height) : false);
(_currentlyDown && xm >= x && ym >= y && xm < x + width && ym < y + height) : isInside(xm, ym));
if (hovered || *selectedPtr == this)
statePressed->draw(Tesselator::instance, (float)x, (float)y);
@@ -547,7 +547,7 @@ void CraftButton::renderBg(Minecraft* minecraft, int xm, int ym) {
//fill(x+1, y+1, x+w-1, y+h-1, 0xff999999);
bool hovered = active && (minecraft->useTouchscreen()?
(_currentlyDown && xm >= x && ym >= y && xm < x + width && ym < y + height) : false);
(_currentlyDown && xm >= x && ym >= y && xm < x + width && ym < y + height) : isInside(xm, ym));
if (hovered || selected)
bgSelected->draw(Tesselator::instance, (float)x, (float)y);

View File

@@ -3,7 +3,7 @@
#include "../../Screen.h"
#include "../../components/ImageButton.h"
#include "../../components/InventoryPane.h"
#include "../../../gamemode/GameMode.h"
#include <gamemode/GameMode.h>
#include "../../../renderer/TileRenderer.h"
#include "../../../player/LocalPlayer.h"
#include "../../../renderer/gles.h"

View File

@@ -1,5 +1,5 @@
#include "HumanoidModel.h"
#include "../Minecraft.h"
#include <Minecraft.h>
#include "../../util/Mth.h"
#include "../../world/entity/player/Player.h"
#include "../../world/entity/player/Inventory.h"

View File

@@ -1,6 +1,5 @@
#include "LocalPlayer.h"
#include "../Minecraft.h"
#include "../../ErrorCodes.h"
#include <Minecraft.h>
#include "../../world/entity/EntityEvent.h"
#include "../../world/entity/player/Player.h"
#include "../../world/inventory/BaseContainerMenu.h"
@@ -35,7 +34,7 @@
#include <errno.h>
#endif
#ifndef STANDALONE_SERVER
#include "../gui/Screen.h"
#include "../gui/screens/FurnaceScreen.h"
#include "../gui/screens/ChestScreen.h"
@@ -44,13 +43,13 @@
#include "../gui/screens/InBedScreen.h"
#include "../gui/screens/TextEditScreen.h"
#include "../particle/TakeAnimationParticle.h"
#endif
#include "../../network/packet/AnimatePacket.h"
#include "../../world/item/ArmorItem.h"
#include "../../network/packet/PlayerArmorEquipmentPacket.h"
#include <MinecraftClient.h>
namespace {
#ifndef STANDALONE_SERVER
static bool isBase64(unsigned char c) {
return (std::isalnum(c) || (c == '+') || (c == '/'));
@@ -233,7 +232,7 @@ static bool fileExists(const std::string& path) {
#endif
}
#ifndef STANDALONE_SERVER
static void* fetchSkinForPlayer(void* param) {
LocalPlayer* player = (LocalPlayer*)param;
@@ -345,33 +344,21 @@ static bool isJumpable(int tileId) {
} // anonymous namespace
LocalPlayer::LocalPlayer(Minecraft* minecraft, Level* level, const std::string& username, int dimension, bool isCreative)
: Player(level, isCreative),
minecraft(minecraft),
input(NULL),
sentInventoryItemId(-1),
sentInventoryItemData(-1),
autoJumpEnabled(true),
armorTypeHash(0),
sprinting(false),
sprintDoubleTapTimer(0),
prevForwardHeld(false)
{
LocalPlayer::LocalPlayer(MinecraftClient& minecraft, Level* level, const std::string& username, int dimension, bool isCreative)
: Player(level, isCreative), minecraft(minecraft) {
this->dimension = dimension;
_init();
#ifndef STANDALONE_SERVER
if (minecraft->options.getStringValue(OPTIONS_USERNAME).size() != 0) {
if (minecraft.options().getStringValue(OPTIONS_USERNAME).size() != 0) {
textureName = "mob/char.png";
this->name = minecraft->options.getStringValue(OPTIONS_USERNAME);
this->name = minecraft.options().getStringValue(OPTIONS_USERNAME);
printf("test \n");
// Fetch user skin and cape from Mojang servers in the background (avoids blocking the main thread)
// TODO: Fix this memory leak
new CThread(fetchSkinForPlayer, this);
new CThread(fetchCapeForPlayer, this);
}
#endif
}
LocalPlayer::~LocalPlayer() {
@@ -381,13 +368,19 @@ LocalPlayer::~LocalPlayer() {
/*private*/
void LocalPlayer::calculateFlight(float xa, float ya, float za) {
float flySpeed = minecraft->options.getProgressValue(OPTIONS_FLY_SPEED);
float sensivity = minecraft->options.getProgressValue(OPTIONS_SENSITIVITY);
float flySpeed = minecraft.options().getProgressValue(OPTIONS_FLY_SPEED);
float sensivity = minecraft.options().getProgressValue(OPTIONS_SENSITIVITY);
xa = xa * flySpeed;
ya = 0;
za = za * flySpeed;
if (sprinting) {
float sprintBoost = getWalkingSpeedModifier(); // 1.3x
xa *= sprintBoost;
za *= sprintBoost;
}
#ifdef ANDROID
if (Keyboard::isKeyDown(103)) ya = .2f * flySpeed;
if (Keyboard::isKeyDown(102)) ya = -.2f * flySpeed;
@@ -428,12 +421,12 @@ void LocalPlayer::tick() {
stopUsingItem();
}
}
if (minecraft->isOnline())
if (minecraft.isOnline())
{
if (std::abs(x - sentX) > .1f || std::abs(y - sentY) > .01f || std::abs(z - sentZ) > .1f || std::abs(sentRotX - xRot) > 1 || std::abs(sentRotY - yRot) > 1)
{
MovePlayerPacket packet(entityId, x, y - heightOffset, z, xRot, yRot);
minecraft->raknetInstance->send(packet);
minecraft.raknetInstance->send(packet);
sentX = x;
sentY = y;
sentZ = z;
@@ -451,7 +444,7 @@ void LocalPlayer::tick() {
sentInventoryItemId = newItemId;
sentInventoryItemData = newItemData;
PlayerEquipmentPacket packet(entityId, newItemId, newItemData);
minecraft->raknetInstance->send(packet);
minecraft.raknetInstance->send(packet);
}
}
/*
@@ -466,15 +459,14 @@ void LocalPlayer::tick() {
*/
updateArmorTypeHash();
#ifndef STANDALONE_SERVER
if (!minecraft->screen && containerMenu) {
if (!minecraft.getScreen() && containerMenu) {
static bool hasPostedError = false;
if (!hasPostedError) {
minecraft->gui.postError( ErrorCodes::ContainerRefStillExistsAfterDestruction );
// @todo
// minecraft.gui().postError( ErrorCodes::ContainerRefStillExistsAfterDestruction );
hasPostedError = true;
}
}
#endif
//LOGI("biome: %s\n", level->getBiomeSource()->getBiome((int)x >> 4, (int)z >> 4)->name.c_str());
}
@@ -485,15 +477,14 @@ void LocalPlayer::aiStep() {
descendTriggerTime--;
bool wasJumping = input->jumping;
#ifndef STANDALONE_SERVER
bool screenCovering = minecraft->screen && !minecraft->screen->passEvents;
bool screenCovering = minecraft.getScreen() && !minecraft.getScreen()->passEvents;
if (!screenCovering)
input->tick(this);
// Sprint: detect W double-tap
{
bool forwardHeld = (input->ya > 0);
if (forwardHeld && !prevForwardHeld && minecraft->options.getBooleanValue(OPTIONS_ALLOW_SPRINT)) {
if (forwardHeld && !prevForwardHeld && minecraft.options().getBooleanValue(OPTIONS_ALLOW_SPRINT)) {
// leading edge of W press
if (sprintDoubleTapTimer > 0)
sprinting = true;
@@ -506,13 +497,13 @@ void LocalPlayer::aiStep() {
if (sprintDoubleTapTimer > 0) sprintDoubleTapTimer--;
prevForwardHeld = forwardHeld;
}
if (input->sneaking || abilities.flying)
if (input->sneaking)
sprinting = false;
if (input->sneaking) {
if (ySlideOffset < 0.2f) ySlideOffset = 0.2f;
}
#endif
if (abilities.mayfly) {
// Check for flight toggle
if (!wasJumping && input->jumping) {
@@ -553,16 +544,16 @@ void LocalPlayer::aiStep() {
void LocalPlayer::closeContainer() {
if (level->isClientSide) {
ContainerClosePacket packet(containerMenu->containerId);
minecraft->raknetInstance->send(packet);
minecraft.raknetInstance->send(packet);
}
super::closeContainer();
minecraft->setScreen(NULL);
minecraft.setScreen(NULL);
}
//@Override
void LocalPlayer::move(float xa, float ya, float za) {
//@note: why is this == minecraft->player needed?
if (this == minecraft->player && minecraft->options.getBooleanValue(OPTIONS_IS_FLYING)) {
//@note: why is this == minecraft.player needed?
if (this == minecraft.getPlayer() && minecraft.options().getBooleanValue(OPTIONS_IS_FLYING)) {
noPhysics = true;
float tmp = walkDist; // update
calculateFlight((float) xa, (float) ya, (float) za);
@@ -582,7 +573,7 @@ void LocalPlayer::move(float xa, float ya, float za) {
float newX = x, newZ = z;
if (autoJumpTime <= 0 && minecraft->options.getBooleanValue(OPTIONS_AUTOJUMP))
if (autoJumpTime <= 0 && minecraft.options().getBooleanValue(OPTIONS_AUTOJUMP))
{
// auto-jump when crossing the middle of a tile, and the tile in the front is blocked
bool jump = false;
@@ -611,12 +602,9 @@ void LocalPlayer::updateAi() {
this->jumping = input->jumping || autoJumpTime > 0;
}
void LocalPlayer::take( Entity* e, int orgCount )
{
#ifndef STANDALONE_SERVER
void LocalPlayer::take( Entity* e, int orgCount ) {
if (e->isItemEntity())
minecraft->particleEngine->add(new TakeAnimationParticle(minecraft->level, (ItemEntity*)e, this, -0.5f));
#endif
minecraft.getParticleEngine()->add(new TakeAnimationParticle(minecraft.level, (ItemEntity*)e, this, -0.5f));
}
void LocalPlayer::setKey( int eventKey, bool eventKeyState )
@@ -678,28 +666,25 @@ void LocalPlayer::hurtTo( int newHealth )
lastHealth = health;
invulnerableTime = invulnerableDuration;
minecraft->player->bypassArmor = true;
minecraft.getPlayer()->bypassArmor = true;
actuallyHurt(dmg);
minecraft->player->bypassArmor = false;
minecraft.getPlayer()->bypassArmor = false;
hurtTime = hurtDuration = 10;
}
}
void LocalPlayer::actuallyHurt( int dmg )
{
#ifndef STANDALONE_SERVER
if (minecraft->screen && minecraft->screen->closeOnPlayerHurt()) {
void LocalPlayer::actuallyHurt( int dmg ) {
if (minecraft.getScreen() && minecraft.getScreen()->closeOnPlayerHurt()) {
if (containerMenu) closeContainer();
else minecraft->setScreen(NULL);
else minecraft.setScreen(NULL);
}
#endif
super::actuallyHurt(dmg);
}
void LocalPlayer::respawn()
{
minecraft->respawnPlayer();
void LocalPlayer::respawn() {
minecraft.respawnPlayer();
}
void LocalPlayer::die(Entity* source)
@@ -708,7 +693,7 @@ void LocalPlayer::die(Entity* source)
// If we're the server, drop the inventory immediately
if (level->isClientSide) {
SendInventoryPacket packet(this, true);
minecraft->raknetInstance->send(packet);
minecraft.raknetInstance->send(packet);
}
inventory->dropAll(level->isClientSide);
for (int i = 0; i < NUM_ARMOR; ++i) {
@@ -729,7 +714,7 @@ void LocalPlayer::swing() {
AnimatePacket packet(AnimatePacket::Swing, this);
packet.reliability = UNRELIABLE;
packet.priority = MEDIUM_PRIORITY;
minecraft->raknetInstance->send(packet);
minecraft.raknetInstance->send(packet);
}
}
@@ -752,31 +737,23 @@ void LocalPlayer::_init() {
}
void LocalPlayer::startCrafting(int x, int y, int z, int tableSize) {
#ifndef STANDALONE_SERVER
if (!minecraft->isCreativeMode())
minecraft->setScreen( new WorkbenchScreen(tableSize) );
#endif
if (!minecraft.isCreativeMode())
minecraft.setScreen( new WorkbenchScreen(tableSize) );
}
void LocalPlayer::startStonecutting(int x, int y, int z) {
#ifndef STANDALONE_SERVER
if (!minecraft->isCreativeMode())
minecraft->setScreen( new StonecutterScreen() );
#endif
if (!minecraft.isCreativeMode())
minecraft.setScreen( new StonecutterScreen() );
}
void LocalPlayer::openFurnace( FurnaceTileEntity* e ) {
#ifndef STANDALONE_SERVER
if (!minecraft->isCreativeMode())
minecraft->setScreen( new FurnaceScreen(this, e) );
#endif
if (!minecraft.isCreativeMode())
minecraft.setScreen( new FurnaceScreen(this, e) );
}
void LocalPlayer::openContainer( ChestTileEntity* container ) {
#ifndef STANDALONE_SERVER
if (!minecraft->isCreativeMode())
minecraft->setScreen( new ChestScreen(this, container) );
#endif
if (!minecraft.isCreativeMode())
minecraft.setScreen( new ChestScreen(this, container) );
}
void LocalPlayer::drop( ItemInstance* item, bool randomly )
@@ -786,7 +763,7 @@ void LocalPlayer::drop( ItemInstance* item, bool randomly )
if (level->isClientSide) {
DropItemPacket packet(entityId, *item);
minecraft->raknetInstance->send(packet);
minecraft.raknetInstance->send(packet);
// delete the ItemEntity here, since we don't add it to level
delete item;
} else {
@@ -800,7 +777,7 @@ void LocalPlayer::causeFallDamage( float distance )
if (dmg > 0) {
if (level->isClientSide) {
SetHealthPacket packet(SetHealthPacket::HEALTH_MODIFY_OFFSET + dmg);
minecraft->raknetInstance->send(packet);
minecraft.raknetInstance->send(packet);
}
}
super::causeFallDamage(distance);
@@ -808,35 +785,33 @@ void LocalPlayer::causeFallDamage( float distance )
}
void LocalPlayer::displayClientMessage( const std::string& messageId ) {
#ifndef STANDALONE_SERVER
minecraft->gui.displayClientMessage(messageId);
#endif
minecraft.gui().displayClientMessage(messageId);
}
int LocalPlayer::startSleepInBed( int x, int y, int z ) {
int startSleepInBedReturnValue = super::startSleepInBed(x, y, z);
#ifndef STANDALONE_SERVER
if(startSleepInBedReturnValue == BedSleepingResult::OK)
minecraft->setScreen(new InBedScreen());
#endif
minecraft.setScreen(new InBedScreen());
return startSleepInBedReturnValue;
}
void LocalPlayer::stopSleepInBed( bool forcefulWakeUp, bool updateLevelList, bool saveRespawnPoint ) {
if(level->isClientSide) {
PlayerActionPacket packet(PlayerActionPacket::STOP_SLEEPING, 0, 0, 0, 0, entityId);
minecraft->raknetInstance->send(packet);
minecraft.raknetInstance->send(packet);
}
#ifndef STANDALONE_SERVER
minecraft->setScreen(NULL);
#endif
minecraft.setScreen(NULL);
super::stopSleepInBed(forcefulWakeUp, updateLevelList, saveRespawnPoint);
}
void LocalPlayer::openTextEdit( TileEntity* tileEntity ) {
#if !defined(STANDALONE_SERVER) && !defined(RPI)
#if !defined(RPI)
if(tileEntity->type == TileEntityType::Sign)
minecraft->setScreen(new TextEditScreen((SignTileEntity*) tileEntity));
minecraft.setScreen(new TextEditScreen((SignTileEntity*) tileEntity));
#endif
}
@@ -844,7 +819,7 @@ void LocalPlayer::updateArmorTypeHash() {
int hash = getArmorTypeHash();
if (hash != armorTypeHash) {
PlayerArmorEquipmentPacket p(this);
minecraft->raknetInstance->send(p);
minecraft.raknetInstance->send(p);
armorTypeHash = hash;
}
}

View File

@@ -7,7 +7,7 @@
#include "../../util/SmoothFloat.h"
#include "../../world/entity/player/Player.h"
class Minecraft;
class MinecraftClient;
class Stat;
class CompoundTag;
@@ -15,7 +15,7 @@ class LocalPlayer: public Player
{
typedef Player super;
public:
LocalPlayer(Minecraft* minecraft, Level* level, const std::string& username, int dimension, bool isCreative);
LocalPlayer(MinecraftClient& minecraft, Level* level, const std::string& username, int dimension, bool isCreative);
~LocalPlayer();
void _init();
@@ -74,10 +74,10 @@ private:
bool isSolidTile(int x, int y, int z);
void updateArmorTypeHash();
public:
IMoveInput* input;
bool autoJumpEnabled;
IMoveInput* input = nullptr;
bool autoJumpEnabled = true;
protected:
Minecraft* minecraft;
MinecraftClient& minecraft;
int jumpTriggerTime;
int ascendTriggerTime;
int descendTriggerTime;
@@ -94,15 +94,15 @@ private:
int autoJumpTime;
int sentInventoryItemId;
int sentInventoryItemData;
int sentInventoryItemId = -1;
int sentInventoryItemData = -1;
int armorTypeHash;
int armorTypeHash = 0;
// sprinting
bool sprinting;
int sprintDoubleTapTimer;
bool prevForwardHeld;
bool sprinting = false;
int sprintDoubleTapTimer = 0;
bool prevForwardHeld = false;
public:
void setSprinting(bool sprint) { sprinting = sprint; }
};

View File

@@ -50,10 +50,8 @@ void KeyboardInput::tick( Player* player )
ya *= 0.3f;
}
#if defined(RPI) || defined(PLATFORM_DESKTOP)
wantUp = jumping;
wantDown = sneaking;
#endif
if (keys[KEY_CRAFT])
player->startCrafting((int)player->x, (int)player->y, (int)player->z, Recipe::SIZE_2X2);

View File

@@ -164,7 +164,7 @@ void TouchscreenInput_TestFps::onConfigChanged(const Config& c) {
float maxPixels = _minecraft->pixelCalc.millimetersToPixels(10);
// float btnSize = Mth::Min(18 * Gui::GuiScale, maxPixels);
float btnSize = pc.millimetersToPixels(50);
float btnSize = pc.millimetersToPixels(18 * Gui::GuiScale);
_model.addArea(AREA_PAUSE, aPause = new RectangleArea(w - 4 - btnSize, 4, w - 4, 4 + btnSize));
_model.addArea(AREA_CHAT, aChat = new RectangleArea(w - 8 - btnSize * 2, 4, w - 8 - btnSize, 4 + btnSize));
@@ -320,6 +320,7 @@ void TouchscreenInput_TestFps::tick( Player* player )
if (Multitouch::isReleased(p)) {
_minecraft->soundEngine->playUI("random.click", 1, 1);
_minecraft->screenChooser.setScreen(SCREEN_CONSOLE);
_minecraft->platform()->showKeyboard();
}
}

View File

@@ -44,7 +44,7 @@ private:
range(b);
range(a);
}
__inline void range(GLfloat& v) {
inline void range(GLfloat& v) {
if (v < 0) v = 0;
if (v > 1) v = 1;
}

View File

@@ -9,7 +9,7 @@
#include "culling/AllowAllCuller.h"
#include "culling/FrustumCuller.h"
#include "entity/EntityRenderDispatcher.h"
#include "../Minecraft.h"
#include <Minecraft.h>
#include "../gamemode/GameMode.h"
#include "../particle/ParticleEngine.h"
#include "../player/LocalPlayer.h"
@@ -153,7 +153,7 @@ void GameRenderer::render(float a) {
int xMouse = (int)(Mouse::getX() * Gui::InvGuiScale);
int yMouse = (int)(Mouse::getY() * Gui::InvGuiScale);
#ifndef PLATFORM_DESKTOP
if (mc->useTouchscreen()) {
const int pid = Multitouch::getFirstActivePointerIdExThisUpdate();
if (pid >= 0) {
@@ -164,7 +164,6 @@ void GameRenderer::render(float a) {
yMouse = -9999;
}
}
#endif
TIMER_POP();
bool hasClearedColorBuffer = false;
@@ -361,9 +360,9 @@ void GameRenderer::renderLevel(float a) {
if (mc->hitResult.isHit() && !cameraEntity->isUnderLiquid(Material::water)) {
TIMER_POP_PUSH("select");
Player* player = (Player*) cameraEntity;
if (mc->useTouchscreen()) {
// if (mc->useTouchscreen()) {
levelRenderer->renderHitSelect(player, mc->hitResult, 0, NULL, a); //player.inventory->getSelected(), a);
}
// }
levelRenderer->renderHit(player, mc->hitResult, 0, NULL, a);//player->inventory.getSelected(), a);
}
}
@@ -657,11 +656,9 @@ void GameRenderer::pick(float a) {
float range = mc->gameMode->getPickRange();
bool isPicking = true;
#ifndef PLATFORM_DESKTOP
bool freeform = mc->useTouchscreen() && !mc->options.getBooleanValue(OPTIONS_IS_JOY_TOUCH_AREA);
#else
bool freeform = false;
#endif
bool freeform = mc->useTouchscreen(); //&& !mc->options.getBooleanValue(OPTIONS_IS_JOY_TOUCH_AREA);
if (freeform) {
isPicking = updateFreeformPickDirection(a, pickDirection);
} else {

View File

@@ -5,7 +5,7 @@
#include "entity/EntityRenderDispatcher.h"
#include "entity/EntityRenderer.h"
#include "entity/MobRenderer.h"
#include "../Minecraft.h"
#include <Minecraft.h>
#include "../player/LocalPlayer.h"
#include "../../world/entity/player/Player.h"
#include "../../world/item/Item.h"

View File

@@ -4,7 +4,7 @@
#include "DistanceChunkSorter.h"
#include "Chunk.h"
#include "TileRenderer.h"
#include "../Minecraft.h"
#include <Minecraft.h>
#include "../../util/Mth.h"
#include "../../world/entity/player/Player.h"
#include "../../world/level/tile/LevelEvent.h"

View File

@@ -9,7 +9,7 @@
#include "gles.h"
#include <vector>
class Minecraft;
class MinecraftClient;
class Textures;
class Culler;
class Chunk;
@@ -33,7 +33,7 @@ public:
float zOld;
float destroyProgress;
LevelRenderer(Minecraft* mc);
LevelRenderer(MinecraftClient& mc);
~LevelRenderer();
void setLevel(Level* level);
@@ -77,7 +77,7 @@ private:
void resortChunks(int xc, int yc, int zc);
void deleteChunks();
//void checkQueryResults(int from, int to);
__inline int getLinearCoord(int x, int y, int z) {
inline int getLinearCoord(int x, int y, int z) {
return (z * yChunks + y) * xChunks + x;
}
int noEntityRenderFrames;

View File

@@ -18,7 +18,7 @@ public:
void add(int list);
void addR(const RenderChunk& chunk);
__inline void next() { ++listIndex; }
inline void next() { ++listIndex; }
void render();
void renderChunks();

View File

@@ -72,18 +72,18 @@ public:
int getColor();
__inline void beginOverride() {
inline void beginOverride() {
begin();
voidBeginAndEndCalls(true);
}
__inline void endOverrideAndDraw() {
inline void endOverrideAndDraw() {
voidBeginAndEndCalls(false);
draw();
}
__inline bool isOverridden() {
inline bool isOverridden() {
return _voidBeginEnd;
}
__inline RenderChunk endOverride(int bufferId) {
inline RenderChunk endOverride(int bufferId) {
voidBeginAndEndCalls(false);
return end(true, bufferId);
}

View File

@@ -4,34 +4,20 @@
#include "ptexture/DynamicTexture.h"
#include "../Options.h"
#include "../../platform/time.h"
#include "../../AppPlatform.h"
#include "../../util/StringUtils.h"
/*static*/ int Textures::textureChanges = 0;
/*static*/ bool Textures::MIPMAP = false;
/*static*/ const TextureId Textures::InvalidId = -1;
Textures::Textures( Options* options_, AppPlatform* platform_ )
: clamp(false),
blur(false),
options(options_),
platform(platform_),
lastBoundTexture(Textures::InvalidId)
{
}
Textures::~Textures()
{
Textures::~Textures() {
clear();
for (unsigned int i = 0; i < dynamicTextures.size(); ++i)
delete dynamicTextures[i];
}
void Textures::clear()
{
void Textures::clear() {
for (TextureMap::iterator it = idMap.begin(); it != idMap.end(); ++it) {
if (it->second != Textures::InvalidId)
if (it->second != TEXTURES_INVALID_ID)
glDeleteTextures(1, &it->second);
}
for (TextureImageMap::iterator it = loadedImages.begin(); it != loadedImages.end(); ++it) {
@@ -41,7 +27,7 @@ void Textures::clear()
idMap.clear();
loadedImages.clear();
lastBoundTexture = Textures::InvalidId;
lastBoundTexture = TEXTURES_INVALID_ID;
}
TextureId Textures::loadAndBindTexture( const std::string& resourceName )
@@ -51,7 +37,7 @@ TextureId Textures::loadAndBindTexture( const std::string& resourceName )
//t.start();
TextureId id = loadTexture(resourceName);
//t.stop();
if (id != Textures::InvalidId)
if (id != TEXTURES_INVALID_ID)
bind(id);
//t.printEvery(1000);
@@ -59,25 +45,24 @@ TextureId Textures::loadAndBindTexture( const std::string& resourceName )
return id;
}
TextureId Textures::loadTexture( const std::string& resourceName, bool inTextureFolder /* = true */ )
{
TextureId Textures::loadTexture(const std::string& resourceName, bool inTextureFolder) {
TextureMap::iterator it = idMap.find(resourceName);
if (it != idMap.end())
return it->second;
bool isUrl = Util::startsWith(resourceName, "http://") || Util::startsWith(resourceName, "https://");
TextureData texdata = platform->loadTexture(resourceName, isUrl ? false : inTextureFolder);
TextureData texdata = m_platform.loadTexture(resourceName, isUrl ? false : inTextureFolder);
if (texdata.data)
return assignTexture(resourceName, texdata);
else if (texdata.identifier != InvalidId) {
else if (texdata.identifier != TEXTURES_INVALID_ID) {
//LOGI("Adding id: %d for %s\n", texdata.identifier, resourceName.c_str());
idMap.insert(std::make_pair(resourceName, texdata.identifier));
}
else {
idMap.insert(std::make_pair(resourceName, Textures::InvalidId));
idMap.insert(std::make_pair(resourceName, TEXTURES_INVALID_ID));
//loadedImages.insert(std::make_pair(InvalidId, texdata));
}
return Textures::InvalidId;
return TEXTURES_INVALID_ID;
}
TextureId Textures::assignTexture( const std::string& resourceName, const TextureData& img )
@@ -87,13 +72,14 @@ TextureId Textures::assignTexture( const std::string& resourceName, const Textur
bind(id);
if (MIPMAP) {
#ifdef TEXTURES_MIPMAP
glTexParameteri2(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri2(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
} else {
#else
glTexParameteri2(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri2(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
#endif
if (blur) {
glTexParameteri2(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri2(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

View File

@@ -6,9 +6,13 @@
#include <string>
#include <map>
#include <utility>
#include <IPlatform.h>
#include "gles.h"
#include "TextureData.h"
#define TEXTURES_INVALID_ID -1
#define TEXTURES_MIPMAP 0
class DynamicTexture;
class Options;
class AppPlatform;
@@ -24,20 +28,21 @@ typedef std::map<TextureId, TextureData> TextureImageMap;
class Textures
{
public:
Textures(Options* options_, AppPlatform* platform_);
Textures(Options& options, IPlatform& platform) : m_options(options), m_platform(platform) {}
~Textures();
void addDynamicTexture(DynamicTexture* dynamicTexture);
__inline void bind(TextureId id) {
if (id != Textures::InvalidId && lastBoundTexture != id) {
inline void bind(TextureId id) {
if (id != TEXTURES_INVALID_ID && lastBoundTexture != id) {
glBindTexture2(GL_TEXTURE_2D, id);
lastBoundTexture = id;
++textureChanges;
} else if (id == Textures::InvalidId){
} else if (id == TEXTURES_INVALID_ID){
LOGI("invalidId!\n");
}
}
TextureId loadTexture(const std::string& resourceName, bool inTextureFolder = true);
TextureId loadAndBindTexture(const std::string& resourceName);
@@ -49,28 +54,26 @@ public:
void clear();
void reloadAll();
__inline static bool isTextureIdValid(TextureId t) { return t != Textures::InvalidId; }
inline static bool isTextureIdValid(TextureId t) { return t != TEXTURES_INVALID_ID; }
private:
int smoothBlend(int c0, int c1);
int crispBlend(int c0, int c1);
public:
static bool MIPMAP;
static int textureChanges;
static const TextureId InvalidId;
private:
TextureMap idMap;
TextureImageMap loadedImages;
Options* options;
AppPlatform* platform;
Options& m_options;
IPlatform& m_platform;
bool clamp;
bool blur;
bool clamp = false;
bool blur = false;
int lastBoundTexture;
int lastBoundTexture = TEXTURES_INVALID_ID;
std::vector<DynamicTexture*> dynamicTextures;
};

View File

@@ -1,6 +1,6 @@
#include "TileRenderer.h"
#include "Chunk.h"
#include "../Minecraft.h"
#include <Minecraft.h>
#include "Tesselator.h"
#include "../../world/level/LevelSource.h"

View File

@@ -17,8 +17,8 @@ PlayerRenderer::PlayerRenderer( HumanoidModel* humanoidModel, float shadow )
: super(humanoidModel, shadow),
playerModel64(humanoidModel),
playerModel32(new HumanoidModel(0, 0, 64, 32)),
armorParts1(new HumanoidModel(1.0f, 0, 64, 64)),
armorParts2(new HumanoidModel(0.5f, 0, 64, 64))
armorParts1(new HumanoidModel(1.0f, 0, 64, 32)),
armorParts2(new HumanoidModel(0.5f, 0, 64, 32))
{
// default to legacy skin path until we know the exact texture size
model = playerModel32;
@@ -77,10 +77,10 @@ void PlayerRenderer::render(Entity* mob_, float x, float y, float z, float rot,
model = desired;
humanoidModel = desired;
}
// LOGI("[PlayerRenderer] %s: skin=%s, modelTex=%dx%d, desired=%s\n",
// ((Player*)mob)->name.c_str(), mob->getTexture().c_str(),
// humanoidModel->texWidth, humanoidModel->texHeight,
// (desired == playerModel64 ? "64" : "32"));
LOGI("[PlayerRenderer] %s: skin=%s, modelTex=%dx%d, desired=%s\n",
((Player*)mob)->name.c_str(), mob->getTexture().c_str(),
humanoidModel->texWidth, humanoidModel->texHeight,
(desired == playerModel64 ? "64" : "32"));
HumanoidMobRenderer::render(mob_, x, y, z, rot, a);
}

View File

@@ -1,6 +1,6 @@
#include "SoundEngine.h"
#include "../Options.h"
#include "../Minecraft.h"
#include <Minecraft.h>
#include "../../world/entity/Mob.h"

View File

@@ -1,6 +1,6 @@
#include "SoundEngine.h"
#include "../Options.h"
#include "../Minecraft.h"
#include <Minecraft.h>
#include "../../world/entity/Mob.h"
/*

59
src/gamemode/CreativeMode.cpp Executable file
View File

@@ -0,0 +1,59 @@
#include "CreativeMode.h"
#include <Minecraft.h>
#include <world/level/Level.h>
#include <world/entity/player/Abilities.h>
static const int DestructionTickDelay = 5;
CreativeMode::CreativeMode(Minecraft& minecraft)
: super(minecraft)
{
}
void CreativeMode::startDestroyBlock(Player* player, int x, int y, int z, int face) {
if(player->getCarriedItem() != NULL && player->getCarriedItem()->id == Item::bow->id)
return;
creativeDestroyBlock(player, x, y, z, face);
destroyDelay = DestructionTickDelay;
}
void CreativeMode::creativeDestroyBlock(Player* player, int x, int y, int z, int face) {
minecraft.level->extinguishFire(x, y, z, face);
destroyBlock(player, x, y, z, face);
}
void CreativeMode::continueDestroyBlock(Player* player, int x, int y, int z, int face) {
destroyDelay--;
if (destroyDelay <= 0) {
destroyDelay = DestructionTickDelay;
creativeDestroyBlock(player, x, y, z, face);
}
}
void CreativeMode::stopDestroyBlock(Player* player) {
destroyDelay = 0;
}
void CreativeMode::initAbilities( Abilities& abilities ) {
abilities.mayfly = true;
abilities.instabuild = true;
abilities.invulnerable = true;
}
bool CreativeMode::isCreativeType() {
return true;
}
void CreativeMode::releaseUsingItem( Player* player ) {
if(player->getCarriedItem() != NULL) {
int oldItemId = player->getCarriedItem()->id;
int oldAux = player->getAuxData();
super::releaseUsingItem(player);
if(player->getCarriedItem() != NULL && player->getCarriedItem()->id == oldItemId) {
player->getCarriedItem()->setAuxValue(oldAux);
}
} else {
super::releaseUsingItem(player);
}
}

View File

@@ -9,11 +9,11 @@ class CreativeMode: public GameMode
{
typedef GameMode super;
public:
CreativeMode(Minecraft* minecraft);
CreativeMode(Minecraft& minecraft);
void startDestroyBlock(int x, int y, int z, int face);
void continueDestroyBlock(int x, int y, int z, int face);
void stopDestroyBlock();
void startDestroyBlock(Player* player, int x, int y, int z, int face);
void continueDestroyBlock(Player* player, int x, int y, int z, int face);
void stopDestroyBlock(Player* player);
bool isCreativeType();
@@ -21,7 +21,7 @@ public:
void releaseUsingItem(Player* player);
private:
void creativeDestroyBlock(int x, int y, int z, int face);
void creativeDestroyBlock(Player* player, int x, int y, int z, int face);
};
#endif /*NET_MINECRAFT_CLIENT_GAMEMODE__CreativeMode_H__*/

View File

@@ -1,13 +1,8 @@
#include "CreatorMode.h"
#include "../Minecraft.h"
#include "../particle/ParticleEngine.h"
#include "../player/LocalPlayer.h"
#include "../renderer/LevelRenderer.h"
#include "../sound/SoundEngine.h"
#include "../../world/level/Level.h"
//#include "../../network/Packet.h"
#include "../../network/packet/RemoveBlockPacket.h"
#include "../../world/entity/player/Abilities.h"
#include "world/entity/player/Player.h"
#include "world/level/Level.h"
#include <Minecraft.h>
#include <world/entity/player/Abilities.h>
static const int DestructionTickDelay = 5;
@@ -41,7 +36,7 @@ private:
int _tickId;
};
CreatorMode::CreatorMode(Minecraft* minecraft)
CreatorMode::CreatorMode(Minecraft& minecraft)
: super(minecraft)
{
_creator = new Creator();
@@ -51,34 +46,35 @@ CreatorMode::~CreatorMode() {
delete _creator;
}
void CreatorMode::startDestroyBlock(int x, int y, int z, int face) {
if(minecraft->player->getCarriedItem() != NULL && minecraft->player->getCarriedItem()->id == Item::bow->id)
void CreatorMode::startDestroyBlock(Player* player, int x, int y, int z, int face) {
if(player->getCarriedItem() != NULL && player->getCarriedItem()->id == Item::bow->id)
return;
CreatorDestroyBlock(x, y, z, face);
CreatorDestroyBlock(player, x, y, z, face);
destroyDelay = DestructionTickDelay;
}
void CreatorMode::CreatorDestroyBlock(int x, int y, int z, int face) {
minecraft->level->extinguishFire(x, y, z, face);
destroyBlock(x, y, z, face);
void CreatorMode::CreatorDestroyBlock(Player* player, int x, int y, int z, int face) {
minecraft.level->extinguishFire(x, y, z, face);
destroyBlock(player, x, y, z, face);
}
void CreatorMode::continueDestroyBlock(int x, int y, int z, int face) {
void CreatorMode::continueDestroyBlock(Player* player, int x, int y, int z, int face) {
destroyDelay--;
if (destroyDelay <= 0) {
destroyDelay = DestructionTickDelay;
CreatorDestroyBlock(x, y, z, face);
CreatorDestroyBlock(player, x, y, z, face);
}
}
bool CreatorMode::useItemOn( Player* player, Level* level, ItemInstance* item, int x, int y, int z, int face, const Vec3& hit ) {
bool CreatorMode::useItemOn(Player* player, Level* level, ItemInstance* item, int x, int y, int z, int face, const Vec3& hit ) {
if (item && item->id == ((Item*)Item::sword_iron)->id)
_creator->addevent_blockUse(player->entityId, x, y, z, face);
return super::useItemOn(player, level, item, x, y, z, face, hit);
}
void CreatorMode::stopDestroyBlock() {
void CreatorMode::stopDestroyBlock(Player* player) {
destroyDelay = 0;
}
@@ -110,6 +106,6 @@ ICreator* CreatorMode::getCreator() {
}
void CreatorMode::tick() {
_creator->setTick(minecraft->level->getTime());
_creator->setTick(minecraft.level->getTime());
super::tick();
}

View File

@@ -4,7 +4,7 @@
//package net.minecraft.client.gamemode;
#include "GameMode.h"
#include "../../world/PosTranslator.h"
#include <world/PosTranslator.h>
class ICreator {
public:
@@ -102,12 +102,12 @@ class CreatorMode: public GameMode
{
typedef GameMode super;
public:
CreatorMode(Minecraft* minecraft);
CreatorMode(Minecraft& minecraft);
~CreatorMode();
void startDestroyBlock(int x, int y, int z, int face);
void continueDestroyBlock(int x, int y, int z, int face);
void stopDestroyBlock();
void startDestroyBlock(Player* player, int x, int y, int z, int face);
void continueDestroyBlock(Player* player, int x, int y, int z, int face);
void stopDestroyBlock(Player* player);
bool useItemOn(Player* player, Level* level, ItemInstance* item, int x, int y, int z, int face, const Vec3& hit);
@@ -120,7 +120,7 @@ public:
void releaseUsingItem(Player* player);
private:
void CreatorDestroyBlock(int x, int y, int z, int face);
void CreatorDestroyBlock(Player* player, int x, int y, int z, int face);
Creator* _creator;
};

View File

@@ -1,35 +1,15 @@
#include "GameMode.h"
#include "../Minecraft.h"
#include "../../network/packet/UseItemPacket.h"
#include "../../network/packet/PlayerActionPacket.h"
#include "../../world/level/Level.h"
#include "../../world/item/ItemInstance.h"
#include "../player/LocalPlayer.h"
#include "client/Options.h"
#ifndef STANDALONE_SERVER
#include "../sound/SoundEngine.h"
#include "../particle/ParticleEngine.h"
#endif
#include "../../network/RakNetInstance.h"
#include "../../network/packet/RemoveBlockPacket.h"
#ifndef STANDALONE_SERVER
#include "../renderer/LevelRenderer.h"
#endif
#include "../../world/level/material/Material.h"
#include <Minecraft.h>
#include <network/packet/UseItemPacket.h>
#include <network/packet/PlayerActionPacket.h>
#include <world/level/Level.h>
#include <world/item/ItemInstance.h>
#include <client/player/LocalPlayer.h>
#include <client/Options.h>
#include <network/RakNetInstance.h>
#include <network/packet/RemoveBlockPacket.h>
#include <world/level/material/Material.h>
GameMode::GameMode( Minecraft* minecraft)
: minecraft(minecraft),
destroyProgress(0),
oDestroyProgress(0),
destroyTicks(0),
destroyDelay(0)
{
}
/*virtual*/
Player* GameMode::createPlayer(Level* level) {
return new LocalPlayer(minecraft, level, minecraft->options.getStringValue(OPTIONS_USERNAME), level->dimension->id, isCreativeType());
}
/*virtual*/
void GameMode::interact(Player* player, Entity* entity) {
@@ -38,23 +18,24 @@ void GameMode::interact(Player* player, Entity* entity) {
/*virtual*/
void GameMode::attack(Player* player, Entity* entity) {
if (minecraft->level->adventureSettings.noPvP && entity->isPlayer())
if (minecraft.level->adventureSettings.noPvP && entity->isPlayer())
return;
if (minecraft->level->adventureSettings.noPvM && entity->isMob())
if (minecraft.level->adventureSettings.noPvM && entity->isMob())
return;
player->attack(entity);
}
/* virtual */
void GameMode::startDestroyBlock( int x, int y, int z, int face ) {
if(minecraft->player->getCarriedItem() != NULL && minecraft->player->getCarriedItem()->id == Item::bow->id)
void GameMode::startDestroyBlock(Player* player, int x, int y, int z, int face ) {
if(player->getCarriedItem() != NULL && player->getCarriedItem()->id == Item::bow->id)
return;
destroyBlock(x, y, z, face);
destroyBlock(player, x, y, z, face);
}
/*virtual*/
bool GameMode::destroyBlock(int x, int y, int z, int face) {
Level* level = minecraft->level;
bool GameMode::destroyBlock(Player* player, int x, int y, int z, int face) {
Level* level = minecraft.level;
Tile* oldTile = Tile::tiles[level->getTile(x, y, z)];
if (!oldTile)
return false;
@@ -65,22 +46,12 @@ bool GameMode::destroyBlock(int x, int y, int z, int face) {
return false;
}
}
#ifndef STANDALONE_SERVER
minecraft->particleEngine->destroy(x, y, z);
#endif
int data = level->getData(x, y, z);
bool changed = level->setTile(x, y, z, 0);
if (changed) {
#ifndef STANDALONE_SERVER
minecraft->soundEngine->play(oldTile->soundType->getBreakSound(), x + 0.5f, y + 0.5f, z + 0.5f, (oldTile->soundType->getVolume() + 1) / 2, oldTile->soundType->getPitch() * 0.8f);
#endif
oldTile->destroy(level, x, y, z, data);
if (minecraft->options.getBooleanValue(OPTIONS_DESTROY_VIBRATION)) minecraft->platform()->vibrate(24);
if (minecraft->isOnline()) {
RemoveBlockPacket packet(minecraft->player, x, y, z);
minecraft->raknetInstance->send(packet);
}
minecraft.onBlockDestroyed(player, x, y, z, face);
}
return changed;
}
@@ -92,7 +63,7 @@ bool GameMode::useItemOn(Player* player, Level* level, ItemInstance* item, int x
item = player->inventory->getSelected();
if(level->isClientSide) {
UseItemPacket packet(x, y, z, face, item, player->entityId, clickX, clickY, clickZ);
minecraft->raknetInstance->send(packet);
minecraft.raknetInstance->send(packet);
}
int t = level->getTile(x, y, z);
if (t == Tile::invisible_bedrock->id) return false;
@@ -118,7 +89,7 @@ bool GameMode::useItem( Player* player, Level* level, ItemInstance* item ) {
ItemInstance* itemInstance = item->use(level, player);
if(level->isClientSide) {
UseItemPacket packet(item, player->entityId, player->aimDirection);
minecraft->raknetInstance->send(packet);
minecraft.raknetInstance->send(packet);
}
if (itemInstance != item || (itemInstance != NULL && itemInstance->count != oldCount)) {
//player.inventory.items[player.inventory.selected] = itemInstance;
@@ -149,9 +120,9 @@ void GameMode::initPlayer( Player* player ) {
}
void GameMode::releaseUsingItem(Player* player){
if(minecraft->level->isClientSide) {
if(minecraft.level->isClientSide) {
PlayerActionPacket packet(PlayerActionPacket::RELEASE_USE_ITEM, 0, 0, 0, 0, player->entityId);
minecraft->raknetInstance->send(packet);
minecraft.raknetInstance->send(packet);
}
player->releaseUsingItem();
}
@@ -160,15 +131,3 @@ void GameMode::tick() {
oDestroyProgress = destroyProgress;
}
void GameMode::render( float a ) {
#ifndef STANDALONE_SERVER
if (destroyProgress <= 0) {
minecraft->gui.progress = 0;
minecraft->levelRenderer->destroyProgress = 0;
} else {
float dp = oDestroyProgress + (destroyProgress - oDestroyProgress) * a;
minecraft->gui.progress = dp;
minecraft->levelRenderer->destroyProgress = dp;
}
#endif
}

View File

@@ -3,7 +3,7 @@
//package net.minecraft.client.gamemode;
#include "../../world/level/tile/Tile.h"
#include <world/level/tile/Tile.h>
class ItemInstance;
class Minecraft;
@@ -11,23 +11,22 @@ class Level;
class Player;
class Abilities;
class GameMode
{
class GameMode {
protected:
Minecraft* minecraft;
Minecraft& minecraft;
public:
GameMode(Minecraft* minecraft);
GameMode(Minecraft& minecraft) : minecraft(minecraft) {}
virtual ~GameMode() {}
virtual void initLevel(Level* level) {}
virtual void startDestroyBlock(int x, int y, int z, int face);
virtual bool destroyBlock(int x, int y, int z, int face);
virtual void continueDestroyBlock(int x, int y, int z, int face) = 0;
virtual void stopDestroyBlock() {}
virtual void startDestroyBlock(Player* player, int x, int y, int z, int face);
virtual bool destroyBlock(Player* player, int x, int y, int z, int face);
virtual void continueDestroyBlock(Player* player, int x, int y, int z, int face) = 0;
virtual void stopDestroyBlock(Player* player) {}
virtual void tick();
virtual void render(float a);
virtual float getPickRange();
/* void postLevelGen(LevelGen levelGen, Level level) {} */
@@ -35,7 +34,6 @@ public:
virtual bool useItem(Player* player, Level* level, ItemInstance* item);
virtual bool useItemOn(Player* player, Level* level, ItemInstance* item, int x, int y, int z, int face, const Vec3& hit);
virtual Player* createPlayer(Level* level);
virtual void initPlayer(Player* player);
virtual void adjustPlayer(Player* player) {}
virtual bool canHurtPlayer() { return false; }
@@ -53,11 +51,11 @@ public:
virtual void releaseUsingItem(Player* player);
float oDestroyProgress;
float destroyProgress;
float oDestroyProgress = 0;
float destroyProgress = 0;
protected:
int destroyTicks;
int destroyDelay;
int destroyTicks = 0;
int destroyDelay = 0;
};
#endif /*NET_MINECRAFT_CLIENT_GAMEMODE__GameMode_H__*/

93
src/gamemode/SurvivalMode.cpp Executable file
View File

@@ -0,0 +1,93 @@
#include "SurvivalMode.h"
#include <Minecraft.h>
#include <world/level/Level.h>
#include <world/entity/player/Abilities.h>
SurvivalMode::SurvivalMode( Minecraft& minecraft )
: super(minecraft),
xDestroyBlock(-1),
yDestroyBlock(-1),
zDestroyBlock(-1)
{
}
void SurvivalMode::continueDestroyBlock(Player* player, int x, int y, int z, int face ) {
if (destroyDelay > 0) {
destroyDelay--;
return;
}
if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) {
int t = minecraft.level->getTile(x, y, z);
if (t == 0) return;
Tile* tile = Tile::tiles[t];
destroyProgress += tile->getDestroyProgress(player);
if ((++destroyTicks & 3) == 1) {
#ifndef STANDALONE_SERVER
if (tile != NULL) {
minecraft->soundEngine->play(tile->soundType->getStepSound(), x + 0.5f, y + 0.5f, z + 0.5f, (tile->soundType->getVolume() + 1) / 8, tile->soundType->getPitch() * 0.5f);
}
#endif
}
if (destroyProgress >= 1) {
destroyBlock(player, x, y, z, face);
destroyProgress = 0;
oDestroyProgress = 0;
destroyTicks = 0;
destroyDelay = 5;
}
} else {
destroyProgress = 0;
oDestroyProgress = 0;
destroyTicks = 0;
xDestroyBlock = x;
yDestroyBlock = y;
zDestroyBlock = z;
}
}
bool SurvivalMode::destroyBlock(Player* player, int x, int y, int z, int face ) {
int t = minecraft.level->getTile(x, y, z);
int data = minecraft.level->getData(x, y, z);
bool changed = GameMode::destroyBlock(player, x, y, z, face);
bool couldDestroy = player->canDestroy(Tile::tiles[t]);
ItemInstance* item = player->inventory->getSelected();
if (item != NULL) {
item->mineBlock(t, x, y, z);
if (item->count == 0) {
//item->snap(minecraft->player);
player->inventory->clearSlot(player->inventory->selected);
}
}
if (changed && couldDestroy) {
ItemInstance instance(t, 1, data);
Tile::tiles[t]->playerDestroy(minecraft.level, player, x, y, z, data);
}
return changed;
}
void SurvivalMode::stopDestroyBlock(Player* player) {
destroyProgress = 0;
destroyDelay = 0;
}
void SurvivalMode::initAbilities( Abilities& abilities ) {
abilities.flying = false;
abilities.mayfly = false;
abilities.instabuild = false;
abilities.invulnerable = false;
}
void SurvivalMode::startDestroyBlock(Player* player, int x, int y, int z, int face ) {
if(player->getCarriedItem() != NULL && player->getCarriedItem()->id == Item::bow->id)
return;
int t = minecraft.level->getTile(x, y, z);
if (t > 0 && destroyProgress == 0) Tile::tiles[t]->attack(minecraft.level, x, y, z, player);
if (t > 0 && Tile::tiles[t]->getDestroyProgress(player) >= 1)
destroyBlock(player, x, y, z, face);
}

View File

@@ -10,12 +10,12 @@ class SurvivalMode: public GameMode
{
typedef GameMode super;
public:
SurvivalMode(Minecraft* minecraft);
SurvivalMode(Minecraft& minecraft);
bool destroyBlock(int x, int y, int z, int face);
void startDestroyBlock(int x, int y, int z, int face);
void continueDestroyBlock(int x, int y, int z, int face);
void stopDestroyBlock();
bool destroyBlock(Player* player, int x, int y, int z, int face);
void startDestroyBlock(Player* player, int x, int y, int z, int face);
void continueDestroyBlock(Player* player, int x, int y, int z, int face);
void stopDestroyBlock(Player* player);
bool canHurtPlayer() { return true; }

View File

@@ -1,6 +1,6 @@
#include "I18n.h"
#include <sstream>
#include "../AppPlatform.h"
#include <IPlatform.h>
#include "../util/StringUtils.h"
#include "../world/level/tile/Tile.h"
#include "../world/item/ItemInstance.h"
@@ -8,8 +8,7 @@
I18n::Map I18n::_strings;
void I18n::loadLanguage( AppPlatform* platform, const std::string& languageCode )
{
void I18n::loadLanguage(IPlatform& platform, const std::string& languageCode ) {
_strings.clear();
fillTranslations(platform, "lang/en_US.lang", true);
@@ -26,8 +25,7 @@ bool I18n::get( const std::string& id, std::string& out ) {
return false;
}
std::string I18n::get( const std::string& id )
{
std::string I18n::get( const std::string& id ) {
Map::const_iterator cit = _strings.find(id);
if (cit != _strings.end())
return cit->second;
@@ -35,13 +33,11 @@ std::string I18n::get( const std::string& id )
return id + '<';//lang.getElement(id);
}
void I18n::fillTranslations( AppPlatform* platform, const std::string& filename, bool overwrite )
{
BinaryBlob blob = platform->readAssetFile(filename);
if (!blob.data || blob.size <= 0)
return;
void I18n::fillTranslations(IPlatform& platform, const std::string& filename, bool overwrite ) {
auto blob = platform.readAssetFile(filename);
if (blob.empty()) return;
std::string data((const char*)blob.data, blob.size);
std::string data(blob.begin(), blob.end());
std::stringstream fin(data, std::ios_base::in);
std::string line;
@@ -58,12 +54,9 @@ void I18n::fillTranslations( AppPlatform* platform, const std::string& filename,
std::string value = Util::stringTrim(line.substr(spos + 1));
_strings.insert( std::make_pair(key, value ) );
}
delete[] blob.data;
}
std::string I18n::getDescriptionString( const ItemInstance& item )
{
std::string I18n::getDescriptionString( const ItemInstance& item ) {
// Convert to lower. Normally std::transform would be used, but tolower might be
// implemented with a macro in certain C-implementations -> messing stuff up
const std::string desc = item.getDescriptionId();

View File

@@ -3,17 +3,17 @@
//package net.minecraft.locale;
#include "IPlatform.h"
#include <map>
#include <string>
class AppPlatform;
class ItemInstance;
class I18n
{
class I18n {
typedef std::map<std::string, std::string> Map;
public:
static void loadLanguage(AppPlatform* platform, const std::string& languageCode);
static void loadLanguage(IPlatform& platform, const std::string& languageCode);
static bool get(const std::string& id, std::string& out);
static std::string get(const std::string& id);
@@ -24,7 +24,7 @@ public:
static std::string getDescriptionString( const ItemInstance& item );
private:
static void fillTranslations(AppPlatform* platform, const std::string& filename, bool overwrite);
static void fillTranslations(IPlatform& platform, const std::string& filename, bool overwrite);
static Map _strings;
};

View File

@@ -1,46 +1,9 @@
/**
Entry point for cross compilation.
#include "MinecraftClient.h"
This is ugly, yes. But it will change in the "half near" future
to a more correct system of solving the cross-platform entry
point "problem" */
#define _SECURE_SCL 0
// #ifdef WIN32
// #include "vld.h"
// #endif
#include "platform/log.h"
#ifdef WIN32
#endif
#ifdef ANDROID
#endif
#include "NinecraftApp.h"
#define MAIN_CLASS NinecraftApp
// #ifdef PLATFORM_WINDOWS
// #include "main_win32.h"
// #endif
#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB)
#include "main_glfw.h"
#endif
#ifdef PLATFORM_ANDROID
#ifdef PRE_ANDROID23
#include "main_android_java.h"
#else
#include "main_android.h"
#endif
#endif
#ifdef PLATFORM_RPI
#include "main_rpi.h"
#endif
int main() {
MinecraftClient minecraft(App::CreatePlatform());
minecraft.run();
return 0;
}

View File

@@ -250,10 +250,10 @@ static void pointerMove(int pointerId, int x, int y) {
Multitouch::feed(0, 0, x, y, pointerId);
}
__inline static const float padXtoSigned(int x) {
inline static const float padXtoSigned(int x) {
return (x - 483.0f) * 0.002070393374741201f;
}
__inline static const float padYtoSigned(int y) {
inline static const float padYtoSigned(int y) {
return (y - 180.0f) * 0.005555555555555556f;
}

View File

@@ -1,20 +1,22 @@
#include <iostream>
#include "NinecraftApp.h"
#include "AppPlatform.h"
#include <IPlatform.h>
#include <memory>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include "MinecraftServer.h"
#include "platform/server/PlatformServer.h"
#include "world/level/LevelSettings.h"
#include "world/level/Level.h"
#include "server/ArgumentsSettings.h"
#include "platform/time.h"
#include "SharedConstants.h"
#define MAIN_CLASS NinecraftApp
static App* g_app = 0;
static int g_exitCode = 0;
void signal_callback_handler(int signum) {
std::cout << "Signum caught: " << signum << std::endl;
if(signum == 2 || signum == 3){ // SIGINT || SIGQUIT
@@ -29,6 +31,7 @@ void signal_callback_handler(int signum) {
int main(int numArguments, char* pszArgs[]) {
ArgumentsSettings aSettings(numArguments, pszArgs);
if(aSettings.getShowHelp()) {
ArgumentsSettings defaultSettings(0, NULL);
printf("Minecraft Pockect Edition Server %s\n", Common::getGameVersionString("").c_str());
@@ -43,34 +46,34 @@ int main(int numArguments, char* pszArgs[]) {
printf("-------------------------------------------------------\n");
return 0;
}
printf("Level Name: %s\n", aSettings.getLevelName().c_str());
AppContext appContext;
appContext.platform = new AppPlatform();
App* app = new MAIN_CLASS();
signal(SIGINT, signal_callback_handler);
g_app = app;
((MAIN_CLASS*)g_app)->externalStoragePath = aSettings.getExternalPath();
((MAIN_CLASS*)g_app)->externalCacheStoragePath = aSettings.getCachePath();
g_app->init(appContext);
printf("Level Name: %s\n", aSettings.getLevelName().c_str());
MinecraftServer server(App::CreatePlatform());
signal(SIGINT, signal_callback_handler);
g_app = &server;
server.externalStoragePath = aSettings.getExternalPath();
server.externalCacheStoragePath = aSettings.getCachePath();
server.init();
LevelSettings settings(getEpochTimeS(), GameType::Creative);
float startTime = getTimeS();
((MAIN_CLASS*)g_app)->selectLevel(aSettings.getLevelDir(), aSettings.getLevelName(), settings);
((MAIN_CLASS*)g_app)->hostMultiplayer(aSettings.getPort());
server.selectLevel(aSettings.getLevelDir(), aSettings.getLevelName(), settings);
server.hostMultiplayer(aSettings.getPort());
std::cout << "Level has been generated in " << getTimeS() - startTime << std::endl;
((MAIN_CLASS*)g_app)->level->saveLevelData();
server.level->saveLevelData();
std::cout << "Level has been saved!" << std::endl;
while(!app->wantToQuit()) {
app->update();
while(!server.wantToQuit()) {
server.update();
//pthread_yield();
sleepMs(20);
}
((MAIN_CLASS*)g_app)->level->saveLevelData();
delete app;
appContext.platform->finish();
delete appContext.platform;
server.level->saveLevelData();
std::cout << "Quit correctly" << std::endl;
return g_exitCode;

View File

@@ -2,6 +2,7 @@
#define MAIN_GLFW_H__
#include "App.h"
#include "NinecraftApp.h"
#include "client/renderer/entity/PlayerRenderer.h"
#include "client/renderer/gles.h"
#include "GLFW/glfw3.h"
@@ -16,201 +17,56 @@
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
static App* g_app = 0;
int transformKey(int glfwkey) {
if (glfwkey >= GLFW_KEY_F1 && glfwkey <= GLFW_KEY_F12) {
return glfwkey - 178;
}
// void loop() {
// using clock = std::chrono::steady_clock;
// auto frameStart = clock::now();
switch (glfwkey) {
case GLFW_KEY_ESCAPE: return Keyboard::KEY_ESCAPE;
case GLFW_KEY_TAB: return Keyboard::KEY_TAB;
case GLFW_KEY_BACKSPACE: return Keyboard::KEY_BACKSPACE;
case GLFW_KEY_LEFT_SHIFT: return Keyboard::KEY_LSHIFT;
case GLFW_KEY_ENTER: return Keyboard::KEY_RETURN;
case GLFW_KEY_LEFT_CONTROL: return Keyboard::KEY_LEFT_CTRL;
default: return glfwkey;
}
}
// g_app->update();
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if(action == GLFW_REPEAT) return;
// glfwSwapBuffers(((AppPlatform_glfw*)g_app->platform())->window);
// glfwPollEvents();
if (key == GLFW_KEY_F11 && action == GLFW_PRESS) {
GLFWmonitor* monitor = glfwGetWindowMonitor(window);
if (monitor) {
// Currently fullscreen → go windowed
glfwSetWindowMonitor(window, NULL, 80, 80, 854, 480, 0);
} else {
// Currently windowed → go fullscreen on primary monitor
GLFWmonitor* primary = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(primary);
glfwSetWindowMonitor(window, primary, 0, 0, mode->width, mode->height, mode->refreshRate);
}
return;
}
Keyboard::feed(transformKey(key), action);
}
void character_callback(GLFWwindow* window, unsigned int codepoint) {
Keyboard::feedText(codepoint);
}
static void cursor_position_callback(GLFWwindow* window, double xpos, double ypos) {
static double lastX = 0.0, lastY = 0.0;
static bool firstMouse = true;
if (firstMouse) {
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
double deltaX = xpos - lastX;
double deltaY = ypos - lastY;
lastX = xpos;
lastY = ypos;
if (glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED) {
Mouse::feed(0, 0, xpos, ypos, deltaX, deltaY);
} else {
Mouse::feed( MouseAction::ACTION_MOVE, 0, xpos, ypos);
}
Multitouch::feed(0, 0, xpos, ypos, 0);
}
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) {
if(action == GLFW_REPEAT) return;
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
if (button == GLFW_MOUSE_BUTTON_LEFT) {
Mouse::feed( MouseAction::ACTION_LEFT, action, xpos, ypos);
Multitouch::feed(1, action, xpos, ypos, 0);
}
if (button == GLFW_MOUSE_BUTTON_RIGHT) {
Mouse::feed( MouseAction::ACTION_RIGHT, action, xpos, ypos);
}
}
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) {
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
Mouse::feed(3, 0, xpos, ypos, 0, yoffset);
}
void window_size_callback(GLFWwindow* window, int width, int height) {
if (g_app) g_app->setSize(width, height);
}
void error_callback(int error, const char* desc) {
printf("Error: %s\n", desc);
}
void loop() {
using clock = std::chrono::steady_clock;
auto frameStart = clock::now();
g_app->update();
glfwSwapBuffers(((AppPlatform_glfw*)g_app->platform())->window);
glfwPollEvents();
glfwSwapInterval(((MAIN_CLASS*)g_app)->options.getBooleanValue(OPTIONS_VSYNC) ? 1 : 0);
if(((MAIN_CLASS*)g_app)->options.getBooleanValue(OPTIONS_LIMIT_FRAMERATE)) {
auto frameEnd = clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(frameEnd - frameStart);
auto target = std::chrono::microseconds(33333); // ~30 fps
if(elapsed < target)
std::this_thread::sleep_for(target - elapsed);
}
}
// glfwSwapInterval(((MAIN_CLASS*)g_app)->options.getBooleanValue(OPTIONS_VSYNC) ? 1 : 0);
// if(((MAIN_CLASS*)g_app)->options.getBooleanValue(OPTIONS_LIMIT_FRAMERATE)) {
// auto frameEnd = clock::now();
// auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(frameEnd - frameStart);
// auto target = std::chrono::microseconds(33333); // ~30 fps
// if(elapsed < target)
// std::this_thread::sleep_for(target - elapsed);
// }
// }
int main(void) {
AppContext appContext;
#ifndef STANDALONE_SERVER
// Platform init.
appContext.platform = new AppPlatform_glfw();
#if defined(DEBUG) && defined(__EMSCRIPTEN__)
EM_ASM({
console.log(FS.readdir("/"));
console.log(FS.readdir("/data"));
console.log(FS.readdir("/data/images"));
});
#endif
appContext.platform = new AppPlatformGlfw();
glfwSetErrorCallback(error_callback);
AppPlatformGlfw* platform = (AppPlatformGlfw*)appContext.platform;
if (!glfwInit()) {
if (!platform->init()) {
return 1;
}
glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_NATIVE_CONTEXT_API);
#ifndef __EMSCRIPTEN__
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
#else
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 1);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
#endif
App* app = (App*)new NinecraftApp();
app->init(appContext);
app->setSize(platform->getScreenWidth(), platform->getScreenHeight());
AppPlatform_glfw* platform = (AppPlatform_glfw*)appContext.platform;
platform->window = glfwCreateWindow(appContext.platform->getScreenWidth(), appContext.platform->getScreenHeight(), "Minecraft PE 0.6.1", NULL, NULL);
if (platform->window == NULL) {
return 1;
}
glfwSetKeyCallback(platform->window, key_callback);
glfwSetCharCallback(platform->window, character_callback);
glfwSetCursorPosCallback(platform->window, cursor_position_callback);
glfwSetMouseButtonCallback(platform->window, mouse_button_callback);
glfwSetScrollCallback(platform->window, scroll_callback);
glfwSetWindowSizeCallback(platform->window, window_size_callback);
glfwMakeContextCurrent(platform->window);
#ifndef __EMSCRIPTEN__
gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
glfwSwapInterval(0);
#endif
#endif
App* app = new MAIN_CLASS();
g_app = app;
((MAIN_CLASS*)g_app)->externalStoragePath = ".";
((MAIN_CLASS*)g_app)->externalCacheStoragePath = ".";
g_app->init(appContext);
g_app->setSize(appContext.platform->getScreenWidth(), appContext.platform->getScreenHeight());
auto loop = [app]() {
app->update();
};
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
// Main event loop
while(!glfwWindowShouldClose(platform->window) && !app->wantToQuit()) {
while(!app->wantToQuit()) {
loop();
}
#endif
delete app;
#ifndef STANDALONE_SERVER
// Exit.
glfwDestroyWindow(platform->window);
glfwTerminate();
#endif
appContext.platform->finish();
delete appContext.platform;

View File

@@ -115,7 +115,7 @@ public:
return it->second;
}
__inline bool contains(const std::string& name) const {
inline bool contains(const std::string& name) const {
return tags.find(name) != tags.end();
}
bool contains(const std::string& name, int type) const {

View File

@@ -1,6 +1,7 @@
#include "ClientSideNetworkHandler.h"
#include <MinecraftClient.h>
#include "client/Options.h"
#include "gamemode/GameMode.h"
#include "packet/PacketInclude.h"
#include "RakNetInstance.h"
#include "../world/level/chunk/ChunkSource.h"
@@ -8,11 +9,7 @@
#include "../world/level/storage/LevelStorageSource.h"
#include "../world/entity/player/Player.h"
#include "../world/entity/player/Inventory.h"
#include "../client/Minecraft.h"
#include "../client/gamemode/GameMode.h"
#ifndef STANDALONE_SERVER
#include "../client/gui/screens/DisconnectionScreen.h"
#endif
#include <Minecraft.h>
#include "../client/player/LocalPlayer.h"
#include "../client/multiplayer/MultiPlayerLevel.h"
#include "../client/player/input/KeyboardInput.h"
@@ -22,9 +19,6 @@
#include "../world/level/Explosion.h"
#include "../world/level/tile/entity/FurnaceTileEntity.h"
#include "../world/inventory/BaseContainerMenu.h"
#ifndef STANDALONE_SERVER
#include "../client/particle/TakeAnimationParticle.h"
#endif
#include "../world/entity/EntityFactory.h"
#include "../world/entity/item/PrimedTnt.h"
#include "../world/entity/projectile/Arrow.h"
@@ -35,12 +29,9 @@
static MultiPlayerLevel* mpcast(Level* l) { return (MultiPlayerLevel*) l; }
ClientSideNetworkHandler::ClientSideNetworkHandler(Minecraft* minecraft, IRakNetInstance* raknetInstance)
ClientSideNetworkHandler::ClientSideNetworkHandler(MinecraftClient& minecraft, IRakNetInstance* raknetInstance)
: minecraft(minecraft),
raknetInstance(raknetInstance),
level(NULL),
requestNextChunkPosition(0),
requestNextChunkIndex(0)
raknetInstance(raknetInstance)
{
rakPeer = raknetInstance->getPeer();
}
@@ -86,7 +77,7 @@ void ClientSideNetworkHandler::onConnect(const RakNet::RakNetGUID& hostGuid)
serverGuid = hostGuid;
clearChunksLoaded();
LoginPacket packet(minecraft->options.getStringValue(OPTIONS_USERNAME).c_str(), SharedConstants::NetworkProtocolVersion);
LoginPacket packet(minecraft.options().getStringValue(OPTIONS_USERNAME).c_str(), SharedConstants::NetworkProtocolVersion);
raknetInstance->send(packet);
}
@@ -103,14 +94,14 @@ void ClientSideNetworkHandler::onDisconnect(const RakNet::RakNetGUID& guid)
level->isClientSide = false;
for (int i = (int)level->players.size()-1; i >= 0; --i ) {
Player* p = level->players[i];
if (p != minecraft->player) {
if (p != minecraft.getPlayer()) {
p->reallyRemoveIfPlayer = true;
level->removeEntity(p);
}
}
}
#ifndef STANDALONE_SERVER
minecraft->gui.addMessage("Disconnected from server");
minecraft.gui.addMessage("Disconnected from server");
#endif
}
@@ -123,13 +114,13 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, LoginSta
if (packet->status == LoginStatus::Failed_ClientOld) {
LOGI("Disconnect! Client is outdated!\n");
#ifndef STANDALONE_SERVER
minecraft->setScreen(new DisconnectionScreen("Could not connect: Outdated client!"));
minecraft.setScreen(new DisconnectionScreen("Could not connect: Outdated client!"));
#endif
}
if (packet->status == LoginStatus::Failed_ServerOld) {
LOGI("Disconnect! Server is outdated!\n");
#ifndef STANDALONE_SERVER
minecraft->setScreen(new DisconnectionScreen("Could not connect: Outdated server!"));
minecraft.setScreen(new DisconnectionScreen("Could not connect: Outdated server!"));
#endif
}
}
@@ -141,13 +132,13 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, StartGam
#ifdef RPI
if (packet->gameType != GameType::Creative) {
minecraft->setScreen(new DisconnectionScreen("Could not connect: Incompatible server!"));
minecraft.setScreen(new DisconnectionScreen("Could not connect: Incompatible server!"));
return;
}
#endif
const std::string& levelId = LevelStorageSource::TempLevelId;
LevelStorageSource* storageSource = minecraft->getLevelSource();
LevelStorageSource* storageSource = minecraft.getLevelSource();
storageSource->deleteLevel(levelId);
//level = new Level(storageSource->selectLevel(levelId, true), "temp", packet->levelSeed, SharedConstants::StorageVersion);
MultiPlayerLevel* level = new MultiPlayerLevel(
@@ -158,22 +149,22 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, StartGam
level->isClientSide = true;
bool isCreative = (packet->gameType == GameType::Creative);
LocalPlayer* player = new LocalPlayer(minecraft, level, minecraft->options.getStringValue(OPTIONS_USERNAME), level->dimension->id, isCreative);
LocalPlayer* player = new LocalPlayer(minecraft, level, minecraft.options().getStringValue(OPTIONS_USERNAME), level->dimension->id, isCreative);
player->owner = rakPeer->GetMyGUID();
player->entityId = packet->entityId;
player->moveTo(packet->x, packet->y, packet->z, player->yRot, player->xRot);
LOGI("new pos: %f, %f [%f - %f]\n", player->x, player->z, player->bb.y0, player->bb.y1);
minecraft->setLevel(level, "ClientSideNetworkHandler -> setLevel", player);
minecraft->setIsCreativeMode(isCreative);
minecraft.setLevel(level, "ClientSideNetworkHandler -> setLevel", player);
minecraft.setIsCreativeMode(isCreative);
}
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, MessagePacket* packet)
{
LOGI("MessagePacket\n");
#ifndef STANDALONE_SERVER
minecraft->gui.addMessage(packet->message.C_String());
minecraft.gui.addMessage(packet->message.C_String());
#endif
}
@@ -270,8 +261,8 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, AddPlaye
}
LOGI("AddPlayerPacket\n");
Player* player = new RemotePlayer(level, minecraft->isCreativeMode());
minecraft->gameMode->initAbilities(player->abilities);
Player* player = new RemotePlayer(level, minecraft.isCreativeMode());
minecraft.gameMode->initAbilities(player->abilities);
player->entityId = packet->entityId;
level->addEntity(player);
@@ -292,12 +283,12 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, AddPlaye
std::string message = packet->name.C_String();
message += " joined the game";
#ifndef STANDALONE_SERVER
minecraft->gui.addMessage(message);
minecraft.gui.addMessage(message);
#endif
}
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, RemovePlayerPacket* packet) {
if (!level || source == minecraft->player->owner) return;
if (!level || source == minecraft.getPlayer()->owner) return;
if (Player* player = findPlayer(level, packet->entityId, &packet->owner)) {
player->reallyRemoveIfPlayer = true;
@@ -316,7 +307,7 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, RemovePl
//std::string message = packet->name.C_String();
//message += " joined the game";
//minecraft->gui.addMessage(message);
//minecraft.gui.addMessage(message);
}
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, RemoveEntityPacket* packet)
@@ -324,7 +315,7 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, RemoveEn
if (!level) return;
Entity* entity = level->getEntity(packet->entityId);
LOGI("RemoveEntityPacket %p %p, %d\n", entity, minecraft->player, entity?(int)(entity->isPlayer()): -1);
LOGI("RemoveEntityPacket %p %p, %d\n", entity, minecraft.getPlayer(), entity?(int)(entity->isPlayer()): -1);
if (!entity) return;
level->removeEntity(entity);
@@ -355,7 +346,7 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, TakeItem
item = ((ItemEntity*) e)->item;
#ifndef STANDALONE_SERVER
if (Entity* to = level->getEntity(packet->playerId))
minecraft->particleEngine->add(new TakeAnimationParticle(level, (ItemEntity*)e, to, -0.5f));
minecraft.particleEngine->add(new TakeAnimationParticle(level, (ItemEntity*)e, to, -0.5f));
#endif
}
else if (e->getEntityTypeId() == EntityTypes::IdArrow)
@@ -365,10 +356,10 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, TakeItem
return;
// try take it and if we don't have space; re-throw it
if (minecraft->player->entityId == packet->playerId
&& !minecraft->player->inventory->add(&item)) {
if (minecraft.getPlayer()->entityId == packet->playerId
&& !minecraft.getPlayer()->inventory->add(&item)) {
DropItemPacket dropPacket(packet->playerId, item);
minecraft->raknetInstance->send(dropPacket);
minecraft.raknetInstance->send(dropPacket);
}
level->playSound(e, "random.pop", 0.2f, 1.0f * 2.f);
}
@@ -438,16 +429,16 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ExplodeP
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, LevelEventPacket* packet) {
if (!level) return;
if(packet->eventId == LevelEvent::ALL_PLAYERS_SLEEPING) {
minecraft->player->setAllPlayersSleeping();
minecraft.getPlayer()->setAllPlayersSleeping();
}
else {
minecraft->level->levelEvent(NULL, packet->eventId, packet->x, packet->y, packet->z, packet->data);
minecraft.level->levelEvent(NULL, packet->eventId, packet->x, packet->y, packet->z, packet->data);
}
}
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, TileEventPacket* packet) {
if (!level) return;
minecraft->level->tileEvent(packet->x, packet->y, packet->z, packet->b0, packet->b1);
minecraft.level->tileEvent(packet->x, packet->y, packet->z, packet->b0, packet->b1);
}
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, EntityEventPacket* packet) {
@@ -631,7 +622,7 @@ void ClientSideNetworkHandler::arrangeRequestChunkOrder() {
int cz = CHUNK_CACHE_WIDTH / 2;
// If player exists, let's sort around him
Player* p = minecraft? minecraft->player : NULL;
Player* p = minecraft.getPlayer();
if (p) {
cx = Mth::floor(p->x / (float)CHUNK_WIDTH);
cz = Mth::floor(p->z / (float)CHUNK_DEPTH);
@@ -717,9 +708,9 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, Interact
{
Player* player = (Player*) src;
if (InteractPacket::Attack == packet->action)
minecraft->gameMode->attack(player, entity);
minecraft.gameMode->attack(player, entity);
if (InteractPacket::Interact == packet->action)
minecraft->gameMode->interact(player, entity);
minecraft.gameMode->interact(player, entity);
}
}
@@ -759,7 +750,7 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, AnimateP
return;
// Own player - Then don't play... :
if (minecraft->player->entityId == packet->entityId) {
if (minecraft.getPlayer()->entityId == packet->entityId) {
if (packet->action == AnimatePacket::Swing) return;
}
@@ -788,26 +779,26 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, UseItemP
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, SetHealthPacket* packet)
{
if (!level || !minecraft->player)
if (!level || !minecraft.getPlayer())
return;
minecraft->player->hurtTo(packet->health);
minecraft.getPlayer()->hurtTo(packet->health);
}
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, SetSpawnPositionPacket* packet) {
if (!level || !minecraft || !minecraft->player) return;
if (!level || !minecraft.getPlayer()) return;
if (!level->inRange(packet->x, packet->y, packet->z)) return;
minecraft->player->setRespawnPosition(Pos(packet->x, packet->y, packet->z));
minecraft.getPlayer()->setRespawnPosition(Pos(packet->x, packet->y, packet->z));
level->getLevelData()->setSpawn(packet->x, packet->y, packet->z);
}
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, HurtArmorPacket* packet) {
if (!level || !minecraft->player) {
if (!level || !minecraft.getPlayer()) {
return;
}
minecraft->player->hurtArmor(packet->dmg);
minecraft.getPlayer()->hurtArmor(packet->dmg);
}
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, RespawnPacket* packet)
@@ -820,43 +811,43 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, RespawnP
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ContainerOpenPacket* packet)
{
if (!level || !minecraft || !minecraft->player)
if (!level)
return;
if (packet->type == ContainerType::FURNACE) {
FurnaceTileEntity* te = new FurnaceTileEntity();
te->clientSideOnly = true;
minecraft->player->openFurnace(te);
if (minecraft->player->containerMenu)
minecraft->player->containerMenu->containerId = packet->containerId;
minecraft.getPlayer()->openFurnace(te);
if (minecraft.getPlayer()->containerMenu)
minecraft.getPlayer()->containerMenu->containerId = packet->containerId;
}
if (packet->type == ContainerType::CONTAINER) {
ChestTileEntity* te = new ChestTileEntity();
te->clientSideOnly = true;
minecraft->player->openContainer(te);
if (minecraft->player->containerMenu)
minecraft->player->containerMenu->containerId = packet->containerId;
minecraft.getPlayer()->openContainer(te);
if (minecraft.getPlayer()->containerMenu)
minecraft.getPlayer()->containerMenu->containerId = packet->containerId;
}
}
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ContainerClosePacket* packet)
{
if (minecraft && minecraft->player && minecraft->player->containerMenu)
minecraft->player->closeContainer();
if (minecraft.getPlayer() && minecraft.getPlayer()->containerMenu)
minecraft.getPlayer()->closeContainer();
}
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ContainerSetContentPacket* packet)
{
if (!minecraft || !minecraft->player)
if (!minecraft.getPlayer())
return;
if (packet->containerId == 0) {
for (unsigned int i = 0; i < packet->items.size(); ++i) {
minecraft->player->inventory->setItem(Inventory::MAX_SELECTION_SIZE + i, &packet->items[i]);
minecraft.getPlayer()->inventory->setItem(Inventory::MAX_SELECTION_SIZE + i, &packet->items[i]);
}
} else if (minecraft->player->containerMenu && minecraft->player->containerMenu->containerId == packet->containerId) {
} else if (minecraft.getPlayer()->containerMenu && minecraft.getPlayer()->containerMenu->containerId == packet->containerId) {
for (unsigned int i = 0; i < packet->items.size(); ++i) {
minecraft->player->containerMenu->setSlot(i, &packet->items[i]);
minecraft.getPlayer()->containerMenu->setSlot(i, &packet->items[i]);
}
}
}
@@ -865,28 +856,28 @@ void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, Containe
{
//LOGI("ContainerSetSlot\n");
if (!minecraft->player
|| !minecraft->player->containerMenu
|| minecraft->player->containerMenu->containerId != packet->containerId)
if (!minecraft.getPlayer()
|| !minecraft.getPlayer()->containerMenu
|| minecraft.getPlayer()->containerMenu->containerId != packet->containerId)
return;
//minecraft->player->containerMenu->setSlot(packet->slot, packet->item.isNull()? NULL : &packet->item);
minecraft->player->containerMenu->setSlot(packet->slot, &packet->item);
//minecraft.getPlayer()->containerMenu->setSlot(packet->slot, packet->item.isNull()? NULL : &packet->item);
minecraft.getPlayer()->containerMenu->setSlot(packet->slot, &packet->item);
}
void ClientSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ContainerSetDataPacket* packet)
{
//LOGI("ContainerSetData\n");
if (minecraft->player && minecraft->player->containerMenu && minecraft->player->containerMenu->containerId == packet->containerId) {
if (minecraft.getPlayer() && minecraft.getPlayer()->containerMenu && minecraft.getPlayer()->containerMenu->containerId == packet->containerId) {
//LOGI("client: SetData2 %d, %d\n", packet->id, packet->value);
minecraft->player->containerMenu->setData(packet->id, packet->value);
minecraft.getPlayer()->containerMenu->setData(packet->id, packet->value);
}
}
void ClientSideNetworkHandler::handle( const RakNet::RakNetGUID& source, ChatPacket* packet )
{
#ifndef STANDALONE_SERVER
minecraft->gui.displayClientMessage(packet->message);
minecraft.gui.displayClientMessage(packet->message);
#endif
}

View File

@@ -8,7 +8,7 @@
#include <vector>
class Minecraft;
class MinecraftClient;
class Level;
class IRakNetInstance;
@@ -29,7 +29,7 @@ typedef struct IntPair {
class ClientSideNetworkHandler : public NetEventCallback
{
public:
ClientSideNetworkHandler(Minecraft* minecraft, IRakNetInstance* raknetInstance);
ClientSideNetworkHandler(MinecraftClient& minecraft, IRakNetInstance* raknetInstance);
virtual ~ClientSideNetworkHandler();
virtual void levelGenerated(Level* level);
@@ -87,19 +87,19 @@ private:
void clearChunksLoaded();
private:
Minecraft* minecraft;
Level* level;
MinecraftClient& minecraft;
Level* level = nullptr;
IRakNetInstance* raknetInstance;
RakNet::RakPeerInterface* rakPeer;
RakNet::RakNetGUID serverGuid;
BlockUpdateList bufferedBlockUpdates;
int requestNextChunkPosition;
int requestNextChunkPosition = 0;
static const int NumRequestChunks = CHUNK_CACHE_WIDTH * CHUNK_CACHE_WIDTH;
int requestNextChunkIndex;
int requestNextChunkIndex = 0;
IntPair requestNextChunkIndexList[NumRequestChunks];
bool chunksLoaded[NumRequestChunks];
};

View File

@@ -5,11 +5,10 @@
#include "../raknet/BitStream.h"
#include "../raknet/MessageIdentifiers.h"
#include "../raknet/GetTime.h"
#include "../AppConstants.h"
#include "../platform/log.h"
#define APP_IDENTIFIER "MCCPP;" APP_VERSION_STRING ";"
#define APP_IDENTIFIER "MCCPP;Demo;"
#define APP_IDENTIFIER_MINECON "MCCPP;MINECON;"
RakNetInstance::RakNetInstance()

View File

@@ -5,19 +5,53 @@
#include "../world/entity/player/Inventory.h"
#include "../world/Container.h"
#include "../world/inventory/BaseContainerMenu.h"
#include "packet/PacketInclude.h"
#include "MinecraftClient.h"
#include "gamemode/GameMode.h"
#include "RakNetInstance.h"
#include "../client/Minecraft.h"
#include <MinecraftClient.h>
#include "../client/player/LocalPlayer.h"
#include "../client/gamemode/GameMode.h"
#include "../raknet/RakPeerInterface.h"
#include "../raknet/PacketPriority.h"
#ifndef STANDALONE_SERVER
#include "../client/sound/SoundEngine.h"
#endif
#include "../server/ServerPlayer.h"
#include "../world/entity/item/FallingTile.h"
#include "network/packet/AddEntityPacket.h"
#include "network/packet/AddItemEntityPacket.h"
#include "network/packet/AddMobPacket.h"
#include "network/packet/AddPaintingPacket.h"
#include "network/packet/AddPlayerPacket.h"
#include "network/packet/AdventureSettingsPacket.h"
#include "network/packet/AnimatePacket.h"
#include "network/packet/ChatPacket.h"
#include "network/packet/ChunkDataPacket.h"
#include "network/packet/ContainerSetSlotPacket.h"
#include "network/packet/DropItemPacket.h"
#include "network/packet/EntityEventPacket.h"
#include "network/packet/InteractPacket.h"
#include "network/packet/LevelEventPacket.h"
#include "network/packet/LoginPacket.h"
#include "network/packet/LoginStatusPacket.h"
#include "network/packet/MessagePacket.h"
#include "network/packet/MovePlayerPacket.h"
#include "network/packet/PlayerActionPacket.h"
#include "network/packet/PlayerArmorEquipmentPacket.h"
#include "network/packet/PlayerEquipmentPacket.h"
#include "network/packet/ReadyPacket.h"
#include "network/packet/RemoveBlockPacket.h"
#include "network/packet/RemoveEntityPacket.h"
#include "network/packet/RemovePlayerPacket.h"
#include "network/packet/RequestChunkPacket.h"
#include "network/packet/RespawnPacket.h"
#include "network/packet/SendInventoryPacket.h"
#include "network/packet/SetHealthPacket.h"
#include "network/packet/SetTimePacket.h"
#include "network/packet/SignUpdatePacket.h"
#include "network/packet/StartGamePacket.h"
#include "network/packet/TileEventPacket.h"
#include "network/packet/UpdateBlockPacket.h"
#include "network/packet/UseItemPacket.h"
#include "world/entity/Painting.h"
#include "world/level/tile/entity/TileEntity.h"
#define TIMES(x) for(int itc ## __LINE__ = 0; itc ## __LINE__ < x; ++ itc ## __LINE__)
@@ -52,16 +86,19 @@ void ServerSideNetworkHandler::tileChanged(int x, int y, int z)
}
Packet* ServerSideNetworkHandler::getAddPacketFromEntity( Entity* entity ) {
if (entity->isMob() && !entity->isPlayer()) { //@fix: This code is duplicated. See if it can be unified.
if (minecraft->player) {
// I guess this should always be true, but it crashed somewhere in this
// function once and I only see this one as a potential problem
return new AddMobPacket((Mob*)entity);
}
}
else if (entity->isPlayer()) {
// if (entity->isMob() && !entity->isPlayer()) { //@fix: This code is duplicated. See if it can be unified.
// auto client = dynamic_cast<MinecraftClient*>(minecraft);
} else if (entity->isItemEntity()) {
// if (client && client->getPlayer()) {
// // I guess this should always be true, but it crashed somewhere in this
// // function once and I only see this one as a potential problem
// return new AddMobPacket((Mob*)entity);
// }
// }
// else if (entity->isPlayer()) {
// } else
if (entity->isItemEntity()) {
AddItemEntityPacket* packet = new AddItemEntityPacket((ItemEntity*)entity);
entity->xd = packet->xa();
entity->yd = packet->ya();
@@ -409,9 +446,11 @@ void ServerSideNetworkHandler::levelGenerated( Level* level )
{
this->level = level;
if (minecraft->player) {
minecraft->player->owner = rakPeer->GetMyGUID();
}
// auto client = dynamic_cast<MinecraftClient*>(minecraft);
// if (client && client->getPlayer()) {
// client->getPlayer()->owner = rakPeer->GetMyGUID();
// }
level->addListener(this);
#ifndef STANDALONE_SERVER
@@ -485,10 +524,12 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, AnimateP
if (!level)
return;
// Own player -> invalid
if (minecraft->player && minecraft->player->entityId == packet->entityId) {
return;
}
// auto client = dynamic_cast<MinecraftClient*>(minecraft);
// // Own player -> invalid
// if (client && client->getPlayer() && client->getPlayer()->entityId == packet->entityId) {
// return;
// }
Entity* entity = level->getEntity(packet->entityId);
if (!entity || !entity->isPlayer())
@@ -605,8 +646,11 @@ void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, Containe
Player* p = findPlayer(level, &source);
if (!p) return;
if (p != minecraft->player)
static_cast<ServerPlayer*>(p)->doCloseContainer();
// // if (p != minecraft->player)
// static_cast<ServerPlayer*>(p)->doCloseContainer();
if (auto sp = dynamic_cast<ServerPlayer*>(p))
sp->doCloseContainer();
}
void ServerSideNetworkHandler::handle(const RakNet::RakNetGUID& source, ContainerSetSlotPacket* packet) {
@@ -672,7 +716,7 @@ void ServerSideNetworkHandler::handle( const RakNet::RakNetGUID& source, SignUpd
void ServerSideNetworkHandler::allowIncomingConnections( bool doAllow )
{
if (doAllow) {
raknetInstance->announceServer(minecraft->options.getStringValue(OPTIONS_USERNAME));
raknetInstance->announceServer(minecraft->getServerName());
} else {
raknetInstance->announceServer("");
}

View File

@@ -1,7 +1,8 @@
#include "CommandServer.h"
#include "../../client/Minecraft.h"
#include <Minecraft.h>
#include "../../world/level/Level.h"
#include "../../world/entity/Entity.h"
#include "gamemode/CreatorMode.h"
#ifdef WIN32
#define SERR(x) (WSA ## x)
@@ -14,10 +15,8 @@
#include "../RakNetInstance.h"
#include "../packet/ChatPacket.h"
#include "../packet/AdventureSettingsPacket.h"
#include "../../world/level/LevelSettings.h"
#include "../../world/entity/player/Player.h"
#include "../../client/gamemode/CreatorMode.h"
#include "../../client/player/LocalPlayer.h"
#include <world/level/LevelSettings.h>
#include <world/entity/player/Player.h>
#include "../RakNetInstance.h"
const std::string NullString;
@@ -262,6 +261,7 @@ std::string CommandServer::parse(ConnectedClient& client, const std::string& s)
return ToStringOk(y);
}
#if 0
//
// Player related get, set and query
//
@@ -316,6 +316,7 @@ std::string CommandServer::parse(ConnectedClient& client, const std::string& s)
apiPosTranslate.to(x, y, z);
return ToStringOk(x, y, z);
}
#endif
//
// Entity
@@ -385,6 +386,7 @@ std::string CommandServer::parse(ConnectedClient& client, const std::string& s)
return NullString;
}
#if 0
//
// Camera
//
@@ -430,6 +432,7 @@ std::string CommandServer::parse(ConnectedClient& client, const std::string& s)
e->moveTo((float)x + 0.5f, (float)y, (float)z + 0.5f, e->yRot, e->xRot);
return NullString;
}
#endif
//
// Entities
@@ -445,6 +448,8 @@ std::string CommandServer::parse(ConnectedClient& client, const std::string& s)
return s.str();
}
#if 0
//
// Set and restore Checkpoint
//
@@ -478,6 +483,7 @@ std::string CommandServer::parse(ConnectedClient& client, const std::string& s)
}
return success? NullString : Fail;
}
#endif
//
// Event queries
@@ -540,9 +546,9 @@ void CommandServer::tick() {
_updateClients();
++t;
if (mc->cameraTargetPlayer == camera) {
camera->tick();
}
// if (mc->cameraTargetPlayer == camera) {
// camera->tick();
// }
}
void CommandServer::_updateAccept() {
@@ -587,9 +593,9 @@ bool CommandServer::_updateClient(ConnectedClient& client) {
}
void CommandServer::dispatchPacket( Packet& p ) {
if (!mc->netCallback || !mc->player) return;
const RakNet::RakNetGUID& guid = ((Player*)mc->player)->owner;
mc->raknetInstance->send(p);
// if (!mc->netCallback || !mc->player) return;
// const RakNet::RakNetGUID& guid = ((Player*)mc->player)->owner;
// mc->raknetInstance->send(p);
//p.handle(guid, mc->netCallback);
}
@@ -609,6 +615,7 @@ std::string CommandServer::handleEventPollMessage( ConnectedClient& client, cons
ICreator::EventList<ICreator::TileEvent>& events = c->getTileEvents();
std::stringstream ss;
events.write(ss, apiPosTranslate, client.lastPoll_blockHit);
client.lastPoll_blockHit = mc->level->getTime();
@@ -630,7 +637,7 @@ std::string CommandServer::handleSetSetting( const std::string& setting, int val
{
bool status = value != 0;
if (setting == "autojump") mc->player->autoJumpEnabled = status;
// if (setting == "autojump") mc->player->autoJumpEnabled = status;
AdventureSettingsPacket::Flags flag = (AdventureSettingsPacket::Flags)0;
if (setting == "nametags_visible") flag = AdventureSettingsPacket::ShowNameTags;

View File

@@ -1,7 +1,7 @@
#ifndef APPPLATFORM_ANDROID_H__
#define APPPLATFORM_ANDROID_H__
#include "AppPlatform.h"
#include <IPlatform.h>
#include "client/renderer/gles.h"
#include "platform/log.h"
#include "platform/time.h"
@@ -322,7 +322,7 @@ public:
}
}
__inline unsigned int rgbToBgr(unsigned int p) {
inline unsigned int rgbToBgr(unsigned int p) {
return (p & 0xff00ff00) | ((p >> 16) & 0xff) | ((p << 16) & 0xff0000);
}
@@ -536,7 +536,7 @@ public:
return env->CallBooleanMethod(instance, _methodIsNetworkEnabled, onlyWifiAllowed);
}
static __inline bool isSquare(int n) {
static inline bool isSquare(int n) {
int L = n & 0xf;
if (((1 << L) & 0x213) == 0) return false;

View File

@@ -0,0 +1,235 @@
#include "PlatformGlfw.h"
#include <IPlatform.h>
#include "platform/input/Keyboard.h"
#include "platform/input/Mouse.h"
#include "platform/log.h"
#include <GLFW/glfw3.h>
#include <png.h>
#include "platform/HttpClient.h"
#include "util/StringUtils.h"
#include <fstream>
#include <ctime>
#include <vector>
#ifdef _WIN32
#include <windows.h>
#include <shellapi.h>
#endif
#include "App.h"
bool PlatformGlfw::init() {
glfwSetErrorCallback(PlatformGlfw::error_callback);
if (!glfwInit()) {
return false;
}
glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_NATIVE_CONTEXT_API);
#ifndef __EMSCRIPTEN__
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
#else
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 1);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
#endif
m_window = glfwCreateWindow(getScreenWidth(), getScreenHeight(), "Minecraft PE 0.6.1", NULL, NULL);
if (m_window == nullptr) {
return false;
}
glfwSetKeyCallback(m_window, key_callback);
glfwSetCharCallback(m_window, character_callback);
glfwSetCursorPosCallback(m_window, cursor_position_callback);
glfwSetMouseButtonCallback(m_window, mouse_button_callback);
glfwSetScrollCallback(m_window, scroll_callback);
glfwSetWindowSizeCallback(m_window, window_size_callback);
glfwSetWindowUserPointer(m_window, this);
glfwMakeContextCurrent(m_window);
#ifndef __EMSCRIPTEN__
gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
glfwSwapInterval(0);
#endif
}
void PlatformGlfw::finish() {
glfwDestroyWindow(m_window);
glfwTerminate();
}
int PlatformGlfw::transformKey(int glfwkey) {
if (glfwkey >= GLFW_KEY_F1 && glfwkey <= GLFW_KEY_F12) {
return glfwkey - 178;
}
switch (glfwkey) {
case GLFW_KEY_ESCAPE: return Keyboard::KEY_ESCAPE;
case GLFW_KEY_TAB: return Keyboard::KEY_TAB;
case GLFW_KEY_BACKSPACE: return Keyboard::KEY_BACKSPACE;
case GLFW_KEY_LEFT_SHIFT: return Keyboard::KEY_LSHIFT;
case GLFW_KEY_ENTER: return Keyboard::KEY_RETURN;
case GLFW_KEY_LEFT_CONTROL: return Keyboard::KEY_LEFT_CTRL;
default: return glfwkey;
}
}
void PlatformGlfw::cursor_position_callback(GLFWwindow* window, double xpos, double ypos) {
static double lastX = 0.0, lastY = 0.0;
static bool firstMouse = true;
if (firstMouse) {
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
double deltaX = xpos - lastX;
double deltaY = ypos - lastY;
lastX = xpos;
lastY = ypos;
if (glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED) {
Mouse::feed(0, 0, xpos, ypos, deltaX, deltaY);
} else {
Mouse::feed( MouseAction::ACTION_MOVE, 0, xpos, ypos);
}
// Multitouch::feed(0, 0, xpos, ypos, 0);
}
void PlatformGlfw::mouse_button_callback(GLFWwindow* window, int button, int action, int mods) {
if(action == GLFW_REPEAT) return;
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
if (button == GLFW_MOUSE_BUTTON_LEFT) {
Mouse::feed( MouseAction::ACTION_LEFT, action, xpos, ypos);
// Multitouch::feed(1, action, xpos, ypos, 0);
}
if (button == GLFW_MOUSE_BUTTON_RIGHT) {
Mouse::feed( MouseAction::ACTION_RIGHT, action, xpos, ypos);
}
}
void PlatformGlfw::character_callback(GLFWwindow* window, unsigned int codepoint) {
Keyboard::feedText(codepoint);
}
void PlatformGlfw::scroll_callback(GLFWwindow* window, double xoffset, double yoffset) {
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
Mouse::feed(3, 0, xpos, ypos, 0, yoffset);
}
void PlatformGlfw::error_callback(int error, const char* desc) {
LOGE("GLFW Error (%d): %s", error, desc);
}
void PlatformGlfw::window_size_callback(GLFWwindow* window, int width, int height) {
PlatformGlfw* app = (PlatformGlfw*)glfwGetWindowUserPointer(window);
app->windowSizeChanged = true;
}
float PlatformGlfw::getPixelsPerMillimeter() {
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
int width_mm, height_mm;
glfwGetMonitorPhysicalSize(monitor, &width_mm, &height_mm);
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
return (float)mode->width / (float)width_mm;
}
TextureData PlatformGlfw::loadTexture(const std::string& filename_, bool textureFolder) {
// Support fetching PNG textures via HTTP/HTTPS (for skins, etc)
if (Util::startsWith(filename_, "http://") || Util::startsWith(filename_, "https://")) {
std::vector<unsigned char> body;
if (HttpClient::download(filename_, body) && !body.empty()) {
return loadTextureFromMemory(body.data(), body.size());
}
return TextureData();
}
TextureData out;
std::string filename = textureFolder? "data/images/" + filename_
: filename_;
std::ifstream source(filename.c_str(), std::ios::binary);
if (!source) {
LOGI("Couldn't find file: %s\n", filename.c_str());
return out;
}
std::vector<unsigned char> fileData((std::istreambuf_iterator<char>(source)), std::istreambuf_iterator<char>());
source.close();
if (fileData.empty()) {
LOGI("Couldn't read file: %s\n", filename.c_str());
return out;
}
return loadTextureFromMemory(fileData.data(), fileData.size());
}
std::string PlatformGlfw::getDateString(int s) {
time_t tm = s;
char mbstr[100];
std::strftime(mbstr, sizeof(mbstr), "%F %T", std::localtime(&tm));
return std::string(mbstr);
}
void PlatformGlfw::hideCursor(bool hide) {
int isHide = hide ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_HIDDEN;
glfwSetInputMode(m_window, GLFW_CURSOR, isHide);
}
void PlatformGlfw::openURL(const std::string& url) {
#ifdef _WIN32
ShellExecuteA(NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL);
#elif __linux__
std::string command = "xdg-open " + url;
system(command.c_str());
#elif __EMSCRIPTEN__
emscripten_run_script(std::string("window.open('" + url + "', '_blank')").c_str());
#endif
}
void PlatformGlfw::swapBuffers() {
glfwSwapBuffers(m_window);
glfwPollEvents();
// @todo
// if(((MAIN_CLASS*)g_app)->options.getBooleanValue(OPTIONS_LIMIT_FRAMERATE)) {
// auto frameEnd = clock::now();
// auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(frameEnd - frameStart);
// auto target = std::chrono::microseconds(33333); // ~30 fps
// if(elapsed < target)
// std::this_thread::sleep_for(target - elapsed);
// }
}
void PlatformGlfw::setVSync(bool on) {
IPlatform::setVSync(on);
glfwSwapInterval(on);
}

View File

@@ -0,0 +1,75 @@
#ifndef APPPLATFORM_GLFW_H__
#define APPPLATFORM_GLFW_H__
#include <IPlatform.h>
#include "platform/log.h"
#include "platform/HttpClient.h"
#include "platform/PngLoader.h"
#include "client/renderer/gles.h"
#include "world/level/storage/FolderMethods.h"
#include <png.h>
#include <GLFW/glfw3.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/html5.h>
#endif
class PlatformGlfw : public IPlatform {
public:
bool init() override;
void finish() override;
TextureData loadTexture(const std::string& filename_, bool textureFolder) override;
TextureData loadTextureFromMemory(const unsigned char* data, size_t size) override { return loadPngFromMemory(data, size); }
std::string getDateString(int s) override;
int getScreenWidth() override {
#ifdef __EMSCRIPTEN__
int w, h;
emscripten_get_canvas_element_size("canvas", &w, &h);
return w;
#endif
return 854;
};
int getScreenHeight() override {
#ifdef __EMSCRIPTEN__
int w, h;
emscripten_get_canvas_element_size("canvas", &w, &h);
return h;
#endif
return 480;
};
float getPixelsPerMillimeter() override;
bool supportsTouchscreen() override { return false; /* glfw supports only mouse and keyboard */ }
void hideCursor(bool hide) override;
void openURL(const std::string& url) override;
void swapBuffers() override;
void setVSync(bool on) override;
private:
static int transformKey(int glfwkey);
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods);
static void character_callback(GLFWwindow* window, unsigned int codepoint);
static void cursor_position_callback(GLFWwindow* window, double xpos, double ypos);
static void mouse_button_callback(GLFWwindow* window, int button, int action, int mods);
static void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
static void window_size_callback(GLFWwindow* window, int width, int height);
static void error_callback(int error, const char* desc);
GLFWwindow* m_window;
};
#endif /*APPPLATFORM_GLFW_H__*/

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