Almost done implementing simple graphics!! (hopefully)

This commit is contained in:
sam-astro 2022-01-11 19:51:09 -05:00
parent 036470a14e
commit 59d0bd5c56
10 changed files with 489 additions and 187 deletions

View File

@ -558,29 +558,29 @@ int parseSlang(string script)
return 0;
}
int main(int argc, char* argv[])
{
// Get builtin script contents
ifstream builtin("../Slang/builtin.slg");
stringstream builtinString;
builtinString << builtin.rdbuf();
// Gathers builtin functions and variables
GetBuiltins(builtinString.str());
functionValues = builtinFunctionValues;
globalVariableValues = builtinVarVals;
// Get default script contents
ifstream script("../Slang/script.slg");
stringstream scriptString;
scriptString << script.rdbuf();
while (true) {
system("pause");
break;
}
parseSlang(scriptString.str());
return 0;
}
//
//int main(int argc, char* argv[])
//{
// // Get builtin script contents
// ifstream builtin("../Slang/builtin.slg");
// stringstream builtinString;
// builtinString << builtin.rdbuf();
//
// // Gathers builtin functions and variables
// GetBuiltins(builtinString.str());
// functionValues = builtinFunctionValues;
// globalVariableValues = builtinVarVals;
//
// // Get default script contents
// ifstream script("../Slang/script.slg");
// stringstream scriptString;
// scriptString << script.rdbuf();
//
// while (true) {
// system("pause");
// break;
// }
// parseSlang(scriptString.str());
//
// return 0;
//}

View File

@ -80,8 +80,8 @@
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<IncludePath>D:\Code\SDL2-2.0.18\include;D:\Code\SDL2_image-2.0.5\include;$(IncludePath)</IncludePath>
<LibraryPath>D:\Code\SDL2-2.0.18\lib\x64;D:\Code\SDL2_image-2.0.5\lib\x64;$(LibraryPath)</LibraryPath>
<IncludePath>D:\Code\SDL2-2.0.18\include;D:\Code\SDL2_image-2.0.5\include;D:\Code\SDL2_ttf-2.0.15\include;$(IncludePath)</IncludePath>
<LibraryPath>D:\Code\SDL2_ttf-2.0.15\lib\x64;D:\Code\SDL2-2.0.18\lib\x64;D:\Code\SDL2_image-2.0.5\lib\x64;$(LibraryPath)</LibraryPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
@ -123,13 +123,13 @@
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>D:\Code\boost;D:\Code\SDL2-2.0.18;D:\Code\SDL2_image-2.0.5;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>D:\Code\SDL2_ttf-2.0.15;D:\Code\boost;D:\Code\SDL2-2.0.18;D:\Code\SDL2_image-2.0.5;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>SDL2.lib;SDL2main.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>D:\Code\SDL2-2.0.18\lib\x64;D:\Code\boost\libs;D:\Code\SDL2_image-2.0.5\lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>SDL2.lib;SDL2main.lib;SDL2_ttf.lib;SDL2_image.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>D:\Code\SDL2_ttf-2.0.15\lib\x64;D:\Code\SDL2-2.0.18\lib\x64;D:\Code\boost\libs;D:\Code\SDL2_image-2.0.5\lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
@ -150,9 +150,9 @@
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="eval.cpp" />
<ClCompile Include="graphics.cpp" />
<ClCompile Include="Main.cpp" />
<ClCompile Include="strops.cpp" />
<ClCompile Include="tut\02_getting_an_image_on_the_screen.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="builtin.h" />

View File

@ -24,7 +24,7 @@
<ClCompile Include="strops.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="tut\02_getting_an_image_on_the_screen.cpp">
<ClCompile Include="graphics.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>

BIN
Slang/arial.ttf Normal file

Binary file not shown.

View File

