Mason McCuskey - Developing a GUI in C++ and DirectX

Здесь есть возможность читать онлайн «Mason McCuskey - Developing a GUI in C++ and DirectX» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Developing a GUI in C++ and DirectX: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Developing a GUI in C++ and DirectX»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

At first glance, it may seem like I’m reinventing the wheel; Windows already comes with a very complex, very functional GUI. Unfortunately, while the Windows GUI is great for office apps, quite frequently, it’s not suited for many games. Games tend to want a more precise control over the GUI than Windows can provide (for example, games may want to use alpha-blending to implement partially transparent windows - easy if you’ve written your own GUI, but next to impossible using the Windows GUI).
This article will walk you though how to create a GUI using C++ and DirectX. The series is divided into several parts, each dealing with a specific aspect of GUI programming:
Part I: The Basics, and the Mouse
Part II: Windows
Part III: Controls
Part IV: Resource Editors and Other Madness
NOTE: This document was originally four separate articles on www.gamedev.net. I’ve concatenated all four into one for the XGDC, but they remain otherwise unchanged. - Mason

Developing a GUI in C++ and DirectX — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Developing a GUI in C++ and DirectX», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Mason McCuskey

Developing a GUI in C++ and DirectX

Part I: The Basics, and the Mouse

Before I get started, I want to throw out a disclaimer: I’m going to outline the approach I used when I created the GUI system for my upcoming title, Quaternion. Treat this text as one solution to a very intricate problem, nothing more. I’m not saying that this way of making a GUI is the fastest or easiest way; I’m simply outlining a solution that worked for me. Also, this text is not complete. Like one of those Bob-Vila TV episodes, it skips over the easy stuff and concentrates on the interesting. There is no attached source file; there are code snippets in the text, and that’s it. In that code, I’ve stripped out a lot of layers of indirection that aren’t relevant to what I’m trying to show (i.e. the wrappers that you’d probably have for your DirectX functions, non-relevant initialization and cleanup code, etc). Also, beware of bugs - I’ve done lots of bug checking, but I’m only human. If you find a bug, please let me know about it by emailing mason@spin-studios.com.

I’m making several assumptions about your knowledge. I’m assuming you know the basics of how event-driven programming works (message queues, etc), and I’m assuming you have a strong grasp of PDL (the commenting language - if you don’t know what this is, read Code Complete, by Steve McConnell), and C++. I used C++ to implement my GUI system, because I’m a card-carrying member of the C++ fan club, and because the OOP of C++ work great for implementing window and control types. Shameless plug for the C++ language: Note the power of OOP in this solution, and ask yourself if you could do the same thing as easily in C.

Let’s start by defining our scope. It’s important to realize up front that we’re not remaking Windows 95, we’re just trying to get a simple GUI up for a game, so we don’t have to implement every single control and GUI construct. We only need a few parts for this simple GUI: a mouse pointer, a generic window, and some dialog controls to place within that window. We’re also going to need a resource editor, a program that will allow us to design dialogs by graphically dropping controls at various places.

Start with the basics - The Rendering Loop

I’m going to start at the top, by defining a function that will calculate and draw one frame of our GUI system. Let’s call this function RenderGUI(). In PDL, RenderGUI does something like this:

void CApplication::RenderGUI(void) {

// get position and button status of mouse cursor

// calculate mouse cursor’s effects on windows / send messages

// render all windows

// render mouse

// flip to screen

}

Pretty straightforward for now. Basically, we grab the new position and status of the mouse cursor, calculate any changes that are caused by the new position, render all our windows, render the mouse cursor, then push the whole thing to the screen.

The Mouse

Now that we’ve got a main function, we’re going to create a mouse class. This mouse class will initialize the rodent, and will be responsible for querying its position and storing the results. Here’s the definition:

