Отправляет email-рассылки с помощью сервиса Sendsay
  Все выпуски  

СообЧА. Программирование на Delphi


Информационный Канал Subscribe.Ru

Untitled Document
===СообЧа: Программирование на дельфи для чайников и не только===

Автор рассылки: Pixel .
Учередитель проекта : COOLer.
Рассылка выходит постоянно с Августа 2001г.

Наш веб-сайт pixelsoft.narod.ru
Рассылка благодарит компанию ОЗОН, за периодичеки покупаемый софт.


Все желающие оказать помощь проекту, пишите на адрес pixela ,с пометкой Support, со своими предложениями.

В этом номере :

Обзор литературы
Roto-zoom: Изврат в квадрате...
Свет в конце туннеля!


Lets get away, just for one day...
(c)Rammstein

Опять Eye-candy, demo-make выпуск...

ЛЮЮЮДИ !!!! ПОМОГИТЕ С ФРАКТАЛАМИ !

Ведущий рассылки, также предоставляет следующие услуги:
WEB-design с применением FLASH
Баннероизготовление(любые форматы и размеры)
ART-design логотипов, обоев на рабочий стол и т.п.
Верстка сайтов с потимизацией под 36к соединение без потери
графических "наворотов"
Фонд поддержки наших проектов и рассылки:
Получатель: ИНН 7707083893 Новгородское ОСБ № 8629
Счет получателя: 47422810343029900030
Банк получателя :Новгородское ОСБ № 8629 г.Великий Новгород
30101810100000000698 Бик 044959698
Храпунову Кириллу Алексеевичу


К заголовку
Обзор литературы

А теперь снова наш рекламный пунктик... ой, всмысле обзор.

На сей раз хотел бы представить вам тот список лит-ры, который необходимо прочесть для овладевания БАЗОВЫМИ навыками по дельфи:
(Для тех кто будет это читать попрошу соблюдать порядок прочтения)
1. "Turbo pascal 7.0" (второе издание, автор Грызлов В.И)
В данной книге расписаны основные приемы работы с паскалевским кодом, методы оптимизации программы и дан базовый курс по ООП. Как не странно, но все таки некоторые "программисты" забывают что дельфи вырос на Object pascal , коде.


2."Программирование в дельфи 5" (автор П.Дарахвелидзе)
Данная книжка знакомит вас с азами дельфи и разводит понятия дельфи и object pascal , объясняя основные черты дельфи кода. Также, даны основные понятия о классах и объектах дельфи, описана методика работы со стандартными API и VCL. Чем мне нравится эта книга, так это очень глубоким изучением работы с БД и СУБД под дельфи.

3."Дельфи 5, наиболее полное пособие"(автора не помню, книга с 1 к 1-му таким же названием есть для дельфи 6, циферки только разные :) )
Данная книга, относится к разделу справочников, то есть , подразумевается, что у вас есть базовые умения в среде Дельфи. В этой книге рассмотрены примеры создания своего VCL или ActiveX компонента, несколько слов уделяется сетевому программированию, а также есть справочные сведения по многим ф-циям библиотек System,Shelapi,Filectrls,Strings,Shellapi.

P.s
Что мне наименее нравится, так это то, что ни в одной встреченной/прочитанной мною книге не охвачены аспекты по работе с ДЛЛками и NetAPI, напрочь опущен тот факт, что дельфи может писать CGI программы(помните счетчик в одном из номеров?) да и оновные "грабли" на которые все наступают тоже не охвачены.

Все книги можно найти тут...


К заголовку

Данный код требует FastLIB VCL, очень неплох для любителей повыпендриваться и демомейкеров... К сожалению, без файла с ресурсами будет крутиться надпиь "Picture or resource not found" , так что поковыряйтесь с картинкой не поленитесь, оно того стоит...

Набор классов FastLib
--------------------------------------------------------

Библиотека для работы с растровой графикой.

Проверялся на Delphi 3,5

Оригинал: http://www.gfody.com/
--------------------------------------------------------

Delphi GFX - все о создании игр и графике на Delphi

http://www.delphigfx.narod.ru


------------------------------------------------Begin of project1.dpr(Для компактности окна у приложения с начала нет...)

program rotozoom; // example for FastLIB http://gfody.com
// by: gordy <gfody@home.com>
{$R sunghi.res} // этого файла у вас нет
{$R *.res}
{$R-}

uses
Windows, Messages, FastDIB, FastFiles, FastBlend;

