Question

texture map

Asked by: jhshukla

For some reason the texture is not being applied to the polygon. it draws the polygon with the last color set. what is wrong with the code? as it is obivous from the looking at the code, it is using MFC/C++. no glut* solutions please. and ignore potential memory leaks, etc. i take care of it in a different routine.

void COpenGL3View::LoadTexture(const char * path)
{
      struct bmp_header
      {
            char sig[2];
            unsigned int fileSize, res1, dataOffset;
            unsigned int bmpHeaderSize, width, height;
            unsigned short planes, bpp;
            unsigned int compression, dataSize;
            unsigned int hres, vres;
            unsigned int numColors, impColors;
      } header;
      ifstream infile (path);
      infile.read(&header.sig[0], 2);
      infile.read((char*)&header.fileSize, 4*6);
      infile.read((char*)&header.planes, 2*2);
      infile.read((char*)&header.compression, 4*5);
      char str[512] = "";
      sprintf(str, "filesize = %d\ndata = %d\nheadersize = %d\nwidth = %d, height = %d\n"
                         "planes = %d, bpp = %d\ncompression = %d\ndatasize = %d\n"
                         "hres = %d, vres = %d\nnumcolors = %d, impcolors = %x",
                         header.fileSize, header.dataOffset, header.bmpHeaderSize, header.width, header.height,
                         header.planes, header.bpp, header.compression, header.dataSize,
                         header.hres, header.vres, header.numColors, header.impColors);
      //MessageBox(str);
      texture = malloc(header.dataSize);
      if ( texture != NULL )
      {
            infile.seekg(header.dataOffset);
            infile.read((char*)texture, header.dataSize);
            sprintf(str, "file read success\nfirst pixel is (%02x,%02x,%02x)",
                  ((unsigned char*)texture)[0],
                  ((unsigned char*)texture)[1],
                  ((unsigned char*)texture)[2]);
            //MessageBox(str);
      }
      ::glBindTexture(GL_TEXTURE_2D, 1);
      ::glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
      ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);      // not really relevant
      ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);      // -"-
      ::glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);      // -"-
      ::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, header.width, header.height, 0, GL_RGB, GL_UNSIGNED_BYTE, texture);

      ::glEnable(GL_TEXTURE_2D);
}

BOOL COpenGL3View::RenderScene()
{
      ::glBindTexture(GL_TEXTURE_2D, 1);
      ::glEnable(GL_TEXTURE_2D);
      glBegin(GL_POLYGON);
      {
            ::glTexCoord2i(  0,  0); ::glVertex3f(0,  0,  0);
            ::glTexCoord2i(171,  0); ::glVertex3f(0,  0,100);
            ::glTexCoord2i(171,171); ::glVertex3f(0,100,100);
            ::glTexCoord2i(  0,171); ::glVertex3f(0,100,  0);
      }
      glEnd();
      ::glDisable(GL_TEXTURE_2D);

      /* the code below is fine */
      /*
      glEnable(GL_LIGHTING);
      auxSolidSphere( 0.7*50 );
      glDisable(GL_LIGHTING);
      */

      glBegin(GL_LINES); // x y z axes
      {
            ::glColor3f(1,0,0); ::glVertex3f( 0, 0, 0); ::glVertex3f( 200, 0, 0);
            ::glColor3f(0,1,0); ::glVertex3f( 0, 0, 0); ::glVertex3f( 0, 200, 0);
            ::glColor3f(0,0,1); ::glVertex3f( 0, 0, 0); ::glVertex3f( 0, 0, 200);
      }
      glEnd();
      return true;
}

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-07-22 at 15:49:22ID21501560
Tags

texture

Topic

OpenGL Graphics & Game Programming

Participating Experts
2
Points
50
Comments
35

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. OpenGL Texture Mapping
    Hey folks, I need a piece of Delphi4-code that makes use of plain OpenGL-syntax and does the following: A rectangle with a texture on it (loaded from a BMP) turning e.g. around the z-axis with a background image (also loaded from a BMP) behind the scene. The main problem ...
  2. Render a height map on a texture ?
    Does anyone know, or can explain how to perform shading and/or refraction of a height map on a texture or image. Say we have a 20 X 20 array which holds height values ranging from 0 to 10. How can I use this map to apply it to a 20 by 20 image ?
  3. Texture Mapping OpenGl
    Hi, I need to do a texture mapping on a 3D object, cube mapping,sphere mapping and cylinder mapping. My program now,includes the ability to load *.skl format,then *.obj/*.off and then *.wgt(weights file). I have hierarchy window which has a tree of all the skeleton bon...
  4. texture mapping
    hi all, how to texture map a cylinder sphere or any arbitrary object in opengl.i want the entire commands not any LINKS. prabhu
  5. Binding a texture "*.bmp" to glutSolidCube?
    Please somebody help me! Is it possible to use textures on glutSolidCube/glutWireCube and glutSolidSphere/glutWireSphere? Cheers Tony!
  6. Placing a Texture on a Cube
    I am drawing a fireplace. Void DrawFirePlace () { glPushMatrix(); glTranslatef(2.75, -1.0, 1.2); glRotatef(0.0, 1.0, 0.0, 0.0); glScalef(5.0,5.0,15.0); drawCube(); glPopMatrix(); glPushMatrix(); glTranslatef(2.75, -1.5, .65); glRotatef(0...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: _corey_Posted on 2005-07-22 at 23:23:21ID: 14508699

I don't see an immediate problem.  However, I also don't see an place where COpenGL3View::LoadTexture is called.

You need to use GetError to check for errors after binding and loading the texture.

corey

 

by: ikeworkPosted on 2005-07-23 at 03:47:27ID: 14509269

you must create a new texture-name with glGenTextures, which is passed as second parameter in glBindTexture later, you passed "1" as texture-name in glBindTexture. this is from opengl.org about glGenTextures:


     NAME
        glGenTextures      - generate texture names

     C SPECIFICATION
        void glGenTextures( GLsizei n,  GLuint *textures )


     PARAMETERS
        n          Specifies the number of texture names to be
                generated.

        textures  Specifies an array in which      the generated texture
                names are stored.

so insert this into your code:

GLuint tex_name;
/* 1 means we need 1 texture name to be generated */
glGenTextures(1, &tex_name);
::glBindTexture(GL_TEXTURE_2D, tex_name);
/* here go ahead with your code ... */


and later in your code to free the texture-resource:
glDeleteTextures( 1, &tex_name);


here are detailed desriptions for glGenTextures and glDeleteTextures:
http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/gentextures.html
http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/deletetextures.html


good luck,
ike

 

by: ikeworkPosted on 2005-07-23 at 03:56:51ID: 14509285

to be clear: if you use more than one texture, then the above variable "tex_name" must be available, whereever you have to activate that texture, that means whereever you want call glBindTexture (GL_TEXTURE_2D, tex_name). so in your code it should be accessable at least in COpenGL3View::LoadTexture and COpenGL3View::RenderScene. if you only use one texture, then you dont need to "reactivate" that texture in BOOL COpenGL3View::RenderScene(), otherwise you have to do this:

