Manual_dev

SDL2 base code

Jul 8th, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.20 KB | None | 0 0
  1. /*This source code copyrighted by Lazy Foo' Productions (2004-2015)
  2. and may not be redistributed without written permission.*/
  3.  
  4. //Using SDL, SDL_image, SDL_ttf, SDL_mixer, standard IO, math, and strings
  5. #include <SDL.h>
  6. #include <SDL_image.h>
  7. #include <SDL_mixer.h>
  8. #include <stdio.h>
  9. #include <string>
  10. #include <SDL_ttf.h>
  11. #include <stdio.h>
  12. #include <string>
  13. #include <cmath>
  14. #include <iostream>
  15.  
  16. //Screen dimension constants
  17. const int SCREEN_WIDTH = 640;
  18. const int SCREEN_HEIGHT = 480;
  19.  
  20. //Texture wrapper class
  21. class LTexture
  22. {
  23. public:
  24. //Initializes variables
  25. LTexture();
  26.  
  27. //Deallocates memory
  28. ~LTexture();
  29.  
  30. //Loads image at specified path
  31. bool loadFromFile(std::string path);
  32.  
  33. #ifdef _SDL_TTF_H
  34. //Creates image from font string
  35. bool loadFromRenderedText(std::string textureText, SDL_Color textColor);
  36. #endif
  37.  
  38. //Deallocates texture
  39. void free();
  40.  
  41. //Set color modulation
  42. void setColor(Uint8 red, Uint8 green, Uint8 blue);
  43.  
  44. //Set blending
  45. void setBlendMode(SDL_BlendMode blending);
  46.  
  47. //Set alpha modulation
  48. void setAlpha(Uint8 alpha);
  49.  
  50. //Renders texture at given point
  51. void render(int x, int y, SDL_Rect* clip = NULL, double angle = 0.0, SDL_Point* center = NULL, SDL_RendererFlip flip = SDL_FLIP_NONE);
  52.  
  53. //Gets image dimensions
  54. int getWidth();
  55. int getHeight();
  56.  
  57. private:
  58. //The actual hardware texture
  59. SDL_Texture* mTexture;
  60.  
  61. //Image dimensions
  62. int mWidth;
  63. int mHeight;
  64. };
  65.  
  66. //Starts up SDL and creates window
  67. bool init();
  68.  
  69. //Loads media
  70. bool loadMedia();
  71.  
  72. //Frees media and shuts down SDL
  73. void close();
  74.  
  75. //The window we'll be rendering to
  76. SDL_Window* gWindow = NULL;
  77.  
  78. //The window renderer
  79. SDL_Renderer* gRenderer = NULL;
  80.  
  81. //Scene texture
  82. LTexture gPromptTexture;
  83.  
  84. //The music that will be played
  85. Mix_Music *gMusic = NULL;
  86.  
  87. //The sound effects that will be used
  88. Mix_Chunk *gScratch = NULL;
  89. Mix_Chunk *gHigh = NULL;
  90. Mix_Chunk *gMedium = NULL;
  91. Mix_Chunk *gLow = NULL;
  92.  
  93.  
  94. //Globally used font
  95. TTF_Font *gFont = NULL;
  96.  
  97.  
  98. //Rendered texture
  99. LTexture gTextTexture;
  100.  
  101. LTexture::LTexture()
  102. {
  103. //Initialize
  104. mTexture = NULL;
  105. mWidth = 0;
  106. mHeight = 0;
  107. }
  108.  
  109. LTexture::~LTexture()
  110. {
  111. //Deallocate
  112. free();
  113. }
  114.  
  115. bool LTexture::loadFromFile(std::string path)
  116. {
  117. //Get rid of preexisting texture
  118. free();
  119.  
  120. //The final texture
  121. SDL_Texture* newTexture = NULL;
  122.  
  123. //Load image at specified path
  124. SDL_Surface* loadedSurface = IMG_Load(path.c_str());
  125. if (loadedSurface == NULL)
  126. {
  127. printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError());
  128. }
  129. else
  130. {
  131. //Color key image
  132. SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, 0, 0xFF, 0xFF));
  133.  
  134. //Create texture from surface pixels
  135. newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface);
  136. if (newTexture == NULL)
  137. {
  138. printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError());
  139. }
  140. else
  141. {
  142. //Get image dimensions
  143. mWidth = loadedSurface->w;
  144. mHeight = loadedSurface->h;
  145. }
  146.  
  147. //Get rid of old loaded surface
  148. SDL_FreeSurface(loadedSurface);
  149. }
  150.  
  151. //Return success
  152. mTexture = newTexture;
  153. return mTexture != NULL;
  154. }
  155.  
  156. #ifdef _SDL_TTF_H
  157. bool LTexture::loadFromRenderedText(std::string textureText, SDL_Color textColor)
  158. {
  159. //Get rid of preexisting texture
  160. free();
  161.  
  162. //Render text surface
  163. SDL_Surface* textSurface = TTF_RenderText_Solid(gFont, textureText.c_str(), textColor);
  164. if (textSurface != NULL)
  165. {
  166. //Create texture from surface pixels
  167. mTexture = SDL_CreateTextureFromSurface(gRenderer, textSurface);
  168. if (mTexture == NULL)
  169. {
  170. printf("Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError());
  171. }
  172. else
  173. {
  174. //Get image dimensions
  175. mWidth = textSurface->w;
  176. mHeight = textSurface->h;
  177. }
  178.  
  179. //Get rid of old surface
  180. SDL_FreeSurface(textSurface);
  181. }
  182. else
  183. {
  184. printf("Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError());
  185. }
  186.  
  187.  
  188. //Return success
  189. return mTexture != NULL;
  190. }
  191.  
  192.  
  193. #endif
  194.  
  195. void LTexture::free()
  196. {
  197. //Free texture if it exists
  198. if (mTexture != NULL)
  199. {
  200. SDL_DestroyTexture(mTexture);
  201. mTexture = NULL;
  202. mWidth = 0;
  203. mHeight = 0;
  204. }
  205. }
  206.  
  207. void LTexture::setColor(Uint8 red, Uint8 green, Uint8 blue)
  208. {
  209. //Modulate texture rgb
  210. SDL_SetTextureColorMod(mTexture, red, green, blue);
  211. }
  212.  
  213. void LTexture::setBlendMode(SDL_BlendMode blending)
  214. {
  215. //Set blending function
  216. SDL_SetTextureBlendMode(mTexture, blending);
  217. }
  218.  
  219. void LTexture::setAlpha(Uint8 alpha)
  220. {
  221. //Modulate texture alpha
  222. SDL_SetTextureAlphaMod(mTexture, alpha);
  223. }
  224.  
  225. void LTexture::render(int x, int y, SDL_Rect* clip, double angle, SDL_Point* center, SDL_RendererFlip flip)
  226. {
  227. //Set rendering space and render to screen
  228. SDL_Rect renderQuad = { x, y, mWidth, mHeight };
  229.  
  230. //Set clip rendering dimensions
  231. if (clip != NULL)
  232. {
  233. renderQuad.w = clip->w;
  234. renderQuad.h = clip->h;
  235. }
  236.  
  237. //Render to screen
  238. SDL_RenderCopyEx(gRenderer, mTexture, clip, &renderQuad, angle, center, flip);
  239. }
  240.  
  241. int LTexture::getWidth()
  242. {
  243. return mWidth;
  244. }
  245.  
  246. int LTexture::getHeight()
  247. {
  248. return mHeight;
  249. }
  250.  
  251. bool init()
  252. {
  253. //Initialization flag
  254. bool success = true;
  255.  
  256. //Initialize SDL
  257. if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0)
  258. {
  259. printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
  260. success = false;
  261. }
  262. else
  263. {
  264. //Set texture filtering to linear
  265. if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"))
  266. {
  267. printf("Warning: Linear texture filtering not enabled!");
  268. }
  269.  
  270. //Create window
  271. gWindow = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
  272. if (gWindow == NULL)
  273. {
  274. printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
  275. success = false;
  276. }
  277. else
  278. {
  279. //Create vsynced renderer for window
  280. gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
  281. if (gRenderer == NULL)
  282. {
  283. printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError());
  284. success = false;
  285. }
  286. else
  287. {
  288. //Initialize renderer color
  289. SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
  290.  
  291. //Initialize PNG loading
  292. int imgFlags = IMG_INIT_PNG;
  293. if (!(IMG_Init(imgFlags) & imgFlags))
  294. {
  295. printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
  296. success = false;
  297. }
  298.  
  299. //Initialize SDL_mixer
  300. if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
  301. {
  302. printf("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError());
  303. success = false;
  304. }
  305.  
  306. //Initialize SDL_ttf
  307. if (TTF_Init() == -1)
  308. {
  309. printf("SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError());
  310. success = false;
  311. }
  312. }
  313. }
  314. }
  315.  
  316. return success;
  317. }
  318.  
  319. bool loadMedia()
  320. {
  321. //Loading success flag
  322. bool success = true;
  323.  
  324. //Load prompt texture
  325. /*if (!gPromptTexture.loadFromFile("resources/image/prompt.png"))
  326. {
  327. printf("Failed to load prompt texture!\n");
  328. success = false;
  329. }
  330. */
  331. //Load music
  332. gMusic = Mix_LoadMUS("resources/audio/Greenday - 21 Guns.mp3");
  333. if (gMusic == NULL)
  334. {
  335. printf("Failed to load beat music! SDL_mixer Error: %s\n", Mix_GetError());
  336. success = false;
  337. }
  338.  
  339. //Load sound effects
  340. gScratch = Mix_LoadWAV("resources/audio/scratch.wav");
  341. if (gScratch == NULL)
  342. {
  343. printf("Failed to load scratch sound effect! SDL_mixer Error: %s\n", Mix_GetError());
  344. success = false;
  345. }
  346.  
  347. gHigh = Mix_LoadWAV("resources/audio/high.wav");
  348. if (gHigh == NULL)
  349. {
  350. printf("Failed to load high sound effect! SDL_mixer Error: %s\n", Mix_GetError());
  351. success = false;
  352. }
  353.  
  354. gMedium = Mix_LoadWAV("resources/audio/medium.wav");
  355. if (gMedium == NULL)
  356. {
  357. printf("Failed to load medium sound effect! SDL_mixer Error: %s\n", Mix_GetError());
  358. success = false;
  359. }
  360.  
  361. gLow = Mix_LoadWAV("resources/audio/low.wav");
  362. if (gLow == NULL)
  363. {
  364. printf("Failed to load low sound effect! SDL_mixer Error: %s\n", Mix_GetError());
  365. success = false;
  366. }
  367.  
  368.  
  369. //Open the font
  370. gFont = TTF_OpenFont("resources/image/lazy.ttf", 28);
  371. if (gFont == NULL)
  372. {
  373. printf("Failed to load lazy font! SDL_ttf Error: %s\n", TTF_GetError());
  374. success = false;
  375. }
  376. else
  377. {
  378. //Render text
  379. SDL_Color textColor = { 0, 0, 0 };
  380. if (!gTextTexture.loadFromRenderedText("The quick brown fox jumps over the lazy dog", textColor))
  381. {
  382. printf("Failed to render text texture!\n");
  383. success = false;
  384. }
  385. }
  386.  
  387. return success;
  388. }
  389.  
  390. void close()
  391. {
  392. //Free loaded images
  393. gPromptTexture.free();
  394.  
  395. gTextTexture.free();
  396. //Free the sound effects
  397. Mix_FreeChunk(gScratch);
  398. Mix_FreeChunk(gHigh);
  399. Mix_FreeChunk(gMedium);
  400. Mix_FreeChunk(gLow);
  401. gScratch = NULL;
  402. gHigh = NULL;
  403. gMedium = NULL;
  404. gLow = NULL;
  405.  
  406. //Free the music
  407. Mix_FreeMusic(gMusic);
  408. gMusic = NULL;
  409.  
  410. //Destroy window
  411. SDL_DestroyRenderer(gRenderer);
  412. SDL_DestroyWindow(gWindow);
  413. gWindow = NULL;
  414. gRenderer = NULL;
  415.  
  416. //Quit SDL subsystems
  417. Mix_Quit();
  418. TTF_Quit();
  419. IMG_Quit();
  420. SDL_Quit();
  421.  
  422. }
  423.  
  424. int main(int argc, char* args[])
  425. {
  426. //Start up SDL and create window
  427. if (!init())
  428. {
  429. printf("Failed to initialize!\n");
  430. }
  431. else
  432. {
  433. //Load media
  434. if (!loadMedia())
  435. {
  436. printf("Failed to load media!\n");
  437. }
  438. else
  439. {
  440. //Main loop flag
  441. bool quit = false;
  442.  
  443. //Event handler
  444. SDL_Event e;
  445.  
  446. //While application is running
  447. while (!quit)
  448. {
  449. //Handle events on queue
  450. while (SDL_PollEvent(&e) != 0)
  451. {
  452. //User requests quit
  453. if (e.type == SDL_QUIT)
  454. {
  455. quit = true;
  456. }
  457. //Handle key press
  458. else if (e.type == SDL_KEYDOWN)
  459. {
  460. switch (e.key.keysym.sym)
  461. {
  462. //Play high sound effect
  463. case SDLK_1:
  464. Mix_PlayChannel(-1, gHigh, 0);
  465. break;
  466.  
  467. //Play medium sound effect
  468. case SDLK_2:
  469. Mix_PlayChannel(-1, gMedium, 0);
  470. break;
  471.  
  472. //Play low sound effect
  473. case SDLK_3:
  474. Mix_PlayChannel(-1, gLow, 0);
  475. break;
  476.  
  477. //Play scratch sound effect
  478. case SDLK_4:
  479. Mix_PlayChannel(-1, gScratch, 0);
  480. break;
  481.  
  482. case SDLK_9:
  483. //If there is no music playing
  484. if (Mix_PlayingMusic() == 0)
  485. {
  486. //Play the music
  487. Mix_PlayMusic(gMusic, -1);
  488. }
  489. //If music is being played
  490. else
  491. {
  492. //If the music is paused
  493. if (Mix_PausedMusic() == 1)
  494. {
  495. //Resume the music
  496. Mix_ResumeMusic();
  497. }
  498. //If the music is playing
  499. else
  500. {
  501. //Pause the music
  502. Mix_PauseMusic();
  503. }
  504. }
  505. break;
  506.  
  507. case SDLK_0:
  508. //Stop the music
  509. Mix_HaltMusic();
  510. break;
  511. }
  512. }
  513. }
  514.  
  515. //Clear screen
  516. SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
  517. SDL_RenderClear(gRenderer);
  518.  
  519. //Render current frame
  520. gTextTexture.render((SCREEN_WIDTH - gTextTexture.getWidth()) / 2, (SCREEN_HEIGHT - gTextTexture.getHeight()) / 2);
  521.  
  522. //Update screen
  523. SDL_RenderPresent(gRenderer);
  524. }
  525. }
  526. }
  527.  
  528. //Free resources and close SDL
  529.  
  530. std::cin.get();
  531. close();
  532.  
  533. return 0;
  534. }
Advertisement
Add Comment
Please, Sign In to add comment