6 Commits

33 changed files with 1207 additions and 25 deletions

View File

@@ -5,7 +5,7 @@ namespace TSE
{ {
#define TSE_VERSION_MAJOR 0 #define TSE_VERSION_MAJOR 0
#define TSE_VERSION_MINOR 1 #define TSE_VERSION_MINOR 1
#define TSE_VERSION_BUILD 2 #define TSE_VERSION_BUILD 4
#define TSE_VERSION_STRING std::to_string(TSE_VERSION_MAJOR) + "." + std::to_string(TSE_VERSION_MINOR) + "." + std::to_string(TSE_VERSION_BUILD) #define TSE_VERSION_STRING std::to_string(TSE_VERSION_MAJOR) + "." + std::to_string(TSE_VERSION_MINOR) + "." + std::to_string(TSE_VERSION_BUILD)

View File

@@ -3,6 +3,7 @@
#include "interfaces/IRenderer.hpp" #include "interfaces/IRenderer.hpp"
TSE::Camera* TSE::Camera::mainCamera = nullptr; TSE::Camera* TSE::Camera::mainCamera = nullptr;
TSE::ICameraHelper* TSE::Camera::helper = nullptr;
float TSE::Camera::GetRenderScale() const float TSE::Camera::GetRenderScale() const
{ {
@@ -182,6 +183,7 @@ void TSE::Camera::PreDraw(IShader *shader)
viewMatrix = BuildView_Zplus_RH(worlmatrix); viewMatrix = BuildView_Zplus_RH(worlmatrix);
shader->SetUniform("camMatrix", &viewMatrix); shader->SetUniform("camMatrix", &viewMatrix);
helper->OnRenderTargetChanged(lastRtSize.x, lastRtSize.y);
} }
void TSE::Camera::PostDraw() void TSE::Camera::PostDraw()

View File

@@ -17,6 +17,12 @@ namespace TSE
Perspective = 2, Perspective = 2,
}; };
class ICameraHelper
{
public:
inline virtual void OnRenderTargetChanged(float width, float height) {};
};
class Camera : public IResizeNotifiable, public BehaviourScript class Camera : public IResizeNotifiable, public BehaviourScript
{ {
private: private:
@@ -35,6 +41,7 @@ namespace TSE
Vector2 lastRtSize = {0, 0}; Vector2 lastRtSize = {0, 0};
public: public:
static ICameraHelper* helper;
static Camera* mainCamera; static Camera* mainCamera;
// Getter // Getter

View File

@@ -0,0 +1,281 @@
#include "TileMap.hpp"
TSE::TileMapChunk::TileMapChunk(int _chunksize, const Vector2 &_pos, SortingOrder _order)
{
chunksize = _chunksize;
pos = _pos;
order = _order;
}
void TSE::TileMapChunk::SetTile(const Vector2& p, const Vector2& Spriteindex, TileSet* set)
{
sprites[p] = set->GetSpriteIdAt(Spriteindex.x, Spriteindex.y);
}
void TSE::TileMapChunk::RemoveTile(Vector2 p)
{
sprites.erase(p);
}
void TSE::TileMapChunk::SetOrdering(SortingOrder _order)
{
order = _order;
}
void TSE::TileMapChunk::GetOrderedPositions(Vector2 *array)
{
switch (order)
{
case TopLeft:
for (int y = 0; y < chunksize; y++)
{
Vector2 offset = nextLine * y;
for (int x = 0; x < chunksize; x++)
{
Vector2 p(x,y);
auto v = sprites.find(p);
if(v != sprites.end())
*array++ = v->first - offset;
}
}
break;
case TopRight:
for (int y = 0; y < chunksize; y++)
{
Vector2 offset = nextLine * y;
for (int x = chunksize - 1; x >= 0; x--)
{
Vector2 p(x,y);
auto v = sprites.find(p);
if(v != sprites.end())
*array++ = v->first - offset;
}
}
break;
case BottomLeft:
for (int y = chunksize - 1; y >= 0; y--)
{
Vector2 offset = nextLine * y;
for (int x = 0; x < chunksize; x++)
{
Vector2 p(x,y);
auto v = sprites.find(p);
if(v != sprites.end())
*array++ = v->first - offset;
}
}
break;
case BottomRight:
for (int y = chunksize - 1; y >= 0; y--)
{
Vector2 offset = nextLine * y;
for (int x = chunksize - 1; x >= 0; x--)
{
Vector2 p(x,y);
auto v = sprites.find(p);
if(v != sprites.end())
*array++ = v->first - offset;
}
}
break;
}
}
void TSE::TileMapChunk::GetOrderedSpriteIds(int *array)
{
switch (order)
{
case TopLeft:
for (int y = 0; y < chunksize; y++)
{
for (int x = 0; x < chunksize; x++)
{
Vector2 p(x,y);
auto v = sprites.find(p);
if(v != sprites.end())
*array++ = v->second;
}
}
break;
case TopRight:
for (int y = 0; y < chunksize; y++)
{
for (int x = chunksize - 1; x >= 0; x--)
{
Vector2 p(x,y);
auto v = sprites.find(p);
if(v != sprites.end())
*array++ = v->second;
}
}
break;
case BottomLeft:
for (int y = chunksize - 1; y >= 0; y--)
{
for (int x = 0; x < chunksize; x++)
{
Vector2 p(x,y);
auto v = sprites.find(p);
if(v != sprites.end())
*array++ = v->second;
}
}
break;
case BottomRight:
for (int y = chunksize - 1; y >= 0; y--)
{
for (int x = chunksize - 1; x >= 0; x--)
{
Vector2 p(x,y);
auto v = sprites.find(p);
if(v != sprites.end())
*array++ = v->second;
}
}
break;
}
}
int TSE::TileMapChunk::GetChunksize()
{
return chunksize;
}
int TSE::TileMapChunk::GetSpriteCount()
{
return sprites.size();
}
void TSE::TileMap::RemoveTile(Vector2 p)
{
Vector2 chunkInnerPos = LocalToChunkPos(p);
Vector2 chunkIndex = p - chunkInnerPos;
if(chunks.contains(chunkIndex))
chunks[chunkIndex].RemoveTile(chunkInnerPos);
}
void TSE::TileMap::SetTile(Vector2 p, Vector2 Spriteindex)
{
Vector2 chunkInnerPos = LocalToChunkPos(p);
Vector2 chunkIndex = p - chunkInnerPos;
if(!chunks.contains(chunkIndex))
{
chunks[chunkIndex] = TileMapChunk(chunkSize, chunkIndex, order);
chunks[chunkIndex].nextLine = nextLine;
CheckBounds(chunkIndex);
}
chunks[chunkIndex].SetTile(chunkInnerPos, Spriteindex, set);
}
TSE::TileMapChunk* TSE::TileMap::GetChunk(const Vector2 &pos)
{
auto chunk = chunks.find(pos);
if(chunk == chunks.end())
return nullptr;
return &chunks[pos];
}
void TSE::TileMap::GetChunkPositionsInOrder(Vector2 *arr)
{
switch (order)
{
case TopLeft:
for (int y = bounds.p1.y; y < bounds.p2.y + 1; y++)
{
for (int x = bounds.p1.x; x < bounds.p2.x + 1; x++)
{
Vector2 p(x,y);
auto v = chunks.find(p);
if(v != chunks.end())
*arr++ = v->first;
}
}
break;
case TopRight:
for (int y = bounds.p1.y; y < bounds.p2.y + 1; y++)
{
for (int x = bounds.p2.x; x > bounds.p1.x - 1; x--)
{
Vector2 p(x,y);
auto v = chunks.find(p);
if(v != chunks.end())
*arr++ = v->first;
}
}
break;
case BottomLeft:
for (int y = bounds.p2.y; y > bounds.p1.y - 1; y--)
{
for (int x = bounds.p1.x; x < bounds.p2.x + 1; x++)
{
Vector2 p(x,y);
auto v = chunks.find(p);
if(v != chunks.end())
*arr++ = v->first;
}
}
break;
case BottomRight:
for (int y = bounds.p2.y; y > bounds.p1.y - 1; y--)
{
for (int x = bounds.p2.x; x > bounds.p1.x - 1; x--)
{
Vector2 p(x,y);
auto v = chunks.find(p);
if(v != chunks.end())
*arr++ = v->first;
}
}
break;
}
}
int TSE::TileMap::GetChunkCount()
{
return chunks.size();
}
TSE::TileSet *TSE::TileMap::GetTileSet()
{
return set;
}
void TSE::TileMap::SetNextLineOffset(const Vector2 &offset)
{
nextLine = offset;
for(auto& [_, chunk] : chunks)
{
chunk.nextLine = offset;
}
}
TSE::Vector2 TSE::TileMap::GetNextLineOffset()
{
return nextLine;
}
void TSE::TileMap::CheckBounds(Vector2 pos)
{
if(pos.x > bounds.p2.x)
bounds.p2.x = pos.x;
if(pos.y > bounds.p2.y)
bounds.p2.y = pos.y;
if(pos.x < bounds.p1.x)
bounds.p1.x = pos.x;
if(pos.y < bounds.p1.y)
bounds.p1.y = pos.y;
}
TSE::Vector2 TSE::TileMap::LocalToChunkPos(const Vector2 &v)
{
Vector2 p = Vector2((int)v.x % chunkSize, (int)v.y % chunkSize);
if(p.x < 0) p.x += chunkSize;
if(p.y < 0) p.y += chunkSize;
return p;
}
TSE::Vector2 TSE::TileMap::ChunkToLocalPos(const Vector2 &v, const TileMapChunk &chunk)
{
return v + chunk.pos * chunkSize;
}

View File

@@ -0,0 +1,73 @@
#pragma once
#define TILE_MAP typeid(TSE::TileMap).name()
#include <unordered_map>
#include "elements/BehaviourScript.hpp"
#include "Vector2.hpp"
#include "elements/Sprite.hpp"
#include "elements/TileSet.hpp"
namespace TSE
{
enum SortingOrder
{
TopRight,
TopLeft,
BottomRight,
BottomLeft,
};
struct TileMapChunk
{
private:
SortingOrder order;
int chunksize;
std::unordered_map<Vector2, int> sprites;
public:
Vector2 nextLine;
Vector2 pos;
TileMapChunk(int _chunksize = 16, const Vector2& _pos = {0,0}, SortingOrder _order = TopRight);
void SetTile(const Vector2& p, const Vector2& Spriteindex, TileSet* set);
void RemoveTile(Vector2 p);
void SetOrdering(SortingOrder _order);
void GetOrderedPositions(Vector2* array);
void GetOrderedSpriteIds(int* array);
int GetChunksize();
int GetSpriteCount();
};
class TileMap : public BehaviourScript
{
private:
Rect bounds = Rect(0,0,0,0);
Vector2 nextLine = Vector2(-0.5f, 1.25f);
public:
int chunkSize = 16;
SortingOrder order = TopRight;
Vector2 SpriteScale = Vector2(1,1);
TileSet* set;
std::unordered_map<Vector2, TileMapChunk> chunks;
void RemoveTile(Vector2 p);
void SetTile(Vector2 p, Vector2 Spriteindex);
TileMapChunk* GetChunk(const Vector2& pos);
void GetChunkPositionsInOrder(Vector2* arr);
int GetChunkCount();
TileSet* GetTileSet();
const Rect& GetBounds() const { return bounds; }
void SetNextLineOffset(const Vector2& offset);
Vector2 GetNextLineOffset();
inline const char* GetName() override
{
return "Tile Map";
}
private:
void CheckBounds(Vector2 pos);
Vector2 LocalToChunkPos(const Vector2& v);
Vector2 ChunkToLocalPos(const Vector2& v, const TileMapChunk& chunk);
};
} // namespace TSE

View File

@@ -148,6 +148,98 @@ void TSE::Texture::GetPixel(const Vector2 &pos, Color &c) const
GetPixel(pos.x, pos.y, c); GetPixel(pos.x, pos.y, c);
} }
TSE::Texture TSE::Texture::CutOut(const Vector2 &pos, Vector2 &size) const
{
Texture result = Texture(0,0);
if(bmp == nullptr)
{
TSE_ERROR("Failed to cut out texture. Source bitmap was nullptr.");
Texture::makeError(result);
return result;
}
const int left = static_cast<int>(pos.x);
const int top = static_cast<int>(pos.y);
const int width = static_cast<int>(size.x);
const int height = static_cast<int>(size.y);
if(width <= 0 || height <= 0)
{
TSE_ERROR("Failed to cut out texture. Size must be greater than 0.");
Texture::makeError(result);
return result;
}
const int texWidth = static_cast<int>(Width());
const int texHeight = static_cast<int>(Height());
if(left < 0 || top < 0 || left + width > texWidth || top + height > texHeight)
{
TSE_ERROR("Failed to cut out texture. Region out of bounds.");
Texture::makeError(result);
return result;
}
FIBITMAP* cut = FreeImage_Copy(bmp, left, top, left + width, top + height);
if(cut == nullptr)
{
TSE_ERROR("Failed to cut out texture. FreeImage_Copy returned nullptr.");
Texture::makeError(result);
return result;
}
Texture out = Texture(width, height, Bpp);
if(out.bmp != nullptr)
FreeImage_Unload(out.bmp);
out.bmp = cut;
out.imagePtr = FreeImage_GetBits(cut);
out.Bpp = Bpp;
out.chanels = chanels;
out.Size = Vector2(width, height);
out.Apply();
return out;
}
void TSE::Texture::PasteIn(const Vector2 &pos, Texture &t)
{
if(bmp == nullptr)
{
TSE_ERROR("Failed to paste texture. Destination bitmap was nullptr.");
return;
}
if(t.bmp == nullptr)
{
TSE_ERROR("Failed to paste texture. Source bitmap was nullptr.");
return;
}
if(Bpp != t.Bpp)
{
TSE_ERROR("Failed to paste texture. Source and destination Bpp do not match.");
return;
}
const int left = static_cast<int>(pos.x);
const int top = static_cast<int>(pos.y);
const int srcWidth = static_cast<int>(t.Width());
const int srcHeight = static_cast<int>(t.Height());
const int texWidth = static_cast<int>(Width());
const int texHeight = static_cast<int>(Height());
if(left < 0 || top < 0 || left + srcWidth > texWidth || top + srcHeight > texHeight)
{
TSE_ERROR("Failed to paste texture. Region out of bounds.");
return;
}
if(!FreeImage_Paste(bmp, t.bmp, left, top, 256))
{
TSE_ERROR("Failed to paste texture. FreeImage_Paste returned false.");
return;
}
imagePtr = FreeImage_GetBits(bmp);
Apply();
}
void TSE::Texture::SetPixelNoApply(const Vector2 &pos, const Color &c) void TSE::Texture::SetPixelNoApply(const Vector2 &pos, const Color &c)
{ {
SetPixelNoApply(pos.x, pos.y, c); SetPixelNoApply(pos.x, pos.y, c);

View File

@@ -38,6 +38,8 @@ namespace TSE
byte* GetImagePtr() const; byte* GetImagePtr() const;
void SetPixel(const Vector2& pos, const Color& c); void SetPixel(const Vector2& pos, const Color& c);
void GetPixel(const Vector2& pos, Color& c) const; void GetPixel(const Vector2& pos, Color& c) const;
Texture CutOut(const Vector2& pos, Vector2& size) const;
void PasteIn(const Vector2& pos, Texture& t);
void SetPixelNoApply(const Vector2& pos, const Color& c); void SetPixelNoApply(const Vector2& pos, const Color& c);
void ToSprite(Sprite& s); void ToSprite(Sprite& s);
void SetChanels(const byte& ch); void SetChanels(const byte& ch);

View File

@@ -33,3 +33,24 @@ void TSE::TileSet::GetSpriteAt(int x, int y, Sprite &s)
s = Sprite(tex, Rect(startpos, endpos)); s = Sprite(tex, Rect(startpos, endpos));
} }
int TSE::TileSet::GetSpriteIdAt(int x, int y)
{
if(x < 0 || x >= resx || y < 0 || y >= resy)
{
TSE_ERROR("The sprite you are trying to access is out of range");
return -1;
}
return y * resx + x;
}
uint TSE::TileSet::GetTextueID()
{
return tex->GetTextureId();
}
TSE::Vector2 TSE::TileSet::GetCount()
{
return Vector2(resx, resy);
}

