Jump to content
  • Advertisement

Search the Community

Showing results for tags '2D' in content posted in Graphics and GPU Programming.



More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Categories

  • Audio
    • Music and Sound FX
  • Business
    • Business and Law
    • Career Development
    • Production and Management
  • Game Design
    • Game Design and Theory
    • Writing for Games
    • UX for Games
  • Industry
    • Interviews
    • Event Coverage
  • Programming
    • Artificial Intelligence
    • General and Gameplay Programming
    • Graphics and GPU Programming
    • Engines and Middleware
    • Math and Physics
    • Networking and Multiplayer
  • Visual Arts
  • Archive

Categories

  • Audio
  • Visual Arts
  • Programming
  • Writing

Categories

  • Game Dev Loadout
  • Game Dev Unchained

Categories

  • Game Developers Conference
    • GDC 2017
    • GDC 2018
  • Power-Up Digital Games Conference
    • PDGC I: Words of Wisdom
    • PDGC II: The Devs Strike Back
    • PDGC III: Syntax Error

Forums

  • Audio
    • Music and Sound FX
  • Business
    • Games Career Development
    • Production and Management
    • Games Business and Law
  • Game Design
    • Game Design and Theory
    • Writing for Games
  • Programming
    • Artificial Intelligence
    • Engines and Middleware
    • General and Gameplay Programming
    • Graphics and GPU Programming
    • Math and Physics
    • Networking and Multiplayer
  • Visual Arts
    • 2D and 3D Art
    • Critique and Feedback
  • Community
    • GameDev Challenges
    • GDNet+ Member Forum
    • GDNet Lounge
    • GDNet Comments, Suggestions, and Ideas
    • Coding Horrors
    • Your Announcements
    • Hobby Project Classifieds
    • Indie Showcase
    • Article Writing
  • Affiliates
    • NeHe Productions
    • AngelCode
  • Topical
    • Virtual and Augmented Reality
    • News
  • Workshops
    • C# Workshop
    • CPP Workshop
    • Freehand Drawing Workshop
    • Hands-On Interactive Game Development
    • SICP Workshop
    • XNA 4.0 Workshop
  • Archive
    • Topical
    • Affiliates
    • Contests
    • Technical
  • GameDev Challenges's Topics
  • For Beginners's Forum

Calendars

  • Community Calendar
  • Games Industry Events
  • Game Jams
  • GameDev Challenges's Schedule

Blogs

There are no results to display.

There are no results to display.

Product Groups

  • Advertisements
  • GameDev Gear

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


About Me


Website


Role


Twitter


Github


Twitch


Steam

