Showing posts with label c. Show all posts
Showing posts with label c. Show all posts

Thursday, May 26, 2011

glVertexPointer example c/c++ java

Name

glVertexPointer - define an array of vertex coordinates

C Specification

void glVertexPointer(GLint size,
    GLenum type,
    GLsizei stride,
    const GLvoid * pointer)

Parameters

size
Specifies the number of coordinates per vertex. Must be 2, 3, or 4. The initial value is 4.
type
Specifies the data type of each vertex coordinate in the array. Symbolic constants GL_BYTE, GL_SHORT, and GL_FIXED, are accepted. However, the initial value is GL_FLOAT. The common profile accepts the symbolic constant GL_FLOAT as well.
stride 
Specifies the byte offset between consecutive vertices. If stride is 0, the vertices are understood to be tightly packed in the array. The initial value is 0.
pointer
Specifies a pointer to the first coordinate of the first vertex in the array. The initial value is 0.

Description

glVertexPointer specifies the location and data of an array of vertex coordinates to use when rendering. size specifies the number of coordinates per vertex and type the data type of the coordinates. stride specifies the byte stride from one vertex to the next allowing vertices and attributes to be packed into a single array or stored in separate arrays. (glVertexPointer Single-array storage may be more efficient on some implementations.) When a vertex array is specified, size, type, stride, and pointer are saved as client-side state.
If the vertex array is enabled, it is used when glDrawArrays, or glDrawElements is called. To enable and disable the vertex array, call glEnableClientState and glDisableClientState with the argument GL_VERTEX_ARRAY. The vertex array is initially disabled and isn't accessed when glDrawArrays or glDrawElements is called.
Use glDrawArrays to construct a sequence of primitives (all of the same type) from prespecified vertex and vertex attribute arrays. Use glDrawElements to construct a sequence of primitives by indexing vertices and vertex attributes.

Notes

glVertexPointer is typically implemented on the client side.

Errors

GL_INVALID_VALUE is generated if size is not 2, 3, or 4.
GL_INVALID_ENUM is generated if type is is not an accepted value.
GL_INVALID_VALUE is generated if stride is negative.

Copyright

Copyright © 2003 Silicon Graphics, Inc.
This document is licensed under the SGI Free Software B License. For details, see http://oss.sgi.com/projects/FreeB/.

See Also

glColorPointer, glDrawArrays, glDrawElements, glEnable, glNormalPointer, glTexCoordPointer

Example - glVertexPointer

  1. package kr.ac.uos.je;  
  2.   
  3. import java.nio.ByteBuffer;  
  4. import java.nio.ByteOrder;  
  5. import java.nio.FloatBuffer;  
  6.   
  7. import javax.microedition.khronos.egl.EGLConfig;  
  8. import javax.microedition.khronos.opengles.GL10;  
  9.   
  10. import android.opengl.GLSurfaceView.Renderer;  
  11.   
  12. public class GLRenderer implements Renderer{  
  13.   
  14.       
  15. /**  
  16.  * Default Construct  
  17.  */  
  18.     public GLRenderer() {  
  19.         //Dump Vertex to Buffer  
  20.         triangleVertexBuffer = createFloatBuffer(triangle);  
  21.           
  22.     }  
  23.     @Override  
  24.     public void onSurfaceCreated(GL10 gl, EGLConfig config) {  
  25.         //배경을 흰색으로 clear  
  26.         gl.glClearColor(1, 1, 1, 1);  
  27.         //glHint - 특정한 렌더링 기능에 대한 선택적인 제어   
  28.         gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);  
  29.     }  
  30.   
  31.     @Override  
  32.     public void onSurfaceChanged(GL10 gl, int width, int height) {  
  33.     }  
  34.   
  35.     private float[] triangle = new float[]{  
  36.             -0.5f, 0, 0,  
  37.             0, 0.5f, 0,  
  38.             0.5f, 0, 0  
  39.     };  
  40.       
  41.     private FloatBuffer triangleVertexBuffer;  
  42.   
  43. /**  
  44.  * Here's Where We Do All The Drawing  
  45.  */  
  46.     @Override  
  47.     public void onDrawFrame(GL10 gl) {  
  48.         //Clear The Screen And The Depth Buffer  
  49.         gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);  
  50.         //Reset View  
  51.         gl.glLoadIdentity();  
  52.         //Set Triangle Color to RED  
  53.         gl.glColor4f(1, 0, 0, 0.5f);  
  54.         //Set Vertex  
  55.         gl.glVertexPointer(3, GL10.GL_FLOAT, 0, triangleVertexBuffer);  
  56.         gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);  
  57.         //Draw Triangle  
  58.         gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 3);  
  59.         gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);  
  60.     }  
  61.       
  62.     protected FloatBuffer createFloatBuffer(float[] array){  
  63.         ByteBuffer byteBuffer = ByteBuffer.allocateDirect(array.length << 2);  
  64.         byteBuffer.order(ByteOrder.nativeOrder());  
  65.         FloatBuffer floatBuffer = byteBuffer.asFloatBuffer();  
  66.         floatBuffer.put(array);  
  67.         floatBuffer.position(0);  
  68.         return floatBuffer;  
  69.     }  
  70.   
  71. }