@ -22,38 +22,11 @@ vector<string> types = { "int", "float", "string", "bool", "void", "null", "Circ
unordered_map<string, vector<vector<string>>> builtinFunctionValues;
unordered_map<string, boost::any> builtinVarVals;
Parser mainWindow;
class NullType {
public:
string type = "NULL";
};
class Circle
{
public:
int x;
int y;
float r;
};
class Image
{
public:
int x;
int y;
float r;
SDL_Surface* surface;
SDL_Texture* texture;
/*int LoadImage(string PATH)
{
surface = IMG_Load("Path/To/Your/Image.png");
texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_FreeSurface(surface);
}*/
};
boost::any nullType;
int LogWarning(const string& warningText)
@ -150,18 +123,18 @@ boost::any CPPFunction(const string& name, const vector<boost::any>& args)
return AnyAsInt(args[0]);
else if (name == "CPP.Graphics.Init")
{
cout << "\x1B[32mInit graphics\033[0m\t\t" << endl;
mainWindow.Start(AnyAsInt(args[0]), AnyAsInt(args[1]));
/*cout << "\x1B[32mInit graphics\033[0m\t\t" << endl;
mainWindow.Start(AnyAsInt(args[0]), AnyAsInt(args[1]));*/
}
else if (name == "CPP.Graphics.Circle")
{
Circle c;
/*Circle c;
c.x = AnyAsInt(args[0]);
c.y = AnyAsInt(args[1]);
c.r = AnyAsInt(args[2]);
boost::any a = c;
Circle d = any_cast<Circle>(a);
return d;
return d;*/
}
else if (name == "CPP.System.Print")
cout << AnyAsString(args[0]);

BIN
Slang/circle.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 802 B

405
Slang/graphics.cpp Normal file
View File

@ -0,0 +1,405 @@
#include <chrono>
#include <SDL.h>
#include <SDL_ttf.h>
#include <SDL_image.h>
#include <string>
//#include "graphics.h"
const int WINDOW_WIDTH = 1280;
const int WINDOW_HEIGHT = 720;
enum Buttons
{
PaddleOneUp = 0,
PaddleOneDown,
PaddleTwoUp,
PaddleTwoDown,
};
const float PADDLE_SPEED = 1.0f;
//The window we'll be rendering to
SDL_Window* gWindow = NULL;
//The renderer we'll be rendering to
SDL_Renderer* gRenderer = NULL;
//The surface contained by the window
SDL_Surface* gScreenSurface = NULL;
SDL_Surface* loadSurface(std::string path)
{
//The final optimized image
SDL_Surface* optimizedSurface = NULL;
//Load image at specified path
SDL_Surface* loadedSurface = IMG_Load(path.c_str());
if (loadedSurface == NULL)
{
printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError());
}
else
{
//Convert surface to screen format
optimizedSurface = SDL_ConvertSurface(loadedSurface, gScreenSurface->format, 0);
if (optimizedSurface == NULL)
{
printf("Unable to optimize image %s! SDL Error: %s\n", path.c_str(), SDL_GetError());
}
//Get rid of old loaded surface
SDL_FreeSurface(loadedSurface);
}
return optimizedSurface;
}
class Vec2
{
public:
Vec2()
: x(0.0f), y(0.0f)
{}
Vec2(float x, float y)
: x(x), y(y)
{}
Vec2 operator+(Vec2 const& rhs)
{
return Vec2(x + rhs.x, y + rhs.y);
}
Vec2& operator+=(Vec2 const& rhs)
{
x += rhs.x;
y += rhs.y;
return *this;
}
Vec2 operator*(float rhs)
{
return Vec2(x * rhs, y * rhs);
}
float x, y;
};
const int BALL_WIDTH = 15;
const int BALL_HEIGHT = 15;
class Ball
{
public:
Ball(Vec2 position)
: position(position)
{
rect.x = static_cast<int>(position.x);
rect.y = static_cast<int>(position.y);
rect.w = BALL_WIDTH;
rect.h = BALL_HEIGHT;
}
void Draw(SDL_Renderer* renderer)
{
rect.x = static_cast<int>(position.x);
rect.y = static_cast<int>(position.y);
SDL_RenderFillRect(renderer, &rect);
}
Vec2 position;
SDL_Rect rect{};
};
const int PADDLE_WIDTH = 15;
const int PADDLE_HEIGHT = 80;
class Paddle
{
public:
Paddle(Vec2 position, Vec2 velocity)
: position(position), velocity(velocity)
{
rect.x = static_cast<int>(position.x);
rect.y = static_cast<int>(position.y);
rect.w = PADDLE_WIDTH;
rect.h = PADDLE_HEIGHT;
}
void Update(float dt)
{
position += velocity * dt;
if (position.y < 0)
{
// Restrict to top of the screen
position.y = 0;
}
else if (position.y > (WINDOW_HEIGHT - PADDLE_HEIGHT))
{
// Restrict to bottom of the screen
position.y = WINDOW_HEIGHT - PADDLE_HEIGHT;
}
}
void Draw(SDL_Renderer* renderer)
{
rect.y = static_cast<int>(position.y);
SDL_RenderFillRect(renderer, &rect);
}
Vec2 position;
Vec2 velocity;
SDL_Rect rect{};
};
class Sprite
{
public:
Sprite(Vec2 position, std::string path)
: position(position)
{
rect.x = static_cast<int>(position.x);
rect.y = static_cast<int>(position.y);
rect.w = PADDLE_WIDTH;
rect.h = PADDLE_HEIGHT;
SDL_Surface* surface = loadSurface(path);
texture = SDL_CreateTextureFromSurface(gRenderer, surface);
SDL_FreeSurface(surface);
}
void Draw()
{
rect.y = static_cast<int>(position.y);
//SDL_RenderFillRect(renderer, &rect);
SDL_RenderCopy(gRenderer, texture, NULL, &rect);
}
Vec2 position;
std::string path;
SDL_Rect rect{};
SDL_Texture* texture;
};
class PlayerScore
{
public:
PlayerScore(Vec2 position, SDL_Renderer* renderer, TTF_Font* font, SDL_Color scoreColor)
: renderer(renderer), font(font)
{
surface = TTF_RenderText_Solid(font, "0", scoreColor);
texture = SDL_CreateTextureFromSurface(renderer, surface);
int width, height;
SDL_QueryTexture(texture, nullptr, nullptr, &width, &height);
rect.x = static_cast<int>(position.x);
rect.y = static_cast<int>(position.y);
rect.w = width;
rect.h = height;
}
~PlayerScore()
{
SDL_FreeSurface(surface);
SDL_DestroyTexture(texture);
}
void Draw()
{
SDL_RenderCopy(renderer, texture, nullptr, &rect);
}
SDL_Renderer* renderer;
TTF_Font* font;
SDL_Surface* surface{};
SDL_Texture* texture{};
SDL_Rect rect{};
};
int main(int argc, char* argv[])
{
// Initialize SDL components
SDL_Init(SDL_INIT_VIDEO);
TTF_Init();
gWindow = SDL_CreateWindow("Pong", 20, 20, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
gRenderer = SDL_CreateRenderer(gWindow, -1, 0);
//Get window surface
gScreenSurface = SDL_GetWindowSurface(gWindow);
// Initialize the font
TTF_Font* scoreFont = TTF_OpenFont("arial.ttf", 40);
SDL_Color scoreColor = { 0xFF, 0xFF, 0xFF, 0xFF };
// Create the player score text fields
PlayerScore playerOneScoreText(Vec2(WINDOW_WIDTH / 4, 20), gRenderer, scoreFont, scoreColor);
PlayerScore playerTwoScoreText(Vec2(3 * WINDOW_WIDTH / 4, 20), gRenderer, scoreFont, scoreColor);
// Create the ball
Ball ball(
Vec2((WINDOW_WIDTH / 2.0f) - (BALL_WIDTH / 2.0f),
(WINDOW_HEIGHT / 2.0f) - (BALL_WIDTH / 2.0f)));
// Create the paddles
Paddle paddleOne(
Vec2(50.0f, WINDOW_HEIGHT / 2.0f),
Vec2(0.0f, 0.0f));
Paddle paddleTwo(
Vec2(WINDOW_WIDTH - 50.0f, WINDOW_HEIGHT / 2.0f),
Vec2(0.0f, 0.0f));
Sprite randomAssSprite(
Vec2((WINDOW_WIDTH / 2.0f) - (100 / 2.0f),
(WINDOW_HEIGHT / 2.0f) - (100 / 2.0f)), "./circle.png");
// Game logic
{
bool running = true;
bool buttons[4] = {};
float dt = 0.0f;
// Continue looping and processing events until user exits
while (running)
{
auto startTime = std::chrono::high_resolution_clock::now();
SDL_Event event;
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
running = false;
}
else if (event.type == SDL_KEYDOWN)
{
if (event.key.keysym.sym == SDLK_ESCAPE)
{
running = false;
}
else if (event.key.keysym.sym == SDLK_w)
{
buttons[Buttons::PaddleOneUp] = true;
}
else if (event.key.keysym.sym == SDLK_s)
{
buttons[Buttons::PaddleOneDown] = true;
}
else if (event.key.keysym.sym == SDLK_UP)
{
buttons[Buttons::PaddleTwoUp] = true;
}
else if (event.key.keysym.sym == SDLK_DOWN)
{
buttons[Buttons::PaddleTwoDown] = true;
}
}
else if (event.type == SDL_KEYUP)
{
if (event.key.keysym.sym == SDLK_w)
{
buttons[Buttons::PaddleOneUp] = false;
}
else if (event.key.keysym.sym == SDLK_s)
{
buttons[Buttons::PaddleOneDown] = false;
}
else if (event.key.keysym.sym == SDLK_UP)
{
buttons[Buttons::PaddleTwoUp] = false;
}
else if (event.key.keysym.sym == SDLK_DOWN)
{
buttons[Buttons::PaddleTwoDown] = false;
}
}
}
if (buttons[Buttons::PaddleOneUp])
{
paddleOne.velocity.y = -PADDLE_SPEED;
}
else if (buttons[Buttons::PaddleOneDown])
{
paddleOne.velocity.y = PADDLE_SPEED;
}
else
{
paddleOne.velocity.y = 0.0f;
}
if (buttons[Buttons::PaddleTwoUp])
{
paddleTwo.velocity.y = -PADDLE_SPEED;
}
else if (buttons[Buttons::PaddleTwoDown])
{
paddleTwo.velocity.y = PADDLE_SPEED;
}
else
{
paddleTwo.velocity.y = 0.0f;
}
// Update the paddle positions
paddleOne.Update(dt);
paddleTwo.Update(dt);
// Clear the window to black
SDL_SetRenderDrawColor(gRenderer, 0x0, 0x0, 0x0, 0xFF);
SDL_RenderClear(gRenderer);
// Set the draw color to be white
SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
// Draw the net
for (int y = 0; y < WINDOW_HEIGHT; ++y)
{
if (y % 5)
{
SDL_RenderDrawPoint(gRenderer, WINDOW_WIDTH / 2, y);
}
}
// Draw the ball
ball.Draw(gRenderer);
// Draw the paddles
paddleOne.Draw(gRenderer);
paddleTwo.Draw(gRenderer);
// Display the scores
playerOneScoreText.Draw();
playerTwoScoreText.Draw();
randomAssSprite.Draw();
// Present the backbuffer
SDL_RenderPresent(gRenderer);
// Calculate frame time
auto stopTime = std::chrono::high_resolution_clock::now();
dt = std::chrono::duration<float, std::chrono::milliseconds::period>(stopTime - startTime).count();
}
}
// Cleanup
SDL_DestroyRenderer(gRenderer);
SDL_DestroyWindow(gWindow);
TTF_CloseFont(scoreFont);
SDL_Quit();
return 0;
}