Found 70 results

  1. Hello there, I have tried following various OpenGL tutorials and I'm now at a point where I can render multiple 2d sprites with textures. For that I have a sprite class: Header: #ifndef SPRITE_H #define SPRITE_H #include <GL/glew.h> #include "Shader.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "Texture.h" #include <stb_image.h> #include "Camera.h" class Sprite { public: Sprite(GLfloat x, GLfloat y, GLfloat width, GLfloat height, Shader& shader, Texture *texture); ~Sprite(); void draw(Camera &camera); void setPosition(float x, float y, float z); void move(float x, float y, float z); void setTexture(Texture *texture); Texture getTexture(); float x, y, width, height; private: void init(GLfloat x, GLfloat y, GLfloat width, GLfloat height, Shader& shader, Texture *texture); GLuint VBO = 0, VAO = 0, EBO = 0; GLint transformShaderLocation, viewShaderLocation, projectionShaderLocation; Shader* shader; glm::mat4 transform, projection, view; Texture *texture; }; #endif Code: #include "Sprite.h" Sprite::Sprite(GLfloat x, GLfloat y, GLfloat width, GLfloat height, Shader& shader, Texture *texture) { init(x, y, width, height, shader, texture); } void Sprite::init(GLfloat x, GLfloat y, GLfloat width, GLfloat height, Shader& shader, Texture *texture) { this->shader = &shader; this->x = x; this->y = y; this->width = width; this->height = height; GLfloat vertices[] = { width / 2 , height / 2, 0.0f, /* Top Right */ 1.0f, 1.0f, width / 2 , -height / 2 , 0.0f, /* Bottom Right*/ 1.0f, 0.0f, -width / 2 ,-height / 2 , 0.0f, /* Bottom Left */ 0.0f, 0.0f, -width / 2 , height / 2 , 0.0f, /* Top Left */ 0.0f, 1.0f }; GLuint indices[] = { 0, 1, 3, // 1 1, 2, 3 // 2 }; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); //Position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // TexCoord glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); transformShaderLocation = glGetUniformLocation(shader.program, "transform"); viewShaderLocation = glGetUniformLocation(shader.program, "view"); projectionShaderLocation = glGetUniformLocation(shader.program, "projection"); transform = glm::translate(transform, glm::vec3(x , y , 0)); this->texture = texture; } Sprite::~Sprite() { //DELETE BUFFERS glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); glDeleteBuffers(1, &VAO); delete texture; } void Sprite::draw(Camera &camera) { shader->Use(); glBindTexture(GL_TEXTURE_2D, texture->texture); view = camera.getView(); projection = camera.getProjection(); // Pass to shaders glUniformMatrix4fv(transformShaderLocation, 1, GL_FALSE, glm::value_ptr(transform)); glUniformMatrix4fv(viewShaderLocation, 1, GL_FALSE, glm::value_ptr(view)); // Note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once. glUniformMatrix4fv(projectionShaderLocation, 1, GL_FALSE, glm::value_ptr(projection)); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glBindVertexArray(0); } void Sprite::setPosition(float x, float y, float z) { //Z? transform = glm::translate(transform, glm::vec3(x - this->x , y - this->y , z)); this->x = x; this->y = y; } void Sprite::move(float x, float y, float z) { transform = glm::translate(transform, glm::vec3(x, y , z)); this->x += x; this->y += y; } void Sprite::setTexture(Texture *texture) { delete this->texture; this->texture = texture; } Texture Sprite::getTexture() { return *texture; } When I want to draw something, I create an instance of the sprite class with it's own Texture and use sprite->draw(); in the draw loop for each sprite to draw it. This works perfectly fine. To improve the performance, I now want to create a spritebatch. As far as I understood it puts all the sprites together so it can send them all at once to the gpu. I had no clue how to get started, so I just created a spritebatch class which put all the vertices and indices into one object every time draw() is called, and actually only draws when flush() is called. Here's the header file: #ifndef SPRITEBATCH_H #define SPRITEBATCH_H #include <glm/glm.hpp> #include "Texture.h" #include <GL/glew.h> #include "Camera.h" #include "Shader.h" #include <vector> class SpriteBatch { public: SpriteBatch(Shader& shader, Camera &camera); ~SpriteBatch(); void draw(Texture *texture, GLfloat x, GLfloat y, GLfloat width, GLfloat height); void flush(); private: GLfloat vertices[800]; GLuint indices[800]; int index{ 0 }; int indicesIndex{ 0 }; GLuint VBO = 0, VAO = 0, EBO = 0; GLint transformShaderLocation, viewShaderLocation, projectionShaderLocation; Shader *shader; Camera *camera; std::vector<Texture*>* textures; glm::mat4 transform, projection, view; }; #endif And the class. I added some comments here: #include "SpriteBatch.h" SpriteBatch::SpriteBatch(Shader& shader, Camera &camera) { this->shader = &shader; this->camera = &camera; textures = new std::vector<Texture*>(); } SpriteBatch::~SpriteBatch() { glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); glDeleteBuffers(1, &VAO); //delete texture; } void SpriteBatch::draw(Texture *texture, GLfloat x, GLfloat y, GLfloat width, GLfloat height) { textures->push_back(texture); vertices[index] = width/2 ; vertices[index + 1] = height/2; vertices[index + 2] = 0.0f; vertices[index + 3] = 1.0f; vertices[index + 4] = 1.0f; vertices[index + 5] = width / 2; vertices[index + 6] = -height / 2; vertices[index + 7] = 0.0f; vertices[index + 8] = 1.0f; vertices[index + 9] = 0.0f; vertices[index + 10] = -width / 2; vertices[index + 11] = -height / 2; vertices[index + 12] = 0.0f; vertices[index + 13] = 0.0f; vertices[index + 14] = 0.0f; vertices[index + 15] = -width / 2; vertices[index + 16] = height / 2; vertices[index + 17] = 0.0f; vertices[index + 18] = 0.0f; vertices[index + 19] = 1.0f; index += 20; indices[indicesIndex] = 0; indices[indicesIndex + 1] = 1; indices[indicesIndex + 2] = 3; indices[indicesIndex + 3] = 1; indices[indicesIndex + 4] = 2; indices[indicesIndex + 5] = 3; indicesIndex += 6; } void SpriteBatch::flush() { if (index == 0) return; //Ensures that there are sprites added //Debug information. This works perfectly int spritesInBatch = index / 20; std::cout << spritesInBatch << " I : " << index << std::endl; int drawn = 0; //Create Buffers glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); //Bind vertices glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //Bind indices glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); //Position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // TexCoord glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); //VAO glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); //Shader locations transformShaderLocation = glGetUniformLocation(shader->program, "transform"); viewShaderLocation = glGetUniformLocation(shader->program, "view"); projectionShaderLocation = glGetUniformLocation(shader->program, "projection"); //Draw //So this sets the texture for each sprites and draws it afterwards with the right texture. At least that's how it should work. for (int i = 0; i < spritesInBatch; i++) { Texture *tex = textures->at(i); shader->Use(); glBindTexture(GL_TEXTURE_2D, tex->texture); //? view = camera->getView(); projection = camera->getProjection(); // Pass them to the shaders glUniformMatrix4fv(transformShaderLocation, 1, GL_FALSE, glm::value_ptr(transform)); glUniformMatrix4fv(viewShaderLocation, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projectionShaderLocation, 1, GL_FALSE, glm::value_ptr(projection)); //Draw VAO glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, indicesIndex, GL_UNSIGNED_INT, 0); glBindVertexArray(0); } //Sets index 0 to welcome new sprites index = 0; } It also puts the textures into a list. The code to draw two sprites is this: spriteBatch->draw(&_sprite1->getTexture(), _sprite1->x, _sprite1->y, _sprite1->width, _sprite1->height); spriteBatch->draw(&_sprite1->getTexture(), _sprite1->x+10, _sprite1->y+10, _sprite1->width*2, _sprite1->height); spriteBatch->flush(); but I only get one small black rectangle in the bottom left corner. It works perfectly when I draw the sprites without the spritebatch; _sprite1->draw(*camera); _sprite2->draw(*camera); I think I messed up in the flush() method, but I have no clue how to implement this. I'd be grateful if someone can help me with it. Thank you!
  2. I hope this is the correct place to post this, but I have been having some issues. I am new to this site and to python/pygame so please humor me. My game is suppose to have a four way split screen so that four players can compete against each other at once. The way I went about creating this is by making an "action_surface" that acts as the main canvas and four subsurface's that are positioned into four quadrants. As I create each subsurface object, I store it into a list so that each "camera" (aka. subsurface) can be easily accessed. Here is the code for that: Camera.py import pygame, random class Camera: cameras = [] def __init__(self, screen, action_surface, screen_size): self.screen = screen self.surface = action_surface.subsurface(pygame.Rect(0,0,screen_size[0]/2,screen_size[1]/2)) Camera.cameras.append(self.surface) cam_count = len(Camera.cameras) print(cam_count) print(Camera.cameras) @staticmethod def update(screen, screen_size): for s in range(0,100): pygame.draw.rect(Camera.cameras[1], (0,255,255), pygame.Rect(s*100, s*100, 10, 10)) pygame.draw.rect(Camera.cameras[3], (0,0,255), pygame.Rect(s*110, s*110, 10, 10)) if len(Camera.cameras) > 0: for i in range(0, len(Camera.cameras)): if (i%2==0): screen.blit(Camera.cameras[i], (0, ((i/2)*(screen_size[1]/(len(Camera.cameras)/2))))) else: screen.blit(Camera.cameras[i], ((screen_size[0]/2), (((i/2)-0.5)*(screen_size[1]/(len(Camera.cameras)/2))))) In theory, what this should allow me to do is access each camera from their index and draw to the individually. Unfortunately, this is not what happens. In reality, when I select any of the camera's and attempt to draw art, all the cameras (surfaces) are updated with a duplicate copy of such art! As you might be able to tell, this is not the desired effect I am going for. But, none the less this has happened. I am hoping that maybe somebody with more experience than me can give some insight on how to fix this problem. Thanks.
  3. I have the following setup in a GUI library I'm making (for fun). Ignore the colors and positions being integers, it's just to serve the purpose of illustration. Code: // Example program #include <iostream> #include <string> class Rect { public: virtual void Draw(const int position) const = 0; }; class ColorRect : public Rect { public: virtual void Draw(const int position) const override { /* does a draw */ } int color; }; class TextureRect : public Rect { public: virtual void Draw(const int position) const override { /* does a draw textured */ } int texture; }; class Widget { public: Rect* background; int position; virtual void Draw() const { background->Draw(position); } virtual void Update() { /* might do stuff */ } }; class Button : public Widget { public: virtual void Draw() const override { Widget::Draw(); border->Draw(position); } Rect* border; }; int main() { ColorRect redRect; redRect.color = 1; ColorRect blueRect; blueRect.color = 2; TextureRect textRect; textRect.texture = 1; Button b1; b1.border = &blueRect; b1.background = &redRect; b1.position = 1; Button b2; b2.border = &blueRect; b2.background = &textRect; b2.position = 2 while(true) { b1.Update(); b2.Update(); b1.Draw(); b2.Draw(); } } I think it should be obvious that the Rect class is a Flyweight that is used by multiple different objects at the same time. What I want to do now, for example, is have b1 animate it's border Rect. This animation should not affect the other Widget*s that use the same Rect*, i.e their animation needs to be paused, started and have a different "current frame". I'm hesitant to create an "Animated Rect" class or something, because then the only way to handle separate animation is for that class to hold a map of pointers to Widgets that are using it or something. In addition; I would also want to animate, for example, the position. Which means ideally the interface that you use to animate positions (which are specific to the object), is the same as the one used to animate the texture or color (which is shared amongst objects currently). Whatever it is that would hold the Animation state would need to hold a few things like frame_rate and probably time_since_updated or something. I just can't work out where to put it, or what to reorganise to fit in.
  4. Hey guys, what's up? I've been building a 2D game with SDL, and I'd really like it to have that retro console/arcade look and feel. This mostly because those are the kinds of games I play, and have since I was a kid, but also partly because 8-bit sprites or (S)NES sprite sheets are about as good as I get in terms of graphic design (lol). But those old games had really small sprites, 8x8 at the least or 64x64 at the most. And of course, those old consoles had a surprisingly small resolution of 256x240. Another important note here: I'm really only targeting PCs for now; I know SDL can be ported to pretty much anything, but I only have my PC to test it on. I'm also using Windows 10 x64 and Visual Studio 2017, if that helps. So I started out by using "fake" fullscreen (passing SDL_WINDOW_FULLSCREEN_DESKTOP into the window creation functions). But this turned out to be a problem because SDL's drawing functions are pixel based. This is good IMOt, because it makes the math simpler and keeps the images crisper. But you can't get half-a-pixel, so scaling to fit the player's desktop is literally impossible in some cases. The end result is I had to draw black bars across the top and bottom, not just on the left and right. If possible I would like to avoid that, so I switched to "real" fullscreen (SDL_WINDOW_FULLSCREE). The lowest I could get it to go is 640x480, which is perfect (all image widths and heights can be multiplied by two to fill in the space). But is 640x480 still supported on modern monitors? The fact that it worked on my laptop is all well and good, but I'm afraid it would be a problem for others. I remember using Game Maker (before it was a "studio") back in the early 2000s and that resolution was not an issue back then. But is it still supported in 2018? My laptop is relatively new (about 2 years old), a Dell running at 1366x768 normally. If the answer is "no", what resolution(s) should I be using for this type of game? Thanks & happy Labor Day weekend!
  5. hello. I'm trying to understand how i can convert a bitmap array to a single yuv file. I'm trying to do this for register webcamera from windows and android. Next i would use ffmpeg for convert the yuv file to a video. Is possible? My chose to the single file because i save the max possible space in a stream in memory after write it to disk, for performances. i found this http://embedav.blogspot.com/2013/06/convert-rgb-to-yuv420-planar-format-in.html but i'm not understand how i can use it for an array of bitmap.but a yuv file not have any header? very thanks. ps. I must use java or c# but i understand c++ as well i should do something of easy , then no big code library in c++ but is possible in some methods to save big quantity of data in only a file for transform this file to a video with ffmpeg? this is my real question.
  6. Hello, I am currently reading Procedural Generation Content with C++. They start you off with a basic template using SFML, and it slowly builds off it. I have noticed a bug that is really bothering me now. I thought it might have been an error on my part. Unfortunately, it seems to be the source code in general. I did a google for the source code on github to see if someone fixed the problem. I only found some people who literally copied the final example's source code, which isn't helpful because I own it already. What is happening is when I am stationary and press either down or right, there is a quick red flicker. If I am already moving and press down or right, there is no problem. I've tried messing around with the texture manager and they have done in a way I have not come across yet and I'm wondering if this is the issue or if I'm wasting my time. I would like to keep the book's code, but I might just replace the whole thing. // Gets a texture from the texture manager from an ID. sf::Texture& TextureManager::GetTexture(const int textureID) { auto it = m_textures.begin(); auto found = false; while (it != m_textures.end()) { if (it->second.first == textureID) { return *it->second.second; } else { ++it; } } } I can't recall exactly what I did. But messing around with a modern for loop and the traditional way gave me different results. With one of the for loops, I got a "white" flicker when I went left now. I changed it back and the white is now gone. So I believe it has something to do with this. The original code from the book did this for (auto it = m_textures.begin(); it != m_textures.end(); ++it) { if (it->second.first == textureID) { return *it->second.second; } } When I changed the for loop to the modern iteration, the white flicker appears. So I have no idea what that means since I thought it was the same thing. I hope this is enough information for an idea of the problem. Down below I posted a link of the source code from someone's Github that is basically the exact same from the basic template standpoint. If anyone can get me through this, I would greatly appreciate it. https://github.com/utilForever/ProceduralContentGeneration Thanks, have a great day!
  7. Hi all, I have been spending so much time trying to replicate a basic effect similar to these: Glowing line or Tron lines or More tron lines I've tried to use blurring using the shrink, horizontal and vertical passes, expand technique but the results of my implementation are crappy. I simply want my custom, non-textured 2d polygons to have a glow around them, in a size and color I can define. For example, I want to draw a blue rectangle using 2 triangles and have a glow around the shape. I am not sure how to best achieve this and what technique to use. I am prototyping an idea so performance is not an issue, I just want to get the pixels properly on the screen and I just can't figure out how to do it! It seems this effect has been done to death by now and should be easy, but I can't wrap my head around it, I'm not good at shaders at all I'm afraid. Are the Rastertek blur or glow tutorials the way to go? I'm using DirectX 11. Any tips or suggestions would be greatly appreciated!
  8. Here is another example and request to improve the quality of special rare card with Shadero The shine effect use the object rotation and there is no script added Le holographic use the world space coordinate to change the color plasma of the holographic texture. Also, a mask is applied and, you can easily add a soft holographic overlay over it. Hope you like it. shadero180.mp4
  9. The orb include: multiple texture change multiple wave distortion bubble effect smoke like distortion twist distortion filters color hdr support fisheye effect Hope you like it Shadero_Sprite_2D_Shader_Editor_Diablo_Like_Orb.mp4
  10. Hi guys, I'm having a problem rendering with DWrite, and I don't understand why, can you help me figure it out? As you can see in the image below, if you look carefully you'll notice that the top of R8 is cut (missing 1 row of pixels), the bottom of R11 is cut again, the 4 in R14 is rendered weird compared to the 4 in R4 and so on, if you look closely you'll spot more yourself. I can't figure out why ūüėē Under the image I'll also leave the code, in case I'm doing something wrong like with type conversion or stuff. Any help is much appreciated #include "GBAEmulator_PCH.h" #include "Disassembler.h" #include "GBAEmulator.h" Disassembler::Disassembler(LONG width, LONG height, HINSTANCE hInstance, GBAEmulator* emuInstance) : D2DWindowBase(width, height, hInstance, emuInstance), m_background(0.156f, 0.087f, 0.16f, 1.f), m_textFormat{ nullptr } { //Init Window std::string className = "Disassembler"; std::string windowName = "Disassembler"; WNDCLASSEX clientClass{}; clientClass.cbSize = sizeof(WNDCLASSEX); clientClass.style = CS_HREDRAW | CS_VREDRAW; clientClass.lpfnWndProc = GBAEmulator::DisassemblerWinProc; clientClass.hInstance = m_hInstance; //clientClass.hIcon =; TODO: Add Icon clientClass.hCursor = LoadCursor(m_hInstance, IDC_ARROW); clientClass.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1); clientClass.lpszClassName = className.c_str(); //clientClass.hIconSm =; TODO: Add Icon DWORD windowStyle = WS_VISIBLE | WS_CAPTION | WS_MINIMIZEBOX | WS_TABSTOP | WS_SYSMENU; m_isValid = InitWindow(windowName, clientClass, windowStyle, false); //Init DWrite if (m_isValid) m_isValid = InitDWrite(); std::vector<std::wstring> tempEntries{ L"PC: ", L"R0: ", L"R1: ", L"R2: ", L"R3: ", L"R4: ", L"R5: ", L"R6: ", L"R7: ", L"R8: ", L"R9: ", L"R10: ", L"R11: ", L"R12: ", L"R13: ", L"R14: ", L"R15: ", L"R16: " }; std::wstring value = L"-UNDEFINED-"; FLOAT left{}, top{}, right{ 300.f }, bottom{ 50.f }; for (auto& s : tempEntries) { m_entries.emplace_back(TextEntry{ s, value, D2D1_RECT_F{ left, top, right, bottom} }); top += 30.f; bottom += 30.f; } } bool Disassembler::InitDWrite() { //Set Text Format HRESULT hr; hr = m_DWriteFactory->CreateTextFormat( L"consolas", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 22.f, L"en-US", &m_textFormat ); if (FAILED(hr)) { MessageBox(NULL, "Failed to create TextFormat", "Error", MB_OK); return false; } //Set Colors m_renderTarget->CreateSolidColorBrush( D2D1::ColorF(D2D1::ColorF::SkyBlue), &m_fillBrush1 ); m_renderTarget->CreateSolidColorBrush( D2D1::ColorF(D2D1::ColorF::Crimson), &m_fillBrush2 ); return true; } Disassembler::~Disassembler() { DestroyWindow(m_hwnd); if (m_textFormat) m_textFormat->Release(); if (m_fillBrush1) m_fillBrush1->Release(); if (m_fillBrush2) m_fillBrush2->Release(); } void Disassembler::Updade(float deltaTime) { } void Disassembler::Draw() { m_renderTarget->BeginDraw(); m_renderTarget->Clear(m_background); for (auto& entry : m_entries) { DrawEntryWithShadow(entry); } m_renderTarget->EndDraw(); } void Disassembler::DrawEntryWithShadow(const TextEntry& entry) { //shadow offset D2D1_RECT_F shadowPos = entry.position; shadowPos.top += 1.05f; shadowPos.left -= 0.95f; //draw text DrawEntry(entry.text, shadowPos, m_fillBrush2); DrawEntry(entry.text, entry.position, m_fillBrush1); D2D1_RECT_F valuePos = entry.position; FLOAT valueOffset = 50.f; valuePos.left += valueOffset; valuePos.right += valueOffset; shadowPos.left += valueOffset; shadowPos.right += valueOffset; //draw value DrawEntry(entry.value, shadowPos, m_fillBrush2); DrawEntry(entry.value, valuePos, m_fillBrush1); } void Disassembler::DrawEntry(const std::wstring& text, const D2D1_RECT_F& pos, ID2D1SolidColorBrush* brush) { m_renderTarget->DrawTextA( text.c_str(), static_cast<UINT>(text.size()), m_textFormat, pos, brush, D2D1_DRAW_TEXT_OPTIONS_NONE ); }
  11. If someone could assist me through this I would be really grateful. I'm using SharpDX/C#/WinForms but I think this could more apply to directx in general. I'm very new to graphics programming and I'm really just trying to do something as simple as displaying a rectangle to the screen. Here is my issue: I have the below code: ---------------------------------------------------------- var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(1024, 768, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = false, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; I'm not sure if the window is loading in full screen. Actually to make it go full screen I actually have to set the forms property to: this.WindowState = FormWindowState.Maximized; but that only seems lke Im using a C# code to maximize the form. For instance if I don't set the form to maximize, the form loads at the original size if IsWindowed is set to false. I recall with directx programing using dx7, when I set full screen you could actually see what looked like a display resolution change. I'm not seeing that. It pretty much looks like the form is loaded at the same size as the screen and not the value I provide in modeDescription. This is not what I want as well because I want to set the display to 1024x768 to avoid stretching of my graphics in wide screens. Can someone help me make sense of this please.
  12. like this? const D3DXMATRIX robertx = D3DXMATRIX(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
  13. Hello everyone, I'm trying to display a 2D texture to screen but the rendering isn't working correctly. First of all I did follow this tutorial to be able to render a Text to screen (I adapted it to render with OpenGL ES 2.0) : https://learnopengl.com/code_viewer.php?code=in-practice/text_rendering So here is the shader I'm using : const char gVertexShader[] = "#version 320 es\n" "layout (location = 0) in vec4 vertex;\n" "out vec2 TexCoords;\n" "uniform mat4 projection;\n" "void main() {\n" " gl_Position = projection * vec4(vertex.xy, 0.0, 1.0);\n" " TexCoords = vertex.zw;\n" "}\n"; const char gFragmentShader[] = "#version 320 es\n" "precision mediump float;\n" "in vec2 TexCoords;\n" "out vec4 color;\n" "uniform sampler2D text;\n" "uniform vec3 textColor;\n" "void main() {\n" " vec4 sampled = vec4(1.0, 1.0, 1.0, texture(text, TexCoords).r);\n" " color = vec4(textColor, 1.0) * sampled;\n" "}\n"; The render text works very well so I would like to keep those Shaders program to render a texture loaded from PNG. For that I'm using libPNG to load the PNG to a texture, here is my code : GLuint Cluster::loadPngFromPath(const char *file_name, int *width, int *height) { png_byte header[8]; FILE *fp = fopen(file_name, "rb"); if (fp == 0) { return 0; } fread(header, 1, 8, fp); if (png_sig_cmp(header, 0, 8)) { fclose(fp); return 0; } png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { fclose(fp); return 0; } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL); fclose(fp); return 0; } png_infop end_info = png_create_info_struct(png_ptr); if (!end_info) { png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL); fclose(fp); return 0; } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); fclose(fp); return 0; } png_init_io(png_ptr, fp); png_set_sig_bytes(png_ptr, 8); png_read_info(png_ptr, info_ptr); int bit_depth, color_type; png_uint_32 temp_width, temp_height; png_get_IHDR(png_ptr, info_ptr, &temp_width, &temp_height, &bit_depth, &color_type, NULL, NULL, NULL); if (width) { *width = temp_width; } if (height) { *height = temp_height; } png_read_update_info(png_ptr, info_ptr); int rowbytes = png_get_rowbytes(png_ptr, info_ptr); rowbytes += 3 - ((rowbytes-1) % 4); png_byte * image_data; image_data = (png_byte *) malloc(rowbytes * temp_height * sizeof(png_byte)+15); if (image_data == NULL) { png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); fclose(fp); return 0; } png_bytep * row_pointers = (png_bytep *) malloc(temp_height * sizeof(png_bytep)); if (row_pointers == NULL) { png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); free(image_data); fclose(fp); return 0; } int i; for (i = 0; i < temp_height; i++) { row_pointers[temp_height - 1 - i] = image_data + i * rowbytes; } png_read_image(png_ptr, row_pointers); GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, GL_ZERO, GL_RGB, temp_width, temp_height, GL_ZERO, GL_RGB, GL_UNSIGNED_BYTE, image_data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); free(image_data); free(row_pointers); fclose(fp); return texture; } This code just generates the texture and I store the id on memory And then I want to display my texture on any position (X, Y) of my screen so I did the following (That's works, at least the positioning). //MY TEXTURE IS 32x32 pixels ! void Cluster::printTexture(GLuint idTexture, GLfloat x, GLfloat y) { glActiveTexture(GL_TEXTURE0); glBindVertexArray(VAO); GLfloat vertices[6][4] = { { x, y + 32, 0.0, 0.0 }, { x, y, 0.0, 1.0 }, { x + 32, y, 1.0, 1.0 }, { x, y + 32, 0.0, 0.0 }, { x + 32, y, 1.0, 1.0 }, { x + 32, y + 32, 1.0, 0.0 } }; glBindTexture(GL_TEXTURE_2D, idTexture); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferSubData(GL_ARRAY_BUFFER, GL_ZERO, sizeof(vertices), vertices); glBindBuffer(GL_ARRAY_BUFFER, GL_ZERO); glUniform1i(this->mTextShaderHandle, GL_ZERO); glDrawArrays(GL_TRIANGLE_STRIP, GL_ZERO, 6); } My .png is a blue square. The result is that my texture is not loaded correctly. It is not complete and there are many small black spots. I don't know what's going on ? It could be the vertices or the load ? Or maybe I need to add something on the shader. I don't know, I really need help. Thanks !
  14. So I have this code to create a textbox ui element with SDL2 and for the most part it works: #include <iostream> #include "TextboxUi.hpp" #include "../Engine/Text.hpp"; #include "../Utility/SdlUtility.hpp"; #include "../Engine/Game.hpp"; TextboxUi::TextboxUi(int x, int y, int width, int height, SDL_Color backgroundColor, SDL_Color textColor) { _background = {x, y, width, height}; _backgroundColor = backgroundColor; _textColor = textColor; } void TextboxUi::setValue(std::string value) { _value = value; } void TextboxUi::handleInput(SDL_Event &event) { switch (event.type) { case SDL_TEXTINPUT: { if (_isActive) { _value += event.text.text; _cursorPosition += 1; } break; } case SDL_TEXTEDITING: { break; } case SDL_KEYUP: { switch (event.key.keysym.sym) { case SDLK_BACKSPACE: if (_value.size() == 0) { break; } _cursorPosition -= 1; _value.erase(_cursorPosition, 1); break; case SDLK_s: { if (!_isActive) { _isActive = true; } break; } case SDLK_LEFT: { if (_cursorPosition == 0) { break; } _cursorPosition -= 1; break; } case SDLK_RIGHT: { if (_cursorPosition == _value.size()) { break; } _cursorPosition += 1; break; } case SDLK_ESCAPE: _isActive = false; _value = ""; break; default: break; } break; } default: break; } } void TextboxUi::enable() { _isActive = true; } void TextboxUi::disable() { _isActive = false; } void TextboxUi::draw(SDL_Renderer* renderer) { SdlUtility::setRenderDrawColor(Game::renderer, _backgroundColor); SDL_RenderFillRect(Game::renderer, &_background); // if there is no text Text would fail to create the surface and texture (not quite sure why) if (_value.size() == 0) { return; } Text text = Text("Assets/Fonts/Vera.ttf", 12, _value, _textColor); text.display(_background.x + 5, _background.y + 2); // @todo implement visual for text cursor } The one last thing I want to do before I call this textbox done for the time being is try to figure out how to simulate a cursor. At this point just getting a solid cursor would be final (though ultimately I would like to have it blinking. I have the cursor position so I know between which characters the cursor should be however I am not sure how to calculate that. Is there a way to calculate the width of a given string without actually rendering said sting to the screen with SDL2 / SDL2_ttf?
  15. Hello Everyone! I'm learning openGL, and currently i'm making a simple 2D game engine to test what I've learn so far. In order to not say to much, i made a video in which i'm showing you the behavior of the rendering. Video: What i was expecting to happen, was the player moving around. When i render only the player, he moves as i would expect. When i add a second Sprite object, instead of the Player, this new sprite object is moving and finally if i add a third Sprite object the third one is moving. And the weird think is that i'm transforming the Vertices of the Player so why the transformation is being applied somewhere else? Take a look at my code: Sprite Class (You mostly need to see the Constructor, the Render Method and the Move Method) #include "Brain.h" #include <glm/gtc/matrix_transform.hpp> #include <vector> struct Sprite::Implementation { //Position. struct pos pos; //Tag. std::string tag; //Texture. Texture *texture; //Model matrix. glm::mat4 model; //Vertex Array Object. VertexArray *vao; //Vertex Buffer Object. VertexBuffer *vbo; //Layout. VertexBufferLayout *layout; //Index Buffer Object. IndexBuffer *ibo; //Shader. Shader *program; //Brains. std::vector<Brain *> brains; //Deconstructor. ~Implementation(); }; Sprite::Sprite(std::string image_path, std::string tag, float x, float y) { //Create Pointer To Implementaion. m_Impl = new Implementation(); //Set the Position of the Sprite object. m_Impl->pos.x = x; m_Impl->pos.y = y; //Set the tag. m_Impl->tag = tag; //Create The Texture. m_Impl->texture = new Texture(image_path); //Initialize the model Matrix. m_Impl->model = glm::mat4(1.0f); //Get the Width and the Height of the Texture. int width = m_Impl->texture->GetWidth(); int height = m_Impl->texture->GetHeight(); //Create the Verticies. float verticies[] = { //Positions //Texture Coordinates. x, y, 0.0f, 0.0f, x + width, y, 1.0f, 0.0f, x + width, y + height, 1.0f, 1.0f, x, y + height, 0.0f, 1.0f }; //Create the Indicies. unsigned int indicies[] = { 0, 1, 2, 2, 3, 0 }; //Create Vertex Array. m_Impl->vao = new VertexArray(); //Create the Vertex Buffer. m_Impl->vbo = new VertexBuffer((void *)verticies, sizeof(verticies)); //Create The Layout. m_Impl->layout = new VertexBufferLayout(); m_Impl->layout->PushFloat(2); m_Impl->layout->PushFloat(2); m_Impl->vao->AddBuffer(m_Impl->vbo, m_Impl->layout); //Create the Index Buffer. m_Impl->ibo = new IndexBuffer(indicies, 6); //Create the new shader. m_Impl->program = new Shader("Shaders/SpriteShader.shader"); } //Render. void Sprite::Render(Window * window) { //Create the projection Matrix based on the current window width and height. glm::mat4 proj = glm::ortho(0.0f, (float)window->GetWidth(), 0.0f, (float)window->GetHeight(), -1.0f, 1.0f); //Set the MVP Uniform. m_Impl->program->setUniformMat4f("u_MVP", proj * m_Impl->model); //Run All The Brains (Scripts) of this game object (sprite). for (unsigned int i = 0; i < m_Impl->brains.size(); i++) { //Get Current Brain. Brain *brain = m_Impl->brains[i]; //Call the start function only once! if (brain->GetStart()) { brain->SetStart(false); brain->Start(); } //Call the update function every frame. brain->Update(); } //Render. window->GetRenderer()->Draw(m_Impl->vao, m_Impl->ibo, m_Impl->texture, m_Impl->program); } void Sprite::Move(float speed, bool left, bool right, bool up, bool down) { if (left) { m_Impl->pos.x -= speed; m_Impl->model = glm::translate(m_Impl->model, glm::vec3(-speed, 0, 0)); } if (right) { m_Impl->pos.x += speed; m_Impl->model = glm::translate(m_Impl->model, glm::vec3(speed, 0, 0)); } if (up) { m_Impl->pos.y += speed; m_Impl->model = glm::translate(m_Impl->model, glm::vec3(0, speed, 0)); } if (down) { m_Impl->pos.y -= speed; m_Impl->model = glm::translate(m_Impl->model, glm::vec3(0, -speed, 0)); } } void Sprite::AddBrain(Brain * brain) { //Push back the brain object. m_Impl->brains.push_back(brain); } pos *Sprite::GetPos() { return &m_Impl->pos; } std::string Sprite::GetTag() { return m_Impl->tag; } int Sprite::GetWidth() { return m_Impl->texture->GetWidth(); } int Sprite::GetHeight() { return m_Impl->texture->GetHeight(); } Sprite::~Sprite() { delete m_Impl; } //Implementation Deconstructor. Sprite::Implementation::~Implementation() { delete texture; delete vao; delete vbo; delete layout; delete ibo; delete program; } Renderer Class #include "Renderer.h" #include "Error.h" Renderer::Renderer() { } Renderer::~Renderer() { } void Renderer::Draw(VertexArray * vao, IndexBuffer * ibo, Texture *texture, Shader * program) { vao->Bind(); ibo->Bind(); program->Bind(); if (texture != NULL) texture->Bind(); GLCall(glDrawElements(GL_TRIANGLES, ibo->GetCount(), GL_UNSIGNED_INT, NULL)); } void Renderer::Clear(float r, float g, float b) { GLCall(glClearColor(r, g, b, 1.0)); GLCall(glClear(GL_COLOR_BUFFER_BIT)); } void Renderer::Update(GLFWwindow *window) { /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); } Shader Code #shader vertex #version 330 core layout(location = 0) in vec4 aPos; layout(location = 1) in vec2 aTexCoord; out vec2 t_TexCoord; uniform mat4 u_MVP; void main() { gl_Position = u_MVP * aPos; t_TexCoord = aTexCoord; } #shader fragment #version 330 core out vec4 aColor; in vec2 t_TexCoord; uniform sampler2D u_Texture; void main() { aColor = texture(u_Texture, t_TexCoord); } Also i'm pretty sure that every time i'm hitting the up, down, left and right arrows on the keyboard, i'm changing the model Matrix of the Player and not the others. Window Class: #include "Window.h" #include <GL/glew.h> #include <GLFW/glfw3.h> #include "Error.h" #include "Renderer.h" #include "Scene.h" #include "Input.h" //Global Variables. int screen_width, screen_height; //On Window Resize. void OnWindowResize(GLFWwindow *window, int width, int height); //Implementation Structure. struct Window::Implementation { //GLFW Window. GLFWwindow *GLFW_window; //Renderer. Renderer *renderer; //Delta Time. double delta_time; //Frames Per Second. int fps; //Scene. Scene *scnene; //Input. Input *input; //Deconstructor. ~Implementation(); }; //Window Constructor. Window::Window(std::string title, int width, int height) { //Initializing width and height. screen_width = width; screen_height = height; //Create Pointer To Implementation. m_Impl = new Implementation(); //Try initializing GLFW. if (!glfwInit()) { std::cout << "GLFW could not be initialized!" << std::endl; std::cout << "Press ENTER to exit..." << std::endl; std::cin.get(); exit(-1); } //Setting up OpenGL Version 3.3 Core Profile. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); /* Create a windowed mode window and its OpenGL context */ m_Impl->GLFW_window = glfwCreateWindow(width, height, title.c_str(), NULL, NULL); if (!m_Impl->GLFW_window) { std::cout << "GLFW could not create a window!" << std::endl; std::cout << "Press ENTER to exit..." << std::endl; std::cin.get(); glfwTerminate(); exit(-1); } /* Make the window's context current */ glfwMakeContextCurrent(m_Impl->GLFW_window); //Initialize GLEW. if(glewInit() != GLEW_OK) { std::cout << "GLEW could not be initialized!" << std::endl; std::cout << "Press ENTER to exit..." << std::endl; std::cin.get(); glfwTerminate(); exit(-1); } //Enabling Blending. GLCall(glEnable(GL_BLEND)); GLCall(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); //Setting the ViewPort. GLCall(glViewport(0, 0, width, height)); //**********Initializing Implementation**********// m_Impl->renderer = new Renderer(); m_Impl->delta_time = 0.0; m_Impl->fps = 0; m_Impl->input = new Input(this); //**********Initializing Implementation**********// //Set Frame Buffer Size Callback. glfwSetFramebufferSizeCallback(m_Impl->GLFW_window, OnWindowResize); } //Window Deconstructor. Window::~Window() { delete m_Impl; } //Window Main Loop. void Window::MainLoop() { //Time Variables. double start_time = 0, end_time = 0, old_time = 0, total_time = 0; //Frames Counter. int frames = 0; /* Loop until the user closes the window */ while (!glfwWindowShouldClose(m_Impl->GLFW_window)) { old_time = start_time; //Total time of previous frame. start_time = glfwGetTime(); //Current frame start time. //Calculate the Delta Time. m_Impl->delta_time = start_time - old_time; //Get Frames Per Second. if (total_time >= 1) { m_Impl->fps = frames; total_time = 0; frames = 0; } //Clearing The Screen. m_Impl->renderer->Clear(0, 0, 0); //Render The Scene. if (m_Impl->scnene != NULL) m_Impl->scnene->Render(this); //Updating the Screen. m_Impl->renderer->Update(m_Impl->GLFW_window); //Increasing frames counter. frames++; //End Time. end_time = glfwGetTime(); //Total time after the frame completed. total_time += end_time - start_time; } //Terminate GLFW. glfwTerminate(); } //Load Scene. void Window::LoadScene(Scene * scene) { //Set the scene. m_Impl->scnene = scene; } //Get Delta Time. double Window::GetDeltaTime() { return m_Impl->delta_time; } //Get FPS. int Window::GetFPS() { return m_Impl->fps; } //Get Width. int Window::GetWidth() { return screen_width; } //Get Height. int Window::GetHeight() { return screen_height; } //Get Input. Input * Window::GetInput() { return m_Impl->input; } Renderer * Window::GetRenderer() { return m_Impl->renderer; } GLFWwindow * Window::GetGLFWindow() { return m_Impl->GLFW_window; } //Implementation Deconstructor. Window::Implementation::~Implementation() { delete renderer; delete input; } //OnWindowResize void OnWindowResize(GLFWwindow *window, int width, int height) { screen_width = width; screen_height = height; //Updating the ViewPort. GLCall(glViewport(0, 0, width, height)); } Brain Class #include "Brain.h" #include "Sprite.h" #include "Window.h" struct Brain::Implementation { //Just A Flag. bool started; //Window Pointer. Window *window; //Sprite Pointer. Sprite *sprite; }; Brain::Brain(Window *window, Sprite *sprite) { //Create Pointer To Implementation. m_Impl = new Implementation(); //Initialize Implementation. m_Impl->started = true; m_Impl->window = window; m_Impl->sprite = sprite; } Brain::~Brain() { //Delete Pointer To Implementation. delete m_Impl; } void Brain::Start() { } void Brain::Update() { } Window * Brain::GetWindow() { return m_Impl->window; } Sprite * Brain::GetSprite() { return m_Impl->sprite; } bool Brain::GetStart() { return m_Impl->started; } void Brain::SetStart(bool value) { m_Impl->started = value; } Script Class (Its a Brain Subclass!!!) #include "Script.h" Script::Script(Window *window, Sprite *sprite) : Brain(window, sprite) { } Script::~Script() { } void Script::Start() { std::cout << "Game Started!" << std::endl; } void Script::Update() { Input *input = this->GetWindow()->GetInput(); Sprite *sp = this->GetSprite(); //Move this sprite. this->GetSprite()->Move(200 * this->GetWindow()->GetDeltaTime(), input->GetKeyDown("left"), input->GetKeyDown("right"), input->GetKeyDown("up"), input->GetKeyDown("down")); std::cout << sp->GetTag().c_str() << ".x = " << sp->GetPos()->x << ", " << sp->GetTag().c_str() << ".y = " << sp->GetPos()->y << std::endl; } Main: #include "SpaceShooterEngine.h" #include "Script.h" int main() { Window w("title", 600,600); Scene *scene = new Scene(); Sprite *player = new Sprite("Resources/Images/player.png", "Player", 100,100); Sprite *other = new Sprite("Resources/Images/cherno.png", "Other", 400, 100); Sprite *other2 = new Sprite("Resources/Images/cherno.png", "Other", 300, 400); Brain *brain = new Script(&w, player); player->AddBrain(brain); scene->AddSprite(player); scene->AddSprite(other); scene->AddSprite(other2); w.LoadScene(scene); w.MainLoop(); return 0; } I literally can't find what is wrong. If you need more code, ask me to post it. I will also attach all the source files. Brain.cpp Error.cpp IndexBuffer.cpp Input.cpp Renderer.cpp Scene.cpp Shader.cpp Sprite.cpp Texture.cpp VertexArray.cpp VertexBuffer.cpp VertexBufferLayout.cpp Window.cpp Brain.h Error.h IndexBuffer.h Input.h Renderer.h Scene.h Shader.h SpaceShooterEngine.h Sprite.h Texture.h VertexArray.h VertexBuffer.h VertexBufferLayout.h Window.h
  16. For a 2D game, does using a float2 for position increases performance in any way? I know that in the end the vertex shader will have to return a float4 anyway, but does using a float2 decreases the amount of data that will have to be sent from the CPU to the GPU?
  17. Hi, I am trying to implement a custom texture atlas creator tool in C++, need suggestion regarding any opensource fast API or library for image import and export? Also this tool will compress the final output atlas image into multiple formats like DXT5, PVRTC and ETC based on user input, what should be the best way to implement this? Thanks
  18. I'm having a spot of bother trying to create bitmaps with an appropriate palette for programs written with SGDK( Sega Genesis Development Kit ). At first I tried MSPaint as it has a 16 colour bitmap save feature, but it doesn't seem to generate a 16 colour palette for the bitmap. I tried Gimp, but aside from "create an index", I'm not having much luck there either, but I'm wondering if thats just my lack of experience with that graphics package. Come to think of it, its not every day one tries to make images for a 30 year old games console with a palettized colour system, so tutorials are very slim indeed. There is a tiles tutorial for SGDK which provides a moon image, and that loads in fine, but if I try to make an image from scratch I notice the palette entries are missing, and the bitmap data seems to have the first row or two of pixels chopped off...so I am assuming the bitmap file is missing the palette data. Just wondering how that moon image was made and in what package... If push comes to shove I suppose I could write my own image program to create such palettized bitmaps, but it seems a bit extreme with all these 2D image editing programs to choose from. I would have asked on Sprites Mind, but have been unsuccessful in registering. Which is a shame because it seems a very friendly and helpful place. Cheers.
  19. Hi all, I've been playing around with D2D and Directwrite, to add text rendering in my 3d engine/ framework. Using system fonts all works fine, by loading them up using directwrite factory -> CreateTextFormat("font name", nullptr...) etc. But now I'd also like to load in an external truetype font file (TTF), also using DirectWrite. After trying a lot of options and looking at examples, I just can't figure out how to turn a TTF font file into a usable custom font collection (which I can then use in CreateTextFormat). Below are some snippets of things I'm trying. Any hints what I should look for/ try, are appreciated. std::wstring fontFilename = L"WESTTEST.TTF"; CComPtr<IDWriteFontFile> tFontFile = NULL; m_dwFactory->CreateFontFileReference(fontFilename.c_str(), NULL, &tFontFile); IDWriteFontFile* fontFileArray[] = {tFontFile}; CComPtr<IDWriteFontFileLoader> fontFileLoader; m_dwFactory->RegisterFontFileLoader(fontFileLoader); int tkey = 3; m_dwFactory->CreateCustomFontFileReference(&tkey, sizeof(int), fontFileLoader, &tFontFile); CComPtr<IDWriteFontCollectionLoader> fontCollLoader; m_dwFactory->RegisterFontCollectionLoader(fontCollLoader); m_dwFactory->CreateCustomFontCollection(fontCollLoader, &tkey, sizeof(int), &m_dwFontColl); // continue - working code HRESULT result = m_dwFactory->CreateTextFormat(L"Arial", nullptr, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 14.0f, L"", &m_dwFormat);
  20. I am trying to oscillate a 2D object about a point, while the object has already been drawn then later I want to oscillate it by specifying the pivot point, how to proceed, please help me.It is for a mini project.I am using codeblocks and using c programing language along with OpenGL to do this, I have attached main .c file and .cpb file below (For reference I have attached the code for that object also below .) I have attached a .png file as what is my 2D image looks like.I want to oscillate that image about its top point(i.e cap tip). #include <GL/glut.h> #include <math.h> #define PI 3.14159265358979324 void myinit() { glClearColor(1.0,1.0,1.0,0.0); glMatrixMode (GL_PROJECTION); gluOrtho2D(0.0, 200.0, 0.0, 150.0); //glutPostRedisplay(); } void display(void) { float r3 = 4.0; // Radius of circle. float x3 = 80.0; // X-coordinate of center of circle. float y3 = 67.0; float r1 = 1.0; // Radius of circle. float x1 = 77.0; // X-coordinate of center of circle. float y1 = 73.0; float r2 = 1.0; // Radius of circle. float x2 = 83.0; // X-coordinate of center of circle. float y2 = 73.0; float R = 3.0; // Radius of circle. float X = 80.0; // X-coordinate of center of circle. float Y = 103.0; // Y-coordinate of center of circle. int numVertices = 25; // Number of vertices on circle. float t = 0; // Angle parameter. int i; glClear(GL_COLOR_BUFFER_BIT); //glColor3f(0.5, 0.5, 0.5); glLineWidth(2.0); glEnable(GL_LINE_STIPPLE); //glLineStipple(1,0x00ff); //draw a line glBegin(GL_LINES); glColor3f(0.92, 0.78, 0.62); glVertex2f(80.0,60.0); glVertex2f(90.0,65.0); glVertex2f(90.0,65.0); glVertex2f(90.0,75.0); glColor3f(0.137255, 0.556863, 0.137255);//0.0, 0.5, 0.0); glVertex2f(90.0,75.0); glVertex2f(80.0,80.0); glVertex2f(80.0,80.0); glVertex2f(70.0,75.0); glColor3f(0.92, 0.78, 0.62); glVertex2f(70.0,75.0); glVertex2f(70.0,65.0); glVertex2f(70.0,65.0); glVertex2f(80.0,60.0); glColor3f( 0.137255, 0.556863, 0.137255); glVertex2f(90.0,75.0); glVertex2f(80.0,100.0); glVertex2f(80.0,100.0); glVertex2f(70.0,75.0); glEnd(); glFlush(); glBegin(GL_POLYGON); glColor3f(0.1, 0.9, 0.0); for(int i = 0; i < numVertices; ++i) { //glColor3ub(rand()%256, rand()%256, rand()%256); glVertex3f(X + R * cos(t), Y + R * sin(t), 0.0); t += 2 * PI / numVertices; } glEnd(); glFlush(); glBegin(GL_POLYGON); glColor3f(0.647059, 0.164706, 0.164706); for(int i = 0; i < numVertices; ++i) { glVertex3f(x1 + r1 * cos(t), y1 + r1 * sin(t), 0.0); t += 2 * PI / numVertices; } glEnd(); glFlush(); glBegin(GL_POLYGON); glColor3f(0.647059, 0.164706, 0.164706); for(int i = 0; i < numVertices; ++i) { glVertex3f(x2 + r2 * cos(t), y2 + r2 * sin(t), 0.0); t += 2 * PI / numVertices; } glEnd(); glFlush(); glBegin(GL_POLYGON); glColor3f(1.0, 0.7, 0.0); for(int i = 0; i < numVertices; ++i) { glVertex3f(x3 + r3 * cos(t), y3 + r3 * sin(t), 0.0); t += - PI / numVertices; } glEnd(); glFlush(); } void main(int argc,char *argv[]) { glutInit(&argc,argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize (1000, 1000); glutInitWindowPosition (0, 0); glutCreateWindow ("joker"); myinit(); glutDisplayFunc(display); glutMainLoop(); } thanks in advance, please help me joker.cbp main.c
  21. Weird buffalo 11454

    2D Weird behaviour in Winapi.

    #include "stdafx.h" #include<windows.h> #include "Global.h" LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); void initBackBuffer(HWND hwnd); HDC hBackDC = NULL; HBITMAP hBackBitmap = NULL; void draw(HWND hwnd) { HDC hWinDC = GetDC(hwnd); SetBitmapBits(hBackBitmap, HEIGHT * WIDTH * sizeof(DWORD), (const void*)(screenBuffer)); BitBlt(hWinDC, 0, 0, WIDTH, HEIGHT, hBackDC, 0, 0, SRCCOPY); ReleaseDC(hwnd, hWinDC); } int WINAPI wWinMain(HINSTANCE hInstace, HINSTANCE hPrevInstace, LPWSTR lpCmdLine, int nCmdShow) { memset(screenBuffer, 0, sizeof(screenBuffer)); MSG msg = { 0 }; WNDCLASS wnd = { 0 }; wnd.lpfnWndProc = WndProc; wnd.hInstance = hInstace; wnd.lpszClassName = L"Window"; if (!RegisterClass(&wnd)) { return 0; } HWND hwnd = CreateWindowEx(NULL, wnd.lpszClassName, L"Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, WIDTH, HEIGHT, NULL, NULL, hInstace, NULL); if (!hwnd) { return 0; } ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); for (int j = 0; j <= 495; j++) { for (int i = 0; i < 512; i++) { screenBuffer[i * WIDTH + j] = 0x00FF0000; } } while (true) { if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) { break; } TranslateMessage(&msg); DispatchMessage(&msg); } draw(hwnd); } return msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){ switch (msg){ case WM_CREATE: initBackBuffer(hwnd); break; case WM_DESTROY: DeleteDC(hBackDC); DeleteObject(hBackBitmap); PostQuitMessage(0); break; } return DefWindowProc(hwnd, msg, wParam, lParam); } void initBackBuffer(HWND hwnd) { HDC hWinDC = GetDC(hwnd); hBackDC = CreateCompatibleDC(hWinDC); hBackBitmap = CreateCompatibleBitmap(hWinDC, WIDTH, HEIGHT); SetBitmapBits(hBackBitmap, HEIGHT * WIDTH * sizeof(DWORD), (const void*)(screenBuffer)); SelectObject(hBackDC, hBackBitmap); ReleaseDC(hwnd, hWinDC); } The output I am getting is : The WIDTH and HEIGHT is both 512 pixels but I running for (int j = 0; j <= 495; j++) { for (int i = 0; i < 512; i++) { screenBuffer[i * WIDTH + j] = 0x00FF0000; } } from 0 to 495 so that means that my actual WIDTH is 495 pixels and not 512 pixels. Where did the rest of 512 - 495 pixels go ?
  22. Objective : I want to draw a buffer of pixel (DWORD buf[WIDTH*HEIGHT]) to the whole client window. I am somewhat familiar with Winapi but not with GDI, reading the MSDN and other sources on the internet, I have came up with the following program. Problem : The code is not working. I have initialised all elements of my buffer ( buf[] ) to 0. So I should get a black screen on my window, but I getting a regular white window. Can somebody point me what's wrong am I doing ? Code : #include<Windows.h> #include "stdafx.h" LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); const int HEIGHT = 512; const int WIDTH = 512; DWORD buf[WIDTH * HEIGHT]; BITMAPINFO bmi = { 0 }; HDC hWinDC = NULL; HDC hbitDC = NULL; HBITMAP hBitmap = NULL; int WINAPI wWinMain(HINSTANCE hInstace, HINSTANCE hPrevInstace, LPWSTR lpCmdLine, int nCmdShow) { memset(buf, 0, sizeof(buf)/sizeof(DWORD)); MSG msg = { 0 }; WNDCLASS wnd = { 0 }; wnd.lpfnWndProc = WndProc; wnd.hInstance = hInstace; wnd.lpszClassName = L"Window"; if (!RegisterClass(&wnd)) { return 0; } HWND hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, wnd.lpszClassName, L"Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, WIDTH, HEIGHT, NULL, NULL, hInstace, NULL); if (!hwnd) { return 0; } ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){ HDC hWdc = NULL; switch (msg){ case WM_CREATE: bmi.bmiHeader.biSize = sizeof(BITMAPCOREHEADER); bmi.bmiHeader.biWidth = WIDTH; bmi.bmiHeader.biHeight = HEIGHT; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; break; case WM_PAINT: PAINTSTRUCT ps; hWdc = BeginPaint(hwnd, &ps); hWinDC = GetDC(hwnd); hbitDC = CreateCompatibleDC(hWinDC); hBitmap = CreateDIBSection(hWinDC, &bmi, DIB_RGB_COLORS, (void**)&buf, NULL, NULL); SelectObject(hbitDC, hBitmap); BitBlt(hWdc, 0, 0, WIDTH, HEIGHT, hbitDC, 0, 0, SRCCOPY); EndPaint(hwnd, &ps); break; case WM_KEYUP: if (wParam == 0x41) { SendMessage(hwnd, WM_PAINT, NULL, NULL); } break; case WM_DESTROY: DeleteDC(hbitDC); ReleaseDC(hwnd, hWinDC); PostQuitMessage(0); break; } return DefWindowProc(hwnd, msg, wParam, lParam); }
  23. Hi, Two questions: I am trying to rotate chroma in YUV colour space by separating each of the components and applying the following formula. int Ut = ((U-128) * cos(hue[H]) + (V-128) * sin(hue[H])) + 128; int Vt = ((V-128) * cos(hue[H]) - (U-128) * sin(hue[H])) + 128; ...where hue[H] is an array of rotation angles between 0.0 and 360.0. This seems to work OK but is dog slow. Is there a way to speed this up by converting to integer only calculation and doing away with cosine and sinus? Second, when doing conversion between YUV and RGB, it seems that luma is also affected after rotation. To demonstrate what I mean, I am randomly rotating each line's chroma. The process is: Convert from RGB to YUV > rotate chroma > convert to RGB. Top left is the original image, the two images on the right are U and V and the bottom left is the luma. As you can see, it seems to have some artefacts from rotation. Is there a way to avoid this? Thanks CJ
  24. I really, really would like to have smooth, artifact-free resize of an app that renders its content using Direct2D. (In point of fact, the app is an editor, but I'm using "game-like" techniques to render the UI, and a solution to this problem would be useful for games). I've been playing with this for a while, and am frustrated that I have a couple of "almost" solutions, but nothing that works robustly. I wrote up my explorations (with links to code) on my blog. The code happens to be in Rust, but I'm calling WinAPI pretty directly, so a working recipe would be easy enough to adapt to or from C++. I'm feeling stuck enough on this that I'm offering a $2500 bounty for a proper solution. I'd love to be able to make forward progress, and don't want to spend a lot more time on it myself. I'm not 100% it's even possible on Windows, though I see glimmers of hope.
  25. I have an game application in Direct3D 9 which create a couple of views (window's) , a couple of swap chains, and create a D3D device. When in windowed mode with a single view (window/monitor), it works fine. But when in fullscreen mode with a couple of views it fails. When I set both views' D3DPRESENT_PARAMETERS' Windowed to false, CreateDevice(...) leads to an application APPLICATION NOT RESPONDING When I set just one of the views' D3DPRESENT_PARAMETERS' Windowed to false (and the other to true), CreateDevice(...) returns D3DERR_INVALIDCALL What might be happening ? any advice is welcome. Thanks ! The code: d3d_object = Direct3DCreate9( D3D_SDK_VERSION ); if ( FAILED( d3d_object->GetDeviceCaps( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &d3dCaps ) ) ) { swprintf_( errbuf, _T( "Failed To obtain DeviceCaps D3D" ) ); return FALSE; } ... if ( pcgaming()->active ) //Windowed { hr = d3d_object->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, WindowHandle(), //D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED, D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED, &present_parameters[ 0 ], &ddraw ); } else // Fullscreen { if ( WindowHandleTop() ) { hr = d3d_object->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, WindowHandle(), D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED | D3DCREATE_ADAPTERGROUP_DEVICE, //D3DCREATE_HARDWARE_VERTEXPROCESSING present_parameters, &ddraw
  • Advertisement
√ó

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!