This commit is contained in:
2017-11-05 17:22:46 -08:00
104 changed files with 4272 additions and 3750 deletions

1
.gitignore vendored
View File

@@ -1,2 +1,3 @@
Kraken.xcodeproj/xcuserdata
kraken_win/build/
build/

34
.travis.yml Normal file
View File

@@ -0,0 +1,34 @@
language: cpp
compiler: clang
branches:
only:
- master
matrix:
include:
- os: linux
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- libc++-dev
- os: osx
osx_image: xcode9.1
# Build steps
script:
- mkdir build
- cd build
- cmake .. && make
- cd archive
- tar cvzf kraken-$TRAVIS_OS_NAME-$TRAVIS_TAG.tar.gz *
deploy:
provider: releases
api_key: $GITHUB_TOKEN
file: build/archive/kraken-$TRAVIS_OS_NAME-$TRAVIS_TAG.tar.gz
skip_cleanup: true
on:
tags: true

87
CMakeLists.txt Normal file
View File

@@ -0,0 +1,87 @@
cmake_minimum_required (VERSION 2.6)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
if (NOT WIN32)
set(CMAKE_CXX_COMPILER "clang++")
endif()
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -stdlib=libc++ -lc++abi")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
project (Kraken)
macro (add_sources)
file (RELATIVE_PATH _relPath "${PROJECT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}")
foreach (_src ${ARGN})
if (_relPath)
list (APPEND SRCS "${_relPath}/${_src}")
else()
list (APPEND SRCS "${_src}")
endif()
endforeach()
if (_relPath)
# propagate SRCS to parent directory
set (SRCS ${SRCS} PARENT_SCOPE)
endif()
endmacro()
macro (add_public_header)
file (RELATIVE_PATH _relPath "${PROJECT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}")
foreach (_src ${ARGN})
if (_relPath)
list (APPEND KRAKEN_PUBLIC_HEADERS "${_relPath}/${_src}")
else()
list (APPEND KRAKEN_PUBLIC_HEADERS "${_src}")
endif()
endforeach()
if (_relPath)
# propagate KRAKEN_PUBLIC_HEADERS to parent directory
set (KRAKEN_PUBLIC_HEADERS ${KRAKEN_PUBLIC_HEADERS} PARENT_SCOPE)
endif()
endmacro()
IF(APPLE)
# SET(GUI_TYPE MACOSX_BUNDLE)
# INCLUDE_DIRECTORIES ( /Developer/Headers/FlatCarbon )
FIND_LIBRARY(OPENGL_LIBRARY OpenGL)
FIND_LIBRARY(AUDIO_TOOLBOX_LIBRARY AudioToolbox)
MARK_AS_ADVANCED (OPENGL_LIBRARY
AUDIO_TOOLBOX_LIBRARY)
SET(EXTRA_LIBS ${OPENGL_LIBRARY} ${AUDIO_TOOLBOX_LIBRARY})
FIND_PATH(COCOA_INCLUDE_DIR OpenGL/gl3.h)
ENDIF (APPLE)
add_subdirectory(kraken)
add_library(kraken STATIC ${SRCS} ${KRAKEN_PUBLIC_HEADERS})
TARGET_LINK_LIBRARIES( kraken ${EXTRA_LIBS} )
SET_TARGET_PROPERTIES(
kraken
PROPERTIES
FRAMEWORK ON
SOVERSION 0
VERSION 0.1.0
PUBLIC_HEADER "${KRAKEN_PUBLIC_HEADERS}"
PRIVATE_HEADER "${PRIVATE_HEADER_FILES}"
ARCHIVE_OUTPUT_DIRECTORY "archive"
LIBRARY_OUTPUT_DIRECTORY "lib"
OUTPUT_NAME kraken
)
set(Boost_USE_STATIC_LIBS ON) # only find static libs
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
find_package(Boost 1.65.1)
if(Boost_FOUND)
include_directories(${Boost_INCLUDE_DIRS})
target_link_libraries(kraken ${Boost_LIBRARIES})
endif()
# add_custom_target(package
# COMMENT "Compressing..."
# WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/archive"
# COMMAND ${CMAKE_COMMAND} -E tar "cfvz" "kraken.tgz" "*"
# )

16
kraken/CMakeLists.txt Normal file
View File

@@ -0,0 +1,16 @@
include_directories(public)
add_subdirectory(public)
set(KRAKEN_PUBLIC_HEADERS "${KRAKEN_PUBLIC_HEADERS}" PARENT_SCOPE)
add_sources(scalar.cpp)
add_sources(vector2.cpp)
add_sources(vector3.cpp)
add_sources(vector4.cpp)
add_sources(triangle3.cpp)
add_sources(quaternion.cpp)
add_sources(matrix4.cpp)
add_sources(aabb.cpp)
add_sources(hitinfo.cpp)
# Private Implementation
add_sources(KRDataBlock.cpp)

View File

@@ -1,73 +0,0 @@
//
// KRAABB.h
// KREngine
//
// Created by Kearwood Gilbert on 2012-08-30.
// Copyright (c) 2012 Kearwood Software. All rights reserved.
//
// Axis aligned bounding box
#ifndef KRAABB_H
#define KRAABB_H
#include "KRVector3.h"
class KRMat4;
class KRVector2;
class KRAABB {
public:
KRAABB(const KRVector3 &minPoint, const KRVector3 &maxPoint);
KRAABB(const KRVector3 &corner1, const KRVector3 &corner2, const KRMat4 &modelMatrix);
KRAABB();
~KRAABB();
void scale(const KRVector3 &s);
void scale(float s);
KRVector3 center() const;
KRVector3 size() const;
float volume() const;
bool intersects(const KRAABB& b) const;
bool contains(const KRAABB &b) const;
bool contains(const KRVector3 &v) const;
bool intersectsLine(const KRVector3 &v1, const KRVector3 &v2) const;
bool intersectsRay(const KRVector3 &v1, const KRVector3 &dir) const;
bool intersectsSphere(const KRVector3 &center, float radius) const;
void encapsulate(const KRAABB & b);
KRAABB& operator =(const KRAABB& b);
bool operator ==(const KRAABB& b) const;
bool operator !=(const KRAABB& b) const;
// Comparison operators are implemented to allow insertion into sorted containers such as std::set
bool operator >(const KRAABB& b) const;
bool operator <(const KRAABB& b) const;
KRVector3 min;
KRVector3 max;
static KRAABB Infinite();
static KRAABB Zero();
float longest_radius() const;
KRVector3 nearestPoint(const KRVector3 & v) const;
};
namespace std {
template<>
struct hash<KRAABB> {
public:
size_t operator()(const KRAABB &s) const
{
size_t h1 = hash<KRVector3>()(s.min);
size_t h2 = hash<KRVector3>()(s.max);
return h1 ^ ( h2 << 1 );
}
};
}
#endif /* defined(KRAABB_H) */

View File

@@ -94,11 +94,11 @@ void KRAmbientZone::render(KRCamera *pCamera, std::vector<KRPointLight *> &point
bool bVisualize = pCamera->settings.debug_display == KRRenderSettings::KRENGINE_DEBUG_DISPLAY_SIREN_AMBIENT_ZONES;
if(renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT && bVisualize) {
KRMat4 sphereModelMatrix = getModelMatrix();
Matrix4 sphereModelMatrix = getModelMatrix();
KRShader *pShader = getContext().getShaderManager()->getShader("visualize_overlay", pCamera, point_lights, directional_lights, spot_lights, 0, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, renderPass);
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, sphereModelMatrix, point_lights, directional_lights, spot_lights, 0, renderPass, KRVector3::Zero(), 0.0f, KRVector4::Zero())) {
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, sphereModelMatrix, point_lights, directional_lights, spot_lights, 0, renderPass, Vector3::Zero(), 0.0f, Vector4::Zero())) {
// Enable additive blending
GLDEBUG(glEnable(GL_BLEND));
@@ -137,19 +137,19 @@ void KRAmbientZone::setGradientDistance(float gradient_distance)
m_gradient_distance = gradient_distance;
}
KRAABB KRAmbientZone::getBounds() {
AABB KRAmbientZone::getBounds() {
// Ambient zones always have a -1, -1, -1 to 1, 1, 1 bounding box
return KRAABB(-KRVector3::One(), KRVector3::One(), getModelMatrix());
return AABB(-Vector3::One(), Vector3::One(), getModelMatrix());
}
float KRAmbientZone::getContainment(const KRVector3 &pos)
float KRAmbientZone::getContainment(const Vector3 &pos)
{
KRAABB bounds = getBounds();
AABB bounds = getBounds();
if(bounds.contains(pos)) {
KRVector3 size = bounds.size();
KRVector3 diff = pos - bounds.center();
Vector3 size = bounds.size();
Vector3 diff = pos - bounds.center();
diff = diff * 2.0f;
diff = KRVector3(diff.x / size.x, diff.y / size.y, diff.z / size.z);
diff = Vector3(diff.x / size.x, diff.y / size.y, diff.z / size.z);
float d = diff.magnitude();
if(m_gradient_distance <= 0.0f) {

View File

@@ -35,9 +35,9 @@ public:
float getAmbientGain();
void setAmbientGain(float ambient_gain);
virtual KRAABB getBounds();
virtual AABB getBounds();
float getContainment(const KRVector3 &pos);
float getContainment(const Vector3 &pos);
private:
std::string m_zone;

View File

@@ -20,22 +20,22 @@ class KRAudioBuffer
public:
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();
KRAudioSample *getAudioSample();
int getIndex();
private:
KRAudioManager *m_pSoundManager;
int m_index;
int m_frameCount;
int m_frameCount;
int m_frameRate;
int m_bytesPerFrame;
KRDataBlock *m_pData;
KRAudioSample *m_audioSample;
};

File diff suppressed because it is too large Load Diff

View File

@@ -36,7 +36,6 @@
#include "KRContextObject.h"
#include "KRDataBlock.h"
#include "KRMat4.h"
#include "KRAudioSource.h"
#include "KRDSP.h"
@@ -106,11 +105,11 @@ public:
// Listener position and orientation
KRScene *getListenerScene();
void setListenerScene(KRScene *scene);
void setListenerOrientation(const KRVector3 &position, const KRVector3 &forward, const KRVector3 &up);
void setListenerOrientationFromModelMatrix(const KRMat4 &modelMatrix);
KRVector3 &getListenerForward();
KRVector3 &getListenerPosition();
KRVector3 &getListenerUp();
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
@@ -167,9 +166,9 @@ private:
float m_global_ambient_gain;
float m_global_gain;
KRVector3 m_listener_position;
KRVector3 m_listener_forward;
KRVector3 m_listener_up;
Vector3 m_listener_position;
Vector3 m_listener_forward;
Vector3 m_listener_up;
unordered_map<std::string, KRAudioSample *> m_sounds;
@@ -224,14 +223,14 @@ private:
void renderReverbImpulseResponse(int impulse_response_offset, int frame_count_log2);
void renderLimiter();
std::vector<KRVector2> m_hrtf_sample_locations;
std::vector<Vector2> m_hrtf_sample_locations;
float *m_hrtf_data;
unordered_map<KRVector2, KRDSP::SplitComplex> m_hrtf_spectral[2];
unordered_map<Vector2, KRDSP::SplitComplex> m_hrtf_spectral[2];
KRVector2 getNearestHRTFSample(const KRVector2 &dir);
void getHRTFMix(const KRVector2 &dir, KRVector2 &hrtf1, KRVector2 &hrtf2, KRVector2 &hrtf3, KRVector2 &hrtf4, float &mix1, float &mix2, float &mix3, float &mix4);
KRAudioSample *getHRTFSample(const KRVector2 &hrtf_dir);
KRDSP::SplitComplex getHRTFSpectral(const KRVector2 &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
@@ -245,7 +244,7 @@ private:
#endif
unordered_multimap<KRVector2, 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

@@ -178,11 +178,11 @@ void KRAudioSource::render(KRCamera *pCamera, std::vector<KRPointLight *> &point
bool bVisualize = false;
if(renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT && bVisualize) {
KRMat4 sphereModelMatrix = getModelMatrix();
Matrix4 sphereModelMatrix = getModelMatrix();
KRShader *pShader = getContext().getShaderManager()->getShader("visualize_overlay", pCamera, point_lights, directional_lights, spot_lights, 0, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, renderPass);
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, sphereModelMatrix, point_lights, directional_lights, spot_lights, 0, renderPass, KRVector3::Zero(), 0.0f, KRVector4::Zero())) {
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, sphereModelMatrix, point_lights, directional_lights, spot_lights, 0, renderPass, Vector3::Zero(), 0.0f, Vector4::Zero())) {
// Enable additive blending
GLDEBUG(glEnable(GL_BLEND));

View File

@@ -14,7 +14,7 @@
/*
This class is a pure-virtual base class intended to be subclassed to define behavior of KRNode's in the scene
*/
class KRBehavior;
@@ -31,16 +31,16 @@ class KRBehavior
public:
static void RegisterFactoryCTOR(std::string behaviorName, KRBehaviorFactoryFunction fnFactory);
static void UnregisterFactoryCTOR(std::string behaviorName);
KRBehavior();
virtual ~KRBehavior();
KRNode *getNode() const;
virtual void init();
virtual void update(float deltaTime) = 0;
virtual void visibleUpdate(float deltatime) = 0;
void __setNode(KRNode *node);
static KRBehavior *LoadXML(KRNode *node, tinyxml2::XMLElement *e);
private:
KRNode *__node;

View File

@@ -35,8 +35,8 @@ void KRBone::loadXML(tinyxml2::XMLElement *e)
setScaleCompensation(true);
}
KRAABB KRBone::getBounds() {
return KRAABB(-KRVector3::One(), KRVector3::One(), getModelMatrix()); // Only required for bone debug visualization
AABB KRBone::getBounds() {
return AABB(-Vector3::One(), Vector3::One(), getModelMatrix()); // Only required for bone debug visualization
}
void KRBone::render(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, KRNode::RenderPass renderPass)
@@ -48,7 +48,7 @@ void KRBone::render(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights
bool bVisualize = pCamera->settings.debug_display == KRRenderSettings::KRENGINE_DEBUG_DISPLAY_BONES;
if(renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT && bVisualize) {
KRMat4 sphereModelMatrix = getModelMatrix();
Matrix4 sphereModelMatrix = getModelMatrix();
// Enable additive blending
GLDEBUG(glEnable(GL_BLEND));
@@ -63,7 +63,7 @@ void KRBone::render(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights
KRShader *pShader = getContext().getShaderManager()->getShader("visualize_overlay", pCamera, point_lights, directional_lights, spot_lights, 0, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, renderPass);
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, sphereModelMatrix, point_lights, directional_lights, spot_lights, 0, renderPass, KRVector3::Zero(), 0.0f, KRVector4::Zero())) {
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, sphereModelMatrix, point_lights, directional_lights, spot_lights, 0, renderPass, Vector3::Zero(), 0.0f, Vector4::Zero())) {
std::vector<KRMesh *> sphereModels = getContext().getMeshManager()->getModel("__sphere");
if(sphereModels.size()) {
for(int i=0; i < sphereModels[0]->getSubmeshCount(); i++) {
@@ -87,11 +87,11 @@ void KRBone::render(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights
}
void KRBone::setBindPose(const KRMat4 &pose)
void KRBone::setBindPose(const Matrix4 &pose)
{
m_bind_pose = pose;
}
const KRMat4 &KRBone::getBindPose()
const Matrix4 &KRBone::getBindPose()
{
return m_bind_pose;
}

View File

@@ -20,14 +20,14 @@ public:
virtual std::string getElementName();
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual void loadXML(tinyxml2::XMLElement *e);
virtual KRAABB getBounds();
virtual AABB getBounds();
void render(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, KRNode::RenderPass renderPass);
void setBindPose(const KRMat4 &pose);
const KRMat4 &getBindPose();
void setBindPose(const Matrix4 &pose);
const Matrix4 &getBindPose();
private:
KRMat4 m_bind_pose;
Matrix4 m_bind_pose;
};

View File

@@ -30,7 +30,6 @@
//
#include "KREngine-common.h"
#include "KRVector2.h"
#include "KRCamera.h"
#include "KRStockGeometry.h"
#include "KRDirectionalLight.h"
@@ -54,9 +53,9 @@ KRCamera::KRCamera(KRScene &scene, std::string name) : KRNode(scene, name) {
volumetricLightAccumulationBuffer = 0;
volumetricLightAccumulationTexture = 0;
m_frame_times_filled = 0;
m_downsample = KRVector2::One();
m_downsample = Vector2::One();
m_fade_color = KRVector4::Zero();
m_fade_color = Vector4::Zero();
}
KRCamera::~KRCamera() {
@@ -109,18 +108,18 @@ void KRCamera::renderFrame(GLint defaultFBO, GLint renderBufferWidth, GLint rend
KRScene &scene = getScene();
KRMat4 modelMatrix = getModelMatrix();
KRMat4 viewMatrix = KRMat4::LookAt(KRMat4::Dot(modelMatrix, KRVector3::Zero()), KRMat4::Dot(modelMatrix, KRVector3::Forward()), KRVector3::Normalize(KRMat4::DotNoTranslate(modelMatrix, KRVector3::Up())));
Matrix4 modelMatrix = getModelMatrix();
Matrix4 viewMatrix = Matrix4::LookAt(Matrix4::Dot(modelMatrix, Vector3::Zero()), Matrix4::Dot(modelMatrix, Vector3::Forward()), Vector3::Normalize(Matrix4::DotNoTranslate(modelMatrix, Vector3::Up())));
//KRMat4 viewMatrix = KRMat4::Invert(getModelMatrix());
//Matrix4 viewMatrix = Matrix4::Invert(getModelMatrix());
settings.setViewportSize(KRVector2(m_backingWidth, m_backingHeight));
KRMat4 projectionMatrix;
settings.setViewportSize(Vector2(m_backingWidth, m_backingHeight));
Matrix4 projectionMatrix;
projectionMatrix.perspective(settings.perspective_fov, settings.m_viewportSize.x / settings.m_viewportSize.y, settings.perspective_nearz, settings.perspective_farz);
m_viewport = KRViewport(settings.getViewportSize(), viewMatrix, projectionMatrix);
m_viewport.setLODBias(settings.getLODBias());
KRVector3 vecCameraDirection = m_viewport.getCameraDirection();
Vector3 vecCameraDirection = m_viewport.getCameraDirection();
scene.updateOctree(m_viewport);
@@ -313,7 +312,7 @@ void KRCamera::renderFrame(GLint defaultFBO, GLint renderBufferWidth, GLint rend
}
if(m_pSkyBoxTexture) {
getContext().getShaderManager()->selectShader("sky_box", *this, std::vector<KRPointLight *>(), std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, m_viewport, KRMat4(), false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, KRNode::RENDER_PASS_FORWARD_OPAQUE, KRVector3::Zero(), 0.0f, KRVector4::Zero());
getContext().getShaderManager()->selectShader("sky_box", *this, std::vector<KRPointLight *>(), std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, m_viewport, Matrix4(), false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, KRNode::RENDER_PASS_FORWARD_OPAQUE, Vector3::Zero(), 0.0f, Vector4::Zero());
getContext().getTextureManager()->selectTexture(0, m_pSkyBoxTexture, 0.0f, KRTexture::TEXTURE_USAGE_SKY_CUBE);
@@ -420,7 +419,7 @@ void KRCamera::renderFrame(GLint defaultFBO, GLint renderBufferWidth, GLint rend
GL_PUSH_GROUP_MARKER("Volumetric Lighting");
KRViewport volumetricLightingViewport = KRViewport(KRVector2(volumetricBufferWidth, volumetricBufferHeight), m_viewport.getViewMatrix(), m_viewport.getProjectionMatrix());
KRViewport volumetricLightingViewport = KRViewport(Vector2(volumetricBufferWidth, volumetricBufferHeight), m_viewport.getViewMatrix(), m_viewport.getProjectionMatrix());
if(settings.volumetric_environment_downsample != 0) {
// Set render target
@@ -477,11 +476,11 @@ void KRCamera::renderFrame(GLint defaultFBO, GLint renderBufferWidth, GLint rend
KRShader *pVisShader = getContext().getShaderManager()->getShader("visualize_overlay", this, std::vector<KRPointLight *>(), std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, KRNode::RENDER_PASS_FORWARD_TRANSPARENT);
m_pContext->getMeshManager()->bindVBO(&getContext().getMeshManager()->KRENGINE_VBO_DATA_3D_CUBE_VERTICES, 1.0f);
for(unordered_map<KRAABB, int>::iterator itr=m_viewport.getVisibleBounds().begin(); itr != m_viewport.getVisibleBounds().end(); itr++) {
KRMat4 matModel = KRMat4();
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());
if(getContext().getShaderManager()->selectShader(*this, pVisShader, m_viewport, matModel, std::vector<KRPointLight *>(), std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, KRNode::RENDER_PASS_FORWARD_TRANSPARENT, KRVector3::Zero(), 0.0f, KRVector4::Zero())) {
if(getContext().getShaderManager()->selectShader(*this, pVisShader, m_viewport, matModel, std::vector<KRPointLight *>(), std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, KRNode::RENDER_PASS_FORWARD_TRANSPARENT, Vector3::Zero(), 0.0f, Vector4::Zero())) {
GLDEBUG(glDrawArrays(GL_TRIANGLE_STRIP, 0, 14));
}
}
@@ -695,8 +694,8 @@ void KRCamera::renderPost()
GLDEBUG(glDisable(GL_DEPTH_TEST));
KRShader *postShader = m_pContext->getShaderManager()->getShader("PostShader", this, std::vector<KRPointLight *>(), std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, KRNode::RENDER_PASS_FORWARD_TRANSPARENT);
KRVector3 rim_color;
getContext().getShaderManager()->selectShader(*this, postShader, m_viewport, KRMat4(), std::vector<KRPointLight *>(), std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, KRNode::RENDER_PASS_FORWARD_TRANSPARENT, rim_color, 0.0f, m_fade_color);
Vector3 rim_color;
getContext().getShaderManager()->selectShader(*this, postShader, m_viewport, Matrix4(), std::vector<KRPointLight *>(), std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, KRNode::RENDER_PASS_FORWARD_TRANSPARENT, rim_color, 0.0f, m_fade_color);
m_pContext->getTextureManager()->selectTexture(GL_TEXTURE_2D, 0, compositeDepthTexture);
m_pContext->getTextureManager()->selectTexture(GL_TEXTURE_2D, 1, compositeColorTexture);
@@ -718,10 +717,10 @@ void KRCamera::renderPost()
// KRShader *blitShader = m_pContext->getShaderManager()->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++) {
// KRMat4 viewMatrix = KRMat4();
// Matrix4 viewMatrix = Matrix4();
// viewMatrix.scale(0.20, 0.20, 0.20);
// viewMatrix.translate(-0.70, 0.70 - 0.45 * iShadow, 0.0);
// getContext().getShaderManager()->selectShader(blitShader, KRViewport(getViewportSize(), viewMatrix, KRMat4()), shadowViewports, KRMat4(), KRVector3(), NULL, 0, KRNode::RENDER_PASS_FORWARD_TRANSPARENT);
// getContext().getShaderManager()->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);
@@ -809,12 +808,12 @@ void KRCamera::renderPost()
int iTexCol = iChar % 16;
int iTexRow = 15 - (iChar - iTexCol) / 16;
KRVector2 top_left_pos = KRVector2(-1.0f + dScaleX * iCol, dScaleY * iRow - 1.0);
KRVector2 bottom_right_pos = KRVector2(-1.0 + dScaleX * (iCol + 1), dScaleY * iRow + dScaleY - 1.0);
top_left_pos += KRVector2(1.0f / 2048.0f * 0.5f, 1.0f / 1536.0f * 0.5f);
bottom_right_pos += KRVector2(1.0f / 2048.0f * 0.5f, 1.0f / 1536.0f * 0.5f);
KRVector2 top_left_uv = KRVector2(dTexScale * iTexCol, dTexScale * iTexRow);
KRVector2 bottom_right_uv = KRVector2(dTexScale * iTexCol + dTexScale, dTexScale * iTexRow + dTexScale);
Vector2 top_left_pos = Vector2(-1.0f + dScaleX * iCol, dScaleY * iRow - 1.0);
Vector2 bottom_right_pos = Vector2(-1.0 + dScaleX * (iCol + 1), dScaleY * iRow + dScaleY - 1.0);
top_left_pos += Vector2(1.0f / 2048.0f * 0.5f, 1.0f / 1536.0f * 0.5f);
bottom_right_pos += Vector2(1.0f / 2048.0f * 0.5f, 1.0f / 1536.0f * 0.5f);
Vector2 top_left_uv = Vector2(dTexScale * iTexCol, dTexScale * iTexRow);
Vector2 bottom_right_uv = Vector2(dTexScale * iTexCol + dTexScale, dTexScale * iTexRow + dTexScale);
vertex_data[vertex_count].x = top_left_pos.x;
vertex_data[vertex_count].y = top_left_pos.y;
@@ -880,7 +879,7 @@ void KRCamera::renderPost()
GLDEBUG(glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA));
KRShader *fontShader = m_pContext->getShaderManager()->getShader("debug_font", this, std::vector<KRPointLight *>(), std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, KRNode::RENDER_PASS_FORWARD_TRANSPARENT);
getContext().getShaderManager()->selectShader(*this, fontShader, m_viewport, KRMat4(), std::vector<KRPointLight *>(), std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, KRNode::RENDER_PASS_FORWARD_TRANSPARENT, KRVector3::Zero(), 0.0f, KRVector4::Zero());
getContext().getShaderManager()->selectShader(*this, fontShader, m_viewport, Matrix4(), std::vector<KRPointLight *>(), std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, KRNode::RENDER_PASS_FORWARD_TRANSPARENT, Vector3::Zero(), 0.0f, Vector4::Zero());
m_pContext->getTextureManager()->selectTexture(0, m_pContext->getTextureManager()->getTexture("font"), 0.0f, KRTexture::TEXTURE_USAGE_UI);
@@ -1097,7 +1096,7 @@ const KRViewport &KRCamera::getViewport() const
}
KRVector2 KRCamera::getDownsample()
Vector2 KRCamera::getDownsample()
{
return m_downsample;
}
@@ -1107,12 +1106,12 @@ void KRCamera::setDownsample(float v)
m_downsample = v;
}
void KRCamera::setFadeColor(const KRVector4 &fade_color)
void KRCamera::setFadeColor(const Vector4 &fade_color)
{
m_fade_color = fade_color;
}
KRVector4 KRCamera::getFadeColor()
Vector4 KRCamera::getFadeColor()
{
return m_fade_color;
}

View File

@@ -34,9 +34,6 @@
#include "KREngine-common.h"
#include "KRMat4.h"
#include "KRVector2.h"
#include "KRAABB.h"
#include "KRShader.h"
#include "KRContextObject.h"
#include "KRTexture.h"
@@ -69,11 +66,11 @@ public:
std::string getDebugText();
void flushSkybox(); // this will delete the skybox and cause the camera to reload a new skybox based on the settings
KRVector2 getDownsample();
Vector2 getDownsample();
void setDownsample(float v);
void setFadeColor(const KRVector4 &fade_color);
KRVector4 getFadeColor();
void setFadeColor(const Vector4 &fade_color);
Vector4 getFadeColor();
void setSkyBox(const std::string &skyBox);
const std::string getSkyBox() const;
@@ -100,9 +97,9 @@ private:
float m_particlesAbsoluteTime;
KRVector2 m_downsample;
Vector2 m_downsample;
KRVector4 m_fade_color;
Vector4 m_fade_color;
typedef struct {
GLfloat x;

View File

@@ -33,7 +33,6 @@
#include "KRCollider.h"
#include "KRContext.h"
#include "KRMesh.h"
#include "KRQuaternion.h"
KRCollider::KRCollider(KRScene &scene, std::string collider_name, std::string model_name, unsigned int layer_mask, float audio_occlusion) : KRNode(scene, collider_name) {
@@ -84,32 +83,32 @@ void KRCollider::loadModel() {
}
}
KRAABB KRCollider::getBounds() {
AABB KRCollider::getBounds() {
loadModel();
if(m_models.size() > 0) {
return KRAABB(m_models[0]->getMinPoint(), m_models[0]->getMaxPoint(), getModelMatrix());
return AABB(m_models[0]->getMinPoint(), m_models[0]->getMaxPoint(), getModelMatrix());
} else {
return KRAABB::Infinite();
return AABB::Infinite();
}
}
bool KRCollider::lineCast(const KRVector3 &v0, const KRVector3 &v1, KRHitInfo &hitinfo, unsigned int layer_mask)
bool KRCollider::lineCast(const Vector3 &v0, const Vector3 &v1, KRHitInfo &hitinfo, unsigned int layer_mask)
{
if(layer_mask & m_layer_mask ) { // Only test if layer masks have a common bit set
loadModel();
if(m_models.size()) {
if(getBounds().intersectsLine(v0, v1)) {
KRVector3 v0_model_space = KRMat4::Dot(getInverseModelMatrix(), v0);
KRVector3 v1_model_space = KRMat4::Dot(getInverseModelMatrix(), v1);
Vector3 v0_model_space = Matrix4::Dot(getInverseModelMatrix(), v0);
Vector3 v1_model_space = Matrix4::Dot(getInverseModelMatrix(), v1);
KRHitInfo hitinfo_model_space;
if(hitinfo.didHit()) {
KRVector3 hit_position_model_space = KRMat4::Dot(getInverseModelMatrix(), hitinfo.getPosition());
hitinfo_model_space = KRHitInfo(hit_position_model_space, KRMat4::DotNoTranslate(getInverseModelMatrix(), hitinfo.getNormal()), (hit_position_model_space - v0_model_space).magnitude(), hitinfo.getNode());
Vector3 hit_position_model_space = Matrix4::Dot(getInverseModelMatrix(), hitinfo.getPosition());
hitinfo_model_space = KRHitInfo(hit_position_model_space, Matrix4::DotNoTranslate(getInverseModelMatrix(), hitinfo.getNormal()), (hit_position_model_space - v0_model_space).magnitude(), hitinfo.getNode());
}
if(m_models[0]->lineCast(v0_model_space, v1_model_space, hitinfo_model_space)) {
KRVector3 hit_position_world_space = KRMat4::Dot(getModelMatrix(), hitinfo_model_space.getPosition());
hitinfo = KRHitInfo(hit_position_world_space, KRVector3::Normalize(KRMat4::DotNoTranslate(getModelMatrix(), hitinfo_model_space.getNormal())), (hit_position_world_space - v0).magnitude(), this);
Vector3 hit_position_world_space = Matrix4::Dot(getModelMatrix(), hitinfo_model_space.getPosition());
hitinfo = KRHitInfo(hit_position_world_space, Vector3::Normalize(Matrix4::DotNoTranslate(getModelMatrix(), hitinfo_model_space.getNormal())), (hit_position_world_space - v0).magnitude(), this);
return true;
}
}
@@ -118,23 +117,23 @@ bool KRCollider::lineCast(const KRVector3 &v0, const KRVector3 &v1, KRHitInfo &h
return false;
}
bool KRCollider::rayCast(const KRVector3 &v0, const KRVector3 &dir, KRHitInfo &hitinfo, unsigned int layer_mask)
bool KRCollider::rayCast(const Vector3 &v0, const Vector3 &dir, KRHitInfo &hitinfo, unsigned int layer_mask)
{
if(layer_mask & m_layer_mask) { // Only test if layer masks have a common bit set
loadModel();
if(m_models.size()) {
if(getBounds().intersectsRay(v0, dir)) {
KRVector3 v0_model_space = KRMat4::Dot(getInverseModelMatrix(), v0);
KRVector3 dir_model_space = KRVector3::Normalize(KRMat4::DotNoTranslate(getInverseModelMatrix(), dir));
Vector3 v0_model_space = Matrix4::Dot(getInverseModelMatrix(), v0);
Vector3 dir_model_space = Vector3::Normalize(Matrix4::DotNoTranslate(getInverseModelMatrix(), dir));
KRHitInfo hitinfo_model_space;
if(hitinfo.didHit()) {
KRVector3 hit_position_model_space = KRMat4::Dot(getInverseModelMatrix(), hitinfo.getPosition());
hitinfo_model_space = KRHitInfo(hit_position_model_space, KRVector3::Normalize(KRMat4::DotNoTranslate(getInverseModelMatrix(), hitinfo.getNormal())), (hit_position_model_space - v0_model_space).magnitude(), hitinfo.getNode());
Vector3 hit_position_model_space = Matrix4::Dot(getInverseModelMatrix(), hitinfo.getPosition());
hitinfo_model_space = KRHitInfo(hit_position_model_space, Vector3::Normalize(Matrix4::DotNoTranslate(getInverseModelMatrix(), hitinfo.getNormal())), (hit_position_model_space - v0_model_space).magnitude(), hitinfo.getNode());
}
if(m_models[0]->rayCast(v0_model_space, dir_model_space, hitinfo_model_space)) {
KRVector3 hit_position_world_space = KRMat4::Dot(getModelMatrix(), hitinfo_model_space.getPosition());
hitinfo = KRHitInfo(hit_position_world_space, KRVector3::Normalize(KRMat4::DotNoTranslate(getModelMatrix(), hitinfo_model_space.getNormal())), (hit_position_world_space - v0).magnitude(), this);
Vector3 hit_position_world_space = Matrix4::Dot(getModelMatrix(), hitinfo_model_space.getPosition());
hitinfo = KRHitInfo(hit_position_world_space, Vector3::Normalize(Matrix4::DotNoTranslate(getModelMatrix(), hitinfo_model_space.getNormal())), (hit_position_world_space - v0).magnitude(), this);
return true;
}
}
@@ -143,14 +142,14 @@ bool KRCollider::rayCast(const KRVector3 &v0, const KRVector3 &dir, KRHitInfo &h
return false;
}
bool KRCollider::sphereCast(const KRVector3 &v0, const KRVector3 &v1, float radius, KRHitInfo &hitinfo, unsigned int layer_mask)
bool KRCollider::sphereCast(const Vector3 &v0, const Vector3 &v1, float radius, KRHitInfo &hitinfo, unsigned int layer_mask)
{
if(layer_mask & m_layer_mask) { // Only test if layer masks have a common bit set
loadModel();
if(m_models.size()) {
KRAABB sphereCastBounds = KRAABB( // TODO - Need to cache this; perhaps encasulate within a "spherecast" class to be passed through these functions
KRVector3(KRMIN(v0.x, v1.x) - radius, KRMIN(v0.y, v1.y) - radius, KRMIN(v0.z, v1.z) - radius),
KRVector3(KRMAX(v0.x, v1.x) + radius, KRMAX(v0.y, v1.y) + radius, KRMAX(v0.z, v1.z) + radius)
AABB sphereCastBounds = AABB( // TODO - Need to cache this; perhaps encasulate within a "spherecast" class to be passed through these functions
Vector3(KRMIN(v0.x, v1.x) - radius, KRMIN(v0.y, v1.y) - radius, KRMIN(v0.z, v1.z) - radius),
Vector3(KRMAX(v0.x, v1.x) + radius, KRMAX(v0.y, v1.y) + radius, KRMAX(v0.z, v1.z) + radius)
);
if(getBounds().intersects(sphereCastBounds)) {
@@ -199,7 +198,7 @@ void KRCollider::render(KRCamera *pCamera, std::vector<KRPointLight *> &point_li
KRShader *pShader = getContext().getShaderManager()->getShader("visualize_overlay", pCamera, point_lights, directional_lights, spot_lights, 0, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, renderPass);
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, getModelMatrix(), point_lights, directional_lights, spot_lights, 0, renderPass, KRVector3::Zero(), 0.0f, KRVector4::Zero())) {
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, getModelMatrix(), point_lights, directional_lights, spot_lights, 0, renderPass, Vector3::Zero(), 0.0f, Vector4::Zero())) {
// Enable additive blending
GLDEBUG(glEnable(GL_BLEND));

View File

@@ -38,8 +38,6 @@
#define KRAKEN_COLLIDER_AUDIO 2
#include "KRMesh.h"
#include "KRMat4.h"
#include "KRVector3.h"
#include "KRModel.h"
#include "KRCamera.h"
#include "KRMeshManager.h"
@@ -57,11 +55,11 @@ public:
virtual std::string getElementName();
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual void loadXML(tinyxml2::XMLElement *e);
virtual KRAABB getBounds();
virtual AABB getBounds();
bool lineCast(const KRVector3 &v0, const KRVector3 &v1, KRHitInfo &hitinfo, unsigned int layer_mask);
bool rayCast(const KRVector3 &v0, const KRVector3 &v1, KRHitInfo &hitinfo, unsigned int layer_mask);
bool sphereCast(const KRVector3 &v0, const KRVector3 &v1, float radius, KRHitInfo &hitinfo, unsigned int layer_mask);
bool lineCast(const Vector3 &v0, const Vector3 &v1, KRHitInfo &hitinfo, unsigned int layer_mask);
bool rayCast(const Vector3 &v0, const Vector3 &v1, KRHitInfo &hitinfo, unsigned int layer_mask);
bool sphereCast(const Vector3 &v0, const Vector3 &v1, float radius, KRHitInfo &hitinfo, unsigned int layer_mask);
unsigned int getLayerMask();
void setLayerMask(unsigned int layer_mask);

View File

@@ -23,6 +23,8 @@ int KRContext::KRENGINE_GPU_MEM_TARGET;
int KRContext::KRENGINE_MAX_TEXTURE_DIM;
int KRContext::KRENGINE_MIN_TEXTURE_DIM;
int KRContext::KRENGINE_PRESTREAM_DISTANCE;
int KRContext::KRENGINE_SYS_ALLOCATION_GRANULARITY;
int KRContext::KRENGINE_SYS_PAGE_SIZE;
#if TARGET_OS_IPHONE
@@ -69,6 +71,24 @@ KRContext::KRContext() : m_streamer(*this)
m_pSoundManager = new KRAudioManager(*this);
m_pUnknownManager = new KRUnknownManager(*this);
m_streamingEnabled = true;
#if defined(_WIN32) || defined(_WIN64)
SYSTEM_INFO winSysInfo;
GetSystemInfo(&winSysInfo);
KRENGINE_SYS_ALLOCATION_GRANULARITY = winSysInfo.dwAllocationGranularity;
KRENGINE_SYS_PAGE_SIZE = winSysInfo.dwPageSize;
#elif defined(__APPLE__)
KRENGINE_SYS_PAGE_SIZE = getpagesize();
KRENGINE_SYS_ALLOCATION_GRANULARITY = KRENGINE_SYS_PAGE_SIZE;
#else
#error Unsupported
#endif
createDeviceContexts();
}
@@ -135,7 +155,7 @@ void KRContext::SetLogCallback(log_callback *log_callback, void *user_data)
s_log_callback_user_data = user_data;
}
void KRContext::Log(log_level level, const std::string &message_format, ...)
void KRContext::Log(log_level level, const std::string message_format, ...)
{
va_list args;
va_start(args, message_format);

View File

@@ -31,6 +31,8 @@ public:
static int KRENGINE_MAX_TEXTURE_DIM;
static int KRENGINE_MIN_TEXTURE_DIM;
static int KRENGINE_PRESTREAM_DISTANCE;
static int KRENGINE_SYS_ALLOCATION_GRANULARITY;
static int KRENGINE_SYS_PAGE_SIZE;
KRContext();
@@ -87,7 +89,7 @@ public:
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 Log(log_level level, const std::string &message_format, ...);
static void Log(log_level level, const std::string message_format, ...);
void doStreaming();
void receivedMemoryWarning();

View File

@@ -54,8 +54,9 @@ void FFTWorkspace::create(size_t length)
cos_table = new float[size];
sin_table = new float[size];
for (int i = 0; i < size / 2; i++) {
cos_table[i] = cos(2 * M_PI * i / length);
sin_table[i] = sin(2 * M_PI * i / length);
float a = 2 * M_PI * i / length;
cos_table[i] = cos(a);
sin_table[i] = sin(a);
}
}
@@ -73,27 +74,88 @@ void FFTWorkspace::destroy()
void FFTForward(const FFTWorkspace &workspace, SplitComplex *src, size_t count)
{
#error TODO - Implement
// Radix-2 Decimation in Time FFT Algorithm
// http://en.dsplib.org/content/fft_dec_in_time.html
// Only power-of-two sizes supported
assert((count & (count - 1)) == 0);
int levels = 0;
while (1 << levels <= count) {
levels++;
}
for (size_t i = 0; i < count; i++) {
size_t j = 0;
for (int k = 0; k < levels; k++) {
j <<= 1;
j |= ((i >> k) & 1);
}
if (j > i) {
float temp = src->realp[i];
src->realp[i] = src->realp[j];
src->realp[j] = temp;
temp = src->imagp[i];
src->imagp[i] = src->imagp[j];
src->imagp[j] = temp;
}
}
for (size_t size = 2; size <= count; size *= 2) {
size_t halfsize = size / 2;
size_t step = count / size;
for (size_t i = 0; i < count; i += size) {
for (size_t j = i, k = 0; j < i + halfsize; j++, k += step) {
float temp_real = src->realp[j + halfsize] * workspace.cos_table[k];
temp_real += src->imagp[j + halfsize] * workspace.sin_table[k];
float temp_imag = -src->realp[j + halfsize] * workspace.sin_table[k];
temp_imag += src->imagp[j + halfsize] * workspace.cos_table[k];
src->realp[j + halfsize] = src->realp[j] - temp_real;
src->imagp[j + halfsize] = src->imagp[j] - temp_imag;
src->realp[j] += temp_real;
src->imagp[j] += temp_imag;
}
}
}
}
void FFTInverse(const FFTWorkspace &workspace, SplitComplex *src, size_t count)
{
#error TODO - Implement
SplitComplex swapped;
swapped.imagp = src->realp;
swapped.realp = src->imagp;
FFTForward(workspace, &swapped, count);
}
void Int16ToFloat(const short *src, size_t srcStride, float *dest, size_t destStride, size_t count)
{
#error TODO - Implement
const short *r = src;
float *w = dest;
while (w < dest + destStride * count) {
*w = (float)*r;
r += srcStride;
w += destStride;
}
}
void Scale(float *buffer, float scale, size_t count)
{
#error TODO - Implement
float *w = buffer;
while (w < buffer + count) {
*w *= scale;
w++;
}
}
void ScaleCopy(const float *src, float scale, float *dest, size_t count)
{
#error TODO - Implement
const float *r = src;
float *w = dest;
while (w < dest + count) {
*w = *r * scale;
w++;
r++;
}
}
void ScaleCopy(const SplitComplex *src, float scale, SplitComplex *dest, size_t count)
@@ -104,23 +166,40 @@ void ScaleCopy(const SplitComplex *src, float scale, SplitComplex *dest, size_t
void ScaleRamp(float *buffer, float scaleStart, float scaleStep, size_t count)
{
#error TODO - Implement
float *w = buffer;
float s = scaleStart;
while (w < buffer + count) {
*w *= s;
w++;
s += scaleStep;
}
}
void Accumulate(float *buffer, size_t bufferStride, const float *buffer2, size_t buffer2Stride, size_t count)
{
#error TODO - Implement
float *w = buffer;
const float *r = buffer2;
while (w < buffer + bufferStride * count) {
*w *= *r;
w += bufferStride;
r += buffer2Stride;
}
}
void Accumulate(SplitComplex *buffer, const SplitComplex *buffer2, size_t count)
{
#error TODO - Implement
for (size_t i = 0; i < count; i++) {
buffer->imagp[i] += buffer2->imagp[i];
buffer->realp[i] += buffer2->realp[i];
}
}
void Multiply(const SplitComplex *a, const SplitComplex *b, SplitComplex *c, size_t count)
{
#error TODO - Implement
for (size_t i = 0; i < count; i++) {
c->realp[i] = a->realp[i] * b->realp[i] - a->imagp[i] * b->imagp[i];
c->imagp[i] = a->realp[i] * b->imagp[i] + a->imagp[i] * b->realp[i];
}
}
} // namespace KRDSP

View File

@@ -36,11 +36,8 @@
#include <errno.h>
#ifdef __APPLE__
int KRAKEN_MEM_PAGE_SIZE = getpagesize();
#define KRAKEN_MEM_ROUND_DOWN_PAGE(x) ((x) & ~(KRAKEN_MEM_PAGE_SIZE - 1))
#define KRAKEN_MEM_ROUND_UP_PAGE(x) ((((x) - 1) & ~(KRAKEN_MEM_PAGE_SIZE - 1)) + KRAKEN_MEM_PAGE_SIZE)
#endif
#define KRAKEN_MEM_ROUND_DOWN_PAGE(x) ((x) & ~(KRContext::KRENGINE_SYS_ALLOCATION_GRANULARITY - 1))
#define KRAKEN_MEM_ROUND_UP_PAGE(x) ((((x) - 1) & ~(KRContext::KRENGINE_SYS_ALLOCATION_GRANULARITY - 1)) + KRContext::KRENGINE_SYS_ALLOCATION_GRANULARITY)
int m_mapCount = 0;
size_t m_mapSize = 0;
@@ -52,10 +49,10 @@ KRDataBlock::KRDataBlock() {
m_data_offset = 0;
#if defined(_WIN32) || defined(_WIN64)
m_hPackFile = INVALID_HANDLE_VALUE;
#else
m_hFileMapping = NULL;
#elif defined(__APPLE__)
m_fdPackFile = 0;
#endif
m_fileName = "";
m_mmapData = NULL;
m_fileOwnerDataBlock = NULL;
@@ -70,7 +67,8 @@ KRDataBlock::KRDataBlock(void *data, size_t size) {
m_data_offset = 0;
#if defined(_WIN32) || defined(_WIN64)
m_hPackFile = INVALID_HANDLE_VALUE;
#else
m_hFileMapping = NULL;
#elif defined(__APPLE__)
m_fdPackFile = 0;
#endif
m_fileName = "";
@@ -90,22 +88,27 @@ KRDataBlock::~KRDataBlock() {
void KRDataBlock::unload()
{
assert(m_lockCount == 0);
#if defined(_WIN32) || defined(_WIN64)
if (m_hPackFile != INVALID_HANDLE_VALUE) {
CloseHandle(m_hPackFile);
m_hPackFile = INVALID_HANDLE_VALUE;
}
#elif defined(__APPLE__)
if(m_fdPackFile) {
// Memory mapped file
if(m_fileOwnerDataBlock == this) {
close(m_fdPackFile);
}
m_fdPackFile = 0;
} else if(m_data != NULL && m_bMalloced) {
}
#endif
if(m_data != NULL && m_bMalloced) {
// Malloc'ed data
free(m_data);
}
#if defined(_WIN32) || defined(_WIN64)
m_hPackFile = INVALID_HANDLE_VALUE;
#endif
m_bMalloced = false;
m_data = NULL;
m_data_size = 0;
@@ -132,19 +135,34 @@ bool KRDataBlock::load(const std::string &path)
{
bool success = false;
unload();
struct stat statbuf;
m_bReadOnly = true;
#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) {
m_fileOwnerDataBlock = this;
m_fileName = KRResource::GetFileBase(path);
FILE_STANDARD_INFO fileInfo;
if(GetFileInformationByHandleEx(m_hPackFile, FileStandardInfo, &fileInfo, sizeof(fileInfo))) {
m_data_size = fileInfo.AllocationSize.QuadPart;
m_data_offset = 0;
success = true;
}
}
#elif defined(__APPLE__)
m_fdPackFile = open(path.c_str(), O_RDONLY);
if(m_fdPackFile >= 0) {
m_fileOwnerDataBlock = this;
m_fileName = KRResource::GetFileBase(path);
if(fstat(m_fdPackFile, &statbuf) >= 0) {
m_data_size = statbuf.st_size;
m_data_offset = 0;
success = true;
}
m_fileOwnerDataBlock = this;
m_fileName = KRResource::GetFileBase(path);
if(fstat(m_fdPackFile, &statbuf) >= 0) {
m_data_size = statbuf.st_size;
m_data_offset = 0;
success = true;
}
}
#endif
if(!success) {
// If anything failed, don't leave the object in an invalid state
unload();
@@ -158,8 +176,15 @@ KRDataBlock *KRDataBlock::getSubBlock(int start, int length)
KRDataBlock *new_block = new KRDataBlock();
new_block->m_data_size = length;
if(m_fdPackFile) {
new_block->m_fdPackFile = m_fdPackFile;
#if defined(_WIN32) || defined(_WIN64)
if(m_hPackFile) {
new_block->m_hPackFile = m_hPackFile;
#elif defined(__APPLE__)
if (m_fdPackFile) {
new_block->m_fdPackFile = m_fdPackFile;
#else
#error Unsupported
#endif
new_block->m_fileOwnerDataBlock = m_fileOwnerDataBlock;
new_block->m_data_offset = start + m_data_offset;
} else if(m_bMalloced) {
@@ -190,7 +215,13 @@ size_t KRDataBlock::getSize() const {
// Expand 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 KRDataBlock::expand(size_t size)
{
if(m_data == NULL && m_fdPackFile == 0) {
#if defined(_WIN32) || defined(_WIN64)
if(m_data == NULL && m_hPackFile == 0) {
#elif defined(__APPLE__)
if (m_data == NULL && m_fdPackFile == 0) {
#else
#error Unsupported
#endif
// Starting with an empty data block; allocate memory on the heap
m_data = malloc(size);
assert(m_data != NULL);
@@ -206,10 +237,10 @@ void KRDataBlock::expand(size_t size)
// ... 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);
assert(pNewData != NULL);
// Copy exising data
copy(pNewData);
// Unload existing data allocation, which is now redundant
size_t new_size = m_data_size + size; // We need to store this before unload() as unload() will reset it
unload();
@@ -224,7 +255,7 @@ void KRDataBlock::expand(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);
@@ -239,10 +270,34 @@ void KRDataBlock::copy(void *dest) {
// Copy a range of data to the destination pointer
void KRDataBlock::copy(void *dest, int start, int count) {
#if defined(_WIN32) || defined(_WIN64)
if (m_lockCount == 0 && m_hPackFile != 0) {
// Optimization: If we haven't mmap'ed or malloced the data already, pread() it directly from the file into the buffer
LARGE_INTEGER distance;
distance.QuadPart = start + m_data_offset;
bool success = SetFilePointerEx(m_hPackFile, distance, NULL, FILE_BEGIN);
assert(success);
void *w = dest;
DWORD bytes_remaining = count;
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;
bytes_remaining -= bytes_read;
}
assert(bytes_remaining == 0);
#elif defined(__APPLE__)
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);
#else
#error Unsupported
#endif
} else {
lock();
memcpy((unsigned char *)dest, (unsigned char *)m_data + start, count);
@@ -266,33 +321,81 @@ void KRDataBlock::append(const std::string &s)
// Save the data to a file.
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;
hNewFile = CreateFile(path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hNewFile == INVALID_HANDLE_VALUE) {
success = false;
}
if (success) {
hFileMapping = CreateFileMappingFromApp(hNewFile, NULL, PAGE_READWRITE, m_data_size, NULL);
if (hFileMapping == NULL) {
success = false;
}
}
if (success) {
pNewData = MapViewOfFileFromApp(hFileMapping, FILE_MAP_WRITE, 0, m_data_size);
if (pNewData == NULL) {
success = false;
}
}
if (success) {
// Copy data to new file
copy(pNewData);
}
if (pNewData != NULL) {
UnmapViewOfFile(pNewData);
}
if (hFileMapping != NULL) {
CloseHandle(hFileMapping);
}
if (hNewFile != INVALID_HANDLE_VALUE) {
CloseHandle(hNewFile);
}
return success;
#elif defined(__APPLE__)
int fdNewFile = open(path.c_str(), O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);
if(fdNewFile == -1) {
return false;
} else {
// Seek to end of file and write a byte to enlarge it
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) {
close(fdNewFile);
return false;
} else if(m_data != NULL) {
// Copy data to new file
copy(pNewData);
// Unmap the new file
munmap(pNewData, m_data_size);
// Close the new file
close(fdNewFile);
}
return true;
}
// Seek to end of file and write a byte to enlarge it
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) {
close(fdNewFile);
return false;
}
if(m_data != NULL) {
// Copy data to new file
copy(pNewData);
// Unmap the new file
munmap(pNewData, m_data_size);
// Close the new file
close(fdNewFile);
}
return true;
#else
#error Unsupported
#endif
}
// Get contents as a string
@@ -311,18 +414,32 @@ std::string KRDataBlock::getString()
void KRDataBlock::lock()
{
if(m_lockCount == 0) {
// Memory mapped file; ensure data is mapped to ram
#if defined(_WIN32) || defined(_WIN64)
if(m_hFileMapping) {
#elif defined(__APPLE__)
if(m_fdPackFile) {
#else
#error Unsupported
#endif
if(m_data_size < KRENGINE_MIN_MMAP) {
m_data = malloc(m_data_size);
assert(m_data != NULL);
copy(m_data);
} else {
size_t alignment_offset = m_data_offset & (KRContext::KRENGINE_SYS_ALLOCATION_GRANULARITY - 1);
assert(m_mmapData == NULL);
#if defined(_WIN32) || defined(_WIN64)
m_hFileMapping = CreateFileMappingFromApp(m_hPackFile, NULL, m_bReadOnly ? PAGE_READONLY : PAGE_READWRITE, m_data_size, NULL);
assert(m_hFileMapping != NULL);
m_mmapData = MapViewOfFileFromApp(m_hPackFile, m_bReadOnly ? FILE_MAP_READ : FILE_MAP_WRITE, m_data_offset - alignment_offset, m_data_size + alignment_offset);
assert(m_mmapData != NULL);
#elif defined(__APPLE__)
//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
size_t alignment_offset = m_data_offset & (KRAKEN_MEM_PAGE_SIZE - 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) {
@@ -353,6 +470,9 @@ void KRDataBlock::lock()
}
assert(false); // mmap() failed.
}
#else
#error Unsupported
#endif
m_mapCount++;
m_mapSize += m_data_size;
m_mapOverhead += alignment_offset + KRAKEN_MEM_ROUND_UP_PAGE(m_data_size + alignment_offset) - m_data_size + alignment_offset;
@@ -369,24 +489,41 @@ void KRDataBlock::unlock()
{
// We expect that the data block was previously locked
assertLocked();
if(m_lockCount == 1) {
// Memory mapped file; ensure data is unmapped from ram
#if defined(_WIN32) || defined(_WIN64)
if (m_hPackFile) {
#elif defined(__APPLE__)
if(m_fdPackFile) {
#else
#error Undefined
#endif
if(m_data_size < KRENGINE_MIN_MMAP) {
free(m_data);
m_data = NULL;
} else {
//fprintf(stderr, "KRDataBlock::unlock - \"%s\" (%i)\n", m_fileOwnerDataBlock->m_fileName.c_str(), m_lockCount);
#if defined(_WIN32) || defined(_WIN64)
if (m_mmapData != NULL) {
UnmapViewOfFile(m_mmapData);
}
if(m_hFileMapping != NULL) {
CloseHandle(m_hFileMapping);
m_hFileMapping = NULL;
}
#elif defined(__APPLE__)
munmap(m_mmapData, m_data_size);
#else
#error Undefined
#endif
m_data = NULL;
m_mmapData = NULL;
m_mapCount--;
m_mapSize -= m_data_size;
size_t alignment_offset = m_data_offset & (KRAKEN_MEM_PAGE_SIZE - 1);
size_t alignment_offset = m_data_offset & (KRContext::KRENGINE_SYS_ALLOCATION_GRANULARITY - 1);
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);
}

View File

@@ -105,7 +105,8 @@ private:
// For memory mapped objects:
#if defined(_WIN32) || defined(_WIN64)
HANDLE m_hPackFile;
#else
HANDLE m_hFileMapping;
#elif defined(__APPLE__)
int m_fdPackFile;
#endif

View File

@@ -11,8 +11,6 @@
#include "KRDirectionalLight.h"
#include "KRShader.h"
#include "KRContext.h"
#include "KRMat4.h"
#include "KRQuaternion.h"
#include "assert.h"
#include "KRStockGeometry.h"
@@ -30,12 +28,12 @@ std::string KRDirectionalLight::getElementName() {
return "directional_light";
}
KRVector3 KRDirectionalLight::getWorldLightDirection() {
return KRMat4::Dot(getWorldRotation().rotationMatrix(), getLocalLightDirection());
Vector3 KRDirectionalLight::getWorldLightDirection() {
return Matrix4::Dot(getWorldRotation().rotationMatrix(), getLocalLightDirection());
}
KRVector3 KRDirectionalLight::getLocalLightDirection() {
return KRVector3::Up(); //&KRF HACK changed from KRVector3::Forward(); - to compensate for the way Maya handles post rotation.
Vector3 KRDirectionalLight::getLocalLightDirection() {
return Vector3::Up(); //&KRF HACK changed from Vector3::Forward(); - to compensate for the way Maya handles post rotation.
}
@@ -54,32 +52,32 @@ int KRDirectionalLight::configureShadowBufferViewports(const KRViewport &viewpor
float max_depth = 1.0f;
*/
KRAABB worldSpacefrustrumSliceBounds = KRAABB(KRVector3(-1.0f, -1.0f, -1.0f), KRVector3(1.0f, 1.0f, 1.0f), KRMat4::Invert(viewport.getViewProjectionMatrix()));
AABB worldSpacefrustrumSliceBounds = AABB(Vector3(-1.0f, -1.0f, -1.0f), Vector3(1.0f, 1.0f, 1.0f), Matrix4::Invert(viewport.getViewProjectionMatrix()));
worldSpacefrustrumSliceBounds.scale(KRENGINE_SHADOW_BOUNDS_EXTRA_SCALE);
KRVector3 shadowLook = -KRVector3::Normalize(getWorldLightDirection());
Vector3 shadowLook = -Vector3::Normalize(getWorldLightDirection());
KRVector3 shadowUp(0.0, 1.0, 0.0);
if(KRVector3::Dot(shadowUp, shadowLook) > 0.99f) shadowUp = KRVector3(0.0, 0.0, 1.0); // Ensure shadow look direction is not parallel with the shadowUp direction
Vector3 shadowUp(0.0, 1.0, 0.0);
if(Vector3::Dot(shadowUp, shadowLook) > 0.99f) shadowUp = Vector3(0.0, 0.0, 1.0); // Ensure shadow look direction is not parallel with the shadowUp direction
// KRMat4 matShadowView = KRMat4::LookAt(viewport.getCameraPosition() - shadowLook, viewport.getCameraPosition(), shadowUp);
// KRMat4 matShadowProjection = KRMat4();
// Matrix4 matShadowView = Matrix4::LookAt(viewport.getCameraPosition() - shadowLook, viewport.getCameraPosition(), shadowUp);
// Matrix4 matShadowProjection = Matrix4();
// matShadowProjection.scale(0.001, 0.001, 0.001);
KRMat4 matShadowView = KRMat4::LookAt(worldSpacefrustrumSliceBounds.center() - shadowLook, worldSpacefrustrumSliceBounds.center(), shadowUp);
KRMat4 matShadowProjection = KRMat4();
KRAABB shadowSpaceFrustrumSliceBounds = KRAABB(worldSpacefrustrumSliceBounds.min, worldSpacefrustrumSliceBounds.max, KRMat4::Invert(matShadowProjection));
KRAABB shadowSpaceSceneBounds = KRAABB(getScene().getRootOctreeBounds().min, getScene().getRootOctreeBounds().max, KRMat4::Invert(matShadowProjection));
Matrix4 matShadowView = Matrix4::LookAt(worldSpacefrustrumSliceBounds.center() - shadowLook, worldSpacefrustrumSliceBounds.center(), shadowUp);
Matrix4 matShadowProjection = Matrix4();
AABB shadowSpaceFrustrumSliceBounds = AABB(worldSpacefrustrumSliceBounds.min, worldSpacefrustrumSliceBounds.max, Matrix4::Invert(matShadowProjection));
AABB shadowSpaceSceneBounds = AABB(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
matShadowProjection.scale(1.0f / shadowSpaceFrustrumSliceBounds.size().x, 1.0f / shadowSpaceFrustrumSliceBounds.size().y, 1.0f / shadowSpaceFrustrumSliceBounds.size().z);
KRMat4 matBias;
Matrix4 matBias;
matBias.bias();
matShadowProjection *= matBias;
KRViewport newShadowViewport = KRViewport(KRVector2(KRENGINE_SHADOW_MAP_WIDTH, KRENGINE_SHADOW_MAP_HEIGHT), matShadowView, matShadowProjection);
KRAABB prevShadowBounds = KRAABB(-KRVector3::One(), KRVector3::One(), KRMat4::Invert(m_shadowViewports[iShadow].getViewProjectionMatrix()));
KRAABB minimumShadowBounds = KRAABB(-KRVector3::One(), KRVector3::One(), KRMat4::Invert(newShadowViewport.getViewProjectionMatrix()));
KRViewport newShadowViewport = KRViewport(Vector2(KRENGINE_SHADOW_MAP_WIDTH, KRENGINE_SHADOW_MAP_HEIGHT), matShadowView, matShadowProjection);
AABB prevShadowBounds = AABB(-Vector3::One(), Vector3::One(), Matrix4::Invert(m_shadowViewports[iShadow].getViewProjectionMatrix()));
AABB minimumShadowBounds = AABB(-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
m_shadowViewports[iShadow] = newShadowViewport;
@@ -103,16 +101,16 @@ void KRDirectionalLight::render(KRCamera *pCamera, std::vector<KRPointLight *> &
std::vector<KRDirectionalLight *> this_light;
this_light.push_back(this);
KRMat4 matModelViewInverseTranspose = viewport.getViewMatrix() * getModelMatrix();
Matrix4 matModelViewInverseTranspose = viewport.getViewMatrix() * getModelMatrix();
matModelViewInverseTranspose.transpose();
matModelViewInverseTranspose.invert();
KRVector3 light_direction_view_space = getWorldLightDirection();
light_direction_view_space = KRMat4::Dot(matModelViewInverseTranspose, light_direction_view_space);
Vector3 light_direction_view_space = getWorldLightDirection();
light_direction_view_space = Matrix4::Dot(matModelViewInverseTranspose, light_direction_view_space);
light_direction_view_space.normalize();
KRShader *pShader = getContext().getShaderManager()->getShader("light_directional", pCamera, std::vector<KRPointLight *>(), this_light, std::vector<KRSpotLight *>(), 0, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, renderPass);
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, getModelMatrix(), std::vector<KRPointLight *>(), this_light, std::vector<KRSpotLight *>(), 0, renderPass, KRVector3::Zero(), 0.0f, KRVector4::Zero())) {
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, getModelMatrix(), std::vector<KRPointLight *>(), this_light, std::vector<KRSpotLight *>(), 0, renderPass, Vector3::Zero(), 0.0f, Vector4::Zero())) {
pShader->setUniform(KRShader::KRENGINE_UNIFORM_LIGHT_DIRECTION_VIEW_SPACE, light_direction_view_space);
pShader->setUniform(KRShader::KRENGINE_UNIFORM_LIGHT_COLOR, m_color);
@@ -131,7 +129,7 @@ void KRDirectionalLight::render(KRCamera *pCamera, std::vector<KRPointLight *> &
}
}
KRAABB KRDirectionalLight::getBounds()
AABB KRDirectionalLight::getBounds()
{
return KRAABB::Infinite();
return AABB::Infinite();
}

View File

@@ -10,7 +10,6 @@
#define KREngine_KRDirectionalLight_h
#include "KRLight.h"
#include "KRMat4.h"
class KRDirectionalLight : public KRLight {
@@ -20,11 +19,11 @@ public:
virtual ~KRDirectionalLight();
virtual std::string getElementName();
KRVector3 getLocalLightDirection();
KRVector3 getWorldLightDirection();
Vector3 getLocalLightDirection();
Vector3 getWorldLightDirection();
virtual void render(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, KRNode::RenderPass renderPass);
virtual KRAABB getBounds();
virtual AABB getBounds();
protected:

View File

@@ -11,9 +11,9 @@
#ifndef KRENGINE_COMMON_H
#define KRENGINE_COMMON_H
float const PI = 3.141592653589793f;
float const D2R = PI * 2 / 360;
#include "public/kraken.h"
#include "KRHelpers.h"
using namespace kraken;
#include <stdint.h>
#include <vector>
@@ -31,21 +31,18 @@ float const D2R = PI * 2 / 360;
#include <stdint.h>
#include <stdio.h>
#if defined(_WIN32) || defined(_WIN64)
#include "../3rdparty/tinyxml2/tinyxml2.h"
#else
#if defined(__APPLE__)
#include <sys/mman.h>
#include <unistd.h>
#include <pthread.h>
#include <Accelerate/Accelerate.h>
#include <AudioToolbox/AudioToolbox.h>
#include <AudioToolbox/AudioFile.h>
#include <AudioToolbox/ExtendedAudioFile.h>
#include <AudioToolbox/AUGraph.h>
#include "tinyxml2.h"
#endif
#include <boost/tokenizer.hpp>
@@ -218,20 +215,14 @@ fprintf(stderr, "Error at line number %d, in file %s. Returned %d for call %s\n"
#endif
#define KRMIN(x,y) ((x) < (y) ? (x) : (y))
#define KRMAX(x,y) ((x) > (y) ? (x) : (y))
#define KRCLAMP(x, min, max) (KRMAX(KRMIN(x, max), min))
#define KRALIGN(x) ((x + 3) & ~0x03)
typedef enum {
STREAM_LEVEL_OUT,
STREAM_LEVEL_IN_LQ,
STREAM_LEVEL_IN_HQ
} kraken_stream_level;
#include "KRVector4.h"
#include "KRVector3.h"
#include "KRVector2.h"
#include "KRBehavior.h"
#endif
using namespace kraken;

View File

@@ -30,8 +30,8 @@
//
// #include "KRTextureManager.h"
#include "KRMat4.h"
#include "KRVector3.h"
#include "Matrix4.h"
#include "Vector3.h"
#include "KRMesh.h"
#include "KRScene.h"
#include "KRContext.h"

View File

@@ -1,16 +0,0 @@
//
// KRFloat.h
// Kraken
//
// Created by Kearwood Gilbert on 2013-05-03.
// Copyright (c) 2013 Kearwood Software. All rights reserved.
//
#ifndef KRFLOAT_H
#define KRFLOAT_H
namespace KRFloat {
float SmoothStep(float a, float b, float t);
};
#endif /* defined(KRFLOAT_H) */

50
kraken/KRHelpers.cpp Normal file
View File

@@ -0,0 +1,50 @@
#include "KREngine-common.h"
#include "KRHelpers.h"
namespace kraken {
void SetUniform(GLint location, const Vector2 &v)
{
if (location != -1) GLDEBUG(glUniform2f(location, v.x, v.y));
}
void SetUniform(GLint location, const Vector3 &v)
{
if (location != -1) GLDEBUG(glUniform3f(location, v.x, v.y, v.z));
}
void SetUniform(GLint location, const Vector4 &v)
{
if (location != -1) GLDEBUG(glUniform4f(location, v.x, v.y, v.z, v.w));
}
void SetUniform(GLint location, const Matrix4 &v)
{
if (location != -1) GLDEBUG(glUniformMatrix4fv(location, 1, GL_FALSE, v.c));
}
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...
if (value != default_value) {
e->SetAttribute((base_name + "_x").c_str(), value.x);
e->SetAttribute((base_name + "_y").c_str(), value.y);
e->SetAttribute((base_name + "_z").c_str(), value.z);
}
}
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
&& e->QueryFloatAttribute((base_name + "_y").c_str(), &value.y) == tinyxml2::XML_SUCCESS
&& e->QueryFloatAttribute((base_name + "_z").c_str(), &value.z) == tinyxml2::XML_SUCCESS) {
return value;
} else {
return default_value;
}
}
} // namespace kraken

34
kraken/KRHelpers.h Normal file
View File

@@ -0,0 +1,34 @@
#ifndef KRHELPERS_H
#define KRHELPERS_H
#if defined(_WIN32) || defined(_WIN64)
#include <GL/glew.h>
#elif defined(__linux__) || defined(__unix__) || defined(__posix__)
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glext.h>
#elif defined(__APPLE__)
#include <OpenGL/gl3.h>
#include <OpenGL/gl3ext.h>
#endif
#include "../3rdparty/tinyxml2/tinyxml2.h"
#define KRMIN(x,y) ((x) < (y) ? (x) : (y))
#define KRMAX(x,y) ((x) > (y) ? (x) : (y))
#define KRCLAMP(x, min, max) (KRMAX(KRMIN(x, max), min))
#define KRALIGN(x) ((x + 3) & ~0x03)
float const PI = 3.141592653589793f;
float const D2R = PI * 2 / 360;
namespace kraken {
void SetUniform(GLint location, const Vector2 &v);
void SetUniform(GLint location, const Vector3 &v);
void SetUniform(GLint location, const Vector4 &v);
void SetUniform(GLint location, const Matrix4 &v);
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
#endif

View File

@@ -14,7 +14,7 @@ KRLODGroup::KRLODGroup(KRScene &scene, std::string name) : KRNode(scene, name)
{
m_min_distance = 0.0f;
m_max_distance = 0.0f;
m_reference = KRAABB(KRVector3::Zero(), KRVector3::Zero());
m_reference = AABB(Vector3::Zero(), Vector3::Zero());
m_use_world_units = true;
}
@@ -71,7 +71,7 @@ void KRLODGroup::loadXML(tinyxml2::XMLElement *e)
z = 0.0f;
}
m_reference.min = KRVector3(x,y,z);
m_reference.min = Vector3(x,y,z);
x=0.0f; y=0.0f; z=0.0f;
if(e->QueryFloatAttribute("reference_max_x", &x) != tinyxml2::XML_SUCCESS) {
@@ -83,7 +83,7 @@ void KRLODGroup::loadXML(tinyxml2::XMLElement *e)
if(e->QueryFloatAttribute("reference_max_z", &z) != tinyxml2::XML_SUCCESS) {
z = 0.0f;
}
m_reference.max = KRVector3(x,y,z);
m_reference.max = Vector3(x,y,z);
m_use_world_units = true;
if(e->QueryBoolAttribute("use_world_units", &m_use_world_units) != tinyxml2::XML_SUCCESS) {
@@ -92,12 +92,12 @@ void KRLODGroup::loadXML(tinyxml2::XMLElement *e)
}
const KRAABB &KRLODGroup::getReference() const
const AABB &KRLODGroup::getReference() const
{
return m_reference;
}
void KRLODGroup::setReference(const KRAABB &reference)
void KRLODGroup::setReference(const AABB &reference)
{
m_reference = reference;
}
@@ -114,19 +114,19 @@ KRNode::LodVisibility KRLODGroup::calcLODVisibility(const KRViewport &viewport)
float sqr_distance;
float sqr_prestream_distance;
KRVector3 world_camera_position = viewport.getCameraPosition();
KRVector3 local_camera_position = worldToLocal(world_camera_position);
KRVector3 local_reference_point = m_reference.nearestPoint(local_camera_position);
Vector3 world_camera_position = viewport.getCameraPosition();
Vector3 local_camera_position = worldToLocal(world_camera_position);
Vector3 local_reference_point = m_reference.nearestPoint(local_camera_position);
if(m_use_world_units) {
KRVector3 world_reference_point = localToWorld(local_reference_point);
Vector3 world_reference_point = localToWorld(local_reference_point);
sqr_distance = (world_camera_position - world_reference_point).sqrMagnitude() * (lod_bias * lod_bias);
sqr_prestream_distance = getContext().KRENGINE_PRESTREAM_DISTANCE * getContext().KRENGINE_PRESTREAM_DISTANCE;
} else {
sqr_distance = (local_camera_position - local_reference_point).sqrMagnitude() * (lod_bias * lod_bias);
KRVector3 world_reference_point = localToWorld(local_reference_point);
sqr_prestream_distance = worldToLocal(KRVector3::Normalize(world_reference_point - world_camera_position) * getContext().KRENGINE_PRESTREAM_DISTANCE).sqrMagnitude(); // TODO, FINDME - Optimize with precalc?
Vector3 world_reference_point = localToWorld(local_reference_point);
sqr_prestream_distance = worldToLocal(Vector3::Normalize(world_reference_point - world_camera_position) * getContext().KRENGINE_PRESTREAM_DISTANCE).sqrMagnitude(); // TODO, FINDME - Optimize with precalc?
}

View File

@@ -25,8 +25,8 @@ public:
void setMinDistance(float min_distance);
void setMaxDistance(float max_distance);
const KRAABB &getReference() const;
void setReference(const KRAABB &reference);
const AABB &getReference() const;
void setReference(const AABB &reference);
void setUseWorldUnits(bool use_world_units);
bool getUseWorldUnits() const;
@@ -35,7 +35,7 @@ public:
private:
float m_min_distance;
float m_max_distance;
KRAABB m_reference; // Point of reference, used for distance calculation. Usually set to the bounding box center
AABB m_reference; // Point of reference, used for distance calculation. Usually set to the bounding box center
bool m_use_world_units;
};

View File

@@ -11,8 +11,6 @@
#include "KRLight.h"
#include "KRNode.h"
#include "KRMat4.h"
#include "KRVector3.h"
#include "KRCamera.h"
#include "KRContext.h"
@@ -28,7 +26,7 @@ KRLight::KRLight(KRScene &scene, std::string name) : KRNode(scene, name)
{
m_intensity = 1.0f;
m_dust_particle_intensity = 1.0f;
m_color = KRVector3::One();
m_color = Vector3::One();
m_flareTexture = "";
m_pFlareTexture = NULL;
m_flareSize = 0.0;
@@ -88,7 +86,7 @@ void KRLight::loadXML(tinyxml2::XMLElement *e) {
if(e->QueryFloatAttribute("color_b", &z) != tinyxml2::XML_SUCCESS) {
z = 1.0;
}
m_color = KRVector3(x,y,z);
m_color = Vector3(x,y,z);
if(e->QueryFloatAttribute("intensity", &m_intensity) != tinyxml2::XML_SUCCESS) {
m_intensity = 100.0;
@@ -158,11 +156,11 @@ float KRLight::getIntensity() {
return m_intensity;
}
const KRVector3 &KRLight::getColor() {
const Vector3 &KRLight::getColor() {
return m_color;
}
void KRLight::setColor(const KRVector3 &color) {
void KRLight::setColor(const Vector3 &color) {
m_color = color;
}
@@ -200,7 +198,7 @@ void KRLight::render(KRCamera *pCamera, std::vector<KRPointLight *> &point_light
GLDEBUG(glEnable(GL_DEPTH_TEST));
GLDEBUG(glDepthRangef(0.0, 1.0));
KRMat4 particleModelMatrix;
Matrix4 particleModelMatrix;
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(viewport.getCameraPosition());
@@ -222,10 +220,10 @@ void KRLight::render(KRCamera *pCamera, std::vector<KRPointLight *> &point_light
KRShader *pParticleShader = m_pContext->getShaderManager()->getShader("dust_particle", pCamera, this_point_light, this_directional_light, this_spot_light, 0, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, renderPass);
if(getContext().getShaderManager()->selectShader(*pCamera, pParticleShader, viewport, particleModelMatrix, this_point_light, this_directional_light, this_spot_light, 0, renderPass, KRVector3::Zero(), 0.0f, KRVector4::Zero())) {
if(getContext().getShaderManager()->selectShader(*pCamera, pParticleShader, viewport, particleModelMatrix, this_point_light, this_directional_light, this_spot_light, 0, renderPass, Vector3::Zero(), 0.0f, Vector4::Zero())) {
pParticleShader->setUniform(KRShader::KRENGINE_UNIFORM_LIGHT_COLOR, m_color * pCamera->settings.dust_particle_intensity * m_dust_particle_intensity * m_intensity);
pParticleShader->setUniform(KRShader::KRENGINE_UNIFORM_PARTICLE_ORIGIN, KRMat4::DotWDiv(KRMat4::Invert(particleModelMatrix), KRVector3::Zero()));
pParticleShader->setUniform(KRShader::KRENGINE_UNIFORM_PARTICLE_ORIGIN, Matrix4::DotWDiv(Matrix4::Invert(particleModelMatrix), Vector3::Zero()));
pParticleShader->setUniform(KRShader::KRENGINE_UNIFORM_FLARE_SIZE, m_dust_particle_size);
KRDataBlock particle_index_data;
@@ -258,14 +256,14 @@ void KRLight::render(KRCamera *pCamera, std::vector<KRPointLight *> &point_light
KRShader *pFogShader = m_pContext->getShaderManager()->getShader(shader_name, pCamera, this_point_light, this_directional_light, this_spot_light, 0, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, KRNode::RENDER_PASS_ADDITIVE_PARTICLES);
if(getContext().getShaderManager()->selectShader(*pCamera, pFogShader, viewport, KRMat4(), this_point_light, this_directional_light, this_spot_light, 0, KRNode::RENDER_PASS_VOLUMETRIC_EFFECTS_ADDITIVE, KRVector3::Zero(), 0.0f, KRVector4::Zero())) {
if(getContext().getShaderManager()->selectShader(*pCamera, pFogShader, viewport, Matrix4(), this_point_light, this_directional_light, this_spot_light, 0, KRNode::RENDER_PASS_VOLUMETRIC_EFFECTS_ADDITIVE, Vector3::Zero(), 0.0f, Vector4::Zero())) {
int slice_count = (int)(pCamera->settings.volumetric_environment_quality * 495.0) + 5;
float slice_near = -pCamera->settings.getPerspectiveNearZ();
float slice_far = -pCamera->settings.volumetric_environment_max_distance;
float slice_spacing = (slice_far - slice_near) / slice_count;
pFogShader->setUniform(KRShader::KRENGINE_UNIFORM_SLICE_DEPTH_SCALE, KRVector2(slice_near, slice_spacing));
pFogShader->setUniform(KRShader::KRENGINE_UNIFORM_SLICE_DEPTH_SCALE, Vector2(slice_near, slice_spacing));
pFogShader->setUniform(KRShader::KRENGINE_UNIFORM_LIGHT_COLOR, (m_color * pCamera->settings.volumetric_environment_intensity * m_intensity * -slice_spacing / 1000.0f));
KRDataBlock index_data;
@@ -279,14 +277,14 @@ void KRLight::render(KRCamera *pCamera, std::vector<KRPointLight *> &point_light
if(m_flareTexture.size() && m_flareSize > 0.0f) {
KRMat4 occlusion_test_sphere_matrix = KRMat4();
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) {
occlusion_test_sphere_matrix *= m_parentNode->getModelMatrix();
}
if(getContext().getShaderManager()->selectShader("occlusion_test", *pCamera, point_lights, directional_lights, spot_lights, 0, viewport, occlusion_test_sphere_matrix, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, renderPass, KRVector3::Zero(), 0.0f, KRVector4::Zero())) {
if(getContext().getShaderManager()->selectShader("occlusion_test", *pCamera, point_lights, directional_lights, spot_lights, 0, viewport, occlusion_test_sphere_matrix, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, renderPass, Vector3::Zero(), 0.0f, Vector4::Zero())) {
GLDEBUG(glGenQueriesEXT(1, &m_occlusionQuery));
#if TARGET_OS_IPHONE
@@ -334,7 +332,7 @@ void KRLight::render(KRCamera *pCamera, std::vector<KRPointLight *> &point_light
// Render light flare on transparency pass
KRShader *pShader = getContext().getShaderManager()->getShader("flare", pCamera, point_lights, directional_lights, spot_lights, 0, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, renderPass);
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, getModelMatrix(), point_lights, directional_lights, spot_lights, 0, renderPass, KRVector3::Zero(), 0.0f, KRVector4::Zero())) {
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, getModelMatrix(), point_lights, directional_lights, spot_lights, 0, renderPass, Vector3::Zero(), 0.0f, Vector4::Zero())) {
pShader->setUniform(KRShader::KRENGINE_UNIFORM_MATERIAL_ALPHA, 1.0f);
pShader->setUniform(KRShader::KRENGINE_UNIFORM_FLARE_SIZE, m_flareSize);
m_pContext->getTextureManager()->selectTexture(0, m_pFlareTexture, 0.0f, KRTexture::TEXTURE_USAGE_LIGHT_FLARE);
@@ -365,7 +363,7 @@ void KRLight::allocateShadowBuffers(int cBuffers) {
// Allocate newly required buffers
for(int iShadow = 0; iShadow < cBuffers; iShadow++) {
KRVector2 viewportSize = m_shadowViewports[iShadow].getSize();
Vector2 viewportSize = m_shadowViewports[iShadow].getSize();
if(!shadowDepthTexture[iShadow]) {
shadowValid[iShadow] = false;
@@ -451,7 +449,7 @@ void KRLight::renderShadowBuffers(KRCamera *pCamera)
// Use shader program
KRShader *shadowShader = m_pContext->getShaderManager()->getShader("ShadowShader", pCamera, std::vector<KRPointLight *>(), std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, KRNode::RENDER_PASS_FORWARD_TRANSPARENT);
getContext().getShaderManager()->selectShader(*pCamera, shadowShader, m_shadowViewports[iShadow], KRMat4(), std::vector<KRPointLight *>(), std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, KRNode::RENDER_PASS_SHADOWMAP, KRVector3::Zero(), 0.0f, KRVector4::Zero());
getContext().getShaderManager()->selectShader(*pCamera, shadowShader, m_shadowViewports[iShadow], Matrix4(), std::vector<KRPointLight *>(), std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, KRNode::RENDER_PASS_SHADOWMAP, Vector3::Zero(), 0.0f, Vector4::Zero());
getScene().render(pCamera, m_shadowViewports[iShadow].getVisibleBounds(), m_shadowViewports[iShadow], KRNode::RENDER_PASS_SHADOWMAP, true);

View File

@@ -34,8 +34,8 @@ public:
float getIntensity();
void setDecayStart(float decayStart);
float getDecayStart();
const KRVector3 &getColor();
void setColor(const KRVector3 &color);
const Vector3 &getColor();
void setColor(const Vector3 &color);
void setFlareTexture(std::string flare_texture);
void setFlareSize(float flare_size);
@@ -54,7 +54,7 @@ protected:
float m_intensity;
float m_decayStart;
KRVector3 m_color;
Vector3 m_color;
std::string m_flareTexture;
KRTexture *m_pFlareTexture;

View File

@@ -1,130 +0,0 @@
//
// KRMat4.h
// KREngine
//
// Copyright 2012 Kearwood Gilbert. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY KEARWOOD GILBERT ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KEARWOOD GILBERT OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Kearwood Gilbert.
//
#include "KRVector3.h"
#include "KRVector4.h"
#include "KREngine-common.h"
#ifndef KRMAT4_I
#define KRMAT4_I
#define EMPTY_MATRIX4 { 0.0, 0.0, 0.0, 0.0,\
0.0, 0.0, 0.0, 0.0,\
0.0, 0.0, 0.0, 0.0,\
0.0, 0.0, 0.0, 0.0 }
#define IDENTITY_MATRIX4 { 1.0, 0.0, 0.0, 0.0,\
0.0, 1.0, 0.0, 0.0,\
0.0, 0.0, 1.0, 0.0,\
0.0, 0.0, 0.0, 1.0 }
typedef enum {
X_AXIS,
Y_AXIS,
Z_AXIS
} AXIS;
class KRQuaternion;
class KRMat4 {
public:
float c[16]; // Matrix components, in column-major order
// Default constructor - Creates an identity matrix
KRMat4();
KRMat4(float *pMat);
KRMat4(const KRVector3 &axis_x, const KRVector3 &axis_y, const KRVector3 &axis_z, const KRVector3 &trans);
// Destructor
~KRMat4();
// Copy constructor
KRMat4(const KRMat4 &m);
// Overload assignment operator
KRMat4& operator=(const KRMat4 &m);
// Overload comparison operator
bool operator==(const KRMat4 &m) const;
// Overload compound multiply operator
KRMat4& operator*=(const KRMat4 &m);
float& operator[](unsigned i);
float operator[](unsigned i) const;
// Overload multiply operator
//KRMat4& operator*(const KRMat4 &m);
KRMat4 operator*(const KRMat4 &m) const;
float *getPointer();
void perspective(float fov, float aspect, float nearz, float farz);
void ortho(float left, float right, float top, float bottom, float nearz, float farz);
void translate(float x, float y, float z);
void translate(const KRVector3 &v);
void scale(float x, float y, float z);
void scale(const KRVector3 &v);
void scale(float s);
void rotate(float angle, AXIS axis);
void rotate(const KRQuaternion &q);
void bias();
bool invert();
void transpose();
static KRVector3 DotNoTranslate(const KRMat4 &m, const KRVector3 &v); // Dot product without including translation; useful for transforming normals and tangents
static KRMat4 Invert(const KRMat4 &m);
static KRMat4 Transpose(const KRMat4 &m);
static KRVector3 Dot(const KRMat4 &m, const KRVector3 &v);
static KRVector4 Dot4(const KRMat4 &m, const KRVector4 &v);
static float DotW(const KRMat4 &m, const KRVector3 &v);
static KRVector3 DotWDiv(const KRMat4 &m, const KRVector3 &v);
static KRMat4 LookAt(const KRVector3 &cameraPos, const KRVector3 &lookAtPos, const KRVector3 &upDirection);
static KRMat4 Translation(const KRVector3 &v);
static KRMat4 Rotation(const KRVector3 &v);
static KRMat4 Scaling(const KRVector3 &v);
void setUniform(GLint location) const;
};
#endif // KRMAT4_I

View File

@@ -44,10 +44,10 @@ KRMaterial::KRMaterial(KRContext &context, const char *szName) : KRResource(cont
m_pNormalMap = NULL;
m_pReflectionMap = NULL;
m_pReflectionCube = NULL;
m_ambientColor = KRVector3::Zero();
m_diffuseColor = KRVector3::One();
m_specularColor = KRVector3::One();
m_reflectionColor = KRVector3::Zero();
m_ambientColor = Vector3::Zero();
m_diffuseColor = Vector3::One();
m_specularColor = Vector3::One();
m_reflectionColor = Vector3::Zero();
m_tr = (GLfloat)1.0f;
m_ns = (GLfloat)0.0f;
m_ambientMap = "";
@@ -56,14 +56,14 @@ KRMaterial::KRMaterial(KRContext &context, const char *szName) : KRResource(cont
m_normalMap = "";
m_reflectionMap = "";
m_reflectionCube = "";
m_ambientMapOffset = KRVector2(0.0f, 0.0f);
m_specularMapOffset = KRVector2(0.0f, 0.0f);
m_diffuseMapOffset = KRVector2(0.0f, 0.0f);
m_ambientMapScale = KRVector2(1.0f, 1.0f);
m_specularMapScale = KRVector2(1.0f, 1.0f);
m_diffuseMapScale = KRVector2(1.0f, 1.0f);
m_reflectionMapOffset = KRVector2(0.0f, 0.0f);
m_reflectionMapScale = KRVector2(1.0f, 1.0f);
m_ambientMapOffset = Vector2(0.0f, 0.0f);
m_specularMapOffset = Vector2(0.0f, 0.0f);
m_diffuseMapOffset = Vector2(0.0f, 0.0f);
m_ambientMapScale = Vector2(1.0f, 1.0f);
m_specularMapScale = Vector2(1.0f, 1.0f);
m_diffuseMapScale = Vector2(1.0f, 1.0f);
m_reflectionMapOffset = Vector2(0.0f, 0.0f);
m_reflectionMapScale = Vector2(1.0f, 1.0f);
m_alpha_mode = KRMATERIAL_ALPHA_MODE_OPAQUE;
}
@@ -144,31 +144,31 @@ bool KRMaterial::save(KRDataBlock &data) {
return true;
}
void KRMaterial::setAmbientMap(std::string texture_name, KRVector2 texture_scale, KRVector2 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, KRVector2 texture_scale, KRVector2 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, KRVector2 texture_scale, KRVector2 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, KRVector2 texture_scale, KRVector2 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, KRVector2 texture_scale, KRVector2 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;
@@ -186,19 +186,19 @@ KRMaterial::alpha_mode_type KRMaterial::getAlphaMode() {
return m_alpha_mode;
}
void KRMaterial::setAmbient(const KRVector3 &c) {
void KRMaterial::setAmbient(const Vector3 &c) {
m_ambientColor = c;
}
void KRMaterial::setDiffuse(const KRVector3 &c) {
void KRMaterial::setDiffuse(const Vector3 &c) {
m_diffuseColor = c;
}
void KRMaterial::setSpecular(const KRVector3 &c) {
void KRMaterial::setSpecular(const Vector3 &c) {
m_specularColor = c;
}
void KRMaterial::setReflection(const KRVector3 &c) {
void KRMaterial::setReflection(const Vector3 &c) {
m_reflectionColor = c;
}
@@ -302,15 +302,15 @@ void KRMaterial::getTextures()
}
}
bool KRMaterial::bind(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const std::vector<KRBone *> &bones, const std::vector<KRMat4> &bind_poses, const KRViewport &viewport, const KRMat4 &matModel, KRTexture *pLightMap, KRNode::RenderPass renderPass, const KRVector3 &rim_color, float rim_power, float lod_coverage) {
bool KRMaterial::bind(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const std::vector<KRBone *> &bones, const std::vector<Matrix4> &bind_poses, const KRViewport &viewport, const Matrix4 &matModel, KRTexture *pLightMap, KRNode::RenderPass renderPass, const Vector3 &rim_color, float rim_power, float lod_coverage) {
bool bLightMap = pLightMap && pCamera->settings.bEnableLightMap;
getTextures();
KRVector2 default_scale = KRVector2::One();
KRVector2 default_offset = KRVector2::Zero();
Vector2 default_scale = Vector2::One();
Vector2 default_offset = Vector2::Zero();
bool bHasReflection = m_reflectionColor != KRVector3::Zero();
bool bHasReflection = m_reflectionColor != Vector3::Zero();
bool bDiffuseMap = m_pDiffuseMap != NULL && pCamera->settings.bEnableDiffuseMap;
bool bNormalMap = m_pNormalMap != NULL && pCamera->settings.bEnableNormalMap;
bool bSpecMap = m_pSpecularMap != NULL && pCamera->settings.bEnableSpecMap;
@@ -322,7 +322,7 @@ bool KRMaterial::bind(KRCamera *pCamera, std::vector<KRPointLight *> &point_ligh
KRShader *pShader = getContext().getShaderManager()->getShader("ObjectShader", pCamera, point_lights, directional_lights, spot_lights, bones.size(), bDiffuseMap, bNormalMap, bSpecMap, bReflectionMap, bReflectionCubeMap, bLightMap, m_diffuseMapScale != default_scale && bDiffuseMap, m_specularMapScale != default_scale && bSpecMap, m_normalMapScale != default_scale && bNormalMap, m_reflectionMapScale != default_scale && bReflectionMap, m_diffuseMapOffset != default_offset && bDiffuseMap, m_specularMapOffset != default_offset && bSpecMap, m_normalMapOffset != default_offset && bNormalMap, m_reflectionMapOffset != default_offset && bReflectionMap, bAlphaTest, bAlphaBlend, renderPass, rim_power != 0.0f);
KRVector4 fade_color;
Vector4 fade_color;
if(!getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, matModel, point_lights, directional_lights, spot_lights, 0, renderPass, rim_color, rim_power, fade_color)) {
return false;
}
@@ -334,23 +334,23 @@ bool KRMaterial::bind(KRCamera *pCamera, std::vector<KRPointLight *> &point_ligh
for(int bone_index=0; bone_index < bones.size(); bone_index++) {
KRBone *bone = bones[bone_index];
// KRVector3 initialRotation = bone->getInitialLocalRotation();
// KRVector3 rotation = bone->getLocalRotation();
// KRVector3 initialTranslation = bone->getInitialLocalTranslation();
// KRVector3 translation = bone->getLocalTranslation();
// KRVector3 initialScale = bone->getInitialLocalScale();
// KRVector3 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);
KRMat4 skin_bone_bind_pose = bind_poses[bone_index];
KRMat4 active_mat = bone->getActivePoseMatrix();
KRMat4 inv_bind_mat = bone->getInverseBindPoseMatrix();
KRMat4 inv_bind_mat2 = KRMat4::Invert(bind_poses[bone_index]);
KRMat4 t = (inv_bind_mat * active_mat);
KRMat4 t2 = inv_bind_mat2 * bone->getModelMatrix();
Matrix4 skin_bone_bind_pose = bind_poses[bone_index];
Matrix4 active_mat = bone->getActivePoseMatrix();
Matrix4 inv_bind_mat = bone->getInverseBindPoseMatrix();
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++) {
*bone_mat_component++ = t[i];
}
@@ -365,14 +365,14 @@ bool KRMaterial::bind(KRCamera *pCamera, std::vector<KRPointLight *> &point_ligh
if(renderPass == KRNode::RENDER_PASS_FORWARD_OPAQUE) {
// We pre-multiply the light color with the material color in the forward renderer
pShader->setUniform(KRShader::KRENGINE_UNIFORM_MATERIAL_DIFFUSE, KRVector3(m_diffuseColor.x * pCamera->settings.light_intensity.x, m_diffuseColor.y * pCamera->settings.light_intensity.y, m_diffuseColor.z * pCamera->settings.light_intensity.z));
pShader->setUniform(KRShader::KRENGINE_UNIFORM_MATERIAL_DIFFUSE, Vector3(m_diffuseColor.x * pCamera->settings.light_intensity.x, m_diffuseColor.y * pCamera->settings.light_intensity.y, m_diffuseColor.z * pCamera->settings.light_intensity.z));
} else {
pShader->setUniform(KRShader::KRENGINE_UNIFORM_MATERIAL_DIFFUSE, m_diffuseColor);
}
if(renderPass == KRNode::RENDER_PASS_FORWARD_OPAQUE) {
// We pre-multiply the light color with the material color in the forward renderer
pShader->setUniform(KRShader::KRENGINE_UNIFORM_MATERIAL_SPECULAR, KRVector3(m_specularColor.x * pCamera->settings.light_intensity.x, m_specularColor.y * pCamera->settings.light_intensity.y, m_specularColor.z * pCamera->settings.light_intensity.z));
pShader->setUniform(KRShader::KRENGINE_UNIFORM_MATERIAL_SPECULAR, Vector3(m_specularColor.x * pCamera->settings.light_intensity.x, m_specularColor.y * pCamera->settings.light_intensity.y, m_specularColor.z * pCamera->settings.light_intensity.z));
} else {
pShader->setUniform(KRShader::KRENGINE_UNIFORM_MATERIAL_SPECULAR, m_specularColor);
}

View File

@@ -36,8 +36,6 @@
#include "KRShader.h"
#include "KRCamera.h"
#include "KRResource.h"
#include "KRVector2.h"
#include "KRVector3.h"
#include "KRScene.h"
#include "KRBone.h"
@@ -65,16 +63,16 @@ public:
virtual bool save(KRDataBlock &data);
void setAmbientMap(std::string texture_name, KRVector2 texture_scale, KRVector2 texture_offset);
void setDiffuseMap(std::string texture_name, KRVector2 texture_scale, KRVector2 texture_offset);
void setSpecularMap(std::string texture_name, KRVector2 texture_scale, KRVector2 texture_offset);
void setReflectionMap(std::string texture_name, KRVector2 texture_scale, KRVector2 texture_offset);
void setAmbientMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset);
void setDiffuseMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset);
void setSpecularMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset);
void setReflectionMap(std::string texture_name, Vector2 texture_scale, Vector2 texture_offset);
void setReflectionCube(std::string texture_name);
void setNormalMap(std::string texture_name, KRVector2 texture_scale, KRVector2 texture_offset);
void setAmbient(const KRVector3 &c);
void setDiffuse(const KRVector3 &c);
void setSpecular(const KRVector3 &c);
void setReflection(const KRVector3 &c);
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 setTransparency(GLfloat a);
void setShininess(GLfloat s);
void setAlphaMode(alpha_mode_type blend_mode);
@@ -84,7 +82,7 @@ public:
bool isTransparent();
const std::string &getName() const;
bool bind(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const std::vector<KRBone *> &bones, const std::vector<KRMat4> &bind_poses, const KRViewport &viewport, const KRMat4 &matModel, KRTexture *pLightMap, KRNode::RenderPass renderPass, const KRVector3 &rim_color, float rim_power, float lod_coverage = 0.0f);
bool bind(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const std::vector<KRBone *> &bones, const std::vector<Matrix4> &bind_poses, const KRViewport &viewport, const Matrix4 &matModel, KRTexture *pLightMap, KRNode::RenderPass renderPass, const Vector3 &rim_color, float rim_power, float lod_coverage = 0.0f);
bool needsVertexTangents();
@@ -107,21 +105,21 @@ private:
std::string m_reflectionCube;
std::string m_normalMap;
KRVector2 m_ambientMapScale;
KRVector2 m_ambientMapOffset;
KRVector2 m_diffuseMapScale;
KRVector2 m_diffuseMapOffset;
KRVector2 m_specularMapScale;
KRVector2 m_specularMapOffset;
KRVector2 m_reflectionMapScale;
KRVector2 m_reflectionMapOffset;
KRVector2 m_normalMapScale;
KRVector2 m_normalMapOffset;
Vector2 m_ambientMapScale;
Vector2 m_ambientMapOffset;
Vector2 m_diffuseMapScale;
Vector2 m_diffuseMapOffset;
Vector2 m_specularMapScale;
Vector2 m_specularMapOffset;
Vector2 m_reflectionMapScale;
Vector2 m_reflectionMapOffset;
Vector2 m_normalMapScale;
Vector2 m_normalMapOffset;
KRVector3 m_ambientColor; // Ambient rgb
KRVector3 m_diffuseColor; // Diffuse rgb
KRVector3 m_specularColor; // Specular rgb
KRVector3 m_reflectionColor; // Reflection rgb
Vector3 m_ambientColor; // Ambient rgb
Vector3 m_diffuseColor; // Diffuse rgb
Vector3 m_specularColor; // Specular rgb
Vector3 m_reflectionColor; // Reflection rgb
//GLfloat m_ka_r, m_ka_g, m_ka_b; // Ambient rgb
//GLfloat m_kd_r, m_kd_g, m_kd_b; // Diffuse rgb

View File

@@ -162,49 +162,49 @@ bool KRMaterialManager::load(const char *szName, KRDataBlock *data) {
char *pScan2 = szSymbol[1];
float r = strtof(pScan2, &pScan2);
if(cSymbols == 2) {
pMaterial->setAmbient(KRVector3(r, r, r));
pMaterial->setAmbient(Vector3(r, r, r));
} else if(cSymbols == 4) {
pScan2 = szSymbol[2];
float g = strtof(pScan2, &pScan2);
pScan2 = szSymbol[3];
float b = strtof(pScan2, &pScan2);
pMaterial->setAmbient(KRVector3(r, g, b));
pMaterial->setAmbient(Vector3(r, g, b));
}
} else if(strcmp(szSymbol[0], "kd") == 0) {
char *pScan2 = szSymbol[1];
float r = strtof(pScan2, &pScan2);
if(cSymbols == 2) {
pMaterial->setDiffuse(KRVector3(r, r, r));
pMaterial->setDiffuse(Vector3(r, r, r));
} else if(cSymbols == 4) {
pScan2 = szSymbol[2];
float g = strtof(pScan2, &pScan2);
pScan2 = szSymbol[3];
float b = strtof(pScan2, &pScan2);
pMaterial->setDiffuse(KRVector3(r, g, b));
pMaterial->setDiffuse(Vector3(r, g, b));
}
} else if(strcmp(szSymbol[0], "ks") == 0) {
char *pScan2 = szSymbol[1];
float r = strtof(pScan2, &pScan2);
if(cSymbols == 2) {
pMaterial->setSpecular(KRVector3(r, r, r));
pMaterial->setSpecular(Vector3(r, r, r));
} else if(cSymbols == 4) {
pScan2 = szSymbol[2];
float g = strtof(pScan2, &pScan2);
pScan2 = szSymbol[3];
float b = strtof(pScan2, &pScan2);
pMaterial->setSpecular(KRVector3(r, g, b));
pMaterial->setSpecular(Vector3(r, g, b));
}
} else if(strcmp(szSymbol[0], "kr") == 0) {
char *pScan2 = szSymbol[1];
float r = strtof(pScan2, &pScan2);
if(cSymbols == 2) {
pMaterial->setReflection(KRVector3(r, r, r));
pMaterial->setReflection(Vector3(r, r, r));
} else if(cSymbols == 4) {
pScan2 = szSymbol[2];
float g = strtof(pScan2, &pScan2);
pScan2 = szSymbol[3];
float b = strtof(pScan2, &pScan2);
pMaterial->setReflection(KRVector3(r, g, b));
pMaterial->setReflection(Vector3(r, g, b));
}
} else if(strcmp(szSymbol[0], "tr") == 0) {
char *pScan2 = szSymbol[1];
@@ -228,8 +228,8 @@ bool KRMaterialManager::load(const char *szName, KRDataBlock *data) {
*pLastPeriod = '\0';
}
KRVector2 texture_scale = KRVector2(1.0f, 1.0f);
KRVector2 texture_offset = KRVector2(0.0f, 0.0f);
Vector2 texture_scale = Vector2(1.0f, 1.0f);
Vector2 texture_offset = Vector2(0.0f, 0.0f);
int iScanSymbol = 2;
int iScaleParam = -1;

View File

@@ -34,8 +34,6 @@
#include "KRMesh.h"
#include "KRVector3.h"
#include "KRTriangle3.h"
#include "KRShader.h"
#include "KRShaderManager.h"
#include "KRContext.h"
@@ -161,8 +159,8 @@ void KRMesh::loadPack(KRDataBlock *data) {
m_pIndexBaseData = m_pData->getSubBlock(sizeof(pack_header) + sizeof(pack_material) * ph.submesh_count + sizeof(pack_bone) * ph.bone_count + KRALIGN(2 * ph.index_count), ph.index_base_count * 8);
m_pIndexBaseData->lock();
m_minPoint = KRVector3(ph.minx, ph.miny, ph.minz);
m_maxPoint = KRVector3(ph.maxx, ph.maxy, ph.maxz);
m_minPoint = Vector3(ph.minx, ph.miny, ph.minz);
m_maxPoint = Vector3(ph.maxx, ph.maxy, ph.maxz);
updateAttributeOffsets();
}
@@ -256,7 +254,7 @@ kraken_stream_level KRMesh::getStreamLevel()
return stream_level;
}
void KRMesh::render(const std::string &object_name, KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, const KRMat4 &matModel, KRTexture *pLightMap, KRNode::RenderPass renderPass, const std::vector<KRBone *> &bones, const KRVector3 &rim_color, float rim_power, float lod_coverage) {
void KRMesh::render(const std::string &object_name, KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, const Matrix4 &matModel, KRTexture *pLightMap, KRNode::RenderPass renderPass, const std::vector<KRBone *> &bones, const Vector3 &rim_color, float rim_power, float lod_coverage) {
//fprintf(stderr, "Rendering model: %s\n", m_name.c_str());
if(renderPass != KRNode::RENDER_PASS_ADDITIVE_PARTICLES && renderPass != KRNode::RENDER_PASS_PARTICLE_OCCLUSION && renderPass != KRNode::RENDER_PASS_VOLUMETRIC_EFFECTS_ADDITIVE) {
@@ -290,7 +288,7 @@ void KRMesh::render(const std::string &object_name, KRCamera *pCamera, std::vect
if(pMaterial != NULL && pMaterial == (*mat_itr)) {
if((!pMaterial->isTransparent() && renderPass != KRNode::RENDER_PASS_FORWARD_TRANSPARENT) || (pMaterial->isTransparent() && renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT)) {
std::vector<KRMat4> bone_bind_poses;
std::vector<Matrix4> bone_bind_poses;
for(int i=0; i < bones.size(); i++) {
bone_bind_poses.push_back(getBoneBindPose(i));
}
@@ -534,7 +532,7 @@ void KRMesh::LoadData(const KRMesh::mesh_info &mi, bool calculate_normals, bool
bool use_short_uvb = true;
if(use_short_vertexes) {
for(std::vector<KRVector3>::const_iterator itr=mi.vertices.begin(); itr != mi.vertices.end(); itr++) {
for(std::vector<Vector3>::const_iterator itr=mi.vertices.begin(); itr != mi.vertices.end(); itr++) {
if(fabsf((*itr).x) > 1.0f || fabsf((*itr).y) > 1.0f || fabsf((*itr).z) > 1.0f) {
use_short_vertexes = false;
}
@@ -542,7 +540,7 @@ void KRMesh::LoadData(const KRMesh::mesh_info &mi, bool calculate_normals, bool
}
if(use_short_uva) {
for(std::vector<KRVector2>::const_iterator itr=mi.uva.begin(); itr != mi.uva.end(); itr++) {
for(std::vector<Vector2>::const_iterator itr=mi.uva.begin(); itr != mi.uva.end(); itr++) {
if(fabsf((*itr).x) > 1.0f || fabsf((*itr).y) > 1.0f) {
use_short_uva = false;
}
@@ -550,7 +548,7 @@ void KRMesh::LoadData(const KRMesh::mesh_info &mi, bool calculate_normals, bool
}
if(use_short_uvb) {
for(std::vector<KRVector2>::const_iterator itr=mi.uvb.begin(); itr != mi.uvb.end(); itr++) {
for(std::vector<Vector2>::const_iterator itr=mi.uvb.begin(); itr != mi.uvb.end(); itr++) {
if(fabsf((*itr).x) > 1.0f || fabsf((*itr).y) > 1.0f) {
use_short_uvb = false;
}
@@ -640,7 +638,7 @@ void KRMesh::LoadData(const KRMesh::mesh_info &mi, bool calculate_normals, bool
memset(getVertexData(), 0, m_vertex_size * mi.vertices.size());
for(int iVertex=0; iVertex < mi.vertices.size(); iVertex++) {
KRVector3 source_vertex = mi.vertices[iVertex];
Vector3 source_vertex = mi.vertices[iVertex];
setVertexPosition(iVertex, source_vertex);
if(mi.bone_names.size()) {
for(int bone_weight_index=0; bone_weight_index<KRENGINE_MAX_BONE_WEIGHTS_PER_VERTEX; bone_weight_index++) {
@@ -667,10 +665,10 @@ void KRMesh::LoadData(const KRMesh::mesh_info &mi, bool calculate_normals, bool
setVertexUVB(iVertex, mi.uvb[iVertex]);
}
if(mi.normals.size() > iVertex) {
setVertexNormal(iVertex, KRVector3::Normalize(mi.normals[iVertex]));
setVertexNormal(iVertex, Vector3::Normalize(mi.normals[iVertex]));
}
if(mi.tangents.size() > iVertex) {
setVertexTangent(iVertex, KRVector3::Normalize(mi.tangents[iVertex]));
setVertexTangent(iVertex, Vector3::Normalize(mi.tangents[iVertex]));
}
}
@@ -699,19 +697,19 @@ void KRMesh::LoadData(const KRMesh::mesh_info &mi, bool calculate_normals, bool
if(calculate_normals || calculate_tangents) {
// NOTE: This will not work properly if the vertices are already indexed
for(int iVertex=0; iVertex < mi.vertices.size(); iVertex+= 3) {
KRVector3 p1 = getVertexPosition(iVertex);
KRVector3 p2 = getVertexPosition(iVertex+1);
KRVector3 p3 = getVertexPosition(iVertex+2);
KRVector3 v1 = p2 - p1;
KRVector3 v2 = p3 - p1;
Vector3 p1 = getVertexPosition(iVertex);
Vector3 p2 = getVertexPosition(iVertex+1);
Vector3 p3 = getVertexPosition(iVertex+2);
Vector3 v1 = p2 - p1;
Vector3 v2 = p3 - p1;
// -- Calculate normal if missing --
if(calculate_normals) {
KRVector3 first_normal = getVertexNormal(iVertex);
Vector3 first_normal = getVertexNormal(iVertex);
if(first_normal.x == 0.0f && first_normal.y == 0.0f && first_normal.z == 0.0f) {
// Note - We don't take into consideration smoothing groups or smoothing angles when generating normals; all generated normals represent flat shaded polygons
KRVector3 normal = KRVector3::Cross(v1, v2);
Vector3 normal = Vector3::Cross(v1, v2);
normal.normalize();
setVertexNormal(iVertex, normal);
@@ -722,18 +720,18 @@ void KRMesh::LoadData(const KRMesh::mesh_info &mi, bool calculate_normals, bool
// -- Calculate tangent vector for normal mapping --
if(calculate_tangents) {
KRVector3 first_tangent = getVertexTangent(iVertex);
Vector3 first_tangent = getVertexTangent(iVertex);
if(first_tangent.x == 0.0f && first_tangent.y == 0.0f && first_tangent.z == 0.0f) {
KRVector2 uv0 = getVertexUVA(iVertex);
KRVector2 uv1 = getVertexUVA(iVertex + 1);
KRVector2 uv2 = getVertexUVA(iVertex + 2);
Vector2 uv0 = getVertexUVA(iVertex);
Vector2 uv1 = getVertexUVA(iVertex + 1);
Vector2 uv2 = getVertexUVA(iVertex + 2);
KRVector2 st1 = KRVector2(uv1.x - uv0.x, uv1.y - uv0.y);
KRVector2 st2 = KRVector2(uv2.x - uv0.x, uv2.y - uv0.y);
Vector2 st1 = Vector2(uv1.x - uv0.x, uv1.y - uv0.y);
Vector2 st2 = Vector2(uv2.x - uv0.x, uv2.y - uv0.y);
double coef = 1/ (st1.x * st2.y - st2.x * st1.y);
KRVector3 tangent(
Vector3 tangent(
coef * ((v1.x * st2.y) + (v2.x * -st1.y)),
coef * ((v1.y * st2.y) + (v2.y * -st1.y)),
coef * ((v1.z * st2.y) + (v2.z * -st1.y))
@@ -764,11 +762,11 @@ void KRMesh::LoadData(const KRMesh::mesh_info &mi, bool calculate_normals, bool
optimize();
}
KRVector3 KRMesh::getMinPoint() const {
Vector3 KRMesh::getMinPoint() const {
return m_minPoint;
}
KRVector3 KRMesh::getMaxPoint() const {
Vector3 KRMesh::getMaxPoint() const {
return m_maxPoint;
}
@@ -859,67 +857,67 @@ int KRMesh::getVertexCount(int submesh) const
return getSubmesh(submesh)->vertex_count;
}
KRVector3 KRMesh::getVertexPosition(int index) const
Vector3 KRMesh::getVertexPosition(int index) const
{
if(has_vertex_attribute(KRENGINE_ATTRIB_VERTEX_SHORT)) {
short *v = (short *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_VERTEX_SHORT]);
return KRVector3((float)v[0] / 32767.0f, (float)v[1] / 32767.0f, (float)v[2] / 32767.0f);
return Vector3((float)v[0] / 32767.0f, (float)v[1] / 32767.0f, (float)v[2] / 32767.0f);
} else if(has_vertex_attribute(KRENGINE_ATTRIB_VERTEX)) {
return KRVector3((float *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_VERTEX]));
return Vector3((float *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_VERTEX]));
} else {
return KRVector3::Zero();
return Vector3::Zero();
}
}
KRVector3 KRMesh::getVertexNormal(int index) const
Vector3 KRMesh::getVertexNormal(int index) const
{
if(has_vertex_attribute(KRENGINE_ATTRIB_NORMAL_SHORT)) {
short *v = (short *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_NORMAL_SHORT]);
return KRVector3((float)v[0] / 32767.0f, (float)v[1] / 32767.0f, (float)v[2] / 32767.0f);
return Vector3((float)v[0] / 32767.0f, (float)v[1] / 32767.0f, (float)v[2] / 32767.0f);
} else if(has_vertex_attribute(KRENGINE_ATTRIB_NORMAL)) {
return KRVector3((float *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_NORMAL]));
return Vector3((float *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_NORMAL]));
} else {
return KRVector3::Zero();
return Vector3::Zero();
}
}
KRVector3 KRMesh::getVertexTangent(int index) const
Vector3 KRMesh::getVertexTangent(int index) const
{
if(has_vertex_attribute(KRENGINE_ATTRIB_TANGENT_SHORT)) {
short *v = (short *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_TANGENT_SHORT]);
return KRVector3((float)v[0] / 32767.0f, (float)v[1] / 32767.0f, (float)v[2] / 32767.0f);
return Vector3((float)v[0] / 32767.0f, (float)v[1] / 32767.0f, (float)v[2] / 32767.0f);
} else if(has_vertex_attribute(KRENGINE_ATTRIB_TANGENT)) {
return KRVector3((float *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_TANGENT]));
return Vector3((float *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_TANGENT]));
} else {
return KRVector3::Zero();
return Vector3::Zero();
}
}
KRVector2 KRMesh::getVertexUVA(int index) const
Vector2 KRMesh::getVertexUVA(int index) const
{
if(has_vertex_attribute(KRENGINE_ATTRIB_TEXUVA_SHORT)) {
short *v = (short *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_TEXUVA_SHORT]);
return KRVector2((float)v[0] / 32767.0f, (float)v[1] / 32767.0f);
return Vector2((float)v[0] / 32767.0f, (float)v[1] / 32767.0f);
} else if(has_vertex_attribute(KRENGINE_ATTRIB_TEXUVA)) {
return KRVector2((float *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_TEXUVA]));
return Vector2((float *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_TEXUVA]));
} else {
return KRVector2::Zero();
return Vector2::Zero();
}
}
KRVector2 KRMesh::getVertexUVB(int index) const
Vector2 KRMesh::getVertexUVB(int index) const
{
if(has_vertex_attribute(KRENGINE_ATTRIB_TEXUVB_SHORT)) {
short *v = (short *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_TEXUVB_SHORT]);
return KRVector2((float)v[0] / 32767.0f, (float)v[1] / 32767.0f);
return Vector2((float)v[0] / 32767.0f, (float)v[1] / 32767.0f);
} else if(has_vertex_attribute(KRENGINE_ATTRIB_TEXUVB)) {
return KRVector2((float *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_TEXUVB]));
return Vector2((float *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_TEXUVB]));
} else {
return KRVector2::Zero();
return Vector2::Zero();
}
}
void KRMesh::setVertexPosition(int index, const KRVector3 &v)
void KRMesh::setVertexPosition(int index, const Vector3 &v)
{
if(has_vertex_attribute(KRENGINE_ATTRIB_VERTEX_SHORT)) {
short *vert = (short *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_VERTEX_SHORT]);
@@ -934,7 +932,7 @@ void KRMesh::setVertexPosition(int index, const KRVector3 &v)
}
}
void KRMesh::setVertexNormal(int index, const KRVector3 &v)
void KRMesh::setVertexNormal(int index, const Vector3 &v)
{
if(has_vertex_attribute(KRENGINE_ATTRIB_NORMAL_SHORT)) {
short *vert = (short *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_NORMAL_SHORT]);
@@ -949,7 +947,7 @@ void KRMesh::setVertexNormal(int index, const KRVector3 &v)
}
}
void KRMesh::setVertexTangent(int index, const KRVector3 & v)
void KRMesh::setVertexTangent(int index, const Vector3 & v)
{
if(has_vertex_attribute(KRENGINE_ATTRIB_TANGENT_SHORT)) {
short *vert = (short *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_TANGENT_SHORT]);
@@ -964,7 +962,7 @@ void KRMesh::setVertexTangent(int index, const KRVector3 & v)
}
}
void KRMesh::setVertexUVA(int index, const KRVector2 &v)
void KRMesh::setVertexUVA(int index, const Vector2 &v)
{
if(has_vertex_attribute(KRENGINE_ATTRIB_TEXUVA_SHORT)) {
short *vert = (short *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_TEXUVA_SHORT]);
@@ -977,7 +975,7 @@ void KRMesh::setVertexUVA(int index, const KRVector2 &v)
}
}
void KRMesh::setVertexUVB(int index, const KRVector2 &v)
void KRMesh::setVertexUVB(int index, const Vector2 &v)
{
if(has_vertex_attribute(KRENGINE_ATTRIB_TEXUVB_SHORT)) {
short *vert = (short *)(getVertexData(index) + m_vertex_attribute_offset[KRENGINE_ATTRIB_TEXUVB_SHORT]);
@@ -1095,9 +1093,9 @@ char *KRMesh::getBoneName(int bone_index)
return getBone(bone_index)->szName;
}
KRMat4 KRMesh::getBoneBindPose(int bone_index)
Matrix4 KRMesh::getBoneBindPose(int bone_index)
{
return KRMat4(getBone(bone_index)->bind_pose);
return Matrix4(getBone(bone_index)->bind_pose);
}
KRMesh::model_format_t KRMesh::getModelFormat() const
@@ -1106,9 +1104,9 @@ KRMesh::model_format_t KRMesh::getModelFormat() const
return f;
}
bool KRMesh::rayCast(const KRVector3 &start, const KRVector3 &dir, const KRTriangle3 &tri, const KRVector3 &tri_n0, const KRVector3 &tri_n1, const KRVector3 &tri_n2, KRHitInfo &hitinfo)
bool KRMesh::rayCast(const Vector3 &start, const Vector3 &dir, const Triangle3 &tri, const Vector3 &tri_n0, const Vector3 &tri_n1, const Vector3 &tri_n2, KRHitInfo &hitinfo)
{
KRVector3 hit_point;
Vector3 hit_point;
if(tri.rayCast(start, dir, hit_point)) {
// ---===--- hit_point is in triangle ---===---
@@ -1124,7 +1122,7 @@ bool KRMesh::rayCast(const KRVector3 &start, const KRVector3 &dir, const KRTrian
distance_v0 /= distance_total;
distance_v1 /= distance_total;
distance_v2 /= distance_total;
KRVector3 normal = KRVector3::Normalize(tri_n0 * (1.0 - distance_v0) + tri_n1 * (1.0 - distance_v1) + tri_n2 * (1.0 - distance_v2));
Vector3 normal = Vector3::Normalize(tri_n0 * (1.0 - distance_v0) + tri_n1 * (1.0 - distance_v1) + tri_n2 * (1.0 - distance_v2));
hitinfo = KRHitInfo(hit_point, normal, new_hit_distance);
return true;
@@ -1140,7 +1138,7 @@ bool KRMesh::rayCast(const KRVector3 &start, const KRVector3 &dir, const KRTrian
}
bool KRMesh::rayCast(const KRVector3 &start, const KRVector3 &dir, KRHitInfo &hitinfo) const
bool KRMesh::rayCast(const Vector3 &start, const Vector3 &dir, KRHitInfo &hitinfo) const
{
m_pData->lock();
bool hit_found = false;
@@ -1156,7 +1154,7 @@ bool KRMesh::rayCast(const KRVector3 &start, const KRVector3 &dir, KRHitInfo &hi
tri_vert_index[1] = getTriangleVertexIndex(submesh_index, triangle_index*3 + 1);
tri_vert_index[2] = getTriangleVertexIndex(submesh_index, triangle_index*3 + 2);
KRTriangle3 tri = KRTriangle3(getVertexPosition(tri_vert_index[0]), getVertexPosition(tri_vert_index[1]), getVertexPosition(tri_vert_index[2]));
Triangle3 tri = Triangle3(getVertexPosition(tri_vert_index[0]), getVertexPosition(tri_vert_index[1]), getVertexPosition(tri_vert_index[2]));
if(rayCast(start, dir, tri, getVertexNormal(tri_vert_index[0]), getVertexNormal(tri_vert_index[1]), getVertexNormal(tri_vert_index[2]), hitinfo)) hit_found = true;
}
@@ -1186,7 +1184,7 @@ bool KRMesh::rayCast(const KRVector3 &start, const KRVector3 &dir, KRHitInfo &hi
}
bool KRMesh::sphereCast(const KRMat4 &model_to_world, const KRVector3 &v0, const KRVector3 &v1, float radius, KRHitInfo &hitinfo) const
bool KRMesh::sphereCast(const Matrix4 &model_to_world, const Vector3 &v0, const Vector3 &v1, float radius, KRHitInfo &hitinfo) const
{
m_pData->lock();
@@ -1202,12 +1200,12 @@ bool KRMesh::sphereCast(const KRMat4 &model_to_world, const KRVector3 &v0, const
tri_vert_index[1] = getTriangleVertexIndex(submesh_index, triangle_index*3 + 1);
tri_vert_index[2] = getTriangleVertexIndex(submesh_index, triangle_index*3 + 2);
KRTriangle3 tri = KRTriangle3(getVertexPosition(tri_vert_index[0]), getVertexPosition(tri_vert_index[1]), getVertexPosition(tri_vert_index[2]));
Triangle3 tri = Triangle3(getVertexPosition(tri_vert_index[0]), getVertexPosition(tri_vert_index[1]), getVertexPosition(tri_vert_index[2]));
if(sphereCast(model_to_world, v0, v1, radius, tri, hitinfo)) hit_found = true;
/*
KRTriangle3 tri2 = KRTriangle3(getVertexPosition(tri_vert_index[1]), getVertexPosition(tri_vert_index[0]), getVertexPosition(tri_vert_index[2]));
Triangle3 tri2 = Triangle3(getVertexPosition(tri_vert_index[1]), getVertexPosition(tri_vert_index[0]), getVertexPosition(tri_vert_index[2]));
if(sphereCast(model_to_world, v0, v1, radius, tri2, new_hitinfo)) hit_found = true;
*/
@@ -1238,16 +1236,16 @@ bool KRMesh::sphereCast(const KRMat4 &model_to_world, const KRVector3 &v0, const
return hit_found;
}
bool KRMesh::sphereCast(const KRMat4 &model_to_world, const KRVector3 &v0, const KRVector3 &v1, float radius, const KRTriangle3 &tri, KRHitInfo &hitinfo)
bool KRMesh::sphereCast(const Matrix4 &model_to_world, const Vector3 &v0, const Vector3 &v1, float radius, const Triangle3 &tri, KRHitInfo &hitinfo)
{
KRVector3 dir = KRVector3::Normalize(v1 - v0);
KRVector3 start = v0;
Vector3 dir = Vector3::Normalize(v1 - v0);
Vector3 start = v0;
KRVector3 new_hit_point;
Vector3 new_hit_point;
float new_hit_distance;
KRTriangle3 world_tri = KRTriangle3(KRMat4::Dot(model_to_world, tri[0]), KRMat4::Dot(model_to_world, tri[1]), KRMat4::Dot(model_to_world, tri[2]));
Triangle3 world_tri = Triangle3(Matrix4::Dot(model_to_world, tri[0]), Matrix4::Dot(model_to_world, tri[1]), Matrix4::Dot(model_to_world, tri[2]));
if(world_tri.sphereCast(start, dir, radius, new_hit_point, new_hit_distance)) {
if((!hitinfo.didHit() || hitinfo.getDistance() > new_hit_distance) && new_hit_distance <= (v1 - v0).magnitude()) {
@@ -1261,7 +1259,7 @@ bool KRMesh::sphereCast(const KRMat4 &model_to_world, const KRVector3 &v0, const
distance_v0 /= distance_total;
distance_v1 /= distance_total;
distance_v2 /= distance_total;
KRVector3 normal = KRVector3::Normalize(KRMat4::DotNoTranslate(model_to_world, (tri_n0 * (1.0 - distance_v0) + tri_n1 * (1.0 - distance_v1) + tri_n2 * (1.0 - distance_v2))));
Vector3 normal = Vector3::Normalize(Matrix4::DotNoTranslate(model_to_world, (tri_n0 * (1.0 - distance_v0) + tri_n1 * (1.0 - distance_v1) + tri_n2 * (1.0 - distance_v2))));
*/
hitinfo = KRHitInfo(new_hit_point, world_tri.calculateNormal(), new_hit_distance);
return true;
@@ -1271,11 +1269,11 @@ bool KRMesh::sphereCast(const KRMat4 &model_to_world, const KRVector3 &v0, const
return false;
}
bool KRMesh::lineCast(const KRVector3 &v0, const KRVector3 &v1, KRHitInfo &hitinfo) const
bool KRMesh::lineCast(const Vector3 &v0, const Vector3 &v1, KRHitInfo &hitinfo) const
{
m_pData->lock();
KRHitInfo new_hitinfo;
KRVector3 dir = KRVector3::Normalize(v1 - v0);
Vector3 dir = Vector3::Normalize(v1 - v0);
if(rayCast(v0, dir, new_hitinfo)) {
if((new_hitinfo.getPosition() - v0).sqrMagnitude() <= (v1 - v0).sqrMagnitude()) {
// The hit was between v1 and v2
@@ -1316,7 +1314,7 @@ void KRMesh::convertToIndexed()
}
if(submesh_index == 0 || vertex_index_offset + vertex_count > 0xffff) {
mi.vertex_index_bases.push_back(std::pair<int, int>(mi.vertex_indexes.size(), mi.vertices.size()));
mi.vertex_index_bases.push_back(std::pair<int, int>((int)mi.vertex_indexes.size(), (int)mi.vertices.size()));
vertex_index_offset = 0;
vertex_index_base_start_vertex = mi.vertices.size();
}
@@ -1335,11 +1333,11 @@ void KRMesh::convertToIndexed()
for(int i=0; i < vertex_count; i++) {
KRVector3 vertex_position = getVertexPosition(source_index);
KRVector2 vertex_uva = getVertexUVA(source_index);
KRVector2 vertex_uvb = getVertexUVB(source_index);
KRVector3 vertex_normal = getVertexNormal(source_index);
KRVector3 vertex_tangent = getVertexTangent(source_index);
Vector3 vertex_position = getVertexPosition(source_index);
Vector2 vertex_uva = getVertexUVA(source_index);
Vector2 vertex_uvb = getVertexUVB(source_index);
Vector3 vertex_normal = getVertexNormal(source_index);
Vector3 vertex_tangent = getVertexTangent(source_index);
std::vector<int> vertex_bone_indexes;
if(has_vertex_attribute(KRENGINE_ATTRIB_BONEINDEXES)) {
vertex_bone_indexes.push_back(getBoneIndex(source_index, 0));
@@ -1452,7 +1450,7 @@ void KRMesh::convertToIndexed()
}
if(vertex_index_offset + vertex_count > 0xffff) {
mi.vertex_index_bases.push_back(std::pair<int, int>(mi.vertex_indexes.size(), mi.vertices.size()));
mi.vertex_index_bases.push_back(std::pair<int, int>((int)mi.vertex_indexes.size(), (int)mi.vertices.size()));
vertex_index_offset = 0;
vertex_index_base_start_vertex = mi.vertices.size();
}

View File

@@ -3,17 +3,17 @@
// KREngine
//
// Copyright 2012 Kearwood Gilbert. All rights reserved.
//
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
//
// THIS SOFTWARE IS PROVIDED BY KEARWOOD GILBERT ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KEARWOOD GILBERT OR
@@ -23,21 +23,21 @@
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Kearwood Gilbert.
//
#include "KREngine-common.h"
#include "KRVector2.h"
#include "KRMat4.h"
#include "KRContext.h"
#include "KRBone.h"
#include "KRMeshManager.h"
#include "KREngine-common.h"
using namespace kraken;
#define MAX_VBO_SIZE 65535
#define KRENGINE_MAX_BONE_WEIGHTS_PER_VERTEX 4
#define KRENGINE_MAX_NAME_LENGTH 256
@@ -51,28 +51,25 @@
#include "KRMaterialManager.h"
#include "KRCamera.h"
#include "KRViewport.h"
#include "KRHitInfo.h"
class KRMaterial;
class KRNode;
class KRTriangle3;
class KRMesh : public KRResource {
public:
KRMesh(KRContext &context, std::string name, KRDataBlock *data);
KRMesh(KRContext &context, std::string name);
virtual ~KRMesh();
kraken_stream_level getStreamLevel();
void preStream(float lodCoverage);
bool hasTransparency();
typedef enum {
KRENGINE_ATTRIB_VERTEX = 0,
KRENGINE_ATTRIB_NORMAL,
@@ -88,54 +85,54 @@ public:
KRENGINE_ATTRIB_TEXUVB_SHORT,
KRENGINE_NUM_ATTRIBUTES
} vertex_attrib_t;
typedef enum {
KRENGINE_MODEL_FORMAT_TRIANGLES = 0,
KRENGINE_MODEL_FORMAT_STRIP,
KRENGINE_MODEL_FORMAT_INDEXED_TRIANGLES,
KRENGINE_MODEL_FORMAT_INDEXED_STRIP
} model_format_t;
typedef struct {
model_format_t format;
std::vector<KRVector3> vertices;
std::vector<Vector3> vertices;
std::vector<__uint16_t> vertex_indexes;
std::vector<std::pair<int, int> > vertex_index_bases;
std::vector<KRVector2> uva;
std::vector<KRVector2> uvb;
std::vector<KRVector3> normals;
std::vector<KRVector3> tangents;
std::vector<Vector2> uva;
std::vector<Vector2> uvb;
std::vector<Vector3> normals;
std::vector<Vector3> tangents;
std::vector<int> submesh_starts;
std::vector<int> submesh_lengths;
std::vector<std::string> material_names;
std::vector<std::string> bone_names;
std::vector<std::vector<int> > bone_indexes;
std::vector<KRMat4> bone_bind_poses;
std::vector<Matrix4> bone_bind_poses;
std::vector<std::vector<float> > bone_weights;
} mesh_info;
void render(const std::string &object_name, KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, const KRMat4 &matModel, KRTexture *pLightMap, KRNode::RenderPass renderPass, const std::vector<KRBone *> &bones, const KRVector3 &rim_color, float rim_power, float lod_coverage = 0.0f);
void render(const std::string &object_name, KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, const Matrix4 &matModel, KRTexture *pLightMap, KRNode::RenderPass renderPass, 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);
void LoadData(const mesh_info &mi, bool calculate_normals, bool calculate_tangents);
void loadPack(KRDataBlock *data);
void convertToIndexed();
void optimize();
void optimizeIndexes();
void renderSubmesh(int iSubmesh, KRNode::RenderPass renderPass, const std::string &object_name, const std::string &material_name, float lodCoverage);
GLfloat getMaxDimension();
KRVector3 getMinPoint() const;
KRVector3 getMaxPoint() const;
Vector3 getMinPoint() const;
Vector3 getMaxPoint() const;
class Submesh {
public:
Submesh() {};
@@ -150,7 +147,7 @@ public:
delete (*itr);
}
};
GLint start_vertex;
GLsizei vertex_count;
char szMaterialName[KRENGINE_MAX_NAME_LENGTH];
@@ -170,7 +167,7 @@ public:
int32_t vertex_count;
char szName[KRENGINE_MAX_NAME_LENGTH];
} pack_material;
typedef struct {
char szName[KRENGINE_MAX_NAME_LENGTH];
float bind_pose[16];
@@ -178,75 +175,75 @@ public:
int getLODCoverage() const;
std::string getLODBaseName() const;
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);
int getSubmeshCount() const;
int getVertexCount(int submesh) const;
int getTriangleVertexIndex(int submesh, int index) const;
KRVector3 getVertexPosition(int index) const;
KRVector3 getVertexNormal(int index) const;
KRVector3 getVertexTangent(int index) const;
KRVector2 getVertexUVA(int index) const;
KRVector2 getVertexUVB(int index) const;
Vector3 getVertexPosition(int index) const;
Vector3 getVertexNormal(int index) const;
Vector3 getVertexTangent(int index) const;
Vector2 getVertexUVA(int index) const;
Vector2 getVertexUVB(int index) const;
int getBoneIndex(int index, int weight_index) const;
float getBoneWeight(int index, int weight_index) const;
void setVertexPosition(int index, const KRVector3 &v);
void setVertexNormal(int index, const KRVector3 &v);
void setVertexTangent(int index, const KRVector3 & v);
void setVertexUVA(int index, const KRVector2 &v);
void setVertexUVB(int index, const KRVector2 &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);
static size_t VertexSizeForAttributes(__int32_t vertex_attrib_flags);
static size_t AttributeOffset(__int32_t vertex_attrib, __int32_t vertex_attrib_flags);
int getBoneCount();
char *getBoneName(int bone_index);
KRMat4 getBoneBindPose(int bone_index);
Matrix4 getBoneBindPose(int bone_index);
model_format_t getModelFormat() const;
bool lineCast(const KRVector3 &v0, const KRVector3 &v1, KRHitInfo &hitinfo) const;
bool rayCast(const KRVector3 &v0, const KRVector3 &dir, KRHitInfo &hitinfo) const;
bool sphereCast(const KRMat4 &model_to_world, const KRVector3 &v0, const KRVector3 &v1, float radius, KRHitInfo &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);
void load(); // Load immediately into the GPU rather than passing through the streamer
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;
void getSubmeshes();
void getMaterials();
static bool rayCast(const KRVector3 &start, const KRVector3 &dir, const KRTriangle3 &tri, const KRVector3 &tri_n0, const KRVector3 &tri_n1, const KRVector3 &tri_n2, KRHitInfo &hitinfo);
static bool sphereCast(const KRMat4 &model_to_world, const KRVector3 &v0, const KRVector3 &v1, float radius, const KRTriangle3 &tri, KRHitInfo &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;
bool m_hasTransparency;
KRVector3 m_minPoint, m_maxPoint;
Vector3 m_minPoint, m_maxPoint;
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)
@@ -259,16 +256,16 @@ private:
int32_t index_base_count;
unsigned char reserved[444]; // Pad out to 512 bytes
} pack_header;
vector<Submesh *> m_submeshes;
int m_vertex_attribute_offset[KRENGINE_NUM_ATTRIBUTES];
int m_vertex_size;
void updateAttributeOffsets();
void setName(const std::string name);
pack_material *getSubmesh(int mesh_index) const;
unsigned char *getVertexData() const;
size_t getVertexDataOffset() const;
@@ -278,15 +275,15 @@ private:
__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 releaseData();
void createDataBlocks(KRMeshManager::KRVBOData::vbo_type t);
};

View File

@@ -38,20 +38,20 @@ KRMeshCube::KRMeshCube(KRContext &context) : KRMesh(context, "__cube")
KRMesh::mesh_info mi;
mi.vertices.push_back(KRVector3(1.0, 1.0, 1.0));
mi.vertices.push_back(KRVector3(-1.0, 1.0, 1.0));
mi.vertices.push_back(KRVector3(1.0,-1.0, 1.0));
mi.vertices.push_back(KRVector3(-1.0,-1.0, 1.0));
mi.vertices.push_back(KRVector3(-1.0,-1.0,-1.0));
mi.vertices.push_back(KRVector3(-1.0, 1.0, 1.0));
mi.vertices.push_back(KRVector3(-1.0, 1.0,-1.0));
mi.vertices.push_back(KRVector3(1.0, 1.0, 1.0));
mi.vertices.push_back(KRVector3(1.0, 1.0,-1.0));
mi.vertices.push_back(KRVector3(1.0,-1.0, 1.0));
mi.vertices.push_back(KRVector3(1.0,-1.0,-1.0));
mi.vertices.push_back(KRVector3(-1.0,-1.0,-1.0));
mi.vertices.push_back(KRVector3(1.0, 1.0,-1.0));
mi.vertices.push_back(KRVector3(-1.0, 1.0,-1.0));
mi.vertices.push_back(Vector3(1.0, 1.0, 1.0));
mi.vertices.push_back(Vector3(-1.0, 1.0, 1.0));
mi.vertices.push_back(Vector3(1.0,-1.0, 1.0));
mi.vertices.push_back(Vector3(-1.0,-1.0, 1.0));
mi.vertices.push_back(Vector3(-1.0,-1.0,-1.0));
mi.vertices.push_back(Vector3(-1.0, 1.0, 1.0));
mi.vertices.push_back(Vector3(-1.0, 1.0,-1.0));
mi.vertices.push_back(Vector3(1.0, 1.0, 1.0));
mi.vertices.push_back(Vector3(1.0, 1.0,-1.0));
mi.vertices.push_back(Vector3(1.0,-1.0, 1.0));
mi.vertices.push_back(Vector3(1.0,-1.0,-1.0));
mi.vertices.push_back(Vector3(-1.0,-1.0,-1.0));
mi.vertices.push_back(Vector3(1.0, 1.0,-1.0));
mi.vertices.push_back(Vector3(-1.0, 1.0,-1.0));
mi.submesh_starts.push_back(0);

View File

@@ -127,7 +127,7 @@ public:
GLfloat x;
GLfloat y;
GLfloat z;
} KRVector3D;
} Vector3D;
typedef struct {
GLfloat u;
@@ -135,12 +135,12 @@ public:
} TexCoord;
typedef struct {
KRVector3D vertex;
Vector3D vertex;
TexCoord uva;
} RandomParticleVertexData;
typedef struct {
KRVector3D vertex;
Vector3D vertex;
} VolumetricLightingVertexData;

View File

@@ -38,15 +38,15 @@ KRMeshQuad::KRMeshQuad(KRContext &context) : KRMesh(context, "__quad")
KRMesh::mesh_info mi;
mi.vertices.push_back(KRVector3(-1.0f, -1.0f, 0.0f));
mi.vertices.push_back(KRVector3(1.0f, -1.0f, 0.0f));
mi.vertices.push_back(KRVector3(-1.0f, 1.0f, 0.0f));
mi.vertices.push_back(KRVector3(1.0f, 1.0f, 0.0f));
mi.vertices.push_back(Vector3(-1.0f, -1.0f, 0.0f));
mi.vertices.push_back(Vector3(1.0f, -1.0f, 0.0f));
mi.vertices.push_back(Vector3(-1.0f, 1.0f, 0.0f));
mi.vertices.push_back(Vector3(1.0f, 1.0f, 0.0f));
mi.uva.push_back(KRVector2(0.0f, 0.0f));
mi.uva.push_back(KRVector2(1.0f, 0.0f));
mi.uva.push_back(KRVector2(0.0f, 1.0f));
mi.uva.push_back(KRVector2(1.0f, 1.0f));
mi.uva.push_back(Vector2(0.0f, 0.0f));
mi.uva.push_back(Vector2(1.0f, 0.0f));
mi.uva.push_back(Vector2(0.0f, 1.0f));
mi.uva.push_back(Vector2(1.0f, 1.0f));
mi.submesh_starts.push_back(0);

View File

@@ -52,25 +52,25 @@ KRMeshSphere::KRMeshSphere(KRContext &context) : KRMesh(context, "__sphere")
~Facet3() {
}
KRVector3 p1;
KRVector3 p2;
KRVector3 p3;
Vector3 p1;
Vector3 p2;
Vector3 p3;
};
std::vector<Facet3> f = std::vector<Facet3>(facet_count);
int i,it;
float a;
KRVector3 p[6] = {
KRVector3(0,0,1),
KRVector3(0,0,-1),
KRVector3(-1,-1,0),
KRVector3(1,-1,0),
KRVector3(1,1,0),
KRVector3(-1,1,0)
Vector3 p[6] = {
Vector3(0,0,1),
Vector3(0,0,-1),
Vector3(-1,-1,0),
Vector3(1,-1,0),
Vector3(1,1,0),
Vector3(-1,1,0)
};
KRVector3 pa,pb,pc;
Vector3 pa,pb,pc;
int nt = 0,ntold;
/* Create the level 0 object */

View File

@@ -34,9 +34,8 @@
#include "KRModel.h"
#include "KRContext.h"
#include "KRMesh.h"
#include "KRQuaternion.h"
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, KRVector3 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;
@@ -80,12 +79,12 @@ tinyxml2::XMLElement *KRModel::saveXML( tinyxml2::XMLNode *parent)
e->SetAttribute("lod_min_coverage", m_min_lod_coverage);
e->SetAttribute("receives_shadow", m_receivesShadow ? "true" : "false");
e->SetAttribute("faces_camera", m_faces_camera ? "true" : "false");
m_rim_color.setXMLAttribute("rim_color", e, KRVector3::Zero());
kraken::setXMLAttribute("rim_color", e, m_rim_color, Vector3::Zero());
e->SetAttribute("rim_power", m_rim_power);
return e;
}
void KRModel::setRimColor(const KRVector3 &rim_color)
void KRModel::setRimColor(const Vector3 &rim_color)
{
m_rim_color = rim_color;
}
@@ -95,7 +94,7 @@ void KRModel::setRimPower(float rim_power)
m_rim_power = rim_power;
}
KRVector3 KRModel::getRimColor()
Vector3 KRModel::getRimColor()
{
return m_rim_color;
}
@@ -197,11 +196,11 @@ void KRModel::render(KRCamera *pCamera, std::vector<KRPointLight *> &point_light
m_pContext->getTextureManager()->selectTexture(5, m_pLightMap, lod_coverage, KRTexture::TEXTURE_USAGE_LIGHT_MAP);
}
KRMat4 matModel = getModelMatrix();
Matrix4 matModel = getModelMatrix();
if(m_faces_camera) {
KRVector3 model_center = KRMat4::Dot(matModel, KRVector3::Zero());
KRVector3 camera_pos = viewport.getCameraPosition();
matModel = KRQuaternion(KRVector3::Forward(), KRVector3::Normalize(camera_pos - model_center)).rotationMatrix() * matModel;
Vector3 model_center = Matrix4::Dot(matModel, Vector3::Zero());
Vector3 camera_pos = viewport.getCameraPosition();
matModel = Quaternion(Vector3::Forward(), Vector3::Normalize(camera_pos - model_center)).rotationMatrix() * matModel;
}
pModel->render(getName(), pCamera, point_lights, directional_lights, spot_lights, viewport, matModel, m_pLightMap, renderPass, m_bones[pModel], m_rim_color, m_rim_power, lod_coverage);
@@ -242,23 +241,23 @@ kraken_stream_level KRModel::getStreamLevel(const KRViewport &viewport)
return stream_level;
}
KRAABB KRModel::getBounds() {
AABB KRModel::getBounds() {
loadModel();
if(m_models.size() > 0) {
if(m_faces_camera) {
KRAABB normal_bounds = KRAABB(m_models[0]->getMinPoint(), m_models[0]->getMaxPoint(), getModelMatrix());
AABB normal_bounds = AABB(m_models[0]->getMinPoint(), m_models[0]->getMaxPoint(), getModelMatrix());
float max_dimension = normal_bounds.longest_radius();
return KRAABB(normal_bounds.center()-KRVector3(max_dimension), normal_bounds.center() + KRVector3(max_dimension));
return AABB(normal_bounds.center()-Vector3(max_dimension), normal_bounds.center() + Vector3(max_dimension));
} else {
if(!(m_boundsCachedMat == getModelMatrix())) {
m_boundsCachedMat = getModelMatrix();
m_boundsCached = KRAABB(m_models[0]->getMinPoint(), m_models[0]->getMaxPoint(), getModelMatrix());
m_boundsCached = AABB(m_models[0]->getMinPoint(), m_models[0]->getMaxPoint(), getModelMatrix());
}
return m_boundsCached;
}
} else {
return KRAABB::Infinite();
return AABB::Infinite();
}
}

View File

@@ -29,16 +29,12 @@
// or implied, of Kearwood Gilbert.
//
#include "KREngine-common.h"
#ifndef KRMODEL_H
#define KRMODEL_H
#include "KRMesh.h"
#include "KRMat4.h"
#include "KRVector3.h"
#include "KRModel.h"
#include "KRCamera.h"
#include "KRMeshManager.h"
@@ -51,7 +47,7 @@
class KRModel : public KRNode {
public:
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, KRVector3 rim_color = KRVector3::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();
@@ -59,11 +55,11 @@ public:
virtual void render(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, KRNode::RenderPass renderPass);
virtual KRAABB getBounds();
virtual AABB getBounds();
void setRimColor(const KRVector3 &rim_color);
void setRimColor(const Vector3 &rim_color);
void setRimPower(float rim_power);
KRVector3 getRimColor();
Vector3 getRimColor();
float getRimPower();
void setLightMap(const std::string &name);
@@ -88,11 +84,11 @@ private:
bool m_faces_camera;
KRMat4 m_boundsCachedMat;
KRAABB m_boundsCached;
Matrix4 m_boundsCachedMat;
AABB m_boundsCached;
KRVector3 m_rim_color;
Vector3 m_rim_color;
float m_rim_power;
};

View File

@@ -18,8 +18,6 @@
#include "KRCollider.h"
#include "KRParticleSystem.h"
#include "KRParticleSystemNewtonian.h"
#include "KRAABB.h"
#include "KRQuaternion.h"
#include "KRBone.h"
#include "KRLocator.h"
#include "KRAudioSource.h"
@@ -30,28 +28,28 @@
KRNode::KRNode(KRScene &scene, std::string name) : KRContextObject(scene.getContext())
{
m_name = name;
m_localScale = KRVector3::One();
m_localRotation = KRVector3::Zero();
m_localTranslation = KRVector3::Zero();
m_localScale = Vector3::One();
m_localRotation = Vector3::Zero();
m_localTranslation = Vector3::Zero();
m_initialLocalTranslation = m_localTranslation;
m_initialLocalScale = m_localScale;
m_initialLocalRotation = m_localRotation;
m_rotationOffset = KRVector3::Zero();
m_scalingOffset = KRVector3::Zero();
m_rotationPivot = KRVector3::Zero();
m_scalingPivot = KRVector3::Zero();
m_preRotation = KRVector3::Zero();
m_postRotation = KRVector3::Zero();
m_rotationOffset = Vector3::Zero();
m_scalingOffset = Vector3::Zero();
m_rotationPivot = Vector3::Zero();
m_scalingPivot = Vector3::Zero();
m_preRotation = Vector3::Zero();
m_postRotation = Vector3::Zero();
m_initialRotationOffset = KRVector3::Zero();
m_initialScalingOffset = KRVector3::Zero();
m_initialRotationPivot = KRVector3::Zero();
m_initialScalingPivot = KRVector3::Zero();
m_initialPreRotation = KRVector3::Zero();
m_initialPostRotation = KRVector3::Zero();
m_initialRotationOffset = Vector3::Zero();
m_initialScalingOffset = Vector3::Zero();
m_initialRotationPivot = Vector3::Zero();
m_initialScalingPivot = Vector3::Zero();
m_initialPreRotation = Vector3::Zero();
m_initialPostRotation = Vector3::Zero();
m_parentNode = NULL;
m_pScene = &scene;
@@ -60,9 +58,9 @@ KRNode::KRNode(KRScene &scene, std::string name) : KRContextObject(scene.getCont
m_bindPoseMatrixValid = false;
m_activePoseMatrixValid = false;
m_inverseBindPoseMatrixValid = false;
m_modelMatrix = KRMat4();
m_bindPoseMatrix = KRMat4();
m_activePoseMatrix = KRMat4();
m_modelMatrix = Matrix4();
m_bindPoseMatrix = Matrix4();
m_activePoseMatrix = Matrix4();
m_lod_visible = LOD_VISIBILITY_HIDDEN;
m_scale_compensation = false;
m_boundsValid = false;
@@ -125,17 +123,15 @@ tinyxml2::XMLElement *KRNode::saveXML(tinyxml2::XMLNode *parent) {
tinyxml2::XMLElement *e = doc->NewElement(getElementName().c_str());
tinyxml2::XMLNode *n = parent->InsertEndChild(e);
e->SetAttribute("name", m_name.c_str());
m_localTranslation.setXMLAttribute("translate", e, KRVector3::Zero());
m_localScale.setXMLAttribute("scale", e, KRVector3::One());
(m_localRotation * (180.0f / M_PI)).setXMLAttribute("rotate", e, KRVector3::Zero());
m_rotationOffset.setXMLAttribute("rotate_offset", e, KRVector3::Zero());
m_scalingOffset.setXMLAttribute("scale_offset", e, KRVector3::Zero());
m_rotationPivot.setXMLAttribute("rotate_pivot", e, KRVector3::Zero());
m_scalingPivot.setXMLAttribute("scale_pivot", e, KRVector3::Zero());
(m_preRotation * (180.0f / M_PI)).setXMLAttribute("pre_rotate", e, KRVector3::Zero());
(m_postRotation * (180.0f / M_PI)).setXMLAttribute("post_rotate", e, KRVector3::Zero());
kraken::setXMLAttribute("translate", e, m_localTranslation, Vector3::Zero());
kraken::setXMLAttribute("scale", e, m_localScale, Vector3::One());
kraken::setXMLAttribute("rotate", e, (m_localRotation * (180.0f / M_PI)), Vector3::Zero());
kraken::setXMLAttribute("rotate_offset", e, m_rotationOffset, Vector3::Zero());
kraken::setXMLAttribute("scale_offset", e, m_scalingOffset, Vector3::Zero());
kraken::setXMLAttribute("rotate_pivot", e, m_rotationPivot, Vector3::Zero());
kraken::setXMLAttribute("scale_pivot", e, m_scalingPivot, Vector3::Zero());
kraken::setXMLAttribute("pre_rotate", e, (m_preRotation * (180.0f / M_PI)), Vector3::Zero());
kraken::setXMLAttribute("post_rotate", e, (m_postRotation * (180.0f / M_PI)), Vector3::Zero());
for(std::set<KRNode *>::iterator itr=m_childNodes.begin(); itr != m_childNodes.end(); ++itr) {
KRNode *child = (*itr);
@@ -146,21 +142,19 @@ tinyxml2::XMLElement *KRNode::saveXML(tinyxml2::XMLNode *parent) {
void KRNode::loadXML(tinyxml2::XMLElement *e) {
m_name = e->Attribute("name");
m_localTranslation.getXMLAttribute("translate", e, KRVector3::Zero());
m_localScale.getXMLAttribute("scale", e, KRVector3::One());
m_localRotation.getXMLAttribute("rotate", e, KRVector3::Zero());
m_localTranslation = kraken::getXMLAttribute("translate", e, Vector3::Zero());
m_localScale = kraken::getXMLAttribute("scale", e, Vector3::One());
m_localRotation = kraken::getXMLAttribute("rotate", e, Vector3::Zero());
m_localRotation *= M_PI / 180.0f; // Convert degrees to radians
m_preRotation.getXMLAttribute("pre_rotate", e, KRVector3::Zero());
m_preRotation = kraken::getXMLAttribute("pre_rotate", e, Vector3::Zero());
m_preRotation *= M_PI / 180.0f; // Convert degrees to radians
m_postRotation.getXMLAttribute("post_rotate", e, KRVector3::Zero());
m_postRotation = kraken::getXMLAttribute("post_rotate", e, Vector3::Zero());
m_postRotation *= M_PI / 180.0f; // Convert degrees to radians
m_rotationOffset.getXMLAttribute("rotate_offset", e, KRVector3::Zero());
m_scalingOffset.getXMLAttribute("scale_offset", e, KRVector3::Zero());
m_rotationPivot.getXMLAttribute("rotate_pivot", e, KRVector3::Zero());
m_scalingPivot.getXMLAttribute("scale_pivot", e, KRVector3::Zero());
m_rotationOffset = kraken::getXMLAttribute("rotate_offset", e, Vector3::Zero());
m_scalingOffset = kraken::getXMLAttribute("scale_offset", e, Vector3::Zero());
m_rotationPivot = kraken::getXMLAttribute("rotate_pivot", e, Vector3::Zero());
m_scalingPivot = kraken::getXMLAttribute("scale_pivot", e, Vector3::Zero());
m_initialLocalTranslation = m_localTranslation;
m_initialLocalScale = m_localScale;
@@ -197,7 +191,7 @@ void KRNode::loadXML(tinyxml2::XMLElement *e) {
}
}
void KRNode::setLocalTranslation(const KRVector3 &v, bool set_original) {
void KRNode::setLocalTranslation(const Vector3 &v, bool set_original) {
m_localTranslation = v;
if(set_original) {
m_initialLocalTranslation = v;
@@ -206,40 +200,40 @@ void KRNode::setLocalTranslation(const KRVector3 &v, bool set_original) {
invalidateModelMatrix();
}
void KRNode::setWorldTranslation(const KRVector3 &v)
void KRNode::setWorldTranslation(const Vector3 &v)
{
if(m_parentNode) {
setLocalTranslation(KRMat4::Dot(m_parentNode->getInverseModelMatrix(), v));
setLocalTranslation(Matrix4::Dot(m_parentNode->getInverseModelMatrix(), v));
} else {
setLocalTranslation(v);
}
}
void KRNode::setWorldRotation(const KRVector3 &v)
void KRNode::setWorldRotation(const Vector3 &v)
{
if(m_parentNode) {
setLocalRotation((KRQuaternion(v) * -m_parentNode->getWorldRotation()).eulerXYZ());
setPreRotation(KRVector3::Zero());
setPostRotation(KRVector3::Zero());
setLocalRotation((Quaternion(v) * -m_parentNode->getWorldRotation()).eulerXYZ());
setPreRotation(Vector3::Zero());
setPostRotation(Vector3::Zero());
} else {
setLocalRotation(v);
setPreRotation(KRVector3::Zero());
setPostRotation(KRVector3::Zero());
setPreRotation(Vector3::Zero());
setPostRotation(Vector3::Zero());
}
}
void KRNode::setWorldScale(const KRVector3 &v)
void KRNode::setWorldScale(const Vector3 &v)
{
if(m_parentNode) {
setLocalScale(KRMat4::DotNoTranslate(m_parentNode->getInverseModelMatrix(), v));
setLocalScale(Matrix4::DotNoTranslate(m_parentNode->getInverseModelMatrix(), v));
} else {
setLocalScale(v);
}
}
void KRNode::setLocalScale(const KRVector3 &v, bool set_original) {
void KRNode::setLocalScale(const Vector3 &v, bool set_original) {
m_localScale = v;
if(set_original) {
m_initialLocalScale = v;
@@ -248,7 +242,7 @@ void KRNode::setLocalScale(const KRVector3 &v, bool set_original) {
invalidateModelMatrix();
}
void KRNode::setLocalRotation(const KRVector3 &v, bool set_original) {
void KRNode::setLocalRotation(const Vector3 &v, bool set_original) {
m_localRotation = v;
if(set_original) {
m_initialLocalRotation = v;
@@ -258,7 +252,7 @@ void KRNode::setLocalRotation(const KRVector3 &v, bool set_original) {
}
void KRNode::setRotationOffset(const KRVector3 &v, bool set_original)
void KRNode::setRotationOffset(const Vector3 &v, bool set_original)
{
m_rotationOffset = v;
if(set_original) {
@@ -268,7 +262,7 @@ void KRNode::setRotationOffset(const KRVector3 &v, bool set_original)
invalidateModelMatrix();
}
void KRNode::setScalingOffset(const KRVector3 &v, bool set_original)
void KRNode::setScalingOffset(const Vector3 &v, bool set_original)
{
m_scalingOffset = v;
if(set_original) {
@@ -278,7 +272,7 @@ void KRNode::setScalingOffset(const KRVector3 &v, bool set_original)
invalidateModelMatrix();
}
void KRNode::setRotationPivot(const KRVector3 &v, bool set_original)
void KRNode::setRotationPivot(const Vector3 &v, bool set_original)
{
m_rotationPivot = v;
if(set_original) {
@@ -287,7 +281,7 @@ void KRNode::setRotationPivot(const KRVector3 &v, bool set_original)
}
invalidateModelMatrix();
}
void KRNode::setScalingPivot(const KRVector3 &v, bool set_original)
void KRNode::setScalingPivot(const Vector3 &v, bool set_original)
{
m_scalingPivot = v;
if(set_original) {
@@ -296,7 +290,7 @@ void KRNode::setScalingPivot(const KRVector3 &v, bool set_original)
}
invalidateModelMatrix();
}
void KRNode::setPreRotation(const KRVector3 &v, bool set_original)
void KRNode::setPreRotation(const Vector3 &v, bool set_original)
{
m_preRotation = v;
if(set_original) {
@@ -305,7 +299,7 @@ void KRNode::setPreRotation(const KRVector3 &v, bool set_original)
}
invalidateModelMatrix();
}
void KRNode::setPostRotation(const KRVector3 &v, bool set_original)
void KRNode::setPostRotation(const Vector3 &v, bool set_original)
{
m_postRotation = v;
if(set_original) {
@@ -315,81 +309,81 @@ void KRNode::setPostRotation(const KRVector3 &v, bool set_original)
invalidateModelMatrix();
}
const KRVector3 &KRNode::getRotationOffset()
const Vector3 &KRNode::getRotationOffset()
{
return m_rotationOffset;
}
const KRVector3 &KRNode::getScalingOffset()
const Vector3 &KRNode::getScalingOffset()
{
return m_scalingOffset;
}
const KRVector3 &KRNode::getRotationPivot()
const Vector3 &KRNode::getRotationPivot()
{
return m_rotationPivot;
}
const KRVector3 &KRNode::getScalingPivot()
const Vector3 &KRNode::getScalingPivot()
{
return m_scalingPivot;
}
const KRVector3 &KRNode::getPreRotation()
const Vector3 &KRNode::getPreRotation()
{
return m_preRotation;
}
const KRVector3 &KRNode::getPostRotation()
const Vector3 &KRNode::getPostRotation()
{
return m_postRotation;
}
const KRVector3 &KRNode::getInitialRotationOffset()
const Vector3 &KRNode::getInitialRotationOffset()
{
return m_initialRotationOffset;
}
const KRVector3 &KRNode::getInitialScalingOffset()
const Vector3 &KRNode::getInitialScalingOffset()
{
return m_initialScalingOffset;
}
const KRVector3 &KRNode::getInitialRotationPivot()
const Vector3 &KRNode::getInitialRotationPivot()
{
return m_initialRotationPivot;
}
const KRVector3 &KRNode::getInitialScalingPivot()
const Vector3 &KRNode::getInitialScalingPivot()
{
return m_initialScalingPivot;
}
const KRVector3 &KRNode::getInitialPreRotation()
const Vector3 &KRNode::getInitialPreRotation()
{
return m_initialPreRotation;
}
const KRVector3 &KRNode::getInitialPostRotation()
const Vector3 &KRNode::getInitialPostRotation()
{
return m_initialPostRotation;
}
const KRVector3 &KRNode::getLocalTranslation() {
const Vector3 &KRNode::getLocalTranslation() {
return m_localTranslation;
}
const KRVector3 &KRNode::getLocalScale() {
const Vector3 &KRNode::getLocalScale() {
return m_localScale;
}
const KRVector3 &KRNode::getLocalRotation() {
const Vector3 &KRNode::getLocalRotation() {
return m_localRotation;
}
const KRVector3 &KRNode::getInitialLocalTranslation() {
const Vector3 &KRNode::getInitialLocalTranslation() {
return m_initialLocalTranslation;
}
const KRVector3 &KRNode::getInitialLocalScale() {
const Vector3 &KRNode::getInitialLocalScale() {
return m_initialLocalScale;
}
const KRVector3 &KRNode::getInitialLocalRotation() {
const Vector3 &KRNode::getInitialLocalRotation() {
return m_initialLocalRotation;
}
const KRVector3 KRNode::getWorldTranslation() {
return localToWorld(KRVector3::Zero());
const Vector3 KRNode::getWorldTranslation() {
return localToWorld(Vector3::Zero());
}
const KRVector3 KRNode::getWorldScale() {
return KRMat4::DotNoTranslate(getModelMatrix(), m_localScale);
const Vector3 KRNode::getWorldScale() {
return Matrix4::DotNoTranslate(getModelMatrix(), m_localScale);
}
std::string KRNode::getElementName() {
@@ -433,8 +427,8 @@ KRNode *KRNode::LoadXML(KRScene &scene, tinyxml2::XMLElement *e) {
if(e->QueryFloatAttribute("rim_power", &rim_power) != tinyxml2::XML_SUCCESS) {
rim_power = 0.0f;
}
KRVector3 rim_color = KRVector3::Zero();
rim_color.getXMLAttribute("rim_color", e, KRVector3::Zero());
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) {
new_node = new KRCollider(scene, szName, e->Attribute("mesh"), 65535, 1.0f);
@@ -482,14 +476,14 @@ KRScene &KRNode::getScene() {
return *m_pScene;
}
KRAABB KRNode::getBounds() {
AABB KRNode::getBounds() {
if(!m_boundsValid) {
KRAABB bounds = KRAABB::Zero();
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() != KRAABB::Zero()) {
if(child->getBounds() != AABB::Zero()) {
if(first_child) {
first_child = false;
bounds = child->getBounds();
@@ -529,11 +523,11 @@ void KRNode::invalidateBindPoseMatrix()
}
}
const KRMat4 &KRNode::getModelMatrix()
const Matrix4 &KRNode::getModelMatrix()
{
if(!m_modelMatrixValid) {
m_modelMatrix = KRMat4();
m_modelMatrix = Matrix4();
bool parent_is_bone = false;
if(dynamic_cast<KRBone *>(m_parentNode)) {
@@ -544,40 +538,40 @@ const KRMat4 &KRNode::getModelMatrix()
// WorldTransform = ParentWorldTransform * T * Roff * Rp * Rpre * R * Rpost * Rp-1 * Soff * Sp * S * Sp-1
m_modelMatrix = KRMat4::Translation(-m_scalingPivot)
* KRMat4::Scaling(m_localScale)
* KRMat4::Translation(m_scalingPivot)
* KRMat4::Translation(m_scalingOffset)
* KRMat4::Translation(-m_rotationPivot)
//* (KRQuaternion(m_postRotation) * KRQuaternion(m_localRotation) * KRQuaternion(m_preRotation)).rotationMatrix()
* KRMat4::Rotation(m_postRotation)
* KRMat4::Rotation(m_localRotation)
* KRMat4::Rotation(m_preRotation)
* KRMat4::Translation(m_rotationPivot)
* KRMat4::Translation(m_rotationOffset);
m_modelMatrix = Matrix4::Translation(-m_scalingPivot)
* Matrix4::Scaling(m_localScale)
* Matrix4::Translation(m_scalingPivot)
* Matrix4::Translation(m_scalingOffset)
* Matrix4::Translation(-m_rotationPivot)
//* (Quaternion(m_postRotation) * Quaternion(m_localRotation) * Quaternion(m_preRotation)).rotationMatrix()
* Matrix4::Rotation(m_postRotation)
* Matrix4::Rotation(m_localRotation)
* Matrix4::Rotation(m_preRotation)
* Matrix4::Translation(m_rotationPivot)
* Matrix4::Translation(m_rotationOffset);
if(m_parentNode) {
m_modelMatrix.rotate(m_parentNode->getWorldRotation());
m_modelMatrix.translate(KRMat4::Dot(m_parentNode->getModelMatrix(), m_localTranslation));
m_modelMatrix.translate(Matrix4::Dot(m_parentNode->getModelMatrix(), m_localTranslation));
} else {
m_modelMatrix.translate(m_localTranslation);
}
} else {
// WorldTransform = ParentWorldTransform * T * Roff * Rp * Rpre * R * Rpost * Rp-1 * Soff * Sp * S * Sp-1
m_modelMatrix = KRMat4::Translation(-m_scalingPivot)
* KRMat4::Scaling(m_localScale)
* KRMat4::Translation(m_scalingPivot)
* KRMat4::Translation(m_scalingOffset)
* KRMat4::Translation(-m_rotationPivot)
//* (KRQuaternion(m_postRotation) * KRQuaternion(m_localRotation) * KRQuaternion(m_preRotation)).rotationMatrix()
* KRMat4::Rotation(m_postRotation)
* KRMat4::Rotation(m_localRotation)
* KRMat4::Rotation(m_preRotation)
* KRMat4::Translation(m_rotationPivot)
* KRMat4::Translation(m_rotationOffset)
* KRMat4::Translation(m_localTranslation);
m_modelMatrix = Matrix4::Translation(-m_scalingPivot)
* Matrix4::Scaling(m_localScale)
* Matrix4::Translation(m_scalingPivot)
* Matrix4::Translation(m_scalingOffset)
* Matrix4::Translation(-m_rotationPivot)
//* (Quaternion(m_postRotation) * Quaternion(m_localRotation) * Quaternion(m_preRotation)).rotationMatrix()
* Matrix4::Rotation(m_postRotation)
* Matrix4::Rotation(m_localRotation)
* Matrix4::Rotation(m_preRotation)
* Matrix4::Translation(m_rotationPivot)
* Matrix4::Translation(m_rotationOffset)
* Matrix4::Translation(m_localTranslation);
if(m_parentNode) {
m_modelMatrix *= m_parentNode->getModelMatrix();
@@ -590,10 +584,10 @@ const KRMat4 &KRNode::getModelMatrix()
return m_modelMatrix;
}
const KRMat4 &KRNode::getBindPoseMatrix()
const Matrix4 &KRNode::getBindPoseMatrix()
{
if(!m_bindPoseMatrixValid) {
m_bindPoseMatrix = KRMat4();
m_bindPoseMatrix = Matrix4();
bool parent_is_bone = false;
if(dynamic_cast<KRBone *>(m_parentNode)) {
@@ -601,22 +595,22 @@ const KRMat4 &KRNode::getBindPoseMatrix()
}
if(getScaleCompensation() && parent_is_bone) {
m_bindPoseMatrix = KRMat4::Translation(-m_initialScalingPivot)
* KRMat4::Scaling(m_initialLocalScale)
* KRMat4::Translation(m_initialScalingPivot)
* KRMat4::Translation(m_initialScalingOffset)
* KRMat4::Translation(-m_initialRotationPivot)
//* (KRQuaternion(m_initialPostRotation) * KRQuaternion(m_initialLocalRotation) * KRQuaternion(m_initialPreRotation)).rotationMatrix()
* KRMat4::Rotation(m_initialPostRotation)
* KRMat4::Rotation(m_initialLocalRotation)
* KRMat4::Rotation(m_initialPreRotation)
* KRMat4::Translation(m_initialRotationPivot)
* KRMat4::Translation(m_initialRotationOffset);
m_bindPoseMatrix = Matrix4::Translation(-m_initialScalingPivot)
* Matrix4::Scaling(m_initialLocalScale)
* Matrix4::Translation(m_initialScalingPivot)
* Matrix4::Translation(m_initialScalingOffset)
* Matrix4::Translation(-m_initialRotationPivot)
//* (Quaternion(m_initialPostRotation) * Quaternion(m_initialLocalRotation) * Quaternion(m_initialPreRotation)).rotationMatrix()
* Matrix4::Rotation(m_initialPostRotation)
* Matrix4::Rotation(m_initialLocalRotation)
* Matrix4::Rotation(m_initialPreRotation)
* Matrix4::Translation(m_initialRotationPivot)
* Matrix4::Translation(m_initialRotationOffset);
//m_bindPoseMatrix.translate(m_localTranslation);
if(m_parentNode) {
m_bindPoseMatrix.rotate(m_parentNode->getBindPoseWorldRotation());
m_bindPoseMatrix.translate(KRMat4::Dot(m_parentNode->getBindPoseMatrix(), m_localTranslation));
m_bindPoseMatrix.translate(Matrix4::Dot(m_parentNode->getBindPoseMatrix(), m_localTranslation));
} else {
m_bindPoseMatrix.translate(m_localTranslation);
}
@@ -624,18 +618,18 @@ const KRMat4 &KRNode::getBindPoseMatrix()
// WorldTransform = ParentWorldTransform * T * Roff * Rp * Rpre * R * Rpost * Rp-1 * Soff * Sp * S * Sp-1
m_bindPoseMatrix = KRMat4::Translation(-m_initialScalingPivot)
* KRMat4::Scaling(m_initialLocalScale)
* KRMat4::Translation(m_initialScalingPivot)
* KRMat4::Translation(m_initialScalingOffset)
* KRMat4::Translation(-m_initialRotationPivot)
// * (KRQuaternion(m_initialPostRotation) * KRQuaternion(m_initialLocalRotation) * KRQuaternion(m_initialPreRotation)).rotationMatrix()
* KRMat4::Rotation(m_initialPostRotation)
* KRMat4::Rotation(m_initialLocalRotation)
* KRMat4::Rotation(m_initialPreRotation)
* KRMat4::Translation(m_initialRotationPivot)
* KRMat4::Translation(m_initialRotationOffset)
* KRMat4::Translation(m_initialLocalTranslation);
m_bindPoseMatrix = Matrix4::Translation(-m_initialScalingPivot)
* Matrix4::Scaling(m_initialLocalScale)
* Matrix4::Translation(m_initialScalingPivot)
* Matrix4::Translation(m_initialScalingOffset)
* Matrix4::Translation(-m_initialRotationPivot)
// * (Quaternion(m_initialPostRotation) * Quaternion(m_initialLocalRotation) * Quaternion(m_initialPreRotation)).rotationMatrix()
* Matrix4::Rotation(m_initialPostRotation)
* Matrix4::Rotation(m_initialLocalRotation)
* Matrix4::Rotation(m_initialPreRotation)
* Matrix4::Translation(m_initialRotationPivot)
* Matrix4::Translation(m_initialRotationOffset)
* Matrix4::Translation(m_initialLocalTranslation);
if(m_parentNode && parent_is_bone) {
@@ -649,11 +643,11 @@ const KRMat4 &KRNode::getBindPoseMatrix()
return m_bindPoseMatrix;
}
const KRMat4 &KRNode::getActivePoseMatrix()
const Matrix4 &KRNode::getActivePoseMatrix()
{
if(!m_activePoseMatrixValid) {
m_activePoseMatrix = KRMat4();
m_activePoseMatrix = Matrix4();
bool parent_is_bone = false;
if(dynamic_cast<KRBone *>(m_parentNode)) {
@@ -661,38 +655,38 @@ const KRMat4 &KRNode::getActivePoseMatrix()
}
if(getScaleCompensation() && parent_is_bone) {
m_activePoseMatrix= KRMat4::Translation(-m_scalingPivot)
* KRMat4::Scaling(m_localScale)
* KRMat4::Translation(m_scalingPivot)
* KRMat4::Translation(m_scalingOffset)
* KRMat4::Translation(-m_rotationPivot)
* KRMat4::Rotation(m_postRotation)
* KRMat4::Rotation(m_localRotation)
* KRMat4::Rotation(m_preRotation)
* KRMat4::Translation(m_rotationPivot)
* KRMat4::Translation(m_rotationOffset);
m_activePoseMatrix= Matrix4::Translation(-m_scalingPivot)
* Matrix4::Scaling(m_localScale)
* Matrix4::Translation(m_scalingPivot)
* Matrix4::Translation(m_scalingOffset)
* Matrix4::Translation(-m_rotationPivot)
* Matrix4::Rotation(m_postRotation)
* Matrix4::Rotation(m_localRotation)
* Matrix4::Rotation(m_preRotation)
* Matrix4::Translation(m_rotationPivot)
* Matrix4::Translation(m_rotationOffset);
if(m_parentNode) {
m_activePoseMatrix.rotate(m_parentNode->getActivePoseWorldRotation());
m_activePoseMatrix.translate(KRMat4::Dot(m_parentNode->getActivePoseMatrix(), m_localTranslation));
m_activePoseMatrix.translate(Matrix4::Dot(m_parentNode->getActivePoseMatrix(), m_localTranslation));
} else {
m_activePoseMatrix.translate(m_localTranslation);
}
} else {
// WorldTransform = ParentWorldTransform * T * Roff * Rp * Rpre * R * Rpost * Rp-1 * Soff * Sp * S * Sp-1
m_activePoseMatrix = KRMat4::Translation(-m_scalingPivot)
* KRMat4::Scaling(m_localScale)
* KRMat4::Translation(m_scalingPivot)
* KRMat4::Translation(m_scalingOffset)
* KRMat4::Translation(-m_rotationPivot)
* KRMat4::Rotation(m_postRotation)
* KRMat4::Rotation(m_localRotation)
* KRMat4::Rotation(m_preRotation)
* KRMat4::Translation(m_rotationPivot)
* KRMat4::Translation(m_rotationOffset)
* KRMat4::Translation(m_localTranslation);
m_activePoseMatrix = Matrix4::Translation(-m_scalingPivot)
* Matrix4::Scaling(m_localScale)
* Matrix4::Translation(m_scalingPivot)
* Matrix4::Translation(m_scalingOffset)
* Matrix4::Translation(-m_rotationPivot)
* Matrix4::Rotation(m_postRotation)
* Matrix4::Rotation(m_localRotation)
* Matrix4::Rotation(m_preRotation)
* Matrix4::Translation(m_rotationPivot)
* Matrix4::Translation(m_rotationOffset)
* Matrix4::Translation(m_localTranslation);
if(m_parentNode && parent_is_bone) {
@@ -707,42 +701,42 @@ const KRMat4 &KRNode::getActivePoseMatrix()
}
const KRQuaternion KRNode::getWorldRotation() {
KRQuaternion world_rotation = KRQuaternion(m_postRotation) * KRQuaternion(m_localRotation) * KRQuaternion(m_preRotation);
const Quaternion KRNode::getWorldRotation() {
Quaternion world_rotation = Quaternion(m_postRotation) * Quaternion(m_localRotation) * Quaternion(m_preRotation);
if(m_parentNode) {
world_rotation = world_rotation * m_parentNode->getWorldRotation();
}
return world_rotation;
}
const KRQuaternion KRNode::getBindPoseWorldRotation() {
KRQuaternion world_rotation = KRQuaternion(m_initialPostRotation) * KRQuaternion(m_initialLocalRotation) * KRQuaternion(m_initialPreRotation);
const Quaternion KRNode::getBindPoseWorldRotation() {
Quaternion world_rotation = Quaternion(m_initialPostRotation) * Quaternion(m_initialLocalRotation) * Quaternion(m_initialPreRotation);
if(dynamic_cast<KRBone *>(m_parentNode)) {
world_rotation = world_rotation * m_parentNode->getBindPoseWorldRotation();
}
return world_rotation;
}
const KRQuaternion KRNode::getActivePoseWorldRotation() {
KRQuaternion world_rotation = KRQuaternion(m_postRotation) * KRQuaternion(m_localRotation) * KRQuaternion(m_preRotation);
const Quaternion KRNode::getActivePoseWorldRotation() {
Quaternion world_rotation = Quaternion(m_postRotation) * Quaternion(m_localRotation) * Quaternion(m_preRotation);
if(dynamic_cast<KRBone *>(m_parentNode)) {
world_rotation = world_rotation * m_parentNode->getActivePoseWorldRotation();
}
return world_rotation;
}
const KRMat4 &KRNode::getInverseModelMatrix()
const Matrix4 &KRNode::getInverseModelMatrix()
{
if(!m_inverseModelMatrixValid) {
m_inverseModelMatrix = KRMat4::Invert(getModelMatrix());
m_inverseModelMatrix = Matrix4::Invert(getModelMatrix());
}
return m_inverseModelMatrix;
}
const KRMat4 &KRNode::getInverseBindPoseMatrix()
const Matrix4 &KRNode::getInverseBindPoseMatrix()
{
if(!m_inverseBindPoseMatrixValid ) {
m_inverseBindPoseMatrix = KRMat4::Invert(getBindPoseMatrix());
m_inverseBindPoseMatrix = Matrix4::Invert(getBindPoseMatrix());
m_inverseBindPoseMatrixValid = true;
}
return m_inverseBindPoseMatrix;
@@ -774,87 +768,87 @@ void KRNode::SetAttribute(node_attribute_type attrib, float v)
//printf("%s - ", m_name.c_str());
switch(attrib) {
case KRENGINE_NODE_ATTRIBUTE_TRANSLATE_X:
setLocalTranslation(KRVector3(v, m_localTranslation.y, m_localTranslation.z));
setLocalTranslation(Vector3(v, m_localTranslation.y, m_localTranslation.z));
break;
case KRENGINE_NODE_ATTRIBUTE_TRANSLATE_Y:
setLocalTranslation(KRVector3(m_localTranslation.x, v, m_localTranslation.z));
setLocalTranslation(Vector3(m_localTranslation.x, v, m_localTranslation.z));
break;
case KRENGINE_NODE_ATTRIBUTE_TRANSLATE_Z:
setLocalTranslation(KRVector3(m_localTranslation.x, m_localTranslation.y, v));
setLocalTranslation(Vector3(m_localTranslation.x, m_localTranslation.y, v));
break;
case KRENGINE_NODE_ATTRIBUTE_SCALE_X:
setLocalScale(KRVector3(v, m_localScale.y, m_localScale.z));
setLocalScale(Vector3(v, m_localScale.y, m_localScale.z));
break;
case KRENGINE_NODE_ATTRIBUTE_SCALE_Y:
setLocalScale(KRVector3(m_localScale.x, v, m_localScale.z));
setLocalScale(Vector3(m_localScale.x, v, m_localScale.z));
break;
case KRENGINE_NODE_ATTRIBUTE_SCALE_Z:
setLocalScale(KRVector3(m_localScale.x, m_localScale.y, v));
setLocalScale(Vector3(m_localScale.x, m_localScale.y, v));
break;
case KRENGINE_NODE_ATTRIBUTE_ROTATE_X:
setLocalRotation(KRVector3(v * DEGREES_TO_RAD, m_localRotation.y, m_localRotation.z));
setLocalRotation(Vector3(v * DEGREES_TO_RAD, m_localRotation.y, m_localRotation.z));
break;
case KRENGINE_NODE_ATTRIBUTE_ROTATE_Y:
setLocalRotation(KRVector3(m_localRotation.x, v * DEGREES_TO_RAD, m_localRotation.z));
setLocalRotation(Vector3(m_localRotation.x, v * DEGREES_TO_RAD, m_localRotation.z));
break;
case KRENGINE_NODE_ATTRIBUTE_ROTATE_Z:
setLocalRotation(KRVector3(m_localRotation.x, m_localRotation.y, v * DEGREES_TO_RAD));
setLocalRotation(Vector3(m_localRotation.x, m_localRotation.y, v * DEGREES_TO_RAD));
break;
case KRENGINE_NODE_ATTRIBUTE_PRE_ROTATION_X:
setPreRotation(KRVector3(v * DEGREES_TO_RAD, m_preRotation.y, m_preRotation.z));
setPreRotation(Vector3(v * DEGREES_TO_RAD, m_preRotation.y, m_preRotation.z));
break;
case KRENGINE_NODE_ATTRIBUTE_PRE_ROTATION_Y:
setPreRotation(KRVector3(m_preRotation.x, v * DEGREES_TO_RAD, m_preRotation.z));
setPreRotation(Vector3(m_preRotation.x, v * DEGREES_TO_RAD, m_preRotation.z));
break;
case KRENGINE_NODE_ATTRIBUTE_PRE_ROTATION_Z:
setPreRotation(KRVector3(m_preRotation.x, m_preRotation.y, v * DEGREES_TO_RAD));
setPreRotation(Vector3(m_preRotation.x, m_preRotation.y, v * DEGREES_TO_RAD));
break;
case KRENGINE_NODE_ATTRIBUTE_POST_ROTATION_X:
setPostRotation(KRVector3(v * DEGREES_TO_RAD, m_postRotation.y, m_postRotation.z));
setPostRotation(Vector3(v * DEGREES_TO_RAD, m_postRotation.y, m_postRotation.z));
break;
case KRENGINE_NODE_ATTRIBUTE_POST_ROTATION_Y:
setPostRotation(KRVector3(m_postRotation.x, v * DEGREES_TO_RAD, m_postRotation.z));
setPostRotation(Vector3(m_postRotation.x, v * DEGREES_TO_RAD, m_postRotation.z));
break;
case KRENGINE_NODE_ATTRIBUTE_POST_ROTATION_Z:
setPostRotation(KRVector3(m_postRotation.x, m_postRotation.y, v * DEGREES_TO_RAD));
setPostRotation(Vector3(m_postRotation.x, m_postRotation.y, v * DEGREES_TO_RAD));
break;
case KRENGINE_NODE_ATTRIBUTE_ROTATION_PIVOT_X:
setRotationPivot(KRVector3(v, m_rotationPivot.y, m_rotationPivot.z));
setRotationPivot(Vector3(v, m_rotationPivot.y, m_rotationPivot.z));
break;
case KRENGINE_NODE_ATTRIBUTE_ROTATION_PIVOT_Y:
setRotationPivot(KRVector3(m_rotationPivot.x, v, m_rotationPivot.z));
setRotationPivot(Vector3(m_rotationPivot.x, v, m_rotationPivot.z));
break;
case KRENGINE_NODE_ATTRIBUTE_ROTATION_PIVOT_Z:
setRotationPivot(KRVector3(m_rotationPivot.x, m_rotationPivot.y, v));
setRotationPivot(Vector3(m_rotationPivot.x, m_rotationPivot.y, v));
break;
case KRENGINE_NODE_ATTRIBUTE_SCALE_PIVOT_X:
setScalingPivot(KRVector3(v, m_scalingPivot.y, m_scalingPivot.z));
setScalingPivot(Vector3(v, m_scalingPivot.y, m_scalingPivot.z));
break;
case KRENGINE_NODE_ATTRIBUTE_SCALE_PIVOT_Y:
setScalingPivot(KRVector3(m_scalingPivot.x, v, m_scalingPivot.z));
setScalingPivot(Vector3(m_scalingPivot.x, v, m_scalingPivot.z));
break;
case KRENGINE_NODE_ATTRIBUTE_SCALE_PIVOT_Z:
setScalingPivot(KRVector3(m_scalingPivot.x, m_scalingPivot.y, v));
setScalingPivot(Vector3(m_scalingPivot.x, m_scalingPivot.y, v));
break;
case KRENGINE_NODE_ATTRIBUTE_ROTATE_OFFSET_X:
setRotationOffset(KRVector3(v, m_rotationOffset.y, m_rotationOffset.z));
setRotationOffset(Vector3(v, m_rotationOffset.y, m_rotationOffset.z));
break;
case KRENGINE_NODE_ATTRIBUTE_ROTATE_OFFSET_Y:
setRotationOffset(KRVector3(m_rotationOffset.x, v, m_rotationOffset.z));
setRotationOffset(Vector3(m_rotationOffset.x, v, m_rotationOffset.z));
break;
case KRENGINE_NODE_ATTRIBUTE_ROTATE_OFFSET_Z:
setRotationOffset(KRVector3(m_rotationOffset.x, m_rotationOffset.y, v));
setRotationOffset(Vector3(m_rotationOffset.x, m_rotationOffset.y, v));
break;
case KRENGINE_NODE_SCALE_OFFSET_X:
setScalingOffset(KRVector3(v, m_scalingOffset.y, m_scalingOffset.z));
setScalingOffset(Vector3(v, m_scalingOffset.y, m_scalingOffset.z));
break;
case KRENGINE_NODE_SCALE_OFFSET_Y:
setScalingOffset(KRVector3(m_scalingOffset.x, v, m_scalingOffset.z));
setScalingOffset(Vector3(m_scalingOffset.x, v, m_scalingOffset.z));
break;
case KRENGINE_NODE_SCALE_OFFSET_Z:
setScalingOffset(KRVector3(m_scalingOffset.x, m_scalingOffset.y, v));
setScalingOffset(Vector3(m_scalingOffset.x, m_scalingOffset.y, v));
break;
}
}
@@ -923,14 +917,14 @@ KRNode::LodVisibility KRNode::getLODVisibility()
return m_lod_visible;
}
const KRVector3 KRNode::localToWorld(const KRVector3 &local_point)
const Vector3 KRNode::localToWorld(const Vector3 &local_point)
{
return KRMat4::Dot(getModelMatrix(), local_point);
return Matrix4::Dot(getModelMatrix(), local_point);
}
const KRVector3 KRNode::worldToLocal(const KRVector3 &world_point)
const Vector3 KRNode::worldToLocal(const Vector3 &world_point)
{
return KRMat4::Dot(getInverseModelMatrix(), world_point);
return Matrix4::Dot(getInverseModelMatrix(), world_point);
}
void KRNode::addBehavior(KRBehavior *behavior)

View File

@@ -10,20 +10,24 @@
#define KRNODE_H
#include "KRResource.h"
#include "KRVector3.h"
#include "KRViewport.h"
#include "KROctreeNode.h"
#include "KRBehavior.h"
using namespace kraken;
namespace kraken {
class Matrix4;
class AABB;
} // namespace kraken
class KRCamera;
class KRShaderManager;
class KRMeshManager;
class KRMaterialManager;
class KRMat4;
class KRTextureManager;
class KRContext;
class KRScene;
class KRAABB;
class KRNode;
class KRPointLight;
class KRSpotLight;
@@ -70,62 +74,62 @@ public:
const std::set<KRNode *> &getChildren();
KRNode *getParent();
void setLocalTranslation(const KRVector3 &v, bool set_original = false);
void setLocalScale(const KRVector3 &v, bool set_original = false);
void setLocalRotation(const KRVector3 &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 KRVector3 &v, bool set_original = false);
void setScalingOffset(const KRVector3 &v, bool set_original = false);
void setRotationPivot(const KRVector3 &v, bool set_original = false);
void setScalingPivot(const KRVector3 &v, bool set_original = false);
void setPreRotation(const KRVector3 &v, bool set_original = false);
void setPostRotation(const KRVector3 &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 KRVector3 &getRotationOffset();
const KRVector3 &getScalingOffset();
const KRVector3 &getRotationPivot();
const KRVector3 &getScalingPivot();
const KRVector3 &getPreRotation();
const KRVector3 &getPostRotation();
const Vector3 &getRotationOffset();
const Vector3 &getScalingOffset();
const Vector3 &getRotationPivot();
const Vector3 &getScalingPivot();
const Vector3 &getPreRotation();
const Vector3 &getPostRotation();
const KRVector3 &getInitialRotationOffset();
const KRVector3 &getInitialScalingOffset();
const KRVector3 &getInitialRotationPivot();
const KRVector3 &getInitialScalingPivot();
const KRVector3 &getInitialPreRotation();
const KRVector3 &getInitialPostRotation();
const Vector3 &getInitialRotationOffset();
const Vector3 &getInitialScalingOffset();
const Vector3 &getInitialRotationPivot();
const Vector3 &getInitialScalingPivot();
const Vector3 &getInitialPreRotation();
const Vector3 &getInitialPostRotation();
const KRVector3 &getLocalTranslation();
const KRVector3 &getLocalScale();
const KRVector3 &getLocalRotation();
const Vector3 &getLocalTranslation();
const Vector3 &getLocalScale();
const Vector3 &getLocalRotation();
const KRVector3 &getInitialLocalTranslation();
const KRVector3 &getInitialLocalScale();
const KRVector3 &getInitialLocalRotation();
const Vector3 &getInitialLocalTranslation();
const Vector3 &getInitialLocalScale();
const Vector3 &getInitialLocalRotation();
const KRVector3 getWorldTranslation();
const KRVector3 getWorldScale();
const KRQuaternion getWorldRotation();
const Vector3 getWorldTranslation();
const Vector3 getWorldScale();
const Quaternion getWorldRotation();
const KRQuaternion getBindPoseWorldRotation();
const KRQuaternion getActivePoseWorldRotation();
const Quaternion getBindPoseWorldRotation();
const Quaternion getActivePoseWorldRotation();
const KRVector3 localToWorld(const KRVector3 &local_point);
const KRVector3 worldToLocal(const KRVector3 &world_point);
const Vector3 localToWorld(const Vector3 &local_point);
const Vector3 worldToLocal(const Vector3 &world_point);
void setWorldTranslation(const KRVector3 &v);
void setWorldScale(const KRVector3 &v);
void setWorldRotation(const KRVector3 &v);
void setWorldTranslation(const Vector3 &v);
void setWorldScale(const Vector3 &v);
void setWorldRotation(const Vector3 &v);
virtual KRAABB getBounds();
virtual AABB getBounds();
void invalidateBounds() const;
const KRMat4 &getModelMatrix();
const KRMat4 &getInverseModelMatrix();
const KRMat4 &getBindPoseMatrix();
const KRMat4 &getActivePoseMatrix();
const KRMat4 &getInverseBindPoseMatrix();
const Matrix4 &getModelMatrix();
const Matrix4 &getInverseModelMatrix();
const Matrix4 &getBindPoseMatrix();
const Matrix4 &getActivePoseMatrix();
const Matrix4 &getInverseBindPoseMatrix();
enum node_attribute_type {
KRENGINE_NODE_ATTRIBUTE_NONE,
@@ -182,27 +186,27 @@ public:
virtual void setLODVisibility(LodVisibility lod_visibility);
protected:
KRVector3 m_localTranslation;
KRVector3 m_localScale;
KRVector3 m_localRotation;
Vector3 m_localTranslation;
Vector3 m_localScale;
Vector3 m_localRotation;
KRVector3 m_rotationOffset;
KRVector3 m_scalingOffset;
KRVector3 m_rotationPivot;
KRVector3 m_scalingPivot;
KRVector3 m_preRotation;
KRVector3 m_postRotation;
Vector3 m_rotationOffset;
Vector3 m_scalingOffset;
Vector3 m_rotationPivot;
Vector3 m_scalingPivot;
Vector3 m_preRotation;
Vector3 m_postRotation;
KRVector3 m_initialLocalTranslation;
KRVector3 m_initialLocalScale;
KRVector3 m_initialLocalRotation;
Vector3 m_initialLocalTranslation;
Vector3 m_initialLocalScale;
Vector3 m_initialLocalRotation;
KRVector3 m_initialRotationOffset;
KRVector3 m_initialScalingOffset;
KRVector3 m_initialRotationPivot;
KRVector3 m_initialScalingPivot;
KRVector3 m_initialPreRotation;
KRVector3 m_initialPostRotation;
Vector3 m_initialRotationOffset;
Vector3 m_initialScalingOffset;
Vector3 m_initialRotationPivot;
Vector3 m_initialScalingPivot;
Vector3 m_initialPreRotation;
Vector3 m_initialPostRotation;
LodVisibility m_lod_visible;
@@ -215,18 +219,18 @@ private:
long m_lastRenderFrame;
void invalidateModelMatrix();
void invalidateBindPoseMatrix();
KRMat4 m_modelMatrix;
KRMat4 m_inverseModelMatrix;
KRMat4 m_bindPoseMatrix;
KRMat4 m_activePoseMatrix;
KRMat4 m_inverseBindPoseMatrix;
Matrix4 m_modelMatrix;
Matrix4 m_inverseModelMatrix;
Matrix4 m_bindPoseMatrix;
Matrix4 m_activePoseMatrix;
Matrix4 m_inverseBindPoseMatrix;
bool m_modelMatrixValid;
bool m_inverseModelMatrixValid;
bool m_bindPoseMatrixValid;
bool m_activePoseMatrixValid;
bool m_inverseBindPoseMatrixValid;
mutable KRAABB m_bounds;
mutable AABB m_bounds;
mutable bool m_boundsValid;
std::string m_name;

View File

@@ -25,10 +25,10 @@ KROctree::~KROctree()
void KROctree::add(KRNode *pNode)
{
KRAABB nodeBounds = pNode->getBounds();
if(nodeBounds == KRAABB::Zero()) {
AABB nodeBounds = pNode->getBounds();
if(nodeBounds == AABB::Zero()) {
// This item is not visible, don't add it to the octree or outer scene nodes
} else if(nodeBounds == KRAABB::Infinite()) {
} else if(nodeBounds == AABB::Infinite()) {
// This item is infinitely large; we track it separately
m_outerSceneNodes.insert(pNode);
} else {
@@ -40,12 +40,12 @@ void KROctree::add(KRNode *pNode)
// Keep encapsulating the root node until the new root contains the inserted node
bool bInsideRoot = false;
while(!bInsideRoot) {
KRAABB rootBounds = m_pRootNode->getBounds();
KRVector3 rootSize = rootBounds.size();
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) {
m_pRootNode = new KROctreeNode(NULL, KRAABB(rootBounds.min - rootSize, rootBounds.max), 7, m_pRootNode);
m_pRootNode = new KROctreeNode(NULL, AABB(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) {
m_pRootNode = new KROctreeNode(NULL, KRAABB(rootBounds.min, rootBounds.max + rootSize), 0, m_pRootNode);
m_pRootNode = new KROctreeNode(NULL, AABB(rootBounds.min, rootBounds.max + rootSize), 0, m_pRootNode);
} else {
bInsideRoot = true;
}
@@ -97,7 +97,7 @@ std::set<KRNode *> &KROctree::getOuterSceneNodes()
}
bool KROctree::lineCast(const KRVector3 &v0, const KRVector3 &v1, KRHitInfo &hitinfo, unsigned int layer_mask)
bool KROctree::lineCast(const Vector3 &v0, const Vector3 &v1, KRHitInfo &hitinfo, unsigned int layer_mask)
{
bool hit_found = false;
std::vector<KRCollider *> outer_colliders;
@@ -118,7 +118,7 @@ bool KROctree::lineCast(const KRVector3 &v0, const KRVector3 &v1, KRHitInfo &hit
return hit_found;
}
bool KROctree::rayCast(const KRVector3 &v0, const KRVector3 &dir, KRHitInfo &hitinfo, unsigned int layer_mask)
bool KROctree::rayCast(const Vector3 &v0, const Vector3 &dir, KRHitInfo &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++) {
@@ -133,7 +133,7 @@ bool KROctree::rayCast(const KRVector3 &v0, const KRVector3 &dir, KRHitInfo &hit
return hit_found;
}
bool KROctree::sphereCast(const KRVector3 &v0, const KRVector3 &v1, float radius, KRHitInfo &hitinfo, unsigned int layer_mask)
bool KROctree::sphereCast(const Vector3 &v0, const Vector3 &v1, float radius, KRHitInfo &hitinfo, unsigned int layer_mask)
{
bool hit_found = false;
std::vector<KRCollider *> outer_colliders;

View File

@@ -11,8 +11,6 @@
#include "KREngine-common.h"
#include "KROctreeNode.h"
#include "KRMat4.h"
#include "KRHitInfo.h"
class KRNode;
@@ -20,22 +18,22 @@ class KROctree {
public:
KROctree();
~KROctree();
void add(KRNode *pNode);
void remove(KRNode *pNode);
void update(KRNode *pNode);
KROctreeNode *getRootNode();
std::set<KRNode *> &getOuterSceneNodes();
bool lineCast(const KRVector3 &v0, const KRVector3 &v1, KRHitInfo &hitinfo, unsigned int layer_mask);
bool rayCast(const KRVector3 &v0, const KRVector3 &dir, KRHitInfo &hitinfo, unsigned int layer_mask);
bool sphereCast(const KRVector3 &v0, const KRVector3 &v1, float radius, KRHitInfo &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;
void shrink();
};

View File

@@ -10,7 +10,7 @@
#include "KRNode.h"
#include "KRCollider.h"
KROctreeNode::KROctreeNode(KROctreeNode *parent, const KRAABB &bounds) : m_bounds(bounds)
KROctreeNode::KROctreeNode(KROctreeNode *parent, const AABB &bounds) : m_bounds(bounds)
{
m_parent = parent;
@@ -21,7 +21,7 @@ KROctreeNode::KROctreeNode(KROctreeNode *parent, const KRAABB &bounds) : m_bound
m_activeQuery = false;
}
KROctreeNode::KROctreeNode(KROctreeNode *parent, const KRAABB &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;
@@ -76,7 +76,7 @@ void KROctreeNode::endOcclusionQuery()
}
KRAABB KROctreeNode::getBounds()
AABB KROctreeNode::getBounds()
{
return m_bounds;
}
@@ -95,16 +95,16 @@ void KROctreeNode::add(KRNode *pNode)
}
}
KRAABB KROctreeNode::getChildBounds(int iChild)
AABB KROctreeNode::getChildBounds(int iChild)
{
KRVector3 center = m_bounds.center();
Vector3 center = m_bounds.center();
return KRAABB(
KRVector3(
return AABB(
Vector3(
(iChild & 1) == 0 ? m_bounds.min.x : center.x,
(iChild & 2) == 0 ? m_bounds.min.y : center.y,
(iChild & 4) == 0 ? m_bounds.min.z : center.z),
KRVector3(
Vector3(
(iChild & 1) == 0 ? center.x : m_bounds.max.x,
(iChild & 2) == 0 ? center.y : m_bounds.max.y,
(iChild & 4) == 0 ? center.z : m_bounds.max.z)
@@ -196,7 +196,7 @@ std::set<KRNode *> &KROctreeNode::getSceneNodes()
}
bool KROctreeNode::lineCast(const KRVector3 &v0, const KRVector3 &v1, KRHitInfo &hitinfo, unsigned int layer_mask)
bool KROctreeNode::lineCast(const Vector3 &v0, const Vector3 &v1, KRHitInfo &hitinfo, unsigned int layer_mask)
{
bool hit_found = false;
if(hitinfo.didHit() && v1 != hitinfo.getPosition()) {
@@ -224,7 +224,7 @@ bool KROctreeNode::lineCast(const KRVector3 &v0, const KRVector3 &v1, KRHitInfo
return hit_found;
}
bool KROctreeNode::rayCast(const KRVector3 &v0, const KRVector3 &dir, KRHitInfo &hitinfo, unsigned int layer_mask)
bool KROctreeNode::rayCast(const Vector3 &v0, const Vector3 &dir, KRHitInfo &hitinfo, unsigned int layer_mask)
{
bool hit_found = false;
if(hitinfo.didHit()) {
@@ -252,7 +252,7 @@ bool KROctreeNode::rayCast(const KRVector3 &v0, const KRVector3 &dir, KRHitInfo
return hit_found;
}
bool KROctreeNode::sphereCast(const KRVector3 &v0, const KRVector3 &v1, float radius, KRHitInfo &hitinfo, unsigned int layer_mask)
bool KROctreeNode::sphereCast(const Vector3 &v0, const Vector3 &v1, float radius, KRHitInfo &hitinfo, unsigned int layer_mask)
{
bool hit_found = false;
/*
@@ -264,7 +264,7 @@ bool KROctreeNode::sphereCast(const KRVector3 &v0, const KRVector3 &v1, float ra
} else {
*/
KRAABB swept_bounds = KRAABB(KRVector3(KRMIN(v0.x, v1.x) - radius, KRMIN(v0.y, v1.y) - radius, KRMIN(v0.z, v1.z) - radius), KRVector3(KRMAX(v0.x, v1.x) + radius, KRMAX(v0.y, v1.y) + radius, KRMAX(v0.z, v1.z) + radius));
AABB swept_bounds = AABB(Vector3(KRMIN(v0.x, v1.x) - radius, KRMIN(v0.y, v1.y) - radius, KRMIN(v0.z, v1.z) - radius), Vector3(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)) {

View File

@@ -10,56 +10,54 @@
#define KROCTREENODE_H
#include "KREngine-common.h"
#include "KRVector3.h"
#include "KRAABB.h"
#include "KRHitInfo.h"
#include "public/hitinfo.h"
class KRNode;
class KROctreeNode {
public:
KROctreeNode(KROctreeNode *parent, const KRAABB &bounds);
KROctreeNode(KROctreeNode *parent, const KRAABB &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();
void add(KRNode *pNode);
void remove(KRNode *pNode);
void update(KRNode *pNode);
KRAABB getBounds();
AABB getBounds();
KROctreeNode *getParent();
void setChildNode(int iChild, KROctreeNode *pChild);
int getChildIndex(KRNode *pNode);
KRAABB getChildBounds(int iChild);
AABB getChildBounds(int iChild);
void trim();
bool isEmpty() const;
bool canShrinkRoot() const;
KROctreeNode *stripChild();
void beginOcclusionQuery();
void endOcclusionQuery();
GLuint m_occlusionQuery;
bool m_occlusionTested;
bool m_activeQuery;
bool lineCast(const KRVector3 &v0, const KRVector3 &v1, KRHitInfo &hitinfo, unsigned int layer_mask);
bool rayCast(const KRVector3 &v0, const KRVector3 &dir, KRHitInfo &hitinfo, unsigned int layer_mask);
bool sphereCast(const KRVector3 &v0, const KRVector3 &v1, float radius, KRHitInfo &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:
KRAABB m_bounds;
AABB m_bounds;
KROctreeNode *m_parent;
KROctreeNode *m_children[8];
std::set<KRNode *>m_sceneNodes;
};

View File

@@ -19,7 +19,7 @@ public:
virtual void loadXML(tinyxml2::XMLElement *e);
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual KRAABB getBounds() = 0;
virtual AABB getBounds() = 0;
virtual void render(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, KRNode::RenderPass renderPass) = 0;

View File

@@ -6,8 +6,9 @@
// Copyright (c) 2012 Kearwood Software. All rights reserved.
//
#include "KREngine-common.h"
#include "KRParticleSystemNewtonian.h"
#include "KRAABB.h"
#include "KRTexture.h"
#include "KRContext.h"
@@ -38,9 +39,9 @@ tinyxml2::XMLElement *KRParticleSystemNewtonian::saveXML( tinyxml2::XMLNode *par
}
KRAABB KRParticleSystemNewtonian::getBounds()
AABB KRParticleSystemNewtonian::getBounds()
{
return KRAABB(-KRVector3::One(), KRVector3::One(), getModelMatrix());
return AABB(-Vector3::One(), Vector3::One(), getModelMatrix());
}
void KRParticleSystemNewtonian::physicsUpdate(float deltaTime)
@@ -75,8 +76,8 @@ void KRParticleSystemNewtonian::render(KRCamera *pCamera, std::vector<KRPointLig
KRShader *pParticleShader = m_pContext->getShaderManager()->getShader("dust_particle", pCamera, point_lights, directional_lights, spot_lights, 0, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, renderPass);
KRVector3 rim_color; KRVector4 fade_color;
if(getContext().getShaderManager()->selectShader(*pCamera, pParticleShader, viewport, getModelMatrix(), point_lights, directional_lights, spot_lights, 0, renderPass, KRVector3::Zero(), 0.0f, KRVector4::Zero())) {
Vector3 rim_color; Vector4 fade_color;
if(getContext().getShaderManager()->selectShader(*pCamera, pParticleShader, viewport, getModelMatrix(), point_lights, directional_lights, spot_lights, 0, renderPass, Vector3::Zero(), 0.0f, Vector4::Zero())) {
pParticleShader->setUniform(KRShader::KRENGINE_UNIFORM_FLARE_SIZE, 1.0f);
KRDataBlock index_data;

View File

@@ -21,7 +21,7 @@ public:
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual KRAABB getBounds();
virtual AABB getBounds();
virtual void render(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, KRNode::RenderPass renderPass);

View File

@@ -9,8 +9,6 @@
#include "KREngine-common.h"
#include "KRPointLight.h"
#include "KRMat4.h"
#include "KRVector3.h"
#include "KRCamera.h"
#include "KRContext.h"
#include "KRStockGeometry.h"
@@ -33,12 +31,12 @@ std::string KRPointLight::getElementName() {
return "point_light";
}
KRAABB KRPointLight::getBounds() {
AABB KRPointLight::getBounds() {
float influence_radius = m_decayStart - sqrt(m_intensity * 0.01f) / sqrt(KRLIGHT_MIN_INFLUENCE);
if(influence_radius < m_flareOcclusionSize) {
influence_radius = m_flareOcclusionSize;
}
return KRAABB(KRVector3(-influence_radius), KRVector3(influence_radius), getModelMatrix());
return AABB(Vector3(-influence_radius), Vector3(influence_radius), getModelMatrix());
}
void KRPointLight::render(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, KRNode::RenderPass renderPass)
@@ -55,22 +53,22 @@ void KRPointLight::render(KRCamera *pCamera, std::vector<KRPointLight *> &point_
std::vector<KRPointLight *> this_light;
this_light.push_back(this);
KRVector3 light_position = getLocalTranslation();
Vector3 light_position = getLocalTranslation();
float influence_radius = m_decayStart - sqrt(m_intensity * 0.01f) / sqrt(KRLIGHT_MIN_INFLUENCE);
KRMat4 sphereModelMatrix = KRMat4();
Matrix4 sphereModelMatrix = Matrix4();
sphereModelMatrix.scale(influence_radius);
sphereModelMatrix.translate(light_position.x, light_position.y, light_position.z);
if(viewport.visible(getBounds())) { // Cull out any lights not within the view frustrum
KRVector3 view_light_position = KRMat4::Dot(viewport.getViewMatrix(), light_position);
Vector3 view_light_position = Matrix4::Dot(viewport.getViewMatrix(), light_position);
bool bInsideLight = view_light_position.sqrMagnitude() <= (influence_radius + pCamera->settings.getPerspectiveNearZ()) * (influence_radius + pCamera->settings.getPerspectiveNearZ());
KRShader *pShader = getContext().getShaderManager()->getShader(bVisualize ? "visualize_overlay" : (bInsideLight ? "light_point_inside" : "light_point"), pCamera, this_light, std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, renderPass);
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, sphereModelMatrix, this_light, std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, renderPass, KRVector3::Zero(), 0.0f, KRVector4::Zero())) {
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, sphereModelMatrix, this_light, std::vector<KRDirectionalLight *>(), std::vector<KRSpotLight *>(), 0, renderPass, Vector3::Zero(), 0.0f, Vector4::Zero())) {
pShader->setUniform(KRShader::KRENGINE_UNIFORM_LIGHT_COLOR, m_color);
@@ -148,25 +146,25 @@ void KRPointLight::generateMesh() {
~Facet3() {
}
KRVector3 p1;
KRVector3 p2;
KRVector3 p3;
Vector3 p1;
Vector3 p2;
Vector3 p3;
};
std::vector<Facet3> f = std::vector<Facet3>(facet_count);
int i,it;
float a;
KRVector3 p[6] = {
KRVector3(0,0,1),
KRVector3(0,0,-1),
KRVector3(-1,-1,0),
KRVector3(1,-1,0),
KRVector3(1,1,0),
KRVector3(-1,1,0)
Vector3 p[6] = {
Vector3(0,0,1),
Vector3(0,0,-1),
Vector3(-1,-1,0),
Vector3(1,-1,0),
Vector3(1,1,0),
Vector3(-1,1,0)
};
KRVector3 pa,pb,pc;
Vector3 pa,pb,pc;
int nt = 0,ntold;
/* Create the level 0 object */

View File

@@ -10,7 +10,6 @@
#define KRPOINTLIGHT_H
#include "KRLight.h"
#include "KRMat4.h"
class KRPointLight : public KRLight {
@@ -20,7 +19,7 @@ public:
virtual ~KRPointLight();
virtual std::string getElementName();
virtual KRAABB getBounds();
virtual AABB getBounds();
virtual void render(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, KRNode::RenderPass renderPass);

View File

@@ -1,360 +0,0 @@
//
// KRQuaternion.cpp
// KREngine
//
// Copyright 2012 Kearwood Gilbert. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY KEARWOOD GILBERT ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KEARWOOD GILBERT OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Kearwood Gilbert.
//
#include "KRQuaternion.h"
#include "KRVector3.h"
KRQuaternion::KRQuaternion() {
m_val[0] = 1.0;
m_val[1] = 0.0;
m_val[2] = 0.0;
m_val[3] = 0.0;
}
KRQuaternion::KRQuaternion(float w, float x, float y, float z) {
m_val[0] = w;
m_val[1] = x;
m_val[2] = y;
m_val[3] = z;
}
KRQuaternion::KRQuaternion(const KRQuaternion& p) {
m_val[0] = p[0];
m_val[1] = p[1];
m_val[2] = p[2];
m_val[3] = p[3];
}
KRQuaternion& KRQuaternion::operator =( const KRQuaternion& p ) {
m_val[0] = p[0];
m_val[1] = p[1];
m_val[2] = p[2];
m_val[3] = p[3];
return *this;
}
KRQuaternion::KRQuaternion(const KRVector3 &euler) {
setEulerZYX(euler);
}
KRQuaternion::KRQuaternion(const KRVector3 &from_vector, const KRVector3 &to_vector) {
KRVector3 a = KRVector3::Cross(from_vector, to_vector);
m_val[0] = a[0];
m_val[1] = a[1];
m_val[2] = a[2];
m_val[3] = sqrt(from_vector.sqrMagnitude() * to_vector.sqrMagnitude()) + KRVector3::Dot(from_vector, to_vector);
normalize();
}
KRQuaternion::~KRQuaternion() {
}
void KRQuaternion::setEulerXYZ(const KRVector3 &euler)
{
*this = KRQuaternion::FromAngleAxis(KRVector3(1.0f, 0.0f, 0.0f), euler.x)
* KRQuaternion::FromAngleAxis(KRVector3(0.0f, 1.0f, 0.0f), euler.y)
* KRQuaternion::FromAngleAxis(KRVector3(0.0f, 0.0f, 1.0f), euler.z);
}
void KRQuaternion::setEulerZYX(const KRVector3 &euler) {
// ZYX Order!
float c1 = cos(euler[0] * 0.5f);
float c2 = cos(euler[1] * 0.5f);
float c3 = cos(euler[2] * 0.5f);
float s1 = sin(euler[0] * 0.5f);
float s2 = sin(euler[1] * 0.5f);
float s3 = sin(euler[2] * 0.5f);
m_val[0] = c1 * c2 * c3 + s1 * s2 * s3;
m_val[1] = s1 * c2 * c3 - c1 * s2 * s3;
m_val[2] = c1 * s2 * c3 + s1 * c2 * s3;
m_val[3] = c1 * c2 * s3 - s1 * s2 * c3;
}
float KRQuaternion::operator [](unsigned i) const {
return m_val[i];
}
float &KRQuaternion::operator [](unsigned i) {
return m_val[i];
}
KRVector3 KRQuaternion::eulerXYZ() const {
double a2 = 2 * (m_val[0] * m_val[2] - m_val[1] * m_val[3]);
if(a2 <= -0.99999) {
return KRVector3(
2.0 * atan2(m_val[1], m_val[0]),
-PI * 0.5f,
0
);
} else if(a2 >= 0.99999) {
return KRVector3(
2.0 * atan2(m_val[1], m_val[0]),
PI * 0.5f,
0
);
} else {
return KRVector3(
atan2(2 * (m_val[0] * m_val[1] + m_val[2] * m_val[3]), (1 - 2 * (m_val[1] * m_val[1] + m_val[2] * m_val[2]))),
asin(a2),
atan2(2 * (m_val[0] * m_val[3] + m_val[1] * m_val[2]), (1 - 2 * (m_val[2] * m_val[2] + m_val[3] * m_val[3])))
);
}
}
bool operator ==(KRQuaternion &v1, KRQuaternion &v2) {
return
v1[0] == v2[0]
&& v1[1] == v2[1]
&& v1[2] == v2[2]
&& v1[3] == v2[3];
}
bool operator !=(KRQuaternion &v1, KRQuaternion &v2) {
return
v1[0] != v2[0]
|| v1[1] != v2[1]
|| v1[2] != v2[2]
|| v1[3] != v2[3];
}
KRQuaternion KRQuaternion::operator *(const KRQuaternion &v) {
float t0 = (m_val[3]-m_val[2])*(v[2]-v[3]);
float t1 = (m_val[0]+m_val[1])*(v[0]+v[1]);
float t2 = (m_val[0]-m_val[1])*(v[2]+v[3]);
float t3 = (m_val[3]+m_val[2])*(v[0]-v[1]);
float t4 = (m_val[3]-m_val[1])*(v[1]-v[2]);
float t5 = (m_val[3]+m_val[1])*(v[1]+v[2]);
float t6 = (m_val[0]+m_val[2])*(v[0]-v[3]);
float t7 = (m_val[0]-m_val[2])*(v[0]+v[3]);
float t8 = t5+t6+t7;
float t9 = (t4+t8)/2;
return KRQuaternion(
t0+t9-t5,
t1+t9-t8,
t2+t9-t7,
t3+t9-t6
);
}
KRQuaternion KRQuaternion::operator *(float v) const {
return KRQuaternion(m_val[0] * v, m_val[1] * v, m_val[2] * v, m_val[3] * v);
}
KRQuaternion KRQuaternion::operator /(float num) const {
float inv_num = 1.0f / num;
return KRQuaternion(m_val[0] * inv_num, m_val[1] * inv_num, m_val[2] * inv_num, m_val[3] * inv_num);
}
KRQuaternion KRQuaternion::operator +(const KRQuaternion &v) const {
return KRQuaternion(m_val[0] + v[0], m_val[1] + v[1], m_val[2] + v[2], m_val[3] + v[3]);
}
KRQuaternion KRQuaternion::operator -(const KRQuaternion &v) const {
return KRQuaternion(m_val[0] - v[0], m_val[1] - v[1], m_val[2] - v[2], m_val[3] - v[3]);
}
KRQuaternion& KRQuaternion::operator +=(const KRQuaternion& v) {
m_val[0] += v[0];
m_val[1] += v[1];
m_val[2] += v[2];
m_val[3] += v[3];
return *this;
}
KRQuaternion& KRQuaternion::operator -=(const KRQuaternion& v) {
m_val[0] -= v[0];
m_val[1] -= v[1];
m_val[2] -= v[2];
m_val[3] -= v[3];
return *this;
}
KRQuaternion& KRQuaternion::operator *=(const KRQuaternion& v) {
float t0 = (m_val[3]-m_val[2])*(v[2]-v[3]);
float t1 = (m_val[0]+m_val[1])*(v[0]+v[1]);
float t2 = (m_val[0]-m_val[1])*(v[2]+v[3]);
float t3 = (m_val[3]+m_val[2])*(v[0]-v[1]);
float t4 = (m_val[3]-m_val[1])*(v[1]-v[2]);
float t5 = (m_val[3]+m_val[1])*(v[1]+v[2]);
float t6 = (m_val[0]+m_val[2])*(v[0]-v[3]);
float t7 = (m_val[0]-m_val[2])*(v[0]+v[3]);
float t8 = t5+t6+t7;
float t9 = (t4+t8)/2;
m_val[0] = t0+t9-t5;
m_val[1] = t1+t9-t8;
m_val[2] = t2+t9-t7;
m_val[3] = t3+t9-t6;
return *this;
}
KRQuaternion& KRQuaternion::operator *=(const float& v) {
m_val[0] *= v;
m_val[1] *= v;
m_val[2] *= v;
m_val[3] *= v;
return *this;
}
KRQuaternion& KRQuaternion::operator /=(const float& v) {
float inv_v = 1.0f / v;
m_val[0] *= inv_v;
m_val[1] *= inv_v;
m_val[2] *= inv_v;
m_val[3] *= inv_v;
return *this;
}
KRQuaternion KRQuaternion::operator +() const {
return *this;
}
KRQuaternion KRQuaternion::operator -() const {
return KRQuaternion(-m_val[0], -m_val[1], -m_val[2], -m_val[3]);
}
KRQuaternion Normalize(const KRQuaternion &v1) {
float inv_magnitude = 1.0f / sqrtf(v1[0] * v1[0] + v1[1] * v1[1] + v1[2] * v1[2] + v1[3] * v1[3]);
return KRQuaternion(
v1[0] * inv_magnitude,
v1[1] * inv_magnitude,
v1[2] * inv_magnitude,
v1[3] * inv_magnitude
);
}
void KRQuaternion::normalize() {
float inv_magnitude = 1.0f / sqrtf(m_val[0] * m_val[0] + m_val[1] * m_val[1] + m_val[2] * m_val[2] + m_val[3] * m_val[3]);
m_val[0] *= inv_magnitude;
m_val[1] *= inv_magnitude;
m_val[2] *= inv_magnitude;
m_val[3] *= inv_magnitude;
}
KRQuaternion Conjugate(const KRQuaternion &v1) {
return KRQuaternion(v1[0], -v1[1], -v1[2], -v1[3]);
}
void KRQuaternion::conjugate() {
m_val[1] = -m_val[1];
m_val[2] = -m_val[2];
m_val[3] = -m_val[3];
}
KRMat4 KRQuaternion::rotationMatrix() const {
KRMat4 matRotate;
/*
KRVector3 euler = eulerXYZ();
matRotate.rotate(euler.x, X_AXIS);
matRotate.rotate(euler.y, Y_AXIS);
matRotate.rotate(euler.z, Z_AXIS);
*/
// FINDME - Determine why the more optimal routine commented below wasn't working
matRotate.c[0] = 1.0 - 2.0 * (m_val[2] * m_val[2] + m_val[3] * m_val[3]);
matRotate.c[1] = 2.0 * (m_val[1] * m_val[2] - m_val[0] * m_val[3]);
matRotate.c[2] = 2.0 * (m_val[0] * m_val[2] + m_val[1] * m_val[3]);
matRotate.c[4] = 2.0 * (m_val[1] * m_val[2] + m_val[0] * m_val[3]);
matRotate.c[5] = 1.0 - 2.0 * (m_val[1] * m_val[1] + m_val[3] * m_val[3]);
matRotate.c[6] = 2.0 * (m_val[2] * m_val[3] - m_val[0] * m_val[1]);
matRotate.c[8] = 2.0 * (m_val[1] * m_val[3] - m_val[0] * m_val[2]);
matRotate.c[9] = 2.0 * (m_val[0] * m_val[1] + m_val[2] * m_val[3]);
matRotate.c[10] = 1.0 - 2.0 * (m_val[1] * m_val[1] + m_val[2] * m_val[2]);
return matRotate;
}
KRQuaternion KRQuaternion::FromAngleAxis(const KRVector3 &axis, float angle)
{
float ha = angle * 0.5f;
float sha = sin(ha);
return KRQuaternion(cos(ha), axis.x * sha, axis.y * sha, axis.z * sha);
}
float KRQuaternion::Dot(const KRQuaternion &v1, const KRQuaternion &v2)
{
return v1.m_val[0] * v2.m_val[0] + v1.m_val[1] * v2.m_val[1] + v1.m_val[2] * v2.m_val[2] + v1.m_val[3] * v2.m_val[3];
}
KRQuaternion KRQuaternion::Lerp(const KRQuaternion &a, const KRQuaternion &b, float t)
{
if (t <= 0.0f) {
return a;
} else if (t >= 1.0f) {
return b;
}
return a * (1.0f - t) + b * t;
}
KRQuaternion KRQuaternion::Slerp(const KRQuaternion &a, const KRQuaternion &b, float t)
{
if (t <= 0.0f) {
return a;
}
if (t >= 1.0f) {
return b;
}
float coshalftheta = Dot(a, b);
KRQuaternion c = a;
// Angle is greater than 180. We can negate the angle/quat to get the
// shorter rotation to reach the same destination.
if ( coshalftheta < 0.0f ) {
coshalftheta = -coshalftheta;
c = -c;
}
if ( coshalftheta > (1.0f - std::numeric_limits<float>::epsilon())) {
// Angle is tiny - save some computation by lerping instead.
return Lerp(c, b, t);
}
float halftheta = acos(coshalftheta);
return (c * sin((1.0f - t) * halftheta) + b * sin(t * halftheta)) / sin(halftheta);
}

View File

@@ -1,89 +0,0 @@
//
// KRQuaternion.h
// KREngine
//
// Copyright 2012 Kearwood Gilbert. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY KEARWOOD GILBERT ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KEARWOOD GILBERT OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Kearwood Gilbert.
//
#ifndef KRQUATERNION_H
#define KRQUATERNION_H
#include "KREngine-common.h"
#include "KRMat4.h"
class KRVector3;
class KRQuaternion {
public:
KRQuaternion();
KRQuaternion(float w, float x, float y, float z);
KRQuaternion(const KRQuaternion& p);
KRQuaternion(const KRVector3 &euler);
KRQuaternion(const KRVector3 &from_vector, const KRVector3 &to_vector);
~KRQuaternion();
KRQuaternion& operator =( const KRQuaternion& p );
KRQuaternion operator +(const KRQuaternion &v) const;
KRQuaternion operator -(const KRQuaternion &v) const;
KRQuaternion operator +() const;
KRQuaternion operator -() const;
KRQuaternion operator *(const KRQuaternion &v);
KRQuaternion operator *(float num) const;
KRQuaternion operator /(float num) const;
KRQuaternion& operator +=(const KRQuaternion& v);
KRQuaternion& operator -=(const KRQuaternion& v);
KRQuaternion& operator *=(const KRQuaternion& v);
KRQuaternion& operator *=(const float& v);
KRQuaternion& operator /=(const float& v);
friend bool operator ==(KRQuaternion &v1, KRQuaternion &v2);
friend bool operator !=(KRQuaternion &v1, KRQuaternion &v2);
float& operator [](unsigned i);
float operator [](unsigned i) const;
void setEulerXYZ(const KRVector3 &euler);
void setEulerZYX(const KRVector3 &euler);
KRVector3 eulerXYZ() const;
KRMat4 rotationMatrix() const;
void normalize();
static KRQuaternion Normalize(const KRQuaternion &v1);
void conjugate();
static KRQuaternion Conjugate(const KRQuaternion &v1);
static KRQuaternion FromAngleAxis(const KRVector3 &axis, float angle);
static KRQuaternion Lerp(const KRQuaternion &a, const KRQuaternion &b, float t);
static KRQuaternion Slerp(const KRQuaternion &a, const KRQuaternion &b, float t);
static float Dot(const KRQuaternion &v1, const KRQuaternion &v2);
private:
float m_val[4];
};
#endif

View File

@@ -33,8 +33,8 @@ KRRenderSettings::KRRenderSettings()
bEnableDeferredLighting = false;
max_anisotropy = 4.0f;
ambient_intensity = KRVector3::Zero();
light_intensity = KRVector3::One();
ambient_intensity = Vector3::Zero();
light_intensity = Vector3::One();
perspective_fov = 45.0 * D2R;
perspective_nearz = 0.3f; // was 0.05f
@@ -67,7 +67,7 @@ KRRenderSettings::KRRenderSettings()
fog_near = 50.0f;
fog_far = 500.0f;
fog_density = 0.0005f;
fog_color = KRVector3(0.45, 0.45, 0.5);
fog_color = Vector3(0.45, 0.45, 0.5);
fog_type = 0;
dust_particle_intensity = 0.25f;
@@ -153,11 +153,11 @@ KRRenderSettings& KRRenderSettings::operator=(const KRRenderSettings &s)
return *this;
}
const KRVector2 &KRRenderSettings::getViewportSize() {
const Vector2 &KRRenderSettings::getViewportSize() {
return m_viewportSize;
}
void KRRenderSettings::setViewportSize(const KRVector2 &size) {
void KRRenderSettings::setViewportSize(const Vector2 &size) {
m_viewportSize = size;
}

View File

@@ -19,8 +19,8 @@ public:
// Overload assignment operator
KRRenderSettings& operator=(const KRRenderSettings &s);
const KRVector2 &getViewportSize();
void setViewportSize(const KRVector2 &size);
const Vector2 &getViewportSize();
void setViewportSize(const Vector2 &size);
float getPerspectiveNearZ();
float getPerspectiveFarZ();
@@ -45,8 +45,8 @@ public:
bool bEnableDiffuse;
bool bEnableSpecular;
bool bEnableDeferredLighting;
KRVector3 light_intensity;
KRVector3 ambient_intensity;
Vector3 light_intensity;
Vector3 ambient_intensity;
float perspective_fov;
int dof_quality;
@@ -61,7 +61,7 @@ public:
float vignette_radius;
float vignette_falloff;
KRVector2 m_viewportSize;
Vector2 m_viewportSize;
int m_cShadowBuffers;
@@ -76,7 +76,7 @@ public:
float fog_near;
float fog_far;
float fog_density;
KRVector3 fog_color;
Vector3 fog_color;
int fog_type; // 0 = no fog, 1 = linear, 2 = exponential, 3 = exponential squared
float dust_particle_intensity;

View File

@@ -22,7 +22,6 @@
#include "KRSpotLight.h"
#include "KRNode.h"
#include "KRScene.h"
#include "KRQuaternion.h"
#include "KRBone.h"
#include "KRLocator.h"
#include "KRBundle.h"
@@ -591,7 +590,7 @@ void LoadNode(FbxScene* pFbxScene, KRNode *parent_node, FbxGeometryConverter *pG
// Transform = T * Roff * Rp * Rpre * R * Rpost * inverse(Rp) * Soff * Sp * S * inverse(Sp)
int node_has_n_points = 0; // this will be 3 if the node_frame_key_position is complete after the import animated properties loop
KRVector3 node_key_frame_position = KRVector3(0.0, 0.0, 0.0);
Vector3 node_key_frame_position = Vector3(0.0, 0.0, 0.0);
// ADDED 3, 2013 by Peter to store the key frame (start location) of an animation
// the x, y, z translation position of the animation will be extracted from the curves
// as they are added to the animation layer in the loop below ..
@@ -918,22 +917,22 @@ void LoadNode(FbxScene* pFbxScene, KRNode *parent_node, FbxGeometryConverter *pG
// do we store it as node_local or store it as the world translation? or somewhere else ??
//
KRVector3 node_translation = KRVector3(local_translation[0], local_translation[1], local_translation[2]); // T * Roff * Rp
KRVector3 node_rotation = KRVector3(local_rotation[0], local_rotation[1], local_rotation[2]) / 180.0 * M_PI;
KRVector3 node_scale = KRVector3(local_scale[0], local_scale[1], local_scale[2]);
Vector3 node_translation = Vector3(local_translation[0], local_translation[1], local_translation[2]); // T * Roff * Rp
Vector3 node_rotation = Vector3(local_rotation[0], local_rotation[1], local_rotation[2]) / 180.0 * M_PI;
Vector3 node_scale = Vector3(local_scale[0], local_scale[1], local_scale[2]);
KRVector3 node_rotation_offset = KRVector3(rotation_offset[0], rotation_offset[1], rotation_offset[2]);
KRVector3 node_scaling_offset = KRVector3(scaling_offset[0], scaling_offset[1], scaling_offset[2]);
KRVector3 node_rotation_pivot = KRVector3(rotation_pivot[0], rotation_pivot[1], rotation_pivot[2]);
KRVector3 node_scaling_pivot = KRVector3(scaling_pivot[0], scaling_pivot[1], scaling_pivot[2]);
KRVector3 node_pre_rotation, node_post_rotation;
Vector3 node_rotation_offset = Vector3(rotation_offset[0], rotation_offset[1], rotation_offset[2]);
Vector3 node_scaling_offset = Vector3(scaling_offset[0], scaling_offset[1], scaling_offset[2]);
Vector3 node_rotation_pivot = Vector3(rotation_pivot[0], rotation_pivot[1], rotation_pivot[2]);
Vector3 node_scaling_pivot = Vector3(scaling_pivot[0], scaling_pivot[1], scaling_pivot[2]);
Vector3 node_pre_rotation, node_post_rotation;
if(rotation_active) {
node_pre_rotation = KRVector3(pre_rotation[0], pre_rotation[1], pre_rotation[2]) / 180.0 * M_PI;
node_post_rotation = KRVector3(post_rotation[0], post_rotation[1], post_rotation[2]) / 180.0 * M_PI;
node_pre_rotation = Vector3(pre_rotation[0], pre_rotation[1], pre_rotation[2]) / 180.0 * M_PI;
node_post_rotation = Vector3(post_rotation[0], post_rotation[1], post_rotation[2]) / 180.0 * M_PI;
//&KRF HACK removing this line (above) to prevent the post rotation from corrupting the default light values; the FBX is importing a post rotation and setting it to -90 degrees
} else {
node_pre_rotation = KRVector3::Zero();
node_post_rotation = KRVector3::Zero();
node_pre_rotation = Vector3::Zero();
node_post_rotation = Vector3::Zero();
}
// printf(" Local Translation: %f %f %f\n", local_translation[0], local_translation[1], local_translation[2]);
@@ -955,7 +954,7 @@ void LoadNode(FbxScene* pFbxScene, KRNode *parent_node, FbxGeometryConverter *pG
KRLODSet *lod_set = new KRLODSet(parent_node->getScene(), name);
parent_node->addChild(lod_set);
KRAABB reference_bounds;
AABB reference_bounds;
// Create a lod_group node for each fbx child node
int child_count = pNode->GetChildCount();
for(int i = 0; i < child_count; i++)
@@ -1023,7 +1022,7 @@ void LoadNode(FbxScene* pFbxScene, KRNode *parent_node, FbxGeometryConverter *pG
reference_bounds = new_node->getBounds();
}
new_node->setReference(KRAABB(reference_bounds.min, reference_bounds.max, new_node->getInverseModelMatrix()));
new_node->setReference(AABB(reference_bounds.min, reference_bounds.max, new_node->getInverseModelMatrix()));
}
} else {
KRNode *new_node = NULL;
@@ -1116,15 +1115,15 @@ void LoadMaterial(KRContext &context, FbxSurfaceMaterial *pMaterial) {
// Ambient Color
lKFbxDouble3 =((FbxSurfacePhong *) pMaterial)->Ambient;
new_material->setAmbient(KRVector3(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]));
new_material->setAmbient(Vector3(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]));
// Diffuse Color
lKFbxDouble3 =((FbxSurfacePhong *) pMaterial)->Diffuse;
new_material->setDiffuse(KRVector3(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]));
new_material->setDiffuse(Vector3(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]));
// Specular Color (unique to Phong materials)
lKFbxDouble3 =((FbxSurfacePhong *) pMaterial)->Specular;
new_material->setSpecular(KRVector3(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]));
new_material->setSpecular(Vector3(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]));
// Emissive Color
//lKFbxDouble3 =((KFbxSurfacePhong *) pMaterial)->Emissive;
@@ -1156,18 +1155,18 @@ void LoadMaterial(KRContext &context, FbxSurfaceMaterial *pMaterial) {
//lKFbxDouble3 =((FbxSurfacePhong *) pMaterial)->Reflection;
// We modulate Relection color by reflection factor, as we only have one "reflection color" variable in Kraken
new_material->setReflection(KRVector3(/*lKFbxDouble3.Get()[0] * */lKFbxDouble1.Get(), /*lKFbxDouble3.Get()[1] * */lKFbxDouble1.Get(), /*lKFbxDouble3.Get()[2] * */lKFbxDouble1.Get()));
new_material->setReflection(Vector3(/*lKFbxDouble3.Get()[0] * */lKFbxDouble1.Get(), /*lKFbxDouble3.Get()[1] * */lKFbxDouble1.Get(), /*lKFbxDouble3.Get()[2] * */lKFbxDouble1.Get()));
} else if(pMaterial->GetClassId().Is(FbxSurfaceLambert::ClassId) ) {
// We found a Lambert material.
// Ambient Color
lKFbxDouble3=((FbxSurfaceLambert *)pMaterial)->Ambient;
new_material->setAmbient(KRVector3(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]));
new_material->setAmbient(Vector3(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]));
// Diffuse Color
lKFbxDouble3 =((FbxSurfaceLambert *)pMaterial)->Diffuse;
new_material->setDiffuse(KRVector3(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]));
new_material->setDiffuse(Vector3(lKFbxDouble3.Get()[0], lKFbxDouble3.Get()[1], lKFbxDouble3.Get()[2]));
// Emissive
//lKFbxDouble3 =((KFbxSurfaceLambert *)pMaterial)->Emissive;
@@ -1211,7 +1210,7 @@ void LoadMaterial(KRContext &context, FbxSurfaceMaterial *pMaterial) {
FbxFileTexture *pFileTexture = FbxCast<FbxFileTexture>(pTexture);
if(pFileTexture) {
new_material->setDiffuseMap(KRResource::GetFileBase(pFileTexture->GetFileName()), KRVector2(pTexture->GetScaleU(), pTexture->GetScaleV()), KRVector2(pTexture->GetTranslationU(), pTexture->GetTranslationV()));
new_material->setDiffuseMap(KRResource::GetFileBase(pFileTexture->GetFileName()), Vector2(pTexture->GetScaleU(), pTexture->GetScaleV()), Vector2(pTexture->GetTranslationU(), pTexture->GetTranslationV()));
}
}
@@ -1228,7 +1227,7 @@ void LoadMaterial(KRContext &context, FbxSurfaceMaterial *pMaterial) {
FbxTexture* pTexture = FbxCast <FbxTexture> (pProperty.GetSrcObject(FbxCriteria::ObjectType(FbxTexture::ClassId),0));
FbxFileTexture *pFileTexture = FbxCast<FbxFileTexture>(pTexture);
if(pFileTexture) {
new_material->setSpecularMap(KRResource::GetFileBase(pFileTexture->GetFileName()), KRVector2(pTexture->GetScaleU(), pTexture->GetScaleV()), KRVector2(pTexture->GetTranslationU(), pTexture->GetTranslationV()));
new_material->setSpecularMap(KRResource::GetFileBase(pFileTexture->GetFileName()), Vector2(pTexture->GetScaleU(), pTexture->GetScaleV()), Vector2(pTexture->GetTranslationU(), pTexture->GetTranslationV()));
}
}
@@ -1246,7 +1245,7 @@ void LoadMaterial(KRContext &context, FbxSurfaceMaterial *pMaterial) {
FbxTexture* pTexture = pProperty.GetSrcObject<FbxTexture>(0);
FbxFileTexture *pFileTexture = FbxCast<FbxFileTexture>(pTexture);
if(pFileTexture) {
new_material->setNormalMap(KRResource::GetFileBase(pFileTexture->GetFileName()), KRVector2(pTexture->GetScaleU(), pTexture->GetScaleV()), KRVector2(pTexture->GetTranslationU(), pTexture->GetTranslationV()));
new_material->setNormalMap(KRResource::GetFileBase(pFileTexture->GetFileName()), Vector2(pTexture->GetScaleU(), pTexture->GetScaleV()), Vector2(pTexture->GetTranslationU(), pTexture->GetTranslationV()));
}
}
@@ -1301,16 +1300,16 @@ void LoadMesh(KRContext &context, FbxScene* pFbxScene, FbxGeometryConverter *pGe
/*
FbxMatrix fbx_bind_pose_matrix;
KRMat4 bind_pose;
Matrix4 bind_pose;
PoseList pose_list;
FbxArray<int> pose_indices;
if(FbxPose::GetBindPoseContaining(pFbxScene, cluster->GetLink(), pose_list, pose_indices)) {
fbx_bind_pose_matrix = (*pose_list)[0].GetMatrix(pose_indices[0]);
bind_pose = KRMat4(
KRVector3(fbx_bind_pose_matrix.GetColumn(0).mData),
KRVector3(fbx_bind_pose_matrix.GetColumn(1).mData),
KRVector3(fbx_bind_pose_matrix.GetColumn(2).mData),
KRVector3(fbx_bind_pose_matrix.GetColumn(3).mData)
bind_pose = Matrix4(
Vector3(fbx_bind_pose_matrix.GetColumn(0).mData),
Vector3(fbx_bind_pose_matrix.GetColumn(1).mData),
Vector3(fbx_bind_pose_matrix.GetColumn(2).mData),
Vector3(fbx_bind_pose_matrix.GetColumn(3).mData)
);
fprintf(stderr, "Found bind pose(s)!\n");
}
@@ -1318,11 +1317,11 @@ void LoadMesh(KRContext &context, FbxScene* pFbxScene, FbxGeometryConverter *pGe
FbxAMatrix link_matrix;
cluster->GetTransformLinkMatrix(link_matrix);
mi.bone_bind_poses.push_back(KRMat4(
KRVector3(link_matrix.GetColumn(0).mData),
KRVector3(link_matrix.GetColumn(1).mData),
KRVector3(link_matrix.GetColumn(2).mData),
KRVector3(link_matrix.GetColumn(3).mData)
mi.bone_bind_poses.push_back(Matrix4(
Vector3(link_matrix.GetColumn(0).mData),
Vector3(link_matrix.GetColumn(1).mData),
Vector3(link_matrix.GetColumn(2).mData),
Vector3(link_matrix.GetColumn(3).mData)
));
int cluster_control_point_count = cluster->GetControlPointIndicesCount();
@@ -1382,11 +1381,11 @@ void LoadMesh(KRContext &context, FbxScene* pFbxScene, FbxGeometryConverter *pGe
// std::vector<std::vector<float> > bone_weights;
// std::vector<std::vector<int> > bone_indexes;
//
// std::vector<KRVector3> vertices;
// std::vector<KRVector2> uva;
// std::vector<KRVector2> uvb;
// std::vector<KRVector3> normals;
// std::vector<KRVector3> tangents;
// std::vector<Vector3> vertices;
// std::vector<Vector2> uva;
// std::vector<Vector2> uvb;
// std::vector<Vector3> normals;
// std::vector<Vector3> tangents;
// std::vector<int> submesh_lengths;
// std::vector<int> submesh_starts;
// std::vector<std::string> material_names;
@@ -1435,7 +1434,7 @@ void LoadMesh(KRContext &context, FbxScene* pFbxScene, FbxGeometryConverter *pGe
// ----====---- Read Vertex Position ----====----
int lControlPointIndex = pMesh->GetPolygonVertex(iPolygon, iVertex);
FbxVector4 v = control_points[lControlPointIndex];
mi.vertices.push_back(KRVector3(v[0], v[1], v[2]));
mi.vertices.push_back(Vector3(v[0], v[1], v[2]));
if(mi.bone_names.size() > 0) {
control_point_weight_info_t &weight_info = control_point_weights[lControlPointIndex];
@@ -1449,8 +1448,8 @@ void LoadMesh(KRContext &context, FbxScene* pFbxScene, FbxGeometryConverter *pGe
mi.bone_weights.push_back(vertex_bone_weights);
}
KRVector2 new_uva = KRVector2(0.0, 0.0);
KRVector2 new_uvb = KRVector2(0.0, 0.0);
Vector2 new_uva = Vector2(0.0, 0.0);
Vector2 new_uvb = Vector2(0.0, 0.0);
// ----====---- Read UVs ----====----
@@ -1463,7 +1462,7 @@ void LoadMesh(KRContext &context, FbxScene* pFbxScene, FbxGeometryConverter *pGe
bool unmapped = false;
if(pMesh->GetPolygonVertexUV(iPolygon, iVertex, setName, uv, unmapped)) {
if(!unmapped) {
new_uva = KRVector2(uv[0], uv[1]);
new_uva = Vector2(uv[0], uv[1]);
}
}
mi.uva.push_back(new_uva);
@@ -1475,7 +1474,7 @@ void LoadMesh(KRContext &context, FbxScene* pFbxScene, FbxGeometryConverter *pGe
bool unmapped = false;
if(pMesh->GetPolygonVertexUV(iPolygon, iVertex, setName, uv, unmapped)) {
if(!unmapped) {
new_uvb = KRVector2(uv[0], uv[1]);
new_uvb = Vector2(uv[0], uv[1]);
}
}
mi.uvb.push_back(new_uvb);
@@ -1485,7 +1484,7 @@ void LoadMesh(KRContext &context, FbxScene* pFbxScene, FbxGeometryConverter *pGe
FbxVector4 new_normal;
if(pMesh->GetPolygonVertexNormal(iPolygon, iVertex, new_normal)) {
mi.normals.push_back(KRVector3(new_normal[0], new_normal[1], new_normal[2]));
mi.normals.push_back(Vector3(new_normal[0], new_normal[1], new_normal[2]));
}
/*
@@ -1514,7 +1513,7 @@ void LoadMesh(KRContext &context, FbxScene* pFbxScene, FbxGeometryConverter *pGe
}
}
if(l == 0) {
mi.tangents.push_back(KRVector3(new_tangent[0], new_tangent[1], new_tangent[2]));
mi.tangents.push_back(Vector3(new_tangent[0], new_tangent[1], new_tangent[2]));
}
}
@@ -1716,7 +1715,7 @@ KRNode *LoadLight(KRNode *parent_node, FbxNode* pNode) {
}
if(new_light) {
new_light->setColor(KRVector3(light_color[0], light_color[1], light_color[2]));
new_light->setColor(Vector3(light_color[0], light_color[1], light_color[2]));
new_light->setIntensity(light_intensity);
new_light->setDecayStart(light_decaystart);
}

View File

@@ -101,9 +101,9 @@ std::vector<KRResource *> KRResource::LoadObj(KRContext &context, const std::str
int *pFaces = (int *)malloc(sizeof(int) * (cFaces + 1));
assert(pFaces != NULL);
std::vector<KRVector3> indexed_vertices;
std::vector<KRVector2> indexed_uva;
std::vector<KRVector3> indexed_normals;
std::vector<Vector3> indexed_vertices;
std::vector<Vector2> indexed_uva;
std::vector<Vector3> indexed_normals;
int *pFace = pFaces;
int *pMaterialFaces = pFace++;
@@ -154,7 +154,7 @@ std::vector<KRResource *> KRResource::LoadObj(KRContext &context, const std::str
y = strtof(pChar, &pChar);
pChar = szSymbol[3];
z = strtof(pChar, &pChar);
indexed_vertices.push_back(KRVector3(x,y,z));
indexed_vertices.push_back(Vector3(x,y,z));
} else if(strcmp(szSymbol[0], "vt") == 0) {
// Vertex Texture UV Coordinate (vt)
char *pChar = szSymbol[1];
@@ -163,7 +163,7 @@ std::vector<KRResource *> KRResource::LoadObj(KRContext &context, const std::str
u = strtof(pChar, &pChar);
pChar = szSymbol[2];
v = strtof(pChar, &pChar);
indexed_uva.push_back(KRVector2(u,v));
indexed_uva.push_back(Vector2(u,v));
} else if(strcmp(szSymbol[0], "vn") == 0) {
// Vertex Normal (vn)
float x,y,z;
@@ -173,7 +173,7 @@ std::vector<KRResource *> KRResource::LoadObj(KRContext &context, const std::str
y = strtof(pChar, &pChar);
pChar = szSymbol[3];
z = strtof(pChar, &pChar);
indexed_normals.push_back(KRVector3(x,y,z));
indexed_normals.push_back(Vector3(x,y,z));
} else if(strcmp(szSymbol[0], "f") == 0) {
// Face (f)
int cFaceVertices = cSymbols - 1;
@@ -249,12 +249,12 @@ std::vector<KRResource *> KRResource::LoadObj(KRContext &context, const std::str
int *pMaterialEndFace = pFace + *pFace++;
while(pFace < pMaterialEndFace && iVertex < cVertexData) {
int cFaceVertexes = *pFace;
KRVector3 firstFaceVertex;
KRVector3 prevFaceVertex;
KRVector3 firstFaceNormal;
KRVector3 prevFaceNormal;
KRVector2 firstFaceUva;
KRVector2 prevFaceUva;
Vector3 firstFaceVertex;
Vector3 prevFaceVertex;
Vector3 firstFaceNormal;
Vector3 prevFaceNormal;
Vector2 firstFaceUva;
Vector2 prevFaceUva;
for(int iFaceVertex=0; iFaceVertex < cFaceVertexes; iFaceVertex++) {
if(iFaceVertex > 2) {
// There have already been 3 vertices. Now we need to split the quad into a second triangle composed of the 1st, 3rd, and 4th vertices
@@ -268,14 +268,14 @@ std::vector<KRResource *> KRResource::LoadObj(KRContext &context, const std::str
mi.uva.push_back(prevFaceUva);
mi.normals.push_back(prevFaceNormal);
}
KRVector3 vertex = indexed_vertices[pFace[iFaceVertex*3+1]];
KRVector2 new_uva;
Vector3 vertex = indexed_vertices[pFace[iFaceVertex*3+1]];
Vector2 new_uva;
if(pFace[iFaceVertex*3+2] >= 0) {
new_uva = indexed_uva[pFace[iFaceVertex*3+2]];
}
KRVector3 normal;
Vector3 normal;
if(pFace[iFaceVertex*3+3] >= 0){
KRVector3 normal = indexed_normals[pFace[iFaceVertex*3+3]];
Vector3 normal = indexed_normals[pFace[iFaceVertex*3+3]];
}
mi.vertices.push_back(vertex);
@@ -321,7 +321,7 @@ std::vector<KRResource *> KRResource::LoadObj(KRContext &context, const std::str
// TODO: Bones not yet supported for OBJ
// std::vector<std::string> bone_names;
// std::vector<KRMat4> bone_bind_poses;
// std::vector<Matrix4> bone_bind_poses;
// std::vector<std::vector<int> > bone_indexes;
// std::vector<std::vector<float> > bone_weights;
//

View File

@@ -93,11 +93,11 @@ void KRReverbZone::render(KRCamera *pCamera, std::vector<KRPointLight *> &point_
bool bVisualize = pCamera->settings.debug_display == KRRenderSettings::KRENGINE_DEBUG_DISPLAY_SIREN_REVERB_ZONES;
if(renderPass == KRNode::RENDER_PASS_FORWARD_TRANSPARENT && bVisualize) {
KRMat4 sphereModelMatrix = getModelMatrix();
Matrix4 sphereModelMatrix = getModelMatrix();
KRShader *pShader = getContext().getShaderManager()->getShader("visualize_overlay", pCamera, point_lights, directional_lights, spot_lights, 0, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, renderPass);
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, sphereModelMatrix, point_lights, directional_lights, spot_lights, 0, renderPass, KRVector3::Zero(), 0.0f, KRVector4::Zero())) {
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, sphereModelMatrix, point_lights, directional_lights, spot_lights, 0, renderPass, Vector3::Zero(), 0.0f, Vector4::Zero())) {
// Enable additive blending
GLDEBUG(glEnable(GL_BLEND));
@@ -136,19 +136,19 @@ void KRReverbZone::setGradientDistance(float gradient_distance)
m_gradient_distance = gradient_distance;
}
KRAABB KRReverbZone::getBounds() {
AABB KRReverbZone::getBounds() {
// Reverb zones always have a -1, -1, -1 to 1, 1, 1 bounding box
return KRAABB(-KRVector3::One(), KRVector3::One(), getModelMatrix());
return AABB(-Vector3::One(), Vector3::One(), getModelMatrix());
}
float KRReverbZone::getContainment(const KRVector3 &pos)
float KRReverbZone::getContainment(const Vector3 &pos)
{
KRAABB bounds = getBounds();
AABB bounds = getBounds();
if(bounds.contains(pos)) {
KRVector3 size = bounds.size();
KRVector3 diff = pos - bounds.center();
Vector3 size = bounds.size();
Vector3 diff = pos - bounds.center();
diff = diff * 2.0f;
diff = KRVector3(diff.x / size.x, diff.y / size.y, diff.z / size.z);
diff = Vector3(diff.x / size.x, diff.y / size.y, diff.z / size.z);
float d = diff.magnitude();
if(m_gradient_distance <= 0.0f) {

View File

@@ -35,9 +35,9 @@ public:
float getReverbGain();
void setReverbGain(float reverb_gain);
virtual KRAABB getBounds();
virtual AABB getBounds();
float getContainment(const KRVector3 &pos);
float getContainment(const Vector3 &pos);
private:
std::string m_zone;

View File

@@ -30,8 +30,6 @@
//
#include "KREngine-common.h"
#include "KRVector3.h"
#include "KRMat4.h"
#include "KRLight.h"
@@ -41,7 +39,6 @@
#include "KRDirectionalLight.h"
#include "KRSpotLight.h"
#include "KRPointLight.h"
#include "KRQuaternion.h"
#include "KRAudioManager.h"
const long KRENGINE_OCCLUSION_TEST_EXPIRY = 10;
@@ -100,18 +97,18 @@ std::set<KRLight *> &KRScene::getLights()
return m_lights;
}
void KRScene::render(KRCamera *pCamera, unordered_map<KRAABB, int> &visibleBounds, const KRViewport &viewport, KRNode::RenderPass renderPass, bool new_frame) {
void KRScene::render(KRCamera *pCamera, unordered_map<AABB, int> &visibleBounds, const KRViewport &viewport, KRNode::RenderPass renderPass, bool new_frame) {
if(new_frame) {
// Expire cached occlusion test results.
// Cached "failed" results are expired on the next frame (marked with .second of -1)
// Cached "success" results are expired after KRENGINE_OCCLUSION_TEST_EXPIRY frames (marked with .second of the last frame
std::set<KRAABB> expired_visible_bounds;
for(unordered_map<KRAABB, int>::iterator visible_bounds_itr = visibleBounds.begin(); visible_bounds_itr != visibleBounds.end(); visible_bounds_itr++) {
std::set<AABB> expired_visible_bounds;
for(unordered_map<AABB, int>::iterator visible_bounds_itr = visibleBounds.begin(); visible_bounds_itr != visibleBounds.end(); visible_bounds_itr++) {
if((*visible_bounds_itr).second == -1 || (*visible_bounds_itr).second + KRENGINE_OCCLUSION_TEST_EXPIRY < getContext().getCurrentFrame()) {
expired_visible_bounds.insert((*visible_bounds_itr).first);
}
}
for(std::set<KRAABB>::iterator expired_visible_bounds_itr = expired_visible_bounds.begin(); expired_visible_bounds_itr != expired_visible_bounds.end(); expired_visible_bounds_itr++) {
for(std::set<AABB>::iterator expired_visible_bounds_itr = expired_visible_bounds.begin(); expired_visible_bounds_itr != expired_visible_bounds.end(); expired_visible_bounds_itr++) {
visibleBounds.erase(*expired_visible_bounds_itr);
}
}
@@ -178,11 +175,11 @@ void KRScene::render(KRCamera *pCamera, unordered_map<KRAABB, int> &visibleBound
}
}
void KRScene::render(KROctreeNode *pOctreeNode, unordered_map<KRAABB, int> &visibleBounds, KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, KRNode::RenderPass renderPass, std::vector<KROctreeNode *> &remainingOctrees, std::vector<KROctreeNode *> &remainingOctreesTestResults, std::vector<KROctreeNode *> &remainingOctreesTestResultsOnly, bool bOcclusionResultsPass, bool bOcclusionTestResultsOnly)
void KRScene::render(KROctreeNode *pOctreeNode, unordered_map<AABB, int> &visibleBounds, KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, KRNode::RenderPass renderPass, std::vector<KROctreeNode *> &remainingOctrees, std::vector<KROctreeNode *> &remainingOctreesTestResults, std::vector<KROctreeNode *> &remainingOctreesTestResultsOnly, bool bOcclusionResultsPass, bool bOcclusionTestResultsOnly)
{
if(pOctreeNode) {
KRAABB octreeBounds = pOctreeNode->getBounds();
AABB octreeBounds = pOctreeNode->getBounds();
if(bOcclusionResultsPass) {
// ----====---- Occlusion results pass ----====----
@@ -211,7 +208,7 @@ void KRScene::render(KROctreeNode *pOctreeNode, unordered_map<KRAABB, int> &visi
bool in_viewport = false;
if(renderPass == KRNode::RENDER_PASS_PRESTREAM) {
// When pre-streaming, objects are streamed in behind and in-front of the camera
KRAABB viewportExtents = KRAABB(viewport.getCameraPosition() - KRVector3(pCamera->settings.getPerspectiveFarZ()), viewport.getCameraPosition() + KRVector3(pCamera->settings.getPerspectiveFarZ()));
AABB viewportExtents = AABB(viewport.getCameraPosition() - Vector3(pCamera->settings.getPerspectiveFarZ()), viewport.getCameraPosition() + Vector3(pCamera->settings.getPerspectiveFarZ()));
in_viewport = octreeBounds.intersects(viewportExtents);
} else {
in_viewport = viewport.visible(pOctreeNode->getBounds());
@@ -230,7 +227,7 @@ void KRScene::render(KROctreeNode *pOctreeNode, unordered_map<KRAABB, int> &visi
if(!bVisible) {
// Assume bounding boxes are visible without occlusion test queries if the camera is inside the box.
// The near clipping plane of the camera is taken into consideration by expanding the match area
KRAABB cameraExtents = KRAABB(viewport.getCameraPosition() - KRVector3(pCamera->settings.getPerspectiveNearZ()), viewport.getCameraPosition() + KRVector3(pCamera->settings.getPerspectiveNearZ()));
AABB cameraExtents = AABB(viewport.getCameraPosition() - Vector3(pCamera->settings.getPerspectiveNearZ()), viewport.getCameraPosition() + Vector3(pCamera->settings.getPerspectiveNearZ()));
bVisible = octreeBounds.intersects(cameraExtents);
if(bVisible) {
// Record the frame number in which the camera was within the bounds
@@ -243,7 +240,7 @@ void KRScene::render(KROctreeNode *pOctreeNode, unordered_map<KRAABB, int> &visi
if(!bVisible) {
// Check if a previous occlusion query has returned true, taking advantage of temporal consistency of visible elements from frame to frame
// If the previous frame rendered this octree, then attempt to render it in this frame without performing a pre-occlusion test
unordered_map<KRAABB, int>::iterator match_itr = visibleBounds.find(octreeBounds);
unordered_map<AABB, int>::iterator match_itr = visibleBounds.find(octreeBounds);
if(match_itr != visibleBounds.end()) {
if((*match_itr).second == -1) {
// We have already tested these bounds with a negative result
@@ -277,10 +274,10 @@ void KRScene::render(KROctreeNode *pOctreeNode, unordered_map<KRAABB, int> &visi
KRMat4 matModel = KRMat4();
Matrix4 matModel = Matrix4();
matModel.scale(octreeBounds.size() * 0.5f);
matModel.translate(octreeBounds.center());
KRMat4 mvpmatrix = matModel * viewport.getViewProjectionMatrix();
Matrix4 mvpmatrix = matModel * viewport.getViewProjectionMatrix();
getContext().getMeshManager()->bindVBO(&getContext().getMeshManager()->KRENGINE_VBO_DATA_3D_CUBE_VERTICES, 1.0f);
@@ -301,7 +298,7 @@ void KRScene::render(KROctreeNode *pOctreeNode, unordered_map<KRAABB, int> &visi
GLDEBUG(glDepthMask(GL_FALSE));
}
if(getContext().getShaderManager()->selectShader("occlusion_test", *pCamera, point_lights, directional_lights, spot_lights, 0, viewport, matModel, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, KRNode::RENDER_PASS_FORWARD_TRANSPARENT, KRVector3::Zero(), 0.0f, KRVector4::Zero())) {
if(getContext().getShaderManager()->selectShader("occlusion_test", *pCamera, point_lights, directional_lights, spot_lights, 0, viewport, matModel, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, KRNode::RENDER_PASS_FORWARD_TRANSPARENT, Vector3::Zero(), 0.0f, Vector4::Zero())) {
GLDEBUG(glDrawArrays(GL_TRIANGLE_STRIP, 0, 14));
m_pContext->getMeshManager()->log_draw_call(renderPass, "octree", "occlusion_test", 14);
}
@@ -568,31 +565,31 @@ void KRScene::addDefaultLights()
{
KRDirectionalLight *light1 = new KRDirectionalLight(*this, "default_light1");
light1->setLocalRotation((KRQuaternion(KRVector3(0.0, M_PI * 0.10, 0.0)) * KRQuaternion(KRVector3(0.0, 0.0, -M_PI * 0.15))).eulerXYZ());
light1->setLocalRotation((Quaternion(Vector3(0.0, M_PI * 0.10, 0.0)) * Quaternion(Vector3(0.0, 0.0, -M_PI * 0.15))).eulerXYZ());
m_pRootNode->addChild(light1);
}
KRAABB KRScene::getRootOctreeBounds()
AABB KRScene::getRootOctreeBounds()
{
if(m_nodeTree.getRootNode()) {
return m_nodeTree.getRootNode()->getBounds();
} else {
return KRAABB(-KRVector3::One(), KRVector3::One());
return AABB(-Vector3::One(), Vector3::One());
}
}
bool KRScene::lineCast(const KRVector3 &v0, const KRVector3 &v1, KRHitInfo &hitinfo, unsigned int layer_mask)
bool KRScene::lineCast(const Vector3 &v0, const Vector3 &v1, KRHitInfo &hitinfo, unsigned int layer_mask)
{
return m_nodeTree.lineCast(v0, v1, hitinfo, layer_mask);
}
bool KRScene::rayCast(const KRVector3 &v0, const KRVector3 &dir, KRHitInfo &hitinfo, unsigned int layer_mask)
bool KRScene::rayCast(const Vector3 &v0, const Vector3 &dir, KRHitInfo &hitinfo, unsigned int layer_mask)
{
return m_nodeTree.rayCast(v0, dir, hitinfo, layer_mask);
}
bool KRScene::sphereCast(const KRVector3 &v0, const KRVector3 &v1, float radius, KRHitInfo &hitinfo, unsigned int layer_mask)
bool KRScene::sphereCast(const Vector3 &v0, const Vector3 &v1, float radius, KRHitInfo &hitinfo, unsigned int layer_mask)
{
return m_nodeTree.sphereCast(v0, v1, radius, hitinfo, layer_mask);
}

View File

@@ -3,17 +3,17 @@
// KREngine
//
// Copyright 2012 Kearwood Gilbert. All rights reserved.
//
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
//
// THIS SOFTWARE IS PROVIDED BY KEARWOOD GILBERT ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KEARWOOD GILBERT OR
@@ -23,7 +23,7 @@
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Kearwood Gilbert.
@@ -35,7 +35,6 @@
#include "KREngine-common.h"
#include "KRModel.h"
#include "KRMat4.h"
#include "KRMesh.h"
#include "KRCamera.h"
#include "KRMeshManager.h"
@@ -53,71 +52,71 @@ class KRScene : public KRResource {
public:
KRScene(KRContext &context, std::string name);
virtual ~KRScene();
virtual std::string getExtension();
virtual bool save(KRDataBlock &data);
static KRScene *Load(KRContext &context, const std::string &name, KRDataBlock *data);
KRNode *getRootNode();
KRLight *getFirstLight();
kraken_stream_level getStreamLevel();
bool lineCast(const KRVector3 &v0, const KRVector3 &v1, KRHitInfo &hitinfo, unsigned int layer_mask);
bool rayCast(const KRVector3 &v0, const KRVector3 &dir, KRHitInfo &hitinfo, unsigned int layer_mask);
bool sphereCast(const KRVector3 &v0, const KRVector3 &v1, float radius, KRHitInfo &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);
void renderFrame(GLint defaultFBO, float deltaTime, int width, int height);
void render(KRCamera *pCamera, unordered_map<KRAABB, int> &visibleBounds, const KRViewport &viewport, KRNode::RenderPass renderPass, bool new_frame);
void render(KROctreeNode *pOctreeNode, unordered_map<KRAABB, int> &visibleBounds, KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, KRNode::RenderPass renderPass, std::vector<KROctreeNode *> &remainingOctrees, std::vector<KROctreeNode *> &remainingOctreesTestResults, std::vector<KROctreeNode *> &remainingOctreesTestResultsOnly, bool bOcclusionResultsPass, bool bOcclusionTestResultsOnly);
void render(KRCamera *pCamera, unordered_map<AABB, int> &visibleBounds, const KRViewport &viewport, KRNode::RenderPass renderPass, bool new_frame);
void render(KROctreeNode *pOctreeNode, unordered_map<AABB, int> &visibleBounds, KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, KRNode::RenderPass renderPass, std::vector<KROctreeNode *> &remainingOctrees, std::vector<KROctreeNode *> &remainingOctreesTestResults, std::vector<KROctreeNode *> &remainingOctreesTestResultsOnly, bool bOcclusionResultsPass, bool bOcclusionTestResultsOnly);
void updateOctree(const KRViewport &viewport);
void buildOctreeForTheFirstTime();
void notify_sceneGraphCreate(KRNode *pNode);
void notify_sceneGraphDelete(KRNode *pNode);
void notify_sceneGraphModify(KRNode *pNode);
void physicsUpdate(float deltaTime);
void addDefaultLights();
KRAABB getRootOctreeBounds();
AABB getRootOctreeBounds();
std::set<KRAmbientZone *> &getAmbientZones();
std::set<KRReverbZone *> &getReverbZones();
std::set<KRLocator *> &getLocators();
std::set<KRLight *> &getLights();
private:
KRNode *m_pRootNode;
KRLight *m_pFirstLight;
std::set<KRNode *> m_newNodes;
std::set<KRNode *> m_modifiedNodes;
std::set<KRNode *> m_physicsNodes;
std::set<KRAmbientZone *> m_ambientZoneNodes;
std::set<KRReverbZone *> m_reverbZoneNodes;
std::set<KRLocator *> m_locatorNodes;
std::set<KRLight *> m_lights;
KROctree m_nodeTree;
public:
template <class T> T *find()
{
if(m_pRootNode) return m_pRootNode->find<T>();
return NULL;
}
template <class T> T *find(const std::string &name)
{
if(m_pRootNode) return m_pRootNode->find<T>(name);

View File

@@ -277,7 +277,7 @@ void KRShader::setUniform(int location, int value)
}
}
void KRShader::setUniform(int location, const KRVector2 &value)
void KRShader::setUniform(int location, const Vector2 &value)
{
if(m_uniforms[location] != -1) {
int value_index = m_uniform_value_index[location];
@@ -295,7 +295,7 @@ void KRShader::setUniform(int location, const KRVector2 &value)
}
}
}
void KRShader::setUniform(int location, const KRVector3 &value)
void KRShader::setUniform(int location, const Vector3 &value)
{
if(m_uniforms[location] != -1) {
int value_index = m_uniform_value_index[location];
@@ -313,7 +313,7 @@ void KRShader::setUniform(int location, const KRVector3 &value)
}
}
}
void KRShader::setUniform(int location, const KRVector4 &value)
void KRShader::setUniform(int location, const Vector4 &value)
{
if(m_uniforms[location] != -1) {
int value_index = m_uniform_value_index[location];
@@ -332,7 +332,7 @@ void KRShader::setUniform(int location, const KRVector4 &value)
}
}
void KRShader::setUniform(int location, const KRMat4 &value)
void KRShader::setUniform(int location, const Matrix4 &value)
{
if(m_uniforms[location] != -1) {
int value_index = m_uniform_value_index[location];
@@ -351,7 +351,7 @@ void KRShader::setUniform(int location, const KRMat4 &value)
}
}
bool KRShader::bind(KRCamera &camera, const KRViewport &viewport, const KRMat4 &matModel, const std::vector<KRPointLight *> &point_lights, const std::vector<KRDirectionalLight *> &directional_lights, const std::vector<KRSpotLight *>&spot_lights, const KRNode::RenderPass &renderPass, const KRVector3 &rim_color, float rim_power, const KRVector4 &fade_color) {
bool KRShader::bind(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, const Vector3 &rim_color, float rim_power, const Vector4 &fade_color) {
if(m_iProgram == 0) {
return false;
}
@@ -405,7 +405,7 @@ bool KRShader::bind(KRCamera &camera, const KRViewport &viewport, const KRMat4 &
m_pContext->getTextureManager()->_setWrapModeT(5, GL_CLAMP_TO_EDGE);
}
KRMat4 matBias;
Matrix4 matBias;
matBias.translate(1.0, 1.0, 1.0);
matBias.scale(0.5);
for(int iShadow=0; iShadow < cShadowBuffers; iShadow++) {
@@ -413,11 +413,11 @@ bool KRShader::bind(KRCamera &camera, const KRViewport &viewport, const KRMat4 &
}
if(m_uniforms[KRENGINE_UNIFORM_LIGHT_DIRECTION_MODEL_SPACE] != -1) {
KRMat4 inverseModelMatrix = matModel;
Matrix4 inverseModelMatrix = matModel;
inverseModelMatrix.invert();
// Bind the light direction vector
KRVector3 lightDirObject = KRMat4::Dot(inverseModelMatrix, directional_light->getWorldLightDirection());
Vector3 lightDirObject = Matrix4::Dot(inverseModelMatrix, directional_light->getWorldLightDirection());
lightDirObject.normalize();
setUniform(KRENGINE_UNIFORM_LIGHT_DIRECTION_MODEL_SPACE, lightDirObject);
}
@@ -433,38 +433,38 @@ bool KRShader::bind(KRCamera &camera, const KRViewport &viewport, const KRMat4 &
if(m_uniforms[KRENGINE_UNIFORM_CAMERAPOS_MODEL_SPACE] != -1) {
KRMat4 inverseModelMatrix = matModel;
Matrix4 inverseModelMatrix = matModel;
inverseModelMatrix.invert();
if(m_uniforms[KRENGINE_UNIFORM_CAMERAPOS_MODEL_SPACE] != -1) {
// Transform location of camera to object space for calculation of specular halfVec
KRVector3 cameraPosObject = KRMat4::Dot(inverseModelMatrix, viewport.getCameraPosition());
Vector3 cameraPosObject = Matrix4::Dot(inverseModelMatrix, viewport.getCameraPosition());
setUniform(KRENGINE_UNIFORM_CAMERAPOS_MODEL_SPACE, cameraPosObject);
}
}
if(m_uniforms[KRENGINE_UNIFORM_MVP] != -1 || m_uniforms[KRShader::KRENGINE_UNIFORM_INVMVP] != -1) {
// Bind our modelmatrix variable to be a uniform called mvpmatrix in our shaderprogram
KRMat4 mvpMatrix = matModel * viewport.getViewProjectionMatrix();
Matrix4 mvpMatrix = matModel * viewport.getViewProjectionMatrix();
setUniform(KRENGINE_UNIFORM_MVP, mvpMatrix);
if(m_uniforms[KRShader::KRENGINE_UNIFORM_INVMVP] != -1) {
setUniform(KRShader::KRENGINE_UNIFORM_INVMVP, KRMat4::Invert(mvpMatrix));
setUniform(KRShader::KRENGINE_UNIFORM_INVMVP, Matrix4::Invert(mvpMatrix));
}
}
if(m_uniforms[KRShader::KRENGINE_UNIFORM_VIEW_SPACE_MODEL_ORIGIN] != -1 || m_uniforms[KRENGINE_UNIFORM_MODEL_VIEW_INVERSE_TRANSPOSE] != -1 || m_uniforms[KRShader::KRENGINE_UNIFORM_MODEL_VIEW] != -1) {
KRMat4 matModelView = matModel * viewport.getViewMatrix();
Matrix4 matModelView = matModel * viewport.getViewMatrix();
setUniform(KRENGINE_UNIFORM_MODEL_VIEW, matModelView);
if(m_uniforms[KRShader::KRENGINE_UNIFORM_VIEW_SPACE_MODEL_ORIGIN] != -1) {
KRVector3 view_space_model_origin = KRMat4::Dot(matModelView, KRVector3::Zero()); // Origin point of model space is the light source position. No perspective, so no w divide required
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(KRENGINE_UNIFORM_VIEW_SPACE_MODEL_ORIGIN, view_space_model_origin);
}
if(m_uniforms[KRENGINE_UNIFORM_MODEL_VIEW_INVERSE_TRANSPOSE] != -1) {
KRMat4 matModelViewInverseTranspose = matModelView;
Matrix4 matModelViewInverseTranspose = matModelView;
matModelViewInverseTranspose.transpose();
matModelViewInverseTranspose.invert();
setUniform(KRENGINE_UNIFORM_MODEL_VIEW_INVERSE_TRANSPOSE, matModelViewInverseTranspose);
@@ -472,7 +472,7 @@ bool KRShader::bind(KRCamera &camera, const KRViewport &viewport, const KRMat4 &
}
if(m_uniforms[KRENGINE_UNIFORM_MODEL_INVERSE_TRANSPOSE] != -1) {
KRMat4 matModelInverseTranspose = matModel;
Matrix4 matModelInverseTranspose = matModel;
matModelInverseTranspose.transpose();
matModelInverseTranspose.invert();
setUniform(KRENGINE_UNIFORM_MODEL_INVERSE_TRANSPOSE, matModelInverseTranspose);
@@ -483,7 +483,7 @@ bool KRShader::bind(KRCamera &camera, const KRViewport &viewport, const KRMat4 &
}
if(m_uniforms[KRShader::KRENGINE_UNIFORM_INVMVP_NO_TRANSLATE] != -1) {
KRMat4 matInvMVPNoTranslate = matModel * viewport.getViewMatrix();;
Matrix4 matInvMVPNoTranslate = matModel * viewport.getViewMatrix();;
// Remove the translation
matInvMVPNoTranslate.getPointer()[3] = 0;
matInvMVPNoTranslate.getPointer()[7] = 0;
@@ -503,7 +503,7 @@ bool KRShader::bind(KRCamera &camera, const KRViewport &viewport, const KRMat4 &
}
if(m_uniforms[KRENGINE_UNIFORM_VIEWPORT] != -1) {
setUniform(KRENGINE_UNIFORM_VIEWPORT, KRVector4(
setUniform(KRENGINE_UNIFORM_VIEWPORT, Vector4(
(GLfloat)0.0,
(GLfloat)0.0,
(GLfloat)viewport.getSize().x,

View File

@@ -36,7 +36,6 @@
#include "KREngine-common.h"
#include "KRShader.h"
#include "KRMat4.h"
#include "KRCamera.h"
#include "KRNode.h"
#include "KRViewport.h"
@@ -47,7 +46,7 @@ public:
virtual ~KRShader();
const char *getKey() const;
bool bind(KRCamera &camera, const KRViewport &viewport, const KRMat4 &matModel, const std::vector<KRPointLight *> &point_lights, const std::vector<KRDirectionalLight *> &directional_lights, const std::vector<KRSpotLight *>&spot_lights, const KRNode::RenderPass &renderPass, const KRVector3 &rim_color, float rim_power, const KRVector4 &fade_color);
bool bind(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, const Vector3 &rim_color, float rim_power, const Vector4 &fade_color);
enum {
KRENGINE_UNIFORM_MATERIAL_AMBIENT = 0,
@@ -140,20 +139,20 @@ public:
std::vector<float> m_uniform_value_float;
std::vector<int> m_uniform_value_int;
std::vector<KRVector2> m_uniform_value_vector2;
std::vector<KRVector3> m_uniform_value_vector3;
std::vector<KRVector4> m_uniform_value_vector4;
std::vector<KRMat4> m_uniform_value_mat4;
std::vector<Vector2> m_uniform_value_vector2;
std::vector<Vector3> m_uniform_value_vector3;
std::vector<Vector4> m_uniform_value_vector4;
std::vector<Matrix4> m_uniform_value_mat4;
char m_szKey[256];
void setUniform(int location, float value);
void setUniform(int location, int value);
void setUniform(int location, const KRVector2 &value);
void setUniform(int location, const KRVector3 &value);
void setUniform(int location, const KRVector4 &value);
void setUniform(int location, const KRMat4 &value);
void setUniform(int location, const Vector2 &value);
void setUniform(int location, const Vector3 &value);
void setUniform(int location, const Vector4 &value);
void setUniform(int location, const Matrix4 &value);
private:
GLuint m_iProgram;

View File

@@ -233,7 +233,7 @@ KRShader *KRShaderManager::getShader(const std::string &shader_name, KRCamera *p
KRContext::Log(KRContext::LOG_LEVEL_ERROR, "Fragment Shader Missing: %s", platform_shader_name.c_str());
}
KRVector4 fade_color = pCamera->getFadeColor();
Vector4 fade_color = pCamera->getFadeColor();
char szKey[256];
sprintf(szKey, "%i_%i_%i_%i_%i_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%d_%i_%s_%i_%d_%d_%f_%f_%f_%f_%f_%f_%f_%f_%f_%f_%f", light_directional_count, light_point_count, light_spot_count, bone_count, pCamera->settings.fog_type, pCamera->settings.bEnablePerPixel,bAlphaTest, bAlphaBlend, bDiffuseMap, bNormalMap, bSpecMap, bReflectionMap, bReflectionCubeMap, pCamera->settings.bDebugPSSM, iShadowQuality, pCamera->settings.bEnableAmbient, pCamera->settings.bEnableDiffuse, pCamera->settings.bEnableSpecular, bLightMap, bDiffuseMapScale, bSpecMapScale, bReflectionMapScale, bNormalMapScale, bDiffuseMapOffset, bSpecMapOffset, bReflectionMapOffset, bNormalMapOffset,pCamera->settings.volumetric_environment_enable && pCamera->settings.volumetric_environment_downsample != 0, renderPass, shader_name.c_str(),pCamera->settings.dof_quality,pCamera->settings.bEnableFlash,pCamera->settings.bEnableVignette,pCamera->settings.dof_depth,pCamera->settings.dof_falloff,pCamera->settings.flash_depth,pCamera->settings.flash_falloff,pCamera->settings.flash_intensity,pCamera->settings.vignette_radius,pCamera->settings.vignette_falloff, fade_color.x, fade_color.y, fade_color.z, fade_color.w);
@@ -245,13 +245,13 @@ KRShader *KRShaderManager::getShader(const std::string &shader_name, KRCamera *p
return pShader;
}
bool KRShaderManager::selectShader(const std::string &shader_name, KRCamera &camera, const std::vector<KRPointLight *> &point_lights, const std::vector<KRDirectionalLight *> &directional_lights, const std::vector<KRSpotLight *>&spot_lights, int bone_count, const KRViewport &viewport, const KRMat4 &matModel, bool bDiffuseMap, bool bNormalMap, bool bSpecMap, bool bReflectionMap, bool bReflectionCubeMap, bool bLightMap, bool bDiffuseMapScale,bool bSpecMapScale, bool bNormalMapScale, bool bReflectionMapScale, bool bDiffuseMapOffset, bool bSpecMapOffset, bool bNormalMapOffset, bool bReflectionMapOffset, bool bAlphaTest, bool bAlphaBlend, KRNode::RenderPass renderPass, const KRVector3 &rim_color, float rim_power, const KRVector4 &fade_color)
bool KRShaderManager::selectShader(const std::string &shader_name, KRCamera &camera, const std::vector<KRPointLight *> &point_lights, const std::vector<KRDirectionalLight *> &directional_lights, const std::vector<KRSpotLight *>&spot_lights, int bone_count, const KRViewport &viewport, const Matrix4 &matModel, bool bDiffuseMap, bool bNormalMap, bool bSpecMap, bool bReflectionMap, bool bReflectionCubeMap, bool bLightMap, bool bDiffuseMapScale,bool bSpecMapScale, bool bNormalMapScale, bool bReflectionMapScale, bool bDiffuseMapOffset, bool bSpecMapOffset, bool bNormalMapOffset, bool bReflectionMapOffset, bool bAlphaTest, bool bAlphaBlend, KRNode::RenderPass renderPass, const Vector3 &rim_color, float rim_power, const Vector4 &fade_color)
{
KRShader *pShader = getShader(shader_name, &camera, point_lights, directional_lights, spot_lights, bone_count, bDiffuseMap, bNormalMap, bSpecMap, bReflectionMap, bReflectionCubeMap, bLightMap, bDiffuseMapScale, bSpecMapScale, bNormalMapScale, bReflectionMapScale, bDiffuseMapOffset, bSpecMapOffset, bNormalMapOffset, bReflectionMapOffset, bAlphaTest, bAlphaBlend, renderPass, rim_power != 0.0f);
return selectShader(camera, pShader, viewport, matModel, point_lights, directional_lights, spot_lights, bone_count, renderPass, rim_color, rim_power, fade_color);
}
bool KRShaderManager::selectShader(KRCamera &camera, KRShader *pShader, const KRViewport &viewport, const KRMat4 &matModel, const std::vector<KRPointLight *> &point_lights, const std::vector<KRDirectionalLight *> &directional_lights, const std::vector<KRSpotLight *>&spot_lights, int bone_count, const KRNode::RenderPass &renderPass, const KRVector3 &rim_color, float rim_power, const KRVector4 &fade_color)
bool KRShaderManager::selectShader(KRCamera &camera, KRShader *pShader, const KRViewport &viewport, const Matrix4 &matModel, const std::vector<KRPointLight *> &point_lights, const std::vector<KRDirectionalLight *> &directional_lights, const std::vector<KRSpotLight *>&spot_lights, int bone_count, const KRNode::RenderPass &renderPass, const Vector3 &rim_color, float rim_power, const Vector4 &fade_color)
{
if(pShader) {
return pShader->bind(camera, viewport, matModel, point_lights, directional_lights, spot_lights, renderPass, rim_color, rim_power, fade_color);

View File

@@ -60,9 +60,9 @@ public:
KRShader *getShader(const std::string &shader_name, KRCamera *pCamera, const std::vector<KRPointLight *> &point_lights, const std::vector<KRDirectionalLight *> &directional_lights, const std::vector<KRSpotLight *>&spot_lights, int bone_count, bool bDiffuseMap, bool bNormalMap, bool bSpecMap, bool bReflectionMap, bool bReflectionCubeMap, bool bLightMap, bool bDiffuseMapScale,bool bSpecMapScale, bool bNormalMapScale, bool bReflectionMapScale, bool bDiffuseMapOffset, bool bSpecMapOffset, bool bNormalMapOffset, bool bReflectionMapOffset, bool bAlphaTest, bool bAlphaBlend, KRNode::RenderPass renderPass, bool bRimColor = false);
bool selectShader(KRCamera &camera, KRShader *pShader, const KRViewport &viewport, const KRMat4 &matModel, const std::vector<KRPointLight *> &point_lights, const std::vector<KRDirectionalLight *> &directional_lights, const std::vector<KRSpotLight *>&spot_lights, int bone_count, const KRNode::RenderPass &renderPass, const KRVector3 &rim_color, float rim_power, const KRVector4 &fade_color);
bool selectShader(KRCamera &camera, KRShader *pShader, const KRViewport &viewport, const Matrix4 &matModel, const std::vector<KRPointLight *> &point_lights, const std::vector<KRDirectionalLight *> &directional_lights, const std::vector<KRSpotLight *>&spot_lights, int bone_count, const KRNode::RenderPass &renderPass, const Vector3 &rim_color, float rim_power, const Vector4 &fade_color);
bool selectShader(const std::string &shader_name, KRCamera &camera, const std::vector<KRPointLight *> &point_lights, const std::vector<KRDirectionalLight *> &directional_lights, const std::vector<KRSpotLight *>&spot_lights, int bone_count, const KRViewport &viewport, const KRMat4 &matModel, bool bDiffuseMap, bool bNormalMap, bool bSpecMap, bool bReflectionMap, bool bReflectionCubeMap, bool bLightMap, bool bDiffuseMapScale,bool bSpecMapScale, bool bNormalMapScale, bool bReflectionMapScale, bool bDiffuseMapOffset, bool bSpecMapOffset, bool bNormalMapOffset, bool bReflectionMapOffset, bool bAlphaTest, bool bAlphaBlend, KRNode::RenderPass renderPass, const KRVector3 &rim_color, float rim_power, const KRVector4 &fade_color);
bool selectShader(const std::string &shader_name, KRCamera &camera, const std::vector<KRPointLight *> &point_lights, const std::vector<KRDirectionalLight *> &directional_lights, const std::vector<KRSpotLight *>&spot_lights, int bone_count, const KRViewport &viewport, const Matrix4 &matModel, bool bDiffuseMap, bool bNormalMap, bool bSpecMap, bool bReflectionMap, bool bReflectionCubeMap, bool bLightMap, bool bDiffuseMapScale,bool bSpecMapScale, bool bNormalMapScale, bool bReflectionMapScale, bool bDiffuseMapOffset, bool bSpecMapOffset, bool bNormalMapOffset, bool bReflectionMapOffset, bool bAlphaTest, bool bAlphaBlend, KRNode::RenderPass renderPass, const Vector3 &rim_color, float rim_power, const Vector4 &fade_color);
long getShaderHandlesUsed();

View File

@@ -50,12 +50,12 @@ void KRSpotLight::setOuterAngle(float outerAngle) {
m_outerAngle = outerAngle;
}
KRAABB KRSpotLight::getBounds() {
AABB KRSpotLight::getBounds() {
float influence_radius = m_decayStart - sqrt(m_intensity * 0.01f) / sqrt(KRLIGHT_MIN_INFLUENCE);
if(influence_radius < m_flareOcclusionSize) {
influence_radius = m_flareOcclusionSize;
}
return KRAABB(KRVector3(-influence_radius), KRVector3(influence_radius), getModelMatrix());
return AABB(Vector3(-influence_radius), Vector3(influence_radius), getModelMatrix());
}

View File

@@ -19,7 +19,7 @@ public:
virtual std::string getElementName();
virtual tinyxml2::XMLElement *saveXML( tinyxml2::XMLNode *parent);
virtual void loadXML(tinyxml2::XMLElement *e);
virtual KRAABB getBounds();
virtual AABB getBounds();
float getInnerAngle();
float getOuterAngle();

View File

@@ -11,8 +11,6 @@
#include "KRSprite.h"
#include "KRNode.h"
#include "KRMat4.h"
#include "KRVector3.h"
#include "KRCamera.h"
#include "KRContext.h"
@@ -78,8 +76,8 @@ float KRSprite::getSpriteAlpha() const
return m_spriteAlpha;
}
KRAABB KRSprite::getBounds() {
return KRAABB(-KRVector3::One() * 0.5f, KRVector3::One() * 0.5f, getModelMatrix());
AABB KRSprite::getBounds() {
return AABB(-Vector3::One() * 0.5f, Vector3::One() * 0.5f, getModelMatrix());
}
@@ -130,7 +128,7 @@ void KRSprite::render(KRCamera *pCamera, std::vector<KRPointLight *> &point_ligh
// Render light sprite on transparency pass
KRShader *pShader = getContext().getShaderManager()->getShader("sprite", pCamera, point_lights, directional_lights, spot_lights, 0, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, renderPass);
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, getModelMatrix(), point_lights, directional_lights, spot_lights, 0, renderPass, KRVector3::Zero(), 0.0f, KRVector4::Zero())) {
if(getContext().getShaderManager()->selectShader(*pCamera, pShader, viewport, getModelMatrix(), point_lights, directional_lights, spot_lights, 0, renderPass, Vector3::Zero(), 0.0f, Vector4::Zero())) {
pShader->setUniform(KRShader::KRENGINE_UNIFORM_MATERIAL_ALPHA, m_spriteAlpha);
m_pContext->getTextureManager()->selectTexture(0, m_pSpriteTexture, 0.0f, KRTexture::TEXTURE_USAGE_SPRITE);
m_pContext->getMeshManager()->bindVBO(&m_pContext->getMeshManager()->KRENGINE_VBO_DATA_2D_SQUARE_VERTICES, 1.0f);

View File

@@ -28,7 +28,7 @@ public:
virtual void render(KRCamera *pCamera, std::vector<KRPointLight *> &point_lights, std::vector<KRDirectionalLight *> &directional_lights, std::vector<KRSpotLight *>&spot_lights, const KRViewport &viewport, KRNode::RenderPass renderPass);
virtual KRAABB getBounds();
virtual AABB getBounds();
protected:

View File

@@ -1,218 +0,0 @@
//
// KRVector2.cpp
// KREngine
//
// Created by Kearwood Gilbert on 12-03-22.
// Copyright (c) 2012 Kearwood Software. All rights reserved.
//
#include "KREngine-common.h"
#include "KRVector2.h"
KRVector2::KRVector2() {
x = 0.0;
y = 0.0;
}
KRVector2::KRVector2(float X, float Y) {
x = X;
y = Y;
}
KRVector2::KRVector2(float v) {
x = v;
y = v;
}
KRVector2::KRVector2(float *v) {
x = v[0];
y = v[1];
}
KRVector2::KRVector2(const KRVector2 &v) {
x = v.x;
y = v.y;
}
// KRVector2 swizzle getters
KRVector2 KRVector2::yx() const
{
return KRVector2(y,x);
}
// KRVector2 swizzle setters
void KRVector2::yx(const KRVector2 &v)
{
y = v.x;
x = v.y;
}
KRVector2 KRVector2::Min() {
return KRVector2(-std::numeric_limits<float>::max());
}
KRVector2 KRVector2::Max() {
return KRVector2(std::numeric_limits<float>::max());
}
KRVector2 KRVector2::Zero() {
return KRVector2(0.0f);
}
KRVector2 KRVector2::One() {
return KRVector2(1.0f);
}
KRVector2::~KRVector2() {
}
KRVector2& KRVector2::operator =(const KRVector2& b) {
x = b.x;
y = b.y;
return *this;
}
KRVector2 KRVector2::operator +(const KRVector2& b) const {
return KRVector2(x + b.x, y + b.y);
}
KRVector2 KRVector2::operator -(const KRVector2& b) const {
return KRVector2(x - b.x, y - b.y);
}
KRVector2 KRVector2::operator +() const {
return *this;
}
KRVector2 KRVector2::operator -() const {
return KRVector2(-x, -y);
}
KRVector2 KRVector2::operator *(const float v) const {
return KRVector2(x * v, y * v);
}
KRVector2 KRVector2::operator /(const float v) const {
float inv_v = 1.0f / v;
return KRVector2(x * inv_v, y * inv_v);
}
KRVector2& KRVector2::operator +=(const KRVector2& b) {
x += b.x;
y += b.y;
return *this;
}
KRVector2& KRVector2::operator -=(const KRVector2& b) {
x -= b.x;
y -= b.y;
return *this;
}
KRVector2& KRVector2::operator *=(const float v) {
x *= v;
y *= v;
return *this;
}
KRVector2& KRVector2::operator /=(const float v) {
float inv_v = 1.0f / v;
x *= inv_v;
y *= inv_v;
return *this;
}
bool KRVector2::operator ==(const KRVector2& b) const {
return x == b.x && y == b.y;
}
bool KRVector2::operator !=(const KRVector2& b) const {
return x != b.x || y != b.y;
}
bool KRVector2::operator >(const KRVector2& b) const
{
// Comparison operators are implemented to allow insertion into sorted containers such as std::set
if(x > b.x) {
return true;
} else if(x < b.x) {
return false;
} else if(y > b.y) {
return true;
} else {
return false;
}
}
bool KRVector2::operator <(const KRVector2& b) const
{
// Comparison operators are implemented to allow insertion into sorted containers such as std::set
if(x < b.x) {
return true;
} else if(x > b.x) {
return false;
} else if(y < b.y) {
return true;
} else {
return false;
}
}
float& KRVector2::operator[] (unsigned i) {
switch(i) {
case 0:
return x;
case 1:
default:
return y;
}
}
float KRVector2::operator[](unsigned i) const {
switch(i) {
case 0:
return x;
case 1:
default:
return y;
}
}
void KRVector2::normalize() {
float inv_magnitude = 1.0f / sqrtf(x * x + y * y);
x *= inv_magnitude;
y *= inv_magnitude;
}
float KRVector2::sqrMagnitude() const {
return x * x + y * y;
}
float KRVector2::magnitude() const {
return sqrtf(x * x + y * y);
}
KRVector2 KRVector2::Normalize(const KRVector2 &v) {
float inv_magnitude = 1.0f / sqrtf(v.x * v.x + v.y * v.y);
return KRVector2(v.x * inv_magnitude, v.y * inv_magnitude);
}
float KRVector2::Cross(const KRVector2 &v1, const KRVector2 &v2) {
return v1.x * v2.y - v1.y * v2.x;
}
float KRVector2::Dot(const KRVector2 &v1, const KRVector2 &v2) {
return v1.x * v2.x + v1.y * v2.y;
}
void KRVector2::setUniform(GLint location) const
{
if(location != -1) GLDEBUG(glUniform2f(location, x, y));
}

View File

@@ -1,118 +0,0 @@
//
// KRVector2.h
// KREngine
//
// Copyright 2012 Kearwood Gilbert. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY KEARWOOD GILBERT ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KEARWOOD GILBERT OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Kearwood Gilbert.
//
#ifndef KRVECTOR2
#define KRVECTOR2
#include "KREngine-common.h"
class KRVector2 {
public:
union {
struct {
float x, y;
};
float c[2];
};
KRVector2();
KRVector2(float X, float Y);
KRVector2(float v);
KRVector2(float *v);
KRVector2(const KRVector2 &v);
~KRVector2();
// KRVector2 swizzle getters
KRVector2 yx() const;
// KRVector2 swizzle setters
void yx(const KRVector2 &v);
KRVector2& operator =(const KRVector2& b);
KRVector2 operator +(const KRVector2& b) const;
KRVector2 operator -(const KRVector2& b) const;
KRVector2 operator +() const;
KRVector2 operator -() const;
KRVector2 operator *(const float v) const;
KRVector2 operator /(const float v) const;
KRVector2& operator +=(const KRVector2& b);
KRVector2& operator -=(const KRVector2& b);
KRVector2& operator *=(const float v);
KRVector2& operator /=(const float v);
// Comparison operators are implemented to allow insertion into sorted containers such as std::set
bool operator >(const KRVector2& b) const;
bool operator <(const KRVector2& b) const;
bool operator ==(const KRVector2& b) const;
bool operator !=(const KRVector2& b) const;
float& operator[](unsigned i);
float operator[](unsigned i) const;
float sqrMagnitude() const;
float magnitude() const;
void normalize();
static KRVector2 Normalize(const KRVector2 &v);
static float Cross(const KRVector2 &v1, const KRVector2 &v2);
static float Dot(const KRVector2 &v1, const KRVector2 &v2);
static KRVector2 Min();
static KRVector2 Max();
static KRVector2 Zero();
static KRVector2 One();
void setUniform(GLint location) const;
private:
};
namespace std {
template<>
struct hash<KRVector2> {
public:
size_t operator()(const KRVector2 &s) const
{
size_t h1 = hash<float>()(s.x);
size_t h2 = hash<float>()(s.y);
return h1 ^ ( h2 << 1 );
}
};
};
#endif

View File

@@ -1,446 +0,0 @@
//
// KRVector3.cpp
// KREngine
//
// Copyright 2012 Kearwood Gilbert. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY KEARWOOD GILBERT ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KEARWOOD GILBERT OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Kearwood Gilbert.
//
#include "KREngine-common.h"
#include "KRVector3.h"
const KRVector3 KRVECTOR3_ZERO(0.0f, 0.0f, 0.0f);
//default constructor
KRVector3::KRVector3()
{
x = 0.0f;
y = 0.0f;
z = 0.0f;
}
KRVector3::KRVector3(const KRVector3 &v) {
x = v.x;
y = v.y;
z = v.z;
}
KRVector3::KRVector3(const KRVector4 &v) {
x = v.x;
y = v.y;
z = v.z;
}
KRVector3::KRVector3(float *v) {
x = v[0];
y = v[1];
z = v[2];
}
KRVector3::KRVector3(double *v) {
x = (float)v[0];
y = (float)v[1];
z = (float)v[2];
}
KRVector2 KRVector3::xx() const
{
return KRVector2(x,x);
}
KRVector2 KRVector3::xy() const
{
return KRVector2(x,y);
}
KRVector2 KRVector3::xz() const
{
return KRVector2(x,z);
}
KRVector2 KRVector3::yx() const
{
return KRVector2(y,x);
}
KRVector2 KRVector3::yy() const
{
return KRVector2(y,y);
}
KRVector2 KRVector3::yz() const
{
return KRVector2(y,z);
}
KRVector2 KRVector3::zx() const
{
return KRVector2(z,x);
}
KRVector2 KRVector3::zy() const
{
return KRVector2(z,y);
}
KRVector2 KRVector3::zz() const
{
return KRVector2(z,z);
}
void KRVector3::xy(const KRVector2 &v)
{
x = v.x;
y = v.y;
}
void KRVector3::xz(const KRVector2 &v)
{
x = v.x;
z = v.y;
}
void KRVector3::yx(const KRVector2 &v)
{
y = v.x;
x = v.y;
}
void KRVector3::yz(const KRVector2 &v)
{
y = v.x;
z = v.y;
}
void KRVector3::zx(const KRVector2 &v)
{
z = v.x;
x = v.y;
}
void KRVector3::zy(const KRVector2 &v)
{
z = v.x;
y = v.y;
}
KRVector3 KRVector3::Min() {
return KRVector3(-std::numeric_limits<float>::max());
}
KRVector3 KRVector3::Max() {
return KRVector3(std::numeric_limits<float>::max());
}
const KRVector3 &KRVector3::Zero() {
return KRVECTOR3_ZERO;
}
KRVector3 KRVector3::One() {
return KRVector3(1.0f, 1.0f, 1.0f);
}
KRVector3 KRVector3::Forward() {
return KRVector3(0.0f, 0.0f, 1.0f);
}
KRVector3 KRVector3::Backward() {
return KRVector3(0.0f, 0.0f, -1.0f);
}
KRVector3 KRVector3::Up() {
return KRVector3(0.0f, 1.0f, 0.0f);
}
KRVector3 KRVector3::Down() {
return KRVector3(0.0f, -1.0f, 0.0f);
}
KRVector3 KRVector3::Left() {
return KRVector3(-1.0f, 0.0f, 0.0f);
}
KRVector3 KRVector3::Right() {
return KRVector3(1.0f, 0.0f, 0.0f);
}
void KRVector3::scale(const KRVector3 &v)
{
x *= v.x;
y *= v.y;
z *= v.z;
}
KRVector3 KRVector3::Scale(const KRVector3 &v1, const KRVector3 &v2)
{
return KRVector3(v1.x * v2.x, v1.y * v2.y, v1.z * v2.z);
}
KRVector3 KRVector3::Lerp(const KRVector3 &v1, const KRVector3 &v2, float d) {
return v1 + (v2 - v1) * d;
}
KRVector3 KRVector3::Slerp(const KRVector3 &v1, const KRVector3 &v2, float d) {
// From: http://keithmaggio.wordpress.com/2011/02/15/math-magician-lerp-slerp-and-nlerp/
// Dot product - the cosine of the angle between 2 vectors.
float dot = KRVector3::Dot(v1, v2);
// Clamp it to be in the range of Acos()
if(dot < -1.0f) dot = -1.0f;
if(dot > 1.0f) dot = 1.0f;
// Acos(dot) returns the angle between start and end,
// And multiplying that by percent returns the angle between
// start and the final result.
float theta = acos(dot)*d;
KRVector3 RelativeVec = v2 - v1*dot;
RelativeVec.normalize(); // Orthonormal basis
// The final result.
return ((v1*cos(theta)) + (RelativeVec*sin(theta)));
}
void KRVector3::OrthoNormalize(KRVector3 &normal, KRVector3 &tangent) {
// Gram-Schmidt Orthonormalization
normal.normalize();
KRVector3 proj = normal * Dot(tangent, normal);
tangent = tangent - proj;
tangent.normalize();
}
KRVector3::KRVector3(float v) {
x = v;
y = v;
z = v;
}
KRVector3::KRVector3(float X, float Y, float Z)
{
x = X;
y = Y;
z = Z;
}
KRVector3::~KRVector3()
{
}
KRVector3& KRVector3::operator =(const KRVector3& b) {
x = b.x;
y = b.y;
z = b.z;
return *this;
}
KRVector3& KRVector3::operator =(const KRVector4 &b) {
x = b.x;
y = b.y;
z = b.z;
return *this;
}
KRVector3 KRVector3::operator +(const KRVector3& b) const {
return KRVector3(x + b.x, y + b.y, z + b.z);
}
KRVector3 KRVector3::operator -(const KRVector3& b) const {
return KRVector3(x - b.x, y - b.y, z - b.z);
}
KRVector3 KRVector3::operator +() const {
return *this;
}
KRVector3 KRVector3::operator -() const {
return KRVector3(-x, -y, -z);
}
KRVector3 KRVector3::operator *(const float v) const {
return KRVector3(x * v, y * v, z * v);
}
KRVector3 KRVector3::operator /(const float v) const {
float inv_v = 1.0f / v;
return KRVector3(x * inv_v, y * inv_v, z * inv_v);
}
KRVector3& KRVector3::operator +=(const KRVector3& b) {
x += b.x;
y += b.y;
z += b.z;
return *this;
}
KRVector3& KRVector3::operator -=(const KRVector3& b) {
x -= b.x;
y -= b.y;
z -= b.z;
return *this;
}
KRVector3& KRVector3::operator *=(const float v) {
x *= v;
y *= v;
z *= v;
return *this;
}
KRVector3& KRVector3::operator /=(const float v) {
float inv_v = 1.0f / v;
x *= inv_v;
y *= inv_v;
z *= inv_v;
return *this;
}
bool KRVector3::operator ==(const KRVector3& b) const {
return x == b.x && y == b.y && z == b.z;
}
bool KRVector3::operator !=(const KRVector3& b) const {
return x != b.x || y != b.y || z != b.z;
}
float& KRVector3::operator[](unsigned i) {
switch(i) {
case 0:
return x;
case 1:
return y;
default:
case 2:
return z;
}
}
float KRVector3::operator[](unsigned i) const {
switch(i) {
case 0:
return x;
case 1:
return y;
case 2:
default:
return z;
}
}
float KRVector3::sqrMagnitude() const {
// calculate the square of the magnitude (useful for comparison of magnitudes without the cost of a sqrt() function)
return x * x + y * y + z * z;
}
float KRVector3::magnitude() const {
return sqrtf(x * x + y * y + z * z);
}
void KRVector3::normalize() {
float inv_magnitude = 1.0f / sqrtf(x * x + y * y + z * z);
x *= inv_magnitude;
y *= inv_magnitude;
z *= inv_magnitude;
}
KRVector3 KRVector3::Normalize(const KRVector3 &v) {
float inv_magnitude = 1.0f / sqrtf(v.x * v.x + v.y * v.y + v.z * v.z);
return KRVector3(v.x * inv_magnitude, v.y * inv_magnitude, v.z * inv_magnitude);
}
KRVector3 KRVector3::Cross(const KRVector3 &v1, const KRVector3 &v2) {
return KRVector3(v1.y * v2.z - v1.z * v2.y,
v1.z * v2.x - v1.x * v2.z,
v1.x * v2.y - v1.y * v2.x);
}
float KRVector3::Dot(const KRVector3 &v1, const KRVector3 &v2) {
return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
}
bool KRVector3::operator >(const KRVector3& b) const
{
// Comparison operators are implemented to allow insertion into sorted containers such as std::set
if(x > b.x) {
return true;
} else if(x < b.x) {
return false;
} else if(y > b.y) {
return true;
} else if(y < b.y) {
return false;
} else if(z > b.z) {
return true;
} else {
return false;
}
}
bool KRVector3::operator <(const KRVector3& b) const
{
// Comparison operators are implemented to allow insertion into sorted containers such as std::set
if(x < b.x) {
return true;
} else if(x > b.x) {
return false;
} else if(y < b.y) {
return true;
} else if(y > b.y) {
return false;
} else if(z < b.z) {
return true;
} else {
return false;
}
}
void KRVector3::setUniform(GLint location) const
{
if(location != -1) GLDEBUG(glUniform3f(location, x, y, z));
}
void KRVector3::setXMLAttribute(const std::string &base_name, tinyxml2::XMLElement *e, const KRVector3 &default_value)
{
// TODO - Increase number of digits after the decimal in floating point format (6 -> 12?)
// FINDME, TODO - This needs optimization...
if(*this != default_value) {
e->SetAttribute((base_name + "_x").c_str(), x);
e->SetAttribute((base_name + "_y").c_str(), y);
e->SetAttribute((base_name + "_z").c_str(), z);
}
}
void KRVector3::getXMLAttribute(const std::string &base_name, tinyxml2::XMLElement *e, const KRVector3 &default_value)
{
float new_x = 0.0f;
float new_y = 0.0f;
float new_z = 0.0f;
if(e->QueryFloatAttribute((base_name + "_x").c_str(), &new_x) == tinyxml2::XML_SUCCESS
&& e->QueryFloatAttribute((base_name + "_y").c_str(), &new_y) == tinyxml2::XML_SUCCESS
&& e->QueryFloatAttribute((base_name + "_z").c_str(), &new_z) == tinyxml2::XML_SUCCESS) {
x = new_x;
y = new_y;
z = new_z;
} else {
*this = default_value;
}
}

View File

@@ -1,147 +0,0 @@
//
// KRVector3.h
// KREngine
//
// Copyright 2012 Kearwood Gilbert. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY KEARWOOD GILBERT ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KEARWOOD GILBERT OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Kearwood Gilbert.
//
#ifndef KRVECTOR3
#define KRVECTOR3
#include "KREngine-common.h"
class KRVector2;
class KRVector4;
class KRVector3 {
public:
union {
struct {
float x, y, z;
};
float c[3];
};
KRVector3();
KRVector3(float X, float Y, float Z);
KRVector3(float v);
KRVector3(float *v);
KRVector3(double *v);
KRVector3(const KRVector3 &v);
KRVector3(const KRVector4 &v);
~KRVector3();
// KRVector2 swizzle getters
KRVector2 xx() const;
KRVector2 xy() const;
KRVector2 xz() const;
KRVector2 yx() const;
KRVector2 yy() const;
KRVector2 yz() const;
KRVector2 zx() const;
KRVector2 zy() const;
KRVector2 zz() const;
// KRVector2 swizzle setters
void xy(const KRVector2 &v);
void xz(const KRVector2 &v);
void yx(const KRVector2 &v);
void yz(const KRVector2 &v);
void zx(const KRVector2 &v);
void zy(const KRVector2 &v);
KRVector3& operator =(const KRVector3& b);
KRVector3& operator =(const KRVector4& b);
KRVector3 operator +(const KRVector3& b) const;
KRVector3 operator -(const KRVector3& b) const;
KRVector3 operator +() const;
KRVector3 operator -() const;
KRVector3 operator *(const float v) const;
KRVector3 operator /(const float v) const;
KRVector3& operator +=(const KRVector3& b);
KRVector3& operator -=(const KRVector3& b);
KRVector3& operator *=(const float v);
KRVector3& operator /=(const float v);
bool operator ==(const KRVector3& b) const;
bool operator !=(const KRVector3& b) const;
// Comparison operators are implemented to allow insertion into sorted containers such as std::set
bool operator >(const KRVector3& b) const;
bool operator <(const KRVector3& b) const;
float& operator[](unsigned i);
float operator[](unsigned i) const;
float sqrMagnitude() const; // calculate the square of the magnitude (useful for comparison of magnitudes without the cost of a sqrt() function)
float magnitude() const;
void scale(const KRVector3 &v);
void normalize();
static KRVector3 Normalize(const KRVector3 &v);
static KRVector3 Cross(const KRVector3 &v1, const KRVector3 &v2);
static float Dot(const KRVector3 &v1, const KRVector3 &v2);
static KRVector3 Min();
static KRVector3 Max();
static const KRVector3 &Zero();
static KRVector3 One();
static KRVector3 Forward();
static KRVector3 Backward();
static KRVector3 Up();
static KRVector3 Down();
static KRVector3 Left();
static KRVector3 Right();
static KRVector3 Scale(const KRVector3 &v1, const KRVector3 &v2);
static KRVector3 Lerp(const KRVector3 &v1, const KRVector3 &v2, float d);
static KRVector3 Slerp(const KRVector3 &v1, const KRVector3 &v2, float d);
static void OrthoNormalize(KRVector3 &normal, KRVector3 &tangent); // Gram-Schmidt Orthonormalization
void setUniform(GLint location) const;
void setXMLAttribute(const std::string &base_name, tinyxml2::XMLElement *e, const KRVector3 &default_value);
void getXMLAttribute(const std::string &base_name, tinyxml2::XMLElement *e, const KRVector3 &default_value);
};
namespace std {
template<>
struct hash<KRVector3> {
public:
size_t operator()(const KRVector3 &s) const
{
size_t h1 = hash<float>()(s.x);
size_t h2 = hash<float>()(s.y);
size_t h3 = hash<float>()(s.z);
return h1 ^ ( h2 << 1 ) ^ (h3 << 2);
}
};
};
#endif

View File

@@ -1,106 +0,0 @@
//
// KRVector4.h
// KREngine
//
// Copyright 2012 Kearwood Gilbert. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY KEARWOOD GILBERT ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KEARWOOD GILBERT OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Kearwood Gilbert.
//
#ifndef KRVECTOR4_H
#define KRVECTOR4_H
#include "KREngine-common.h"
class KRVector3;
class KRVector4 {
public:
union {
struct {
float x, y, z, w;
};
float c[4];
};
KRVector4();
KRVector4(float X, float Y, float Z, float W);
KRVector4(float v);
KRVector4(float *v);
KRVector4(const KRVector4 &v);
KRVector4(const KRVector3 &v, float W);
~KRVector4();
KRVector4& operator =(const KRVector4& b);
KRVector4 operator +(const KRVector4& b) const;
KRVector4 operator -(const KRVector4& b) const;
KRVector4 operator +() const;
KRVector4 operator -() const;
KRVector4 operator *(const float v) const;
KRVector4 operator /(const float v) const;
KRVector4& operator +=(const KRVector4& b);
KRVector4& operator -=(const KRVector4& b);
KRVector4& operator *=(const float v);
KRVector4& operator /=(const float v);
bool operator ==(const KRVector4& b) const;
bool operator !=(const KRVector4& b) const;
// Comparison operators are implemented to allow insertion into sorted containers such as std::set
bool operator >(const KRVector4& b) const;
bool operator <(const KRVector4& b) const;
float& operator[](unsigned i);
float operator[](unsigned i) const;
float sqrMagnitude() const; // calculate the square of the magnitude (useful for comparison of magnitudes without the cost of a sqrt() function)
float magnitude() const;
void normalize();
static KRVector4 Normalize(const KRVector4 &v);
static float Dot(const KRVector4 &v1, const KRVector4 &v2);
static KRVector4 Min();
static KRVector4 Max();
static const KRVector4 &Zero();
static KRVector4 One();
static KRVector4 Forward();
static KRVector4 Backward();
static KRVector4 Up();
static KRVector4 Down();
static KRVector4 Left();
static KRVector4 Right();
static KRVector4 Lerp(const KRVector4 &v1, const KRVector4 &v2, float d);
static KRVector4 Slerp(const KRVector4 &v1, const KRVector4 &v2, float d);
static void OrthoNormalize(KRVector4 &normal, KRVector4 &tangent); // Gram-Schmidt Orthonormalization
void setUniform(GLint location) const;
};
#endif

View File

@@ -8,22 +8,20 @@
#define KRENGINE_SWAP_INT(x,y) {int t;t=x;x=y;y=t;}
#include "KRVector2.h"
#include "KRMat4.h"
#include "KRViewport.h"
#include "KRLight.h"
#include "KREngine-common.h"
#include "KRViewport.h"
KRViewport::KRViewport()
{
m_size = KRVector2::One();
m_matProjection = KRMat4();
m_matView = KRMat4();
m_size = Vector2::One();
m_matProjection = Matrix4();
m_matView = Matrix4();
m_lodBias = 0.0f;
calculateDerivedValues();
}
KRViewport::KRViewport(const KRVector2 &size, const KRMat4 &matView, const KRMat4 &matProjection)
KRViewport::KRViewport(const Vector2 &size, const Matrix4 &matView, const Matrix4 &matProjection)
{
m_size = size;
m_matView = matView;
@@ -50,59 +48,59 @@ KRViewport::~KRViewport()
}
const KRVector2 &KRViewport::getSize() const
const Vector2 &KRViewport::getSize() const
{
return m_size;
}
const KRMat4 &KRViewport::getViewMatrix() const
const Matrix4 &KRViewport::getViewMatrix() const
{
return m_matView;
}
const KRMat4 &KRViewport::getProjectionMatrix() const
const Matrix4 &KRViewport::getProjectionMatrix() const
{
return m_matProjection;
}
void KRViewport::setSize(const KRVector2 &size)
void KRViewport::setSize(const Vector2 &size)
{
m_size = size;
}
void KRViewport::setViewMatrix(const KRMat4 &matView)
void KRViewport::setViewMatrix(const Matrix4 &matView)
{
m_matView = matView;
calculateDerivedValues();
}
void KRViewport::setProjectionMatrix(const KRMat4 &matProjection)
void KRViewport::setProjectionMatrix(const Matrix4 &matProjection)
{
m_matProjection = matProjection;
calculateDerivedValues();
}
const KRMat4 &KRViewport::KRViewport::getViewProjectionMatrix() const
const Matrix4 &KRViewport::KRViewport::getViewProjectionMatrix() const
{
return m_matViewProjection;
}
const KRMat4 &KRViewport::getInverseViewMatrix() const
const Matrix4 &KRViewport::getInverseViewMatrix() const
{
return m_matInverseView;
}
const KRMat4 &KRViewport::getInverseProjectionMatrix() const
const Matrix4 &KRViewport::getInverseProjectionMatrix() const
{
return m_matInverseProjection;
}
const KRVector3 &KRViewport::getCameraDirection() const
const Vector3 &KRViewport::getCameraDirection() const
{
return m_cameraDirection;
}
const KRVector3 &KRViewport::getCameraPosition() const
const Vector3 &KRViewport::getCameraPosition() const
{
return m_cameraPosition;
}
@@ -120,10 +118,10 @@ const int *KRViewport::getBackToFrontOrder() const
void KRViewport::calculateDerivedValues()
{
m_matViewProjection = m_matView * m_matProjection;
m_matInverseView = KRMat4::Invert(m_matView);
m_matInverseProjection = KRMat4::Invert(m_matProjection);
m_cameraPosition = KRMat4::Dot(m_matInverseView, KRVector3::Zero());
m_cameraDirection = KRMat4::Dot(m_matInverseView, KRVector3(0.0, 0.0, 1.0)) - KRMat4::Dot(m_matInverseView, KRVector3(0.0, 0.0, 0.0));
m_matInverseView = Matrix4::Invert(m_matView);
m_matInverseProjection = Matrix4::Invert(m_matProjection);
m_cameraPosition = Matrix4::Dot(m_matInverseView, Vector3::Zero());
m_cameraDirection = Matrix4::Dot(m_matInverseView, Vector3(0.0, 0.0, 1.0)) - Matrix4::Dot(m_matInverseView, Vector3(0.0, 0.0, 0.0));
for(int i=0; i<8; i++) {
m_frontToBackOrder[i] = i;
@@ -156,7 +154,7 @@ void KRViewport::calculateDerivedValues()
}
unordered_map<KRAABB, int> &KRViewport::getVisibleBounds()
unordered_map<AABB, int> &KRViewport::getVisibleBounds()
{
return m_visibleBounds;
}
@@ -171,15 +169,15 @@ void KRViewport::setLODBias(float lod_bias)
m_lodBias = lod_bias;
}
float KRViewport::coverage(const KRAABB &b) const
float KRViewport::coverage(const AABB &b) const
{
if(!visible(b)) {
return 0.0f; // Culled out by view frustrum
} else {
KRVector3 nearest_point = b.nearestPoint(getCameraPosition());
Vector3 nearest_point = b.nearestPoint(getCameraPosition());
float distance = (nearest_point - getCameraPosition()).magnitude();
KRVector3 v = KRMat4::DotWDiv(m_matProjection, getCameraPosition() + getCameraDirection() * distance);
Vector3 v = Matrix4::DotWDiv(m_matProjection, getCameraPosition() + getCameraDirection() * distance);
float screen_depth = distance / 1000.0f;
@@ -187,11 +185,11 @@ float KRViewport::coverage(const KRAABB &b) const
/*
KRVector2 screen_min;
KRVector2 screen_max;
Vector2 screen_min;
Vector2 screen_max;
// Loop through all corners and transform them to screen space
for(int i=0; i<8; i++) {
KRVector3 screen_pos = KRMat4::DotWDiv(m_matViewProjection, KRVector3(i & 1 ? b.min.x : b.max.x, i & 2 ? b.min.y : b.max.y, i & 4 ? b.min.z : b.max.z));
Vector3 screen_pos = Matrix4::DotWDiv(m_matViewProjection, Vector3(i & 1 ? b.min.x : b.max.x, i & 2 ? b.min.y : b.max.y, i & 4 ? b.min.z : b.max.z));
if(i==0) {
screen_min = screen_pos.xy();
screen_max = screen_pos.xy();
@@ -215,7 +213,7 @@ float KRViewport::coverage(const KRAABB &b) const
}
bool KRViewport::visible(const KRAABB &b) const
bool KRViewport::visible(const AABB &b) const
{
// test if bounding box would be within the visible range of the clip space transformed by matViewProjection
// This is used for view frustrum culling
@@ -223,12 +221,12 @@ bool KRViewport::visible(const KRAABB &b) const
int outside_count[6] = {0, 0, 0, 0, 0, 0};
for(int iCorner=0; iCorner<8; iCorner++) {
KRVector4 sourceCornerVertex = KRVector4(
Vector4 sourceCornerVertex = Vector4(
(iCorner & 1) == 0 ? b.min.x : b.max.x,
(iCorner & 2) == 0 ? b.min.y : b.max.y,
(iCorner & 4) == 0 ? b.min.z : b.max.z, 1.0f);
KRVector4 cornerVertex = KRMat4::Dot4(m_matViewProjection, sourceCornerVertex);
Vector4 cornerVertex = Matrix4::Dot4(m_matViewProjection, sourceCornerVertex);
if(cornerVertex.x < -cornerVertex.w) {
outside_count[0]++;

View File

@@ -10,65 +10,62 @@
#define KRENGINE_KRVIEWPORT_H
#include "KREngine-common.h"
#include "KRVector2.h"
#include "KRMat4.h"
#include "KRAABB.h"
class KRLight;
class KRViewport {
public:
KRViewport();
KRViewport(const KRVector2 &size, const KRMat4 &matView, const KRMat4 &matProjection);
KRViewport(const Vector2 &size, const Matrix4 &matView, const Matrix4 &matProjection);
~KRViewport();
const KRVector2 &getSize() const;
const KRMat4 &getViewMatrix() const;
const KRMat4 &getProjectionMatrix() const;
const KRMat4 &getViewProjectionMatrix() const;
const KRMat4 &getInverseViewMatrix() const;
const KRMat4 &getInverseProjectionMatrix() const;
const KRVector3 &getCameraDirection() const;
const KRVector3 &getCameraPosition() const;
const Vector2 &getSize() const;
const Matrix4 &getViewMatrix() const;
const Matrix4 &getProjectionMatrix() const;
const Matrix4 &getViewProjectionMatrix() const;
const Matrix4 &getInverseViewMatrix() const;
const Matrix4 &getInverseProjectionMatrix() const;
const Vector3 &getCameraDirection() const;
const Vector3 &getCameraPosition() const;
const int *getFrontToBackOrder() const;
const int *getBackToFrontOrder() const;
void setSize(const KRVector2 &size);
void setViewMatrix(const KRMat4 &matView);
void setProjectionMatrix(const KRMat4 &matProjection);
void setSize(const Vector2 &size);
void setViewMatrix(const Matrix4 &matView);
void setProjectionMatrix(const Matrix4 &matProjection);
float getLODBias() const;
void setLODBias(float lod_bias);
// Overload assignment operator
KRViewport& operator=(const KRViewport &v);
unordered_map<KRAABB, int> &getVisibleBounds();
unordered_map<AABB, int> &getVisibleBounds();
const std::set<KRLight *> &getVisibleLights();
void setVisibleLights(const std::set<KRLight *> visibleLights);
bool visible(const KRAABB &b) const;
float coverage(const KRAABB &b) const;
bool visible(const AABB &b) const;
float coverage(const AABB &b) const;
private:
KRVector2 m_size;
KRMat4 m_matView;
KRMat4 m_matProjection;
Vector2 m_size;
Matrix4 m_matView;
Matrix4 m_matProjection;
float m_lodBias;
// Derived values
KRMat4 m_matViewProjection;
KRMat4 m_matInverseView;
KRMat4 m_matInverseProjection;
KRVector3 m_cameraDirection;
KRVector3 m_cameraPosition;
Matrix4 m_matViewProjection;
Matrix4 m_matInverseView;
Matrix4 m_matInverseProjection;
Vector3 m_cameraDirection;
Vector3 m_cameraPosition;
int m_frontToBackOrder[8];
int m_backToFrontOrder[8];
void calculateDerivedValues();
unordered_map<KRAABB, int> m_visibleBounds; // AABB's that output fragments in the last frame
unordered_map<AABB, int> m_visibleBounds; // AABB's that output fragments in the last frame
};

92
kraken/KRAABB.cpp → kraken/aabb.cpp Executable file → Normal file
View File

@@ -6,27 +6,28 @@
// Copyright (c) 2012 Kearwood Software. All rights reserved.
//
#include "KRAABB.h"
#include "KRMat4.h"
#include "KRVector2.h"
#include "public/kraken.h"
#include "assert.h"
#include "KRHelpers.h"
KRAABB::KRAABB()
namespace kraken {
AABB::AABB()
{
min = KRVector3::Min();
max = KRVector3::Max();
min = Vector3::Min();
max = Vector3::Max();
}
KRAABB::KRAABB(const KRVector3 &minPoint, const KRVector3 &maxPoint)
AABB::AABB(const Vector3 &minPoint, const Vector3 &maxPoint)
{
min = minPoint;
max = maxPoint;
}
KRAABB::KRAABB(const KRVector3 &corner1, const KRVector3 &corner2, const KRMat4 &modelMatrix)
AABB::AABB(const Vector3 &corner1, const Vector3 &corner2, const Matrix4 &modelMatrix)
{
for(int iCorner=0; iCorner<8; iCorner++) {
KRVector3 sourceCornerVertex = KRMat4::DotWDiv(modelMatrix, KRVector3(
Vector3 sourceCornerVertex = Matrix4::DotWDiv(modelMatrix, Vector3(
(iCorner & 1) == 0 ? corner1.x : corner2.x,
(iCorner & 2) == 0 ? corner1.y : corner2.y,
(iCorner & 4) == 0 ? corner1.z : corner2.z));
@@ -46,12 +47,12 @@ KRAABB::KRAABB(const KRVector3 &corner1, const KRVector3 &corner2, const KRMat4
}
}
KRAABB::~KRAABB()
AABB::~AABB()
{
}
KRAABB& KRAABB::operator =(const KRAABB& b)
AABB& AABB::operator =(const AABB& b)
{
min = b.min;
max = b.max;
@@ -59,47 +60,47 @@ KRAABB& KRAABB::operator =(const KRAABB& b)
return *this;
}
bool KRAABB::operator ==(const KRAABB& b) const
bool AABB::operator ==(const AABB& b) const
{
return min == b.min && max == b.max;
}
bool KRAABB::operator !=(const KRAABB& b) const
bool AABB::operator !=(const AABB& b) const
{
return min != b.min || max != b.max;
}
KRVector3 KRAABB::center() const
Vector3 AABB::center() const
{
return (min + max) * 0.5f;
}
KRVector3 KRAABB::size() const
Vector3 AABB::size() const
{
return max - min;
}
float KRAABB::volume() const
float AABB::volume() const
{
KRVector3 s = size();
Vector3 s = size();
return s.x * s.y * s.z;
}
void KRAABB::scale(const KRVector3 &s)
void AABB::scale(const Vector3 &s)
{
KRVector3 prev_center = center();
KRVector3 prev_size = size();
KRVector3 new_scale = KRVector3(prev_size.x * s.x, prev_size.y * s.y, prev_size.z * s.z) * 0.5f;
Vector3 prev_center = center();
Vector3 prev_size = size();
Vector3 new_scale = Vector3(prev_size.x * s.x, prev_size.y * s.y, prev_size.z * s.z) * 0.5f;
min = prev_center - new_scale;
max = prev_center + new_scale;
}
void KRAABB::scale(float s)
void AABB::scale(float s)
{
scale(KRVector3(s));
scale(Vector3(s));
}
bool KRAABB::operator >(const KRAABB& b) const
bool AABB::operator >(const AABB& b) const
{
// Comparison operators are implemented to allow insertion into sorted containers such as std::set
if(min > b.min) {
@@ -113,7 +114,7 @@ bool KRAABB::operator >(const KRAABB& b) const
}
}
bool KRAABB::operator <(const KRAABB& b) const
bool AABB::operator <(const AABB& b) const
{
// Comparison operators are implemented to allow insertion into sorted containers such as std::set
@@ -128,34 +129,34 @@ bool KRAABB::operator <(const KRAABB& b) const
}
}
bool KRAABB::intersects(const KRAABB& b) const
bool AABB::intersects(const AABB& b) const
{
// Return true if the two volumes intersect
return min.x <= b.max.x && min.y <= b.max.y && min.z <= b.max.z && max.x >= b.min.x && max.y >= b.min.y && max.z >= b.min.z;
}
bool KRAABB::contains(const KRAABB &b) const
bool AABB::contains(const AABB &b) const
{
// Return true if the passed KRAABB is entirely contained within this KRAABB
return b.min.x >= min.x && b.min.y >= min.y && b.min.z >= min.z && b.max.x <= max.x && b.max.y <= max.y && b.max.z <= max.z;
}
bool KRAABB::contains(const KRVector3 &v) const
bool AABB::contains(const Vector3 &v) const
{
return v.x >= min.x && v.x <= max.x && v.y >= min.y && v.y <= max.y && v.z >= min.z && v.z <= max.z;
}
KRAABB KRAABB::Infinite()
AABB AABB::Infinite()
{
return KRAABB(KRVector3::Min(), KRVector3::Max());
return AABB(Vector3::Min(), Vector3::Max());
}
KRAABB KRAABB::Zero()
AABB AABB::Zero()
{
return KRAABB(KRVector3::Zero(), KRVector3::Zero());
return AABB(Vector3::Zero(), Vector3::Zero());
}
float KRAABB::longest_radius() const
float AABB::longest_radius() const
{
float radius1 = (center() - min).magnitude();
float radius2 = (max - center()).magnitude();
@@ -163,9 +164,9 @@ float KRAABB::longest_radius() const
}
bool KRAABB::intersectsLine(const KRVector3 &v1, const KRVector3 &v2) const
bool AABB::intersectsLine(const Vector3 &v1, const Vector3 &v2) const
{
KRVector3 dir = KRVector3::Normalize(v2 - v1);
Vector3 dir = Vector3::Normalize(v2 - v1);
float length = (v2 - v1).magnitude();
// EZ cases: if the ray starts inside the box, or ends inside
@@ -179,7 +180,7 @@ bool KRAABB::intersectsLine(const KRVector3 &v1, const KRVector3 &v2) const
return true ;
// the algorithm says, find 3 t's,
KRVector3 t ;
Vector3 t ;
// LARGEST t is the only one we need to test if it's on the face.
for(int i = 0 ; i < 3 ; i++) {
@@ -194,7 +195,7 @@ bool KRAABB::intersectsLine(const KRVector3 &v1, const KRVector3 &v2) const
if(t[1] > t[mi]) mi = 1;
if(t[2] > t[mi]) mi = 2;
if(t[mi] >= 0 && t[mi] <= length) {
KRVector3 pt = v1 + dir * t[mi];
Vector3 pt = v1 + dir * t[mi];
// check it's in the box in other 2 dimensions
int o1 = ( mi + 1 ) % 3 ; // i=0: o1=1, o2=2, i=1: o1=2,o2=0 etc.
@@ -206,7 +207,7 @@ bool KRAABB::intersectsLine(const KRVector3 &v1, const KRVector3 &v2) const
return false ; // the ray did not hit the box.
}
bool KRAABB::intersectsRay(const KRVector3 &v1, const KRVector3 &dir) const
bool AABB::intersectsRay(const Vector3 &v1, const Vector3 &dir) const
{
/*
Fast Ray-Box Intersection
@@ -223,8 +224,8 @@ bool KRAABB::intersectsRay(const KRVector3 &v1, const KRVector3 &dir) const
} quadrant[3];
bool inside = true;
KRVector3 maxT;
KRVector3 coord;
Vector3 maxT;
Vector3 coord;
double candidatePlane[3];
// Find candidate planes; this loop can be avoided if rays cast all from the eye(assume perpsective view)
@@ -282,7 +283,7 @@ bool KRAABB::intersectsRay(const KRVector3 &v1, const KRVector3 &dir) const
return true; /* ray hits box */
}
bool KRAABB::intersectsSphere(const KRVector3 &center, float radius) const
bool AABB::intersectsSphere(const Vector3 &center, float radius) const
{
// Arvo's Algorithm
@@ -318,7 +319,7 @@ bool KRAABB::intersectsSphere(const KRVector3 &center, float radius) const
return squaredDistance <= radius;
}
void KRAABB::encapsulate(const KRAABB & b)
void AABB::encapsulate(const AABB & b)
{
if(b.min.x < min.x) min.x = b.min.x;
if(b.min.y < min.y) min.y = b.min.y;
@@ -329,7 +330,10 @@ void KRAABB::encapsulate(const KRAABB & b)
if(b.max.z > max.z) max.z = b.max.z;
}
KRVector3 KRAABB::nearestPoint(const KRVector3 & v) const
Vector3 AABB::nearestPoint(const Vector3 & v) const
{
return KRVector3(KRCLAMP(v.x, min.x, max.x), KRCLAMP(v.y, min.y, max.y), KRCLAMP(v.z, min.z, max.z));
return Vector3(KRCLAMP(v.x, min.x, max.x), KRCLAMP(v.y, min.y, max.y), KRCLAMP(v.z, min.z, max.z));
}
} // namespace kraken

View File

@@ -1,5 +1,5 @@
//
// KRHitInfo.cpp
// HitInfo.cpp
// KREngine
//
// Copyright 2012 Kearwood Gilbert. All rights reserved.
@@ -29,18 +29,19 @@
// or implied, of Kearwood Gilbert.
//
#include "KRHitInfo.h"
#include "KRContext.h"
#include "public/kraken.h"
KRHitInfo::KRHitInfo()
namespace kraken {
HitInfo::HitInfo()
{
m_position = KRVector3::Zero();
m_normal = KRVector3::Zero();
m_position = Vector3::Zero();
m_normal = Vector3::Zero();
m_distance = 0.0f;
m_node = NULL;
}
KRHitInfo::KRHitInfo(const KRVector3 &position, const KRVector3 &normal, const float distance, KRNode *node)
HitInfo::HitInfo(const Vector3 &position, const Vector3 &normal, const float distance, KRNode *node)
{
m_position = position;
m_normal = normal;
@@ -48,7 +49,7 @@ KRHitInfo::KRHitInfo(const KRVector3 &position, const KRVector3 &normal, const f
m_node = node;
}
KRHitInfo::KRHitInfo(const KRVector3 &position, const KRVector3 &normal, const float distance)
HitInfo::HitInfo(const Vector3 &position, const Vector3 &normal, const float distance)
{
m_position = position;
m_normal = normal;
@@ -56,37 +57,37 @@ KRHitInfo::KRHitInfo(const KRVector3 &position, const KRVector3 &normal, const f
m_node = NULL;
}
KRHitInfo::~KRHitInfo()
HitInfo::~HitInfo()
{
}
bool KRHitInfo::didHit() const
bool HitInfo::didHit() const
{
return m_normal != KRVector3::Zero();
return m_normal != Vector3::Zero();
}
KRVector3 KRHitInfo::getPosition() const
Vector3 HitInfo::getPosition() const
{
return m_position;
}
KRVector3 KRHitInfo::getNormal() const
Vector3 HitInfo::getNormal() const
{
return m_normal;
}
float KRHitInfo::getDistance() const
float HitInfo::getDistance() const
{
return m_distance;
}
KRNode *KRHitInfo::getNode() const
KRNode *HitInfo::getNode() const
{
return m_node;
}
KRHitInfo& KRHitInfo::operator =(const KRHitInfo& b)
HitInfo& HitInfo::operator =(const HitInfo& b)
{
m_position = b.m_position;
m_normal = b.m_normal;
@@ -94,3 +95,6 @@ KRHitInfo& KRHitInfo::operator =(const KRHitInfo& b)
m_node = b.m_node;
return *this;
}
} // namespace kraken

141
kraken/KRMat4.cpp → kraken/matrix4.cpp Executable file → Normal file
View File

@@ -1,5 +1,5 @@
//
// KRMat4.cpp
// Matrix4.cpp
// KREngine
//
// Copyright 2012 Kearwood Gilbert. All rights reserved.
@@ -29,12 +29,12 @@
// or implied, of Kearwood Gilbert.
//
#include "KREngine-common.h"
#include "public/kraken.h"
#include <string.h>
#include "KRMat4.h"
#include "KRQuaternion.h"
namespace kraken {
KRMat4::KRMat4() {
Matrix4::Matrix4() {
// Default constructor - Initialize with an identity matrix
static const float IDENTITY_MATRIX[] = {
1.0, 0.0, 0.0, 0.0,
@@ -46,53 +46,53 @@ KRMat4::KRMat4() {
}
KRMat4::KRMat4(float *pMat) {
Matrix4::Matrix4(float *pMat) {
memcpy(c, pMat, sizeof(float) * 16);
}
KRMat4::KRMat4(const KRVector3 &axis_x, const KRVector3 &axis_y, const KRVector3 &axis_z, const KRVector3 &trans)
Matrix4::Matrix4(const Vector3 &new_axis_x, const Vector3 &new_axis_y, const Vector3 &new_axis_z, const Vector3 &new_transform)
{
c[0] = axis_x.x; c[1] = axis_x.y; c[2] = axis_x.z; c[3] = 0.0f;
c[4] = axis_y.x; c[5] = axis_y.y; c[6] = axis_y.z; c[7] = 0.0f;
c[8] = axis_z.x; c[9] = axis_z.y; c[10] = axis_z.z; c[11] = 0.0f;
c[12] = trans.x; c[13] = trans.y; c[14] = trans.z; c[15] = 1.0f;
c[0] = new_axis_x.x; c[1] = new_axis_x.y; c[2] = new_axis_x.z; c[3] = 0.0f;
c[4] = new_axis_y.x; c[5] = new_axis_y.y; c[6] = new_axis_y.z; c[7] = 0.0f;
c[8] = new_axis_z.x; c[9] = new_axis_z.y; c[10] = new_axis_z.z; c[11] = 0.0f;
c[12] = new_transform.x; c[13] = new_transform.y; c[14] = new_transform.z; c[15] = 1.0f;
}
KRMat4::~KRMat4() {
Matrix4::~Matrix4() {
}
float *KRMat4::getPointer() {
float *Matrix4::getPointer() {
return c;
}
// Copy constructor
KRMat4::KRMat4(const KRMat4 &m) {
Matrix4::Matrix4(const Matrix4 &m) {
memcpy(c, m.c, sizeof(float) * 16);
}
KRMat4& KRMat4::operator=(const KRMat4 &m) {
Matrix4& Matrix4::operator=(const Matrix4 &m) {
if(this != &m) { // Prevent self-assignment.
memcpy(c, m.c, sizeof(float) * 16);
}
return *this;
}
float& KRMat4::operator[](unsigned i) {
float& Matrix4::operator[](unsigned i) {
return c[i];
}
float KRMat4::operator[](unsigned i) const {
float Matrix4::operator[](unsigned i) const {
return c[i];
}
// Overload comparison operator
bool KRMat4::operator==(const KRMat4 &m) const {
bool Matrix4::operator==(const Matrix4 &m) const {
return memcmp(c, m.c, sizeof(float) * 16) == 0;
}
// Overload compound multiply operator
KRMat4& KRMat4::operator*=(const KRMat4 &m) {
Matrix4& Matrix4::operator*=(const Matrix4 &m) {
float temp[16];
int x,y;
@@ -113,8 +113,8 @@ KRMat4& KRMat4::operator*=(const KRMat4 &m) {
}
// Overload multiply operator
KRMat4 KRMat4::operator*(const KRMat4 &m) const {
KRMat4 ret = *this;
Matrix4 Matrix4::operator*(const Matrix4 &m) const {
Matrix4 ret = *this;
ret *= m;
return ret;
}
@@ -122,7 +122,7 @@ KRMat4 KRMat4::operator*(const KRMat4 &m) const {
/* Generate a perspective view matrix using a field of view angle fov,
* window aspect ratio, near and far clipping planes */
void KRMat4::perspective(float fov, float aspect, float nearz, float farz) {
void Matrix4::perspective(float fov, float aspect, float nearz, float farz) {
memset(c, 0, sizeof(float) * 16);
@@ -146,8 +146,8 @@ void KRMat4::perspective(float fov, float aspect, float nearz, float farz) {
}
/* Perform translation operations on a matrix */
void KRMat4::translate(float x, float y, float z) {
KRMat4 newMatrix; // Create new identity matrix
void Matrix4::translate(float x, float y, float z) {
Matrix4 newMatrix; // Create new identity matrix
newMatrix.c[12] = x;
newMatrix.c[13] = y;
@@ -156,13 +156,13 @@ void KRMat4::translate(float x, float y, float z) {
*this *= newMatrix;
}
void KRMat4::translate(const KRVector3 &v)
void Matrix4::translate(const Vector3 &v)
{
translate(v.x, v.y, v.z);
}
/* Rotate a matrix by an angle on a X, Y, or Z axis */
void KRMat4::rotate(float angle, AXIS axis) {
void Matrix4::rotate(float angle, AXIS axis) {
const int cos1[3] = { 5, 0, 0 }; // cos(angle)
const int cos2[3] = { 10, 10, 5 }; // cos(angle)
const int sin1[3] = { 9, 2, 4 }; // -sin(angle)
@@ -192,7 +192,7 @@ void KRMat4::rotate(float angle, AXIS axis) {
*/
KRMat4 newMatrix; // Create new identity matrix
Matrix4 newMatrix; // Create new identity matrix
newMatrix.c[cos1[axis]] = cos(angle);
newMatrix.c[sin1[axis]] = -sin(angle);
@@ -202,14 +202,14 @@ void KRMat4::rotate(float angle, AXIS axis) {
*this *= newMatrix;
}
void KRMat4::rotate(const KRQuaternion &q)
void Matrix4::rotate(const Quaternion &q)
{
*this *= q.rotationMatrix();
}
/* Scale matrix by separate x, y, and z amounts */
void KRMat4::scale(float x, float y, float z) {
KRMat4 newMatrix; // Create new identity matrix
void Matrix4::scale(float x, float y, float z) {
Matrix4 newMatrix; // Create new identity matrix
newMatrix.c[0] = x;
newMatrix.c[5] = y;
@@ -218,17 +218,17 @@ void KRMat4::scale(float x, float y, float z) {
*this *= newMatrix;
}
void KRMat4::scale(const KRVector3 &v) {
void Matrix4::scale(const Vector3 &v) {
scale(v.x, v.y, v.z);
}
/* Scale all dimensions equally */
void KRMat4::scale(float s) {
void Matrix4::scale(float s) {
scale(s,s,s);
}
// Initialize with a bias matrix
void KRMat4::bias() {
void Matrix4::bias() {
static const float BIAS_MATRIX[] = {
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
@@ -240,7 +240,7 @@ void KRMat4::bias() {
/* Generate an orthographic view matrix */
void KRMat4::ortho(float left, float right, float top, float bottom, float nearz, float farz) {
void Matrix4::ortho(float left, float right, float top, float bottom, float nearz, float farz) {
memset(c, 0, sizeof(float) * 16);
c[0] = 2.0f / (right - left);
c[5] = 2.0f / (bottom - top);
@@ -250,7 +250,7 @@ void KRMat4::ortho(float left, float right, float top, float bottom, float nearz
}
/* Replace matrix with its inverse */
bool KRMat4::invert() {
bool Matrix4::invert() {
// Based on gluInvertMatrix implementation
float inv[16], det;
@@ -304,7 +304,7 @@ bool KRMat4::invert() {
return true;
}
void KRMat4::transpose() {
void Matrix4::transpose() {
float trans[16];
for(int x=0; x<4; x++) {
for(int y=0; y<4; y++) {
@@ -314,19 +314,19 @@ void KRMat4::transpose() {
memcpy(c, trans, sizeof(float) * 16);
}
/* Dot Product, returning KRVector3 */
KRVector3 KRMat4::Dot(const KRMat4 &m, const KRVector3 &v) {
return KRVector3(
/* Dot Product, returning Vector3 */
Vector3 Matrix4::Dot(const Matrix4 &m, const Vector3 &v) {
return Vector3(
v.c[0] * m.c[0] + v.c[1] * m.c[4] + v.c[2] * m.c[8] + m.c[12],
v.c[0] * m.c[1] + v.c[1] * m.c[5] + v.c[2] * m.c[9] + m.c[13],
v.c[0] * m.c[2] + v.c[1] * m.c[6] + v.c[2] * m.c[10] + m.c[14]
);
}
KRVector4 KRMat4::Dot4(const KRMat4 &m, const KRVector4 &v) {
Vector4 Matrix4::Dot4(const Matrix4 &m, const Vector4 &v) {
#ifdef KRAKEN_USE_ARM_NEON
KRVector4 d;
Vector4 d;
asm volatile (
"vld1.32 {d0, d1}, [%1] \n\t" //Q0 = v
"vld1.32 {d18, d19}, [%0]! \n\t" //Q1 = m
@@ -346,7 +346,7 @@ KRVector4 KRMat4::Dot4(const KRMat4 &m, const KRVector4 &v) {
);
return d;
#else
return KRVector4(
return Vector4(
v.c[0] * m.c[0] + v.c[1] * m.c[4] + v.c[2] * m.c[8] + m.c[12],
v.c[0] * m.c[1] + v.c[1] * m.c[5] + v.c[2] * m.c[9] + m.c[13],
v.c[0] * m.c[2] + v.c[1] * m.c[6] + v.c[2] * m.c[10] + m.c[14],
@@ -356,34 +356,34 @@ KRVector4 KRMat4::Dot4(const KRMat4 &m, const KRVector4 &v) {
}
// Dot product without including translation; useful for transforming normals and tangents
KRVector3 KRMat4::DotNoTranslate(const KRMat4 &m, const KRVector3 &v)
Vector3 Matrix4::DotNoTranslate(const Matrix4 &m, const Vector3 &v)
{
return KRVector3(
return Vector3(
v.x * m.c[0] + v.y * m.c[4] + v.z * m.c[8],
v.x * m.c[1] + v.y * m.c[5] + v.z * m.c[9],
v.x * m.c[2] + v.y * m.c[6] + v.z * m.c[10]
);
}
/* Dot Product, returning w component as if it were a KRVector4 (This will be deprecated once KRVector4 is implemented instead*/
float KRMat4::DotW(const KRMat4 &m, const KRVector3 &v) {
/* Dot Product, returning w component as if it were a Vector4 (This will be deprecated once Vector4 is implemented instead*/
float Matrix4::DotW(const Matrix4 &m, const Vector3 &v) {
return v.x * m.c[0*4 + 3] + v.y * m.c[1*4 + 3] + v.z * m.c[2*4 + 3] + m.c[3*4 + 3];
}
/* Dot Product followed by W-divide */
KRVector3 KRMat4::DotWDiv(const KRMat4 &m, const KRVector3 &v) {
KRVector4 r = Dot4(m, KRVector4(v, 1.0f));
return KRVector3(r) / r.w;
Vector3 Matrix4::DotWDiv(const Matrix4 &m, const Vector3 &v) {
Vector4 r = Dot4(m, Vector4(v, 1.0f));
return Vector3(r) / r.w;
}
KRMat4 KRMat4::LookAt(const KRVector3 &cameraPos, const KRVector3 &lookAtPos, const KRVector3 &upDirection)
Matrix4 Matrix4::LookAt(const Vector3 &cameraPos, const Vector3 &lookAtPos, const Vector3 &upDirection)
{
KRMat4 matLookat;
KRVector3 lookat_z_axis = lookAtPos - cameraPos;
Matrix4 matLookat;
Vector3 lookat_z_axis = lookAtPos - cameraPos;
lookat_z_axis.normalize();
KRVector3 lookat_x_axis = KRVector3::Cross(upDirection, lookat_z_axis);
Vector3 lookat_x_axis = Vector3::Cross(upDirection, lookat_z_axis);
lookat_x_axis.normalize();
KRVector3 lookat_y_axis = KRVector3::Cross(lookat_z_axis, lookat_x_axis);
Vector3 lookat_y_axis = Vector3::Cross(lookat_z_axis, lookat_x_axis);
matLookat.getPointer()[0] = lookat_x_axis.x;
matLookat.getPointer()[1] = lookat_y_axis.x;
@@ -397,35 +397,30 @@ KRMat4 KRMat4::LookAt(const KRVector3 &cameraPos, const KRVector3 &lookAtPos, co
matLookat.getPointer()[9] = lookat_y_axis.z;
matLookat.getPointer()[10] = lookat_z_axis.z;
matLookat.getPointer()[12] = -KRVector3::Dot(lookat_x_axis, cameraPos);
matLookat.getPointer()[13] = -KRVector3::Dot(lookat_y_axis, cameraPos);
matLookat.getPointer()[14] = -KRVector3::Dot(lookat_z_axis, cameraPos);
matLookat.getPointer()[12] = -Vector3::Dot(lookat_x_axis, cameraPos);
matLookat.getPointer()[13] = -Vector3::Dot(lookat_y_axis, cameraPos);
matLookat.getPointer()[14] = -Vector3::Dot(lookat_z_axis, cameraPos);
return matLookat;
}
KRMat4 KRMat4::Invert(const KRMat4 &m)
Matrix4 Matrix4::Invert(const Matrix4 &m)
{
KRMat4 matInvert = m;
Matrix4 matInvert = m;
matInvert.invert();
return matInvert;
}
KRMat4 KRMat4::Transpose(const KRMat4 &m)
Matrix4 Matrix4::Transpose(const Matrix4 &m)
{
KRMat4 matTranspose = m;
Matrix4 matTranspose = m;
matTranspose.transpose();
return matTranspose;
}
void KRMat4::setUniform(GLint location) const
Matrix4 Matrix4::Translation(const Vector3 &v)
{
if(location != -1) GLDEBUG(glUniformMatrix4fv(location, 1, GL_FALSE, c));
}
KRMat4 KRMat4::Translation(const KRVector3 &v)
{
KRMat4 m;
Matrix4 m;
m[12] = v.x;
m[13] = v.y;
m[14] = v.z;
@@ -433,19 +428,21 @@ KRMat4 KRMat4::Translation(const KRVector3 &v)
return m;
}
KRMat4 KRMat4::Rotation(const KRVector3 &v)
Matrix4 Matrix4::Rotation(const Vector3 &v)
{
KRMat4 m;
Matrix4 m;
m.rotate(v.x, X_AXIS);
m.rotate(v.y, Y_AXIS);
m.rotate(v.z, Z_AXIS);
return m;
}
KRMat4 KRMat4::Scaling(const KRVector3 &v)
Matrix4 Matrix4::Scaling(const Vector3 &v)
{
KRMat4 m;
Matrix4 m;
m.scale(v);
return m;
}
} // namespace kraken

View File

@@ -0,0 +1,11 @@
add_public_header(kraken.h)
add_public_header(scalar.h)
add_public_header(vector2.h)
add_public_header(vector3.h)
add_public_header(vector4.h)
add_public_header(triangle3.h)
add_public_header(quaternion.h)
add_public_header(aabb.h)
add_public_header(matrix4.h)
add_public_header(hitinfo.h)
set(KRAKEN_PUBLIC_HEADERS "${KRAKEN_PUBLIC_HEADERS}" PARENT_SCOPE)

79
kraken/public/aabb.h Normal file
View File

@@ -0,0 +1,79 @@
//
// KRAABB.h
// KREngine
//
// Created by Kearwood Gilbert on 2012-08-30.
// Copyright (c) 2012 Kearwood Software. All rights reserved.
//
// Axis aligned bounding box (AABB)
#ifndef KRAKEN_AABB_H
#define KRAKEN_AABB_H
#include <functional> // for hash<>
#include "vector2.h"
#include "vector3.h"
namespace kraken {
class Matrix4;
class AABB {
public:
Vector3 min;
Vector3 max;
AABB(const Vector3 &minPoint, const Vector3 &maxPoint);
AABB(const Vector3 &corner1, const Vector3 &corner2, const Matrix4 &modelMatrix);
AABB();
~AABB();
void scale(const Vector3 &s);
void scale(float s);
Vector3 center() const;
Vector3 size() const;
float volume() const;
bool intersects(const AABB& b) const;
bool contains(const AABB &b) const;
bool contains(const Vector3 &v) const;
bool intersectsLine(const Vector3 &v1, const Vector3 &v2) const;
bool intersectsRay(const Vector3 &v1, const Vector3 &dir) const;
bool intersectsSphere(const Vector3 &center, float radius) const;
void encapsulate(const AABB & b);
AABB& operator =(const AABB& b);
bool operator ==(const AABB& b) const;
bool operator !=(const AABB& b) const;
// Comparison operators are implemented to allow insertion into sorted containers such as std::set
bool operator >(const AABB& b) const;
bool operator <(const AABB& b) const;
static AABB Infinite();
static AABB Zero();
float longest_radius() const;
Vector3 nearestPoint(const Vector3 & v) const;
};
} // namespace kraken
namespace std {
template<>
struct hash<kraken::AABB> {
public:
size_t operator()(const kraken::AABB &s) const
{
size_t h1 = hash<kraken::Vector3>()(s.min);
size_t h2 = hash<kraken::Vector3>()(s.max);
return h1 ^ ( h2 << 1 );
}
};
} // namespace std
#endif /* defined(KRAKEN_AABB_H) */

View File

@@ -29,34 +29,37 @@
// or implied, of Kearwood Gilbert.
//
#ifndef KRHITINFO_H
#define KRHITINFO_H
#ifndef KRAKEN_HITINFO_H
#define KRAKEN_HITINFO_H
#include "KRVector3.h"
#include "vector3.h"
class KRNode;
class KRHitInfo {
namespace kraken {
class HitInfo {
public:
KRHitInfo();
KRHitInfo(const KRVector3 &position, const KRVector3 &normal, const float distance);
KRHitInfo(const KRVector3 &position, const KRVector3 &normal, const float distance, KRNode *node);
~KRHitInfo();
KRVector3 getPosition() const;
KRVector3 getNormal() const;
HitInfo();
HitInfo(const Vector3 &position, const Vector3 &normal, const float distance);
HitInfo(const Vector3 &position, const Vector3 &normal, const float distance, KRNode *node);
~HitInfo();
Vector3 getPosition() const;
Vector3 getNormal() const;
float getDistance() const;
KRNode *getNode() const;
bool didHit() const;
KRHitInfo& operator =(const KRHitInfo& b);
HitInfo& operator =(const HitInfo& b);
private:
KRNode *m_node;
KRVector3 m_position;
KRVector3 m_normal;
Vector3 m_position;
Vector3 m_normal;
float m_distance;
};
} // namespace kraken
#endif

14
kraken/public/kraken.h Normal file
View File

@@ -0,0 +1,14 @@
#ifndef KRAKEN_H
#define KRAKEN_H
#include "scalar.h"
#include "vector2.h"
#include "vector3.h"
#include "vector4.h"
#include "matrix4.h"
#include "quaternion.h"
#include "aabb.h"
#include "triangle3.h"
#include "hitinfo.h"
#endif // KRAKEN_H

136
kraken/public/matrix4.h Normal file
View File

@@ -0,0 +1,136 @@
//
// Matrix4.h
// Kraken
//
// Copyright 2017 Kearwood Gilbert. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY KEARWOOD GILBERT ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KEARWOOD GILBERT OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Kearwood Gilbert.
//
#include "vector3.h"
#include "vector4.h"
#ifndef KRAKEN_MATRIX4_H
#define KRAKEN_MATRIX4_H
namespace kraken {
typedef enum {
X_AXIS,
Y_AXIS,
Z_AXIS
} AXIS;
class Quaternion;
class Matrix4 {
public:
union {
struct {
Vector4 axis_x, axis_y, axis_z, transform;
};
// Matrix components, in column-major order
float c[16];
};
// Default constructor - Creates an identity matrix
Matrix4();
Matrix4(float *pMat);
Matrix4(const Vector3 &new_axis_x, const Vector3 &new_axis_y, const Vector3 &new_axis_z, const Vector3 &new_transform);
// Destructor
~Matrix4();
// Copy constructor
Matrix4(const Matrix4 &m);
// Overload assignment operator
Matrix4& operator=(const Matrix4 &m);
// Overload comparison operator
bool operator==(const Matrix4 &m) const;
// Overload compound multiply operator
Matrix4& operator*=(const Matrix4 &m);
float& operator[](unsigned i);
float operator[](unsigned i) const;
// Overload multiply operator
//Matrix4& operator*(const Matrix4 &m);
Matrix4 operator*(const Matrix4 &m) const;
float *getPointer();
void perspective(float fov, float aspect, float nearz, float farz);
void ortho(float left, float right, float top, float bottom, float nearz, float farz);
void translate(float x, float y, float z);
void translate(const Vector3 &v);
void scale(float x, float y, float z);
void scale(const Vector3 &v);
void scale(float s);
void rotate(float angle, AXIS axis);
void rotate(const Quaternion &q);
void bias();
bool invert();
void transpose();
static Vector3 DotNoTranslate(const Matrix4 &m, const Vector3 &v); // Dot product without including translation; useful for transforming normals and tangents
static Matrix4 Invert(const Matrix4 &m);
static Matrix4 Transpose(const Matrix4 &m);
static Vector3 Dot(const Matrix4 &m, const Vector3 &v);
static Vector4 Dot4(const Matrix4 &m, const Vector4 &v);
static float DotW(const Matrix4 &m, const Vector3 &v);
static Vector3 DotWDiv(const Matrix4 &m, const Vector3 &v);
static Matrix4 LookAt(const Vector3 &cameraPos, const Vector3 &lookAtPos, const Vector3 &upDirection);
static Matrix4 Translation(const Vector3 &v);
static Matrix4 Rotation(const Vector3 &v);
static Matrix4 Scaling(const Vector3 &v);
};
} // namespace kraken
namespace std {
template<>
struct hash<kraken::Matrix4> {
public:
size_t operator()(const kraken::Matrix4 &s) const
{
size_t h1 = hash<kraken::Vector4>()(s.axis_x);
size_t h2 = hash<kraken::Vector4>()(s.axis_y);
size_t h3 = hash<kraken::Vector4>()(s.axis_z);
size_t h4 = hash<kraken::Vector4>()(s.transform);
return h1 ^ (h2 << 1) ^ (h3 << 2) ^ (h4 << 3);
}
};
} // namespace std
#endif // KRAKEN_MATRIX4_H

110
kraken/public/quaternion.h Normal file
View File

@@ -0,0 +1,110 @@
//
// Quaternion.h
// KREngine
//
// Copyright 2012 Kearwood Gilbert. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY KEARWOOD GILBERT ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KEARWOOD GILBERT OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Kearwood Gilbert.
//
#ifndef KRAKEN_QUATERNION_H
#define KRAKEN_QUATERNION_H
#include "vector3.h"
namespace kraken {
class Quaternion {
public:
union {
struct {
float w, x, y, z;
};
float c[4];
};
Quaternion();
Quaternion(float w, float x, float y, float z);
Quaternion(const Quaternion& p);
Quaternion(const Vector3 &euler);
Quaternion(const Vector3 &from_vector, const Vector3 &to_vector);
~Quaternion();
Quaternion& operator =( const Quaternion& p );
Quaternion operator +(const Quaternion &v) const;
Quaternion operator -(const Quaternion &v) const;
Quaternion operator +() const;
Quaternion operator -() const;
Quaternion operator *(const Quaternion &v);
Quaternion operator *(float num) const;
Quaternion operator /(float num) const;
Quaternion& operator +=(const Quaternion& v);
Quaternion& operator -=(const Quaternion& v);
Quaternion& operator *=(const Quaternion& v);
Quaternion& operator *=(const float& v);
Quaternion& operator /=(const float& v);
friend bool operator ==(Quaternion &v1, Quaternion &v2);
friend bool operator !=(Quaternion &v1, Quaternion &v2);
float& operator [](unsigned i);
float operator [](unsigned i) const;
void setEulerXYZ(const Vector3 &euler);
void setEulerZYX(const Vector3 &euler);
Vector3 eulerXYZ() const;
Matrix4 rotationMatrix() const;
void normalize();
static Quaternion Normalize(const Quaternion &v1);
void conjugate();
static Quaternion Conjugate(const Quaternion &v1);
static Quaternion FromAngleAxis(const Vector3 &axis, float angle);
static Quaternion Lerp(const Quaternion &a, const Quaternion &b, float t);
static Quaternion Slerp(const Quaternion &a, const Quaternion &b, float t);
static float Dot(const Quaternion &v1, const Quaternion &v2);
};
} // namespace kraken
namespace std {
template<>
struct hash<kraken::Quaternion> {
public:
size_t operator()(const kraken::Quaternion &s) const
{
size_t h1 = hash<float>()(s.c[0]);
size_t h2 = hash<float>()(s.c[1]);
size_t h3 = hash<float>()(s.c[2]);
size_t h4 = hash<float>()(s.c[3]);
return h1 ^ (h2 << 1) ^ (h3 << 2) ^ (h4 << 3);
}
};
} // namespace std
#endif // KRAKEN_QUATERNION_H

42
kraken/KRTriangle3.h → kraken/public/scalar.h Executable file → Normal file
View File

@@ -1,8 +1,8 @@
//
// KRTriangle.h
// KREngine
// KRFloat.h
// Kraken
//
// Copyright 2012 Kearwood Gilbert. All rights reserved.
// Copyright 2017 Kearwood Gilbert. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
@@ -29,35 +29,13 @@
// or implied, of Kearwood Gilbert.
//
#ifndef KRTRIANGLE3_H
#define KRTRIANGLE3_H
#ifndef KRAKEN_SCALAR_H
#define KRAKEN_SCALAR_H
#include "KRVector3.h"
namespace kraken {
class KRTriangle3
{
public:
KRTriangle3(const KRTriangle3 &tri);
KRTriangle3(const KRVector3 &v1, const KRVector3 &v2, const KRVector3 &v3);
~KRTriangle3();
KRVector3 calculateNormal() const;
bool operator ==(const KRTriangle3& b) const;
bool operator !=(const KRTriangle3& b) const;
KRTriangle3& operator =(const KRTriangle3& b);
KRVector3& operator[](unsigned i);
KRVector3 operator[](unsigned i) const;
bool rayCast(const KRVector3 &start, const KRVector3 &dir, KRVector3 &hit_point) const;
bool sphereCast(const KRVector3 &start, const KRVector3 &dir, float radius, KRVector3 &hit_point, float &hit_distance) const;
bool containsPoint(const KRVector3 &p) const;
KRVector3 closestPointOnTriangle(const KRVector3 &p) const;
private:
KRVector3 m_c[3];
};
float SmoothStep(float a, float b, float t);
#endif // KRTRIANGLE3_H
}; // namespace kraken
#endif // KRAKEN_SCALAR_H

79
kraken/public/triangle3.h Normal file
View File

@@ -0,0 +1,79 @@
//
// KRTriangle.h
// KREngine
//
// Copyright 2012 Kearwood Gilbert. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY KEARWOOD GILBERT ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KEARWOOD GILBERT OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Kearwood Gilbert.
//
#ifndef KRAKEN_TRIANGLE3_H
#define KRAKEN_TRIANGLE3_H
#include "vector3.h"
namespace kraken {
class Triangle3
{
public:
Vector3 vert[3];
Triangle3(const Triangle3 &tri);
Triangle3(const Vector3 &v1, const Vector3 &v2, const Vector3 &v3);
~Triangle3();
Vector3 calculateNormal() const;
bool operator ==(const Triangle3& b) const;
bool operator !=(const Triangle3& b) const;
Triangle3& operator =(const Triangle3& b);
Vector3& operator[](unsigned int i);
Vector3 operator[](unsigned int i) const;
bool rayCast(const Vector3 &start, const Vector3 &dir, Vector3 &hit_point) const;
bool sphereCast(const Vector3 &start, const Vector3 &dir, float radius, Vector3 &hit_point, float &hit_distance) const;
bool containsPoint(const Vector3 &p) const;
Vector3 closestPointOnTriangle(const Vector3 &p) const;
};
} // namespace kraken
namespace std {
template<>
struct hash<kraken::Triangle3> {
public:
size_t operator()(const kraken::Triangle3 &s) const
{
size_t h1 = hash<kraken::Vector3>()(s.vert[0]);
size_t h2 = hash<kraken::Vector3>()(s.vert[1]);
size_t h3 = hash<kraken::Vector3>()(s.vert[2]);
return h1 ^ (h2 << 1) ^ (h3 << 2);
}
};
} // namespace std
#endif // KRAKEN_TRIANGLE3_H

117
kraken/public/vector2.h Normal file
View File

@@ -0,0 +1,117 @@
//
// vector2.h
// Kraken
//
// Copyright 2017 Kearwood Gilbert. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY KEARWOOD GILBERT ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KEARWOOD GILBERT OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Kearwood Gilbert.
//
#ifndef KRAKEN_VECTOR2_H
#define KRAKEN_VECTOR2_H
#include <functional> // for hash<>
#include <limits> // for std::numeric_limits<>
#include <math.h> // for sqrtf
namespace kraken {
class Vector2 {
public:
union {
struct {
float x, y;
};
float c[2];
};
Vector2();
Vector2(float X, float Y);
Vector2(float v);
Vector2(float *v);
Vector2(const Vector2 &v);
~Vector2();
// Vector2 swizzle getters
Vector2 yx() const;
// Vector2 swizzle setters
void yx(const Vector2 &v);
Vector2& operator =(const Vector2& b);
Vector2 operator +(const Vector2& b) const;
Vector2 operator -(const Vector2& b) const;
Vector2 operator +() const;
Vector2 operator -() const;
Vector2 operator *(const float v) const;
Vector2 operator /(const float v) const;
Vector2& operator +=(const Vector2& b);
Vector2& operator -=(const Vector2& b);
Vector2& operator *=(const float v);
Vector2& operator /=(const float v);
// Comparison operators are implemented to allow insertion into sorted containers such as std::set
bool operator >(const Vector2& b) const;
bool operator <(const Vector2& b) const;
bool operator ==(const Vector2& b) const;
bool operator !=(const Vector2& b) const;
float& operator[](unsigned i);
float operator[](unsigned i) const;
float sqrMagnitude() const;
float magnitude() const;
void normalize();
static Vector2 Normalize(const Vector2 &v);
static float Cross(const Vector2 &v1, const Vector2 &v2);
static float Dot(const Vector2 &v1, const Vector2 &v2);
static Vector2 Min();
static Vector2 Max();
static Vector2 Zero();
static Vector2 One();
};
} // namespace kraken
namespace std {
template<>
struct hash<kraken::Vector2> {
public:
size_t operator()(const kraken::Vector2 &s) const
{
size_t h1 = hash<float>()(s.x);
size_t h2 = hash<float>()(s.y);
return h1 ^ (h2 << 1);
}
};
} // namespace std
#endif // KRAKEN_VECTOR2_H

146
kraken/public/vector3.h Normal file
View File

@@ -0,0 +1,146 @@
//
// Vector3.h
// Kraken
//
// Copyright 2017 Kearwood Gilbert. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY KEARWOOD GILBERT ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KEARWOOD GILBERT OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Kearwood Gilbert.
//
#ifndef KRAKEN_VECTOR3_H
#define KRAKEN_VECTOR3_H
#include <functional> // for hash<>
#include "vector2.h"
#include "vector4.h"
namespace kraken {
class Vector3 {
public:
union {
struct {
float x, y, z;
};
float c[3];
};
Vector3();
Vector3(float X, float Y, float Z);
Vector3(float v);
Vector3(float *v);
Vector3(double *v);
Vector3(const Vector3 &v);
Vector3(const Vector4 &v);
~Vector3();
// Vector2 swizzle getters
Vector2 xx() const;
Vector2 xy() const;
Vector2 xz() const;
Vector2 yx() const;
Vector2 yy() const;
Vector2 yz() const;
Vector2 zx() const;
Vector2 zy() const;
Vector2 zz() const;
// Vector2 swizzle setters
void xy(const Vector2 &v);
void xz(const Vector2 &v);
void yx(const Vector2 &v);
void yz(const Vector2 &v);
void zx(const Vector2 &v);
void zy(const Vector2 &v);
Vector3& operator =(const Vector3& b);
Vector3& operator =(const Vector4& b);
Vector3 operator +(const Vector3& b) const;
Vector3 operator -(const Vector3& b) const;
Vector3 operator +() const;
Vector3 operator -() const;
Vector3 operator *(const float v) const;
Vector3 operator /(const float v) const;
Vector3& operator +=(const Vector3& b);
Vector3& operator -=(const Vector3& b);
Vector3& operator *=(const float v);
Vector3& operator /=(const float v);
bool operator ==(const Vector3& b) const;
bool operator !=(const Vector3& b) const;
// Comparison operators are implemented to allow insertion into sorted containers such as std::set
bool operator >(const Vector3& b) const;
bool operator <(const Vector3& b) const;
float& operator[](unsigned i);
float operator[](unsigned i) const;
float sqrMagnitude() const; // calculate the square of the magnitude (useful for comparison of magnitudes without the cost of a sqrt() function)
float magnitude() const;
void scale(const Vector3 &v);
void normalize();
static Vector3 Normalize(const Vector3 &v);
static Vector3 Cross(const Vector3 &v1, const Vector3 &v2);
static float Dot(const Vector3 &v1, const Vector3 &v2);
static Vector3 Min();
static Vector3 Max();
static const Vector3 &Zero();
static Vector3 One();
static Vector3 Forward();
static Vector3 Backward();
static Vector3 Up();
static Vector3 Down();
static Vector3 Left();
static Vector3 Right();
static Vector3 Scale(const Vector3 &v1, const Vector3 &v2);
static Vector3 Lerp(const Vector3 &v1, const Vector3 &v2, float d);
static Vector3 Slerp(const Vector3 &v1, const Vector3 &v2, float d);
static void OrthoNormalize(Vector3 &normal, Vector3 &tangent); // Gram-Schmidt Orthonormalization
};
} // namespace kraken
namespace std {
template<>
struct hash<kraken::Vector3> {
public:
size_t operator()(const kraken::Vector3 &s) const
{
size_t h1 = hash<float>()(s.x);
size_t h2 = hash<float>()(s.y);
size_t h3 = hash<float>()(s.z);
return h1 ^ (h2 << 1) ^ (h3 << 2);
}
};
} // namespace std
#endif // KRAKEN_VECTOR3_H

122
kraken/public/vector4.h Normal file
View File

@@ -0,0 +1,122 @@
//
// Vector4.h
// Kraken
//
// Copyright 2017 Kearwood Gilbert. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY KEARWOOD GILBERT ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KEARWOOD GILBERT OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Kearwood Gilbert.
//
#ifndef KRAKEN_VECTOR4_H
#define KRAKEN_VECTOR4_H
#include <functional> // for hash<>
namespace kraken {
class Vector3;
class Vector4 {
public:
union {
struct {
float x, y, z, w;
};
float c[4];
};
Vector4();
Vector4(float X, float Y, float Z, float W);
Vector4(float v);
Vector4(float *v);
Vector4(const Vector4 &v);
Vector4(const Vector3 &v, float W);
~Vector4();
Vector4& operator =(const Vector4& b);
Vector4 operator +(const Vector4& b) const;
Vector4 operator -(const Vector4& b) const;
Vector4 operator +() const;
Vector4 operator -() const;
Vector4 operator *(const float v) const;
Vector4 operator /(const float v) const;
Vector4& operator +=(const Vector4& b);
Vector4& operator -=(const Vector4& b);
Vector4& operator *=(const float v);
Vector4& operator /=(const float v);
bool operator ==(const Vector4& b) const;
bool operator !=(const Vector4& b) const;
// Comparison operators are implemented to allow insertion into sorted containers such as std::set
bool operator >(const Vector4& b) const;
bool operator <(const Vector4& b) const;
float& operator[](unsigned i);
float operator[](unsigned i) const;
float sqrMagnitude() const; // calculate the square of the magnitude (useful for comparison of magnitudes without the cost of a sqrt() function)
float magnitude() const;
void normalize();
static Vector4 Normalize(const Vector4 &v);
static float Dot(const Vector4 &v1, const Vector4 &v2);
static Vector4 Min();
static Vector4 Max();
static const Vector4 &Zero();
static Vector4 One();
static Vector4 Forward();
static Vector4 Backward();
static Vector4 Up();
static Vector4 Down();
static Vector4 Left();
static Vector4 Right();
static Vector4 Lerp(const Vector4 &v1, const Vector4 &v2, float d);
static Vector4 Slerp(const Vector4 &v1, const Vector4 &v2, float d);
static void OrthoNormalize(Vector4 &normal, Vector4 &tangent); // Gram-Schmidt Orthonormalization
};
} // namespace kraken
namespace std {
template<>
struct hash<kraken::Vector4> {
public:
size_t operator()(const kraken::Vector4 &s) const
{
size_t h1 = hash<float>()(s.x);
size_t h2 = hash<float>()(s.y);
size_t h3 = hash<float>()(s.z);
size_t h4 = hash<float>()(s.w);
return h1 ^ (h2 << 1) ^ (h3 << 2) ^ (h4 << 3);
}
};
} // namespace std
#endif // KRAKEN_VECTOR4_H

365
kraken/quaternion.cpp Normal file
View File

@@ -0,0 +1,365 @@
//
// Quaternion.cpp
// KREngine
//
// Copyright 2012 Kearwood Gilbert. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY KEARWOOD GILBERT ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KEARWOOD GILBERT OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Kearwood Gilbert.
//
#include "public/kraken.h"
#include "KRHelpers.h"
namespace kraken {
Quaternion::Quaternion() {
c[0] = 1.0;
c[1] = 0.0;
c[2] = 0.0;
c[3] = 0.0;
}
Quaternion::Quaternion(float w, float x, float y, float z) {
c[0] = w;
c[1] = x;
c[2] = y;
c[3] = z;
}
Quaternion::Quaternion(const Quaternion& p) {
c[0] = p[0];
c[1] = p[1];
c[2] = p[2];
c[3] = p[3];
}
Quaternion& Quaternion::operator =( const Quaternion& p ) {
c[0] = p[0];
c[1] = p[1];
c[2] = p[2];
c[3] = p[3];
return *this;
}
Quaternion::Quaternion(const Vector3 &euler) {
setEulerZYX(euler);
}
Quaternion::Quaternion(const Vector3 &from_vector, const Vector3 &to_vector) {
Vector3 a = Vector3::Cross(from_vector, to_vector);
c[0] = a[0];
c[1] = a[1];
c[2] = a[2];
c[3] = sqrt(from_vector.sqrMagnitude() * to_vector.sqrMagnitude()) + Vector3::Dot(from_vector, to_vector);
normalize();
}
Quaternion::~Quaternion() {
}
void Quaternion::setEulerXYZ(const Vector3 &euler)
{
*this = Quaternion::FromAngleAxis(Vector3(1.0f, 0.0f, 0.0f), euler.x)
* Quaternion::FromAngleAxis(Vector3(0.0f, 1.0f, 0.0f), euler.y)
* Quaternion::FromAngleAxis(Vector3(0.0f, 0.0f, 1.0f), euler.z);
}
void Quaternion::setEulerZYX(const Vector3 &euler) {
// ZYX Order!
float c1 = cos(euler[0] * 0.5f);
float c2 = cos(euler[1] * 0.5f);
float c3 = cos(euler[2] * 0.5f);
float s1 = sin(euler[0] * 0.5f);
float s2 = sin(euler[1] * 0.5f);
float s3 = sin(euler[2] * 0.5f);
c[0] = c1 * c2 * c3 + s1 * s2 * s3;
c[1] = s1 * c2 * c3 - c1 * s2 * s3;
c[2] = c1 * s2 * c3 + s1 * c2 * s3;
c[3] = c1 * c2 * s3 - s1 * s2 * c3;
}
float Quaternion::operator [](unsigned i) const {
return c[i];
}
float &Quaternion::operator [](unsigned i) {
return c[i];
}
Vector3 Quaternion::eulerXYZ() const {
double a2 = 2 * (c[0] * c[2] - c[1] * c[3]);
if(a2 <= -0.99999) {
return Vector3(
2.0 * atan2(c[1], c[0]),
-PI * 0.5f,
0
);
} else if(a2 >= 0.99999) {
return Vector3(
2.0 * atan2(c[1], c[0]),
PI * 0.5f,
0
);
} else {
return Vector3(
atan2(2 * (c[0] * c[1] + c[2] * c[3]), (1 - 2 * (c[1] * c[1] + c[2] * c[2]))),
asin(a2),
atan2(2 * (c[0] * c[3] + c[1] * c[2]), (1 - 2 * (c[2] * c[2] + c[3] * c[3])))
);
}
}
bool operator ==(Quaternion &v1, Quaternion &v2) {
return
v1[0] == v2[0]
&& v1[1] == v2[1]
&& v1[2] == v2[2]
&& v1[3] == v2[3];
}
bool operator !=(Quaternion &v1, Quaternion &v2) {
return
v1[0] != v2[0]
|| v1[1] != v2[1]
|| v1[2] != v2[2]
|| v1[3] != v2[3];
}
Quaternion Quaternion::operator *(const Quaternion &v) {
float t0 = (c[3]-c[2])*(v[2]-v[3]);
float t1 = (c[0]+c[1])*(v[0]+v[1]);
float t2 = (c[0]-c[1])*(v[2]+v[3]);
float t3 = (c[3]+c[2])*(v[0]-v[1]);
float t4 = (c[3]-c[1])*(v[1]-v[2]);
float t5 = (c[3]+c[1])*(v[1]+v[2]);
float t6 = (c[0]+c[2])*(v[0]-v[3]);
float t7 = (c[0]-c[2])*(v[0]+v[3]);
float t8 = t5+t6+t7;
float t9 = (t4+t8)/2;
return Quaternion(
t0+t9-t5,
t1+t9-t8,
t2+t9-t7,
t3+t9-t6
);
}
Quaternion Quaternion::operator *(float v) const {
return Quaternion(c[0] * v, c[1] * v, c[2] * v, c[3] * v);
}
Quaternion Quaternion::operator /(float num) const {
float inv_num = 1.0f / num;
return Quaternion(c[0] * inv_num, c[1] * inv_num, c[2] * inv_num, c[3] * inv_num);
}
Quaternion Quaternion::operator +(const Quaternion &v) const {
return Quaternion(c[0] + v[0], c[1] + v[1], c[2] + v[2], c[3] + v[3]);
}
Quaternion Quaternion::operator -(const Quaternion &v) const {
return Quaternion(c[0] - v[0], c[1] - v[1], c[2] - v[2], c[3] - v[3]);
}
Quaternion& Quaternion::operator +=(const Quaternion& v) {
c[0] += v[0];
c[1] += v[1];
c[2] += v[2];
c[3] += v[3];
return *this;
}
Quaternion& Quaternion::operator -=(const Quaternion& v) {
c[0] -= v[0];
c[1] -= v[1];
c[2] -= v[2];
c[3] -= v[3];
return *this;
}
Quaternion& Quaternion::operator *=(const Quaternion& v) {
float t0 = (c[3]-c[2])*(v[2]-v[3]);
float t1 = (c[0]+c[1])*(v[0]+v[1]);
float t2 = (c[0]-c[1])*(v[2]+v[3]);
float t3 = (c[3]+c[2])*(v[0]-v[1]);
float t4 = (c[3]-c[1])*(v[1]-v[2]);
float t5 = (c[3]+c[1])*(v[1]+v[2]);
float t6 = (c[0]+c[2])*(v[0]-v[3]);
float t7 = (c[0]-c[2])*(v[0]+v[3]);
float t8 = t5+t6+t7;
float t9 = (t4+t8)/2;
c[0] = t0+t9-t5;
c[1] = t1+t9-t8;
c[2] = t2+t9-t7;
c[3] = t3+t9-t6;
return *this;
}
Quaternion& Quaternion::operator *=(const float& v) {
c[0] *= v;
c[1] *= v;
c[2] *= v;
c[3] *= v;
return *this;
}
Quaternion& Quaternion::operator /=(const float& v) {
float inv_v = 1.0f / v;
c[0] *= inv_v;
c[1] *= inv_v;
c[2] *= inv_v;
c[3] *= inv_v;
return *this;
}
Quaternion Quaternion::operator +() const {
return *this;
}
Quaternion Quaternion::operator -() const {
return Quaternion(-c[0], -c[1], -c[2], -c[3]);
}
Quaternion Normalize(const Quaternion &v1) {
float inv_magnitude = 1.0f / sqrtf(v1[0] * v1[0] + v1[1] * v1[1] + v1[2] * v1[2] + v1[3] * v1[3]);
return Quaternion(
v1[0] * inv_magnitude,
v1[1] * inv_magnitude,
v1[2] * inv_magnitude,
v1[3] * inv_magnitude
);
}
void Quaternion::normalize() {
float inv_magnitude = 1.0f / sqrtf(c[0] * c[0] + c[1] * c[1] + c[2] * c[2] + c[3] * c[3]);
c[0] *= inv_magnitude;
c[1] *= inv_magnitude;
c[2] *= inv_magnitude;
c[3] *= inv_magnitude;
}
Quaternion Conjugate(const Quaternion &v1) {
return Quaternion(v1[0], -v1[1], -v1[2], -v1[3]);
}
void Quaternion::conjugate() {
c[1] = -c[1];
c[2] = -c[2];
c[3] = -c[3];
}
Matrix4 Quaternion::rotationMatrix() const {
Matrix4 matRotate;
/*
Vector3 euler = eulerXYZ();
matRotate.rotate(euler.x, X_AXIS);
matRotate.rotate(euler.y, Y_AXIS);
matRotate.rotate(euler.z, Z_AXIS);
*/
// FINDME - Determine why the more optimal routine commented below wasn't working
matRotate.c[0] = 1.0 - 2.0 * (c[2] * c[2] + c[3] * c[3]);
matRotate.c[1] = 2.0 * (c[1] * c[2] - c[0] * c[3]);
matRotate.c[2] = 2.0 * (c[0] * c[2] + c[1] * c[3]);
matRotate.c[4] = 2.0 * (c[1] * c[2] + c[0] * c[3]);
matRotate.c[5] = 1.0 - 2.0 * (c[1] * c[1] + c[3] * c[3]);
matRotate.c[6] = 2.0 * (c[2] * c[3] - c[0] * c[1]);
matRotate.c[8] = 2.0 * (c[1] * c[3] - c[0] * c[2]);
matRotate.c[9] = 2.0 * (c[0] * c[1] + c[2] * c[3]);
matRotate.c[10] = 1.0 - 2.0 * (c[1] * c[1] + c[2] * c[2]);
return matRotate;
}
Quaternion Quaternion::FromAngleAxis(const Vector3 &axis, float angle)
{
float ha = angle * 0.5f;
float sha = sin(ha);
return Quaternion(cos(ha), axis.x * sha, axis.y * sha, axis.z * sha);
}
float Quaternion::Dot(const Quaternion &v1, const Quaternion &v2)
{
return v1.c[0] * v2.c[0] + v1.c[1] * v2.c[1] + v1.c[2] * v2.c[2] + v1.c[3] * v2.c[3];
}
Quaternion Quaternion::Lerp(const Quaternion &a, const Quaternion &b, float t)
{
if (t <= 0.0f) {
return a;
} else if (t >= 1.0f) {
return b;
}
return a * (1.0f - t) + b * t;
}
Quaternion Quaternion::Slerp(const Quaternion &a, const Quaternion &b, float t)
{
if (t <= 0.0f) {
return a;
}
if (t >= 1.0f) {
return b;
}
float coshalftheta = Dot(a, b);
Quaternion c = a;
// Angle is greater than 180. We can negate the angle/quat to get the
// shorter rotation to reach the same destination.
if ( coshalftheta < 0.0f ) {
coshalftheta = -coshalftheta;
c = -c;
}
if ( coshalftheta > (1.0f - std::numeric_limits<float>::epsilon())) {
// Angle is tiny - save some computation by lerping instead.
return Lerp(c, b, t);
}
float halftheta = acos(coshalftheta);
return (c * sin((1.0f - t) * halftheta) + b * sin(t * halftheta)) / sin(halftheta);
}
} // namespace kraken

View File

@@ -6,10 +6,14 @@
// Copyright (c) 2013 Kearwood Software. All rights reserved.
//
#include "KRFloat.h"
#include "public/kraken.h"
float KRFloat::SmoothStep(float a, float b, float t)
namespace kraken {
float SmoothStep(float a, float b, float t)
{
float d = (3.0 * t * t - 2.0 * t * t * t);
return a * (1.0f - d) + b * d;
}
}
} // namespace kraken

282
kraken/KRTriangle3.cpp → kraken/triangle3.cpp Executable file → Normal file
View File

@@ -6,77 +6,143 @@
// Copyright (c) 2014 Kearwood Software. All rights reserved.
//
#include "KRTriangle3.h"
#include "KRVector3.h"
#include "public/kraken.h"
KRTriangle3::KRTriangle3(const KRVector3 &v1, const KRVector3 &v2, const KRVector3 &v3)
using namespace kraken;
namespace {
bool _intersectSphere(const Vector3 &start, const Vector3 &dir, const Vector3 &sphere_center, float sphere_radius, float &distance)
{
// dir must be normalized
// From: http://archive.gamedev.net/archive/reference/articles/article1026.html
// TODO - Move to another class?
Vector3 Q = sphere_center - start;
float c = Q.magnitude();
float v = Vector3::Dot(Q, dir);
float d = sphere_radius * sphere_radius - (c * c - v * v);
if (d < 0.0) {
// No intersection
return false;
}
// Return the distance to the [first] intersecting point
distance = v - sqrt(d);
if (distance < 0.0f) {
return false;
}
return true;
}
bool _sameSide(const Vector3 &p1, const Vector3 &p2, const Vector3 &a, const Vector3 &b)
{
// TODO - Move to Vector3 class?
// From: http://stackoverflow.com/questions/995445/determine-if-a-3d-point-is-within-a-triangle
Vector3 cp1 = Vector3::Cross(b - a, p1 - a);
Vector3 cp2 = Vector3::Cross(b - a, p2 - a);
if (Vector3::Dot(cp1, cp2) >= 0) return true;
return false;
}
Vector3 _closestPointOnLine(const Vector3 &a, const Vector3 &b, const Vector3 &p)
{
// From: http://stackoverflow.com/questions/995445/determine-if-a-3d-point-is-within-a-triangle
// Determine t (the length of the vector from a to p)
Vector3 c = p - a;
Vector3 V = Vector3::Normalize(b - a);
float d = (a - b).magnitude();
float t = Vector3::Dot(V, c);
// Check to see if t is beyond the extents of the line segment
if (t < 0) return a;
if (t > d) return b;
// Return the point between a and b
return a + V * t;
}
} // anonymous namespace
namespace kraken {
Triangle3::Triangle3(const Vector3 &v1, const Vector3 &v2, const Vector3 &v3)
{
m_c[0] = v1;
m_c[1] = v2;
m_c[2] = v3;
vert[0] = v1;
vert[1] = v2;
vert[2] = v3;
}
KRTriangle3::KRTriangle3(const KRTriangle3 &tri)
Triangle3::Triangle3(const Triangle3 &tri)
{
m_c[0] = tri[0];
m_c[1] = tri[1];
m_c[3] = tri[3];
vert[0] = tri[0];
vert[1] = tri[1];
vert[3] = tri[3];
}
KRTriangle3::~KRTriangle3()
Triangle3::~Triangle3()
{
}
bool KRTriangle3::operator ==(const KRTriangle3& b) const
bool Triangle3::operator ==(const Triangle3& b) const
{
return m_c[0] == b[0] && m_c[1] == b[1] && m_c[2] == b[2];
return vert[0] == b[0] && vert[1] == b[1] && vert[2] == b[2];
}
bool KRTriangle3::operator !=(const KRTriangle3& b) const
bool Triangle3::operator !=(const Triangle3& b) const
{
return m_c[0] != b[0] || m_c[1] != b[1] || m_c[2] != b[2];
return vert[0] != b[0] || vert[1] != b[1] || vert[2] != b[2];
}
KRTriangle3& KRTriangle3::operator =(const KRTriangle3& b)
Triangle3& Triangle3::operator =(const Triangle3& b)
{
m_c[0] = b[0];
m_c[1] = b[1];
m_c[3] = b[3];
vert[0] = b[0];
vert[1] = b[1];
vert[3] = b[3];
return *this;
}
KRVector3& KRTriangle3::operator[](unsigned i)
Vector3& Triangle3::operator[](unsigned int i)
{
return m_c[i];
return vert[i];
}
KRVector3 KRTriangle3::operator[](unsigned i) const
Vector3 Triangle3::operator[](unsigned int i) const
{
return m_c[i];
return vert[i];
}
bool KRTriangle3::rayCast(const KRVector3 &start, const KRVector3 &dir, KRVector3 &hit_point) const
bool Triangle3::rayCast(const Vector3 &start, const Vector3 &dir, Vector3 &hit_point) const
{
// algorithm based on Dan Sunday's implementation at http://geomalgorithms.com/a06-_intersect-2.html
const float SMALL_NUM = 0.00000001; // anything that avoids division overflow
KRVector3 u, v, n; // triangle vectors
KRVector3 w0, w; // ray vectors
Vector3 u, v, n; // triangle vectors
Vector3 w0, w; // ray vectors
float r, a, b; // params to calc ray-plane intersect
// get triangle edge vectors and plane normal
u = m_c[1] - m_c[0];
v = m_c[2] - m_c[0];
n = KRVector3::Cross(u, v); // cross product
if (n == KRVector3::Zero()) // triangle is degenerate
u = vert[1] - vert[0];
v = vert[2] - vert[0];
n = Vector3::Cross(u, v); // cross product
if (n == Vector3::Zero()) // triangle is degenerate
return false; // do not deal with this case
w0 = start - m_c[0];
a = -KRVector3::Dot(n, w0);
b = KRVector3::Dot(n,dir);
w0 = start - vert[0];
a = -Vector3::Dot(n, w0);
b = Vector3::Dot(n,dir);
if (fabs(b) < SMALL_NUM) { // ray is parallel to triangle plane
if (a == 0)
return false; // ray lies in triangle plane
@@ -92,16 +158,16 @@ bool KRTriangle3::rayCast(const KRVector3 &start, const KRVector3 &dir, KRVector
// for a segment, also test if (r > 1.0) => no intersect
KRVector3 plane_hit_point = start + dir * r; // intersect point of ray and plane
Vector3 plane_hit_point = start + dir * r; // intersect point of ray and plane
// is plane_hit_point inside triangle?
float uu, uv, vv, wu, wv, D;
uu = KRVector3::Dot(u,u);
uv = KRVector3::Dot(u,v);
vv = KRVector3::Dot(v,v);
w = plane_hit_point - m_c[0];
wu = KRVector3::Dot(w,u);
wv = KRVector3::Dot(w,v);
uu = Vector3::Dot(u,u);
uv = Vector3::Dot(u,v);
vv = Vector3::Dot(v,v);
w = plane_hit_point - vert[0];
wu = Vector3::Dot(w,u);
wv = Vector3::Dot(w,v);
D = uv * uv - uu * vv;
// get and test parametric coords
@@ -118,84 +184,23 @@ bool KRTriangle3::rayCast(const KRVector3 &start, const KRVector3 &dir, KRVector
return true;
}
KRVector3 KRTriangle3::calculateNormal() const
Vector3 Triangle3::calculateNormal() const
{
KRVector3 v1 = m_c[1] - m_c[0];
KRVector3 v2 = m_c[2] - m_c[0];
Vector3 v1 = vert[1] - vert[0];
Vector3 v2 = vert[2] - vert[0];
return KRVector3::Normalize(KRVector3::Cross(v1, v2));
return Vector3::Normalize(Vector3::Cross(v1, v2));
}
bool _intersectSphere(const KRVector3 &start, const KRVector3 &dir, const KRVector3 &sphere_center, float sphere_radius, float &distance)
Vector3 Triangle3::closestPointOnTriangle(const Vector3 &p) const
{
// dir must be normalized
// From: http://archive.gamedev.net/archive/reference/articles/article1026.html
Vector3 a = vert[0];
Vector3 b = vert[1];
Vector3 c = vert[2];
// TODO - Move to another class?
KRVector3 Q = sphere_center - start;
float c = Q.magnitude();
float v = KRVector3::Dot(Q, dir);
float d = sphere_radius * sphere_radius - (c * c - v * v);
if(d < 0.0) {
// No intersection
return false;
}
// Return the distance to the [first] intersecting point
distance = v - sqrt(d);
if(distance < 0.0f) {
return false;
}
return true;
}
bool _sameSide(const KRVector3 &p1, const KRVector3 &p2, const KRVector3 &a, const KRVector3 &b)
{
// TODO - Move to KRVector3 class?
// From: http://stackoverflow.com/questions/995445/determine-if-a-3d-point-is-within-a-triangle
KRVector3 cp1 = KRVector3::Cross(b - a, p1 - a);
KRVector3 cp2 = KRVector3::Cross(b - a, p2 - a);
if(KRVector3::Dot(cp1, cp2) >= 0) return true;
return false;
}
KRVector3 _closestPointOnLine(const KRVector3 &a, const KRVector3 &b, const KRVector3 &p)
{
// From: http://stackoverflow.com/questions/995445/determine-if-a-3d-point-is-within-a-triangle
// Determine t (the length of the vector from a to p)
KRVector3 c = p - a;
KRVector3 V = KRVector3::Normalize(b - a);
float d = (a - b).magnitude();
float t = KRVector3::Dot(V, c);
// Check to see if t is beyond the extents of the line segment
if (t < 0) return a;
if (t > d) return b;
// Return the point between a and b
return a + V * t;
}
KRVector3 KRTriangle3::closestPointOnTriangle(const KRVector3 &p) const
{
KRVector3 a = m_c[0];
KRVector3 b = m_c[1];
KRVector3 c = m_c[2];
KRVector3 Rab = _closestPointOnLine(a, b, p);
KRVector3 Rbc = _closestPointOnLine(b, c, p);
KRVector3 Rca = _closestPointOnLine(c, a, p);
Vector3 Rab = _closestPointOnLine(a, b, p);
Vector3 Rbc = _closestPointOnLine(b, c, p);
Vector3 Rca = _closestPointOnLine(c, a, p);
// return closest [Rab, Rbc, Rca] to p;
float sd_Rab = (p - Rab).sqrMagnitude();
@@ -211,21 +216,21 @@ KRVector3 KRTriangle3::closestPointOnTriangle(const KRVector3 &p) const
}
}
bool KRTriangle3::sphereCast(const KRVector3 &start, const KRVector3 &dir, float radius, KRVector3 &hit_point, float &hit_distance) const
bool Triangle3::sphereCast(const Vector3 &start, const Vector3 &dir, float radius, Vector3 &hit_point, float &hit_distance) const
{
// Dir must be normalized
const float SMALL_NUM = 0.001f; // anything that avoids division overflow
KRVector3 tri_normal = calculateNormal();
Vector3 tri_normal = calculateNormal();
float d = KRVector3::Dot(tri_normal, m_c[0]);
float e = KRVector3::Dot(tri_normal, start) - radius;
float d = Vector3::Dot(tri_normal, vert[0]);
float e = Vector3::Dot(tri_normal, start) - radius;
float cotangent_distance = e - d;
KRVector3 plane_intersect;
Vector3 plane_intersect;
float plane_intersect_distance;
float denom = KRVector3::Dot(tri_normal, dir);
float denom = Vector3::Dot(tri_normal, dir);
if(denom > -SMALL_NUM) {
return false; // dir is co-planar with the triangle or going in the direction of the normal; no intersection
@@ -256,7 +261,7 @@ bool KRTriangle3::sphereCast(const KRVector3 &start, const KRVector3 &dir, float
return true;
} else {
// Triangle does not contain point, cast ray back to sphere from closest point on triangle edge or vertice
KRVector3 closest_point = closestPointOnTriangle(plane_intersect);
Vector3 closest_point = closestPointOnTriangle(plane_intersect);
float reverse_hit_distance;
if(_intersectSphere(closest_point, -dir, start, radius, reverse_hit_distance)) {
// Reverse cast hit sphere
@@ -271,16 +276,16 @@ bool KRTriangle3::sphereCast(const KRVector3 &start, const KRVector3 &dir, float
}
bool KRTriangle3::containsPoint(const KRVector3 &p) const
bool Triangle3::containsPoint(const Vector3 &p) const
{
/*
// From: http://stackoverflow.com/questions/995445/determine-if-a-3d-point-is-within-a-triangle
const float SMALL_NUM = 0.00000001f; // anything that avoids division overflow
// KRVector3 A = m_c[0], B = m_c[1], C = m_c[2];
if (_sameSide(p, m_c[0], m_c[1], m_c[2]) && _sameSide(p, m_c[1], m_c[0], m_c[2]) && _sameSide(p, m_c[2], m_c[0], m_c[1])) {
KRVector3 vc1 = KRVector3::Cross(m_c[0] - m_c[1], m_c[0] - m_c[2]);
if(fabs(KRVector3::Dot(m_c[0] - p, vc1)) <= SMALL_NUM) {
// Vector3 A = vert[0], B = vert[1], C = vert[2];
if (_sameSide(p, vert[0], vert[1], vert[2]) && _sameSide(p, vert[1], vert[0], vert[2]) && _sameSide(p, vert[2], vert[0], vert[1])) {
Vector3 vc1 = Vector3::Cross(vert[0] - vert[1], vert[0] - vert[2]);
if(fabs(Vector3::Dot(vert[0] - p, vc1)) <= SMALL_NUM) {
return true;
}
}
@@ -290,28 +295,28 @@ bool KRTriangle3::containsPoint(const KRVector3 &p) const
// From: http://blogs.msdn.com/b/rezanour/archive/2011/08/07/barycentric-coordinates-and-point-in-triangle-tests.aspx
KRVector3 A = m_c[0];
KRVector3 B = m_c[1];
KRVector3 C = m_c[2];
KRVector3 P = p;
Vector3 A = vert[0];
Vector3 B = vert[1];
Vector3 C = vert[2];
Vector3 P = p;
// Prepare our barycentric variables
KRVector3 u = B - A;
KRVector3 v = C - A;
KRVector3 w = P - A;
Vector3 u = B - A;
Vector3 v = C - A;
Vector3 w = P - A;
KRVector3 vCrossW = KRVector3::Cross(v, w);
KRVector3 vCrossU = KRVector3::Cross(v, u);
Vector3 vCrossW = Vector3::Cross(v, w);
Vector3 vCrossU = Vector3::Cross(v, u);
// Test sign of r
if (KRVector3::Dot(vCrossW, vCrossU) < 0)
if (Vector3::Dot(vCrossW, vCrossU) < 0)
return false;
KRVector3 uCrossW = KRVector3::Cross(u, w);
KRVector3 uCrossV = KRVector3::Cross(u, v);
Vector3 uCrossW = Vector3::Cross(u, w);
Vector3 uCrossV = Vector3::Cross(u, v);
// Test sign of t
if (KRVector3::Dot(uCrossW, uCrossV) < 0)
if (Vector3::Dot(uCrossW, uCrossV) < 0)
return false;
// At this point, we know that r and t and both > 0.
@@ -323,5 +328,4 @@ bool KRTriangle3::containsPoint(const KRVector3 &p) const
return (r + t <= 1);
}
} // namespace kraken

215
kraken/vector2.cpp Normal file
View File

@@ -0,0 +1,215 @@
//
// Vector2.cpp
// KREngine
//
// Created by Kearwood Gilbert on 12-03-22.
// Copyright (c) 2012 Kearwood Software. All rights reserved.
//
#include "public/kraken.h"
namespace kraken {
Vector2::Vector2() {
x = 0.0;
y = 0.0;
}
Vector2::Vector2(float X, float Y) {
x = X;
y = Y;
}
Vector2::Vector2(float v) {
x = v;
y = v;
}
Vector2::Vector2(float *v) {
x = v[0];
y = v[1];
}
Vector2::Vector2(const Vector2 &v) {
x = v.x;
y = v.y;
}
// Vector2 swizzle getters
Vector2 Vector2::yx() const
{
return Vector2(y,x);
}
// Vector2 swizzle setters
void Vector2::yx(const Vector2 &v)
{
y = v.x;
x = v.y;
}
Vector2 Vector2::Min() {
return Vector2(-std::numeric_limits<float>::max());
}
Vector2 Vector2::Max() {
return Vector2(std::numeric_limits<float>::max());
}
Vector2 Vector2::Zero() {
return Vector2(0.0f);
}
Vector2 Vector2::One() {
return Vector2(1.0f);
}
Vector2::~Vector2() {
}
Vector2& Vector2::operator =(const Vector2& b) {
x = b.x;
y = b.y;
return *this;
}
Vector2 Vector2::operator +(const Vector2& b) const {
return Vector2(x + b.x, y + b.y);
}
Vector2 Vector2::operator -(const Vector2& b) const {
return Vector2(x - b.x, y - b.y);
}
Vector2 Vector2::operator +() const {
return *this;
}
Vector2 Vector2::operator -() const {
return Vector2(-x, -y);
}
Vector2 Vector2::operator *(const float v) const {
return Vector2(x * v, y * v);
}
Vector2 Vector2::operator /(const float v) const {
float inv_v = 1.0f / v;
return Vector2(x * inv_v, y * inv_v);
}
Vector2& Vector2::operator +=(const Vector2& b) {
x += b.x;
y += b.y;
return *this;
}
Vector2& Vector2::operator -=(const Vector2& b) {
x -= b.x;
y -= b.y;
return *this;
}
Vector2& Vector2::operator *=(const float v) {
x *= v;
y *= v;
return *this;
}
Vector2& Vector2::operator /=(const float v) {
float inv_v = 1.0f / v;
x *= inv_v;
y *= inv_v;
return *this;
}
bool Vector2::operator ==(const Vector2& b) const {
return x == b.x && y == b.y;
}
bool Vector2::operator !=(const Vector2& b) const {
return x != b.x || y != b.y;
}
bool Vector2::operator >(const Vector2& b) const
{
// Comparison operators are implemented to allow insertion into sorted containers such as std::set
if(x > b.x) {
return true;
} else if(x < b.x) {
return false;
} else if(y > b.y) {
return true;
} else {
return false;
}
}
bool Vector2::operator <(const Vector2& b) const
{
// Comparison operators are implemented to allow insertion into sorted containers such as std::set
if(x < b.x) {
return true;
} else if(x > b.x) {
return false;
} else if(y < b.y) {
return true;
} else {
return false;
}
}
float& Vector2::operator[] (unsigned i) {
switch(i) {
case 0:
return x;
case 1:
default:
return y;
}
}
float Vector2::operator[](unsigned i) const {
switch(i) {
case 0:
return x;
case 1:
default:
return y;
}
}
void Vector2::normalize() {
float inv_magnitude = 1.0f / sqrtf(x * x + y * y);
x *= inv_magnitude;
y *= inv_magnitude;
}
float Vector2::sqrMagnitude() const {
return x * x + y * y;
}
float Vector2::magnitude() const {
return sqrtf(x * x + y * y);
}
Vector2 Vector2::Normalize(const Vector2 &v) {
float inv_magnitude = 1.0f / sqrtf(v.x * v.x + v.y * v.y);
return Vector2(v.x * inv_magnitude, v.y * inv_magnitude);
}
float Vector2::Cross(const Vector2 &v1, const Vector2 &v2) {
return v1.x * v2.y - v1.y * v2.x;
}
float Vector2::Dot(const Vector2 &v1, const Vector2 &v2) {
return v1.x * v2.x + v1.y * v2.y;
}
} // namepsace kraken

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