View File

@@ -18,14 +18,18 @@ namespace TSE
void SetTexture(Texture* tex); void SetTexture(Texture* tex);
void GetSpriteAt(int x, int y, Sprite& s); void GetSpriteAt(int x, int y, Sprite& s);
int GetSpriteIdAt(int x, int y);
uint GetTextueID();
Vector2 GetCount();
inline void SetCount(Vector2& v) inline void SetCount(Vector2& v)
{ {
SetCount(v.x, v.y); SetCount(v.x, v.y);
}; };
inline void GetSpriteAt(Vector2& v, Sprite& s) inline void GetSpriteAt(const Vector2& v, Sprite& s)
{ {
GetSpriteAt(v.x, v.y, s); GetSpriteAt(v.x, v.y, s);
}; };
}; };
} // namespace TSE } // namespace TSE

View File

@@ -15,10 +15,10 @@ namespace TSE
objectEntries[id] = this; objectEntries[id] = this;
} }
Transformable::Transformable(uuids::uuid id) Transformable::Transformable(uuids::uuid _id)
: id(id), position(0, 0, 0), scale(1, 1, 1), rotation(), name("") : id(_id), position(0, 0, 0), scale(1, 1, 1), rotation(), name("")
{ {
objectEntries[id] = this; objectEntries[_id] = this;
} }
Transformable::Transformable(const string &name) Transformable::Transformable(const string &name)
@@ -28,10 +28,14 @@ namespace TSE
objectEntries[id] = this; objectEntries[id] = this;
} }
Transformable::Transformable(const string &name, uuids::uuid id) Transformable::Transformable(const string &name, uuids::uuid _id)
: id(id), position(0, 0, 0), scale(1, 1, 1), rotation(), name(name) : id(_id), position(0, 0, 0), scale(1, 1, 1), rotation(), name(name)
{
objectEntries[_id] = this;
}
Transformable::~Transformable()
{ {
objectEntries[id] = this;
} }
Vector3 Transformable::forward() const Vector3 Transformable::forward() const
@@ -106,7 +110,7 @@ namespace TSE
Matrix4x4 Transformable::GetLocalMatrix() const Matrix4x4 Transformable::GetLocalMatrix() const
{ {
return Matrix4x4::ToTranslationMatrix(position) * Matrix4x4::ToRotationMatrix(rotation) * Matrix4x4::ToScaleMatrix(scale);; return Matrix4x4::ToTranslationMatrix(position) * Matrix4x4::ToRotationMatrix(rotation) * Matrix4x4::ToScaleMatrix(scale);
} }
Matrix4x4 Transformable::GetGlobalMatrix() const Matrix4x4 Transformable::GetGlobalMatrix() const
@@ -366,14 +370,20 @@ namespace TSE
{ {
//deleting children //deleting children
if(!onlyThis) if(!onlyThis)
{
for(auto child : t->children) for(auto child : t->children)
{ {
HardDelete(child); HardDelete(child, onlyThis);
}
t->children.clear();
} }
//deleting atteched scripts //deleting atteched scripts
for (auto& [_, script] : t->components) for (auto& [_, script] : t->components)
{
delete script; delete script;
}
t->components.clear();
//deleting self //deleting self
Delete(t); Delete(t);
@@ -442,6 +452,19 @@ namespace TSE
return objectEntries.size(); return objectEntries.size();
} }
Transformable *Transformable::GetTansformableAt(int i)
{
int x = 0;
for(auto obj : objectEntries)
{
if(i == x++)
{
return obj.second;
}
}
return nullptr;
}
Transformable *Transformable::Find(string name) Transformable *Transformable::Find(string name)
{ {
for(auto obj : objectEntries) for(auto obj : objectEntries)

View File

@@ -36,7 +36,7 @@ namespace TSE
Transformable(uuids::uuid id); Transformable(uuids::uuid id);
Transformable(const string& name); Transformable(const string& name);
Transformable(const string& name, uuids::uuid id); Transformable(const string& name, uuids::uuid id);
~Transformable() = default; ~Transformable();
Vector3 forward() const; Vector3 forward() const;
Vector3 right() const; Vector3 right() const;
@@ -100,6 +100,7 @@ namespace TSE
public: public:
static int GetTansformableCount(); static int GetTansformableCount();
static Transformable* GetTansformableAt(int i);
static Transformable* Find(string name); static Transformable* Find(string name);
static Transformable* Find(uuids::uuid id); static Transformable* Find(uuids::uuid id);
}; };