var
Dst,Src,Blur: TFastDIB;
Handle,hDC,Frames,Fps,i: Integer;
Filter: Boolean=True;
Motion: Boolean=False;
GotMsg: Boolean;
Msg: TMSG;
Pic: Integer=0;
mx,my: array[Word]of Integer; //mod table

const
ResNames: array[0..1]of string = ('sunghi1', 'sunghi2');// названия картинок надо поменять на свои

procedure UpdateFrame;
var
x,y,t1,t2,dx,dy,xd,yd,cx,cy,
sdx,sdy,isin,icos,ax,ay,ex,ey: Integer;
c00,c01,c10,c11: Byte;
pc,sp: PByte;
s: string;
begin
Inc(i);

xd:=((Src.Width shl 16)-(Dst.Width shl 16))div 2;
yd:=((Src.Height shl 16)-(Dst.Height shl 16))div 2;
cx:=Dst.Width shr 1;
cy:=Dst.Height shr 1;

isin:=Round(Sin(Cos(i/90)*15)*65536);
icos:=Round(Cos(Sin(i/360)*35)*65536);

ax:=(cx shl 16)-(icos*cx);
ay:=(cy shl 16)-(isin*cx);

pc:=Pointer(Dst.Bits);
for y:=0 to Dst.Height-1 do
begin
dy:=cy-y;
sdx:=(ax+(isin*dy))+xd;
sdy:=(ay-(icos*dy))+yd;
for x:=0 to Dst.Width-1 do
begin
dx:=Smallint(sdx shr 16);
dy:=Smallint(sdy shr 16);
// using a lookup table instead of mod
if dx<0 then dx:=Src.Width-mx[-dx]-2 else if dx>Src.Width-2 then dx:=mx[dx];
if dy<0 then dy:=Src.AbsHeight-my[-dy]-2 else if dy>Src.AbsHeight-2 then dy:=my[dy];
if Filter then
begin
sp:=@Src.Pixels8[dy,dx];
c00:=sp^; Inc(sp);
c01:=sp^; Inc(sp,Src.BWidth-1);
c10:=sp^; Inc(sp);
c11:=sp^;
ex:=sdx and $FFFF;
ey:=sdy and $FFFF;
t1:=((((c01-c00)*ex)shr 16)+c00)and $FF;
t2:=((((c11-c10)*ex)shr 16)+c10)and $FF;
pc^:=(((t2-t1)*ey)shr 16)+t1;
end else pc^:=Src.Pixels8[dy,dx];
Inc(sdx,icos);
Inc(sdy,isin);
Inc(pc);
end;
Inc(pc,Dst.Gap);
end;

Str(Fps,s);
if i<500 then
begin
Dst.TextOut(5,0,'sung hi rotozoomer - g0rdy');
Dst.TextOut(5,15,'right-click: toggle feedback');
Dst.TextOut(5,30,'left-click: toggle bilinear filter');
Dst.TextOut(5,45,'press a key: change picture');
Dst.TextOut(5,60,s);
end else Dst.TextOut(5,0,s);

if Motion then
begin
Blur.SetSize(Dst.Width,Dst.Height,8);
AvgBlend(Blur,Blur,Dst);
Blur.Draw(hDC,0,0);
end else Dst.Draw(hDC,0,0);

Inc(Frames);
end;

procedure FillModTable;
var
x,y,i: Integer;
begin
x:=0; y:=0;
for i:=0 to 65535 do
begin
mx[i]:=x;
my[i]:=y;
Inc(x); if x=Src.Width-1 then x:=0;
Inc(y); if y=Src.Height-1 then y:=0;
end;
end;

function WindowProc(hWnd,uMsg,wParam,lParam:Longint):Longint; stdcall;
var
ps: TPaintStruct;
begin
case uMsg of

WM_KEYDOWN:
begin
if Pic=0 then Inc(Pic) else Pic:=0;
LoadJPGRes(Src,hInstance,ResNames[Pic],'binary',True);
FillModTable;
Result:=0;
end;

WM_LBUTTONDOWN:
begin
Filter:=not Filter;
Result:=0;
end;

WM_RBUTTONDOWN:
begin
FillChar(Blur.Bits^,Blur.Size,0);
Motion:=not Motion;
Result:=0;
end;

WM_DESTROY:
begin
Src.Free;
Dst.Free;
if Blur<>nil then Blur.Free;
KillTimer(Handle,0);
ReleaseDC(Handle,hDC);
ExitProcess(hInstance);
Result:=0;
end;