class CMouse {

public:

CMouse(); // boring

~CMouse(); // boring

int Init(LPDIRECTINPUT di); // we’ll talk about this later

int Refresh(void); // we’ll talk about this later

int GetButton(int index) {

if (index ‹ 0 || index › NUMMOUSEBUTTONS) return(0);

return(m_button[index]);

}

CPoint GetPosition(void) { return(m_position); }

enum { NUMMOUSEBUTTONS = 3 }; // three button mouse

private:

LPDIRECTINPUTDEVICE m_mousedev;

char m_button[NUMMOUSEBUTTONS]; // state of buttons

CPoint m_position; // actual screen position

};

Pretty straightforward class definition. We’ve got two data pieces, m_button and m_position, abstracted by two functions, GetButton and GetPosition(). Then we’ve got Init and Refresh functions, which initialize the mouse and Refresh its button and position information. The m_mousedev is an interface to our mouse device; we get this interface during Init(), and use it in Refresh to communicate with DirectInput.

So… before we go any further with CMouse, let’s look at the code to initialize DirectInput. Note that this code doesn’tbelong in our CMouse::Init() routine; the DirectInput pointer is used by the entire game, not just the mouse, so the code that inits DirectInput should go in your main init function - the same time you init DirectDraw, DirectSound, etc. A DirectInput interface pointer is different than a DirectInput device pointer; you use DirectInput pointers to get DirectInputDevice pointers.

Here’s the code to initialize the master DirectInput interface pointer:

LPDIRECTINPUT di = NULL;

hr = DirectInputCreate(hinst, DIRECTINPUT_VERSION, &di, NULL);

if (FAILED(hr)) {

// error processing

}

That will put a valid DirectInput interface pointer into di. (Don’t forget to Release() it when your game ends!)

Now that we’ve got a DirectInput interface, let’s begin fleshing out our CMouse by implementing CMouse::Init().

bool CMouse::Init(LPDIRECTINPUT di) {

// Obtain an interface to the system mouse device.

hr = di-›CreateDevice(GUID_SysMouse, (LPDIRECTINPUTDEVICE*)&di_mouse, NULL);

if (FAILED(hr)) {/* handle errors! */}

// Set the data format to "mouse format".

hr = m_mousedev-›SetDataFormat(&c_dfDIMouse);

if (FAILED(hr)) {/* handle errors! */}

// Set the cooperativity level

hr = m_mousedev-›SetCooperativeLevel(hwnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);

if (FAILED(hr)) {/* handle errors! */}

}

That code does three important things. First, it gets a valid DirectInput mouse device interface, and puts it in di_mouse. Next, it sets the data format and the cooperative level for the device, basically letting windows know that we want to query the device as if it were a mouse, and that we don’t want to take exclusive ownership of it. (Exclusive ownership means that we’re the only app that can use the mouse - by specifying DISCL_NONEXCLUSIVE, we’ve told Windows that we’re going to be sharing the mouse with other applications.)

Now let’s flesh out CMouse::Refresh(), the function responsible for updating the CMouse’s internal button state and position variables. Here’s the code.

void CMouse::Refresh(void) {

C done = 0;

int q;

HRESULT hr;

POINT p;

DIMOUSESTATE dims;

if (!m_di) return;

// clear our struct - eventually, directinput will fill this in

memset(&dims, 0, sizeof(DIMOUSESTATE));

if (!m_mousedev) return; // we don’t have a pointer! Bail!

while (!done) {

hr = m_mousedev-›GetDeviceState(sizeof(DIMOUSESTATE), &dims);

if (FAILED(hr)) {

if (hr == DIERR_INPUTLOST || hr == DIERR_NOTACQUIRED) {

// device lost… reacquire

hr = m_mousedev-›Acquire();

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Developing a GUI in C++ and DirectX»

Представляем Вашему вниманию похожие книги на «Developing a GUI in C++ and DirectX» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Developing a GUI in C++ and DirectX»

Обсуждение, отзывы о книге «Developing a GUI in C++ and DirectX» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x