View File

@@ -17,6 +17,7 @@ void TSE::ICursorHandler::Enable()
if(!enabled()) if(!enabled())
{ {
IInputManager::instance()->RegisterCursorHandler(this); IInputManager::instance()->RegisterCursorHandler(this);
Enabled = true;
} }
} }
@@ -25,6 +26,7 @@ void TSE::ICursorHandler::Disable()
if(enabled()) if(enabled())
{ {
IInputManager::instance()->UnregisterCursorHandler(this); IInputManager::instance()->UnregisterCursorHandler(this);
Enabled = false;
} }
} }

View File

@@ -17,6 +17,7 @@ void TSE::IKeyInputHandler::Enable()
if(!enabled()) if(!enabled())
{ {
IInputManager::instance()->RegisterKeyHandler(this); IInputManager::instance()->RegisterKeyHandler(this);
Enabled = true;
} }
} }
@@ -25,6 +26,7 @@ void TSE::IKeyInputHandler::Disable()
if(enabled()) if(enabled())
{ {
IInputManager::instance()->UnregisterKeyHandler(this); IInputManager::instance()->UnregisterKeyHandler(this);
Enabled = false;
} }
} }

View File

@@ -0,0 +1,172 @@
#include "basicEditorCamera.hpp"
#include "elements/Transformable.hpp"
#include "utils/Time.hpp"
#include "BehaviourScripts/Camera.hpp"
#include <cmath>
void TSE::EDITOR::basicEditorCamera::OnUpdate()
{
auto euler = baseObject->GetEuler();
auto finalrot = rotDelta * rotationMultiplier * Time::deltaTime();
rotDelta = Vector2::zero;
if(mouseInputEnabled)
{
euler.y += finalrot.x;
euler.x += finalrot.y;
}
baseObject->SetEuler(euler);
Vector3 move;
if(keyInputEnabled && SceneView::IsHovered)
delta = delta + keydelta * keyMultiplier;
move = baseObject->right() * delta.x;
move = move + baseObject->up() * delta.y;
move = move + baseObject->forward() * delta.z;
delta = Vector3::zero;
move = move * movementMultiplier * Time::deltaTime();
baseObject->position = baseObject->position + move;
}
void TSE::EDITOR::basicEditorCamera::Start()
{
ICursorHandler::Enable();
IKeyInputHandler::Enable();
}
void TSE::EDITOR::basicEditorCamera::OnKeyDown(const Key &key, const Modifier &mods)
{
switch (key)
{
case Key::LeftShift:
isShiftPressed = true;
break;
case Key::W:
keydelta = keydelta + Vector3::forward * keyMultiplier;
break;
case Key::A:
keydelta = keydelta + Vector3::left * keyMultiplier;
break;
case Key::S:
keydelta = keydelta + Vector3::back * keyMultiplier;
break;
case Key::D:
keydelta = keydelta + Vector3::right * keyMultiplier;
break;
case Key::E:
keydelta = keydelta + Vector3::up * keyMultiplier;
break;
case Key::Q:
keydelta = keydelta + Vector3::down * keyMultiplier;
break;
default:
return;
}
}
void TSE::EDITOR::basicEditorCamera::OnKeyUp(const Key &key, const Modifier &mods)
{
switch (key)
{
case Key::LeftShift:
isShiftPressed = false;
break;
case Key::W:
keydelta = keydelta - Vector3::forward * keyMultiplier;
break;
case Key::A:
keydelta = keydelta - Vector3::left * keyMultiplier;
break;
case Key::S:
keydelta = keydelta - Vector3::back * keyMultiplier;
break;
case Key::D:
keydelta = keydelta - Vector3::right * keyMultiplier;
break;
case Key::E:
keydelta = keydelta - Vector3::up * keyMultiplier;
break;
case Key::Q:
keydelta = keydelta - Vector3::down * keyMultiplier;
break;
default:
return;
}
}
void TSE::EDITOR::basicEditorCamera::OnMouseButtonDown(const MouseBtn &btn, const Modifier &mods)
{
if(!mouseInputEnabled) return;
switch (btn)
{
case MouseBtn::RightMouse:
holdingRightClick = true;
break;
case MouseBtn::LeftMouse:
holdingLeftClick = true;
break;
}
}
void TSE::EDITOR::basicEditorCamera::OnMouseButtonUp(const MouseBtn &btn, const Modifier &mods)
{
if(!mouseInputEnabled) return;
switch (btn)
{
case MouseBtn::RightMouse:
holdingRightClick = false;
break;
case MouseBtn::LeftMouse:
holdingLeftClick = false;
break;
default:
return;
}
}
void TSE::EDITOR::basicEditorCamera::OnMousePosition(const Vector2 &pos)
{
if(!mouseInputEnabled || !SceneView::IsHovered) return;
if(isShiftPressed && holdingLeftClick)
{
auto tmp = pos - lastMousepos;
tmp.x *= -1;
delta = delta + tmp;
}
else if(holdingRightClick)
{
rotDelta = rotDelta + (pos - lastMousepos);
}
lastMousepos = pos;
}
void TSE::EDITOR::basicEditorCamera::OnMouseScroll(const Vector2 &mdelta)
{
if(!mouseInputEnabled || !SceneView::IsHovered) return;
Camera* editorCam = (Camera*)Transformable::Find(".EditorCamera")->GetBehaviourScript(CAMERA);
float scale = editorCam->GetRenderScale();
scale += mdelta.y * zoomMultiplier;
scale = std::clamp(scale, zoomMin, zoomMax);
editorCam->SetRenderScale(scale);
}
void TSE::EDITOR::basicEditorCamera::CustomDraw(const bool &debug)
{
ImGui::DragFloat("Rotation Speed", &rotationMultiplier, 0.1f);
ImGui::DragFloat("Movement Speed", &movementMultiplier, 0.1f);
ImGui::DragFloat("Zoom Speed", &zoomMultiplier, 0.1f);
ImGui::DragFloat("key Speed", &keyMultiplier, 0.1f);
ImGui::Checkbox("Keybord Input", &keyInputEnabled);
ImGui::Checkbox("Mouse Input", &mouseInputEnabled);
}

