Here''s a quick explanation of how matrix stacks work in OpenGL. The main matrix stack is the modelview matrix. This is basically the locator (or coordinates I guess) for where in space the next object is going to be drawn (does that make sense?). Its called a stack because you can pile different matrices on. When you call glLoadIdentity() you are reseting this stack (I think, or maybe just having the top matrix an identity matrix). When you call glTranslate*() or glRotate*() you''re putting another matrix on the stack. The order you put them on the stack matters too. If you translate first, then rotate, the resulting stack is different than had you rotated then translated.
How glPushMatrix() and glPopMatrix() work is you can ''push the stack'' and that will save that place. After a push you may add more transforms, but when you pop, everything you added after the push will be erased, and it''ll be in the same position it was when you pushed. You can push multiple times, and the pop will revert the stack to the most recent push. I wonder if I''m making this seem a whole lot harder than it really is...?
--Buzzy
Computer Science Final Project
Well, the explanation kind of makes sense, but I am really not looking into matrix stacks right now. I am more concerned with getting this program to run correctly. There have been a lot of helpful, concerned comments, but I still can''t get the cube to spin. I think the solution might be a lot simpler than some of you imagine, since the original program (without classes) worked perfectly (a simple glLoadIdentity, translate, rotate, and then draw).
What''s going wrong in my code?
p.s.: a person, the reason I use ''my'' is because I was taught to use it in order to mark the private data members. I think it is kind of helpful and it makes sense. While it may not be the best way to do it, I was taught that way, and since this project is going to be graded by my teacher, I better use the techniques she teaches.
What''s going wrong in my code?
p.s.: a person, the reason I use ''my'' is because I was taught to use it in order to mark the private data members. I think it is kind of helpful and it makes sense. While it may not be the best way to do it, I was taught that way, and since this project is going to be graded by my teacher, I better use the techniques she teaches.
quote:
Original post by a person
also for reference. dont create varible names with my infront of them to show there are your varibles. it is not required and makes things look wierd. instead pick names that describe the varible, if you like prefixes, put the varible type infront. like flRot or iLength. this is merely a style concern, because it looks a bit unprofessional currrently. you dont need to change it if you dont want to for this project, but i would siggest starting to tear away from that. you probably picked up the habit from tutorials or how the teacher taught things.
--begin 100% subjective ranting--
The my prefixing is also enforced in coding style at at least one of the top 8 CS universities, and presumably will spread more and more. Its very convienant for declaring instance variables/member variables. And looks much more logical than some of the other notations I have seen such as m_someVar; Incidentally the notation spreads further to inherited public vars which should be prefixed with our. Ie: ourSomeVar. The type specifier prefixes are also specified, so a boolean instance var would be: bMyDone;
Very easy to understand and read at a glance. The example you gave, iLength gives no indication as to what type of variable it is.. I suppose you prefer m_iLength, g_iLength??? *shudder*
--end 100% subjective ranting--
Do this:
for(int i = 0; i <= 10000; i++)
{
glPushMatrix();
glRotatef(i, 1, 1, 1);
glBegin(GL_TRIANGLES);
glVertex3f(-1, 0, 0);
glVertex3f(0, 1, 0);
glVertex3f(1, 0, 0);
// The above just draws a flat triangle
glEnd();
glPopMatrix();
}
After this you should see the flat triangle spinning. You can draw other objects after the glPopMatrix() line... just the flat triangle will spin.
You NEED to call glPushMatrix() and glPopMatrix() to tell OpenGL to rotate just the triangle, otherwise it will spin all the world. Calling them, just objects beeing drawed between them will be affected by the rotation.
Try this code, you'll see.
See you!
[edited by - ChacaL on May 2, 2002 12:55:48 AM]
[edited by - ChacaL on May 3, 2002 2:35:19 AM]
for(int i = 0; i <= 10000; i++)
{
glPushMatrix();
glRotatef(i, 1, 1, 1);
glBegin(GL_TRIANGLES);
glVertex3f(-1, 0, 0);
glVertex3f(0, 1, 0);
glVertex3f(1, 0, 0);
// The above just draws a flat triangle
glEnd();
glPopMatrix();
}
After this you should see the flat triangle spinning. You can draw other objects after the glPopMatrix() line... just the flat triangle will spin.
You NEED to call glPushMatrix() and glPopMatrix() to tell OpenGL to rotate just the triangle, otherwise it will spin all the world. Calling them, just objects beeing drawed between them will be affected by the rotation.
Try this code, you'll see.
See you!
[edited by - ChacaL on May 2, 2002 12:55:48 AM]
[edited by - ChacaL on May 3, 2002 2:35:19 AM]
Domninus: Yes, I am working off NeHe''s base code, so my Main function is exactly the same (except that I declare the objects within Main and pass an apvector to DrawGLScene, rather than passing nothing).
Chacal: Well, I can definitely see how that works, but I don''t like the way it works at all. It will have to go through the for loop 10000 times before jumping out of the loop, which means the program will not monitor for any keystrokes during that time. Also, when it reaches the end, the angle will be 10000. When the function is called the next time, the angle will be 0, and since 10000 is not a multiple of 360 (I don''t think it is), there will be a slight ''skip.''
Chacal: Well, I can definitely see how that works, but I don''t like the way it works at all. It will have to go through the for loop 10000 times before jumping out of the loop, which means the program will not monitor for any keystrokes during that time. Also, when it reaches the end, the angle will be 10000. When the function is called the next time, the angle will be 0, and since 10000 is not a multiple of 360 (I don''t think it is), there will be a slight ''skip.''
Well, since it seems like no one can find the problem, I might as well post all of the code.
I will do each file in a seperate post (not sure if there is a length restriction).
My main file (final_project.cpp):
I will do each file in a seperate post (not sure if there is a length restriction).
My main file (final_project.cpp):
/**************************************************************************| AP Computer Science A || FINAL PROJECT || || Created by: Dan Carroll || || Base code created by Jeff Molofee (NeHe) || - code is available for download at http://nehe.gamedev.net/ || - Jeff's tutorials were used to gain an understanding of the OpenGL || API and to learn the commands necessary for this particular || project. While this program is simplistic, it will be used as || the basis for further exploration in 3d graphics programming. || || Code modified to display a rotating cube inside a rectangular room || - A Cube class was created to draw cubes of various sizes and colors || (rectangular cubes can also be created) || - The apvector class is being utilized to hold multiple Cube objects || and allow for more than one cube to be drawn easily (by only || sending one apvector to the DrawGLScene function, rather than || individual objects). The apvector class is also being used to hold || variables for the cube's color, position, and rotation parameters. || || || Last modified: May 3, 2002 || | \**************************************************************************/#include <windows.h> // Header File For Windows#include <gl\gl.h> // Header File For The OpenGL32 Library#include <gl\glu.h> // Header File For The GLu32 Library#include <gl\glaux.h> // Header File For The GLaux Library#include "cube.h" // Header file for the Cube class#include "apvector.h" // Header file for the AP vector classHGLRC hRC=NULL; // Permanent Rendering ContextHDC hDC=NULL; // Private GDI Device ContextHWND hWnd=NULL; // Holds Our Window HandleHINSTANCE hInstance; // Holds The Instance Of The ApplicationBOOL keys[256]; // Array Used For The Keyboard RoutineBOOL active=TRUE; // Window Active Flag Set To TRUE By DefaultBOOL fullscreen=TRUE; // Fullscreen Flag Set To Fullscreen Mode By DefaultGLfloat cuberot; // Rotation angle for the spinning cubeLRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For WndProcGLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window{ if (height==0) // Prevent A Divide By Zero By { height=1; // Making Height Equal One } glViewport(0, 0, width, height); // Reset The Current Viewport glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glLoadIdentity(); // Reset The Projection Matrix // Calculate The Aspect Ratio Of The Window gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f); glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix glLoadIdentity(); // Reset The Modelview Matrix}int InitGL(GLvoid) // All Setup For OpenGL Goes Here{ glShadeModel(GL_SMOOTH); // Enables Smooth Shading glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Black Background glClearDepth(1.0f); // Depth Buffer Setup glEnable(GL_DEPTH_TEST); // Enables Depth Testing glDepthFunc(GL_LEQUAL); // The Type Of Depth Test To Do glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations return TRUE; // Initialization Went OK}int DrawGLScene(apvector <Cube> cubes) // Here's Where We Do All The Drawing{ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer // Draw the objects for (int i = 0; i < cubes.length(); i++) { glLoadIdentity(); cubes.Draw();<br> }<br><br>/* glLoadIdentity();<br> glTranslatef(0.0f,-1.0f,-7.0f);<br> cubes[0].Draw();<br><br> glLoadIdentity();<br> glTranslatef(0.0f,-1.0f,-5.0f);<br> cubes[1].Draw();<br>*/</font><br> <font color="blue">return</font> TRUE; <font color="gray">// Everything Went OK<br></font><br>}<br><br>GL<font color="blue">void</font> KillGLWindow(GLvoid) <font color="gray">// Properly Kill The Window<br></font><br>{<br> <font color="blue">if</font> (fullscreen) <font color="gray">// Are We In Fullscreen Mode?<br></font><br> {<br> ChangeDisplaySettings(NULL,0); <font color="gray">// If So Switch Back To The Desktop<br></font><br> ShowCursor(TRUE); <font color="gray">// Show Mouse Pointer<br></font><br> }<br> <font color="blue">if</font> (hRC) <font color="gray">// Do We Have A Rendering Context?<br></font><br> {<br> <font color="blue">if</font> (!wglMakeCurrent(NULL,NULL)) <font color="gray">// Are We Able To Release The DC And RC Contexts?<br></font><br> {<br> MessageBox(NULL,<font color="darkred">"Release Of DC And RC Failed."</font>,<font color="darkred">"SHUTDOWN ERROR"</font>,MB_OK | MB_ICONINFORMATION);<br> }<br> <font color="blue">if</font> (!wglDeleteContext(hRC)) <font color="gray">// Are We Able To Delete The RC?<br></font><br> {<br> MessageBox(NULL,<font color="darkred">"Release Rendering Context Failed."</font>,<font color="darkred">"SHUTDOWN ERROR"</font>,MB_OK | MB_ICONINFORMATION);<br> }<br> hRC=NULL; <font color="gray">// Set RC To NULL<br></font><br> }<br> <font color="blue">if</font> (hDC && !ReleaseDC(hWnd,hDC)) <font color="gray">// Are We Able To Release The DC<br></font><br> {<br> MessageBox(NULL,<font color="darkred">"Release Device Context Failed."</font>,<font color="darkred">"SHUTDOWN ERROR"</font>,MB_OK | MB_ICONINFORMATION);<br> hDC=NULL; <font color="gray">// Set DC To NULL<br></font><br> }<br> <font color="blue">if</font> (hWnd && !DestroyWindow(hWnd)) <font color="gray">// Are We Able To Destroy The Window?<br></font><br> {<br> MessageBox(NULL,<font color="darkred">"Could Not Release hWnd."</font>,<font color="darkred">"SHUTDOWN ERROR"</font>,MB_OK | MB_ICONINFORMATION);<br> hWnd=NULL; <font color="gray">// Set hWnd To NULL<br></font><br> }<br> <font color="blue">if</font> (!UnregisterClass(<font color="darkred">"OpenGL"</font>,hInstance)) <font color="gray">// Are We Able To Unregister Class<br></font><br> {<br> MessageBox(NULL,<font color="darkred">"Could Not Un<font color="blue">register</font> Class."</font>,<font color="darkred">"SHUTDOWN ERROR"</font>,MB_OK | MB_ICONINFORMATION);<br> hInstance=NULL; <font color="gray">// Set hInstance To NULL<br></font><br> }<br>}<br><br>BOOL CreateGLWindow(char* title, <font color="blue">int</font> width, <font color="blue">int</font> height, <font color="blue">int</font> bits, BOOL fullscreenflag)<br>{<br> GLu<font color="blue">int</font> PixelFormat; <font color="gray">// Holds The Results After Searching For A Match<br></font><br> WNDCLASS wc; <font color="gray">// Windows Class Structure<br></font><br> DWORD dwExStyle; <font color="gray"><font color="gray"><font color="gray">// Window Extended Style<br></font></font></font><br> DWORD dwStyle; <font color="gray">// Window Style<br></font><br> RECT WindowRect; <font color="gray">// Grabs Rectangle Upper Left / Lower Right Values<br></font><br> WindowRect.left=(long)0; <font color="gray">// Set Left Value To 0<br></font><br> WindowRect.right=(long)width; <font color="gray">// Set Right Value To Requested Width<br></font><br> WindowRect.top=(long)0; <font color="gray">// Set Top Value To 0<br></font><br> WindowRect.bottom=(long)height; <font color="gray">// Set Bottom Value To Requested Height<br></font><br> fullscreen=fullscreenflag; <font color="gray">// Set The Global Fullscreen Flag<br></font><br> hInstance = GetModuleHandle(NULL); <font color="gray">// Grab An Instance For Our Window<br></font><br> wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; <font color="gray">// Redraw On Move, And Own DC For Window<br></font><br> wc.lpfnWndProc = (WNDPROC) WndProc; <font color="gray">// WndProc Handles Messages<br></font><br> wc.cbClsExtra = 0; <font color="gray"><font color="gray">// No Extra Window Data<br></font></font><br> wc.cbWndExtra = 0; <font color="gray"><font color="gray">// No Extra Window Data<br></font></font><br> wc.hInstance = hInstance; <font color="gray">// Set The Instance<br></font><br> wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); <font color="gray">// Load The Default Icon<br></font><br> wc.hCursor = LoadCursor(NULL, IDC_ARROW); <font color="gray">// Load The Arrow Pointer<br></font><br> wc.hbrBackground = NULL; <font color="gray">// No Background Required For GL<br></font><br> wc.lpszMenuName = NULL; <font color="gray">// We Don't Want A Menu<br></font><br> wc.lpszClassName = <font color="darkred">"OpenGL"</font>; <font color="gray">// Set The Class Name<br></font><br><br> <font color="blue">if</font> (!RegisterClass(&wc)) <font color="gray">// Attempt To Register The Window Class<br></font><br> {<br> MessageBox(NULL,<font color="darkred">"Failed To Register The Window Class."</font>,<font color="darkred">"ERROR"</font>,MB_OK|MB_ICONEXCLAMATION);<br> <font color="blue">return</font> FALSE; <font color="gray"><font color="gray">// Exit And Return FALSE<br></font></font><br> }<br> <font color="blue">if</font> (fullscreen) <font color="gray">// Attempt Fullscreen Mode?<br></font><br> {<br> DEVMODE dmScreenSettings; <font color="gray">// Device Mode<br></font><br> memset(&dmScreenSettings,0,<font color="blue">sizeof</font>(dmScreenSettings)); <font color="gray">// Makes Sure Memory's Cleared<br></font><br> dmScreenSettings.dmSize=<font color="blue">sizeof</font>(dmScreenSettings); <font color="gray">// Size Of The Devmode Structure<br></font><br> dmScreenSettings.dmPelsWidth = width; <font color="gray">// Selected Screen Width<br></font><br> dmScreenSettings.dmPelsHeight = height; <font color="gray">// Selected Screen Height<br></font><br> dmScreenSettings.dmBitsPerPel = bits; <font color="gray">// Selected Bits Per Pixel<br></font><br> dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;<br><br> <font color="gray">// Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.<br></font><br> <font color="blue">if</font> (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)<br> {<br> <font color="gray">// If The Mode Fails, Offer Two Options. Quit Or Run In A Window.<br></font><br> <font color="blue">if</font> (MessageBox(NULL,<font color="darkred">"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?"</font>,<font color="darkred">"NeHe GL"</font>,MB_YESNO|MB_ICONEXCLAMATION)==IDYES)<br> {<br> fullscreen=FALSE; <font color="gray">// Select Windowed Mode (Fullscreen=FALSE)<br></font><br> }<br> <font color="blue">else</font><br> {<br> <font color="gray">// Pop Up A Message Box Letting User Know The Program Is Closing.<br></font><br> MessageBox(NULL,<font color="darkred">"Program Will Now Close."</font>,<font color="darkred">"ERROR"</font>,MB_OK|MB_ICONSTOP);<br> <font color="blue">return</font> FALSE; <font color="gray"><font color="gray">// Exit And Return FALSE<br></font></font><br> }<br> }<br> }<br> <font color="blue">if</font> (fullscreen) <font color="gray">// Are We Still In Fullscreen Mode?<br></font><br> {<br> dwExStyle=WS_EX_APPWINDOW; <font color="gray"><font color="gray"><font color="gray">// Window Extended Style<br></font></font></font><br> dwStyle=WS_POPUP; <font color="gray"><font color="gray">// Windows Style<br></font></font><br> ShowCursor(FALSE); <font color="gray">// Hide Mouse Pointer<br></font><br> }<br> <font color="blue">else</font><br> {<br> dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; <font color="gray"><font color="gray"><font color="gray">// Window Extended Style<br></font></font></font><br> dwStyle=WS_OVERLAPPEDWINDOW; <font color="gray"><font color="gray">// Windows Style<br></font></font><br> }<br><br> AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); <font color="gray">// Adjust Window To True Requested Size<br></font><br><br> <font color="blue">if</font> (!(hWnd=CreateWindowEx( dwExStyle, <font color="gray">// Extended Style For The Window<br></font><br> <font color="darkred">"OpenGL"</font>, <font color="gray">// Class Name<br></font><br> title, <font color="gray">// Window Title<br></font><br> WS_CLIPSIBLINGS | <font color="gray"><font color="gray">// Required Window Style<br></font></font><br> WS_CLIPCHILDREN | <font color="gray"><font color="gray">// Required Window Style<br></font></font><br> dwStyle, <font color="gray">// Selected Window Style<br></font><br> 0, 0, <font color="gray">// Window Position<br></font><br> WindowRect.right-WindowRect.left, <font color="gray">// Calculate Adjusted Window Width<br></font><br> WindowRect.bottom-WindowRect.top, <font color="gray">// Calculate Adjusted Window Height<br></font><br> NULL, <font color="gray">// No Parent Window<br></font><br> NULL, <font color="gray">// No Menu<br></font><br> hInstance, <font color="gray"><font color="gray">// Instance<br></font></font><br> NULL))) <font color="gray">// Don't Pass Anything To WM_CREATE<br></font><br> {<br> KillGLWindow(); <font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray">// Reset The Display<br></font></font></font></font></font></font></font><br> MessageBox(NULL,<font color="darkred">"Window Creation Error."</font>,<font color="darkred">"ERROR"</font>,MB_OK|MB_ICONEXCLAMATION);<br> <font color="blue">return</font> FALSE; <font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray">// Return FALSE<br></font></font></font></font></font></font></font><br> }<br> <font color="blue">static</font> PIXELFORMATDESCRIPTOR pfd= <font color="gray">// pfd Tells Windows How We Want Things To Be<br></font><br> {<br> <font color="blue">sizeof</font>(PIXELFORMATDESCRIPTOR), <font color="gray">// Size Of This Pixel Format Descriptor<br></font><br> 1, <font color="gray">// Version Number<br></font><br> PFD_DRAW_TO_WINDOW | <font color="gray">// Format Must Support Window<br></font><br> PFD_SUPPORT_OPENGL | <font color="gray">// Format Must Support OpenGL<br></font><br> PFD_DOUBLEBUFFER, <font color="gray">// Must Support Double Buffering<br></font><br> PFD_TYPE_RGBA, <font color="gray">// Request An RGBA Format<br></font><br> bits, <font color="gray">// Select Our Color Depth<br></font><br> 0, 0, 0, 0, 0, 0, <font color="gray">// Color Bits Ignored<br></font><br> 0, <font color="gray">// No Alpha Buffer<br></font><br> 0, <font color="gray">// Shift Bit Ignored<br></font><br> 0, <font color="gray">// No Accumulation Buffer<br></font><br> 0, 0, 0, 0, <font color="gray">// Accumulation Bits Ignored<br></font><br> 16, <font color="gray">// 16Bit Z-Buffer (Depth Buffer)<br></font><br> 0, <font color="gray">// No Stencil Buffer<br></font><br> 0, <font color="gray">// No Auxiliary Buffer<br></font><br> PFD_MAIN_PLANE, <font color="gray">// Main Drawing Layer<br></font><br> 0, <font color="gray">// Reserved<br></font><br> 0, 0, 0 <font color="gray">// Layer Masks Ignored<br></font><br> };<br><br> <font color="blue">if</font> (!(hDC=GetDC(hWnd))) <font color="gray">// Did We Get A Device Context?<br></font><br> {<br> KillGLWindow(); <font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray">// Reset The Display<br></font></font></font></font></font></font></font><br> MessageBox(NULL,<font color="darkred">"Can't Create A GL Device Context."</font>,<font color="darkred">"ERROR"</font>,MB_OK|MB_ICONEXCLAMATION);<br> <font color="blue">return</font> FALSE; <font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray">// Return FALSE<br></font></font></font></font></font></font></font><br> }<br> <font color="blue">if</font> (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) <font color="gray">// Did Windows Find A Matching Pixel Format?<br></font><br> {<br> KillGLWindow(); <font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray">// Reset The Display<br></font></font></font></font></font></font></font><br> MessageBox(NULL,<font color="darkred">"Can't Find A Suitable PixelFormat."</font>,<font color="darkred">"ERROR"</font>,MB_OK|MB_ICONEXCLAMATION);<br> <font color="blue">return</font> FALSE; <font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray">// Return FALSE<br></font></font></font></font></font></font></font><br> }<br> <font color="blue">if</font>(!SetPixelFormat(hDC,PixelFormat,&pfd)) <font color="gray">// Are We Able To Set The Pixel Format?<br></font><br> {<br> KillGLWindow(); <font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray">// Reset The Display<br></font></font></font></font></font></font></font><br> MessageBox(NULL,<font color="darkred">"Can't Set The PixelFormat."</font>,<font color="darkred">"ERROR"</font>,MB_OK|MB_ICONEXCLAMATION);<br> <font color="blue">return</font> FALSE; <font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray">// Return FALSE<br></font></font></font></font></font></font></font><br> }<br> <font color="blue">if</font> (!(hRC=wglCreateContext(hDC))) <font color="gray">// Are We Able To Get A Rendering Context?<br></font><br> {<br> KillGLWindow(); <font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray">// Reset The Display<br></font></font></font></font></font></font></font><br> MessageBox(NULL,<font color="darkred">"Can't Create A GL Rendering Context."</font>,<font color="darkred">"ERROR"</font>,MB_OK|MB_ICONEXCLAMATION);<br> <font color="blue">return</font> FALSE; <font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray">// Return FALSE<br></font></font></font></font></font></font></font><br> }<br> <font color="blue">if</font>(!wglMakeCurrent(hDC,hRC)) <font color="gray">// Try To Activate The Rendering Context<br></font><br> {<br> KillGLWindow(); <font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray">// Reset The Display<br></font></font></font></font></font></font></font><br> MessageBox(NULL,<font color="darkred">"Can't Activate The GL Rendering Context."</font>,<font color="darkred">"ERROR"</font>,MB_OK|MB_ICONEXCLAMATION);<br> <font color="blue">return</font> FALSE; <font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray">// Return FALSE<br></font></font></font></font></font></font></font><br> }<br><br> ShowWindow(hWnd,SW_SHOW); <font color="gray">// Show The Window<br></font><br> SetForegroundWindow(hWnd); <font color="gray">// Slightly Higher Priority<br></font><br> SetFocus(hWnd); <font color="gray">// Sets Keyboard Focus To The Window<br></font><br> ReSizeGLScene(width, height); <font color="gray">// Set Up Our Perspective GL Screen<br></font><br><br> <font color="blue">if</font> (!InitGL()) <font color="gray">// Initialize Our Newly Created GL Window<br></font><br> {<br> KillGLWindow(); <font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray">// Reset The Display<br></font></font></font></font></font></font></font><br> MessageBox(NULL,<font color="darkred">"Initialization Failed."</font>,<font color="darkred">"ERROR"</font>,MB_OK|MB_ICONEXCLAMATION);<br> <font color="blue">return</font> FALSE; <font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray"><font color="gray">// Return FALSE<br></font></font></font></font></font></font></font><br> }<br><br> <font color="blue">return</font> TRUE; <font color="gray">// Success<br></font><br>}<br><br>LRESULT CALLBACK WndProc( HWND hWnd, <font color="gray">// Handle For This Window<br></font><br> UINT uMsg, <font color="gray">// Message For This Window<br></font><br> WPARAM wParam, <font color="gray"><font color="gray">// Additional Message Information<br></font></font><br> LPARAM lParam) <font color="gray"><font color="gray">// Additional Message Information<br></font></font><br>{<br> <font color="blue">switch</font> (uMsg) <font color="gray">// Check For Windows Messages<br></font><br> {<br> <font color="blue">case</font> WM_ACTIVATE: <font color="gray">// Watch For Window Activate Message<br></font><br> {<br> <font color="blue">if</font> (!HIWORD(wParam)) <font color="gray">// Check Minimization State<br></font><br> {<br> active=TRUE; <font color="gray">// Program Is Active<br></font><br> }<br> <font color="blue">else</font><br> {<br> active=FALSE; <font color="gray">// Program Is No Longer Active<br></font><br> }<br><br> <font color="blue">return</font> 0; <font color="gray">// Return To The Message Loop<br></font><br> }<br><br> <font color="blue">case</font> WM_SYSCOMMAND: <font color="gray">// Intercept System Commands<br></font><br> {<br> <font color="blue">switch</font> (wParam) <font color="gray">// Check System Calls<br></font><br> {<br> <font color="blue">case</font> SC_SCREENSAVE: <font color="gray">// Screensaver Trying To Start?<br></font><br> <font color="blue">case</font> SC_MONITORPOWER: <font color="gray">// Monitor Trying To Enter Powersave?<br></font><br> <font color="blue">return</font> 0; <font color="gray">// Prevent From Happening<br></font><br> }<br> break; <font color="gray">// Exit<br></font><br> }<br> <font color="blue">case</font> WM_CLOSE: <font color="gray">// Did We Receive A Close Message?<br></font><br> {<br> PostQuitMessage(0); <font color="gray">// Send A Quit Message<br></font><br> <font color="blue">return</font> 0; <font color="gray"><font color="gray"><font color="gray"><font color="gray">// Jump Back<br></font></font></font></font><br> }<br> <font color="blue">case</font> WM_KEYDOWN: <font color="gray">// Is A Key Being Held Down?<br></font><br> {<br> keys[<font color="purple">wParam</font>] = TRUE; <font color="gray">// If So, Mark It As TRUE<br></font><br> <font color="blue">return</font> 0; <font color="gray"><font color="gray"><font color="gray"><font color="gray">// Jump Back<br></font></font></font></font><br> }<br> <font color="blue">case</font> WM_KEYUP: <font color="gray">// Has A Key Been Released?<br></font><br> {<br> keys[<font color="purple">wParam</font>] = FALSE; <font color="gray">// If So, Mark It As FALSE<br></font><br> <font color="blue">return</font> 0; <font color="gray"><font color="gray"><font color="gray"><font color="gray">// Jump Back<br></font></font></font></font><br> }<br> <font color="blue">case</font> WM_SIZE: <font color="gray">// Resize The OpenGL Window<br></font><br> {<br> ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); <font color="gray">// LoWord=Width, HiWord=Height<br></font><br> <font color="blue">return</font> 0; <font color="gray"><font color="gray"><font color="gray"><font color="gray">// Jump Back<br></font></font></font></font><br> }<br> }<br><br> <font color="gray">// Pass All Unhandled Messages To DefWindowProc<br></font><br> <font color="blue">return</font> DefWindowProc(hWnd,uMsg,wParam,lParam);<br>}<br><br><font color="blue">int</font> WINAPI WinMain( HINSTANCE hInstance, <font color="gray"><font color="gray">// Instance<br></font></font><br> HINSTANCE hPrevInstance, <font color="gray">// Previous Instance<br></font><br> LPSTR lpCmdLine, <font color="gray">// Command Line Parameters<br></font><br> <font color="blue">int</font> nCmdShow) <font color="gray">// Window Show State<br></font><br>{<br> MSG msg; <font color="gray">// Windows Message Structure<br></font><br> BOOL done=FALSE; <font color="gray">// Bool Variable To Exit Loop<br></font><br><br> <font color="gray">// Ask The User Which Screen Mode They Prefer<br></font><br> <font color="blue">if</font> (MessageBox(NULL,<font color="darkred">"Would You Like To Run In Fullscreen Mode?"</font>, <font color="darkred">"Start FullScreen?"</font>,MB_YESNO|MB_ICONQUESTION)==IDNO)<br> {<br> fullscreen=FALSE; <font color="gray">// Windowed Mode<br></font><br> }<br> <font color="gray">// Create Our OpenGL Window<br></font><br> <font color="blue">if</font> (!CreateGLWindow(<font color="darkred">"Dan Carroll's Final Project"</font>,640,480,16,fullscreen))<br> {<br> <font color="blue">return</font> 0; <font color="gray"><font color="gray">// Quit If Window Was Not Created<br></font></font><br> }<br><br> <font color="gray">// Create cube objects<br></font><br> Cube room(6.0f,6.0f,15.0f);<br> Cube cube(1.0f,1.0f,1.0f);<br><br> <font color="gray">// Modify cube parameters<br></font><br> room.SetColor(0.5f,0.5f,0.5f);<br> room.ShowDepth(TRUE);<br> room.SetPosition(0.0f,-1.0f,-7.0f);<br> cube.IsRotation(TRUE);<br> cube.SetColor(0.2f,0.1f,1.0f);<br> cube.SetPosition(0.0f,-1.0f,-5.0f);<br> cube.SetRotation(2.0f,1.0f,1.0f,0.0f);<br><br> apvector <Cube> cubes(2);<br> cubes[<font color="purple">0</font>] = room;<br> cubes[<font color="purple">1</font>] = cube;<br><br> <font color="blue">while</font>(!done) <font color="gray">// Loop That Runs Until done=TRUE<br></font><br> {<br> <font color="blue">if</font> (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) <font color="gray">// Is There A Message Waiting?<br></font><br> {<br> <font color="blue">if</font> (msg.message==WM_QUIT) <font color="gray">// Have We Received A Quit Message?<br></font><br> {<br> done=TRUE; <font color="gray">// If So done=TRUE<br></font><br> }<br> <font color="blue">else</font> <font color="gray">// If Not, Deal With Window Messages<br></font><br> {<br> TranslateMessage(&msg); <font color="gray">// Translate The Message<br></font><br> DispatchMessage(&msg); <font color="gray">// Dispatch The Message<br></font><br> }<br> }<br> <font color="blue">else</font> <font color="gray">// If There Are No Messages<br></font><br> {<br> <font color="gray">// Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene()<br></font><br> <font color="blue">if</font> (active) <font color="gray">// Program Active?<br></font><br> {<br> <font color="blue">if</font> (keys[<font color="purple">VK_ESCAPE</font>]) <font color="gray">// Was ESC Pressed?<br></font><br> {<br> done=TRUE; <font color="gray">// ESC Signalled A Quit<br></font><br> }<br> <font color="blue">else</font> <font color="gray">// Not Time To Quit, Update Screen<br></font><br> {<br> DrawGLScene(cubes); <font color="gray">// Draw The Scene<br></font><br> SwapBuffers(hDC); <font color="gray">// Swap Buffers (Double Buffering)<br></font><br> }<br> }<br> <font color="blue">if</font> (keys[<font color="purple">VK_F1</font>]) <font color="gray">// Is F1 Being Pressed?<br></font><br> {<br> keys[<font color="purple">VK_F1</font>]=FALSE; <font color="gray">// If So Make Key FALSE<br></font><br> KillGLWindow(); <font color="gray">// Kill Our Current Window<br></font><br> fullscreen=!fullscreen; <font color="gray">// Toggle Fullscreen / Windowed Mode<br></font><br> <font color="gray">// Recreate Our OpenGL Window<br></font><br> <font color="blue">if</font> (!CreateGLWindow(<font color="darkred">"Dan Carroll's Final Project"</font>,640,480,16,fullscreen))<br> {<br> <font color="blue">return</font> 0; <font color="gray"><font color="gray">// Quit If Window Was Not Created<br></font></font><br> }<br> }<br> }<br> }<br> <font color="gray">// Shutdown<br></font><br> KillGLWindow(); <font color="gray">// Kill The Window<br></font><br> <font color="blue">return</font> (msg.wParam); <font color="gray">// Exit The Program<br></font><br>}<br> </pre></DIV><!–ENDSCRIPT–><br><br><i>Edit: Some of the formatting got messed up, but the code is all there. And for some reason it treats a large portion of the code as commented out, but trust me, it is not! </i> <br><br><SPAN CLASS=editedby>[edited by - Erunama on May 3, 2002 4:26:38 PM]</SPAN>
I'll squeeze two header files into one here.
My Cube class header file (cube.h):
Edit: Some weird green font stuff going on here...
[edited by - Erunama on May 3, 2002 4:32:46 PM]
My Cube class header file (cube.h):
#ifndef _CUBE_H#define _CUBE_H#include <windows.h> // Header File For Windows#include <gl\gl.h> // Header File For The OpenGL32 Library#include <gl\glu.h> // Header File For The GLu32 Library#include <gl\glaux.h> // Header File For The GLaux Library#include "apvector.h"class Cube{ public://///////////////////////////////////////////////////////////////////// constructors Cube(); Cube(GLfloat length, GLfloat width, GLfloat height);/////////////////////////////////////////////////////////////////////// destructor ~Cube();/////////////////////////////////////////////////////////////////////// modifying functions void SetDimensions(GLfloat length, GLfloat width, GLfloat height); void SetColor(GLfloat red, GLfloat green, GLfloat blue); void ShowDepth(BOOL depth); void IsRotation(BOOL rotation); void SetRotation(GLfloat change, GLfloat x, GLfloat y, GLfloat z); void SetPosition(GLfloat x, GLfloat y, GLfloat z); void Draw(); // uses private data members to draw cube on the screen private: // cube size variables GLfloat myHeight; // height of the cube (along y axis) GLfloat myLength; // length of the cube (along z axis) GLfloat myWidth; // width of the cube (along x axis) // cube state variables BOOL myDepth; // shade the cube? BOOL myRotate; // rotate the cube? BOOL amIDefined; // draw the cube? // rotation variables apvector<GLfloat> myRot; // vector holding the rotational axis GLfloat myAngle; // the cube's current angle GLfloat myChange; // the rate that the cube spins apvector<GLfloat> myPosition; // vector holding the position values apvector<GLfloat> myColor; // vector holding the color values (R,G,B)};#endif And the apvector header file (apvector.h): #ifndef _APVECTOR_H#define _APVECTOR_H// *******************************************************************// Last Revised: 8/14/98, abort changed to exit//// January 13,1998, added explicit to int constructor// APCS vector class template//// implements "safe" (range-checked) arrays// examples are given at the end of this file// *******************************************************************// If your compiler supports the keyword explicit, comment out the// #define explicit line below, leaving the #define means explicit// is ignored, but doesn't generate an error//// This will disallow a typically erroneous implicit type-conversion:// vector<int> v( 10 );// v = 0; // Oops!! Allowed because of implicit type-con2lversion.#define explicittemplate <class itemType>class apvector{ public: // constructors/destructor apvector( ); // default constructor (size==0) explicit apvector( int size ); // initial size of vector is size apvector( int size, const itemType & fillValue ); // all entries == fillValue apvector( const apvector & vec ); // copy constructor ~apvector( ); // destructor // assignment const apvector & operator = ( const apvector & vec ); // accessors int length( ) const; // capacity of vector // indexing itemType & operator [ ] ( int index ); // indexing with range checking const itemType & operator [ ] ( int index ) const; // indexing with range checking // modifiers void resize( int newSize ); // change size dynamically; // can result in losing values private: int mySize; // # elements in array itemType * myList; // array used for storage};// *******************************************************************// Specifications for vector functions//// The template parameter itemType must satisfy the following two conditions:// (1) itemType has a 0-argument constructor// (2) operator = is defined for itemType// Any violation of these conditions may result in compilation failure.//// Any violation of a function's precondition will result in an error message// followed by a call to exit.//// constructors/destructor//// apvector( )// postcondition: vector has a capacity of 0 items, and therefore it will// need to be resized//// apvector( int size )// precondition: size >= 0// postcondition: vector has a capacity of size items//// apvector( int size, const itemType & fillValue )// precondition: size >= 0// postcondition: vector has a capacity of size items, all of which are set// by assignment to fillValue after default construction//// apvector( const apvector & vec )// postcondition: vector is a copy of vec//// ~apvector( )// postcondition: vector is destroyed//// assignment//// const apvector & operator = ( const apvector & rhs )// postcondition: normal assignment via copying has been performed;// if vector and rhs were different sizes, vector// has been resized to match the size of rhs//// accessor//// int length( ) const// postcondition: returns vector's size (number of memory cells// allocated for vector)//// indexing//// itemType & operator [ ] ( int k ) -- index into nonconst vector// const itemType & operator [ ] ( int k ) const -- index into const vector// description: range-checked indexing, returning kth item// precondition: 0 <= k < length()// postcondition: returns the kth item//// modifier//// void resize( int newSize )// description: resizes the vector to newSize elements// precondition: the current capacity of vector is length; newSize >= 0//// postcondition: the current capacity of vector is newSize; for each k// such that 0 <= k <= min(length, newSize), vector[k]// is a copy of the original; other elements of vector are// initialized using the 0-argument itemType constructor// Note: if newSize < length, elements may be lost//// examples of use// apvector<int> v1; // 0-element vector// apvector<int> v2(4); // 4-element vector// apvector<int> v3(4, 22); // 4-element vector, all elements == 22.#include "apvector.cpp"#endif
Edit: Some weird green font stuff going on here...
[edited by - Erunama on May 3, 2002 4:32:46 PM]
And finally, my Cube class source code (cube.cpp):
Ok! Now that there are no questions about exactly what my code is, can anyone figure out my problem?
Edit: Tried to fix some errors, but there seems to be a problem with the 'source' tags. Before you ask about missing header files or the like, make sure you scroll over because cut-and-paste seems to have screwed with things like the carriage returns
Edit #2: Hrmmmm, now the apvector.cpp code has disappeared. Hopefully, it will come back now. If not, I don't think you really need it to analyze my code.
[edited by - Erunama on May 3, 2002 4:42:42 PM]
[edited by - Erunama on May 3, 2002 4:44:51 PM]
#include <windows.h> // Header File For Windows#include <gl\gl.h> // Header File For The OpenGL32 Library#include <gl\glu.h> // Header File For The GLu32 Library#include <gl\glaux.h> // Header File For The GLaux Library#include "cube.h" // Header file for the Cube class#include "apvector.h"// constructorsCube::Cube() : amIDefined(FALSE){}Cube::Cube(GLfloat x, GLfloat y, GLfloat z) : amIDefined(TRUE), myLength(z), myHeight(y), myWidth(x), myDepth(FALSE), myRotate(FALSE), myAngle(0.0f), myChange(0.0f), myRot(3), myPosition(3), myColor(3){ // set default position to center of screen myPosition[0] = 0.0f; myPosition[1] = 0.0f; myPosition[2] = 0.0f; // set default color to white myColor[0] = 1.0f; myColor[1] = 1.0f; myColor[2] = 1.0f;}Cube::~Cube(){}// modifying functionsvoid Cube::SetDimensions(GLfloat x, GLfloat y, GLfloat z){ myLength = z; myWidth = x; myHeight = y;}void Cube::SetColor(GLfloat red, GLfloat green, GLfloat blue){ myColor[0] = red; myColor[1] = green; myColor[2] = blue;}void Cube::ShowDepth(BOOL depth){ myDepth = depth;}void Cube::IsRotation(BOOL rotation){ myRotate = rotation;}void Cube::SetRotation(GLfloat change, GLfloat x, GLfloat y, GLfloat z){ myChange = change; myRot[0] = x; myRot[1] = y; myRot[2] = z;}void Cube::SetPosition(GLfloat x, GLfloat y, GLfloat z){ myPosition[0] = x; myPosition[1] = y; myPosition[2] = z;}void Cube::Draw(){ if(amIDefined) { glTranslatef(myPosition[0],myPosition[1],myPosition[2]); if(myRotate) { glRotatef(myAngle,myRot[0],myRot[1],myRot[2]); myAngle += myChange; } //Start drawing the cube glBegin(GL_QUADS); glColor3f(myColor[0],myColor[1],myColor[2]); // Draw the left side of the cube glVertex3f(-(myWidth/2.0f),(myHeight/2.0f),(myLength/2.0f)); glVertex3f(-(myWidth/2.0f),-(myHeight/2.0f),(myLength/2.0f)); if(myDepth) glColor3f(myColor[0] - 0.15f,myColor[1] - 0.15f,myColor[2] - 0.15f); glVertex3f(-(myWidth/2.0f),-(myHeight/2.0f),-(myLength/2.0f)); glVertex3f(-(myWidth/2.0f),(myHeight/2.0f),-(myLength/2.0f)); glColor3f(myColor[0],myColor[1],myColor[2]); // Draw the right side of the cube glVertex3f((myWidth/2.0f),(myHeight/2.0f),(myLength/2.0f)); glVertex3f((myWidth/2.0f),-(myHeight/2.0f),(myLength/2.0f)); if(myDepth) glColor3f(myColor[0] - 0.15f,myColor[1] - 0.15f,myColor[2] - 0.15f); glVertex3f((myWidth/2.0f),-(myHeight/2.0f),-(myLength/2.0f)); glVertex3f((myWidth/2.0f),(myHeight/2.0f),-(myLength/2.0f)); // Draw the back of the cube glVertex3f(-(myWidth/2.0f),(myHeight/2.0f),-(myLength/2.0f)); glVertex3f(-(myWidth/2.0f),-(myHeight/2.0f),-(myLength/2.0f)); glVertex3f((myWidth/2.0f),-(myHeight/2.0f),-(myLength/2.0f)); glVertex3f((myWidth/2.0f),(myHeight/2.0f),-(myLength/2.0f)); glColor3f(myColor[0],myColor[1],myColor[2]); // Draw the front of the cube glVertex3f(-(myWidth/2.0f),(myHeight/2.0f),(myLength/2.0f)); glVertex3f(-(myWidth/2.0f),-(myHeight/2.0f),(myLength/2.0f)); glVertex3f((myWidth/2.0f),-(myHeight/2.0f),(myLength/2.0f)); glVertex3f((myWidth/2.0f),(myHeight/2.0f),(myLength/2.0f)); if(myDepth) glColor3f(myColor[0] - 0.2f,myColor[1] - 0.2f,myColor[2] - 0.2f); // Draw the top of the cube glVertex3f(-(myWidth/2.0f),(myHeight/2.0f),(myLength/2.0f)); glVertex3f((myWidth/2.0f),(myHeight/2.0f),(myLength/2.0f)); if(myDepth) glColor3f(myColor[0] - 0.25f,myColor[1] - 0.25f,myColor[2] - 0.25f); glVertex3f((myWidth/2.0f),(myHeight/2.0f),-(myLength/2.0f)); glVertex3f(-(myWidth/2.0f),(myHeight/2.0f),-(myLength/2.0f)); // Draw the bottom of the cube glVertex3f(-(myWidth/2.0f),-(myHeight/2.0f),(myLength/2.0f)); glVertex3f((myWidth/2.0f),-(myHeight/2.0f),(myLength/2.0f)); if(myDepth) glColor3f(myColor[0] - 0.25f,myColor[1] - 0.25f,myColor[2] - 0.25f); glVertex3f((myWidth/2.0f),-(myHeight/2.0f),-(myLength/2.0f)); glVertex3f(-(myWidth/2.0f),-(myHeight/2.0f),-(myLength/2.0f)); glEnd(); }} Feel free to use this class in your own projects. The shading technique is really primitive, but I actually think it looks kind of decent. It took me a long time to figure out how to do the Draw function by using just three variables, but it works great!Here is the apvector.cpp file:[source]// *******************************************************************// Last Revised: 8/14/98// changed abort to exit//// APCS vector class IMPLEMENTATION//// see vector.h for complete documentation of functions//// vector class consistent with a subset of the standard C++ vector class// as defined in the draft ANSI standard (part of standard template library)// *******************************************************************#include <stdlib.h>#include <assert.h>#include <iostream.h>#include "apvector.h"template <class itemType>apvector<itemType>::apvector()//postcondition: vector has a capacity of 0 items, and therefore it will// need to be resized : mySize(0), myList(0){}template <class itemType>apvector<itemType>::apvector(int size)// precondition: size >= 0// postcondition: vector has a capacity of size items : mySize(size), myList(new itemType[size]){}template <class itemType>apvector<itemType>::apvector(int size, const itemType & fillValue)// precondition: size >= 0// postcondition: vector has a capacity of size items, all of which are set// by assignment to fillValue after default construction : mySize(size), myList(new itemType[size]){ int k; for(k = 0; k < size; k++) { myList[k] = fillValue; }}template <class itemType>apvector<itemType>::apvector(const apvector<itemType> & vec)// postcondition: vector is a copy of vec : mySize(vec.length()), myList(new itemType[mySize]){ int k; // copy elements for(k = 0; k < mySize; k++){ myList[k] = vec.myList[k]; }}template <class itemType>apvector<itemType>::~apvector ()// postcondition: vector is destroyed{ delete [] myList;}template <class itemType>const apvector<itemType> &apvector<itemType>::operator = (const apvector<itemType> & rhs)// postcondition: normal assignment via copying has been performed;// if vector and rhs were different sizes, vector// has been resized to match the size of rhs{ if (this != &rhs) // don't assign to self! { delete [] myList; // get rid of old storage mySize = rhs.length(); myList = new itemType [mySize]; // allocate new storage // copy rhs int k; for(k=0; k < mySize; k++) { myList[k] = rhs.myList[k]; } } return *this; // permit a = b = c = d}template <class itemType>int apvector<itemType>::length() const// postcondition: returns vector's size (number of memory cells// allocated for vector){ return mySize;}template <class itemType>itemType & apvector<itemType>::operator [] (int k)// description: range-checked indexing, returning kth item// precondition: 0 <= k < length()// postcondition: returns the kth item{ if (k < 0 || mySize <= k) { cerr << "Illegal vector index: " << k << " max index = "; cerr << (mySize-1) << endl; exit(1); } return myList[k];}template <class itemType>const itemType & apvector<itemType>::operator [] (int k) const// safe indexing, returning const reference to avoid modification// precondition: 0 <= index < length// postcondition: return index-th item// exception: exits if index is out-of-bounds{ if (k < 0 || mySize <= k) { cerr << "Illegal vector index: " << k << " max index = "; cerr << (mySize-1) << endl; exit(1); } return myList[k];}template <class itemType>void apvector<itemType>::resize(int newSize)// description: resizes the vector to newSize elements// precondition: the current capacity of vector is length(); newSize >= 0// postcondition: the current capacity of vector is newSize; for each k// such that 0 <= k <= min(length, newSize), vector[k]// is a copy of the original; other elements of vector are// initialized using the 0-argument itemType constructor// Note: if newSize < length, elements may be lost{ int k; int numToCopy = newSize < mySize ? newSize : mySize; // allocate new storage and copy element into new storage itemType * newList = new itemType[newSize]; for(k=0; k < numToCopy; k++) { newList[k] = myList[k]; } delete [] myList; // de-allocate old storage mySize = newSize; // assign new storage/size myList = newList;}
Ok! Now that there are no questions about exactly what my code is, can anyone figure out my problem?
Edit: Tried to fix some errors, but there seems to be a problem with the 'source' tags. Before you ask about missing header files or the like, make sure you scroll over because cut-and-paste seems to have screwed with things like the carriage returns
Edit #2: Hrmmmm, now the apvector.cpp code has disappeared. Hopefully, it will come back now. If not, I don't think you really need it to analyze my code.
[edited by - Erunama on May 3, 2002 4:42:42 PM]
[edited by - Erunama on May 3, 2002 4:44:51 PM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement