1 #include "imgui_sdl.h"
2 
3 #include "SDL.h"
4 
5 #include "imgui.h"
6 
7 #include <map>
8 #include <list>
9 #include <cmath>
10 #include <array>
11 #include <vector>
12 #include <memory>
13 #include <iostream>
14 #include <algorithm>
15 #include <functional>
16 #include <unordered_map>
17 
18 namespace
19 {
20 	// make_unique is C++14
21 	template<typename T, typename... Args>
make_unique(Args &&...args)22 	std::unique_ptr<T> make_unique(Args&&... args)
23 	{
24 		return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
25 	}
26 
27 	struct Device* CurrentDevice = nullptr;
28 
29 	namespace TupleHash
30 	{
31 		template <typename T> struct Hash
32 		{
operator ()__anonae6ee72b0111::TupleHash::Hash33 			std::size_t operator()(const T& value) const
34 			{
35 				return std::hash<T>()(value);
36 			}
37 		};
38 
CombineHash(std::size_t & seed,const T & value)39 		template <typename T> void CombineHash(std::size_t& seed, const T& value)
40 		{
41 			seed ^= TupleHash::Hash<T>()(value) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
42 		}
43 
44 		template <typename Tuple, std::size_t Index = std::tuple_size<Tuple>::value - 1> struct Hasher
45 		{
Hash__anonae6ee72b0111::TupleHash::Hasher46 			static void Hash(std::size_t& seed, const Tuple& tuple)
47 			{
48 				Hasher<Tuple, Index - 1>::Hash(seed, tuple);
49 				CombineHash(seed, std::get<Index>(tuple));
50 			}
51 		};
52 
53 		template <typename Tuple> struct Hasher<Tuple, 0>
54 		{
Hash__anonae6ee72b0111::TupleHash::Hasher55 			static void Hash(std::size_t& seed, const Tuple& tuple)
56 			{
57 				CombineHash(seed, std::get<0>(tuple));
58 			}
59 		};
60 
61 		template <typename... T> struct Hash<std::tuple<T...>>
62 		{
operator ()__anonae6ee72b0111::TupleHash::Hash63 			std::size_t operator()(const std::tuple<T...>& value) const
64 			{
65 				std::size_t seed = 0;
66 				Hasher<std::tuple<T...>>::Hash(seed, value);
67 				return seed;
68 			}
69 		};
70 	}
71 
72 	template <typename Key, typename Value, std::size_t Size> class LRUCache
73 	{
74 	public:
Contains(const Key & key) const75 		bool Contains(const Key& key) const
76 		{
77 			return Container.find(key) != Container.end();
78 		}
79 
At(const Key & key)80 		const Value& At(const Key& key)
81 		{
82 			assert(Contains(key));
83 
84 			const auto location = Container.find(key);
85 			Order.splice(Order.begin(), Order, location->second);
86 			return location->second->second;
87 		}
88 
Insert(const Key & key,Value value)89 		void Insert(const Key& key, Value value)
90 		{
91 			const auto existingLocation = Container.find(key);
92 			if (existingLocation != Container.end())
93 			{
94 				Order.erase(existingLocation->second);
95 				Container.erase(existingLocation);
96 			}
97 
98 			Order.push_front(std::make_pair(key, std::move(value)));
99 			Container.insert(std::make_pair(key, Order.begin()));
100 
101 			Clean();
102 		}
103 
Reset()104 		void Reset()
105 		{
106 			Order.clear();
107 			Container.clear();
108 		}
109 	private:
Clean()110 		void Clean()
111 		{
112 			while (Container.size() > Size)
113 			{
114 				auto last = Order.end();
115 				last--;
116 				Container.erase(last->first);
117 				Order.pop_back();
118 			}
119 		}
120 
121 		std::list<std::pair<Key, Value>> Order;
122 		std::unordered_map<Key, decltype(Order.begin()), TupleHash::Hash<Key>> Container;
123 	};
124 
125 	struct Color
126 	{
127 		const float R, G, B, A;
128 
Color__anonae6ee72b0111::Color129 		explicit Color(uint32_t color)
130 			: R(((color >> 0) & 0xff) / 255.0f), G(((color >> 8) & 0xff) / 255.0f), B(((color >> 16) & 0xff) / 255.0f), A(((color >> 24) & 0xff) / 255.0f) { }
Color__anonae6ee72b0111::Color131 		Color(float r, float g, float b, float a) : R(r), G(g), B(b), A(a) { }
132 
operator *__anonae6ee72b0111::Color133 		Color operator*(const Color& c) const { return Color(R * c.R, G * c.G, B * c.B, A * c.A); }
operator *__anonae6ee72b0111::Color134 		Color operator*(float v) const { return Color(R * v, G * v, B * v, A * v); }
operator +__anonae6ee72b0111::Color135 		Color operator+(const Color& c) const { return Color(R + c.R, G + c.G, B + c.B, A + c.A); }
136 
ToInt__anonae6ee72b0111::Color137 		uint32_t ToInt() const
138 		{
139 			return	((static_cast<int>(R * 255) & 0xff) << 0)
140 				  | ((static_cast<int>(G * 255) & 0xff) << 8)
141 				  | ((static_cast<int>(B * 255) & 0xff) << 16)
142 				  | ((static_cast<int>(A * 255) & 0xff) << 24);
143 		}
144 
UseAsDrawColor__anonae6ee72b0111::Color145 		void UseAsDrawColor(SDL_Renderer* renderer) const
146 		{
147 			SDL_SetRenderDrawColor(renderer,
148 				static_cast<uint8_t>(R * 255),
149 				static_cast<uint8_t>(G * 255),
150 				static_cast<uint8_t>(B * 255),
151 				static_cast<uint8_t>(A * 255));
152 		}
153 	};
154 
155 	struct Device
156 	{
157 		SDL_Renderer* Renderer;
158 		bool CacheWasInvalidated = false;
159 
160 		struct ClipRect
161 		{
162 			int X, Y, Width, Height;
163 		} Clip;
164 
165 		struct TriangleCacheItem
166 		{
167 			SDL_Texture* Texture = nullptr;
168 			int Width = 0, Height = 0;
169 
~TriangleCacheItem__anonae6ee72b0111::Device::TriangleCacheItem170 			~TriangleCacheItem() { if (Texture) SDL_DestroyTexture(Texture); }
171 		};
172 
173 		// You can tweak these to values that you find that work the best.
174 		static constexpr std::size_t UniformColorTriangleCacheSize = 512;
175 		static constexpr std::size_t GenericTriangleCacheSize = 64;
176 
177 		// Uniform color is identified by its color and the coordinates of the edges.
178 		using UniformColorTriangleKey = std::tuple<uint32_t, int, int, int, int, int, int>;
179 		// The generic triangle cache unfortunately has to be basically a full representation of the triangle.
180 		// This includes the (offset) vertex positions, texture coordinates and vertex colors.
181 		using GenericTriangleVertexKey = std::tuple<int, int, double, double, uint32_t>;
182 		using GenericTriangleKey = std::tuple<GenericTriangleVertexKey, GenericTriangleVertexKey, GenericTriangleVertexKey>;
183 
184 		LRUCache<UniformColorTriangleKey, std::unique_ptr<TriangleCacheItem>, UniformColorTriangleCacheSize> UniformColorTriangleCache;
185 		LRUCache<GenericTriangleKey, std::unique_ptr<TriangleCacheItem>, GenericTriangleCacheSize> GenericTriangleCache;
186 
Device__anonae6ee72b0111::Device187 		Device(SDL_Renderer* renderer) : Renderer(renderer) { }
188 
SetClipRect__anonae6ee72b0111::Device189 		void SetClipRect(const ClipRect& rect)
190 		{
191 			Clip = rect;
192 			const SDL_Rect clip = { rect.X, rect.Y, rect.Width, rect.Height };
193 			SDL_RenderSetClipRect(Renderer, &clip);
194 		}
195 
EnableClip__anonae6ee72b0111::Device196 		void EnableClip() { SetClipRect(Clip); }
DisableClip__anonae6ee72b0111::Device197 		void DisableClip() { SDL_RenderSetClipRect(Renderer, nullptr); }
198 
SetAt__anonae6ee72b0111::Device199 		void SetAt(int x, int y, const Color& color)
200 		{
201 			color.UseAsDrawColor(Renderer);
202 			SDL_RenderDrawPoint(Renderer, x, y);
203 		}
204 
MakeTexture__anonae6ee72b0111::Device205 		SDL_Texture* MakeTexture(int width, int height)
206 		{
207 			SDL_Texture* texture = SDL_CreateTexture(Renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_TARGET, width, height);
208 			SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
209 			return texture;
210 		}
211 
UseAsRenderTarget__anonae6ee72b0111::Device212 		void UseAsRenderTarget(SDL_Texture* texture)
213 		{
214 			SDL_SetRenderTarget(Renderer, texture);
215 			if (texture)
216 			{
217 				SDL_SetRenderDrawColor(Renderer, 0, 0, 0, 0);
218 				SDL_RenderClear(Renderer);
219 			}
220 		}
221 	};
222 
223 	struct Texture
224 	{
225 		SDL_Surface* Surface;
226 		SDL_Texture* Source;
227 
~Texture__anonae6ee72b0111::Texture228 		~Texture()
229 		{
230 			SDL_FreeSurface(Surface);
231 			SDL_DestroyTexture(Source);
232 		}
233 
Sample__anonae6ee72b0111::Texture234 		Color Sample(float u, float v) const
235 		{
236 			const int x = static_cast<int>(std::round(u * (Surface->w - 1) + 0.5f));
237 			const int y = static_cast<int>(std::round(v * (Surface->h - 1) + 0.5f));
238 
239 			const int location = y * Surface->w + x;
240 			assert(location < Surface->w * Surface->h);
241 
242 			return Color(static_cast<uint32_t*>(Surface->pixels)[location]);
243 		}
244 	};
245 
246 	template <typename T> class InterpolatedFactorEquation
247 	{
248 	public:
InterpolatedFactorEquation(const T & value0,const T & value1,const T & value2,const ImVec2 & v0,const ImVec2 & v1,const ImVec2 & v2)249 		InterpolatedFactorEquation(const T& value0, const T& value1, const T& value2, const ImVec2& v0, const ImVec2& v1, const ImVec2& v2)
250 			: Value0(value0), Value1(value1), Value2(value2), V0(v0), V1(v1), V2(v2),
251 			Divisor((V1.y - V2.y) * (V0.x - V2.x) + (V2.x - V1.x) * (V0.y - V2.y)) { }
252 
Evaluate(float x,float y) const253 		T Evaluate(float x, float y) const
254 		{
255 			const float w1 = ((V1.y - V2.y) * (x - V2.x) + (V2.x - V1.x) * (y - V2.y)) / Divisor;
256 			const float w2 = ((V2.y - V0.y) * (x - V2.x) + (V0.x - V2.x) * (y - V2.y)) / Divisor;
257 			const float w3 = 1.0f - w1 - w2;
258 
259 			return static_cast<T>((Value0 * w1) + (Value1 * w2) + (Value2 * w3));
260 		}
261 	private:
262 		const T Value0;
263 		const T Value1;
264 		const T Value2;
265 
266 		const ImVec2& V0;
267 		const ImVec2& V1;
268 		const ImVec2& V2;
269 
270 		const float Divisor;
271 	};
272 
273 	struct Rect
274 	{
275 		float MinX, MinY, MaxX, MaxY;
276 		float MinU, MinV, MaxU, MaxV;
277 
IsOnExtreme__anonae6ee72b0111::Rect278 		bool IsOnExtreme(const ImVec2& point) const
279 		{
280 			return (point.x == MinX || point.x == MaxX) && (point.y == MinY || point.y == MaxY);
281 		}
282 
UsesOnlyColor__anonae6ee72b0111::Rect283 		bool UsesOnlyColor() const
284 		{
285 			const ImVec2& whitePixel = ImGui::GetIO().Fonts->TexUvWhitePixel;
286 
287 			return MinU == MaxU && MinU == whitePixel.x && MinV == MaxV && MaxV == whitePixel.y;
288 		}
289 
CalculateBoundingBox__anonae6ee72b0111::Rect290 		static Rect CalculateBoundingBox(const ImDrawVert& v0, const ImDrawVert& v1, const ImDrawVert& v2)
291 		{
292 			return Rect{
293 				std::min({ v0.pos.x, v1.pos.x, v2.pos.x }),
294 				std::min({ v0.pos.y, v1.pos.y, v2.pos.y }),
295 				std::max({ v0.pos.x, v1.pos.x, v2.pos.x }),
296 				std::max({ v0.pos.y, v1.pos.y, v2.pos.y }),
297 				std::min({ v0.uv.x, v1.uv.x, v2.uv.x }),
298 				std::min({ v0.uv.y, v1.uv.y, v2.uv.y }),
299 				std::max({ v0.uv.x, v1.uv.x, v2.uv.x }),
300 				std::max({ v0.uv.y, v1.uv.y, v2.uv.y })
301 			};
302 		}
303 	};
304 
305 	struct FixedPointTriangleRenderInfo
306 	{
307 		int X1, X2, X3, Y1, Y2, Y3;
308 		int MinX, MaxX, MinY, MaxY;
309 
CalculateFixedPointTriangleInfo__anonae6ee72b0111::FixedPointTriangleRenderInfo310 		static FixedPointTriangleRenderInfo CalculateFixedPointTriangleInfo(const ImVec2& v1, const ImVec2& v2, const ImVec2& v3)
311 		{
312 			static constexpr float scale = 16.0f;
313 
314 			const int x1 = static_cast<int>(std::round(v1.x * scale));
315 			const int x2 = static_cast<int>(std::round(v2.x * scale));
316 			const int x3 = static_cast<int>(std::round(v3.x * scale));
317 
318 			const int y1 = static_cast<int>(std::round(v1.y * scale));
319 			const int y2 = static_cast<int>(std::round(v2.y * scale));
320 			const int y3 = static_cast<int>(std::round(v3.y * scale));
321 
322 			int minX = (std::min({ x1, x2, x3 }) + 0xF) >> 4;
323 			int maxX = (std::max({ x1, x2, x3 }) + 0xF) >> 4;
324 			int minY = (std::min({ y1, y2, y3 }) + 0xF) >> 4;
325 			int maxY = (std::max({ y1, y2, y3 }) + 0xF) >> 4;
326 
327 			return FixedPointTriangleRenderInfo{ x1, x2, x3, y1, y2, y3, minX, maxX, minY, maxY };
328 		}
329 	};
330 
DrawTriangleWithColorFunction(const FixedPointTriangleRenderInfo & renderInfo,const std::function<Color (float x,float y)> & colorFunction,Device::TriangleCacheItem * cacheItem)331 	void DrawTriangleWithColorFunction(const FixedPointTriangleRenderInfo& renderInfo, const std::function<Color(float x, float y)>& colorFunction, Device::TriangleCacheItem* cacheItem)
332 	{
333 		// Implementation source: https://web.archive.org/web/20171128164608/http://forum.devmaster.net/t/advanced-rasterization/6145.
334 		// This is a fixed point implementation that rounds to top-left.
335 
336 		const int deltaX12 = renderInfo.X1 - renderInfo.X2;
337 		const int deltaX23 = renderInfo.X2 - renderInfo.X3;
338 		const int deltaX31 = renderInfo.X3 - renderInfo.X1;
339 
340 		const int deltaY12 = renderInfo.Y1 - renderInfo.Y2;
341 		const int deltaY23 = renderInfo.Y2 - renderInfo.Y3;
342 		const int deltaY31 = renderInfo.Y3 - renderInfo.Y1;
343 
344 		const int fixedDeltaX12 = deltaX12 << 4;
345 		const int fixedDeltaX23 = deltaX23 << 4;
346 		const int fixedDeltaX31 = deltaX31 << 4;
347 
348 		const int fixedDeltaY12 = deltaY12 << 4;
349 		const int fixedDeltaY23 = deltaY23 << 4;
350 		const int fixedDeltaY31 = deltaY31 << 4;
351 
352 		const int width = renderInfo.MaxX - renderInfo.MinX;
353 		const int height = renderInfo.MaxY - renderInfo.MinY;
354 		if (width == 0 || height == 0) return;
355 
356 		int c1 = deltaY12 * renderInfo.X1 - deltaX12 * renderInfo.Y1;
357 		int c2 = deltaY23 * renderInfo.X2 - deltaX23 * renderInfo.Y2;
358 		int c3 = deltaY31 * renderInfo.X3 - deltaX31 * renderInfo.Y3;
359 
360 		if (deltaY12 < 0 || (deltaY12 == 0 && deltaX12 > 0)) c1++;
361 		if (deltaY23 < 0 || (deltaY23 == 0 && deltaX23 > 0)) c2++;
362 		if (deltaY31 < 0 || (deltaY31 == 0 && deltaX31 > 0)) c3++;
363 
364 		int edgeStart1 = c1 + deltaX12 * (renderInfo.MinY << 4) - deltaY12 * (renderInfo.MinX << 4);
365 		int edgeStart2 = c2 + deltaX23 * (renderInfo.MinY << 4) - deltaY23 * (renderInfo.MinX << 4);
366 		int edgeStart3 = c3 + deltaX31 * (renderInfo.MinY << 4) - deltaY31 * (renderInfo.MinX << 4);
367 
368 		SDL_Texture* cache = CurrentDevice->MakeTexture(width, height);
369 		CurrentDevice->DisableClip();
370 		CurrentDevice->UseAsRenderTarget(cache);
371 
372 		for (int y = renderInfo.MinY; y < renderInfo.MaxY; y++)
373 		{
374 			int edge1 = edgeStart1;
375 			int edge2 = edgeStart2;
376 			int edge3 = edgeStart3;
377 
378 			for (int x = renderInfo.MinX; x < renderInfo.MaxX; x++)
379 			{
380 				if (edge1 > 0 && edge2 > 0 && edge3 > 0)
381 				{
382 					CurrentDevice->SetAt(x - renderInfo.MinX, y - renderInfo.MinY, colorFunction(x + 0.5f, y + 0.5f));
383 				}
384 
385 				edge1 -= fixedDeltaY12;
386 				edge2 -= fixedDeltaY23;
387 				edge3 -= fixedDeltaY31;
388 			}
389 
390 			edgeStart1 += fixedDeltaX12;
391 			edgeStart2 += fixedDeltaX23;
392 			edgeStart3 += fixedDeltaX31;
393 		}
394 
395 		CurrentDevice->UseAsRenderTarget(nullptr);
396 		CurrentDevice->EnableClip();
397 
398 		cacheItem->Texture = cache;
399 		cacheItem->Width = width;
400 		cacheItem->Height = height;
401 	}
402 
DrawCachedTriangle(const Device::TriangleCacheItem & triangle,const FixedPointTriangleRenderInfo & renderInfo)403 	void DrawCachedTriangle(const Device::TriangleCacheItem& triangle, const FixedPointTriangleRenderInfo& renderInfo)
404 	{
405 		const SDL_Rect destination = { renderInfo.MinX, renderInfo.MinY, triangle.Width, triangle.Height };
406 		SDL_RenderCopy(CurrentDevice->Renderer, triangle.Texture, nullptr, &destination);
407 	}
408 
DrawTriangle(const ImDrawVert & v1,const ImDrawVert & v2,const ImDrawVert & v3,const Texture * texture)409 	void DrawTriangle(const ImDrawVert& v1, const ImDrawVert& v2, const ImDrawVert& v3, const Texture* texture)
410 	{
411 		// The naming inconsistency in the parameters is intentional. The fixed point algorithm wants the vertices in a counter clockwise order.
412 		const auto& renderInfo = FixedPointTriangleRenderInfo::CalculateFixedPointTriangleInfo(v3.pos, v2.pos, v1.pos);
413 
414 		// First we check if there is a cached version of this triangle already waiting for us. If so, we can just do a super fast texture copy.
415 
416 		const auto key = std::make_tuple(
417 			std::make_tuple(static_cast<int>(std::round(v1.pos.x)) - renderInfo.MinX, static_cast<int>(std::round(v1.pos.y)) - renderInfo.MinY, v1.uv.x, v1.uv.y, v1.col),
418 			std::make_tuple(static_cast<int>(std::round(v2.pos.x)) - renderInfo.MinX, static_cast<int>(std::round(v2.pos.y)) - renderInfo.MinY, v2.uv.x, v2.uv.y, v2.col),
419 			std::make_tuple(static_cast<int>(std::round(v3.pos.x)) - renderInfo.MinX, static_cast<int>(std::round(v3.pos.y)) - renderInfo.MinY, v3.uv.x, v3.uv.y, v3.col));
420 
421 		if (CurrentDevice->GenericTriangleCache.Contains(key))
422 		{
423 			const auto& cached = CurrentDevice->GenericTriangleCache.At(key);
424 			DrawCachedTriangle(*cached, renderInfo);
425 
426 			return;
427 		}
428 
429 		const InterpolatedFactorEquation<float> textureU(v1.uv.x, v2.uv.x, v3.uv.x, v1.pos, v2.pos, v3.pos);
430 		const InterpolatedFactorEquation<float> textureV(v1.uv.y, v2.uv.y, v3.uv.y, v1.pos, v2.pos, v3.pos);
431 
432 		const InterpolatedFactorEquation<Color> shadeColor(Color(v1.col), Color(v2.col), Color(v3.col), v1.pos, v2.pos, v3.pos);
433 
434 		auto cached = make_unique<Device::TriangleCacheItem>();
435 		DrawTriangleWithColorFunction(renderInfo, [&](float x, float y) {
436 			const float u = textureU.Evaluate(x, y);
437 			const float v = textureV.Evaluate(x, y);
438 			const Color sampled = texture->Sample(u, v);
439 			const Color shade = shadeColor.Evaluate(x, y);
440 
441 			return sampled * shade;
442 		}, cached.get());
443 
444 		if (!cached->Texture) return;
445 
446 		const SDL_Rect destination = { renderInfo.MinX, renderInfo.MinY, cached->Width, cached->Height };
447 		SDL_RenderCopy(CurrentDevice->Renderer, cached->Texture, nullptr, &destination);
448 
449 		CurrentDevice->GenericTriangleCache.Insert(key, std::move(cached));
450 	}
451 
DrawUniformColorTriangle(const ImDrawVert & v1,const ImDrawVert & v2,const ImDrawVert & v3)452 	void DrawUniformColorTriangle(const ImDrawVert& v1, const ImDrawVert& v2, const ImDrawVert& v3)
453 	{
454 		const Color color(v1.col);
455 
456 		// The naming inconsistency in the parameters is intentional. The fixed point algorithm wants the vertices in a counter clockwise order.
457 		const auto& renderInfo = FixedPointTriangleRenderInfo::CalculateFixedPointTriangleInfo(v3.pos, v2.pos, v1.pos);
458 
459 		const auto key =std::make_tuple(v1.col,
460 			static_cast<int>(std::round(v1.pos.x)) - renderInfo.MinX, static_cast<int>(std::round(v1.pos.y)) - renderInfo.MinY,
461 			static_cast<int>(std::round(v2.pos.x)) - renderInfo.MinX, static_cast<int>(std::round(v2.pos.y)) - renderInfo.MinY,
462 			static_cast<int>(std::round(v3.pos.x)) - renderInfo.MinX, static_cast<int>(std::round(v3.pos.y)) - renderInfo.MinY);
463 		if (CurrentDevice->UniformColorTriangleCache.Contains(key))
464 		{
465 			const auto& cached = CurrentDevice->UniformColorTriangleCache.At(key);
466 			DrawCachedTriangle(*cached, renderInfo);
467 
468 			return;
469 		}
470 
471 		auto cached = make_unique<Device::TriangleCacheItem>();
472 		DrawTriangleWithColorFunction(renderInfo, [&color](float, float) { return color; }, cached.get());
473 
474 		if (!cached->Texture) return;
475 
476 		const SDL_Rect destination = { renderInfo.MinX, renderInfo.MinY, cached->Width, cached->Height };
477 		SDL_RenderCopy(CurrentDevice->Renderer, cached->Texture, nullptr, &destination);
478 
479 		CurrentDevice->UniformColorTriangleCache.Insert(key, std::move(cached));
480 	}
481 
DrawRectangle(const Rect & bounding,SDL_Texture * texture,int textureWidth,int textureHeight,const Color & color,bool doHorizontalFlip,bool doVerticalFlip)482 	void DrawRectangle(const Rect& bounding, SDL_Texture* texture, int textureWidth, int textureHeight, const Color& color, bool doHorizontalFlip, bool doVerticalFlip)
483 	{
484 		// We are safe to assume uniform color here, because the caller checks it and and uses the triangle renderer to render those.
485 
486 		const SDL_Rect destination = {
487 			static_cast<int>(bounding.MinX),
488 			static_cast<int>(bounding.MinY),
489 			static_cast<int>(bounding.MaxX - bounding.MinX),
490 			static_cast<int>(bounding.MaxY - bounding.MinY)
491 		};
492 
493 		// If the area isn't textured, we can just draw a rectangle with the correct color.
494 		if (bounding.UsesOnlyColor())
495 		{
496 			color.UseAsDrawColor(CurrentDevice->Renderer);
497 			SDL_RenderFillRect(CurrentDevice->Renderer, &destination);
498 		}
499 		else
500 		{
501 			// We can now just calculate the correct source rectangle and draw it.
502 
503 			const SDL_Rect source = {
504 				static_cast<int>(bounding.MinU * textureWidth),
505 				static_cast<int>(bounding.MinV * textureHeight),
506 				static_cast<int>((bounding.MaxU - bounding.MinU) * textureWidth),
507 				static_cast<int>((bounding.MaxV - bounding.MinV) * textureHeight)
508 			};
509 
510 			const SDL_RendererFlip flip = static_cast<SDL_RendererFlip>((doHorizontalFlip ? SDL_FLIP_HORIZONTAL : 0) | (doVerticalFlip ? SDL_FLIP_VERTICAL : 0));
511 
512 			SDL_SetTextureColorMod(texture, static_cast<uint8_t>(color.R * 255), static_cast<uint8_t>(color.G * 255), static_cast<uint8_t>(color.B * 255));
513 			SDL_RenderCopyEx(CurrentDevice->Renderer, texture, &source, &destination, 0.0, nullptr, flip);
514 		}
515 	}
516 
DrawRectangle(const Rect & bounding,const Texture * texture,const Color & color,bool doHorizontalFlip,bool doVerticalFlip)517 	void DrawRectangle(const Rect& bounding, const Texture* texture, const Color& color, bool doHorizontalFlip, bool doVerticalFlip)
518 	{
519 		DrawRectangle(bounding, texture->Source, texture->Surface->w, texture->Surface->h, color, doHorizontalFlip, doVerticalFlip);
520 	}
521 
DrawRectangle(const Rect & bounding,SDL_Texture * texture,const Color & color,bool doHorizontalFlip,bool doVerticalFlip)522 	void DrawRectangle(const Rect& bounding, SDL_Texture* texture, const Color& color, bool doHorizontalFlip, bool doVerticalFlip)
523 	{
524 		int width, height;
525 		SDL_QueryTexture(texture, nullptr, nullptr, &width, &height);
526 		DrawRectangle(bounding, texture, width, height, color, doHorizontalFlip, doVerticalFlip);
527 	}
528 }
529 
530 namespace ImGuiSDL
531 {
ImGuiSDLEventWatch(void * userdata,SDL_Event * event)532 	static int ImGuiSDLEventWatch(void* userdata, SDL_Event* event) {
533 		if (event->type == SDL_RENDER_TARGETS_RESET) {
534 			// Device lost event, applies to DirectX and some mobile devices.
535 			CurrentDevice->CacheWasInvalidated = true;
536 		}
537 		return 0;
538 	}
539 
Initialize(SDL_Renderer * renderer,int windowWidth,int windowHeight)540 	void Initialize(SDL_Renderer* renderer, int windowWidth, int windowHeight)
541 	{
542 		ImGuiIO& io = ImGui::GetIO();
543 		io.DisplaySize.x = static_cast<float>(windowWidth);
544 		io.DisplaySize.y = static_cast<float>(windowHeight);
545 
546 		ImGui::GetStyle().WindowRounding = 0.0f;
547 		ImGui::GetStyle().AntiAliasedFill = false;
548 		ImGui::GetStyle().AntiAliasedLines = false;
549 		ImGui::GetStyle().ChildRounding = 0.0f;
550 		ImGui::GetStyle().PopupRounding = 0.0f;
551 		ImGui::GetStyle().FrameRounding = 0.0f;
552 		ImGui::GetStyle().ScrollbarRounding = 0.0f;
553 		ImGui::GetStyle().GrabRounding = 0.0f;
554 		ImGui::GetStyle().TabRounding = 0.0f;
555 
556 		// Loads the font texture.
557 		unsigned char* pixels;
558 		int width, height;
559 		io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
560 		static constexpr uint32_t rmask = 0x000000ff, gmask = 0x0000ff00, bmask = 0x00ff0000, amask = 0xff000000;
561 		SDL_Surface* surface = SDL_CreateRGBSurfaceFrom(pixels, width, height, 32, 4 * width, rmask, gmask, bmask, amask);
562 
563 		Texture* texture = new Texture();
564 		texture->Surface = surface;
565 		texture->Source = SDL_CreateTextureFromSurface(renderer, surface);
566 		io.Fonts->TexID = (void*)texture;
567 
568 		CurrentDevice = new Device(renderer);
569 		SDL_AddEventWatch(ImGuiSDLEventWatch, nullptr);
570 	}
571 
Deinitialize()572 	void Deinitialize()
573 	{
574 		// Frees up the memory of the font texture.
575 		ImGuiIO& io = ImGui::GetIO();
576 		Texture* texture = static_cast<Texture*>(io.Fonts->TexID);
577 		delete texture;
578 
579 		delete CurrentDevice;
580 		SDL_DelEventWatch(ImGuiSDLEventWatch, nullptr);
581 	}
582 
Render(ImDrawData * drawData)583 	void Render(ImDrawData* drawData)
584 	{
585 		if (CurrentDevice->CacheWasInvalidated) {
586 			CurrentDevice->CacheWasInvalidated = false;
587 			CurrentDevice->GenericTriangleCache.Reset();
588 			CurrentDevice->UniformColorTriangleCache.Reset();
589 		}
590 
591 		SDL_BlendMode blendMode;
592 		SDL_GetRenderDrawBlendMode(CurrentDevice->Renderer, &blendMode);
593 		SDL_SetRenderDrawBlendMode(CurrentDevice->Renderer, SDL_BLENDMODE_BLEND);
594 
595 		Uint8 initialR, initialG, initialB, initialA;
596 		SDL_GetRenderDrawColor(CurrentDevice->Renderer, &initialR, &initialG, &initialB, &initialA);
597 
598 		SDL_bool initialClipEnabled = SDL_RenderIsClipEnabled(CurrentDevice->Renderer);
599 		SDL_Rect initialClipRect;
600 		SDL_RenderGetClipRect(CurrentDevice->Renderer, &initialClipRect);
601 
602 		SDL_Texture* initialRenderTarget = SDL_GetRenderTarget(CurrentDevice->Renderer);
603 
604 		ImGuiIO& io = ImGui::GetIO();
605 
606 		for (int n = 0; n < drawData->CmdListsCount; n++)
607 		{
608 			auto commandList = drawData->CmdLists[n];
609 			auto vertexBuffer = commandList->VtxBuffer;
610 			auto indexBuffer = commandList->IdxBuffer.Data;
611 
612 			for (int cmd_i = 0; cmd_i < commandList->CmdBuffer.Size; cmd_i++)
613 			{
614 				const ImDrawCmd* drawCommand = &commandList->CmdBuffer[cmd_i];
615 
616 				const Device::ClipRect clipRect = {
617 					static_cast<int>(drawCommand->ClipRect.x),
618 					static_cast<int>(drawCommand->ClipRect.y),
619 					static_cast<int>(drawCommand->ClipRect.z - drawCommand->ClipRect.x),
620 					static_cast<int>(drawCommand->ClipRect.w - drawCommand->ClipRect.y)
621 				};
622 				CurrentDevice->SetClipRect(clipRect);
623 
624 				if (drawCommand->UserCallback)
625 				{
626 					drawCommand->UserCallback(commandList, drawCommand);
627 				}
628 				else
629 				{
630 					const bool isWrappedTexture = drawCommand->TextureId == io.Fonts->TexID;
631 
632 					// Loops over triangles.
633 					for (unsigned int i = 0; i + 3 <= drawCommand->ElemCount; i += 3)
634 					{
635 						const ImDrawVert& v0 = vertexBuffer[indexBuffer[i + 0]];
636 						const ImDrawVert& v1 = vertexBuffer[indexBuffer[i + 1]];
637 						const ImDrawVert& v2 = vertexBuffer[indexBuffer[i + 2]];
638 
639 						const Rect& bounding = Rect::CalculateBoundingBox(v0, v1, v2);
640 
641 						const bool isTriangleUniformColor = v0.col == v1.col && v1.col == v2.col;
642 						const bool doesTriangleUseOnlyColor = bounding.UsesOnlyColor();
643 
644 						// Actually, since we render a whole bunch of rectangles, we try to first detect those, and render them more efficiently.
645 						// How are rectangles detected? It's actually pretty simple: If all 6 vertices lie on the extremes of the bounding box,
646 						// it's a rectangle.
647 						if (i + 6 <= drawCommand->ElemCount)
648 						{
649 							const ImDrawVert& v3 = vertexBuffer[indexBuffer[i + 3]];
650 							const ImDrawVert& v4 = vertexBuffer[indexBuffer[i + 4]];
651 							const ImDrawVert& v5 = vertexBuffer[indexBuffer[i + 5]];
652 
653 							const bool isUniformColor = isTriangleUniformColor && v2.col == v3.col && v3.col == v4.col && v4.col == v5.col;
654 
655 							if (isUniformColor
656 							&& bounding.IsOnExtreme(v0.pos)
657 							&& bounding.IsOnExtreme(v1.pos)
658 							&& bounding.IsOnExtreme(v2.pos)
659 							&& bounding.IsOnExtreme(v3.pos)
660 							&& bounding.IsOnExtreme(v4.pos)
661 							&& bounding.IsOnExtreme(v5.pos))
662 							{
663 								// ImGui gives the triangles in a nice order: the first vertex happens to be the topleft corner of our rectangle.
664 								// We need to check for the orientation of the texture, as I believe in theory ImGui could feed us a flipped texture,
665 								// so that the larger texture coordinates are at topleft instead of bottomright.
666 								// We don't consider equal texture coordinates to require a flip, as then the rectangle is mostlikely simply a colored rectangle.
667 								const bool doHorizontalFlip = v2.uv.x < v0.uv.x;
668 								const bool doVerticalFlip = v2.uv.x < v0.uv.x;
669 
670 								if (isWrappedTexture)
671 								{
672 									DrawRectangle(bounding, static_cast<const Texture*>(drawCommand->TextureId), Color(v0.col), doHorizontalFlip, doVerticalFlip);
673 								}
674 								else
675 								{
676 									DrawRectangle(bounding, static_cast<SDL_Texture*>(drawCommand->TextureId), Color(v0.col), doHorizontalFlip, doVerticalFlip);
677 								}
678 
679 								i += 3;  // Additional increment to account for the extra 3 vertices we consumed.
680 								continue;
681 							}
682 						}
683 
684 						if (isTriangleUniformColor && doesTriangleUseOnlyColor)
685 						{
686 							DrawUniformColorTriangle(v0, v1, v2);
687 						}
688 						else
689 						{
690 							// Currently we assume that any non rectangular texture samples the font texture. Dunno if that's what actually happens, but it seems to work.
691 							assert(isWrappedTexture);
692 							DrawTriangle(v0, v1, v2, static_cast<const Texture*>(drawCommand->TextureId));
693 						}
694 					}
695 				}
696 
697 				indexBuffer += drawCommand->ElemCount;
698 			}
699 		}
700 
701 		CurrentDevice->DisableClip();
702 
703 		SDL_SetRenderTarget(CurrentDevice->Renderer, initialRenderTarget);
704 
705 		SDL_RenderSetClipRect(CurrentDevice->Renderer, initialClipEnabled ? &initialClipRect : nullptr);
706 
707 		SDL_SetRenderDrawColor(CurrentDevice->Renderer,
708 			initialR, initialG, initialB, initialA);
709 
710 		SDL_SetRenderDrawBlendMode(CurrentDevice->Renderer, blendMode);
711 	}
712 }
713