glViewport example c c++ objc java

Name

glViewport - set the viewport

C Specification

void glViewport(GLint x, GLint y, GLsizei width, GLsizei height)

Parameters

x, y
Specify the lower left corner of the viewport rectangle, in pixels. The initial value is (0, 0).
width, height
Specify the width and height of the viewport. When a GL context is first attached to a surface (e.g. window), width and height are set to the dimensions of that surface.

Description

glViewport specifies the affine transformation of x and y from normalized device coordinates to window coordinates. Let (xnd, ynd) be normalized device coordinates. Then the window coordinates (xw, yw) are computed as follows:
xw = ( xnd + 1 ) width/2 + x
yw = ( ynd + 1 ) height/2 + y
Viewport width and height are silently clamped to a range that depends on the implementation. To query this range, call glGetInteger with argument GL_MAX_VIEWPORT_DIMS.

Errors

GL_INVALID_VALUE is generated if either width or height is negative.

Associated Gets

glGetInteger with argument GL_MAX_VIEWPORT_DIMS

Copyright

Copyright © 2003 Silicon Graphics, Inc.
This document is licensed under the SGI Free Software B License. For details, see http://oss.sgi.com/projects/FreeB/.

See Also

glDepthRange, glGetInteger

Example of glViewport

void reshape(int width, int height)
{
 glClearColor(1.0, 1.0, 1.0, 0.0);
 glMatrixMode(GL_PROJECTION);
 glViewport(0, 0, width, height);
 glLoadIdentity();
 gluOrtho2D(-0.5,0.5,-0.5,0.5);
 printf("reshape function called. ");
}

glTexImage2D example c c++ java objc

Name

glTexImage2D - specify a two-dimensional texture image

C Specification

void glTexImage2D(GLenum target,
    GLint level,
    GLint internalformat,
    GLsizei width,
    GLsizei height,
    GLint border,
    GLenum format,
    GLenum type,
    const GLvoid * pixels)

Parameters

target
Specifies the target texture. Must be GL_TEXTURE_2D.
level
Specifies the level-of-detail number. Level 0 is the base image level. Level n is the nth mipmap reduction image. Must be greater or equal 0.
internalformat
Specifies the color components in the texture. Must be same as format. The following symbolic values are accepted: GL_ALPHA, GL_RGB, GL_RGBA, GL_LUMINANCE, or GL_LUMINANCE_ALPHA.
width
Specifies the width of the texture image. Must be 2n + 2border for some integer n. All implementations support texture images that are at least 64 texels wide.
height
Specifies the height of the texture image. Must be 2m + 2border for some integer m. All implementations support texture images that are at least 64 texels high.
border
Specifies the width of the border. Must be 0. (glTexImage2D)
format
Specifies the format of the pixel data. Must be same as internalformat. The following symbolic values are accepted: GL_ALPHA, GL_RGB, GL_RGBA, GL_LUMINANCE, and GL_LUMINANCE_ALPHA.
type
Specifies the data type of the pixel data. The following symbolic values are accepted: GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_4_4_4_4, and GL_UNSIGNED_SHORT_5_5_5_1.
pixels
Specifies a pointer to the image data in memory.

Description for glTexImage2D