BOOL COpenGL3View::RenderScene()
{
    /* activate that texture, only needed if you activated another texture after loading */
    ::glBindTexture(GL_TEXTURE_2D, tex_name );

    ....
}


 

by: ikeworkPosted on 2005-07-23 at 04:04:54ID: 14509298

>> and ignore potential memory leaks, etc. i take care of it in a different routine.

i guess you dont want to hear ;) but
you better take care of it in that routine. you should always deallocate at that layer/routine where you allocated. so better free texture in COpenGL3View::LoadTexture(const char * path), since it isnt needed anymore, opengl copied all relevant stuff about it. at least you would get a problem from multiple calls of COpenGL3View::LoadTexture, even if this application calls it only once. maybe your next application will do it more often ....

 

by: _corey_Posted on 2005-07-23 at 10:34:05ID: 14510803

If he is just constantly using the same texture name, then it shouldn't fail completely.

I have a feeling that the issue is a failed texture load and that he needs to check the error after binding and loading in the LoadTexture method.

corey

 

by: jhshuklaPosted on 2005-07-25 at 07:50:06ID: 14518208

>> you should always deallocate at that layer/routine where you allocated.
it's a class member and is also used elsewhere. thx anyways for showing diff scenarios. i will change the routine.

>> I have a feeling that the issue is a failed texture load
corey, that turned out to be true.

okay, this is the new code and I narrowed down the error to glTexImage2D().
    GLenum error;
    ::glGenTextures(1, &n_texID);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("1");
    ::glBindTexture(GL_TEXTURE_2D, n_texID);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("2");
    ::glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("3");
    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("4");
    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("5");
    ::glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("6");
    ::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
                   header.width, header.height, 0,
                   GL_RGB, GL_UNSIGNED_BYTE, texture);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("7");           <<===== breaks here
    switch ( error )
    {
        case GL_NO_ERROR:           MessageBox("no error"); break;
        case GL_INVALID_ENUM:       MessageBox("enum"); break;
        case GL_INVALID_VALUE:      MessageBox("value"); break;           <<===== breaks here
        case GL_INVALID_OPERATION:  MessageBox("operation"); break;
        case GL_STACK_OVERFLOW:     MessageBox("overflow"); break;
        case GL_STACK_UNDERFLOW:    MessageBox("underflow"); break;
        case GL_OUT_OF_MEMORY:      MessageBox("out of mem"); break;
        default:                    MessageBox("we are in trouble"); break;
    }

the file I read is a standard 24-bit .bmp created thru M$paint.

 

by: _corey_Posted on 2005-07-25 at 09:19:42ID: 14519100

What are the width and height values?

Also, what is the size of the texture data memory you pass to glTextImage2D?

corey

 

by: jhshuklaPosted on 2005-07-25 at 09:30:34ID: 14519248

342x342 as read from the file header. I confirmed that those are right numbers by checking file properties from paint itself.
    texture = malloc(header.dataSize);
header.dataSize = 351576 but, 342*342*(24/8) = 350892.

what do you suggest I should do? how is malloc(header.dataSize*header.dataSize*ceiling(header.bpp/8))?

 

by: _corey_Posted on 2005-07-25 at 09:43:12ID: 14519384

The problem is the texture dimensions.  Using those formats, you must have a power-of-two square texture.

The notes on this page should help you out: http://developer.3dlabs.com/documents/GLmanpages/glteximage2d.htm

Now, you could simply create a texture that pads the size to a power-of-two dimension or recreate your original texture.

You should look into rectangular textures and non-power-of-two texture extensions for more options.

Corey

 

by: jhshuklaPosted on 2005-07-25 at 11:50:46ID: 14520688

no difference. 256x256 is giving the same results as the initial case.

 

by: _corey_Posted on 2005-07-25 at 12:03:54ID: 14520817

That is strange.

Can you dump the dataSize, dimensions and error result for me with this new texture?

corey

 

by: jhshuklaPosted on 2005-07-25 at 12:24:41ID: 14521036

filesize = 196662
dataOffset = 54
headerSize = 40
width = 256, height = 256
planes = 1, bpp = 24
compression = 0
datasize = 196608
hres = 0, vres = 0          <<< strange from this point onwards
numColors = 0, impColors = 0xcccccccc

OnDraw(CDC *pDC)
{
...
    ::glPushMatrix();
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox("18");
    RenderScene();
    ::glPopMatrix();
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox("19"); <<< error here. error = GL_INVALID_OPERATION
...
}

 

by: _corey_Posted on 2005-07-25 at 12:28:05ID: 14521072

Does an error occur inside of the RenderScene call or during the texture load now?

That BMP header looks ok.

corey

 

by: jhshuklaPosted on 2005-07-25 at 13:20:26ID: 14521500

actually it is inside RenderScene()

BOOL COpenGL3View::RenderScene()
{
    GLenum error;
    ::glEnable(GL_TEXTURE_2D);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("x");
    glBegin(GL_POLYGON);
    {
        ::glTexCoord2f(0, 0);
        error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("9");
        ::glVertex3f(0,  0,  0);
        error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("10");
        ::glTexCoord2f(1, 0);
        error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("11");
        ::glVertex3f(0,  0,100);
        error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("12");
        ::glTexCoord2f(1, 1);
        error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("13");
        ::glVertex3f(0,100,100);
        error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("14");
        ::glTexCoord2f( 0, 1);
        error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("15");
        ::glVertex3f(0,100,  0);
        error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("16");
    }
    glEnd();
    ::glDisable(GL_TEXTURE_2D);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("16a"); <<< here it gives the error, INVALID_OPERATION

    glEnable(GL_LIGHTING);
    auxSolidSphere( 0.7*50 );
    glDisable(GL_LIGHTING);

    glBegin(GL_LINES);
    {
        ::glColor3f(1,0,0); ::glVertex3f( 0, 0, 0); ::glVertex3f( 200, 0, 0);
        ::glColor3f(0,1,0); ::glVertex3f( 0, 0, 0); ::glVertex3f( 0, 200, 0);
        ::glColor3f(0,0,1); ::glVertex3f( 0, 0, 0); ::glVertex3f( 0, 0, 200);
    }
    glEnd();
    return true;
}

 

by: jhshuklaPosted on 2005-07-25 at 13:24:17ID: 14521534

the thing that I don't understand is that why is it not giving me error codes when it is not succeeding?

 

by: jhshuklaPosted on 2005-07-25 at 13:26:43ID: 14521546

ignore the previous code snippet; it is giving INVALID_OPERATION error on glEnd(). damn!

 

by: _corey_Posted on 2005-07-25 at 13:31:02ID: 14521581

You're going to hate this, but thie issue there is the glGetError call between glBegin and glEnd.  The call is ignored but the error flag is set.

Remove those and see if you have any other errors.