View File

@@ -0,0 +1,60 @@
#pragma once
#define BASIC_EDITOR_CAMERA typeid(basicEditorCamera).name()
#include "elements/BehaviourScript.hpp"
#include "interfaces/ICursorHandler.hpp"
#include "interfaces/IKeyInputHandler.hpp"
#include "Vector2.hpp"
#include "Vector3.hpp"
#include "imgui/imgui.h"
#include "UI/windows/SceneView.hpp"
namespace TSE::EDITOR
{
class basicEditorCamera : public BehaviourScript, public ICursorHandler, public IKeyInputHandler
{
private:
bool keyInputEnabled = true;
bool mouseInputEnabled = true;
bool isShiftPressed = false;
bool holdingRightClick = false;
bool holdingLeftClick = false;
Vector3 delta = Vector3::zero;
Vector3 keydelta = Vector3::zero;
Vector2 rotDelta = Vector2::zero;
Vector2 lastMousepos;
float keyMultiplier = 0.5f;
float rotationMultiplier = 150;
float movementMultiplier = 64;
float zoomMultiplier = 2;
const float zoomMin = 6;
const float zoomMax = 500;
public:
void OnUpdate() override;
void Start() override;
inline const char* GetName() override
{
return "basicEditorCamera";
}
void OnKeyDown(const Key& key, const Modifier& mods) override;
void OnKeyUp(const Key& key, const Modifier& mods) override;
void OnMouseButtonDown(const MouseBtn& btn, const Modifier& mods) override;
void OnMouseButtonUp(const MouseBtn& btn, const Modifier& mods) override;
void OnMousePosition(const Vector2& pos) override;
void OnMouseScroll(const Vector2& delta) override;
void CustomDraw(const bool& debug) override;
};
} // namespace TSE::EDITOR

View File