View File

@ -23,7 +23,52 @@ class Parser
public:
int Start(int SCREEN_W, int SCREEN_H)
{
//// variable declarations
//SDL_Window* win = NULL;
//SDL_Renderer* renderer = NULL;
//int w, h; // texture width & height
//// Initialize SDL.
//if (SDL_Init(SDL_INIT_VIDEO) < 0)
// return 1;
//// create the window and renderer
//// note that the renderer is accelerated
//win = SDL_CreateWindow("Image Loading", 100, 100, SCREEN_W, SCREEN_H, 0);
//renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
//// load our image
//SDL_Surface* imgSurface = IMG_Load("circle.png");
//// main loop
//while (1) {
// // event handling
// SDL_Event e;
// if (SDL_PollEvent(&e)) {
// if (e.type == SDL_QUIT)
// break;
// else if (e.type == SDL_KEYUP && e.key.keysym.sym == SDLK_ESCAPE)
// break;
// }
// // clear the screen
// SDL_RenderClear(renderer);
// // copy the texture to the rendering context
// SDL_RenderCopy(renderer, img, NULL, &texr);
// // flip the backbuffer
// // this means that everything that we prepared behind the screens is actually shown
// SDL_RenderPresent(renderer);
//}
//SDL_DestroyTexture(img);
//SDL_DestroyRenderer(renderer);
//SDL_DestroyWindow(win);
//return 0;
////Initialize SDL
//if (SDL_Init(SDL_INIT_VIDEO) < 0)
@ -58,7 +103,7 @@ public:
//SDL_DestroyWindow(window);
//Quit SDL subsystems
//SDL_Quit();
SDL_Quit();
return 0;
}