Also, .BMP files usually have the BGR byte format.  If things look odd, then you should try loading the image with the GL_BGR_EXT format.  You can leave internal format as RGB.

corey

 

by: jhshuklaPosted on 2005-07-25 at 14:10:37ID: 14521924

no error but we are back to the beginning.

>> Also, .BMP files usually have the BGR byte format.
I figured that but din't know how to fix it. thx.

 

by: jhshuklaPosted on 2005-07-25 at 14:12:23ID: 14521938

>> You're going to hate this, but thie issue there is the glGetError call between glBegin and glEnd.  The call is ignored but the error flag is set.
yeah i definitely hate this. if the error flag is set it should give me error on the second call to getError().

 

by: _corey_Posted on 2005-07-25 at 14:25:18ID: 14522026

No no, the glGetError call is ignored between the glBegin and glEnd so everything doesn't go nuts but the error flag is still set from doing this.

I don't know why you are not seeing any textures.

What happens if you only render the polygon and don't execute the other code below that?

corey

 

by: jhshuklaPosted on 2005-07-25 at 15:16:49ID: 14522417

same as before. do you mind looking at the full code?

 

by: _corey_Posted on 2005-07-25 at 16:25:33ID: 14522713

I don't mind.

corey

 

by: jhshuklaPosted on 2005-07-26 at 07:29:34ID: 14527456

// MainFrm.h : interface of the CMainFrame class
//


#pragma once
class CMainFrame : public CMDIFrameWnd
{
    DECLARE_DYNAMIC(CMainFrame)
public:
    CMainFrame();

// Attributes
public:

// Operations
public:

// Overrides
public:
    virtual BOOL PreCreateWindow(CREATESTRUCT& cs);

// Implementation
public:
    virtual ~CMainFrame();
#ifdef _DEBUG
    virtual void AssertValid() const;
    virtual void Dump(CDumpContext& dc) const;
#endif

protected:  // control bar embedded members
    CToolBar    m_wndToolBar;

// Generated message map functions
protected:
    afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
    DECLARE_MESSAGE_MAP()
};

========================================================

// MainFrm.cpp : implementation of the CMainFrame class
//

#include "stdafx.h"
#include "OpenGL3.h"

#include "MainFrm.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CMainFrame

IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd)
    ON_WM_CREATE()
END_MESSAGE_MAP()


// CMainFrame construction/destruction

CMainFrame::CMainFrame()
{
    // TODO: add member initialization code here
}

CMainFrame::~CMainFrame()
{
}


int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
    if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1)
        return -1;
   
    if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
        | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
        !m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
    {
        TRACE0("Failed to create toolbar\n");
        return -1;      // fail to create
    }
    // TODO: Delete these three lines if you don't want the toolbar to be dockable
    m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
    EnableDocking(CBRS_ALIGN_ANY);
    DockControlBar(&m_wndToolBar);

    return 0;
}

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
    if( !CMDIFrameWnd::PreCreateWindow(cs) )
        return FALSE;
    // TODO: Modify the Window class or styles here by modifying
    //  the CREATESTRUCT cs

    return TRUE;
}


// CMainFrame diagnostics

#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
    CMDIFrameWnd::AssertValid();
}

void CMainFrame::Dump(CDumpContext& dc) const
{
    CMDIFrameWnd::Dump(dc);
}

#endif //_DEBUG


// CMainFrame message handlers

========================================================
above two files are auto generated
========================================================

 

by: jhshuklaPosted on 2005-07-26 at 07:30:37ID: 14527466

// ChildFrm.h : interface of the CChildFrame class
//


#pragma once


class CChildFrame : public CMDIChildWnd
{
    DECLARE_DYNCREATE(CChildFrame)
public:
    CChildFrame();

// Attributes
public:

// Operations
public:

// Overrides
    virtual BOOL PreCreateWindow(CREATESTRUCT& cs);

// Implementation
public:
    virtual ~CChildFrame();
#ifdef _DEBUG
    virtual void AssertValid() const;
    virtual void Dump(CDumpContext& dc) const;
#endif

// Generated message map functions
protected:
    DECLARE_MESSAGE_MAP()
};

======================================================

// ChildFrm.cpp : implementation of the CChildFrame class
//
#include "stdafx.h"
#include "OpenGL3.h"

#include "ChildFrm.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CChildFrame

IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWnd)

BEGIN_MESSAGE_MAP(CChildFrame, CMDIChildWnd)
END_MESSAGE_MAP()


// CChildFrame construction/destruction

CChildFrame::CChildFrame()
{
    // TODO: add member initialization code here
}

CChildFrame::~CChildFrame()
{
}


BOOL CChildFrame::PreCreateWindow(CREATESTRUCT& cs)
{
    // TODO: Modify the Window class or styles here by modifying the CREATESTRUCT cs
    if( !CMDIChildWnd::PreCreateWindow(cs) )
        return FALSE;

    return TRUE;
}


// CChildFrame diagnostics

#ifdef _DEBUG
void CChildFrame::AssertValid() const
{
    CMDIChildWnd::AssertValid();
}

void CChildFrame::Dump(CDumpContext& dc) const
{
    CMDIChildWnd::Dump(dc);
}

#endif //_DEBUG


// CChildFrame message handlers

======================================================
auto generated
======================================================

 

by: jhshuklaPosted on 2005-07-26 at 07:31:39ID: 14527479

// OpenGL3.h : main header file for the OpenGL3 application
//
#pragma once

#ifndef __AFXWIN_H__
    #error include 'stdafx.h' before including this file for PCH
#endif

#include "resource.h"       // main symbols


// COpenGL3App:
// See OpenGL3.cpp for the implementation of this class
//

class COpenGL3App : public CWinApp
{
public:
    COpenGL3App();


// Overrides
public:
    virtual BOOL InitInstance();

// Implementation
    afx_msg void OnAppAbout();
    DECLARE_MESSAGE_MAP()
};

extern COpenGL3App theApp;

======================================================

// OpenGL3.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "OpenGL3.h"
#include "MainFrm.h"

#include "ChildFrm.h"
#include "OpenGL3Doc.h"
#include "OpenGL3View.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// COpenGL3App

BEGIN_MESSAGE_MAP(COpenGL3App, CWinApp)
    ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
    // Standard file based document commands
    ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
    ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
END_MESSAGE_MAP()


// COpenGL3App construction

COpenGL3App::COpenGL3App()
{
    // TODO: add construction code here,
    // Place all significant initialization in InitInstance
}


// The one and only COpenGL3App object

COpenGL3App theApp;

// COpenGL3App initialization