@@ -3,6 +3,7 @@
#include "BehaviourScriptRegistry.hpp" #include "BehaviourScriptRegistry.hpp"
#include "BehaviourScripts/AudioListener.hpp" #include "BehaviourScripts/AudioListener.hpp"
#include "BehaviourScripts/AudioSource.hpp" #include "BehaviourScripts/AudioSource.hpp"
#include "BehaviourScripts/basicEditorCamera.hpp"
TSE::EDITOR::EditorSubsystem::EditorSubsystem() : sv(nullptr), editorLayer("") TSE::EDITOR::EditorSubsystem::EditorSubsystem() : sv(nullptr), editorLayer("")
{ {
@@ -34,8 +35,8 @@ TSE::EDITOR::EditorSubsystem::EditorSubsystem() : sv(nullptr), editorLayer("")
editorCam->SetRenderTarget(rt); editorCam->SetRenderTarget(rt);
editorCamera->AddBehaviourScript(editorCam); editorCamera->AddBehaviourScript(editorCam);
// basicCameraControls controls = basicCameraControls(); basicEditorCamera* controls = new basicEditorCamera();
// editorCamera->AddBehaviourScript(&controls); editorCamera->AddBehaviourScript(controls);
editorLayer = Layer(".editor"); editorLayer = Layer(".editor");
editorLayer.AddTransformable(editorCamera); editorLayer.AddTransformable(editorCamera);

View File

@@ -64,7 +64,7 @@ namespace TSE::EDITOR
// Suchfeld mit X Button // Suchfeld mit X Button
ImGui::PushItemWidth(-style.FramePadding.x * 4 - 24); // Platz für Clear Button ImGui::PushItemWidth(-style.FramePadding.x * 4 - 24); // Platz für Clear Button
ImGui::InputTextWithHint("##SearchField", "Suchfeld", searchBuffer, IM_ARRAYSIZE(searchBuffer)); ImGui::InputTextWithHint("##SearchField", "Search", searchBuffer, IM_ARRAYSIZE(searchBuffer));
ImGui::PopItemWidth(); ImGui::PopItemWidth();
ImGui::SameLine(); ImGui::SameLine();
@@ -203,6 +203,10 @@ namespace TSE::EDITOR
{ {
Draw((ParticleSystem*)element, debug); Draw((ParticleSystem*)element, debug);
} }
else if (name == "Tile Map")
{
Draw((TileMap*)element, debug);
}
else else
{ {
element->CustomDraw(debug); element->CustomDraw(debug);
@@ -813,6 +817,44 @@ namespace TSE::EDITOR
ImGui::Unindent(20.0f); ImGui::Unindent(20.0f);
} }
} }
void ElementDrawer::Draw(TileMap *element, const bool &debug)
{
int orderIndex = static_cast<int>(element->order);
const char* orderItems[] = { "TopRight", "TopLeft", "BottomRight", "BottomLeft" };
if (ImGui::Combo("Order", &orderIndex, orderItems, IM_ARRAYSIZE(orderItems)))
{
element->order = static_cast<SortingOrder>(orderIndex);
for (auto& [_, chunk] : element->chunks)
{
chunk.SetOrdering(element->order);
}
}
ImGui::BeginDisabled();
ImGui::DragInt("Chunk Size", &element->chunkSize, 1.0f);
ImGui::EndDisabled();
Vector2 nextLine = element->GetNextLineOffset();
if (ImGui::DragFloat2("Next Line Offset", &nextLine.x, 0.01f))
{
element->SetNextLineOffset(nextLine);
}
ImGui::DragFloat2("Sprite Scale", &element->SpriteScale.x, 0.01f);
if (debug)
{
Rect bounds = element->GetBounds();
ImGui::Separator();
ImGui::TextDisabled("Bounds");
ImGui::BeginDisabled();
ImGui::InputFloat2("Min", &bounds.p1.x);
ImGui::InputFloat2("Max", &bounds.p2.x);
ImGui::EndDisabled();
ImGui::TextDisabled(("Chunk Count: " + std::to_string(element->GetChunkCount())).c_str());
}
}
void ElementDrawer::DrawAudioClipCompact(AudioClip *element, const bool &debug, const std::string &label) void ElementDrawer::DrawAudioClipCompact(AudioClip *element, const bool &debug, const std::string &label)
{ {
float item_spacing = ImGui::GetStyle().ItemSpacing.x; float item_spacing = ImGui::GetStyle().ItemSpacing.x;

View File

@@ -13,6 +13,7 @@
#include "BehaviourScripts/ParticleSystem.hpp" #include "BehaviourScripts/ParticleSystem.hpp"
#include "BehaviourScripts/AudioListener.hpp" #include "BehaviourScripts/AudioListener.hpp"
#include "BehaviourScripts/AudioSource.hpp" #include "BehaviourScripts/AudioSource.hpp"
#include "BehaviourScripts/TileMap.hpp"
namespace TSE::EDITOR namespace TSE::EDITOR
{ {
@@ -79,6 +80,7 @@ namespace TSE::EDITOR
static void Draw(AudioClip* element, const bool& debug, const std::string& label = "", const bool small = false); static void Draw(AudioClip* element, const bool& debug, const std::string& label = "", const bool small = false);
static void Draw(Camera* element, const bool& debug); static void Draw(Camera* element, const bool& debug);
static void Draw(ParticleSystem* element, const bool& debug); static void Draw(ParticleSystem* element, const bool& debug);
static void Draw(TileMap* element, const bool& debug);
static void DrawAudioClipCompact(AudioClip* element, const bool& debug, const std::string& label); static void DrawAudioClipCompact(AudioClip* element, const bool& debug, const std::string& label);
static void DrawAudioClipNormal(AudioClip* element, const bool& debug, const std::string& label); static void DrawAudioClipNormal(AudioClip* element, const bool& debug, const std::string& label);

View File

@@ -17,7 +17,7 @@ void TSE::EDITOR::CameraView::Define()
} }
ImGuiWindowFlags flags2 = ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar; ImGuiWindowFlags flags2 = ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar;
if(ImGui::BeginChild("##SceneChild", {0,0}, ImGuiChildFlags_None, flags2)) if(ImGui::BeginChild("##CameraChild", {0,0}, ImGuiChildFlags_None, flags2))
{ {
ImGui::Image(fb->GetTextureId(), {fb->Width(), fb->Height()},{0,1}, {1,0}); ImGui::Image(fb->GetTextureId(), {fb->Width(), fb->Height()},{0,1}, {1,0});
auto vec2 = ImGui::GetWindowSize(); auto vec2 = ImGui::GetWindowSize();

View File

@@ -11,6 +11,8 @@ void TSE::EDITOR::HirearchieView::SetScene(Scene *s)
currentScene = s; currentScene = s;
} }
bool selectedFound = false;
void TSE::EDITOR::HirearchieView::Define() void TSE::EDITOR::HirearchieView::Define()
{ {
if(currentScene == nullptr) return; if(currentScene == nullptr) return;
@@ -32,6 +34,7 @@ void TSE::EDITOR::HirearchieView::Define()
if(collapseOpen) if(collapseOpen)
{ {
int layerCount = currentScene->GetLayerCount(); int layerCount = currentScene->GetLayerCount();
selectedFound = false;
for (int i = 0; i < layerCount; i++) for (int i = 0; i < layerCount; i++)
{ {
auto layer = currentScene->GetLayerAt(i); auto layer = currentScene->GetLayerAt(i);
@@ -39,6 +42,11 @@ void TSE::EDITOR::HirearchieView::Define()
DisplayLayer(layer); DisplayLayer(layer);
} }
if(!selectedFound && PropertiesView::GetCurrentInspectableType() == InspectableType::Transformable)
{
PropertiesView::ForceClearInspectorElement();
}
} }
if(activatePopUpNamingLayer) if(activatePopUpNamingLayer)
@@ -123,6 +131,7 @@ void TSE::EDITOR::HirearchieView::MenuBar()
ImGui::EndMenuBar(); ImGui::EndMenuBar();
} }
void TSE::EDITOR::HirearchieView::DisplayLayer(Layer *l) void TSE::EDITOR::HirearchieView::DisplayLayer(Layer *l)
{ {
ImGui::Indent(20.0f); ImGui::Indent(20.0f);
@@ -198,8 +207,10 @@ void TSE::EDITOR::HirearchieView::DisplayObj(Transformable *t, Layer *l)
if(selected == t->id) if(selected == t->id)
{ {
flags |= ImGuiTreeNodeFlags_Selected; flags |= ImGuiTreeNodeFlags_Selected;
selectedFound = true;
} }
bool open = ImGui::TreeNodeEx((t->GetName() + "##" + to_string(t->id)).c_str(), flags); string name = t->GetName() + "##" + to_string(t->id);
bool open = ImGui::TreeNodeEx((name).c_str(), flags);
if(ImGui::BeginPopupContextItem()) if(ImGui::BeginPopupContextItem())
{ {
bool disabled = false; bool disabled = false;
@@ -281,6 +292,7 @@ void TSE::EDITOR::HirearchieView::DisplayObj(Transformable *t, Layer *l)
{ {
selected = t->id; selected = t->id;
PropertiesView::SetInspectorElement(InspectableType::Transformable, t); PropertiesView::SetInspectorElement(InspectableType::Transformable, t);
selectedFound = true;
} }
if(open) if(open)
{ {

View File

@@ -30,6 +30,11 @@ void TSE::EDITOR::PropertiesView::MenuBar()
ImGui::EndMenuBar(); ImGui::EndMenuBar();
} }
TSE::EDITOR::InspectableType TSE::EDITOR::PropertiesView::GetCurrentInspectableType()
{
return currentlyInspecting.type;
}
void TSE::EDITOR::PropertiesView::SetInspectorElement(InspectableType type, void *element) void TSE::EDITOR::PropertiesView::SetInspectorElement(InspectableType type, void *element)
{ {
if(!locked) if(!locked)

View File

@@ -17,6 +17,7 @@ namespace TSE::EDITOR
void Define() override; void Define() override;
void MenuBar(); void MenuBar();
static InspectableType GetCurrentInspectableType();
static void SetInspectorElement(InspectableType type, void* element); static void SetInspectorElement(InspectableType type, void* element);
static void ClearInspectorElement(); static void ClearInspectorElement();
static void ForceClearInspectorElement(); static void ForceClearInspectorElement();

View File

@@ -16,6 +16,14 @@ void TSE::EDITOR::SceneView::Define()
{ {
fb->SetSize({vec2.x, vec2.y}); fb->SetSize({vec2.x, vec2.y});
} }
if(ImGui::IsWindowFocused())
{
IsHovered = true;
}
else
{
IsHovered = false;
}
} }
ImGui::EndChild(); ImGui::EndChild();
} }

View File

@@ -10,6 +10,7 @@ namespace TSE::EDITOR
private: private:
TSE::IRenderTexture* fb; TSE::IRenderTexture* fb;
public: public:
inline static bool IsHovered = false;
SceneView(TSE::IRenderTexture* frameBuffer); SceneView(TSE::IRenderTexture* frameBuffer);
void Define() override; void Define() override;
}; };

View File

@@ -17,18 +17,21 @@ void TSE::GLFW::InputGlfw::KeyCallback(GLFWwindow *window, int key, int scancode
case 1: //down case 1: //down
for(auto handler : ((InputGlfw*)instance())->keyHandler) for(auto handler : ((InputGlfw*)instance())->keyHandler)
{ {
if(handler->enabled())
handler->OnKeyDown((Key)key, (Modifier)mods); handler->OnKeyDown((Key)key, (Modifier)mods);
} }
break; break;
case 0: //up case 0: //up
for(auto handler : ((InputGlfw*)instance())->keyHandler) for(auto handler : ((InputGlfw*)instance())->keyHandler)
{ {
if(handler->enabled())
handler->OnKeyUp((Key)key, (Modifier)mods); handler->OnKeyUp((Key)key, (Modifier)mods);
} }
break; break;
case 2: //hold case 2: //hold
for(auto handler : ((InputGlfw*)instance())->keyHandler) for(auto handler : ((InputGlfw*)instance())->keyHandler)
{ {
if(handler->enabled())
handler->OnKeyHold((Key)key, (Modifier)mods); handler->OnKeyHold((Key)key, (Modifier)mods);
} }
break; break;
@@ -42,18 +45,21 @@ void TSE::GLFW::InputGlfw::MouseButtonCallback(GLFWwindow *window, int button, i
case 1: //down case 1: //down
for(auto handler : ((InputGlfw*)instance())->cursorHandler) for(auto handler : ((InputGlfw*)instance())->cursorHandler)
{ {
if(handler->enabled())
handler->OnMouseButtonDown((MouseBtn)button, (Modifier)mods); handler->OnMouseButtonDown((MouseBtn)button, (Modifier)mods);
} }
break; break;
case 0: //up case 0: //up
for(auto handler : ((InputGlfw*)instance())->cursorHandler) for(auto handler : ((InputGlfw*)instance())->cursorHandler)
{ {
if(handler->enabled())
handler->OnMouseButtonUp((MouseBtn)button, (Modifier)mods); handler->OnMouseButtonUp((MouseBtn)button, (Modifier)mods);
} }
break; break;
case 2: //hold case 2: //hold
for(auto handler : ((InputGlfw*)instance())->cursorHandler) for(auto handler : ((InputGlfw*)instance())->cursorHandler)
{ {
if(handler->enabled())
handler->OnMouseButtonHold((MouseBtn)button, (Modifier)mods); handler->OnMouseButtonHold((MouseBtn)button, (Modifier)mods);
} }
break; break;
@@ -64,6 +70,7 @@ void TSE::GLFW::InputGlfw::CursorPosCallback(GLFWwindow *window, double xpos, do
{ {
for(auto handler : ((InputGlfw*)instance())->cursorHandler) for(auto handler : ((InputGlfw*)instance())->cursorHandler)
{ {
if(handler->enabled())
handler->OnMousePosition(Vector2(xpos, ypos)); handler->OnMousePosition(Vector2(xpos, ypos));
} }
} }
@@ -72,6 +79,7 @@ void TSE::GLFW::InputGlfw::ScrollCallback(GLFWwindow *window, double xoffset, do
{ {
for(auto handler : ((InputGlfw*)instance())->cursorHandler) for(auto handler : ((InputGlfw*)instance())->cursorHandler)
{ {
if(handler->enabled())
handler->OnMouseScroll(Vector2(xoffset, yoffset)); handler->OnMouseScroll(Vector2(xoffset, yoffset));
} }
} }
@@ -106,6 +114,7 @@ void TSE::GLFW::InputGlfw::CharCallback(GLFWwindow *window, unsigned int codepoi
for(auto handler : ((InputGlfw*)instance())->keyHandler) for(auto handler : ((InputGlfw*)instance())->keyHandler)
{ {
if(handler->enabled())
handler->OnChar(msg); handler->OnChar(msg);
} }
} }

View File

@@ -0,0 +1,17 @@
#pragma once
#include "BehaviourScripts/Camera.hpp"
#include "GL/gl3w.h"
#include "GL/gl.h"
namespace TSE::GLFW
{
class CameraHelperOpenGL : public ICameraHelper
{
public:
inline void OnRenderTargetChanged(float width, float height) override
{
glViewport(0, 0, width, height);
};
};
} // namespace TSE::GLFW

View File

@@ -13,6 +13,7 @@
#include "interfaces/IRenderer.hpp" #include "interfaces/IRenderer.hpp"
#include "BehaviourScripts/Camera.hpp" #include "BehaviourScripts/Camera.hpp"
#include "RenderTextureCreatorOpenGL.hpp" #include "RenderTextureCreatorOpenGL.hpp"
#include "CameraHelperOpenGL.hpp"
TSE::GLFW::OpenGLRenderingBackend::OpenGLRenderingBackend(Color _backgroundColor, bool _vsync) TSE::GLFW::OpenGLRenderingBackend::OpenGLRenderingBackend(Color _backgroundColor, bool _vsync)
: OpenGLRenderingBackend(_backgroundColor, _vsync, 0, false){ } : OpenGLRenderingBackend(_backgroundColor, _vsync, 0, false){ }
@@ -39,6 +40,7 @@ void TSE::GLFW::OpenGLRenderingBackend::InitPreWindow()
{ {
IRenderTexture::factory = new RenderTextureCreatorOpenGL(); IRenderTexture::factory = new RenderTextureCreatorOpenGL();
Texture::helper = new TextureHelperOpenGL(); Texture::helper = new TextureHelperOpenGL();
Camera::helper = new CameraHelperOpenGL();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, TSE_OPENGL_VERSION_MAJOR); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, TSE_OPENGL_VERSION_MAJOR);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, TSE_OPENGL_VERSION_MINOR); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, TSE_OPENGL_VERSION_MINOR);

View File

@@ -0,0 +1,212 @@
#include "basicTileMapShader.hpp"
#include "BehaviourScripts/Renderable.hpp"
#include "BehaviourScripts/TileMap.hpp"
#include "Color.hpp"
#include "basicTileMapShaderGLSL.hpp"
#define SHADER_MESH_INDEX 0
#define SHADER_POS_INDEX 1
#define SHADER_SPRITE_INDEX 2
#define SHADER_PACKAGE_SIZE sizeof(float) * (3 + 1)
TSE::GLFW::BasicTileMapShader* TSE::GLFW::BasicTileMapShader::instance = nullptr;
TSE::GLFW::BasicTileMapShader *TSE::GLFW::BasicTileMapShader::Instance()
{
return instance;
}
void TSE::GLFW::BasicTileMapShader::Destroy()
{
if(instance != nullptr)
delete instance;
instance = nullptr;
}
void TSE::GLFW::BasicTileMapShader::Init(float width, float height)
{
std::vector<std::unique_ptr<ShaderPart>> parts;
parts.push_back(ShaderPart::LoadFromString(vertTile, GL_VERTEX_SHADER));
parts.push_back(ShaderPart::LoadFromString(fragTile, GL_FRAGMENT_SHADER));
instance = new BasicTileMapShader(std::move(parts));
instance->Enable();
int texIDs[] = { 0 };
instance->SetUniform("atlas", 0);
instance->Disable();
}
TSE::GLFW::BasicTileMapShader::BasicTileMapShader(std::vector<std::unique_ptr<ShaderPart>> &&parts) : Shader(parts)
{
PackageSize = SHADER_PACKAGE_SIZE;
}
TSE::GLFW::BasicTileMapShader::~BasicTileMapShader()
{
if (meshVBO) glDeleteBuffers(1, &meshVBO);
if (meshIBO) glDeleteBuffers(1, &meshIBO);
}
void TSE::GLFW::BasicTileMapShader::SetMesh(const void *verts, int vertCount, int stride, int floatCountPerVertex, int posOffsetBytes, GLenum primitive, const void *indices, int indexCount, GLenum indexType)
{
GLint prevVAO = 0, prevArrayBuffer = 0, prevElementBuffer = 0;
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &prevVAO);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &prevArrayBuffer);
glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &prevElementBuffer);
if (!meshVBO) glGenBuffers(1, &meshVBO);
glBindBuffer(GL_ARRAY_BUFFER, meshVBO);
glBufferData(GL_ARRAY_BUFFER, vertCount * stride, verts, GL_STATIC_DRAW);
if (indices && indexCount > 0)
{
if (!meshIBO) glGenBuffers(1, &meshIBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshIBO);
GLsizeiptr idxSize =
(indexType == GL_UNSIGNED_INT ? 4 :
indexType == GL_UNSIGNED_SHORT? 2 : 1) * indexCount;
glBufferData(GL_ELEMENT_ARRAY_BUFFER, idxSize, indices, GL_STATIC_DRAW);
meshIndexCount = indexCount;
meshIndexType = indexType;
}
else
{
// Kein Index-Buffer
if (meshIBO) { glDeleteBuffers(1, &meshIBO); meshIBO = 0; }
meshIndexCount = 0;
}
meshVertexCount = vertCount;
meshStride = stride;
meshPosOffset = posOffsetBytes;
meshPosSize = floatCountPerVertex;
meshPrimitive = primitive;
meshReady = true;
glBindBuffer(GL_ARRAY_BUFFER, prevArrayBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, prevElementBuffer);
glBindVertexArray(prevVAO);
}
void TSE::GLFW::BasicTileMapShader::OnEnable() const
{
if (!meshReady)
{
// Fallback: unit-Quad als TRIANGLE_FAN (4 Vertices, 2D Positionen)
const float quad[8] = { -0.5f,-0.5f, 0.5f,-0.5f, 0.5f,0.5f, -0.5f,0.5f };
const_cast<BasicTileMapShader*>(this)->SetMesh(
quad, 4, sizeof(float)*2, 2, 0, GL_TRIANGLE_FAN
);
}
GLint prevArrayBuffer = 0;
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &prevArrayBuffer);
glBindBuffer(GL_ARRAY_BUFFER, meshVBO);
glEnableVertexAttribArray(SHADER_MESH_INDEX); // LOC_QUAD/pos
glVertexAttribPointer(SHADER_MESH_INDEX, meshPosSize, GL_FLOAT, GL_FALSE, meshStride, (void*)meshPosOffset);
glVertexAttribDivisor(SHADER_MESH_INDEX, 0); // per-vertex (Mesh)
glBindBuffer(GL_ARRAY_BUFFER, prevArrayBuffer);
// layout 1: position (vec3)
glEnableVertexAttribArray(SHADER_POS_INDEX);
glVertexAttribPointer(SHADER_POS_INDEX, 3, GL_FLOAT, GL_FALSE, PackageSize, (void*)0);
glVertexAttribDivisor(SHADER_POS_INDEX, 1);
// layout 2: spriteindex (float)
glEnableVertexAttribArray(SHADER_SPRITE_INDEX);
glVertexAttribPointer(SHADER_SPRITE_INDEX, 1, GL_FLOAT, GL_FALSE, PackageSize, (void*)(sizeof(float)*3));
glVertexAttribDivisor(SHADER_SPRITE_INDEX, 1);
}
void TSE::GLFW::BasicTileMapShader::OnDisable() const
{
glDisableVertexAttribArray(SHADER_MESH_INDEX);
glDisableVertexAttribArray(SHADER_POS_INDEX);
glDisableVertexAttribArray(SHADER_SPRITE_INDEX);
}
void TSE::GLFW::BasicTileMapShader::OnFlush()
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureID);
}
void TSE::GLFW::BasicTileMapShader::OnDrawCall(int indexCount)
{
if (instanceCount <= 0) return;
SetUniform("spriteCount", &SpriteCount);
SetUniform("spriteScale", &SpriteScale);
GLint prevElementBuffer = 0;
glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &prevElementBuffer);
if (meshIBO && meshIndexCount > 0)
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshIBO);
glDrawElementsInstanced(meshPrimitive, meshIndexCount, meshIndexType, (void*)0, instanceCount);
}
else
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glDrawArraysInstanced(meshPrimitive, 0, meshVertexCount, instanceCount);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, (GLuint)prevElementBuffer);
instanceCount = 0;
}
void TSE::GLFW::BasicTileMapShader::OnSubmit(const Transformable &t, float *&target, TransformationStack &stack, void (*restartDrawcall)(IRenderer &), IRenderer &rnd)
{
auto* r = dynamic_cast<Renderable*>(t.GetBehaviourScript(RENDERABLE));
if (!r) return;
auto* tm = dynamic_cast<TileMap*>(t.GetBehaviourScript(TILE_MAP));
if (!tm) return;
auto tileSet = tm->GetTileSet();
TextureID = tileSet->GetTextueID();
SpriteCount = tileSet->GetCount();
SpriteScale = tm->SpriteScale;
int chunkcount = tm->GetChunkCount();
Vector2 orderedChunks[chunkcount];
tm->GetChunkPositionsInOrder(orderedChunks);
Matrix4x4 matr = t.GetLocalMatrix();
stack.Push(matr);
for(auto chunkPos : orderedChunks)
{
auto chunk = tm->GetChunk(chunkPos);
int spriteCount = chunk->GetSpriteCount();
Vector2 spritePositions[spriteCount];
int spriteIds[spriteCount];
chunk->GetOrderedPositions(spritePositions);
chunk->GetOrderedSpriteIds(spriteIds);
int chunkSize = chunk->GetChunksize();
for (int i = 0; i < spriteCount; i++)
{
Matrix4x4 mat = Matrix4x4::ToTranslationMatrix((chunkPos - chunk->nextLine * chunkPos.y) + spritePositions[i]) * Matrix4x4::ToRotationMatrix(Quaternion()) * Matrix4x4::ToScaleMatrix({1,1,1});
stack.Push(mat);
Vector3 pos = stack.Top() * Vector3(0,0,0);
*target++ = pos.x;
*target++ = pos.y;
*target++ = pos.z;
*target++ = spriteIds[i];
++instanceCount;
stack.Pop();
if(instanceCount >= 20000)
restartDrawcall(rnd);
}
}
restartDrawcall(rnd);
}