Texturing maps a portion of a specified texture image onto each graphical primitive for which texturing is enabled. To enable and disable two-dimensional texturing, call glEnable and glDisable with argument GL_TEXTURE_2D. Two-dimensional texturing is initially disabled.
To define texture images, call glTexImage2D. The arguments describe the parameters of the texture image, such as height, width, width of the border, level-of-detail number (see glTexParameter), and number of color components provided. The last three arguments describe how the image is represented in memory.
Data is read from pixels as a sequence of unsigned bytes or shorts, depending on type. These values are grouped into sets of one, two, three, or four values, depending on format, to form elements.
When type is GL_UNSIGNED_BYTE, each of these bytes is interpreted as one color component, depending on format. When type is one of GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_5_5_5_1, each unsigned value is interpreted as containing all the components for a single pixel, with the color components arranged according to format. (glTexImage2D)
The first element corresponds to the lower left corner of the texture image. Subsequent elements progress left-to-right through the remaining texels in the lowest row of the texture image, and then in successively higher rows of the texture image. The final element corresponds to the upper right corner of the texture image.
By default, adjacent pixels are taken from adjacent memory locations, except that after all width pixels are read, the read pointer is advanced to the next four-byte boundary. The four-byte row alignment is specified by glPixelStore with argument GL_UNPACK_ALIGNMENT, and it can be set to one, two, four, or eight bytes.
format determines the composition of each element in pixels. It can assume one of the following symbolic values:
GL_ALPHA
Each element is a single alpha component. The GL converts it to floating point and assembles it into an RGBA element by attaching 0 for red, green, and blue.
GL_RGB
Each element is an RGB triple. The GL converts it to fixed-point or floating-point and assembles it into an RGBA element by attaching 1 for alpha.
GL_RGBA
Each element contains all four components. The GL converts it to fixed-point or floating-point.
GL_LUMINANCE
Each element is a single luminance value. The GL converts it to fixed-point or floating-point, then assembles it into an RGBA element by replicating the luminance value three times for red, green, and blue and attaching 1 for alpha.
GL_LUMINANCE_ALPHA
Each element is a luminance/alpha pair. The GL converts it to fixed-point or floating point, then assembles it into an RGBA element by replicating the luminance value three times for red, green, and blue.

Notes

pixels may be NULL. In this case texture memory is allocated to accommodate a texture of width width and height height. You can then download subtextures to initialize this texture memory. The image is undefined if the user tries to apply an uninitialized portion of the texture image to a primitive.
glTexImage2D specifies the two-dimensional texture for the currently bound texture specified with glBindTexture, and the current texture unit, specified with glActiveTexture.

Errors

GL_INVALID_ENUM is generated if target is not GL_TEXTURE_2D.
GL_INVALID_ENUM is generated if format is not an accepted constant.
GL_INVALID_ENUM is generated if type is not a type constant.
GL_INVALID_VALUE is generated if level is less than 0.
GL_INVALID_VALUE may be generated if level is greater than log2max, where max is the returned value of GL_MAX_TEXTURE_SIZE.
GL_INVALID_VALUE is generated if internalformat is not an accepted constant.
GL_INVALID_VALUE is generated if width or height is less than 0 or greater than GL_MAX_TEXTURE_SIZE, or if either cannot be represented as 2k + 2border for some integer k.
GL_INVALID_VALUE is generated if border is not 0.
GL_INVALID_OPERATION is generated if internalformat and format are not the same.
GL_INVALID_OPERATION is generated if type is GL_UNSIGNED_SHORT_5_6_5 and format is not GL_RGB.
GL_INVALID_OPERATION is generated if typeis one of GL_UNSIGNED_SHORT_4_4_4_4, or GL_UNSIGNED_SHORT_5_5_5_1 and formatis not GL_RGBA.

Associated Gets

glGetInteger with argument GL_MAX_TEXTURE_SIZE

Copyright

Copyright © 2003 Silicon Graphics, Inc.
This document is licensed under the SGI Free Software B License. For details, see http://oss.sgi.com/projects/FreeB/.

See Also

glActiveTexture, glBindTexture, glCopyTexImage2D, glCopyTexSubImage2D, glGetInteger, glMatrixMode, glPixelStore, glTexEnv, glTexSubImage2D, glTexParameter

Example of glTexImage2D

{
BYTE *pBuffer;//RGB Data storage
int bmpwidth, bmpheight;
TCHAR filename[100];

wcscpy(filename, L"\\Storage Card\\DieTexture.bmp");
LoadBmpFile(filename, &pBuffer, &bmpwidth, &bmpheight);
glBindTexture(GL_TEXTURE_2D, texture); // texture에 binding
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);   
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, bmpwidth, bmpheight, 0, GL_RGB, GL_UNSIGNED_BYTE, pBuffer);