BOOL COpenGL3App::InitInstance()
{
    CWinApp::InitInstance();

    // Standard initialization
    // If you are not using these features and wish to reduce the size
    // of your final executable, you should remove from the following
    // the specific initialization routines you do not need
    // Change the registry key under which our settings are stored
    // TODO: You should modify this string to be something appropriate
    // such as the name of your company or organization
    SetRegistryKey(_T("Local AppWizard-Generated Applications"));
    LoadStdProfileSettings(0);  // Load standard INI file options (including MRU)
    // Register the application's document templates.  Document templates
    //  serve as the connection between documents, frame windows and views
    CMultiDocTemplate* pDocTemplate;
    pDocTemplate = new CMultiDocTemplate(IDR_OpenGL3TYPE,
        RUNTIME_CLASS(COpenGL3Doc),
        RUNTIME_CLASS(CChildFrame), // custom MDI child frame
        RUNTIME_CLASS(COpenGL3View));
    if (!pDocTemplate)
        return FALSE;
    AddDocTemplate(pDocTemplate);
    // create main MDI Frame window
    CMainFrame* pMainFrame = new CMainFrame;
    if (!pMainFrame || !pMainFrame->LoadFrame(IDR_MAINFRAME))
        return FALSE;
    m_pMainWnd = pMainFrame;
    // call DragAcceptFiles only if there's a suffix
    //  In an MDI app, this should occur immediately after setting m_pMainWnd
    // Parse command line for standard shell commands, DDE, file open
    CCommandLineInfo cmdInfo;
    ParseCommandLine(cmdInfo);
    // Dispatch commands specified on the command line.  Will return FALSE if
    // app was launched with /RegServer, /Register, /Unregserver or /Unregister.
    if (!ProcessShellCommand(cmdInfo))
        return FALSE;
    // The main window has been initialized, so show and update it
    pMainFrame->ShowWindow(m_nCmdShow);
    pMainFrame->UpdateWindow();
    return TRUE;
}



// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
    CAboutDlg();

// Dialog Data
    enum { IDD = IDD_ABOUTBOX };

protected:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
    DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()

// App command to run the dialog
void COpenGL3App::OnAppAbout()
{
    CAboutDlg aboutDlg;
    aboutDlg.DoModal();
}


// COpenGL3App message handlers

======================================================
auto generated
======================================================

 

by: jhshuklaPosted on 2005-07-26 at 07:33:07ID: 14527490

// OpenGL3Doc.h : interface of the COpenGL3Doc class
//


#pragma once

class COpenGL3Doc : public CDocument
{
protected: // create from serialization only
    COpenGL3Doc();
    DECLARE_DYNCREATE(COpenGL3Doc)

// Attributes
public:

// Operations
public:

// Overrides
    public:
    virtual BOOL OnNewDocument();
    virtual void Serialize(CArchive& ar);

// Implementation
public:
    virtual ~COpenGL3Doc();
#ifdef _DEBUG
    virtual void AssertValid() const;
    virtual void Dump(CDumpContext& dc) const;
#endif

protected:

// Generated message map functions
protected:
    DECLARE_MESSAGE_MAP()
};


========================================================

// OpenGL3Doc.cpp : implementation of the COpenGL3Doc class
//

#include "stdafx.h"
#include "OpenGL3.h"

#include "OpenGL3Doc.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// COpenGL3Doc

IMPLEMENT_DYNCREATE(COpenGL3Doc, CDocument)

BEGIN_MESSAGE_MAP(COpenGL3Doc, CDocument)
END_MESSAGE_MAP()


// COpenGL3Doc construction/destruction

COpenGL3Doc::COpenGL3Doc()
{
    // TODO: add one-time construction code here

}

COpenGL3Doc::~COpenGL3Doc()
{
}

BOOL COpenGL3Doc::OnNewDocument()
{
    if (!CDocument::OnNewDocument())
        return FALSE;

    // TODO: add reinitialization code here
    // (SDI documents will reuse this document)

    return TRUE;
}




// COpenGL3Doc serialization

void COpenGL3Doc::Serialize(CArchive& ar)
{
    if (ar.IsStoring())
    {
        // TODO: add storing code here
    }
    else
    {
        // TODO: add loading code here
    }
}


// COpenGL3Doc diagnostics

#ifdef _DEBUG
void COpenGL3Doc::AssertValid() const
{
    CDocument::AssertValid();
}

void COpenGL3Doc::Dump(CDumpContext& dc) const
{
    CDocument::Dump(dc);
}
#endif //_DEBUG


// COpenGL3Doc commands

========================================================
auto generated
========================================================

 

by: _corey_Posted on 2005-07-26 at 07:34:26ID: 14527507

I will be reading through this.

corey

 

by: jhshuklaPosted on 2005-07-26 at 07:35:28ID: 14527517

// OpenGL3View.h : interface of the COpenGL3View class
//


#pragma once

#include <gl\gl.h>
#include <gl\glu.h>
#include <gl\glaux.h>

class COpenGL3View : public CView
{
private:
    void * texture;
protected: // create from serialization only
    COpenGL3View();
    DECLARE_DYNCREATE(COpenGL3View)

// Attributes
public:
    COpenGL3Doc* GetDocument() const;

// Operations
public:

// Overrides
    public:
    virtual void OnDraw(CDC* pDC);  // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:

// Implementation
public:
    virtual ~COpenGL3View();
#ifdef _DEBUG
    virtual void AssertValid() const;
    virtual void Dump(CDumpContext& dc) const;
#endif

protected:

// Generated message map functions
protected:
    DECLARE_MESSAGE_MAP()
public:
    afx_msg void OnDestroy();
    afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
    afx_msg BOOL OnEraseBkgnd(CDC* pDC);
    afx_msg void OnSize(UINT nType, int cx, int cy);
    afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
    afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt);
    virtual void OnInitialUpdate();
public:
    virtual BOOL SetupPixelFormat( void );
    virtual BOOL SetupViewPort( int cx, int cy );
    virtual BOOL SetupViewingFrustum( GLdouble );
    virtual BOOL SetupViewingTransform( void );
    virtual BOOL RenderScene( void );
    virtual __inline BOOL PreRenderScene( void ){return true;}

// private utility functions
private:
    void LoadTexture(const char *);
    void SetError( int e );
    BOOL init( void );

    HGLRC m_hRC;
    CDC *m_pDC;

    static const char * const _ErrorStrings[];
    const char *m_ErrorString;
    GLuint n_texID;

protected:
    struct vector3d { float x, y, z; } eye, line_of_sight, up;
    struct spherical { int r; float phi, theta; } view_vector;
    float view_angle, step_size;

    inline vector3d cross(vector3d a, vector3d b)
    {
        vector3d result;
        result.x = a.y*b.z-a.z*b.y;
        result.y = a.z*b.x-a.x*b.z;
        result.z = a.x*b.y-a.y*b.x;
        return result;
    }
};

#ifndef _DEBUG  // debug version in OpenGL3View.cpp
inline COpenGL3Doc* COpenGL3View::GetDocument() const
   { return reinterpret_cast<COpenGL3Doc*>(m_pDocument); }
#endif

==============================================================

// OpenGL3View.cpp : implementation of the COpenGL3View class
//

#include "stdafx.h"
#include "OpenGL3.h"

