Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP Scripting #69

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ add_subdirectory(dawn)
message("========== EXAMPLES ==========")
add_subdirectory(examples)

message("========== LUA SHOOTER ==========")
add_subdirectory(lua_shooter)

message("========== SANDBOX ==========")
add_subdirectory(sandbox)

Expand Down
6 changes: 4 additions & 2 deletions src/dawn/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,8 @@ set(SOURCE_FILES
resource/Resource.h
resource/ResourceCache.cpp
resource/ResourceCache.h
resource/TextResource.cpp
resource/TextResource.h
scene/BulletDynamics.h
scene/CLinearMotion.h
scene/CameraController.cpp
Expand All @@ -189,8 +191,8 @@ set(SOURCE_FILES
scene/SLinearMotion.h
scene/SceneManager.cpp
scene/SceneManager.h
script/LuaState.cpp
script/LuaState.h
script/LuaVM.cpp
script/LuaVM.h
script/Sol.h
ui/Imgui.h
ui/UserInterface.cpp
Expand Down
2 changes: 1 addition & 1 deletion src/dawn/Script.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
#pragma once

#include "Base.h"
#include "script/LuaState.h"
#include "script/LuaVM.h"
6 changes: 1 addition & 5 deletions src/dawn/core/Engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
#include "renderer/Renderer.h"
#include "resource/ResourceCache.h"
#include "scene/SceneManager.h"
#include "script/LuaState.h"
#include "script/LuaVM.h"

// Required for getBasePath/getPrefPath.
#if DW_PLATFORM == DW_WIN32
Expand Down Expand Up @@ -129,10 +129,6 @@ void Engine::setup(const CommandLine& cmdline) {
context_->setDefaultConfig();
}

// Initialise the Lua VM first so bindings can be defined in Constructors
context_->addModule<LuaState>();
// TODO(David): bind engine services to lua?

// Create the engine subsystems.
auto* renderer = context_->addModule<Renderer>();
auto renderer_result = Result<void>();
Expand Down
13 changes: 13 additions & 0 deletions src/dawn/core/io/InputStream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,19 @@ String InputStream::readLine(char delim) {
}
return out;
}
Result<Vector<byte>> InputStream::readAll() {
if (size_ == 0) {
return makeError("Unable to read entire InputStream. Size is 0.");
}
Vector<byte> buffer;
buffer.resize(size_);
auto read = readData(buffer.data(), size_);
if (!eof()) {
return makeError(tinyformat::format(
"Attempted to read %s bytes. Actually read %s bytes and didn't read EOF.", read));
}
return std::move(buffer);
}

bool InputStream::eof() const {
return position_ >= size_;
Expand Down
12 changes: 8 additions & 4 deletions src/dawn/core/io/InputStream.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,21 @@ class DW_API InputStream {
/// @return Number of bytes read
virtual usize readData(void* dest, usize size) = 0;

/// Read all bytes from the stream.
/// @return A buffer containing all the bytes in the stream, or an error.
Result<Vector<byte>> readAll();

/// Reads a string up to a certain character
/// @param delim Delimeter character
String readLine(char delim = '\n');

/// Moves the position of the cursor in the stream.
/// @param position Offset from the start of the stream, in bytes
virtual void seek(usize position) = 0;

/// Check if the end of the stream has been reached
bool eof() const;

/// Reads a string up to a certain character
/// @param delim Delimeter character
String readLine(char delim = '\n');

/// Returns the current position in the input stream
usize position() const;

Expand Down
8 changes: 3 additions & 5 deletions src/dawn/resource/ResourceCache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ Pair<String, Path> parseResourcePath(const ResourcePath& resource_path) {
ResourcePackage::ResourcePackage(Context* ctx, const Path& package) : Object(ctx) {
}

Result<SharedPtr<InputStream>, String> ResourcePackage::getFile(
const ResourcePath& path_within_location) {
Result<SharedPtr<InputStream>> ResourcePackage::getFile(const ResourcePath& path_within_location) {
return makeError(
"ResourcePackage::getFile() - Loading from a ResourcePackage is unimplemented.");
}
Expand All @@ -29,7 +28,7 @@ ResourceFilesystemPath::ResourceFilesystemPath(Context* ctx, const Path& path)
: Object(ctx), path_{path} {
}

Result<SharedPtr<InputStream>, String> ResourceFilesystemPath::getFile(
Result<SharedPtr<InputStream>> ResourceFilesystemPath::getFile(
const ResourcePath& path_within_location) {
Path full_path = path_ + path_within_location;
log().info("Loading resource from filesystem at " + full_path);
Expand Down Expand Up @@ -60,8 +59,7 @@ void ResourceCache::addPackage(const String& package, UniquePtr<ResourcePackage>
resource_packages_.emplace(makePair(package, std::move(file)));
}

Result<SharedPtr<InputStream>, String> ResourceCache::getResourceData(
const ResourcePath& resource_path) {
Result<SharedPtr<InputStream>> ResourceCache::loadRaw(const ResourcePath& resource_path) {
// Parse resource path.
auto path = parseResourcePath(resource_path);
String package = path.first;
Expand Down
12 changes: 7 additions & 5 deletions src/dawn/resource/ResourceCache.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Pair<String, Path> parseResourcePath(const ResourcePath& resource_path);
class DW_API ResourceLocation {
public:
virtual ~ResourceLocation() = default;
virtual Result<SharedPtr<InputStream>, String> getFile(
virtual Result<SharedPtr<InputStream>> getFile(
const ResourcePath& path_within_location) = 0;
};

Expand All @@ -26,7 +26,7 @@ class DW_API ResourcePackage : public Object, public ResourceLocation {

ResourcePackage(Context* ctx, const Path& package);

Result<SharedPtr<InputStream>, String> getFile(
Result<SharedPtr<InputStream>> getFile(
const ResourcePath& path_within_location) override;
};

Expand All @@ -36,7 +36,7 @@ class DW_API ResourceFilesystemPath : public Object, public ResourceLocation {

ResourceFilesystemPath(Context* ctx, const Path& path);

Result<SharedPtr<InputStream>, String> getFile(
Result<SharedPtr<InputStream>> getFile(
const ResourcePath& path_within_location) override;

private:
Expand All @@ -53,6 +53,9 @@ class DW_API ResourceCache : public Module {
void addPath(const String& package, const Path& path);
void addPackage(const String& package, UniquePtr<ResourcePackage> file);

// Raw API to read resource data.
Result<SharedPtr<InputStream>> loadRaw(const ResourcePath &resource_path);

template <typename T>
SharedPtr<T> addCustomResource(const ResourcePath& resource_path, SharedPtr<T> resource) {
String name(resource_path);
Expand Down Expand Up @@ -80,7 +83,7 @@ class DW_API ResourceCache : public Module {
}

// Load the file which contains this resource data.
auto resource_data = getResourceData(resource_path);
auto resource_data = loadRaw(resource_path);
if (!resource_data) {
return makeError(str::format("Cannot find resource %s. Reason: %s", resource_path,
resource_data.error()));
Expand All @@ -97,7 +100,6 @@ class DW_API ResourceCache : public Module {
}

private:
Result<SharedPtr<InputStream>, String> getResourceData(const Path& filename);

Map<String, UniquePtr<ResourceLocation>> resource_packages_;
HashMap<String, SharedPtr<Resource>> resource_cache_;
Expand Down
24 changes: 24 additions & 0 deletions src/dawn/resource/TextResource.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Dawn Engine
* Written by David Avedissian (c) 2012-2019 ([email protected])
*/
#include "Core.h"
#include "resource/TextResource.h"

namespace dw {
TextResource::TextResource(Context* ctx) : Resource(ctx) {
}

Result<void> TextResource::beginLoad(const String&, InputStream& src) {
auto result = src.readAll();
if (!result) {
return makeError(result.error());
}
data_ = String(static_cast<const char*>(static_cast<void*>(result->data())), result->size());
return {};
}

Result<void> TextResource::save(OutputStream& dest) {
dest.writeData(data_.data(), data_.size());
}
} // namespace dw
24 changes: 24 additions & 0 deletions src/dawn/resource/TextResource.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Dawn Engine
* Written by David Avedissian (c) 2012-2019 ([email protected])
*/
#pragma once

#include "resource/Resource.h"

namespace dw {
class DW_API TextResource : public Resource {
public:
DW_OBJECT(TextResource);

TextResource(Context* ctx);

Result<void> beginLoad(const String& asset_name, InputStream& src) override;
Result<void> save(OutputStream& dest) override;

String data();

private:
String data_;
};
} // namespace dw
30 changes: 0 additions & 30 deletions src/dawn/script/LuaState.cpp

This file was deleted.

21 changes: 0 additions & 21 deletions src/dawn/script/LuaState.h

This file was deleted.

61 changes: 61 additions & 0 deletions src/dawn/script/LuaVM.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Dawn Engine
* Written by David Avedissian (c) 2012-2019 ([email protected])
*/
#include "Base.h"
#include "LuaVM.h"

namespace dw {
namespace {
void redirectLuaPrintToLogger(Context& context, sol::state& state) {
state.script(R"""(
function print(...)
local arg = {...}
local str
str = ''
for i = 1, #arg do
if str ~= '' then str = str .. '\t' end
str = str .. tostring(arg[i])
end
str = str .. '\n'
__dw_write_log(debug.getinfo(2).short_src, str)
end)""");
}

void registerWorldLib(sol::state& state) {
}
} // namespace

LuaVM::LuaVM(Context* context) : Object(context) {
state_.open_libraries(sol::lib::base, sol::lib::package, sol::lib::coroutine, sol::lib::string,
sol::lib::os, sol::lib::math, sol::lib::table, sol::lib::debug,
sol::lib::bit32);
state_.set_function("__dw_write_log", [this](const char* caller, const char* str) {
log().info("%s: %s", caller, str);
});
redirectLuaPrintToLogger(*context, state_);
registerWorldLib(state_);
}

sol::state& LuaVM::state() {
return state_;
}

Result<void> LuaVM::execute(const String& text) {
try {
state_.script(text);
} catch (const sol::error& e) {
return makeError(e.what());
}
return {};
}

Result<void> LuaVM::execute(InputStream& is) {
auto read_result = is.readAll();
if (!read_result) {
return makeError(read_result.error());
}
return execute(String(static_cast<const char*>(static_cast<void*>(read_result->data())),
read_result->size()));
}
} // namespace dw
32 changes: 32 additions & 0 deletions src/dawn/script/LuaVM.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Dawn Engine
* Written by David Avedissian (c) 2012-2019 ([email protected])
*/
#pragma once

#include "Sol.h"
#include "core/io/InputStream.h"

namespace dw {

// Manages a Lua virtual machine, with the "dw" library set.
class DW_API LuaVM : public Object {
public:
DW_OBJECT(LuaVM);

LuaVM(Context* context);
virtual ~LuaVM() = default;

// Get a reference to the internal state.
sol::state& state();

// Execute a file from a string.
Result<void> execute(const String& text);

// Execute a file from an input stream.
Result<void> execute(InputStream& is);

private:
sol::state state_;
};
} // namespace dw
10 changes: 10 additions & 0 deletions src/lua_shooter/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Dawn Engine
# Written by David Avedissian (c) 2012-2019 ([email protected])

add_dawn_executable(
DwLuaShooter
SRCS
Main.cpp
RESOURCE_PKGS
${CMAKE_CURRENT_SOURCE_DIR}/data
${CMAKE_SOURCE_DIR}/media/examples)
Loading