delete pBuffer;
}

glFrustumf example java c c++ objc

Name

glFrustumf , glFrustumx - multiply the current matrix by a perspective matrix

C Specification

void glFrustumf(GLfloat left,
    GLfloat right,
    GLfloat bottom,
    GLfloat top,
    GLfloat near,
    GLfloat far)

void glFrustumx(GLfixed left,
    GLfixed right,
    GLfixed bottom,
    GLfixed top,
    GLfixed near,
    GLfixed far)

Parameters

left, right
Specify the coordinates for the left and right vertical clipping planes.
bottom, top
Specify the coordinates for the bottom and top horizontal clipping planes.
near, far
Specify the distances to the near and far depth clipping planes. Both distances must be positive.

Description

glFrustum describes a perspective matrix that produces a perspective projection. The current matrix (see glMatrixMode) is multiplied by this matrix and the result replaces the current matrix, as if glMultMatrix were called with the following matrix as its argument:
(
2/(right - left) 0 A 0
0 2/(top - bottom) B 0
0 0 C D
0 0 -1 0
)
where
A = - (right + left)/(right - left)
B = - (top + bottom)/(top - bottom)
C = - (far + near)/(far - near)
D = - 2farnear/(far - near)
Typically, the matrix mode is GL_PROJECTION, and (left, bottom, -near) and (right, top, -near) specify the points on the near clipping plane that are mapped to the lower left and upper right corners of the window, assuming that the eye is located at (0, 0, 0). -far specifies the location of the far clipping plane. Both near and far must be positive.
Use glPushMatrix and glPopMatrix to save and restore the current matrix stack.

Notes

Depth buffer precision is affected by the values specified for near and far. The greater the ratio of far to near is, the less effective the depth buffer will be at distinguishing between surfaces that are near each other. If
r = far/near
roughly log2(r) bits of depth buffer precision are lost. Because r approaches infinity as near approaches 0, near must never be set to 0.

Errors

GL_INVALID_VALUE is generated if near or far is not positive, or if left = right, or bottom = top.

Copyright

Copyright © 2003 Silicon Graphics, Inc.
This document is licensed under the SGI Free Software B License. For details, see http://oss.sgi.com/projects/FreeB/.

See Also

glOrtho, glMatrixMode, glMultMatrix, glPushMatrix, glViewport

Example

package com.minkandroid.ui.sample.work;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import com.minkandroid.ui.sample.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLSurfaceView;
import android.opengl.GLUtils;
class COpenGLRenderTest implements GLSurfaceView.Renderer {
public class TestRect
{
private IntBuffer mVertexBuffer;
private IntBuffer mColorBuffer;
private ByteBuffer mIndexBuffer;
private FloatBuffer mTexBuffer;
public TestRect()
{
int one = 0x40000;
int vertices[] = {
-one, one, one/4, //0
one, one, one/4, //1
one, -one, one/4,//2
-one, -one, one/4//3
};
// int one = 1;
// int vertices[] = {
// -one, one, 0, //0
// one, one, 0, //1
// one, -one, 0,//2
// -one, -one, 0//3
// };

/**
* 버텍스가 반시계방향이건 아니건 그냥 버텍스와 텍스쳐는 그냥 매핑된다.
* 하지만 원이미지와 화면은 상하 반전해야한다.
* V --> Texture
* 0--1 3--2
* | | | |
* 3--2 0--1
*/
float verticesTex[] = {
(float)0, (float)0,
(float)1, (float)0,
(float)1, (float)1,
(float)0, (float)1
};
// int colors[] = {
// 0, 0, 0, one,
// one, 0, 0, one,
// one, one, 0, one,
// 0, one, 0, one
// };
int colors[] = {
0, 0, 0, 0x1000,
0x1000, 0, 0, 0x1000,
0x1000, 0x1000, 0, 0x1000,
0, 0x1000, 0, 0x1000
};
byte indices[] = {
0, 1, 3, 1, 2, 3
};
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);
vbb.order(ByteOrder.nativeOrder());
mVertexBuffer = vbb.asIntBuffer();
mVertexBuffer.put(vertices);
mVertexBuffer.position(0);

ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length*4);
cbb.order(ByteOrder.nativeOrder());
mColorBuffer = cbb.asIntBuffer();
mColorBuffer.put(colors);
mColorBuffer.position(0);

mIndexBuffer = ByteBuffer.allocateDirect(indices.length);
mIndexBuffer.put(indices);
mIndexBuffer.position(0);
ByteBuffer fbb = ByteBuffer.allocateDirect(verticesTex.length*4);
fbb.order(ByteOrder.nativeOrder());
mTexBuffer = fbb.asFloatBuffer();
mTexBuffer.put(verticesTex);
mTexBuffer.position(0);
}
public void draw(GL10 gl)
{
//시계방향으로 감기
gl.glFrontFace(GL10.GL_CW);
// which one should NOT be drawn
//gl.glCullFace(GL10.GL_BACK);

//3: 배열의 3개씩 읽어온다.
gl.glVertexPointer(3, GL10.GL_FIXED, 0, mVertexBuffer);
//4: 배열의 4개씩 읽어온다.
gl.glColorPointer(4, GL10.GL_FIXED, 0, mColorBuffer);
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer);
//삼각형형태로 그린다. 6:인덱스의수
gl.glDrawElements(GL10.GL_TRIANGLES, 6, GL10.GL_UNSIGNED_BYTE, mIndexBuffer);
}
}