#include "OpenGL3Doc.h"
#include "OpenGL3View.h"
#include ".\opengl3view.h"

#include <fstream>
using namespace std;

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define PI 3.14159f

// COpenGL3View

IMPLEMENT_DYNCREATE(COpenGL3View, CView)

BEGIN_MESSAGE_MAP(COpenGL3View, CView)
    ON_WM_DESTROY()
    ON_WM_CREATE()
    ON_WM_ERASEBKGND()
    ON_WM_SIZE()
    ON_WM_KEYDOWN()
    ON_WM_MOUSEWHEEL()
END_MESSAGE_MAP()

const char * const COpenGL3View::_ErrorStrings[] =
{
    {"No error"},
    {"no DC"},
    {"choose pix failed"},
    {"select pix failed"},
    {"wgl create failed"},
    {"wgl current failed"},
    {"wgl delete failed"},
    {"swap failed"}
};

// COpenGL3View construction/destruction

COpenGL3View::COpenGL3View()
:texture(NULL)
{
    // TODO: add construction code here
    eye.x = 450;
    eye.y = 10;
    eye.z = 10;

    line_of_sight.x = -1;
    line_of_sight.y = 0;
    line_of_sight.z = 0;

    up.x = 0;
    up.y = 0;
    up.z = 1;

    view_vector.r = 1;
    view_vector.phi = 0.0f;
    view_vector.theta = PI;
}

COpenGL3View::~COpenGL3View()
{
    if (texture != NULL)
    {
        free(texture);
        texture = NULL;
    }
}

BOOL COpenGL3View::PreCreateWindow(CREATESTRUCT& cs)
{
    // TODO: Modify the Window class or styles here by modifying
    //  the CREATESTRUCT cs

    cs.style |= WS_CLIPSIBLINGS | WS_CLIPCHILDREN;

    return CView::PreCreateWindow(cs);
}

void COpenGL3View::SetError( int e )
{
    if ( _ErrorStrings[0] == m_ErrorString )
        m_ErrorString = _ErrorStrings[e];
}

// COpenGL3View drawing

void COpenGL3View::OnDraw(CDC* /*pDC*/)
{
    GLenum error;
    COpenGL3Doc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);

    // TODO: add draw code for native data here
    ::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox("17");

    ::glPushMatrix();
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox("18");
    RenderScene();
    ::glPopMatrix();
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox("19");
    switch ( error )
    {
        case GL_NO_ERROR:           MessageBox("no error");         break;
        case GL_INVALID_ENUM:       MessageBox("enum");             break;
        case GL_INVALID_VALUE:      MessageBox("value");            break;
        case GL_INVALID_OPERATION:  MessageBox("operation");        break;
        case GL_STACK_OVERFLOW:     MessageBox("overflow");         break;
        case GL_STACK_UNDERFLOW:    MessageBox("underflow");        break;
        case GL_OUT_OF_MEMORY:      MessageBox("out of mem");       break;
        default:                    MessageBox("we are in trouble");break;
    }

    ::glFinish();
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox("20");

    if ( false == ::SwapBuffers( m_pDC->GetSafeHdc() ) )
    {
        SetError(7);
    }
}


// COpenGL3View diagnostics

#ifdef _DEBUG
void COpenGL3View::AssertValid() const
{
    CView::AssertValid();
}

void COpenGL3View::Dump(CDumpContext& dc) const
{
    CView::Dump(dc);
}

COpenGL3Doc* COpenGL3View::GetDocument() const // non-debug version is inline
{
    ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(COpenGL3Doc)));
    return (COpenGL3Doc*)m_pDocument;
}
#endif //_DEBUG


// COpenGL3View message handlers

void COpenGL3View::OnDestroy()
{
    CView::OnDestroy();

    // TODO: Add your message handler code here
   
    if ( false == ::wglMakeCurrent( 0, 0 ) )
        SetError(2);
   
    if ( false == ::wglDeleteContext( m_hRC ) )
        SetError(6);

    if ( m_pDC )
        delete m_pDC;
   
}

int COpenGL3View::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
    if (CView::OnCreate(lpCreateStruct) == -1)
        return -1;

    // TODO:  Add your specialized creation code here

    init();
    return 0;
}

BOOL COpenGL3View::OnEraseBkgnd(CDC* pDC)
{
    // TODO: Add your message handler code here and/or call default

    //return CView::OnEraseBkgnd(pDC);
    return true;
}

void COpenGL3View::OnSize(UINT nType, int cx, int cy)
{
    CView::OnSize(nType, cx, cy);

    // TODO: Add your message handler code here
    GLdouble aspect_ratio;

    if ( cx <= 0 || cy <= 0 )
        return;

    SetupViewPort( cx, cy );

    aspect_ratio = (GLdouble)cx/(GLdouble)cy;
    ::glMatrixMode(GL_PROJECTION);
    ::glLoadIdentity();

    SetupViewingFrustum( aspect_ratio );
    ::glMatrixMode(GL_MODELVIEW);
    ::glLoadIdentity();

    SetupViewingTransform();
}

void COpenGL3View::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    // TODO: Add your message handler code here and/or call default

    CView::OnKeyDown(nChar, nRepCnt, nFlags);
}

BOOL COpenGL3View::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
{
    // TODO: Add your message handler code here and/or call default

    return CView::OnMouseWheel(nFlags, zDelta, pt);
}

void COpenGL3View::OnInitialUpdate()
{
    CView::OnInitialUpdate();

    // TODO: Add your specialized code here and/or call the base class
    LoadTexture("texture.bmp");
}

BOOL COpenGL3View::SetupPixelFormat( void )
{
    PIXELFORMATDESCRIPTOR pfd =
        {
            sizeof (PIXELFORMATDESCRIPTOR),    // size of this PFD
            1,                                // version number
            PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_TYPE_RGBA,
            24,                                // bpp
            0, 0, 0, 0, 0, 0,                // color bits ignored (?)
            0,                                // no alpha buffer
            0,                                // shift bit ignored (?)
            0,                                // no accumulation buffer
            0, 0, 0, 0,                        // accumulation bits ignored (?)
            16,                                // 16bit z-buffer
            0,                                // no stencil buffer
            0,                                // no auxiliary buffer (?)
            PFD_MAIN_PLANE,                    // main layer (?)
            0,                                // reserved
            0, 0, 0                            // layer masks ignored (?)
        };
    int pixelformat;
    if ( 0 == ( pixelformat = ::ChoosePixelFormat ( m_pDC->GetSafeHdc(), &pfd ) ) )
    {
        SetError(2);
        return false;
    }

    if ( false == ::SetPixelFormat ( m_pDC->GetSafeHdc(), pixelformat, &pfd ) )
    {
        SetError(3);
        return false;
    }

    return true;
}

BOOL COpenGL3View::SetupViewPort( int cx, int cy )
{
    glViewport(0, 0, cx, cy);
    return true;
}

