Auto format C++ source

This commit is contained in:
2022-08-08 01:07:26 -07:00
parent c5a640e22d
commit 7433d54c16
155 changed files with 17259 additions and 16879 deletions

View File

@@ -42,7 +42,7 @@ void KRAmbientZone::InitNodeInfo(KrNodeInfo* nodeInfo)
nodeInfo->ambient_zone.sample = -1;
}
KRAmbientZone::KRAmbientZone(KRScene &scene, std::string name) : KRNode(scene, name)
KRAmbientZone::KRAmbientZone(KRScene& scene, std::string name) : KRNode(scene, name)
{
m_ambient = "";
m_ambient_gain = 1.0f;
@@ -52,16 +52,16 @@ KRAmbientZone::KRAmbientZone(KRScene &scene, std::string name) : KRNode(scene, n
}
KRAmbientZone::~KRAmbientZone()
{
}
{}
std::string KRAmbientZone::getElementName() {
std::string KRAmbientZone::getElementName()
{
return "ambient_zone";
}
tinyxml2::XMLElement *KRAmbientZone::saveXML( tinyxml2::XMLNode *parent)
tinyxml2::XMLElement* KRAmbientZone::saveXML(tinyxml2::XMLNode* parent)
{
tinyxml2::XMLElement *e = KRNode::saveXML(parent);
tinyxml2::XMLElement* e = KRNode::saveXML(parent);
e->SetAttribute("zone", m_zone.c_str());
e->SetAttribute("sample", m_ambient.c_str());
e->SetAttribute("gain", m_ambient_gain);
@@ -69,21 +69,21 @@ tinyxml2::XMLElement *KRAmbientZone::saveXML( tinyxml2::XMLNode *parent)
return e;
}
void KRAmbientZone::loadXML(tinyxml2::XMLElement *e)
void KRAmbientZone::loadXML(tinyxml2::XMLElement* e)
{
KRNode::loadXML(e);
m_zone = e->Attribute("zone");
m_gradient_distance = 0.25f;
if(e->QueryFloatAttribute("gradient", &m_gradient_distance) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("gradient", &m_gradient_distance) != tinyxml2::XML_SUCCESS) {
m_gradient_distance = 0.25f;
}
m_ambient = e->Attribute("sample");
m_ambient_gain = 1.0f;
if(e->QueryFloatAttribute("gain", &m_ambient_gain) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("gain", &m_ambient_gain) != tinyxml2::XML_SUCCESS) {
m_ambient_gain = 1.0f;
}
}
@@ -93,7 +93,7 @@ std::string KRAmbientZone::getAmbient()
return m_ambient;
}
void KRAmbientZone::setAmbient(const std::string &ambient)
void KRAmbientZone::setAmbient(const std::string& ambient)
{
m_ambient = ambient;
}
@@ -113,20 +113,20 @@ std::string KRAmbientZone::getZone()
return m_zone;
}
void KRAmbientZone::setZone(const std::string &zone)
void KRAmbientZone::setZone(const std::string& zone)
{
m_zone = zone;
}
void KRAmbientZone::render(RenderInfo& ri)
{
if(m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
if (m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
KRNode::render(ri);
bool bVisualize = ri.camera->settings.debug_display == KRRenderSettings::KRENGINE_DEBUG_DISPLAY_SIREN_AMBIENT_ZONES;
if(ri.renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT && bVisualize) {
if (ri.renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT && bVisualize) {
KRMesh* sphereModel = getContext().getMeshManager()->getMaxLODModel("__sphere");
if (sphereModel) {
@@ -144,7 +144,7 @@ void KRAmbientZone::render(RenderInfo& ri)
info.modelFormat = sphereModel->getModelFormat();
info.vertexAttributes = sphereModel->getVertexAttributes();
KRPipeline *pPipeline = getContext().getPipelineManager()->getPipeline(*ri.surface, info);
KRPipeline* pPipeline = getContext().getPipelineManager()->getPipeline(*ri.surface, info);
pPipeline->bind(ri.commandBuffer, *ri.camera, ri.viewport, sphereModelMatrix, &ri.point_lights, &ri.directional_lights, &ri.spot_lights, ri.renderPass);
sphereModel->renderNoMaterials(ri.commandBuffer, ri.renderPass, getName(), "visualize_overlay", 1.0f);
@@ -163,22 +163,23 @@ void KRAmbientZone::setGradientDistance(float gradient_distance)
m_gradient_distance = gradient_distance;
}
AABB KRAmbientZone::getBounds() {
AABB KRAmbientZone::getBounds()
{
// Ambient zones always have a -1, -1, -1 to 1, 1, 1 bounding box
return AABB::Create(-Vector3::One(), Vector3::One(), getModelMatrix());
}
float KRAmbientZone::getContainment(const Vector3 &pos)
float KRAmbientZone::getContainment(const Vector3& pos)
{
AABB bounds = getBounds();
if(bounds.contains(pos)) {
if (bounds.contains(pos)) {
Vector3 size = bounds.size();
Vector3 diff = pos - bounds.center();
diff = diff * 2.0f;
diff = Vector3::Create(diff.x / size.x, diff.y / size.y, diff.z / size.z);
float d = diff.magnitude();
if(m_gradient_distance <= 0.0f) {
if (m_gradient_distance <= 0.0f) {
// Avoid division by zero
d = d > 1.0f ? 0.0f : 1.0f;
} else {

View File

@@ -35,33 +35,34 @@
#include "KRNode.h"
#include "KRTexture.h"
class KRAmbientZone : public KRNode {
class KRAmbientZone : public KRNode
{
public:
static void InitNodeInfo(KrNodeInfo* nodeInfo);
KRAmbientZone(KRScene &scene, std::string name);
KRAmbientZone(KRScene& scene, std::string name);
virtual ~KRAmbientZone();
virtual std::string getElementName();
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual void loadXML(tinyxml2::XMLElement *e);
virtual tinyxml2::XMLElement* saveXML(tinyxml2::XMLNode* parent);
virtual void loadXML(tinyxml2::XMLElement* e);
void render(RenderInfo& ri);
std::string getZone();
void setZone(const std::string &zone);
void setZone(const std::string& zone);
float getGradientDistance();
void setGradientDistance(float gradient_distance);
std::string getAmbient();
void setAmbient(const std::string &ambient);
void setAmbient(const std::string& ambient);
float getAmbientGain();
void setAmbientGain(float ambient_gain);
virtual AABB getBounds();
float getContainment(const Vector3 &pos);
float getContainment(const Vector3& pos);
private:
std::string m_zone;

View File

@@ -35,7 +35,7 @@
#include "KRAnimationCurve.h"
#include "KREngine-common.h"
KRAnimation::KRAnimation(KRContext &context, std::string name) : KRResource(context, name)
KRAnimation::KRAnimation(KRContext& context, std::string name) : KRResource(context, name)
{
m_auto_play = false;
m_loop = false;
@@ -46,122 +46,124 @@ KRAnimation::KRAnimation(KRContext &context, std::string name) : KRResource(cont
}
KRAnimation::~KRAnimation()
{
for(unordered_map<std::string, KRAnimationLayer *>::iterator itr = m_layers.begin(); itr != m_layers.end(); ++itr){
for (unordered_map<std::string, KRAnimationLayer*>::iterator itr = m_layers.begin(); itr != m_layers.end(); ++itr) {
delete (*itr).second;
}
}
std::string KRAnimation::getExtension() {
std::string KRAnimation::getExtension()
{
return "kranimation";
}
void KRAnimation::addLayer(KRAnimationLayer *layer)
void KRAnimation::addLayer(KRAnimationLayer* layer)
{
m_layers[layer->getName()] = layer;
}
bool KRAnimation::save(KRDataBlock &data) {
bool KRAnimation::save(KRDataBlock& data)
{
tinyxml2::XMLDocument doc;
tinyxml2::XMLElement *animation_node = doc.NewElement( "animation" );
tinyxml2::XMLElement* animation_node = doc.NewElement("animation");
doc.InsertEndChild(animation_node);
animation_node->SetAttribute("loop", m_loop ? "true" : "false");
animation_node->SetAttribute("auto_play", m_auto_play ? "true" : "false");
animation_node->SetAttribute("duration", m_duration);
animation_node->SetAttribute("start_time", m_start_time);
for(unordered_map<std::string, KRAnimationLayer *>::iterator itr = m_layers.begin(); itr != m_layers.end(); ++itr){
for (unordered_map<std::string, KRAnimationLayer*>::iterator itr = m_layers.begin(); itr != m_layers.end(); ++itr) {
(*itr).second->saveXML(animation_node);
}
tinyxml2::XMLPrinter p;
doc.Print(&p);
data.append((void *)p.CStr(), strlen(p.CStr())+1);
data.append((void*)p.CStr(), strlen(p.CStr()) + 1);
return true;
}
KRAnimation *KRAnimation::Load(KRContext &context, const std::string &name, KRDataBlock *data)
KRAnimation* KRAnimation::Load(KRContext& context, const std::string& name, KRDataBlock* data)
{
std::string xml_string = data->getString();
tinyxml2::XMLDocument doc;
doc.Parse(xml_string.c_str());
KRAnimation *new_animation = new KRAnimation(context, name);
KRAnimation* new_animation = new KRAnimation(context, name);
tinyxml2::XMLElement *animation_node = doc.RootElement();
tinyxml2::XMLElement* animation_node = doc.RootElement();
if(animation_node->QueryFloatAttribute("duration", &new_animation->m_duration) != tinyxml2::XML_SUCCESS) {
if (animation_node->QueryFloatAttribute("duration", &new_animation->m_duration) != tinyxml2::XML_SUCCESS) {
new_animation->m_duration = 0.0f; // Default value
}
if(animation_node->QueryFloatAttribute("start_time", &new_animation->m_start_time) != tinyxml2::XML_SUCCESS) {
if (animation_node->QueryFloatAttribute("start_time", &new_animation->m_start_time) != tinyxml2::XML_SUCCESS) {
new_animation->m_start_time = 0.0f; // Default value
}
if(animation_node->QueryBoolAttribute("loop", &new_animation->m_loop) != tinyxml2::XML_SUCCESS) {
if (animation_node->QueryBoolAttribute("loop", &new_animation->m_loop) != tinyxml2::XML_SUCCESS) {
new_animation->m_loop = false; // Default value
}
if(animation_node->QueryBoolAttribute("auto_play", &new_animation->m_auto_play) != tinyxml2::XML_SUCCESS) {
if (animation_node->QueryBoolAttribute("auto_play", &new_animation->m_auto_play) != tinyxml2::XML_SUCCESS) {
new_animation->m_auto_play = false; // Default value
}
for(tinyxml2::XMLElement *child_element=animation_node->FirstChildElement(); child_element != NULL; child_element = child_element->NextSiblingElement()) {
if(strcmp(child_element->Name(), "layer") == 0) {
KRAnimationLayer *new_layer = new KRAnimationLayer(context);
for (tinyxml2::XMLElement* child_element = animation_node->FirstChildElement(); child_element != NULL; child_element = child_element->NextSiblingElement()) {
if (strcmp(child_element->Name(), "layer") == 0) {
KRAnimationLayer* new_layer = new KRAnimationLayer(context);
new_layer->loadXML(child_element);
new_animation->m_layers[new_layer->getName()] = new_layer;
}
}
if(new_animation->m_auto_play) {
if (new_animation->m_auto_play) {
new_animation->m_playing = true;
}
// KRNode *n = KRNode::LoadXML(*new_scene, scene_element->FirstChildElement());
// KRNode *n = KRNode::LoadXML(*new_scene, scene_element->FirstChildElement());
delete data;
return new_animation;
}
unordered_map<std::string, KRAnimationLayer *> &KRAnimation::getLayers()
unordered_map<std::string, KRAnimationLayer*>& KRAnimation::getLayers()
{
return m_layers;
}
KRAnimationLayer *KRAnimation::getLayer(const char *szName)
KRAnimationLayer* KRAnimation::getLayer(const char* szName)
{
return m_layers[szName];
}
void KRAnimation::update(float deltaTime)
{
if(m_playing) {
if (m_playing) {
m_local_time += deltaTime;
}
if(m_loop) {
while(m_local_time > m_duration) {
if (m_loop) {
while (m_local_time > m_duration) {
m_local_time -= m_duration;
}
} else if(m_local_time > m_duration) {
} else if (m_local_time > m_duration) {
m_local_time = m_duration;
m_playing = false;
getContext().getAnimationManager()->updateActiveAnimations(this);
}
for(unordered_map<std::string, KRAnimationLayer *>::iterator layer_itr = m_layers.begin(); layer_itr != m_layers.end(); layer_itr++) {
KRAnimationLayer *layer = (*layer_itr).second;
for(std::vector<KRAnimationAttribute *>::iterator attribute_itr = layer->getAttributes().begin(); attribute_itr != layer->getAttributes().end(); attribute_itr++) {
KRAnimationAttribute *attribute = *attribute_itr;
for (unordered_map<std::string, KRAnimationLayer*>::iterator layer_itr = m_layers.begin(); layer_itr != m_layers.end(); layer_itr++) {
KRAnimationLayer* layer = (*layer_itr).second;
for (std::vector<KRAnimationAttribute*>::iterator attribute_itr = layer->getAttributes().begin(); attribute_itr != layer->getAttributes().end(); attribute_itr++) {
KRAnimationAttribute* attribute = *attribute_itr;
// TODO - Currently only a single layer supported per animation -- need to either implement combining of multiple layers or ask the FBX sdk to bake all layers into one
KRAnimationCurve *curve = attribute->getCurve();
KRNode *target = attribute->getTarget();
KRAnimationCurve* curve = attribute->getCurve();
KRNode* target = attribute->getTarget();
KRNode::node_attribute_type attribute_type = attribute->getTargetAttribute();
if(curve != NULL && target != NULL) {
if (curve != NULL && target != NULL) {
target->SetAttribute(attribute_type, curve->getValue(m_local_time + m_start_time));
}
}
@@ -236,24 +238,24 @@ void KRAnimation::setLooping(bool looping)
KRAnimation *KRAnimation::split(const std::string &name, float start_time, float duration, bool strip_unchanging_attributes, bool clone_curves)
KRAnimation* KRAnimation::split(const std::string& name, float start_time, float duration, bool strip_unchanging_attributes, bool clone_curves)
{
KRAnimation *new_animation = new KRAnimation(getContext(), name);
KRAnimation* new_animation = new KRAnimation(getContext(), name);
new_animation->setStartTime(start_time);
new_animation->setDuration(duration);
new_animation->m_loop = m_loop;
new_animation->m_auto_play = m_auto_play;
int new_curve_count = 0;
for(unordered_map<std::string, KRAnimationLayer *>::iterator layer_itr = m_layers.begin(); layer_itr != m_layers.end(); layer_itr++) {
KRAnimationLayer *layer = (*layer_itr).second;
KRAnimationLayer *new_layer = new KRAnimationLayer(getContext());
for (unordered_map<std::string, KRAnimationLayer*>::iterator layer_itr = m_layers.begin(); layer_itr != m_layers.end(); layer_itr++) {
KRAnimationLayer* layer = (*layer_itr).second;
KRAnimationLayer* new_layer = new KRAnimationLayer(getContext());
new_layer->setName(layer->getName());
new_layer->setRotationAccumulationMode(layer->getRotationAccumulationMode());
new_layer->setScaleAccumulationMode(layer->getScaleAccumulationMode());
new_layer->setWeight(layer->getWeight());
new_animation->m_layers[new_layer->getName()] = new_layer;
for(std::vector<KRAnimationAttribute *>::iterator attribute_itr = layer->getAttributes().begin(); attribute_itr != layer->getAttributes().end(); attribute_itr++) {
KRAnimationAttribute *attribute = *attribute_itr;
for (std::vector<KRAnimationAttribute*>::iterator attribute_itr = layer->getAttributes().begin(); attribute_itr != layer->getAttributes().end(); attribute_itr++) {
KRAnimationAttribute* attribute = *attribute_itr;
// Updated Dec 9, 2013 by Peter to change the way that attributes are stripped.
//
@@ -268,27 +270,27 @@ KRAnimation *KRAnimation::split(const std::string &name, float start_time, float
if (targetAttribute > 0) { // we have a valid target that fits within a group of 3
targetAttribute--; // this is now group relative 0,1,2 is the first group .. 3,4,5 is the second group, etc.
KRAnimationCurve *curve = attribute->getCurve(); // this is the curve we are currently handling
KRAnimationCurve* curve = attribute->getCurve(); // this is the curve we are currently handling
int placeInGroup = targetAttribute % 3; // this will be 0, 1 or 2
static long placeLookup[] = { 1, 2, -1, 1, -2, -1 };
KRAnimationAttribute *attribute2 = *(attribute_itr + placeLookup[placeInGroup*2]);
KRAnimationAttribute *attribute3 = *(attribute_itr + placeLookup[placeInGroup*2+1]);
KRAnimationCurve *curve2 = attribute2->getCurve();
KRAnimationCurve *curve3 = attribute3->getCurve();
KRAnimationAttribute* attribute2 = *(attribute_itr + placeLookup[placeInGroup * 2]);
KRAnimationAttribute* attribute3 = *(attribute_itr + placeLookup[placeInGroup * 2 + 1]);
KRAnimationCurve* curve2 = attribute2->getCurve();
KRAnimationCurve* curve3 = attribute3->getCurve();
bool include_attribute = true;
if(strip_unchanging_attributes) {
if (strip_unchanging_attributes) {
include_attribute = curve->valueChanges(start_time, duration) |
curve2->valueChanges(start_time, duration) |
curve3->valueChanges(start_time, duration);
}
if(include_attribute) {
KRAnimationAttribute *new_attribute = new KRAnimationAttribute(getContext());
KRAnimationCurve *new_curve = curve;
if(clone_curves) {
if (include_attribute) {
KRAnimationAttribute* new_attribute = new KRAnimationAttribute(getContext());
KRAnimationCurve* new_curve = curve;
if (clone_curves) {
std::string new_curve_name = name + "_curve" + std::to_string(++new_curve_count);
new_curve = curve->split(new_curve_name, start_time, duration);
}
@@ -308,10 +310,10 @@ KRAnimation *KRAnimation::split(const std::string &name, float start_time, float
void KRAnimation::deleteCurves()
{
for(unordered_map<std::string, KRAnimationLayer *>::iterator layer_itr = m_layers.begin(); layer_itr != m_layers.end(); layer_itr++) {
KRAnimationLayer *layer = (*layer_itr).second;
for(std::vector<KRAnimationAttribute *>::iterator attribute_itr = layer->getAttributes().begin(); attribute_itr != layer->getAttributes().end(); attribute_itr++) {
KRAnimationAttribute *attribute = *attribute_itr;
for (unordered_map<std::string, KRAnimationLayer*>::iterator layer_itr = m_layers.begin(); layer_itr != m_layers.end(); layer_itr++) {
KRAnimationLayer* layer = (*layer_itr).second;
for (std::vector<KRAnimationAttribute*>::iterator attribute_itr = layer->getAttributes().begin(); attribute_itr != layer->getAttributes().end(); attribute_itr++) {
KRAnimationAttribute* attribute = *attribute_itr;
attribute->deleteCurve();
}
}
@@ -319,12 +321,12 @@ void KRAnimation::deleteCurves()
void KRAnimation::_lockData()
{
for(unordered_map<std::string, KRAnimationLayer *>::iterator layer_itr = m_layers.begin(); layer_itr != m_layers.end(); layer_itr++) {
KRAnimationLayer *layer = (*layer_itr).second;
for(std::vector<KRAnimationAttribute *>::iterator attribute_itr = layer->getAttributes().begin(); attribute_itr != layer->getAttributes().end(); attribute_itr++) {
KRAnimationAttribute *attribute = *attribute_itr;
KRAnimationCurve *curve = attribute->getCurve();
if(curve) {
for (unordered_map<std::string, KRAnimationLayer*>::iterator layer_itr = m_layers.begin(); layer_itr != m_layers.end(); layer_itr++) {
KRAnimationLayer* layer = (*layer_itr).second;
for (std::vector<KRAnimationAttribute*>::iterator attribute_itr = layer->getAttributes().begin(); attribute_itr != layer->getAttributes().end(); attribute_itr++) {
KRAnimationAttribute* attribute = *attribute_itr;
KRAnimationCurve* curve = attribute->getCurve();
if (curve) {
curve->_lockData();
}
}
@@ -333,12 +335,12 @@ void KRAnimation::_lockData()
void KRAnimation::_unlockData()
{
for(unordered_map<std::string, KRAnimationLayer *>::iterator layer_itr = m_layers.begin(); layer_itr != m_layers.end(); layer_itr++) {
KRAnimationLayer *layer = (*layer_itr).second;
for(std::vector<KRAnimationAttribute *>::iterator attribute_itr = layer->getAttributes().begin(); attribute_itr != layer->getAttributes().end(); attribute_itr++) {
KRAnimationAttribute *attribute = *attribute_itr;
KRAnimationCurve *curve = attribute->getCurve();
if(curve) {
for (unordered_map<std::string, KRAnimationLayer*>::iterator layer_itr = m_layers.begin(); layer_itr != m_layers.end(); layer_itr++) {
KRAnimationLayer* layer = (*layer_itr).second;
for (std::vector<KRAnimationAttribute*>::iterator attribute_itr = layer->getAttributes().begin(); attribute_itr != layer->getAttributes().end(); attribute_itr++) {
KRAnimationAttribute* attribute = *attribute_itr;
KRAnimationCurve* curve = attribute->getCurve();
if (curve) {
curve->_unlockData();
}
}

View File

@@ -38,20 +38,21 @@
#include "KRAnimationLayer.h"
class KRAnimation : public KRResource {
class KRAnimation : public KRResource
{
public:
KRAnimation(KRContext &context, std::string name);
KRAnimation(KRContext& context, std::string name);
virtual ~KRAnimation();
virtual std::string getExtension();
virtual bool save(KRDataBlock &data);
virtual bool save(KRDataBlock& data);
static KRAnimation *Load(KRContext &context, const std::string &name, KRDataBlock *data);
static KRAnimation* Load(KRContext& context, const std::string& name, KRDataBlock* data);
void addLayer(KRAnimationLayer *layer);
unordered_map<std::string, KRAnimationLayer *> &getLayers();
KRAnimationLayer *getLayer(const char *szName);
void addLayer(KRAnimationLayer* layer);
unordered_map<std::string, KRAnimationLayer*>& getLayers();
KRAnimationLayer* getLayer(const char* szName);
bool getAutoPlay() const;
void setAutoPlay(bool auto_play);
bool getLooping() const;
@@ -67,14 +68,14 @@ public:
void setStartTime(float start_time);
bool isPlaying();
KRAnimation *split(const std::string &name, float start_time, float duration, bool strip_unchanging_attributes = true, bool clone_curves = true);
KRAnimation* split(const std::string& name, float start_time, float duration, bool strip_unchanging_attributes = true, bool clone_curves = true);
void deleteCurves();
void _lockData();
void _unlockData();
private:
unordered_map<std::string, KRAnimationLayer *> m_layers;
unordered_map<std::string, KRAnimationLayer*> m_layers;
bool m_auto_play;
bool m_loop;
bool m_playing;

View File

@@ -35,7 +35,7 @@
#include "KRAnimationCurveManager.h"
KRAnimationAttribute::KRAnimationAttribute(KRContext &context) : KRContextObject(context)
KRAnimationAttribute::KRAnimationAttribute(KRContext& context) : KRContextObject(context)
{
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_NONE;
m_target = NULL;
@@ -47,15 +47,15 @@ KRAnimationAttribute::~KRAnimationAttribute()
}
tinyxml2::XMLElement *KRAnimationAttribute::saveXML( tinyxml2::XMLNode *parent)
tinyxml2::XMLElement* KRAnimationAttribute::saveXML(tinyxml2::XMLNode* parent)
{
tinyxml2::XMLDocument *doc = parent->GetDocument();
tinyxml2::XMLElement *e = doc->NewElement("attribute");
tinyxml2::XMLDocument* doc = parent->GetDocument();
tinyxml2::XMLElement* e = doc->NewElement("attribute");
parent->InsertEndChild(e);
e->SetAttribute("curve", m_curve_name.c_str());
e->SetAttribute("target", m_target_name.c_str());
const char *szAttribute = "none";
switch(m_node_attribute) {
const char* szAttribute = "none";
switch (m_node_attribute) {
case KRNode::KRENGINE_NODE_ATTRIBUTE_NONE:
szAttribute = "none";
break;
@@ -149,7 +149,7 @@ tinyxml2::XMLElement *KRAnimationAttribute::saveXML( tinyxml2::XMLNode *parent)
return e;
}
void KRAnimationAttribute::loadXML(tinyxml2::XMLElement *e)
void KRAnimationAttribute::loadXML(tinyxml2::XMLElement* e)
{
m_target = NULL;
m_curve = NULL;
@@ -159,62 +159,62 @@ void KRAnimationAttribute::loadXML(tinyxml2::XMLElement *e)
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_NONE;
const char *szAttribute = e->Attribute("attribute");
if(strcmp(szAttribute, "none") == 0) {
const char* szAttribute = e->Attribute("attribute");
if (strcmp(szAttribute, "none") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_NONE;
} else if(strcmp(szAttribute, "translate_x") == 0) {
} else if (strcmp(szAttribute, "translate_x") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_TRANSLATE_X;
} else if(strcmp(szAttribute, "translate_y") == 0) {
} else if (strcmp(szAttribute, "translate_y") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_TRANSLATE_Y;
} else if(strcmp(szAttribute, "translate_z") == 0) {
} else if (strcmp(szAttribute, "translate_z") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_TRANSLATE_Z;
} else if(strcmp(szAttribute, "rotate_x") == 0) {
} else if (strcmp(szAttribute, "rotate_x") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_ROTATE_X;
} else if(strcmp(szAttribute, "rotate_y") == 0) {
} else if (strcmp(szAttribute, "rotate_y") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_ROTATE_Y;
} else if(strcmp(szAttribute, "rotate_z") == 0) {
} else if (strcmp(szAttribute, "rotate_z") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_ROTATE_Z;
} else if(strcmp(szAttribute, "scale_x") == 0) {
} else if (strcmp(szAttribute, "scale_x") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_SCALE_X;
} else if(strcmp(szAttribute, "scale_y") == 0) {
} else if (strcmp(szAttribute, "scale_y") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_SCALE_Y;
} else if(strcmp(szAttribute, "scale_z") == 0) {
} else if (strcmp(szAttribute, "scale_z") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_SCALE_Z;
} else if(strcmp(szAttribute, "pre_rotate_x") == 0) {
} else if (strcmp(szAttribute, "pre_rotate_x") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_PRE_ROTATION_X;
} else if(strcmp(szAttribute, "pre_rotate_y") == 0) {
} else if (strcmp(szAttribute, "pre_rotate_y") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_PRE_ROTATION_Y;
} else if(strcmp(szAttribute, "pre_rotate_z") == 0) {
} else if (strcmp(szAttribute, "pre_rotate_z") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_PRE_ROTATION_Z;
} else if(strcmp(szAttribute, "post_rotate_x") == 0) {
} else if (strcmp(szAttribute, "post_rotate_x") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_POST_ROTATION_X;
} else if(strcmp(szAttribute, "post_rotate_y") == 0) {
} else if (strcmp(szAttribute, "post_rotate_y") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_POST_ROTATION_Y;
} else if(strcmp(szAttribute, "post_rotate_z") == 0) {
} else if (strcmp(szAttribute, "post_rotate_z") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_POST_ROTATION_Z;
} else if(strcmp(szAttribute, "rotate_pivot_x") == 0) {
} else if (strcmp(szAttribute, "rotate_pivot_x") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_ROTATION_PIVOT_X;
} else if(strcmp(szAttribute, "rotate_pivot_y") == 0) {
} else if (strcmp(szAttribute, "rotate_pivot_y") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_ROTATION_PIVOT_Y;
} else if(strcmp(szAttribute, "rotate_pivot_z") == 0) {
} else if (strcmp(szAttribute, "rotate_pivot_z") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_ROTATION_PIVOT_Z;
} else if(strcmp(szAttribute, "scale_pivot_x") == 0) {
} else if (strcmp(szAttribute, "scale_pivot_x") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_SCALE_PIVOT_X;
} else if(strcmp(szAttribute, "scale_pivot_y") == 0) {
} else if (strcmp(szAttribute, "scale_pivot_y") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_SCALE_PIVOT_Y;
} else if(strcmp(szAttribute, "scale_pivot_z") == 0) {
} else if (strcmp(szAttribute, "scale_pivot_z") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_SCALE_PIVOT_Z;
} else if(strcmp(szAttribute, "rotate_offset_x") == 0) {
} else if (strcmp(szAttribute, "rotate_offset_x") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_ROTATE_OFFSET_X;
} else if(strcmp(szAttribute, "rotate_offset_y") == 0) {
} else if (strcmp(szAttribute, "rotate_offset_y") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_ROTATE_OFFSET_Y;
} else if(strcmp(szAttribute, "rotate_offset_z") == 0) {
} else if (strcmp(szAttribute, "rotate_offset_z") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_ROTATE_OFFSET_Z;
} else if(strcmp(szAttribute, "scale_offset_x") == 0) {
} else if (strcmp(szAttribute, "scale_offset_x") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_SCALE_OFFSET_X;
} else if(strcmp(szAttribute, "scale_offset_y") == 0) {
} else if (strcmp(szAttribute, "scale_offset_y") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_SCALE_OFFSET_Y;
} else if(strcmp(szAttribute, "scale_offset_z") == 0) {
} else if (strcmp(szAttribute, "scale_offset_z") == 0) {
m_node_attribute = KRNode::KRENGINE_NODE_SCALE_OFFSET_Z;
} else {
m_node_attribute = KRNode::KRENGINE_NODE_ATTRIBUTE_NONE;
@@ -236,7 +236,7 @@ std::string KRAnimationAttribute::getTargetName() const
return m_target_name;
}
void KRAnimationAttribute::setTargetName(const std::string &target_name)
void KRAnimationAttribute::setTargetName(const std::string& target_name)
{
m_target_name = target_name;
m_target = NULL;
@@ -247,26 +247,26 @@ std::string KRAnimationAttribute::getCurveName() const
return m_curve_name;
}
void KRAnimationAttribute::setCurveName(const std::string &curve_name)
void KRAnimationAttribute::setCurveName(const std::string& curve_name)
{
m_curve_name = curve_name;
m_curve = NULL;
}
KRNode *KRAnimationAttribute::getTarget()
KRNode* KRAnimationAttribute::getTarget()
{
if(m_target == NULL) {
if (m_target == NULL) {
m_target = getContext().getSceneManager()->getFirstScene()->getRootNode()->find<KRNode>(m_target_name); // FINDME, HACK! - This won't work with multiple scenes in a context; we should move the animations out of KRAnimationManager and attach them to the parent nodes of the animated KRNode's
}
if(m_target == NULL) {
if (m_target == NULL) {
KRContext::Log(KRContext::LOG_LEVEL_ERROR, "Kraken - Animation attribute could not find object: %s", m_target_name.c_str());
}
return m_target;
}
KRAnimationCurve *KRAnimationAttribute::getCurve()
KRAnimationCurve* KRAnimationAttribute::getCurve()
{
if(m_curve == NULL) {
if (m_curve == NULL) {
m_curve = getContext().getAnimationCurveManager()->getAnimationCurve(m_curve_name.c_str());
}
return m_curve;
@@ -274,8 +274,8 @@ KRAnimationCurve *KRAnimationAttribute::getCurve()
void KRAnimationAttribute::deleteCurve()
{
KRAnimationCurve *curve = getCurve();
if(curve) {
KRAnimationCurve* curve = getCurve();
if (curve) {
getContext().getAnimationCurveManager()->deleteAnimationCurve(curve);
m_curve = NULL;
}

View File

@@ -36,25 +36,26 @@
#include "KRNode.h"
#include "KRAnimationCurve.h"
class KRAnimationAttribute : public KRContextObject {
class KRAnimationAttribute : public KRContextObject
{
public:
KRAnimationAttribute(KRContext &context);
KRAnimationAttribute(KRContext& context);
~KRAnimationAttribute();
tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
void loadXML(tinyxml2::XMLElement *e);
tinyxml2::XMLElement* saveXML(tinyxml2::XMLNode* parent);
void loadXML(tinyxml2::XMLElement* e);
std::string getCurveName() const;
void setCurveName(const std::string &curve_name);
void setCurveName(const std::string& curve_name);
std::string getTargetName() const;
void setTargetName(const std::string &target_name);
void setTargetName(const std::string& target_name);
KRNode::node_attribute_type getTargetAttribute() const;
void setTargetAttribute(KRNode::node_attribute_type target_attribute);
KRNode *getTarget();
KRAnimationCurve *getCurve();
KRNode* getTarget();
KRAnimationCurve* getCurve();
void deleteCurve();
@@ -63,6 +64,6 @@ private:
std::string m_curve_name;
KRNode::node_attribute_type m_node_attribute;
KRNode *m_target;
KRAnimationCurve *m_curve;
KRNode* m_target;
KRAnimationCurve* m_curve;
};

View File

@@ -33,12 +33,12 @@
#include "KRAnimationCurve.h"
#include "KRDataBlock.h"
KRAnimationCurve::KRAnimationCurve(KRContext &context, const std::string &name) : KRResource(context, name)
KRAnimationCurve::KRAnimationCurve(KRContext& context, const std::string& name) : KRResource(context, name)
{
m_pData = new KRDataBlock();
m_pData->expand(sizeof(animation_curve_header));
m_pData->lock();
animation_curve_header *header = (animation_curve_header *)m_pData->getStart();
animation_curve_header* header = (animation_curve_header*)m_pData->getStart();
strcpy(header->szTag, "KRCURVE1.0 ");
header->frame_rate = 30.0f;
header->frame_start = 0;
@@ -51,7 +51,7 @@ KRAnimationCurve::~KRAnimationCurve()
m_pData->unload();
delete m_pData;
}
bool KRAnimationCurve::load(KRDataBlock *data)
bool KRAnimationCurve::load(KRDataBlock* data)
{
m_pData->unload();
delete m_pData;
@@ -59,23 +59,26 @@ bool KRAnimationCurve::load(KRDataBlock *data)
return true;
}
std::string KRAnimationCurve::getExtension() {
std::string KRAnimationCurve::getExtension()
{
return "kranimationcurve";
}
bool KRAnimationCurve::save(const std::string& path) {
bool KRAnimationCurve::save(const std::string& path)
{
return m_pData->save(path);
}
bool KRAnimationCurve::save(KRDataBlock &data) {
bool KRAnimationCurve::save(KRDataBlock& data)
{
data.append(*m_pData);
return true;
}
KRAnimationCurve *KRAnimationCurve::Load(KRContext &context, const std::string &name, KRDataBlock *data)
KRAnimationCurve* KRAnimationCurve::Load(KRContext& context, const std::string& name, KRDataBlock* data)
{
KRAnimationCurve *new_animation_curve = new KRAnimationCurve(context, name);
if(new_animation_curve->load(data)) {
KRAnimationCurve* new_animation_curve = new KRAnimationCurve(context, name);
if (new_animation_curve->load(data)) {
return new_animation_curve;
} else {
delete new_animation_curve;
@@ -87,7 +90,7 @@ KRAnimationCurve *KRAnimationCurve::Load(KRContext &context, const std::string &
int KRAnimationCurve::getFrameCount()
{
m_pData->lock();
int frame_count = ((animation_curve_header *)m_pData->getStart())->frame_count;
int frame_count = ((animation_curve_header*)m_pData->getStart())->frame_count;
m_pData->unlock();
return frame_count;
@@ -97,17 +100,17 @@ void KRAnimationCurve::setFrameCount(int frame_count)
{
m_pData->lock();
int prev_frame_count = getFrameCount();
if(frame_count != prev_frame_count) {
if (frame_count != prev_frame_count) {
float fill_value = 0.0f;
if(prev_frame_count > 0) {
if (prev_frame_count > 0) {
fill_value = getValue(prev_frame_count - 1);
}
m_pData->expand(sizeof(animation_curve_header) + sizeof(float) * frame_count - m_pData->getSize());
float *frame_data = (float *)((char *)m_pData->getStart() + sizeof(animation_curve_header));
for(int frame_number=prev_frame_count; frame_number < frame_count; frame_number++) {
float* frame_data = (float*)((char*)m_pData->getStart() + sizeof(animation_curve_header));
for (int frame_number = prev_frame_count; frame_number < frame_count; frame_number++) {
frame_data[frame_number] = fill_value;
}
((animation_curve_header *)m_pData->getStart())->frame_count = frame_count;
((animation_curve_header*)m_pData->getStart())->frame_count = frame_count;
}
m_pData->unlock();
}
@@ -115,7 +118,7 @@ void KRAnimationCurve::setFrameCount(int frame_count)
float KRAnimationCurve::getFrameRate()
{
m_pData->lock();
float frame_rate =((animation_curve_header *)m_pData->getStart())->frame_rate;
float frame_rate = ((animation_curve_header*)m_pData->getStart())->frame_rate;
m_pData->unlock();
return frame_rate;
}
@@ -123,14 +126,14 @@ float KRAnimationCurve::getFrameRate()
void KRAnimationCurve::setFrameRate(float frame_rate)
{
m_pData->lock();
((animation_curve_header *)m_pData->getStart())->frame_rate = frame_rate;
((animation_curve_header*)m_pData->getStart())->frame_rate = frame_rate;
m_pData->unlock();
}
int KRAnimationCurve::getFrameStart()
{
m_pData->lock();
int frame_start = ((animation_curve_header *)m_pData->getStart())->frame_start;
int frame_start = ((animation_curve_header*)m_pData->getStart())->frame_start;
m_pData->unlock();
return frame_start;
}
@@ -138,7 +141,7 @@ int KRAnimationCurve::getFrameStart()
void KRAnimationCurve::setFrameStart(int frame_number)
{
m_pData->lock();
((animation_curve_header *)m_pData->getStart())->frame_start = frame_number;
((animation_curve_header*)m_pData->getStart())->frame_start = frame_number;
m_pData->unlock();
}
@@ -147,12 +150,12 @@ float KRAnimationCurve::getValue(int frame_number)
m_pData->lock();
//printf("frame_number: %i\n", frame_number);
int clamped_frame = frame_number - getFrameStart();
if(clamped_frame < 0) {
if (clamped_frame < 0) {
clamped_frame = 0;
} else if(clamped_frame >= getFrameCount()) {
clamped_frame = getFrameCount()-1;
} else if (clamped_frame >= getFrameCount()) {
clamped_frame = getFrameCount() - 1;
}
float *frame_data = (float *)((char *)m_pData->getStart() + sizeof(animation_curve_header));
float* frame_data = (float*)((char*)m_pData->getStart() + sizeof(animation_curve_header));
float v = frame_data[clamped_frame];
m_pData->unlock();
return v;
@@ -162,8 +165,8 @@ void KRAnimationCurve::setValue(int frame_number, float value)
{
m_pData->lock();
int clamped_frame = frame_number - getFrameStart();
if(clamped_frame >= 0 && clamped_frame < getFrameCount()) {
float *frame_data = (float *)((char *)m_pData->getStart() + sizeof(animation_curve_header));
if (clamped_frame >= 0 && clamped_frame < getFrameCount()) {
float* frame_data = (float*)((char*)m_pData->getStart() + sizeof(animation_curve_header));
frame_data[clamped_frame] = value;
}
m_pData->unlock();
@@ -195,8 +198,8 @@ bool KRAnimationCurve::valueChanges(int start_frame, int frame_count)
bool change_found = false;
// Range of frames is not inclusive of last frame
for(int frame_number = start_frame + 1; frame_number < start_frame + frame_count && !change_found; frame_number++) {
if(getValue(frame_number) != first_value) {
for (int frame_number = start_frame + 1; frame_number < start_frame + frame_count && !change_found; frame_number++) {
if (getValue(frame_number) != first_value) {
change_found = true;
}
}
@@ -205,14 +208,14 @@ bool KRAnimationCurve::valueChanges(int start_frame, int frame_count)
return change_found;
}
KRAnimationCurve *KRAnimationCurve::split(const std::string &name, float start_time, float duration)
KRAnimationCurve* KRAnimationCurve::split(const std::string& name, float start_time, float duration)
{
return split(name, (int)(start_time * getFrameRate()), (int)(duration * getFrameRate()));
}
KRAnimationCurve *KRAnimationCurve::split(const std::string &name, int start_frame, int frame_count)
KRAnimationCurve* KRAnimationCurve::split(const std::string& name, int start_frame, int frame_count)
{
KRAnimationCurve *new_curve = new KRAnimationCurve(getContext(), name);
KRAnimationCurve* new_curve = new KRAnimationCurve(getContext(), name);
new_curve->setFrameRate(getFrameRate());
new_curve->setFrameStart(start_frame);
@@ -220,7 +223,7 @@ KRAnimationCurve *KRAnimationCurve::split(const std::string &name, int start_fra
new_curve->m_pData->lock();
// Range of frames is not inclusive of last frame
for(int frame_number = start_frame; frame_number < start_frame + frame_count; frame_number++) {
for (int frame_number = start_frame; frame_number < start_frame + frame_count; frame_number++) {
new_curve->setValue(frame_number, getValue(frame_number)); // TODO - MEMCPY here?
}
new_curve->m_pData->unlock();

View File

@@ -36,16 +36,17 @@
#include "KRDataBlock.h"
#include "KRResource.h"
class KRAnimationCurve : public KRResource {
class KRAnimationCurve : public KRResource
{
public:
KRAnimationCurve(KRContext &context, const std::string &name);
KRAnimationCurve(KRContext& context, const std::string& name);
virtual ~KRAnimationCurve();
virtual std::string getExtension();
virtual bool save(const std::string& path);
virtual bool save(KRDataBlock &data);
virtual bool load(KRDataBlock *data);
virtual bool save(KRDataBlock& data);
virtual bool load(KRDataBlock* data);
float getFrameRate();
void setFrameRate(float frame_rate);
@@ -58,21 +59,22 @@ public:
void setValue(int frame_number, float value);
static KRAnimationCurve *Load(KRContext &context, const std::string &name, KRDataBlock *data);
static KRAnimationCurve* Load(KRContext& context, const std::string& name, KRDataBlock* data);
bool valueChanges(float start_time, float duration);
bool valueChanges(int start_frame, int frame_count);
KRAnimationCurve *split(const std::string &name, float start_time, float duration);
KRAnimationCurve *split(const std::string &name, int start_frame, int frame_count);
KRAnimationCurve* split(const std::string& name, float start_time, float duration);
KRAnimationCurve* split(const std::string& name, int start_frame, int frame_count);
void _lockData();
void _unlockData();
private:
KRDataBlock *m_pData;
KRDataBlock* m_pData;
typedef struct {
typedef struct
{
char szTag[16];
float frame_rate;
int32_t frame_start;

View File

@@ -32,18 +32,20 @@
#include "KRAnimationCurveManager.h"
#include "KRAnimationCurve.h"
KRAnimationCurveManager::KRAnimationCurveManager(KRContext &context) : KRResourceManager(context)
KRAnimationCurveManager::KRAnimationCurveManager(KRContext& context) : KRResourceManager(context)
{
}
KRAnimationCurveManager::~KRAnimationCurveManager() {
for(unordered_map<std::string, KRAnimationCurve *>::iterator itr = m_animationCurves.begin(); itr != m_animationCurves.end(); ++itr){
KRAnimationCurveManager::~KRAnimationCurveManager()
{
for (unordered_map<std::string, KRAnimationCurve*>::iterator itr = m_animationCurves.begin(); itr != m_animationCurves.end(); ++itr) {
delete (*itr).second;
}
}
void KRAnimationCurveManager::deleteAnimationCurve(KRAnimationCurve *curve) {
void KRAnimationCurveManager::deleteAnimationCurve(KRAnimationCurve* curve)
{
m_animationCurves.erase(curve->getName());
delete curve;
}
@@ -63,28 +65,31 @@ KRResource* KRAnimationCurveManager::getResource(const std::string& name, const
return nullptr;
}
KRAnimationCurve *KRAnimationCurveManager::loadAnimationCurve(const std::string &name, KRDataBlock *data) {
KRAnimationCurve *pAnimationCurve = KRAnimationCurve::Load(*m_pContext, name, data);
if(pAnimationCurve) {
KRAnimationCurve* KRAnimationCurveManager::loadAnimationCurve(const std::string& name, KRDataBlock* data)
{
KRAnimationCurve* pAnimationCurve = KRAnimationCurve::Load(*m_pContext, name, data);
if (pAnimationCurve) {
m_animationCurves[name] = pAnimationCurve;
}
return pAnimationCurve;
}
KRAnimationCurve *KRAnimationCurveManager::getAnimationCurve(const std::string &name) {
unordered_map<std::string, KRAnimationCurve *>::iterator itr = m_animationCurves.find(name);
if(itr == m_animationCurves.end()) {
KRAnimationCurve* KRAnimationCurveManager::getAnimationCurve(const std::string& name)
{
unordered_map<std::string, KRAnimationCurve*>::iterator itr = m_animationCurves.find(name);
if (itr == m_animationCurves.end()) {
return NULL; // Not found
} else {
return (*itr).second;
}
}
unordered_map<std::string, KRAnimationCurve *> &KRAnimationCurveManager::getAnimationCurves() {
unordered_map<std::string, KRAnimationCurve*>& KRAnimationCurveManager::getAnimationCurves()
{
return m_animationCurves;
}
void KRAnimationCurveManager::addAnimationCurve(KRAnimationCurve *new_animation_curve)
void KRAnimationCurveManager::addAnimationCurve(KRAnimationCurve* new_animation_curve)
{
assert(new_animation_curve != NULL);
m_animationCurves[new_animation_curve->getName()] = new_animation_curve;

View File

@@ -41,22 +41,23 @@
using std::map;
class KRAnimationCurveManager : public KRResourceManager {
class KRAnimationCurveManager : public KRResourceManager
{
public:
KRAnimationCurveManager(KRContext &context);
KRAnimationCurveManager(KRContext& context);
virtual ~KRAnimationCurveManager();
virtual KRResource* loadResource(const std::string& name, const std::string& extension, KRDataBlock* data) override;
virtual KRResource* getResource(const std::string& name, const std::string& extension) override;
KRAnimationCurve *loadAnimationCurve(const std::string &name, KRDataBlock *data);
KRAnimationCurve *getAnimationCurve(const std::string &name);
void addAnimationCurve(KRAnimationCurve *new_animation_curve);
unordered_map<std::string, KRAnimationCurve *> &getAnimationCurves();
KRAnimationCurve* loadAnimationCurve(const std::string& name, KRDataBlock* data);
KRAnimationCurve* getAnimationCurve(const std::string& name);
void addAnimationCurve(KRAnimationCurve* new_animation_curve);
unordered_map<std::string, KRAnimationCurve*>& getAnimationCurves();
void deleteAnimationCurve(KRAnimationCurve *curve);
void deleteAnimationCurve(KRAnimationCurve* curve);
private:
unordered_map<std::string, KRAnimationCurve *> m_animationCurves;
unordered_map<std::string, KRAnimationCurve*> m_animationCurves;
};

View File

@@ -31,7 +31,7 @@
#include "KRAnimationLayer.h"
KRAnimationLayer::KRAnimationLayer(KRContext &context) : KRContextObject(context)
KRAnimationLayer::KRAnimationLayer(KRContext& context) : KRContextObject(context)
{
m_name = "";
m_blend_mode = KRENGINE_ANIMATION_BLEND_MODE_ADDITIVE;
@@ -41,7 +41,7 @@ KRAnimationLayer::KRAnimationLayer(KRContext &context) : KRContextObject(context
KRAnimationLayer::~KRAnimationLayer()
{
for(std::vector<KRAnimationAttribute *>::iterator itr = m_attributes.begin(); itr != m_attributes.end(); ++itr){
for (std::vector<KRAnimationAttribute*>::iterator itr = m_attributes.begin(); itr != m_attributes.end(); ++itr) {
delete (*itr);
}
}
@@ -51,20 +51,20 @@ std::string KRAnimationLayer::getName() const
return m_name;
}
void KRAnimationLayer::setName(const std::string &name)
void KRAnimationLayer::setName(const std::string& name)
{
m_name = name;
}
tinyxml2::XMLElement *KRAnimationLayer::saveXML( tinyxml2::XMLNode *parent)
tinyxml2::XMLElement* KRAnimationLayer::saveXML(tinyxml2::XMLNode* parent)
{
tinyxml2::XMLDocument *doc = parent->GetDocument();
tinyxml2::XMLElement *e = doc->NewElement("layer");
tinyxml2::XMLNode *n = parent->InsertEndChild(e);
tinyxml2::XMLDocument* doc = parent->GetDocument();
tinyxml2::XMLElement* e = doc->NewElement("layer");
tinyxml2::XMLNode* n = parent->InsertEndChild(e);
e->SetAttribute("name", m_name.c_str());
e->SetAttribute("weight", m_weight);
switch(m_blend_mode) {
switch (m_blend_mode) {
case KRENGINE_ANIMATION_BLEND_MODE_ADDITIVE:
e->SetAttribute("blend_mode", "additive");
break;
@@ -76,7 +76,7 @@ tinyxml2::XMLElement *KRAnimationLayer::saveXML( tinyxml2::XMLNode *parent)
break;
}
switch(m_rotation_accumulation_mode) {
switch (m_rotation_accumulation_mode) {
case KRENGINE_ANIMATION_ROTATION_ACCUMULATION_BY_CHANNEL:
e->SetAttribute("rotation_accumulation_mode", "by_channel");
break;
@@ -85,7 +85,7 @@ tinyxml2::XMLElement *KRAnimationLayer::saveXML( tinyxml2::XMLNode *parent)
break;
}
switch(m_scale_accumulation_mode) {
switch (m_scale_accumulation_mode) {
case KRENGINE_ANIMATION_SCALE_ACCUMULATION_ADDITIVE:
e->SetAttribute("scale_accumulation_mode", "additive");
break;
@@ -94,52 +94,52 @@ tinyxml2::XMLElement *KRAnimationLayer::saveXML( tinyxml2::XMLNode *parent)
break;
}
for(std::vector<KRAnimationAttribute *>::iterator itr = m_attributes.begin(); itr != m_attributes.end(); ++itr){
for (std::vector<KRAnimationAttribute*>::iterator itr = m_attributes.begin(); itr != m_attributes.end(); ++itr) {
(*itr)->saveXML(n);
}
return e;
}
void KRAnimationLayer::loadXML(tinyxml2::XMLElement *e)
void KRAnimationLayer::loadXML(tinyxml2::XMLElement* e)
{
m_name = e->Attribute("name");
if(e->QueryFloatAttribute("weight", &m_weight) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("weight", &m_weight) != tinyxml2::XML_SUCCESS) {
m_weight = 1.0f; // default
}
const char *szBlendMode = e->Attribute("blend_mode");
if(strcmp(szBlendMode, "additive") == 0) {
const char* szBlendMode = e->Attribute("blend_mode");
if (strcmp(szBlendMode, "additive") == 0) {
m_blend_mode = KRENGINE_ANIMATION_BLEND_MODE_ADDITIVE;
} else if(strcmp(szBlendMode, "override") == 0) {
} else if (strcmp(szBlendMode, "override") == 0) {
m_blend_mode = KRENGINE_ANIMATION_BLEND_MODE_OVERRIDE;
} else if(strcmp(szBlendMode, "override_passthrough") == 0) {
} else if (strcmp(szBlendMode, "override_passthrough") == 0) {
m_blend_mode = KRENGINE_ANIMATION_BLEND_MODE_OVERRIDE_PASSTHROUGH;
} else {
m_blend_mode = KRENGINE_ANIMATION_BLEND_MODE_ADDITIVE; // default
}
const char *szRotationAccumulationMode = e->Attribute("rotation_accumulation_mode");
if(strcmp(szRotationAccumulationMode, "by_channel") == 0) {
const char* szRotationAccumulationMode = e->Attribute("rotation_accumulation_mode");
if (strcmp(szRotationAccumulationMode, "by_channel") == 0) {
m_rotation_accumulation_mode = KRENGINE_ANIMATION_ROTATION_ACCUMULATION_BY_CHANNEL;
} else if(strcmp(szRotationAccumulationMode, "by_layer") == 0) {
} else if (strcmp(szRotationAccumulationMode, "by_layer") == 0) {
m_rotation_accumulation_mode = KRENGINE_ANIMATION_ROTATION_ACCUMULATION_BY_LAYER;
} else {
m_rotation_accumulation_mode = KRENGINE_ANIMATION_ROTATION_ACCUMULATION_BY_LAYER; // default
}
const char *szScaleAccumulationMode = e->Attribute("scale_accumulation_mode");
if(strcmp(szScaleAccumulationMode, "additive") == 0) {
const char* szScaleAccumulationMode = e->Attribute("scale_accumulation_mode");
if (strcmp(szScaleAccumulationMode, "additive") == 0) {
m_scale_accumulation_mode = KRENGINE_ANIMATION_SCALE_ACCUMULATION_ADDITIVE;
} else if(strcmp(szScaleAccumulationMode, "multiply") == 0) {
} else if (strcmp(szScaleAccumulationMode, "multiply") == 0) {
m_scale_accumulation_mode = KRENGINE_ANIMATION_SCALE_ACCUMULATION_MULTIPLY;
} else {
m_scale_accumulation_mode = KRENGINE_ANIMATION_SCALE_ACCUMULATION_MULTIPLY; // default
}
for(tinyxml2::XMLElement *child_element=e->FirstChildElement(); child_element != NULL; child_element = child_element->NextSiblingElement()) {
if(strcmp(child_element->Name(), "attribute") == 0) {
KRAnimationAttribute *new_attribute = new KRAnimationAttribute(getContext());
for (tinyxml2::XMLElement* child_element = e->FirstChildElement(); child_element != NULL; child_element = child_element->NextSiblingElement()) {
if (strcmp(child_element->Name(), "attribute") == 0) {
KRAnimationAttribute* new_attribute = new KRAnimationAttribute(getContext());
new_attribute->loadXML(child_element);
m_attributes.push_back(new_attribute);
}
@@ -162,7 +162,7 @@ KRAnimationLayer::blend_mode_t KRAnimationLayer::getBlendMode() const
return m_blend_mode;
}
void KRAnimationLayer::setBlendMode(const KRAnimationLayer::blend_mode_t &blend_mode)
void KRAnimationLayer::setBlendMode(const KRAnimationLayer::blend_mode_t& blend_mode)
{
m_blend_mode = blend_mode;
}
@@ -172,7 +172,7 @@ KRAnimationLayer::rotation_accumulation_mode_t KRAnimationLayer::getRotationAccu
return m_rotation_accumulation_mode;
}
void KRAnimationLayer::setRotationAccumulationMode(const KRAnimationLayer::rotation_accumulation_mode_t &rotation_accumulation_mode)
void KRAnimationLayer::setRotationAccumulationMode(const KRAnimationLayer::rotation_accumulation_mode_t& rotation_accumulation_mode)
{
m_rotation_accumulation_mode = rotation_accumulation_mode;
}
@@ -182,17 +182,17 @@ KRAnimationLayer::scale_accumulation_mode_t KRAnimationLayer::getScaleAccumulati
return m_scale_accumulation_mode;
}
void KRAnimationLayer::setScaleAccumulationMode(const KRAnimationLayer::scale_accumulation_mode_t &scale_accumulation_mode)
void KRAnimationLayer::setScaleAccumulationMode(const KRAnimationLayer::scale_accumulation_mode_t& scale_accumulation_mode)
{
m_scale_accumulation_mode = scale_accumulation_mode;
}
void KRAnimationLayer::addAttribute(KRAnimationAttribute *attribute)
void KRAnimationLayer::addAttribute(KRAnimationAttribute* attribute)
{
m_attributes.push_back(attribute);
}
std::vector<KRAnimationAttribute *> &KRAnimationLayer::getAttributes()
std::vector<KRAnimationAttribute*>& KRAnimationLayer::getAttributes()
{
return m_attributes;
}

View File

@@ -36,51 +36,55 @@
#include "KRAnimationAttribute.h"
namespace tinyxml2 {
class XMLNode;
class XMLAttribute;
class XMLNode;
class XMLAttribute;
}
class KRAnimationLayer : public KRContextObject {
class KRAnimationLayer : public KRContextObject
{
public:
KRAnimationLayer(KRContext &context);
KRAnimationLayer(KRContext& context);
~KRAnimationLayer();
tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
void loadXML(tinyxml2::XMLElement *e);
tinyxml2::XMLElement* saveXML(tinyxml2::XMLNode* parent);
void loadXML(tinyxml2::XMLElement* e);
std::string getName() const;
void setName(const std::string &name);
void setName(const std::string& name);
float getWeight() const;
void setWeight(float weight);
typedef enum {
typedef enum
{
KRENGINE_ANIMATION_BLEND_MODE_ADDITIVE,
KRENGINE_ANIMATION_BLEND_MODE_OVERRIDE,
KRENGINE_ANIMATION_BLEND_MODE_OVERRIDE_PASSTHROUGH
} blend_mode_t;
blend_mode_t getBlendMode() const;
void setBlendMode(const blend_mode_t &blend_mode);
void setBlendMode(const blend_mode_t& blend_mode);
typedef enum {
typedef enum
{
KRENGINE_ANIMATION_ROTATION_ACCUMULATION_BY_LAYER,
KRENGINE_ANIMATION_ROTATION_ACCUMULATION_BY_CHANNEL
} rotation_accumulation_mode_t;
rotation_accumulation_mode_t getRotationAccumulationMode() const;
void setRotationAccumulationMode(const rotation_accumulation_mode_t &rotation_accumulation_mode);
void setRotationAccumulationMode(const rotation_accumulation_mode_t& rotation_accumulation_mode);
typedef enum {
typedef enum
{
KRENGINE_ANIMATION_SCALE_ACCUMULATION_MULTIPLY,
KRENGINE_ANIMATION_SCALE_ACCUMULATION_ADDITIVE
} scale_accumulation_mode_t;
scale_accumulation_mode_t getScaleAccumulationMode() const;
void setScaleAccumulationMode(const scale_accumulation_mode_t &scale_accumulation_mode);
void setScaleAccumulationMode(const scale_accumulation_mode_t& scale_accumulation_mode);
void addAttribute(KRAnimationAttribute *attribute);
std::vector<KRAnimationAttribute *> &getAttributes();
void addAttribute(KRAnimationAttribute* attribute);
std::vector<KRAnimationAttribute*>& getAttributes();
private:
std::string m_name;
@@ -89,5 +93,5 @@ private:
rotation_accumulation_mode_t m_rotation_accumulation_mode;
scale_accumulation_mode_t m_scale_accumulation_mode;
std::vector<KRAnimationAttribute *> m_attributes;
std::vector<KRAnimationAttribute*> m_attributes;
};

View File

@@ -32,36 +32,37 @@
#include "KRAnimationManager.h"
#include "KRAnimation.h"
KRAnimationManager::KRAnimationManager(KRContext &context) : KRResourceManager(context)
KRAnimationManager::KRAnimationManager(KRContext& context) : KRResourceManager(context)
{
}
KRAnimationManager::~KRAnimationManager() {
for(std::set<KRAnimation *>::iterator itr = m_activeAnimations.begin(); itr != m_activeAnimations.end(); itr++) {
KRAnimation *animation = *itr;
KRAnimationManager::~KRAnimationManager()
{
for (std::set<KRAnimation*>::iterator itr = m_activeAnimations.begin(); itr != m_activeAnimations.end(); itr++) {
KRAnimation* animation = *itr;
animation->_unlockData();
}
for(unordered_map<std::string, KRAnimation *>::iterator itr = m_animations.begin(); itr != m_animations.end(); ++itr){
for (unordered_map<std::string, KRAnimation*>::iterator itr = m_animations.begin(); itr != m_animations.end(); ++itr) {
delete (*itr).second;
}
}
void KRAnimationManager::startFrame(float deltaTime)
{
for(std::set<KRAnimation *>::iterator itr = m_animationsToUpdate.begin(); itr != m_animationsToUpdate.end(); itr++) {
KRAnimation *animation = *itr;
std::set<KRAnimation *>::iterator active_animations_itr = m_activeAnimations.find(animation);
if(animation->isPlaying()) {
for (std::set<KRAnimation*>::iterator itr = m_animationsToUpdate.begin(); itr != m_animationsToUpdate.end(); itr++) {
KRAnimation* animation = *itr;
std::set<KRAnimation*>::iterator active_animations_itr = m_activeAnimations.find(animation);
if (animation->isPlaying()) {
// Add playing animations to the active animations list
if(active_animations_itr == m_activeAnimations.end()) {
if (active_animations_itr == m_activeAnimations.end()) {
m_activeAnimations.insert(animation);
animation->_lockData();
}
} else {
// Remove stopped animations from the active animations list
if(active_animations_itr != m_activeAnimations.end()) {
if (active_animations_itr != m_activeAnimations.end()) {
m_activeAnimations.erase(active_animations_itr);
animation->_unlockData();
}
@@ -70,8 +71,8 @@ void KRAnimationManager::startFrame(float deltaTime)
m_animationsToUpdate.clear();
for(std::set<KRAnimation *>::iterator active_animations_itr = m_activeAnimations.begin(); active_animations_itr != m_activeAnimations.end(); active_animations_itr++) {
KRAnimation *animation = *active_animations_itr;
for (std::set<KRAnimation*>::iterator active_animations_itr = m_activeAnimations.begin(); active_animations_itr != m_activeAnimations.end(); active_animations_itr++) {
KRAnimation* animation = *active_animations_itr;
animation->update(deltaTime);
}
}
@@ -96,35 +97,37 @@ KRResource* KRAnimationManager::getResource(const std::string& name, const std::
return nullptr;
}
KRAnimation *KRAnimationManager::loadAnimation(const char *szName, KRDataBlock *data) {
KRAnimation *pAnimation = KRAnimation::Load(*m_pContext, szName, data);
KRAnimation* KRAnimationManager::loadAnimation(const char* szName, KRDataBlock* data)
{
KRAnimation* pAnimation = KRAnimation::Load(*m_pContext, szName, data);
addAnimation(pAnimation);
return pAnimation;
}
KRAnimation *KRAnimationManager::getAnimation(const char *szName) {
KRAnimation* KRAnimationManager::getAnimation(const char* szName)
{
return m_animations[szName];
}
unordered_map<std::string, KRAnimation *> &KRAnimationManager::getAnimations() {
unordered_map<std::string, KRAnimation*>& KRAnimationManager::getAnimations()
{
return m_animations;
}
void KRAnimationManager::addAnimation(KRAnimation *new_animation)
void KRAnimationManager::addAnimation(KRAnimation* new_animation)
{
m_animations[new_animation->getName()] = new_animation;
updateActiveAnimations(new_animation);
}
void KRAnimationManager::updateActiveAnimations(KRAnimation *animation)
void KRAnimationManager::updateActiveAnimations(KRAnimation* animation)
{
m_animationsToUpdate.insert(animation);
}
void KRAnimationManager::deleteAnimation(KRAnimation *animation, bool delete_curves)
void KRAnimationManager::deleteAnimation(KRAnimation* animation, bool delete_curves)
{
if(delete_curves)
{
if (delete_curves) {
animation->deleteCurves();
}
m_animations.erase(animation->getName());

View File

@@ -41,28 +41,29 @@
class KRAnimationManager : public KRResourceManager {
class KRAnimationManager : public KRResourceManager
{
public:
KRAnimationManager(KRContext &context);
KRAnimationManager(KRContext& context);
virtual ~KRAnimationManager();
virtual KRResource* loadResource(const std::string& name, const std::string& extension, KRDataBlock* data) override;
virtual KRResource* getResource(const std::string& name, const std::string& extension) override;
KRAnimation *loadAnimation(const char *szName, KRDataBlock *data);
KRAnimation *getAnimation(const char *szName);
void addAnimation(KRAnimation *new_animation);
unordered_map<std::string, KRAnimation *> &getAnimations();
void deleteAnimation(KRAnimation *animation, bool delete_curves);
KRAnimation* loadAnimation(const char* szName, KRDataBlock* data);
KRAnimation* getAnimation(const char* szName);
void addAnimation(KRAnimation* new_animation);
unordered_map<std::string, KRAnimation*>& getAnimations();
void deleteAnimation(KRAnimation* animation, bool delete_curves);
void startFrame(float deltaTime);
void endFrame(float deltaTime);
void updateActiveAnimations(KRAnimation *animation);
void updateActiveAnimations(KRAnimation* animation);
private:
unordered_map<std::string, KRAnimation *> m_animations;
set<KRAnimation *> m_activeAnimations;
set<KRAnimation *> m_animationsToUpdate;
unordered_map<std::string, KRAnimation*> m_animations;
set<KRAnimation*> m_activeAnimations;
set<KRAnimation*> m_animationsToUpdate;
};

View File

@@ -33,7 +33,7 @@
#include "KRAudioManager.h"
KRAudioBuffer::KRAudioBuffer(KRAudioManager *manager, KRAudioSample *sound, int index, int frameCount, int frameRate, int bytesPerFrame, void (*fn_populate)(KRAudioSample *, int, void *))
KRAudioBuffer::KRAudioBuffer(KRAudioManager* manager, KRAudioSample* sound, int index, int frameCount, int frameRate, int bytesPerFrame, void (*fn_populate)(KRAudioSample*, int, void*))
{
m_pSoundManager = manager;
m_frameCount = frameCount;
@@ -53,7 +53,7 @@ KRAudioBuffer::~KRAudioBuffer()
m_pSoundManager->recycleBufferData(m_pData);
}
KRAudioSample *KRAudioBuffer::getAudioSample()
KRAudioSample* KRAudioBuffer::getAudioSample()
{
return m_audioSample;
}
@@ -68,9 +68,9 @@ int KRAudioBuffer::getFrameRate()
return m_frameRate;
}
signed short *KRAudioBuffer::getFrameData()
signed short* KRAudioBuffer::getFrameData()
{
return (signed short *)m_pData->getStart();
return (signed short*)m_pData->getStart();
}
int KRAudioBuffer::getIndex()

View File

@@ -40,23 +40,23 @@ class KRAudioSample;
class KRAudioBuffer
{
public:
KRAudioBuffer(KRAudioManager *manager, KRAudioSample *sound, int index, int frameCount, int frameRate, int bytesPerFrame, void (*fn_populate)(KRAudioSample *, int, void *));
KRAudioBuffer(KRAudioManager* manager, KRAudioSample* sound, int index, int frameCount, int frameRate, int bytesPerFrame, void (*fn_populate)(KRAudioSample*, int, void*));
~KRAudioBuffer();
int getFrameCount();
int getFrameRate();
signed short *getFrameData();
signed short* getFrameData();
KRAudioSample *getAudioSample();
KRAudioSample* getAudioSample();
int getIndex();
private:
KRAudioManager *m_pSoundManager;
KRAudioManager* m_pSoundManager;
int m_index;
int m_frameCount;
int m_frameRate;
int m_bytesPerFrame;
KRDataBlock *m_pData;
KRDataBlock* m_pData;
KRAudioSample *m_audioSample;
KRAudioSample* m_audioSample;
};

File diff suppressed because it is too large Load Diff

View File

@@ -59,9 +59,9 @@ const int KRENGINE_AUDIO_BLOCK_LOG2N = 7; // 2 ^ KRENGINE_AUDIO_BLOCK_LOG2N =
// 7 is 128 .. NOTE: the hrtf code uses magic numbers everywhere and is hardcoded to 128 samples per frame
const int KRENGINE_AUDIO_BLOCK_LENGTH = 1 << KRENGINE_AUDIO_BLOCK_LOG2N;
// Length of one block to process. Determines the latency of the audio system and sets size for FFT's used in HRTF convolution
// the AUGraph works in 1024 sample chunks. At 128 we are making 8 consecutive calls to the renderBlock method for each
// render initiated by the AUGraph.
// Length of one block to process. Determines the latency of the audio system and sets size for FFT's used in HRTF convolution
// the AUGraph works in 1024 sample chunks. At 128 we are making 8 consecutive calls to the renderBlock method for each
// render initiated by the AUGraph.
const int KRENGINE_REVERB_MAX_FFT_LOG2 = 15;
const int KRENGINE_REVERB_WORKSPACE_SIZE = 1 << KRENGINE_REVERB_MAX_FFT_LOG2;
@@ -79,42 +79,45 @@ const int KRENGINE_AUDIO_ANTICLICK_SAMPLES = 64;
class KRAmbientZone;
class KRReverbZone;
typedef struct {
typedef struct
{
float weight;
KRAmbientZone *ambient_zone;
KRAudioSample *ambient_sample;
KRAmbientZone* ambient_zone;
KRAudioSample* ambient_sample;
} siren_ambient_zone_weight_info;
typedef struct {
typedef struct
{
float weight;
KRReverbZone *reverb_zone;
KRAudioSample *reverb_sample;
KRReverbZone* reverb_zone;
KRAudioSample* reverb_sample;
} siren_reverb_zone_weight_info;
class KRAudioManager : public KRResourceManager {
class KRAudioManager : public KRResourceManager
{
public:
KRAudioManager(KRContext &context);
KRAudioManager(KRContext& context);
virtual ~KRAudioManager();
void destroy();
virtual KRResource* loadResource(const std::string& name, const std::string& extension, KRDataBlock* data) override;
virtual KRResource* getResource(const std::string& name, const std::string& extension) override;
unordered_map<std::string, KRAudioSample *> &getSounds();
unordered_map<std::string, KRAudioSample*>& getSounds();
void add(KRAudioSample *Sound);
void add(KRAudioSample* Sound);
KRAudioSample *load(const std::string &name, const std::string &extension, KRDataBlock *data);
KRAudioSample *get(const std::string &name);
KRAudioSample* load(const std::string& name, const std::string& extension, KRDataBlock* data);
KRAudioSample* get(const std::string& name);
// Listener position and orientation
KRScene *getListenerScene();
void setListenerScene(KRScene *scene);
void setListenerOrientation(const Vector3 &position, const Vector3 &forward, const Vector3 &up);
void setListenerOrientationFromModelMatrix(const Matrix4 &modelMatrix);
Vector3 &getListenerForward();
Vector3 &getListenerPosition();
Vector3 &getListenerUp();
KRScene* getListenerScene();
void setListenerScene(KRScene* scene);
void setListenerOrientation(const Vector3& position, const Vector3& forward, const Vector3& up);
void setListenerOrientationFromModelMatrix(const Matrix4& modelMatrix);
Vector3& getListenerForward();
Vector3& getListenerPosition();
Vector3& getListenerUp();
// Global audio gain / attenuation
@@ -129,15 +132,15 @@ public:
void makeCurrentContext();
KRDataBlock *getBufferData(int size);
void recycleBufferData(KRDataBlock *data);
KRDataBlock* getBufferData(int size);
void recycleBufferData(KRDataBlock* data);
void activateAudioSource(KRAudioSource *audioSource);
void deactivateAudioSource(KRAudioSource *audioSource);
void activateAudioSource(KRAudioSource* audioSource);
void deactivateAudioSource(KRAudioSource* audioSource);
__int64_t getAudioFrame();
KRAudioBuffer *getBuffer(KRAudioSample &audio_sample, int buffer_index);
KRAudioBuffer* getBuffer(KRAudioSample& audio_sample, int buffer_index);
static void mute(bool onNotOff);
void goToSleep();
@@ -156,8 +159,8 @@ public:
float getReverbMaxLength();
void setReverbMaxLength(float max_length);
void _registerOpenAudioSample(KRAudioSample *audioSample);
void _registerCloseAudioSample(KRAudioSample *audioSample);
void _registerOpenAudioSample(KRAudioSample* audioSample);
void _registerCloseAudioSample(KRAudioSample* audioSample);
private:
bool m_enable_audio;
@@ -165,7 +168,7 @@ private:
bool m_enable_reverb;
float m_reverb_max_length;
KRScene *m_listener_scene; // For now, only one scene is allowed to have active audio at once
KRScene* m_listener_scene; // For now, only one scene is allowed to have active audio at once
float m_global_reverb_send_level;
float m_global_ambient_gain;
@@ -175,15 +178,15 @@ private:
Vector3 m_listener_forward;
Vector3 m_listener_up;
unordered_map<std::string, KRAudioSample *> m_sounds;
unordered_map<std::string, KRAudioSample*> m_sounds;
std::vector<KRDataBlock *> m_bufferPoolIdle;
std::vector<KRDataBlock*> m_bufferPoolIdle;
std::vector<KRAudioBuffer *> m_bufferCache;
std::vector<KRAudioBuffer*> m_bufferCache;
std::set<KRAudioSource *> m_activeAudioSources;
std::set<KRAudioSource*> m_activeAudioSources;
std::set<KRAudioSample *> m_openAudioSamples;
std::set<KRAudioSample*> m_openAudioSamples;
void initAudio();
void initHRTF();
@@ -197,29 +200,29 @@ private:
AUGraph m_auGraph;
AudioUnit m_auMixer;
static OSStatus renderInput(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData);
void renderAudio(UInt32 inNumberFrames, AudioBufferList *ioData);
static OSStatus renderInput(void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData);
void renderAudio(UInt32 inNumberFrames, AudioBufferList* ioData);
#endif
KRDSP::FFTWorkspace m_fft_setup[KRENGINE_REVERB_MAX_FFT_LOG2 - KRENGINE_AUDIO_BLOCK_LOG2N + 1];
__int64_t m_audio_frame; // Number of audio frames processed since the start of the application
float *m_reverb_input_samples; // Circular-buffered reverb input, single channel
float* m_reverb_input_samples; // Circular-buffered reverb input, single channel
int m_reverb_input_next_sample; // Pointer to next sample in reverb buffer
int m_reverb_sequence;
KRAudioSample *m_reverb_impulse_responses[KRENGINE_MAX_REVERB_IMPULSE_MIX];
KRAudioSample* m_reverb_impulse_responses[KRENGINE_MAX_REVERB_IMPULSE_MIX];
float m_reverb_impulse_responses_weight[KRENGINE_MAX_REVERB_IMPULSE_MIX];
float *m_output_accumulation; // Interleaved output accumulation buffer
float* m_output_accumulation; // Interleaved output accumulation buffer
int m_output_accumulation_block_start;
int m_output_sample;
float *m_workspace_data;
float* m_workspace_data;
KRDSP::SplitComplex m_workspace[3];
float *getBlockAddress(int block_offset);
float* getBlockAddress(int block_offset);
void renderBlock();
void renderReverb();
void renderAmbient();
@@ -229,13 +232,13 @@ private:
void renderLimiter();
std::vector<Vector2> m_hrtf_sample_locations;
float *m_hrtf_data;
float* m_hrtf_data;
unordered_map<Vector2, KRDSP::SplitComplex> m_hrtf_spectral[2];
Vector2 getNearestHRTFSample(const Vector2 &dir);
void getHRTFMix(const Vector2 &dir, Vector2 &hrtf1, Vector2 &hrtf2, Vector2 &hrtf3, Vector2 &hrtf4, float &mix1, float &mix2, float &mix3, float &mix4);
KRAudioSample *getHRTFSample(const Vector2 &hrtf_dir);
KRDSP::SplitComplex getHRTFSpectral(const Vector2 &hrtf_dir, const int channel);
Vector2 getNearestHRTFSample(const Vector2& dir);
void getHRTFMix(const Vector2& dir, Vector2& hrtf1, Vector2& hrtf2, Vector2& hrtf3, Vector2& hrtf4, float& mix1, float& mix2, float& mix3, float& mix4);
KRAudioSample* getHRTFSample(const Vector2& hrtf_dir);
KRDSP::SplitComplex getHRTFSpectral(const Vector2& hrtf_dir, const int channel);
unordered_map<std::string, siren_ambient_zone_weight_info> m_ambient_zone_weights;
float m_ambient_zone_total_weight = 0.0f; // For normalizing zone weights
@@ -249,7 +252,7 @@ private:
#endif
unordered_multimap<Vector2, std::pair<KRAudioSource *, std::pair<float, float> > > m_mapped_sources, m_prev_mapped_sources;
unordered_multimap<Vector2, std::pair<KRAudioSource*, std::pair<float, float> > > m_mapped_sources, m_prev_mapped_sources;
bool m_anticlick_block;
bool m_high_quality_hrtf; // If true, 4 HRTF samples will be interpolated; if false, the nearest HRTF sample will be used without interpolation
};

View File

@@ -36,7 +36,7 @@
#include "KRContext.h"
#include "KRDSP.h"
KRAudioSample::KRAudioSample(KRContext &context, std::string name, std::string extension) : KRResource(context, name)
KRAudioSample::KRAudioSample(KRContext& context, std::string name, std::string extension) : KRResource(context, name)
{
m_pData = new KRDataBlock();
m_extension = extension;
@@ -54,7 +54,7 @@ KRAudioSample::KRAudioSample(KRContext &context, std::string name, std::string e
m_last_frame_used = 0;
}
KRAudioSample::KRAudioSample(KRContext &context, std::string name, std::string extension, KRDataBlock *data) : KRResource(context, name)
KRAudioSample::KRAudioSample(KRContext& context, std::string name, std::string extension, KRDataBlock* data) : KRResource(context, name)
{
m_pData = data;
m_extension = extension;
@@ -97,11 +97,11 @@ float KRAudioSample::sample(int frame_offset, int frame_rate, int channel)
int c = KRMIN(channel, m_channelsPerFrame - 1);
if(frame_offset < 0) {
if (frame_offset < 0) {
return 0.0f; // Past the beginning of the recording
} else {
int sample_frame;
if(m_frameRate == frame_rate) {
if (m_frameRate == frame_rate) {
// No resampling required
sample_frame = frame_offset;
} else {
@@ -110,37 +110,37 @@ float KRAudioSample::sample(int frame_offset, int frame_rate, int channel)
}
int maxFramesPerBuffer = KRENGINE_AUDIO_MAX_BUFFER_SIZE / m_bytesPerFrame;
int buffer_index = sample_frame / maxFramesPerBuffer;
if(buffer_index >= m_bufferCount) {
if (buffer_index >= m_bufferCount) {
return 0.0f; // Past the end of the recording
} else {
__int64_t buffer_offset = frame_offset - buffer_index * maxFramesPerBuffer;
KRAudioBuffer *buffer = getContext().getAudioManager()->getBuffer(*this, buffer_index);
if(buffer == NULL) {
KRAudioBuffer* buffer = getContext().getAudioManager()->getBuffer(*this, buffer_index);
if (buffer == NULL) {
return 0.0f;
} else if(buffer_offset >= buffer->getFrameCount()) {
} else if (buffer_offset >= buffer->getFrameCount()) {
return 0.0f; // past the end of the recording
} else {
short *frame = buffer->getFrameData() + (buffer_offset * m_channelsPerFrame);
short* frame = buffer->getFrameData() + (buffer_offset * m_channelsPerFrame);
return frame[c] / 32767.0f;
}
}
}
}
void KRAudioSample::sample(__int64_t frame_offset, int frame_count, int channel, float *buffer, float amplitude, bool loop)
void KRAudioSample::sample(__int64_t frame_offset, int frame_count, int channel, float* buffer, float amplitude, bool loop)
{
loadInfo();
m_last_frame_used = (int)getContext().getAudioManager()->getAudioFrame();
if(loop) {
if (loop) {
int buffer_offset = 0;
int frames_left = frame_count;
int sample_length = (int)getFrameCount();
while(frames_left) {
while (frames_left) {
int next_frame = (int)(((__int64_t)frame_offset + (__int64_t)buffer_offset) % sample_length);
if(next_frame + frames_left >= sample_length) {
if (next_frame + frames_left >= sample_length) {
int frames_processed = sample_length - next_frame;
sample(next_frame, frames_processed, channel, buffer + buffer_offset, amplitude, false);
frames_left -= frames_processed;
@@ -153,16 +153,16 @@ void KRAudioSample::sample(__int64_t frame_offset, int frame_count, int channel,
} else {
int c = KRMIN(channel, m_channelsPerFrame - 1);
if(frame_offset + frame_count <= 0) {
if (frame_offset + frame_count <= 0) {
// Range is entirely before the sample
memset(buffer, 0, frame_count * sizeof(float));
} else if(frame_offset >= m_totalFrames) {
} else if (frame_offset >= m_totalFrames) {
// Range is entirely after the sample
memset(buffer, 0, frame_count * sizeof(float));
} else {
int start_frame = (int)(frame_offset < 0 ? 0 : frame_offset);
int prefix_frames = (int)(frame_offset < 0 ? -frame_offset : 0);
if(prefix_frames > 0) {
if (prefix_frames > 0) {
// Prefix with padding of 0's
memset(buffer, 0, prefix_frames * sizeof(float));
}
@@ -172,18 +172,18 @@ void KRAudioSample::sample(__int64_t frame_offset, int frame_count, int channel,
int buffer_index = start_frame / frames_per_buffer;
int buffer_offset = start_frame % frames_per_buffer;
int processed_frames = prefix_frames;
while(processed_frames < frame_count) {
while (processed_frames < frame_count) {
int frames_left = frame_count - processed_frames;
if(buffer_index >= m_bufferCount) {
if (buffer_index >= m_bufferCount) {
// Suffix with padding of 0's
memset(buffer + processed_frames, 0, frames_left * sizeof(float));
processed_frames += frames_left;
} else {
KRAudioBuffer *source_buffer = getContext().getAudioManager()->getBuffer(*this, buffer_index);
KRAudioBuffer* source_buffer = getContext().getAudioManager()->getBuffer(*this, buffer_index);
int frames_to_copy = source_buffer->getFrameCount() - buffer_offset;
if(frames_to_copy > frames_left) frames_to_copy = frames_left;
if(frames_to_copy > 0) {
signed short *source_data = source_buffer->getFrameData() + buffer_offset * m_channelsPerFrame + c;
if (frames_to_copy > frames_left) frames_to_copy = frames_left;
if (frames_to_copy > 0) {
signed short* source_data = source_buffer->getFrameData() + buffer_offset * m_channelsPerFrame + c;
KRDSP::Int16ToFloat(source_data, m_channelsPerFrame, buffer + processed_frames, 1, frames_to_copy);
//memcpy(buffer + processed_frames, source_buffer->getFrameData() + buffer_offset, frames_to_copy * m_channelsPerFrame * sizeof(float));
processed_frames += frames_to_copy;
@@ -202,13 +202,13 @@ void KRAudioSample::sample(__int64_t frame_offset, int frame_count, int channel,
#ifdef __APPLE__
// Apple Audio Toolbox
OSStatus KRAudioSample::ReadProc( // AudioFile_ReadProc
void * inClientData,
void* inClientData,
SInt64 inPosition,
UInt32 requestCount,
void * buffer,
UInt32 * actualCount)
void* buffer,
UInt32* actualCount)
{
KRAudioSample *sound = (KRAudioSample *)inClientData;
KRAudioSample* sound = (KRAudioSample*)inClientData;
UInt32 max_count = sound->m_pData->getSize() - inPosition;
*actualCount = requestCount < max_count ? requestCount : max_count;
sound->m_pData->copy(buffer, inPosition, *actualCount);
@@ -216,25 +216,25 @@ OSStatus KRAudioSample::ReadProc( // AudioFile_ReadProc
}
SInt64 KRAudioSample::GetSizeProc( // AudioFile_GetSizeProc
void * inClientData)
void* inClientData)
{
KRAudioSample *sound = (KRAudioSample *)inClientData;
KRAudioSample* sound = (KRAudioSample*)inClientData;
return sound->m_pData->getSize();
}
OSStatus KRAudioSample::SetSizeProc( // AudioFile_SetSizeProc
void * inClientData,
void* inClientData,
SInt64 inSize)
{
return -1; // Writing not supported
}
OSStatus KRAudioSample::WriteProc( // AudioFile_WriteProc
void * inClientData,
void* inClientData,
SInt64 inPosition,
UInt32 requestCount,
const void *buffer,
UInt32 * actualCount)
const void* buffer,
UInt32* actualCount)
{
return -1; // Writing not supported
}
@@ -243,21 +243,21 @@ OSStatus KRAudioSample::WriteProc( // AudioFile_WriteProc
void KRAudioSample::openFile()
{
#ifdef __APPLE__
// Apple Audio Toolbox
// Apple Audio Toolbox
// AudioFileInitializeWithCallbacks
if(m_fileRef == NULL) {
if (m_fileRef == NULL) {
// printf("Call to KRAudioSample::openFile() with extension: %s\n", m_extension.c_str());
// The m_extension is valid (it's either wav or mp3 for the files in Circa project)
// so we can key off the extension and use a different data handler for mp3 files if we want to
//
// printf("Call to KRAudioSample::openFile() with extension: %s\n", m_extension.c_str());
// The m_extension is valid (it's either wav or mp3 for the files in Circa project)
// so we can key off the extension and use a different data handler for mp3 files if we want to
//
// Temp variables
UInt32 propertySize;
// ---- Open audio file ----
assert(AudioFileOpenWithCallbacks((void *)this, ReadProc, WriteProc, GetSizeProc, SetSizeProc, 0, &m_audio_file_id) == noErr);
assert(AudioFileOpenWithCallbacks((void*)this, ReadProc, WriteProc, GetSizeProc, SetSizeProc, 0, &m_audio_file_id) == noErr);
assert(ExtAudioFileWrapAudioFileID(m_audio_file_id, false, &m_fileRef) == noErr);
// ---- Get file format information ----
@@ -287,7 +287,7 @@ void KRAudioSample::openFile()
m_frameRate = outputFormat.mSampleRate;
int maxFramesPerBuffer = KRENGINE_AUDIO_MAX_BUFFER_SIZE / m_bytesPerFrame;
m_bufferCount = (m_totalFrames+maxFramesPerBuffer-1)/maxFramesPerBuffer; // CEIL(_totalFrames / maxFramesPerBuffer)
m_bufferCount = (m_totalFrames + maxFramesPerBuffer - 1) / maxFramesPerBuffer; // CEIL(_totalFrames / maxFramesPerBuffer)
m_channelsPerFrame = outputFormat.mChannelsPerFrame;
@@ -302,12 +302,12 @@ void KRAudioSample::closeFile()
{
#ifdef __APPLE__
// Apple Audio Toolbox
if(m_fileRef) {
if (m_fileRef) {
ExtAudioFileDispose(m_fileRef);
m_fileRef = NULL;
}
if(m_audio_file_id) {
if (m_audio_file_id) {
AudioFileClose(m_audio_file_id);
m_audio_file_id = 0;
}
@@ -318,7 +318,7 @@ void KRAudioSample::closeFile()
void KRAudioSample::loadInfo()
{
if(m_frameRate == 0) {
if (m_frameRate == 0) {
openFile();
closeFile();
}
@@ -329,7 +329,7 @@ std::string KRAudioSample::getExtension()
return m_extension;
}
bool KRAudioSample::save(KRDataBlock &data)
bool KRAudioSample::save(KRDataBlock& data)
{
data.append(*m_pData);
return true;
@@ -347,7 +347,7 @@ int KRAudioSample::getBufferCount()
return m_bufferCount;
}
void KRAudioSample::PopulateBuffer(KRAudioSample *sound, int index, void *data)
void KRAudioSample::PopulateBuffer(KRAudioSample* sound, int index, void* data)
{
int maxFramesPerBuffer = KRENGINE_AUDIO_MAX_BUFFER_SIZE / sound->m_bytesPerFrame;
int startFrame = index * maxFramesPerBuffer;
@@ -367,7 +367,7 @@ void KRAudioSample::PopulateBuffer(KRAudioSample *sound, int index, void *data)
#endif
}
KRAudioBuffer *KRAudioSample::getBuffer(int index)
KRAudioBuffer* KRAudioSample::getBuffer(int index)
{
openFile();
@@ -375,10 +375,10 @@ KRAudioBuffer *KRAudioSample::getBuffer(int index)
int startFrame = index * maxFramesPerBuffer;
__uint32_t frameCount = (__uint32_t)KRMIN(m_totalFrames - startFrame, maxFramesPerBuffer);
KRAudioBuffer *buffer = new KRAudioBuffer(getContext().getAudioManager(), this, index, frameCount, m_frameRate, m_bytesPerFrame, PopulateBuffer);
KRAudioBuffer* buffer = new KRAudioBuffer(getContext().getAudioManager(), this, index, frameCount, m_frameRate, m_bytesPerFrame, PopulateBuffer);
if(m_bufferCount == 1) {
// [self closeFile]; // We don't need to hold on to a file handle if not streaming
if (m_bufferCount == 1) {
// [self closeFile]; // We don't need to hold on to a file handle if not streaming
}
return buffer;
}
@@ -387,7 +387,7 @@ void KRAudioSample::_endFrame()
{
const __int64_t AUDIO_SAMPLE_EXPIRY_FRAMES = 500;
__int64_t current_frame = getContext().getAudioManager()->getAudioFrame();
if(current_frame > m_last_frame_used + AUDIO_SAMPLE_EXPIRY_FRAMES) {
if (current_frame > m_last_frame_used + AUDIO_SAMPLE_EXPIRY_FRAMES) {
closeFile();
}
}

View File

@@ -38,26 +38,27 @@
class KRAudioBuffer;
class KRAudioSample : public KRResource {
class KRAudioSample : public KRResource
{
public:
KRAudioSample(KRContext &context, std::string name, std::string extension);
KRAudioSample(KRContext &context, std::string name, std::string extension, KRDataBlock *data);
KRAudioSample(KRContext& context, std::string name, std::string extension);
KRAudioSample(KRContext& context, std::string name, std::string extension, KRDataBlock* data);
virtual ~KRAudioSample();
virtual std::string getExtension();
virtual bool save(KRDataBlock &data);
virtual bool save(KRDataBlock& data);
float getDuration();
KRAudioBuffer *getBuffer(int index);
KRAudioBuffer* getBuffer(int index);
int getBufferCount();
// Siren audio engine interface
int getChannelCount();
__int64_t getFrameCount();
float sample(int frame_offset, int frame_rate, int channel);
void sample(__int64_t frame_offset, int frame_count, int channel, float *buffer, float amplitude, bool loop);
void sample(__int64_t frame_offset, int frame_count, int channel, float* buffer, float amplitude, bool loop);
void _endFrame();
private:
@@ -65,7 +66,7 @@ private:
__int64_t m_last_frame_used;
std::string m_extension;
KRDataBlock *m_pData;
KRDataBlock* m_pData;
#ifdef __APPLE__
// Apple Audio Toolbox
@@ -73,25 +74,25 @@ private:
ExtAudioFileRef m_fileRef;
static OSStatus ReadProc( // AudioFile_ReadProc
void * inClientData,
void* inClientData,
SInt64 inPosition,
UInt32 requestCount,
void * buffer,
UInt32 * actualCount);
void* buffer,
UInt32* actualCount);
static OSStatus WriteProc( // AudioFile_WriteProc
void * inClientData,
void* inClientData,
SInt64 inPosition,
UInt32 requestCount,
const void *buffer,
UInt32 * actualCount);
const void* buffer,
UInt32* actualCount);
static SInt64 GetSizeProc( // AudioFile_GetSizeProc
void * inClientData);
void* inClientData);
static OSStatus SetSizeProc( // AudioFile_SetSizeProc
void * inClientData,
void* inClientData,
SInt64 inSize);
#endif
@@ -106,5 +107,5 @@ private:
void closeFile();
void loadInfo();
static void PopulateBuffer(KRAudioSample *sound, int index, void *data);
static void PopulateBuffer(KRAudioSample* sound, int index, void* data);
};

View File

@@ -51,7 +51,7 @@ void KRAudioSource::InitNodeInfo(KrNodeInfo* nodeInfo)
nodeInfo->audio_source.sample = -1;
}
KRAudioSource::KRAudioSource(KRScene &scene, std::string name) : KRNode(scene, name)
KRAudioSource::KRAudioSource(KRScene& scene, std::string name) : KRNode(scene, name)
{
m_currentBufferFrame = 0;
m_playing = false;
@@ -74,19 +74,20 @@ KRAudioSource::KRAudioSource(KRScene &scene, std::string name) : KRNode(scene, n
KRAudioSource::~KRAudioSource()
{
while(m_audioBuffers.size()) {
while (m_audioBuffers.size()) {
delete m_audioBuffers.front();
m_audioBuffers.pop();
}
}
std::string KRAudioSource::getElementName() {
std::string KRAudioSource::getElementName()
{
return "audio_source";
}
tinyxml2::XMLElement *KRAudioSource::saveXML( tinyxml2::XMLNode *parent)
tinyxml2::XMLElement* KRAudioSource::saveXML(tinyxml2::XMLNode* parent)
{
tinyxml2::XMLElement *e = KRNode::saveXML(parent);
tinyxml2::XMLElement* e = KRNode::saveXML(parent);
e->SetAttribute("sample", m_audio_sample_name.c_str());
e->SetAttribute("gain", m_gain);
e->SetAttribute("pitch", m_pitch);
@@ -100,59 +101,59 @@ tinyxml2::XMLElement *KRAudioSource::saveXML( tinyxml2::XMLNode *parent)
return e;
}
void KRAudioSource::loadXML(tinyxml2::XMLElement *e)
void KRAudioSource::loadXML(tinyxml2::XMLElement* e)
{
m_audio_sample_name = e->Attribute("sample");
float gain = 1.0f;
if(e->QueryFloatAttribute("gain", &gain) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("gain", &gain) != tinyxml2::XML_SUCCESS) {
gain = 1.0f;
}
setGain(gain);
float pitch = 1.0f;
if(e->QueryFloatAttribute("pitch", &pitch) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("pitch", &pitch) != tinyxml2::XML_SUCCESS) {
pitch = 1.0f;
}
setPitch(m_pitch);
bool looping = false;
if(e->QueryBoolAttribute("looping", &looping) != tinyxml2::XML_SUCCESS) {
if (e->QueryBoolAttribute("looping", &looping) != tinyxml2::XML_SUCCESS) {
looping = false;
}
setLooping(looping);
bool is3d = true;
if(e->QueryBoolAttribute("is3d", &is3d) != tinyxml2::XML_SUCCESS) {
if (e->QueryBoolAttribute("is3d", &is3d) != tinyxml2::XML_SUCCESS) {
is3d = true;
}
setIs3D(is3d);
float reference_distance = 1.0f;
if(e->QueryFloatAttribute("reference_distance", &reference_distance) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("reference_distance", &reference_distance) != tinyxml2::XML_SUCCESS) {
reference_distance = 1.0f;
}
setReferenceDistance(reference_distance);
float reverb = 0.0f;
if(e->QueryFloatAttribute("reverb", &reverb) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("reverb", &reverb) != tinyxml2::XML_SUCCESS) {
reverb = 0.0f;
}
setReverb(reverb);
float rolloff_factor = 2.0f;
if(e->QueryFloatAttribute("rolloff_factor", &rolloff_factor) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("rolloff_factor", &rolloff_factor) != tinyxml2::XML_SUCCESS) {
rolloff_factor = 2.0f;
}
setRolloffFactor(rolloff_factor);
m_enable_obstruction = true;
if(e->QueryBoolAttribute("enable_obstruction", &m_enable_obstruction) != tinyxml2::XML_SUCCESS) {
if (e->QueryBoolAttribute("enable_obstruction", &m_enable_obstruction) != tinyxml2::XML_SUCCESS) {
m_enable_obstruction = true;
}
m_enable_occlusion = true;
if(e->QueryBoolAttribute("enable_occlusion", &m_enable_occlusion) != tinyxml2::XML_SUCCESS) {
if (e->QueryBoolAttribute("enable_occlusion", &m_enable_occlusion) != tinyxml2::XML_SUCCESS) {
m_enable_occlusion = true;
}
@@ -161,14 +162,14 @@ void KRAudioSource::loadXML(tinyxml2::XMLElement *e)
void KRAudioSource::prime()
{
if(!m_isPrimed) {
if(m_audioFile == NULL && m_audio_sample_name.size() != 0) {
if (!m_isPrimed) {
if (m_audioFile == NULL && m_audio_sample_name.size() != 0) {
m_audioFile = getContext().getAudioManager()->get(m_audio_sample_name);
}
if(m_audioFile) {
if (m_audioFile) {
// Prime the buffer queue
m_nextBufferIndex = 0;
for(int i=0; i < KRENGINE_AUDIO_BUFFERS_PER_SOURCE; i++) {
for (int i = 0; i < KRENGINE_AUDIO_BUFFERS_PER_SOURCE; i++) {
queueBuffer();
}
@@ -179,7 +180,7 @@ void KRAudioSource::prime()
void KRAudioSource::queueBuffer()
{
KRAudioBuffer *buffer = m_audioFile->getBuffer(m_nextBufferIndex);
KRAudioBuffer* buffer = m_audioFile->getBuffer(m_nextBufferIndex);
m_audioBuffers.push(buffer);
m_nextBufferIndex = (m_nextBufferIndex + 1) % m_audioFile->getBufferCount();
}
@@ -187,13 +188,13 @@ void KRAudioSource::queueBuffer()
void KRAudioSource::render(RenderInfo& ri)
{
if(m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
if (m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
KRNode::render(ri);
bool bVisualize = false;
if(ri.renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT && bVisualize) {
if (ri.renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT && bVisualize) {
KRMesh* sphereModel = getContext().getMeshManager()->getMaxLODModel("__sphere");
if (sphereModel) {
Matrix4 sphereModelMatrix = getModelMatrix();
@@ -307,7 +308,7 @@ void KRAudioSource::setIs3D(bool is3D)
void KRAudioSource::advanceBuffer()
{
if(m_audioBuffers.size()) {
if (m_audioBuffers.size()) {
delete m_audioBuffers.front();
m_audioBuffers.pop();
}
@@ -318,7 +319,7 @@ void KRAudioSource::physicsUpdate(float deltaTime)
{
KRNode::physicsUpdate(deltaTime);
KRAudioManager *audioManager = getContext().getAudioManager();
KRAudioManager* audioManager = getContext().getAudioManager();
audioManager->activateAudioSource(this);
}
@@ -328,8 +329,8 @@ void KRAudioSource::play()
// play() does not automatically seek to the beginning of the sample. Call setAudioFrame( 0 ) first if you wish the playback to begin at the start of the audio sample.
// If not set to looping, audio playback ends automatically at the end of the sample
if(!m_playing) {
KRAudioManager *audioManager = getContext().getAudioManager();
if (!m_playing) {
KRAudioManager* audioManager = getContext().getAudioManager();
assert(m_start_audio_frame == -1);
m_start_audio_frame = audioManager->getAudioFrame() - m_paused_audio_frame;
m_paused_audio_frame = -1;
@@ -343,7 +344,7 @@ void KRAudioSource::stop()
// Stop playback of audio. If audio is already stopped, this has no effect.
// If play() is called afterwards, playback will continue at the current audio sample position.
if(m_playing) {
if (m_playing) {
m_paused_audio_frame = getAudioFrame();
m_start_audio_frame = -1;
m_playing = false;
@@ -359,7 +360,7 @@ bool KRAudioSource::isPlaying()
}
void KRAudioSource::setSample(const std::string &sound_name)
void KRAudioSource::setSample(const std::string& sound_name)
{
m_audio_sample_name = sound_name;
}
@@ -369,9 +370,9 @@ std::string KRAudioSource::getSample()
return m_audio_sample_name;
}
KRAudioSample *KRAudioSource::getAudioSample()
KRAudioSample* KRAudioSource::getAudioSample()
{
if(m_audioFile == NULL && m_audio_sample_name.size() != 0) {
if (m_audioFile == NULL && m_audio_sample_name.size() != 0) {
m_audioFile = getContext().getAudioManager()->get(m_audio_sample_name);
}
return m_audioFile;
@@ -381,22 +382,22 @@ void KRAudioSource::advanceFrames(int frame_count)
{
m_currentBufferFrame += frame_count;
KRAudioBuffer *buffer = getBuffer();
while(buffer != NULL && m_currentBufferFrame >= buffer->getFrameCount()) {
KRAudioBuffer* buffer = getBuffer();
while (buffer != NULL && m_currentBufferFrame >= buffer->getFrameCount()) {
m_currentBufferFrame -= buffer->getFrameCount();
advanceBuffer();
buffer = getBuffer();
}
if(buffer == NULL) {
if (buffer == NULL) {
m_currentBufferFrame = 0;
stop();
}
}
KRAudioBuffer *KRAudioSource::getBuffer()
KRAudioBuffer* KRAudioSource::getBuffer()
{
if(m_playing) {
if (m_playing) {
prime();
return m_audioBuffers.front();
} else {
@@ -413,7 +414,7 @@ __int64_t KRAudioSource::getAudioFrame()
{
// Returns the audio playback position in units of integer audio frames.
if(m_playing) {
if (m_playing) {
return getContext().getAudioManager()->getAudioFrame() - m_start_audio_frame;
} else {
return m_paused_audio_frame;
@@ -423,7 +424,7 @@ __int64_t KRAudioSource::getAudioFrame()
void KRAudioSource::setAudioFrame(__int64_t next_frame)
{
// Sets the audio playback position with units of integer audio frames.
if(m_playing) {
if (m_playing) {
m_start_audio_frame = getContext().getAudioManager()->getAudioFrame() - next_frame;
} else {
m_paused_audio_frame = next_frame;
@@ -444,13 +445,13 @@ void KRAudioSource::setAudioTime(float new_position)
setAudioFrame((__int64_t)(new_position * 44100.0f));
}
void KRAudioSource::sample(int frame_count, int channel, float *buffer, float gain)
void KRAudioSource::sample(int frame_count, int channel, float* buffer, float gain)
{
KRAudioSample *source_sample = getAudioSample();
if(source_sample && m_playing) {
KRAudioSample* source_sample = getAudioSample();
if (source_sample && m_playing) {
__int64_t next_frame = getAudioFrame();
source_sample->sample(next_frame, frame_count, channel, buffer, gain, m_looping);
if(!m_looping && next_frame > source_sample->getFrameCount()) {
if (!m_looping && next_frame > source_sample->getFrameCount()) {
stop();
}
} else {

View File

@@ -39,15 +39,16 @@
class KRAudioSample;
class KRAudioBuffer;
class KRAudioSource : public KRNode {
class KRAudioSource : public KRNode
{
public:
static void InitNodeInfo(KrNodeInfo* nodeInfo);
KRAudioSource(KRScene &scene, std::string name);
KRAudioSource(KRScene& scene, std::string name);
virtual ~KRAudioSource();
virtual std::string getElementName();
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual void loadXML(tinyxml2::XMLElement *e);
virtual tinyxml2::XMLElement* saveXML(tinyxml2::XMLNode* parent);
virtual void loadXML(tinyxml2::XMLElement* e);
virtual void physicsUpdate(float deltaTime);
void render(RenderInfo& ri);
@@ -86,10 +87,10 @@ public:
// ---- End: Audio Playback Controls ----
void setSample(const std::string &sound_name);
void setSample(const std::string& sound_name);
std::string getSample();
KRAudioSample *getAudioSample();
KRAudioSample* getAudioSample();
float getGain();
void setGain(float gain);
@@ -121,10 +122,10 @@ public:
// ---- Siren Audio Engine Interface ----
void advanceFrames(int frame_count);
KRAudioBuffer *getBuffer();
KRAudioBuffer* getBuffer();
int getBufferFrame();
void sample(int frame_count, int channel, float *buffer, float gain);
void sample(int frame_count, int channel, float* buffer, float gain);
private:
__int64_t m_start_audio_frame; // Global audio frame that matches the start of the audio sample playback; when paused or not playing, this contains a value of -1
@@ -134,12 +135,12 @@ private:
std::string m_audio_sample_name;
KRAudioSample *m_audioFile;
KRAudioSample* m_audioFile;
unsigned int m_sourceID;
float m_gain;
float m_pitch;
bool m_looping;
std::queue<KRAudioBuffer *> m_audioBuffers;
std::queue<KRAudioBuffer*> m_audioBuffers;
int m_nextBufferIndex;
bool m_playing;
bool m_is3d;

View File

@@ -49,30 +49,30 @@ void KRBehavior::init()
// Note: Subclasses are not expected to call this method
}
KRNode *KRBehavior::getNode() const
KRNode* KRBehavior::getNode() const
{
return __node;
}
void KRBehavior::__setNode(KRNode *node)
void KRBehavior::__setNode(KRNode* node)
{
__node = node;
}
KRBehavior *KRBehavior::LoadXML(KRNode *node, tinyxml2::XMLElement *e)
KRBehavior* KRBehavior::LoadXML(KRNode* node, tinyxml2::XMLElement* e)
{
std::map<std::string, std::string> attributes;
for(const tinyxml2::XMLAttribute *attribute = e->FirstAttribute(); attribute != NULL; attribute = attribute->Next()) {
for (const tinyxml2::XMLAttribute* attribute = e->FirstAttribute(); attribute != NULL; attribute = attribute->Next()) {
attributes[attribute->Name()] = attribute->Value();
}
const char *szElementName = e->Attribute("type");
if(szElementName == NULL) {
const char* szElementName = e->Attribute("type");
if (szElementName == NULL) {
return NULL;
}
KRBehaviorFactoryFunctionMap::const_iterator itr = m_factoryFunctions.find(szElementName);
if(itr == m_factoryFunctions.end()) {
if (itr == m_factoryFunctions.end()) {
return NULL;
}
return (*itr->second)(attributes);

View File

@@ -46,7 +46,7 @@ namespace tinyxml2 {
class XMLElement;
} // namespace tinyxml2
typedef KRBehavior *(*KRBehaviorFactoryFunction)(std::map<std::string, std::string> attributes);
typedef KRBehavior* (*KRBehaviorFactoryFunction)(std::map<std::string, std::string> attributes);
typedef std::map<std::string, KRBehaviorFactoryFunction> KRBehaviorFactoryFunctionMap;
class KRBehavior
@@ -57,14 +57,14 @@ public:
KRBehavior();
virtual ~KRBehavior();
KRNode *getNode() const;
KRNode* getNode() const;
virtual void init();
virtual void update(float deltaTime) = 0;
virtual void visibleUpdate(float deltatime) = 0;
void __setNode(KRNode *node);
void __setNode(KRNode* node);
static KRBehavior *LoadXML(KRNode *node, tinyxml2::XMLElement *e);
static KRBehavior* LoadXML(KRNode* node, tinyxml2::XMLElement* e);
private:
KRNode *__node;
KRNode* __node;
};

View File

@@ -39,45 +39,46 @@ void KRBone::InitNodeInfo(KrNodeInfo* nodeInfo)
// No additional members
}
KRBone::KRBone(KRScene &scene, std::string name) : KRNode(scene, name)
KRBone::KRBone(KRScene& scene, std::string name) : KRNode(scene, name)
{
setScaleCompensation(true);
}
KRBone::~KRBone()
{
}
{}
std::string KRBone::getElementName() {
std::string KRBone::getElementName()
{
return "bone";
}
tinyxml2::XMLElement *KRBone::saveXML( tinyxml2::XMLNode *parent)
tinyxml2::XMLElement* KRBone::saveXML(tinyxml2::XMLNode* parent)
{
tinyxml2::XMLElement *e = KRNode::saveXML(parent);
tinyxml2::XMLElement* e = KRNode::saveXML(parent);
return e;
}
void KRBone::loadXML(tinyxml2::XMLElement *e)
void KRBone::loadXML(tinyxml2::XMLElement* e)
{
KRNode::loadXML(e);
setScaleCompensation(true);
}
AABB KRBone::getBounds() {
AABB KRBone::getBounds()
{
return AABB::Create(-Vector3::One(), Vector3::One(), getModelMatrix()); // Only required for bone debug visualization
}
void KRBone::render(RenderInfo& ri)
{
if(m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
if (m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
KRNode::render(ri);
bool bVisualize = ri.camera->settings.debug_display == KRRenderSettings::KRENGINE_DEBUG_DISPLAY_BONES;
if(ri.renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT && bVisualize) {
if (ri.renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT && bVisualize) {
KRMesh* sphereModel = getContext().getMeshManager()->getMaxLODModel("__sphere");
if (sphereModel) {
Matrix4 sphereModelMatrix = getModelMatrix();
@@ -94,7 +95,7 @@ void KRBone::render(RenderInfo& ri)
info.modelFormat = sphereModel->getModelFormat();
info.vertexAttributes = sphereModel->getVertexAttributes();
KRPipeline *pShader = getContext().getPipelineManager()->getPipeline(*ri.surface, info);
KRPipeline* pShader = getContext().getPipelineManager()->getPipeline(*ri.surface, info);
pShader->bind(ri.commandBuffer, *ri.camera, ri.viewport, sphereModelMatrix, &ri.point_lights, &ri.directional_lights, &ri.spot_lights, ri.renderPass);
sphereModel->renderNoMaterials(ri.commandBuffer, ri.renderPass, getName(), "visualize_overlay", 1.0f);
@@ -103,11 +104,11 @@ void KRBone::render(RenderInfo& ri)
}
void KRBone::setBindPose(const Matrix4 &pose)
void KRBone::setBindPose(const Matrix4& pose)
{
m_bind_pose = pose;
}
const Matrix4 &KRBone::getBindPose()
const Matrix4& KRBone::getBindPose()
{
return m_bind_pose;
}

View File

@@ -37,21 +37,22 @@
class RenderInfo;
class KRBone : public KRNode {
class KRBone : public KRNode
{
public:
static void InitNodeInfo(KrNodeInfo* nodeInfo);
KRBone(KRScene &scene, std::string name);
KRBone(KRScene& scene, std::string name);
virtual ~KRBone();
virtual std::string getElementName();
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual void loadXML(tinyxml2::XMLElement *e);
virtual tinyxml2::XMLElement* saveXML(tinyxml2::XMLNode* parent);
virtual void loadXML(tinyxml2::XMLElement* e);
virtual AABB getBounds();
void render(RenderInfo& ri);
void setBindPose(const Matrix4 &pose);
const Matrix4 &getBindPose();
void setBindPose(const Matrix4& pose);
const Matrix4& getBindPose();
private:
Matrix4 m_bind_pose;
};

View File

@@ -49,26 +49,26 @@ typedef struct _tar_header
} tar_header_type;
KRBundle::KRBundle(KRContext &context, std::string name, KRDataBlock *pData) : KRResource(context, name)
KRBundle::KRBundle(KRContext& context, std::string name, KRDataBlock* pData) : KRResource(context, name)
{
m_pData = pData;
__int64_t file_pos = 0;
while(file_pos < (__int64_t)m_pData->getSize()) {
while (file_pos < (__int64_t)m_pData->getSize()) {
tar_header_type file_header;
m_pData->copy(&file_header, (int)file_pos, sizeof(file_header));
size_t file_size = strtol(file_header.file_size, NULL, 8);
file_pos += 512; // Skip past the header to the file contents
if(file_header.file_name[0] != '\0' && file_header.file_name[0] != '.') {
if (file_header.file_name[0] != '\0' && file_header.file_name[0] != '.') {
// We ignore the last two records in the tar file, which are zero'ed out tar_header structures
KRDataBlock *pFileData = pData->getSubBlock((int)file_pos, (int)file_size);
KRDataBlock* pFileData = pData->getSubBlock((int)file_pos, (int)file_size);
context.loadResource(file_header.file_name, pFileData);
}
file_pos += RoundUpSize(file_size);
}
}
KRBundle::KRBundle(KRContext &context, std::string name) : KRResource(context, name)
KRBundle::KRBundle(KRContext& context, std::string name) : KRResource(context, name)
{
// Create an empty krbundle (tar) file, initialized with two zero-ed out file headers, which terminate it.
m_pData = new KRDataBlock();
@@ -81,7 +81,7 @@ KRBundle::KRBundle(KRContext &context, std::string name) : KRResource(context, n
size_t KRBundle::RoundUpSize(size_t s)
{
// Get amount of padding needed to increase s to a 512 byte alignment
if((s & 0x01ff) == 0) {
if ((s & 0x01ff) == 0) {
// file size is a multiple of 512 bytes, we can just add it
return s;
} else {
@@ -106,15 +106,16 @@ bool KRBundle::save(const std::string& path)
return m_pData->save(path);
}
bool KRBundle::save(KRDataBlock &data) {
if(m_pData->getSize() > KRENGINE_KRBUNDLE_HEADER_SIZE * 2) {
bool KRBundle::save(KRDataBlock& data)
{
if (m_pData->getSize() > KRENGINE_KRBUNDLE_HEADER_SIZE * 2) {
// Only output krbundles that contain files
data.append(*m_pData);
}
return true;
}
KRDataBlock* KRBundle::append(KRResource &resource)
KRDataBlock* KRBundle::append(KRResource& resource)
{
// Serialize resource to binary representation
KRDataBlock resource_data;
@@ -130,18 +131,18 @@ KRDataBlock* KRBundle::append(KRResource &resource)
m_pData->lock();
// Get location of file header
tar_header_type *file_header = (tar_header_type *)((unsigned char *)m_pData->getEnd() - padding_size - resource_data.getSize() - KRENGINE_KRBUNDLE_HEADER_SIZE);
tar_header_type* file_header = (tar_header_type*)((unsigned char*)m_pData->getEnd() - padding_size - resource_data.getSize() - KRENGINE_KRBUNDLE_HEADER_SIZE);
// Zero out new file header
memset(file_header, 0, KRENGINE_KRBUNDLE_HEADER_SIZE);
// Copy resource data
resource_data.lock();
memcpy((unsigned char *)m_pData->getEnd() - padding_size - resource_data.getSize(), resource_data.getStart(), resource_data.getSize());
memcpy((unsigned char*)m_pData->getEnd() - padding_size - resource_data.getSize(), resource_data.getStart(), resource_data.getSize());
resource_data.unlock();
// Zero out alignment padding and terminating set of file header blocks
memset((unsigned char *)m_pData->getEnd() - padding_size, 0, padding_size);
memset((unsigned char*)m_pData->getEnd() - padding_size, 0, padding_size);
// Populate new file header fields
strncpy(file_header->file_name, file_name.c_str(), 100);
@@ -156,14 +157,14 @@ KRDataBlock* KRBundle::append(KRResource &resource)
// Calculate and write checksum for header
memset(file_header->checksum, ' ', 8); // Must be filled with spaces and no null terminator during checksum calculation
int check_sum = 0;
for(int i=0; i < KRENGINE_KRBUNDLE_HEADER_SIZE; i++) {
unsigned char *byte_ptr = (unsigned char *)file_header;
for (int i = 0; i < KRENGINE_KRBUNDLE_HEADER_SIZE; i++) {
unsigned char* byte_ptr = (unsigned char*)file_header;
check_sum += byte_ptr[i];
}
sprintf(file_header->checksum, "%07o", check_sum);
m_pData->unlock();
KRDataBlock *pFileData = m_pData->getSubBlock((int)resource_data_start, (int)resource_data.getSize());
KRDataBlock* pFileData = m_pData->getSubBlock((int)resource_data_start, (int)resource_data.getSize());
return pFileData;
}

View File

@@ -34,18 +34,19 @@
#include "KRResource.h"
#include "KRDataBlock.h"
class KRBundle : public KRResource {
class KRBundle : public KRResource
{
public:
KRBundle(KRContext &context, std::string name, KRDataBlock *pData);
KRBundle(KRContext &context, std::string name);
KRBundle(KRContext& context, std::string name, KRDataBlock* pData);
KRBundle(KRContext& context, std::string name);
virtual ~KRBundle();
virtual std::string getExtension();
virtual bool save(const std::string& path);
virtual bool save(KRDataBlock &data);
virtual bool save(KRDataBlock& data);
KRDataBlock* append(KRResource &resource);
KRDataBlock* append(KRResource& resource);
private:
KRDataBlock *m_pData;
KRDataBlock* m_pData;
static size_t RoundUpSize(size_t s);
};

View File

@@ -33,12 +33,14 @@
#include "KRBundle.h"
KRBundleManager::KRBundleManager(KRContext &context) : KRResourceManager(context) {
KRBundleManager::KRBundleManager(KRContext& context) : KRResourceManager(context)
{
}
KRBundleManager::~KRBundleManager() {
for(unordered_map<std::string, KRBundle *>::iterator itr = m_bundles.begin(); itr != m_bundles.end(); ++itr){
KRBundleManager::~KRBundleManager()
{
for (unordered_map<std::string, KRBundle*>::iterator itr = m_bundles.begin(); itr != m_bundles.end(); ++itr) {
delete (*itr).second;
}
m_bundles.clear();
@@ -47,7 +49,7 @@ KRBundleManager::~KRBundleManager() {
KRResource* KRBundleManager::loadResource(const std::string& name, const std::string& extension, KRDataBlock* data)
{
if (extension.compare("krbundle") == 0) {
return loadBundle(name.c_str() , data);
return loadBundle(name.c_str(), data);
}
return nullptr;
}
@@ -59,25 +61,27 @@ KRResource* KRBundleManager::getResource(const std::string& name, const std::str
return nullptr;
}
KRBundle *KRBundleManager::loadBundle(const char *szName, KRDataBlock *pData)
KRBundle* KRBundleManager::loadBundle(const char* szName, KRDataBlock* pData)
{
KRBundle *pBundle = new KRBundle(*m_pContext, szName, pData);
KRBundle* pBundle = new KRBundle(*m_pContext, szName, pData);
m_bundles[szName] = pBundle;
return pBundle;
}
KRBundle *KRBundleManager::createBundle(const char *szName)
KRBundle* KRBundleManager::createBundle(const char* szName)
{
// TODO: Check for name conflicts
KRBundle *pBundle = new KRBundle(*m_pContext, szName);
KRBundle* pBundle = new KRBundle(*m_pContext, szName);
m_bundles[szName] = pBundle;
return pBundle;
}
KRBundle *KRBundleManager::getBundle(const char *szName) {
KRBundle* KRBundleManager::getBundle(const char* szName)
{
return m_bundles[szName];
}
unordered_map<std::string, KRBundle *> KRBundleManager::getBundles() {
unordered_map<std::string, KRBundle*> KRBundleManager::getBundles()
{
return m_bundles;
}

View File

@@ -40,21 +40,22 @@
class KRContext;
class KRBundle;
class KRBundleManager : public KRResourceManager {
class KRBundleManager : public KRResourceManager
{
public:
KRBundleManager(KRContext &context);
KRBundleManager(KRContext& context);
~KRBundleManager();
virtual KRResource* loadResource(const std::string& name, const std::string& extension, KRDataBlock* data) override;
virtual KRResource* getResource(const std::string& name, const std::string& extension) override;
KRBundle *loadBundle(const char *szName, KRDataBlock *pData);
KRBundle *getBundle(const char *szName);
KRBundle* loadBundle(const char* szName, KRDataBlock* pData);
KRBundle* getBundle(const char* szName);
KRBundle* createBundle(const char* szName);
std::vector<std::string> getBundleNames();
unordered_map<std::string, KRBundle *> getBundles();
unordered_map<std::string, KRBundle*> getBundles();
private:
unordered_map<std::string, KRBundle *> m_bundles;
unordered_map<std::string, KRBundle*> m_bundles;
};

View File

@@ -42,7 +42,8 @@ void KRCamera::InitNodeInfo(KrNodeInfo* nodeInfo)
nodeInfo->camera.skybox_texture = -1;
}
KRCamera::KRCamera(KRScene &scene, std::string name) : KRNode(scene, name) {
KRCamera::KRCamera(KRScene& scene, std::string name) : KRNode(scene, name)
{
m_last_frame_start = 0;
m_particlesAbsoluteTime = 0.0f;
@@ -70,31 +71,33 @@ KRCamera::KRCamera(KRScene &scene, std::string name) : KRNode(scene, name) {
);
}
KRCamera::~KRCamera() {
KRCamera::~KRCamera()
{
destroyBuffers();
}
std::string KRCamera::getElementName() {
std::string KRCamera::getElementName()
{
return "camera";
}
tinyxml2::XMLElement *KRCamera::saveXML( tinyxml2::XMLNode *parent)
tinyxml2::XMLElement* KRCamera::saveXML(tinyxml2::XMLNode* parent)
{
tinyxml2::XMLElement *e = KRNode::saveXML(parent);
tinyxml2::XMLElement* e = KRNode::saveXML(parent);
e->SetAttribute("skybox", m_skyBox.c_str());
return e;
}
void KRCamera::loadXML(tinyxml2::XMLElement *e)
void KRCamera::loadXML(tinyxml2::XMLElement* e)
{
KRNode::loadXML(e);
const char *szSkyBoxName = e->Attribute("skybox");
const char* szSkyBoxName = e->Attribute("skybox");
m_skyBox = szSkyBoxName ? szSkyBoxName : "";
}
void KRCamera::setSkyBox(const std::string &skyBox)
void KRCamera::setSkyBox(const std::string& skyBox)
{
m_pSkyBoxTexture = NULL;
m_skyBox = skyBox;
@@ -110,15 +113,15 @@ void KRCamera::renderFrame(VkCommandBuffer& commandBuffer, KRSurface& compositeS
{
// ----====---- Record timing information for measuring FPS ----====----
uint64_t current_time = m_pContext->getAbsoluteTimeMilliseconds();
if(m_last_frame_start != 0) {
if (m_last_frame_start != 0) {
m_frame_times[m_pContext->getCurrentFrame() % KRAKEN_FPS_AVERAGE_FRAME_COUNT] = (int)(current_time - m_last_frame_start);
if(m_frame_times_filled < KRAKEN_FPS_AVERAGE_FRAME_COUNT) m_frame_times_filled++;
if (m_frame_times_filled < KRAKEN_FPS_AVERAGE_FRAME_COUNT) m_frame_times_filled++;
}
m_last_frame_start = current_time;
createBuffers(compositeSurface.getWidth(), compositeSurface.getHeight());
KRScene &scene = getScene();
KRScene& scene = getScene();
Matrix4 modelMatrix = getModelMatrix();
Matrix4 viewMatrix = Matrix4::LookAt(Matrix4::Dot(modelMatrix, Vector3::Zero()), Matrix4::Dot(modelMatrix, Vector3::Forward()), Vector3::Normalize(Matrix4::DotNoTranslate(modelMatrix, Vector3::Up())));
@@ -140,7 +143,7 @@ void KRCamera::renderFrame(VkCommandBuffer& commandBuffer, KRSurface& compositeS
scene.render(commandBuffer, compositeSurface, this, m_viewport.getVisibleBounds(), m_viewport, KRNode::RENDER_PASS_PRESTREAM, true);
// ----====---- Generate Shadowmaps for Lights ----====----
if(settings.m_cShadowBuffers > 0) {
if (settings.m_cShadowBuffers > 0) {
GL_PUSH_GROUP_MARKER("Generate Shadowmaps");
scene.render(commandBuffer, compositeSurface, this, m_viewport.getVisibleBounds(), m_viewport, KRNode::RENDER_PASS_GENERATE_SHADOWMAPS, false /*settings.bEnableDeferredLighting*/);
@@ -148,7 +151,7 @@ void KRCamera::renderFrame(VkCommandBuffer& commandBuffer, KRSurface& compositeS
GL_POP_GROUP_MARKER;
}
if(settings.bEnableDeferredLighting) {
if (settings.bEnableDeferredLighting) {
// ----====---- Opaque Geometry, Deferred rendering Pass 1 ----====----
@@ -251,11 +254,11 @@ void KRCamera::renderFrame(VkCommandBuffer& commandBuffer, KRSurface& compositeS
GL_PUSH_GROUP_MARKER("Sky Box");
if(!m_pSkyBoxTexture && m_skyBox.length()) {
if (!m_pSkyBoxTexture && m_skyBox.length()) {
m_pSkyBoxTexture = getContext().getTextureManager()->getTextureCube(m_skyBox.c_str());
}
if(m_pSkyBoxTexture) {
if (m_pSkyBoxTexture) {
std::string shader_name("sky_box");
PipelineInfo info{};
@@ -307,13 +310,13 @@ void KRCamera::renderFrame(VkCommandBuffer& commandBuffer, KRSurface& compositeS
// ----====---- Volumetric Lighting ----====----
if(settings.volumetric_environment_enable) {
if (settings.volumetric_environment_enable) {
GL_PUSH_GROUP_MARKER("Volumetric Lighting");
KRViewport volumetricLightingViewport = KRViewport(Vector2::Create((float)volumetricBufferWidth, (float)volumetricBufferHeight), m_viewport.getViewMatrix(), m_viewport.getProjectionMatrix());
if(settings.volumetric_environment_downsample != 0) {
if (settings.volumetric_environment_downsample != 0) {
// Set render target
GLDEBUG(glBindFramebuffer(GL_FRAMEBUFFER, volumetricLightAccumulationBuffer));
GLDEBUG(glClearColor(0.0f, 0.0f, 0.0f, 0.0f));
@@ -342,7 +345,7 @@ void KRCamera::renderFrame(VkCommandBuffer& commandBuffer, KRSurface& compositeS
GL_PUSH_GROUP_MARKER("Debug Overlays");
if(settings.debug_display == KRRenderSettings::KRENGINE_DEBUG_DISPLAY_OCTREE) {
if (settings.debug_display == KRRenderSettings::KRENGINE_DEBUG_DISPLAY_OCTREE) {
KRMeshManager::KRVBOData& vertices = getContext().getMeshManager()->KRENGINE_VBO_DATA_3D_CUBE_VERTICES;
PipelineInfo info{};
@@ -353,10 +356,10 @@ void KRCamera::renderFrame(VkCommandBuffer& commandBuffer, KRSurface& compositeS
info.rasterMode = RasterMode::kAdditive;
info.vertexAttributes = vertices.getVertexAttributes();
info.modelFormat = ModelFormat::KRENGINE_MODEL_FORMAT_STRIP;
KRPipeline *pVisShader = getContext().getPipelineManager()->getPipeline(compositeSurface, info);
KRPipeline* pVisShader = getContext().getPipelineManager()->getPipeline(compositeSurface, info);
m_pContext->getMeshManager()->bindVBO(commandBuffer, &vertices, 1.0f);
for(unordered_map<AABB, int>::iterator itr=m_viewport.getVisibleBounds().begin(); itr != m_viewport.getVisibleBounds().end(); itr++) {
for (unordered_map<AABB, int>::iterator itr = m_viewport.getVisibleBounds().begin(); itr != m_viewport.getVisibleBounds().end(); itr++) {
Matrix4 matModel = Matrix4();
matModel.scale((*itr).first.size() * 0.5f);
matModel.translate((*itr).first.center());
@@ -366,7 +369,7 @@ void KRCamera::renderFrame(VkCommandBuffer& commandBuffer, KRSurface& compositeS
}
GL_POP_GROUP_MARKER;
// fprintf(stderr, "VBO Mem: %i Kbyte Texture Mem: %i/%i Kbyte (active/total) Shader Handles: %i Visible Bounds: %i Max Texture LOD: %i\n", (int)m_pContext->getMeshManager()->getMemUsed() / 1024, (int)m_pContext->getTextureManager()->getActiveMemUsed() / 1024, (int)m_pContext->getTextureManager()->getMemUsed() / 1024, (int)m_pContext->getPipelineManager()->getShaderHandlesUsed(), (int)m_visibleBounds.size(), m_pContext->getTextureManager()->getLODDimCap());
// fprintf(stderr, "VBO Mem: %i Kbyte Texture Mem: %i/%i Kbyte (active/total) Shader Handles: %i Visible Bounds: %i Max Texture LOD: %i\n", (int)m_pContext->getMeshManager()->getMemUsed() / 1024, (int)m_pContext->getTextureManager()->getActiveMemUsed() / 1024, (int)m_pContext->getTextureManager()->getMemUsed() / 1024, (int)m_pContext->getPipelineManager()->getShaderHandlesUsed(), (int)m_visibleBounds.size(), m_pContext->getTextureManager()->getLODDimCap());
GL_PUSH_GROUP_MARKER("Post Processing");
@@ -376,7 +379,8 @@ void KRCamera::renderFrame(VkCommandBuffer& commandBuffer, KRSurface& compositeS
}
void KRCamera::createBuffers(GLint renderBufferWidth, GLint renderBufferHeight) {
void KRCamera::createBuffers(GLint renderBufferWidth, GLint renderBufferHeight)
{
// TODO - Vulkan Refactoring..
/*
if(renderBufferWidth != m_backingWidth || renderBufferHeight != m_backingHeight) {
@@ -567,37 +571,37 @@ void KRCamera::renderPost(VkCommandBuffer& commandBuffer, KRSurface& surface)
*/
// if(bShowShadowBuffer) {
// KRPipeline *blitShader = m_pContext->getPipelineManager()->getShader("simple_blit", this, false, false, false, 0, false, false, false, false, false, false, false, false, false, false, false, false, false, KRNode::RENDER_PASS_FORWARD_TRANSPARENT);
//
// for(int iShadow=0; iShadow < m_cShadowBuffers; iShadow++) {
// Matrix4 viewMatrix = Matrix4();
// viewMatrix.scale(0.20, 0.20, 0.20);
// viewMatrix.translate(-0.70, 0.70 - 0.45 * iShadow, 0.0);
// getContext().getPipelineManager()->selectShader(blitShader, KRViewport(getViewportSize(), viewMatrix, Matrix4()), shadowViewports, Matrix4(), Vector3(), NULL, 0, KRNode::RENDER_PASS_FORWARD_TRANSPARENT);
// m_pContext->getTextureManager()->selectTexture(1, NULL);
// m_pContext->getMeshManager()->bindVBO(&getContext().getMeshManager()->KRENGINE_VBO_DATA_2D_SQUARE_VERTICES);
// m_pContext->getTextureManager()->_setActiveTexture(0);
// GLDEBUG(glBindTexture(GL_TEXTURE_2D, shadowDepthTexture[iShadow]));
//#if GL_EXT_shadow_samplers
// GLDEBUG(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_EXT, GL_NONE)); // TODO - Detect GL_EXT_shadow_samplers and only activate if available
//#endif
// GLDEBUG(glDrawArrays(GL_TRIANGLE_STRIP, 0, 4));
//#if GL_EXT_shadow_samplers
// GLDEBUG(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_EXT, GL_COMPARE_REF_TO_TEXTURE_EXT)); // TODO - Detect GL_EXT_shadow_samplers and only activate if available
//#endif
// }
//
// m_pContext->getTextureManager()->selectTexture(0, NULL);
// m_pContext->getTextureManager()->_setActiveTexture(0);
// GLDEBUG(glBindTexture(GL_TEXTURE_2D, 0));
// }
const char *szText = settings.m_debug_text.c_str();
// if(bShowShadowBuffer) {
// KRPipeline *blitShader = m_pContext->getPipelineManager()->getShader("simple_blit", this, false, false, false, 0, false, false, false, false, false, false, false, false, false, false, false, false, false, KRNode::RENDER_PASS_FORWARD_TRANSPARENT);
//
// for(int iShadow=0; iShadow < m_cShadowBuffers; iShadow++) {
// Matrix4 viewMatrix = Matrix4();
// viewMatrix.scale(0.20, 0.20, 0.20);
// viewMatrix.translate(-0.70, 0.70 - 0.45 * iShadow, 0.0);
// getContext().getPipelineManager()->selectShader(blitShader, KRViewport(getViewportSize(), viewMatrix, Matrix4()), shadowViewports, Matrix4(), Vector3(), NULL, 0, KRNode::RENDER_PASS_FORWARD_TRANSPARENT);
// m_pContext->getTextureManager()->selectTexture(1, NULL);
// m_pContext->getMeshManager()->bindVBO(&getContext().getMeshManager()->KRENGINE_VBO_DATA_2D_SQUARE_VERTICES);
// m_pContext->getTextureManager()->_setActiveTexture(0);
// GLDEBUG(glBindTexture(GL_TEXTURE_2D, shadowDepthTexture[iShadow]));
//#if GL_EXT_shadow_samplers
// GLDEBUG(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_EXT, GL_NONE)); // TODO - Detect GL_EXT_shadow_samplers and only activate if available
//#endif
// GLDEBUG(glDrawArrays(GL_TRIANGLE_STRIP, 0, 4));
//#if GL_EXT_shadow_samplers
// GLDEBUG(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_EXT, GL_COMPARE_REF_TO_TEXTURE_EXT)); // TODO - Detect GL_EXT_shadow_samplers and only activate if available
//#endif
// }
//
// m_pContext->getTextureManager()->selectTexture(0, NULL);
// m_pContext->getTextureManager()->_setActiveTexture(0);
// GLDEBUG(glBindTexture(GL_TEXTURE_2D, 0));
// }
const char* szText = settings.m_debug_text.c_str();
std::string debug_text;
if(settings.debug_display != KRRenderSettings::KRENGINE_DEBUG_DISPLAY_NONE) {
if (settings.debug_display != KRRenderSettings::KRENGINE_DEBUG_DISPLAY_NONE) {
debug_text = getDebugText();;
if(debug_text.length() > 0) {
if (debug_text.length() > 0) {
szText = debug_text.c_str();
}
}
@@ -605,31 +609,31 @@ void KRCamera::renderPost(VkCommandBuffer& commandBuffer, KRSurface& surface)
// TODO - Test code for Vulkan conversion, remove once texture streaming working
szText = "Hello, earthlings!";
if(*szText) {
if (*szText) {
int row_count = 1;
const int MAX_TABS = 5;
const int TAB_EXTRA = 2;
int tab_cols[MAX_TABS] = {0, 0, 0, 0, 0};
int tab_cols[MAX_TABS] = { 0, 0, 0, 0, 0 };
int iCol = 0;
int iTab = 0;
const char *pChar = szText;
while(*pChar) {
const char* pChar = szText;
while (*pChar) {
char c = *pChar++;
if(c == '\n') {
if (c == '\n') {
row_count++;
iCol = 0;
iTab = 0;
} else if(c == '\t') {
} else if (c == '\t') {
iCol = 0;
iTab++;
} else {
iCol++;
if(iCol > tab_cols[iTab]) tab_cols[iTab] = iCol;
if (iCol > tab_cols[iTab]) tab_cols[iTab] = iCol;
}
}
iCol = 0;
for(iTab=0; iTab < MAX_TABS; iTab++) {
for (iTab = 0; iTab < MAX_TABS; iTab++) {
iCol += tab_cols[iTab] + TAB_EXTRA;
tab_cols[iTab] = iCol;
}
@@ -637,29 +641,29 @@ void KRCamera::renderPost(VkCommandBuffer& commandBuffer, KRSurface& surface)
const int DEBUG_TEXT_COLUMNS = 256;
const int DEBUG_TEXT_ROWS = 128;
if(m_debug_text_vertices.getSize() == 0) {
if (m_debug_text_vertices.getSize() == 0) {
m_debug_text_vertices.expand(sizeof(DebugTextVertexData) * DEBUG_TEXT_COLUMNS * DEBUG_TEXT_ROWS * 6);
}
int vertex_count = 0;
m_debug_text_vertices.lock();
DebugTextVertexData *vertex_data = (DebugTextVertexData *)m_debug_text_vertices.getStart();
DebugTextVertexData* vertex_data = (DebugTextVertexData*)m_debug_text_vertices.getStart();
pChar = szText;
float dScaleX = 2.0f / (1024.0f / 16.0f);
float dScaleY = 2.0f / (768.0f / 16.0f);
float dTexScale = 1.0f / 16.0f;
int iRow = row_count - 1; iCol = 0; iTab = 0;
while(*pChar) {
while (*pChar) {
char c = *pChar++;
if(c == '\n') {
if (c == '\n') {
iCol = 0;
iTab = 0;
iRow--;
} else if(c == '\t') {
} else if (c == '\t') {
iCol = tab_cols[iTab++];
} else {
if(iCol < DEBUG_TEXT_COLUMNS && iRow < DEBUG_TEXT_ROWS) {
if (iCol < DEBUG_TEXT_COLUMNS && iRow < DEBUG_TEXT_ROWS) {
int iChar = c - '\0';
int iTexCol = iChar % 16;
int iTexRow = 15 - (iChar - iTexCol) / 16;
@@ -728,7 +732,7 @@ void KRCamera::renderPost(VkCommandBuffer& commandBuffer, KRSurface& surface)
info.cullMode = CullMode::kCullNone;
info.vertexAttributes = (1 << KRMesh::KRENGINE_ATTRIB_VERTEX) | (1 << KRMesh::KRENGINE_ATTRIB_TEXUVA);
info.modelFormat = ModelFormat::KRENGINE_MODEL_FORMAT_TRIANGLES;
KRPipeline *fontShader = m_pContext->getPipelineManager()->getPipeline(surface, info);
KRPipeline* fontShader = m_pContext->getPipelineManager()->getPipeline(surface, info);
fontShader->bind(commandBuffer, *this, m_viewport, Matrix4(), nullptr, nullptr, nullptr, KRNode::RENDER_PASS_FORWARD_TRANSPARENT);
m_pContext->getTextureManager()->selectTexture(0, m_pContext->getTextureManager()->getTexture("font"), 0.0f, KRTexture::TEXTURE_USAGE_UI);
@@ -741,7 +745,7 @@ void KRCamera::renderPost(VkCommandBuffer& commandBuffer, KRSurface& surface)
m_debug_text_vertices.unlock();
} else {
if(m_debug_text_vertices.getSize() > 0) {
if (m_debug_text_vertices.getSize() > 0) {
m_debug_text_vertices = KRDataBlock();
}
}
@@ -756,20 +760,20 @@ std::string KRCamera::getDebugText()
uint64_t fps = 0;
if(m_frame_times_filled == KRAKEN_FPS_AVERAGE_FRAME_COUNT) {
for(int i=0; i < KRAKEN_FPS_AVERAGE_FRAME_COUNT; i++) {
if (m_frame_times_filled == KRAKEN_FPS_AVERAGE_FRAME_COUNT) {
for (int i = 0; i < KRAKEN_FPS_AVERAGE_FRAME_COUNT; i++) {
fps += m_frame_times[i];
}
fps = 1000000 / (fps / KRAKEN_FPS_AVERAGE_FRAME_COUNT); // Order of division chosen to prevent overflow
}
switch(settings.debug_display) {
switch (settings.debug_display) {
case KRRenderSettings::KRENGINE_DEBUG_DISPLAY_NONE: // ----====---- No debug display ----====----
break;
case KRRenderSettings::KRENGINE_DEBUG_DISPLAY_TIME: // ----====---- Time / FPS ----====----
{
if(fps > 0) {
if (fps > 0) {
stream << "FPS\t" << fps;
}
}
@@ -786,7 +790,7 @@ std::string KRCamera::getDebugText()
TASK_BASIC_INFO,
(task_info_t)&info,
&size);
if( kerr == KERN_SUCCESS ) {
if (kerr == KERN_SUCCESS) {
stream << "\tResident\tVirtual\tTotal";
stream << "\nCPU\t" << (info.resident_size / 1024 / 1024) << " MB\t" << (info.virtual_size / 1024 / 1024) << " MB\t" << ((info.resident_size + info.virtual_size) / 1024 / 1024) << " MB";
} else {
@@ -798,9 +802,9 @@ std::string KRCamera::getDebugText()
mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
vm_size_t pagesize = 0;
vm_statistics_data_t vm_stat;
if(host_page_size(host_port, &pagesize) != KERN_SUCCESS) {
if (host_page_size(host_port, &pagesize) != KERN_SUCCESS) {
stream << "\n\nERROR: Could not get VM page size.";
} else if(host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS) {
} else if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS) {
stream << "\n\nERROR: Could not get VM stats.";
} else {
stream << "\n\n\n\tWired\tActive\tInactive\tFree\tTotal";
@@ -832,7 +836,7 @@ std::string KRCamera::getDebugText()
stream << "\n\n\n\t# Active\t# Used\tActive\tUsed\tThroughput\n";
stream << "Textures\t" << texture_count_active << "\t" << texture_count << "\t" << (texture_mem_active / 1024) << " KB\t" << (texture_mem_used / 1024) << " KB\t" << (texture_mem_throughput / 1024) << " KB / frame\n";
stream << "VBO's\t" << vbo_count_active << "\t" << vbo_count_active << "\t" << (vbo_mem_active / 1024) <<" KB\t" << (vbo_mem_used / 1024) << " KB\t" << (vbo_mem_throughput / 1024) << " KB / frame\n";
stream << "VBO's\t" << vbo_count_active << "\t" << vbo_count_active << "\t" << (vbo_mem_active / 1024) << " KB\t" << (vbo_mem_used / 1024) << " KB\t" << (vbo_mem_throughput / 1024) << " KB / frame\n";
stream << "\nGPU Total\t\t\t" << (total_mem_active / 1024) << " KB\t" << (total_mem_used / 1024) << " KB\t" << (total_mem_throughput / 1024) << " KB / frame";
}
break;
@@ -841,10 +845,10 @@ std::string KRCamera::getDebugText()
{
bool first = true;
int texture_count = 0;
std::set<KRTexture *> active_textures = m_pContext->getTextureManager()->getActiveTextures();
for(std::set<KRTexture *>::iterator itr=active_textures.begin(); itr != active_textures.end(); itr++) {
KRTexture *texture = *itr;
if(first) {
std::set<KRTexture*> active_textures = m_pContext->getTextureManager()->getActiveTextures();
for (std::set<KRTexture*>::iterator itr = active_textures.begin(); itr != active_textures.end(); itr++) {
KRTexture* texture = *itr;
if (first) {
first = false;
} else {
stream << "\n";
@@ -855,7 +859,7 @@ std::string KRCamera::getDebugText()
stream << " KB";
stream << "\t";
stream << texture->getMaxMipMap();
if(texture->hasMipmaps() && texture->getCurrentLodMaxDim() != texture->getMaxMipMap()) {
if (texture->hasMipmaps() && texture->getCurrentLodMaxDim() != texture->getMaxMipMap()) {
stream << " px => ";
stream << texture->getCurrentLodMaxDim();
}
@@ -877,10 +881,10 @@ std::string KRCamera::getDebugText()
long draw_call_count = 0;
long vertex_count = 0;
stream << "\tVerts\tPass\tObject\tMaterial";
for(std::vector<KRMeshManager::draw_call_info>::iterator itr = draw_calls.begin(); itr != draw_calls.end(); itr++) {
for (std::vector<KRMeshManager::draw_call_info>::iterator itr = draw_calls.begin(); itr != draw_calls.end(); itr++) {
draw_call_count++;
stream << "\n" << draw_call_count << "\t" << (*itr).vertex_count << "\t";
switch((*itr).pass) {
switch ((*itr).pass) {
case KRNode::RENDER_PASS_FORWARD_OPAQUE:
stream << "opaq";
break;
@@ -943,7 +947,7 @@ std::string KRCamera::getDebugText()
}
const KRViewport &KRCamera::getViewport() const
const KRViewport& KRCamera::getViewport() const
{
return m_viewport;
}
@@ -959,7 +963,7 @@ void KRCamera::setDownsample(float v)
m_downsample = Vector2::Create(v);
}
void KRCamera::setFadeColor(const Vector4 &fade_color)
void KRCamera::setFadeColor(const Vector4& fade_color)
{
m_fade_color = fade_color;
}

View File

@@ -48,22 +48,23 @@ class KRScene;
class KRViewport;
class KRSurface;
class KRCamera : public KRNode {
class KRCamera : public KRNode
{
public:
static void InitNodeInfo(KrNodeInfo* nodeInfo);
KRCamera(KRScene &scene, std::string name);
KRCamera(KRScene& scene, std::string name);
virtual ~KRCamera();
void renderFrame(VkCommandBuffer& commandBuffer, KRSurface& compositeSurface);
KRRenderSettings settings;
const KRViewport &getViewport() const;
const KRViewport& getViewport() const;
virtual std::string getElementName();
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual void loadXML(tinyxml2::XMLElement *e);
virtual tinyxml2::XMLElement* saveXML(tinyxml2::XMLNode* parent);
virtual void loadXML(tinyxml2::XMLElement* e);
std::string getDebugText();
@@ -71,10 +72,10 @@ public:
Vector2 getDownsample();
void setDownsample(float v);
void setFadeColor(const Vector4 &fade_color);
void setFadeColor(const Vector4& fade_color);
Vector4 getFadeColor();
void setSkyBox(const std::string &skyBox);
void setSkyBox(const std::string& skyBox);
const std::string getSkyBox() const;
private:
@@ -92,7 +93,7 @@ private:
void destroyBuffers();
KRTexture *m_pSkyBoxTexture;
KRTexture* m_pSkyBoxTexture;
std::string m_skyBox;
KRViewport m_viewport;
@@ -102,7 +103,8 @@ private:
Vector4 m_fade_color;
typedef struct {
typedef struct
{
float x;
float y;
float z;
@@ -113,7 +115,7 @@ private:
KRDataBlock m_debug_text_vertices;
KRMeshManager::KRVBOData m_debug_text_vbo_data;
// std::string getDebugText();
// std::string getDebugText();
uint64_t m_last_frame_start;
int m_frame_times[KRAKEN_FPS_AVERAGE_FRAME_COUNT];

View File

@@ -43,79 +43,85 @@ void KRCollider::InitNodeInfo(KrNodeInfo* nodeInfo)
nodeInfo->collider.mesh = -1;
}
KRCollider::KRCollider(KRScene &scene, std::string collider_name, std::string model_name, unsigned int layer_mask, float audio_occlusion) : KRNode(scene, collider_name) {
KRCollider::KRCollider(KRScene& scene, std::string collider_name, std::string model_name, unsigned int layer_mask, float audio_occlusion) : KRNode(scene, collider_name)
{
m_model_name = model_name;
m_layer_mask = layer_mask;
m_audio_occlusion = audio_occlusion;
m_model = nullptr;
}
KRCollider::~KRCollider() {
KRCollider::~KRCollider()
{
}
std::string KRCollider::getElementName() {
std::string KRCollider::getElementName()
{
return "collider";
}
tinyxml2::XMLElement *KRCollider::saveXML( tinyxml2::XMLNode *parent)
tinyxml2::XMLElement* KRCollider::saveXML(tinyxml2::XMLNode* parent)
{
tinyxml2::XMLElement *e = KRNode::saveXML(parent);
tinyxml2::XMLElement* e = KRNode::saveXML(parent);
e->SetAttribute("mesh", m_model_name.c_str());
e->SetAttribute("layer_mask", m_layer_mask);
e->SetAttribute("audio_occlusion", m_audio_occlusion);
return e;
}
void KRCollider::loadXML(tinyxml2::XMLElement *e) {
void KRCollider::loadXML(tinyxml2::XMLElement* e)
{
KRNode::loadXML(e);
m_model_name = e->Attribute("mesh");
m_layer_mask = 65535;
if(e->QueryUnsignedAttribute("layer_mask", &m_layer_mask) != tinyxml2::XML_SUCCESS) {
if (e->QueryUnsignedAttribute("layer_mask", &m_layer_mask) != tinyxml2::XML_SUCCESS) {
m_layer_mask = 65535;
}
m_audio_occlusion = 1.0f;
if(e->QueryFloatAttribute("audio_occlusion", &m_audio_occlusion) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("audio_occlusion", &m_audio_occlusion) != tinyxml2::XML_SUCCESS) {
m_audio_occlusion = 1.0f;
}
}
void KRCollider::loadModel() {
if(m_model == nullptr) {
void KRCollider::loadModel()
{
if (m_model == nullptr) {
m_model = m_pContext->getMeshManager()->getMaxLODModel(m_model_name.c_str());
if(m_model) {
if (m_model) {
getScene().notify_sceneGraphModify(this);
}
}
}
AABB KRCollider::getBounds() {
AABB KRCollider::getBounds()
{
loadModel();
if(m_model) {
if (m_model) {
return AABB::Create(m_model->getMinPoint(), m_model->getMaxPoint(), getModelMatrix());
} else {
return AABB::Infinite();
}
}
bool KRCollider::lineCast(const Vector3 &v0, const Vector3 &v1, HitInfo &hitinfo, unsigned int layer_mask)
bool KRCollider::lineCast(const Vector3& v0, const Vector3& v1, HitInfo& hitinfo, unsigned int layer_mask)
{
if(layer_mask & m_layer_mask ) { // Only test if layer masks have a common bit set
if (layer_mask & m_layer_mask) { // Only test if layer masks have a common bit set
loadModel();
if(m_model) {
if(getBounds().intersectsLine(v0, v1)) {
if (m_model) {
if (getBounds().intersectsLine(v0, v1)) {
Vector3 v0_model_space = Matrix4::Dot(getInverseModelMatrix(), v0);
Vector3 v1_model_space = Matrix4::Dot(getInverseModelMatrix(), v1);
HitInfo hitinfo_model_space;
if(hitinfo.didHit()) {
if (hitinfo.didHit()) {
Vector3 hit_position_model_space = Matrix4::Dot(getInverseModelMatrix(), hitinfo.getPosition());
hitinfo_model_space = HitInfo(hit_position_model_space, Matrix4::DotNoTranslate(getInverseModelMatrix(), hitinfo.getNormal()), (hit_position_model_space - v0_model_space).magnitude(), hitinfo.getNode());
}
if(m_model->lineCast(v0_model_space, v1_model_space, hitinfo_model_space)) {
if (m_model->lineCast(v0_model_space, v1_model_space, hitinfo_model_space)) {
Vector3 hit_position_world_space = Matrix4::Dot(getModelMatrix(), hitinfo_model_space.getPosition());
hitinfo = HitInfo(hit_position_world_space, Vector3::Normalize(Matrix4::DotNoTranslate(getModelMatrix(), hitinfo_model_space.getNormal())), (hit_position_world_space - v0).magnitude(), this);
return true;
@@ -126,21 +132,21 @@ bool KRCollider::lineCast(const Vector3 &v0, const Vector3 &v1, HitInfo &hitinfo
return false;
}
bool KRCollider::rayCast(const Vector3 &v0, const Vector3 &dir, HitInfo &hitinfo, unsigned int layer_mask)
bool KRCollider::rayCast(const Vector3& v0, const Vector3& dir, HitInfo& hitinfo, unsigned int layer_mask)
{
if(layer_mask & m_layer_mask) { // Only test if layer masks have a common bit set
if (layer_mask & m_layer_mask) { // Only test if layer masks have a common bit set
loadModel();
if(m_model) {
if(getBounds().intersectsRay(v0, dir)) {
if (m_model) {
if (getBounds().intersectsRay(v0, dir)) {
Vector3 v0_model_space = Matrix4::Dot(getInverseModelMatrix(), v0);
Vector3 dir_model_space = Vector3::Normalize(Matrix4::DotNoTranslate(getInverseModelMatrix(), dir));
HitInfo hitinfo_model_space;
if(hitinfo.didHit()) {
if (hitinfo.didHit()) {
Vector3 hit_position_model_space = Matrix4::Dot(getInverseModelMatrix(), hitinfo.getPosition());
hitinfo_model_space = HitInfo(hit_position_model_space, Vector3::Normalize(Matrix4::DotNoTranslate(getInverseModelMatrix(), hitinfo.getNormal())), (hit_position_model_space - v0_model_space).magnitude(), hitinfo.getNode());
}
if(m_model->rayCast(v0_model_space, dir_model_space, hitinfo_model_space)) {
if (m_model->rayCast(v0_model_space, dir_model_space, hitinfo_model_space)) {
Vector3 hit_position_world_space = Matrix4::Dot(getModelMatrix(), hitinfo_model_space.getPosition());
hitinfo = HitInfo(hit_position_world_space, Vector3::Normalize(Matrix4::DotNoTranslate(getModelMatrix(), hitinfo_model_space.getNormal())), (hit_position_world_space - v0).magnitude(), this);
return true;
@@ -151,18 +157,18 @@ bool KRCollider::rayCast(const Vector3 &v0, const Vector3 &dir, HitInfo &hitinfo
return false;
}
bool KRCollider::sphereCast(const Vector3 &v0, const Vector3 &v1, float radius, HitInfo &hitinfo, unsigned int layer_mask)
bool KRCollider::sphereCast(const Vector3& v0, const Vector3& v1, float radius, HitInfo& hitinfo, unsigned int layer_mask)
{
if(layer_mask & m_layer_mask) { // Only test if layer masks have a common bit set
if (layer_mask & m_layer_mask) { // Only test if layer masks have a common bit set
loadModel();
if(m_model) {
if (m_model) {
AABB sphereCastBounds = AABB::Create( // TODO - Need to cache this; perhaps encasulate within a "spherecast" class to be passed through these functions
Vector3::Create(KRMIN(v0.x, v1.x) - radius, KRMIN(v0.y, v1.y) - radius, KRMIN(v0.z, v1.z) - radius),
Vector3::Create(KRMAX(v0.x, v1.x) + radius, KRMAX(v0.y, v1.y) + radius, KRMAX(v0.z, v1.z) + radius)
);
if(getBounds().intersects(sphereCastBounds)) {
if(m_model->sphereCast(getModelMatrix(), v0, v1, radius, hitinfo)) {
if (getBounds().intersects(sphereCastBounds)) {
if (m_model->sphereCast(getModelMatrix(), v0, v1, radius, hitinfo)) {
hitinfo = HitInfo(hitinfo.getPosition(), hitinfo.getNormal(), hitinfo.getDistance(), this);
return true;
}
@@ -195,13 +201,13 @@ void KRCollider::setAudioOcclusion(float audio_occlusion)
void KRCollider::render(RenderInfo& ri)
{
if(m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
if (m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
KRNode::render(ri);
if(ri.renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT && ri.camera->settings.debug_display == KRRenderSettings::KRENGINE_DEBUG_DISPLAY_COLLIDERS) {
if (ri.renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT && ri.camera->settings.debug_display == KRRenderSettings::KRENGINE_DEBUG_DISPLAY_COLLIDERS) {
loadModel();
if(m_model) {
if (m_model) {
GL_PUSH_GROUP_MARKER("Debug Overlays");
@@ -217,7 +223,7 @@ void KRCollider::render(RenderInfo& ri)
info.modelFormat = m_model->getModelFormat();
info.vertexAttributes = m_model->getVertexAttributes();
KRPipeline *pShader = getContext().getPipelineManager()->getPipeline(*ri.surface, info);
KRPipeline* pShader = getContext().getPipelineManager()->getPipeline(*ri.surface, info);
pShader->bind(ri.commandBuffer, *ri.camera, ri.viewport, getModelMatrix(), &ri.point_lights, &ri.directional_lights, &ri.spot_lights, ri.renderPass);

View File

@@ -46,22 +46,23 @@
#include "KRMesh.h"
#include "KRTexture.h"
class KRCollider : public KRNode {
class KRCollider : public KRNode
{
public:
static void InitNodeInfo(KrNodeInfo* nodeInfo);
KRCollider(KRScene &scene, std::string collider_name, std::string model_name, unsigned int layer_mask, float audio_occlusion);
KRCollider(KRScene& scene, std::string collider_name, std::string model_name, unsigned int layer_mask, float audio_occlusion);
virtual ~KRCollider();
virtual std::string getElementName();
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual void loadXML(tinyxml2::XMLElement *e);
virtual tinyxml2::XMLElement* saveXML(tinyxml2::XMLNode* parent);
virtual void loadXML(tinyxml2::XMLElement* e);
virtual AABB getBounds();
bool lineCast(const Vector3 &v0, const Vector3 &v1, HitInfo &hitinfo, unsigned int layer_mask);
bool rayCast(const Vector3 &v0, const Vector3 &v1, HitInfo &hitinfo, unsigned int layer_mask);
bool sphereCast(const Vector3 &v0, const Vector3 &v1, float radius, HitInfo &hitinfo, unsigned int layer_mask);
bool lineCast(const Vector3& v0, const Vector3& v1, HitInfo& hitinfo, unsigned int layer_mask);
bool rayCast(const Vector3& v0, const Vector3& v1, HitInfo& hitinfo, unsigned int layer_mask);
bool sphereCast(const Vector3& v0, const Vector3& v1, float radius, HitInfo& hitinfo, unsigned int layer_mask);
unsigned int getLayerMask();
void setLayerMask(unsigned int layer_mask);

View File

@@ -79,15 +79,15 @@ int KRContext::KRENGINE_SYS_PAGE_SIZE;
std::mutex KRContext::g_SurfaceInfoMutex;
std::mutex KRContext::g_DeviceInfoMutex;
KRContext::log_callback *KRContext::s_log_callback = NULL;
void *KRContext::s_log_callback_user_data = NULL;
KRContext::log_callback* KRContext::s_log_callback = NULL;
void* KRContext::s_log_callback_user_data = NULL;
KRContext::KRContext(const KrInitializeInfo* initializeInfo)
: m_resourceMapSize(initializeInfo->resourceMapSize)
{
m_presentationThread = std::make_unique<KRPresentationThread>(*this);
m_streamerThread = std::make_unique<KRStreamerThread>(*this);
m_resourceMap = (KRResource **)malloc(sizeof(KRResource*) * m_resourceMapSize);
m_resourceMap = (KRResource**)malloc(sizeof(KRResource*) * m_resourceMapSize);
memset(m_resourceMap, 0, m_resourceMapSize * sizeof(KRResource*));
m_streamingEnabled = false;
#ifdef __APPLE__
@@ -138,7 +138,8 @@ KRContext::KRContext(const KrInitializeInfo* initializeInfo)
m_streamerThread->start();
}
KRContext::~KRContext() {
KRContext::~KRContext()
{
m_presentationThread->stop();
m_streamerThread->stop();
m_pSceneManager.reset();
@@ -167,7 +168,7 @@ KRContext::~KRContext() {
}
}
void KRContext::SetLogCallback(log_callback *log_callback, void *user_data)
void KRContext::SetLogCallback(log_callback* log_callback, void* user_data)
{
s_log_callback = log_callback;
s_log_callback_user_data = user_data;
@@ -178,13 +179,13 @@ void KRContext::Log(log_level level, const std::string message_format, ...)
va_list args;
va_start(args, message_format);
if(s_log_callback) {
if (s_log_callback) {
const int LOG_BUFFER_SIZE = 32768;
char log_buffer[LOG_BUFFER_SIZE];
vsnprintf(log_buffer, LOG_BUFFER_SIZE, message_format.c_str(), args);
s_log_callback(s_log_callback_user_data, std::string(log_buffer), level);
} else {
FILE *out_file = level == LOG_LEVEL_INFORMATION ? stdout : stderr;
FILE* out_file = level == LOG_LEVEL_INFORMATION ? stdout : stderr;
fprintf(out_file, "Kraken - INFO: ");
vfprintf(out_file, message_format.c_str(), args);
fprintf(out_file, "\n");
@@ -193,91 +194,105 @@ void KRContext::Log(log_level level, const std::string message_format, ...)
va_end(args);
}
KRBundleManager *KRContext::getBundleManager() {
KRBundleManager* KRContext::getBundleManager()
{
return m_pBundleManager.get();
}
KRSceneManager *KRContext::getSceneManager() {
KRSceneManager* KRContext::getSceneManager()
{
return m_pSceneManager.get();
}
KRTextureManager *KRContext::getTextureManager() {
KRTextureManager* KRContext::getTextureManager()
{
return m_pTextureManager.get();
}
KRMaterialManager *KRContext::getMaterialManager() {
KRMaterialManager* KRContext::getMaterialManager()
{
return m_pMaterialManager.get();
}
KRPipelineManager *KRContext::getPipelineManager() {
KRPipelineManager* KRContext::getPipelineManager()
{
return m_pPipelineManager.get();
}
KRMeshManager *KRContext::getMeshManager() {
KRMeshManager* KRContext::getMeshManager()
{
return m_pMeshManager.get();
}
KRAnimationManager *KRContext::getAnimationManager() {
KRAnimationManager* KRContext::getAnimationManager()
{
return m_pAnimationManager.get();
}
KRAnimationCurveManager *KRContext::getAnimationCurveManager() {
KRAnimationCurveManager* KRContext::getAnimationCurveManager()
{
return m_pAnimationCurveManager.get();
}
KRAudioManager *KRContext::getAudioManager() {
KRAudioManager* KRContext::getAudioManager()
{
return m_pSoundManager.get();
}
KRShaderManager *KRContext::getShaderManager() {
KRShaderManager* KRContext::getShaderManager()
{
return m_pShaderManager.get();
}
KRSourceManager *KRContext::getSourceManager() {
KRSourceManager* KRContext::getSourceManager()
{
return m_pSourceManager.get();
}
KRSurfaceManager* KRContext::getSurfaceManager() {
KRSurfaceManager* KRContext::getSurfaceManager()
{
return m_surfaceManager.get();
}
KRDeviceManager* KRContext::getDeviceManager() {
KRDeviceManager* KRContext::getDeviceManager()
{
return m_deviceManager.get();
}
KRUnknownManager *KRContext::getUnknownManager() {
KRUnknownManager* KRContext::getUnknownManager()
{
return m_pUnknownManager.get();
}
std::vector<KRResource *> KRContext::getResources()
std::vector<KRResource*> KRContext::getResources()
{
std::vector<KRResource *> resources;
std::vector<KRResource*> resources;
for(unordered_map<std::string, KRScene *>::iterator itr = m_pSceneManager->getScenes().begin(); itr != m_pSceneManager->getScenes().end(); itr++) {
for (unordered_map<std::string, KRScene*>::iterator itr = m_pSceneManager->getScenes().begin(); itr != m_pSceneManager->getScenes().end(); itr++) {
resources.push_back((*itr).second);
}
for(unordered_map<std::string, KRTexture *>::iterator itr = m_pTextureManager->getTextures().begin(); itr != m_pTextureManager->getTextures().end(); itr++) {
for (unordered_map<std::string, KRTexture*>::iterator itr = m_pTextureManager->getTextures().begin(); itr != m_pTextureManager->getTextures().end(); itr++) {
resources.push_back((*itr).second);
}
for(unordered_map<std::string, KRMaterial *>::iterator itr = m_pMaterialManager->getMaterials().begin(); itr != m_pMaterialManager->getMaterials().end(); itr++) {
for (unordered_map<std::string, KRMaterial*>::iterator itr = m_pMaterialManager->getMaterials().begin(); itr != m_pMaterialManager->getMaterials().end(); itr++) {
resources.push_back((*itr).second);
}
for(unordered_multimap<std::string, KRMesh *>::iterator itr = m_pMeshManager->getModels().begin(); itr != m_pMeshManager->getModels().end(); itr++) {
for (unordered_multimap<std::string, KRMesh*>::iterator itr = m_pMeshManager->getModels().begin(); itr != m_pMeshManager->getModels().end(); itr++) {
resources.push_back((*itr).second);
}
for(unordered_map<std::string, KRAnimation *>::iterator itr = m_pAnimationManager->getAnimations().begin(); itr != m_pAnimationManager->getAnimations().end(); itr++) {
for (unordered_map<std::string, KRAnimation*>::iterator itr = m_pAnimationManager->getAnimations().begin(); itr != m_pAnimationManager->getAnimations().end(); itr++) {
resources.push_back((*itr).second);
}
for(unordered_map<std::string, KRAnimationCurve *>::iterator itr = m_pAnimationCurveManager->getAnimationCurves().begin(); itr != m_pAnimationCurveManager->getAnimationCurves().end(); itr++) {
for (unordered_map<std::string, KRAnimationCurve*>::iterator itr = m_pAnimationCurveManager->getAnimationCurves().begin(); itr != m_pAnimationCurveManager->getAnimationCurves().end(); itr++) {
resources.push_back((*itr).second);
}
for(unordered_map<std::string, KRAudioSample *>::iterator itr = m_pSoundManager->getSounds().begin(); itr != m_pSoundManager->getSounds().end(); itr++) {
for (unordered_map<std::string, KRAudioSample*>::iterator itr = m_pSoundManager->getSounds().begin(); itr != m_pSoundManager->getSounds().end(); itr++) {
resources.push_back((*itr).second);
}
unordered_map<std::string, unordered_map<std::string, KRSource *> > sources = m_pSourceManager->getSources();
for(unordered_map<std::string, unordered_map<std::string, KRSource *> >::iterator itr = sources.begin(); itr != sources.end(); itr++) {
for(unordered_map<std::string, KRSource *>::iterator itr2 = (*itr).second.begin(); itr2 != (*itr).second.end(); itr2++) {
unordered_map<std::string, unordered_map<std::string, KRSource*> > sources = m_pSourceManager->getSources();
for (unordered_map<std::string, unordered_map<std::string, KRSource*> >::iterator itr = sources.begin(); itr != sources.end(); itr++) {
for (unordered_map<std::string, KRSource*>::iterator itr2 = (*itr).second.begin(); itr2 != (*itr).second.end(); itr2++) {
resources.push_back((*itr2).second);
}
}
unordered_map<std::string, unordered_map<std::string, KRShader *> > shaders = m_pShaderManager->getShaders();
for(unordered_map<std::string, unordered_map<std::string, KRShader *> >::iterator itr = shaders.begin(); itr != shaders.end(); itr++) {
for(unordered_map<std::string, KRShader *>::iterator itr2 = (*itr).second.begin(); itr2 != (*itr).second.end(); itr2++) {
unordered_map<std::string, unordered_map<std::string, KRShader*> > shaders = m_pShaderManager->getShaders();
for (unordered_map<std::string, unordered_map<std::string, KRShader*> >::iterator itr = shaders.begin(); itr != shaders.end(); itr++) {
for (unordered_map<std::string, KRShader*>::iterator itr2 = (*itr).second.begin(); itr2 != (*itr).second.end(); itr2++) {
resources.push_back((*itr2).second);
}
}
unordered_map<std::string, unordered_map<std::string, KRUnknown *> > unknowns = m_pUnknownManager->getUnknowns();
for(unordered_map<std::string, unordered_map<std::string, KRUnknown *> >::iterator itr = unknowns.begin(); itr != unknowns.end(); itr++) {
for(unordered_map<std::string, KRUnknown *>::iterator itr2 = (*itr).second.begin(); itr2 != (*itr).second.end(); itr2++) {
unordered_map<std::string, unordered_map<std::string, KRUnknown*> > unknowns = m_pUnknownManager->getUnknowns();
for (unordered_map<std::string, unordered_map<std::string, KRUnknown*> >::iterator itr = unknowns.begin(); itr != unknowns.end(); itr++) {
for (unordered_map<std::string, KRUnknown*>::iterator itr2 = (*itr).second.begin(); itr2 != (*itr).second.end(); itr2++) {
resources.push_back((*itr2).second);
}
}
@@ -285,98 +300,99 @@ std::vector<KRResource *> KRContext::getResources()
return resources;
}
KRResource* KRContext::loadResource(const std::string &file_name, KRDataBlock *data) {
KRResource* KRContext::loadResource(const std::string& file_name, KRDataBlock* data)
{
std::string name = KRResource::GetFileBase(file_name);
std::string extension = KRResource::GetFileExtension(file_name);
KRResource *resource = nullptr;
KRResource* resource = nullptr;
// fprintf(stderr, "KRContext::loadResource - Loading: %s\n", file_name.c_str());
// fprintf(stderr, "KRContext::loadResource - Loading: %s\n", file_name.c_str());
if(extension.compare("krbundle") == 0) {
if (extension.compare("krbundle") == 0) {
resource = m_pBundleManager->loadBundle(name.c_str(), data);
} else if(extension.compare("krmesh") == 0) {
} else if (extension.compare("krmesh") == 0) {
resource = m_pMeshManager->loadModel(name.c_str(), data);
} else if(extension.compare("krscene") == 0) {
} else if (extension.compare("krscene") == 0) {
resource = m_pSceneManager->loadScene(name.c_str(), data);
} else if(extension.compare("kranimation") == 0) {
} else if (extension.compare("kranimation") == 0) {
resource = m_pAnimationManager->loadAnimation(name.c_str(), data);
} else if(extension.compare("kranimationcurve") == 0) {
} else if (extension.compare("kranimationcurve") == 0) {
resource = m_pAnimationCurveManager->loadAnimationCurve(name.c_str(), data);
} else if(extension.compare("pvr") == 0) {
} else if (extension.compare("pvr") == 0) {
resource = m_pTextureManager->loadTexture(name.c_str(), extension.c_str(), data);
} else if(extension.compare("ktx") == 0) {
} else if (extension.compare("ktx") == 0) {
resource = m_pTextureManager->loadTexture(name.c_str(), extension.c_str(), data);
} else if(extension.compare("tga") == 0) {
} else if (extension.compare("tga") == 0) {
resource = m_pTextureManager->loadTexture(name.c_str(), extension.c_str(), data);
} else if(extension.compare("spv") == 0) {
} else if (extension.compare("spv") == 0) {
// SPIR-V shader binary
resource = m_pShaderManager->load(name, extension, data);
} else if(extension.compare("vert") == 0) {
} else if (extension.compare("vert") == 0) {
// vertex shader
resource = m_pSourceManager->load(name, extension, data);
} else if(extension.compare("frag") == 0) {
} else if (extension.compare("frag") == 0) {
// fragment shader
resource = m_pSourceManager->load(name, extension, data);
} else if(extension.compare("tesc") == 0) {
} else if (extension.compare("tesc") == 0) {
// tessellation control shader
resource = m_pSourceManager->load(name, extension, data);
} else if(extension.compare("tese") == 0) {
} else if (extension.compare("tese") == 0) {
// tessellation evaluation shader
resource = m_pSourceManager->load(name, extension, data);
} else if(extension.compare("geom") == 0) {
} else if (extension.compare("geom") == 0) {
// geometry shader
resource = m_pSourceManager->load(name, extension, data);
} else if(extension.compare("comp") == 0) {
} else if (extension.compare("comp") == 0) {
// compute shader
resource = m_pSourceManager->load(name, extension, data);
} else if(extension.compare("mesh") == 0) {
} else if (extension.compare("mesh") == 0) {
// mesh shader
resource = m_pSourceManager->load(name, extension, data);
} else if(extension.compare("task") == 0) {
} else if (extension.compare("task") == 0) {
// task shader
resource = m_pSourceManager->load(name, extension, data);
} else if(extension.compare("rgen") == 0) {
} else if (extension.compare("rgen") == 0) {
// ray generation shader
resource = m_pSourceManager->load(name, extension, data);
} else if(extension.compare("rint") == 0) {
} else if (extension.compare("rint") == 0) {
// ray intersection shader
resource = m_pSourceManager->load(name, extension, data);
} else if(extension.compare("rahit") == 0) {
} else if (extension.compare("rahit") == 0) {
// ray any hit shader
resource = m_pSourceManager->load(name, extension, data);
} else if(extension.compare("rchit") == 0) {
} else if (extension.compare("rchit") == 0) {
// ray closest hit shader
resource = m_pSourceManager->load(name, extension, data);
} else if(extension.compare("rmiss") == 0) {
} else if (extension.compare("rmiss") == 0) {
// ray miss shader
resource = m_pSourceManager->load(name, extension, data);
} else if(extension.compare("rcall") == 0) {
} else if (extension.compare("rcall") == 0) {
// ray callable shader
resource = m_pSourceManager->load(name, extension, data);
} else if(extension.compare("glsl") == 0) {
} else if (extension.compare("glsl") == 0) {
// glsl included by other shaders
resource = m_pSourceManager->load(name, extension, data);
} else if(extension.compare("options") == 0) {
} else if (extension.compare("options") == 0) {
// shader pre-processor options definition file
resource = m_pSourceManager->load(name, extension, data);
} else if(extension.compare("mtl") == 0) {
} else if (extension.compare("mtl") == 0) {
resource = m_pMaterialManager->load(name.c_str(), data);
} else if(extension.compare("mp3") == 0) {
} else if (extension.compare("mp3") == 0) {
resource = m_pSoundManager->load(name.c_str(), extension, data);
} else if(extension.compare("wav") == 0) {
} else if (extension.compare("wav") == 0) {
resource = m_pSoundManager->load(name.c_str(), extension, data);
} else if(extension.compare("aac") == 0) {
} else if (extension.compare("aac") == 0) {
resource = m_pSoundManager->load(name.c_str(), extension, data);
} else if(extension.compare("obj") == 0) {
} else if (extension.compare("obj") == 0) {
resource = KRResource::LoadObj(*this, file_name);
#if !TARGET_OS_IPHONE
/*
/*
// FINDME, TODO, HACK! - Uncomment
} else if(extension.compare("fbx") == 0) {
resource = KRResource::LoadFbx(*this, file_name);
*/
} else if(extension.compare("blend") == 0) {
*/
} else if (extension.compare("blend") == 0) {
resource = KRResource::LoadBlenderScene(*this, file_name);
#endif
} else {
@@ -385,18 +401,19 @@ KRResource* KRContext::loadResource(const std::string &file_name, KRDataBlock *d
return resource;
}
KrResult KRContext::loadResource(const KrLoadResourceInfo* loadResourceInfo) {
KrResult KRContext::loadResource(const KrLoadResourceInfo* loadResourceInfo)
{
if (loadResourceInfo->resourceHandle < 0 || loadResourceInfo->resourceHandle >= m_resourceMapSize) {
return KR_ERROR_OUT_OF_BOUNDS;
}
KRDataBlock *data = new KRDataBlock();
if(!data->load(loadResourceInfo->pResourcePath)) {
KRDataBlock* data = new KRDataBlock();
if (!data->load(loadResourceInfo->pResourcePath)) {
KRContext::Log(KRContext::LOG_LEVEL_ERROR, "KRContext::loadResource - Failed to open file: %s", loadResourceInfo->pResourcePath);
delete data;
return KR_ERROR_UNEXPECTED;
}
KRResource *resource = loadResource(loadResourceInfo->pResourcePath, data);
KRResource* resource = loadResource(loadResourceInfo->pResourcePath, data);
m_resourceMap[loadResourceInfo->resourceHandle] = resource;
return KR_SUCCESS;
}
@@ -608,7 +625,7 @@ float KRContext::getAbsoluteTime() const
long KRContext::getAbsoluteTimeMilliseconds()
{
#if defined(ANDROID)
return std::chrono::duration_cast< std::chrono::milliseconds >(
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
#elif defined(__APPLE__)
return (long)(mach_absolute_time() / 1000 * m_timebase_info.numer / m_timebase_info.denom); // Division done first to avoid potential overflow
@@ -619,7 +636,7 @@ long KRContext::getAbsoluteTimeMilliseconds()
#if TARGET_OS_IPHONE || TARGET_OS_MAC
void KRContext::getMemoryStats(long &free_memory)
void KRContext::getMemoryStats(long& free_memory)
{
free_memory = 0;
@@ -628,9 +645,9 @@ void KRContext::getMemoryStats(long &free_memory)
vm_size_t pagesize = 0;
vm_statistics_data_t vm_stat;
// int total_ram = 256 * 1024 * 1024;
if(host_page_size(host_port, &pagesize) != KERN_SUCCESS) {
if (host_page_size(host_port, &pagesize) != KERN_SUCCESS) {
KRContext::Log(KRContext::LOG_LEVEL_ERROR, "Could not get VM page size.");
} else if(host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS) {
} else if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS) {
KRContext::Log(KRContext::LOG_LEVEL_ERROR, "Could not get VM stats.");
} else {
// total_ram = (vm_stat.wire_count + vm_stat.active_count + vm_stat.inactive_count + vm_stat.free_count) * pagesize;

View File

@@ -54,7 +54,8 @@ class KRStreamerThread;
class KRDeviceManager;
class KRSurfaceManager;
class KRContext {
class KRContext
{
public:
static int KRENGINE_MAX_PIPELINE_HANDLES;
static int KRENGINE_GPU_MEM_MAX;
@@ -97,21 +98,21 @@ public:
KrResult updateNode(const KrUpdateNodeInfo* pUpdateNodeInfo);
KRResource* loadResource(const std::string &file_name, KRDataBlock *data);
KRResource* loadResource(const std::string& file_name, KRDataBlock* data);
KRBundleManager *getBundleManager();
KRSceneManager *getSceneManager();
KRTextureManager *getTextureManager();
KRMaterialManager *getMaterialManager();
KRPipelineManager *getPipelineManager();
KRMeshManager *getMeshManager();
KRAnimationManager *getAnimationManager();
KRAnimationCurveManager *getAnimationCurveManager();
KRAudioManager *getAudioManager();
KRUnknownManager *getUnknownManager();
KRShaderManager *getShaderManager();
KRSourceManager *getSourceManager();
KRBundleManager* getBundleManager();
KRSceneManager* getSceneManager();
KRTextureManager* getTextureManager();
KRMaterialManager* getMaterialManager();
KRPipelineManager* getPipelineManager();
KRMeshManager* getMeshManager();
KRAnimationManager* getAnimationManager();
KRAnimationCurveManager* getAnimationCurveManager();
KRAudioManager* getAudioManager();
KRUnknownManager* getUnknownManager();
KRShaderManager* getShaderManager();
KRSourceManager* getSourceManager();
KRSurfaceManager* getSurfaceManager();
KRDeviceManager* getDeviceManager();
@@ -124,22 +125,23 @@ public:
long getAbsoluteTimeMilliseconds();
std::vector<KRResource *> getResources();
std::vector<KRResource*> getResources();
#if TARGET_OS_IPHONE || TARGET_OS_MAC
// XXX This doesn't belong here, and might not actually be needed at all
void getMemoryStats(long &free_memory);
void getMemoryStats(long& free_memory);
#endif
typedef enum {
typedef enum
{
LOG_LEVEL_INFORMATION,
LOG_LEVEL_WARNING,
LOG_LEVEL_ERROR
} log_level;
typedef void log_callback(void *userdata, const std::string &message, log_level level);
typedef void log_callback(void* userdata, const std::string& message, log_level level);
static void SetLogCallback(log_callback *log_callback, void *user_data);
static void SetLogCallback(log_callback* log_callback, void* user_data);
static void Log(log_level level, const std::string message_format, ...);
void doStreaming();
@@ -181,8 +183,8 @@ private:
// m_streamingEnabled is set to true once all managers are loaded
std::atomic<bool> m_streamingEnabled;
static log_callback *s_log_callback;
static void *s_log_callback_user_data;
static log_callback* s_log_callback;
static void* s_log_callback_user_data;
unordered_multimap<std::string, KRResource*> m_resources;

View File

@@ -31,7 +31,7 @@
#include "KRContextObject.h"
KRContextObject::KRContextObject(KRContext &context)
KRContextObject::KRContextObject(KRContext& context)
{
m_pContext = &context;
}
@@ -41,7 +41,7 @@ KRContextObject::~KRContextObject()
}
KRContext &KRContextObject::getContext() const
KRContext& KRContextObject::getContext() const
{
return *m_pContext;
}

View File

@@ -33,13 +33,14 @@
class KRContext;
class KRContextObject {
class KRContextObject
{
public:
KRContextObject(KRContext &context);
KRContextObject(KRContext& context);
~KRContextObject();
KRContext &getContext() const;
KRContext& getContext() const;
protected:
KRContext *m_pContext;
KRContext* m_pContext;
};

View File

@@ -39,53 +39,56 @@ namespace KRDSP {
#define KRDSP_APPLE_VDSP
#include <Accelerate/Accelerate.h>
#else
// Slow, but portable fallback implementation
// Slow, but portable fallback implementation
#define KRDSP_SLOW
#endif
#if defined(KRDSP_APPLE_VDSP)
// Apple vDSP
typedef DSPSplitComplex SplitComplex;
struct FFTWorkspace {
typedef DSPSplitComplex SplitComplex;
struct FFTWorkspace
{
FFTSetup setup;
void create(size_t length);
void destroy();
FFTWorkspace();
~FFTWorkspace();
};
};
#elif defined(KRDSP_SLOW)
typedef struct {
float *realp;
float *imagp;
} SplitComplex;
typedef struct
{
float* realp;
float* imagp;
} SplitComplex;
struct FFTWorkspace {
float *sin_table;
float *cos_table;
struct FFTWorkspace
{
float* sin_table;
float* cos_table;
void create(size_t length);
void destroy();
FFTWorkspace();
~FFTWorkspace();
};
};
#else
#error Not Implemented
#endif
void FFTForward(const FFTWorkspace &workspace, SplitComplex *src, size_t count);
void FFTInverse(const FFTWorkspace &workspace, SplitComplex *src, size_t count);
void Int16ToFloat(const short *src, size_t srcStride, float *dest, size_t destStride, size_t count);
void Scale(float *buffer, float scale, size_t count);
void ScaleCopy(const float *src, float scale, float *dest, size_t count);
void ScaleCopy(const SplitComplex *src, float scale, SplitComplex *dest, size_t count);
void ScaleRamp(float *buffer, float scaleStart, float scaleStep, size_t count);
void Accumulate(float *buffer, size_t bufferStride, const float *buffer2, size_t buffer2Stride, size_t count);
void Accumulate(SplitComplex *buffer, const SplitComplex *buffer2, size_t count);
void Multiply(const SplitComplex *a, const SplitComplex *b, SplitComplex *c, size_t count);
void FFTForward(const FFTWorkspace& workspace, SplitComplex* src, size_t count);
void FFTInverse(const FFTWorkspace& workspace, SplitComplex* src, size_t count);
void Int16ToFloat(const short* src, size_t srcStride, float* dest, size_t destStride, size_t count);
void Scale(float* buffer, float scale, size_t count);
void ScaleCopy(const float* src, float scale, float* dest, size_t count);
void ScaleCopy(const SplitComplex* src, float scale, SplitComplex* dest, size_t count);
void ScaleRamp(float* buffer, float scaleStart, float scaleStep, size_t count);
void Accumulate(float* buffer, size_t bufferStride, const float* buffer2, size_t buffer2Stride, size_t count);
void Accumulate(SplitComplex* buffer, const SplitComplex* buffer2, size_t count);
void Multiply(const SplitComplex* a, const SplitComplex* b, SplitComplex* c, size_t count);
} // namespace KRDSP

View File

@@ -72,7 +72,7 @@ void FFTWorkspace::destroy()
}
}
void FFTForward(const FFTWorkspace &workspace, SplitComplex *src, size_t count)
void FFTForward(const FFTWorkspace& workspace, SplitComplex* src, size_t count)
{
// Radix-2 Decimation in Time FFT Algorithm
// http://en.dsplib.org/content/fft_dec_in_time.html
@@ -119,7 +119,7 @@ void FFTForward(const FFTWorkspace &workspace, SplitComplex *src, size_t count)
}
}
void FFTInverse(const FFTWorkspace &workspace, SplitComplex *src, size_t count)
void FFTInverse(const FFTWorkspace& workspace, SplitComplex* src, size_t count)
{
SplitComplex swapped;
swapped.imagp = src->realp;
@@ -127,10 +127,10 @@ void FFTInverse(const FFTWorkspace &workspace, SplitComplex *src, size_t count)
FFTForward(workspace, &swapped, count);
}
void Int16ToFloat(const short *src, size_t srcStride, float *dest, size_t destStride, size_t count)
void Int16ToFloat(const short* src, size_t srcStride, float* dest, size_t destStride, size_t count)
{
const short *r = src;
float *w = dest;
const short* r = src;
float* w = dest;
while (w < dest + destStride * count) {
*w = (float)*r;
r += srcStride;
@@ -138,19 +138,19 @@ void Int16ToFloat(const short *src, size_t srcStride, float *dest, size_t destSt
}
}
void Scale(float *buffer, float scale, size_t count)
void Scale(float* buffer, float scale, size_t count)
{
float *w = buffer;
float* w = buffer;
while (w < buffer + count) {
*w *= scale;
w++;
}
}
void ScaleCopy(const float *src, float scale, float *dest, size_t count)
void ScaleCopy(const float* src, float scale, float* dest, size_t count)
{
const float *r = src;
float *w = dest;
const float* r = src;
float* w = dest;
while (w < dest + count) {
*w = *r * scale;
w++;
@@ -158,15 +158,15 @@ void ScaleCopy(const float *src, float scale, float *dest, size_t count)
}
}
void ScaleCopy(const SplitComplex *src, float scale, SplitComplex *dest, size_t count)
void ScaleCopy(const SplitComplex* src, float scale, SplitComplex* dest, size_t count)
{
ScaleCopy(src->realp, scale, dest->realp, count);
ScaleCopy(src->imagp, scale, dest->imagp, count);
}
void ScaleRamp(float *buffer, float scaleStart, float scaleStep, size_t count)
void ScaleRamp(float* buffer, float scaleStart, float scaleStep, size_t count)
{
float *w = buffer;
float* w = buffer;
float s = scaleStart;
while (w < buffer + count) {
*w *= s;
@@ -175,10 +175,10 @@ void ScaleRamp(float *buffer, float scaleStart, float scaleStep, size_t count)
}
}
void Accumulate(float *buffer, size_t bufferStride, const float *buffer2, size_t buffer2Stride, size_t count)
void Accumulate(float* buffer, size_t bufferStride, const float* buffer2, size_t buffer2Stride, size_t count)
{
float *w = buffer;
const float *r = buffer2;
float* w = buffer;
const float* r = buffer2;
while (w < buffer + bufferStride * count) {
*w *= *r;
w += bufferStride;
@@ -186,7 +186,7 @@ void Accumulate(float *buffer, size_t bufferStride, const float *buffer2, size_t
}
}
void Accumulate(SplitComplex *buffer, const SplitComplex *buffer2, size_t count)
void Accumulate(SplitComplex* buffer, const SplitComplex* buffer2, size_t count)
{
for (size_t i = 0; i < count; i++) {
buffer->imagp[i] += buffer2->imagp[i];
@@ -194,7 +194,7 @@ void Accumulate(SplitComplex *buffer, const SplitComplex *buffer2, size_t count)
}
}
void Multiply(const SplitComplex *a, const SplitComplex *b, SplitComplex *c, size_t count)
void Multiply(const SplitComplex* a, const SplitComplex* b, SplitComplex* c, size_t count)
{
for (size_t i = 0; i < count; i++) {
c->realp[i] = a->realp[i] * b->realp[i] - a->imagp[i] * b->imagp[i];

View File

@@ -62,54 +62,54 @@ void FFTWorkspace::destroy()
}
}
void FFTForward(const FFTWorkspace &workspace, SplitComplex *src, size_t count)
void FFTForward(const FFTWorkspace& workspace, SplitComplex* src, size_t count)
{
vDSP_fft_zip(workspace.setup, src, 1, count, kFFTDirection_Forward);
}
void FFTInverse(const FFTWorkspace &workspace, SplitComplex *src, size_t count)
void FFTInverse(const FFTWorkspace& workspace, SplitComplex* src, size_t count)
{
vDSP_fft_zip(workspace.setup, src, 1, count, kFFTDirection_Inverse);
}
void Int16ToFloat(const short *src, size_t srcStride, float *dest, size_t destStride, size_t count)
void Int16ToFloat(const short* src, size_t srcStride, float* dest, size_t destStride, size_t count)
{
vDSP_vflt16(src, srcStride, dest, destStride, count);
}
void Scale(float *buffer, float scale, size_t count)
void Scale(float* buffer, float scale, size_t count)
{
vDSP_vsmul(buffer, 1, &scale, buffer, 1, count);
}
void ScaleCopy(const float *src, float scale, float *dest, size_t count)
void ScaleCopy(const float* src, float scale, float* dest, size_t count)
{
vDSP_vsmul(src, 1, &scale, dest, 1, count);
}
void ScaleCopy(const SplitComplex *src, float scale, SplitComplex *dest, size_t count)
void ScaleCopy(const SplitComplex* src, float scale, SplitComplex* dest, size_t count)
{
ScaleCopy(src->realp, scale, dest->realp, count);
ScaleCopy(src->imagp, scale, dest->imagp, count);
}
void ScaleRamp(float *buffer, float scaleStart, float scaleStep, size_t count)
void ScaleRamp(float* buffer, float scaleStart, float scaleStep, size_t count)
{
vDSP_vrampmul(buffer, 1, &scaleStart, &scaleStep, buffer, 1, count);
}
void Accumulate(float *buffer, size_t bufferStride, const float *buffer2, size_t buffer2Stride, size_t count)
void Accumulate(float* buffer, size_t bufferStride, const float* buffer2, size_t buffer2Stride, size_t count)
{
vDSP_vadd(buffer, bufferStride, buffer2, buffer2Stride, buffer, bufferStride, count);
}
void Accumulate(SplitComplex *buffer, const SplitComplex *buffer2, size_t count)
void Accumulate(SplitComplex* buffer, const SplitComplex* buffer2, size_t count)
{
vDSP_zvadd(buffer2, 1, buffer, 1, buffer, 1, count);
}
void Multiply(const SplitComplex *a, const SplitComplex *b, SplitComplex *c, size_t count)
void Multiply(const SplitComplex* a, const SplitComplex* b, SplitComplex* c, size_t count)
{
vDSP_zvmul(a, 1, b, 1, c, 1, count, 1);
}

View File

@@ -47,7 +47,8 @@ int m_mapCount = 0;
size_t m_mapSize = 0;
size_t m_mapOverhead = 0;
KRDataBlock::KRDataBlock() {
KRDataBlock::KRDataBlock()
{
m_data = NULL;
m_data_size = 0;
m_data_offset = 0;
@@ -65,7 +66,8 @@ KRDataBlock::KRDataBlock() {
m_bReadOnly = false;
}
KRDataBlock::KRDataBlock(void *data, size_t size) {
KRDataBlock::KRDataBlock(void* data, size_t size)
{
m_data = NULL;
m_data_size = 0;
m_data_offset = 0;
@@ -84,7 +86,8 @@ KRDataBlock::KRDataBlock(void *data, size_t size) {
load(data, size);
}
KRDataBlock::~KRDataBlock() {
KRDataBlock::~KRDataBlock()
{
unload();
}
@@ -102,16 +105,16 @@ void KRDataBlock::unload()
m_hPackFile = INVALID_HANDLE_VALUE;
}
#elif defined(__APPLE__)
if(m_fdPackFile) {
if (m_fdPackFile) {
// Memory mapped file
if(m_fileOwnerDataBlock == this) {
if (m_fileOwnerDataBlock == this) {
close(m_fdPackFile);
}
m_fdPackFile = 0;
}
#endif
if(m_data != NULL && m_bMalloced) {
if (m_data != NULL && m_bMalloced) {
// Malloc'ed data
free(m_data);
}
@@ -127,7 +130,7 @@ void KRDataBlock::unload()
}
// Encapsulate a pointer. Note - The pointer will not be free'ed
bool KRDataBlock::load(void *data, size_t size)
bool KRDataBlock::load(void* data, size_t size)
{
unload();
m_data = data;
@@ -138,7 +141,7 @@ bool KRDataBlock::load(void *data, size_t size)
}
// Load a file into memory using mmap. The data pointer will be protected as read-only until append() or expand() is called
bool KRDataBlock::load(const std::string &path)
bool KRDataBlock::load(const std::string& path)
{
bool success = false;
unload();
@@ -147,11 +150,11 @@ bool KRDataBlock::load(const std::string &path)
#if defined(_WIN32) || defined(_WIN64)
m_hPackFile = CreateFile(path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(m_hPackFile != INVALID_HANDLE_VALUE) {
if (m_hPackFile != INVALID_HANDLE_VALUE) {
m_fileOwnerDataBlock = this;
m_fileName = KRResource::GetFileBase(path);
FILE_STANDARD_INFO fileInfo;
if(GetFileInformationByHandleEx(m_hPackFile, FileStandardInfo, &fileInfo, sizeof(fileInfo))) {
if (GetFileInformationByHandleEx(m_hPackFile, FileStandardInfo, &fileInfo, sizeof(fileInfo))) {
m_data_size = fileInfo.EndOfFile.QuadPart;
m_data_offset = 0;
success = true;
@@ -159,18 +162,18 @@ bool KRDataBlock::load(const std::string &path)
}
#elif defined(__APPLE__)
m_fdPackFile = open(path.c_str(), O_RDONLY);
if(m_fdPackFile >= 0) {
if (m_fdPackFile >= 0) {
m_fileOwnerDataBlock = this;
m_fileName = KRResource::GetFileBase(path);
struct stat statbuf;
if(fstat(m_fdPackFile, &statbuf) >= 0) {
if (fstat(m_fdPackFile, &statbuf) >= 0) {
m_data_size = statbuf.st_size;
m_data_offset = 0;
success = true;
}
}
#endif
if(!success) {
if (!success) {
// If anything failed, don't leave the object in an invalid state
unload();
}
@@ -178,13 +181,13 @@ bool KRDataBlock::load(const std::string &path)
}
// Create a KRDataBlock encapsulating a sub-region of this block. The caller is responsible to free the object.
KRDataBlock *KRDataBlock::getSubBlock(int start, int length)
KRDataBlock* KRDataBlock::getSubBlock(int start, int length)
{
KRDataBlock *new_block = new KRDataBlock();
KRDataBlock* new_block = new KRDataBlock();
new_block->m_data_size = length;
#if defined(_WIN32) || defined(_WIN64)
if(m_hPackFile != INVALID_HANDLE_VALUE) {
if (m_hPackFile != INVALID_HANDLE_VALUE) {
new_block->m_hPackFile = m_hPackFile;
#elif defined(__APPLE__) || defined(ANDROID)
if (m_fdPackFile) {
@@ -194,8 +197,8 @@ KRDataBlock *KRDataBlock::getSubBlock(int start, int length)
#endif
new_block->m_fileOwnerDataBlock = m_fileOwnerDataBlock;
new_block->m_data_offset = start + m_data_offset;
} else if(m_bMalloced) {
new_block->m_data = (unsigned char *)m_data + start + m_data_offset;
} else if (m_bMalloced) {
new_block->m_data = (unsigned char*)m_data + start + m_data_offset;
}
new_block->m_bReadOnly = true;
@@ -203,19 +206,22 @@ KRDataBlock *KRDataBlock::getSubBlock(int start, int length)
}
// Return a pointer to the start of the data block
void *KRDataBlock::getStart() {
void* KRDataBlock::getStart()
{
assertLocked();
return m_data;
}
// Return a pointer to the byte after the end of the data block
void *KRDataBlock::getEnd() {
void* KRDataBlock::getEnd()
{
assertLocked();
return (unsigned char *)m_data + m_data_size;
return (unsigned char*)m_data + m_data_size;
}
// Return the size of the data block. Use append() or expand() to make the data block larger
size_t KRDataBlock::getSize() const {
size_t KRDataBlock::getSize() const
{
return m_data_size;
}
@@ -223,7 +229,7 @@ size_t KRDataBlock::getSize() const {
void KRDataBlock::expand(size_t size)
{
#if defined(_WIN32) || defined(_WIN64)
if(m_data == NULL && m_hPackFile == INVALID_HANDLE_VALUE) {
if (m_data == NULL && m_hPackFile == INVALID_HANDLE_VALUE) {
#elif defined(__APPLE__) || defined(ANDROID)
if (m_data == NULL && m_fdPackFile == 0) {
#else
@@ -235,14 +241,14 @@ void KRDataBlock::expand(size_t size)
m_data_size = size;
m_data_offset = 0;
m_bMalloced = true;
} else if(m_bMalloced) {
} else if (m_bMalloced) {
// Starting with a malloc'ed data block; realloc it expand
m_data = realloc(m_data, m_data_size + size);
m_data_size += size;
} else {
// Starting with a mmap'ed data block, an encapsulated pointer, or a sub-block; copy it to ram before expanding to avoid updating the original file until save() is called
// ... Or starting with a pointer reference, we must make our own copy and must not free the pointer
void *pNewData = malloc(m_data_size + size);
void* pNewData = malloc(m_data_size + size);
assert(pNewData != NULL);
// Copy exising data
@@ -259,24 +265,27 @@ void KRDataBlock::expand(size_t size)
}
// Append data to the end of the block, increasing the size of the block and making it read-write.
void KRDataBlock::append(void *data, size_t size) {
void KRDataBlock::append(void* data, size_t size)
{
// Expand the data block
expand(size);
// Fill the new space with the data to append
lock();
memcpy((unsigned char *)m_data + m_data_size - size, data, size);
memcpy((unsigned char*)m_data + m_data_size - size, data, size);
unlock();
}
// Copy the entire data block to the destination pointer
void KRDataBlock::copy(void *dest) {
void KRDataBlock::copy(void* dest)
{
copy(dest, 0, (int)m_data_size);
}
// Copy a range of data to the destination pointer
void KRDataBlock::copy(void *dest, int start, int count) {
void KRDataBlock::copy(void* dest, int start, int count)
{
#if defined(_WIN32) || defined(_WIN64)
if (m_lockCount == 0 && m_hPackFile != INVALID_HANDLE_VALUE) {
// Optimization: If we haven't mmap'ed or malloced the data already, ReadFile() it directly from the file into the buffer
@@ -285,19 +294,19 @@ void KRDataBlock::copy(void *dest, int start, int count) {
bool success = SetFilePointerEx(m_hPackFile, distance, NULL, FILE_BEGIN);
assert(success);
void *w = dest;
void* w = dest;
DWORD bytes_remaining = count;
while(bytes_remaining > 0) {
while (bytes_remaining > 0) {
DWORD bytes_read = 0;
success = ReadFile(m_hPackFile, w, bytes_remaining, &bytes_read, NULL);
assert(success);
assert(bytes_read > 0);
w = (unsigned char *)w + bytes_read;
w = (unsigned char*)w + bytes_read;
bytes_remaining -= bytes_read;
}
assert(bytes_remaining == 0);
#elif defined(__APPLE__) || defined(ANDROID)
if(m_lockCount == 0 && m_fdPackFile != 0) {
if (m_lockCount == 0 && m_fdPackFile != 0) {
// Optimization: If we haven't mmap'ed or malloced the data already, pread() it directly from the file into the buffer
ssize_t r = pread(m_fdPackFile, dest, count, start + m_data_offset);
assert(r != -1);
@@ -306,20 +315,21 @@ void KRDataBlock::copy(void *dest, int start, int count) {
#endif
} else {
lock();
memcpy((unsigned char *)dest, (unsigned char *)m_data + start, count);
memcpy((unsigned char*)dest, (unsigned char*)m_data + start, count);
unlock();
}
}
}
// Append data to the end of the block, increasing the size of the block and making it read-write.
void KRDataBlock::append(KRDataBlock &data) {
void KRDataBlock::append(KRDataBlock & data)
{
data.lock();
append(data.getStart(), data.getSize());
data.unlock();
}
// Append string to the end of the block, increasing the size of the block and making it read-write. The resulting datablock includes a terminating character
void KRDataBlock::append(const std::string &s)
void KRDataBlock::append(const std::string & s)
{
const char* szText = s.c_str();
size_t text_length = strlen(szText);
@@ -339,12 +349,13 @@ void KRDataBlock::append(const std::string &s)
}
// Save the data to a file.
bool KRDataBlock::save(const std::string& path) {
bool KRDataBlock::save(const std::string & path)
{
#if defined(_WIN32) || defined(_WIN64)
bool success = true;
HANDLE hNewFile = INVALID_HANDLE_VALUE;
HANDLE hFileMapping = NULL;
void *pNewData = NULL;
void* pNewData = NULL;
hNewFile = CreateFile(path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hNewFile == INVALID_HANDLE_VALUE) {
@@ -386,21 +397,21 @@ bool KRDataBlock::save(const std::string& path) {
#elif defined(__APPLE__) || defined(ANDROID)
int fdNewFile = open(path.c_str(), O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);
if(fdNewFile == -1) {
if (fdNewFile == -1) {
return false;
}
// Seek to end of file and write a byte to enlarge it
lseek(fdNewFile, m_data_size-1, SEEK_SET);
lseek(fdNewFile, m_data_size - 1, SEEK_SET);
write(fdNewFile, "", 1);
// Now map it...
void *pNewData = mmap(0, m_data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fdNewFile, 0);
if(pNewData == (caddr_t) -1) {
void* pNewData = mmap(0, m_data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fdNewFile, 0);
if (pNewData == (caddr_t)-1) {
close(fdNewFile);
return false;
}
if(m_data != NULL) {
if (m_data != NULL) {
// Copy data to new file
copy(pNewData);
@@ -422,9 +433,9 @@ std::string KRDataBlock::getString()
{
KRDataBlock b;
b.append(*this);
b.append((void *)"\0", 1); // Ensure data is null terminated, to read as a string safely
b.append((void*)"\0", 1); // Ensure data is null terminated, to read as a string safely
b.lock();
std::string ret = std::string((char *)b.getStart());
std::string ret = std::string((char*)b.getStart());
b.unlock();
return ret;
}
@@ -462,17 +473,17 @@ void ReportWindowsLastError(LPCTSTR lpszFunction)
// Lock the memory, forcing it to be loaded into a contiguous block of address space
void KRDataBlock::lock()
{
if(m_lockCount == 0) {
if (m_lockCount == 0) {
// Memory mapped file; ensure data is mapped to ram
#if defined(_WIN32) || defined(_WIN64)
if(m_hPackFile != INVALID_HANDLE_VALUE) {
if (m_hPackFile != INVALID_HANDLE_VALUE) {
#elif defined(__APPLE__) || defined(ANDROID)
if(m_fdPackFile) {
if (m_fdPackFile) {
#else
#error Unsupported
#endif
if(m_data_size < KRENGINE_MIN_MMAP) {
if (m_data_size < KRENGINE_MIN_MMAP) {
m_data = malloc(m_data_size);
assert(m_data != NULL);
copy(m_data);
@@ -481,13 +492,13 @@ void KRDataBlock::lock()
assert(m_mmapData == NULL);
#if defined(_WIN32) || defined(_WIN64)
m_hFileMapping = CreateFileMappingFromApp(m_hPackFile, NULL, m_bReadOnly ? PAGE_READONLY : PAGE_READWRITE, m_fileOwnerDataBlock->getSize(), NULL);
if(m_hFileMapping == NULL) {
if (m_hFileMapping == NULL) {
ReportWindowsLastError("CreateFileMappingFromApp");
}
assert(m_hFileMapping != NULL);
m_mmapData = MapViewOfFileFromApp(m_hFileMapping, m_bReadOnly ? FILE_MAP_READ | FILE_MAP_COPY : FILE_MAP_WRITE, m_data_offset - alignment_offset, m_data_size + alignment_offset);
if(m_mmapData == NULL) {
if (m_mmapData == NULL) {
ReportWindowsLastError("MapViewOfFileFromApp");
}
assert(m_mmapData != NULL);
@@ -495,9 +506,9 @@ void KRDataBlock::lock()
//fprintf(stderr, "KRDataBlock::lock - \"%s\" (%i)\n", m_fileOwnerDataBlock->m_fileName.c_str(), m_lockCount);
// Round m_data_offset down to the next memory page, as required by mmap
if ((m_mmapData = mmap(0, m_data_size + alignment_offset, m_bReadOnly ? PROT_READ : PROT_WRITE, MAP_SHARED, m_fdPackFile, m_data_offset - alignment_offset)) == (caddr_t) -1) {
if ((m_mmapData = mmap(0, m_data_size + alignment_offset, m_bReadOnly ? PROT_READ : PROT_WRITE, MAP_SHARED, m_fdPackFile, m_data_offset - alignment_offset)) == (caddr_t)-1) {
int iError = errno;
switch(iError) {
switch (iError) {
case EACCES:
KRContext::Log(KRContext::LOG_LEVEL_ERROR, "mmap failed with EACCES");
break;
@@ -532,11 +543,11 @@ void KRDataBlock::lock()
m_mapSize += m_data_size;
m_mapOverhead += alignment_offset + KRAKEN_MEM_ROUND_UP_PAGE(m_data_size + alignment_offset) - m_data_size + alignment_offset;
// fprintf(stderr, "Mapped: %i Size: %d Overhead: %d\n", m_mapCount, m_mapSize, m_mapOverhead);
m_data = (unsigned char *)m_mmapData + alignment_offset;
m_data = (unsigned char*)m_mmapData + alignment_offset;
}
}
}
m_lockCount++;
m_lockCount++;
}
// Unlock the memory, releasing the address space for use by other allocations
@@ -546,17 +557,17 @@ void KRDataBlock::unlock()
assertLocked();
if(m_lockCount == 1) {
if (m_lockCount == 1) {
// Memory mapped file; ensure data is unmapped from ram
#if defined(_WIN32) || defined(_WIN64)
if (m_hPackFile != INVALID_HANDLE_VALUE) {
#elif defined(__APPLE__) || defined(ANDROID)
if(m_fdPackFile) {
if (m_fdPackFile) {
#else
#error Undefined
#endif
if(m_data_size < KRENGINE_MIN_MMAP) {
if (m_data_size < KRENGINE_MIN_MMAP) {
free(m_data);
m_data = NULL;
} else {
@@ -565,7 +576,7 @@ void KRDataBlock::unlock()
if (m_mmapData != NULL) {
UnmapViewOfFile(m_mmapData);
}
if(m_hFileMapping != NULL) {
if (m_hFileMapping != NULL) {
CloseHandle(m_hFileMapping);
m_hFileMapping = NULL;
}
@@ -584,7 +595,7 @@ void KRDataBlock::unlock()
}
}
}
m_lockCount--;
m_lockCount--;
}
// Assert if not locked

View File

@@ -39,32 +39,33 @@
#define KRENGINE_MIN_MMAP 32768
class KRDataBlock {
class KRDataBlock
{
public:
KRDataBlock();
KRDataBlock(void *data, size_t size);
KRDataBlock(void* data, size_t size);
~KRDataBlock();
// Encapsulate a pointer. Note - The pointer will not be free'ed
bool load(void *data, size_t size);
bool load(void* data, size_t size);
// Load a file into memory using mmap. The data pointer will be protected as read-only until append() or expand() is called
bool load(const std::string &path);
bool load(const std::string& path);
// Save the data to a file.
bool save(const std::string& path);
// Create a KRDataBlock encapsulating a sub-region of this block. The caller is responsible to free the object.
KRDataBlock *getSubBlock(int start, int length);
KRDataBlock* getSubBlock(int start, int length);
// Append data to the end of the block, increasing the size of the block and making it read-write.
void append(void *data, size_t size);
void append(void* data, size_t size);
// Append data to the end of the block, increasing the size of the block and making it read-write.
void append(KRDataBlock &data);
void append(KRDataBlock& data);
// Append string to the end of the block, increasing the size of the block and making it read-write. The null terminating character is included
void append(const std::string &s);
void append(const std::string& s);
// Expand or shrink the data block, and switch it to read-write mode. Note - this may result in a mmap'ed file being copied to malloc'ed ram and then closed
void expand(size_t size);
@@ -73,10 +74,10 @@ public:
void unload();
// Return a pointer to the start of the data block
void *getStart();
void* getStart();
// Return a pointer to the one byte after the end of the data block
void *getEnd();
void* getEnd();
// Return the size of the data block. Use append() or expand() to make the data block larger
size_t getSize() const;
@@ -85,10 +86,10 @@ public:
std::string getString();
// Copy the entire data block to the destination pointer
void copy(void *dest);
void copy(void* dest);
// Copy a range of data to the destination pointer
void copy(void *dest, int start, int count);
void copy(void* dest, int start, int count);
// Lock the memory, forcing it to be loaded into a contiguous block of address space
void lock();
@@ -97,7 +98,7 @@ public:
void unlock();
private:
void *m_data;
void* m_data;
size_t m_data_size;
size_t m_data_offset;
@@ -110,8 +111,8 @@ private:
#endif
std::string m_fileName;
KRDataBlock *m_fileOwnerDataBlock;
void *m_mmapData;
KRDataBlock* m_fileOwnerDataBlock;
void* m_mmapData;
// For malloc'ed objects:
bool m_bMalloced;

View File

@@ -422,7 +422,7 @@ bool KRDevice::initStagingBuffer(VkDeviceSize size, StagingBufferInfo* info
#if KRENGINE_DEBUG_GPU_LABELS
, const char* debug_label
#endif // KRENGINE_DEBUG_GPU_LABELS
)
)
{
if (!createBuffer(
size,

View File

@@ -76,7 +76,7 @@ public:
void streamStart();
void streamUpload(KRDataBlock& data, VkBuffer destination);
void streamUpload(void *data, size_t size, VkBuffer destination);
void streamUpload(void* data, size_t size, VkBuffer destination);
void streamUpload(void* data, size_t size, Vector2i dimensions, VkImage destination);
void streamEnd();
@@ -101,7 +101,8 @@ public:
std::vector<VkCommandBuffer> m_transferCommandBuffers;
VmaAllocator m_allocator;
struct StagingBufferInfo {
struct StagingBufferInfo
{
VkBuffer buffer;
VmaAllocation allocation;
size_t size;

View File

@@ -162,23 +162,19 @@ void KRDeviceManager::createDevices()
bool addDevice = false;
if (candidateDevices.empty()) {
addDevice = true;
}
else {
} else {
VkPhysicalDeviceType collectedType = candidateDevices[0]->m_deviceProperties.deviceType;
if (collectedType == device->m_deviceProperties.deviceType) {
addDevice = true;
}
else if (device->m_deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) {
} else if (device->m_deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) {
// Discrete GPU's are always the best choice
candidateDevices.clear();
addDevice = true;
}
else if (collectedType != VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU && device->m_deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU) {
} else if (collectedType != VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU && device->m_deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU) {
// Integrated GPU's are the second best choice
candidateDevices.clear();
addDevice = true;
}
else if (collectedType != VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU && collectedType != VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU && device->m_deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU) {
} else if (collectedType != VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU && collectedType != VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU && device->m_deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU) {
// Virtual GPU's are the 3rd best choice
candidateDevices.clear();
addDevice = true;

View File

@@ -43,7 +43,7 @@ void KRDirectionalLight::InitNodeInfo(KrNodeInfo* nodeInfo)
// No additional members
}
KRDirectionalLight::KRDirectionalLight(KRScene &scene, std::string name) : KRLight(scene, name)
KRDirectionalLight::KRDirectionalLight(KRScene& scene, std::string name) : KRLight(scene, name)
{
}
@@ -53,24 +53,28 @@ KRDirectionalLight::~KRDirectionalLight()
}
std::string KRDirectionalLight::getElementName() {
std::string KRDirectionalLight::getElementName()
{
return "directional_light";
}
Vector3 KRDirectionalLight::getWorldLightDirection() {
Vector3 KRDirectionalLight::getWorldLightDirection()
{
return Matrix4::Dot(getWorldRotation().rotationMatrix(), getLocalLightDirection());
}
Vector3 KRDirectionalLight::getLocalLightDirection() {
Vector3 KRDirectionalLight::getLocalLightDirection()
{
return Vector3::Up(); //&KRF HACK changed from Vector3::Forward(); - to compensate for the way Maya handles post rotation.
}
int KRDirectionalLight::configureShadowBufferViewports(const KRViewport &viewport) {
int KRDirectionalLight::configureShadowBufferViewports(const KRViewport& viewport)
{
const float KRENGINE_SHADOW_BOUNDS_EXTRA_SCALE = 1.25f; // Scale to apply to view frustrum bounds so that we don't need to refresh shadows on every frame
int cShadows = 1;
for(int iShadow=0; iShadow < cShadows; iShadow++) {
for (int iShadow = 0; iShadow < cShadows; iShadow++) {
/*
TODO - Determine if we still need this...
@@ -87,7 +91,7 @@ int KRDirectionalLight::configureShadowBufferViewports(const KRViewport &viewpor
Vector3 shadowLook = -Vector3::Normalize(getWorldLightDirection());
Vector3 shadowUp = Vector3::Create(0.0, 1.0, 0.0);
if(Vector3::Dot(shadowUp, shadowLook) > 0.99f) shadowUp = Vector3::Create(0.0, 0.0, 1.0); // Ensure shadow look direction is not parallel with the shadowUp direction
if (Vector3::Dot(shadowUp, shadowLook) > 0.99f) shadowUp = Vector3::Create(0.0, 0.0, 1.0); // Ensure shadow look direction is not parallel with the shadowUp direction
// Matrix4 matShadowView = Matrix4::LookAt(viewport.getCameraPosition() - shadowLook, viewport.getCameraPosition(), shadowUp);
// Matrix4 matShadowProjection = Matrix4();
@@ -97,7 +101,7 @@ int KRDirectionalLight::configureShadowBufferViewports(const KRViewport &viewpor
Matrix4 matShadowProjection = Matrix4();
AABB shadowSpaceFrustrumSliceBounds = AABB::Create(worldSpacefrustrumSliceBounds.min, worldSpacefrustrumSliceBounds.max, Matrix4::Invert(matShadowProjection));
AABB shadowSpaceSceneBounds = AABB::Create(getScene().getRootOctreeBounds().min, getScene().getRootOctreeBounds().max, Matrix4::Invert(matShadowProjection));
if(shadowSpaceSceneBounds.min.z < shadowSpaceFrustrumSliceBounds.min.z) shadowSpaceFrustrumSliceBounds.min.z = shadowSpaceSceneBounds.min.z; // Include any potential shadow casters that are outside the view frustrum
if (shadowSpaceSceneBounds.min.z < shadowSpaceFrustrumSliceBounds.min.z) shadowSpaceFrustrumSliceBounds.min.z = shadowSpaceSceneBounds.min.z; // Include any potential shadow casters that are outside the view frustrum
matShadowProjection.scale(1.0f / shadowSpaceFrustrumSliceBounds.size().x, 1.0f / shadowSpaceFrustrumSliceBounds.size().y, 1.0f / shadowSpaceFrustrumSliceBounds.size().z);
Matrix4 matBias;
@@ -108,7 +112,7 @@ int KRDirectionalLight::configureShadowBufferViewports(const KRViewport &viewpor
AABB prevShadowBounds = AABB::Create(-Vector3::One(), Vector3::One(), Matrix4::Invert(m_shadowViewports[iShadow].getViewProjectionMatrix()));
AABB minimumShadowBounds = AABB::Create(-Vector3::One(), Vector3::One(), Matrix4::Invert(newShadowViewport.getViewProjectionMatrix()));
minimumShadowBounds.scale(1.0f / KRENGINE_SHADOW_BOUNDS_EXTRA_SCALE);
if(!prevShadowBounds.contains(minimumShadowBounds) || !shadowValid[iShadow] || true) { // FINDME, HACK - Re-generating the shadow map every frame. This should only be needed if the shadow contains non-static geometry
if (!prevShadowBounds.contains(minimumShadowBounds) || !shadowValid[iShadow] || true) { // FINDME, HACK - Re-generating the shadow map every frame. This should only be needed if the shadow contains non-static geometry
m_shadowViewports[iShadow] = newShadowViewport;
shadowValid[iShadow] = false;
fprintf(stderr, "Kraken - Generate shadow maps...\n");
@@ -118,16 +122,17 @@ int KRDirectionalLight::configureShadowBufferViewports(const KRViewport &viewpor
return 1;
}
void KRDirectionalLight::render(RenderInfo& ri) {
void KRDirectionalLight::render(RenderInfo& ri)
{
if(m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
if (m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
KRLight::render(ri);
if(ri.renderPass == KRNode::RENDER_PASS_DEFERRED_LIGHTS) {
if (ri.renderPass == KRNode::RENDER_PASS_DEFERRED_LIGHTS) {
// Lights are rendered on the second pass of the deferred renderer
std::vector<KRDirectionalLight *> this_light;
std::vector<KRDirectionalLight*> this_light;
this_light.push_back(this);
Matrix4 matModelViewInverseTranspose = ri.viewport.getViewMatrix() * getModelMatrix();
@@ -151,7 +156,7 @@ void KRDirectionalLight::render(RenderInfo& ri) {
info.vertexAttributes = vertices.getVertexAttributes();
info.modelFormat = ModelFormat::KRENGINE_MODEL_FORMAT_STRIP;
KRPipeline *pShader = getContext().getPipelineManager()->getPipeline(*ri.surface, info);
KRPipeline* pShader = getContext().getPipelineManager()->getPipeline(*ri.surface, info);
pShader->setUniform(KRPipeline::Uniform::light_direction_view_space, light_direction_view_space);
pShader->setUniform(KRPipeline::Uniform::light_color, m_color);
pShader->setUniform(KRPipeline::Uniform::light_intensity, m_intensity * 0.01f);

View File

@@ -33,12 +33,13 @@
#include "KRLight.h"
class KRDirectionalLight : public KRLight {
class KRDirectionalLight : public KRLight
{
public:
static void InitNodeInfo(KrNodeInfo* nodeInfo);
KRDirectionalLight(KRScene &scene, std::string name);
KRDirectionalLight(KRScene& scene, std::string name);
virtual ~KRDirectionalLight();
virtual std::string getElementName();
@@ -50,7 +51,7 @@ public:
protected:
virtual int configureShadowBufferViewports(const KRViewport &viewport);
virtual int configureShadowBufferViewports(const KRViewport& viewport);
};

View File

@@ -253,7 +253,8 @@ fprintf(stderr, "Error at line number %d, in file %s. Returned %d for call %s\n"
#endif
typedef enum {
typedef enum
{
STREAM_LEVEL_OUT,
STREAM_LEVEL_IN_LQ,
STREAM_LEVEL_IN_HQ

View File

@@ -37,43 +37,46 @@
#include "KREngine-common.h"
typedef enum KREngineParameterType {KRENGINE_PARAMETER_INT, KRENGINE_PARAMETER_FLOAT, KRENGINE_PARAMETER_BOOL} KREngineParameterType;
typedef enum KREngineParameterType
{
KRENGINE_PARAMETER_INT, KRENGINE_PARAMETER_FLOAT, KRENGINE_PARAMETER_BOOL
} KREngineParameterType;
namespace kraken {
void set_parameter(const std::string &parameter_name, float parameter_value);
void set_debug_text(const std::string &print_text);
void set_parameter(const std::string& parameter_name, float parameter_value);
void set_debug_text(const std::string& print_text);
};
#ifdef __OBJC__
@interface KREngine : NSObject
+ (KREngine *)sharedInstance;
+ (KREngine*)sharedInstance;
@property(nonatomic, readonly) NSDictionary *parameter_names;
@property(nonatomic, assign) KRContext *context;
@property(nonatomic, retain) NSString *debug_text;
@property(nonatomic, assign, readonly) KRRenderSettings *settings;
@property(nonatomic, readonly) NSDictionary* parameter_names;
@property(nonatomic, assign) KRContext* context;
@property(nonatomic, retain) NSString* debug_text;
@property(nonatomic, assign, readonly) KRRenderSettings* settings;
- (id)init;
- (BOOL)loadResource:(NSString *)path;
-(id)init;
-(BOOL)loadResource:(NSString*)path;
// Parameter enumeration interface
-(int)getParameterCount;
-(NSString *)getParameterNameWithIndex: (int)i;
-(NSString *)getParameterLabelWithIndex: (int)i;
-(NSString*)getParameterNameWithIndex: (int)i;
-(NSString*)getParameterLabelWithIndex: (int)i;
-(KREngineParameterType)getParameterTypeWithIndex: (int)i;
-(float)getParameterMinWithIndex: (int)i;
-(float)getParameterMaxWithIndex: (int)i;
-(float)getParameterValueWithIndex: (int)i;
-(void)setParameterValueWithIndex: (int)i Value: (float)v;
-(void)setParameterValueWithName: (NSString *)name Value: (float)v;
-(int)getParameterIndexWithName: (NSString *)name;
-(void)setParameterValueWithIndex: (int)i Value : (float)v;
-(void)setParameterValueWithName: (NSString*)name Value : (float)v;
-(int)getParameterIndexWithName: (NSString*)name;
- (void)renderScene: (KRScene *)pScene WithDeltaTime: (float)deltaTime AndWidth: (int)width AndHeight: (int)height AndDefaultFBO: (GLint)defaultFBO;
-(void)renderScene: (KRScene*)pScene WithDeltaTime : (float)deltaTime AndWidth : (int)width AndHeight : (int)height AndDefaultFBO : (GLint)defaultFBO;
//- (void)renderScene: (KRScene *)pScene WithDeltaTime: (float)deltaTime;
- (void)setNearZ: (float)dNearZ;
- (void)setFarZ: (float)dFarZ;
-(void)setNearZ: (float)dNearZ;
-(void)setFarZ: (float)dFarZ;
@end

View File

@@ -35,7 +35,7 @@
namespace kraken {
void setXMLAttribute(const std::string &base_name, tinyxml2::XMLElement *e, const Vector3 &value, const Vector3 &default_value)
void setXMLAttribute(const std::string& base_name, tinyxml2::XMLElement* e, const Vector3& value, const Vector3& default_value)
{
// TODO - Increase number of digits after the decimal in floating point format (6 -> 12?)
// FINDME, TODO - This needs optimization...
@@ -46,7 +46,7 @@ void setXMLAttribute(const std::string &base_name, tinyxml2::XMLElement *e, cons
}
}
const Vector3 getXMLAttribute(const std::string &base_name, tinyxml2::XMLElement *e, const Vector3 &default_value)
const Vector3 getXMLAttribute(const std::string& base_name, tinyxml2::XMLElement* e, const Vector3& default_value)
{
Vector3 value;
if (e->QueryFloatAttribute((base_name + "_x").c_str(), &value.x) == tinyxml2::XML_SUCCESS

View File

@@ -60,7 +60,7 @@ float const PI = 3.141592653589793f;
float const D2R = PI * 2 / 360;
namespace kraken {
void setXMLAttribute(const std::string &base_name, ::tinyxml2::XMLElement *e, const Vector3 &value, const Vector3 &default_value);
const Vector3 getXMLAttribute(const std::string &base_name, ::tinyxml2::XMLElement *e, const Vector3 &default_value);
void setXMLAttribute(const std::string& base_name, ::tinyxml2::XMLElement* e, const Vector3& value, const Vector3& default_value);
const Vector3 getXMLAttribute(const std::string& base_name, ::tinyxml2::XMLElement* e, const Vector3& default_value);
} // namespace kraken

View File

@@ -44,7 +44,7 @@ void KRLODGroup::InitNodeInfo(KrNodeInfo* nodeInfo)
nodeInfo->lod_group.use_world_units = true;
}
KRLODGroup::KRLODGroup(KRScene &scene, std::string name) : KRNode(scene, name)
KRLODGroup::KRLODGroup(KRScene& scene, std::string name) : KRNode(scene, name)
{
m_min_distance = 0.0f;
m_max_distance = 0.0f;
@@ -53,16 +53,16 @@ KRLODGroup::KRLODGroup(KRScene &scene, std::string name) : KRNode(scene, name)
}
KRLODGroup::~KRLODGroup()
{
}
{}
std::string KRLODGroup::getElementName() {
std::string KRLODGroup::getElementName()
{
return "lod_group";
}
tinyxml2::XMLElement *KRLODGroup::saveXML( tinyxml2::XMLNode *parent)
tinyxml2::XMLElement* KRLODGroup::saveXML(tinyxml2::XMLNode* parent)
{
tinyxml2::XMLElement *e = KRNode::saveXML(parent);
tinyxml2::XMLElement* e = KRNode::saveXML(parent);
e->SetAttribute("min_distance", m_min_distance);
e->SetAttribute("max_distance", m_max_distance);
@@ -79,66 +79,66 @@ tinyxml2::XMLElement *KRLODGroup::saveXML( tinyxml2::XMLNode *parent)
return e;
}
void KRLODGroup::loadXML(tinyxml2::XMLElement *e)
void KRLODGroup::loadXML(tinyxml2::XMLElement* e)
{
KRNode::loadXML(e);
m_min_distance = 0.0f;
if(e->QueryFloatAttribute("min_distance", &m_min_distance) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("min_distance", &m_min_distance) != tinyxml2::XML_SUCCESS) {
m_min_distance = 0.0f;
}
m_max_distance = 0.0f;
if(e->QueryFloatAttribute("max_distance", &m_max_distance) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("max_distance", &m_max_distance) != tinyxml2::XML_SUCCESS) {
m_max_distance = 0.0f;
}
float x=0.0f, y=0.0f, z=0.0f;
if(e->QueryFloatAttribute("reference_min_x", &x) != tinyxml2::XML_SUCCESS) {
float x = 0.0f, y = 0.0f, z = 0.0f;
if (e->QueryFloatAttribute("reference_min_x", &x) != tinyxml2::XML_SUCCESS) {
x = 0.0f;
}
if(e->QueryFloatAttribute("reference_min_y", &y) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("reference_min_y", &y) != tinyxml2::XML_SUCCESS) {
y = 0.0f;
}
if(e->QueryFloatAttribute("reference_min_z", &z) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("reference_min_z", &z) != tinyxml2::XML_SUCCESS) {
z = 0.0f;
}
m_reference.min = Vector3::Create(x,y,z);
m_reference.min = Vector3::Create(x, y, z);
x=0.0f; y=0.0f; z=0.0f;
if(e->QueryFloatAttribute("reference_max_x", &x) != tinyxml2::XML_SUCCESS) {
x = 0.0f; y = 0.0f; z = 0.0f;
if (e->QueryFloatAttribute("reference_max_x", &x) != tinyxml2::XML_SUCCESS) {
x = 0.0f;
}
if(e->QueryFloatAttribute("reference_max_y", &y) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("reference_max_y", &y) != tinyxml2::XML_SUCCESS) {
y = 0.0f;
}
if(e->QueryFloatAttribute("reference_max_z", &z) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("reference_max_z", &z) != tinyxml2::XML_SUCCESS) {
z = 0.0f;
}
m_reference.max = Vector3::Create(x,y,z);
m_reference.max = Vector3::Create(x, y, z);
m_use_world_units = true;
if(e->QueryBoolAttribute("use_world_units", &m_use_world_units) != tinyxml2::XML_SUCCESS) {
if (e->QueryBoolAttribute("use_world_units", &m_use_world_units) != tinyxml2::XML_SUCCESS) {
m_use_world_units = true;
}
}
const AABB &KRLODGroup::getReference() const
const AABB& KRLODGroup::getReference() const
{
return m_reference;
}
void KRLODGroup::setReference(const AABB &reference)
void KRLODGroup::setReference(const AABB& reference)
{
m_reference = reference;
}
KRNode::LodVisibility KRLODGroup::calcLODVisibility(const KRViewport &viewport)
KRNode::LodVisibility KRLODGroup::calcLODVisibility(const KRViewport& viewport)
{
if(m_min_distance == 0 && m_max_distance == 0) {
if (m_min_distance == 0 && m_max_distance == 0) {
return LOD_VISIBILITY_VISIBLE;
} else {
float lod_bias = viewport.getLODBias();
@@ -152,7 +152,7 @@ KRNode::LodVisibility KRLODGroup::calcLODVisibility(const KRViewport &viewport)
Vector3 local_camera_position = worldToLocal(world_camera_position);
Vector3 local_reference_point = m_reference.nearestPoint(local_camera_position);
if(m_use_world_units) {
if (m_use_world_units) {
Vector3 world_reference_point = localToWorld(local_reference_point);
sqr_distance = (world_camera_position - world_reference_point).sqrMagnitude() * (lod_bias * lod_bias);
sqr_prestream_distance = (float)(getContext().KRENGINE_PRESTREAM_DISTANCE * getContext().KRENGINE_PRESTREAM_DISTANCE);
@@ -166,9 +166,9 @@ KRNode::LodVisibility KRLODGroup::calcLODVisibility(const KRViewport &viewport)
float sqr_min_visible_distance = m_min_distance * m_min_distance;
float sqr_max_visible_distance = m_max_distance * m_max_distance;
if((sqr_distance >= sqr_min_visible_distance || m_min_distance == 0) && (sqr_distance < sqr_max_visible_distance || m_max_distance == 0)) {
if ((sqr_distance >= sqr_min_visible_distance || m_min_distance == 0) && (sqr_distance < sqr_max_visible_distance || m_max_distance == 0)) {
return LOD_VISIBILITY_VISIBLE;
} else if((sqr_distance >= sqr_min_visible_distance - sqr_prestream_distance || m_min_distance == 0) && (sqr_distance < sqr_max_visible_distance + sqr_prestream_distance || m_max_distance == 0)) {
} else if ((sqr_distance >= sqr_min_visible_distance - sqr_prestream_distance || m_min_distance == 0) && (sqr_distance < sqr_max_visible_distance + sqr_prestream_distance || m_max_distance == 0)) {
return LOD_VISIBILITY_PRESTREAM;
} else {
return LOD_VISIBILITY_HIDDEN;

View File

@@ -34,26 +34,27 @@
#include "KRResource.h"
#include "KRNode.h"
class KRLODGroup : public KRNode {
class KRLODGroup : public KRNode
{
public:
static void InitNodeInfo(KrNodeInfo* nodeInfo);
KRLODGroup(KRScene &scene, std::string name);
KRLODGroup(KRScene& scene, std::string name);
virtual ~KRLODGroup();
virtual std::string getElementName();
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual void loadXML(tinyxml2::XMLElement *e);
virtual tinyxml2::XMLElement* saveXML(tinyxml2::XMLNode* parent);
virtual void loadXML(tinyxml2::XMLElement* e);
float getMinDistance();
float getMaxDistance();
void setMinDistance(float min_distance);
void setMaxDistance(float max_distance);
const AABB &getReference() const;
void setReference(const AABB &reference);
const AABB& getReference() const;
void setReference(const AABB& reference);
void setUseWorldUnits(bool use_world_units);
bool getUseWorldUnits() const;
LodVisibility calcLODVisibility(const KRViewport &viewport);
LodVisibility calcLODVisibility(const KRViewport& viewport);
private:
float m_min_distance;

View File

@@ -40,43 +40,43 @@ void KRLODSet::InitNodeInfo(KrNodeInfo* nodeInfo)
// No additional members
}
KRLODSet::KRLODSet(KRScene &scene, std::string name) : KRNode(scene, name)
KRLODSet::KRLODSet(KRScene& scene, std::string name) : KRNode(scene, name)
{
}
KRLODSet::~KRLODSet()
{
}
{}
std::string KRLODSet::getElementName() {
std::string KRLODSet::getElementName()
{
return "lod_set";
}
tinyxml2::XMLElement *KRLODSet::saveXML( tinyxml2::XMLNode *parent)
tinyxml2::XMLElement* KRLODSet::saveXML(tinyxml2::XMLNode* parent)
{
tinyxml2::XMLElement *e = KRNode::saveXML(parent);
tinyxml2::XMLElement* e = KRNode::saveXML(parent);
return e;
}
void KRLODSet::loadXML(tinyxml2::XMLElement *e)
void KRLODSet::loadXML(tinyxml2::XMLElement* e)
{
KRNode::loadXML(e);
}
void KRLODSet::updateLODVisibility(const KRViewport &viewport)
void KRLODSet::updateLODVisibility(const KRViewport& viewport)
{
if(m_lod_visible >= LOD_VISIBILITY_PRESTREAM) {
if (m_lod_visible >= LOD_VISIBILITY_PRESTREAM) {
/*
// FINDME, TODO, HACK - Disabled streamer delayed LOD load due to performance issues:
KRLODGroup *new_active_lod_group = NULL;
*/
// Upgrade and downgrade LOD groups as needed
for(std::set<KRNode *>::iterator itr=m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
KRLODGroup *lod_group = dynamic_cast<KRLODGroup *>(*itr);
for (std::set<KRNode*>::iterator itr = m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
KRLODGroup* lod_group = dynamic_cast<KRLODGroup*>(*itr);
assert(lod_group != NULL);
LodVisibility group_lod_visibility = KRMIN(lod_group->calcLODVisibility(viewport), m_lod_visible);
/*
@@ -99,10 +99,10 @@ void KRLODSet::updateLODVisibility(const KRViewport &viewport)
*/
bool streamer_ready = true;
if(streamer_ready) {
if (streamer_ready) {
// Upgrade and downgrade LOD groups as needed
for(std::set<KRNode *>::iterator itr=m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
KRLODGroup *lod_group = dynamic_cast<KRLODGroup *>(*itr);
for (std::set<KRNode*>::iterator itr = m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
KRLODGroup* lod_group = dynamic_cast<KRLODGroup*>(*itr);
assert(lod_group != NULL);
LodVisibility group_lod_visibility = KRMIN(lod_group->calcLODVisibility(viewport), m_lod_visible);
lod_group->setLODVisibility(group_lod_visibility);
@@ -115,31 +115,31 @@ void KRLODSet::updateLODVisibility(const KRViewport &viewport)
void KRLODSet::setLODVisibility(KRNode::LodVisibility lod_visibility)
{
if(lod_visibility == LOD_VISIBILITY_HIDDEN) {
if (lod_visibility == LOD_VISIBILITY_HIDDEN) {
KRNode::setLODVisibility(lod_visibility);
} else if(m_lod_visible != lod_visibility) {
} else if (m_lod_visible != lod_visibility) {
// Don't automatically recurse into our children, as only one of those will be activated, by updateLODVisibility
if(m_lod_visible == LOD_VISIBILITY_HIDDEN && lod_visibility >= LOD_VISIBILITY_PRESTREAM) {
if (m_lod_visible == LOD_VISIBILITY_HIDDEN && lod_visibility >= LOD_VISIBILITY_PRESTREAM) {
getScene().notify_sceneGraphCreate(this);
}
m_lod_visible = lod_visibility;
}
}
kraken_stream_level KRLODSet::getStreamLevel(const KRViewport &viewport)
kraken_stream_level KRLODSet::getStreamLevel(const KRViewport& viewport)
{
KRLODGroup *new_active_lod_group = NULL;
KRLODGroup* new_active_lod_group = NULL;
// Upgrade and downgrade LOD groups as needed
for(std::set<KRNode *>::iterator itr=m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
KRLODGroup *lod_group = dynamic_cast<KRLODGroup *>(*itr);
for (std::set<KRNode*>::iterator itr = m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
KRLODGroup* lod_group = dynamic_cast<KRLODGroup*>(*itr);
assert(lod_group != NULL);
if(lod_group->calcLODVisibility(viewport) == LOD_VISIBILITY_VISIBLE) {
if (lod_group->calcLODVisibility(viewport) == LOD_VISIBILITY_VISIBLE) {
new_active_lod_group = lod_group;
}
}
if(new_active_lod_group) {
if (new_active_lod_group) {
return new_active_lod_group->getStreamLevel(viewport);
} else {
return kraken_stream_level::STREAM_LEVEL_IN_HQ;

View File

@@ -36,18 +36,19 @@
class KRLODGroup;
class KRLODSet : public KRNode {
class KRLODSet : public KRNode
{
public:
static void InitNodeInfo(KrNodeInfo* nodeInfo);
KRLODSet(KRScene &scene, std::string name);
KRLODSet(KRScene& scene, std::string name);
virtual ~KRLODSet();
virtual std::string getElementName();
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual void loadXML(tinyxml2::XMLElement *e);
virtual tinyxml2::XMLElement* saveXML(tinyxml2::XMLNode* parent);
virtual void loadXML(tinyxml2::XMLElement* e);
virtual void updateLODVisibility(const KRViewport &viewport);
virtual void updateLODVisibility(const KRViewport& viewport);
virtual void setLODVisibility(LodVisibility lod_visibility);
virtual kraken_stream_level getStreamLevel(const KRViewport &viewport);
virtual kraken_stream_level getStreamLevel(const KRViewport& viewport);
};

View File

@@ -60,7 +60,7 @@ void KRLight::InitNodeInfo(KrNodeInfo* nodeInfo)
nodeInfo->light.light_shafts = true;
}
KRLight::KRLight(KRScene &scene, std::string name) : KRNode(scene, name)
KRLight::KRLight(KRScene& scene, std::string name) : KRNode(scene, name)
{
m_intensity = 1.0f;
m_dust_particle_intensity = 1.0f;
@@ -79,7 +79,7 @@ KRLight::KRLight(KRScene &scene, std::string name) : KRNode(scene, name)
// Initialize shadow buffers
m_cShadowBuffers = 0;
for(int iBuffer=0; iBuffer < KRENGINE_MAX_SHADOW_BUFFERS; iBuffer++) {
for (int iBuffer = 0; iBuffer < KRENGINE_MAX_SHADOW_BUFFERS; iBuffer++) {
shadowFramebuffer[iBuffer] = 0;
shadowDepthTexture[iBuffer] = 0;
shadowValid[iBuffer] = false;
@@ -88,16 +88,16 @@ KRLight::KRLight(KRScene &scene, std::string name) : KRNode(scene, name)
KRLight::~KRLight()
{
if(m_occlusionQuery) {
if (m_occlusionQuery) {
GLDEBUG(glDeleteQueriesEXT(1, &m_occlusionQuery));
m_occlusionQuery = 0;
}
allocateShadowBuffers(0);
}
tinyxml2::XMLElement *KRLight::saveXML( tinyxml2::XMLNode *parent)
tinyxml2::XMLElement* KRLight::saveXML(tinyxml2::XMLNode* parent)
{
tinyxml2::XMLElement *e = KRNode::saveXML(parent);
tinyxml2::XMLElement* e = KRNode::saveXML(parent);
e->SetAttribute("intensity", m_intensity);
e->SetAttribute("color_r", m_color.x);
e->SetAttribute("color_g", m_color.y);
@@ -114,61 +114,62 @@ tinyxml2::XMLElement *KRLight::saveXML( tinyxml2::XMLNode *parent)
return e;
}
void KRLight::loadXML(tinyxml2::XMLElement *e) {
void KRLight::loadXML(tinyxml2::XMLElement* e)
{
KRNode::loadXML(e);
float x=1.0f,y=1.0f,z=1.0f;
if(e->QueryFloatAttribute("color_r", &x) != tinyxml2::XML_SUCCESS) {
float x = 1.0f, y = 1.0f, z = 1.0f;
if (e->QueryFloatAttribute("color_r", &x) != tinyxml2::XML_SUCCESS) {
x = 1.0;
}
if(e->QueryFloatAttribute("color_g", &y) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("color_g", &y) != tinyxml2::XML_SUCCESS) {
y = 1.0;
}
if(e->QueryFloatAttribute("color_b", &z) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("color_b", &z) != tinyxml2::XML_SUCCESS) {
z = 1.0;
}
m_color = Vector3::Create(x,y,z);
m_color = Vector3::Create(x, y, z);
if(e->QueryFloatAttribute("intensity", &m_intensity) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("intensity", &m_intensity) != tinyxml2::XML_SUCCESS) {
m_intensity = 100.0;
}
if(e->QueryFloatAttribute("decay_start", &m_decayStart) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("decay_start", &m_decayStart) != tinyxml2::XML_SUCCESS) {
m_decayStart = 0.0;
}
if(e->QueryFloatAttribute("flare_size", &m_flareSize) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("flare_size", &m_flareSize) != tinyxml2::XML_SUCCESS) {
m_flareSize = 0.0;
}
if(e->QueryFloatAttribute("flare_occlusion_size", &m_flareOcclusionSize) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("flare_occlusion_size", &m_flareOcclusionSize) != tinyxml2::XML_SUCCESS) {
m_flareOcclusionSize = 0.05f;
}
if(e->QueryBoolAttribute("casts_shadow", &m_casts_shadow) != tinyxml2::XML_SUCCESS) {
if (e->QueryBoolAttribute("casts_shadow", &m_casts_shadow) != tinyxml2::XML_SUCCESS) {
m_casts_shadow = true;
}
if(e->QueryBoolAttribute("light_shafts", &m_light_shafts) != tinyxml2::XML_SUCCESS) {
if (e->QueryBoolAttribute("light_shafts", &m_light_shafts) != tinyxml2::XML_SUCCESS) {
m_light_shafts = true;
}
m_dust_particle_density = 0.1f;
if(e->QueryFloatAttribute("dust_particle_density", &m_dust_particle_density) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("dust_particle_density", &m_dust_particle_density) != tinyxml2::XML_SUCCESS) {
m_dust_particle_density = 0.1f;
}
m_dust_particle_size = 1.0f;
if(e->QueryFloatAttribute("dust_particle_size", &m_dust_particle_size) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("dust_particle_size", &m_dust_particle_size) != tinyxml2::XML_SUCCESS) {
m_dust_particle_size = 1.0f;
}
m_dust_particle_intensity = 1.0f;
if(e->QueryFloatAttribute("dust_particle_intensity", &m_dust_particle_intensity) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("dust_particle_intensity", &m_dust_particle_intensity) != tinyxml2::XML_SUCCESS) {
m_dust_particle_intensity = 1.0f;
}
const char *szFlareTexture = e->Attribute("flare_texture");
if(szFlareTexture) {
const char* szFlareTexture = e->Attribute("flare_texture");
if (szFlareTexture) {
m_flareTexture = szFlareTexture;
} else {
m_flareTexture = "";
@@ -176,58 +177,68 @@ void KRLight::loadXML(tinyxml2::XMLElement *e) {
m_pFlareTexture = NULL;
}
void KRLight::setFlareTexture(std::string flare_texture) {
void KRLight::setFlareTexture(std::string flare_texture)
{
m_flareTexture = flare_texture;
m_pFlareTexture = NULL;
}
void KRLight::setFlareSize(float flare_size) {
void KRLight::setFlareSize(float flare_size)
{
m_flareSize = flare_size;
}
void KRLight::setFlareOcclusionSize(float occlusion_size) {
void KRLight::setFlareOcclusionSize(float occlusion_size)
{
m_flareOcclusionSize = occlusion_size;
}
void KRLight::setIntensity(float intensity) {
void KRLight::setIntensity(float intensity)
{
m_intensity = intensity;
}
float KRLight::getIntensity() {
float KRLight::getIntensity()
{
return m_intensity;
}
const Vector3 &KRLight::getColor() {
const Vector3& KRLight::getColor()
{
return m_color;
}
void KRLight::setColor(const Vector3 &color) {
void KRLight::setColor(const Vector3& color)
{
m_color = color;
}
void KRLight::setDecayStart(float decayStart) {
void KRLight::setDecayStart(float decayStart)
{
m_decayStart = decayStart;
}
float KRLight::getDecayStart() {
float KRLight::getDecayStart()
{
return m_decayStart;
}
void KRLight::render(RenderInfo& ri) {
void KRLight::render(RenderInfo& ri)
{
if(m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
if (m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
KRNode::render(ri);
if(ri.renderPass == KRNode::RENDER_PASS_GENERATE_SHADOWMAPS && (ri.camera->settings.volumetric_environment_enable || ri.camera->settings.dust_particle_enable || (ri.camera->settings.m_cShadowBuffers > 0 && m_casts_shadow))) {
if (ri.renderPass == KRNode::RENDER_PASS_GENERATE_SHADOWMAPS && (ri.camera->settings.volumetric_environment_enable || ri.camera->settings.dust_particle_enable || (ri.camera->settings.m_cShadowBuffers > 0 && m_casts_shadow))) {
allocateShadowBuffers(configureShadowBufferViewports(ri.viewport));
renderShadowBuffers(ri);
}
if(ri.renderPass == KRNode::RENDER_PASS_ADDITIVE_PARTICLES && ri.camera->settings.dust_particle_enable) {
if (ri.renderPass == KRNode::RENDER_PASS_ADDITIVE_PARTICLES && ri.camera->settings.dust_particle_enable) {
// Render brownian particles for dust floating in air
if(m_cShadowBuffers >= 1 && shadowValid[0] && m_dust_particle_density > 0.0f && m_dust_particle_size > 0.0f && m_dust_particle_intensity > 0.0f) {
if (m_cShadowBuffers >= 1 && shadowValid[0] && m_dust_particle_density > 0.0f && m_dust_particle_size > 0.0f && m_dust_particle_intensity > 0.0f) {
if(ri.viewport.visible(getBounds()) || true) { // FINDME, HACK need to remove "|| true"?
if (ri.viewport.visible(getBounds()) || true) { // FINDME, HACK need to remove "|| true"?
float particle_range = 600.0f;
@@ -240,19 +251,19 @@ void KRLight::render(RenderInfo& ri) {
particleModelMatrix.scale(particle_range); // Scale the box symetrically to ensure that we don't have an uneven distribution of particles for different angles of the view frustrum
particleModelMatrix.translate(ri.viewport.getCameraPosition());
std::vector<KRDirectionalLight *> this_directional_light;
std::vector<KRSpotLight *> this_spot_light;
std::vector<KRPointLight *> this_point_light;
KRDirectionalLight *directional_light = dynamic_cast<KRDirectionalLight *>(this);
KRSpotLight *spot_light = dynamic_cast<KRSpotLight *>(this);
KRPointLight *point_light = dynamic_cast<KRPointLight *>(this);
if(directional_light) {
std::vector<KRDirectionalLight*> this_directional_light;
std::vector<KRSpotLight*> this_spot_light;
std::vector<KRPointLight*> this_point_light;
KRDirectionalLight* directional_light = dynamic_cast<KRDirectionalLight*>(this);
KRSpotLight* spot_light = dynamic_cast<KRSpotLight*>(this);
KRPointLight* point_light = dynamic_cast<KRPointLight*>(this);
if (directional_light) {
this_directional_light.push_back(directional_light);
}
if(spot_light) {
if (spot_light) {
this_spot_light.push_back(spot_light);
}
if(point_light) {
if (point_light) {
this_point_light.push_back(point_light);
}
@@ -268,7 +279,7 @@ void KRLight::render(RenderInfo& ri) {
info.cullMode = CullMode::kCullNone;
info.vertexAttributes = (1 << KRMesh::KRENGINE_ATTRIB_VERTEX) | (1 << KRMesh::KRENGINE_ATTRIB_TEXUVA);
info.modelFormat = ModelFormat::KRENGINE_MODEL_FORMAT_TRIANGLES;
KRPipeline *pParticleShader = m_pContext->getPipelineManager()->getPipeline(*ri.surface, info);
KRPipeline* pParticleShader = m_pContext->getPipelineManager()->getPipeline(*ri.surface, info);
pParticleShader->setUniform(KRPipeline::Uniform::light_color, m_color * ri.camera->settings.dust_particle_intensity * m_dust_particle_intensity * m_intensity);
pParticleShader->setUniform(KRPipeline::Uniform::particle_origin, Matrix4::DotWDiv(Matrix4::Invert(particleModelMatrix), Vector3::Zero()));
@@ -283,22 +294,22 @@ void KRLight::render(RenderInfo& ri) {
}
if(ri.renderPass == KRNode::RENDER_PASS_VOLUMETRIC_EFFECTS_ADDITIVE && ri.camera->settings.volumetric_environment_enable && m_light_shafts) {
if (ri.renderPass == KRNode::RENDER_PASS_VOLUMETRIC_EFFECTS_ADDITIVE && ri.camera->settings.volumetric_environment_enable && m_light_shafts) {
std::string shader_name = ri.camera->settings.volumetric_environment_downsample != 0 ? "volumetric_fog_downsampled" : "volumetric_fog";
std::vector<KRDirectionalLight *> this_directional_light;
std::vector<KRSpotLight *> this_spot_light;
std::vector<KRPointLight *> this_point_light;
KRDirectionalLight *directional_light = dynamic_cast<KRDirectionalLight *>(this);
KRSpotLight *spot_light = dynamic_cast<KRSpotLight *>(this);
KRPointLight *point_light = dynamic_cast<KRPointLight *>(this);
if(directional_light) {
std::vector<KRDirectionalLight*> this_directional_light;
std::vector<KRSpotLight*> this_spot_light;
std::vector<KRPointLight*> this_point_light;
KRDirectionalLight* directional_light = dynamic_cast<KRDirectionalLight*>(this);
KRSpotLight* spot_light = dynamic_cast<KRSpotLight*>(this);
KRPointLight* point_light = dynamic_cast<KRPointLight*>(this);
if (directional_light) {
this_directional_light.push_back(directional_light);
}
if(spot_light) {
if (spot_light) {
this_spot_light.push_back(spot_light);
}
if(point_light) {
if (point_light) {
this_point_light.push_back(point_light);
}
@@ -314,7 +325,7 @@ void KRLight::render(RenderInfo& ri) {
info.vertexAttributes = (1 << KRMesh::KRENGINE_ATTRIB_VERTEX);
info.modelFormat = ModelFormat::KRENGINE_MODEL_FORMAT_TRIANGLES;
KRPipeline *pFogShader = m_pContext->getPipelineManager()->getPipeline(*ri.surface, info);
KRPipeline* pFogShader = m_pContext->getPipelineManager()->getPipeline(*ri.surface, info);
int slice_count = (int)(ri.camera->settings.volumetric_environment_quality * 495.0) + 5;
@@ -331,15 +342,15 @@ void KRLight::render(RenderInfo& ri) {
}
if(ri.renderPass == KRNode::RENDER_PASS_PARTICLE_OCCLUSION) {
if(m_flareTexture.size() && m_flareSize > 0.0f) {
if (ri.renderPass == KRNode::RENDER_PASS_PARTICLE_OCCLUSION) {
if (m_flareTexture.size() && m_flareSize > 0.0f) {
KRMesh* sphereModel = getContext().getMeshManager()->getMaxLODModel("__sphere");
if (sphereModel) {
Matrix4 occlusion_test_sphere_matrix = Matrix4();
occlusion_test_sphere_matrix.scale(m_localScale * m_flareOcclusionSize);
occlusion_test_sphere_matrix.translate(m_localTranslation);
if(m_parentNode) {
if (m_parentNode) {
occlusion_test_sphere_matrix *= m_parentNode->getModelMatrix();
}
@@ -360,11 +371,11 @@ void KRLight::render(RenderInfo& ri) {
pPipeline->bind(ri.commandBuffer, *info.pCamera, ri.viewport, occlusion_test_sphere_matrix, info.point_lights, info.directional_lights, info.spot_lights, info.renderPass);
GLDEBUG(glGenQueriesEXT(1, &m_occlusionQuery));
#if TARGET_OS_IPHONE || defined(ANDROID)
#if TARGET_OS_IPHONE || defined(ANDROID)
GLDEBUG(glBeginQueryEXT(GL_ANY_SAMPLES_PASSED_EXT, m_occlusionQuery));
#else
#else
GLDEBUG(glBeginQuery(GL_SAMPLES_PASSED, m_occlusionQuery));
#endif
#endif
sphereModel->renderNoMaterials(ri.commandBuffer, ri.renderPass, getName(), "occlusion_test", 1.0f);
@@ -378,21 +389,21 @@ void KRLight::render(RenderInfo& ri) {
}
}
if(ri.renderPass == KRNode::RENDER_PASS_ADDITIVE_PARTICLES) {
if(m_flareTexture.size() && m_flareSize > 0.0f) {
if (ri.renderPass == KRNode::RENDER_PASS_ADDITIVE_PARTICLES) {
if (m_flareTexture.size() && m_flareSize > 0.0f) {
if(m_occlusionQuery) {
if (m_occlusionQuery) {
GLuint params = 0;
GLDEBUG(glGetQueryObjectuivEXT(m_occlusionQuery, GL_QUERY_RESULT_EXT, &params));
GLDEBUG(glDeleteQueriesEXT(1, &m_occlusionQuery));
if(params) {
if (params) {
if(!m_pFlareTexture && m_flareTexture.size()) {
if (!m_pFlareTexture && m_flareTexture.size()) {
m_pFlareTexture = getContext().getTextureManager()->getTexture(m_flareTexture);
}
if(m_pFlareTexture) {
if (m_pFlareTexture) {
KRMeshManager::KRVBOData& vertices = getContext().getMeshManager()->KRENGINE_VBO_DATA_2D_SQUARE_VERTICES;
// Render light flare on transparency pass
@@ -410,7 +421,7 @@ void KRLight::render(RenderInfo& ri) {
info.modelFormat = ModelFormat::KRENGINE_MODEL_FORMAT_STRIP;
KRPipeline *pShader = getContext().getPipelineManager()->getPipeline(*ri.surface, info);
KRPipeline* pShader = getContext().getPipelineManager()->getPipeline(*ri.surface, info);
pShader->setUniform(KRPipeline::Uniform::material_alpha, 1.0f);
pShader->setUniform(KRPipeline::Uniform::flare_size, m_flareSize);
pShader->bind(ri.commandBuffer, *ri.camera, ri.viewport, getModelMatrix(), &ri.point_lights, &ri.directional_lights, &ri.spot_lights, ri.renderPass);
@@ -426,9 +437,10 @@ void KRLight::render(RenderInfo& ri) {
}
}
void KRLight::allocateShadowBuffers(int cBuffers) {
void KRLight::allocateShadowBuffers(int cBuffers)
{
// First deallocate buffers no longer needed
for(int iShadow = cBuffers; iShadow < KRENGINE_MAX_SHADOW_BUFFERS; iShadow++) {
for (int iShadow = cBuffers; iShadow < KRENGINE_MAX_SHADOW_BUFFERS; iShadow++) {
if (shadowDepthTexture[iShadow]) {
GLDEBUG(glDeleteTextures(1, shadowDepthTexture + iShadow));
shadowDepthTexture[iShadow] = 0;
@@ -441,10 +453,10 @@ void KRLight::allocateShadowBuffers(int cBuffers) {
}
// Allocate newly required buffers
for(int iShadow = 0; iShadow < cBuffers; iShadow++) {
for (int iShadow = 0; iShadow < cBuffers; iShadow++) {
Vector2 viewportSize = m_shadowViewports[iShadow].getSize();
if(!shadowDepthTexture[iShadow]) {
if (!shadowDepthTexture[iShadow]) {
shadowValid[iShadow] = false;
GLDEBUG(glGenFramebuffers(1, shadowFramebuffer + iShadow));
@@ -454,7 +466,7 @@ void KRLight::allocateShadowBuffers(int cBuffers) {
GLDEBUG(glBindFramebuffer(GL_FRAMEBUFFER, shadowFramebuffer[iShadow]));
// ----- Create Depth Texture for shadowFramebuffer -----
GLDEBUG( glBindTexture(GL_TEXTURE_2D, shadowDepthTexture[iShadow]));
GLDEBUG(glBindTexture(GL_TEXTURE_2D, shadowDepthTexture[iShadow]));
GLDEBUG(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
GLDEBUG(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
m_pContext->getTextureManager()->_setWrapModeS(shadowDepthTexture[iShadow], GL_CLAMP_TO_EDGE);
@@ -481,20 +493,20 @@ void KRLight::deleteBuffers()
void KRLight::invalidateShadowBuffers()
{
for(int iShadow=0; iShadow < m_cShadowBuffers; iShadow++) {
for (int iShadow = 0; iShadow < m_cShadowBuffers; iShadow++) {
shadowValid[iShadow] = false;
}
}
int KRLight::configureShadowBufferViewports(const KRViewport &viewport)
int KRLight::configureShadowBufferViewports(const KRViewport& viewport)
{
return 0;
}
void KRLight::renderShadowBuffers(RenderInfo& ri)
{
for(int iShadow=0; iShadow < m_cShadowBuffers; iShadow++) {
if(!shadowValid[iShadow]) {
for (int iShadow = 0; iShadow < m_cShadowBuffers; iShadow++) {
if (!shadowValid[iShadow]) {
shadowValid[iShadow] = true;
GLDEBUG(glBindFramebuffer(GL_FRAMEBUFFER, shadowFramebuffer[iShadow]));
@@ -521,7 +533,7 @@ void KRLight::renderShadowBuffers(RenderInfo& ri)
info.renderPass = KRNode::RENDER_PASS_FORWARD_TRANSPARENT;
info.rasterMode = RasterMode::kOpaqueLessTest; // TODO - This is sub-optimal. Evaluate increasing depth buffer resolution instead of disabling depth test.
info.cullMode = CullMode::kCullNone; // Disabling culling, which eliminates some self-cast shadow artifacts
KRPipeline *shadowShader = m_pContext->getPipelineManager()->getPipeline(*ri.surface, info);
KRPipeline* shadowShader = m_pContext->getPipelineManager()->getPipeline(*ri.surface, info);
shadowShader->bind(ri.commandBuffer, *ri.camera, m_shadowViewports[iShadow], Matrix4(), nullptr, nullptr, nullptr, KRNode::RENDER_PASS_SHADOWMAP);
@@ -534,9 +546,9 @@ void KRLight::renderShadowBuffers(RenderInfo& ri)
int KRLight::getShadowBufferCount()
{
int cBuffers=0;
for(int iBuffer=0; iBuffer < m_cShadowBuffers; iBuffer++) {
if(shadowValid[iBuffer]) {
int cBuffers = 0;
for (int iBuffer = 0; iBuffer < m_cShadowBuffers; iBuffer++) {
if (shadowValid[iBuffer]) {
cBuffers++;
} else {
break;
@@ -545,12 +557,12 @@ int KRLight::getShadowBufferCount()
return cBuffers;
}
GLuint *KRLight::getShadowTextures()
GLuint* KRLight::getShadowTextures()
{
return shadowDepthTexture;
}
KRViewport *KRLight::getShadowViewports()
KRViewport* KRLight::getShadowViewports()
{
return m_shadowViewports;
}

View File

@@ -42,21 +42,22 @@ static const float KRLIGHT_MIN_INFLUENCE = 0.15f; // 0.05f
#define KRENGINE_SHADOW_MAP_WIDTH 1024
#define KRENGINE_SHADOW_MAP_HEIGHT 1024
class KRLight : public KRNode {
class KRLight : public KRNode
{
public:
static void InitNodeInfo(KrNodeInfo* nodeInfo);
virtual ~KRLight();
virtual std::string getElementName() = 0;
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual void loadXML(tinyxml2::XMLElement *e);
virtual tinyxml2::XMLElement* saveXML(tinyxml2::XMLNode* parent);
virtual void loadXML(tinyxml2::XMLElement* e);
void setIntensity(float intensity);
float getIntensity();
void setDecayStart(float decayStart);
float getDecayStart();
const Vector3 &getColor();
void setColor(const Vector3 &color);
const Vector3& getColor();
void setColor(const Vector3& color);
void setFlareTexture(std::string flare_texture);
void setFlareSize(float flare_size);
@@ -66,19 +67,19 @@ public:
virtual void render(RenderInfo& ri);
int getShadowBufferCount();
GLuint *getShadowTextures();
KRViewport *getShadowViewports();
GLuint* getShadowTextures();
KRViewport* getShadowViewports();
protected:
KRLight(KRScene &scene, std::string name);
KRLight(KRScene& scene, std::string name);
float m_intensity;
float m_decayStart;
Vector3 m_color;
std::string m_flareTexture;
KRTexture *m_pFlareTexture;
KRTexture* m_pFlareTexture;
float m_flareSize;
float m_flareOcclusionSize;
@@ -100,6 +101,6 @@ protected:
void allocateShadowBuffers(int cBuffers);
void invalidateShadowBuffers();
virtual int configureShadowBufferViewports(const KRViewport &viewport);
virtual int configureShadowBufferViewports(const KRViewport& viewport);
void renderShadowBuffers(RenderInfo& ri);
};

View File

@@ -39,47 +39,47 @@ void KRLocator::InitNodeInfo(KrNodeInfo* nodeInfo)
// No additional members
}
KRLocator::KRLocator(KRScene &scene, std::string name) : KRNode(scene, name)
KRLocator::KRLocator(KRScene& scene, std::string name) : KRNode(scene, name)
{
}
KRLocator::~KRLocator()
{
}
{}
std::string KRLocator::getElementName() {
std::string KRLocator::getElementName()
{
return "locator";
}
tinyxml2::XMLElement *KRLocator::saveXML( tinyxml2::XMLNode *parent)
tinyxml2::XMLElement* KRLocator::saveXML(tinyxml2::XMLNode* parent)
{
tinyxml2::XMLElement *e = KRNode::saveXML(parent);
tinyxml2::XMLElement* e = KRNode::saveXML(parent);
return e;
}
void KRLocator::loadXML(tinyxml2::XMLElement *e)
void KRLocator::loadXML(tinyxml2::XMLElement* e)
{
KRNode::loadXML(e);
}
unordered_map<std::string, int> &KRLocator::getUserIntAttributes()
unordered_map<std::string, int>& KRLocator::getUserIntAttributes()
{
return m_userIntAttributes;
}
unordered_map<std::string, double> &KRLocator::getUserDoubleAttributes()
unordered_map<std::string, double>& KRLocator::getUserDoubleAttributes()
{
return m_userDoubleAttributes;
}
unordered_map<std::string, bool> &KRLocator::getUserBoolAttributes()
unordered_map<std::string, bool>& KRLocator::getUserBoolAttributes()
{
return m_userBoolAttributes;
}
unordered_map<std::string, std::string> &KRLocator::getUserStringAttributes()
unordered_map<std::string, std::string>& KRLocator::getUserStringAttributes()
{
return m_userStringAttributes;
}

View File

@@ -35,19 +35,20 @@
#include "KRNode.h"
#include "KRTexture.h"
class KRLocator : public KRNode {
class KRLocator : public KRNode
{
public:
static void InitNodeInfo(KrNodeInfo* nodeInfo);
KRLocator(KRScene &scene, std::string name);
KRLocator(KRScene& scene, std::string name);
virtual ~KRLocator();
virtual std::string getElementName();
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual void loadXML(tinyxml2::XMLElement *e);
unordered_map<std::string, int> &getUserIntAttributes();
unordered_map<std::string, double> &getUserDoubleAttributes();
unordered_map<std::string, bool> &getUserBoolAttributes();
unordered_map<std::string, std::string> &getUserStringAttributes();
virtual tinyxml2::XMLElement* saveXML(tinyxml2::XMLNode* parent);
virtual void loadXML(tinyxml2::XMLElement* e);
unordered_map<std::string, int>& getUserIntAttributes();
unordered_map<std::string, double>& getUserDoubleAttributes();
unordered_map<std::string, bool>& getUserBoolAttributes();
unordered_map<std::string, std::string>& getUserStringAttributes();
private:
unordered_map<std::string, int> m_userIntAttributes;

View File

@@ -36,7 +36,8 @@
#include "KRContext.h"
KRMaterial::KRMaterial(KRContext &context, const char *szName) : KRResource(context, szName) {
KRMaterial::KRMaterial(KRContext& context, const char* szName) : KRResource(context, szName)
{
m_name = szName;
m_pAmbientMap = NULL;
m_pDiffuseMap = NULL;
@@ -67,11 +68,13 @@ KRMaterial::KRMaterial(KRContext &context, const char *szName) : KRResource(cont
m_alpha_mode = KRMATERIAL_ALPHA_MODE_OPAQUE;
}
KRMaterial::~KRMaterial() {
KRMaterial::~KRMaterial()
{
}
std::string KRMaterial::getExtension() {
std::string KRMaterial::getExtension()
{
return "mtl";
}
@@ -80,10 +83,11 @@ bool KRMaterial::needsVertexTangents()
return m_normalMap.size() > 0;
}
bool KRMaterial::save(KRDataBlock &data) {
bool KRMaterial::save(KRDataBlock& data)
{
std::stringstream stream;
stream.precision(std::numeric_limits<long double>::digits10);
stream.setf(std::ios::fixed,std::ios::floatfield);
stream.setf(std::ios::fixed, std::ios::floatfield);
stream << "newmtl " << m_name;
stream << "\nka " << m_ambientColor.x << " " << m_ambientColor.y << " " << m_ambientColor.z;
@@ -92,37 +96,37 @@ bool KRMaterial::save(KRDataBlock &data) {
stream << "\nkr " << m_reflectionColor.x << " " << m_reflectionColor.y << " " << m_reflectionColor.z;
stream << "\nTr " << m_tr;
stream << "\nNs " << m_ns;
if(m_ambientMap.size()) {
if (m_ambientMap.size()) {
stream << "\nmap_Ka " << m_ambientMap << ".pvr -s " << m_ambientMapScale.x << " " << m_ambientMapScale.y << " -o " << m_ambientMapOffset.x << " " << m_ambientMapOffset.y;
} else {
stream << "\n# map_Ka filename.pvr -s 1.0 1.0 -o 0.0 0.0";
}
if(m_diffuseMap.size()) {
if (m_diffuseMap.size()) {
stream << "\nmap_Kd " << m_diffuseMap << ".pvr -s " << m_diffuseMapScale.x << " " << m_diffuseMapScale.y << " -o " << m_diffuseMapOffset.x << " " << m_diffuseMapOffset.y;
} else {
stream << "\n# map_Kd filename.pvr -s 1.0 1.0 -o 0.0 0.0";
}
if(m_specularMap.size()) {
if (m_specularMap.size()) {
stream << "\nmap_Ks " << m_specularMap << ".pvr -s " << m_specularMapScale.x << " " << m_specularMapScale.y << " -o " << m_specularMapOffset.x << " " << m_specularMapOffset.y << "\n";
} else {
stream << "\n# map_Ks filename.pvr -s 1.0 1.0 -o 0.0 0.0";
}
if(m_normalMap.size()) {
if (m_normalMap.size()) {
stream << "\nmap_Normal " << m_normalMap << ".pvr -s " << m_normalMapScale.x << " " << m_normalMapScale.y << " -o " << m_normalMapOffset.x << " " << m_normalMapOffset.y;
} else {
stream << "\n# map_Normal filename.pvr -s 1.0 1.0 -o 0.0 0.0";
}
if(m_reflectionMap.size()) {
if (m_reflectionMap.size()) {
stream << "\nmap_Reflection " << m_reflectionMap << ".pvr -s " << m_reflectionMapScale.x << " " << m_reflectionMapScale.y << " -o " << m_reflectionMapOffset.x << " " << m_reflectionMapOffset.y;
} else {
stream << "\n# map_Reflection filename.pvr -s 1.0 1.0 -o 0.0 0.0";
}
if(m_reflectionCube.size()) {
if (m_reflectionCube.size()) {
stream << "\nmap_ReflectionCube " << m_reflectionCube << ".pvr";
} else {
stream << "\n# map_ReflectionCube cubemapname";
}
switch(m_alpha_mode) {
switch (m_alpha_mode) {
case KRMATERIAL_ALPHA_MODE_OPAQUE:
stream << "\nalpha_mode opaque";
break;
@@ -144,76 +148,91 @@ bool KRMaterial::save(KRDataBlock &data) {
return true;
}
void KRMaterial::setAmbientMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset) {
void KRMaterial::setAmbientMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset)
{
m_ambientMap = texture_name;
m_ambientMapScale = texture_scale;
m_ambientMapOffset = texture_offset;
}
void KRMaterial::setDiffuseMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset) {
void KRMaterial::setDiffuseMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset)
{
m_diffuseMap = texture_name;
m_diffuseMapScale = texture_scale;
m_diffuseMapOffset = texture_offset;
}
void KRMaterial::setSpecularMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset) {
void KRMaterial::setSpecularMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset)
{
m_specularMap = texture_name;
m_specularMapScale = texture_scale;
m_specularMapOffset = texture_offset;
}
void KRMaterial::setNormalMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset) {
void KRMaterial::setNormalMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset)
{
m_normalMap = texture_name;
m_normalMapScale = texture_scale;
m_normalMapOffset = texture_offset;
}
void KRMaterial::setReflectionMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset) {
void KRMaterial::setReflectionMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset)
{
m_reflectionMap = texture_name;
m_reflectionMapScale = texture_scale;
m_reflectionMapOffset = texture_offset;
}
void KRMaterial::setReflectionCube(std::string texture_name) {
void KRMaterial::setReflectionCube(std::string texture_name)
{
m_reflectionCube = texture_name;
}
void KRMaterial::setAlphaMode(KRMaterial::alpha_mode_type alpha_mode) {
void KRMaterial::setAlphaMode(KRMaterial::alpha_mode_type alpha_mode)
{
m_alpha_mode = alpha_mode;
}
KRMaterial::alpha_mode_type KRMaterial::getAlphaMode() {
KRMaterial::alpha_mode_type KRMaterial::getAlphaMode()
{
return m_alpha_mode;
}
void KRMaterial::setAmbient(const Vector3 &c) {
void KRMaterial::setAmbient(const Vector3& c)
{
m_ambientColor = c;
}
void KRMaterial::setDiffuse(const Vector3 &c) {
void KRMaterial::setDiffuse(const Vector3& c)
{
m_diffuseColor = c;
}
void KRMaterial::setSpecular(const Vector3 &c) {
void KRMaterial::setSpecular(const Vector3& c)
{
m_specularColor = c;
}
void KRMaterial::setReflection(const Vector3 &c) {
void KRMaterial::setReflection(const Vector3& c)
{
m_reflectionColor = c;
}
void KRMaterial::setTransparency(float a) {
if(a < 1.0f && m_alpha_mode == KRMaterial::KRMATERIAL_ALPHA_MODE_OPAQUE) {
void KRMaterial::setTransparency(float a)
{
if (a < 1.0f && m_alpha_mode == KRMaterial::KRMATERIAL_ALPHA_MODE_OPAQUE) {
setAlphaMode(KRMaterial::KRMATERIAL_ALPHA_MODE_BLENDONESIDE);
}
m_tr = a;
}
void KRMaterial::setShininess(float s) {
void KRMaterial::setShininess(float s)
{
m_ns = s;
}
bool KRMaterial::isTransparent() {
bool KRMaterial::isTransparent()
{
return m_tr < 1.0 || m_alpha_mode == KRMATERIAL_ALPHA_MODE_BLENDONESIDE || m_alpha_mode == KRMATERIAL_ALPHA_MODE_BLENDTWOSIDE;
}
@@ -221,27 +240,27 @@ void KRMaterial::preStream(float lodCoverage)
{
getTextures();
if(m_pAmbientMap) {
if (m_pAmbientMap) {
m_pAmbientMap->resetPoolExpiry(lodCoverage, KRTexture::TEXTURE_USAGE_AMBIENT_MAP);
}
if(m_pDiffuseMap) {
if (m_pDiffuseMap) {
m_pDiffuseMap->resetPoolExpiry(lodCoverage, KRTexture::TEXTURE_USAGE_DIFFUSE_MAP);
}
if(m_pNormalMap) {
if (m_pNormalMap) {
m_pNormalMap->resetPoolExpiry(lodCoverage, KRTexture::TEXTURE_USAGE_NORMAL_MAP);
}
if(m_pSpecularMap) {
if (m_pSpecularMap) {
m_pSpecularMap->resetPoolExpiry(lodCoverage, KRTexture::TEXTURE_USAGE_SPECULAR_MAP);
}
if(m_pReflectionMap) {
if (m_pReflectionMap) {
m_pReflectionMap->resetPoolExpiry(lodCoverage, KRTexture::TEXTURE_USAGE_REFLECTION_MAP);
}
if(m_pReflectionCube) {
if (m_pReflectionCube) {
m_pReflectionCube->resetPoolExpiry(lodCoverage, KRTexture::TEXTURE_USAGE_REFECTION_CUBE);
}
}
@@ -253,27 +272,27 @@ kraken_stream_level KRMaterial::getStreamLevel()
getTextures();
if(m_pAmbientMap) {
if (m_pAmbientMap) {
stream_level = KRMIN(stream_level, m_pAmbientMap->getStreamLevel(KRTexture::TEXTURE_USAGE_AMBIENT_MAP));
}
if(m_pDiffuseMap) {
if (m_pDiffuseMap) {
stream_level = KRMIN(stream_level, m_pDiffuseMap->getStreamLevel(KRTexture::TEXTURE_USAGE_DIFFUSE_MAP));
}
if(m_pNormalMap) {
if (m_pNormalMap) {
stream_level = KRMIN(stream_level, m_pNormalMap->getStreamLevel(KRTexture::TEXTURE_USAGE_NORMAL_MAP));
}
if(m_pSpecularMap) {
if (m_pSpecularMap) {
stream_level = KRMIN(stream_level, m_pSpecularMap->getStreamLevel(KRTexture::TEXTURE_USAGE_SPECULAR_MAP));
}
if(m_pReflectionMap) {
if (m_pReflectionMap) {
stream_level = KRMIN(stream_level, m_pReflectionMap->getStreamLevel(KRTexture::TEXTURE_USAGE_REFLECTION_MAP));
}
if(m_pReflectionCube) {
if (m_pReflectionCube) {
stream_level = KRMIN(stream_level, m_pReflectionCube->getStreamLevel(KRTexture::TEXTURE_USAGE_REFECTION_CUBE));
}
@@ -282,27 +301,27 @@ kraken_stream_level KRMaterial::getStreamLevel()
void KRMaterial::getTextures()
{
if(!m_pAmbientMap && m_ambientMap.size()) {
if (!m_pAmbientMap && m_ambientMap.size()) {
m_pAmbientMap = getContext().getTextureManager()->getTexture(m_ambientMap);
}
if(!m_pDiffuseMap && m_diffuseMap.size()) {
if (!m_pDiffuseMap && m_diffuseMap.size()) {
m_pDiffuseMap = getContext().getTextureManager()->getTexture(m_diffuseMap);
}
if(!m_pNormalMap && m_normalMap.size()) {
if (!m_pNormalMap && m_normalMap.size()) {
m_pNormalMap = getContext().getTextureManager()->getTexture(m_normalMap);
}
if(!m_pSpecularMap && m_specularMap.size()) {
if (!m_pSpecularMap && m_specularMap.size()) {
m_pSpecularMap = getContext().getTextureManager()->getTexture(m_specularMap);
}
if(!m_pReflectionMap && m_reflectionMap.size()) {
if (!m_pReflectionMap && m_reflectionMap.size()) {
m_pReflectionMap = getContext().getTextureManager()->getTexture(m_reflectionMap);
}
if(!m_pReflectionCube && m_reflectionCube.size()) {
if (!m_pReflectionCube && m_reflectionCube.size()) {
m_pReflectionCube = getContext().getTextureManager()->getTextureCube(m_reflectionCube.c_str());
}
}
void KRMaterial::bind(const KRNode::RenderInfo& ri, ModelFormat modelFormat, __uint32_t vertexAttributes, CullMode cullMode, const std::vector<KRBone *> &bones, const std::vector<Matrix4> &bind_poses, const Matrix4 &matModel, KRTexture *pLightMap, const Vector3 &rim_color, float rim_power, float lod_coverage)
void KRMaterial::bind(const KRNode::RenderInfo& ri, ModelFormat modelFormat, __uint32_t vertexAttributes, CullMode cullMode, const std::vector<KRBone*>& bones, const std::vector<Matrix4>& bind_poses, const Matrix4& matModel, KRTexture* pLightMap, const Vector3& rim_color, float rim_power, float lod_coverage)
{
bool bLightMap = pLightMap && ri.camera->settings.bEnableLightMap;
@@ -350,29 +369,29 @@ void KRMaterial::bind(const KRNode::RenderInfo& ri, ModelFormat modelFormat, __u
info.modelFormat = modelFormat;
info.vertexAttributes = vertexAttributes;
info.cullMode = cullMode;
KRPipeline *pShader = getContext().getPipelineManager()->getPipeline(*ri.surface, info);
KRPipeline* pShader = getContext().getPipelineManager()->getPipeline(*ri.surface, info);
// Rim highlighting parameters
pShader->setUniform(KRPipeline::Uniform::rim_color, rim_color);
pShader->setUniform(KRPipeline::Uniform::rim_power, rim_power);
// Bind bones
if(pShader->hasUniform(KRPipeline::Uniform::bone_transforms)) {
if (pShader->hasUniform(KRPipeline::Uniform::bone_transforms)) {
float bone_mats[256 * 16];
float *bone_mat_component = bone_mats;
for(int bone_index=0; bone_index < bones.size(); bone_index++) {
KRBone *bone = bones[bone_index];
float* bone_mat_component = bone_mats;
for (int bone_index = 0; bone_index < bones.size(); bone_index++) {
KRBone* bone = bones[bone_index];
// Vector3 initialRotation = bone->getInitialLocalRotation();
// Vector3 rotation = bone->getLocalRotation();
// Vector3 initialTranslation = bone->getInitialLocalTranslation();
// Vector3 translation = bone->getLocalTranslation();
// Vector3 initialScale = bone->getInitialLocalScale();
// Vector3 scale = bone->getLocalScale();
//
// Vector3 initialRotation = bone->getInitialLocalRotation();
// Vector3 rotation = bone->getLocalRotation();
// Vector3 initialTranslation = bone->getInitialLocalTranslation();
// Vector3 translation = bone->getLocalTranslation();
// Vector3 initialScale = bone->getInitialLocalScale();
// Vector3 scale = bone->getLocalScale();
//
//printf("%s - delta rotation: %.4f %.4f %.4f\n", bone->getName().c_str(), (rotation.x - initialRotation.x) * 180.0 / M_PI, (rotation.y - initialRotation.y) * 180.0 / M_PI, (rotation.z - initialRotation.z) * 180.0 / M_PI);
//printf("%s - delta translation: %.4f %.4f %.4f\n", bone->getName().c_str(), translation.x - initialTranslation.x, translation.y - initialTranslation.y, translation.z - initialTranslation.z);
// printf("%s - delta scale: %.4f %.4f %.4f\n", bone->getName().c_str(), scale.x - initialScale.x, scale.y - initialScale.y, scale.z - initialScale.z);
// printf("%s - delta scale: %.4f %.4f %.4f\n", bone->getName().c_str(), scale.x - initialScale.x, scale.y - initialScale.y, scale.z - initialScale.z);
Matrix4 skin_bone_bind_pose = bind_poses[bone_index];
Matrix4 active_mat = bone->getActivePoseMatrix();
@@ -380,11 +399,11 @@ void KRMaterial::bind(const KRNode::RenderInfo& ri, ModelFormat modelFormat, __u
Matrix4 inv_bind_mat2 = Matrix4::Invert(bind_poses[bone_index]);
Matrix4 t = (inv_bind_mat * active_mat);
Matrix4 t2 = inv_bind_mat2 * bone->getModelMatrix();
for(int i=0; i < 16; i++) {
for (int i = 0; i < 16; i++) {
*bone_mat_component++ = t[i];
}
}
if(pShader->hasUniform(KRPipeline::Uniform::bone_transforms)) {
if (pShader->hasUniform(KRPipeline::Uniform::bone_transforms)) {
pShader->setUniform(KRPipeline::Uniform::bone_transforms, (Matrix4*)bone_mats, bones.size());
}
}
@@ -392,14 +411,14 @@ void KRMaterial::bind(const KRNode::RenderInfo& ri, ModelFormat modelFormat, __u
pShader->setUniform(KRPipeline::Uniform::material_ambient, m_ambientColor + ri.camera->settings.ambient_intensity);
if(ri.renderPass == KRNode::RENDER_PASS_FORWARD_OPAQUE) {
if (ri.renderPass == KRNode::RENDER_PASS_FORWARD_OPAQUE) {
// We pre-multiply the light color with the material color in the forward renderer
pShader->setUniform(KRPipeline::Uniform::material_diffuse, Vector3::Create(m_diffuseColor.x * ri.camera->settings.light_intensity.x, m_diffuseColor.y * ri.camera->settings.light_intensity.y, m_diffuseColor.z * ri.camera->settings.light_intensity.z));
} else {
pShader->setUniform(KRPipeline::Uniform::material_diffuse, m_diffuseColor);
}
if(ri.renderPass == KRNode::RENDER_PASS_FORWARD_OPAQUE) {
if (ri.renderPass == KRNode::RENDER_PASS_FORWARD_OPAQUE) {
// We pre-multiply the light color with the material color in the forward renderer
pShader->setUniform(KRPipeline::Uniform::material_specular, Vector3::Create(m_specularColor.x * ri.camera->settings.light_intensity.x, m_specularColor.y * ri.camera->settings.light_intensity.y, m_specularColor.z * ri.camera->settings.light_intensity.z));
} else {
@@ -419,23 +438,23 @@ void KRMaterial::bind(const KRNode::RenderInfo& ri, ModelFormat modelFormat, __u
pShader->setUniform(KRPipeline::Uniform::material_alpha, m_tr);
if(bDiffuseMap) {
if (bDiffuseMap) {
m_pContext->getTextureManager()->selectTexture(0, m_pDiffuseMap, lod_coverage, KRTexture::TEXTURE_USAGE_DIFFUSE_MAP);
}
if(bSpecMap) {
if (bSpecMap) {
m_pContext->getTextureManager()->selectTexture(1, m_pSpecularMap, lod_coverage, KRTexture::TEXTURE_USAGE_SPECULAR_MAP);
}
if(bNormalMap) {
if (bNormalMap) {
m_pContext->getTextureManager()->selectTexture(2, m_pNormalMap, lod_coverage, KRTexture::TEXTURE_USAGE_NORMAL_MAP);
}
if(bReflectionCubeMap && (ri.renderPass == KRNode::RENDER_PASS_FORWARD_OPAQUE || ri.renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT || ri.renderPass == KRNode::RENDER_PASS_DEFERRED_OPAQUE)) {
if (bReflectionCubeMap && (ri.renderPass == KRNode::RENDER_PASS_FORWARD_OPAQUE || ri.renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT || ri.renderPass == KRNode::RENDER_PASS_DEFERRED_OPAQUE)) {
m_pContext->getTextureManager()->selectTexture(4, m_pReflectionCube, lod_coverage, KRTexture::TEXTURE_USAGE_REFECTION_CUBE);
}
if(bReflectionMap && (ri.renderPass == KRNode::RENDER_PASS_FORWARD_OPAQUE || ri.renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT || ri.renderPass == KRNode::RENDER_PASS_DEFERRED_OPAQUE)) {
if (bReflectionMap && (ri.renderPass == KRNode::RENDER_PASS_FORWARD_OPAQUE || ri.renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT || ri.renderPass == KRNode::RENDER_PASS_DEFERRED_OPAQUE)) {
// GL_TEXTURE7 is used for reading the depth buffer in gBuffer pass 2 and re-used for the reflection map in gBuffer Pass 3 and in forward rendering
m_pContext->getTextureManager()->selectTexture(7, m_pReflectionMap, lod_coverage, KRTexture::TEXTURE_USAGE_REFLECTION_MAP);
}
@@ -443,7 +462,7 @@ void KRMaterial::bind(const KRNode::RenderInfo& ri, ModelFormat modelFormat, __u
pShader->bind(ri.commandBuffer, *ri.camera, ri.viewport, matModel, &ri.point_lights, &ri.directional_lights, &ri.spot_lights, ri.renderPass);
}
const std::string &KRMaterial::getName() const
const std::string& KRMaterial::getName() const
{
return m_name;
}

View File

@@ -50,20 +50,22 @@ class KRTextureManager;
class KRContext;
class KRSurface;
class KRMaterial : public KRResource {
class KRMaterial : public KRResource
{
public:
typedef enum {
typedef enum
{
KRMATERIAL_ALPHA_MODE_OPAQUE, // Non-transparent materials
KRMATERIAL_ALPHA_MODE_TEST, // Alpha in diffuse texture is interpreted as punch-through when < 0.5
KRMATERIAL_ALPHA_MODE_BLENDONESIDE, // Blended alpha with backface culling
KRMATERIAL_ALPHA_MODE_BLENDTWOSIDE // Blended alpha rendered in two passes. First pass renders backfaces; second pass renders frontfaces.
} alpha_mode_type;
KRMaterial(KRContext &context, const char *szName);
KRMaterial(KRContext& context, const char* szName);
virtual ~KRMaterial();
virtual std::string getExtension();
virtual bool save(KRDataBlock &data);
virtual bool save(KRDataBlock& data);
void setAmbientMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset);
@@ -72,10 +74,10 @@ public:
void setReflectionMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset);
void setReflectionCube(std::string texture_name);
void setNormalMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset);
void setAmbient(const Vector3 &c);
void setDiffuse(const Vector3 &c);
void setSpecular(const Vector3 &c);
void setReflection(const Vector3 &c);
void setAmbient(const Vector3& c);
void setDiffuse(const Vector3& c);
void setSpecular(const Vector3& c);
void setReflection(const Vector3& c);
void setTransparency(float a);
void setShininess(float s);
void setAlphaMode(alpha_mode_type blend_mode);
@@ -83,7 +85,7 @@ public:
bool isTransparent();
const std::string &getName() const;
const std::string& getName() const;
void bind(const KRNode::RenderInfo& ri, ModelFormat modelFormat, __uint32_t vertexAttributes, CullMode cullMode, const std::vector<KRBone*>& bones, const std::vector<Matrix4>& bind_poses, const Matrix4& matModel, KRTexture* pLightMap, const Vector3& rim_color, float rim_power, float lod_coverage = 0.0f);
@@ -95,12 +97,12 @@ public:
private:
std::string m_name;
KRTexture *m_pAmbientMap; // mtl map_Ka value
KRTexture *m_pDiffuseMap; // mtl map_Kd value
KRTexture *m_pSpecularMap; // mtl map_Ks value
KRTexture *m_pReflectionMap; // mtl refl value
KRTexture *m_pReflectionCube;
KRTexture *m_pNormalMap; // mtl map_Normal value
KRTexture* m_pAmbientMap; // mtl map_Ka value
KRTexture* m_pDiffuseMap; // mtl map_Kd value
KRTexture* m_pSpecularMap; // mtl map_Ks value
KRTexture* m_pReflectionMap; // mtl refl value
KRTexture* m_pReflectionCube;
KRTexture* m_pNormalMap; // mtl map_Normal value
std::string m_ambientMap;
std::string m_diffuseMap;
std::string m_specularMap;

View File

@@ -33,13 +33,14 @@
#include "KRMaterialManager.h"
KRMaterialManager::KRMaterialManager(KRContext &context, KRTextureManager *pTextureManager, KRPipelineManager *pPipelineManager) : KRResourceManager(context)
KRMaterialManager::KRMaterialManager(KRContext& context, KRTextureManager* pTextureManager, KRPipelineManager* pPipelineManager) : KRResourceManager(context)
{
m_pTextureManager = pTextureManager;
m_pPipelineManager = pPipelineManager;
}
KRMaterialManager::~KRMaterialManager() {
KRMaterialManager::~KRMaterialManager()
{
}
@@ -62,19 +63,20 @@ KRResource* KRMaterialManager::getResource(const std::string& name, const std::s
return nullptr;
}
unordered_map<std::string, KRMaterial *> &KRMaterialManager::getMaterials()
unordered_map<std::string, KRMaterial*>& KRMaterialManager::getMaterials()
{
return m_materials;
}
KRMaterial *KRMaterialManager::getMaterial(const std::string &name) {
KRMaterial* KRMaterialManager::getMaterial(const std::string& name)
{
std::string lowerName = name;
std::transform(lowerName.begin(), lowerName.end(),
lowerName.begin(), ::tolower);
unordered_map<std::string, KRMaterial *>::iterator itr = m_materials.find(lowerName);
if(itr == m_materials.end()) {
unordered_map<std::string, KRMaterial*>::iterator itr = m_materials.find(lowerName);
if (itr == m_materials.end()) {
KRContext::Log(KRContext::LOG_LEVEL_WARNING, "Material not found: %s", name.c_str());
// Not found
return NULL;
@@ -83,7 +85,8 @@ KRMaterial *KRMaterialManager::getMaterial(const std::string &name) {
}
}
void KRMaterialManager::add(KRMaterial *new_material) {
void KRMaterialManager::add(KRMaterial* new_material)
{
// FINDME, TODO - Potential memory leak if multiple materials with the same name are added
std::string lowerName = new_material->getName();
std::transform(lowerName.begin(), lowerName.end(),
@@ -92,34 +95,35 @@ void KRMaterialManager::add(KRMaterial *new_material) {
m_materials[lowerName] = new_material;
}
KRMaterial* KRMaterialManager::load(const char *szName, KRDataBlock *data) {
KRMaterial *pMaterial = NULL;
KRMaterial* KRMaterialManager::load(const char* szName, KRDataBlock* data)
{
KRMaterial* pMaterial = NULL;
char szSymbol[16][256];
data->lock();
char *pScan = (char *)data->getStart();
char *pEnd = (char *)data->getEnd();
while(pScan < pEnd) {
char* pScan = (char*)data->getStart();
char* pEnd = (char*)data->getEnd();
while (pScan < pEnd) {
// Scan through whitespace
while(pScan < pEnd && (*pScan == ' ' || *pScan == '\t' || *pScan == '\r' || *pScan == '\n')) {
while (pScan < pEnd && (*pScan == ' ' || *pScan == '\t' || *pScan == '\r' || *pScan == '\n')) {
pScan++;
}
if(*pScan == '#') {
if (*pScan == '#') {
// Line is a comment line
// Scan to the end of the line
while(pScan < pEnd && *pScan != '\r' && *pScan != '\n') {
while (pScan < pEnd && *pScan != '\r' && *pScan != '\n') {
pScan++;
}
} else {
int cSymbols = 0;
while(pScan < pEnd && *pScan != '\n' && *pScan != '\r') {
while (pScan < pEnd && *pScan != '\n' && *pScan != '\r') {
char *pDest = szSymbol[cSymbols++];
while(pScan < pEnd && *pScan != ' ' && *pScan != '\n' && *pScan != '\r') {
if(*pScan >= 'A' && *pScan <= 'Z') {
char* pDest = szSymbol[cSymbols++];
while (pScan < pEnd && *pScan != ' ' && *pScan != '\n' && *pScan != '\r') {
if (*pScan >= 'A' && *pScan <= 'Z') {
*pDest++ = *pScan++ + 'a' - 'A'; // convert to lower case for case sensitve comparison later
} else {
*pDest++ = *pScan++;
@@ -128,98 +132,98 @@ KRMaterial* KRMaterialManager::load(const char *szName, KRDataBlock *data) {
*pDest = '\0';
// Scan through whitespace, but don't advance to next line
while(pScan < pEnd && (*pScan == ' ' || *pScan == '\t')) {
while (pScan < pEnd && (*pScan == ' ' || *pScan == '\t')) {
pScan++;
}
}
if(cSymbols > 0) {
if (cSymbols > 0) {
if(strcmp(szSymbol[0], "newmtl") == 0 && cSymbols >= 2) {
if (strcmp(szSymbol[0], "newmtl") == 0 && cSymbols >= 2) {
pMaterial = new KRMaterial(*m_pContext, szSymbol[1]);
m_materials[szSymbol[1]] = pMaterial;
}
if(pMaterial != NULL) {
if(strcmp(szSymbol[0], "alpha_mode") == 0) {
if(cSymbols == 2) {
if(strcmp(szSymbol[1], "test") == 0) {
if (pMaterial != NULL) {
if (strcmp(szSymbol[0], "alpha_mode") == 0) {
if (cSymbols == 2) {
if (strcmp(szSymbol[1], "test") == 0) {
pMaterial->setAlphaMode(KRMaterial::KRMATERIAL_ALPHA_MODE_TEST);
} else if(strcmp(szSymbol[1], "blendoneside") == 0) {
} else if (strcmp(szSymbol[1], "blendoneside") == 0) {
pMaterial->setAlphaMode(KRMaterial::KRMATERIAL_ALPHA_MODE_BLENDONESIDE);
} else if(strcmp(szSymbol[1], "blendtwoside") == 0) {
} else if (strcmp(szSymbol[1], "blendtwoside") == 0) {
pMaterial->setAlphaMode(KRMaterial::KRMATERIAL_ALPHA_MODE_BLENDTWOSIDE);
} else {
pMaterial->setAlphaMode(KRMaterial::KRMATERIAL_ALPHA_MODE_OPAQUE);
}
}
} else if(strcmp(szSymbol[0], "ka") == 0) {
char *pScan2 = szSymbol[1];
} else if (strcmp(szSymbol[0], "ka") == 0) {
char* pScan2 = szSymbol[1];
float r = strtof(pScan2, &pScan2);
if(cSymbols == 2) {
if (cSymbols == 2) {
pMaterial->setAmbient(Vector3::Create(r, r, r));
} else if(cSymbols == 4) {
} else if (cSymbols == 4) {
pScan2 = szSymbol[2];
float g = strtof(pScan2, &pScan2);
pScan2 = szSymbol[3];
float b = strtof(pScan2, &pScan2);
pMaterial->setAmbient(Vector3::Create(r, g, b));
}
} else if(strcmp(szSymbol[0], "kd") == 0) {
char *pScan2 = szSymbol[1];
} else if (strcmp(szSymbol[0], "kd") == 0) {
char* pScan2 = szSymbol[1];
float r = strtof(pScan2, &pScan2);
if(cSymbols == 2) {
if (cSymbols == 2) {
pMaterial->setDiffuse(Vector3::Create(r, r, r));
} else if(cSymbols == 4) {
} else if (cSymbols == 4) {
pScan2 = szSymbol[2];
float g = strtof(pScan2, &pScan2);
pScan2 = szSymbol[3];
float b = strtof(pScan2, &pScan2);
pMaterial->setDiffuse(Vector3::Create(r, g, b));
}
} else if(strcmp(szSymbol[0], "ks") == 0) {
char *pScan2 = szSymbol[1];
} else if (strcmp(szSymbol[0], "ks") == 0) {
char* pScan2 = szSymbol[1];
float r = strtof(pScan2, &pScan2);
if(cSymbols == 2) {
if (cSymbols == 2) {
pMaterial->setSpecular(Vector3::Create(r, r, r));
} else if(cSymbols == 4) {
} else if (cSymbols == 4) {
pScan2 = szSymbol[2];
float g = strtof(pScan2, &pScan2);
pScan2 = szSymbol[3];
float b = strtof(pScan2, &pScan2);
pMaterial->setSpecular(Vector3::Create(r, g, b));
}
} else if(strcmp(szSymbol[0], "kr") == 0) {
char *pScan2 = szSymbol[1];
} else if (strcmp(szSymbol[0], "kr") == 0) {
char* pScan2 = szSymbol[1];
float r = strtof(pScan2, &pScan2);
if(cSymbols == 2) {
if (cSymbols == 2) {
pMaterial->setReflection(Vector3::Create(r, r, r));
} else if(cSymbols == 4) {
} else if (cSymbols == 4) {
pScan2 = szSymbol[2];
float g = strtof(pScan2, &pScan2);
pScan2 = szSymbol[3];
float b = strtof(pScan2, &pScan2);
pMaterial->setReflection(Vector3::Create(r, g, b));
}
} else if(strcmp(szSymbol[0], "tr") == 0) {
char *pScan2 = szSymbol[1];
} else if (strcmp(szSymbol[0], "tr") == 0) {
char* pScan2 = szSymbol[1];
float a = strtof(pScan2, &pScan2);
pMaterial->setTransparency(a);
} else if(strcmp(szSymbol[0], "ns") == 0) {
char *pScan2 = szSymbol[1];
} else if (strcmp(szSymbol[0], "ns") == 0) {
char* pScan2 = szSymbol[1];
float a = strtof(pScan2, &pScan2);
pMaterial->setShininess(a);
} else if(strncmp(szSymbol[0], "map", 3) == 0) {
} else if (strncmp(szSymbol[0], "map", 3) == 0) {
// Truncate file extension
char *pScan2 = szSymbol[1];
char *pLastPeriod = NULL;
while(*pScan2 != '\0') {
if(*pScan2 == '.') {
char* pScan2 = szSymbol[1];
char* pLastPeriod = NULL;
while (*pScan2 != '\0') {
if (*pScan2 == '.') {
pLastPeriod = pScan2;
}
pScan2++;
}
if(pLastPeriod) {
if (pLastPeriod) {
*pLastPeriod = '\0';
}
@@ -229,28 +233,28 @@ KRMaterial* KRMaterialManager::load(const char *szName, KRDataBlock *data) {
int iScanSymbol = 2;
int iScaleParam = -1;
int iOffsetParam = -1;
while(iScanSymbol < cSymbols) {
if(strcmp(szSymbol[iScanSymbol], "-s") == 0) {
while (iScanSymbol < cSymbols) {
if (strcmp(szSymbol[iScanSymbol], "-s") == 0) {
// Scale
iScaleParam = 0;
iOffsetParam = -1;
} else if(strcmp(szSymbol[iScanSymbol], "-o") == 0) {
} else if (strcmp(szSymbol[iScanSymbol], "-o") == 0) {
// Offset
iOffsetParam = 0;
iScaleParam = -1;
} else {
char *pScan3 = szSymbol[iScanSymbol];
char* pScan3 = szSymbol[iScanSymbol];
float v = strtof(pScan3, &pScan3);
if(iScaleParam == 0) {
if (iScaleParam == 0) {
texture_scale.x = v;
iScaleParam++;
} else if(iScaleParam == 1) {
} else if (iScaleParam == 1) {
texture_scale.y = v;
iScaleParam++;
} else if(iOffsetParam == 0) {
} else if (iOffsetParam == 0) {
texture_offset.x = v;
iOffsetParam++;
} else if(iOffsetParam == 1) {
} else if (iOffsetParam == 1) {
texture_offset.y = v;
iOffsetParam++;
}
@@ -258,17 +262,17 @@ KRMaterial* KRMaterialManager::load(const char *szName, KRDataBlock *data) {
iScanSymbol++;
}
if(strcmp(szSymbol[0], "map_ka") == 0) {
if (strcmp(szSymbol[0], "map_ka") == 0) {
pMaterial->setAmbientMap(szSymbol[1], texture_scale, texture_offset);
} else if(strcmp(szSymbol[0], "map_kd") == 0) {
} else if (strcmp(szSymbol[0], "map_kd") == 0) {
pMaterial->setDiffuseMap(szSymbol[1], texture_scale, texture_offset);
} else if(strcmp(szSymbol[0], "map_ks") == 0) {
} else if (strcmp(szSymbol[0], "map_ks") == 0) {
pMaterial->setSpecularMap(szSymbol[1], texture_scale, texture_offset);
} else if(strcmp(szSymbol[0], "map_normal") == 0) {
} else if (strcmp(szSymbol[0], "map_normal") == 0) {
pMaterial->setNormalMap(szSymbol[1], texture_scale, texture_offset);
} else if(strcmp(szSymbol[0], "map_reflection") == 0) {
} else if (strcmp(szSymbol[0], "map_reflection") == 0) {
pMaterial->setReflectionMap(szSymbol[1], texture_scale, texture_offset);
} else if(strcmp(szSymbol[0], "map_reflectioncube") == 0) {
} else if (strcmp(szSymbol[0], "map_reflectioncube") == 0) {
pMaterial->setReflectionCube(szSymbol[1]);
}
}

View File

@@ -43,23 +43,24 @@ class KRMaterial;
using std::map;
class KRMaterialManager : public KRResourceManager {
class KRMaterialManager : public KRResourceManager
{
public:
KRMaterialManager(KRContext &context, KRTextureManager *pTextureManager, KRPipelineManager *pPipelineManager);
KRMaterialManager(KRContext& context, KRTextureManager* pTextureManager, KRPipelineManager* pPipelineManager);
virtual ~KRMaterialManager();
virtual KRResource* loadResource(const std::string& name, const std::string& extension, KRDataBlock* data) override;
virtual KRResource* getResource(const std::string& name, const std::string& extension) override;
KRMaterial* load(const char *szName, KRDataBlock *data);
void add(KRMaterial *new_material);
KRMaterial *getMaterial(const std::string &name);
KRMaterial* load(const char* szName, KRDataBlock* data);
void add(KRMaterial* new_material);
KRMaterial* getMaterial(const std::string& name);
unordered_map<std::string, KRMaterial *> &getMaterials();
unordered_map<std::string, KRMaterial*>& getMaterials();
private:
unordered_map<std::string, KRMaterial *> m_materials;
KRTextureManager *m_pTextureManager;
KRPipelineManager *m_pPipelineManager;
unordered_map<std::string, KRMaterial*> m_materials;
KRTextureManager* m_pTextureManager;
KRPipelineManager* m_pPipelineManager;
};

File diff suppressed because it is too large Load Diff

View File

@@ -65,13 +65,14 @@ enum class ModelFormat : __uint8_t
KRENGINE_MODEL_FORMAT_INDEXED_STRIP
};
class KRMesh : public KRResource {
class KRMesh : public KRResource
{
public:
static void parseName(const std::string& name, std::string& lodBaseName, int& lodCoverage);
KRMesh(KRContext &context, std::string name, KRDataBlock *data);
KRMesh(KRContext &context, std::string name);
KRMesh(KRContext& context, std::string name, KRDataBlock* data);
KRMesh(KRContext& context, std::string name);
virtual ~KRMesh();
kraken_stream_level getStreamLevel();
@@ -79,7 +80,8 @@ public:
bool hasTransparency();
typedef enum {
typedef enum
{
KRENGINE_ATTRIB_VERTEX = 0,
KRENGINE_ATTRIB_NORMAL,
KRENGINE_ATTRIB_TANGENT,
@@ -97,7 +99,8 @@ public:
typedef struct {
typedef struct
{
ModelFormat format;
std::vector<Vector3> vertices;
std::vector<__uint16_t> vertex_indexes;
@@ -115,16 +118,16 @@ public:
std::vector<std::vector<float> > bone_weights;
} mesh_info;
void render(const KRNode::RenderInfo& ri, const std::string &object_name, const Matrix4 &matModel, KRTexture *pLightMap, const std::vector<KRBone *> &bones, const Vector3 &rim_color, float rim_power, float lod_coverage = 0.0f);
void render(const KRNode::RenderInfo& ri, const std::string& object_name, const Matrix4& matModel, KRTexture* pLightMap, const std::vector<KRBone*>& bones, const Vector3& rim_color, float rim_power, float lod_coverage = 0.0f);
std::string m_lodBaseName;
virtual std::string getExtension();
virtual bool save(const std::string& path);
virtual bool save(KRDataBlock &data);
virtual bool save(KRDataBlock& data);
void LoadData(const mesh_info &mi, bool calculate_normals, bool calculate_tangents);
void loadPack(KRDataBlock *data);
void LoadData(const mesh_info& mi, bool calculate_normals, bool calculate_tangents);
void loadPack(KRDataBlock* data);
void convertToIndexed();
void optimize();
@@ -138,17 +141,20 @@ public:
Vector3 getMinPoint() const;
Vector3 getMaxPoint() const;
class Submesh {
class Submesh
{
public:
Submesh() {};
~Submesh() {
for(auto itr = vbo_data_blocks.begin(); itr != vbo_data_blocks.end(); itr++) {
Submesh()
{};
~Submesh()
{
for (auto itr = vbo_data_blocks.begin(); itr != vbo_data_blocks.end(); itr++) {
delete (*itr);
}
for(auto itr = vertex_data_blocks.begin(); itr != vertex_data_blocks.end(); itr++) {
for (auto itr = vertex_data_blocks.begin(); itr != vertex_data_blocks.end(); itr++) {
delete (*itr);
}
for(auto itr = index_data_blocks.begin(); itr != index_data_blocks.end(); itr++) {
for (auto itr = index_data_blocks.begin(); itr != index_data_blocks.end(); itr++) {
delete (*itr);
}
};
@@ -156,14 +162,17 @@ public:
GLint start_vertex;
GLsizei vertex_count;
char szMaterialName[KRENGINE_MAX_NAME_LENGTH];
vector<KRDataBlock *> vertex_data_blocks;
vector<KRDataBlock *> index_data_blocks;
vector<KRMeshManager::KRVBOData *> vbo_data_blocks;
vector<KRDataBlock*> vertex_data_blocks;
vector<KRDataBlock*> index_data_blocks;
vector<KRMeshManager::KRVBOData*> vbo_data_blocks;
};
typedef struct {
union {
struct { // For Indexed triangles / strips
typedef struct
{
union
{
struct
{ // For Indexed triangles / strips
uint16_t index_group;
uint16_t index_group_offset;
};
@@ -173,7 +182,8 @@ public:
char szName[KRENGINE_MAX_NAME_LENGTH];
} pack_material;
typedef struct {
typedef struct
{
char szName[KRENGINE_MAX_NAME_LENGTH];
float bind_pose[16];
} pack_bone;
@@ -182,7 +192,7 @@ public:
std::string getLODBaseName() const;
static bool lod_sort_predicate(const KRMesh *m1, const KRMesh *m2);
static bool lod_sort_predicate(const KRMesh* m1, const KRMesh* m2);
bool has_vertex_attribute(vertex_attrib_t attribute_type) const;
static bool has_vertex_attribute(int vertex_attrib_flags, vertex_attrib_t attribute_type);
@@ -199,11 +209,11 @@ public:
int getBoneIndex(int index, int weight_index) const;
float getBoneWeight(int index, int weight_index) const;
void setVertexPosition(int index, const Vector3 &v);
void setVertexNormal(int index, const Vector3 &v);
void setVertexTangent(int index, const Vector3 & v);
void setVertexUVA(int index, const Vector2 &v);
void setVertexUVB(int index, const Vector2 &v);
void setVertexPosition(int index, const Vector3& v);
void setVertexNormal(int index, const Vector3& v);
void setVertexTangent(int index, const Vector3& v);
void setVertexUVA(int index, const Vector2& v);
void setVertexUVB(int index, const Vector2& v);
void setBoneIndex(int index, int weight_index, int bone_index);
void setBoneWeight(int index, int weight_index, float bone_weight);
@@ -212,36 +222,36 @@ public:
static VkFormat AttributeVulkanFormat(__int32 vertex_attrib);
int getBoneCount();
char *getBoneName(int bone_index);
char* getBoneName(int bone_index);
Matrix4 getBoneBindPose(int bone_index);
ModelFormat getModelFormat() const;
bool lineCast(const Vector3 &v0, const Vector3 &v1, HitInfo &hitinfo) const;
bool rayCast(const Vector3 &v0, const Vector3 &dir, HitInfo &hitinfo) const;
bool sphereCast(const Matrix4 &model_to_world, const Vector3 &v0, const Vector3 &v1, float radius, HitInfo &hitinfo) const;
bool lineCast(const Vector3& v0, const Vector3& v1, HitInfo& hitinfo) const;
bool rayCast(const Vector3& v0, const Vector3& dir, HitInfo& hitinfo) const;
bool sphereCast(const Matrix4& model_to_world, const Vector3& v0, const Vector3& v1, float radius, HitInfo& hitinfo) const;
static int GetLODCoverage(const std::string &name);
static int GetLODCoverage(const std::string& name);
protected:
bool m_constant; // TRUE if this should be always loaded and should not be passed through the streamer
private:
KRDataBlock *m_pData;
KRDataBlock *m_pMetaData;
KRDataBlock *m_pIndexBaseData;
KRDataBlock* m_pData;
KRDataBlock* m_pMetaData;
KRDataBlock* m_pIndexBaseData;
void getSubmeshes();
void getMaterials();
void renderSubmesh(VkCommandBuffer& commandBuffer, int iSubmesh, KRNode::RenderPass renderPass, const std::string& object_name, const std::string& material_name, float lodCoverage);
static bool rayCast(const Vector3 &start, const Vector3 &dir, const Triangle3 &tri, const Vector3 &tri_n0, const Vector3 &tri_n1, const Vector3 &tri_n2, HitInfo &hitinfo);
static bool sphereCast(const Matrix4 &model_to_world, const Vector3 &v0, const Vector3 &v1, float radius, const Triangle3 &tri, HitInfo &hitinfo);
static bool rayCast(const Vector3& start, const Vector3& dir, const Triangle3& tri, const Vector3& tri_n0, const Vector3& tri_n1, const Vector3& tri_n2, HitInfo& hitinfo);
static bool sphereCast(const Matrix4& model_to_world, const Vector3& v0, const Vector3& v1, float radius, const Triangle3& tri, HitInfo& hitinfo);
int m_lodCoverage; // This LOD level is activated when the bounding box of the model will cover less than this percent of the screen (100 = highest detail model)
vector<KRMaterial *> m_materials;
set<KRMaterial *> m_uniqueMaterials;
vector<KRMaterial*> m_materials;
set<KRMaterial*> m_uniqueMaterials;
bool m_hasTransparency;
@@ -251,7 +261,8 @@ private:
typedef struct {
typedef struct
{
char szTag[16];
int32_t model_format; // 0 == Triangle list, 1 == Triangle strips, 2 == Indexed triangle list, 3 == Indexed triangle strips, rest are reserved (model_format_t enum)
int32_t vertex_attrib_flags;
@@ -264,7 +275,7 @@ private:
unsigned char reserved[444]; // Pad out to 512 bytes
} pack_header;
vector<Submesh *> m_submeshes;
vector<Submesh*> m_submeshes;
int m_vertex_attribute_offset[KRENGINE_NUM_ATTRIBUTES];
int m_vertex_size;
void updateAttributeOffsets();
@@ -273,18 +284,18 @@ private:
pack_material *getSubmesh(int mesh_index) const;
unsigned char *getVertexData() const;
pack_material* getSubmesh(int mesh_index) const;
unsigned char* getVertexData() const;
size_t getVertexDataOffset() const;
unsigned char *getVertexData(int index) const;
__uint16_t *getIndexData() const;
unsigned char* getVertexData(int index) const;
__uint16_t* getIndexData() const;
size_t getIndexDataOffset() const;
__uint32_t *getIndexBaseData() const;
pack_header *getHeader() const;
pack_bone *getBone(int index);
__uint32_t* getIndexBaseData() const;
pack_header* getHeader() const;
pack_bone* getBone(int index);
void getIndexedRange(int index_group, int &start_index_offset, int &start_vertex_offset, int &index_count, int &vertex_count) const;
void getIndexedRange(int index_group, int& start_index_offset, int& start_vertex_offset, int& index_count, int& vertex_count) const;
void releaseData();

View File

@@ -32,7 +32,7 @@
#include "KRMeshCube.h"
KRMeshCube::KRMeshCube(KRContext &context) : KRMesh(context, "__cube")
KRMeshCube::KRMeshCube(KRContext& context) : KRMesh(context, "__cube")
{
m_constant = true;
@@ -40,18 +40,18 @@ KRMeshCube::KRMeshCube(KRContext &context) : KRMesh(context, "__cube")
mi.vertices.push_back(Vector3::Create(1.0, 1.0, 1.0));
mi.vertices.push_back(Vector3::Create(-1.0, 1.0, 1.0));
mi.vertices.push_back(Vector3::Create(1.0,-1.0, 1.0));
mi.vertices.push_back(Vector3::Create(-1.0,-1.0, 1.0));
mi.vertices.push_back(Vector3::Create(-1.0,-1.0,-1.0));
mi.vertices.push_back(Vector3::Create(1.0, -1.0, 1.0));
mi.vertices.push_back(Vector3::Create(-1.0, -1.0, 1.0));
mi.vertices.push_back(Vector3::Create(-1.0, -1.0, -1.0));
mi.vertices.push_back(Vector3::Create(-1.0, 1.0, 1.0));
mi.vertices.push_back(Vector3::Create(-1.0, 1.0,-1.0));
mi.vertices.push_back(Vector3::Create(-1.0, 1.0, -1.0));
mi.vertices.push_back(Vector3::Create(1.0, 1.0, 1.0));
mi.vertices.push_back(Vector3::Create(1.0, 1.0,-1.0));
mi.vertices.push_back(Vector3::Create(1.0,-1.0, 1.0));
mi.vertices.push_back(Vector3::Create(1.0,-1.0,-1.0));
mi.vertices.push_back(Vector3::Create(-1.0,-1.0,-1.0));
mi.vertices.push_back(Vector3::Create(1.0, 1.0,-1.0));
mi.vertices.push_back(Vector3::Create(-1.0, 1.0,-1.0));
mi.vertices.push_back(Vector3::Create(1.0, 1.0, -1.0));
mi.vertices.push_back(Vector3::Create(1.0, -1.0, 1.0));
mi.vertices.push_back(Vector3::Create(1.0, -1.0, -1.0));
mi.vertices.push_back(Vector3::Create(-1.0, -1.0, -1.0));
mi.vertices.push_back(Vector3::Create(1.0, 1.0, -1.0));
mi.vertices.push_back(Vector3::Create(-1.0, 1.0, -1.0));
mi.submesh_starts.push_back(0);

View File

@@ -33,9 +33,10 @@
#include "KRMesh.h"
class KRMeshCube : public KRMesh {
class KRMeshCube : public KRMesh
{
public:
KRMeshCube(KRContext &context);
KRMeshCube(KRContext& context);
virtual ~KRMeshCube();
private:
};

View File

@@ -50,7 +50,8 @@ KRMeshManager::KRMeshManager(KRContext& context)
}
void KRMeshManager::init() {
void KRMeshManager::init()
{
addModel(new KRMeshCube(*m_pContext));
addModel(new KRMeshQuad(*m_pContext));
addModel(new KRMeshSphere(*m_pContext));
@@ -108,8 +109,9 @@ void KRMeshManager::init() {
}
KRMeshManager::~KRMeshManager() {
for(unordered_multimap<std::string, KRMesh *>::iterator itr = m_models.begin(); itr != m_models.end(); ++itr){
KRMeshManager::~KRMeshManager()
{
for (unordered_multimap<std::string, KRMesh*>::iterator itr = m_models.begin(); itr != m_models.end(); ++itr) {
delete (*itr).second;
}
m_models.clear();
@@ -138,21 +140,24 @@ KRResource* KRMeshManager::getResource(const std::string& name, const std::strin
return nullptr;
}
KRMesh *KRMeshManager::loadModel(const char *szName, KRDataBlock *pData) {
KRMesh *pModel = new KRMesh(*m_pContext, szName, pData);
KRMesh* KRMeshManager::loadModel(const char* szName, KRDataBlock* pData)
{
KRMesh* pModel = new KRMesh(*m_pContext, szName, pData);
addModel(pModel);
return pModel;
}
void KRMeshManager::addModel(KRMesh *model) {
void KRMeshManager::addModel(KRMesh* model)
{
std::string lowerName = model->getLODBaseName();
std::transform(lowerName.begin(), lowerName.end(),
lowerName.begin(), ::tolower);
m_models.insert(std::pair<std::string, KRMesh *>(lowerName, model));
m_models.insert(std::pair<std::string, KRMesh*>(lowerName, model));
}
KRMesh* KRMeshManager::getMaxLODModel(const char* szName) {
KRMesh* KRMeshManager::getMaxLODModel(const char* szName)
{
std::vector<KRMesh*> models = getModel(szName);
// models are always in order of highest LOD first
if (models.size()) {
@@ -161,46 +166,48 @@ KRMesh* KRMeshManager::getMaxLODModel(const char* szName) {
return nullptr;
}
std::vector<KRMesh *> KRMeshManager::getModel(const char *szName) {
std::vector<KRMesh*> KRMeshManager::getModel(const char* szName)
{
std::string lowerName = szName;
std::transform(lowerName.begin(), lowerName.end(),
lowerName.begin(), ::tolower);
std::vector<KRMesh *> matching_models;
std::vector<KRMesh*> matching_models;
std::pair<unordered_multimap<std::string, KRMesh *>::iterator, unordered_multimap<std::string, KRMesh *>::iterator> range = m_models.equal_range(lowerName);
for(unordered_multimap<std::string, KRMesh *>::iterator itr_match = range.first; itr_match != range.second; itr_match++) {
std::pair<unordered_multimap<std::string, KRMesh*>::iterator, unordered_multimap<std::string, KRMesh*>::iterator> range = m_models.equal_range(lowerName);
for (unordered_multimap<std::string, KRMesh*>::iterator itr_match = range.first; itr_match != range.second; itr_match++) {
matching_models.push_back(itr_match->second);
}
std::sort(matching_models.begin(), matching_models.end(), KRMesh::lod_sort_predicate);
if(matching_models.size() == 0) {
if (matching_models.size() == 0) {
KRContext::Log(KRContext::LOG_LEVEL_INFORMATION, "Model not found: %s", lowerName.c_str());
}
return matching_models;
}
unordered_multimap<std::string, KRMesh *> &KRMeshManager::getModels() {
unordered_multimap<std::string, KRMesh*>& KRMeshManager::getModels()
{
return m_models;
}
void KRMeshManager::bindVBO(VkCommandBuffer& commandBuffer, KRVBOData *vbo_data, float lodCoverage)
void KRMeshManager::bindVBO(VkCommandBuffer& commandBuffer, KRVBOData* vbo_data, float lodCoverage)
{
vbo_data->resetPoolExpiry(lodCoverage);
bool vbo_changed = false;
if(m_currentVBO == NULL) {
if (m_currentVBO == NULL) {
vbo_changed = true;
} else if(m_currentVBO->m_data != vbo_data->m_data) {
} else if (m_currentVBO->m_data != vbo_data->m_data) {
vbo_changed = true;
}
if(vbo_changed) {
if (vbo_changed) {
if(m_vbosActive.find(vbo_data->m_data) != m_vbosActive.end()) {
if (m_vbosActive.find(vbo_data->m_data) != m_vbosActive.end()) {
m_currentVBO = m_vbosActive[vbo_data->m_data];
} else {
m_currentVBO = vbo_data;
@@ -215,7 +222,7 @@ void KRMeshManager::bindVBO(VkCommandBuffer& commandBuffer, KRVBOData *vbo_data,
void KRMeshManager::startFrame(float deltaTime)
{
m_memoryTransferredThisFrame = 0;
if(m_draw_call_log_used) {
if (m_draw_call_log_used) {
// Only log draw calls on the next frame if the draw call log was used on last frame
m_draw_call_log_used = false;
m_draw_call_logging_enabled = true;
@@ -225,23 +232,23 @@ void KRMeshManager::startFrame(float deltaTime)
// TODO - Implement proper double-buffering to reduce copy operations
m_streamerFenceMutex.lock();
if(m_streamerComplete) {
if (m_streamerComplete) {
assert(m_activeVBOs_streamer_copy.size() == 0); // The streamer should have emptied this if it really did complete
const long KRENGINE_VBO_EXPIRY_FRAMES = 1;
std::set<KRVBOData *> expiredVBOs;
for(auto itr=m_vbosActive.begin(); itr != m_vbosActive.end(); itr++) {
KRVBOData *activeVBO = (*itr).second;
std::set<KRVBOData*> expiredVBOs;
for (auto itr = m_vbosActive.begin(); itr != m_vbosActive.end(); itr++) {
KRVBOData* activeVBO = (*itr).second;
activeVBO->_swapHandles();
if (activeVBO->getType() == KRVBOData::CONSTANT) {
// Ensure that CONSTANT data is always loaded
float priority = std::numeric_limits<float>::max();
m_activeVBOs_streamer_copy.push_back(std::pair<float, KRVBOData*>(priority, activeVBO));
} else if(activeVBO->getLastFrameUsed() + KRENGINE_VBO_EXPIRY_FRAMES < getContext().getCurrentFrame()) {
} else if (activeVBO->getLastFrameUsed() + KRENGINE_VBO_EXPIRY_FRAMES < getContext().getCurrentFrame()) {
// Expire VBO's that haven't been used in a long time
switch(activeVBO->getType()) {
switch (activeVBO->getType()) {
case KRVBOData::STREAMING:
case KRVBOData::IMMEDIATE:
activeVBO->unload();
@@ -252,16 +259,16 @@ void KRMeshManager::startFrame(float deltaTime)
}
expiredVBOs.insert(activeVBO);
} else if(activeVBO->getType() == KRVBOData::STREAMING) {
} else if (activeVBO->getType() == KRVBOData::STREAMING) {
float priority = activeVBO->getStreamPriority();
m_activeVBOs_streamer_copy.push_back(std::pair<float, KRVBOData *>(priority, activeVBO));
m_activeVBOs_streamer_copy.push_back(std::pair<float, KRVBOData*>(priority, activeVBO));
}
}
for(std::set<KRVBOData *>::iterator itr=expiredVBOs.begin(); itr != expiredVBOs.end(); itr++) {
for (std::set<KRVBOData*>::iterator itr = expiredVBOs.begin(); itr != expiredVBOs.end(); itr++) {
m_vbosActive.erase((*itr)->m_data);
}
if(m_activeVBOs_streamer_copy.size() > 0) {
if (m_activeVBOs_streamer_copy.size() > 0) {
m_streamerComplete = false;
}
}
@@ -274,7 +281,7 @@ void KRMeshManager::endFrame(float deltaTime)
m_currentVBO = nullptr;
}
void KRMeshManager::doStreaming(long &memoryRemaining, long &memoryRemainingThisFrame)
void KRMeshManager::doStreaming(long& memoryRemaining, long& memoryRemainingThisFrame)
{
// TODO - Implement proper double-buffering to reduce copy operations
@@ -282,7 +289,7 @@ void KRMeshManager::doStreaming(long &memoryRemaining, long &memoryRemainingThis
m_activeVBOs_streamer = std::move(m_activeVBOs_streamer_copy);
m_streamerFenceMutex.unlock();
if(m_activeVBOs_streamer.size() > 0) {
if (m_activeVBOs_streamer.size() > 0) {
balanceVBOMemory(memoryRemaining, memoryRemainingThisFrame);
m_streamerFenceMutex.lock();
@@ -293,16 +300,16 @@ void KRMeshManager::doStreaming(long &memoryRemaining, long &memoryRemainingThis
}
}
void KRMeshManager::balanceVBOMemory(long &memoryRemaining, long &memoryRemainingThisFrame)
void KRMeshManager::balanceVBOMemory(long& memoryRemaining, long& memoryRemainingThisFrame)
{
std::sort(m_activeVBOs_streamer.begin(), m_activeVBOs_streamer.end(), std::greater<std::pair<float, KRVBOData *>>());
std::sort(m_activeVBOs_streamer.begin(), m_activeVBOs_streamer.end(), std::greater<std::pair<float, KRVBOData*>>());
for(auto vbo_itr = m_activeVBOs_streamer.begin(); vbo_itr != m_activeVBOs_streamer.end(); vbo_itr++) {
KRVBOData *vbo_data = (*vbo_itr).second;
for (auto vbo_itr = m_activeVBOs_streamer.begin(); vbo_itr != m_activeVBOs_streamer.end(); vbo_itr++) {
KRVBOData* vbo_data = (*vbo_itr).second;
long vbo_size = vbo_data->getSize();
if(!vbo_data->isVBOLoaded()) {
if(memoryRemainingThisFrame > vbo_size) {
if (!vbo_data->isVBOLoaded()) {
if (memoryRemainingThisFrame > vbo_size) {
vbo_data->load();
memoryRemainingThisFrame -= vbo_size;
}
@@ -319,7 +326,7 @@ long KRMeshManager::getMemUsed()
long KRMeshManager::getMemActive()
{
long mem_active = 0;
for(unordered_map<KRDataBlock *, KRVBOData *>::iterator itr = m_vbosActive.begin(); itr != m_vbosActive.end(); itr++) {
for (unordered_map<KRDataBlock*, KRVBOData*>::iterator itr = m_vbosActive.begin(); itr != m_vbosActive.end(); itr++) {
mem_active += (*itr).second->getSize();
}
return mem_active;
@@ -327,12 +334,12 @@ long KRMeshManager::getMemActive()
void KRMeshManager::initVolumetricLightingVertexes()
{
if(m_volumetricLightingVertexData.getSize() == 0) {
if (m_volumetricLightingVertexData.getSize() == 0) {
m_volumetricLightingVertexData.expand(sizeof(VolumetricLightingVertexData) * KRENGINE_MAX_VOLUMETRIC_PLANES * 6);
m_volumetricLightingVertexData.lock();
VolumetricLightingVertexData * vertex_data = (VolumetricLightingVertexData *)m_volumetricLightingVertexData.getStart();
int iVertex=0;
for(int iPlane=0; iPlane < KRENGINE_MAX_VOLUMETRIC_PLANES; iPlane++) {
VolumetricLightingVertexData* vertex_data = (VolumetricLightingVertexData*)m_volumetricLightingVertexData.getStart();
int iVertex = 0;
for (int iPlane = 0; iPlane < KRENGINE_MAX_VOLUMETRIC_PLANES; iPlane++) {
vertex_data[iVertex].vertex.x = -1.0f;
vertex_data[iVertex].vertex.y = -1.0f;
vertex_data[iVertex].vertex.z = (float)iPlane;
@@ -377,18 +384,18 @@ void KRMeshManager::initVolumetricLightingVertexes()
void KRMeshManager::initRandomParticles()
{
if(m_randomParticleVertexData.getSize() == 0) {
if (m_randomParticleVertexData.getSize() == 0) {
m_randomParticleVertexData.expand(sizeof(RandomParticleVertexData) * KRENGINE_MAX_RANDOM_PARTICLES * 3);
m_randomParticleVertexData.lock();
RandomParticleVertexData *vertex_data = (RandomParticleVertexData *)m_randomParticleVertexData.getStart();
RandomParticleVertexData* vertex_data = (RandomParticleVertexData*)m_randomParticleVertexData.getStart();
// Generate vertices for randomly placed equilateral triangles with a side length of 1 and an origin point centered so that an inscribed circle can be efficiently rendered without wasting fill
float equilateral_triangle_height = sqrt(3.0f) * 0.5f;
float inscribed_circle_radius = 1.0f / (2.0f * sqrt(3.0f));
int iVertex=0;
for(int iParticle=0; iParticle < KRENGINE_MAX_RANDOM_PARTICLES; iParticle++) {
int iVertex = 0;
for (int iParticle = 0; iParticle < KRENGINE_MAX_RANDOM_PARTICLES; iParticle++) {
vertex_data[iVertex].vertex.x = (float)(rand() % 2000) / 1000.0f - 1000.0f;
vertex_data[iVertex].vertex.y = (float)(rand() % 2000) / 1000.0f - 1000.0f;
vertex_data[iVertex].vertex.z = (float)(rand() % 2000) / 1000.0f - 1000.0f;
@@ -396,16 +403,16 @@ void KRMeshManager::initRandomParticles()
vertex_data[iVertex].uva.y = -inscribed_circle_radius;
iVertex++;
vertex_data[iVertex].vertex.x = vertex_data[iVertex-1].vertex.x;
vertex_data[iVertex].vertex.y = vertex_data[iVertex-1].vertex.y;
vertex_data[iVertex].vertex.z = vertex_data[iVertex-1].vertex.z;
vertex_data[iVertex].vertex.x = vertex_data[iVertex - 1].vertex.x;
vertex_data[iVertex].vertex.y = vertex_data[iVertex - 1].vertex.y;
vertex_data[iVertex].vertex.z = vertex_data[iVertex - 1].vertex.z;
vertex_data[iVertex].uva.x = 0.5f;
vertex_data[iVertex].uva.y = -inscribed_circle_radius;
iVertex++;
vertex_data[iVertex].vertex.x = vertex_data[iVertex-1].vertex.x;
vertex_data[iVertex].vertex.y = vertex_data[iVertex-1].vertex.y;
vertex_data[iVertex].vertex.z = vertex_data[iVertex-1].vertex.z;
vertex_data[iVertex].vertex.x = vertex_data[iVertex - 1].vertex.x;
vertex_data[iVertex].vertex.y = vertex_data[iVertex - 1].vertex.y;
vertex_data[iVertex].vertex.z = vertex_data[iVertex - 1].vertex.z;
vertex_data[iVertex].uva.x = 0.0f;
vertex_data[iVertex].uva.y = -inscribed_circle_radius + equilateral_triangle_height;
iVertex++;
@@ -432,9 +439,9 @@ size_t KRMeshManager::getActiveVBOCount()
return m_vbosActive.size();
}
void KRMeshManager::log_draw_call(KRNode::RenderPass pass, const std::string &object_name, const std::string &material_name, int vertex_count)
void KRMeshManager::log_draw_call(KRNode::RenderPass pass, const std::string& object_name, const std::string& material_name, int vertex_count)
{
if(m_draw_call_logging_enabled) {
if (m_draw_call_logging_enabled) {
draw_call_info info;
info.pass = pass;
strncpy(info.object_name, object_name.c_str(), 256);
@@ -468,7 +475,7 @@ KRMeshManager::KRVBOData::KRVBOData()
memset(m_allocations, 0, sizeof(AllocationInfo) * KRENGINE_MAX_GPU_COUNT);
}
KRMeshManager::KRVBOData::KRVBOData(KRMeshManager *manager, KRDataBlock *data, KRDataBlock *index_data, int vertex_attrib_flags, bool static_vbo, vbo_type t
KRMeshManager::KRVBOData::KRVBOData(KRMeshManager* manager, KRDataBlock* data, KRDataBlock* index_data, int vertex_attrib_flags, bool static_vbo, vbo_type t
#if KRENGINE_DEBUG_GPU_LABELS
, const char* debug_label
#endif
@@ -478,14 +485,14 @@ KRMeshManager::KRVBOData::KRVBOData(KRMeshManager *manager, KRDataBlock *data, K
memset(m_allocations, 0, sizeof(AllocationInfo) * KRENGINE_MAX_GPU_COUNT);
m_is_vbo_loaded = false;
m_is_vbo_ready = false;
init(manager, data,index_data,vertex_attrib_flags, static_vbo, t
init(manager, data, index_data, vertex_attrib_flags, static_vbo, t
#if KRENGINE_DEBUG_GPU_LABELS
, debug_label
#endif
);
}
void KRMeshManager::KRVBOData::init(KRMeshManager *manager, KRDataBlock *data, KRDataBlock *index_data, int vertex_attrib_flags, bool static_vbo, vbo_type t
void KRMeshManager::KRVBOData::init(KRMeshManager* manager, KRDataBlock* data, KRDataBlock* index_data, int vertex_attrib_flags, bool static_vbo, vbo_type t
#if KRENGINE_DEBUG_GPU_LABELS
, const char* debug_label
#endif
@@ -502,7 +509,7 @@ void KRMeshManager::KRVBOData::init(KRMeshManager *manager, KRDataBlock *data, K
m_vertex_attrib_flags = vertex_attrib_flags;
m_size = m_data->getSize();
if(m_index_data != NULL) {
if (m_index_data != NULL) {
m_size += m_index_data->getSize();
}
@@ -527,7 +534,7 @@ void KRMeshManager::KRVBOData::load()
void KRMeshManager::KRVBOData::load(VkCommandBuffer& commandBuffer)
{
// TODO - We should load on each GPU only if there is a surface using the mesh
if(isVBOLoaded()) {
if (isVBOLoaded()) {
return;
}
@@ -607,7 +614,7 @@ void KRMeshManager::KRVBOData::load(VkCommandBuffer& commandBuffer)
m_manager->m_vboMemUsed += getSize();
m_manager->m_memoryTransferredThisFrame += getSize();
if(m_type != STREAMING) {
if (m_type != STREAMING) {
_swapHandles();
}
}
@@ -630,7 +637,7 @@ void KRMeshManager::KRVBOData::unload()
memset(&allocation, 0, sizeof(AllocationInfo));
}
if(isVBOLoaded()) {
if (isVBOLoaded()) {
m_manager->m_vboMemUsed -= getSize();
}
@@ -653,7 +660,7 @@ void KRMeshManager::KRVBOData::bind(VkCommandBuffer& commandBuffer)
void KRMeshManager::KRVBOData::resetPoolExpiry(float lodCoverage)
{
long current_frame = m_manager->getContext().getCurrentFrame();
if(current_frame != m_last_frame_used) {
if (current_frame != m_last_frame_used) {
m_last_frame_used = current_frame;
m_last_frame_max_lod_coverage = 0.0f;
@@ -666,7 +673,7 @@ void KRMeshManager::KRVBOData::resetPoolExpiry(float lodCoverage)
float KRMeshManager::KRVBOData::getStreamPriority()
{
long current_frame = m_manager->getContext().getCurrentFrame();
if(current_frame > m_last_frame_used + 5) {
if (current_frame > m_last_frame_used + 5) {
return 1.0f - KRCLAMP((float)(current_frame - m_last_frame_used) / 60.0f, 0.0f, 1.0f);
} else {
return 10000.0f + m_last_frame_max_lod_coverage * 10.0f;
@@ -678,9 +685,9 @@ void KRMeshManager::KRVBOData::_swapHandles()
m_is_vbo_ready = m_is_vbo_loaded;
}
void KRMeshManager::primeVBO(KRVBOData *vbo_data)
void KRMeshManager::primeVBO(KRVBOData* vbo_data)
{
if(m_vbosActive.find(vbo_data->m_data) == m_vbosActive.end()) {
if (m_vbosActive.find(vbo_data->m_data) == m_vbosActive.end()) {
m_vbosActive[vbo_data->m_data] = vbo_data;
}
}

View File

@@ -41,12 +41,13 @@
class KRContext;
class KRMesh;
class KRMeshManager : public KRResourceManager {
class KRMeshManager : public KRResourceManager
{
public:
static const int KRENGINE_MAX_VOLUMETRIC_PLANES=500;
static const int KRENGINE_MAX_RANDOM_PARTICLES=150000;
static const int KRENGINE_MAX_VOLUMETRIC_PLANES = 500;
static const int KRENGINE_MAX_RANDOM_PARTICLES = 150000;
KRMeshManager(KRContext &context);
KRMeshManager(KRContext& context);
void init();
virtual ~KRMeshManager();
@@ -56,19 +57,21 @@ public:
void startFrame(float deltaTime);
void endFrame(float deltaTime);
KRMesh *loadModel(const char *szName, KRDataBlock *pData);
std::vector<KRMesh *> getModel(const char *szName);
KRMesh* loadModel(const char* szName, KRDataBlock* pData);
std::vector<KRMesh*> getModel(const char* szName);
KRMesh* KRMeshManager::getMaxLODModel(const char* szName);
void addModel(KRMesh *model);
void addModel(KRMesh* model);
std::vector<std::string> getModelNames();
unordered_multimap<std::string, KRMesh *> &getModels();
unordered_multimap<std::string, KRMesh*>& getModels();
class KRVBOData {
class KRVBOData
{
public:
typedef enum {
typedef enum
{
STREAMING,
// STREAMING data is loaded asynchronously, with transfer queues in the streamer thread.
@@ -81,12 +84,12 @@ public:
} vbo_type;
KRVBOData();
KRVBOData(KRMeshManager *manager, KRDataBlock *data, KRDataBlock *index_data, int vertex_attrib_flags, bool static_vbo, vbo_type t
KRVBOData(KRMeshManager* manager, KRDataBlock* data, KRDataBlock* index_data, int vertex_attrib_flags, bool static_vbo, vbo_type t
#if KRENGINE_DEBUG_GPU_LABELS
, const char* debug_label
#endif
);
void init(KRMeshManager *manager, KRDataBlock *data, KRDataBlock *index_data, int vertex_attrib_flags, bool static_vbo, vbo_type t
void init(KRMeshManager* manager, KRDataBlock* data, KRDataBlock* index_data, int vertex_attrib_flags, bool static_vbo, vbo_type t
#if KRENGINE_DEBUG_GPU_LABELS
, const char* debug_label
#endif
@@ -94,11 +97,17 @@ public:
~KRVBOData();
KRDataBlock *m_data;
KRDataBlock *m_index_data;
KRDataBlock* m_data;
KRDataBlock* m_index_data;
bool isVBOLoaded() { return m_is_vbo_loaded; }
bool isVBOReady() { return m_is_vbo_ready; }
bool isVBOLoaded()
{
return m_is_vbo_loaded;
}
bool isVBOReady()
{
return m_is_vbo_ready;
}
void load();
void load(VkCommandBuffer& commandBuffer);
void unload();
@@ -108,12 +117,21 @@ public:
KRVBOData(const KRVBOData& o) = delete;
KRVBOData& operator=(const KRVBOData& o) = delete;
long getSize() { return (long)m_size; }
long getSize()
{
return (long)m_size;
}
void resetPoolExpiry(float lodCoverage);
long getLastFrameUsed() { return m_last_frame_used; }
long getLastFrameUsed()
{
return m_last_frame_used;
}
vbo_type getType() { return m_type; }
vbo_type getType()
{
return m_type;
}
float getStreamPriority();
@@ -124,7 +142,7 @@ public:
uint32_t getVertexAttributes();
private:
KRMeshManager *m_manager;
KRMeshManager* m_manager;
int m_vertex_attrib_flags;
long m_size;
@@ -135,7 +153,8 @@ public:
bool m_is_vbo_loaded;
bool m_is_vbo_ready;
typedef struct {
typedef struct
{
KrDeviceHandle device;
VkBuffer vertex_buffer;
VmaAllocation vertex_allocation;
@@ -150,16 +169,18 @@ public:
#endif
};
void bindVBO(VkCommandBuffer& commandBuffer, KRVBOData *vbo_data, float lodCoverage);
void bindVBO(VkCommandBuffer& commandBuffer, KRVBOData* vbo_data, float lodCoverage);
long getMemUsed();
long getMemActive();
typedef struct {
typedef struct
{
Vector3 vertex;
Vector2 uva;
} RandomParticleVertexData;
typedef struct {
typedef struct
{
Vector3 vertex;
} VolumetricLightingVertexData;
@@ -167,14 +188,15 @@ public:
size_t getActiveVBOCount();
struct draw_call_info {
struct draw_call_info
{
KRNode::RenderPass pass;
char object_name[256];
char material_name[256];
int vertex_count;
};
void log_draw_call(KRNode::RenderPass pass, const std::string &object_name, const std::string &material_name, int vertex_count);
void log_draw_call(KRNode::RenderPass pass, const std::string& object_name, const std::string& material_name, int vertex_count);
std::vector<draw_call_info> getDrawCalls();
@@ -185,7 +207,7 @@ public:
KRVBOData KRENGINE_VBO_DATA_VOLUMETRIC_LIGHTING;
void doStreaming(long &memoryRemaining, long &memoryRemainingThisFrame);
void doStreaming(long& memoryRemaining, long& memoryRemainingThisFrame);
private:
KRDataBlock KRENGINE_VBO_3D_CUBE_VERTICES;
@@ -193,14 +215,14 @@ private:
KRDataBlock KRENGINE_VBO_2D_SQUARE_VERTICES;
__int32_t KRENGINE_VBO_2D_SQUARE_ATTRIBS;
unordered_multimap<std::string, KRMesh *> m_models; // Multiple models with the same name/key may be inserted, representing multiple LOD levels of the model
unordered_multimap<std::string, KRMesh*> m_models; // Multiple models with the same name/key may be inserted, representing multiple LOD levels of the model
long m_vboMemUsed;
KRVBOData *m_currentVBO;
KRVBOData* m_currentVBO;
unordered_map<KRDataBlock *, KRVBOData *> m_vbosActive;
std::vector<std::pair<float, KRVBOData *> > m_activeVBOs_streamer;
std::vector<std::pair<float, KRVBOData *> > m_activeVBOs_streamer_copy;
unordered_map<KRDataBlock*, KRVBOData*> m_vbosActive;
std::vector<std::pair<float, KRVBOData*> > m_activeVBOs_streamer;
std::vector<std::pair<float, KRVBOData*> > m_activeVBOs_streamer_copy;
KRDataBlock m_randomParticleVertexData;
KRDataBlock m_volumetricLightingVertexData;
@@ -214,9 +236,9 @@ private:
std::mutex m_streamerFenceMutex;
bool m_streamerComplete;
void balanceVBOMemory(long &memoryRemaining, long &memoryRemainingThisFrame);
void balanceVBOMemory(long& memoryRemaining, long& memoryRemainingThisFrame);
void primeVBO(KRVBOData *vbo_data);
void primeVBO(KRVBOData* vbo_data);
void initRandomParticles();
void initVolumetricLightingVertexes();

View File

@@ -32,7 +32,7 @@
#include "KRMeshQuad.h"
KRMeshQuad::KRMeshQuad(KRContext &context) : KRMesh(context, "__quad")
KRMeshQuad::KRMeshQuad(KRContext& context) : KRMesh(context, "__quad")
{
m_constant = true;

View File

@@ -33,9 +33,10 @@
#include "KRMesh.h"
class KRMeshQuad : public KRMesh {
class KRMeshQuad : public KRMesh
{
public:
KRMeshQuad(KRContext &context);
KRMeshQuad(KRContext& context);
virtual ~KRMeshQuad();
private:
};

View File

@@ -32,7 +32,7 @@
#include "KRMeshSphere.h"
KRMeshSphere::KRMeshSphere(KRContext &context) : KRMesh(context, "__sphere")
KRMeshSphere::KRMeshSphere(KRContext& context) : KRMesh(context, "__sphere")
{
m_constant = true;
@@ -46,7 +46,7 @@ KRMeshSphere::KRMeshSphere(KRContext &context) : KRMesh(context, "__sphere")
std::vector<Triangle3> f = std::vector<Triangle3>(facet_count);
int i,it;
int i, it;
float a;
Vector3 p[6] = {
Vector3::Create(0,0,1),
@@ -57,12 +57,12 @@ KRMeshSphere::KRMeshSphere(KRContext &context) : KRMesh(context, "__sphere")
Vector3::Create(-1,1,0)
};
Vector3 pa,pb,pc;
int nt = 0,ntold;
Vector3 pa, pb, pc;
int nt = 0, ntold;
/* Create the level 0 object */
a = 1.0f / sqrtf(2.0f);
for (i=0;i<6;i++) {
for (i = 0; i < 6; i++) {
p[i].x *= a;
p[i].y *= a;
}
@@ -77,9 +77,9 @@ KRMeshSphere::KRMeshSphere(KRContext &context) : KRMesh(context, "__sphere")
nt = 8;
/* Bisect each edge and move to the surface of a unit sphere */
for (it=0;it<iterations;it++) {
for (it = 0; it < iterations; it++) {
ntold = nt;
for (i=0;i<ntold;i++) {
for (i = 0; i < ntold; i++) {
pa.x = (f[i][0].x + f[i][1].x) / 2;
pa.y = (f[i][0].y + f[i][1].y) / 2;
pa.z = (f[i][0].z + f[i][1].z) / 2;
@@ -101,7 +101,7 @@ KRMeshSphere::KRMeshSphere(KRContext &context) : KRMesh(context, "__sphere")
}
}
for(int facet_index=0; facet_index < facet_count; facet_index++) {
for (int facet_index = 0; facet_index < facet_count; facet_index++) {
mi.vertices.push_back(f[facet_index][0]);
mi.vertices.push_back(f[facet_index][1]);
mi.vertices.push_back(f[facet_index][2]);

View File

@@ -33,9 +33,10 @@
#include "KRMesh.h"
class KRMeshSphere : public KRMesh {
class KRMeshSphere : public KRMesh
{
public:
KRMeshSphere(KRContext &context);
KRMeshSphere(KRContext& context);
virtual ~KRMeshSphere();
private:
};

View File

@@ -49,7 +49,8 @@ void KRModel::InitNodeInfo(KrNodeInfo* nodeInfo)
nodeInfo->model.rim_power = 0.0f;
}
KRModel::KRModel(KRScene &scene, std::string instance_name, std::string model_name, std::string light_map, float lod_min_coverage, bool receives_shadow, bool faces_camera, Vector3 rim_color, float rim_power) : KRNode(scene, instance_name) {
KRModel::KRModel(KRScene& scene, std::string instance_name, std::string model_name, std::string light_map, float lod_min_coverage, bool receives_shadow, bool faces_camera, Vector3 rim_color, float rim_power) : KRNode(scene, instance_name)
{
m_lightMap = light_map;
m_pLightMap = NULL;
m_model_name = model_name;
@@ -77,17 +78,19 @@ KRModel::KRModel(KRScene &scene, std::string instance_name, std::string model_na
m_boundsCachedMat.c[15] = -1.0f;
}
KRModel::~KRModel() {
KRModel::~KRModel()
{
}
std::string KRModel::getElementName() {
std::string KRModel::getElementName()
{
return "model";
}
tinyxml2::XMLElement *KRModel::saveXML( tinyxml2::XMLNode *parent)
tinyxml2::XMLElement* KRModel::saveXML(tinyxml2::XMLNode* parent)
{
tinyxml2::XMLElement *e = KRNode::saveXML(parent);
tinyxml2::XMLElement* e = KRNode::saveXML(parent);
e->SetAttribute("mesh", m_model_name.c_str());
e->SetAttribute("light_map", m_lightMap.c_str());
e->SetAttribute("lod_min_coverage", m_min_lod_coverage);
@@ -98,7 +101,7 @@ tinyxml2::XMLElement *KRModel::saveXML( tinyxml2::XMLNode *parent)
return e;
}
void KRModel::setRimColor(const Vector3 &rim_color)
void KRModel::setRimColor(const Vector3& rim_color)
{
m_rim_color = rim_color;
}
@@ -118,7 +121,7 @@ float KRModel::getRimPower()
return m_rim_power;
}
void KRModel::setLightMap(const std::string &name)
void KRModel::setLightMap(const std::string& name)
{
m_lightMap = name;
m_pLightMap = NULL;
@@ -129,19 +132,20 @@ std::string KRModel::getLightMap()
return m_lightMap;
}
void KRModel::loadModel() {
if(m_models.size() == 0) {
std::vector<KRMesh *> models = m_pContext->getMeshManager()->getModel(m_model_name.c_str()); // The model manager returns the LOD levels in sorted order, with the highest detail first
unordered_map<KRMesh *, std::vector<KRBone *> > bones;
if(models.size() > 0) {
void KRModel::loadModel()
{
if (m_models.size() == 0) {
std::vector<KRMesh*> models = m_pContext->getMeshManager()->getModel(m_model_name.c_str()); // The model manager returns the LOD levels in sorted order, with the highest detail first
unordered_map<KRMesh*, std::vector<KRBone*> > bones;
if (models.size() > 0) {
bool all_bones_found = true;
for(std::vector<KRMesh *>::iterator model_itr = models.begin(); model_itr != models.end(); model_itr++) {
KRMesh *model = *model_itr;
std::vector<KRBone *> model_bones;
for (std::vector<KRMesh*>::iterator model_itr = models.begin(); model_itr != models.end(); model_itr++) {
KRMesh* model = *model_itr;
std::vector<KRBone*> model_bones;
int bone_count = model->getBoneCount();
for(int bone_index=0; bone_index < bone_count; bone_index++) {
KRBone *matching_bone = dynamic_cast<KRBone *>(getScene().getRootNode()->find<KRNode>(model->getBoneName(bone_index)));
if(matching_bone) {
for (int bone_index = 0; bone_index < bone_count; bone_index++) {
KRBone* matching_bone = dynamic_cast<KRBone*>(getScene().getRootNode()->find<KRNode>(model->getBoneName(bone_index)));
if (matching_bone) {
model_bones.push_back(matching_bone);
} else {
all_bones_found = false; // Reject when there are any missing bones or multiple matches
@@ -149,7 +153,7 @@ void KRModel::loadModel() {
}
bones[model] = model_bones;
}
if(all_bones_found) {
if (all_bones_found) {
m_models = models;
m_bones = bones;
getScene().notify_sceneGraphModify(this);
@@ -160,17 +164,18 @@ void KRModel::loadModel() {
}
}
void KRModel::render(KRNode::RenderInfo& ri) {
void KRModel::render(KRNode::RenderInfo& ri)
{
if(m_lod_visible >= LOD_VISIBILITY_PRESTREAM && ri.renderPass == KRNode::RENDER_PASS_PRESTREAM) {
if (m_lod_visible >= LOD_VISIBILITY_PRESTREAM && ri.renderPass == KRNode::RENDER_PASS_PRESTREAM) {
preStream(ri.viewport);
}
if(m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
if (m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
KRNode::render(ri);
if(ri.renderPass != KRNode::RENDER_PASS_DEFERRED_LIGHTS
if (ri.renderPass != KRNode::RENDER_PASS_DEFERRED_LIGHTS
&& ri.renderPass != KRNode::RENDER_PASS_ADDITIVE_PARTICLES
&& ri.renderPass != KRNode::RENDER_PASS_PARTICLE_OCCLUSION
&& ri.renderPass != KRNode::RENDER_PASS_VOLUMETRIC_EFFECTS_ADDITIVE
@@ -178,7 +183,7 @@ void KRModel::render(KRNode::RenderInfo& ri) {
&& ri.renderPass != KRNode::RENDER_PASS_PRESTREAM) {
loadModel();
if(m_models.size() > 0) {
if (m_models.size() > 0) {
// Don't render meshes on second pass of the deferred lighting renderer, as only lights will be applied
/*
@@ -192,31 +197,31 @@ void KRModel::render(KRNode::RenderInfo& ri) {
float lod_coverage = ri.viewport.coverage(getBounds()); // This also checks the view frustrum culling
if(lod_coverage > m_min_lod_coverage) {
if (lod_coverage > m_min_lod_coverage) {
// ---===--- Select the best LOD model based on screen coverage ---===---
std::vector<KRMesh *>::iterator itr=m_models.begin();
KRMesh *pModel = *itr++;
std::vector<KRMesh*>::iterator itr = m_models.begin();
KRMesh* pModel = *itr++;
while(itr != m_models.end()) {
KRMesh *pLODModel = *itr++;
if((float)pLODModel->getLODCoverage() / 100.0f > lod_coverage && pLODModel->getLODCoverage() < pModel->getLODCoverage()) {
while (itr != m_models.end()) {
KRMesh* pLODModel = *itr++;
if ((float)pLODModel->getLODCoverage() / 100.0f > lod_coverage && pLODModel->getLODCoverage() < pModel->getLODCoverage()) {
pModel = pLODModel;
} else {
break;
}
}
if(m_pLightMap == NULL && m_lightMap.size()) {
if (m_pLightMap == NULL && m_lightMap.size()) {
m_pLightMap = getContext().getTextureManager()->getTexture(m_lightMap);
}
if(m_pLightMap && ri.camera->settings.bEnableLightMap && ri.renderPass != RENDER_PASS_SHADOWMAP && ri.renderPass != RENDER_PASS_GENERATE_SHADOWMAPS) {
if (m_pLightMap && ri.camera->settings.bEnableLightMap && ri.renderPass != RENDER_PASS_SHADOWMAP && ri.renderPass != RENDER_PASS_GENERATE_SHADOWMAPS) {
m_pContext->getTextureManager()->selectTexture(5, m_pLightMap, lod_coverage, KRTexture::TEXTURE_USAGE_LIGHT_MAP);
}
Matrix4 matModel = getModelMatrix();
if(m_faces_camera) {
if (m_faces_camera) {
Vector3 model_center = Matrix4::Dot(matModel, Vector3::Zero());
Vector3 camera_pos = ri.viewport.getCameraPosition();
matModel = Quaternion::Create(Vector3::Forward(), Vector3::Normalize(camera_pos - model_center)).rotationMatrix() * matModel;
@@ -228,48 +233,49 @@ void KRModel::render(KRNode::RenderInfo& ri) {
}
}
void KRModel::preStream(const KRViewport &viewport)
void KRModel::preStream(const KRViewport& viewport)
{
loadModel();
float lod_coverage = viewport.coverage(getBounds());
for(auto itr = m_models.begin(); itr != m_models.end(); itr++) {
for (auto itr = m_models.begin(); itr != m_models.end(); itr++) {
(*itr)->preStream(lod_coverage);
}
if(m_pLightMap == NULL && m_lightMap.size()) {
if (m_pLightMap == NULL && m_lightMap.size()) {
m_pLightMap = getContext().getTextureManager()->getTexture(m_lightMap);
}
if(m_pLightMap) {
if (m_pLightMap) {
m_pLightMap->resetPoolExpiry(lod_coverage, KRTexture::TEXTURE_USAGE_LIGHT_MAP);
}
}
kraken_stream_level KRModel::getStreamLevel(const KRViewport &viewport)
kraken_stream_level KRModel::getStreamLevel(const KRViewport& viewport)
{
kraken_stream_level stream_level = KRNode::getStreamLevel(viewport);
loadModel();
for(auto itr = m_models.begin(); itr != m_models.end(); itr++) {
for (auto itr = m_models.begin(); itr != m_models.end(); itr++) {
stream_level = KRMIN(stream_level, (*itr)->getStreamLevel());
}
return stream_level;
}
AABB KRModel::getBounds() {
AABB KRModel::getBounds()
{
loadModel();
if(m_models.size() > 0) {
if(m_faces_camera) {
if (m_models.size() > 0) {
if (m_faces_camera) {
AABB normal_bounds = AABB::Create(m_models[0]->getMinPoint(), m_models[0]->getMaxPoint(), getModelMatrix());
float max_dimension = normal_bounds.longest_radius();
return AABB::Create(normal_bounds.center()-Vector3::Create(max_dimension), normal_bounds.center() + Vector3::Create(max_dimension));
return AABB::Create(normal_bounds.center() - Vector3::Create(max_dimension), normal_bounds.center() + Vector3::Create(max_dimension));
} else {
if(!(m_boundsCachedMat == getModelMatrix())) {
if (!(m_boundsCachedMat == getModelMatrix())) {
m_boundsCachedMat = getModelMatrix();
m_boundsCached = AABB::Create(m_models[0]->getMinPoint(), m_models[0]->getMaxPoint(), getModelMatrix());
}

View File

@@ -43,37 +43,38 @@
#include "KRTexture.h"
#include "KRBone.h"
class KRModel : public KRNode {
class KRModel : public KRNode
{
public:
static void InitNodeInfo(KrNodeInfo* nodeInfo);
KRModel(KRScene &scene, std::string instance_name, std::string model_name, std::string light_map, float lod_min_coverage, bool receives_shadow, bool faces_camera, Vector3 rim_color = Vector3::Zero(), float rim_power = 0.0f);
KRModel(KRScene& scene, std::string instance_name, std::string model_name, std::string light_map, float lod_min_coverage, bool receives_shadow, bool faces_camera, Vector3 rim_color = Vector3::Zero(), float rim_power = 0.0f);
virtual ~KRModel();
virtual std::string getElementName();
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual tinyxml2::XMLElement* saveXML(tinyxml2::XMLNode* parent);
virtual void render(KRNode::RenderInfo& ri);
virtual AABB getBounds();
void setRimColor(const Vector3 &rim_color);
void setRimColor(const Vector3& rim_color);
void setRimPower(float rim_power);
Vector3 getRimColor();
float getRimPower();
void setLightMap(const std::string &name);
void setLightMap(const std::string& name);
std::string getLightMap();
virtual kraken_stream_level getStreamLevel(const KRViewport &viewport);
virtual kraken_stream_level getStreamLevel(const KRViewport& viewport);
private:
void preStream(const KRViewport &viewport);
void preStream(const KRViewport& viewport);
std::vector<KRMesh *> m_models;
unordered_map<KRMesh *, std::vector<KRBone *> > m_bones; // Outer std::map connects model to set of bones
KRTexture *m_pLightMap;
std::vector<KRMesh*> m_models;
unordered_map<KRMesh*, std::vector<KRBone*> > m_bones; // Outer std::map connects model to set of bones
KRTexture* m_pLightMap;
std::string m_lightMap;
std::string m_model_name;

View File

@@ -63,7 +63,7 @@ void KRNode::InitNodeInfo(KrNodeInfo* nodeInfo)
nodeInfo->scale_pivot = Vector3::Zero();
}
KRNode::KRNode(KRScene &scene, std::string name) : KRContextObject(scene.getContext())
KRNode::KRNode(KRScene& scene, std::string name) : KRContextObject(scene.getContext())
{
m_name = name;
m_localScale = Vector3::One();
@@ -104,24 +104,25 @@ KRNode::KRNode(KRScene &scene, std::string name) : KRContextObject(scene.getCont
m_boundsValid = false;
m_lastRenderFrame = -1000;
for(int i=0; i < KRENGINE_NODE_ATTRIBUTE_COUNT; i++) {
for (int i = 0; i < KRENGINE_NODE_ATTRIBUTE_COUNT; i++) {
m_animation_mask[i] = false;
}
}
KRNode::~KRNode() {
KRNode::~KRNode()
{
while(m_childNodes.size() > 0) {
delete *m_childNodes.begin();
while (m_childNodes.size() > 0) {
delete* m_childNodes.begin();
}
for(std::set<KRBehavior *>::iterator itr = m_behaviors.begin(); itr != m_behaviors.end(); itr++) {
delete *itr;
for (std::set<KRBehavior*>::iterator itr = m_behaviors.begin(); itr != m_behaviors.end(); itr++) {
delete* itr;
}
m_behaviors.clear();
if(m_parentNode) {
if (m_parentNode) {
m_parentNode->childDeleted(this);
}
@@ -131,7 +132,7 @@ KRNode::~KRNode() {
void KRNode::setScaleCompensation(bool scale_compensation)
{
if(m_scale_compensation != scale_compensation) {
if (m_scale_compensation != scale_compensation) {
m_scale_compensation = scale_compensation;
invalidateModelMatrix();
invalidateBindPoseMatrix();
@@ -142,24 +143,26 @@ bool KRNode::getScaleCompensation()
return m_scale_compensation;
}
void KRNode::childDeleted(KRNode *child_node)
void KRNode::childDeleted(KRNode* child_node)
{
m_childNodes.erase(child_node);
invalidateBounds();
getScene().notify_sceneGraphModify(this);
}
void KRNode::addChild(KRNode *child) {
void KRNode::addChild(KRNode* child)
{
assert(child->m_parentNode == NULL);
child->m_parentNode = this;
m_childNodes.insert(child);
child->setLODVisibility(m_lod_visible); // Child node inherits LOD visibility status from parent
}
tinyxml2::XMLElement *KRNode::saveXML(tinyxml2::XMLNode *parent) {
tinyxml2::XMLDocument *doc = parent->GetDocument();
tinyxml2::XMLElement *e = doc->NewElement(getElementName().c_str());
tinyxml2::XMLNode *n = parent->InsertEndChild(e);
tinyxml2::XMLElement* KRNode::saveXML(tinyxml2::XMLNode* parent)
{
tinyxml2::XMLDocument* doc = parent->GetDocument();
tinyxml2::XMLElement* e = doc->NewElement(getElementName().c_str());
tinyxml2::XMLNode* n = parent->InsertEndChild(e);
e->SetAttribute("name", m_name.c_str());
kraken::setXMLAttribute("translate", e, m_localTranslation, Vector3::Zero());
kraken::setXMLAttribute("scale", e, m_localScale, Vector3::One());
@@ -171,14 +174,15 @@ tinyxml2::XMLElement *KRNode::saveXML(tinyxml2::XMLNode *parent) {
kraken::setXMLAttribute("pre_rotate", e, (m_preRotation * (180.0f / (float)M_PI)), Vector3::Zero());
kraken::setXMLAttribute("post_rotate", e, (m_postRotation * (180.0f / (float)M_PI)), Vector3::Zero());
for(std::set<KRNode *>::iterator itr=m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
KRNode *child = (*itr);
for (std::set<KRNode*>::iterator itr = m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
KRNode* child = (*itr);
child->saveXML(n);
}
return e;
}
void KRNode::loadXML(tinyxml2::XMLElement *e) {
void KRNode::loadXML(tinyxml2::XMLElement* e)
{
m_name = e->Attribute("name");
m_localTranslation = kraken::getXMLAttribute("translate", e, Vector3::Zero());
m_localScale = kraken::getXMLAttribute("scale", e, Vector3::One());
@@ -211,36 +215,37 @@ void KRNode::loadXML(tinyxml2::XMLElement *e) {
m_modelMatrixValid = false;
m_inverseModelMatrixValid = false;
for(tinyxml2::XMLElement *child_element=e->FirstChildElement(); child_element != NULL; child_element = child_element->NextSiblingElement()) {
const char *szElementName = child_element->Name();
if(strcmp(szElementName, "behavior") == 0) {
KRBehavior *behavior = KRBehavior::LoadXML(this, child_element);
if(behavior) {
for (tinyxml2::XMLElement* child_element = e->FirstChildElement(); child_element != NULL; child_element = child_element->NextSiblingElement()) {
const char* szElementName = child_element->Name();
if (strcmp(szElementName, "behavior") == 0) {
KRBehavior* behavior = KRBehavior::LoadXML(this, child_element);
if (behavior) {
addBehavior(behavior);
behavior->init();
}
} else {
KRNode *child_node = KRNode::LoadXML(getScene(), child_element);
KRNode* child_node = KRNode::LoadXML(getScene(), child_element);
if(child_node) {
if (child_node) {
addChild(child_node);
}
}
}
}
void KRNode::setLocalTranslation(const Vector3 &v, bool set_original) {
void KRNode::setLocalTranslation(const Vector3& v, bool set_original)
{
m_localTranslation = v;
if(set_original) {
if (set_original) {
m_initialLocalTranslation = v;
invalidateBindPoseMatrix();
}
invalidateModelMatrix();
}
void KRNode::setWorldTranslation(const Vector3 &v)
void KRNode::setWorldTranslation(const Vector3& v)
{
if(m_parentNode) {
if (m_parentNode) {
setLocalTranslation(Matrix4::Dot(m_parentNode->getInverseModelMatrix(), v));
} else {
setLocalTranslation(v);
@@ -248,9 +253,9 @@ void KRNode::setWorldTranslation(const Vector3 &v)
}
void KRNode::setWorldRotation(const Vector3 &v)
void KRNode::setWorldRotation(const Vector3& v)
{
if(m_parentNode) {
if (m_parentNode) {
setLocalRotation((Quaternion::Create(v) * -m_parentNode->getWorldRotation()).eulerXYZ());
setPreRotation(Vector3::Zero());
setPostRotation(Vector3::Zero());
@@ -262,27 +267,29 @@ void KRNode::setWorldRotation(const Vector3 &v)
}
void KRNode::setWorldScale(const Vector3 &v)
void KRNode::setWorldScale(const Vector3& v)
{
if(m_parentNode) {
if (m_parentNode) {
setLocalScale(Matrix4::DotNoTranslate(m_parentNode->getInverseModelMatrix(), v));
} else {
setLocalScale(v);
}
}
void KRNode::setLocalScale(const Vector3 &v, bool set_original) {
void KRNode::setLocalScale(const Vector3& v, bool set_original)
{
m_localScale = v;
if(set_original) {
if (set_original) {
m_initialLocalScale = v;
invalidateBindPoseMatrix();
}
invalidateModelMatrix();
}
void KRNode::setLocalRotation(const Vector3 &v, bool set_original) {
void KRNode::setLocalRotation(const Vector3& v, bool set_original)
{
m_localRotation = v;
if(set_original) {
if (set_original) {
m_initialLocalRotation = v;
invalidateBindPoseMatrix();
}
@@ -290,201 +297,211 @@ void KRNode::setLocalRotation(const Vector3 &v, bool set_original) {
}
void KRNode::setRotationOffset(const Vector3 &v, bool set_original)
void KRNode::setRotationOffset(const Vector3& v, bool set_original)
{
m_rotationOffset = v;
if(set_original) {
if (set_original) {
m_initialRotationOffset = v;
invalidateBindPoseMatrix();
}
invalidateModelMatrix();
}
void KRNode::setScalingOffset(const Vector3 &v, bool set_original)
void KRNode::setScalingOffset(const Vector3& v, bool set_original)
{
m_scalingOffset = v;
if(set_original) {
if (set_original) {
m_initialScalingOffset = v;
invalidateBindPoseMatrix();
}
invalidateModelMatrix();
}
void KRNode::setRotationPivot(const Vector3 &v, bool set_original)
void KRNode::setRotationPivot(const Vector3& v, bool set_original)
{
m_rotationPivot = v;
if(set_original) {
if (set_original) {
m_initialRotationPivot = v;
invalidateBindPoseMatrix();
}
invalidateModelMatrix();
}
void KRNode::setScalingPivot(const Vector3 &v, bool set_original)
void KRNode::setScalingPivot(const Vector3& v, bool set_original)
{
m_scalingPivot = v;
if(set_original) {
if (set_original) {
m_initialScalingPivot = v;
invalidateBindPoseMatrix();
}
invalidateModelMatrix();
}
void KRNode::setPreRotation(const Vector3 &v, bool set_original)
void KRNode::setPreRotation(const Vector3& v, bool set_original)
{
m_preRotation = v;
if(set_original) {
if (set_original) {
m_initialPreRotation = v;
invalidateBindPoseMatrix();
}
invalidateModelMatrix();
}
void KRNode::setPostRotation(const Vector3 &v, bool set_original)
void KRNode::setPostRotation(const Vector3& v, bool set_original)
{
m_postRotation = v;
if(set_original) {
if (set_original) {
m_initialPostRotation = v;
invalidateBindPoseMatrix();
}
invalidateModelMatrix();
}
const Vector3 &KRNode::getRotationOffset()
const Vector3& KRNode::getRotationOffset()
{
return m_rotationOffset;
}
const Vector3 &KRNode::getScalingOffset()
const Vector3& KRNode::getScalingOffset()
{
return m_scalingOffset;
}
const Vector3 &KRNode::getRotationPivot()
const Vector3& KRNode::getRotationPivot()
{
return m_rotationPivot;
}
const Vector3 &KRNode::getScalingPivot()
const Vector3& KRNode::getScalingPivot()
{
return m_scalingPivot;
}
const Vector3 &KRNode::getPreRotation()
const Vector3& KRNode::getPreRotation()
{
return m_preRotation;
}
const Vector3 &KRNode::getPostRotation()
const Vector3& KRNode::getPostRotation()
{
return m_postRotation;
}
const Vector3 &KRNode::getInitialRotationOffset()
const Vector3& KRNode::getInitialRotationOffset()
{
return m_initialRotationOffset;
}
const Vector3 &KRNode::getInitialScalingOffset()
const Vector3& KRNode::getInitialScalingOffset()
{
return m_initialScalingOffset;
}
const Vector3 &KRNode::getInitialRotationPivot()
const Vector3& KRNode::getInitialRotationPivot()
{
return m_initialRotationPivot;
}
const Vector3 &KRNode::getInitialScalingPivot()
const Vector3& KRNode::getInitialScalingPivot()
{
return m_initialScalingPivot;
}
const Vector3 &KRNode::getInitialPreRotation()
const Vector3& KRNode::getInitialPreRotation()
{
return m_initialPreRotation;
}
const Vector3 &KRNode::getInitialPostRotation()
const Vector3& KRNode::getInitialPostRotation()
{
return m_initialPostRotation;
}
const Vector3 &KRNode::getLocalTranslation() {
const Vector3& KRNode::getLocalTranslation()
{
return m_localTranslation;
}
const Vector3 &KRNode::getLocalScale() {
const Vector3& KRNode::getLocalScale()
{
return m_localScale;
}
const Vector3 &KRNode::getLocalRotation() {
const Vector3& KRNode::getLocalRotation()
{
return m_localRotation;
}
const Vector3 &KRNode::getInitialLocalTranslation() {
const Vector3& KRNode::getInitialLocalTranslation()
{
return m_initialLocalTranslation;
}
const Vector3 &KRNode::getInitialLocalScale() {
const Vector3& KRNode::getInitialLocalScale()
{
return m_initialLocalScale;
}
const Vector3 &KRNode::getInitialLocalRotation() {
const Vector3& KRNode::getInitialLocalRotation()
{
return m_initialLocalRotation;
}
const Vector3 KRNode::getWorldTranslation() {
const Vector3 KRNode::getWorldTranslation()
{
return localToWorld(Vector3::Zero());
}
const Vector3 KRNode::getWorldScale() {
const Vector3 KRNode::getWorldScale()
{
return Matrix4::DotNoTranslate(getModelMatrix(), m_localScale);
}
std::string KRNode::getElementName() {
std::string KRNode::getElementName()
{
return "node";
}
KRNode *KRNode::LoadXML(KRScene &scene, tinyxml2::XMLElement *e) {
KRNode *new_node = NULL;
const char *szElementName = e->Name();
const char *szName = e->Attribute("name");
if(strcmp(szElementName, "node") == 0) {
KRNode* KRNode::LoadXML(KRScene& scene, tinyxml2::XMLElement* e)
{
KRNode* new_node = NULL;
const char* szElementName = e->Name();
const char* szName = e->Attribute("name");
if (strcmp(szElementName, "node") == 0) {
new_node = new KRNode(scene, szName);
} else if(strcmp(szElementName, "lod_set") == 0) {
} else if (strcmp(szElementName, "lod_set") == 0) {
new_node = new KRLODSet(scene, szName);
} else if(strcmp(szElementName, "lod_group") == 0) {
} else if (strcmp(szElementName, "lod_group") == 0) {
new_node = new KRLODGroup(scene, szName);
} else if(strcmp(szElementName, "point_light") == 0) {
} else if (strcmp(szElementName, "point_light") == 0) {
new_node = new KRPointLight(scene, szName);
} else if(strcmp(szElementName, "directional_light") == 0) {
} else if (strcmp(szElementName, "directional_light") == 0) {
new_node = new KRDirectionalLight(scene, szName);
} else if(strcmp(szElementName, "spot_light") == 0) {
} else if (strcmp(szElementName, "spot_light") == 0) {
new_node = new KRSpotLight(scene, szName);
} else if(strcmp(szElementName, "particles_newtonian") == 0) {
} else if (strcmp(szElementName, "particles_newtonian") == 0) {
new_node = new KRParticleSystemNewtonian(scene, szName);
} else if(strcmp(szElementName, "sprite") == 0) {
} else if (strcmp(szElementName, "sprite") == 0) {
new_node = new KRSprite(scene, szName);
} else if(strcmp(szElementName, "model") == 0) {
} else if (strcmp(szElementName, "model") == 0) {
float lod_min_coverage = 0.0f;
if(e->QueryFloatAttribute("lod_min_coverage", &lod_min_coverage) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("lod_min_coverage", &lod_min_coverage) != tinyxml2::XML_SUCCESS) {
lod_min_coverage = 0.0f;
}
bool receives_shadow = true;
if(e->QueryBoolAttribute("receives_shadow", &receives_shadow) != tinyxml2::XML_SUCCESS) {
if (e->QueryBoolAttribute("receives_shadow", &receives_shadow) != tinyxml2::XML_SUCCESS) {
receives_shadow = true;
}
bool faces_camera = false;
if(e->QueryBoolAttribute("faces_camera", &faces_camera) != tinyxml2::XML_SUCCESS) {
if (e->QueryBoolAttribute("faces_camera", &faces_camera) != tinyxml2::XML_SUCCESS) {
faces_camera = false;
}
float rim_power = 0.0f;
if(e->QueryFloatAttribute("rim_power", &rim_power) != tinyxml2::XML_SUCCESS) {
if (e->QueryFloatAttribute("rim_power", &rim_power) != tinyxml2::XML_SUCCESS) {
rim_power = 0.0f;
}
Vector3 rim_color = Vector3::Zero();
rim_color = kraken::getXMLAttribute("rim_color", e, Vector3::Zero());
new_node = new KRModel(scene, szName, e->Attribute("mesh"), e->Attribute("light_map"), lod_min_coverage, receives_shadow, faces_camera, rim_color, rim_power);
} else if(strcmp(szElementName, "collider") == 0) {
} else if (strcmp(szElementName, "collider") == 0) {
new_node = new KRCollider(scene, szName, e->Attribute("mesh"), 65535, 1.0f);
} else if(strcmp(szElementName, "bone") == 0) {
} else if (strcmp(szElementName, "bone") == 0) {
new_node = new KRBone(scene, szName);
} else if(strcmp(szElementName, "locator") == 0) {
} else if (strcmp(szElementName, "locator") == 0) {
new_node = new KRLocator(scene, szName);
} else if(strcmp(szElementName, "audio_source") == 0) {
} else if (strcmp(szElementName, "audio_source") == 0) {
new_node = new KRAudioSource(scene, szName);
} else if(strcmp(szElementName, "ambient_zone") == 0) {
} else if (strcmp(szElementName, "ambient_zone") == 0) {
new_node = new KRAmbientZone(scene, szName);
} else if(strcmp(szElementName, "reverb_zone") == 0) {
} else if (strcmp(szElementName, "reverb_zone") == 0) {
new_node = new KRReverbZone(scene, szName);
} else if(strcmp(szElementName, "camera") == 0) {
} else if (strcmp(szElementName, "camera") == 0) {
new_node = new KRCamera(scene, szName);
}
if(new_node) {
if (new_node) {
new_node->loadXML(e);
}
@@ -493,36 +510,41 @@ KRNode *KRNode::LoadXML(KRScene &scene, tinyxml2::XMLElement *e) {
void KRNode::render(const RenderInfo& ri)
{
if(m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
if (m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
m_lastRenderFrame = getContext().getCurrentFrame();
}
const std::set<KRNode *> &KRNode::getChildren() {
const std::set<KRNode*>& KRNode::getChildren()
{
return m_childNodes;
}
KRNode *KRNode::getParent() {
KRNode* KRNode::getParent()
{
return m_parentNode;
}
const std::string &KRNode::getName() const {
const std::string& KRNode::getName() const
{
return m_name;
}
KRScene &KRNode::getScene() {
KRScene& KRNode::getScene()
{
return *m_pScene;
}
AABB KRNode::getBounds() {
if(!m_boundsValid) {
AABB KRNode::getBounds()
{
if (!m_boundsValid) {
AABB bounds = AABB::Zero();
bool first_child = true;
for(std::set<KRNode *>::iterator itr=m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
KRNode *child = (*itr);
if(child->getBounds() != AABB::Zero()) {
if(first_child) {
for (std::set<KRNode*>::iterator itr = m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
KRNode* child = (*itr);
if (child->getBounds() != AABB::Zero()) {
if (first_child) {
first_child = false;
bounds = child->getBounds();
} else {
@@ -542,8 +564,8 @@ void KRNode::invalidateModelMatrix()
m_modelMatrixValid = false;
m_activePoseMatrixValid = false;
m_inverseModelMatrixValid = false;
for(std::set<KRNode *>::iterator itr=m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
KRNode *child = (*itr);
for (std::set<KRNode*>::iterator itr = m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
KRNode* child = (*itr);
child->invalidateModelMatrix();
}
@@ -555,24 +577,24 @@ void KRNode::invalidateBindPoseMatrix()
{
m_bindPoseMatrixValid = false;
m_inverseBindPoseMatrixValid = false;
for(std::set<KRNode *>::iterator itr=m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
KRNode *child = (*itr);
for (std::set<KRNode*>::iterator itr = m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
KRNode* child = (*itr);
child->invalidateBindPoseMatrix();
}
}
const Matrix4 &KRNode::getModelMatrix()
const Matrix4& KRNode::getModelMatrix()
{
if(!m_modelMatrixValid) {
if (!m_modelMatrixValid) {
m_modelMatrix = Matrix4();
bool parent_is_bone = false;
if(dynamic_cast<KRBone *>(m_parentNode)) {
if (dynamic_cast<KRBone*>(m_parentNode)) {
parent_is_bone = true;
}
if(getScaleCompensation() && parent_is_bone) {
if (getScaleCompensation() && parent_is_bone) {
// WorldTransform = ParentWorldTransform * T * Roff * Rp * Rpre * R * Rpost * Rp-1 * Soff * Sp * S * Sp-1
@@ -588,7 +610,7 @@ const Matrix4 &KRNode::getModelMatrix()
* Matrix4::Translation(m_rotationPivot)
* Matrix4::Translation(m_rotationOffset);
if(m_parentNode) {
if (m_parentNode) {
m_modelMatrix.rotate(m_parentNode->getWorldRotation());
m_modelMatrix.translate(Matrix4::Dot(m_parentNode->getModelMatrix(), m_localTranslation));
@@ -611,7 +633,7 @@ const Matrix4 &KRNode::getModelMatrix()
* Matrix4::Translation(m_rotationOffset)
* Matrix4::Translation(m_localTranslation);
if(m_parentNode) {
if (m_parentNode) {
m_modelMatrix *= m_parentNode->getModelMatrix();
}
}
@@ -622,17 +644,17 @@ const Matrix4 &KRNode::getModelMatrix()
return m_modelMatrix;
}
const Matrix4 &KRNode::getBindPoseMatrix()
const Matrix4& KRNode::getBindPoseMatrix()
{
if(!m_bindPoseMatrixValid) {
if (!m_bindPoseMatrixValid) {
m_bindPoseMatrix = Matrix4();
bool parent_is_bone = false;
if(dynamic_cast<KRBone *>(m_parentNode)) {
if (dynamic_cast<KRBone*>(m_parentNode)) {
parent_is_bone = true;
}
if(getScaleCompensation() && parent_is_bone) {
if (getScaleCompensation() && parent_is_bone) {
m_bindPoseMatrix = Matrix4::Translation(-m_initialScalingPivot)
* Matrix4::Scaling(m_initialLocalScale)
* Matrix4::Translation(m_initialScalingPivot)
@@ -645,7 +667,7 @@ const Matrix4 &KRNode::getBindPoseMatrix()
* Matrix4::Translation(m_initialRotationPivot)
* Matrix4::Translation(m_initialRotationOffset);
//m_bindPoseMatrix.translate(m_localTranslation);
if(m_parentNode) {
if (m_parentNode) {
m_bindPoseMatrix.rotate(m_parentNode->getBindPoseWorldRotation());
m_bindPoseMatrix.translate(Matrix4::Dot(m_parentNode->getBindPoseMatrix(), m_localTranslation));
@@ -669,7 +691,7 @@ const Matrix4 &KRNode::getBindPoseMatrix()
* Matrix4::Translation(m_initialRotationOffset)
* Matrix4::Translation(m_initialLocalTranslation);
if(m_parentNode && parent_is_bone) {
if (m_parentNode && parent_is_bone) {
m_bindPoseMatrix *= m_parentNode->getBindPoseMatrix();
}
@@ -681,19 +703,19 @@ const Matrix4 &KRNode::getBindPoseMatrix()
return m_bindPoseMatrix;
}
const Matrix4 &KRNode::getActivePoseMatrix()
const Matrix4& KRNode::getActivePoseMatrix()
{
if(!m_activePoseMatrixValid) {
if (!m_activePoseMatrixValid) {
m_activePoseMatrix = Matrix4();
bool parent_is_bone = false;
if(dynamic_cast<KRBone *>(m_parentNode)) {
if (dynamic_cast<KRBone*>(m_parentNode)) {
parent_is_bone = true;
}
if(getScaleCompensation() && parent_is_bone) {
m_activePoseMatrix= Matrix4::Translation(-m_scalingPivot)
if (getScaleCompensation() && parent_is_bone) {
m_activePoseMatrix = Matrix4::Translation(-m_scalingPivot)
* Matrix4::Scaling(m_localScale)
* Matrix4::Translation(m_scalingPivot)
* Matrix4::Translation(m_scalingOffset)
@@ -704,7 +726,7 @@ const Matrix4 &KRNode::getActivePoseMatrix()
* Matrix4::Translation(m_rotationPivot)
* Matrix4::Translation(m_rotationOffset);
if(m_parentNode) {
if (m_parentNode) {
m_activePoseMatrix.rotate(m_parentNode->getActivePoseWorldRotation());
m_activePoseMatrix.translate(Matrix4::Dot(m_parentNode->getActivePoseMatrix(), m_localTranslation));
@@ -727,7 +749,7 @@ const Matrix4 &KRNode::getActivePoseMatrix()
* Matrix4::Translation(m_localTranslation);
if(m_parentNode && parent_is_bone) {
if (m_parentNode && parent_is_bone) {
m_activePoseMatrix *= m_parentNode->getActivePoseMatrix();
}
}
@@ -739,41 +761,44 @@ const Matrix4 &KRNode::getActivePoseMatrix()
}
const Quaternion KRNode::getWorldRotation() {
const Quaternion KRNode::getWorldRotation()
{
Quaternion world_rotation = Quaternion::Create(m_postRotation) * Quaternion::Create(m_localRotation) * Quaternion::Create(m_preRotation);
if(m_parentNode) {
if (m_parentNode) {
world_rotation = world_rotation * m_parentNode->getWorldRotation();
}
return world_rotation;
}
const Quaternion KRNode::getBindPoseWorldRotation() {
const Quaternion KRNode::getBindPoseWorldRotation()
{
Quaternion world_rotation = Quaternion::Create(m_initialPostRotation) * Quaternion::Create(m_initialLocalRotation) * Quaternion::Create(m_initialPreRotation);
if(dynamic_cast<KRBone *>(m_parentNode)) {
if (dynamic_cast<KRBone*>(m_parentNode)) {
world_rotation = world_rotation * m_parentNode->getBindPoseWorldRotation();
}
return world_rotation;
}
const Quaternion KRNode::getActivePoseWorldRotation() {
const Quaternion KRNode::getActivePoseWorldRotation()
{
Quaternion world_rotation = Quaternion::Create(m_postRotation) * Quaternion::Create(m_localRotation) * Quaternion::Create(m_preRotation);
if(dynamic_cast<KRBone *>(m_parentNode)) {
if (dynamic_cast<KRBone*>(m_parentNode)) {
world_rotation = world_rotation * m_parentNode->getActivePoseWorldRotation();
}
return world_rotation;
}
const Matrix4 &KRNode::getInverseModelMatrix()
const Matrix4& KRNode::getInverseModelMatrix()
{
if(!m_inverseModelMatrixValid) {
if (!m_inverseModelMatrixValid) {
m_inverseModelMatrix = Matrix4::Invert(getModelMatrix());
}
return m_inverseModelMatrix;
}
const Matrix4 &KRNode::getInverseBindPoseMatrix()
const Matrix4& KRNode::getInverseBindPoseMatrix()
{
if(!m_inverseBindPoseMatrixValid ) {
if (!m_inverseBindPoseMatrixValid) {
m_inverseBindPoseMatrix = Matrix4::Invert(getBindPoseMatrix());
m_inverseBindPoseMatrixValid = true;
}
@@ -784,9 +809,9 @@ void KRNode::physicsUpdate(float deltaTime)
{
const long MIN_DISPLAY_FRAMES = 10;
bool visible = m_lastRenderFrame + MIN_DISPLAY_FRAMES >= getContext().getCurrentFrame();
for(std::set<KRBehavior *>::iterator itr=m_behaviors.begin(); itr != m_behaviors.end(); itr++) {
for (std::set<KRBehavior*>::iterator itr = m_behaviors.begin(); itr != m_behaviors.end(); itr++) {
(*itr)->update(deltaTime);
if(visible) {
if (visible) {
(*itr)->visibleUpdate(deltaTime);
}
}
@@ -799,12 +824,12 @@ bool KRNode::hasPhysics()
void KRNode::SetAttribute(node_attribute_type attrib, float v)
{
if(m_animation_mask[attrib]) return;
if (m_animation_mask[attrib]) return;
const float DEGREES_TO_RAD = (float)M_PI / 180.0f;
//printf("%s - ", m_name.c_str());
switch(attrib) {
switch (attrib) {
case KRENGINE_NODE_ATTRIBUTE_TRANSLATE_X:
setLocalTranslation(Vector3::Create(v, m_localTranslation.y, m_localTranslation.z));
break;
@@ -906,14 +931,14 @@ bool KRNode::getAnimationEnabled(node_attribute_type attrib) const
void KRNode::removeFromOctreeNodes()
{
for(std::set<KROctreeNode *>::iterator itr=m_octree_nodes.begin(); itr != m_octree_nodes.end(); itr++) {
KROctreeNode *octree_node = *itr;
for (std::set<KROctreeNode*>::iterator itr = m_octree_nodes.begin(); itr != m_octree_nodes.end(); itr++) {
KROctreeNode* octree_node = *itr;
octree_node->remove(this);
// FINDME, TODO - This should be moved to the KROctree class
while(octree_node) {
while (octree_node) {
octree_node->trim();
if(octree_node->isEmpty()) {
if (octree_node->isEmpty()) {
octree_node = octree_node->getParent();
} else {
octree_node = NULL;
@@ -923,15 +948,15 @@ void KRNode::removeFromOctreeNodes()
m_octree_nodes.clear();
}
void KRNode::addToOctreeNode(KROctreeNode *octree_node)
void KRNode::addToOctreeNode(KROctreeNode* octree_node)
{
m_octree_nodes.insert(octree_node);
}
void KRNode::updateLODVisibility(const KRViewport &viewport)
void KRNode::updateLODVisibility(const KRViewport& viewport)
{
if(m_lod_visible >= LOD_VISIBILITY_PRESTREAM) {
for(std::set<KRNode *>::iterator itr=m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
if (m_lod_visible >= LOD_VISIBILITY_PRESTREAM) {
for (std::set<KRNode*>::iterator itr = m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
(*itr)->updateLODVisibility(viewport);
}
}
@@ -939,16 +964,16 @@ void KRNode::updateLODVisibility(const KRViewport &viewport)
void KRNode::setLODVisibility(KRNode::LodVisibility lod_visibility)
{
if(m_lod_visible != lod_visibility) {
if(m_lod_visible == LOD_VISIBILITY_HIDDEN && lod_visibility >= LOD_VISIBILITY_PRESTREAM) {
if (m_lod_visible != lod_visibility) {
if (m_lod_visible == LOD_VISIBILITY_HIDDEN && lod_visibility >= LOD_VISIBILITY_PRESTREAM) {
getScene().notify_sceneGraphCreate(this);
} else if(m_lod_visible >= LOD_VISIBILITY_PRESTREAM && lod_visibility == LOD_VISIBILITY_HIDDEN) {
} else if (m_lod_visible >= LOD_VISIBILITY_PRESTREAM && lod_visibility == LOD_VISIBILITY_HIDDEN) {
getScene().notify_sceneGraphDelete(this);
}
m_lod_visible = lod_visibility;
for(std::set<KRNode *>::iterator itr=m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
for (std::set<KRNode*>::iterator itr = m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
(*itr)->setLODVisibility(lod_visibility);
}
}
@@ -959,33 +984,33 @@ KRNode::LodVisibility KRNode::getLODVisibility()
return m_lod_visible;
}
const Vector3 KRNode::localToWorld(const Vector3 &local_point)
const Vector3 KRNode::localToWorld(const Vector3& local_point)
{
return Matrix4::Dot(getModelMatrix(), local_point);
}
const Vector3 KRNode::worldToLocal(const Vector3 &world_point)
const Vector3 KRNode::worldToLocal(const Vector3& world_point)
{
return Matrix4::Dot(getInverseModelMatrix(), world_point);
}
void KRNode::addBehavior(KRBehavior *behavior)
void KRNode::addBehavior(KRBehavior* behavior)
{
m_behaviors.insert(behavior);
behavior->__setNode(this);
getScene().notify_sceneGraphModify(this);
}
std::set<KRBehavior *> &KRNode::getBehaviors()
std::set<KRBehavior*>& KRNode::getBehaviors()
{
return m_behaviors;
}
kraken_stream_level KRNode::getStreamLevel(const KRViewport &viewport)
kraken_stream_level KRNode::getStreamLevel(const KRViewport& viewport)
{
kraken_stream_level stream_level = kraken_stream_level::STREAM_LEVEL_IN_HQ;
for(std::set<KRNode *>::iterator itr=m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
for (std::set<KRNode*>::iterator itr = m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
stream_level = KRMIN(stream_level, (*itr)->getStreamLevel(viewport));
}
@@ -995,7 +1020,7 @@ kraken_stream_level KRNode::getStreamLevel(const KRViewport &viewport)
void KRNode::invalidateBounds() const
{
m_boundsValid = false;
if(m_parentNode) {
if (m_parentNode) {
m_parentNode->invalidateBounds();
}
}

View File

@@ -56,14 +56,15 @@ class KRPointLight;
class KRSpotLight;
class KRDirectionalLight;
namespace tinyxml2 {
class XMLNode;
class XMLAttribute;
class XMLNode;
class XMLAttribute;
}
class KRNode : public KRContextObject
{
public:
enum RenderPass {
enum RenderPass
{
RENDER_PASS_FORWARD_OPAQUE,
RENDER_PASS_DEFERRED_GBUFFER,
RENDER_PASS_DEFERRED_LIGHTS,
@@ -77,13 +78,15 @@ public:
RENDER_PASS_PRESTREAM
};
enum LodVisibility {
enum LodVisibility
{
LOD_VISIBILITY_HIDDEN,
LOD_VISIBILITY_PRESTREAM,
LOD_VISIBILITY_VISIBLE
};
class RenderInfo {
class RenderInfo
{
public:
RenderInfo(VkCommandBuffer& cb)
: commandBuffer(cb)
@@ -106,55 +109,55 @@ public:
static void InitNodeInfo(KrNodeInfo* nodeInfo);
KRNode(KRScene &scene, std::string name);
KRNode(KRScene& scene, std::string name);
virtual ~KRNode();
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual tinyxml2::XMLElement* saveXML(tinyxml2::XMLNode* parent);
static KRNode *LoadXML(KRScene &scene, tinyxml2::XMLElement *e);
virtual void loadXML(tinyxml2::XMLElement *e);
static KRNode* LoadXML(KRScene& scene, tinyxml2::XMLElement* e);
virtual void loadXML(tinyxml2::XMLElement* e);
virtual std::string getElementName();
const std::string &getName() const;
const std::string& getName() const;
void addChild(KRNode *child);
const std::set<KRNode *> &getChildren();
KRNode *getParent();
void addChild(KRNode* child);
const std::set<KRNode*>& getChildren();
KRNode* getParent();
void setLocalTranslation(const Vector3 &v, bool set_original = false);
void setLocalScale(const Vector3 &v, bool set_original = false);
void setLocalRotation(const Vector3 &v, bool set_original = false);
void setLocalTranslation(const Vector3& v, bool set_original = false);
void setLocalScale(const Vector3& v, bool set_original = false);
void setLocalRotation(const Vector3& v, bool set_original = false);
void setRotationOffset(const Vector3 &v, bool set_original = false);
void setScalingOffset(const Vector3 &v, bool set_original = false);
void setRotationPivot(const Vector3 &v, bool set_original = false);
void setScalingPivot(const Vector3 &v, bool set_original = false);
void setPreRotation(const Vector3 &v, bool set_original = false);
void setPostRotation(const Vector3 &v, bool set_original = false);
void setRotationOffset(const Vector3& v, bool set_original = false);
void setScalingOffset(const Vector3& v, bool set_original = false);
void setRotationPivot(const Vector3& v, bool set_original = false);
void setScalingPivot(const Vector3& v, bool set_original = false);
void setPreRotation(const Vector3& v, bool set_original = false);
void setPostRotation(const Vector3& v, bool set_original = false);
const Vector3 &getRotationOffset();
const Vector3 &getScalingOffset();
const Vector3 &getRotationPivot();
const Vector3 &getScalingPivot();
const Vector3 &getPreRotation();
const Vector3 &getPostRotation();
const Vector3& getRotationOffset();
const Vector3& getScalingOffset();
const Vector3& getRotationPivot();
const Vector3& getScalingPivot();
const Vector3& getPreRotation();
const Vector3& getPostRotation();
const Vector3 &getInitialRotationOffset();
const Vector3 &getInitialScalingOffset();
const Vector3 &getInitialRotationPivot();
const Vector3 &getInitialScalingPivot();
const Vector3 &getInitialPreRotation();
const Vector3 &getInitialPostRotation();
const Vector3& getInitialRotationOffset();
const Vector3& getInitialScalingOffset();
const Vector3& getInitialRotationPivot();
const Vector3& getInitialScalingPivot();
const Vector3& getInitialPreRotation();
const Vector3& getInitialPostRotation();
const Vector3 &getLocalTranslation();
const Vector3 &getLocalScale();
const Vector3 &getLocalRotation();
const Vector3& getLocalTranslation();
const Vector3& getLocalScale();
const Vector3& getLocalRotation();
const Vector3 &getInitialLocalTranslation();
const Vector3 &getInitialLocalScale();
const Vector3 &getInitialLocalRotation();
const Vector3& getInitialLocalTranslation();
const Vector3& getInitialLocalScale();
const Vector3& getInitialLocalRotation();
const Vector3 getWorldTranslation();
const Vector3 getWorldScale();
@@ -163,22 +166,23 @@ public:
const Quaternion getBindPoseWorldRotation();
const Quaternion getActivePoseWorldRotation();
const Vector3 localToWorld(const Vector3 &local_point);
const Vector3 worldToLocal(const Vector3 &world_point);
const Vector3 localToWorld(const Vector3& local_point);
const Vector3 worldToLocal(const Vector3& world_point);
void setWorldTranslation(const Vector3 &v);
void setWorldScale(const Vector3 &v);
void setWorldRotation(const Vector3 &v);
void setWorldTranslation(const Vector3& v);
void setWorldScale(const Vector3& v);
void setWorldRotation(const Vector3& v);
virtual AABB getBounds();
void invalidateBounds() const;
const Matrix4 &getModelMatrix();
const Matrix4 &getInverseModelMatrix();
const Matrix4 &getBindPoseMatrix();
const Matrix4 &getActivePoseMatrix();
const Matrix4 &getInverseBindPoseMatrix();
const Matrix4& getModelMatrix();
const Matrix4& getInverseModelMatrix();
const Matrix4& getBindPoseMatrix();
const Matrix4& getActivePoseMatrix();
const Matrix4& getInverseBindPoseMatrix();
enum node_attribute_type {
enum node_attribute_type
{
KRENGINE_NODE_ATTRIBUTE_NONE,
KRENGINE_NODE_ATTRIBUTE_TRANSLATE_X,
KRENGINE_NODE_ATTRIBUTE_TRANSLATE_Y,
@@ -212,14 +216,14 @@ public:
void SetAttribute(node_attribute_type attrib, float v);
KRScene &getScene();
KRScene& getScene();
virtual void render(const RenderInfo& ri);
virtual void physicsUpdate(float deltaTime);
virtual bool hasPhysics();
virtual void updateLODVisibility(const KRViewport &viewport);
virtual void updateLODVisibility(const KRViewport& viewport);
LodVisibility getLODVisibility();
void setScaleCompensation(bool scale_compensation);
@@ -228,7 +232,7 @@ public:
bool getAnimationEnabled(node_attribute_type attrib) const;
virtual kraken_stream_level getStreamLevel(const KRViewport &viewport);
virtual kraken_stream_level getStreamLevel(const KRViewport& viewport);
virtual void setLODVisibility(LodVisibility lod_visibility);
@@ -257,8 +261,8 @@ protected:
LodVisibility m_lod_visible;
KRNode *m_parentNode;
std::set<KRNode *> m_childNodes;
KRNode* m_parentNode;
std::set<KRNode*> m_childNodes;
bool m_animation_mask[KRENGINE_NODE_ATTRIBUTE_COUNT];
@@ -284,40 +288,40 @@ private:
KRScene *m_pScene;
KRScene* m_pScene;
std::set<KROctreeNode *> m_octree_nodes;
std::set<KROctreeNode*> m_octree_nodes;
bool m_scale_compensation;
std::set<KRBehavior *> m_behaviors;
std::set<KRBehavior*> m_behaviors;
public:
void addBehavior(KRBehavior *behavior);
std::set<KRBehavior *> &getBehaviors();
template <class T> T *getBehavior()
void addBehavior(KRBehavior* behavior);
std::set<KRBehavior*>& getBehaviors();
template <class T> T* getBehavior()
{
for(std::set<KRBehavior *>::iterator itr=m_behaviors.begin(); itr != m_behaviors.end(); itr++) {
T *behavior = dynamic_cast<T *>(*itr);
if(behavior) {
for (std::set<KRBehavior*>::iterator itr = m_behaviors.begin(); itr != m_behaviors.end(); itr++) {
T* behavior = dynamic_cast<T*>(*itr);
if (behavior) {
return behavior;
}
}
return NULL;
}
void removeFromOctreeNodes();
void addToOctreeNode(KROctreeNode *octree_node);
void childDeleted(KRNode *child_node);
void addToOctreeNode(KROctreeNode* octree_node);
void childDeleted(KRNode* child_node);
template <class T> T *find()
template <class T> T* find()
{
T *match = dynamic_cast<T *>(this);
if(match) {
T* match = dynamic_cast<T*>(this);
if (match) {
return match;
}
for(std::set<KRNode *>::const_iterator itr=m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
for (std::set<KRNode*>::const_iterator itr = m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
match = (*itr)->find<T>();
if(match) {
if (match) {
return match;
}
}
@@ -325,18 +329,18 @@ public:
return NULL;
}
template <class T> T *find(const std::string &name)
template <class T> T* find(const std::string& name)
{
T *match = dynamic_cast<T *>(this);
if(match) {
if(name.compare(match->getName()) == 0) {
T* match = dynamic_cast<T*>(this);
if (match) {
if (name.compare(match->getName()) == 0) {
return match;
}
}
for(std::set<KRNode *>::const_iterator itr=m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
for (std::set<KRNode*>::const_iterator itr = m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
match = (*itr)->find<T>(name);
if(match) {
if (match) {
return match;
}
}

View File

@@ -41,33 +41,33 @@ KROctree::KROctree()
KROctree::~KROctree()
{
if(m_pRootNode) {
if (m_pRootNode) {
delete m_pRootNode;
}
}
void KROctree::add(KRNode *pNode)
void KROctree::add(KRNode* pNode)
{
AABB nodeBounds = pNode->getBounds();
if(nodeBounds == AABB::Zero()) {
if (nodeBounds == AABB::Zero()) {
// This item is not visible, don't add it to the octree or outer scene nodes
} else if(nodeBounds == AABB::Infinite()) {
} else if (nodeBounds == AABB::Infinite()) {
// This item is infinitely large; we track it separately
m_outerSceneNodes.insert(pNode);
} else {
if(m_pRootNode == NULL) {
if (m_pRootNode == NULL) {
// First item inserted, create a node large enough to fit it
m_pRootNode = new KROctreeNode(NULL, nodeBounds);
m_pRootNode->add(pNode);
} else {
// Keep encapsulating the root node until the new root contains the inserted node
bool bInsideRoot = false;
while(!bInsideRoot) {
while (!bInsideRoot) {
AABB rootBounds = m_pRootNode->getBounds();
Vector3 rootSize = rootBounds.size();
if(nodeBounds.min.x < rootBounds.min.x || nodeBounds.min.y < rootBounds.min.y || nodeBounds.min.z < rootBounds.min.z) {
if (nodeBounds.min.x < rootBounds.min.x || nodeBounds.min.y < rootBounds.min.y || nodeBounds.min.z < rootBounds.min.z) {
m_pRootNode = new KROctreeNode(NULL, AABB::Create(rootBounds.min - rootSize, rootBounds.max), 7, m_pRootNode);
} else if(nodeBounds.max.x > rootBounds.max.x || nodeBounds.max.y > rootBounds.max.y || nodeBounds.max.z > rootBounds.max.z) {
} else if (nodeBounds.max.x > rootBounds.max.x || nodeBounds.max.y > rootBounds.max.y || nodeBounds.max.z > rootBounds.max.z) {
m_pRootNode = new KROctreeNode(NULL, AABB::Create(rootBounds.min, rootBounds.max + rootSize), 0, m_pRootNode);
} else {
bInsideRoot = true;
@@ -78,10 +78,10 @@ void KROctree::add(KRNode *pNode)
}
}
void KROctree::remove(KRNode *pNode)
void KROctree::remove(KRNode* pNode)
{
if(!m_outerSceneNodes.erase(pNode)) {
if(m_pRootNode) {
if (!m_outerSceneNodes.erase(pNode)) {
if (m_pRootNode) {
pNode->removeFromOctreeNodes();
}
}
@@ -89,7 +89,7 @@ void KROctree::remove(KRNode *pNode)
shrink();
}
void KROctree::update(KRNode *pNode)
void KROctree::update(KRNode* pNode)
{
// TODO: This may be more efficient as an incremental operation rather than removing and re-adding the node
remove(pNode);
@@ -99,80 +99,80 @@ void KROctree::update(KRNode *pNode)
void KROctree::shrink()
{
if(m_pRootNode) {
while(m_pRootNode->canShrinkRoot()) {
KROctreeNode *newRoot = m_pRootNode->stripChild();
if (m_pRootNode) {
while (m_pRootNode->canShrinkRoot()) {
KROctreeNode* newRoot = m_pRootNode->stripChild();
delete m_pRootNode;
m_pRootNode = newRoot;
if(m_pRootNode == NULL) return;
if (m_pRootNode == NULL) return;
}
}
}
KROctreeNode *KROctree::getRootNode()
KROctreeNode* KROctree::getRootNode()
{
return m_pRootNode;
}
std::set<KRNode *> &KROctree::getOuterSceneNodes()
std::set<KRNode*>& KROctree::getOuterSceneNodes()
{
return m_outerSceneNodes;
}
bool KROctree::lineCast(const Vector3 &v0, const Vector3 &v1, HitInfo &hitinfo, unsigned int layer_mask)
bool KROctree::lineCast(const Vector3& v0, const Vector3& v1, HitInfo& hitinfo, unsigned int layer_mask)
{
bool hit_found = false;
std::vector<KRCollider *> outer_colliders;
std::vector<KRCollider*> outer_colliders;
for(std::set<KRNode *>::iterator outer_nodes_itr=m_outerSceneNodes.begin(); outer_nodes_itr != m_outerSceneNodes.end(); outer_nodes_itr++) {
KRCollider *collider = dynamic_cast<KRCollider *>(*outer_nodes_itr);
if(collider) {
for (std::set<KRNode*>::iterator outer_nodes_itr = m_outerSceneNodes.begin(); outer_nodes_itr != m_outerSceneNodes.end(); outer_nodes_itr++) {
KRCollider* collider = dynamic_cast<KRCollider*>(*outer_nodes_itr);
if (collider) {
outer_colliders.push_back(collider);
}
}
for(std::vector<KRCollider *>::iterator itr=outer_colliders.begin(); itr != outer_colliders.end(); itr++) {
if((*itr)->lineCast(v0, v1, hitinfo, layer_mask)) hit_found = true;
for (std::vector<KRCollider*>::iterator itr = outer_colliders.begin(); itr != outer_colliders.end(); itr++) {
if ((*itr)->lineCast(v0, v1, hitinfo, layer_mask)) hit_found = true;
}
if(m_pRootNode) {
if(m_pRootNode->lineCast(v0, v1, hitinfo, layer_mask)) hit_found = true;
if (m_pRootNode) {
if (m_pRootNode->lineCast(v0, v1, hitinfo, layer_mask)) hit_found = true;
}
return hit_found;
}
bool KROctree::rayCast(const Vector3 &v0, const Vector3 &dir, HitInfo &hitinfo, unsigned int layer_mask)
bool KROctree::rayCast(const Vector3& v0, const Vector3& dir, HitInfo& hitinfo, unsigned int layer_mask)
{
bool hit_found = false;
for(std::set<KRNode *>::iterator outer_nodes_itr=m_outerSceneNodes.begin(); outer_nodes_itr != m_outerSceneNodes.end(); outer_nodes_itr++) {
KRCollider *collider = dynamic_cast<KRCollider *>(*outer_nodes_itr);
if(collider) {
if(collider->rayCast(v0, dir, hitinfo, layer_mask)) hit_found = true;
for (std::set<KRNode*>::iterator outer_nodes_itr = m_outerSceneNodes.begin(); outer_nodes_itr != m_outerSceneNodes.end(); outer_nodes_itr++) {
KRCollider* collider = dynamic_cast<KRCollider*>(*outer_nodes_itr);
if (collider) {
if (collider->rayCast(v0, dir, hitinfo, layer_mask)) hit_found = true;
}
}
if(m_pRootNode) {
if(m_pRootNode->rayCast(v0, dir, hitinfo, layer_mask)) hit_found = true;
if (m_pRootNode) {
if (m_pRootNode->rayCast(v0, dir, hitinfo, layer_mask)) hit_found = true;
}
return hit_found;
}
bool KROctree::sphereCast(const Vector3 &v0, const Vector3 &v1, float radius, HitInfo &hitinfo, unsigned int layer_mask)
bool KROctree::sphereCast(const Vector3& v0, const Vector3& v1, float radius, HitInfo& hitinfo, unsigned int layer_mask)
{
bool hit_found = false;
std::vector<KRCollider *> outer_colliders;
std::vector<KRCollider*> outer_colliders;
for(std::set<KRNode *>::iterator outer_nodes_itr=m_outerSceneNodes.begin(); outer_nodes_itr != m_outerSceneNodes.end(); outer_nodes_itr++) {
KRCollider *collider = dynamic_cast<KRCollider *>(*outer_nodes_itr);
if(collider) {
for (std::set<KRNode*>::iterator outer_nodes_itr = m_outerSceneNodes.begin(); outer_nodes_itr != m_outerSceneNodes.end(); outer_nodes_itr++) {
KRCollider* collider = dynamic_cast<KRCollider*>(*outer_nodes_itr);
if (collider) {
outer_colliders.push_back(collider);
}
}
for(std::vector<KRCollider *>::iterator itr=outer_colliders.begin(); itr != outer_colliders.end(); itr++) {
if((*itr)->sphereCast(v0, v1, radius, hitinfo, layer_mask)) hit_found = true;
for (std::vector<KRCollider*>::iterator itr = outer_colliders.begin(); itr != outer_colliders.end(); itr++) {
if ((*itr)->sphereCast(v0, v1, radius, hitinfo, layer_mask)) hit_found = true;
}
if(m_pRootNode) {
if(m_pRootNode->sphereCast(v0, v1, radius, hitinfo, layer_mask)) hit_found = true;
if (m_pRootNode) {
if (m_pRootNode->sphereCast(v0, v1, radius, hitinfo, layer_mask)) hit_found = true;
}
return hit_found;
}

View File

@@ -36,25 +36,26 @@
class KRNode;
class KROctree {
class KROctree
{
public:
KROctree();
~KROctree();
void add(KRNode *pNode);
void remove(KRNode *pNode);
void update(KRNode *pNode);
void add(KRNode* pNode);
void remove(KRNode* pNode);
void update(KRNode* pNode);
KROctreeNode *getRootNode();
std::set<KRNode *> &getOuterSceneNodes();
KROctreeNode* getRootNode();
std::set<KRNode*>& getOuterSceneNodes();
bool lineCast(const Vector3 &v0, const Vector3 &v1, HitInfo &hitinfo, unsigned int layer_mask);
bool rayCast(const Vector3 &v0, const Vector3 &dir, HitInfo &hitinfo, unsigned int layer_mask);
bool sphereCast(const Vector3 &v0, const Vector3 &v1, float radius, HitInfo &hitinfo, unsigned int layer_mask);
bool lineCast(const Vector3& v0, const Vector3& v1, HitInfo& hitinfo, unsigned int layer_mask);
bool rayCast(const Vector3& v0, const Vector3& dir, HitInfo& hitinfo, unsigned int layer_mask);
bool sphereCast(const Vector3& v0, const Vector3& v1, float radius, HitInfo& hitinfo, unsigned int layer_mask);
private:
KROctreeNode *m_pRootNode;
std::set<KRNode *> m_outerSceneNodes;
KROctreeNode* m_pRootNode;
std::set<KRNode*> m_outerSceneNodes;
void shrink();
};

View File

@@ -33,23 +33,27 @@
#include "KRNode.h"
#include "KRCollider.h"
KROctreeNode::KROctreeNode(KROctreeNode *parent, const AABB &bounds) : m_bounds(bounds)
KROctreeNode::KROctreeNode(KROctreeNode* parent, const AABB& bounds) : m_bounds(bounds)
{
m_parent = parent;
for(int i=0; i<8; i++) m_children[i] = NULL;
for (int i = 0; i < 8; i++) {
m_children[i] = NULL;
}
m_occlusionQuery = 0;
m_occlusionTested = false;
m_activeQuery = false;
}
KROctreeNode::KROctreeNode(KROctreeNode *parent, const AABB &bounds, int iChild, KROctreeNode *pChild) : m_bounds(bounds)
KROctreeNode::KROctreeNode(KROctreeNode* parent, const AABB& bounds, int iChild, KROctreeNode* pChild) : m_bounds(bounds)
{
// This constructor is used when expanding the octree and replacing the root node with a new root that encapsulates it
m_parent = parent;
for(int i=0; i<8; i++) m_children[i] = NULL;
for (int i = 0; i < 8; i++) {
m_children[i] = NULL;
}
m_children[iChild] = pChild;
pChild->m_parent = this;
@@ -60,13 +64,13 @@ KROctreeNode::KROctreeNode(KROctreeNode *parent, const AABB &bounds, int iChild,
KROctreeNode::~KROctreeNode()
{
for(int i=0; i<8; i++) {
if(m_children[i] != NULL) {
for (int i = 0; i < 8; i++) {
if (m_children[i] != NULL) {
delete m_children[i];
}
}
if(m_occlusionTested) {
if (m_occlusionTested) {
GLDEBUG(glDeleteQueriesEXT(1, &m_occlusionQuery));
}
}
@@ -74,7 +78,7 @@ KROctreeNode::~KROctreeNode()
void KROctreeNode::beginOcclusionQuery()
{
if(!m_occlusionTested){
if (!m_occlusionTested) {
GLDEBUG(glGenQueriesEXT(1, &m_occlusionQuery));
#if TARGET_OS_IPHONE || defined(ANDROID)
GLDEBUG(glBeginQueryEXT(GL_ANY_SAMPLES_PASSED_EXT, m_occlusionQuery));
@@ -88,7 +92,7 @@ void KROctreeNode::beginOcclusionQuery()
void KROctreeNode::endOcclusionQuery()
{
if(m_activeQuery) {
if (m_activeQuery) {
// Only end a query if we started one
#if TARGET_OS_IPHONE || defined(ANDROID)
GLDEBUG(glEndQueryEXT(GL_ANY_SAMPLES_PASSED_EXT));
@@ -104,14 +108,14 @@ AABB KROctreeNode::getBounds()
return m_bounds;
}
void KROctreeNode::add(KRNode *pNode)
void KROctreeNode::add(KRNode* pNode)
{
int iChild = getChildIndex(pNode);
if(iChild == -1) {
if (iChild == -1) {
m_sceneNodes.insert(pNode);
pNode->addToOctreeNode(this);
} else {
if(m_children[iChild] == NULL) {
if (m_children[iChild] == NULL) {
m_children[iChild] = new KROctreeNode(this, getChildBounds(iChild));
}
m_children[iChild]->add(pNode);
@@ -134,10 +138,10 @@ AABB KROctreeNode::getChildBounds(int iChild)
);
}
int KROctreeNode::getChildIndex(KRNode *pNode)
int KROctreeNode::getChildIndex(KRNode* pNode)
{
for(int iChild=0; iChild < 8; iChild++) {
if(getChildBounds(iChild).contains(pNode->getBounds())) {
for (int iChild = 0; iChild < 8; iChild++) {
if (getChildBounds(iChild).contains(pNode->getBounds())) {
return iChild;
}
}
@@ -146,9 +150,9 @@ int KROctreeNode::getChildIndex(KRNode *pNode)
void KROctreeNode::trim()
{
for(int iChild = 0; iChild < 8; iChild++) {
if(m_children[iChild]) {
if(m_children[iChild]->isEmpty()) {
for (int iChild = 0; iChild < 8; iChild++) {
if (m_children[iChild]) {
if (m_children[iChild]->isEmpty()) {
delete m_children[iChild];
m_children[iChild] = NULL;
}
@@ -156,20 +160,20 @@ void KROctreeNode::trim()
}
}
void KROctreeNode::remove(KRNode *pNode)
void KROctreeNode::remove(KRNode* pNode)
{
m_sceneNodes.erase(pNode);
}
void KROctreeNode::update(KRNode *pNode)
void KROctreeNode::update(KRNode* pNode)
{
}
bool KROctreeNode::isEmpty() const
{
for(int i=0; i<8; i++) {
if(m_children[i]) {
for (int i = 0; i < 8; i++) {
if (m_children[i]) {
return false;
}
}
@@ -179,21 +183,21 @@ bool KROctreeNode::isEmpty() const
bool KROctreeNode::canShrinkRoot() const
{
int cChildren = 0;
for(int i=0; i<8; i++) {
if(m_children[i]) {
for (int i = 0; i < 8; i++) {
if (m_children[i]) {
cChildren++;
}
}
return cChildren <= 1 && m_sceneNodes.empty();
}
KROctreeNode *KROctreeNode::stripChild()
KROctreeNode* KROctreeNode::stripChild()
{
// Return the first found child and update its reference to NULL so that the destructor will not free it. This is used for shrinking the octree
// NOTE: The caller of this function will be responsible for freeing the child object. It is also possible to return a NULL
for(int i=0; i<8; i++) {
if(m_children[i]) {
KROctreeNode *child = m_children[i];
for (int i = 0; i < 8; i++) {
if (m_children[i]) {
KROctreeNode* child = m_children[i];
child->m_parent = NULL;
m_children[i] = NULL;
return child;
@@ -203,40 +207,40 @@ KROctreeNode *KROctreeNode::stripChild()
}
KROctreeNode *KROctreeNode::getParent()
KROctreeNode* KROctreeNode::getParent()
{
return m_parent;
}
KROctreeNode **KROctreeNode::getChildren()
KROctreeNode** KROctreeNode::getChildren()
{
return m_children;
}
std::set<KRNode *> &KROctreeNode::getSceneNodes()
std::set<KRNode*>& KROctreeNode::getSceneNodes()
{
return m_sceneNodes;
}
bool KROctreeNode::lineCast(const Vector3 &v0, const Vector3 &v1, HitInfo &hitinfo, unsigned int layer_mask)
bool KROctreeNode::lineCast(const Vector3& v0, const Vector3& v1, HitInfo& hitinfo, unsigned int layer_mask)
{
bool hit_found = false;
if(hitinfo.didHit() && v1 != hitinfo.getPosition()) {
if (hitinfo.didHit() && v1 != hitinfo.getPosition()) {
// Optimization: If we already have a hit, only search for hits that are closer
hit_found = lineCast(v0, hitinfo.getPosition(), hitinfo, layer_mask);
} else {
if(getBounds().intersectsLine(v0, v1)) {
for(std::set<KRNode *>::iterator nodes_itr=m_sceneNodes.begin(); nodes_itr != m_sceneNodes.end(); nodes_itr++) {
KRCollider *collider = dynamic_cast<KRCollider *>(*nodes_itr);
if(collider) {
if(collider->lineCast(v0, v1, hitinfo, layer_mask)) hit_found = true;
if (getBounds().intersectsLine(v0, v1)) {
for (std::set<KRNode*>::iterator nodes_itr = m_sceneNodes.begin(); nodes_itr != m_sceneNodes.end(); nodes_itr++) {
KRCollider* collider = dynamic_cast<KRCollider*>(*nodes_itr);
if (collider) {
if (collider->lineCast(v0, v1, hitinfo, layer_mask)) hit_found = true;
}
}
for(int i=0; i<8; i++) {
if(m_children[i]) {
if(m_children[i]->lineCast(v0, v1, hitinfo, layer_mask)) {
for (int i = 0; i < 8; i++) {
if (m_children[i]) {
if (m_children[i]->lineCast(v0, v1, hitinfo, layer_mask)) {
hit_found = true;
}
}
@@ -247,24 +251,24 @@ bool KROctreeNode::lineCast(const Vector3 &v0, const Vector3 &v1, HitInfo &hitin
return hit_found;
}
bool KROctreeNode::rayCast(const Vector3 &v0, const Vector3 &dir, HitInfo &hitinfo, unsigned int layer_mask)
bool KROctreeNode::rayCast(const Vector3& v0, const Vector3& dir, HitInfo& hitinfo, unsigned int layer_mask)
{
bool hit_found = false;
if(hitinfo.didHit()) {
if (hitinfo.didHit()) {
// Optimization: If we already have a hit, only search for hits that are closer
hit_found = lineCast(v0, hitinfo.getPosition(), hitinfo, layer_mask); // Note: This is purposefully lineCast as opposed to RayCast
} else {
if(getBounds().intersectsRay(v0, dir)) {
for(std::set<KRNode *>::iterator nodes_itr=m_sceneNodes.begin(); nodes_itr != m_sceneNodes.end(); nodes_itr++) {
KRCollider *collider = dynamic_cast<KRCollider *>(*nodes_itr);
if(collider) {
if(collider->rayCast(v0, dir, hitinfo, layer_mask)) hit_found = true;
if (getBounds().intersectsRay(v0, dir)) {
for (std::set<KRNode*>::iterator nodes_itr = m_sceneNodes.begin(); nodes_itr != m_sceneNodes.end(); nodes_itr++) {
KRCollider* collider = dynamic_cast<KRCollider*>(*nodes_itr);
if (collider) {
if (collider->rayCast(v0, dir, hitinfo, layer_mask)) hit_found = true;
}
}
for(int i=0; i<8; i++) {
if(m_children[i]) {
if(m_children[i]->rayCast(v0, dir, hitinfo, layer_mask)) {
for (int i = 0; i < 8; i++) {
if (m_children[i]) {
if (m_children[i]->rayCast(v0, dir, hitinfo, layer_mask)) {
hit_found = true;
}
}
@@ -275,7 +279,7 @@ bool KROctreeNode::rayCast(const Vector3 &v0, const Vector3 &dir, HitInfo &hitin
return hit_found;
}
bool KROctreeNode::sphereCast(const Vector3 &v0, const Vector3 &v1, float radius, HitInfo &hitinfo, unsigned int layer_mask)
bool KROctreeNode::sphereCast(const Vector3& v0, const Vector3& v1, float radius, HitInfo& hitinfo, unsigned int layer_mask)
{
bool hit_found = false;
/*
@@ -289,18 +293,18 @@ bool KROctreeNode::sphereCast(const Vector3 &v0, const Vector3 &v1, float radius
AABB swept_bounds = AABB::Create(Vector3::Create(KRMIN(v0.x, v1.x) - radius, KRMIN(v0.y, v1.y) - radius, KRMIN(v0.z, v1.z) - radius), Vector3::Create(KRMAX(v0.x, v1.x) + radius, KRMAX(v0.y, v1.y) + radius, KRMAX(v0.z, v1.z) + radius));
// FINDME, TODO - Investigate AABB - swept sphere intersections or OBB - AABB intersections: "if(getBounds().intersectsSweptSphere(v0, v1, radius)) {"
if(getBounds().intersects(swept_bounds)) {
if (getBounds().intersects(swept_bounds)) {
for(std::set<KRNode *>::iterator nodes_itr=m_sceneNodes.begin(); nodes_itr != m_sceneNodes.end(); nodes_itr++) {
KRCollider *collider = dynamic_cast<KRCollider *>(*nodes_itr);
if(collider) {
if(collider->sphereCast(v0, v1, radius, hitinfo, layer_mask)) hit_found = true;
for (std::set<KRNode*>::iterator nodes_itr = m_sceneNodes.begin(); nodes_itr != m_sceneNodes.end(); nodes_itr++) {
KRCollider* collider = dynamic_cast<KRCollider*>(*nodes_itr);
if (collider) {
if (collider->sphereCast(v0, v1, radius, hitinfo, layer_mask)) hit_found = true;
}
}
for(int i=0; i<8; i++) {
if(m_children[i]) {
if(m_children[i]->sphereCast(v0, v1, radius, hitinfo, layer_mask)) {
for (int i = 0; i < 8; i++) {
if (m_children[i]) {
if (m_children[i]->sphereCast(v0, v1, radius, hitinfo, layer_mask)) {
hit_found = true;
}
}

View File

@@ -36,30 +36,31 @@
class KRNode;
class KROctreeNode {
class KROctreeNode
{
public:
KROctreeNode(KROctreeNode *parent, const AABB &bounds);
KROctreeNode(KROctreeNode *parent, const AABB &bounds, int iChild, KROctreeNode *pChild);
KROctreeNode(KROctreeNode* parent, const AABB& bounds);
KROctreeNode(KROctreeNode* parent, const AABB& bounds, int iChild, KROctreeNode* pChild);
~KROctreeNode();
KROctreeNode **getChildren();
std::set<KRNode *> &getSceneNodes();
KROctreeNode** getChildren();
std::set<KRNode*>& getSceneNodes();
void add(KRNode *pNode);
void remove(KRNode *pNode);
void update(KRNode *pNode);
void add(KRNode* pNode);
void remove(KRNode* pNode);
void update(KRNode* pNode);
AABB getBounds();
KROctreeNode *getParent();
void setChildNode(int iChild, KROctreeNode *pChild);
int getChildIndex(KRNode *pNode);
KROctreeNode* getParent();
void setChildNode(int iChild, KROctreeNode* pChild);
int getChildIndex(KRNode* pNode);
AABB getChildBounds(int iChild);
void trim();
bool isEmpty() const;
bool canShrinkRoot() const;
KROctreeNode *stripChild();
KROctreeNode* stripChild();
void beginOcclusionQuery();
void endOcclusionQuery();
@@ -69,16 +70,16 @@ public:
bool m_occlusionTested;
bool m_activeQuery;
bool lineCast(const Vector3 &v0, const Vector3 &v1, HitInfo &hitinfo, unsigned int layer_mask);
bool rayCast(const Vector3 &v0, const Vector3 &dir, HitInfo &hitinfo, unsigned int layer_mask);
bool sphereCast(const Vector3 &v0, const Vector3 &v1, float radius, HitInfo &hitinfo, unsigned int layer_mask);
bool lineCast(const Vector3& v0, const Vector3& v1, HitInfo& hitinfo, unsigned int layer_mask);
bool rayCast(const Vector3& v0, const Vector3& dir, HitInfo& hitinfo, unsigned int layer_mask);
bool sphereCast(const Vector3& v0, const Vector3& v1, float radius, HitInfo& hitinfo, unsigned int layer_mask);
private:
AABB m_bounds;
KROctreeNode *m_parent;
KROctreeNode *m_children[8];
KROctreeNode* m_parent;
KROctreeNode* m_children[8];
std::set<KRNode *>m_sceneNodes;
std::set<KRNode*>m_sceneNodes;
};

View File

@@ -30,7 +30,7 @@
//
#include "KRParticleSystem.h"
KRParticleSystem::KRParticleSystem(KRScene &scene, std::string name) : KRNode(scene, name)
KRParticleSystem::KRParticleSystem(KRScene& scene, std::string name) : KRNode(scene, name)
{
}
@@ -40,14 +40,14 @@ KRParticleSystem::~KRParticleSystem()
}
void KRParticleSystem::loadXML(tinyxml2::XMLElement *e)
void KRParticleSystem::loadXML(tinyxml2::XMLElement* e)
{
}
tinyxml2::XMLElement *KRParticleSystem::saveXML( tinyxml2::XMLNode *parent)
tinyxml2::XMLElement* KRParticleSystem::saveXML(tinyxml2::XMLNode* parent)
{
tinyxml2::XMLElement *e = KRNode::saveXML(parent);
tinyxml2::XMLElement* e = KRNode::saveXML(parent);
return e;
}

View File

@@ -33,20 +33,21 @@
#include "KRNode.h"
class KRParticleSystem : public KRNode {
class KRParticleSystem : public KRNode
{
public:
virtual ~KRParticleSystem();
virtual std::string getElementName() = 0;
virtual void loadXML(tinyxml2::XMLElement *e);
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual void loadXML(tinyxml2::XMLElement* e);
virtual tinyxml2::XMLElement* saveXML(tinyxml2::XMLNode* parent);
virtual AABB getBounds() = 0;
virtual void render(RenderInfo& ri) = 0;
protected:
KRParticleSystem(KRScene &scene, std::string name);
KRParticleSystem(KRScene& scene, std::string name);
private:
};

View File

@@ -35,7 +35,7 @@
#include "KRTexture.h"
#include "KRContext.h"
KRParticleSystemNewtonian::KRParticleSystemNewtonian(KRScene &scene, std::string name) : KRParticleSystem(scene, name)
KRParticleSystemNewtonian::KRParticleSystemNewtonian(KRScene& scene, std::string name) : KRParticleSystem(scene, name)
{
m_particlesAbsoluteTime = 0.0f;
}
@@ -50,14 +50,14 @@ std::string KRParticleSystemNewtonian::getElementName()
return "newtonian_particles";
}
void KRParticleSystemNewtonian::loadXML(tinyxml2::XMLElement *e)
void KRParticleSystemNewtonian::loadXML(tinyxml2::XMLElement* e)
{
KRParticleSystem::loadXML(e);
}
tinyxml2::XMLElement *KRParticleSystemNewtonian::saveXML( tinyxml2::XMLNode *parent)
tinyxml2::XMLElement* KRParticleSystemNewtonian::saveXML(tinyxml2::XMLNode* parent)
{
tinyxml2::XMLElement *e = KRParticleSystem::saveXML(parent);
tinyxml2::XMLElement* e = KRParticleSystem::saveXML(parent);
return e;
}
@@ -78,15 +78,16 @@ bool KRParticleSystemNewtonian::hasPhysics()
return true;
}
void KRParticleSystemNewtonian::render(RenderInfo& ri) {
void KRParticleSystemNewtonian::render(RenderInfo& ri)
{
if(m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
if (m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
KRNode::render(ri);
if(ri.renderPass == KRNode::RENDER_PASS_ADDITIVE_PARTICLES) {
if(ri.viewport.visible(getBounds())) {
KRTexture *pParticleTexture = m_pContext->getTextureManager()->getTexture("flare");
if (ri.renderPass == KRNode::RENDER_PASS_ADDITIVE_PARTICLES) {
if (ri.viewport.visible(getBounds())) {
KRTexture* pParticleTexture = m_pContext->getTextureManager()->getTexture("flare");
m_pContext->getTextureManager()->selectTexture(0, pParticleTexture, 0.0f, KRTexture::TEXTURE_USAGE_PARTICLE);
int particle_count = 10000;
@@ -103,7 +104,7 @@ void KRParticleSystemNewtonian::render(RenderInfo& ri) {
info.vertexAttributes = (1 << KRMesh::KRENGINE_ATTRIB_VERTEX) | (1 << KRMesh::KRENGINE_ATTRIB_TEXUVA);
info.modelFormat = ModelFormat::KRENGINE_MODEL_FORMAT_TRIANGLES;
KRPipeline *pParticleShader = m_pContext->getPipelineManager()->getPipeline(*ri.surface, info);
KRPipeline* pParticleShader = m_pContext->getPipelineManager()->getPipeline(*ri.surface, info);
pParticleShader->setUniform(KRPipeline::Uniform::flare_size, 1.0f);
pParticleShader->bind(ri.commandBuffer, *ri.camera, ri.viewport, getModelMatrix(), &ri.point_lights, &ri.directional_lights, &ri.spot_lights, ri.renderPass);

View File

@@ -33,14 +33,15 @@
#include "KRParticleSystem.h"
class KRParticleSystemNewtonian : public KRParticleSystem {
class KRParticleSystemNewtonian : public KRParticleSystem
{
public:
KRParticleSystemNewtonian(KRScene &scene, std::string name);
KRParticleSystemNewtonian(KRScene& scene, std::string name);
virtual ~KRParticleSystemNewtonian();
virtual std::string getElementName();
virtual void loadXML(tinyxml2::XMLElement *e);
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual void loadXML(tinyxml2::XMLElement* e);
virtual tinyxml2::XMLElement* saveXML(tinyxml2::XMLNode* parent);
virtual AABB getBounds();

View File

@@ -39,7 +39,7 @@
#include "KRRenderPass.h"
const char *KRPipeline::KRENGINE_UNIFORM_NAMES[] = {
const char* KRPipeline::KRENGINE_UNIFORM_NAMES[] = {
"material_ambient", // Uniform::material_ambient
"material_diffuse", // Uniform::material_diffuse
"material_specular", // Uniform::material_specular
@@ -168,35 +168,27 @@ KRPipeline::KRPipeline(KRContext& context, KRSurface& surface, const PipelineInf
SpvReflectInterfaceVariable& input_var = *reflection->input_variables[i];
if (strcmp(input_var.name, "vertex_position") == 0) {
attribute_locations[KRMesh::KRENGINE_ATTRIB_VERTEX] = input_var.location + 1;
}
else if (strcmp(input_var.name, "vertex_normal") == 0) {
} else if (strcmp(input_var.name, "vertex_normal") == 0) {
attribute_locations[KRMesh::KRENGINE_ATTRIB_NORMAL] = input_var.location + 1;
}
else if (strcmp(input_var.name, "vertex_tangent") == 0) {
} else if (strcmp(input_var.name, "vertex_tangent") == 0) {
attribute_locations[KRMesh::KRENGINE_ATTRIB_TANGENT] = input_var.location + 1;
}
else if (strcmp(input_var.name, "vertex_uv") == 0) {
} else if (strcmp(input_var.name, "vertex_uv") == 0) {
attribute_locations[KRMesh::KRENGINE_ATTRIB_TEXUVA] = input_var.location + 1;
}
else if (strcmp(input_var.name, "vertex_lightmap_uv") == 0) {
} else if (strcmp(input_var.name, "vertex_lightmap_uv") == 0) {
attribute_locations[KRMesh::KRENGINE_ATTRIB_TEXUVB] = input_var.location + 1;
}
else if (strcmp(input_var.name, "bone_indexes") == 0) {
} else if (strcmp(input_var.name, "bone_indexes") == 0) {
attribute_locations[KRMesh::KRENGINE_ATTRIB_BONEINDEXES] = input_var.location + 1;
}
else if (strcmp(input_var.name, "bone_weights") == 0) {
} else if (strcmp(input_var.name, "bone_weights") == 0) {
attribute_locations[KRMesh::KRENGINE_ATTRIB_BONEWEIGHTS] = input_var.location + 1;
}
}
initPushConstantStage(ShaderStages::vertex, reflection);
}
else if (shader->getSubExtension().compare("frag") == 0) {
} else if (shader->getSubExtension().compare("frag") == 0) {
stageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
initPushConstantStage(ShaderStages::fragment, reflection);
}
else {
} else {
// failed! TODO - Error handling
}
stageInfo.module = shaderModule;
@@ -454,7 +446,8 @@ KRPipeline::KRPipeline(KRContext& context, KRSurface& surface, const PipelineInf
}
}
KRPipeline::~KRPipeline() {
KRPipeline::~KRPipeline()
{
if (m_graphicsPipeline) {
// TODO: vkDestroyPipeline(device, m_graphicsPipeline, nullptr);
}
@@ -468,7 +461,7 @@ KRPipeline::~KRPipeline() {
}
if(getContext().getPipelineManager()->m_active_pipeline == this) {
if (getContext().getPipelineManager()->m_active_pipeline == this) {
getContext().getPipelineManager()->m_active_pipeline = NULL;
}
if (m_pushConstants[0].buffer) {
@@ -492,8 +485,7 @@ void KRPipeline::initPushConstantStage(ShaderStages stage, const SpvReflectShade
for (int iUniform = 0; iUniform < kUniformCount; iUniform++) {
for (int iMember = 0; iMember < block.member_count; iMember++) {
const SpvReflectBlockVariable& member = block.members[iMember];
if (stricmp(KRENGINE_UNIFORM_NAMES[iUniform], member.name) == 0)
{
if (stricmp(KRENGINE_UNIFORM_NAMES[iUniform], member.name) == 0) {
pushConstants.offset[iUniform] = member.offset;
pushConstants.size[iUniform] = member.size;
}
@@ -535,7 +527,7 @@ void KRPipeline::setUniform(Uniform location, int value)
}
}
void KRPipeline::setUniform(Uniform location, const Vector2 &value)
void KRPipeline::setUniform(Uniform location, const Vector2& value)
{
for (PushConstantStageInfo& stageConstants : m_pushConstants) {
if (stageConstants.size[static_cast<size_t>(location)] == sizeof(value)) {
@@ -544,7 +536,7 @@ void KRPipeline::setUniform(Uniform location, const Vector2 &value)
}
}
}
void KRPipeline::setUniform(Uniform location, const Vector3 &value)
void KRPipeline::setUniform(Uniform location, const Vector3& value)
{
for (PushConstantStageInfo& stageConstants : m_pushConstants) {
if (stageConstants.size[static_cast<size_t>(location)] == sizeof(value)) {
@@ -554,7 +546,7 @@ void KRPipeline::setUniform(Uniform location, const Vector3 &value)
}
}
void KRPipeline::setUniform(Uniform location, const Vector4 &value)
void KRPipeline::setUniform(Uniform location, const Vector4& value)
{
for (PushConstantStageInfo& stageConstants : m_pushConstants) {
if (stageConstants.size[static_cast<size_t>(location)] == sizeof(value)) {
@@ -564,7 +556,7 @@ void KRPipeline::setUniform(Uniform location, const Vector4 &value)
}
}
void KRPipeline::setUniform(Uniform location, const Matrix4 &value)
void KRPipeline::setUniform(Uniform location, const Matrix4& value)
{
for (PushConstantStageInfo& stageConstants : m_pushConstants) {
if (stageConstants.size[static_cast<size_t>(location)] == sizeof(value)) {
@@ -582,7 +574,7 @@ void KRPipeline::setUniform(Uniform location, const Matrix4* value, const size_t
}
}
bool KRPipeline::bind(VkCommandBuffer& commandBuffer, KRCamera &camera, const KRViewport &viewport, const Matrix4 &matModel, const std::vector<KRPointLight *> *point_lights, const std::vector<KRDirectionalLight *> *directional_lights, const std::vector<KRSpotLight *> *spot_lights, const KRNode::RenderPass &renderPass)
bool KRPipeline::bind(VkCommandBuffer& commandBuffer, KRCamera& camera, const KRViewport& viewport, const Matrix4& matModel, const std::vector<KRPointLight*>* point_lights, const std::vector<KRDirectionalLight*>* directional_lights, const std::vector<KRSpotLight*>* spot_lights, const KRNode::RenderPass& renderPass)
{
setUniform(Uniform::absolute_time, getContext().getAbsoluteTime());
@@ -590,7 +582,7 @@ bool KRPipeline::bind(VkCommandBuffer& commandBuffer, KRCamera &camera, const KR
//int light_point_count = 0;
//int light_spot_count = 0;
// TODO - Need to support multiple lights and more light types in forward rendering
if(renderPass != KRNode::RENDER_PASS_DEFERRED_LIGHTS && renderPass != KRNode::RENDER_PASS_DEFERRED_GBUFFER && renderPass != KRNode::RENDER_PASS_DEFERRED_OPAQUE && renderPass != KRNode::RENDER_PASS_GENERATE_SHADOWMAPS) {
if (renderPass != KRNode::RENDER_PASS_DEFERRED_LIGHTS && renderPass != KRNode::RENDER_PASS_DEFERRED_GBUFFER && renderPass != KRNode::RENDER_PASS_DEFERRED_OPAQUE && renderPass != KRNode::RENDER_PASS_GENERATE_SHADOWMAPS) {
if (directional_lights) {
@@ -652,38 +644,38 @@ bool KRPipeline::bind(VkCommandBuffer& commandBuffer, KRCamera &camera, const KR
//light_spot_count = spot_lights.size();
}
if(hasUniform(Uniform::camerapos_model_space)) {
if (hasUniform(Uniform::camerapos_model_space)) {
Matrix4 inverseModelMatrix = matModel;
inverseModelMatrix.invert();
if(hasUniform(Uniform::camerapos_model_space)) {
if (hasUniform(Uniform::camerapos_model_space)) {
// Transform location of camera to object space for calculation of specular halfVec
Vector3 cameraPosObject = Matrix4::Dot(inverseModelMatrix, viewport.getCameraPosition());
setUniform(Uniform::camerapos_model_space, cameraPosObject);
}
}
if(hasUniform(Uniform::mvp) || hasUniform(KRPipeline::Uniform::invmvp)) {
if (hasUniform(Uniform::mvp) || hasUniform(KRPipeline::Uniform::invmvp)) {
// Bind our modelmatrix variable to be a uniform called mvpmatrix in our shaderprogram
Matrix4 mvpMatrix = matModel * viewport.getViewProjectionMatrix();
setUniform(Uniform::mvp, mvpMatrix);
if(hasUniform(KRPipeline::Uniform::invmvp)) {
if (hasUniform(KRPipeline::Uniform::invmvp)) {
setUniform(KRPipeline::Uniform::invmvp, Matrix4::Invert(mvpMatrix));
}
}
if(hasUniform(KRPipeline::Uniform::view_space_model_origin) || hasUniform(Uniform::model_view_inverse_transpose) || hasUniform(KRPipeline::Uniform::model_view)) {
if (hasUniform(KRPipeline::Uniform::view_space_model_origin) || hasUniform(Uniform::model_view_inverse_transpose) || hasUniform(KRPipeline::Uniform::model_view)) {
Matrix4 matModelView = matModel * viewport.getViewMatrix();
setUniform(Uniform::model_view, matModelView);
if(hasUniform(KRPipeline::Uniform::view_space_model_origin)) {
if (hasUniform(KRPipeline::Uniform::view_space_model_origin)) {
Vector3 view_space_model_origin = Matrix4::Dot(matModelView, Vector3::Zero()); // Origin point of model space is the light source position. No perspective, so no w divide required
setUniform(Uniform::view_space_model_origin, view_space_model_origin);
}
if(hasUniform(Uniform::model_view_inverse_transpose)) {
if (hasUniform(Uniform::model_view_inverse_transpose)) {
Matrix4 matModelViewInverseTranspose = matModelView;
matModelViewInverseTranspose.transpose();
matModelViewInverseTranspose.invert();
@@ -691,18 +683,18 @@ bool KRPipeline::bind(VkCommandBuffer& commandBuffer, KRCamera &camera, const KR
}
}
if(hasUniform(Uniform::model_inverse_transpose)) {
if (hasUniform(Uniform::model_inverse_transpose)) {
Matrix4 matModelInverseTranspose = matModel;
matModelInverseTranspose.transpose();
matModelInverseTranspose.invert();
setUniform(Uniform::model_inverse_transpose, matModelInverseTranspose);
}
if(hasUniform(KRPipeline::Uniform::invp)) {
if (hasUniform(KRPipeline::Uniform::invp)) {
setUniform(Uniform::invp, viewport.getInverseProjectionMatrix());
}
if(hasUniform(KRPipeline::Uniform::invmvp_no_translate)) {
if (hasUniform(KRPipeline::Uniform::invmvp_no_translate)) {
Matrix4 matInvMVPNoTranslate = matModel * viewport.getViewMatrix();;
// Remove the translation
matInvMVPNoTranslate.getPointer()[3] = 0;
@@ -718,11 +710,11 @@ bool KRPipeline::bind(VkCommandBuffer& commandBuffer, KRCamera &camera, const KR
}
setUniform(Uniform::model_matrix, matModel);
if(hasUniform(Uniform::projection_matrix)) {
if (hasUniform(Uniform::projection_matrix)) {
setUniform(Uniform::projection_matrix, viewport.getProjectionMatrix());
}
if(hasUniform(Uniform::viewport)) {
if (hasUniform(Uniform::viewport)) {
setUniform(Uniform::viewport, Vector4::Create(
(float)0.0,
(float)0.0,
@@ -732,7 +724,7 @@ bool KRPipeline::bind(VkCommandBuffer& commandBuffer, KRCamera &camera, const KR
);
}
if(hasUniform(Uniform::viewport_downsample)) {
if (hasUniform(Uniform::viewport_downsample)) {
setUniform(Uniform::viewport_downsample, camera.getDownsample());
}
@@ -742,13 +734,13 @@ bool KRPipeline::bind(VkCommandBuffer& commandBuffer, KRCamera &camera, const KR
setUniform(Uniform::fog_density, camera.settings.fog_density);
setUniform(Uniform::fog_color, camera.settings.fog_color);
if(hasUniform(Uniform::fog_scale)) {
if (hasUniform(Uniform::fog_scale)) {
setUniform(Uniform::fog_scale, 1.0f / (camera.settings.fog_far - camera.settings.fog_near));
}
if(hasUniform(Uniform::density_premultiplied_exponential)) {
if (hasUniform(Uniform::density_premultiplied_exponential)) {
setUniform(Uniform::density_premultiplied_exponential, -camera.settings.fog_density * 1.442695f); // -fog_density / log(2)
}
if(hasUniform(Uniform::density_premultiplied_squared)) {
if (hasUniform(Uniform::density_premultiplied_squared)) {
setUniform(Uniform::density_premultiplied_squared, (float)(-camera.settings.fog_density * camera.settings.fog_density * 1.442695)); // -fog_density * fog_density / log(2)
}
@@ -785,7 +777,8 @@ bool KRPipeline::bind(VkCommandBuffer& commandBuffer, KRCamera &camera, const KR
return true;
}
const char *KRPipeline::getKey() const {
const char* KRPipeline::getKey() const
{
return m_szKey;
}

View File

@@ -45,14 +45,16 @@ class KRRenderPass;
enum class ModelFormat : __uint8_t;
struct SpvReflectShaderModule;
enum class CullMode : uint32_t {
enum class CullMode : uint32_t
{
kCullBack = 0,
kCullFront,
kCullNone
};
// Note: RasterMode is likely to be refactored later to a bitfield
enum class RasterMode : uint32_t {
enum class RasterMode : uint32_t
{
kOpaque = 0,
/*
kOpaque is equivalent to:
@@ -173,7 +175,8 @@ enum class RasterMode : uint32_t {
*/
};
class PipelineInfo {
class PipelineInfo
{
public:
const std::string* shader_name;
KRCamera* pCamera;
@@ -204,16 +207,18 @@ public:
KRNode::RenderPass renderPass;
};
class KRPipeline : public KRContextObject {
class KRPipeline : public KRContextObject
{
public:
KRPipeline(KRContext& context, KRSurface& surface, const PipelineInfo& info, const char* szKey, const std::vector<KRShader*>& shaders, uint32_t vertexAttributes, ModelFormat modelFormat);
virtual ~KRPipeline();
const char *getKey() const;
const char* getKey() const;
bool bind(VkCommandBuffer& commandBuffer, KRCamera &camera, const KRViewport &viewport, const Matrix4 &matModel, const std::vector<KRPointLight *> *point_lights, const std::vector<KRDirectionalLight *> *directional_lights, const std::vector<KRSpotLight *>*spot_lights, const KRNode::RenderPass &renderPass);
bool bind(VkCommandBuffer& commandBuffer, KRCamera& camera, const KRViewport& viewport, const Matrix4& matModel, const std::vector<KRPointLight*>* point_lights, const std::vector<KRDirectionalLight*>* directional_lights, const std::vector<KRSpotLight*>* spot_lights, const KRNode::RenderPass& renderPass);
enum class Uniform : uint8_t {
enum class Uniform : uint8_t
{
material_ambient = 0,
material_diffuse,
material_specular,
@@ -301,10 +306,10 @@ public:
bool hasUniform(Uniform location) const;
void setUniform(Uniform location, float value);
void setUniform(Uniform location, int value);
void setUniform(Uniform location, const Vector2 &value);
void setUniform(Uniform location, const Vector3 &value);
void setUniform(Uniform location, const Vector4 &value);
void setUniform(Uniform location, const Matrix4 &value);
void setUniform(Uniform location, const Vector2& value);
void setUniform(Uniform location, const Vector3& value);
void setUniform(Uniform location, const Vector4& value);
void setUniform(Uniform location, const Matrix4& value);
void setUniform(Uniform location, const Matrix4* value, const size_t count);
VkPipeline& getPipeline();

View File

@@ -44,20 +44,21 @@
using namespace std;
KRPipelineManager::KRPipelineManager(KRContext &context) : KRContextObject(context) {
KRPipelineManager::KRPipelineManager(KRContext& context) : KRContextObject(context)
{
m_active_pipeline = NULL;
#ifndef ANDROID
bool success = glslang::InitializeProcess();
if (success) {
printf("GLSLang Initialized.\n");
}
else {
} else {
printf("Failed to initialize GLSLang.\n");
}
#endif // ANDROID
}
KRPipelineManager::~KRPipelineManager() {
KRPipelineManager::~KRPipelineManager()
{
#ifndef ANDROID
glslang::FinalizeProcess();
#endif // ANDROID
@@ -294,7 +295,8 @@ KRPipeline *KRPipelineManager::getPipeline(KRSurface& surface, const PipelineInf
}
*/
size_t KRPipelineManager::getPipelineHandlesUsed() {
size_t KRPipelineManager::getPipelineHandlesUsed()
{
return m_pipelines.size();
}

View File

@@ -48,10 +48,11 @@ class KRPipeline;
class PipelineInfo;
class KRCamera;
class KRPipelineManager : public KRContextObject {
class KRPipelineManager : public KRContextObject
{
public:
KRPipelineManager(KRContext &context);
KRPipelineManager(KRContext& context);
virtual ~KRPipelineManager();
KRPipeline* get(const char* szKey);
@@ -59,7 +60,7 @@ public:
size_t getPipelineHandlesUsed();
KRPipeline *m_active_pipeline;
KRPipeline* m_active_pipeline;
private:
typedef std::map<std::pair<std::string, std::vector<int> >, KRPipeline*> PipelineMap;

View File

@@ -42,7 +42,7 @@ void KRPointLight::InitNodeInfo(KrNodeInfo* nodeInfo)
// No additional members
}
KRPointLight::KRPointLight(KRScene &scene, std::string name) : KRLight(scene, name)
KRPointLight::KRPointLight(KRScene& scene, std::string name) : KRLight(scene, name)
{
m_sphereVertices = NULL;
m_cVertices = 0;
@@ -50,19 +50,21 @@ KRPointLight::KRPointLight(KRScene &scene, std::string name) : KRLight(scene, na
KRPointLight::~KRPointLight()
{
if(m_sphereVertices) {
if (m_sphereVertices) {
delete m_sphereVertices;
m_cVertices = 0;
}
}
std::string KRPointLight::getElementName() {
std::string KRPointLight::getElementName()
{
return "point_light";
}
AABB KRPointLight::getBounds() {
AABB KRPointLight::getBounds()
{
float influence_radius = m_decayStart - sqrt(m_intensity * 0.01f) / sqrt(KRLIGHT_MIN_INFLUENCE);
if(influence_radius < m_flareOcclusionSize) {
if (influence_radius < m_flareOcclusionSize) {
influence_radius = m_flareOcclusionSize;
}
return AABB::Create(Vector3::Create(-influence_radius), Vector3::Create(influence_radius), getModelMatrix());
@@ -70,16 +72,16 @@ AABB KRPointLight::getBounds() {
void KRPointLight::render(RenderInfo& ri)
{
if(m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
if (m_lod_visible <= LOD_VISIBILITY_PRESTREAM) return;
KRLight::render(ri);
bool bVisualize = ri.renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT && ri.camera->settings.bShowDeferred;
if(ri.renderPass == KRNode::RENDER_PASS_DEFERRED_LIGHTS || bVisualize) {
if (ri.renderPass == KRNode::RENDER_PASS_DEFERRED_LIGHTS || bVisualize) {
// Lights are rendered on the second pass of the deferred renderer
std::vector<KRPointLight *> this_light;
std::vector<KRPointLight*> this_light;
this_light.push_back(this);
Vector3 light_position = getLocalTranslation();
@@ -90,7 +92,7 @@ void KRPointLight::render(RenderInfo& ri)
sphereModelMatrix.scale(influence_radius);
sphereModelMatrix.translate(light_position.x, light_position.y, light_position.z);
if(ri.viewport.visible(getBounds())) { // Cull out any lights not within the view frustrum
if (ri.viewport.visible(getBounds())) { // Cull out any lights not within the view frustrum
Vector3 view_light_position = Matrix4::Dot(ri.viewport.getViewMatrix(), light_position);
@@ -104,14 +106,13 @@ void KRPointLight::render(RenderInfo& ri)
info.renderPass = ri.renderPass;
if (bInsideLight) {
info.rasterMode = bVisualize ? RasterMode::kAdditiveNoTest : RasterMode::kAlphaBlendNoTest;
}
else {
} else {
info.rasterMode = bVisualize ? RasterMode::kAdditive : RasterMode::kAlphaBlend;
}
info.vertexAttributes = bInsideLight ? m_pContext->getMeshManager()->KRENGINE_VBO_DATA_2D_SQUARE_VERTICES.getVertexAttributes() : 1 << KRMesh::KRENGINE_ATTRIB_VERTEX;
info.modelFormat = bInsideLight ? ModelFormat::KRENGINE_MODEL_FORMAT_STRIP : ModelFormat::KRENGINE_MODEL_FORMAT_TRIANGLES;
KRPipeline *pShader = getContext().getPipelineManager()->getPipeline(*ri.surface, info);
KRPipeline* pShader = getContext().getPipelineManager()->getPipeline(*ri.surface, info);
pShader->setUniform(KRPipeline::Uniform::light_color, m_color);
pShader->setUniform(KRPipeline::Uniform::light_intensity, m_intensity * 0.01f);
pShader->setUniform(KRPipeline::Uniform::light_decay_start, getDecayStart());
@@ -119,7 +120,7 @@ void KRPointLight::render(RenderInfo& ri)
pShader->setUniform(KRPipeline::Uniform::light_position, light_position);
pShader->bind(ri.commandBuffer, *ri.camera, ri.viewport, sphereModelMatrix, &this_light, nullptr, nullptr, ri.renderPass);
if(bInsideLight) {
if (bInsideLight) {
// Render a full screen quad
m_pContext->getMeshManager()->bindVBO(ri.commandBuffer, &m_pContext->getMeshManager()->KRENGINE_VBO_DATA_2D_SQUARE_VERTICES, 1.0f);
vkCmdDraw(ri.commandBuffer, 4, 1, 0, 0);
@@ -136,15 +137,16 @@ void KRPointLight::render(RenderInfo& ri)
}
}
void KRPointLight::generateMesh() {
void KRPointLight::generateMesh()
{
// Create a triangular facet approximation to a sphere
// Based on algorithm from Paul Bourke: http://paulbourke.net/miscellaneous/sphere_cylinder/
int iterations = 3;
int facet_count = (int)(pow(4, iterations) * 8);
if(m_cVertices != facet_count * 3) {
if(m_sphereVertices) {
if (m_cVertices != facet_count * 3) {
if (m_sphereVertices) {
free(m_sphereVertices);
m_sphereVertices = NULL;
}
@@ -152,12 +154,15 @@ void KRPointLight::generateMesh() {
m_cVertices = facet_count * 3;
class Facet3 {
class Facet3
{
public:
Facet3() {
Facet3()
{
}
~Facet3() {
~Facet3()
{
}
Vector3 p1;
@@ -167,7 +172,7 @@ void KRPointLight::generateMesh() {
std::vector<Facet3> f = std::vector<Facet3>(facet_count);
int i,it;
int i, it;
float a;
Vector3 p[6] = {
Vector3::Create(0,0,1),
@@ -178,12 +183,12 @@ void KRPointLight::generateMesh() {
Vector3::Create(-1,1,0)
};
Vector3 pa,pb,pc;
int nt = 0,ntold;
Vector3 pa, pb, pc;
int nt = 0, ntold;
/* Create the level 0 object */
a = 1.0f / sqrtf(2.0f);
for (i=0;i<6;i++) {
for (i = 0; i < 6; i++) {
p[i].x *= a;
p[i].y *= a;
}
@@ -198,9 +203,9 @@ void KRPointLight::generateMesh() {
nt = 8;
/* Bisect each edge and move to the surface of a unit sphere */
for (it=0;it<iterations;it++) {
for (it = 0; it < iterations; it++) {
ntold = nt;
for (i=0;i<ntold;i++) {
for (i = 0; i < ntold; i++) {
pa.x = (f[i].p1.x + f[i].p2.x) / 2;
pa.y = (f[i].p1.y + f[i].p2.y) / 2;
pa.z = (f[i].p1.z + f[i].p2.z) / 2;
@@ -224,8 +229,8 @@ void KRPointLight::generateMesh() {
m_sphereVertices = (float*)malloc(sizeof(float) * m_cVertices * 3);
assert(m_sphereVertices != NULL);
float*pDest = m_sphereVertices;
for(int facet_index=0; facet_index < facet_count; facet_index++) {
float* pDest = m_sphereVertices;
for (int facet_index = 0; facet_index < facet_count; facet_index++) {
*pDest++ = f[facet_index].p1.x;
*pDest++ = f[facet_index].p1.y;
*pDest++ = f[facet_index].p1.z;

View File

@@ -33,11 +33,11 @@
#include "KRLight.h"
class KRPointLight : public KRLight {
class KRPointLight : public KRLight
{
public:
static void InitNodeInfo(KrNodeInfo* nodeInfo);
KRPointLight(KRScene &scene, std::string name);
KRPointLight(KRScene& scene, std::string name);
virtual ~KRPointLight();
virtual std::string getElementName();
@@ -48,6 +48,6 @@ public:
private:
void generateMesh();
float *m_sphereVertices;
float* m_sphereVertices;
int m_cVertices;
};

View File

@@ -71,8 +71,7 @@ void KRPresentationThread::run()
std::chrono::microseconds sleep_duration(15000);
m_activeState = PresentThreadState::run;
while (m_requestedState != PresentThreadRequest::stop)
{
while (m_requestedState != PresentThreadRequest::stop) {
switch (m_activeState) {
case PresentThreadState::pause:
case PresentThreadState::stop:
@@ -103,7 +102,7 @@ void KRPresentationThread::renderFrame()
unordered_map<KrSurfaceHandle, std::unique_ptr<KRSurface>>& surfaces = m_pContext->getSurfaceManager()->getSurfaces();
KRSceneManager* sceneManager = m_pContext->getSceneManager();
KRScene *scene = sceneManager->getFirstScene();
KRScene* scene = sceneManager->getFirstScene();
for (auto surfaceItr = surfaces.begin(); surfaceItr != surfaces.end(); surfaceItr++) {
KRSurface& surface = *(*surfaceItr).second;

View File

@@ -45,7 +45,7 @@ KRRenderPass::~KRRenderPass()
assert(m_renderPass == VK_NULL_HANDLE);
}
void KRRenderPass::create(KRDevice &device, VkFormat swapChainImageFormat, VkFormat depthImageFormat, const RenderPassInfo& info)
void KRRenderPass::create(KRDevice& device, VkFormat swapChainImageFormat, VkFormat depthImageFormat, const RenderPassInfo& info)
{
if (m_renderPass) {
return;
@@ -110,7 +110,7 @@ void KRRenderPass::create(KRDevice &device, VkFormat swapChainImageFormat, VkFor
}
}
void KRRenderPass::destroy(KRDevice &device)
void KRRenderPass::destroy(KRDevice& device)
{
if (m_renderPass) {
vkDestroyRenderPass(device.m_logicalDevice, m_renderPass, nullptr);

View File

@@ -51,9 +51,9 @@ public:
void create(KRDevice& device, VkFormat swapChainImageFormat, VkFormat depthImageFormat, const RenderPassInfo& info);
void destroy(KRDevice& device);
void begin(VkCommandBuffer &commandBuffer, KRSurface& surface, const Vector4& clearColor);
void begin(VkCommandBuffer& commandBuffer, KRSurface& surface, const Vector4& clearColor);
void end(VkCommandBuffer& commandBuffer);
// private:
// private:
VkRenderPass m_renderPass;
};

View File

@@ -106,7 +106,7 @@ KRRenderSettings::~KRRenderSettings()
}
KRRenderSettings& KRRenderSettings::operator=(const KRRenderSettings &s)
KRRenderSettings& KRRenderSettings::operator=(const KRRenderSettings& s)
{
siren_enable = s.siren_enable;
siren_enable_reverb = s.siren_enable_reverb;
@@ -118,54 +118,54 @@ KRRenderSettings& KRRenderSettings::operator=(const KRRenderSettings &s)
bEnableNormalMap = s.bEnableNormalMap;
bEnableSpecMap = s.bEnableSpecMap;
bEnableReflectionMap = s.bEnableReflectionMap;
bEnableReflection=s.bEnableReflection;
bEnableLightMap=s.bEnableLightMap;
bDebugPSSM=s.bDebugPSSM;
bShowShadowBuffer=s.bShowShadowBuffer;
bShowOctree=s.bShowOctree;
bShowDeferred=s.bShowDeferred;
bEnableAmbient=s.bEnableAmbient;
bEnableDiffuse=s.bEnableDiffuse;
bEnableSpecular=s.bEnableSpecular;
bEnableDeferredLighting=s.bEnableDeferredLighting;
light_intensity=s.light_intensity;
ambient_intensity=s.ambient_intensity;
perspective_fov=s.perspective_fov;
bEnableReflection = s.bEnableReflection;
bEnableLightMap = s.bEnableLightMap;
bDebugPSSM = s.bDebugPSSM;
bShowShadowBuffer = s.bShowShadowBuffer;
bShowOctree = s.bShowOctree;
bShowDeferred = s.bShowDeferred;
bEnableAmbient = s.bEnableAmbient;
bEnableDiffuse = s.bEnableDiffuse;
bEnableSpecular = s.bEnableSpecular;
bEnableDeferredLighting = s.bEnableDeferredLighting;
light_intensity = s.light_intensity;
ambient_intensity = s.ambient_intensity;
perspective_fov = s.perspective_fov;
dof_quality=s.dof_quality;
dof_depth=s.dof_depth;
dof_falloff=s.dof_falloff;
bEnableFlash=s.bEnableFlash;
flash_intensity=s.flash_intensity;
flash_depth=s.flash_depth;
flash_falloff=s.flash_falloff;
dof_quality = s.dof_quality;
dof_depth = s.dof_depth;
dof_falloff = s.dof_falloff;
bEnableFlash = s.bEnableFlash;
flash_intensity = s.flash_intensity;
flash_depth = s.flash_depth;
flash_falloff = s.flash_falloff;
bEnableVignette=s.bEnableVignette;
vignette_radius=s.vignette_radius;
vignette_falloff=s.vignette_falloff;
bEnableVignette = s.bEnableVignette;
vignette_radius = s.vignette_radius;
vignette_falloff = s.vignette_falloff;
m_viewportSize=s.m_viewportSize;
m_viewportSize = s.m_viewportSize;
m_cShadowBuffers=s.m_cShadowBuffers;
m_cShadowBuffers = s.m_cShadowBuffers;
m_debug_text=s.m_debug_text;
m_debug_text = s.m_debug_text;
volumetric_environment_enable=s.volumetric_environment_enable;
volumetric_environment_downsample=s.volumetric_environment_downsample;
volumetric_environment_max_distance=s.volumetric_environment_max_distance;
volumetric_environment_quality=s.volumetric_environment_quality;
volumetric_environment_intensity=s.volumetric_environment_intensity;
volumetric_environment_enable = s.volumetric_environment_enable;
volumetric_environment_downsample = s.volumetric_environment_downsample;
volumetric_environment_max_distance = s.volumetric_environment_max_distance;
volumetric_environment_quality = s.volumetric_environment_quality;
volumetric_environment_intensity = s.volumetric_environment_intensity;
fog_near=s.fog_near;
fog_far=s.fog_far;
fog_density=s.fog_density;
fog_color=s.fog_color;
fog_type=s.fog_type;
fog_near = s.fog_near;
fog_far = s.fog_far;
fog_density = s.fog_density;
fog_color = s.fog_color;
fog_type = s.fog_type;
dust_particle_intensity=s.dust_particle_intensity;
dust_particle_enable=s.dust_particle_enable;
perspective_nearz=s.perspective_nearz;
perspective_farz=s.perspective_farz;
dust_particle_intensity = s.dust_particle_intensity;
dust_particle_enable = s.dust_particle_enable;
perspective_nearz = s.perspective_nearz;
perspective_farz = s.perspective_farz;
debug_display = s.debug_display;
m_lodBias = s.m_lodBias;
@@ -176,11 +176,13 @@ KRRenderSettings& KRRenderSettings::operator=(const KRRenderSettings &s)
return *this;
}
const Vector2 &KRRenderSettings::getViewportSize() {
const Vector2& KRRenderSettings::getViewportSize()
{
return m_viewportSize;
}
void KRRenderSettings::setViewportSize(const Vector2 &size) {
void KRRenderSettings::setViewportSize(const Vector2& size)
{
m_viewportSize = size;
}
@@ -195,13 +197,13 @@ float KRRenderSettings::getPerspectiveFarZ()
void KRRenderSettings::setPerspectiveNear(float v)
{
if(perspective_nearz != v) {
if (perspective_nearz != v) {
perspective_nearz = v;
}
}
void KRRenderSettings::setPerpsectiveFarZ(float v)
{
if(perspective_farz != v) {
if (perspective_farz != v) {
perspective_farz = v;
}
}

View File

@@ -33,16 +33,17 @@
#include "KREngine-common.h"
class KRRenderSettings {
class KRRenderSettings
{
public:
KRRenderSettings();
~KRRenderSettings();
// Overload assignment operator
KRRenderSettings& operator=(const KRRenderSettings &s);
KRRenderSettings& operator=(const KRRenderSettings& s);
const Vector2 &getViewportSize();
void setViewportSize(const Vector2 &size);
const Vector2& getViewportSize();
void setViewportSize(const Vector2& size);
float getPerspectiveNearZ();
float getPerspectiveFarZ();
@@ -106,7 +107,8 @@ public:
float perspective_nearz;
float perspective_farz;
enum debug_display_type{
enum debug_display_type
{
KRENGINE_DEBUG_DISPLAY_NONE = 0,
KRENGINE_DEBUG_DISPLAY_TIME,
KRENGINE_DEBUG_DISPLAY_MEMORY,

View File

@@ -36,12 +36,13 @@
#include "KRResource+blend.h"
KRScene* KRResource::LoadBlenderScene(KRContext &context, const std::string& path) {
KRScene *pScene = new KRScene(context, KRResource::GetFileBase(path));
KRScene* KRResource::LoadBlenderScene(KRContext& context, const std::string& path)
{
KRScene* pScene = new KRScene(context, KRResource::GetFileBase(path));
KRDataBlock data;
if(data.load(path)) {
if (data.load(path)) {
//KRBlendFile blend_file = KRBlendFile(pFile);
}
@@ -49,11 +50,12 @@ KRScene* KRResource::LoadBlenderScene(KRContext &context, const std::string& pat
}
KRBlendFile::KRBlendFile(const void *pFile) {
unsigned char *scan = (unsigned char *)pFile;
KRBlendFile::KRBlendFile(const void* pFile)
{
unsigned char* scan = (unsigned char*)pFile;
readHeader(scan);
std::string block_code = "";
while(block_code != "ENDB") {
while (block_code != "ENDB") {
Block b = Block(this, scan);
block_code = b.getCode();
m_blocks.push_back(b);
@@ -62,21 +64,22 @@ KRBlendFile::KRBlendFile(const void *pFile) {
}
}
void KRBlendFile::readHeader(unsigned char *&scan) {
if(strncmp((char *)scan, "BLENDER", 7) != 0) {
void KRBlendFile::readHeader(unsigned char*& scan)
{
if (strncmp((char*)scan, "BLENDER", 7) != 0) {
// TODO throw exception
}
scan += 7;
if(scan[0] == '_' && scan[1] == 'v') {
if (scan[0] == '_' && scan[1] == 'v') {
// 32-bit, little-endian
m_file_type = KRBLEND_LITTLEENDIAN_32BIT;
} else if(scan[0] == '_' && scan[1] == 'V') {
} else if (scan[0] == '_' && scan[1] == 'V') {
// 32-bit, bit-endian
m_file_type = KRBLEND_BIGENDIAN_32BIT;
} else if(scan[0] == '-' && scan[1] == 'v') {
} else if (scan[0] == '-' && scan[1] == 'v') {
// 64-bit, little-endian
m_file_type = KRBLEND_LITTLEENDIAN_64BIT;
} else if(scan[0] == '-' && scan[1] == 'V') {
} else if (scan[0] == '-' && scan[1] == 'V') {
// 64-bit, big-endian
m_file_type = KRBLEND_BIGENDIAN_64BIT;
} else {
@@ -85,7 +88,8 @@ void KRBlendFile::readHeader(unsigned char *&scan) {
scan += 5; // Skip and ignore version
}
__int32_t KRBlendFile::readInt(unsigned char *&scan) {
__int32_t KRBlendFile::readInt(unsigned char*& scan)
{
__int32_t ret = 0;
// read a 32-bit integer and increment scan
@@ -104,7 +108,8 @@ __int32_t KRBlendFile::readInt(unsigned char *&scan) {
return ret;
}
__int64_t KRBlendFile::readPointer(unsigned char *&scan) {
__int64_t KRBlendFile::readPointer(unsigned char*& scan)
{
__int64_t ret = 0;
// read a 32-bit integer and increment scan
switch (m_file_type) {
@@ -131,12 +136,14 @@ __int64_t KRBlendFile::readPointer(unsigned char *&scan) {
return ret;
}
KRBlendFile::~KRBlendFile() {
KRBlendFile::~KRBlendFile()
{
}
KRBlendFile::Block::Block(KRBlendFile *blendFile, unsigned char *&scan) {
KRBlendFile::Block::Block(KRBlendFile* blendFile, unsigned char*& scan)
{
scan += (__int64_t)scan % 4; // Scan forward until the next 4-byte boundary
char szBlock[5];
szBlock[0] = *scan++;
@@ -152,15 +159,18 @@ KRBlendFile::Block::Block(KRBlendFile *blendFile, unsigned char *&scan) {
m_data = scan;
scan += m_dataSize;
}
KRBlendFile::Block::~Block() {
KRBlendFile::Block::~Block()
{
}
std::string KRBlendFile::Block::getCode() {
std::string KRBlendFile::Block::getCode()
{
return m_code;
}
int KRBlendFile::Block::getDataSize() {
int KRBlendFile::Block::getDataSize()
{
return m_dataSize;
}

View File

@@ -31,14 +31,16 @@
#pragma once
class KRBlendFile {
class KRBlendFile
{
public:
KRBlendFile(const void *pFile);
KRBlendFile(const void* pFile);
~KRBlendFile();
class Block {
class Block
{
public:
Block(KRBlendFile *blendFile, unsigned char *&scan);
Block(KRBlendFile* blendFile, unsigned char*& scan);
~Block();
std::string getCode();
@@ -49,20 +51,21 @@ public:
__int32_t m_sdna_index;
__int32_t m_structure_count;
__int64_t m_prev_pointer;
unsigned char *m_data;
unsigned char* m_data;
};
private:
enum file_type {
enum file_type
{
KRBLEND_LITTLEENDIAN_32BIT,
KRBLEND_LITTLEENDIAN_64BIT,
KRBLEND_BIGENDIAN_32BIT,
KRBLEND_BIGENDIAN_64BIT
} m_file_type;
void readHeader(unsigned char *&scan);
void readHeader(unsigned char*& scan);
__int32_t readInt(unsigned char *&scan);
__int64_t readPointer(unsigned char *&scan);
__int32_t readInt(unsigned char*& scan);
__int64_t readPointer(unsigned char*& scan);
std::vector<Block> m_blocks;
};

File diff suppressed because it is too large Load Diff

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