View File

@@ -0,0 +1,44 @@
#pragma once
#include "GL/gl3w.h"
#include "GL/gl.h"
#include "Shader.hpp"
#include "Types.hpp"
namespace TSE::GLFW
{
class BasicTileMapShader : public Shader
{
private:
static BasicTileMapShader* instance;
mutable bool meshReady = false;
GLuint meshVBO = 0;
GLuint meshIBO = 0;
GLsizei meshVertexCount = 0; // für DrawArraysInstanced
GLsizei meshIndexCount = 0; // für DrawElementsInstanced
GLenum meshPrimitive = GL_TRIANGLES;
GLenum meshIndexType = GL_UNSIGNED_SHORT;
int instanceCount = 0; // eigener Instanzzähler
GLint meshPosSize = 2; // 2D (Billboard-Formen), für 3D Meshes: 3
GLsizei meshStride = sizeof(float) * 2;
size_t meshPosOffset = 0;
GLuint TextureID;
Vector2 SpriteCount;
Vector2 SpriteScale;
public:
static BasicTileMapShader* Instance();
static void Destroy();
static void Init(float width, float height);
BasicTileMapShader(std::vector<std::unique_ptr<ShaderPart>>&& parts);
~BasicTileMapShader();
void SetMesh(const void* verts, int vertCount, int stride, int floatCountPerVertex, int posOffsetBytes, GLenum primitive, const void* indices = nullptr, int indexCount = 0, GLenum indexType = GL_UNSIGNED_SHORT);
protected:
void OnEnable() const override;
void OnDisable() const override;
void OnFlush() override;
void OnDrawCall(int indexCount) override;
void OnSubmit(const Transformable& t, float*& target, TransformationStack& stack, void (*restartDrawcall)(IRenderer&), IRenderer& rnd) override;
};
} // namespace TSE::GLFW