BOOL COpenGL3View::SetupViewingFrustum( GLdouble aspect_ratio )
{
    gluPerspective(40.0f, aspect_ratio, .1f, 2000.0f);
    return true;
}

BOOL COpenGL3View::SetupViewingTransform( void )
{
    ::gluLookAt(eye.x,                 eye.y,                 eye.z,
                eye.x+line_of_sight.x, eye.y+line_of_sight.y, eye.z+line_of_sight.z,
                up.x,                  up.y,                  up.z);
    char str[256];
    sprintf(str, "looking at (%.0f,%.0f,%.0f) from (%.0f,%.0f,%.0f)\nup = (%.0f,%.0f,%.0f)",
            eye.x+line_of_sight.x, eye.y+line_of_sight.y, eye.z+line_of_sight.z,
            eye.x, eye.y, eye.z, up.x, up.y, up.z);
    //MessageBox(str);
    return true;
}

BOOL COpenGL3View::RenderScene()
{
    GLenum error;
    ::glEnable(GL_TEXTURE_2D);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("x");
    glBegin(GL_POLYGON);
    {
        ::glTexCoord2f(0, 0);    //error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("9");
        ::glVertex3f(0,  0,  0); //error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("10");

        ::glTexCoord2f(1, 0);    //error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("11");
        ::glVertex3f(0,  0,100); //error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("12");

        ::glTexCoord2f(1, 1);    //error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("13");
        ::glVertex3f(0,100,100); //error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("14");

        ::glTexCoord2f( 0, 1);   //error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("15");
        ::glVertex3f(0,100,  0); //error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("16");
    }
    glEnd();
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("16a");
    /*
    switch ( error )
    {
        case GL_NO_ERROR:           MessageBox("no error");         break;
        case GL_INVALID_ENUM:       MessageBox("enum");             break;
        case GL_INVALID_VALUE:      MessageBox("value");            break;
        case GL_INVALID_OPERATION:  MessageBox("operation");        break;
        case GL_STACK_OVERFLOW:     MessageBox("overflow");         break;
        case GL_STACK_UNDERFLOW:    MessageBox("underflow");        break;
        case GL_OUT_OF_MEMORY:      MessageBox("out of mem");       break;
        default:                    MessageBox("we are in trouble");break;
    }
    */
    ::glDisable(GL_TEXTURE_2D);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("16b");
    /*
    switch ( error )
    {
        case GL_NO_ERROR:           MessageBox("no error");         break;
        case GL_INVALID_ENUM:       MessageBox("enum");             break;
        case GL_INVALID_VALUE:      MessageBox("value");            break;
        case GL_INVALID_OPERATION:  MessageBox("operation");        break;
        case GL_STACK_OVERFLOW:     MessageBox("overflow");         break;
        case GL_STACK_UNDERFLOW:    MessageBox("underflow");        break;
        case GL_OUT_OF_MEMORY:      MessageBox("out of mem");       break;
        default:                    MessageBox("we are in trouble");break;
    }
    */
    /*
    glEnable(GL_LIGHTING);
    auxSolidSphere( 0.7*50 );
    glDisable(GL_LIGHTING);

    glBegin(GL_LINES);
    {
        ::glColor3f(1,0,0); ::glVertex3f( 0, 0, 0); ::glVertex3f( 200, 0, 0);
        ::glColor3f(0,1,0); ::glVertex3f( 0, 0, 0); ::glVertex3f( 0, 200, 0);
        ::glColor3f(0,0,1); ::glVertex3f( 0, 0, 0); ::glVertex3f( 0, 0, 200);
    }
    glEnd();
    */
    return true;
}
void COpenGL3View::LoadTexture(const char * path)
{
    struct bmp_header
    {
        char sig[2];
        unsigned int fileSize, res1, dataOffset;
        unsigned int bmpHeaderSize, width, height;
        unsigned short planes, bpp;
        unsigned int compression, dataSize;
        unsigned int hres, vres;
        unsigned int numColors, impColors;
    } header;
    ifstream infile (path);
    infile.read(&header.sig[0], 2);
    infile.read((char*)&header.fileSize, 4*6);
    infile.read((char*)&header.planes, 2*2);
    infile.read((char*)&header.compression, 4*5);
    char str[512] = "";
    sprintf(str, "filesize = %d\ndata = %d\nheadersize = %d\nwidth = %d, height = %d\n"
                 "planes = %d, bpp = %d\ncompression = %d\ndatasize = %d\n"
                 "hres = %d, vres = %d\nnumcolors = %d, impcolors = %x",
                 header.fileSize, header.dataOffset, header.bmpHeaderSize, header.width, header.height,
                 header.planes, header.bpp, header.compression, header.dataSize,
                 header.hres, header.vres, header.numColors, header.impColors);
    MessageBox(str);
    texture = malloc(header.dataSize);
    if ( texture != NULL )
    {
        infile.seekg(header.dataOffset);
        infile.read((char*)texture, header.dataSize);
        sprintf(str, "file read success\nfirst pixel is (%02x,%02x,%02x)",
            ((unsigned char*)texture)[0],
            ((unsigned char*)texture)[1],
            ((unsigned char*)texture)[2]);
        MessageBox(str);
        /*
        free(texture);
        texture = NULL;
        */
    }
    {
    GLenum error;
    ::glGenTextures(1, &n_texID);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("1");
    ::glBindTexture(GL_TEXTURE_2D, n_texID);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("2");
    ::glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("3");
    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("4");
    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("5");
    ::glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("6");
    ::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
                   header.width, header.height, 0,
                   GL_RGB, GL_UNSIGNED_BYTE, texture);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("7");
    switch ( error )
    {
        case GL_NO_ERROR:           MessageBox("no error");         break;
        case GL_INVALID_ENUM:       MessageBox("enum");             break;
        case GL_INVALID_VALUE:      MessageBox("value");            break;
        case GL_INVALID_OPERATION:  MessageBox("operation");        break;
        case GL_STACK_OVERFLOW:     MessageBox("overflow");         break;
        case GL_STACK_UNDERFLOW:    MessageBox("underflow");        break;
        case GL_OUT_OF_MEMORY:      MessageBox("out of mem");       break;
        default:                    MessageBox("we are in trouble");break;
    }
    ::glEnable(GL_TEXTURE_2D);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("8");
    }
}
BOOL COpenGL3View::init( void )
{
    m_pDC = new CClientDC(this);
   
    if ( NULL == m_pDC )
    {
        SetError(1);
        return false;
    }

    if ( !SetupPixelFormat() )
    {
        return false;
    }

    if ( 0 == ( m_hRC = ::wglCreateContext( m_pDC->GetSafeHdc() ) ) )
    {
        SetError(4);
        return false;
    }

    if ( false == ::wglMakeCurrent( m_pDC->GetSafeHdc(), m_hRC ) )
    {
        SetError(5);
        return false;
    }

    ::glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    ::glClearDepth(1.0f);
    ::glEnable( GL_DEPTH_TEST | GL_LIGHTING );
    GLfloat mat_ambient[] = { 0.5f, 0.0f, 0.0f, 0.0f };
    GLfloat mat_specular[] = { 0.3f, 0.3f, 0.5f, 1.0f };
    GLfloat mat_diffuse[] = { 0.7f, 0.6f, 0.6f, 2.0f };
    GLfloat light_position[] = { 2.0f, 2.5f, 1.0f, 0.01f };
    GLfloat lm_ambient[] = { 0.2f, 0.2f, 0.2f, 1.0f };

    ::glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
    ::glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
    ::glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
    ::glMaterialf(GL_FRONT, GL_SHININESS, 50.0);
    ::glLightfv(GL_LIGHT0, GL_POSITION, light_position);
    ::glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lm_ambient);

    ::glEnable(GL_LIGHT0);
    ::glShadeModel (GL_SMOOTH); // SMOOTH uses Gouraud model. No Phong
    /*
    Gouraud model will pose problems if the point light source is very close to the
    surface being illuminated. in out case, the light source will be mostly the
    ambient light and the sun. We do have to take care, however, while lighting the
    interior as Gouraud model will first calculate the values on edges and then
    interpolate them. This can produce very undesirable results.
    */

    return true;
}

