Compare commits

..

17 Commits

Author SHA1 Message Date
antc13 24486c314d Reworked the Exporter. 2016-01-13 14:03:58 +01:00
antc13 7b62dc19bf Spitting out Meshes & Animation Data to file. 2016-01-12 15:39:29 +01:00
antc13 0e90382fd1 Merge branch 'master' of https://github.com/teamfisk/TacticalZ into MayaExporter 2016-01-11 13:09:09 +01:00
antc13 1667358e0c We now export animations. 2016-01-08 16:47:04 +01:00
FakeShemp eb5fca898f Fix small bug with push_back order
Commited directly from GitHub. Blame it if something explodes.
2015-12-21 12:55:25 +01:00
antc13 c9db46564f Spitting out files WIP 2015-12-18 16:21:07 +01:00
Teejoon 509a989d3b Merge branch 'MayaExporter' of github.com:teamfisk/TacticalZ into MayaExporter
Conflicts:
	tools/MayaExporter/MayaExporter/Menu.cpp
2015-12-18 10:07:44 +01:00
Teejoon bc4cc5db54 Changed how we get skeletons. Made so that we could get the bind pose for each skeleton in the scene 2015-12-18 10:03:00 +01:00
antc13 73708ec706 You can now add/remove animation clips. 2015-12-17 14:58:46 +01:00
antc13 67017fcaf4 Stepping through the timeline. 2015-12-16 11:33:42 +01:00
antc13 498afb3a5e Merge branch 'MayaExporter' of https://github.com/teamfisk/TacticalZ into MayaExporter
# Conflicts:
#	tools/MayaExporter/MayaExporter/Menu.h
2015-12-15 15:41:18 +01:00
antc13 4e535c1102 File Writer WIP. Rework soon™ 2015-12-15 15:24:46 +01:00
FakeShemp 1689370356 Export the skeletons
Not really tested though
2015-12-15 11:49:59 +01:00
antc13 60b3ce89b2 Skeleton/Joints WIP 2015-12-14 12:59:54 +01:00
antc13 a22d086e60 Tested some of the Material Code. Seems to work. The project should now be following the code standard properly (hopefully). 2015-12-10 11:18:34 +01:00
FakeShemp 74c1beed20 gitignore 2015-12-09 12:03:01 +01:00
FakeShemp c8cb0ee939 Grab all materials 2015-12-09 11:58:49 +01:00
75 changed files with 3182 additions and 2219 deletions
+8
View File
@@ -4,3 +4,11 @@ bin/
lib/
# Because apparently nobody has any self control
*.orig
*.suo
*.sdf
tools/MayaExporter/MayaExporter/x64/Debug/
tools/MayaExporter/x64/Debug/
tools/MayaExporter/MayaExporter/Debug/
tools/MayaExporter/MayaExporter/GeneratedFiles/
+10 -11
View File
@@ -1,17 +1,16 @@
#### Bundled libraries
Libraries bundled along with binaries for Windows (MSVC14), available as a submodule in the *deps* directory of the source tree.
| Project | Version | License |
| ---------------------------------------------------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **[GLFW](http://www.glfw.org)** | 3.1.2 | [zlib/libpng License](http://www.glfw.org/license.html) |
| **[GLM](http://glm.g-truc.net/0.9.5/index.html)** | 0.9.7.1 | [MIT License](http://glm.g-truc.net/copying.txt) |
| **[GLEW](http://glew.sourceforge.net)** | 1.13.0 | [Modified BSD License](http://glew.sourceforge.net/glew.txt), [Mesa 3-D License](http://glew.sourceforge.net/mesa.txt), [Khronos License](http://glew.sourceforge.net/khronos.txt) |
| **[Assimp](http://assimp.sourceforge.net)** | 3.1.1 | [BSD 3-Clause License](http://assimp.sourceforge.net/main_license.html) |
| **[zlib](http://www.zlib.net)** | 1.28 | [zlib License](http://www.zlib.net/zlib_license.html) |
| **[libpng](http://www.libpng.org/pub/png/libpng.html)** | 1.6.19 | [libpng License](http://www.libpng.org/pub/png/src/libpng-LICENSE.txt) |
| **[Xerces-C++](https://xerces.apache.org/xerces-c)** | 3.1.2 | [Apache License Version 2.0](https://www.apache.org/licenses/LICENSE-2.0) |
| **[ImGui](https://github.com/ocornut/imgui)** | 2015-12-12 | [MIT License](https://github.com/ocornut/imgui/blob/de3a154f3801de22c8e0bd2aeabf663a70c05972/LICENSE) |
| **[nativefiledialog](https://github.com/mlabbe/nativefiledialog) | 2016-01-08 | https://github.com/mlabbe/nativefiledialog/blob/master/LICENSE |
| Project | Version | License |
| ------------------------------------------------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **[GLFW](http://www.glfw.org)** | 3.1.2 | [zlib/libpng License](http://www.glfw.org/license.html) |
| **[GLM](http://glm.g-truc.net/0.9.5/index.html)** | 0.9.7.1 | [MIT License](http://glm.g-truc.net/copying.txt) |
| **[GLEW](http://glew.sourceforge.net)** | 1.13.0 | [Modified BSD License](http://glew.sourceforge.net/glew.txt), [Mesa 3-D License](http://glew.sourceforge.net/mesa.txt), [Khronos License](http://glew.sourceforge.net/khronos.txt) |
| **[Assimp](http://assimp.sourceforge.net)** | 3.1.1 | [BSD 3-Clause License](http://assimp.sourceforge.net/main_license.html) |
| **[zlib](http://www.zlib.net)** | 1.28 | [zlib License](http://www.zlib.net/zlib_license.html) |
| **[libpng](http://www.libpng.org/pub/png/libpng.html)** | 1.6.19 | [libpng License](http://www.libpng.org/pub/png/src/libpng-LICENSE.txt) |
| **[Xerces-C++](https://xerces.apache.org/xerces-c)** | 3.1.2 | [Apache License Version 2.0](https://www.apache.org/licenses/LICENSE-2.0) |
| **[ImGui](https://github.com/ocornut/imgui)** | 2015-12-12 | [MIT License](https://github.com/ocornut/imgui/blob/de3a154f3801de22c8e0bd2aeabf663a70c05972/LICENSE) |
#### External libraries
Libraries that are too big to be bundled with the project.
+1 -1
Submodule deps updated: bf83f099ba...1ae6ba5b12
+2 -9
View File
@@ -12,16 +12,9 @@ struct ComponentInfo
unsigned int Stride = 0;
};
struct Field_t
{
std::string Type;
unsigned int Offset;
unsigned int Stride;
};
std::string Name;
std::unordered_map<std::string, Field_t> Fields;
std::vector<const Field_t*> FieldsInOrder;
std::unordered_map<std::string, std::string> FieldTypes;
std::unordered_map<std::string, unsigned int> FieldOffsets;
Meta_t Meta;
std::shared_ptr<char> Defaults = nullptr;
};
+3 -4
View File
@@ -21,7 +21,7 @@ struct ComponentWrapper
template <typename T>
T& Property(std::string name)
{
unsigned int offset = Info.Fields.at(name).Offset;
unsigned int offset = Info.FieldOffsets.at(name);
return *reinterpret_cast<T*>(&Data[offset]);
}
@@ -78,9 +78,8 @@ public:
void AddProperty(std::string fieldName, T defaultValue)
{
m_DefaultValues.push_back(defaultValue);
m_ComponentInfo.Fields[fieldName].Name = typeid(T).name();
m_ComponentInfo.Fields[fieldName].Offset = m_ComponentInfo.Meta.Stride;
m_ComponentInfo.Fields[fieldName].Stride = sizeof(T);
m_ComponentInfo.FieldTypes[fieldName] = typeid(T).name();
m_ComponentInfo.FieldOffsets[fieldName] = m_ComponentInfo.Meta.Stride;
m_ComponentInfo.Meta.Stride += sizeof(T);
}
+25 -31
View File
@@ -3,10 +3,10 @@
#include <string>
#include <boost/filesystem.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/range/adaptors.hpp>
#include <ini_file/ini_file.hpp>
#include "../Common.h"
#include "ResourceManager.h"
@@ -20,52 +20,46 @@ private:
public:
template <typename T>
T Get(std::string key, T defaultValue);
template <typename T>
std::vector<std::pair<std::string, T>> GetAll(std::string key);
template <typename T>
void Set(std::string key, T value);
const ini_file::section* GetSection(std::string section);
const ini_file::section_map& GetSections() { return m_Merged; }
const ini_file::param* GetParam(std::string key);
void SaveToDisk();
private:
boost::filesystem::path m_Path;
ini_file::section_map m_Defaults;
ini_file::section_map m_Overrides;
ini_file::section_map m_Merged;
// Merge ini file section map b into a
void mergeINI(ini_file::section_map& a, const ini_file::section_map& b);
// Convert an ini key delimited by periods to a section and a param
boost::optional<std::pair<std::string, std::string>> tokenizeKey(std::string key);
boost::property_tree::ptree m_PTreeDefaults;
boost::property_tree::ptree m_PTreeOverrides;
boost::property_tree::ptree m_PTreeMerged;
};
template <typename T>
T ConfigFile::Get(std::string key, T defaultValue)
{
auto param = GetParam(key);
if (param == nullptr) {
return defaultValue;
}
return m_PTreeMerged.get<T>(key, defaultValue);
}
return boost::lexical_cast<T>(param->get_value());
template <typename T>
std::vector<std::pair<std::string, T>> ConfigFile::GetAll(std::string key)
{
std::vector<std::pair<std::string, T>> out;
auto parent = m_PTreeMerged.find(key);
if (parent == m_PTreeMerged.not_found()) {
return out;
}
for (auto& child : parent->second) {
T value = boost::lexical_cast<T>(child.second.data());
out.push_back(std::make_pair(child.first, value));
}
return out;
}
template <typename T>
void ConfigFile::Set(std::string key, T value)
{
std::string section;
std::string param;
if (auto tokens = tokenizeKey(key)) {
std::tie(section, param) = *tokens;
} else {
LOG_WARNING("%s: Malformed config key \"%s\"", m_Path.string().c_str(), key.c_str());
return;
}
m_Overrides[section][param] = boost::lexical_cast<std::string>(value);
m_Merged[section][param] = boost::lexical_cast<std::string>(value);
m_PTreeOverrides.put<T>(key, value);
m_PTreeMerged.put<T>(key, value);
}
#endif
-157
View File
@@ -1,157 +0,0 @@
#ifndef DeveloperConsole_h__
#define DeveloperConsole_h__
#include <iostream>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
#include "../Common.h"
#include "ConfigFile.h"
class DeveloperConsole
{
public:
DeveloperConsole() = delete;
static void MergeConfig(std::string configFile)
{
auto config = ResourceManager::Load<ConfigFile>("Config.ini");
LOG_DEBUG("Debug.LogLevel %i", config->Get<int>("Debug.LogLevel", -1));
config->Set("Debug.LogLevel", 8);
LOG_DEBUG("Debug.LogLevel %i", config->Get<int>("Debug.LogLevel", -1));
config->Set("Test.TesTest.Testies", "Hello");
config->SaveToDisk();
for (auto& section : config->GetSections()) {
for (auto& param : *section.second) {
std::cout << "// " << param.second->get_comment() << std::endl;
std::cout << section.first << "." << param.first << " " << param.second->get_value() << std::endl;
}
}
for (auto& section : config->GetSections()) {
for (auto& param : *section.second) {
std::string key = section.first + "." + param.first;
m_VariableBindingSetters[key] = [config, key](std::string value) {
config->Set<std::string>(key, value);
};
m_VariableBindingGetters[key] = [config, key]() {
return config->Get<std::string>(key, "");
};
}
}
}
template <typename T>
static typename std::enable_if<std::is_enum<T>::value, void>::type
BindVariable(std::string path, T& variable)
{
BindVariable<T, std::underlying_type<T>::type>(path, variable);
}
template <typename T, typename R = T>
static typename std::enable_if<!std::is_enum<R>::value, void>::type
BindVariable(std::string path, T& variable)
{
m_VariableBindingSetters[path] = [&variable](std::string value) {
variable = static_cast<T>(boost::lexical_cast<R>(value));
};
m_VariableBindingGetters[path] = [&variable]() {
return boost::lexical_cast<std::string>(static_cast<R>(variable));
};
}
static void Consume(const std::string& command)
{
if (command.empty()) {
return;
}
boost::char_separator<char> argumentSeparator(" ");
tokenizer tokens(command, argumentSeparator);
for (tokenizer::const_iterator it = tokens.begin(); it != tokens.end(); it++) {
consumeToken(it, tokens.end());
}
}
static void Consume(std::istream& stream)
{
std::string input;
std::getline(stream, input);
Consume(input);
/*if (stream.peek() == '\n') {
printValue(key);
} else {
std::string newValue;
stream >> newValue;
if (m_VariableBindingSetters.find(key) != m_VariableBindingSetters.end()) {
m_VariableBindingSetters.at(key)(newValue);
} else {
std::cout << "Unknown path: " << key << std::endl;
}
return;
for (auto& config : m_ConfigFiles) {
config->Set(key, newValue);
config->SaveToDisk();
LOG_DEBUG("Key %s set to new value %s and saved to disk.", key.c_str(), newValue.c_str());
}
} */
}
private:
typedef boost::tokenizer<boost::char_separator<char>> tokenizer;
static std::map<std::string, std::function<std::string()>> m_VariableBindingGetters;
static std::map<std::string, std::function<void(std::string)>> m_VariableBindingSetters;
static std::map<std::string, std::function<std::string(std::string)>> m_VariableBindingMappers;
static std::map<std::string, std::string> m_VariableDocumentation;
static void consumeToken(tokenizer::iterator& token, const tokenizer::iterator end)
{
tokenizer::iterator next = token;
next++;
if (next == end) {
printValue(token);
} else {
setValue(token, end);
}
}
static void printValue(tokenizer::iterator token)
{
std::string key = *token;
std::string value;
if (m_VariableBindingGetters.find(key) != m_VariableBindingGetters.end()) {
std::cout << key << " = " << m_VariableBindingGetters.at(key)() << std::endl;
} else {
std::cout << "Unknown path: " << key << std::endl;
}
return;
if (!value.empty()) {
std::cout << key << " = " << value << std::endl;
} else {
std::cerr << "Unknown path: " << key << std::endl;
}
}
static void setValue(tokenizer::iterator& token, const tokenizer::iterator end)
{
std::string key = *token;
std::string value = *(++token);
if (m_VariableBindingSetters.find(key) != m_VariableBindingSetters.end()) {
m_VariableBindingSetters.at(key)(value);
} else {
std::cout << "Unknown path: " << key << std::endl;
}
}
};
#endif
-1
View File
@@ -2,6 +2,5 @@
#define Entity_h__
typedef unsigned int EntityID;
const static unsigned int EntityID_Invalid = -1;
#endif
-293
View File
@@ -1,293 +0,0 @@
#ifndef EntityFile_h__
#define EntityFile_h__
#include <stack>
#include <boost/lexical_cast.hpp>
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include <xercesc/sax2/DefaultHandler.hpp>
#include <xercesc/sax2/Attributes.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLChar.hpp>
#include <xercesc/sax2/DefaultHandler.hpp>
#include <xercesc/framework/XMLDocumentHandler.hpp>
#include <xercesc/framework/psvi/XSElementDeclaration.hpp>
#include <xercesc/framework/psvi/XSComplexTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSParticle.hpp>
#include <xercesc/framework/psvi/XSModelGroup.hpp>
#include <xercesc/framework/psvi/XSAnnotation.hpp>
#include <xercesc/framework/psvi/XSValue.hpp>
#include <xercesc/framework/XMLGrammarPoolImpl.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/dom/DOMLSInput.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include "../GLM.h"
#include "Util/XercesString.h"
#include "ResourceManager.h"
#include "Entity.h"
#include "ComponentInfo.h"
class EntityFileHandler
{
friend class EntityFileSAXHandler;
public:
// @param EntityID The entity found
// @param EntityID The parent of the entity
typedef std::function<void(EntityID, EntityID, const std::string&)> OnStartEntityCallback;
void SetStartEntityCallback(OnStartEntityCallback c) { m_OnStartEntityCallback = c; }
// @param EntityID The entity the component corresponds to
// @param std::string Type name of the component
typedef std::function<void(EntityID, const std::string&)> OnStartComponentCallback;
void SetStartComponentCallback(OnStartComponentCallback c) { m_OnStartComponentCallback = c; }
// @param EntityID Entity
// @param std::string Component name
// @param std::string Field name
// @param std::map<std::string, std::string> Field attribute names and values
typedef std::function<void(EntityID, const std::string&, const std::string&, const std::map<std::string, std::string>&)> OnStartFieldCallback;
void SetStartFieldCallback(OnStartFieldCallback c) { m_OnStartFieldCallback = c; }
// @param EntityID Entity
// @param std::string Component name
// @param std::string Field name
// @param char* Field data
typedef std::function<void(EntityID, const std::string&, const std::string&, const char*)> OnStartFieldDataCallback;
void SetStartFieldDataCallback(OnStartFieldDataCallback c) { m_OnStartFieldDataCallback = c; }
private:
OnStartEntityCallback m_OnStartEntityCallback = nullptr;
OnStartComponentCallback m_OnStartComponentCallback = nullptr;
OnStartFieldCallback m_OnStartFieldCallback = nullptr;
OnStartFieldDataCallback m_OnStartFieldDataCallback = nullptr;
};
class EntityFileSAXHandler : public xercesc::DefaultHandler
{
public:
enum class State
{
Unknown,
Entity,
Component,
ComponentField
};
EntityFileSAXHandler(const EntityFileHandler* handler, xercesc::SAX2XMLReader* reader)
: m_Handler(handler)
, m_Reader(reader)
{
// 0 is imaginary world entity
m_EntityStack.push(0);
m_StateStack.push(State::Unknown);
}
void startElement(const XMLCh* const _uri, const XMLCh* const _localName, const XMLCh* const _qname, const xercesc::Attributes& attrs) override
{
std::string name = XS::ToString(_localName);
if (m_StateStack.top() == State::Unknown || m_StateStack.top() == State::Entity) {
if (name == "Entity") {
m_StateStack.push(State::Entity);
onStartEntity(attrs);
return;
}
if (name == "EntityRef") {
onStartEntityRef(attrs);
return;
}
}
std::string uri = XS::ToString(_uri);
if (m_StateStack.top() == State::Entity) {
if (uri == "components") {
m_StateStack.push(State::Component);
onStartComponent(name);
return;
}
}
if (m_StateStack.top() == State::Component) {
m_StateStack.push(State::ComponentField);
onStartComponentField(name, attrs);
return;
}
}
void characters(const XMLCh* const chars, const XMLSize_t length) override
{
if (m_StateStack.top() == State::ComponentField) {
char* transcoded = xercesc::XMLString::transcode(chars);
onFieldData(transcoded);
}
}
void endElement(const XMLCh* const _uri, const XMLCh* const _localName, const XMLCh* const _qname) override
{
std::string name = XS::ToString(_localName);
if (m_StateStack.top() == State::Entity) {
if (name == "Entity") {
m_StateStack.pop();
onEndEntity();
return;
}
}
std::string uri = XS::ToString(_uri);
if (m_StateStack.top() == State::Component) {
//if (uri == "components") {
m_StateStack.pop();
onEndComponent(name);
return;
//}
}
if (m_StateStack.top() == State::ComponentField) {
m_StateStack.pop();
onEndComponentField(name);
return;
}
}
void fatalError(const xercesc::SAXParseException& e)
{
XS::ToString s(e.getMessage());
LOG_ERROR("SAXParseException: %s", ((std::string)s).c_str());
//throw e;
}
private:
const EntityFileHandler* m_Handler;
xercesc::XMLGrammarPool* m_GrammarPool;
xercesc::SAX2XMLReader* m_Reader;
//State m_CurrentScope = State::Unknown;
std::stack<State> m_StateStack;
unsigned int m_NextEntityID = 0;
std::stack<EntityID> m_EntityStack;
std::string m_CurrentComponent;
std::string m_CurrentField;
std::map<std::string, std::string> m_CurrentAttributes;
void onStartEntity(const xercesc::Attributes& attrs)
{
EntityID parent = m_EntityStack.top();
if (m_Handler->m_OnStartEntityCallback) {
std::string name;
auto xName = attrs.getValue(XS::ToXMLCh("name"));
if (xName != nullptr) {
name = XS::ToString(xName);
}
m_Handler->m_OnStartEntityCallback(m_NextEntityID, parent, name);
}
m_EntityStack.push(m_NextEntityID);
m_NextEntityID++;
}
void onEndEntity()
{
m_EntityStack.pop();
}
void onStartEntityRef(const xercesc::Attributes& attrs)
{
std::string path = XS::ToString(attrs.getValue(XS::ToXMLCh("file")));
xercesc::SAX2XMLReader* parser = xercesc::XMLReaderFactory::createXMLReader();
parser->setContentHandler(this);
parser->setErrorHandler(this);
parser->parse(path.c_str());
delete parser;
}
void onStartComponent(const std::string& name)
{
//LOG_DEBUG(" Component: %s", name.c_str());
m_CurrentComponent = name;
if (m_Handler->m_OnStartComponentCallback) {
m_Handler->m_OnStartComponentCallback(m_EntityStack.top(), name);
}
}
void onEndComponent(const std::string& name) { }
void onStartComponentField(const std::string& field, const xercesc::Attributes& attrs)
{
//LOG_DEBUG(" Field: %s", field.c_str());
m_CurrentField = field;
m_CurrentAttributes.clear();
for (int i = 0; i < attrs.getLength(); i++) {
auto name = attrs.getQName(i);
auto value = attrs.getValue(name);
//LOG_DEBUG(" %s = %s", (char*)XS::ToString(name), (char*)XS::ToString(value));
m_CurrentAttributes[XS::ToString(name).operator std::string()] = XS::ToString(value).operator std::string();
}
if (m_Handler->m_OnStartFieldCallback) {
m_Handler->m_OnStartFieldCallback(m_EntityStack.top(), m_CurrentComponent, field, m_CurrentAttributes);
}
}
void onEndComponentField(const std::string& field) { }
void onFieldData(char* data)
{
//LOG_DEBUG(" Data: %s", data);
if (m_Handler->m_OnStartFieldDataCallback) {
m_Handler->m_OnStartFieldDataCallback(m_EntityStack.top(), m_CurrentComponent, m_CurrentField, data);
}
xercesc::XMLString::release(&data);
}
};
class EntityFileXMLErrorHandler : public xercesc::ErrorHandler
{
public:
void warning(const xercesc::SAXParseException& e) override
{
reportParseException("Warning", e);
}
void error(const xercesc::SAXParseException& e) override
{
reportParseException("Error", e);
}
void fatalError(const xercesc::SAXParseException& e) override
{
reportParseException("FATAL ERROR", e);
}
void resetErrors() override { }
private:
void reportParseException(std::string type, const xercesc::SAXParseException& e)
{
char* message = xercesc::XMLString::transcode(e.getMessage());
char* systemID = xercesc::XMLString::transcode(e.getSystemId());
std::cerr << systemID << ":" << e.getLineNumber() << ":" << e.getColumnNumber() << std::endl;
std::cerr << type << ": " << message << std::endl;
xercesc::XMLString::release(&systemID);
xercesc::XMLString::release(&message);
}
};
class EntityFile : public Resource
{
friend class ResourceManager;
private:
EntityFile(boost::filesystem::path path);
~EntityFile();
public:
static std::size_t GetTypeStride(std::string typeName);
static void WriteAttributeData(char* outData, const ComponentInfo::Field_t& field, const std::map<std::string, std::string>& attributes);
static void WriteValueData(char* outData, const ComponentInfo::Field_t& field, const char* valueData);
xercesc::XMLGrammarPool* GrammarPool() const { return m_GrammarPool; }
void Parse(const EntityFileHandler* handler) const;
private:
boost::filesystem::path m_FilePath;
xercesc::XMLGrammarPool* m_GrammarPool;
xercesc::SAX2XMLReader* m_SAX2XMLReader;
//std::map<std::string, ::ComponentInfo> m_ComponentInfo;
//std::vector<std::string> m_EntityReferences;
};
#endif
-28
View File
@@ -1,28 +0,0 @@
#ifndef EntityFileParser_h__
#define EntityFileParser_h__
#include "EntityFile.h"
#include "World.h"
class EntityFileParser
{
public:
EntityFileParser(const EntityFile* entityFile);
void MergeEntities(World* world);
private:
const EntityFile* m_EntityFile;
EntityFileHandler m_Handler;
World* m_World = nullptr;
// Maps EntityIDs local to the file to real IDs in the world after they've been
// created in order to resolve parent-child relationships.
std::map<EntityID, EntityID> m_EntityIDMapper;
void onStartEntity(EntityID entity, EntityID parent, const std::string& name);
void onStartComponent(EntityID entity, const std::string& component);
void onStartComponentField(EntityID entity, const std::string& componentType, const std::string& fieldName, const std::map<std::string, std::string>& attributes);
void onFieldData(EntityID entity, const std::string& componentType, const std::string& fieldName, const char* fieldData);
};
#endif
@@ -1,36 +0,0 @@
#ifndef EntityFilePreprocessor_h__
#define EntityFilePreprocessor_h__
#include <xercesc/framework/psvi/XSElementDeclaration.hpp>
#include <xercesc/framework/psvi/XSComplexTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSParticle.hpp>
#include <xercesc/framework/psvi/XSModelGroup.hpp>
#include <xercesc/framework/psvi/XSAnnotation.hpp>
#include <xercesc/framework/psvi/XSValue.hpp>
#include <xercesc/framework/MemBufFormatTarget.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include "Util/XercesString.h"
#include "ResourceManager.h"
#include "World.h"
#include "EntityFile.h"
class EntityFilePreprocessor
{
public:
EntityFilePreprocessor(const EntityFile* entityFile);
void RegisterComponents(World* world);
private:
const EntityFile* m_EntityFile;
std::map<std::string, unsigned int> m_ComponentCounts;
std::map<std::string, ComponentInfo> m_ComponentInfo;
void onStartComponent(EntityID entity, std::string type);
void parseComponentInfo();
void parseDefaults();
};
#endif
-39
View File
@@ -1,39 +0,0 @@
#ifndef EntityFileWriter_h__
#define EntityFileWriter_h__
#include <boost/filesystem.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/framework/LocalFileFormatTarget.hpp>
#include "Util/XercesString.h"
#include "EntityFile.h"
#include "World.h"
class EntityFileWriter
{
public:
EntityFileWriter(boost::filesystem::path file)
: m_FilePath(file)
{
using namespace xercesc;
m_DOMImplementation = DOMImplementationRegistry::getDOMImplementation(XS::ToXMLCh("LS"));
m_DOMLSSerializer = static_cast<DOMImplementationLS*>(m_DOMImplementation)->createLSSerializer();
m_DOMLSSerializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true);
m_DOMLSSerializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);
}
void WriteWorld(World* world);
void WriteEntity(World* world, EntityID entity);
private:
boost::filesystem::path m_FilePath;
xercesc::DOMImplementation* m_DOMImplementation;
xercesc::DOMLSSerializer* m_DOMLSSerializer;
void appendEntityChildren(xercesc::DOMElement* parentElement, const World* world, EntityID entity);
void appentEntityComponents(xercesc::DOMElement* parentElemetn, const World* world, EntityID entity);
};
#endif
+141
View File
@@ -0,0 +1,141 @@
#ifndef EntityXMLFile_h__
#define EntityXMLFile_h__
#include <sstream>
#include "../Common.h"
#include "../GLM.h"
#include <xercesc/dom/DOM.hpp>
#include <xercesc/dom/DOMLSInput.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <xercesc/framework/Wrapper4InputSource.hpp>
#include <xercesc/framework/LocalFileInputSource.hpp>
#include <xercesc/framework/LocalFileFormatTarget.hpp>
#include <xercesc/framework/MemBufFormatTarget.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
#include <xercesc/sax/HandlerBase.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLFloat.hpp>
#include <xercesc/framework/XMLGrammarPoolImpl.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/framework/psvi/XSElementDeclaration.hpp>
#include <xercesc/framework/psvi/XSComplexTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSParticle.hpp>
#include <xercesc/framework/psvi/XSModelGroup.hpp>
#include <xercesc/framework/psvi/XSAnnotation.hpp>
#include <xercesc/framework/psvi/XSValue.hpp>
#include <xercesc/framework/XMLValidator.hpp>
#include "ResourceManager.h"
#include "Entity.h"
#include "ComponentInfo.h"
class World;
class EntityPreprocessorXMLErrorHandler : public xercesc::DOMErrorHandler
{
public:
bool handleError(const xercesc::DOMError &e) override
{
char* message = xercesc::XMLString::transcode(e.getMessage());
std::cerr << "Preprocessor DOMError: " << message << std::endl;
xercesc::XMLString::release(&message);
return false;
}
};
class EntityParserXMLErrorHandler : public xercesc::ErrorHandler
{
public:
void warning(const xercesc::SAXParseException& e) override
{
reportParseException("Warning", e);
}
void error(const xercesc::SAXParseException& e) override
{
reportParseException("Error", e);
}
void fatalError(const xercesc::SAXParseException& e) override
{
reportParseException("FATAL ERROR", e);
}
void resetErrors() override { }
private:
void reportParseException(std::string type, const xercesc::SAXParseException& e)
{
char* message = xercesc::XMLString::transcode(e.getMessage());
char* systemID = xercesc::XMLString::transcode(e.getSystemId());
std::cerr << systemID << ":" << e.getLineNumber() << ":" << e.getColumnNumber() << std::endl;
std::cerr << type << ": " << message << std::endl;
xercesc::XMLString::release(&systemID);
xercesc::XMLString::release(&message);
}
};
class XSTR
{
public:
XSTR(const XMLCh* const xmlString)
{
m_AsChar = xercesc::XMLString::transcode(xmlString);
}
XSTR(const char* normalString)
{
m_AsXMLCh = xercesc::XMLString::transcode(normalString);
}
~XSTR()
{
if (m_AsChar != nullptr) {
xercesc::XMLString::release(&m_AsChar);
}
if (m_AsXMLCh != nullptr) {
xercesc::XMLString::release(&m_AsXMLCh);
}
}
operator const char*() const { return m_AsChar; }
operator const XMLCh*() const { return m_AsXMLCh; }
private:
char* m_AsChar = nullptr;
XMLCh* m_AsXMLCh = nullptr;
};
class EntityXMLFile : public Resource
{
friend class ResourceManager;
private:
EntityXMLFile(std::string path);
public:
~EntityXMLFile();
void PopulateWorld(World* world);
private:
static unsigned int InstanceCount;
std::string m_EntityFile;
xercesc::XMLGrammarPool* m_GrammarPool = nullptr;
EntityParserXMLErrorHandler* m_ErrorHandler = nullptr;
xercesc::XercesDOMParser* m_DOMParser = nullptr;
xercesc::DOMDocument* m_DOMDocument = nullptr;
std::map<std::string, ComponentInfo> m_ComponentInfo;
// Preprocesses the entity file to insert include-by-copy child entities
// TODO: Make this work in memory instead of saving to file
void preprocess(std::string inPath, std::string outPath);
void parseComponentInfo();
void parseDefaults();
void predictComponentAllocation();
void parseEntityGraph(World* world, xercesc::DOMElement* parent, EntityID parentEntity);
std::size_t getTypeStride(std::string typeName);
float getFloatAttribute(const xercesc::DOMElement* element, const char* attribute) const;
void writeData(const xercesc::DOMElement* element, std::string typeName, char* outData);
};
#endif
-23
View File
@@ -80,27 +80,4 @@ static void _LOG(_LOG_LEVEL logLevel, const char* file, const char* func, unsign
#define LOG_DEBUG(format, ...) \
LOG(LOG_LEVEL_DEBUG, format, ##__VA_ARGS__)
// Set the log level temporarily for the current scope
#define LOG_LEVEL_SCOPE(logLevel) \
_LOG_LEVEL_SCOPED_HELPER<logLevel> _logLevelScopedHelper;
template <_LOG_LEVEL LEVEL>
class _LOG_LEVEL_SCOPED_HELPER
{
public:
_LOG_LEVEL_SCOPED_HELPER()
{
m_OriginalLogLevel = LOG_LEVEL;
LOG_LEVEL = LEVEL;
}
~_LOG_LEVEL_SCOPED_HELPER()
{
LOG_LEVEL = m_OriginalLogLevel;
}
private:
_LOG_LEVEL m_OriginalLogLevel;
};
#endif // Logging_h__
-46
View File
@@ -1,46 +0,0 @@
#ifndef Util_XercesString_h__
#define Util_XercesString_h__
#include <string>
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/XMLString.hpp>
namespace XS
{
class ToString
{
public:
ToString(const XMLCh* const str) { m_AsChar = xercesc::XMLString::transcode(str); }
~ToString()
{
if (m_AsChar != nullptr) {
xercesc::XMLString::release(&m_AsChar);
}
}
operator std::string() const { return std::string(m_AsChar); }
private:
char* m_AsChar = nullptr;
};
class ToXMLCh
{
public:
ToXMLCh(const std::string str) { m_Transcoded = xercesc::XMLString::transcode(str.c_str()); }
ToXMLCh(const char* str) { m_Transcoded = xercesc::XMLString::transcode(str); }
~ToXMLCh()
{
if (m_Transcoded != nullptr) {
xercesc::XMLString::release(&m_Transcoded);
}
}
operator const XMLCh*() const { return m_Transcoded; }
private:
XMLCh* m_Transcoded = nullptr;
};
}
#endif
+3 -9
View File
@@ -16,14 +16,13 @@ public:
EntityID CreateEntity(EntityID parent = 0);
// Delete entity and all components within
void DeleteEntity(EntityID entity);
// Check if an entity exists
bool ValidEntity(EntityID entity) const;
// Register a component type and allocate space for it
void RegisterComponent(ComponentInfo& ci);
// Attach a component to an entity and fill it with default values
ComponentWrapper AttachComponent(EntityID entity, std::string componentType);
// Check if an entity has a component
bool HasComponent(EntityID entity, std::string componentType) const;
bool HasComponent(EntityID entity, std::string componentType);
// Get a component of an entity
ComponentWrapper GetComponent(EntityID entity, std::string componentType);
// Delete a component off an entity
@@ -38,19 +37,14 @@ public:
const std::unordered_map<std::string, ComponentPool*>& GetComponentPools() const { return m_ComponentPools; }
// Get the entity children map
const std::unordered_multimap<EntityID, EntityID>& GetEntityChildren() const { return m_EntityChildren; }
// Set the textual name of an entity
void SetName(EntityID entity, const std::string& name);
// Get the textual name of an entity
std::string GetName(EntityID entity) const;
private:
EntityID m_CurrentEntityID = 0;
EntityID m_CurrentEntityID = 1;
std::unordered_map<EntityID, EntityID> m_EntityParents;
// TODO: This should be a more effective structure
std::unordered_multimap<EntityID, EntityID> m_EntityChildren;
std::unordered_map<std::string, ComponentPool*> m_ComponentPools;
std::unordered_map<EntityID, std::string> m_EntityNames;
EntityID generateEntityID();
};
+10 -25
View File
@@ -1,7 +1,6 @@
#include <imgui/imgui.h>
#include <glm/gtx/common.hpp>
#include <boost/filesystem/path.hpp>
#include <nativefiledialog/nfd.h>
#include "../Core/System.h"
#include "../Core/EMousePress.h"
#include "../Core/EMouseRelease.h"
@@ -12,9 +11,6 @@
#include "../Rendering/EPicking.h"
#include "../Core/EFileDropped.h"
#include "../Rendering/RenderQueueFactory.h"
#include "../Core/EntityFilePreprocessor.h"
#include "../Core/EntityFileParser.h"
#include "../Core/EntityFileWriter.h"
class EditorSystem : public ImpureSystem
{
@@ -29,8 +25,6 @@ private:
bool m_Enabled;
bool m_Visible;
boost::filesystem::path m_DefaultEntityDir;
boost::filesystem::path m_CurrentFile;
std::vector<glm::vec2> m_PickingQueue;
enum class WidgetMode
@@ -47,26 +41,22 @@ private:
Global
} m_WidgetSpace = WidgetSpace::Global;
EntityID m_Widget = EntityID_Invalid;
EntityID m_WidgetX = EntityID_Invalid;
EntityID m_WidgetPlaneX = EntityID_Invalid;
EntityID m_WidgetY = EntityID_Invalid;
EntityID m_WidgetPlaneY = EntityID_Invalid;
EntityID m_WidgetZ = EntityID_Invalid;
EntityID m_WidgetPlaneZ = EntityID_Invalid;
EntityID m_WidgetOrigin = EntityID_Invalid;
EntityID m_Widget = 0;
EntityID m_WidgetX = 0;
EntityID m_WidgetPlaneX = 0;
EntityID m_WidgetY = 0;
EntityID m_WidgetPlaneY = 0;
EntityID m_WidgetZ = 0;
EntityID m_WidgetPlaneZ = 0;
EntityID m_WidgetOrigin = 0;
glm::vec3 m_WidgetCurrentAxis;
float m_WidgetPickingDepth = 0.f;
EntityID m_Selection = EntityID_Invalid;
EntityID m_LastSelection = EntityID_Invalid;
EntityID m_UIDraggingEntity = EntityID_Invalid;
EntityID m_Selection = 0;
EntityID m_LastSelection = 0;
glm::vec3 m_Position;
std::string m_LastDroppedFile;
static boost::filesystem::path openDialog(boost::filesystem::path defaultPath);
static boost::filesystem::path saveDialog(boost::filesystem::path defaultPath);
EventRelay<EditorSystem, Events::InputCommand> m_EInputCommand;
bool OnInputCommand(const Events::InputCommand& e);
EventRelay<EditorSystem, Events::MouseRelease> m_EMouseRelease;
@@ -80,15 +70,10 @@ private:
EventRelay<EditorSystem, Events::FileDropped> m_EFileDropped;
bool OnFileDropped(const Events::FileDropped& e);
void createWidget();
void updateWidget();
void setWidgetMode(WidgetMode newMode);
void setWidgetSpace(WidgetSpace space);
void drawUI(World* world, double dt);
bool createDeleteButton(std::string componentType);
bool createEntityNode(World* world, EntityID entity);
void changeParent(EntityID entity, EntityID newParent);
void fileImport(World* world);
void fileSave(World* world);
void fileSaveAs(World* world);
};
+38
View File
@@ -0,0 +1,38 @@
#ifndef DrawFinalPass_h__
#define DrawFinalPass_h__
#include "IRenderer.h"
#include "DrawFinalPassState.h"
#include "LightCullingPass.h"
#include "FrameBuffer.h"
#include "ShaderProgram.h"
#include "Util/UnorderedMapVec2.h"
#include "Texture.h"
class DrawFinalPass
{
public:
DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass);
~DrawFinalPass() { }
void InitializeTextures();
void InitializeFrameBuffers();
void InitializeShaderPrograms();
void Draw(RenderQueueCollection& rq);
//Getters
private:
void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const;
Texture* m_WhiteTexture;
const IRenderer* m_Renderer;
const LightCullingPass* m_LightCullingPass;
ShaderProgram* m_ForwardPlusProgram;
};
#endif
@@ -0,0 +1,15 @@
#ifndef DrawFinalPassState_h__
#define DrawFinalPassState_h__
#include "Rendering/RenderState.h"
class DrawFinalPassState : public RenderState
{
public:
DrawFinalPassState();
~DrawFinalPassState();
private:
};
#endif
+1 -1
View File
@@ -51,7 +51,7 @@ public:
if (it != PickingColorsToEntity->end()) {
pickData.Entity = it->second;
} else {
pickData.Entity = EntityID_Invalid;
pickData.Entity = 0;
}
pickData.Position = ScreenCoords::ToWorldPos(screenCoord.x, screenCoord.y, data.Depth, Resolution, ProjectionMatrix, ViewMatrix);
@@ -0,0 +1,78 @@
#ifndef LightCullingPass_h__
#define LightCullingPass_h__
#define TILE_SIZE 16
#define NUM_LIGHTS 1000
#include "IRenderer.h"
#include "LightCullingPassState.h"
#include "ShaderProgram.h"
class LightCullingPass
{
public:
LightCullingPass(IRenderer* renderer);
~LightCullingPass();
void GenerateNewFrustum();
void CullLights();
void FillLightList(RenderQueueCollection& rq);
GLuint FrustumSSBO() const { return m_FrustumSSBO; }
GLuint LightSSBO() const { return m_LightSSBO; }
GLuint LightGridSSBO() const { return m_LightGridSSBO; }
GLuint LightOffsetSSBO() const { return m_LightOffsetSSBO; }
GLuint LightIndexSSBO() const { return m_LightIndexSSBO; }
private:
void InitializeSSBOs();
void InitializeShaderPrograms();
const IRenderer* m_Renderer;
GLuint m_FrustumSSBO = 0;
GLuint m_LightSSBO = 0;
GLuint m_LightGridSSBO = 0;
GLuint m_LightOffsetSSBO = 0;
GLuint m_LightIndexSSBO = 0;
ShaderProgram* m_CalculateFrustumProgram;
ShaderProgram* m_LightCullProgram;
struct Plane {
glm::vec3 Normal;
float d;
};
struct Frustum {
Plane Planes[4];
};
Frustum m_Frustums[80*45]; //TODO: Renderer: Make this change with resolution
//This should be a component
struct PointLight {
glm::vec4 Position = glm::vec4(0.f);
glm::vec4 Color = glm::vec4(1.f);
float Radius = 5.f;
float Intensity = 0.8f;
float Falloff = 0.3f;
float Padding = 1337;
};
std::vector<PointLight> m_PointLights;
struct LightGrid {
float Start;
float Amount;
glm::vec2 Padding;
};
LightGrid m_LightGrid[80*45]; //TODO: Renderer: Make this change with resolution
int m_LightOffset = 0;
float m_LightIndex[80*45*200]; //TODO: Renderer: Make this change with resolution
};
#endif
+4 -2
View File
@@ -1,6 +1,8 @@
#ifndef PickingPass_h__
#define PickingPass_h__
#include "IRenderer.h"
#include "PickingPassState.h"
#include "FrameBuffer.h"
@@ -9,6 +11,8 @@
#include "../Core/EventBroker.h"
#include "EPicking.h"
class PickingPass
{
public:
@@ -20,7 +24,6 @@ public:
void Draw(RenderQueueCollection& rq);
//Getters
const ShaderProgram& PickingProgram() const { return *m_PickingProgram; }
const std::unordered_map<glm::vec2, EntityID>& PickingColorsToEntity() const { return m_PickingColorsToEntity; }
@@ -28,7 +31,6 @@ public:
GLuint DepthBuffer() const { return m_DepthBuffer; }
const FrameBuffer& PickingBuffer() const { return m_PickingBuffer; }
private:
void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const;
+6 -5
View File
@@ -82,11 +82,12 @@ struct SpriteJob : RenderJob
struct PointLightJob : RenderJob
{
glm::vec3 Position;
glm::vec3 SpecularColor = glm::vec3(1, 1, 1);
glm::vec3 DiffuseColor = glm::vec3(1, 1, 1);
float Radius = 1.f;
float Intensity = 0.8f;
glm::vec4 Position;
glm::vec4 Color;
float Radius;
float Intensity;
float Falloff;
float padding = 123;
void CalculateHash() override
{
+4 -61
View File
@@ -13,19 +13,8 @@
#include "PickingPass.h"
#include "DrawScenePass.h"
#include "DebugCameraInputController.h"
#define TILE_SIZE 16
#define NUM_LIGHTS 3
enum lightType
{
Point,
Spot,
Directional,
Area
};
#include "LightCullingPass.h"
#include "DrawFinalPass.h"
#include "../Core/EventBroker.h"
#include "EPicking.h"
@@ -58,70 +47,24 @@ private:
DrawScenePass* m_DrawScenePass;
PickingPass* m_PickingPass;
LightCullingPass* m_LightCullingPass;
ImGuiRenderPass* m_ImGuiRenderPass;
DrawFinalPass* m_DrawFinalPass;
//----------------------Functions----------------------//
void InitializeWindow();
void InitializeShaders();
void InitializeTextures();
void InitializeSSBOs();
void InitializeRenderPasses();
//TODO: Renderer: Get InputUpdate out of renderer
void InputUpdate(double dt);
//void PickingPass(RenderQueueCollection& rq);
void DrawScreenQuad(GLuint textureToDraw);
//----------------------Forward+-----------------------//
void CalculateFrustum();
void CullLights();
//Frustum
struct Plane {
glm::vec3 Normal;
float d;
};
struct Frustum {
Plane Planes[4];
};
Frustum m_Frustums[80*45]; //TODO: Renderer: Make this change with resolution
//Lights
void TEMPCreateLights();
//TODO: Renderer: Add Directionllights, spotlights and area lights to this as type.
struct PointLight {
glm::vec4 Position = glm::vec4(0.f);
glm::vec4 Color = glm::vec4(1.f);
float Radius = 5.f;
float Intensity = 0.8f;
float Falloff = 0.3f;
float Padding = 1337;
};
PointLight m_PointLights[NUM_LIGHTS];
struct LightGrid {
int Amount;
int Start;
glm::vec2 Padding;
};
LightGrid m_LightGrid[80*45];
int m_LightOffset = 0;
int m_LightIndex[80*45*200];
//-------------------------SSBO------------------------//
GLuint m_FrustumSSBO = 0;
GLuint m_LightSSBO = 1;
GLuint m_LightGridSSBO = 2;
GLuint m_LightOffsetSSBO = 3;
GLuint m_LightIndexSSBO = 4;
void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type);
//--------------------ShaderPrograms-------------------//
ShaderProgram* m_BasicForwardProgram;
ShaderProgram* m_DrawScreenQuadProgram;
ShaderProgram* m_CalculateFrustumProgram;
ShaderProgram* m_LightCullProgram;
};
#endif
+1 -3
View File
@@ -13,13 +13,11 @@
#include "Input/KeyboardInputHandler.h"
#include "Input/MouseInputHandler.h"
#include "Core/EKeyDown.h"
#include "Core/EntityFilePreprocessor.h"
#include "Core/EntityXMLFile.h"
#include "Core/SystemPipeline.h"
#include "RaptorCopterSystem.h"
#include "PlayerSystem.h"
#include "Editor/EditorSystem.h"
#include "Core/EntityFile.h"
#include "Core/EntityFileParser.h"
// Network
#include <boost/thread.hpp>
+1
View File
@@ -7,6 +7,7 @@
<xs:include schemaLocation="Components/RaptorCopter.xsd"/>
<xs:include schemaLocation="Components/Player.xsd"/>
<xs:include schemaLocation="Components/AABB.xsd"/>
<xs:include schemaLocation="Components/PointLight.xsd"/>
<xs:include schemaLocation="Components/Trigger.xsd"/>
<xs:include schemaLocation="Components/Health.xsd"/>
</xs:schema>
@@ -0,0 +1,7 @@
<c:PointLight>
<Color R="1" G="1" B="1" A="1"/>
<Radius>1.0</Radius>
<Intensity>0.8</Intensity>
<Falloff>0.3</Falloff>
<Visible>true</Visible>
</c:PointLight>
@@ -0,0 +1,20 @@
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:t="types">
<xs:import schemaLocation="../Types.xsd" namespace="types"/>
<xs:element name="PointLight">
<xs:annotation>
<xs:documentation>A pointlight that lights up geometry in a radius.</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:all>
<xs:element name="Color" type="t:Color" minOccurs="0"/>
<xs:element name="Radius" type="t:double" minOccurs="0"/>
<xs:element name="Intensity" type="t:double" minOccurs="0"/>
<xs:element name="Falloff" type="t:double" minOccurs="0"/>
<xs:element name="Visible" type="t:bool" minOccurs="0"/>
</xs:all>
</xs:complexType>
</xs:element>
</xs:schema>
-6
View File
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<Entity xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../Types/Entity.xsd" xmlns:c="components">
<Components>
<c:Transform/>
</Components>
</Entity>
@@ -1,68 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Entity xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xi="http://www.w3.org/2001/XInclude" xsi:noNamespaceSchemaLocation="../Types/Entity.xsd" xmlns:c="components" name="RaptorCopter">
<Components>
<c:Transform>
<Position X="0" Y="0"/>
<Orientation X="0.0" Y="0" Z="0.0"/>
</c:Transform>
<c:Model>
<Resource>Models/Core/UnitRaptor.obj</Resource>
<Color R="1" G="0.4" B="0.8"/>
</c:Model>
</Components>
<Children>
<Entity>
<Components>
<c:Transform>
<Position X="0" Y="0"/>
<Orientation X="0" Y="0" Z="0"/>
</c:Transform>
<c:RaptorCopter>
<Speed>20</Speed>
<Axis Y="1"/>
</c:RaptorCopter>
</Components>
<Children>
<Entity>
<Components>
<c:Transform>
<Position X="0" Y="0.4"/>
<Scale X="0.1" Y="0.4" Z="0.1"/>
</c:Transform>
<c:Model>
<Resource>Models/Core/UnitCylinder.obj</Resource>
<Color R="1" G="0.4" B="0.8"/>
</c:Model>
</Components>
</Entity>
<Entity>
<Components>
<c:Transform>
<Position X="0" Y="0.6"/>
<Scale X="1.7" Y="0.03" Z="0.1"/>
<Orientation X="0" Y="0" Z="0"/>
</c:Transform>
<c:Model>
<Resource>Models/Core/UnitCube.obj</Resource>
<Color R="1" G="0.4" B="0.8"/>
</c:Model>
</Components>
</Entity>
<Entity>
<Components>
<c:Transform>
<Position X="0" Y="0.6"/>
<Scale X="1.7" Y="0.03" Z="0.1"/>
<Orientation X="0" Y="1.57" Z="0"/>
</c:Transform>
<c:Model>
<Resource>Models/Core/UnitCube.obj</Resource>
<Color R="1" G="0.4" B="0.8"/>
</c:Model>
</Components>
</Entity>
</Children>
</Entity>
</Children>
</Entity>
+4 -4
View File
@@ -10,7 +10,7 @@
</c:Model>
</Components>
<Children>
<Entity>
<!--<Entity>
<Components>
<c:Transform>
<Position X="-1.5"/>
@@ -20,8 +20,8 @@
<Resource>Models/ScaleWidget.obj</Resource>
</c:Model>
</Components>
</Entity>
<Entity>
</Entity>-->
<!--<Entity>
<Components>
<c:Transform>
<Position X="1.5"/>
@@ -33,7 +33,7 @@
<c:Trigger>
</c:Trigger>
</Components>
</Entity>
</Entity>-->
<!--<Entity>
<Components>
<c:Player>
+1 -8
View File
@@ -16,6 +16,7 @@
<xs:element ref="c:RaptorCopter" minOccurs="0"/>
<xs:element ref="c:Player" minOccurs="0"/>
<xs:element ref="c:Health" minOccurs="0"/>
<xs:element ref="c:PointLight" minOccurs="0"/>
</xs:all>
</xs:complexType>
</xs:element>
@@ -24,19 +25,11 @@
<xs:complexType>
<xs:sequence>
<xs:element ref="Entity" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="EntityRef" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:all>
<xs:attribute name="file" type="xs:string" minOccurs="0"/>
</xs:all>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:all>
<xs:attribute ref="xml:base"/>
<xs:attribute name="name" type="xs:string" minOccurs="0" default=""/>
</xs:complexType>
</xs:element>
</xs:schema>
+154
View File
@@ -0,0 +1,154 @@
#version 430
//in uvec3 gl_NumWorkGroups; //contains the number of workgroups that have been dispatched to a compute shader
//in uvec3 gl_WorkGroupID; //contains the index of the workgroup currently being operated on by a compute shader
//in uvec3 gl_LocalInvocationID; //contains the index of work item currently being operated on by a compute shader
//in uvec3 gl_GlobalInvocationID; //contains the global index of work item currently being operated on by a compute shader
//in uint gl_LocalInvocationIndex; //contains the local linear index of work item currently being operated on by a compute shader
#define MAX_LIGHTS_PER_TILE 200
#define NUM_TILES 3600
#define TILE_SIZE 16
uniform mat4 V;
struct Plane {
vec3 Normal;
float d;
};
struct Frustum {
Plane Planes[4];
};
layout (std430, binding = 0) buffer FrustumBuffer
{
Frustum Data[];
} Frustums;
struct PointLight {
vec4 Position;
vec4 Color;
float Radius;
float Intensity;
float Falloff;
float Padding;
};
layout (std430, binding = 1) buffer LightBuffer
{
PointLight List[];
} PointLights;
struct LightGrid {
float Start;
float Amount;
vec2 Padding;
};
layout (std430, binding = 2) buffer LightGridBuffer
{
LightGrid Data[];
} LightGrids;
layout (std430, binding = 3) buffer LightOffsetBuffer
{
int LightOffset[];
};
layout (std430, binding = 4) buffer LightIndexBuffer
{
float LightIndex[];
};
shared int GroupLightCount;
shared int GroupLightIndexStartOffset;
shared int GroupLightIndex[MAX_LIGHTS_PER_TILE];
shared Frustum GroupFrustum;
int GroupIndex;
bool SphereInsidePlane(vec3 center, float radius, Plane plane)
{
return dot(plane.Normal, center) - plane.d > -radius;
}
bool SphereInsideFrustrum(vec3 center, float radius, Frustum frustum/*, float zNear, float zFar*/)
{
//Check depth here
//if ( sphere.c.z - sphere.r > zNear || sphere.c.z + sphere.r < zFar )
//{
// result = false;
//}
for (int i =0; i < 4; i++)
{
if(! SphereInsidePlane(center, radius, frustum.Planes[i]))
{
return false;
}
}
return true;
}
void AppendLight(int li)
{
int index;
index = atomicAdd(GroupLightCount, 1);
if( index < MAX_LIGHTS_PER_TILE )
{
GroupLightIndex[index] = int(li);
}
}
layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
void main ()
{
GroupIndex = int(gl_WorkGroupID.x + (gl_WorkGroupID.y * 80));
if(gl_LocalInvocationIndex == 0)
{
GroupLightCount = 0;
GroupFrustum = Frustums.Data[GroupIndex];
}
barrier();
memoryBarrierShared();
for(int i = int(gl_LocalInvocationIndex); i < PointLights.List.length(); i += TILE_SIZE*TILE_SIZE)
{
PointLight light = PointLights.List[i];
//if pointlight
//Pos i view antagligen
if(SphereInsideFrustrum( vec3(V * light.Position), light.Radius, GroupFrustum))
{
//TODO: Fix transparent and opaque list, and depth test.
AppendLight( i );
}
//if conelight
//if directional
}
barrier();
memoryBarrierShared();
if(gl_LocalInvocationIndex == 0)
{
GroupLightIndexStartOffset = atomicAdd(LightOffset[0], GroupLightCount);
LightGrids.Data[GroupIndex].Start = GroupLightIndexStartOffset;
LightGrids.Data[GroupIndex].Amount = GroupLightCount;
}
barrier();
for (uint i = gl_LocalInvocationIndex; i < GroupLightCount; i += TILE_SIZE * TILE_SIZE )
{
LightIndex[GroupLightIndexStartOffset + i] = GroupLightIndex[i];
}
}
+132
View File
@@ -0,0 +1,132 @@
#version 430
uniform mat4 M;
uniform mat4 V;
uniform mat4 P;
uniform vec4 Color;
uniform sampler2D texture0;
#define TILE_SIZE 16
struct PointLight {
vec4 Position;
vec4 Color;
float Radius;
float Intensity;
float Falloff;
float Padding;
};
layout (std430, binding = 1) buffer LightBuffer
{
PointLight List[];
} PointLights;
struct LightGrid {
float Start;
float Amount;
vec2 Padding;
};
layout (std430, binding = 2) buffer LightGridBuffer
{
LightGrid Data[];
} LightGrids;
layout (std430, binding = 4) buffer LightIndexBuffer
{
float LightIndex[];
};
in VertexData{
vec3 Position;
vec3 Normal;
vec2 TextureCoordinate;
vec4 DiffuseColor;
}Input;
out vec4 fragmentColor;
vec4 scene_ambient = vec4(0.3,0.3,0.3,1);
struct LightResult {
vec4 Diffuse;
vec4 Specular;
};
float CalcAttenuation(float radius, float dist) {
return 1.0 - smoothstep(radius * 0.3, radius, dist);
}
vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) {
vec4 R = normalize( reflect(-lightVec, normal));
float RdotV = max( dot(R, viewVec), 0.0);
return lightColor * pow(RdotV, 90.0);
}
vec4 CalcDiffuse(vec4 lightColor, vec4 lightVec, vec4 normal) {
float power = max( dot(normal, lightVec), 0.0);
return lightColor * power;
}
LightResult CalcPointLight(vec4 lightPos, float lightRadius, vec4 lightColor, float intensity, vec4 viewVec, vec4 position, vec4 normal)
{
vec4 L = lightPos - position;
float dist = length(L);
L = normalize(L);
float attenuation = CalcAttenuation(lightRadius, dist);
LightResult result;
result.Diffuse = CalcDiffuse(lightColor, L, normal) * attenuation * intensity;
result.Specular = CalcSpecular(lightColor, viewVec, L, normal) * attenuation * intensity;
return result;
}
void main()
{
vec4 texel = texture2D(texture0, Input.TextureCoordinate);
vec4 position = V * M * vec4(Input.Position, 1.0);
vec4 normal = V * vec4(Input.Normal, 0.0);
vec4 viewVec = normalize(-position);
vec2 tilePos;
tilePos.x = int(gl_FragCoord.x/16);
tilePos.y = int(gl_FragCoord.y/16);
LightResult totalLighting;
totalLighting.Diffuse = scene_ambient;
int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * 80));
int start = int(LightGrids.Data[currentTile].Start);
int amount = int(LightGrids.Data[currentTile].Amount);
//for(int i = 0; i < 3; i++)
for(int i = start; i < start + amount; i++)
{
int l = int(LightIndex[i]);
LightResult result = CalcPointLight(V * PointLights.List[l].Position, PointLights.List[l].Radius, PointLights.List[l].Color, PointLights.List[l].Intensity, viewVec, position, normal);
totalLighting.Diffuse += result.Diffuse;
totalLighting.Specular += result.Specular;
}
fragmentColor += Input.DiffuseColor * (totalLighting.Diffuse + totalLighting.Specular) * texel * Color;
//fragmentColor += Input.DiffuseColor * (totalLighting.Diffuse) * texel * Color;
//fragmentColor += vec4(0.0, LightGrids.Data[currentTile].Amount/3.0, 0, 1);
//fragmentColor = texel * Input.DiffuseColor * Color;
if(int(gl_FragCoord.x)%16 == 0 || int(gl_FragCoord.y)%16 == 0 )
{
//fragmentColor += vec4(0.5, 0, 0, 0);
} else {
//fragmentColor += vec4(LightGrids.Data[int(tilePos.x + tilePos.y*80)].Amount/3.0, 0, 0, 1);
}
}
+34
View File
@@ -0,0 +1,34 @@
#version 430
uniform mat4 M;
uniform mat4 V;
uniform mat4 P;
layout(location = 0) in vec3 Position;
layout(location = 1) in vec3 Normal;
layout(location = 2) in vec3 Tangent;
layout(location = 3) in vec3 BiTangent;
layout(location = 4) in vec2 TextureCoords;
layout(location = 5) in vec4 DiffuseVertexColor;
layout(location = 6) in vec4 SpecularVertexColor;
layout(location = 7) in vec4 BoneIndices1;
layout(location = 8) in vec4 BoneIndices2;
layout(location = 9) in vec4 BoneWeights1;
layout(location = 10) in vec4 BoneWeights2;
out VertexData{
vec3 Position;
vec3 Normal;
vec2 TextureCoordinate;
vec4 DiffuseColor;
}Output;
void main()
{
gl_Position = P*V*M * vec4(Position, 1.0);
Output.Position = Position;
Output.TextureCoordinate = TextureCoords;
Output.Normal = Normal;
Output.DiffuseColor = DiffuseVertexColor;
}
+27 -24
View File
@@ -16,7 +16,7 @@ struct Frustum {
layout (std430, binding = 0) buffer FrustumBuffer
{
Frustum Data[3600];
Frustum Data[];
} Frustums;
vec4 ConvertToView(vec4 ScreenCoords)
@@ -43,31 +43,34 @@ Plane ComputePlane( vec3 p0, vec3 p1, vec3 p2 )
layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
void main ()
{
if(gl_GlobalInvocationID.x * TILE_SIZE < ScreenDimensions.x && gl_GlobalInvocationID.y * TILE_SIZE < ScreenDimensions.y) {
//Top-Left = 0 | Top-Right = 1
//Bottom-Left = 2 | Bottom-Right = 3
vec4 ScreenCoords[4];
ScreenCoords[0] = vec4(gl_GlobalInvocationID.x * TILE_SIZE, (gl_GlobalInvocationID.y + 1 ) * TILE_SIZE, -1.0, 1.0); // Z-axis might need to be 1
ScreenCoords[1] = vec4((gl_GlobalInvocationID.x + 1) * TILE_SIZE, (gl_GlobalInvocationID.y + 1) * TILE_SIZE, -1.0, 1.0);
ScreenCoords[2] = vec4(gl_GlobalInvocationID.x * TILE_SIZE, (gl_GlobalInvocationID.y) * TILE_SIZE, -1.0, 1.0);
ScreenCoords[3] = vec4((gl_GlobalInvocationID.x + 1) * TILE_SIZE, (gl_GlobalInvocationID.y) * TILE_SIZE, -1.0, 1.0);
vec3 ViewVectors[4];
for(int i = 0; i < 4; i++) {
ViewVectors[i] = vec3(ConvertToView(ScreenCoords[i]));
}
vec3 EyePos = vec3(0,0,0);
Frustum f;
f.Planes[0] = ComputePlane(EyePos, ViewVectors[2], ViewVectors[0]);
f.Planes[1] = ComputePlane(EyePos, ViewVectors[1], ViewVectors[3]);
f.Planes[2] = ComputePlane(EyePos, ViewVectors[0], ViewVectors[1]);
f.Planes[3] = ComputePlane(EyePos, ViewVectors[3], ViewVectors[2]);
//Top-Left = 0 | Top-Right = 1
//Bottom-Left = 2 | Bottom-Right = 3
vec4 ScreenCoords[4];
ScreenCoords[0] = vec4(gl_GlobalInvocationID.x * TILE_SIZE, (gl_GlobalInvocationID.y + 1) * TILE_SIZE, -1.0, 1.0);
ScreenCoords[1] = vec4((gl_GlobalInvocationID.x + 1) * TILE_SIZE, (gl_GlobalInvocationID.y + 1) * TILE_SIZE, -1.0, 1.0);
ScreenCoords[2] = vec4(gl_GlobalInvocationID.x * TILE_SIZE, (gl_GlobalInvocationID.y) * TILE_SIZE, -1.0, 1.0);
ScreenCoords[3] = vec4((gl_GlobalInvocationID.x + 1) * TILE_SIZE, (gl_GlobalInvocationID.y) * TILE_SIZE, -1.0, 1.0);
Frustums.Data[gl_GlobalInvocationID.x + gl_GlobalInvocationID.y*80] = f;
vec3 ViewVectors[4];
for(int i = 0; i < 4; i++) {
ViewVectors[i] = vec3(ConvertToView(ScreenCoords[i]));
}
vec3 EyePos = vec3(0.0, 0.0 ,0.0);
Frustum f;
f.Planes[0] = ComputePlane(EyePos, ViewVectors[2], ViewVectors[0]); // left plane
f.Planes[1] = ComputePlane(EyePos, ViewVectors[1], ViewVectors[3]); // right plane
f.Planes[2] = ComputePlane(EyePos, ViewVectors[0], ViewVectors[1]); // top plane
f.Planes[3] = ComputePlane(EyePos, ViewVectors[3], ViewVectors[2]); // bottom plane
if ( gl_GlobalInvocationID.x < ScreenDimensions.x / TILE_SIZE && gl_GlobalInvocationID.y < ScreenDimensions.y / TILE_SIZE ) { // inside the screen
Frustums.Data[gl_GlobalInvocationID.x + gl_GlobalInvocationID.y*80] = f;
}
}
-35
View File
@@ -1,35 +0,0 @@
#version 430
//in uvec3 gl_NumWorkGroups;
//in uvec3 gl_WorkGroupID;
//in uvec3 gl_LocalInvocationID;
//in uvec3 gl_GlobalInvocationID;
//in uint gl_LocalInvocationIndex;
#define NUM_LIGHTS 3
#define MAX_LIGHTS_PER_TILE 200
#define NUM_TILES 3600
struct Plane {
vec3 Normal;
float d;
};
struct Frustum {
Plane Planes[4];
};
layout (std430, binding = 0) buffer FrustumBuffer
{
Frustum Data[3600];
} Frustums;
layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
void main ()
{
if(1 == 1) {
}
}
+1 -17
View File
@@ -90,28 +90,12 @@ set(SOURCE_FILES
${SOURCE_FILES_Rendering}
${SOURCE_FILES_Rendering_Util}
${SOURCE_FILES_Collision}
${SOURCE_FILES_Editor}
${CMAKE_SOURCE_DIR}/deps/include/imgui/imgui.cpp
${CMAKE_SOURCE_DIR}/deps/include/imgui/imgui_draw.cpp
${CMAKE_SOURCE_DIR}/deps/include/imgui/imgui_demo.cpp
${CMAKE_SOURCE_DIR}/deps/include/ini_file/ini_file.cpp
${CMAKE_SOURCE_DIR}/deps/include/nativefiledialog/nfd_common.c
${SOURCE_FILES_Editor}
)
# nativefiledialog
if(WIN32)
set(SOURCE_FILES ${SOURCE_FILES}
${CMAKE_SOURCE_DIR}/deps/include/nativefiledialog/nfd_win.cpp
)
endif()
if(UNIX)
set(SOURCE_FILES ${SOURCE_FILES}
${CMAKE_SOURCE_DIR}/deps/include/nativefiledialog/nfd_gtk.c
# TODO: Link with GTK+ here!
)
endif()
set(LIBRARIES
${OPENGL_LIBRARIES}
${GLEW_LIBRARIES}
+19 -93
View File
@@ -7,110 +7,36 @@ ConfigFile::ConfigFile(std::string path)
boost::filesystem::path defaultFile;
defaultFile = m_Path.parent_path() / ("Default" + m_Path.filename().string());
std::fstream file;
// Read defaults
file.open(defaultFile.string());
if (file) {
if (boost::filesystem::exists(defaultFile)) {
try {
file >> m_Defaults;
} catch (ini_file::ini_exceptions::ini_file_exception& e) {
LOG_ERROR("Failed to parse \"%s\":\n%s", defaultFile.string().c_str(), "ini_file_exception");
}
} else {
LOG_WARNING("Failed to find \"%s\"! Relying on hardcoded default values!", defaultFile.string().c_str());
}
file.close();
// Read overrides
file.open(m_Path.string());
if (file) {
try {
file >> m_Overrides;
} catch (ini_file::ini_exceptions::ini_file_exception& e) {
LOG_ERROR("Failed to parse \"%s\":\n%s", defaultFile.string().c_str(), "ini_file_exception");
boost::property_tree::ini_parser::read_ini(defaultFile.string(), m_PTreeDefaults);
} catch (boost::property_tree::ptree_error& e) {
LOG_ERROR("Failed to parse \"%s\":\n%s", defaultFile.string().c_str(), e.what());
}
} else {
LOG_ERROR("Failed to find \"%s\"! Relying on hardcoded default values!", defaultFile.string().c_str());
}
file.close();
// Merge
mergeINI(m_Merged, m_Defaults);
mergeINI(m_Merged, m_Overrides);
}
m_PTreeMerged = m_PTreeDefaults;
const ini_file::section* ConfigFile::GetSection(std::string section)
{
auto sectionIt = m_Merged.find(section);
if (sectionIt == m_Merged.end()) {
LOG_WARNING("%s: Unknown section \"%s\"", m_Path.string().c_str(), section.c_str());
return nullptr;
}
return sectionIt->second.get();
}
const ini_file::param* ConfigFile::GetParam(std::string key)
{
std::string section;
std::string param;
if (auto tokens = tokenizeKey(key)) {
std::tie(section, param) = *tokens;
} else {
LOG_WARNING("%s: Malformed config key \"%s\"", m_Path.string().c_str(), key.c_str());
return nullptr;
}
auto sectionIt = m_Merged.find(section);
if (sectionIt == m_Merged.end()) {
LOG_WARNING("%s: Unknown section \"%s\"", m_Path.string().c_str(), section.c_str());
return nullptr;
}
auto paramIt = sectionIt->second->find(param);
if (paramIt == sectionIt->second->end()) {
LOG_WARNING("%s: Unknown section param \"%s\"", m_Path.string().c_str(), key.c_str());
return nullptr;
}
return paramIt->second.get();
}
void ConfigFile::SaveToDisk()
{
std::ofstream file(m_Path.string());
file << m_Overrides;
file.close();
}
void ConfigFile::mergeINI(ini_file::section_map& to, const ini_file::section_map& from)
{
for (auto& section : from) {
for (auto& param : *section.second) {
auto& p = to[section.first][param.first];
if (!param.second->get_comment().empty()) {
p.set_comment(param.second->get_comment());
// Read overrides
if (boost::filesystem::exists(m_Path)) {
try {
boost::property_tree::ini_parser::read_ini(m_Path.string(), m_PTreeOverrides);
for (auto& topLevelNode : m_PTreeOverrides) {
auto& mergedTopLevelNode = m_PTreeMerged.find(topLevelNode.first);
for (auto& childOverrideNode : topLevelNode.second) {
mergedTopLevelNode->second.put_child(childOverrideNode.first, childOverrideNode.second);
}
}
p.set_value(param.second->get_value());
} catch (boost::property_tree::ptree_error& e) {
LOG_ERROR("Failed to parse \"%s\":\n%s", m_Path.filename().string().c_str(), e.what());
}
}
}
boost::optional<std::pair<std::string, std::string>> ConfigFile::tokenizeKey(std::string key)
void ConfigFile::SaveToDisk()
{
std::size_t delimiter = key.find_last_of('.');
if (delimiter == std::string::npos) {
return boost::none;
}
std::string section = key.substr(0, delimiter);
if (section.empty()) {
return boost::none;
}
std::string param = key.substr(delimiter + 1);
if (param.empty()) {
return boost::none;
}
return std::make_pair(section, param);
}
boost::property_tree::ini_parser::write_ini(m_Path.string(), m_PTreeOverrides);
}
-4
View File
@@ -1,4 +0,0 @@
#include "Core/DeveloperConsole.h"
std::map<std::string, std::function<void(std::string)>> DeveloperConsole::m_VariableBindingSetters;
std::map<std::string, std::function<std::string()>> DeveloperConsole::m_VariableBindingGetters;
-95
View File
@@ -1,95 +0,0 @@
#include "Core/EntityFile.h"
EntityFile::EntityFile(boost::filesystem::path path)
: m_FilePath(path)
{
using namespace xercesc;
XMLPlatformUtils::Initialize();
m_GrammarPool = new XMLGrammarPoolImpl();
m_SAX2XMLReader = XMLReaderFactory::createXMLReader(XMLPlatformUtils::fgMemoryManager, m_GrammarPool);
}
EntityFile::~EntityFile()
{
delete m_SAX2XMLReader;
delete m_GrammarPool;
xercesc::XMLPlatformUtils::Terminate();
}
void EntityFile::Parse(const EntityFileHandler* handler) const
{
using namespace xercesc;
EntityFileSAXHandler saxHandler(handler, nullptr);
m_SAX2XMLReader->setFeature(XMLUni::fgXercesCacheGrammarFromParse, true);
m_SAX2XMLReader->setFeature(XMLUni::fgXercesUseCachedGrammarInParse, true);
m_SAX2XMLReader->setContentHandler(&saxHandler);
m_SAX2XMLReader->setErrorHandler(&saxHandler);
m_SAX2XMLReader->setDeclarationHandler(&saxHandler);
m_SAX2XMLReader->parse(m_FilePath.string().c_str());
}
std::size_t EntityFile::GetTypeStride(std::string typeName)
{
std::map<std::string, size_t> typeStrides{
{ "bool", sizeof(bool) },
{ "int", sizeof(int) },
{ "float", sizeof(float) },
{ "double", sizeof(double) },
{ "string", sizeof(std::string) },
{ "Vector", sizeof(glm::vec3) },
{ "Quaternion", sizeof(glm::quat) },
{ "Color", sizeof(glm::vec4) }
};
auto it = typeStrides.find(typeName);
return (it != typeStrides.end()) ? it->second : 0;
}
void EntityFile::WriteAttributeData(char* outData, const ComponentInfo::Field_t& field, const std::map<std::string, std::string>& attributes)
{
if (field.Type == "Vector") {
glm::vec3 vec;
vec.x = boost::lexical_cast<float>(attributes.at("X"));
vec.y = boost::lexical_cast<float>(attributes.at("Y"));
vec.z = boost::lexical_cast<float>(attributes.at("Z"));
memcpy(outData, reinterpret_cast<char*>(&vec), field.Stride);
} else if (field.Type == "Color") {
glm::vec4 vec;
vec.r = boost::lexical_cast<float>(attributes.at("R"));
vec.g = boost::lexical_cast<float>(attributes.at("G"));
vec.b = boost::lexical_cast<float>(attributes.at("B"));
vec.a = boost::lexical_cast<float>(attributes.at("A"));
memcpy(outData, reinterpret_cast<char*>(&vec), field.Stride);
} else if (field.Type == "Quaternion") {
glm::quat q;
q.x = boost::lexical_cast<float>(attributes.at("X"));
q.y = boost::lexical_cast<float>(attributes.at("Y"));
q.z = boost::lexical_cast<float>(attributes.at("Z"));
q.w = boost::lexical_cast<float>(attributes.at("W"));
memcpy(outData, reinterpret_cast<char*>(&q), field.Stride);
} else if (!attributes.empty()) {
LOG_WARNING("%i attributes not handled by any type conversion!", attributes.size());
}
}
void EntityFile::WriteValueData(char* outData, const ComponentInfo::Field_t& field, const char* valueData)
{
if (field.Type == "int") {
int value = boost::lexical_cast<int>(valueData);
memcpy(outData, reinterpret_cast<char*>(&value), field.Stride);
} else if (field.Type == "float") {
float value = boost::lexical_cast<float>(valueData);
memcpy(outData, reinterpret_cast<char*>(&value), field.Stride);
} else if (field.Type == "double") {
double value = boost::lexical_cast<double>(valueData);
memcpy(outData, reinterpret_cast<char*>(&value), field.Stride);
} else if (field.Type == "bool") {
bool value = (valueData[0] == 't'); // Lazy bool evaluation
memcpy(outData, reinterpret_cast<char*>(&value), field.Stride);
} else if (field.Type == "string") {
new (outData) std::string(valueData);
} else {
LOG_WARNING("Unknown value data type: %s", field.Type.c_str());
}
}
-61
View File
@@ -1,61 +0,0 @@
#include "Core/EntityFileParser.h"
EntityFileParser::EntityFileParser(const EntityFile* entityFile)
: m_EntityFile(entityFile)
{
m_Handler.SetStartEntityCallback(std::bind(&EntityFileParser::onStartEntity, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
m_Handler.SetStartComponentCallback(std::bind(&EntityFileParser::onStartComponent, this, std::placeholders::_1, std::placeholders::_2));
m_Handler.SetStartFieldCallback(std::bind(&EntityFileParser::onStartComponentField, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));
m_Handler.SetStartFieldDataCallback(std::bind(&EntityFileParser::onFieldData, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));
}
void EntityFileParser::MergeEntities(World* world)
{
m_World = world;
m_EntityIDMapper[0] = 0;
m_EntityFile->Parse(&m_Handler);
}
void EntityFileParser::onStartEntity(EntityID entity, EntityID parent, const std::string& name)
{
EntityID realParent = m_EntityIDMapper.at(parent);
EntityID realEntity = m_World->CreateEntity(realParent);
if (!name.empty()) {
m_World->SetName(realEntity, name);
}
m_EntityIDMapper[entity] = realEntity;
LOG_DEBUG("Created entity #%i (%i) with parent %i (%i)", entity, realEntity, parent, realParent);
}
void EntityFileParser::onStartComponent(EntityID entity, const std::string& component)
{
EntityID realEntity = m_EntityIDMapper.at(entity);
m_World->AttachComponent(realEntity, component);
LOG_DEBUG("Attached component of type \"%s\" to entity #%i (%i)", component.c_str(), entity, realEntity);
}
void EntityFileParser::onStartComponentField(EntityID entity, const std::string& componentType, const std::string& fieldName, const std::map<std::string, std::string>& attributes)
{
EntityID realEntity = m_EntityIDMapper.at(entity);
ComponentWrapper component = m_World->GetComponent(realEntity, componentType);
auto& field = component.Info.Fields.at(fieldName);
LOG_DEBUG("Field \"%s\" type \"%s\"", fieldName.c_str(), field.Type.c_str());
LOG_DEBUG("Attributes:");
for (auto& kv : attributes) {
LOG_DEBUG("\t%s = %s", kv.first.c_str(), kv.second.c_str());
}
char* data = component.Data + field.Offset;
EntityFile::WriteAttributeData(data, field, attributes);
}
void EntityFileParser::onFieldData(EntityID entity, const std::string& componentType, const std::string& fieldName, const char* fieldData)
{
EntityID realEntity = m_EntityIDMapper.at(entity);
ComponentWrapper component = m_World->GetComponent(realEntity, componentType);
auto& field = component.Info.Fields.at(fieldName);
char* data = component.Data + field.Offset;
EntityFile::WriteValueData(data, field, fieldData);
}
-229
View File
@@ -1,229 +0,0 @@
#include "Core/EntityFilePreprocessor.h"
EntityFilePreprocessor::EntityFilePreprocessor(const EntityFile* entityFile)
: m_EntityFile(entityFile)
{
EntityFileHandler handler;
handler.SetStartComponentCallback(std::bind(&EntityFilePreprocessor::onStartComponent, this, std::placeholders::_1, std::placeholders::_2));
m_EntityFile->Parse(&handler);
LOG_DEBUG("___ COMPONENT DEFINITIONS ___");
for (auto& kv : m_ComponentCounts) {
LOG_DEBUG("%s: %i", kv.first.c_str(), kv.second);
}
parseComponentInfo();
for (auto& kv : m_ComponentInfo) {
auto& info = kv.second;
LOG_DEBUG("Component: %s (%s)", info.Name.c_str(), info.Meta.Annotation.c_str());
LOG_DEBUG("Stride: %i", info.Meta.Stride);
LOG_DEBUG("Allocation: %i", info.Meta.Allocation);
for (auto& kv : info.Fields) {
auto& field = kv.second;
LOG_DEBUG("\t%i\t%s %s", field.Offset, field.Type, kv.first.c_str());
}
}
parseDefaults();
}
void EntityFilePreprocessor::RegisterComponents(World* world)
{
for (auto& kv : m_ComponentInfo) {
world->RegisterComponent(kv.second);
}
}
void EntityFilePreprocessor::onStartComponent(EntityID entity, std::string type)
{
//LOG_DEBUG("Component: %s", type.c_str());
m_ComponentCounts[type]++;
}
void EntityFilePreprocessor::parseComponentInfo()
{
using namespace xercesc;
EntityFileXMLErrorHandler errorHandler;
auto grammarPool = m_EntityFile->GrammarPool();
bool whateverTheFuckThisIs;
auto xsModel = grammarPool->getXSModel(whateverTheFuckThisIs);
// Find component xsd element declarations
std::cout << "Enumerating components..." << std::endl;
// <xs:element name="ComponentName">
auto topLevelElements = xsModel->getComponents(XSConstants::ELEMENT_DECLARATION);
for (unsigned int i = 0; i < topLevelElements->getLength(); ++i) {
auto element = static_cast<XSElementDeclaration*>(topLevelElements->item(i));
std::string nameSpace = XS::ToString(element->getNamespace());
if (nameSpace != "components") {
continue;
}
ComponentInfo compInfo;
// Name
compInfo.Name = XS::ToString(element->getName());
// Known allocation
compInfo.Meta.Allocation = m_ComponentCounts[compInfo.Name];
// Annotation
auto componentAnnotation = element->getAnnotation();
if (componentAnnotation != nullptr) {
// Parse annotation XML
char* annotationString = XMLString::transcode(componentAnnotation->getAnnotationString());
MemBufInputSource annotationInput(reinterpret_cast<const XMLByte*>(annotationString), strlen(annotationString), "MemBuf: Annotation String");
XercesDOMParser parser(nullptr, XMLPlatformUtils::fgMemoryManager, grammarPool);
parser.setErrorHandler(&errorHandler);
parser.parse(annotationInput);
XMLString::release(&annotationString);
auto doc = parser.getDocument();
// TODO: Add allocation estimations from external file on map-to-map basis
// Add allocation estimation(s)
//auto allocationTags = doc->getElementsByTagName(XSTR("meta:allocation"));
//for (int i = 0; i < allocationTags->getLength(); ++i) {
// auto allocation = dynamic_cast<DOMElement*>(allocationTags->item(i));
// auto child = allocation->getFirstChild();
// if (child == nullptr) {
// continue;
// }
// XSValue::Status status;
// XSValue* val = XSValue::getActualValue(child->getNodeValue(), XSValue::dt_integer, status);
// compInfo.Meta.Allocation += val->fData.fValue.f_int;
//}
// Save documentation string
auto documentationTags = doc->getElementsByTagName(XS::ToXMLCh("xs:documentation"));
if (documentationTags->getLength() != 0) {
auto child = documentationTags->item(0)->getFirstChild();
if (child != nullptr) {
compInfo.Meta.Annotation = XS::ToString(child->getNodeValue());
}
}
} else {
LOG_WARNING("Component is missing an annotation!");
}
// <xs:complexType>
auto typeDefinition = element->getTypeDefinition();
if (typeDefinition->getTypeCategory() != XSTypeDefinition::COMPLEX_TYPE) {
LOG_ERROR("Type definition wasn't COMPLEX_TYPE! Skipping.");
continue;
}
auto complexTypeDefinition = dynamic_cast<XSComplexTypeDefinition*>(typeDefinition);
// <xs:all>
auto modelGroupParticle = complexTypeDefinition->getParticle();
if (modelGroupParticle->getTermType() != XSParticle::TERM_MODELGROUP) {
LOG_ERROR("Model group particle wasn't TERM_MODELGROUP! Skipping.");
continue;
}
auto modelGroup = modelGroupParticle->getModelGroupTerm();
// <xs:element...
// <xs:attribute...
unsigned int fieldOffset = 0;
auto particles = modelGroup->getParticles();
for (unsigned int i = 0; i < particles->size(); ++i) {
auto particle = particles->elementAt(i);
if (particle->getTermType() != XSParticle::TERM_ELEMENT) {
LOG_ERROR("Particle wasn't TERM_ELEMENT! Skipping.");
continue;
}
auto elementDeclaration = particle->getElementTerm();
std::string name = XS::ToString(elementDeclaration->getName());
std::string type = XS::ToString(elementDeclaration->getTypeDefinition()->getName());
size_t stride = EntityFile::GetTypeStride(type);
if (stride == 0) {
std::cout << "Warning: Field \"" << name << "\" in component \"" << compInfo.Name << "\" uses unexpected field type \"" << type << "\". Skipping." << std::endl;
continue;
}
auto& field = compInfo.Fields[name];
field.Type = type;
field.Offset = fieldOffset;
field.Stride = stride;
compInfo.FieldsInOrder.push_back(&field);
fieldOffset += stride;
}
compInfo.Meta.Stride = fieldOffset;
m_ComponentInfo[compInfo.Name] = compInfo;
}
}
void EntityFilePreprocessor::parseDefaults()
{
using namespace xercesc;
EntityFileXMLErrorHandler errorHandler;
for (auto& ci : m_ComponentInfo) {
// Allocate memory for default values
ci.second.Defaults = std::shared_ptr<char>(new char[ci.second.Meta.Stride]);
memset(ci.second.Defaults.get(), 0, ci.second.Meta.Stride);
XercesDOMParser parser(nullptr, XMLPlatformUtils::fgMemoryManager);
parser.setErrorHandler(&errorHandler);
std::string componentName = ci.first;
LOG_DEBUG("Parsing defaults for component %s", componentName.c_str());
boost::filesystem::path defaultsFile = "Schema/Components/" + componentName + ".xml";
parser.parse(defaultsFile.string().c_str());
auto doc = parser.getDocument();
if (doc == nullptr) {
LOG_ERROR("%s not found! Skipping.", defaultsFile.string().c_str());
continue;
}
// Find the node in the components namespace matching the component name
std::string tagName = "c:" + componentName;
auto rootNodes = doc->getElementsByTagName(XS::ToXMLCh(tagName));
if (rootNodes->getLength() == 0) {
LOG_ERROR("Couldn't find defaults for component \"%s\"! Skipping.", componentName.c_str());
continue;
}
auto componentElement = dynamic_cast<DOMElement*>(rootNodes->item(0));
// Fill the default value buffer with values
for (auto& kv : ci.second.Fields) {
std::string fieldName = kv.first;
auto& field = kv.second;
auto fieldNodes = componentElement->getElementsByTagName(XS::ToXMLCh(fieldName));
auto fieldNode = fieldNodes->item(0);
if (fieldNode == nullptr) {
LOG_ERROR("Defaults for component \"%s\" is missing field \"%s\"!", componentName.c_str(), fieldName.c_str());
continue;
}
auto fieldElement = dynamic_cast<DOMElement*>(fieldNode);
char* data = ci.second.Defaults.get() + field.Offset;
// Handle potential field attributes
if (fieldElement->hasAttributes()) {
std::map<std::string, std::string> attributes;
auto attributeMap = fieldElement->getAttributes();
for (int i = 0; i < attributeMap->getLength(); ++i) {
auto attribItem = attributeMap->item(i);
attributes[XS::ToString(attribItem->getNodeName())] = XS::ToString(attribItem->getNodeValue());
}
EntityFile::WriteAttributeData(data, field, attributes);
}
// Handle potential field values
auto childNode = fieldElement->getFirstChild();
if (childNode != nullptr && childNode->getNodeType() == DOMNode::TEXT_NODE) {
char* cstrValue = XMLString::transcode(childNode->getNodeValue());
EntityFile::WriteValueData(data, field, cstrValue);
XMLString::release(&cstrValue);
}
}
}
}
-140
View File
@@ -1,140 +0,0 @@
#include "Core/EntityFileWriter.h"
#define X(str) XS::ToXMLCh(str)
void EntityFileWriter::WriteWorld(World* world)
{
WriteEntity(world, 0);
}
void EntityFileWriter::WriteEntity(World* world, EntityID entity)
{
using namespace xercesc;
DOMDocument* doc = m_DOMImplementation->createDocument(nullptr, X("Entity"), nullptr);
DOMElement* root = doc->getDocumentElement();
root->setAttribute(X("xmlns:xsi"), X("http://www.w3.org/2001/XMLSchema-instance"));
root->setAttribute(X("xsi:noNamespaceSchemaLocation"), X("../Types/Entity.xsd"));
root->setAttribute(X("xmlns:c"), X("components"));
const std::string& name = world->GetName(entity);
if (!name.empty()) {
root->setAttribute(X("name"), X(name));
}
DOMElement* componentsElement = doc->createElement(X("Components"));
root->appendChild(componentsElement);
appentEntityComponents(componentsElement, world, entity);
DOMElement* childrenElement = doc->createElement(X("Children"));
root->appendChild(childrenElement);
appendEntityChildren(childrenElement, world, entity);
try {
LocalFileFormatTarget* target = new LocalFileFormatTarget(X(m_FilePath.string()));
DOMLSOutput* output = static_cast<DOMImplementationLS*>(m_DOMImplementation)->createLSOutput();
output->setByteStream(target);
m_DOMLSSerializer->write(doc, output);
delete target;
} catch (const std::runtime_error& e) {
LOG_ERROR("Failed to save \"%s\": %s", m_FilePath.c_str(), e.what());
}
doc->release();
}
void EntityFileWriter::appendEntityChildren(xercesc::DOMElement* parentElement, const World* world, EntityID entity)
{
using namespace xercesc;
DOMDocument* doc = parentElement->getOwnerDocument();
auto childrenRange = world->GetEntityChildren().equal_range(entity);
for (auto it = childrenRange.first; it != childrenRange.second; ++it) {
EntityID childEntity = it->second;
DOMElement* entityElement = doc->createElement(X("Entity"));
const std::string& name = world->GetName(childEntity);
if (!name.empty()) {
entityElement->setAttribute(X("name"), X(name));
}
parentElement->appendChild(entityElement);
DOMElement* componentsElement = doc->createElement(X("Components"));
entityElement->appendChild(componentsElement);
appentEntityComponents(componentsElement, world, childEntity);
DOMElement* childrenElement = doc->createElement(X("Children"));
entityElement->appendChild(childrenElement);
appendEntityChildren(childrenElement, world, childEntity);
}
}
void EntityFileWriter::appentEntityComponents(xercesc::DOMElement* parentElement, const World* world, EntityID entity)
{
using namespace xercesc;
DOMDocument* doc = parentElement->getOwnerDocument();
auto& componentPools = world->GetComponentPools();
// Step through all component pools to get an entity's components
// HACK: This is sloooow.
for (auto& kv : componentPools) {
const std::string& componentName = kv.first;
if (!world->HasComponent(entity, componentName)) {
continue;
}
std::string qualifiedComponentName = "c:" + componentName;
DOMElement* componentElement = doc->createElement(X(qualifiedComponentName));
parentElement->appendChild(componentElement);
ComponentWrapper c = kv.second->GetByEntity(entity);
for (auto& kv : c.Info.Fields) {
std::string fieldName = kv.first;
auto& field = kv.second;
// Ignore fields that are equal to the default
// HACK: This is probably sloooooow, but it's okay.
if (memcmp(c.Data + field.Offset, c.Info.Defaults.get() + field.Offset, field.Stride) == 0) {
continue;
}
DOMElement* fieldElement = doc->createElement(X(fieldName));
componentElement->appendChild(fieldElement);
if (field.Type == "Vector") {
const glm::vec3& vec = c[fieldName];
fieldElement->setAttribute(X("X"), X(boost::lexical_cast<std::string>(vec.x)));
fieldElement->setAttribute(X("Y"), X(boost::lexical_cast<std::string>(vec.y)));
fieldElement->setAttribute(X("Z"), X(boost::lexical_cast<std::string>(vec.z)));
} else if (field.Type == "Color") {
const glm::vec4& vec = c[fieldName];
fieldElement->setAttribute(X("R"), X(boost::lexical_cast<std::string>(vec.r)));
fieldElement->setAttribute(X("G"), X(boost::lexical_cast<std::string>(vec.g)));
fieldElement->setAttribute(X("B"), X(boost::lexical_cast<std::string>(vec.b)));
fieldElement->setAttribute(X("A"), X(boost::lexical_cast<std::string>(vec.a)));
} else if (field.Type == "Quaternion") {
const glm::quat& q = c[fieldName];
fieldElement->setAttribute(X("X"), X(boost::lexical_cast<std::string>(q.x)));
fieldElement->setAttribute(X("Y"), X(boost::lexical_cast<std::string>(q.y)));
fieldElement->setAttribute(X("Z"), X(boost::lexical_cast<std::string>(q.z)));
fieldElement->setAttribute(X("W"), X(boost::lexical_cast<std::string>(q.w)));
} else if (field.Type == "int") {
const int& value = c[fieldName];
fieldElement->appendChild(doc->createTextNode(X(boost::lexical_cast<std::string>(value))));
} else if (field.Type == "float") {
const float& value = c[fieldName];
fieldElement->appendChild(doc->createTextNode(X(boost::lexical_cast<std::string>(value))));
} else if (field.Type == "double") {
const double& value = c[fieldName];
fieldElement->appendChild(doc->createTextNode(X(boost::lexical_cast<std::string>(value))));
} else if (field.Type == "bool") {
const bool& value = c[fieldName];
if (value) {
fieldElement->appendChild(doc->createTextNode(X("true")));
} else {
fieldElement->appendChild(doc->createTextNode(X("false")));
}
} else if (field.Type == "string") {
const std::string& value = c[fieldName];
fieldElement->appendChild(doc->createTextNode(X(value)));
}
}
}
}
+495
View File
@@ -0,0 +1,495 @@
#include "Core/EntityXMLFile.h"
#include "Core/World.h"
unsigned int EntityXMLFile::InstanceCount = 0;
EntityXMLFile::EntityXMLFile(std::string path)
: m_EntityFile(path)
{
using namespace xercesc;
if (InstanceCount == 0) {
XMLPlatformUtils::Initialize();
}
InstanceCount++;
m_GrammarPool = new XMLGrammarPoolImpl();
m_ErrorHandler = new EntityParserXMLErrorHandler();
m_DOMParser = new XercesDOMParser(nullptr, XMLPlatformUtils::fgMemoryManager, m_GrammarPool);
m_DOMParser->setErrorHandler(m_ErrorHandler);
m_DOMParser->setDoNamespaces(true);
m_DOMParser->setDoXInclude(true);
m_DOMParser->setDoSchema(true);
m_DOMParser->setValidationSchemaFullChecking(true);
m_DOMParser->setValidationScheme(xercesc::XercesDOMParser::Val_Auto);
m_DOMParser->setValidationSchemaFullChecking(true);
m_DOMParser->setValidationConstraintFatal(false);
m_DOMParser->setIncludeIgnorableWhitespace(false);
// Make sure schema grammar is kept after validation
m_DOMParser->cacheGrammarFromParse(true);
// HACK: Use Sax2 parser instead so the entire DOM doesn't have to reside in memory
m_DOMParser->parse(m_EntityFile.c_str());
m_DOMDocument = m_DOMParser->getDocument();
// 1. Fill in ComponentInfo name, fields, default values and metadata from PSVI
parseComponentInfo();
// 2. Parse default value files for those components
parseDefaults();
// 3. Allocate component structures
predictComponentAllocation();
}
EntityXMLFile::~EntityXMLFile()
{
using namespace xercesc;
if (m_DOMParser != nullptr) {
delete m_DOMParser;
}
if (m_ErrorHandler != nullptr) {
delete m_ErrorHandler;
}
if (m_GrammarPool != nullptr) {
delete m_GrammarPool;
}
InstanceCount--;
if (InstanceCount == 0) {
XMLPlatformUtils::Terminate();
}
}
void EntityXMLFile::PopulateWorld(World* world)
{
for (auto& pair : m_ComponentInfo) {
world->RegisterComponent(pair.second);
}
// 4. Parse entity hierarchy
auto root = m_DOMDocument->getDocumentElement();
parseEntityGraph(world, root, 0);
}
void EntityXMLFile::preprocess(std::string inPath, std::string outPath)
{
using namespace xercesc;
static const XMLCh gLS[] = { 'L', 'S', '\0' };
DOMImplementationLS* di = static_cast<DOMImplementationLS*>(DOMImplementationRegistry::getDOMImplementation(gLS));
// Parse the file
DOMLSParser* parser = di->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS, nullptr);
DOMConfiguration* config = parser->getDomConfig();
config->setParameter(XMLUni::fgDOMNamespaces, true);
config->setParameter(XMLUni::fgXercesSchema, true);
config->setParameter(XMLUni::fgXercesHandleMultipleImports, true);
config->setParameter(XMLUni::fgXercesSchemaFullChecking, true);
config->setParameter(XMLUni::fgXercesDoXInclude, true);
auto errHandler = new EntityPreprocessorXMLErrorHandler();
config->setParameter(XMLUni::fgDOMErrorHandler, errHandler);
auto source = new LocalFileInputSource(XSTR(inPath.c_str()));
Wrapper4InputSource* domSourceWrapper = new Wrapper4InputSource(source);
DOMDocument* doc = parser->parse(dynamic_cast<DOMLSInput*>(domSourceWrapper));
// Serialize and output the new XML
DOMLSSerializer* writer = di->createLSSerializer();
DOMLSOutput* output = di->createLSOutput();
XMLFormatTarget* formatTarget = new LocalFileFormatTarget(outPath.c_str());
// TODO: MemBufFormatTarget* formatTarget = new MemBufFormatTarget()
output->setByteStream(formatTarget);
writer->write(doc, output);
delete formatTarget;
output->release();
writer->release();
parser->release();
}
void EntityXMLFile::parseComponentInfo()
{
using namespace xercesc;
bool wasChanged;
XSModel* xsModel = m_GrammarPool->getXSModel(wasChanged);
// Find component xsd element declarations
std::cout << "Enumerating components..." << std::endl;
// <xs:element name="ComponentName">
auto topLevelElements = xsModel->getComponents(XSConstants::ELEMENT_DECLARATION);
for (unsigned int i = 0; i < topLevelElements->getLength(); ++i) {
auto element = static_cast<XSElementDeclaration*>(topLevelElements->item(i));
std::string nameSpace(XSTR(element->getNamespace()));
if (nameSpace != "components") {
continue;
}
ComponentInfo compInfo;
// Name
compInfo.Name = XSTR(element->getName());
// Annotation
auto componentAnnotation = element->getAnnotation();
if (componentAnnotation != nullptr) {
// Parse annotation XML
char* annotationString = XMLString::transcode(componentAnnotation->getAnnotationString());
MemBufInputSource annotationInput(reinterpret_cast<const XMLByte*>(annotationString), strlen(annotationString), "MemBuf: Annotation String");
XercesDOMParser parser(nullptr, XMLPlatformUtils::fgMemoryManager, m_GrammarPool);
parser.setErrorHandler(m_ErrorHandler);
parser.parse(annotationInput);
XMLString::release(&annotationString);
auto doc = parser.getDocument();
// Add allocation estimation(s)
auto allocationTags = doc->getElementsByTagName(XSTR("meta:allocation"));
for (int i = 0; i < allocationTags->getLength(); ++i) {
auto allocation = dynamic_cast<DOMElement*>(allocationTags->item(i));
auto child = allocation->getFirstChild();
if (child == nullptr) {
continue;
}
XSValue::Status status;
XSValue* val = XSValue::getActualValue(child->getNodeValue(), XSValue::dt_integer, status);
compInfo.Meta.Allocation += val->fData.fValue.f_int;
}
// Save documentation string
auto documentationTags = doc->getElementsByTagName(XSTR("xs:documentation"));
if (documentationTags->getLength() != 0) {
auto child = documentationTags->item(0)->getFirstChild();
if (child != nullptr) {
compInfo.Meta.Annotation = XSTR(child->getNodeValue());
}
}
// TODO: Parse annotation string XML
// compInfo.Meta.Allocation = ...
} else {
std::cout << "Warning: Component is missing an annotation!" << std::endl;
}
// <xs:complexType>
auto typeDefinition = element->getTypeDefinition();
if (typeDefinition->getTypeCategory() != XSTypeDefinition::COMPLEX_TYPE) {
std::cerr << "Error: Type definition wasn't COMPLEX_TYPE! Skipping." << std::endl;
continue;
}
auto complexTypeDefinition = dynamic_cast<XSComplexTypeDefinition*>(typeDefinition);
// <xs:all>
auto modelGroupParticle = complexTypeDefinition->getParticle();
if (modelGroupParticle->getTermType() != XSParticle::TERM_MODELGROUP) {
std::cerr << "Error: Model group particle wasn't TERM_MODELGROUP! Skipping." << std::endl;
continue;
}
auto modelGroup = modelGroupParticle->getModelGroupTerm();
// <xs:element...
// <xs:attribute...
unsigned int fieldOffset = 0;
auto particles = modelGroup->getParticles();
for (unsigned int i = 0; i < particles->size(); ++i) {
auto particle = particles->elementAt(i);
if (particle->getTermType() != XSParticle::TERM_ELEMENT) {
std::cerr << "Error: Particle wasn't TERM_ELEMENT! Skipping." << std::endl;
continue;
}
auto elementDeclaration = particle->getElementTerm();
std::string name = XSTR(elementDeclaration->getName());
std::string type = XSTR(elementDeclaration->getTypeDefinition()->getName());
size_t stride = getTypeStride(type);
if (stride == 0) {
std::cout << "Warning: Field \"" << name << "\" in component \"" << compInfo.Name << "\" uses unexpected field type \"" << type << "\". Skipping." << std::endl;
continue;
}
compInfo.FieldTypes[name] = type;
compInfo.FieldOffsets[name] = fieldOffset;
fieldOffset += getTypeStride(type);
}
compInfo.Meta.Stride = fieldOffset;
m_ComponentInfo[compInfo.Name] = compInfo;
}
}
void EntityXMLFile::parseDefaults()
{
using namespace xercesc;
for (auto& ci : m_ComponentInfo) {
// Allocate memory for default values
ci.second.Defaults = std::shared_ptr<char>(new char[ci.second.Meta.Stride]);
memset(ci.second.Defaults.get(), 0, ci.second.Meta.Stride);
XercesDOMParser parser(nullptr, XMLPlatformUtils::fgMemoryManager);
parser.setErrorHandler(m_ErrorHandler);
std::string componentName = ci.first;
LOG_DEBUG("Parsing defaults for component %s", componentName.c_str());
boost::filesystem::path defaultsFile = "Schema/Components/" + componentName + ".xml";
parser.parse(defaultsFile.string().c_str());
auto doc = parser.getDocument();
if (doc == nullptr) {
LOG_ERROR("%s not found! Skipping.", defaultsFile.string().c_str());
continue;
}
// Find the node in the components namespace matching the component name
std::string tagName = "c:" + componentName;
auto rootNodes = doc->getElementsByTagName(XSTR(tagName.c_str()));
if (rootNodes->getLength() == 0) {
LOG_ERROR("Couldn't find defaults for component \"%s\"! Skipping.", componentName.c_str());
continue;
}
auto componentElement = dynamic_cast<DOMElement*>(rootNodes->item(0));
// Fill the default value buffer with values
for (auto& field : ci.second.FieldOffsets) {
std::string fieldName = field.first;
auto fieldNodes = componentElement->getElementsByTagName(XSTR(fieldName.c_str()));
auto fieldNode = fieldNodes->item(0);
if (fieldNode == nullptr) {
LOG_ERROR("Defaults for component \"%s\" is missing field \"%s\"!", componentName.c_str(), fieldName.c_str());
continue;
}
auto fieldElement = dynamic_cast<DOMElement*>(fieldNode);
std::string fieldType = ci.second.FieldTypes.at(fieldName);
unsigned int fieldOffset = ci.second.FieldOffsets.at(fieldName);
writeData(fieldElement, fieldType, ci.second.Defaults.get() + fieldOffset);
}
}
}
void EntityXMLFile::predictComponentAllocation()
{
using namespace xercesc;
auto root = m_DOMDocument->getDocumentElement();
// Count static instances of components present in entity hierarchy
auto components = m_DOMDocument->getElementsByTagNameNS(XSTR("components"), XSTR("*"));
for (int i = 0; i < components->getLength(); ++i) {
auto component = dynamic_cast<DOMElement*>(components->item(i));
std::string componentName = XSTR(component->getLocalName());
auto& compInfo = m_ComponentInfo.at(componentName);
compInfo.Meta.Allocation += 1;
}
std::cout << "COMPONENT INFO" << std::endl;
for (auto& pair : m_ComponentInfo) {
ComponentInfo& ci = pair.second;
std::cout << "Component: " << ci.Name << " (" << ci.Meta.Annotation << ")" << std::endl;
std::cout << " Allocation: " << ci.Meta.Allocation << std::endl;
std::cout << " Fields:" << std::endl;
// Calculate component size
std::size_t stride = 0;
// Add size of fields
for (auto& field : ci.FieldTypes) {
std::cout << " " << field.second << " " << field.first << " (" << getTypeStride(field.second) << " byte)" << std::endl;
stride += getTypeStride(field.second);
}
std::cout << " Stride: " << ci.Meta.Stride << std::endl;
}
}
void EntityXMLFile::parseEntityGraph(World* world, xercesc::DOMElement* element, EntityID parentEntity)
{
using namespace xercesc;
// Create entity
EntityID entity = world->CreateEntity(parentEntity);
LOG_DEBUG("Created entity %i, parent %i", entity, parentEntity);
// Add components
auto components = m_DOMDocument->evaluate(XSTR("Components/*"), element, nullptr, DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE, nullptr);
for (int i = 0; i < components->getSnapshotLength(); i++) {
components->snapshotItem(i);
auto componentElement = dynamic_cast<DOMElement*>(components->getNodeValue());
std::string componentName = XSTR(componentElement->getLocalName());
auto& ci = m_ComponentInfo.at(componentName);
// Attach the component
auto c = world->AttachComponent(entity, componentName);
LOG_DEBUG("Attached %s component", componentName.c_str());
// Write field data
auto fields = componentElement->getChildNodes();
for (int j = 0; j < fields->getLength(); ++j) {
auto fieldNode = fields->item(j);
auto nodeType = fieldNode->getNodeType();
if (nodeType != DOMNode::ELEMENT_NODE) {
continue;
}
auto field = dynamic_cast<DOMElement*>(fields->item(j));
//const XMLCh* value = fields->item(j)->getTextContent();
std::string fieldName(XSTR(field->getLocalName()));
if (ci.FieldTypes.find(fieldName) == ci.FieldTypes.end()) {
std::cout << "Warning: Component \"" << componentName << "\" contains invalid field \"" << fieldName << "\". Skipping." << std::endl;
continue;
}
std::string fieldType = ci.FieldTypes.at(fieldName);
unsigned int fieldOffset = ci.FieldOffsets.at(fieldName);
std::string fieldValue(XSTR(field->getTextContent()));
LOG_DEBUG(" %s %s = %s", fieldType.c_str(), fieldName.c_str(), fieldValue.c_str());
writeData(field, fieldType, c.Data + fieldOffset);
}
}
// Recurse children
auto children = m_DOMDocument->evaluate(XSTR("Children/Entity"), element, nullptr, DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE, nullptr);
for (int i = 0; i < children->getSnapshotLength(); i++) {
children->snapshotItem(i);
parseEntityGraph(world, dynamic_cast<DOMElement*>(children->getNodeValue()), entity);
}
//auto components = m_DOMDocument->getElementsByTagNameNS(XSTR("components"), XSTR("*"));
//for (int i = 0; i < components->getLength(); ++i) {
// auto component = dynamic_cast<DOMElement*>(components->item(i));
// std::string componentName = XSTR(component->getLocalName());
// auto& compStore = m_ComponentStore.at(componentName);
// auto& compInfo = compStore.Info;
// char* data = &compStore.Data[compStore.Size*compStore.Stride];
// compStore.Size += 1;
// auto fields = component->getChildNodes();
// for (int j = 0; j < fields->getLength(); ++j) {
// auto field = fields->item(j);
// auto nodeType = field->getNodeType();
// if (nodeType != DOMNode::ELEMENT_NODE) {
// continue;
// }
// //auto field = dynamic_cast<DOMElement*>(fields->item(j));
// //const XMLCh* value = fields->item(j)->getTextContent();
// std::string fieldName = XSTR(field->getLocalName());
// if (compInfo.FieldTypes.find(fieldName) == compInfo.FieldTypes.end()) {
// std::cout << "Warning: Component \"" << componentName << "\" contains invalid field \"" << fieldName << "\". Skipping." << std::endl;
// continue;
// }
// std::string fieldType = compInfo.FieldTypes.at(fieldName);
// unsigned int fieldOffset = compInfo.FieldOffsets.at(fieldName);
// XSValue::DataType dataType = XSValue::getDataType(XSTR(fieldType.c_str()));
// if (dataType == XSValue::DataType::dt_MAXCOUNT) {
// // TODO:
// continue;
// }
// if (dataType == XSValue::DataType::dt_string) {
// char* str = XMLString::transcode(field->getTextContent());
// std::string standardString(str);
// XMLString::release(&str);
// memcpy(&data[fieldOffset], reinterpret_cast<char*>(&standardString), getTypeStride(fieldType));
// } else {
// XSValue::Status status;
// XSValue* val = XSValue::getActualValue(field->getTextContent(), dataType, status);
// memcpy(&data[fieldOffset], reinterpret_cast<char*>(&val->fData.fValue), getTypeStride(fieldType));
// }
// }
//}
//auto entities = m_DOMDocument->getElementsByTagName(XSTR("Entity"));
//for (int i = 0; i < entities->getLength(); ++i) {
// auto entity = dynamic_cast<DOMElement*>(entities->item(i));
// //entity->setIdAttribute()
// std::cout << "ENTITY " << i + 1 << std::endl;
//}
}
std::size_t EntityXMLFile::getTypeStride(std::string typeName)
{
std::map<std::string, size_t> typeStrides{
{ "bool", sizeof(bool) },
{ "int", sizeof(int) },
{ "float", sizeof(float) },
{ "double", sizeof(double) },
{ "string", sizeof(std::string) },
{ "Vector", sizeof(glm::vec3) },
{ "Quaternion", sizeof(glm::quat) },
{ "Color", sizeof(glm::vec4) }
};
auto it = typeStrides.find(typeName);
return (it != typeStrides.end()) ? it->second : 0;
}
float EntityXMLFile::getFloatAttribute(const xercesc::DOMElement* element, const char* attribute) const
{
using namespace xercesc;
XSValue::Status status;
XSValue* val = XSValue::getActualValue(element->getAttribute(XSTR(attribute)), xercesc::XSValue::DataType::dt_double, status);
if (val == nullptr) {
LOG_ERROR("Element \"%s\" doesn't have an \"%s\" attribute!", XSTR(element->getTagName()), attribute);
return 0.f;
} else {
return static_cast<float>(val->fData.fValue.f_double);
}
}
void EntityXMLFile::writeData(const xercesc::DOMElement* element, std::string typeName, char* outData)
{
using namespace xercesc;
if (typeName == "Vector") {
glm::vec3 vec;
vec.x = getFloatAttribute(element, "X");
vec.y = getFloatAttribute(element, "Y");
vec.z = getFloatAttribute(element, "Z");
memcpy(outData, reinterpret_cast<char*>(&vec), getTypeStride(typeName));
} else if (typeName == "Color") {
glm::vec4 vec;
vec.r = getFloatAttribute(element, "R");
vec.g = getFloatAttribute(element, "G");
vec.b = getFloatAttribute(element, "B");
vec.a = getFloatAttribute(element, "A");
memcpy(outData, reinterpret_cast<char*>(&vec), getTypeStride(typeName));
} else if (typeName == "Quaternion") {
glm::quat q;
q.x = getFloatAttribute(element, "X");
q.y = getFloatAttribute(element, "Y");
q.z = getFloatAttribute(element, "Z");
q.w = getFloatAttribute(element, "W");
memcpy(outData, reinterpret_cast<char*>(&q), getTypeStride(typeName));
} else if (typeName == "float") {
XSValue::Status status;
XSValue* val = XSValue::getActualValue(element->getTextContent(), xercesc::XSValue::DataType::dt_float, status);
memcpy(outData, reinterpret_cast<char*>(&val->fData.fValue.f_float), getTypeStride(typeName));
} else if (typeName == "double") {
XSValue::Status status;
XSValue* val = XSValue::getActualValue(element->getTextContent(), xercesc::XSValue::DataType::dt_double, status);
memcpy(outData, reinterpret_cast<char*>(&val->fData.fValue.f_double), getTypeStride(typeName));
} else if (typeName == "bool") {
XSValue::Status status;
XSValue* val = XSValue::getActualValue(element->getTextContent(), xercesc::XSValue::DataType::dt_boolean, status);
memcpy(outData, reinterpret_cast<char*>(&val->fData.fValue.f_bool), getTypeStride(typeName));
} else {
XSValue::DataType dataType = XSValue::getDataType(XSTR(typeName.c_str()));
if (dataType == XSValue::DataType::dt_string) {
char* str = XMLString::transcode(element->getTextContent());
std::string standardString(str);
new (outData) std::string(str);
XMLString::release(&str);
//memcpy(outData, reinterpret_cast<char*>(&standardString), getTypeStride(typeName));
} else {
//XSValue::Status status;
//XSValue* val = XSValue::getActualValue(element->getTextContent(), dataType, status);
//memcpy(outData, reinterpret_cast<char*>(&val->fData.fValue), getTypeStride(typeName));
LOG_WARNING("Unknown native data type: %s", typeName.c_str());
}
}
}
+7 -36
View File
@@ -10,15 +10,12 @@ World::~World()
EntityID World::CreateEntity(EntityID parent /*= 0*/)
{
EntityID newEntity = generateEntityID();
if (newEntity == parent) {
LOG_WARNING("Invalid parent #%i of Entity#%i", newEntity, parent);
parent = EntityID_Invalid;
}
m_EntityParents[newEntity] = parent;
m_EntityChildren.insert(std::make_pair(parent, newEntity));
return newEntity;
}
void World::DeleteEntity(EntityID entity)
{
// Delete components
@@ -49,26 +46,15 @@ void World::DeleteEntity(EntityID entity)
break;
}
}
// Erase potential name
m_EntityNames.erase(entity);
}
bool World::ValidEntity(EntityID entity) const
{
return m_EntityParents.find(entity) != m_EntityParents.end();
}
void World::RegisterComponent(ComponentInfo& ci)
{
if (m_ComponentPools.find(ci.Name) == m_ComponentPools.end()) {
m_ComponentPools[ci.Name] = new ComponentPool(ci);
}
m_ComponentPools[ci.Name] = new ComponentPool(ci);
}
ComponentWrapper World::AttachComponent(EntityID entity, std::string componentType)
{
// TODO: Allocate dynamic pool if component isn't registered
ComponentPool* pool = m_ComponentPools.at(componentType);
const ComponentInfo& ci = pool->ComponentInfo();
@@ -80,7 +66,8 @@ ComponentWrapper World::AttachComponent(EntityID entity, std::string componentTy
return c;
}
bool World::HasComponent(EntityID entity, std::string componentType) const
bool World::HasComponent(EntityID entity, std::string componentType)
{
ComponentPool* pool = m_ComponentPools.at(componentType);
return pool->KnowsEntity(entity);
@@ -92,6 +79,7 @@ ComponentWrapper World::GetComponent(EntityID entity, std::string componentType)
return pool->GetByEntity(entity);
}
void World::DeleteComponent(EntityID entity, std::string componentType)
{
ComponentPool* pool = m_ComponentPools.at(componentType);
@@ -105,11 +93,13 @@ const ComponentPool* World::GetComponents(std::string componentType)
return (it != m_ComponentPools.end()) ? it->second : nullptr;
}
EntityID World::GetParent(EntityID entity)
{
return m_EntityParents.at(entity);
}
void World::SetParent(EntityID entity, EntityID parent)
{
EntityID lastParent = m_EntityParents.at(entity);
@@ -125,25 +115,6 @@ void World::SetParent(EntityID entity, EntityID parent)
m_EntityChildren.insert(std::make_pair(parent, entity));
}
void World::SetName(EntityID entity, const std::string& name)
{
m_EntityNames[entity] = name;
}
std::string World::GetName(EntityID entity) const
{
if (entity == EntityID_Invalid) {
return "EntityID_Invalid";
}
auto it = m_EntityNames.find(entity);
if (it != m_EntityNames.end()) {
return it->second;
} else {
return std::string();
}
}
EntityID World::generateEntityID()
{
// TODO: Make EntityID generation smarter
+107 -226
View File
@@ -9,7 +9,6 @@ EditorSystem::EditorSystem(EventBroker* eventBroker, IRenderer* renderer)
auto config = ResourceManager::Load<ConfigFile>("Config.ini");
m_Enabled = config->Get<bool>("Debug.EditorEnabled", false);
m_Visible = m_Enabled;
m_DefaultEntityDir = boost::filesystem::path("Schema") / boost::filesystem::path("Entities");
if (!m_Enabled) {
return;
@@ -45,35 +44,6 @@ void EditorSystem::Update(World* world, double dt)
}
}
boost::filesystem::path EditorSystem::openDialog(boost::filesystem::path defaultPath)
{
namespace bfs = boost::filesystem;
auto absolutePath = bfs::absolute(defaultPath);
nfdchar_t* outPath = nullptr;
nfdresult_t result = NFD_OpenDialog(NULL, absolutePath.string().c_str(), &outPath);
if (result == NFD_ERROR) {
LOG_ERROR("NFD Error: %s", NFD_GetError());
return bfs::path();
}
return bfs::absolute(outPath);
}
boost::filesystem::path EditorSystem::saveDialog(boost::filesystem::path defaultPath)
{
namespace bfs = boost::filesystem;
auto absolutePath = bfs::absolute(defaultPath);
nfdchar_t* outPath = nullptr;
nfdresult_t result = NFD_SaveDialog(NULL, absolutePath.string().c_str(), &outPath);
if (result == NFD_ERROR) {
LOG_ERROR("NFD Error: %s", NFD_GetError());
return bfs::path();
}
return bfs::absolute(outPath);
}
bool EditorSystem::OnInputCommand(const Events::InputCommand& e)
{
if (e.Command == "ToggleEditor" && e.Value > 0) {
@@ -111,24 +81,17 @@ bool EditorSystem::OnMousePress(const Events::MousePress& e)
bool EditorSystem::OnMouseMove(const Events::MouseMove& e)
{
if (m_Widget == EntityID_Invalid) {
return false;
}
if (m_Selection == EntityID_Invalid) {
return false;
}
if (m_Selection == m_Widget) {
return false;
}
// TODO: No widgets for root entity until widgets reside in thier own world,
// or the widgets will move relative to the root entity being moved, which is WEEEIRD.
if (m_Selection == 0) {
if (m_Widget == 0) {
return false;
}
if (m_Selection == 0) {
return false;
}
auto widgetTransform = m_World->GetComponent(m_Widget, "Transform");
glm::vec3 widgetOrientation = widgetTransform["Orientation"];
glm::quat totalOrientation = m_Renderer->Camera()->Orientation() * glm::inverse(glm::quat(widgetOrientation));
glm::quat totalOrientation = m_Renderer->Camera()->Orientation() * glm::inverse(glm::quat(widgetOrientation));
int width;
int height;
@@ -159,9 +122,9 @@ bool EditorSystem::OnMouseMove(const Events::MouseMove& e)
if (m_WidgetSpace == WidgetSpace::Global) {
EntityID parent = m_World->GetParent(m_Selection);
glm::quat inverseParentOrientation;
//if (parent != 0) {
if (parent != 0) {
inverseParentOrientation = glm::inverse(RenderQueueFactory::AbsoluteOrientation(m_World, parent));
//}
}
(glm::vec3&)m_World->GetComponent(m_Selection, "Transform")["Position"] += inverseParentOrientation * movement;
} else if (m_WidgetSpace == WidgetSpace::Local) {
auto selectionTransform = m_World->GetComponent(m_Selection, "Transform");
@@ -175,12 +138,12 @@ bool EditorSystem::OnMouseMove(const Events::MouseMove& e)
if (m_WidgetSpace == WidgetSpace::Global) {
EntityID parent = m_World->GetParent(m_Selection);
glm::quat parentOrientation;
//if (parent != 0) {
// parentOrientation = RenderQueueFactory::AbsoluteOrientation(m_World, parent);
//}
if (parent != 0) {
parentOrientation = RenderQueueFactory::AbsoluteOrientation(m_World, parent);
}
glm::vec3& selectionOrientation = m_World->GetComponent(m_Selection, "Transform")["Orientation"];
glm::quat currentOrientation = RenderQueueFactory::AbsoluteOrientation(m_World, m_Selection);
//glm::quat currentOrientation = parentOrientation * glm::quat(selectionOrientation);
//glm::quat currentOrientation = RenderQueueFactory::AbsoluteOrientation(m_World, m_Selection);
glm::quat currentOrientation = parentOrientation * glm::quat(selectionOrientation);
glm::quat deltaOrientation(finalMovement);
selectionOrientation = glm::eulerAngles(glm::inverse(parentOrientation) * (deltaOrientation * currentOrientation));
} else if (m_WidgetSpace == WidgetSpace::Local) {
@@ -241,10 +204,9 @@ bool EditorSystem::OnPicking(const Events::Picking& e)
auto result = e.Pick(pos);
EntityID entity = result.Entity;
if (glm::length2(m_WidgetCurrentAxis) > 0.f) {
// ???
} else {
LOG_INFO("Selected %i", entity);
if (entity != EntityID_Invalid) {
if (entity != 0) {
EntityID parent = m_World->GetParent(entity);
if (parent == m_Widget) {
m_WidgetCurrentAxis = glm::vec3(
@@ -259,12 +221,11 @@ bool EditorSystem::OnPicking(const Events::Picking& e)
//widgetTransform["Position"] = (glm::vec3)selectionTransform["Position"];
} else {
ImGui::SetActiveID(0, nullptr);
if (m_WidgetMode == WidgetMode::None) {
m_WidgetMode = WidgetMode::Translate;
}
setWidgetMode(m_WidgetMode);
m_Selection = entity;
setWidgetMode(m_WidgetMode);
}
} else {
m_Selection = 0;
}
}
}
@@ -279,9 +240,9 @@ bool EditorSystem::OnFileDropped(const Events::FileDropped& e)
return true;
}
void EditorSystem::createWidget()
void EditorSystem::updateWidget()
{
if (m_Widget == EntityID_Invalid) {
if (m_Widget == 0) {
m_Widget = m_World->CreateEntity();
m_World->AttachComponent(m_Widget, "Transform");
m_WidgetX = m_World->CreateEntity(m_Widget);
@@ -308,20 +269,10 @@ void EditorSystem::createWidget()
m_WidgetOrigin = m_World->CreateEntity(m_Widget);
m_World->AttachComponent(m_WidgetOrigin, "Transform");
m_World->AttachComponent(m_WidgetOrigin, "Model");
setWidgetMode(WidgetMode::None);
}
}
void EditorSystem::updateWidget()
{
if (m_Widget == EntityID_Invalid) {
return;
}
if (m_Selection == m_Widget) {
return;
setWidgetMode(WidgetMode::Translate);
}
if (m_Selection != EntityID_Invalid) {
if (m_Selection != 0) {
auto widgetTransform = m_World->GetComponent(m_Widget, "Transform");
glm::vec3 selectionPosition = RenderQueueFactory::AbsolutePosition(m_World, m_Selection);
widgetTransform["Position"] = selectionPosition;
@@ -333,7 +284,7 @@ void EditorSystem::updateWidget()
void EditorSystem::setWidgetMode(WidgetMode newMode)
{
if (m_Widget == EntityID_Invalid) {
if (m_Widget == 0) {
return;
}
@@ -358,7 +309,7 @@ void EditorSystem::setWidgetMode(WidgetMode newMode)
m_World->GetComponent(m_WidgetPlaneY, "Model")["Visible"] = true;
m_World->GetComponent(m_WidgetPlaneZ, "Model")["Visible"] = true;
}
if (m_Selection != EntityID_Invalid) {
if (m_Selection != 0) {
if (m_WidgetSpace == WidgetSpace::Local) {
auto selectionTransform = m_World->GetComponent(m_Selection, "Transform");
widgetTransform["Orientation"] = glm::eulerAngles(RenderQueueFactory::AbsoluteOrientation(m_World, m_Selection));
@@ -370,7 +321,7 @@ void EditorSystem::setWidgetMode(WidgetMode newMode)
m_World->GetComponent(m_WidgetZ, "Model")["Resource"] = "Models/ScaleWidgetZ.obj";
m_World->GetComponent(m_WidgetOrigin, "Model")["Visible"] = true;
m_World->GetComponent(m_WidgetOrigin, "Model")["Resource"] = "Models/ScaleWidgetOrigin.obj";
if (m_Selection != EntityID_Invalid) {
if (m_Selection != 0) {
auto selectionTransform = m_World->GetComponent(m_Selection, "Transform");
widgetTransform["Orientation"] = glm::eulerAngles(RenderQueueFactory::AbsoluteOrientation(m_World, m_Selection));
}
@@ -378,7 +329,7 @@ void EditorSystem::setWidgetMode(WidgetMode newMode)
m_World->GetComponent(m_WidgetX, "Model")["Resource"] = "Models/RotationWidgetX.obj";
m_World->GetComponent(m_WidgetY, "Model")["Resource"] = "Models/RotationWidgetY.obj";
m_World->GetComponent(m_WidgetZ, "Model")["Resource"] = "Models/RotationWidgetZ.obj";
if (m_Selection != EntityID_Invalid) {
if (m_Selection != 0) {
auto selectionTransform = m_World->GetComponent(m_Selection, "Transform");
if (m_WidgetSpace == WidgetSpace::Local) {
widgetTransform["Orientation"] = glm::eulerAngles(RenderQueueFactory::AbsoluteOrientation(m_World, m_Selection));
@@ -388,6 +339,7 @@ void EditorSystem::setWidgetMode(WidgetMode newMode)
m_WidgetMode = newMode;
}
void EditorSystem::setWidgetSpace(WidgetSpace space)
{
m_WidgetSpace = space;
@@ -396,23 +348,16 @@ void EditorSystem::setWidgetSpace(WidgetSpace space)
void EditorSystem::drawUI(World* world, double dt)
{
namespace bfs = boost::filesystem;
ImGui::ShowTestWindow();
//ImGui::ShowStyleEditor();
if (ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu("File")) {
//if (ImGui::MenuItem("New")) { }
if (ImGui::MenuItem("Import", "Ctrl+O")) {
fileImport(world);
}
if (ImGui::MenuItem("Save", "Ctrl+S")) {
fileSave(world);
}
if (ImGui::MenuItem("Save As...", "Ctrl+Shift+S")) {
fileSaveAs(world);
}
if (ImGui::MenuItem("New")) { }
if (ImGui::MenuItem("Open", "Ctrl+O")) { }
if (ImGui::MenuItem("Save", "Ctrl+S")) { }
if (ImGui::MenuItem("Save As...", "Ctrl+Shift+S")) { }
ImGui::Separator();
if (ImGui::MenuItem("Close Editor", "F1")) { }
@@ -447,7 +392,7 @@ void EditorSystem::drawUI(World* world, double dt)
std::string title = std::string("Components #") + std::to_string(m_Selection) + std::string("###Components");
if (ImGui::Begin(title.c_str())) {
if (m_Selection != EntityID_Invalid) {
if (m_Selection != 0) {
auto& pools = world->GetComponentPools();
std::vector<const char*> componentTypes;
@@ -487,16 +432,16 @@ void EditorSystem::drawUI(World* world, double dt)
}
auto& component = world->GetComponent(m_Selection, componentType);
for (auto& kv : ci.Fields) {
const std::string& fieldName = kv.first;
auto& field = kv.second;
for (auto& pair : ci.FieldTypes) {
const std::string& field = pair.first;
const std::string& type = pair.second;
ImGui::PushID(fieldName.c_str());
if (field.Type == "Vector") {
auto& val = component.Property<glm::vec3>(fieldName);
if (fieldName == "Scale") {
ImGui::PushID(field.c_str());
if (type == "Vector") {
auto& val = component.Property<glm::vec3>(field);
if (field == "Scale") {
ImGui::DragFloat3("", glm::value_ptr(val), 0.1f, 0.f, std::numeric_limits<float>::max());
} else if (fieldName == "Orientation") {
} else if (field == "Orientation") {
glm::vec3 tempVal = glm::fmod(val, glm::vec3(glm::two_pi<float>()));
if (ImGui::SliderFloat3("", glm::value_ptr(tempVal), 0.f, glm::two_pi<float>())) {
val = tempVal;
@@ -504,16 +449,16 @@ void EditorSystem::drawUI(World* world, double dt)
} else {
ImGui::DragFloat3("", glm::value_ptr(val), 0.1f, std::numeric_limits<float>::lowest(), std::numeric_limits<float>::max());
}
} else if (field.Type == "Color") {
auto& val = component.Property<glm::vec4>(fieldName);
} else if (type == "Color") {
auto& val = component.Property<glm::vec4>(field);
ImGui::ColorEdit4("", glm::value_ptr(val), true);
} else if (field.Type == "string") {
std::string& val = component.Property<std::string>(fieldName);
} else if (type == "string") {
std::string& val = component.Property<std::string>(field);
char tempString[1024];
memcpy(tempString, val.c_str(), std::min(val.length() + 1, sizeof(tempString)));
if (ImGui::InputText("", tempString, sizeof(tempString))) {
val = std::string(tempString);
LOG_DEBUG("%s::%s changed!", componentType.c_str(), fieldName.c_str());
LOG_DEBUG("%s::%s changed!", componentType.c_str(), field.c_str());
}
// DROP STUFF
if (ImGui::IsItemHovered() && !m_LastDroppedFile.empty()) {
@@ -521,21 +466,21 @@ void EditorSystem::drawUI(World* world, double dt)
m_LastDroppedFile = "";
}
} else if (field.Type == "double") {
float tempVal = static_cast<float>(component.Property<double>(fieldName));
} else if (type == "double") {
float tempVal = static_cast<float>(component.Property<double>(field));
if (ImGui::InputFloat("", &tempVal, 0.01f, 1.f)) {
component.SetProperty(fieldName, static_cast<double>(tempVal));
component.SetProperty(field, static_cast<double>(tempVal));
}
} else if (field.Type == "bool") {
auto& val = component.Property<bool>(fieldName);
} else if (type == "bool") {
auto& val = component.Property<bool>(field);
ImGui::Checkbox("", &val);
} else {
ImGui::TextDisabled(field.Type.c_str());
ImGui::TextDisabled(type.c_str());
}
ImGui::PopID();
ImGui::SameLine();
ImGui::Text(fieldName.c_str());
ImGui::Text(field.c_str());
if (ImGui::IsItemHovered()) {
ImGui::SetTooltip("field annotation goes here");
}
@@ -547,93 +492,74 @@ void EditorSystem::drawUI(World* world, double dt)
}
ImGui::End();
if (ImGui::Begin("Entities")) {
if (ImGui::Begin("Entitites")) {
static EntityID draggingEntity = 0;
auto entityChildren = world->GetEntityChildren();
std::function<void(EntityID)> recurse = [&](EntityID parent) {
auto range = entityChildren.equal_range(parent);
for (auto it = range.first; it != range.second; it++) {
if (createEntityNode(world, it->second)) {
ImVec2 pos = ImGui::GetCursorScreenPos();
float width = ImGui::GetContentRegionAvailWidth();
ImRect bb(pos + ImVec2(20, 0), pos + ImVec2(width, 13));
auto window = ImGui::GetCurrentWindow();
if (m_Selection == it->second) {
const ImU32 col = window->Color(ImGuiCol_HeaderActive);
window->DrawList->AddRectFilled(bb.Min, bb.Max, col);
}
ImGuiID id = window->GetID((std::string("#SelectButton") + std::to_string(it->second)).c_str());
bool hovered = false;
bool held = false;
if (ImGui::ButtonBehavior(bb, id, &hovered, &held)) {
m_Selection = it->second;
}
if (held) {
ImVec2 entityDragDelta = ImGui::GetMouseDragDelta(0);
if (std::abs(entityDragDelta.x) > 0 && std::abs(entityDragDelta.y) > 0) {
if (draggingEntity == 0) {
draggingEntity = it->second;
LOG_DEBUG("Started drag of entity %i", draggingEntity);
}
ImGui::SetNextWindowPos(ImGui::GetIO().MousePos + ImVec2(20, 0));
ImGui::Begin("Change parent", nullptr, ImVec2(0, 0), 0.3f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings);
ImGui::Text("#%i", draggingEntity);
ImGui::End();
}
}
ImGui::SetNextTreeNodeOpened(true, ImGuiSetCond_Once);
if (ImGui::TreeNode((std::string("#") + std::to_string(it->second)).c_str())) {
if (draggingEntity != 0 && ImGui::IsItemHoveredRect() && ImGui::IsMouseReleased(0)) {
LOG_DEBUG("Changed parent of %i to %i", draggingEntity, it->second);
changeParent(draggingEntity, it->second);
draggingEntity = 0;
}
if (ImGui::BeginPopupContextItem("item context menu")) {
if (ImGui::Button("Add")) {
EntityID entity = world->CreateEntity(it->second);
world->AttachComponent(entity, "Transform");
}
ImGui::SameLine();
if (ImGui::Button("Delete")) {
world->DeleteEntity(it->second);
ImGui::CloseCurrentPopup();
if (m_Selection == it->second) {
m_Selection = 0;
}
}
ImGui::EndPopup();
}
recurse(it->second);
ImGui::TreePop();
}
}
};
recurse(EntityID_Invalid);
recurse(0);
}
ImGui::End();
}
bool EditorSystem::createEntityNode(World* world, EntityID entity)
{
// HACK: Don't show the widget entities in the entity tree
if (entity == m_Widget) {
return false;
}
ImVec2 pos = ImGui::GetCursorScreenPos();
float width = ImGui::GetContentRegionAvailWidth();
ImRect bb(pos + ImVec2(20, 0), pos + ImVec2(width, 13));
auto window = ImGui::GetCurrentWindow();
if (m_Selection == entity) {
const ImU32 col = window->Color(ImGuiCol_HeaderActive);
window->DrawList->AddRectFilled(bb.Min, bb.Max, col);
}
ImGuiID id = window->GetID((std::string("#SelectButton") + std::to_string(entity)).c_str());
bool hovered = false;
bool held = false;
if (ImGui::ButtonBehavior(bb, id, &hovered, &held)) {
m_Selection = entity;
}
if (held) {
ImVec2 entityDragDelta = ImGui::GetMouseDragDelta(0);
if (std::abs(entityDragDelta.x) > 0 && std::abs(entityDragDelta.y) > 0) {
if (m_UIDraggingEntity == EntityID_Invalid) {
m_UIDraggingEntity = entity;
LOG_DEBUG("Started drag of entity %i", m_UIDraggingEntity);
}
ImGui::SetNextWindowPos(ImGui::GetIO().MousePos + ImVec2(20, 0));
ImGui::Begin("Change parent", nullptr, ImVec2(0, 0), 0.3f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings);
ImGui::Text("#%i", m_UIDraggingEntity);
ImGui::End();
}
}
ImGui::SetNextTreeNodeOpened(true, ImGuiSetCond_Once);
std::string nodeTitle;
const std::string& entityName = world->GetName(entity);
if (!entityName.empty()) {
nodeTitle = entityName;
} else {
nodeTitle = std::string("#") + std::to_string(entity);
}
if (ImGui::TreeNode(nodeTitle.c_str())) {
if (m_UIDraggingEntity != EntityID_Invalid && ImGui::IsItemHoveredRect() && ImGui::IsMouseReleased(0)) {
LOG_DEBUG("Changed parent of %i to %i", m_UIDraggingEntity, entity);
changeParent(m_UIDraggingEntity, entity);
m_UIDraggingEntity = EntityID_Invalid;
}
if (ImGui::BeginPopupContextItem("item context menu")) {
if (ImGui::Button("Add")) {
EntityID newEntity = world->CreateEntity(entity);
world->AttachComponent(newEntity, "Transform");
}
ImGui::SameLine();
if (ImGui::Button("Delete")) {
world->DeleteEntity(entity);
ImGui::CloseCurrentPopup();
if (!world->ValidEntity(m_Selection)) {
m_Selection = EntityID_Invalid;
}
}
ImGui::EndPopup();
}
return true;
} else {
return false;
}
}
bool EditorSystem::createDeleteButton(std::string componentType)
{
float width = ImGui::GetContentRegionAvailWidth();
@@ -668,48 +594,3 @@ void EditorSystem::changeParent(EntityID entity, EntityID newParent)
m_World->SetParent(entity, newParent);
}
void EditorSystem::fileImport(World* world)
{
m_CurrentFile = openDialog(m_DefaultEntityDir);
auto file = ResourceManager::Load<EntityFile>(m_CurrentFile.string());
EntityFilePreprocessor fpp(file);
fpp.RegisterComponents(world);
EntityFileParser fp(file);
fp.MergeEntities(world);
createWidget();
updateWidget();
}
void EditorSystem::fileSave(World* world)
{
if (boost::filesystem::exists(m_CurrentFile)) {
// HACK: Delete the widgets so they don't appear in the saved file
world->DeleteEntity(m_Widget);
m_Widget = EntityID_Invalid;
EntityFileWriter writer(m_CurrentFile.string());
writer.WriteWorld(world);
createWidget();
} else {
fileSaveAs(world);
}
}
void EditorSystem::fileSaveAs(World* world)
{
auto filePath = saveDialog(m_DefaultEntityDir);
if (filePath.empty()) {
return;
}
// HACK: Delete the widgets so they don't appear in the saved file
world->DeleteEntity(m_Widget);
m_Widget = EntityID_Invalid;
EntityFileWriter writer(filePath.string());
writer.WriteWorld(world);
createWidget();
}
+3 -8
View File
@@ -17,15 +17,10 @@ InputProxy::~InputProxy()
void InputProxy::LoadBindings(std::string file)
{
auto config = ResourceManager::Load<ConfigFile>(file);
auto section = config->GetSection("Bindings");
if (section == nullptr) {
return;
}
for (auto& param : *section) {
for (auto& origin : config->GetAll<std::string>("Bindings")) {
Events::BindOrigin e;
e.Origin = param.first;
e.Command = param.second->get_value();
e.Origin = origin.first;
e.Command = origin.second;
e.Value = 1.f;
if (!e.Command.empty()) {
char prefix = e.Command.at(0);
+65
View File
@@ -0,0 +1,65 @@
#include "Rendering/DrawFinalPass.h"
DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass)
{
m_Renderer = renderer;
m_LightCullingPass = lightCullingPass;
InitializeTextures();
InitializeShaderPrograms();
}
void DrawFinalPass::InitializeTextures()
{
m_WhiteTexture = ResourceManager::Load<Texture>("Textures/Core/Blank.png");
}
void DrawFinalPass::InitializeShaderPrograms()
{
m_ForwardPlusProgram = ResourceManager::Load<ShaderProgram>("#ForwardPlusProgram");
m_ForwardPlusProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/ForwardPlus.vert.glsl")));
m_ForwardPlusProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/ForwardPlus.frag.glsl")));
m_ForwardPlusProgram->Compile();
m_ForwardPlusProgram->Link();
}
void DrawFinalPass::Draw(RenderQueueCollection& rq)
{
GLERROR("DrawFinalPass::Draw: Pre");
DrawFinalPassState state;
m_ForwardPlusProgram->Bind();
GLuint shaderHandle = m_ForwardPlusProgram->GetHandle();
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightCullingPass->LightSSBO());
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO());
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO());
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(m_Renderer->Camera()->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(m_Renderer->Camera()->ProjectionMatrix()));
//TODO: Render: Add code for more jobs than modeljobs.
for (auto &job : rq.Forward) {
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
if(modelJob) {
//TODO: Kolla upp "header/include/common" shader saken så man slipper skicka in asmycket uniforms
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->ModelMatrix));
glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(modelJob->Color));
if(modelJob->DiffuseTexture != nullptr) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, modelJob->DiffuseTexture->m_Texture);
} else {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture);
}
glBindVertexArray(modelJob->Model->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer);
glDrawElementsBaseVertex(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, 0, modelJob->StartIndex);
continue;
}
}
GLERROR("DrawFinalPass::Draw: END");
}
@@ -0,0 +1,17 @@
#include "Rendering/DrawFinalPassState.h"
DrawFinalPassState::DrawFinalPassState()
{
BindFramebuffer(0);
Enable(GL_DEPTH_TEST);
Enable(GL_CULL_FACE);
ClearColor(glm::vec4(200.f / 255, 0.f / 255, 200.f / 255, 0.f));
Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
DrawFinalPassState::~DrawFinalPassState()
{
}
+9 -6
View File
@@ -14,23 +14,21 @@ void DrawScenePass::InitializeTextures()
void DrawScenePass::InitializeShaderPrograms()
{
//Gör så att shaders är en resource, tex som texture classen. Konstruktorn måste vara privat.
m_BasicForwardProgram = ResourceManager::Load<ShaderProgram>("#BasicForwardProgram");
m_BasicForwardProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/BasicForward.vert.glsl")));
m_BasicForwardProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/BasicForward.frag.glsl")));
m_BasicForwardProgram->Compile();
m_BasicForwardProgram->Link();
}
void DrawScenePass::Draw(RenderQueueCollection& rq)
{
//glBindFramebuffer(GL_FRAMEBUFFER, 0);
GLERROR("Renderer::Draw PickingPass");
GLERROR("DrawScenePass::Draw: Pre");
DrawScenePassState state;
m_BasicForwardProgram->Bind();
//TODO: Render: Add code for more jobs than modeljobs.
@@ -39,7 +37,6 @@ void DrawScenePass::Draw(RenderQueueCollection& rq)
if (modelJob) {
GLuint ShaderHandle = m_BasicForwardProgram->GetHandle();
m_BasicForwardProgram->Bind();
//TODO: Kolla upp "header/include/common" shader saken så man slipper skicka in asmycket uniforms
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->ModelMatrix));
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(m_Renderer->Camera()->ViewMatrix()));
@@ -61,6 +58,12 @@ void DrawScenePass::Draw(RenderQueueCollection& rq)
continue;
}
auto spriteJob = std::dynamic_pointer_cast<SpriteJob>(job);
if(spriteJob)
{
//Hello im a sprite, please draw me.
}
}
GLERROR("DrawScene Error");
GLERROR("DrawScenePass::Draw: End");
}
+126
View File
@@ -0,0 +1,126 @@
#include "Rendering/LightCullingPass.h"
LightCullingPass::LightCullingPass(IRenderer* renderer)
{
m_Renderer = renderer;
InitializeSSBOs();
InitializeShaderPrograms();
GenerateNewFrustum();
}
LightCullingPass::~LightCullingPass()
{
}
void LightCullingPass::GenerateNewFrustum()
{
GLERROR("CalculateFrustum Error: Pre");
m_CalculateFrustumProgram->Bind();
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, m_FrustumSSBO);
glUniformMatrix4fv(glGetUniformLocation(m_CalculateFrustumProgram->GetHandle(), "P"), 1, false, glm::value_ptr(m_Renderer->Camera()->ProjectionMatrix()));
glUniform2f(glGetUniformLocation(m_CalculateFrustumProgram->GetHandle(), "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height);
glDispatchCompute(5, 3, 1); //TODO: Renderer: This needs change so resolution will be right.
GLERROR("CalculateFrustum Error: End");
}
void LightCullingPass::CullLights()
{
GLERROR("CullLights Error: Pre");
m_LightOffset = 0;
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightOffsetSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_LightOffset), &m_LightOffset, GL_DYNAMIC_COPY);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightSSBO);
if (m_PointLights.size() > 0) {
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(PointLight) * m_PointLights.size(), &(m_PointLights[0]), GL_DYNAMIC_COPY);
} else {
GLfloat zero = 0.f;
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(GLfloat), &zero , GL_DYNAMIC_COPY);
}
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
m_LightCullProgram->Bind();
glUniformMatrix4fv(glGetUniformLocation(m_LightCullProgram->GetHandle(), "V"), 1, false, glm::value_ptr(m_Renderer->Camera()->ViewMatrix()));
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, m_FrustumSSBO);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightSSBO);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightGridSSBO);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, m_LightOffsetSSBO);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightIndexSSBO);
glDispatchCompute(m_Renderer->Resolution().Width / TILE_SIZE, m_Renderer->Resolution().Height / TILE_SIZE, 1);
GLERROR("CullLights Error: End");
}
void LightCullingPass::FillLightList(RenderQueueCollection& rq)
{
m_PointLights.clear();
for(auto &job : rq.Lights) {
auto pointLightjob = std::dynamic_pointer_cast<PointLightJob>(job);
if (pointLightjob) {
PointLight p;
p.Color = pointLightjob->Color;
p.Falloff = pointLightjob->Falloff;
p.Intensity = pointLightjob->Intensity;
p.Position = glm::vec4(glm::vec3(pointLightjob->Position), 1.f);
p.Radius = pointLightjob->Radius;
p.Padding = 123.f;
m_PointLights.push_back(p);
continue;
}
}
}
void LightCullingPass::InitializeSSBOs()
{
glGenBuffers(1, &m_FrustumSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_FrustumSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_Frustums), &m_Frustums, GL_DYNAMIC_COPY);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLERROR("m_FrustumSSBO");
glGenBuffers(1, &m_LightSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightSSBO);
if(m_PointLights.size() > 0) {
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(PointLight) * m_PointLights.size(), &(m_PointLights[0]), GL_DYNAMIC_COPY);
}
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLERROR("m_LightSSBO");
glGenBuffers(1, &m_LightGridSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightGridSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_LightGrid), &m_LightGrid, GL_DYNAMIC_COPY);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLERROR("m_LightGridSSBO");
glGenBuffers(1, &m_LightOffsetSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightOffsetSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_LightOffset), &m_LightOffset, GL_DYNAMIC_COPY);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLERROR("m_LightOffsetSSBO");
glGenBuffers(1, &m_LightIndexSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightIndexSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_LightIndex), &m_LightIndex, GL_DYNAMIC_COPY);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLERROR("m_LightIndexSSBO");
}
void LightCullingPass::InitializeShaderPrograms()
{
m_CalculateFrustumProgram = ResourceManager::Load<ShaderProgram>("#CalculateFrustumProgram");
m_CalculateFrustumProgram->AddShader(std::shared_ptr<Shader>(new ComputeShader("Shaders/GridFrustum.comp.glsl")));
m_CalculateFrustumProgram->Compile();
m_CalculateFrustumProgram->Link();
m_LightCullProgram = ResourceManager::Load<ShaderProgram>("#LightCullProgram");
m_LightCullProgram->AddShader(std::shared_ptr<Shader>(new ComputeShader("Shaders/CullLights.comp.glsl")));
m_LightCullProgram->Compile();
m_LightCullProgram->Link();
}
+38 -10
View File
@@ -27,16 +27,16 @@ glm::vec3 RenderQueueFactory::AbsolutePosition(World* world, EntityID entity)
{
glm::vec3 position;
while (entity != EntityID_Invalid) {
do {
ComponentWrapper transform = world->GetComponent(entity, "Transform");
EntityID parent = world->GetParent(entity);
//if (parent != EntityID_Invalid) {
if (parent != 0) {
position += AbsoluteOrientation(world, parent) * (glm::vec3)transform["Position"];
//} else {
// position += (glm::vec3)transform["Position"];
//}
} else {
position += (glm::vec3)transform["Position"];
}
entity = parent;
}
} while (entity != 0);
return position;
}
@@ -45,11 +45,11 @@ glm::quat RenderQueueFactory::AbsoluteOrientation(World* world, EntityID entity)
{
glm::quat orientation;
while (entity != EntityID_Invalid) {
do {
ComponentWrapper transform = world->GetComponent(entity, "Transform");
orientation = glm::quat((glm::vec3)transform["Orientation"]) * orientation;
entity = world->GetParent(entity);
}
} while (entity != 0);
return orientation;
}
@@ -58,11 +58,11 @@ glm::vec3 RenderQueueFactory::AbsoluteScale(World* world, EntityID entity)
{
glm::vec3 scale(1.f);
while (entity != EntityID_Invalid) {
do {
ComponentWrapper transform = world->GetComponent(entity, "Transform");
scale *= (glm::vec3)transform["Scale"];
entity = world->GetParent(entity);
}
} while (entity != 0);
return scale;
}
@@ -111,6 +111,34 @@ void RenderQueueFactory::FillModels(World* world, RenderQueue* renderQueue)
void RenderQueueFactory::FillLights(World* world, RenderQueue* renderQueue)
{
auto pointLights = world->GetComponents("PointLight");
if(pointLights == nullptr) {
return;
}
for(auto& pointlightC : *pointLights) {
bool visible = pointlightC["Visible"];
if(!visible) {
continue;
}
auto transformC = world->GetComponent(pointlightC.EntityID, "Transform");
if(&transformC == nullptr) {
return;
}
glm::vec4 color = pointlightC["Color"];
float radius = (double)pointlightC["Radius"];
float intensity = (double)pointlightC["Intensity"];
float falloff = (double)pointlightC["Falloff"];
PointLightJob job;
job.Position = glm::vec4(AbsolutePosition(world, transformC.EntityID), 1.f);
job.Color = color;
job.Radius = radius;
job.Intensity = intensity;
job.Falloff = falloff;
renderQueue->Add(job);
}
}
+1
View File
@@ -3,6 +3,7 @@
bool RenderState::Enable(GLenum cap)
{
if (glIsEnabled(cap)) {
//LOG_WARNING("Trying to enable somthing that is already enabled.");
return false;
}
m_ResetFunctions.push_back(std::bind(glDisable, cap));
+9 -135
View File
@@ -4,20 +4,17 @@ void Renderer::Initialize()
{
InitializeWindow();
// Create default camera
m_DefaultCamera = new ::Camera((float)m_Resolution.Width / m_Resolution.Height, glm::radians(45.f), 0.01f, 5000.f);
m_DefaultCamera->SetPosition(glm::vec3(0, 0, 10));
m_DefaultCamera = new ::Camera((float)m_Resolution.Width / m_Resolution.Height, glm::radians(90.0f), 0.01f, 5000.f);
m_DefaultCamera->SetPosition(glm::vec3(0, 1, 10));
if (m_Camera == nullptr) {
m_Camera = m_DefaultCamera;
}
m_DebugCameraInputController = std::make_shared<DebugCameraInputController<Renderer>>(m_EventBroker, -1);
TEMPCreateLights();
InitializeRenderPasses();
glfwSwapInterval(m_VSYNC);
InitializeShaders();
InitializeTextures();
InitializeSSBOs();
//CalculateFrustum();
m_ScreenQuad = ResourceManager::Load<Model>("Models/Core/ScreenQuad.obj");
m_UnitQuad = ResourceManager::Load<Model>("Models/Core/UnitQuad.obj");
@@ -75,49 +72,10 @@ void Renderer::InitializeShaders()
m_DrawScreenQuadProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/DrawScreenQuad.frag.glsl")));
m_DrawScreenQuadProgram->Compile();
m_DrawScreenQuadProgram->Link();
//m_CalculateFrustumProgram = ResourceManager::Load<ShaderProgram>("#CalculateFrustumProgram");
//m_CalculateFrustumProgram.AddShader(std::shared_ptr<Shader>(new ComputeShader("Shaders/GridFrustum.comp.glsl")));
//m_CalculateFrustumProgram.Compile();
//m_CalculateFrustumProgram.Link();
//m_LightCullProgram = ResourceManager::Load<ShaderProgram>("#LightCullProgram");
//m_LightCullProgram.AddShader(std::shared_ptr<Shader>(new ComputeShader("Shaders/cullLights.comp.glsl")));
//m_LightCullProgram.Compile();
//m_LightCullProgram.Link();
}
void Renderer::InputUpdate(double dt)
{
glm::vec3 m_Position = m_Camera->Position();
if (glfwGetKey(m_Window, GLFW_KEY_O) == GLFW_PRESS)
{
m_Position = glm::vec3(0.f, 0.f, 5.f);
}
if (glfwGetKey(m_Window, GLFW_KEY_W) == GLFW_PRESS)
{
m_Position += m_Camera->Forward() * m_CameraMoveSpeed * (float)dt;
}
if (glfwGetKey(m_Window, GLFW_KEY_S) == GLFW_PRESS)
{
m_Position -= m_Camera->Forward() * m_CameraMoveSpeed * (float)dt;
}
if (glfwGetKey(m_Window, GLFW_KEY_D) == GLFW_PRESS)
{
m_Position += m_Camera->Right() * m_CameraMoveSpeed * (float)dt;
}
if (glfwGetKey(m_Window, GLFW_KEY_A) == GLFW_PRESS)
{
m_Position -= m_Camera->Right() * m_CameraMoveSpeed * (float)dt;
}
if (glfwGetKey(m_Window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS)
{
m_CameraMoveSpeed = 5.f;
}
else {
m_CameraMoveSpeed = 0.5f;
}
m_DebugCameraInputController->Update(dt);
m_Camera->SetOrientation(m_DebugCameraInputController->Orientation());
m_Camera->SetPosition(m_DebugCameraInputController->Position());
@@ -134,11 +92,12 @@ void Renderer::Draw(RenderQueueCollection& rq)
{
m_PickingPass->Draw(rq);
//DrawScreenQuad(m_PickingPass->PickingTexture());
//CullLights();
m_LightCullingPass->FillLightList(rq);
m_LightCullingPass->CullLights();
//m_DrawScenePass->Draw(rq);
m_DrawFinalPass->Draw(rq);
glClearColor(255.f / 255, 163.f / 255, 176.f / 255, 1.f);
m_DrawScenePass->Draw(rq);
GLERROR("Renderer::Draw m_DrawScenePass->Draw");
m_ImGuiRenderPass->Draw();
glfwSwapBuffers(m_Window);
@@ -183,95 +142,10 @@ void Renderer::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filterin
GLERROR("Texture initialization failed");
}
void Renderer::InitializeSSBOs()
{
printf("Size: %i\n", sizeof(m_Frustums));
glGenBuffers(1, &m_FrustumSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_FrustumSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_Frustums), &m_Frustums, GL_DYNAMIC_COPY);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, m_FrustumSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLERROR("m_FrustumSSBO");
glGenBuffers(1, &m_LightSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_PointLights), &m_PointLights, GL_DYNAMIC_COPY);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLERROR("m_LightSSBO");
glGenBuffers(1, &m_LightGridSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightGridSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_LightGrid), &m_LightGrid, GL_DYNAMIC_COPY);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightGridSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLERROR("m_LightGridSSBO");
glGenBuffers(1, &m_LightOffsetSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightOffsetSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_LightOffset), &m_LightOffset, GL_DYNAMIC_COPY);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, m_LightOffsetSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLERROR("m_LightOffsetSSBO");
glGenBuffers(1, &m_LightIndexSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightIndexSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_LightIndex), &m_LightIndex, GL_DYNAMIC_COPY);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightIndexSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLERROR("m_LightIndexSSBO");
}
void Renderer::InitializeRenderPasses()
{
m_DrawScenePass = new DrawScenePass(this);
m_PickingPass = new PickingPass(this, m_EventBroker);
}
void Renderer::CalculateFrustum()
{
GLERROR("CalculateFrustum Error-1");
m_CalculateFrustumProgram->Bind();
GLERROR("CalculateFrustum Error1");
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, m_FrustumSSBO);
GLERROR("CalculateFrustum Error2");
glUniformMatrix4fv(glGetUniformLocation(m_CalculateFrustumProgram->GetHandle(), "P"), 1, false, glm::value_ptr(m_Camera->ProjectionMatrix()));
GLERROR("CalculateFrustum Error3");
glUniform2f(glGetUniformLocation(m_CalculateFrustumProgram->GetHandle(), "ScreenDimensions"), m_Resolution.Width, m_Resolution.Height);
GLERROR("CalculateFrustum Error4");
glDispatchCompute(5, 3, 1);
GLERROR("CalculateFrustum Error5");
}
void Renderer::TEMPCreateLights()
{
for (int i = 0; i < NUM_LIGHTS; i++) {
m_PointLights[i].Position = glm::vec4(i, 0.f, 0.f, 0.f);
m_PointLights[i].Color = glm::vec4(1.f, 0.5f, 0.f + i*0.1f, 1.f);
}
}
void Renderer::CullLights()
{
m_LightCullProgram->Bind();
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, m_FrustumSSBO);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightSSBO);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightGridSSBO);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, m_LightOffsetSSBO);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightIndexSSBO);
glDispatchCompute(m_Resolution.Width / TILE_SIZE, m_Resolution.Height / TILE_SIZE, 1);
GLERROR("CullLights Error");
}
m_LightCullingPass = new LightCullingPass(this);
m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass);
}
Executable → Regular
+2 -16
View File
@@ -2,28 +2,18 @@
#include "Collision/TriggerSystem.h"
#include "Collision/CollisionSystem.h"
#include "Game/HealthSystem.h"
#include "Core/DeveloperConsole.h"
#include "Core/EntityFileWriter.h"
Game::Game(int argc, char* argv[])
{
ResourceManager::RegisterType<ConfigFile>("ConfigFile");
ResourceManager::RegisterType<Model>("Model");
ResourceManager::RegisterType<Texture>("Texture");
ResourceManager::RegisterType<EntityXMLFile>("EntityXMLFile");
ResourceManager::RegisterType<ShaderProgram>("ShaderProgram");
ResourceManager::RegisterType<EntityFile>("EntityFile");
m_Config = ResourceManager::Load<ConfigFile>("Config.ini");
LOG_LEVEL = static_cast<_LOG_LEVEL>(m_Config->Get<int>("Debug.LogLevel", 1));
DeveloperConsole::MergeConfig("Config.ini");
DeveloperConsole::BindVariable("Debug.LogLevel", LOG_LEVEL);
std::string testBind = "Carlito";
DeveloperConsole::BindVariable("Test", testBind);
while (true) {
DeveloperConsole::Consume(std::cin);
}
// Create the core event broker
m_EventBroker = new EventBroker();
@@ -58,11 +48,7 @@ Game::Game(int argc, char* argv[])
m_World = new World();
std::string mapToLoad = m_Config->Get<std::string>("Debug.LoadMap", "");
if (!mapToLoad.empty()) {
auto file = ResourceManager::Load<EntityFile>(mapToLoad);
EntityFilePreprocessor fpp(file);
fpp.RegisterComponents(m_World);
EntityFileParser fp(file);
fp.MergeEntities(m_World);
ResourceManager::Load<EntityXMLFile>(mapToLoad)->PopulateWorld(m_World);
}
// Create system pipeline
+172
View File
@@ -0,0 +1,172 @@
#include "Export.h"
Export::Export()
{
}
bool Export::Meshes(std::string pathName, bool selectedOnly)
{
if (pathName.empty()) {
MGlobal::displayError(MString() + "Export::Meshes() got no pathName. Do not know where to write file");
return false;
}
meshes.clear();
if (selectedOnly) {
// Retrieving the objects we currently have selected
MSelectionList selected;
MGlobal::getActiveSelectionList(selected);
// Loop through or list of selection(s)
for (unsigned int i = 0; i < selected.length(); i++) {
MObject object;
selected.getDependNode(i, object);
if (object.hasFn(MFn::kMesh)) {
MFnDependencyNode thisNode(object);
GetMeshData(object);
}
}
} else {
// Loop through all nodes in the scene
MItDependencyNodes it(MFn::kMesh);
for (; !it.isDone(); it.next()) {
MObject node = it.thisNode();
MFnDependencyNode thisNode(node);
MPlugArray connections;
thisNode.findPlug("inMesh").connectedTo(connections, true, true);
bool next = false;
for (unsigned int i = 0; i < connections.length(); i++) {
if (connections[i].node().apiType() == MFn::kSkinClusterFilter) {
next = true;
break;
}
}
if (next)
continue;
GetMeshData(node);
}
}
MGlobal::displayInfo(MString() + "nrofmeshes: " + meshes.size());
WriteMeshData(pathName);
return true;
}
bool Export::Materials()
{
return true;
}
bool Export::Animations(std::string pathName, std::vector<AnimationInfo> animInfo)
{
if (MAnimControl::currentTime().unit() != MTime::kNTSCField) {
MGlobal::displayError(MString() + "Please change to 60 FPS under Preferences/Settings!");
return false;
}
if (pathName.empty()) {
MGlobal::displayError(MString() + "Export::Animations() got no pathName. Do not know where to write file");
return false;
}
MGlobal::displayInfo("HALLOOOO");
allBindPoses = m_SkeletonHandler.GetBindPoses();
for (auto clip : animInfo) {
MGlobal::displayInfo("preben");
if (!GetAnimationData(clip)) {
MGlobal::displayError(MString() + "Export::Animations() failed to export " + clip.Name.c_str());
return false;
}
}
MGlobal::displayInfo("ghihgihi");
WriteAnimData(pathName);
return true;
}
bool Export::GetMeshData(MObject object)
{
if (!object.hasFn(MFn::kMesh))
return false;
meshes.push_back(m_MeshHandler.GetMeshData(object));
return true;
}
bool Export::GetMaterialData()
{
// Traverse scene and return vector with all materials
std::vector<MaterialNode>* AllMaterials = m_MaterialHandler.DoIt();
// Access the colorR component of one material (example)
cout << AllMaterials->at(0).Color[0] << endl;
MGlobal::displayInfo(MString() + AllMaterials->at(0).Color[0]);
return true;
}
bool Export::GetAnimationData(AnimationInfo animInfo)
{
if (animInfo.Name.empty()) {
MGlobal::displayError(MString() + "A clip does not have a name");
return false;
}
if (animInfo.End - animInfo.Start <= 0) {
MGlobal::displayError(MString() + "A clip ends before it starts or contains 0 frames");
return false;
}
allAnimations.push_back(m_SkeletonHandler.GetAnimData(animInfo.Name, animInfo.Start, animInfo.End));
return true;
}
void Export::WriteMeshData(std::string pathName)
{
m_MeshFile.ASCIIFilePath(pathName +"_mesh.txt");
m_MeshFile.binaryFilePath(pathName + ".mesh");
m_MeshFile.OpenFiles();
for (auto aMesh : meshes) {
m_MeshFile.writeToFiles((OutputData*)&aMesh);
}
m_MeshFile.CloseFiles();
}
void Export::WriteAnimData(std::string pathName)
{
if (allBindPoses.size() > 0) {
m_AnimFile.ASCIIFilePath(pathName + "_anim.txt");
m_AnimFile.binaryFilePath(pathName + ".anim");
m_AnimFile.OpenFiles();
int size = allBindPoses.size();
m_AnimFile.writeToFiles(&size);
size = allAnimations.size();
m_AnimFile.writeToFiles(&size);
//print out all bind poses
for (auto aBindPose : allBindPoses) {
m_AnimFile.writeToFiles((OutputData*)&aBindPose);
}
for (auto aAnimation : allAnimations) {
m_AnimFile.writeToFiles((OutputData*)&aAnimation);
}
m_AnimFile.CloseFiles();
} else
MGlobal::displayInfo("Export::WriteAnimData() got called when allBindPoses contained no data, did not write nor created them");
}
Export::~Export()
{
/* delete m_MaterialHandler;
delete m_SkeletonHandler;
delete m_MeshHandler;*/
}
+54
View File
@@ -0,0 +1,54 @@
#ifndef Export_Export_h__
#define Export_Export_h__
#include <vector>
#include <string>
#include "MayaIncludes.h"
#include "Material.h"
#include "Mesh.h"
#include "Skeleton.h"
#include "WriteToFile.h"
class Export {
public:
Export();
~Export();
struct AnimationInfo {
std::string Name;
int Start;
int End;
};
bool Meshes(std::string pathName, bool selectedOnly = false);
bool Materials();
bool Animations(std::string pathName, std::vector<AnimationInfo> animInfo);
private:
bool GetMeshData(MObject object);
bool GetMaterialData();
bool GetAnimationData(AnimationInfo info);
void WriteMeshData(std::string pathName);
void WriteAnimData(std::string pathName);
Material m_MaterialHandler;
Skeleton m_SkeletonHandler;
MeshClass m_MeshHandler;
//File export
WriteToFile m_MeshFile;
WriteToFile m_AnimFile;
//Mesh Data
std::vector<Mesh> meshes;
//Animation Data
std::vector<BindPoseSkeletonNode> allBindPoses;
std::vector<Animation> allAnimations;
};
#endif
@@ -22,7 +22,7 @@ static const uint qt_meta_data_Menu[] = {
6, // revision
0, // classname
0, 0, // classinfo
7, 14, // methods
5, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
@@ -30,22 +30,19 @@ static const uint qt_meta_data_Menu[] = {
0, // signalCount
// slots: signature, parameters, type, tag, flags
14, 6, 5, 5, 0x08,
35, 5, 5, 5, 0x08,
59, 5, 5, 5, 0x08,
6, 5, 5, 5, 0x08,
30, 5, 5, 5, 0x08,
51, 5, 5, 5, 0x08,
75, 5, 5, 5, 0x08,
95, 5, 5, 5, 0x08,
116, 5, 5, 5, 0x08,
137, 5, 5, 5, 0x08,
91, 5, 5, 5, 0x08,
0 // eod
};
static const char qt_meta_stringdata_Menu[] = {
"Menu\0\0checked\0ExportSelected(bool)\0"
"ExportPathClicked(bool)\0ExportAll(bool)\0"
"CancelClicked(bool)\0Button1Clicked(bool)\0"
"Button2Clicked(bool)\0Button3Clicked(bool)\0"
"Menu\0\0ExportPathClicked(bool)\0"
"AddClipClicked(bool)\0RemoveClipClicked(bool)\0"
"ExportAll(bool)\0CancelClicked(bool)\0"
};
void Menu::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
@@ -54,13 +51,11 @@ void Menu::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void *
Q_ASSERT(staticMetaObject.cast(_o));
Menu *_t = static_cast<Menu *>(_o);
switch (_id) {
case 0: _t->ExportSelected((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 1: _t->ExportPathClicked((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 2: _t->ExportAll((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 3: _t->CancelClicked((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 4: _t->Button1Clicked((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 5: _t->Button2Clicked((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 6: _t->Button3Clicked((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 0: _t->ExportPathClicked((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 1: _t->AddClipClicked((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 2: _t->RemoveClipClicked((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 3: _t->ExportAll((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 4: _t->CancelClicked((*reinterpret_cast< bool(*)>(_a[1]))); break;
default: ;
}
}
@@ -98,9 +93,9 @@ int Menu::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 7)
if (_id < 5)
qt_static_metacall(this, _c, _id, _a);
_id -= 7;
_id -= 5;
}
return _id;
}
@@ -0,0 +1,241 @@
#include "Material.h"
void Material::grabLambertProperties(MaterialNode& material_node, MFnDependencyNode& node)
{
material_node.Name = node.name().asChar();
if (findColorTexture(material_node, node)) {
material_node.Color.fill(1.0f);
}
else {
m_Plug = node.findPlug("colorR");
m_Plug.getValue(material_node.Color[0]);
m_Plug = node.findPlug("colorG");
m_Plug.getValue(material_node.Color[1]);
m_Plug = node.findPlug("colorB");
m_Plug.getValue(material_node.Color[2]);
float TempTransp[3];
m_Plug = node.findPlug("transparencyR");
m_Plug.getValue(TempTransp[0]);
m_Plug = node.findPlug("transparencyG");
m_Plug.getValue(TempTransp[1]);
m_Plug = node.findPlug("transparencyB");
m_Plug.getValue(TempTransp[2]);
MColor TranspNode(TempTransp[0], TempTransp[1], TempTransp[2]);
float DummyH, DummyS;
TranspNode.get(MColor::kHSV, DummyH, DummyS, material_node.Color[3]);
}
if (findIncandescenceTexture(material_node, node)) {
material_node.Incandescence.fill(1.0f);
}
else {
m_Plug = node.findPlug("incandescenceR");
m_Plug.getValue(material_node.Incandescence[0]);
m_Plug = node.findPlug("incandescenceG");
m_Plug.getValue(material_node.Incandescence[1]);
m_Plug = node.findPlug("incandescenceB");
m_Plug.getValue(material_node.Incandescence[2]);
}
findNormalTexture(material_node, node);
}
void Material::grabBlinnProperties(MaterialNode& material_node, MFnDependencyNode& node)
{
if (findSpecularTexture(material_node, node)) {
material_node.Specular.fill(1.0f);
}
else {
m_Plug = node.findPlug("specularColorR");
m_Plug.getValue(material_node.Specular[0]);
m_Plug = node.findPlug("specularColorG");
m_Plug.getValue(material_node.Specular[1]);
m_Plug = node.findPlug("specularColorB");
m_Plug.getValue(material_node.Specular[2]);
}
m_Plug = node.findPlug("reflectivity");
m_Plug.getValue(material_node.ReflectionFactor);
m_Plug = node.findPlug("eccentricity");
float TempEccent;
m_Plug.getValue(TempEccent);
// Blinn works differently from Phong which is used in-game.
// This is some magic numbers and math to make a conversion estimate between the two.
// There is no exact conversion between the two, so there are errors.
// Phong min/max is around Blinn 0.7/0.1
TempEccent = std::max(std::min(TempEccent, 0.7f), 0.1f);
material_node.SpecularExponent = std::max(std::min(((2.66f) + (427.0f) * exp((-14.8f) * TempEccent)), 100.0f), 2.0f);
}
void Material::grabPhongProperties(MaterialNode& material_node, MFnDependencyNode& node)
{
if (findSpecularTexture(material_node, node)) {
material_node.Specular.fill(1.0f);
}
else {
m_Plug = node.findPlug("specularColorR");
m_Plug.getValue(material_node.Specular[0]);
m_Plug = node.findPlug("specularColorG");
m_Plug.getValue(material_node.Specular[1]);
m_Plug = node.findPlug("specularColorB");
m_Plug.getValue(material_node.Specular[2]);
}
m_Plug = node.findPlug("reflectivity");
m_Plug.getValue(material_node.ReflectionFactor);
m_Plug = node.findPlug("cosinePower ");
m_Plug.getValue(material_node.SpecularExponent);
}
bool Material::findColorTexture(MaterialNode& material_node, MFnDependencyNode& node)
{
MPlugArray AllConnections;
m_Plug = node.findPlug("color", true);
m_Plug.connectedTo(AllConnections, true, false);
for (int i = 0; i < AllConnections.length(); i++) {
if (AllConnections[i].node().hasFn(MFn::kFileTexture)) {
MFnDependencyNode TextureNode(AllConnections[i].node());
std::string FullPath = TextureNode.findPlug("ftn").asString().asChar();
m_TexturePaths.push_back(FullPath);
material_node.ColorMapFile = FullPath.substr(FullPath.find_last_of("/"));
// Test
MGlobal::displayInfo(MString() + "Texture file: " + FullPath.c_str());
return true;
}
}
return false;
}
bool Material::findNormalTexture(MaterialNode& material_node, MFnDependencyNode& node)
{
MPlugArray AllConnections;
MPlugArray AllBumpConnections;
m_Plug = node.findPlug("normalCamera", true);
m_Plug.connectedTo(AllConnections, true, false);
for (int i = 0; i < AllConnections.length(); i++) {
if (AllConnections[i].node().apiType() == MFn::kBump) {
MFnDependencyNode BumpNode(AllConnections[i].node());
BumpNode.findPlug("bumpValue").connectedTo(AllBumpConnections, true, false);
for (int j = 0; j < AllBumpConnections.length(); j++) {
if (AllBumpConnections[j].node().hasFn(MFn::kFileTexture)) {
MFnDependencyNode TextureNode(AllBumpConnections[j].node());
std::string FullPath = TextureNode.findPlug("ftn").asString().asChar();
m_TexturePaths.push_back(FullPath);
material_node.NormalMapFile = FullPath.substr(FullPath.find_last_of("/"));
return true;
}
}
}
}
return false;
}
bool Material::findSpecularTexture(MaterialNode& material_node, MFnDependencyNode& node)
{
MPlugArray AllConnections;
m_Plug = node.findPlug("specularColor", true);
m_Plug.connectedTo(AllConnections, true, false);
for (int i = 0; i < AllConnections.length(); i++) {
if (AllConnections[i].node().hasFn(MFn::kFileTexture)) {
MFnDependencyNode TextureNode(AllConnections[i].node());
std::string FullPath = TextureNode.findPlug("ftn").asString().asChar();
m_TexturePaths.push_back(FullPath);
material_node.SpecularMapFile = FullPath.substr(FullPath.find_last_of("/"));
return true;
}
}
return false;
}
bool Material::findIncandescenceTexture(MaterialNode& material_node, MFnDependencyNode& node)
{
MPlugArray AllConnections;
m_Plug = node.findPlug("incandescence", true);
m_Plug.connectedTo(AllConnections, true, false);
for (int i = 0; i < AllConnections.length(); i++) {
if (AllConnections[i].node().hasFn(MFn::kFileTexture)) {
MFnDependencyNode TextureNode(AllConnections[i].node());
std::string FullPath = TextureNode.findPlug("ftn").asString().asChar();
m_TexturePaths.push_back(FullPath);
material_node.SpecularMapFile = FullPath.substr(FullPath.find_last_of("/"));
return true;
}
}
return false;
}
// Returns the absolute path for all textures. Use for copying texture files.
std::vector<std::string>* Material::TexturePaths()
{
return &m_TexturePaths;
}
// Traverse the DAG and grab all the materials
std::vector<MaterialNode>* Material::DoIt()
{
// All materials we care about inherit from Lambert
MItDependencyNodes matIt(MFn::kLambert);
while (!matIt.isDone()) {
MFnDependencyNode MaterialFnDN(matIt.thisNode());
MaterialNode MaterialStorage;
if (matIt.thisNode().hasFn(MFn::kPhong)) {
grabLambertProperties(MaterialStorage, MaterialFnDN);
grabPhongProperties(MaterialStorage, MaterialFnDN);
m_AllMaterials.push_back(MaterialStorage);
}
else if (matIt.thisNode().hasFn(MFn::kBlinn)) {
grabLambertProperties(MaterialStorage, MaterialFnDN);
grabBlinnProperties(MaterialStorage, MaterialFnDN);
m_AllMaterials.push_back(MaterialStorage);
}
else if (matIt.thisNode().hasFn(MFn::kLambert)) {
grabLambertProperties(MaterialStorage, MaterialFnDN);
MaterialStorage.Specular.fill(0.0f);
MaterialStorage.ReflectionFactor = 0.0f;
MaterialStorage.SpecularExponent = 0.0f;
m_AllMaterials.push_back(MaterialStorage);
}
matIt.next();
}
return &m_AllMaterials;
}
@@ -0,0 +1,47 @@
#ifndef Material_Material_h__
#define Material_Material_h__
#include <vector>
#include <array>
#include <algorithm>
#include <cmath>
#include "MayaIncludes.h"
struct MaterialNode
{
std::string Name;
std::array<float, 4> Color;
std::array<float, 3> Incandescence;
std::array<float, 3> Specular;
float ReflectionFactor;
float SpecularExponent;
std::string ColorMapFile;
std::string SpecularMapFile;
std::string NormalMapFile;
std::string IncandescenceMapFile;
};
class Material
{
public:
Material() {};
~Material() {};
std::vector<MaterialNode>* DoIt();
std::vector<std::string>* TexturePaths();
private:
MPlug m_Plug;
std::vector<MaterialNode> m_AllMaterials;
std::vector<std::string> m_TexturePaths;
bool findColorTexture(MaterialNode& material_node, MFnDependencyNode& node);
bool findNormalTexture(MaterialNode& material_node, MFnDependencyNode& node);
bool findSpecularTexture(MaterialNode& material_node, MFnDependencyNode& node);
bool findIncandescenceTexture(MaterialNode& material_node, MFnDependencyNode& node);
void grabLambertProperties(MaterialNode& material_node, MFnDependencyNode& node);
void grabBlinnProperties(MaterialNode& material_node, MFnDependencyNode& node);
void grabPhongProperties(MaterialNode& material_node, MFnDependencyNode& node);
};
#endif // Material_Material_h__
@@ -140,6 +140,7 @@
</DebugInformationFormat>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<Optimization>Disabled</Optimization>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
@@ -152,6 +153,8 @@
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="Export.cpp" />
<ClCompile Include="Material.cpp" />
<ClCompile Include="Menu.cpp" />
<ClCompile Include="GeneratedFiles\Debug\moc_Menu.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
@@ -172,6 +175,9 @@
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="Main.cpp" />
<ClCompile Include="Mesh.cpp" />
<ClCompile Include="Skeleton.cpp" />
<ClCompile Include="WriteToFile.cpp" />
</ItemGroup>
<ItemGroup>
<CustomBuild Include="MayaExporter.ui">
@@ -194,6 +200,11 @@
</CustomBuild>
</ItemGroup>
<ItemGroup>
<ClInclude Include="Export.h" />
<ClInclude Include="Mesh.h" />
<ClInclude Include="OutputData.h" />
<ClInclude Include="Skeleton.h" />
<ClInclude Include="WriteToFile.h" />
<CustomBuild Include="Menu.h">
<Message Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Moc%27ing Menu.h...</Message>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\GeneratedFiles\$(ConfigurationName)\moc_%(Filename).cpp</Outputs>
@@ -213,6 +224,7 @@
<AdditionalInputs Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(QTDIR)\bin\moc.exe;%(FullPath);$(QTDIR)\bin\moc.exe;%(FullPath)</AdditionalInputs>
</CustomBuild>
<ClInclude Include="GeneratedFiles\ui_MayaExporter.h" />
<ClInclude Include="Material.h" />
<ClInclude Include="MayaIncludes.h" />
</ItemGroup>
<ItemGroup>
@@ -50,6 +50,21 @@
<ClCompile Include="Main.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Material.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Mesh.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Skeleton.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="WriteToFile.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Export.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="leeeeel.qrc">
@@ -69,5 +84,23 @@
<ClInclude Include="GeneratedFiles\ui_MayaExporter.h">
<Filter>Generated Files</Filter>
</ClInclude>
<ClInclude Include="Material.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Mesh.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Skeleton.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="WriteToFile.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="OutputData.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Export.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>
@@ -30,6 +30,18 @@
#include <maya/MItDependencyNodes.h>
#include <maya/MFnNurbsCurve.h>
#include <maya/MCommandMessage.h>
#include <maya/MPlug.h>
#include <maya/MAnimControl.h>
#include <maya/MTime.h>
#include <maya/MDataHandle.h>
#include <maya/MTransformationMatrix.h>
#include <maya/MFnMatrixData.h>
#include <maya/MItMeshFaceVertex.h>
#include <maya/MFnSkinCluster.h>
#include <maya/MDagPathArray.h>
#include <maya/MItGeometry.h>
#include <maya/MItMeshVertex.h>
#include <maya/MFnWeightGeometryFilter.h>
// Wrappers
@@ -58,5 +70,6 @@
#pragma comment(lib,"Foundation.lib")
#pragma comment(lib,"OpenMaya.lib")
#pragma comment(lib,"OpenMayaUI.lib")
#pragma comment (lib, "OpenMayaAnim.lib")
#endif
+145 -165
View File
@@ -10,223 +10,200 @@ Menu::Menu()
Menu::Menu(QDialog* dialog)
{
// Save the dialog pointer. Needed when the application gets destroyed
dialogPointer = dialog;
m_DialogPointer = dialog;
// Create QpushButtons & give them names
exportSelectedButton = new QPushButton("&Export Selected", this);
browseButton = new QPushButton("&...", this);
exportAllButton = new QPushButton("&Export All", this);
cancelButton = new QPushButton("&Cancel", this);
m_BrowseButton = new QPushButton("&...", this);
m_ExportAllButton = new QPushButton("&Export", this);
m_CancelButton = new QPushButton("&Cancel", this);
m_AddClipsButton = new QPushButton("&Add Clips", this);
m_RemoveClipsButton = new QPushButton("&Remove Latest Clip", this);
// Option box and checkboxes
QGroupBox *optionsBox = new QGroupBox(tr("Options"));
exportAnimationsButton = new QCheckBox(tr("&Export Animations"));
copyTexturesButton = new QCheckBox(tr("&Copy Textures"));
button3 = new QCheckBox(tr("option3"));
m_ExportSelectedButton = new QCheckBox(tr("&Export Selected"));
m_ExportAnimationsButton = new QCheckBox(tr("&Export Animations"));
m_CopyTexturesButton = new QCheckBox(tr("&Copy Textures"));
m_Button3 = new QCheckBox(tr("Test Materials"));
exportAnimationsButton->setChecked(true);
copyTexturesButton->setChecked(true);
m_ExportAnimationsButton->setChecked(true);
m_CopyTexturesButton->setChecked(true);
QVBoxLayout *vbox = new QVBoxLayout;
vbox->addWidget(exportAnimationsButton);
vbox->addWidget(copyTexturesButton);
vbox->addWidget(button3);
vbox->addWidget(m_ExportSelectedButton);
vbox->addWidget(m_ExportAnimationsButton);
vbox->addWidget(m_CopyTexturesButton);
vbox->addWidget(m_Button3);
vbox->addStretch(1);
optionsBox->setLayout(vbox);
// Connect the buttons with signals & functions
connect(exportSelectedButton, SIGNAL(clicked(bool)), this, SLOT(ExportSelected(bool)));
connect(browseButton, SIGNAL(clicked(bool)), this, SLOT(ExportPathClicked(bool)));
connect(exportAllButton, SIGNAL(clicked(bool)), this, SLOT(ExportAll(bool)));
connect(cancelButton, SIGNAL(clicked(bool)), this, SLOT(CancelClicked(bool)));
connect(m_BrowseButton, SIGNAL(clicked(bool)), this, SLOT(ExportPathClicked(bool)));
connect(m_ExportAllButton, SIGNAL(clicked(bool)), this, SLOT(ExportAll(bool)));
connect(m_CancelButton, SIGNAL(clicked(bool)), this, SLOT(CancelClicked(bool)));
connect(m_AddClipsButton, SIGNAL(clicked(bool)), this, SLOT(AddClipClicked(bool)));
connect(m_RemoveClipsButton, SIGNAL(clicked(bool)), this, SLOT(RemoveClipClicked(bool)));
connect(exportAnimationsButton, SIGNAL(clicked(bool)), this, SLOT(Button1Clicked(bool)));
connect(copyTexturesButton, SIGNAL(clicked(bool)), this, SLOT(Button2Clicked(bool)));
connect(button3, SIGNAL(clicked(bool)), this, SLOT(Button3Clicked(bool)));
connect(m_ExportSelectedButton, SIGNAL(clicked(bool)), this, SLOT(NULL));
connect(m_ExportAnimationsButton, SIGNAL(clicked(bool)), this, SLOT(NULL));
connect(m_CopyTexturesButton, SIGNAL(clicked(bool)), this, SLOT(NULL));
connect(m_Button3, SIGNAL(clicked(bool)), this, SLOT(NULL));
// Creating several layouts, adding widgets & adding them to one layout in the end
QHBoxLayout* topLayout = new QHBoxLayout;
QVBoxLayout* midLayout = new QVBoxLayout;
QHBoxLayout* botLayout = new QHBoxLayout;
QVBoxLayout* baseLayout = new QVBoxLayout;
QHBoxLayout* clipButtonLayout = new QHBoxLayout;
QHBoxLayout* startEndLabelLayout = new QHBoxLayout;
m_ClipLayout = new QVBoxLayout;
exportPath = new QLineEdit;
fileDialog = new QFileDialog;
m_ExportPath = new QLineEdit;
m_FileDialog = new QFileDialog;
QString tmpPath("C:/Users/Nickelodion/Desktop/Baljj");
m_ExportPath->setText(tmpPath);
QLabel* exportLabel = new QLabel;
exportLabel->setText("Export Path:");
QLabel* nameLabel = new QLabel;
nameLabel->setText("Name:");
QLabel* startLabel = new QLabel;
startLabel->setText("Start:");
QLabel* endLabel = new QLabel;
endLabel->setText("End:");
//exportLabel->setText("Export Path:");
midLayout->addWidget(optionsBox);
topLayout->addWidget(exportLabel);
topLayout->addWidget(exportPath);
topLayout->addWidget(browseButton);
topLayout->addWidget(m_ExportPath);
topLayout->addWidget(m_BrowseButton);
botLayout->addWidget(exportSelectedButton);
botLayout->addWidget(exportAllButton);
botLayout->addWidget(cancelButton);
botLayout->addWidget(m_ExportAllButton);
botLayout->addWidget(m_CancelButton);
startEndLabelLayout->addWidget(nameLabel);
startEndLabelLayout->addWidget(startLabel);
startEndLabelLayout->addWidget(endLabel);
clipButtonLayout->addWidget(m_AddClipsButton);
clipButtonLayout->addWidget(m_RemoveClipsButton);
baseLayout->addLayout(topLayout);
baseLayout->addLayout(midLayout);
baseLayout->addSpacing(10);
baseLayout->addLayout(botLayout);
baseLayout->addSpacing(10);
baseLayout->addLayout(clipButtonLayout);
baseLayout->addLayout(startEndLabelLayout);
baseLayout->addLayout(m_ClipLayout);
baseLayout->addStretch();
// Set the layout for our window
dialog->setLayout(baseLayout);
}
void Menu::ExportSelected(bool checked)
{
// Retrieving the objects we currently have selected
MSelectionList selected;
MGlobal::getActiveSelectionList(selected);
// Loop through or list of selection(s)
for (unsigned int i = 0; i < selected.length();i++)
{
MObject object;
selected.getDependNode(i, object);
MFnDependencyNode thisNode(object);
cout << thisNode.name().asChar() << endl;
GetMeshData(object);
for (unsigned int i = 0; i < 3; i++) {
this->AddClipClicked(true);
}
if (exportPath->text().isEmpty())
cout << "Please select a folder." << endl;
else
cout << exportPath->text().toLocal8Bit().constData() << endl;
}
void Menu::ExportPathClicked(bool)
{
// Opens up a file dialog. Save/Changes the name in the exportPath
fileDialog->setFileMode(QFileDialog::Directory);
fileDialog->setOption(QFileDialog::ShowDirsOnly);
QString fileName = fileDialog->getExistingDirectory(this, "Select", "/home", QFileDialog::ShowDirsOnly);
exportPath->setText(fileName);
m_FileDialog->setFileMode(QFileDialog::Directory);
m_FileDialog->setOption(QFileDialog::ShowDirsOnly);
QString fileName = m_FileDialog->getExistingDirectory(this, "Select", "/home", QFileDialog::ShowDirsOnly);
m_ExportPath->setText(fileName);
}
void Menu::AddClipClicked(bool)
{
QHBoxLayout* tempLayout = new QHBoxLayout;
QLineEdit* nameLineEdit = new QLineEdit;
QLineEdit* startLineEdit = new QLineEdit;
QLineEdit* endLineEdit = new QLineEdit;
m_AnimationClipName.push_back(nameLineEdit);
m_StartFrameLines.push_back(startLineEdit);
m_EndFrameLines.push_back(endLineEdit);
tempLayout->addWidget(nameLineEdit);
tempLayout->addWidget(startLineEdit);
tempLayout->addWidget(endLineEdit);
m_ClipLayout->addLayout(tempLayout);
//m_ClipLayout->update();
layouts.push_back(tempLayout);
}
void Menu::RemoveClipClicked(bool)
{
if (m_StartFrameLines.size() > 0) {
QLayoutItem* tempWidget;// = m_ClipLayout->itemAt(0);
for (unsigned int i = 0; i < layouts.size(); i++) {
while ((tempWidget = layouts[layouts.size() - 1]->takeAt(0)) != 0) {
delete tempWidget->widget();
delete tempWidget;
}
}
m_ClipLayout->removeItem(tempWidget);
m_ClipLayout->update();
layouts.pop_back();
m_StartFrameLines.pop_back();
m_EndFrameLines.pop_back();
m_AnimationClipName.pop_back();
}
}
void Menu::ExportAll(bool)
{
MDagPath path;
// Loop through all nodes in the scene
MItDependencyNodes it(MFn::kInvalid);
for (;!it.isDone();it.next())
{
MObject node = it.thisNode();
if (node.hasFn(MFn::kMesh))
{
MFnDependencyNode thisNode(node);
if (m_ExportPath->text().isEmpty()) {
MGlobal::displayError(MString() + "Please select a folder.");
return;
}
cout << thisNode.name().asChar() << endl;
GetMeshData(node);
}
}
if (exportPath->text().isEmpty())
cout << "Please select a folder." << endl;
else
cout << exportPath->text().toLocal8Bit().constData() << endl;
//Export meshes
if (!m_Export.Meshes(m_ExportPath->text().toLocal8Bit().constData(), m_ExportSelectedButton->isChecked())) {
MGlobal::displayError(MString() + "Could not export mesh");
return;
}
std::vector<Export::AnimationInfo> animations;
MGlobal::displayInfo(MString() + "yeeehaa");
for (unsigned int i = 0; i < m_AnimationClipName.size(); i++) {
Export::AnimationInfo thisClip;
MGlobal::displayInfo(MString() + "qwqw");
thisClip.Name = std::string(m_AnimationClipName[i]->text().toLocal8Bit().constData());
MGlobal::displayInfo(MString() + "shizzzz");
thisClip.Start = m_StartFrameLines[i]->text().toInt();
MGlobal::displayInfo(MString() + "dsdsfg");
thisClip.End = m_EndFrameLines[i]->text().toInt();
MGlobal::displayInfo(MString() + "aaaaaaaaaaaaaaaaaaaa");
animations.push_back(thisClip);
}
MGlobal::displayInfo(MString() + "asdf");
if (m_ExportAnimationsButton->isChecked()) {
//Export Animations
if (!m_Export.Animations(m_ExportPath->text().toLocal8Bit().constData(), animations)) {
MGlobal::displayError(MString() + "Could not export animations");
return;
}
}
}
void Menu::CancelClicked(bool)
{
dialogPointer->close();
}
void Menu::Button1Clicked(bool)
{
if(exportAnimationsButton->isChecked())
cout << "1 checked!" << endl;
else
cout << "1 unchecked!" << endl;
}
void Menu::Button2Clicked(bool)
{
if (copyTexturesButton->isChecked())
cout << "2 checked!" << endl;
else
cout << "2 unchecked!" << endl;
}
void Menu::Button3Clicked(bool)
{
if (button3->isChecked())
cout << "3 checked!" << endl;
else
cout << "3 unchecked!" << endl;
}
void Menu::GetMeshData(MObject object)
{
// In here, we retrieve triangulated polygons from the mesh
MFnMesh mesh(object);
map<UINT, vector<UINT>> vertexToIndex;
vector<VertexLayout> verticesData;
vector<UINT>indexArray;
MIntArray intdexOffsetVertexCount, vertices, triangleList;
MPointArray dummy;
UINT vertexIndex;
MVector normal;
MPoint pos;
float2 UV;
VertexLayout thisVertex;
for (MItMeshPolygon meshPolyIter(object); !meshPolyIter.isDone(); meshPolyIter.next())
{
vector<UINT> localVertexToGlobalIndex;
meshPolyIter.getVertices(vertices);
meshPolyIter.getTriangles(dummy, triangleList);
UINT indexOffset = verticesData.size();
for (UINT i = 0; i < vertices.length(); i++)
{
vertexIndex = meshPolyIter.vertexIndex(i);
pos = meshPolyIter.point(i);
pos.get(thisVertex.pos);
meshPolyIter.getNormal(i, normal);
thisVertex.normal[0] = normal[0];
thisVertex.normal[1] = normal[1];
thisVertex.normal[2] = normal[2];
meshPolyIter.getUV(i, UV);
thisVertex.uv[0] = UV[0];
thisVertex.uv[1] = UV[1];
verticesData.push_back(thisVertex);
localVertexToGlobalIndex.push_back(vertexIndex);
cout << "Pos: " << thisVertex.pos[0] << "/" << thisVertex.pos[1] << "/" << thisVertex.pos[2] << endl;
cout << "Normals: " << thisVertex.normal[0] << "/" << thisVertex.normal[1] << "/" << thisVertex.normal[2] << endl;
cout << "UV: " << thisVertex.uv[0] << "/" << thisVertex.uv[1] << endl;
}
for (UINT i = 0; i < triangleList.length(); i++)
{
UINT k = 0;
while (localVertexToGlobalIndex[k] != triangleList[i])
k++;
indexArray.push_back(indexOffset + k);
}
}
}
void Menu::exportMaterial(MObject object)
{
MItDependencyNodes matIt(MFn::kLambert);
m_DialogPointer->close();
}
Menu::~Menu()
@@ -235,5 +212,8 @@ Menu::~Menu()
//delete browseButton;
//delete exportPath;
//delete fileDialog;
fileDialog->~QFileDialog();
m_FileDialog->~QFileDialog();
//delete m_Export;
//delete MaterialHandler;
}
+27 -28
View File
@@ -1,10 +1,9 @@
#ifndef BUTTONS_H
#define BUTTONS_H
#ifndef Menu_Menu_h__
#define Menu_Menu_h__
#include <map>
#include <vector>
#include "MayaIncludes.h"
// Qt
#pragma comment(lib, "QtCore4")
#pragma comment(lib, "QtGui4")
@@ -30,13 +29,11 @@
#include <QtGui/qfiledialog.h>
#include <QtGui/qlineedit.h>
#include <QtGui/qgroupbox.h>
#include <QtGui/qlayoutitem.h>
#include <QtGui/qtabwidget.h>
struct VertexLayout
{
float pos[3];
float normal[3];
float uv[2];
};
#include "MayaIncludes.h"
#include "Export.h"
class Menu : public QWidget
{
@@ -45,35 +42,37 @@ public:
Menu(QDialog* dialog);
~Menu();
void GetMeshData(MObject object);
void exportMaterial(MObject object);
private slots:
void ExportSelected(bool checked);
void ExportPathClicked(bool);
void AddClipClicked(bool);
void RemoveClipClicked(bool);
void ExportAll(bool);
void CancelClicked(bool);
void Button1Clicked(bool);
void Button2Clicked(bool);
void Button3Clicked(bool);
private:
Menu();
QPushButton* exportSelectedButton;
QPushButton* browseButton;
QPushButton* exportAllButton;
QPushButton* cancelButton;
std::vector<QLineEdit*> m_AnimationClipName;
std:: vector<QLineEdit*> m_StartFrameLines;
std::vector<QLineEdit*> m_EndFrameLines;
std::vector<QHBoxLayout*> layouts;
QVBoxLayout* m_ClipLayout;
QCheckBox* exportAnimationsButton;
QCheckBox* copyTexturesButton;
QCheckBox* button3;
QPushButton* m_BrowseButton = nullptr;
QPushButton* m_ExportAllButton = nullptr;
QPushButton* m_CancelButton = nullptr;
QPushButton* m_AddClipsButton = nullptr;
QPushButton* m_RemoveClipsButton = nullptr;
QLineEdit* exportPath;
QFileDialog* fileDialog;
QDialog* dialogPointer;
QCheckBox* m_ExportSelectedButton = nullptr;
QCheckBox* m_ExportAnimationsButton = nullptr;
QCheckBox* m_CopyTexturesButton = nullptr;
QCheckBox* m_Button3 = nullptr;
QLineEdit* m_ExportPath = nullptr;
QFileDialog* m_FileDialog = nullptr;
QDialog* m_DialogPointer = nullptr;
Export m_Export;
};
#endif
+190
View File
@@ -0,0 +1,190 @@
#pragma once
#include "Mesh.h"
using namespace std;
MeshClass::MeshClass()
{
}
std::map<int, MeshClass::WeightInfo> MeshClass::GetWeightData()
{
map<int, WeightInfo> weightMap;
MItDependencyNodes it(MFn::kSkinClusterFilter);
while (!it.isDone()) {
MObject object = it.item();
MFnSkinCluster skinCluster(object);
MDagPathArray influences;
unsigned int nrOfInfluences = skinCluster.influenceObjects(influences);
unsigned int index;
index = skinCluster.indexForOutputConnection(0);
MDagPath skinPath;
skinCluster.getPathAtIndex(index, skinPath);
MItGeometry geomIter(skinPath);
//for (unsigned int i = 0; i < nrOfInfluences; i++) {
// MGlobal::displayInfo(MString() + " Influence object name: " + influences[i].partialPathName().asChar());
//}
WeightInfo weightInfo;
while (!geomIter.isDone()) {
MObject comp = geomIter.component();
MFloatArray weights;
unsigned int influenceCount;
skinCluster.getWeights(skinPath, comp, weights, influenceCount);
MFnDependencyNode test(comp);
unsigned int nrOfWeights = 0;
for (unsigned int j = 0; j < weights.length() && nrOfWeights != 4; j++) {
if (weights[j] > 0.00001) {
weightInfo.BoneWeights[nrOfWeights] = weights[j];
weightInfo.BoneIndices[nrOfWeights] = j;
nrOfWeights++;
}
}
float totalWeight = 0.0f;
for (unsigned int i = 0; i < 4; i++) {
totalWeight += weightInfo.BoneWeights[i];
}
for (unsigned int i = 0; i < 4; i++) {
weightInfo.BoneWeights[i] /= totalWeight;
}
weightMap[geomIter.index()] = weightInfo;
for (unsigned int k = 0; k!=nrOfWeights; k++) {
//MGlobal::displayInfo(MString() + "influence: " + weightInfo.BoneIndices[k] + " weight: " + weightInfo.BoneWeights[k]);
}
geomIter.next();
}
it.next();
}
return weightMap;
}
Mesh MeshClass::GetMeshData(MObject object)
{
Mesh newMesh;
std::vector<VertexLayout>& vertexList = newMesh.Vertices;
std::vector<int>& indexList = newMesh.Indices;
// In here, we retrieve triangulated polygons from the mesh
MFnMesh mesh(object);
map<unsigned int, vector<unsigned int>> vertexToIndex;;
MIntArray intdexOffsetVertexCount, vertices, triangleList;
MPointArray dummy;
unsigned int vertexIndex;
MVector normal;
MPoint pos;
float2 UV;
double biTangent[3];
double biNormal[3];
VertexLayout thisVertex;
MFloatVectorArray biTangents;
MFloatVectorArray biNormals;
std::map<int, WeightInfo> vertexWeights = GetWeightData();
mesh.getTangents(biTangents, MSpace::kObject, NULL);
mesh.getBinormals(biNormals, MSpace::kObject, NULL);
MItMeshFaceVertex faceVert(object);
int intDummy = 0;
for (MItMeshPolygon meshPolyIter(object); !meshPolyIter.isDone(); meshPolyIter.next()) {
vector<unsigned int> localVertexToGlobalIndex;
unsigned int indexOffset = vertexList.size();
meshPolyIter.getVertices(vertices);
meshPolyIter.getTriangles(dummy, triangleList);
//MGlobal::displayInfo("Befor Second Loop");
for (unsigned int i = 0; i < vertices.length(); i++) {
vertexIndex = meshPolyIter.vertexIndex(i);
faceVert.setIndex(meshPolyIter.index(), i, intDummy, intDummy);
//MGlobal::displayInfo("In Second Loop");
faceVert.position().get(thisVertex.Pos);
faceVert.getNormal(normal);
thisVertex.Normal[0] = normal[0];
thisVertex.Normal[1] = normal[1];
thisVertex.Normal[2] = normal[2];
MFloatVector biTangent = biTangents[faceVert.tangentId()];
//MVector tmp = faceVert.getTangent(MSpace::kObject, NULL);
//tmp.get(biTangent);
thisVertex.BiTangent[0] = biTangent[0];
thisVertex.BiTangent[1] = biTangent[1];
thisVertex.BiTangent[2] = biTangent[2];
MFloatVector biNormal = biNormals[faceVert.tangentId()];
//faceVert.getBinormal().get(biNormal);
thisVertex.BiNormal[0] = biNormal[0];
thisVertex.BiNormal[1] = biNormal[1];
thisVertex.BiNormal[2] = biNormal[2];
faceVert.getUV(UV);
thisVertex.Uv[0] = UV[0];
thisVertex.Uv[1] = UV[1];
thisVertex.BoneIndices[0] = vertexWeights[faceVert.vertId()].BoneIndices[0];
thisVertex.BoneIndices[1] = vertexWeights[faceVert.vertId()].BoneIndices[1];
thisVertex.BoneIndices[2] = vertexWeights[faceVert.vertId()].BoneIndices[2];
thisVertex.BoneIndices[3] = vertexWeights[faceVert.vertId()].BoneIndices[3];
thisVertex.BoneWeights[0] = vertexWeights[faceVert.vertId()].BoneWeights[0];
thisVertex.BoneWeights[1] = vertexWeights[faceVert.vertId()].BoneWeights[1];
thisVertex.BoneWeights[2] = vertexWeights[faceVert.vertId()].BoneWeights[2];
thisVertex.BoneWeights[3] = vertexWeights[faceVert.vertId()].BoneWeights[3];
std::vector<VertexLayout>::iterator it = std::find(vertexList.begin(), vertexList.end(), thisVertex);
if (it != vertexList.end()) {
localVertexToGlobalIndex.push_back(vertexIndex);
} else {
localVertexToGlobalIndex.push_back(vertexIndex);
vertexList.push_back(thisVertex);
}
//cout << "Pos: " << thisVertex.Pos[0] << "/" << thisVertex.Pos[1] << "/" << thisVertex.Pos[2] << endl;
//cout << "Normals: " << thisVertex.Normal[0] << "/" << thisVertex.Normal[1] << "/" << thisVertex.Normal[2] << endl;
//cout << "Bi-Normals: " << thisVertex.BiNormal[0] << "/" << thisVertex.BiNormal[1] << "/" << thisVertex.BiNormal[2] << endl;
//cout << "Bi-Tangents: " << thisVertex.BiTangent[0] << "/" << thisVertex.BiTangent[1] << "/" << thisVertex.BiTangent[2] << endl;
//cout << "UV: " << thisVertex.Uv[0] << "/" << thisVertex.Uv[1] << endl;
}
for (unsigned int i = 0; i < triangleList.length(); i++) {
unsigned int k = 0;
if (localVertexToGlobalIndex.size() > 0) {
while (localVertexToGlobalIndex[k] != triangleList[i] && k < localVertexToGlobalIndex.size()) {
k++;
}
indexList.push_back(indexOffset + k);
}
}
}
newMesh.NumIndices = newMesh.Indices.size();
newMesh.NumVertices = newMesh.Vertices.size();
return newMesh;
}
MeshClass::~MeshClass()
{
}
+110
View File
@@ -0,0 +1,110 @@
#ifndef Mesh_Mesh_h__
#define Mesh_Mesh_h__
#include <map>
#include <vector>
#include "OutputData.h"
#include "MayaIncludes.h"
class VertexLayout : public OutputData
{
public:
float Pos[3];
float Normal[3];
float BiNormal[3];
float BiTangent[3];
float Uv[2];
float BoneIndices[4];
float BoneWeights[4];
virtual void WriteBinary(std::ostream& out)
{
out.write((char*)&Pos, sizeof(float) * 3);
out.write((char*)&Normal, sizeof(float) * 3);
out.write((char*)&BiNormal, sizeof(float) * 3);
out.write((char*)&BiTangent, sizeof(float) * 3);
out.write((char*)&Uv, sizeof(float) * 2);
out.write((char*)&BoneIndices, sizeof(float) * 4);
out.write((char*)&BoneWeights, sizeof(float) * 4);
}
virtual void WriteASCII(std::ostream& out) const
{
out << Pos[0] << " " << Pos[1] << " " << Pos[2] << endl;
out << Normal[0] << " " << Normal[1] << " " << Normal[2] << endl;
out << BiNormal[0] << " " << BiNormal[1] << " " << BiNormal[2] << endl;
out << BiTangent[0] << " " << BiTangent[1] << " " << BiTangent[2] << endl;
out << Uv[0] << " " << Uv[1] << endl;
out << BoneIndices[0] << " " << BoneIndices[1] << " " << BoneIndices[2] << " " << BoneIndices[3] << endl;
out << BoneWeights[0] << " " << BoneWeights[1] << " " << BoneWeights[2] << " " << BoneWeights[3] << endl;
}
bool operator==(const VertexLayout& right)
{
return
this->Pos[0] == right.Pos[0] && this->Pos[1] == right.Pos[1] && this->Pos[2] == right.Pos[2] &&
this->Normal[0] == right.Normal[0] && this->Normal[1] == right.Normal[1] && this->Normal[2] == right.Normal[2] &&
this->BiNormal[0] == right.BiNormal[0] && this->BiNormal[1] == right.BiNormal[1] && this->BiNormal[2] == right.BiNormal[2] &&
this->BiTangent[0] == right.BiTangent[0] && this->BiTangent[1] == right.BiTangent[1] && this->BiTangent[2] == right.BiTangent[2] &&
this->Uv[0] == right.Uv[0] && this->Uv[1] == right.Uv[1] &&
this->BoneIndices[0] == right.BoneIndices[0] && this->BoneIndices[1] == right.BoneIndices[1] && this->BoneIndices[2] == right.BoneIndices[2] && this->BoneIndices[3] == right.BoneIndices[3] &&
this->BoneWeights[0] == right.BoneWeights[0] && this->BoneWeights[1] == right.BoneWeights[1] && this->BoneWeights[2] == right.BoneWeights[2] && this->BoneWeights[3] == right.BoneWeights[3]
;
}
};
class Mesh : public OutputData {
public:
int NumVertices;
int NumIndices;
std::vector<VertexLayout> Vertices;
std::vector<int> Indices;
virtual void WriteBinary(std::ostream& out)
{
out.write((char*)&NumVertices, sizeof(int));
out.write((char*)&NumIndices, sizeof(int));
for (auto aVertex : Vertices) {
aVertex.WriteBinary(out);
}
for (auto aIndex : Indices) {
out.write((char*)&aIndex, sizeof(int));
}
}
virtual void WriteASCII(std::ostream& out) const
{
out << "New Mesh _ not in binary" << endl;
out << "Number of vertices: " << NumVertices << endl;
out << "number of indices: " << NumIndices << endl;
int vertexNumber = 0;
for (auto aVertex : Vertices) {
out << "New vertex number: " << vertexNumber << "_ not in binary" << endl;
aVertex.WriteASCII(out);
vertexNumber++;
}
for (int i = 0; i < NumIndices; i += 3) {
out << Indices[i] << " " << Indices[i+1] << " " << Indices[i + 2] << endl;
}
}
};
class MeshClass
{
public:
MeshClass();
Mesh GetMeshData(MObject Object);
~MeshClass();
private:
struct WeightInfo {
float BoneIndices[4] = { 0 };
float BoneWeights[4] = { 0 };
};
std::map<int, WeightInfo> GetWeightData();
};
#endif
@@ -0,0 +1,23 @@
#ifndef OutputData_OutputData_h__
#define OutputData_OutputData_h__
#include <fstream>
//template <typename T>
class OutputData
{
public://std::ostream& out, const OutputData& obj
//OutputData(T& object)
// : m_Object(object)
//{};
friend std::ostream& operator<<(std::ostream& out, const OutputData& obj)
{
obj.WriteASCII(out);
return out;
};
virtual void WriteBinary(std::ostream& out) = 0;
virtual void WriteASCII(std::ostream& out) const = 0;
//T& m_Object = nullptr;
};
#endif
@@ -0,0 +1,251 @@
#include "Skeleton.h"
//std::vector<SkeletonNode> Skeleton::DoIt()
//{
// std::vector<SkeletonNode> m_AllSkeletons;
//
// MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint);
// SkeletonNode SkeletonStorage;
//
// while (!jointIt.isDone()) {
// MFnTransform TransformNode(jointIt.currentItem());
// Joint NewJoint;
//
// if (MFnDependencyNode(TransformNode.parent(0)).name() == "world") {
// if (SkeletonStorage.Joints.size() != 0) {
// m_AllSkeletons.push_back(SkeletonStorage);
//
// SkeletonStorage.Joints.clear();
// SkeletonStorage.Name.clear();
// }
//
// SkeletonStorage.Name = TransformNode.name().asChar();
//
// //NewJoint.ParentIndex = -1; // This joint is root
// }
//
// //NewJoint.Name = TransformNode.name().asChar();
//
// MMatrix Matrix = TransformNode.transformationMatrix();
//
// //double tmp[3];
// //((MTransformationMatrix)Matrix).eulerRotation().asVector().get(tmp);
// //NewJoint.Rotation[0] = tmp[0];
// //NewJoint.Rotation[1] = tmp[1];
// //NewJoint.Rotation[2] = tmp[2];
// //((MTransformationMatrix)Matrix).getScale(tmp, MSpace::Space::kTransform);
// //NewJoint.Scale[0] = tmp[0];
// //NewJoint.Scale[1] = tmp[1];
// //NewJoint.Scale[2] = tmp[2];
// //((MTransformationMatrix)Matrix).getTranslation(MSpace::Space::kTransform).get(tmp);
// //NewJoint.Translation[0] = tmp[0];
// //NewJoint.Translation[1] = tmp[1];
// //NewJoint.Translation[2] = tmp[2];
//
// for (int i = 0; i < 4; i++) {
// for (int j = 0; j < 4; j++) {
// NewJoint.OffsetMatrix[i][j] = Matrix.matrix[i][j];
// }
// }
//
// SkeletonStorage.Joints.push_back(NewJoint);
//
// jointIt.next();
// }
//
// m_AllSkeletons.push_back(SkeletonStorage);
//
// return m_AllSkeletons;
//}
std::string attr[9] = { "scaleX", "scaleY", "scaleZ", "translateX", "translateY", "translateZ", "rotateX", "rotateY", "rotateZ" };
Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int endFrame)
{
std::vector<MObject> animatedJoints;
std::vector<MObject> m_Hierarchy;
Animation returnData;
double oneDivSixty = 1 / 60.0;
returnData.Name = animationName;
returnData.Duration = (endFrame - startFrame) * oneDivSixty;
MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint);
while (!jointIt.isDone())
{
m_Hierarchy.push_back(jointIt.item());
MFnDependencyNode depNode(jointIt.item());
for (int i = 0; i < 9; i++)
{
MStatus tmp;
MPlug plug = depNode.findPlug(attr[i].c_str(), &tmp);
MPlugArray connections;
plug.connectedTo(connections, true, false, 0);
for (int j = 0; j != connections.length(); j++) {
MObject connected = connections[j].node();
if (connected.hasFn(MFn::kAnimCurve)) {
MFnAnimCurve jointAnim(connected);
unsigned int startKeyFrameIndex = jointAnim.findClosest(MTime(startFrame, MTime::kNTSCField), &tmp);
if (tmp == MStatus::kFailure)
MGlobal::displayInfo(MString() + "Fail :c");
if (startFrame * oneDivSixty <= jointAnim.time(startKeyFrameIndex).value() && jointAnim.time(startKeyFrameIndex).value() <= endFrame * oneDivSixty) {
animatedJoints.push_back(jointIt.item());
i = 9;
break;
}
unsigned int endKeyFrameIndex = jointAnim.findClosest(MTime(endFrame, MTime::kNTSCField));
MGlobal::displayInfo(MString() + startKeyFrameIndex + " " + endKeyFrameIndex);
if (startFrame * oneDivSixty <= jointAnim.time(endKeyFrameIndex).value() && jointAnim.time(endKeyFrameIndex).value() <= endFrame * oneDivSixty || endKeyFrameIndex - startKeyFrameIndex > 0) {
animatedJoints.push_back(jointIt.item());
i = 9;
break;
}
MFnTransform MayaJoint(jointIt.item());
MPlug BindPose = MayaJoint.findPlug("bindPose");
MDataHandle DataHandle;
BindPose.getValue(DataHandle);
MFnMatrixData MartixFn(DataHandle.data());
MMatrix BindPoseMatrix = MartixFn.matrix();
if (BindPoseMatrix != MayaJoint.transformationMatrix())
{
MGlobal::displayError(MString() + animationName.c_str() + " is using " + MayaJoint.name() + " that is not in bind pose nor is it key framed in the animation, the exported animation will NOT correspond to the animation in Maya");
}
}
}
}
jointIt.next();
}
int currentFrame = startFrame;
while (currentFrame != endFrame) {
Animation::Keyframe thisKeyFrame;
thisKeyFrame.Index = currentFrame - startFrame;
thisKeyFrame.Time = thisKeyFrame.Index * oneDivSixty;
MAnimControl::setCurrentTime(MTime(currentFrame, MTime::kNTSCField));
MTime time = MAnimControl::currentTime();
for (auto aJoint : animatedJoints){
MFnTransform thisJoint(aJoint);
Animation::Keyframe::JointProperty joint;
auto it = std::find(m_Hierarchy.begin(), m_Hierarchy.end(), thisJoint.object());
if (it != m_Hierarchy.end()) {
joint.ID = it - m_Hierarchy.begin();
}
else {
MGlobal::displayError(MString() + "Could not find joint ID for: " + thisJoint.name());
}
MMatrix Matrix = thisJoint.transformationMatrix();
double tmp[4];
thisJoint.getRotationQuaternion(tmp[0], tmp[1], tmp[2], tmp[3]);
joint.Rotation[0] = tmp[0];
joint.Rotation[1] = tmp[1];
joint.Rotation[2] = tmp[2];
joint.Rotation[3] = tmp[3];
thisJoint.getTranslation(MSpace::kPreTransform).get(tmp);
joint.Position[0] = tmp[0];
joint.Position[1] = tmp[1];
joint.Position[2] = tmp[2];
thisJoint.getScale(tmp);
joint.Scale[0] = tmp[0];
joint.Scale[1] = tmp[1];
joint.Scale[2] = tmp[2];
thisKeyFrame.JointProperties.push_back(joint);
}
returnData.Keyframes.push_back(thisKeyFrame);
currentFrame++;
}
returnData.NumKeyFrames = returnData.Keyframes.size();
returnData.NumberOfJoints = animatedJoints.size();
return returnData;
}
std::vector<BindPoseSkeletonNode> Skeleton::GetBindPoses()
{
std::vector<BindPoseSkeletonNode> m_AllSkeletons;
std::vector<MObject> m_Hierarchy;
MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint);
BindPoseSkeletonNode SkeletonStorage;
while (!jointIt.isDone()) {
MFnTransform MayaJoint(jointIt.currentItem());
BindPoseSkeletonNode::BindPoseJoint NewJoint;
if (MFnDependencyNode(MayaJoint.parent(0)).name() == "world") {
if (SkeletonStorage.Joints.size() != 0) {
m_AllSkeletons.push_back(SkeletonStorage);
SkeletonStorage.Joints.clear();
SkeletonStorage.Name.clear();
}
SkeletonStorage.Name = std::string(MayaJoint.name().asChar());
NewJoint.ParentID = -1; // This joint is root
}
else {
auto it = std::find(m_Hierarchy.begin(), m_Hierarchy.end(), MayaJoint.parent(0));
if (it != m_Hierarchy.end()) {
NewJoint.ParentID = it - m_Hierarchy.begin();
}
else {
MGlobal::displayError(MString() + "Could not find joint parent for: " + MayaJoint.name());
}
}
m_Hierarchy.push_back(MayaJoint.object());
MPlug BindPose = MayaJoint.findPlug("bindPose");
MDataHandle DataHandle;
BindPose.getValue(DataHandle);
MFnMatrixData MartixFn(DataHandle.data());
MMatrix Matrix = MartixFn.matrix();
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
NewJoint.OffsetMatrix[i][j] = Matrix.matrix[i][j];
}
}
NewJoint.Name = MayaJoint.name().asChar();
//double tmp[3];
//((MTransformationMatrix)Matrix).eulerRotation().asVector().get(tmp);
//NewJoint.Rotation[0] = tmp[0];
//NewJoint.Rotation[1] = tmp[1];
//NewJoint.Rotation[2] = tmp[2];
//((MTransformationMatrix)Matrix).getScale(tmp, MSpace::Space::kTransform);
//NewJoint.Scale[0] = tmp[0];
//NewJoint.Scale[1] = tmp[1];
//NewJoint.Scale[2] = tmp[2];
//((MTransformationMatrix)Matrix).getTranslation(MSpace::Space::kTransform).get(tmp);
//NewJoint.Translation[0] = tmp[0];
//NewJoint.Translation[1] = tmp[1];
//NewJoint.Translation[2] = tmp[2];
SkeletonStorage.Joints.push_back(NewJoint);
jointIt.next();
}
m_AllSkeletons.push_back(SkeletonStorage);
return m_AllSkeletons;
}
+119
View File
@@ -0,0 +1,119 @@
#ifndef Skeleton_Skeleton_h__
#define Skeleton_Skeleton_h__
#include <vector>
#include <array>
#include <algorithm>
#include "MayaIncludes.h"
#include "OutputData.h"
class Animation : public OutputData {
public:
struct Keyframe
{
struct JointProperty
{
int ID;
float Position[3];
float Rotation[4];
float Scale[3];
};
int Index;
double Time;
std::vector<JointProperty> JointProperties;
};
std::string Name;
double Duration;
int NumKeyFrames;
int NumberOfJoints;
std::vector<Keyframe> Keyframes;
virtual void WriteBinary(std::ostream& out)
{
out.write(Name.c_str(), Name.size() + 1);
out.write((char*)&Duration, sizeof(double));
out.write((char*)&NumKeyFrames, sizeof(int));
out.write((char*)&NumberOfJoints, sizeof(int));
for (auto aKeyframe : Keyframes) {
out.write((char*)&aKeyframe.Index, sizeof(int));
out.write((char*)&aKeyframe.Time, sizeof(double));
for (auto aJoint : aKeyframe.JointProperties) {
out.write((char*)&aJoint.ID, sizeof(int));
out.write((char*)aJoint.Position, sizeof(float) * 3);
out.write((char*)aJoint.Rotation, sizeof(float) * 4);
out.write((char*)aJoint.Scale, sizeof(float) * 3);
}
}
}
virtual void WriteASCII(std::ostream& out) const
{
out << "Animation Name: " << Name << endl;
out << "Duration: " << Duration << endl;
out << "Number of KeyFrames: " << NumKeyFrames << endl;
out << "Number of Joints: " << NumberOfJoints << endl;
for (auto aKeyframe : Keyframes) {
out << "Frame: " << aKeyframe.Index << endl;
out << "Time: " << aKeyframe.Time << endl;
for (auto aJoint : aKeyframe.JointProperties) {
out << "Joint ID: " << aJoint.ID << endl;
out << aJoint.Position[0] << " " << aJoint.Position[1] << " " << aJoint.Position[2] << endl;
out << aJoint.Rotation[0] << " " << aJoint.Rotation[1] << " " << aJoint.Rotation[2] << " " << aJoint.Rotation[3] << endl;
out << aJoint.Scale[0] << " " << aJoint.Scale[1] << " " << aJoint.Scale[2] << endl;
}
}
}
};
class BindPoseSkeletonNode : public OutputData {
public:
struct BindPoseJoint
{
int ParentID;
std::string Name;
float OffsetMatrix[4][4];
};
std::string Name;
std::vector<BindPoseJoint> Joints;
virtual void WriteBinary(std::ostream& out)
{
out.write(Name.c_str(), Name.size() + 1);
for (auto Joint:Joints)
{
out.write(Joint.Name.c_str(), Joint.Name.size() + 1);
out.write((char*)&Joint.OffsetMatrix, sizeof(float) * 4 * 4);
out.write((char*)&Joint.ParentID, sizeof(int));
}
}
virtual void WriteASCII(std::ostream& out) const
{
out << "Bind Pose: " << Name << endl;
for (auto Joint : Joints)
{
out << Joint.Name << endl;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++){
out << Joint.OffsetMatrix[i][j] << " ";
}
out << endl;
}
out << Joint.ParentID << endl;
}
};
};
class Skeleton {
public:
//std::vector<SkeletonNode> DoIt();
Animation GetAnimData(std::string animationName, int startFrame, int endFrame);
std::vector<BindPoseSkeletonNode> GetBindPoses();
private:
};
#endif //Skeleton_Skeleton_h__
@@ -0,0 +1,38 @@
#include "WriteToFile.h"
WriteToFile::~WriteToFile()
{
CloseFiles();
}
bool WriteToFile::binaryFilePath(string filePathAndFileName)
{
binFileName = filePathAndFileName;
ofstream binFile(filePathAndFileName, ofstream::binary);
if (!binFile)
return false;
return true;
}
bool WriteToFile::ASCIIFilePath(string filePathAndFileName)
{
ASCIIFileName = filePathAndFileName;
ofstream ASCIIFile(filePathAndFileName);
if (!ASCIIFile)
return false;
return true;
}
void WriteToFile::OpenFiles()
{
if (binFile)
binFile.open(binFileName, ofstream::binary);
if (ASCIIFile)
ASCIIFile.open(ASCIIFileName);
}
void WriteToFile::CloseFiles()
{
binFile.close();
ASCIIFile.close();
}
@@ -0,0 +1,63 @@
#ifndef WriteToFile_WriteToFile_h__
#define WriteToFile_WriteToFile_h__
#include "MayaIncludes.h"
#include "OutputData.h"
#include <fstream>
#include <string>
using namespace std;
class WriteToFile
{
public:
~WriteToFile();
bool binaryFilePath(string filePathAndFileName);
bool ASCIIFilePath(string filePathAndFileName);
void writeToFiles(OutputData* toWrite, unsigned int numOfElementToWrite = 1, unsigned int startIndex = 0)
{
MGlobal::displayInfo("WriteToFile::writeToFiles(OutputData*)");
if (ASCIIFile.is_open())
{
for (unsigned int i = startIndex; i < numOfElementToWrite + startIndex; i++)
ASCIIFile << toWrite[i] << endl;
}
if (binFile.is_open())
{
for (unsigned int i = startIndex; i < numOfElementToWrite + startIndex; i++)
toWrite[i].WriteBinary(binFile);
}
}
template <typename T>
void writeToFiles(T* toWrite, unsigned int numOfElementToWrite = 1, unsigned int startIndex = 0)
{
MGlobal::displayInfo("WriteToFile::writeToFiles(T*) - Template T");
if (ASCIIFile.is_open()) {
for (unsigned int i = startIndex; i < numOfElementToWrite + startIndex; i++)
ASCIIFile << toWrite[i] << endl;
}
if (binFile.is_open()) {
for (unsigned int i = startIndex; i < numOfElementToWrite + startIndex; i++)
binFile.write((char*)toWrite, sizeof(T));
}
}
void OpenFiles();
void CloseFiles();
private:
string binFileName;
string ASCIIFileName;
ofstream binFile;
ofstream ASCIIFile;
};
#endif