View File

@@ -0,0 +1,60 @@
#pragma once
inline const char* vertTile = R"(
#version 330 core
layout(location = 0) in vec2 aPos;
layout(location = 1) in vec3 iTilePos;
layout(location = 2) in float iSpriteId;
uniform mat4 prMatrix;
uniform mat4 camMatrix;
uniform vec2 spriteCount;
uniform vec2 spriteScale;
out vec2 vUV;
flat out int vSpriteId;
void main()
{
vec3 local = vec3(aPos.x, aPos.y, 0);
vec2 baseUV = aPos + vec2(0.5);
vec3 tileSize = vec3(spriteScale.x, spriteScale.y, 1);
vec3 worldPos = (iTilePos * tileSize) + (local * tileSize);
gl_Position = prMatrix * camMatrix * vec4(worldPos.x, worldPos.y, worldPos.z, 1.0);
vUV = baseUV;
vSpriteId = int(iSpriteId + 0.5);
}
)";
inline const char* fragTile = R"(
#version 330 core
in vec2 vUV;
flat in int vSpriteId;
uniform sampler2D atlas;
uniform vec2 spriteCount;
out vec4 FragColor;
void main()
{
vec2 tileUVSize = 1.0 / spriteCount;
int cols = int(spriteCount.x);
int sx = vSpriteId % cols;
int sy = vSpriteId / cols;
vec2 atlasOffset = vec2(float(sx), float(sy)) * tileUVSize;
vec2 atlasUV = atlasOffset + (vUV * tileUVSize);
vec4 c = texture(atlas, atlasUV);
if (c.a < 0.01) discard;
FragColor = c;
}
)";