==========================================================
above two files are edited + junk comments
==========================================================

 

by: jhshuklaPosted on 2005-07-27 at 15:40:56ID: 14541703

any luck yet?

 

by: _corey_Posted on 2005-07-27 at 19:58:07ID: 14542822

Well, sorry I had to do some other work before deadline.

However, most of that code seems harmless.  Some notes that I noticed:

1) Reposition the glEnable(GL_TEXTURE_2D) before the bind and load in texture load.
2) The texure load call is in an akward location.  I'd probably have it part of the rest of your init.
3) You don't need to enable GL_TEXTURE_2D again in the render.

corey

 

by: jhshuklaPosted on 2005-07-28 at 10:04:30ID: 14547697

   error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("a");
    ::glEnable( GL_DEPTH_TEST | GL_LIGHTING | GL_TEXTURE_2D);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("b"); <<< gives error if TEXTURE is enabled with either or both of other two flags

anyways I tried using DECAL instead of modulate, disabled lighting, depth. still no diff. here is updated+cleaned *View.cpp:

// OpenGL3View.cpp : implementation of the COpenGL3View class
//

#include "stdafx.h"
#include "OpenGL3.h"

#include "OpenGL3Doc.h"
#include "OpenGL3View.h"
#include ".\opengl3view.h"

#include <fstream>
using namespace std;

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define PI 3.14159f

// COpenGL3View

IMPLEMENT_DYNCREATE(COpenGL3View, CView)

BEGIN_MESSAGE_MAP(COpenGL3View, CView)
    ON_WM_DESTROY()
    ON_WM_CREATE()
    ON_WM_ERASEBKGND()
    ON_WM_SIZE()
    ON_WM_KEYDOWN()
    ON_WM_MOUSEWHEEL()
END_MESSAGE_MAP()

const char * const COpenGL3View::_ErrorStrings[] =
{
    {"No error"},
    {"no DC"},
    {"choose pix failed"},
    {"select pix failed"},
    {"wgl create failed"},
    {"wgl current failed"},
    {"wgl delete failed"},
    {"swap failed"}
};

// COpenGL3View construction/destruction

COpenGL3View::COpenGL3View()
:texture(NULL)
{
    // TODO: add construction code here
    eye.x = 450;
    eye.y = 10;
    eye.z = 10;

    line_of_sight.x = -1;
    line_of_sight.y = 0;
    line_of_sight.z = 0;

    up.x = 0;
    up.y = 0;
    up.z = 1;

    view_vector.r = 1;
    view_vector.phi = 0.0f;
    view_vector.theta = PI;
}

COpenGL3View::~COpenGL3View()
{
    if (texture != NULL)
    {
        free(texture);
        texture = NULL;
    }
}

BOOL COpenGL3View::PreCreateWindow(CREATESTRUCT& cs)
{
    // TODO: Modify the Window class or styles here by modifying
    //  the CREATESTRUCT cs

    cs.style |= WS_CLIPSIBLINGS | WS_CLIPCHILDREN;

    return CView::PreCreateWindow(cs);
}

void COpenGL3View::SetError( int e )
{
    if ( _ErrorStrings[0] == m_ErrorString )
        m_ErrorString = _ErrorStrings[e];
}

// COpenGL3View drawing

void COpenGL3View::OnDraw(CDC* /*pDC*/)
{
    GLenum error;
    COpenGL3Doc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);

    // TODO: add draw code for native data here
    ::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox("17");

    ::glPushMatrix();
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox("18");
    RenderScene();
    ::glPopMatrix();
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox("19");
    switch ( error )
    {
        case GL_NO_ERROR:           MessageBox("no error");         break;
        case GL_INVALID_ENUM:       MessageBox("enum");             break;
        case GL_INVALID_VALUE:      MessageBox("value");            break;
        case GL_INVALID_OPERATION:  MessageBox("operation");        break;
        case GL_STACK_OVERFLOW:     MessageBox("overflow");         break;
        case GL_STACK_UNDERFLOW:    MessageBox("underflow");        break;
        case GL_OUT_OF_MEMORY:      MessageBox("out of mem");       break;
        default:                    MessageBox("we are in trouble");break;
    }

    ::glFinish();
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox("20");

    if ( false == ::SwapBuffers( m_pDC->GetSafeHdc() ) )
    {
        SetError(7);
    }
}


// COpenGL3View diagnostics

#ifdef _DEBUG
void COpenGL3View::AssertValid() const
{
    CView::AssertValid();
}

void COpenGL3View::Dump(CDumpContext& dc) const
{
    CView::Dump(dc);
}

COpenGL3Doc* COpenGL3View::GetDocument() const // non-debug version is inline
{
    ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(COpenGL3Doc)));
    return (COpenGL3Doc*)m_pDocument;
}
#endif //_DEBUG


// COpenGL3View message handlers

void COpenGL3View::OnDestroy()
{
    CView::OnDestroy();

    // TODO: Add your message handler code here
   
    if ( false == ::wglMakeCurrent( 0, 0 ) )
        SetError(2);
   
    if ( false == ::wglDeleteContext( m_hRC ) )
        SetError(6);

    if ( m_pDC )
        delete m_pDC;
   
}

int COpenGL3View::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
    if (CView::OnCreate(lpCreateStruct) == -1)
        return -1;

    // TODO:  Add your specialized creation code here

    init();
    return 0;
}

BOOL COpenGL3View::OnEraseBkgnd(CDC* pDC)
{
    // TODO: Add your message handler code here and/or call default

    //return CView::OnEraseBkgnd(pDC);
    return true;
}