WM_PAINT:
begin
BeginPaint(hWnd,ps);
Dst.Draw(ps.hDC,0,0);
EndPaint(hWnd,ps);
Result:=0;
end;

WM_SIZE:
begin
Dst.SetSize(lParam and $FFFF,lParam shr 16,8);
Dst.SetTransparent(True);
Dst.SetFontEx('Tahoma',5,12,800,False,False,False);
Result:=0;
end;

WM_TIMER:
begin
Fps:=Frames;
Frames:=0;
Result:=0;
end;

else Result:=DefWindowProc(hWnd,uMsg,wParam,lParam);
end;
end;

begin
Src:=TFastDIB.Create;

if HasJPG then LoadJPGRes(Src,hInstance,'sunghi1','binary',True) else
begin
Src.SetSize(300,50,8);
Src.FillColors(0,255,[tfBlack,FRGB(0,100,128),tfWhite]);
Src.SetBkColor(0);
Src.SetTextColor(RGB(255,255,255));
Src.TextOut(0,0,'Intel® Jpeg Library (ijl15.dll) not found!');
end;
FillModTable;

Blur:=TFastDIB.Create;
Blur.FillColors(0,255,[tfBlack,FRGB(0,100,128),tfWhite]);

Dst:=TFastDIB.Create;
Dst.SetSize(500,400,8);
Dst.FillColors(0,255,[tfBlack,FRGB(0,100,128),tfWhite]);
Dst.SetFontEx('Tahoma',5,12,800,False,False,False);
Dst.SetTransparent(True);

hDC:=GetDC(Handle);

Handle:=CreateWindow('#32770','rotozoom - gordy',
WS_VISIBLE or WS_SYSMENU or WS_SIZEBOX,0,0,
(GetSystemMetrics(SM_CXFIXEDFRAME)shl 1)+Dst.Width,
(GetSystemMetrics(SM_CYFIXEDFRAME)shl 1)+GetSystemMetrics(SM_CYCAPTION)+Dst.AbsHeight,
0,0,hInstance,nil);

SetWindowLong(Handle,GWL_WNDPROC,Longint(@WindowProc));
hDC:=GetDC(Handle);

SetTimer(Handle,0,1000,nil);

while Msg.Message<>WM_QUIT do
begin
GotMsg:=PeekMessage(Msg,0,0,0,PM_REMOVE);
if GotMsg then DispatchMessage(Msg) else UpdateFrame;
end;

end.


К заголовку

К данной программке нужен файл tunnel.bmp, размером 128х128 ... Приложение окна не имеет(создает его OpenGL контекстом), поэтому всего 63к в рамере...

//------------------------------------------------------------------------
//
// Author : Jan Horn
// Email : jhorn@global.co.za
// Website : http://home.global.co.za/~jhorn
// Date : 17 June 2001
// Version : 1.0
// Description : Speeding Tunnel
//
//------------------------------------------------------------------------
program Tunnel;

uses
Windows,
Messages,
OpenGL,graphics,
BMP;

const
WND_TITLE = 'Tunnel App by Jan Horn';
FPS_TIMER = 1; // Timer to calculate FPS
FPS_INTERVAL = 1000; // Calculate FPS every 1000 ms

TEXTURE_SPEED = 1/50;

type glCoord = Record
X, Y, Z : glFLoat;
end;
var

h_Wnd : HWND; // Global window handle
h_DC : HDC; // Global device context
h_RC : HGLRC; // OpenGL rendering context
keys : Array[0..255] of Boolean; // Holds keystrokes
FPSCount : Integer = 1; // Counter for FPS
ElapsedTime : Integer; // Elapsed time between frames

// Textures
TunnelTex : glUint;

// User vaiables
Tunnels : Array[0..32, 0..32] of glCoord;
Angle : glFloat;
Speed : glFloat;
Manual : Boolean;

{$R *.RES}

procedure glBindTexture(target: GLenum; texture: GLuint); stdcall; external opengl32;

{------------------------------------------------------------------}
{ Function to convert int to string. (No sysutils = smaller EXE) }
{------------------------------------------------------------------}
function IntToStr(Num : Integer) : String; // using SysUtils increase file size by 100K
begin
Str(Num, result);
end;


{------------------------------------------------------------------}
{ Function to draw the actual scene }
{------------------------------------------------------------------}
procedure glDraw();
var I, J : Integer;
C, J1, J2 : glFloat;
begin

glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
glLoadIdentity(); // Reset The View

glTranslatef(0.0,0.0,-4.2);

