軟渲染器五之win32環境下如何繪製畫素

2021-07-25 01:53:32 字數 2340 閱讀 9743

win32下 如何繪製畫素,也許到你看到這個問題的時候會馬上想到win32的繪製畫素函式setpixel(),如果setpixel函式來做這個軟體渲染器的話,那執行效率將低的可憐,假設我們的視口螢幕為800x600的解析度,也就是螢幕上有800x600個(48萬個)畫素點,也就是繪製整個螢幕的畫素你得至少呼叫48w次setpixel函式,那將是多麼低的效率。有一種更高效的方法,就是定義乙個快取,然後在快取相應位置(對應螢幕的乙個畫素的位置)存入乙個代表顏色的資料,在每幀的最後將快取的資料作為顏色全部輸入到螢幕,這樣效率大大提高,下面請看實現**:

//螢幕寬度和高度 

#define screen_width 800

#define screen_height 600

#define bits 24 //每個畫素的位數

//背後快取,深度快取

byte buffer[screen_width*screen_height*bits / 8]; //每三個byte為乙個畫素,總共有800*600個畫素,800*600*3個byte,bgr的顏色儲存順序,

//主視窗的hdc和handle

static hdc screen_hdc;

static hwnd screen_hwnd;

static hdc hcompatibledc; //相容hdc

static hbitmap hcompatiblebitmap; //相容bitmap

static hbitmap holdbitmap; //舊的bitmap

static bitmapinfo binfo; //bitmapinfo結構體

//填充bitmapinfo結構體

zeromemory(&binfo, sizeof(bitmapinfo));

binfo.bmiheader.bibitcount = 24; //每個畫素多少位,也可直接寫24(rgb)或者32(rgba)

binfo.bmiheader.bicompression = bi_rgb;

binfo.bmiheader.biheight = -screen_height;

binfo.bmiheader.biplanes = 1;

binfo.bmiheader.bisizeimage = 0;

binfo.bmiheader.bisize = sizeof(bitmapinfoheader);

binfo.bmiheader.biwidth = screen_width;

//獲取螢幕hdc

screen_hwnd = hwnd;

screen_hdc = getdc(screen_hwnd);

//獲取相容hdc和相容bitmap,相容bitmap選入相容hdc(每個hdc記憶體每時刻僅能選入乙個gdi資源,gdi資源要選入hdc才能進行繪製)

hcompatibledc = createcompatibledc(screen_hdc);

hcompatiblebitmap = createcompatiblebitmap(screen_hdc, screen_width, screen_height);

holdbitmap = (hbitmap)selectobject(hcompatibledc, hcompatiblebitmap);

//將顏色資料列印到螢幕上,這下面兩個函式每幀都得呼叫

setdibits(screen_hdc, hcompatiblebitmap, 0, screen_height, buffer, (bitmapinfo*)&binfo, dib_rgb_colors);

bitblt(screen_hdc, -1, -1, screen_width, screen_height, hcompatibledc, 0, 0, srccopy);

不過在這裡我用byte陣列儲存的顏色數值,每乙個byte儲存rgb顏色的乙個分量,假設我想視口螢幕位置(x,y)寫入顏色rgb,則**如下:

buffer[int(y) * 800 * 3 + (int(x) + 1) * 3 - 1] = b;

buffer[int(y) * 800 * 3 + (int(x) + 1) * 3 - 2] = g;

buffer[int(y) * 800 * 3 + (int(x) + 1) * 3 - 3] = r;

細心的你也許會發現在位置上顏色順序為bgr,這點我也不知道是為什麼

寫了好幾篇技術部落格,放出程式的執行截圖:

放出我的軟體渲染器源**:

rest framework之渲染器

根據 使用者請求url 或 使用者可接受的型別,篩選出合適的 渲染元件。序列化 友好的展示資料 首先要在settins.py中將rest framework元件加進去 引入渲染器類,然後將他們作為乙個列表的元素賦值給renderer classes 配置屬性,如下 from rest framewo...

Win32下使用OpenGL實現渲染

1.win32下基於directx的實現到處都可以找的到,我這裡實現的是基於opengl的實現 廢話不多說,直接看 1.標頭檔案中的部分 class rendereropengl public renderer,public singleton 2.cpp中的 類中與opengl裝置沒有直接關係的介...

rest framework元件 之 渲染器與版本

渲染器版本 規定頁面顯示的效果 無用,了解即可 區域性渲染 只返回json資料。效果 看另一種情況 既返回json資料,又巢狀在html中。注意 容易出bug.效果如下 看一下原始碼 預設全域性。全域性渲染 rest framework 先看一下原始碼 圈出來指的就是版本。rest framewor...