void COpenGL3View::OnSize(UINT nType, int cx, int cy)
{
    CView::OnSize(nType, cx, cy);

    // TODO: Add your message handler code here
    GLdouble aspect_ratio;

    if ( cx <= 0 || cy <= 0 )
        return;

    SetupViewPort( cx, cy );

    aspect_ratio = (GLdouble)cx/(GLdouble)cy;
    ::glMatrixMode(GL_PROJECTION);
    ::glLoadIdentity();

    SetupViewingFrustum( aspect_ratio );
    ::glMatrixMode(GL_MODELVIEW);
    ::glLoadIdentity();

    SetupViewingTransform();
}

void COpenGL3View::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    // TODO: Add your message handler code here and/or call default

    CView::OnKeyDown(nChar, nRepCnt, nFlags);
}

BOOL COpenGL3View::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
{
    // TODO: Add your message handler code here and/or call default

    return CView::OnMouseWheel(nFlags, zDelta, pt);
}

void COpenGL3View::OnInitialUpdate()
{
    CView::OnInitialUpdate();

    // TODO: Add your specialized code here and/or call the base class
}

BOOL COpenGL3View::SetupPixelFormat( void )
{
    PIXELFORMATDESCRIPTOR pfd =
        {
            sizeof (PIXELFORMATDESCRIPTOR),    // size of this PFD
            1,                                // version number
            PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_TYPE_RGBA,
            24,                                // bpp
            0, 0, 0, 0, 0, 0,                // color bits ignored (?)
            0,                                // no alpha buffer
            0,                                // shift bit ignored (?)
            0,                                // no accumulation buffer
            0, 0, 0, 0,                        // accumulation bits ignored (?)
            16,                                // 16bit z-buffer
            0,                                // no stencil buffer
            0,                                // no auxiliary buffer (?)
            PFD_MAIN_PLANE,                    // main layer (?)
            0,                                // reserved
            0, 0, 0                            // layer masks ignored (?)
        };
    int pixelformat;
    if ( 0 == ( pixelformat = ::ChoosePixelFormat ( m_pDC->GetSafeHdc(), &pfd ) ) )
    {
        SetError(2);
        return false;
    }

    if ( false == ::SetPixelFormat ( m_pDC->GetSafeHdc(), pixelformat, &pfd ) )
    {
        SetError(3);
        return false;
    }

    return true;
}

BOOL COpenGL3View::SetupViewPort( int cx, int cy )
{
    glViewport(0, 0, cx, cy);
    return true;
}

BOOL COpenGL3View::SetupViewingFrustum( GLdouble aspect_ratio )
{
    gluPerspective(30.0f, aspect_ratio, .1f, 2000.0f);
    return true;
}

BOOL COpenGL3View::SetupViewingTransform( void )
{
    ::gluLookAt(eye.x,                 eye.y,                 eye.z,
                eye.x+line_of_sight.x, eye.y+line_of_sight.y, eye.z+line_of_sight.z,
                up.x,                  up.y,                  up.z);
    char str[256];
    sprintf(str, "looking at (%.0f,%.0f,%.0f) from (%.0f,%.0f,%.0f)\nup = (%.0f,%.0f,%.0f)",
            eye.x+line_of_sight.x, eye.y+line_of_sight.y, eye.z+line_of_sight.z,
            eye.x, eye.y, eye.z, up.x, up.y, up.z);
    //MessageBox(str);
    return true;
}

BOOL COpenGL3View::RenderScene()
{
    GLenum error;
    glBegin(GL_QUADS);
    {
        ::glTexCoord2f(0, 0);
        ::glVertex3f(0,  0,  0);

        ::glTexCoord2f(.8, 0);
        ::glVertex3f(0, 80,  0);

        ::glTexCoord2f(1, 1);
        ::glVertex3f(0,100,100);

        ::glTexCoord2f( 0, 1);
        ::glVertex3f(0,  0,100);
    }
    glEnd();
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("16a");
    return true;
}
void COpenGL3View::LoadTexture(const char * path)
{
    struct bmp_header
    {
        char sig[2];
        unsigned int fileSize, res1, dataOffset;
        unsigned int bmpHeaderSize, width, height;
        unsigned short planes, bpp;
        unsigned int compression, dataSize;
        unsigned int hres, vres;
        unsigned int numColors, impColors;
    } header;
    ifstream infile (path);
    infile.read(&header.sig[0], 2);
    infile.read((char*)&header.fileSize, 4*6);
    infile.read((char*)&header.planes, 2*2);
    infile.read((char*)&header.compression, 4*5);
    char str[512] = "";
    sprintf(str, "filesize = %d\ndata = %d\nheadersize = %d\nwidth = %d, height = %d\n"
                 "planes = %d, bpp = %d\ncompression = %d\ndatasize = %d\n"
                 "hres = %d, vres = %d\nnumcolors = %d, impcolors = %x",
                 header.fileSize, header.dataOffset, header.bmpHeaderSize, header.width, header.height,
                 header.planes, header.bpp, header.compression, header.dataSize,
                 header.hres, header.vres, header.numColors, header.impColors);
    MessageBox(str);
    texture = malloc(header.dataSize);
    if ( texture != NULL )
    {
        infile.seekg(header.dataOffset);
        infile.read((char*)texture, header.dataSize);
        sprintf(str, "file read success\nfirst pixel is (%02x,%02x,%02x)",
            ((unsigned char*)texture)[0],
            ((unsigned char*)texture)[1],
            ((unsigned char*)texture)[2]);
        MessageBox(str);
    }
    {
    GLenum error;
    ::glGenTextures(1, &n_texID);
    ::glBindTexture(GL_TEXTURE_2D, n_texID);
    ::glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    ::glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
    ::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
                   header.width, header.height, 0,
                   GL_RGB, GL_UNSIGNED_BYTE, texture);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("7");
    }
}

BOOL COpenGL3View::init( void )
{
    GLenum error;
    {
    m_pDC = new CClientDC(this);
   
    if ( NULL == m_pDC )
    {
        SetError(1);
        return false;
    }

    if ( !SetupPixelFormat() )
    {
        return false;
    }

    if ( 0 == ( m_hRC = ::wglCreateContext( m_pDC->GetSafeHdc() ) ) )
    {
        SetError(4);
        return false;
    }

    if ( false == ::wglMakeCurrent( m_pDC->GetSafeHdc(), m_hRC ) )
    {
        SetError(5);
        return false;
    }
    }
    ::glClearColor(0.125f, 0.0625f, 0.0625f, 0.0f);

    ::glEnable( GL_TEXTURE_2D);
    error = ::glGetError(); if ( error != GL_NO_ERROR ) MessageBox ("b");

    LoadTexture("texture.bmp");
    return true;
}

 

by: jhshuklaPosted on 2005-07-28 at 10:08:25ID: 14547744

edited functions:
init()
LoadTexture()
OnInitialUpdate()
RenderScene()

 

by: _corey_Posted on 2005-07-28 at 10:26:07ID: 14547940

Hrm, can you send the image to me at corey dot taylor at gmail.com ?

You should stick with modulate for now.

corey

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...