if Manual then
Angle :=Angle + speed
else
Angle :=ElapsedTime/14;

// setup tunnel coordinates

for I :=0 to 12 do
begin
for J :=0 to 32 do
begin
// Enable Blending

Tunnels[I, J].X :=(3 - J/12)*cos(2*pi/12*I) + 2*sin((Angle+2*j)/29) + cos((Angle+2*j)/13) - 2*sin(Angle/29) - cos(Angle/13);
Tunnels[I, J].Y :=(3 - J/12)*sin(2*pi/12*I) + 2*cos((Angle+2*j)/33) + sin((Angle+2*j)/17) - 2*cos(Angle/33) - sin(Angle/17);
Tunnels[I, J].Z :=-J;

end;
end;

// draw tunnel
For J :=0 to 30 do
begin
J1 :=J/32 + Angle*TEXTURE_SPEED; // precalculate texture v coords for speed
J2 :=(J+1)/32 + Angle*TEXTURE_SPEED;

// near the end of the tunnel, fade the effect away
if J > 24 then
C :=1.0-(J-24)/10
else
C :=1.0;
glpushmatrix ;
glBlendFunc(GL_one,GL_dst_ALPHA); // Set Blending Mode
glEnable(GL_BLEND);
randomize;
glColor4f(1, 1, 1,1);
glBegin(GL_QUADS);
For I :=0 to 11 do
begin
glTexCoord3f((I-3)/12*3, J1,4); glVertex3f(Tunnels[ I, J ].X, Tunnels[ I, J ].Y, Tunnels[ I, J ].Z);
glTexCoord2f((I-2)/12*3, J1); glVertex3f(Tunnels[I+1, J ].X, Tunnels[I+1, J ].Y, Tunnels[I+1, J ].Z);
glTexCoord2f((I-2)/12*3, J2); glVertex3f(Tunnels[I+1, J+1].X, Tunnels[I+1, J+1].Y, Tunnels[I+1, J+1].Z);
glTexCoord2f((I-3)/12*3, J2); glVertex3f(Tunnels[ I, J+1].X, Tunnels[ I, J+1].Y, Tunnels[ I, J+1].Z);
end;
glDisable(GL_BLEND); // Disable Blending
glpopmatrix();
glColor4f(1, 1, 1,0.9);
glBegin(GL_QUADS);
For I :=0 to 11 do
begin
glTexCoord2f((I-3)/12, J1); glVertex3f(Tunnels[ I, J ].X, Tunnels[ I, J ].Y, Tunnels[ I, J ].Z);
glTexCoord2f((I-2)/12, J1); glVertex3f(Tunnels[I+1, J ].X, Tunnels[I+1, J ].Y, Tunnels[I+1, J ].Z);
glTexCoord2f((I-2)/12, J2); glVertex3f(Tunnels[I+1, J+1].X, Tunnels[I+1, J+1].Y, Tunnels[I+1, J+1].Z);
glTexCoord2f((I-3)/12, J2); glVertex3f(Tunnels[ I, J+1].X, Tunnels[ I, J+1].Y, Tunnels[ I, J+1].Z);
end;
// Disable Blending
glEnd();


end;
end;


{------------------------------------------------------------------}
{ Initialise OpenGL }
{------------------------------------------------------------------}
procedure glInit();
begin

glClearColor(0.0, 0.0, 0.0, 0.0); // Black Background
glShadeModel(GL_SMOOTH); // Enables Smooth Color Shading
glClearDepth(1.0); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enable Depth Buffer
glDepthFunc(GL_LESS); // The Type Of Depth Test To Do

glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); //Realy Nice perspective calculations

glEnable(GL_TEXTURE_2D); // Enable Texture Mapping

LoadTexture('tunnel.bmp', TunnelTex);

Speed :=0;
Angle :=0;
Manual :=FALSE;
end;


{------------------------------------------------------------------}
{ Handle window resize }
{------------------------------------------------------------------}
procedure glResizeWnd(Width, Height : Integer);
begin
if (Height = 0) then // prevent divide by zero exception
Height := 1;
glViewport(0, 0, Width, Height); // Set the viewport for the OpenGL window
glMatrixMode(GL_PROJECTION); // Change Matrix Mode to Projection
glLoadIdentity(); // Reset View
gluPerspective(45.0, Width/Height, 1.0, 100.0); // Do the perspective calculations. Last value = max clipping depth

glMatrixMode(GL_MODELVIEW); // Return to the modelview matrix
glLoadIdentity(); // Reset View
end;


