1 /***************************************************************************
2  *      Mechanized Assault and Exploration Reloaded Projectfile            *
3  *                                                                         *
4  *   This program is free software; you can redistribute it and/or modify  *
5  *   it under the terms of the GNU General Public License as published by  *
6  *   the Free Software Foundation; either version 2 of the License, or     *
7  *   (at your option) any later version.                                   *
8  *                                                                         *
9  *   This program is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU General Public License for more details.                          *
13  *                                                                         *
14  *   You should have received a copy of the GNU General Public License     *
15  *   along with this program; if not, write to the                         *
16  *   Free Software Foundation, Inc.,                                       *
17  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
18  ***************************************************************************/
19 
20 #include <algorithm>
21 #include <vector>
22 #include <cassert>
23 #include <ctime>
24 #include <functional>
25 
26 #include <SDL.h>
27 
28 #include "main.h"
29 #include "video.h"
30 #include "maxrversion.h"
31 #include "defines.h"
32 #include "utility/log.h"
33 #include "pcx.h"
34 #include "unifonts.h"
35 #include "utility/files.h"
36 #include "input/keyboard/keyboard.h"
37 
38 cVideo Video;
39 
40 /*static*/ SDL_Surface* cVideo::buffer = nullptr; // the screen buffer
41 
42 #define COLOURDEPTH 32
43 /** Minimum video mode resultion we need */
44 #define MINWIDTH 640
45 #define MINHEIGHT 480
46 
cVideo()47 cVideo::cVideo() :
48 	sdlWindow (nullptr),
49 	sdlRenderer (nullptr),
50 	sdlTexture (nullptr),
51 	resolutionX (MINWIDTH),
52 	resolutionY (MINHEIGHT),
53 	displayIndex (MINWIDTH),
54 	colorDepth (COLOURDEPTH),
55 	windowMode (false)
56 {
57 	using namespace std::placeholders;
58 
59 	signalConnectionManager.connect (cKeyboard::getInstance().keyPressed, std::bind (&cVideo::keyPressed, this, _1, _2));
60 }
61 
~cVideo()62 cVideo::~cVideo()
63 {
64 	SDL_FreeSurface (cVideo::buffer);
65 	SDL_DestroyTexture (sdlTexture);
66 	SDL_DestroyRenderer (sdlRenderer);
67 	SDL_DestroyWindow (sdlWindow);
68 }
69 
clearMemory()70 void cVideo::clearMemory()
71 {
72 	SDL_FreeSurface (cVideo::buffer);
73 	SDL_DestroyTexture (sdlTexture);
74 	SDL_DestroyRenderer (sdlRenderer);
75 	SDL_DestroyWindow (sdlWindow);
76 	cVideo::buffer = nullptr;
77 	sdlTexture = nullptr;
78 	sdlRenderer = nullptr;
79 	sdlWindow = nullptr;
80 }
81 
init()82 void cVideo::init()
83 {
84 	const auto title = PACKAGE_NAME " " PACKAGE_VERSION " " PACKAGE_REV " ";
85 
86 	sdlWindow = SDL_CreateWindow (title,
87 								  SDL_WINDOWPOS_CENTERED_DISPLAY (getDisplayIndex()), SDL_WINDOWPOS_CENTERED_DISPLAY (getDisplayIndex()),
88 								  MINWIDTH, MINHEIGHT,
89 								  SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL);
90 
91 	{
92 		auto icon = AutoSurface (SDL_LoadBMP (MAXR_ICON));
93 		SDL_SetColorKey (icon.get(), 1, 0xFF00FF);
94 		SDL_SetWindowIcon (sdlWindow, icon.get());
95 	}
96 
97 	sdlRenderer = SDL_CreateRenderer (sdlWindow, -1, 0);
98 
99 	// make the scaled rendering look smoother.
100 	SDL_SetHint (SDL_HINT_RENDER_SCALE_QUALITY, "linear");
101 
102 	detectResolutions();
103 }
104 
showSplashScreen()105 void cVideo::showSplashScreen()
106 {
107 	AutoSurface splash (LoadPCX (SPLASH_BACKGROUND));
108 
109 	SDL_SetWindowBordered (sdlWindow, SDL_FALSE);
110 	SDL_SetWindowSize (sdlWindow, splash->w, splash->h);
111 	SDL_SetWindowPosition (sdlWindow, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
112 	SDL_SetWindowFullscreen (sdlWindow, 0);
113 
114 	initializeBuffer (splash->w, splash->h);
115 
116 	SDL_BlitSurface (splash.get(), nullptr, buffer, nullptr);
117 
118 	draw();
119 }
120 
prepareGameScreen()121 void cVideo::prepareGameScreen()
122 {
123 	SDL_SetWindowBordered (sdlWindow, SDL_TRUE);
124 	SDL_SetWindowSize (sdlWindow, getResolutionX(), getResolutionY());
125 	SDL_SetWindowPosition (sdlWindow, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
126 	SDL_SetWindowFullscreen (sdlWindow, getWindowMode() ? 0 : SDL_WINDOW_FULLSCREEN);
127 
128 	initializeBuffer (getResolutionX(), getResolutionY());
129 
130 	draw();
131 }
132 
initializeBuffer(int width,int height)133 void cVideo::initializeBuffer (int width, int height)
134 {
135 	if (buffer) SDL_FreeSurface (buffer);
136 	buffer = SDL_CreateRGBSurface (0, width, height, getColDepth(), 0, 0, 0, 0);
137 
138 	if (font != nullptr) font->setTargetSurface (buffer);
139 
140 	if (sdlTexture) SDL_DestroyTexture (sdlTexture);
141 	sdlTexture = SDL_CreateTexture (sdlRenderer,
142 									SDL_PIXELFORMAT_ARGB8888,
143 									SDL_TEXTUREACCESS_STREAMING,
144 									width, height);
145 
146 	SDL_RenderSetLogicalSize (sdlRenderer, width, height);
147 }
148 
setResolution(int iWidth,int iHeight,bool bApply)149 void cVideo::setResolution (int iWidth, int iHeight, bool bApply)
150 {
151 	resolutionX = iWidth;
152 	resolutionY = iHeight;
153 
154 	// validate only if we should apply
155 	// because the resolution may be set during reading of settings
156 	// and at this point does no SDL context exist yet
157 	if (bApply)
158 	{
159 		// BEGIN SANITY CHECK SCREEN RES
160 
161 		if (validateResolution (iWidth, iHeight) >= 0)
162 		{
163 			Log.write ("cVideo:  => Found requested video mode " + iToStr (iWidth) + "x" + iToStr (iHeight) + " :)", cLog::eLOG_TYPE_INFO);
164 		}
165 		else
166 		{
167 			Log.write ("cVideo:  => Couldn't find requested video mode " + iToStr (iWidth) + "x" + iToStr (iHeight) + " :(", cLog::eLOG_TYPE_WARNING);
168 			if (haveMinMode())
169 			{
170 				Log.write ("cVideo:  => Edit your config and try default video mode " + iToStr (Video.getMinW()) + "x" + iToStr (Video.getMinH()) + " if I crash now!", cLog::eLOG_TYPE_WARNING);
171 			}
172 			else
173 			{
174 				Log.write ("cVideo:  => Couldn't even find my minimal video mode " + iToStr (Video.getMinW()) + "x" + iToStr (Video.getMinH()) + " - panic! ;(", cLog::eLOG_TYPE_WARNING);
175 			}
176 		}
177 		// END SANITY CHECK SCREEN RES
178 
179 		applyResolution();
180 
181 		resolutionChanged();
182 	}
183 	else
184 	{
185 		Log.write ("cVideo: Resolution set to " + iToStr (iWidth) + "x" + iToStr (iHeight) + " but was not applied yet", cLog::eLOG_TYPE_INFO);
186 	}
187 }
188 
setColDepth(unsigned iDepth)189 int cVideo::setColDepth (unsigned iDepth)
190 {
191 	// TODO: Implement other colourdepths beside 32 & add sanity checks.
192 	//       validate new color depth
193 	if (iDepth != 32)
194 	{
195 		Log.write ("cVideo: TODO: Implement other colourdepths beside 32. Desired " + iToStr (iDepth) + "bpp ignored.", cLog::eLOG_TYPE_WARNING);
196 		return -1;
197 	}
198 	else
199 	{
200 		// TODO: [SDL2] : sanitycheck
201 		colorDepth = iDepth;
202 	}
203 	return 0;
204 }
205 
getColDepth() const206 int cVideo::getColDepth() const
207 {
208 	return colorDepth;
209 }
210 
setDisplayIndex(int index)211 void cVideo::setDisplayIndex (int index)
212 {
213 	displayIndex = index;
214 	// TODO: apply the display index (reassign window to new display)
215 }
216 
getDisplayIndex() const217 int cVideo::getDisplayIndex() const
218 {
219 	return displayIndex;
220 }
221 
setWindowMode(bool bWindowMode,bool bApply)222 void cVideo::setWindowMode (bool bWindowMode, bool bApply)
223 {
224 	windowMode = bWindowMode;
225 	Log.write ("cVideo: Window mode settings changed to " + std::string (getWindowMode() ? "windowmode" : "fullscreen"), cLog::eLOG_TYPE_DEBUG);
226 
227 	if (bApply)
228 	{
229 		applyWindowMode();
230 	}
231 }
232 
draw()233 void cVideo::draw()
234 {
235 	// SDL2: Some SDL2 functions must be called from the main thread only
236 	// at least in some platform/configuration.
237 	// Check for all configurations.
238 	assert (is_main_thread());
239 
240 	// TODO: add sanity check to redraw function
241 
242 	SDL_UpdateTexture (sdlTexture, nullptr, buffer->pixels, buffer->pitch);
243 	SDL_RenderClear (sdlRenderer);
244 	SDL_RenderCopy (sdlRenderer, sdlTexture, nullptr, nullptr);
245 	SDL_RenderPresent (sdlRenderer);
246 }
247 
applyResolution()248 void cVideo::applyResolution()
249 {
250 	const auto windowFlags = SDL_GetWindowFlags (sdlWindow);
251 	const auto isFullscreen = (windowFlags & SDL_WINDOW_FULLSCREEN) != 0;
252 
253 	if (isFullscreen) SDL_SetWindowFullscreen (sdlWindow, 0);
254 
255 	SDL_SetWindowSize (sdlWindow, getResolutionX(), getResolutionY());
256 
257 	applyWindowMode();
258 
259 	initializeBuffer (getResolutionX(), getResolutionY());
260 
261 	draw();
262 }
263 
applyWindowMode()264 void cVideo::applyWindowMode()
265 {
266 	const auto result = SDL_SetWindowFullscreen (sdlWindow, getWindowMode() ? 0 : SDL_WINDOW_FULLSCREEN);
267 	if (result == -1)
268 	{
269 		throw std::runtime_error (std::string ("Could not apply window mode: ") + SDL_GetError() + "'");
270 	}
271 }
272 
clearBuffer()273 void cVideo::clearBuffer()
274 {
275 	SDL_FillRect (buffer, nullptr, SDL_MapRGB (buffer->format, 0, 0, 0));
276 }
277 
getWindowMode() const278 bool cVideo::getWindowMode() const
279 {
280 	return windowMode;
281 }
282 
getResolutionX() const283 int cVideo::getResolutionX() const
284 {
285 	return resolutionX;
286 }
287 
getResolutionY() const288 int cVideo::getResolutionY() const
289 {
290 	return resolutionY;
291 }
292 
detectResolutions()293 void cVideo::detectResolutions()
294 {
295 	const auto numVideoDislplays = SDL_GetNumVideoDisplays();
296 	detectedResolutions.resize (numVideoDislplays);
297 	for (int displayIndex = 0; displayIndex < numVideoDislplays; ++displayIndex)
298 	{
299 		const auto numDisplayModes = SDL_GetNumDisplayModes (displayIndex);
300 
301 		auto& resolutions = detectedResolutions[displayIndex];
302 
303 		resolutions.clear();
304 
305 		for (int displayModeIndex = 0; displayModeIndex < numDisplayModes; ++displayModeIndex)
306 		{
307 			SDL_DisplayMode mode;
308 			SDL_GetDisplayMode (displayIndex, displayModeIndex, &mode);
309 
310 			// skip modes *below* the minimum mode
311 			if (mode.w < MINWIDTH || mode.h < MINHEIGHT) continue;
312 
313 			resolutions.push_back (std::make_pair (mode.w, mode.h));
314 		}
315 		std::sort (resolutions.begin(), resolutions.end());   // lexicographic order
316 		resolutions.erase (std::unique (resolutions.begin(), resolutions.end()), resolutions.end());    // make sure there are no double entries
317 
318 		for (size_t i = 0; i < resolutions.size(); ++i)
319 		{
320 			const auto& resolution = resolutions[i];
321 			Log.write ("cVideo: Display" + iToStr (displayIndex) + " is offering detected video mode " + iToStr (i) + " (" + iToStr (resolution.first) + "x" + iToStr (resolution.second) + ")", cLog::eLOG_TYPE_INFO);
322 		}
323 	}
324 }
325 
getDetectedResolutions() const326 const std::vector<std::pair<int, int>>& cVideo::getDetectedResolutions() const
327 {
328 	const int displayIndex = sdlWindow ? SDL_GetWindowDisplayIndex (sdlWindow) : 0;
329 
330 	return detectedResolutions[displayIndex];
331 }
332 
haveMinMode() const333 bool cVideo::haveMinMode() const
334 {
335 	const auto& resolutions = getDetectedResolutions();
336 	for (const auto& resolution : resolutions)
337 	{
338 		if (resolution.first == MINWIDTH && resolution.second == MINHEIGHT)
339 		{
340 			return true;
341 		}
342 	}
343 
344 	Log.write ("cVideo: Minimal needed video mode (" + iToStr (MINWIDTH) + "x" + iToStr (MINHEIGHT) + ") not detected. Probably bad!", cLog::eLOG_TYPE_ERROR);
345 	return false;
346 }
347 
validateResolution(int width,int height) const348 int cVideo::validateResolution (int width, int height) const
349 {
350 	const auto& resolutions = getDetectedResolutions();
351 	for (size_t i = 0; i < resolutions.size(); i++)
352 	{
353 		if (resolutions[i].first == width && resolutions[i].second == height)
354 		{
355 			return static_cast<int> (i);
356 		}
357 	}
358 	Log.write ("cVideo: Configured video mode (" + iToStr (width) + "x" + iToStr (height) + ") not detected. Resume on own risk!", cLog::eLOG_TYPE_WARNING);
359 	return -1;
360 }
361 
getMinW() const362 int cVideo::getMinW() const
363 {
364 	return MINWIDTH;
365 }
366 
getMinH() const367 int cVideo::getMinH() const
368 {
369 	return MINHEIGHT;
370 }
371 
takeScreenShot(const std::string & filename) const372 void cVideo::takeScreenShot (const std::string& filename) const
373 {
374 	SDL_SaveBMP (buffer, filename.c_str());
375 }
376 
keyPressed(cKeyboard & keyboard,SDL_Keycode key)377 void cVideo::keyPressed (cKeyboard& keyboard, SDL_Keycode key)
378 {
379 	if (keyboard.isAnyModifierActive (toEnumFlag (eKeyModifierType::AltLeft) | toEnumFlag (eKeyModifierType::AltRight)))
380 	{
381 		if (key == SDLK_RETURN)
382 		{
383 			setWindowMode (!getWindowMode(), true);
384 		}
385 		else if (key == SDLK_c)
386 		{
387 			// TODO: may use std::chrono here.
388 			//       Problem is that std::put_time is not supported in gcc < 4.8 iirc
389 			time_t tTime;
390 			tm* tmTime;
391 			char timestr[18];
392 			tTime = time (nullptr);
393 			tmTime = localtime (&tTime);
394 			strftime (timestr, sizeof (timestr), "%Y-%m-%d_%H%M%S", tmTime);
395 			std::string screenshotfile;
396 			int counter = 0;
397 			do
398 			{
399 				counter += 1;
400 				screenshotfile = getUserScreenshotsDir() + "screenie_" + timestr + "_" + iToStr (counter) + ".bmp";
401 			}
402 			while (FileExists (screenshotfile.c_str()));
403 			Log.write ("Screenshot saved to " + screenshotfile, cLog::eLOG_TYPE_INFO);
404 			takeScreenShot (screenshotfile);
405 
406 			screenShotTaken (screenshotfile);
407 		}
408 	}
409 }
410 
applyShadow(const SDL_Rect * rect,SDL_Surface & destination)411 void cVideo::applyShadow (const SDL_Rect* rect, SDL_Surface& destination)
412 {
413 	const SDL_Rect fullscreen = {0, 0, getResolutionX(), getResolutionY()};
414 	if (rect == nullptr) rect = &fullscreen;
415 	SDL_Rect src = { rect->x, rect->y, rect->w, rect->h };
416 	SDL_Rect dest = { rect->x, rect->y, 0, 0 };
417 	SDL_BlitSurface (GraphicsData.gfx_shadow.get(), &src, &destination, &dest);
418 }
419 
blittPerSurfaceAlphaToAlphaChannel(SDL_Surface * src,SDL_Rect * srcrect,SDL_Surface * dst,SDL_Rect * dstrect)420 void blittPerSurfaceAlphaToAlphaChannel (SDL_Surface* src, SDL_Rect* srcrect, SDL_Surface* dst, SDL_Rect* dstrect)
421 {
422 	SDL_Rect temp1, temp2;
423 
424 	if (!dst || !src) return;
425 
426 	// check surface formats
427 	if (!dst->format->Amask || src->format->Amask) return;
428 	if (SDL_GetSurfaceAlphaMod (src, nullptr) != 0) return;
429 
430 	if (srcrect == nullptr)
431 	{
432 		srcrect = &temp1;
433 		srcrect->x = 0;
434 		srcrect->y = 0;
435 		srcrect->h = src->h;
436 		srcrect->w = src->w;
437 	}
438 
439 	if (dstrect == nullptr)
440 	{
441 		dstrect = &temp2;
442 		dstrect->x = 0;
443 		dstrect->y = 0;
444 	}
445 
446 	int width  = srcrect->w;
447 	int height = srcrect->h;
448 
449 	//clip source rect to the source surface
450 	if (srcrect->x < 0)
451 	{
452 		width += srcrect->x;
453 		srcrect->x = 0;
454 	}
455 	if (srcrect->y < 0)
456 	{
457 		height += srcrect->y;
458 		srcrect->y = 0;
459 	}
460 	width  = std::min (src->w - srcrect->x, width);
461 	height = std::min (src->h - srcrect->y, height);
462 
463 	// clip the dest rect to the destination clip rect
464 	if (dstrect->x < dst->clip_rect.x)
465 	{
466 		width -= dst->clip_rect.x - dstrect->x;
467 		srcrect->x += dst->clip_rect.x - dstrect->x;
468 		dstrect->x = dst->clip_rect.x;
469 	}
470 	if (dstrect->y < dst->clip_rect.y)
471 	{
472 		height -= dst->clip_rect.y - dstrect->y;
473 		srcrect->y += dst->clip_rect.y - dstrect->y;
474 		dstrect->y = dst->clip_rect.y;
475 	}
476 	width  = std::min (dst->clip_rect.x + dst->clip_rect.w - dstrect->x, width);
477 	height = std::min (dst->clip_rect.y + dst->clip_rect.h - dstrect->y, height);
478 
479 	if (width <= 0 || height <= 0)
480 	{
481 		dstrect->w = 0;
482 		dstrect->h = 0;
483 		return;
484 	}
485 
486 	if (SDL_MUSTLOCK (src)) SDL_LockSurface (src);
487 	if (SDL_MUSTLOCK (dst)) SDL_LockSurface (dst);
488 
489 	//setup needed variables
490 	Uint8 srcAlpha = 0;
491 	SDL_GetSurfaceAlphaMod (src, &srcAlpha);
492 	const int srmask = src->format->Rmask;
493 	const int sgmask = src->format->Gmask;
494 	const int sbmask = src->format->Bmask;
495 	const int damask = dst->format->Amask;
496 	const int drmask = dst->format->Rmask;
497 	const int dgmask = dst->format->Gmask;
498 	const int dbmask = dst->format->Bmask;
499 	const int rshift = src->format->Rshift - dst->format->Rshift;
500 	const int gshift = src->format->Gshift - dst->format->Gshift;
501 	const int bshift = src->format->Bshift - dst->format->Bshift;
502 	const int ashift = dst->format->Ashift;
503 	Uint32 colorKey = 0;
504 	const bool useColorKey = SDL_GetColorKey (src, &colorKey) == 0;
505 
506 	Uint32* dstPixel = static_cast<Uint32*> (dst->pixels) + dstrect->x + dstrect->y * dst->w;
507 	Uint32* srcPixel = static_cast<Uint32*> (src->pixels) + srcrect->x + srcrect->y * src->w;
508 
509 	for (int y = 0; y < height; y++)
510 	{
511 		for (int x = 0; x < width; x++)
512 		{
513 			const Uint32 dcolor = *dstPixel;
514 			const Uint32 scolor = *srcPixel;
515 
516 			if (useColorKey && scolor == colorKey)
517 			{
518 				dstPixel++;
519 				srcPixel++;
520 				continue;
521 			}
522 
523 			Uint32 r = (scolor & srmask) >> rshift;
524 			Uint32 g = (scolor & sgmask) >> gshift;
525 			Uint32 b = (scolor & sbmask) >> bshift;
526 			Uint32 dalpha = (dcolor & damask) >> ashift;
527 
528 			r = (((dcolor & drmask) >> 8) * (255 - srcAlpha) * dalpha) + r * srcAlpha;
529 			g = (((dcolor & dgmask) * (255 - srcAlpha) * dalpha) >> 8) + g * srcAlpha;
530 			b = (((dcolor & dbmask) * (255 - srcAlpha) * dalpha) >> 8) + b * srcAlpha;
531 
532 			const Uint8 a = srcAlpha + dalpha - (srcAlpha * dalpha) / 255;
533 
534 			if (a > 0)
535 			{
536 				r /= a;
537 				g /= a;
538 				b /= a;
539 			}
540 
541 			r = r & drmask;
542 			g = g & dgmask;
543 			b = b & dbmask;
544 
545 			*dstPixel = r | g | b | a << ashift;
546 
547 			dstPixel++;
548 			srcPixel++;
549 		}
550 
551 		dstPixel += dst->pitch / 4 - width;
552 		srcPixel += src->pitch / 4 - width;
553 	}
554 
555 	if (SDL_MUSTLOCK (src)) SDL_UnlockSurface (src);
556 	if (SDL_MUSTLOCK (dst)) SDL_UnlockSurface (dst);
557 }
558 
blittAlphaSurface(SDL_Surface * src,SDL_Rect * srcrect,SDL_Surface * dst,SDL_Rect * dstrect)559 void blittAlphaSurface (SDL_Surface* src, SDL_Rect* srcrect, SDL_Surface* dst, SDL_Rect* dstrect)
560 {
561 	// TODO: [SDL2] special blitSurface seems useless.
562 	if (dst->format->Amask && SDL_GetSurfaceAlphaMod (src, nullptr) == 0)
563 		blittPerSurfaceAlphaToAlphaChannel (src, srcrect, dst, dstrect);
564 	else
565 		SDL_BlitSurface (src, srcrect, dst, dstrect);
566 }
567 
568 /**
569  * draws one line of the source surface scaled to the destination surface.
570  * @author alzi alias DoctorDeath
571  * @param srcPixelData pointer to the first byte of the line in the pixeldate
572  *        of the source surface.
573  * @param srcWidth width of the line in the sourcesurface.
574  * @param destPixelData pointer to the first byte where in the pixeldate
575  *        of the source surface the line should be drawn.
576  * @param destWidth Directory width of the line how it should be drawn
577  *        to the destination surface.
578  */
579 template<typename Type>
drawStetchedLine(Type * srcPixelData,int srcWidth,Type * destPixelData,int destWidth)580 static void drawStetchedLine (Type* srcPixelData, int srcWidth, Type* destPixelData, int destWidth)
581 {
582 	int i = 0;
583 	int width = destWidth;
584 	Type pixel = 0;
585 	Type* srcEnd = srcPixelData + srcWidth;
586 	// go trough all pixel in this line
587 	while (srcPixelData < srcEnd)
588 	{
589 		pixel = *srcPixelData;
590 drawpixel:
591 		// copy the pixel
592 		*destPixelData++ = pixel;
593 		width--;
594 		i += srcWidth;
595 		if (!width) break;
596 		// draw pixel once more if necessary
597 		if (i < destWidth) goto drawpixel;
598 		// skip pixels when necessary
599 		do
600 		{
601 			i -= destWidth;
602 			srcPixelData++;
603 		}
604 		while (i >= destWidth);
605 	}
606 }
607 
scaleSurface(SDL_Surface * scr,SDL_Surface * dest,int width,int height)608 SDL_Surface* scaleSurface (SDL_Surface* scr, SDL_Surface* dest, int width, int height)
609 {
610 	if (width <= 0 || height <= 0 || !scr) return nullptr;
611 	SDL_Surface* surface;
612 
613 	// can not enlage an existing surface
614 	if (width > scr->w && dest) width = scr->w;
615 	if (height > scr->h && dest) height = scr->h;
616 
617 	// generate new surface if necessary
618 	if (dest == nullptr) surface = SDL_CreateRGBSurface (0, width, height, scr->format->BitsPerPixel, scr->format->Rmask, scr->format->Gmask, scr->format->Bmask, scr->format->Amask);
619 	else
620 	{
621 		// else set the size of the old one
622 		surface = dest;
623 		surface->w = width;
624 		surface->h = height;
625 	}
626 
627 	if (SDL_MUSTLOCK (scr)) SDL_LockSurface (scr);
628 	if (SDL_MUSTLOCK (surface)) SDL_LockSurface (surface);
629 
630 #if 0
631 	// just blit the surface when the new size is identic to the old one
632 	if (scr->w == width && scr->h == height)
633 	{
634 		SDL_BlitSurface (scr, nullptr, surface, nullptr);
635 		return surface;
636 	}
637 #endif
638 	// copy palette when necessary
639 	if (scr->format->BitsPerPixel == 8 && !dest)
640 	{
641 		for (int i = 0; i < 256; i++)
642 		{
643 			surface->format->palette->colors[i].r = scr->format->palette->colors[i].r;
644 			surface->format->palette->colors[i].g = scr->format->palette->colors[i].g;
645 			surface->format->palette->colors[i].b = scr->format->palette->colors[i].b;
646 		}
647 	}
648 
649 	int srcRow = 0;
650 	int destRow = 0;
651 	int i = 0;
652 	// go trough all rows
653 	while (srcRow < scr->h)
654 	{
655 		Uint8* srcPixelData = static_cast<Uint8*> (scr->pixels) + (srcRow * scr->pitch);
656 		// draw the complete line
657 drawline:
658 		Uint8* destPixelData = static_cast<Uint8*> (surface->pixels) + (destRow * surface->pitch);
659 
660 		// pay attention to different surface formats
661 		switch (scr->format->BytesPerPixel)
662 		{
663 			case 1:
664 				drawStetchedLine<Uint8> (srcPixelData, scr->w, destPixelData, surface->w);
665 				break;
666 			case 2:
667 				drawStetchedLine<Uint16> (reinterpret_cast<Uint16*> (srcPixelData), scr->w, (Uint16*) destPixelData, surface->w);
668 				break;
669 			case 3:
670 				// not yet supported
671 				break;
672 			case 4:
673 				drawStetchedLine<Uint32> (reinterpret_cast<Uint32*> (srcPixelData), scr->w, (Uint32*) destPixelData, surface->w);
674 				break;
675 		}
676 		destRow++;
677 		i += scr->h;
678 		// break when we have already finished
679 		if (destRow == surface->h) break;
680 		// draw the line once more when the destiniation surface has
681 		// a bigger height than the source surface
682 		if (i < surface->h) goto drawline;
683 		// skip lines in the source surface when the destination surface has
684 		// a smaller height than the source surface
685 		do
686 		{
687 			i -= surface->h;
688 			srcRow++;
689 		}
690 		while (i >= surface->h);
691 	}
692 
693 	if (SDL_MUSTLOCK (scr)) SDL_UnlockSurface (scr);
694 	if (SDL_MUSTLOCK (surface)) SDL_UnlockSurface (surface);
695 
696 	return surface;
697 }
698 
line(int x1,int y1,int x2,int y2,unsigned int color,SDL_Surface & sf)699 static void line (int x1, int y1, int x2, int y2, unsigned int color, SDL_Surface& sf)
700 {
701 	if (x2 < x1)
702 	{
703 		std::swap (x1, x2);
704 		std::swap (y1, y2);
705 	}
706 	int dx = x2 - x1;
707 	int dy = y2 - y1;
708 	int dir = 1;
709 	if (dy < 0) {dy = -dy; dir = -1;}
710 	int error = 0;
711 	Uint32* ptr = static_cast<Uint32*> (sf.pixels);
712 	if (dx > dy)
713 	{
714 		for (; x1 != x2; x1++, error += dy)
715 		{
716 			if (error > dx) {error -= dx; y1 += dir;}
717 			if (x1 < sf.w && x1 >= 0 && y1 >= 0 && y1 < sf.h)
718 				ptr[x1 + y1 * sf.w] = color;
719 		}
720 		return;
721 	}
722 	for (; y1 != y2; y1 += dir, error += dx)
723 	{
724 		if (error > dy) {error -= dy; x1++;}
725 		if (x1 < sf.w && x1 >= 0 && y1 >= 0 && y1 < sf.h)
726 			ptr[x1 + y1 * sf.w] = color;
727 	}
728 }
729 
730 // CreatePfeil ////////////////////////////////////////////////////////////////
731 // Erzeigt ein Pfeil-Surface:
CreatePfeil(int p1x,int p1y,int p2x,int p2y,int p3x,int p3y,unsigned int color,int size)732 AutoSurface CreatePfeil (int p1x, int p1y, int p2x, int p2y, int p3x, int p3y, unsigned int color, int size)
733 {
734 	AutoSurface sf (SDL_CreateRGBSurface (0, size, size, Video.getColDepth(), 0, 0, 0, 0));
735 	SDL_SetColorKey (sf.get(), SDL_TRUE, 0x00FF00FF);
736 	SDL_FillRect (sf.get(), nullptr, 0x00FF00FF);
737 	SDL_LockSurface (sf.get());
738 
739 	const float fak = size / 64.0f;
740 	p1x = Round (p1x * fak);
741 	p1y = Round (p1y * fak);
742 	p2x = Round (p2x * fak);
743 	p2y = Round (p2y * fak);
744 	p3x = Round (p3x * fak);
745 	p3y = Round (p3y * fak);
746 	line (p1x, p1y, p2x, p2y, color, *sf);
747 	line (p2x, p2y, p3x, p3y, color, *sf);
748 	line (p3x, p3y, p1x, p1y, color, *sf);
749 
750 	SDL_UnlockSurface (sf.get());
751 	return sf;
752 }
753 
setPixel(SDL_Surface & surface,int x,int y,int iColor)754 static void setPixel (SDL_Surface& surface, int x, int y, int iColor)
755 {
756 	// check the surface size
757 	if (x < 0 || x >= surface.w || y < 0 || y >= surface.h) return;
758 	// check the clip rect
759 	if (x < surface.clip_rect.x || x >= surface.clip_rect.x + surface.clip_rect.w ||
760 		y < surface.clip_rect.y || y >= surface.clip_rect.y + surface.clip_rect.h) return;
761 
762 	static_cast<Uint32*> (surface.pixels) [x + y * surface.w] = iColor;
763 }
764 
drawCircle(int iX,int iY,int iRadius,int iColor,SDL_Surface & surface)765 void drawCircle (int iX, int iY, int iRadius, int iColor, SDL_Surface& surface)
766 {
767 	if (iX + iRadius < 0 || iX - iRadius > Video.getResolutionX() ||
768 		iY + iRadius < 0 || iY - iRadius > Video.getResolutionY()) return;
769 	SDL_LockSurface (&surface);
770 
771 	int d = 0;
772 	int xx = 0;
773 	int yy = iRadius;
774 	int bry = Round (0.70710678f * iRadius);
775 	while (yy > bry)
776 	{
777 		int da = d + (xx << 1) + 1;
778 		int db = da - (yy << 1) + 1;
779 		if (abs (da) < abs (db))
780 		{
781 			d = da;
782 			xx++;
783 		}
784 		else
785 		{
786 			d = db;
787 			xx++;
788 			yy--;
789 		}
790 		setPixel (surface, iX + xx, iY + yy, iColor);
791 		setPixel (surface, iX + yy, iY + xx, iColor);
792 		setPixel (surface, iX + yy, iY - xx, iColor);
793 		setPixel (surface, iX + xx, iY - yy, iColor);
794 		setPixel (surface, iX - xx, iY + yy, iColor);
795 		setPixel (surface, iX - yy, iY + xx, iColor);
796 		setPixel (surface, iX - yy, iY - xx, iColor);
797 		setPixel (surface, iX - xx, iY - yy, iColor);
798 	}
799 	SDL_UnlockSurface (&surface);
800 }
801