openGL 頂點,座標系,紋理座標
阿新 • • 發佈:2019-01-03
瞭解座標系是繪製圖形的基礎。在使用openGL的場景中,有世界座標,區域性座標,紋理座標,和螢幕座標幾種。
openGL 座標系:
分3個軸,x,y,z 中心點為o, 箭頭方向為正方向,最大與最小值為1和-1,這是經過歸一化處理的。這樣設計是為了顯示卡計算方便。
螢幕座標系,就是應用在裝置螢幕上的座標系。也就是圖形最終繪製的地方。
左上角為原點,箭頭為正方向,大小又螢幕畫素大小決定。openGL的螢幕座標系,Y軸向上為正。相當於上面那個三維座標系擷取一個二維的XY。
紋理座標系:
也做了歸一化處理。這個座標就代表了一個紋理。openGL是基於定點的網格繪製。就是說,openGL的圖形都是由很多頂點,按照一定的規則連結起來構成的圖形。那麼紋理座標的4個座標點,對映到頂點上。openGL就會把這個紋理應用到4個定點構成的圖形上。
一般我們會把openGL的座標系的中心點,與螢幕的中心點重合。如下:
矩形為螢幕的區域。openGL的繪製方法會把這個座標系的頂點,組合成圖形呈現在螢幕上。當然這個還涉及到攝像機的位置,螢幕剪裁等設定。這裡不考慮。
那麼什麼是頂點呢,就是一個有xyz座標的點。如(0,0,0)或(1,1,1)。XY就和通常的二維座標一樣定位平面的位置。Z軸表示的是深度,openGL就是為了繪製3D圖形而誕生的。頂點座標是做了歸一化處理的float型別。那麼這裡就會涉及到螢幕座標系到openGL座標系的轉化工作。
如圖:
螢幕座標系,左上點為(0,0) 那麼螢幕中心點座標,就是(sreenWidth / 2, screenHeight / 2)。而對應openGL座標系的歸一化座標就是(0,0,0)。所以這裡需要把螢幕座標轉換成openGL的歸一化座標。
- /**
- * Convert x to openGL
- *
- * @param x
- * Screen x offset top left
- * @return Screen x offset top left in OpenGL
- */
- publicstaticfloat toGLX(float x) {
- return -1.0f * ratio + toGLWidth(x);
- }
- /**
- * Convert y to openGL y
- *
- * @param y
-
* Screen y offset top left
- * @return Screen y offset top left in OpenGL
- */
- publicstaticfloat toGLY(float y) {
- return1.0f - toGLHeight(y);
- }
- /**
- * Convert width to openGL width
- *
- * @param width
- * @return Width in openGL
- */
- publicstaticfloat toGLWidth(float width) {
- return2.0f * (width / screenWidth) * ratio;
- }
- /**
- * Convert height to openGL height
- *
- * @param height
- * @return Height in openGL
- */
- publicstaticfloat toGLHeight(float height) {
- return2.0f * (height / screenHeight);
- }
- /**
- * Convert x to screen x
- *
- * @param glX
- * openGL x
- * @return screen x
- */
- publicstaticfloat toScreenX(float glX) {
- return toScreenWidth(glX - (-1 * ratio));
- }
- /**
- * Convert y to screent y
- *
- * @param glY
- * openGL y
- * @return screen y
- */
- publicstaticfloat toScreenY(float glY) {
- return toScreenHeight(1.0f - glY);
- }
- /**
- * Convert glWidth to screen width
- *
- * @param glWidth
- * @return Width in screen
- */
- publicstaticfloat toScreenWidth(float glWidth) {
- return (glWidth * screenWidth) / (2.0f * ratio);
- }
- /**
- * Convert height to screen height
- *
- * @param glHeight
- * @return Height in screen
- */
- publicstaticfloat toScreenHeight(float glHeight) {
- return (glHeight * screenHeight) / 2.0f;
- }