{------------------------------------------------------------------}
{ Processes all the keystrokes }
{------------------------------------------------------------------}
procedure ProcessKeys;
begin
if (keys[VK_UP]) then
begin
if Manual =FALSE then
begin
Manual :=TRUE;
speed := 0.5;
end
else
Speed :=Speed + 0.005;
end;

if (keys[VK_DOWN]) then
begin
if Manual =FALSE then
begin
Manual :=TRUE;
speed := 0.5;
end
else
Speed :=Speed - 0.005;
end
end;


{------------------------------------------------------------------}
{ Determines the application’s response to the messages received }
{------------------------------------------------------------------}
function WndProc(hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
begin
case (Msg) of
WM_CREATE:
begin
// Insert stuff you want executed when the program starts
end;
WM_CLOSE:
begin
PostQuitMessage(0);
Result := 0
end;
WM_KEYDOWN: // Set the pressed key (wparam) to equal true so we can check if its pressed
begin
keys[wParam] := True;
Result := 0;
end;
WM_KEYUP: // Set the released key (wparam) to equal false so we can check if its pressed
begin
keys[wParam] := False;
Result := 0;
end;
WM_SIZE: // Resize the window with the new width and height
begin
glResizeWnd(LOWORD(lParam),HIWORD(lParam));
Result := 0;
end;
WM_TIMER : // Add code here for all timers to be used.
begin
if wParam = FPS_TIMER then
begin
FPSCount :=Round(FPSCount * 1000/FPS_INTERVAL); // calculate to get per Second incase intercal is less or greater than 1 second
SetWindowText(h_Wnd, PChar(WND_TITLE + ' [' + intToStr(FPSCount) + ' FPS]'));
FPSCount := 0;
Result := 0;
end;
end;
else
Result := DefWindowProc(hWnd, Msg, wParam, lParam); // Default result if nothing happens
end;
end;


{---------------------------------------------------------------------}
{ Properly destroys the window created at startup (no memory leaks) }
{---------------------------------------------------------------------}
procedure glKillWnd(Fullscreen : Boolean);
begin

if Fullscreen then // Change back to non fullscreen
begin
ChangeDisplaySettings(devmode(nil^), 0);
ShowCursor(True);
end;

// Makes current rendering context not current, and releases the device
// context that is used by the rendering context.
if (not wglMakeCurrent(h_DC, 0)) then
MessageBox(0, 'Release of DC and RC failed!', 'Error', MB_OK or MB_ICONERROR);

// Attempts to delete the rendering context
if (not wglDeleteContext(h_RC)) then
begin
MessageBox(0, 'Release of rendering context failed!', 'Error', MB_OK or MB_ICONERROR);
h_RC := 0;
end;

// Attemps to release the device context
if ((h_DC = 1) and (ReleaseDC(h_Wnd, h_DC) <> 0)) then
begin
MessageBox(0, 'Release of device context failed!', 'Error', MB_OK or MB_ICONERROR);
h_DC := 0;
end;

// Attempts to destroy the window
if ((h_Wnd <> 0) and (not DestroyWindow(h_Wnd))) then
begin
MessageBox(0, 'Unable to destroy window!', 'Error', MB_OK or MB_ICONERROR);
h_Wnd := 0;
end;

// Attempts to unregister the window class
if (not UnRegisterClass('OpenGL', hInstance)) then
begin
MessageBox(0, 'Unable to unregister window class!', 'Error', MB_OK or MB_ICONERROR);
hInstance := 0;
end;
end;


{--------------------------------------------------------------------}
{ Creates the window and attaches a OpenGL rendering context to it }
{--------------------------------------------------------------------}
function glCreateWnd(Width, Height : Integer; Fullscreen : Boolean; PixelDepth : Integer) : Boolean;
var
wndClass : TWndClass; // Window class
dwStyle : DWORD; // Window styles
dwExStyle : DWORD; // Extended window styles
dmScreenSettings : DEVMODE; // Screen settings (fullscreen, etc...)
PixelFormat : GLuint; // Settings for the OpenGL rendering
h_Instance : HINST; // Current instance
pfd : TPIXELFORMATDESCRIPTOR; // Settings for the OpenGL window
begin
h_Instance := GetModuleHandle(nil); //Grab An Instance For Our Window
ZeroMemory(@wndClass, SizeOf(wndClass)); // Clear the window class structure

with wndClass do // Set up the window class
begin
style := CS_HREDRAW or // Redraws entire window if length changes
CS_VREDRAW or // Redraws entire window if height changes
CS_OWNDC; // Unique device context for the window
lpfnWndProc := @WndProc; // Set the window procedure to our func WndProc
hInstance := h_Instance;
hCursor := LoadCursor(0, IDC_ARROW);
lpszClassName := 'OpenGL';
end;

if (RegisterClass(wndClass) = 0) then // Attemp to register the window class
begin
MessageBox(0, 'Failed to register the window class!', 'Error', MB_OK or MB_ICONERROR);
Result := False;
Exit
end;

// Change to fullscreen if so desired
if Fullscreen then
begin
ZeroMemory(@dmScreenSettings, SizeOf(dmScreenSettings));
with dmScreenSettings do begin // Set parameters for the screen setting
dmSize := SizeOf(dmScreenSettings);
dmPelsWidth := Width; // Window width
dmPelsHeight := Height; // Window height
dmBitsPerPel := PixelDepth; // Window color depth
dmFields := DM_PELSWIDTH or DM_PELSHEIGHT or DM_BITSPERPEL;
end;

// Try to change screen mode to fullscreen
if (ChangeDisplaySettings(dmScreenSettings, CDS_FULLSCREEN) = DISP_CHANGE_FAILED) then
begin
MessageBox(0, 'Unable to switch to fullscreen!', 'Error', MB_OK or MB_ICONERROR);
Fullscreen := False;
end;
end;

// If we are still in fullscreen then
if (Fullscreen) then
begin
dwStyle := WS_POPUP or // Creates a popup window
WS_CLIPCHILDREN // Doesn't draw within child windows
or WS_CLIPSIBLINGS; // Doesn't draw within sibling windows
dwExStyle := WS_EX_APPWINDOW; // Top level window
ShowCursor(False); // Turn of the cursor (gets in the way)
end
else
begin
dwStyle := WS_OVERLAPPEDWINDOW or // Creates an overlapping window
WS_CLIPCHILDREN or // Doesn't draw within child windows
WS_CLIPSIBLINGS; // Doesn't draw within sibling windows
dwExStyle := WS_EX_APPWINDOW or // Top level window
WS_EX_WINDOWEDGE; // Border with a raised edge
end;

// Attempt to create the actual window
h_Wnd := CreateWindowEx(dwExStyle, // Extended window styles
'OpenGL', // Class name
WND_TITLE, // Window title (caption)
dwStyle, // Window styles
0, 0, // Window position
Width, Height, // Size of window
0, // No parent window
0, // No menu
h_Instance, // Instance
nil); // Pass nothing to WM_CREATE
if h_Wnd = 0 then
begin
glKillWnd(Fullscreen); // Undo all the settings we've changed
MessageBox(0, 'Unable to create window!', 'Error', MB_OK or MB_ICONERROR);
Result := False;
Exit;
end;

// Try to get a device context
h_DC := GetDC(h_Wnd);
if (h_DC = 0) then
begin
glKillWnd(Fullscreen);
MessageBox(0, 'Unable to get a device context!', 'Error', MB_OK or MB_ICONERROR);
Result := False;
Exit;
end;

// Settings for the OpenGL window
with pfd do
begin
nSize := SizeOf(TPIXELFORMATDESCRIPTOR); // Size Of This Pixel Format Descriptor
nVersion := 1; // The version of this data structure
dwFlags := PFD_DRAW_TO_WINDOW // Buffer supports drawing to window
or PFD_SUPPORT_OPENGL // Buffer supports OpenGL drawing
or PFD_DOUBLEBUFFER; // Supports double buffering
iPixelType := PFD_TYPE_RGBA; // RGBA color format
cColorBits := PixelDepth; // OpenGL color depth
cRedBits := 0; // Number of red bitplanes
cRedShift := 0; // Shift count for red bitplanes
cGreenBits := 0; // Number of green bitplanes
cGreenShift := 0; // Shift count for green bitplanes
cBlueBits := 0; // Number of blue bitplanes
cBlueShift := 0; // Shift count for blue bitplanes
cAlphaBits := 0; // Not supported
cAlphaShift := 0; // Not supported
cAccumBits := 0; // No accumulation buffer
cAccumRedBits := 0; // Number of red bits in a-buffer
cAccumGreenBits := 0; // Number of green bits in a-buffer
cAccumBlueBits := 0; // Number of blue bits in a-buffer
cAccumAlphaBits := 0; // Number of alpha bits in a-buffer
cDepthBits := 16; // Specifies the depth of the depth buffer
cStencilBits := 0; // Turn off stencil buffer
cAuxBuffers := 0; // Not supported
iLayerType := PFD_MAIN_PLANE; // Ignored
bReserved := 0; // Number of overlay and underlay planes
dwLayerMask := 0; // Ignored
dwVisibleMask := 0; // Transparent color of underlay plane
dwDamageMask := 0; // Ignored
end;

// Attempts to find the pixel format supported by a device context that is the best match to a given pixel format specification.
PixelFormat := ChoosePixelFormat(h_DC, @pfd);
if (PixelFormat = 0) then
begin
glKillWnd(Fullscreen);
MessageBox(0, 'Unable to find a suitable pixel format', 'Error', MB_OK or MB_ICONERROR);
Result := False;
Exit;
end;

// Sets the specified device context's pixel format to the format specified by the PixelFormat.
if (not SetPixelFormat(h_DC, PixelFormat, @pfd)) then
begin
glKillWnd(Fullscreen);
MessageBox(0, 'Unable to set the pixel format', 'Error', MB_OK or MB_ICONERROR);
Result := False;
Exit;
end;

// Create a OpenGL rendering context
h_RC := wglCreateContext(h_DC);
if (h_RC = 0) then
begin
glKillWnd(Fullscreen);
MessageBox(0, 'Unable to create an OpenGL rendering context', 'Error', MB_OK or MB_ICONERROR);
Result := False;
Exit;
end;

// Makes the specified OpenGL rendering context the calling thread's current rendering context
if (not wglMakeCurrent(h_DC, h_RC)) then
begin
glKillWnd(Fullscreen);
MessageBox(0, 'Unable to activate OpenGL rendering context', 'Error', MB_OK or MB_ICONERROR);
Result := False;
Exit;
end;

// Initializes the timer used to calculate the FPS
SetTimer(h_Wnd, FPS_TIMER, FPS_INTERVAL, nil);

// Settings to ensure that the window is the topmost window
ShowWindow(h_Wnd, SW_SHOW);
SetForegroundWindow(h_Wnd);
SetFocus(h_Wnd);

// Ensure the OpenGL window is resized properly
glResizeWnd(Width, Height);
glInit();

Result := True;
end;


{--------------------------------------------------------------------}
{ Main message loop for the application }
{--------------------------------------------------------------------}
function WinMain(hInstance : HINST; hPrevInstance : HINST;
lpCmdLine : PChar; nCmdShow : Integer) : Integer; stdcall;
var
msg : TMsg;
finished : Boolean;
DemoStart, LastTime : DWord;
begin
finished := False;

// Perform application initialization:
if not glCreateWnd(800, 600, FALSE, 32) then
begin
Result := 0;
Exit;
end;

DemoStart := GetTickCount(); // Get Time when demo started

// Main message loop:
while not finished do
begin
if (PeekMessage(msg, 0, 0, 0, PM_REMOVE)) then // Check if there is a message for this window
begin
if (msg.message = WM_QUIT) then // If WM_QUIT message received then we are done
finished := True
else
begin // Else translate and dispatch the message to this window
TranslateMessage(msg);
DispatchMessage(msg);
end;
end
else
begin
Inc(FPSCount); // Increment FPS Counter

LastTime :=ElapsedTime;
ElapsedTime :=GetTickCount() - DemoStart; // Calculate Elapsed Time
ElapsedTime :=(LastTime + ElapsedTime) DIV 2; // Average it out for smoother movement

glDraw(); // Draw the scene
SwapBuffers(h_DC); // Display the scene

if (keys[VK_ESCAPE]) then // If user pressed ESC then set finised TRUE
finished := True
else
ProcessKeys; // Check for any other key Pressed
end;
end;
glKillWnd(FALSE);
Result := msg.wParam;
end;


begin
WinMain( hInstance, hPrevInst, CmdLine, CmdShow );
end.
----------------------------------------------------------------------------------------------------------------------------------------конец программы

ниже модуль для загрузки картинок...

//----------------------------------------------------------------------------
//
// Author : Jan Horn
// Email : jhorn@global.co.za
// Website : http://home.global.co.za/~jhorn
// Date : 8 April 2001
// Description : A unit that used with OpenGL projects to load BMP files
// Usage : LoadTexture(BMPFilename, TextureName);
// eg : LoadTexture('logo.bmp', LogoTex);
//
//----------------------------------------------------------------------------
unit BMP;

interface

uses
Windows, OpenGL;

function LoadTexture(Filename: String; var Texture: GLuint): Boolean;

implementation


function gluBuild2DMipmaps(Target: GLenum; Components, Width, Height: GLint; Format, atype: GLenum; Data: Pointer): GLint; stdcall; external glu32;
procedure glGenTextures(n: GLsizei; var textures: GLuint); stdcall; external opengl32;
procedure glBindTexture(target: GLenum; texture: GLuint); stdcall; external opengl32;


{------------------------------------------------------------------}
{ Load BMP file }
{------------------------------------------------------------------}
procedure LoadBitmap(Filename: String; out Width: Cardinal; out Height: Cardinal; out pData: Pointer);
var
FileHeader: BITMAPFILEHEADER;
InfoHeader: BITMAPINFOHEADER;
Palette: array of RGBQUAD;
BitmapFile: THandle;
BitmapLength: Cardinal;
PaletteLength: Cardinal;
ReadBytes: Cardinal;
Front: ^Byte;
Back: ^Byte;
Temp: Byte;
I : Cardinal;
begin
BitmapFile := CreateFile(PChar(Filename), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
if (BitmapFile = INVALID_HANDLE_VALUE) then begin
MessageBox(0, PChar('Error opening "' + Filename), PChar('BMP Unit'), MB_OK);
Exit;
end;

// Get header information
ReadFile(BitmapFile, FileHeader, SizeOf(FileHeader), ReadBytes, nil);
ReadFile(BitmapFile, InfoHeader, SizeOf(InfoHeader), ReadBytes, nil);

// Get palette
PaletteLength := InfoHeader.biClrUsed;
SetLength(Palette, PaletteLength);
ReadFile(BitmapFile, Palette, PaletteLength, ReadBytes, nil);
if (ReadBytes <> PaletteLength) then begin
MessageBox(0, PChar('Error reading palette'), PChar('BMP Unit'), MB_OK);
Exit;
end;

Width := InfoHeader.biWidth;
Height := InfoHeader.biHeight;
BitmapLength := InfoHeader.biSizeImage;
if BitmapLength = 0 then
BitmapLength := Width * Height * InfoHeader.biBitCount Div 8;

// Get the actual pixel data
GetMem(pData, BitmapLength);
ReadFile(BitmapFile, pData^, BitmapLength, ReadBytes, nil);
if (ReadBytes <> BitmapLength) then begin
MessageBox(0, PChar('Error reading bitmap data'), PChar('BMP Unit'), MB_OK);
Exit;
end;
CloseHandle(BitmapFile);

// Bitmaps are stored BGR and not RGB, so swap the R and B bytes.
for I :=0 to Width * Height - 1 do
begin
Front := Pointer(Cardinal(pData) + I*3);
Back := Pointer(Cardinal(pData) + I*3 + 2);
Temp := Front^;
Front^ := Back^;
Back^ := Temp;
end;
end;


{------------------------------------------------------------------}
{ Load BMP textures }
{------------------------------------------------------------------}
function LoadTexture(Filename: String; var Texture: GLuint): Boolean;
var
pData: Pointer;
Width: Cardinal;
Height: Cardinal;
begin
pData :=nil;
LoadBitmap(Filename, Width, Height, pData);

if (Assigned(pData)) then
Result := True
else
begin
Result := False;
MessageBox(0, PChar('Unable to load ' + filename), 'Loading Textures', MB_OK);
Halt(1);
end;

glGenTextures(1, Texture);
glBindTexture(GL_TEXTURE_2D, Texture);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); {Texture blends with object background}
// glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); {Texture does NOT blend with object background}

{ Select a filtering type. BiLinear filtering produces very good results with little performance impact
GL_NEAREST - Basic texture (grainy looking texture)
GL_LINEAR - BiLinear filtering
GL_LINEAR_MIPMAP_NEAREST - Basic mipmapped texture
GL_LINEAR_MIPMAP_LINEAR - BiLinear Mipmapped texture
}

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); { only first two can be used }
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); { all of the above can be used }

gluBuild2DMipmaps(GL_TEXTURE_2D, 3, Width, Height, GL_RGB, GL_UNSIGNED_BYTE, pData);
// glTexImage2D(GL_TEXTURE_2D, 0, 3, Width, Height, 0, GL_RGB, GL_UNSIGNED_BYTE, pData); // Use when not wanting mipmaps to be built by openGL
end;


end.


 



http://subscribe.ru/
E-mail: ask@subscribe.ru
Отписаться
Убрать рекламу

В избранное