View File

@ -1,121 +0,0 @@
///*This source code copyrighted by Lazy Foo' Productions (2004-2020)
//and may not be redistributed without written permission.*/
//
////Using SDL and standard IO
//#include <SDL.h>
//#include <stdio.h>
//
////Screen dimension constants
//const int SCREEN_WIDTH = 640;
//const int SCREEN_HEIGHT = 480;
//
////Starts up SDL and creates window
//bool init();
//
////Loads media
//bool loadMedia();
//
////Frees media and shuts down SDL
//void close();
//
////The window we'll be rendering to
//SDL_Window* gWindow = NULL;
//
////The surface contained by the window
//SDL_Surface* gScreenSurface = NULL;
//
////The image we will load and show on the screen
//SDL_Surface* gHelloWorld = NULL;
//
//bool init()
//{
// //Initialization flag
// bool success = true;
//
// //Initialize SDL
// if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
// {
// printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
// success = false;
// }
// else
// {
// //Create window
// gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
// if( gWindow == NULL )
// {
// printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
// success = false;
// }
// else
// {
// //Get window surface
// gScreenSurface = SDL_GetWindowSurface( gWindow );
// }
// }
//
// return success;
//}
//
//bool loadMedia()
//{
// //Loading success flag
// bool success = true;
//
// //Load splash image
// gHelloWorld = SDL_LoadBMP( "./tut/hello_world.bmp" );
// if( gHelloWorld == NULL )
// {
// printf( "Unable to load image %s! SDL Error: %s\n", "./tut/hello_world.bmp", SDL_GetError() );
// success = false;
// }
//
// return success;
//}
//
//void close()
//{
// //Deallocate surface
// SDL_FreeSurface( gHelloWorld );
// gHelloWorld = NULL;
//
// //Destroy window
// SDL_DestroyWindow( gWindow );
// gWindow = NULL;
//
// //Quit SDL subsystems
// SDL_Quit();
//}
//
//int main( int argc, char* args[] )
//{
// //Start up SDL and create window
// if( !init() )
// {
// printf( "Failed to initialize!\n" );
// }
// else
// {
// //Load media
// if( !loadMedia() )
// {
// printf( "Failed to load media!\n" );
// }
// else
// {
// //Apply the image
// SDL_BlitSurface( gHelloWorld, NULL, gScreenSurface, NULL );
//
// //Update the surface
// SDL_UpdateWindowSurface( gWindow );
//
// //Wait two seconds
// SDL_Delay( 2000 );
// }
// }
//
// //Free resources and close SDL
// close();
//
// return 0;
//}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 900 KiB