TestRect m_rtTest;
int[] m_texturesID;
Context m_context;
public COpenGLRenderTest(Context context)
{
m_rtTest = new TestRect();
m_context = context;
}
@Override
public void onDrawFrame(GL10 gl)
{
//텍스쳐지원
//gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,GL10.GL_MODULATE);
//화면을 클리어한다. (컬러와 Depth를 클리어 한다)
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_MODELVIEW); //투영을 위한 행렬을 정의 한다.
gl.glLoadIdentity(); //좌표계 초기화를 한다.
gl.glTranslatef(0, 0, -2.0f); //이동
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); //정점 Array를 사용할 수 있게 선언한다.
gl.glEnableClientState(GL10.GL_COLOR_ARRAY); //Color Array를 사용할 수 있게 선언한다.
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
//gl.glActiveTexture(GL10.GL_TEXTURE0);
gl.glBindTexture(GL10.GL_TEXTURE_2D, m_texturesID[0]);
//gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,GL10.GL_REPEAT);
//gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,GL10.GL_REPEAT);
m_rtTest.draw(gl);
}

@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height); //뷰포트를 정의 한다.
float ratio = (float) width / height;
gl.glMatrixMode(GL10.GL_PROJECTION); //투영을 위한 행렬을 정의 한다.
gl.glLoadIdentity(); //좌표계 초기화를 한다.
gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10); //투영을 비율을 정의 한다. 1:화면비율(w/h)
float diam = 8;
float zNear = 10.f;
float zFar = zNear + diam;
int cx = 0, cy = 0;
float left = cx - diam;
float right = cx + diam;
float bottom = cy - diam;
float top = cy + diam;



if ( ratio < 1.0 ) { // window taller than wide
bottom /= ratio;
top /= ratio;
} else {
left *= ratio;
right *= ratio;
}
//Z 축으로 세모가 나열되어 있다고 가정하여 앞에서 바라 봤을 경우 재일 앞 세모만 보인다.
gl.glOrthof(left, right, bottom, top, zNear, zFar);
//Z 축으로 세모가 나열되어 있다고 가정하여 앞에서 바라 봤을 경우, Z축으로 작아지면서 나열되는 세모들이 보인다.
// gl.glFrustumf(left, right, bottom, top, -zNear, zFar);
//gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10); //투영을 비율을 정의 한다. 1:화면비율(w/h)
}

