VIZ++ Class: OpenGLPalette

 VIZ++ Class Library  VIZ++ Samples  VIZ++ ClassTree 

Source code

/*
 * OpenGLPalette.h 
 * Copyright (c) 2015 Antillia.com TOSHIYUKI ARAI. ALL RIGHTS RESERVED. 
 */


// 2015/07/22

#pragma once

#include <viz++/opengl/OpenGLObject.h>
#include <viz++/ClientDC.h>

namespace VIZ {

class OpenGLPalette :public OpenGLObject {
protected:
  HPALETTE hPalette;

public:
  OpenGLPalette(ClientDC* clientDC)
  :hPalette(NULL)
  {
    if (clientDC == NULL) {
      throw IException("Invalid argument: ClientDC is NULL");    
    }
    HDC hDC = clientDC -> get(); 
    createPalette(hDC);
  }

  // See http://www.cs.rit.edu/~ncs/Courses/570/UserGuide/OpenGLonWin-11.html
  virtual void createPalette(HDC hDC)
  {
    if (hDC == NULL) {
      throw IException("Invalid argumet: HDC is NULL");
    }
    
    int pixelFormat = GetPixelFormat(hDC);
    PIXELFORMATDESCRIPTOR pfd;
    memset(&pfd, 0, sizeof(pfd));
    DescribePixelFormat(hDC, pixelFormat, sizeof(pfd), &pfd);

    int paletteSize = 0;

    if (pfd.dwFlags & PFD_NEED_PALETTE) {
        paletteSize = 1 << pfd.cColorBits;
    } else {
        return;
    }
    char* pbuffer = new char[sizeof(LOGPALETTE) + paletteSize * sizeof(PALETTEENTRY) ]; 
    LOGPALETTE* pPal = (LOGPALETTE*)pbuffer;
        
    pPal->palVersion = 0x300;
    pPal->palNumEntries = paletteSize;

    //  RGB color palette 
    int redMask = (1 << pfd.cRedBits) - 1;
    int greenMask = (1 << pfd.cGreenBits) - 1;
    int blueMask = (1 << pfd.cBlueBits) - 1;
  
    for (int i=0; i<paletteSize; ++i) {
      pPal->palPalEntry[i].peRed =
                    (((i >> pfd.cRedShift) & redMask) * 255) / redMask;
      pPal->palPalEntry[i].peGreen =
                    (((i >> pfd.cGreenShift) & greenMask) * 255) / greenMask;
      pPal->palPalEntry[i].peBlue =
                    (((i >> pfd.cBlueShift) & blueMask) * 255) / blueMask;
      pPal->palPalEntry[i].peFlags = 0;
    }
  
    hPalette = CreatePalette(pPal);
    delete [] pbuffer;

    if (hPalette) {
      SelectPalette(hDC, hPalette, FALSE);
      RealizePalette(hDC);
    } else {
      throw IException("Failed to CreatePalette");
    }
  }

  ~OpenGLPalette()
  {
    if (hPalette) {
      DeleteObject(hPalette);
      hPalette = NULL;
    }
  }
};
}

Last modified: 10 Feb 2017

Copyright (c) 2009-2017 Antillia.com ALL RIGHTS RESERVED.