Jeff Molofee - NeHe's OpenGL Tutorials

Здесь есть возможность читать онлайн «Jeff Molofee - NeHe's OpenGL Tutorials» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

NeHe's OpenGL Tutorials: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «NeHe's OpenGL Tutorials»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

NeHe's OpenGL Tutorials — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «NeHe's OpenGL Tutorials», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

You'll notice that if you translate even deeper into the screen the size of the font does not shrink like you'd expect it to. What actually happens when you translate deeper is that you have more control over where the text is on the screen. If you tranlate 1 unit into the screen, you can place the text anywhere from –0.5 to +0.5 on the X axis. If you tranlate 10 units into the screen, you place the text from –5 to +5. It just gives you more control instead of using decimal places to position the text at exact locations. Nothing will change the size of the text. Not even glScalef(x,y,z). If you want the font bigger or smaller, make it bigger or smaller when you create it!

int DrawGLScene(GLvoid) // Here's Where We Do All The Drawing

{

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer

glLoadIdentity(); // Reset The View

glTranslatef(0.0f,0.0f,-1.0f); // Move One Unit Into The Screen

Now we use some fancy math to make the colors pulse. Don't worry if you don't understand what I'm doing. I like to take advantage of as many variables and stupid tricks as I can to achieve results :)

In this case I'm using the two counters we made to move the text around the screen to change the red, green and blue colors. Red will go from –1.0 to 1.0 using COS and counter 1. Green will also go from –1.0 to 1.0 using SIN and counter 2. Blue will go from 0.5 to 1.5 using COS and counter 1 and 2. That way blue will never be 0, and the text should never completely fade out. Stupid, but it works :)

// Pulsing Colors Based On Text Position

glColor3f(1.0f*float(cos(cnt1)), 1.0f*float(sin(cnt2)), 1.0f-0.5f*float(cos(cnt1+cnt2)));

Now for a new command. glRasterPos2f(x,y) will position the Bitmapped Font on the screen. The center of the screen is still 0,0. Notice there's no Z position. Bitmap Fonts only use the X axis (left/right) and Y axis (up/down). Because we translate one unit into the screen, the far left is –0.5, and the far right is +0.5. You'll notice that I move 0.45 pixels to the left on the X axis. This moves the text into the center of the screen. Otherwise it would be more to the right of the screen because it would be drawn from the center to the right.

The fancy(?) math does pretty much the same thing as the color setting math does. It moves the text on the x axis from –0.50 to –0.40 (remember, we subtract 0.45 right off the start). This keeps the text on the screen at all times. It swings left and right using COS and counter 1. It moves from –0.35 to +0.35 on the Y axis using SIN and counter 2.

// Position The Text On The Screen

glRasterPos2f(-0.45f+0.05f*float(cos(cnt1)), 0.35f*float(sin(cnt2)));

Now for my favorite part… Writing the actual text to the screen. I tried to make it super easy, and very user friendly. You'll notice it looks alot like an OpenGL call, combined with the good old fashioned Print statement :) All you do to write the text to the screen is glPrint("{any text you want}"). It's that easy. The text will be drawn onto the screen at the exact spot you positioned it.

Shawn T. sent me modified code that allows glPrint to pass variables to the screen. This means that you can increase a counter and display the results on the screen! It works like this… In the line below you see our normal text. Then there's a space, a dash, a space, then a "symbol" (%7.2f). Now you may look at %7.2f and say what the heck does that mean. It's very simple. % is like a marker saying don't print 7.2f to the screen, because it represents a variable. The 7 means a maximum of 7 digits will be displayed to the left of the decimal place. Then the decimal place, and right after the decimal place is a 2. The 2 means that only two digits will be displayed to the right of the decimal place. Finally, the f. The f means that the number we want to display is a floating point number. We want to display the value of cnt1 on the screen. As an example, if cnt1 was equal to 300.12345f the number we would end up seeing on the screen would be 300.12. The 3, 4, and 5 after the decimal place would be cut off because we only want 2 digits to appear after the decimal place.

I know if you're an experienced C programmer, this is absolute basic stuff, but there may be people out there that have never used printf. If you're interested in learning more about symbols, buy a book, or read through the MSDN.

glPrint("Active OpenGL Text With NeHe – %7.2f", cnt1); // Print GL Text To The Screen

The last thing to do is increase both the counters by different amounts so the colors pulse and the text moves.

cnt1+=0.051f; // Increase The First Counter

cnt2+=0.005f; // Increase The Second Counter

return TRUE; // Everything Went OK

}