@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
gl.glDisable(GL10.GL_DITHER); //움직임 효과를 빠르게 해준다. (흔들림)을 꺼둔다.
//드라이버에 원근보정을 가장 빠르게 요청한다. 하드웨어에 따라서 달라진다.
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,GL10.GL_FASTEST);
gl.glClearColor(.5f, .5f, .5f, 1);
gl.glEnable(GL10.GL_CULL_FACE); //폴리곤 추려 내기.
gl.glShadeModel(GL10.GL_SMOOTH);
//물체를 하나 그리고 그 앞쪽으로 물체를 하나 더 그리면 처음에 그렸던 물체에 나중에 그린 물체가 가리는 현상이 생길 수 있는다.
gl.glEnable(GL10.GL_DEPTH_TEST);
//텟스쳐 맵정의를 한다.
gl.glEnable(GL10.GL_TEXTURE_2D);
//테스처를 특정 별명을 붙혀준다.
m_texturesID = new int[1];
gl.glGenTextures(1, m_texturesID, 0);
//그 별명에 텟스처를 바인드한다.
gl.glBindTexture(GL10.GL_TEXTURE_2D, m_texturesID[0]);
//축소시 가장가까운 픽셀을 참조하여 축소를 한다.
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,GL10.GL_NEAREST);
//확대시 선형으로 확대를 하여 고르게 한다.
gl.glTexParameterf(GL10.GL_TEXTURE_2D,GL10.GL_TEXTURE_MAG_FILTER,GL10.GL_LINEAR);
//경계선을 고르게 한다.
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,GL10.GL_CLAMP_TO_EDGE);
//GL_REPLACE 텍스처를 물체에 입힌다.
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,GL10.GL_REPLACE);
InputStream is = m_context.getResources().openRawResource(R.drawable.test_doc);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is);
}
finally
{
try
{
is.close();
}
catch(IOException e)
{
// Ignore.
}
}
//텍스쳐를 읽어들인다.
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
}

}

Sunday, May 15, 2011

jpeglib example c c++

A jpeglib example is explained in this article. Jpeglib is an open source library that is used to encode and decode JPEG image format. The library is fairly simple to use. See following example for detailed decoding procedure. [jpeglib example]


Step 1. Include files for jpeglib example

#include "jinclude.h"
#include "jpeglib.h"

Step 2. Decoding procedure.

a_pFilename -> jpeg filename.

a_pBuffer -> pointer to image buffer. It's allocated inside the read() function.

bool read(char *a_pFilename, JSAMPLE **a_pBuffer)
{

// Data strucure required for decoding JPEG file.
//
struct jpeg_decompress_struct cInfo;
struct jpeg_error_mgr cErrMgr;

FILE *pFile;
int iRowStride, i;
JSAMPARRAY pRows;

// Check the filename is valid.
//
if( !a_pFilename )
return false;

// open the file in binary mode.
//
pFile = fopen(a_pFilename, "rb");
if( !pFile )
return false;

// 1. Install error manager.
//
cInfo.err = jpeg_std_error(&cErrMgr);

// 2. Create JPEG decompressor object.
//
jpeg_create_decompress(&cInfo);

// 3. Specify the data source.
//
jpeg_stdio_src(&cInfo, pFile);

// 4. Read JPEG Header to extract image information.
//
(void) jpeg_read_header(&cInfo, TRUE);

// From now on, you can access information on the jpeg image by 
// referencing fields of cInfo object.
//

// 5. Set Target Image Format. Here we store the decoded image in JCS_RGB format.
//
cInfo.out_color_space = JCS_RGB;

// 6. Initiate decompress procedure.
//
(void) jpeg_start_decompress(&cInfo);

// 7. Allocate temporary buffer for decoding.
iRowStride = cInfo.output_width * cInfo.output_components;
(*a_pBuffer) = new JSAMPLE[ iRowStride * cInfo.output_height ];
if( !(*a_pBuffer) )
{
// Allocation failed.
jpeg_destroy_decompress(&cInfo);
fclose(pFile);
return false;
}

// Assign row buffers.
//
pRows = new JSAMPROW[ 1 ];
if( !pRows )
{
// Allocation failed.
delete[] (*a_pBuffer);
(*a_pBuffer) = NULL;
jpeg_destroy_decompress(&cInfo);
fclose(pFile);
return false;
}

// Decoding loop:
//
i = 0;
while (cInfo.output_scanline < cInfo.output_height)
{
// Decode it !
pRows[0] = (JSAMPROW)( (*a_pBuffer) + iRowStride * i); // set row buffer
(void) jpeg_read_scanlines(&cInfo, pRows, 1); // decode
i++;
}

// 8. Finish decompression.
//
(void) jpeg_finish_decompress(&cInfo);

// 9. Reclaim resources and return.
//
delete[] pRows;
jpeg_destroy_decompress(&cInfo);
fclose(pFile);

return true;
}