View File

@@ -3,6 +3,7 @@
#include "basicTextureShader.hpp" #include "basicTextureShader.hpp"
#include "ditheringShader.hpp" #include "ditheringShader.hpp"
#include "basicParticleShader.hpp" #include "basicParticleShader.hpp"
#include "basicTileMapShader.hpp"
#include "elements/ShaderRegistry.hpp" #include "elements/ShaderRegistry.hpp"
void TSE::GLFW::LoadBasicShaders(float width, float height) void TSE::GLFW::LoadBasicShaders(float width, float height)
@@ -11,10 +12,12 @@ void TSE::GLFW::LoadBasicShaders(float width, float height)
BasicTextureShader::Init(width, height); BasicTextureShader::Init(width, height);
DitheringShader::Init(width, height); DitheringShader::Init(width, height);
BasicParticleShader::Init(width, height); BasicParticleShader::Init(width, height);
BasicTileMapShader::Init(width, height);
ShaderRegistry::SetShader("Basic Unlit Shader", BasicShader::Instance()); ShaderRegistry::SetShader("Basic Unlit Shader", BasicShader::Instance());
ShaderRegistry::SetShader("Basic Unlit Texture Shader", BasicTextureShader::Instance()); ShaderRegistry::SetShader("Basic Unlit Texture Shader", BasicTextureShader::Instance());
ShaderRegistry::SetShader("Basic Unlit Dithering Shader", DitheringShader::Instance()); ShaderRegistry::SetShader("Basic Unlit Dithering Shader", DitheringShader::Instance());
ShaderRegistry::SetShader("Basic Unlit Particle Shader", BasicParticleShader::Instance()); ShaderRegistry::SetShader("Basic Unlit Particle Shader", BasicParticleShader::Instance());
ShaderRegistry::SetShader("Basic Unlit TileMap Shader", BasicTileMapShader::Instance());
} }
void TSE::GLFW::UnLoadBasicShaders() void TSE::GLFW::UnLoadBasicShaders()
@@ -23,8 +26,10 @@ void TSE::GLFW::UnLoadBasicShaders()
ShaderRegistry::RemoveShader("Basic Unlit Texture Shader"); ShaderRegistry::RemoveShader("Basic Unlit Texture Shader");
ShaderRegistry::RemoveShader("Basic Unlit Dithering Shader"); ShaderRegistry::RemoveShader("Basic Unlit Dithering Shader");
ShaderRegistry::RemoveShader("Basic Unlit Particle Shader"); ShaderRegistry::RemoveShader("Basic Unlit Particle Shader");
ShaderRegistry::RemoveShader("Basic Unlit TileMap Shader");
BasicShader::Destroy(); BasicShader::Destroy();
BasicTextureShader::Destroy(); BasicTextureShader::Destroy();
DitheringShader::Destroy(); DitheringShader::Destroy();
BasicParticleShader::Destroy(); BasicParticleShader::Destroy();
BasicTileMapShader::Destroy();
} }

View File

@@ -11,6 +11,9 @@ namespace TSE
/// @brief the epsilon used as min float value for comparisons in the engine /// @brief the epsilon used as min float value for comparisons in the engine
constexpr float TSE_EPSILON = 1e-6f; constexpr float TSE_EPSILON = 1e-6f;
/// @brief 32-bit golden ratio constant used for hash mixing
constexpr uint TSE_HASH_GOLDEN_RATIO_32 = 0x9e3779b9u;
/// @brief a simple degrees to radiant conversion function /// @brief a simple degrees to radiant conversion function
/// @param deg the degrees value /// @param deg the degrees value
/// @return the radiant value /// @return the radiant value

View File

@@ -1,6 +1,8 @@
#pragma once #pragma once
#include "Types.hpp" #include "Types.hpp"
#include "MathF.hpp"
#include <functional>
namespace TSE namespace TSE
{ {
@@ -135,3 +137,17 @@ namespace TSE
#pragma endregion methods #pragma endregion methods
}; };
} // namespace TSE } // namespace TSE
namespace std
{
template<>
struct hash<TSE::Vector2>
{
size_t operator()(const TSE::Vector2& v) const noexcept
{
size_t h1 = std::hash<float>{}(v.x);
size_t h2 = std::hash<float>{}(v.y);
return h1 ^ (h2 + TSE::TSE_HASH_GOLDEN_RATIO_32 + (h1 << 6) + (h1 >> 2));
}
};
}