The last thing to do is add KillFont() to the end of KillGLWindow() just like I'm showing below. It's important to add this line. It cleans things up before we exit our program.

if (!UnregisterClass("OpenGL",hInstance)) // Are We Able To Unregister Class

{

MessageBox(NULL, "Could Not Unregister Class.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);

hInstance=NULL; // Set hInstance To NULL

}

KillFont(); // Destroy The Font

}

That's it… Everything you need to know in order to use Bitmap Fonts in your own OpenGL projects. I've searched the net looking for a tutorial similar to this one, and have found nothing. Perhaps my site is the first to cover this topic in easy to understand C code? Anyways. Enjoy the tutorial, and happy coding!

Jeff Molofee (NeHe)

* DOWNLOAD Visual C++Code For This Lesson.

* DOWNLOAD Borland C++Code For This Lesson. (Conversion by Patrick Salmons)

* DOWNLOAD DelphiCode For This Lesson. (Conversion by Marc Aarts)

* DOWNLOAD Game GLUTCode For This Lesson. (Conversion by Milikas Anastasios)

* DOWNLOAD Irix / GLUTCode For This Lesson. (Conversion by Rob Fletcher)

* DOWNLOAD JavaCode For This Lesson. (Conversion by Jeff Kirby)

* DOWNLOAD LinuxCode For This Lesson. (Conversion by Richard Campbell)

* DOWNLOAD Linux/GLXCode For This Lesson. (Conversion by Mihael Vrbanec)

* DOWNLOAD Linux/SDLCode For This Lesson. (Conversion by Ti Leggett)

* DOWNLOAD Mac OSCode For This Lesson. (Conversion by Anthony Parker)

* DOWNLOAD Visual BasicCode For This Lesson. (Conversion by Ross Dawson)

* DOWNLOAD Visual BasicCode For This Lesson. (Conversion by Edo)

Lesson 14

This tutorial is a sequel to the last tutorial. In tutorial 13 I taught you how to use Bitmap Fonts. In this tutorial I'll teach you how to use Outline Fonts.

The way we create Outline fonts is fairly similar to the way we made the Bitmap font in lesson 13. However… Outline fonts are about 100 times more cool! You can size Outline fonts. Outline font's can move around the screen in 3D, and outline fonts can have thickness! No more flat 2D characters. With Outline fonts, you can turn any font installed on your computer into a 3D font for OpenGL, complete with proper normals so the characters light up really nice when light shines on them.

A small note, this code is Windows specific. It uses the wgl functions of Windows to build the font. Apparently Apple has agl support that should do the same thing, and X has glx. Unfortunately I can't guarantee this code is portable. If anyone has platform independant code to draw fonts to the screen, send it my way and I'll write another font tutorial.

We start off with the typical code from lesson 1. We'll be adding the stdio.h header file for standard input/output operations; the stdarg.h header file to parse the text and convert variables to text, and finally the math.h header file so we can move the text around the screen using SIN and COS.

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

Интервал:

Закладка:

Сделать

Похожие книги на «NeHe's OpenGL Tutorials»

Представляем Вашему вниманию похожие книги на «NeHe's OpenGL Tutorials» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Jeff Jacobson - Sleep Tight
Jeff Jacobson
Jeff Salyards - Veil of the Deserters
Jeff Salyards
Jeff LaSala - The Darkwood Mask
Jeff LaSala
Jeff Lindsay - Dexter's Final Cut
Jeff Lindsay
libcat.ru: книга без обложки
Неизвестный Автор
libcat.ru: книга без обложки
Неизвестный Автор
libcat.ru: книга без обложки
Неизвестный Автор
libcat.ru: книга без обложки
Неизвестный Автор
Отзывы о книге «NeHe's OpenGL Tutorials»

Обсуждение, отзывы о книге «NeHe's OpenGL Tutorials» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x