• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            天行健 君子當(dāng)自強(qiáng)而不息

            D3D中的材質(zhì)和光照處理


            提示:

            閱讀本文需要一定的3D圖形學(xué)和DirectX9基礎(chǔ),如果你發(fā)現(xiàn)閱讀困難,請(qǐng)參閱D3D中基本立體面的繪制。
            本文用到的坐標(biāo)系統(tǒng)變換函數(shù)請(qǐng)參閱 DirectX 9的坐標(biāo)系統(tǒng)變換
             

            在現(xiàn)實(shí)世界中,物體在各種環(huán)境光線的照射下,吸收了光線的能量,并將這些能量進(jìn)行反射而形成反射光。

            顏色和光照

            物體表面光澤是由于表面的反射光刺激人的眼睛視網(wǎng)膜而引起的一種視官感覺,這種色覺實(shí)際上是由光的波長(zhǎng)決定的。每種波長(zhǎng)的光在光譜中占據(jù)一定的位置,具有特定的色澤和亮度。

            對(duì)于任意波長(zhǎng)為s的光,由于s可分解為s = aR + bG + cB,其中R,G,B為紅色光,綠色光和藍(lán)色光的波長(zhǎng),于是在RGB為基底的情況下,光波長(zhǎng)由三元數(shù)(a, b, c)來決定。因此光的顏色值量化可以這樣來進(jìn)行:首先用顏色值(1, 0, 0)表示紅色R,用顏色值(0, 1, 0)表示綠色G,用(0, 0, 1)表示藍(lán)色B,而任意波長(zhǎng)的光的顏色值C則可用(r, g, b)表示,以表明顏色s = aR + bG + cB 是用RGB三色通過混色而得來的,其中r, g和b取區(qū)間的浮點(diǎn)數(shù)。

            為了實(shí)現(xiàn)像素顏色由暗變明的處理,通常還添加一個(gè)alpha分量來說明顏色的飽和度。此時(shí)顏色值將用四元組(r ,g, b, a)來表示,其中a就是alpha分量,也是一個(gè)介于區(qū)間[0, 1]的浮點(diǎn)數(shù)。當(dāng)r, g和b的顏色值確定以后,通過乘以一個(gè)a分量得到一個(gè)新的顏色值ar+ag+ab,這樣獲得的顏色值并沒有改變?cè)蓄伾腞GB成分比例。

            DirectX提供了以下的一個(gè)存放四元顏色值的結(jié)構(gòu)體D3DCOLORVALUE,來看看具體定義:

            Describes color values.

            typedef struct D3DCOLORVALUE {
            float r;
            float g;
            float b;
            float a;
            } D3DCOLORVALUE, *LPD3DCOLORVALUE;

            Members

            r
            Floating-point value specifying the red component of a color. This value generally is in the range from 0.0 through 1.0, with 0.0 being black.
            g
            Floating-point value specifying the green component of a color. This value generally is in the range from 0.0 through 1.0, with 0.0 being black.
            b
            Floating-point value specifying the blue component of a color. This value generally is in the range from 0.0 through 1.0, with 0.0 being black.
            a
            Floating-point value specifying the alpha component of a color. This value generally is in the range from 0.0 through 1.0, with 0.0 being black.

            Remarks

            You can set the members of this structure to values outside the range of 0 through 1 to implement some unusual effects. Values greater than 1 produce strong lights that tend to wash out a scene. Negative values produce dark lights that actually remove light from a scene.

            由于使用了浮點(diǎn)數(shù)作為顏色值的分量,因而可方便地定義顏色值的加法和乘法等運(yùn)算,以產(chǎn)生新的顏色值。例如:對(duì)于顏色C1 = (a1, r1, g1, b1)和C2 = (a2, r2, g2, b2),定義C1+C2,kC1和C1C2的顏色值如下:

            C1 + C2 = (a1 + a2, r1 + r2, g1 + g2, b1 + b2)
            kC1 = (ka1, kr1, kg1, kb1)
            C1C2 = (a1 x a2, r1 x r2, g1 x g2, b1 x b2)

            為支持顏色值的算術(shù)運(yùn)算,DirectX提供了一個(gè)顏色值的擴(kuò)展結(jié)構(gòu)D3DXCOLOR,來看看它的具體定義:

            typedef struct D3DXCOLOR
            {
            #ifdef __cplusplus
            public:
                D3DXCOLOR() {}
                D3DXCOLOR( DWORD argb );
                D3DXCOLOR( CONST FLOAT * );
                D3DXCOLOR( CONST D3DXFLOAT16 * );
                D3DXCOLOR( CONST D3DCOLORVALUE& );
                D3DXCOLOR( FLOAT r, FLOAT g, FLOAT b, FLOAT a );

                
            // casting
                operator DWORD () const;

                
            operator FLOAT* ();
                
            operator CONST FLOAT* () const;

                
            operator D3DCOLORVALUE* ();
                
            operator CONST D3DCOLORVALUE* () const;

                
            operator D3DCOLORVALUE& ();
                
            operator CONST D3DCOLORVALUE& () const;

                
            // assignment operators
                D3DXCOLOR& operator += ( CONST D3DXCOLOR& );
                D3DXCOLOR& 
            operator -= ( CONST D3DXCOLOR& );
                D3DXCOLOR& 
            operator *= ( FLOAT );
                D3DXCOLOR& 
            operator /= ( FLOAT );

                
            // unary operators
                D3DXCOLOR operator + () const;
                D3DXCOLOR 
            operator - () const;

                
            // binary operators
                D3DXCOLOR operator + ( CONST D3DXCOLOR& ) const;
                D3DXCOLOR 
            operator - ( CONST D3DXCOLOR& ) const;
                D3DXCOLOR 
            operator * ( FLOAT ) const;
                D3DXCOLOR 
            operator / ( FLOAT ) const;

                friend D3DXCOLOR 
            operator * ( FLOAT, CONST D3DXCOLOR& );

                BOOL 
            operator == ( CONST D3DXCOLOR& ) const;
                BOOL 
            operator != ( CONST D3DXCOLOR& ) const;

            #endif //__cplusplus
                FLOAT r, g, b, a;
            } D3DXCOLOR, *LPD3DXCOLOR;

            此外,DirectX還提供了一個(gè)使用整數(shù)來定義顏色值的D3DCOLOR類型,D3DCOLOR類型實(shí)際上是一個(gè)32bit的 DWORD類型。

            typedef DWORD D3DCOLOR;

            該類型的顏色值A(chǔ)lpha, Red, Green, Blue分量各占8個(gè)bit,并從高位字節(jié)到低位字節(jié)進(jìn)行存放,各分量的值范圍均為0~255之間。由于使用整數(shù),D3DCOLOR類型的顏色值的范圍相對(duì)于使用浮點(diǎn)數(shù)的D3DCOLORVALUE顏色值的范圍少。

            為了方便定義D3DCOLOR類型的顏色值, DirectX還提供了如下的兩個(gè)可直接將4個(gè)0~255之間的整數(shù)定義為D3DCOLOR顏色值的宏。
             
            // maps unsigned 8 bits/channel to D3DCOLOR
            #define D3DCOLOR_ARGB(a,r,g,b) \
                ((D3DCOLOR)((((a)&0xff)<<24)|(((r)&0xff)<<16)|(((g)&0xff)<<8)|((b)&0xff)))

            #define D3DCOLOR_RGBA(r,g,b,a) D3DCOLOR_ARGB(a,r,g,b)

            還可利用DirectX提供的D3DCOLOR_XRGB(r, g, b)宏,定義Alpha值為255的D3DCOLOR顏色值。
             
            #define D3DCOLOR_XRGB(r,g,b)   D3DCOLOR_ARGB(0xff,r,g,b)
                                                                        
            光源設(shè)置

            顏色是光的視覺感覺,DirectX為了支持場(chǎng)景的光照渲染,提供了點(diǎn)光源(Point Light),聚焦光源(Spot Light),方向光源(Directional Light)和環(huán)境光源(Ambient Light)4種標(biāo)準(zhǔn)類型的光源設(shè)置。

            點(diǎn)光源是一種向空間各個(gè)方向等強(qiáng)度發(fā)射光的光源,一個(gè)燈泡就是點(diǎn)光源的例子,點(diǎn)光源發(fā)射光的強(qiáng)度隨著距離的增加而逐漸減弱。

            聚焦光源的發(fā)光區(qū)域是一個(gè)圓錐體,內(nèi)錐光的強(qiáng)度沿著聚焦光的主發(fā)射方向,隨距離的增加而逐步衰減,外錐光的強(qiáng)度沿著外徑隨距離的增加而逐步衰減。手電筒是聚焦光源的一個(gè)例子。

            方向光源從無限遠(yuǎn)處以特定的方向發(fā)射平行光線到無窮遠(yuǎn)處,光的強(qiáng)度不隨距離的增加而衰減。太陽(yáng)光就是方向光源的一個(gè)例子,方向光源不需要設(shè)置光源位置,衰減系數(shù)和光照的作用范圍。

            環(huán)境光是根據(jù)場(chǎng)景中的各種光源的綜合照射效果所模擬出的一種光源,這種光源的光來自各個(gè)方向,不做任何的衰減處理,能均勻地照射物體表面的各個(gè)部位。

            如下圖所示:環(huán)境光、點(diǎn)光源、聚光燈以及直射光分別以不同的方式發(fā)射光線



            當(dāng)光源確定以后,就可以進(jìn)一步設(shè)置照射光的各種屬性,以確定物體表面反射光的顏色。

            光源及其反射光線的各種屬性可利用D3DLIGHT9結(jié)構(gòu)體來進(jìn)行設(shè)置,下面是該結(jié)構(gòu)體的具體定義:

            Defines a set of lighting properties.

            typedef struct D3DLIGHT9 {
            D3DLIGHTTYPE Type;
            D3DCOLORVALUE Diffuse;
            D3DCOLORVALUE Specular;
            D3DCOLORVALUE Ambient;
            D3DVECTOR Position;
            D3DVECTOR Direction;
            float Range;
            float Falloff;
            float Attenuation0;
            float Attenuation1;
            float Attenuation2;
            float Theta;
            float Phi;
            } D3DLIGHT9, *LPD3DLIGHT;

            Members

            Type
            Type of the light source. This value is one of the members of the D3DLIGHTTYPE enumerated type.
            Diffuse
            Diffuse color emitted by the light. This member is a D3DCOLORVALUE structure.
            Specular
            Specular color emitted by the light. This member is a D3DCOLORVALUE structure.
            Ambient
            Ambient color emitted by the light. This member is a D3DCOLORVALUE structure.
            Position
            Position of the light in world space, specified by a D3DVECTOR structure. This member has no meaning for directional lights and is ignored in that case.
            Direction
            Direction that the light is pointing in world space, specified by a D3DVECTOR structure. This member has meaning only for directional and spotlights. This vector need not be normalized, but it should have a nonzero length.
            Range
            Distance beyond which the light has no effect. The maximum allowable value for this member is the square root of FLT_MAX. This member does not affect directional lights.
            Falloff

            Decrease in illumination between a spotlight's inner cone (the angle specified by Theta) and the outer edge of the outer cone (the angle specified by Phi).

            The effect of falloff on the lighting is subtle. Furthermore, a small performance penalty is incurred by shaping the falloff curve. For these reasons, most developers set this value to 1.0.
             
            Attenuation0
            Value specifying how the light intensity changes over distance. Attenuation values are ignored for directional lights. This member represents an attenuation constant. For information about attenuation, see Light Properties (Direct3D 9). Valid values for this member range from 0.0 to infinity. For non-directional lights, all three attenuation values should not be set to 0.0 at the same time.
            Attenuation1
            Value specifying how the light intensity changes over distance. Attenuation values are ignored for directional lights. This member represents an attenuation constant. For information about attenuation, see Light Properties (Direct3D 9). Valid values for this member range from 0.0 to infinity. For non-directional lights, all three attenuation values should not be set to 0.0 at the same time.
            Attenuation2
            Value specifying how the light intensity changes over distance. Attenuation values are ignored for directional lights. This member represents an attenuation constant. For information about attenuation, see Light Properties (Direct3D 9). Valid values for this member range from 0.0 to infinity. For non-directional lights, all three attenuation values should not be set to 0.0 at the same time.
            Theta
            Angle, in radians, of a spotlight's inner cone - that is, the fully illuminated spotlight cone. This value must be in the range from 0 through the value specified by Phi.
            Phi
            Angle, in radians, defining the outer edge of the spotlight's outer cone. Points outside this cone are not lit by the spotlight. This value must be between 0 and pi.


            光源參數(shù)設(shè)置完畢,還需要利用IDirect3DDevice9接口的 SetLight函數(shù)將光源設(shè)置到渲染管道流水線中。

            Assigns a set of lighting properties for this device.

            HRESULT SetLight(
            DWORD Index,
            CONST D3DLight9 * pLight
            );

            Parameters

            Index
            [in] Zero-based index of the set of lighting properties to set. If a set of lighting properties exists at this index, it is overwritten by the new properties specified in pLight.
            pLight
            [in] Pointer to a D3DLIGHT9 structure, containing the lighting parameters to set.

            Return Values

            If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

            Remarks

            Set light properties by preparing a D3DLIGHT9 structure and then calling the IDirect3DDevice9::SetLight method. The IDirect3DDevice9::SetLight method accepts the index at which the device should place the set of light properties to its internal list of light properties, and the address of a prepared D3DLIGHT9 structure that defines those properties. You can call IDirect3DDevice9::SetLight with new information as needed to update the light's illumination properties.

            The system allocates memory to accommodate a set of lighting properties each time you call the IDirect3DDevice9::SetLight method with an index that has never been assigned properties. Applications can set a number of lights, with only a subset of the assigned lights enabled at a time. Check the MaxActiveLights member of the D3DCAPS9 structure when you retrieve device capabilities to determine the maximum number of active lights supported by that device. If you no longer need a light, you can disable it or overwrite it with a new set of light properties.

            The following example prepares and sets properties for a white point-light whose emitted light will not attenuate over distance.

            // Assume d3dDevice is a valid pointer to an IDirect3DDevice9 interface.
            D3DLight9 d3dLight;
            HRESULT hr;

            // Initialize the structure.
            ZeroMemory(&D3dLight, sizeof(d3dLight));

            // Set up a white point light.
            d3dLight.Type = D3DLIGHT_POINT;
            d3dLight.Diffuse.r = 1.0f;
            d3dLight.Diffuse.g = 1.0f;
            d3dLight.Diffuse.b = 1.0f;
            d3dLight.Ambient.r = 1.0f;
            d3dLight.Ambient.g = 1.0f;
            d3dLight.Ambient.b = 1.0f;
            d3dLight.Specular.r = 1.0f;
            d3dLight.Specular.g = 1.0f;
            d3dLight.Specular.b = 1.0f;

            // Position it high in the scene and behind the user.
            // Remember, these coordinates are in world space, so
            // the user could be anywhere in world space, too.
            // For the purposes of this example, assume the user
            // is at the origin of world space.
            d3dLight.Position.x = 0.0f;
            d3dLight.Position.y = 1000.0f;
            d3dLight.Position.z = -100.0f;

            // Don't attenuate.
            d3dLight.Attenuation0 = 1.0f;
            d3dLight.Range = 1000.0f;

            // Set the property information for the first light.
            hr = d3dDevice->SetLight(0, &d3dLight);
            if (SUCCEEDED(hr))
            // Handle Success
            else
            // Handle failure

            Enable a light source by calling the IDirect3DDevice9::LightEnable method for the device.


            將光源設(shè)置給渲染管道流水線后,還需要利用IDirect3DDevice9接口的LightEnable函數(shù)開啟該光源,否則渲染管道流水線將不會(huì)采用該光源的參數(shù)進(jìn)行光照處理。

            Enables or disables a set of lighting parameters within a device.

            HRESULT LightEnable(
            DWORD LightIndex,
            BOOL bEnable
            );
            LightIndex
            [in] Zero-based index of the set of lighting parameters that are the target of this method.
            bEnable
            [in] Value that indicates if the set of lighting parameters are being enabled or disabled. Set this parameter to TRUE to enable lighting with the parameters at the specified index, or FALSE to disable it.

            If the method succeeds, the return value is D3D_OK. If the method fails, the return value can be D3DERR_INVALIDCALL.

            If a value for LightIndex is outside the range of the light property sets assigned within the device, the IDirect3DDevice9::LightEnable method creates a light source represented by a D3DLIGHT9 structure with the following properties and sets its enabled state to the value specified in bEnable.
             

            Member Default
            Type D3DLIGHT_DIRECTIONAL
            Diffuse (R:1, G:1, B:1, A:0)
            Specular (R:0, G:0, B:0, A:0)
            Ambient (R:0, G:0, B:0, A:0)
            Position (0, 0, 0)
            Direction (0, 0, 1)
            Range 0
            Falloff 0
            Attenuation0 0
            Attenuation1 0
            Attenuation2 0
            Theta 0
            Phi 0

            當(dāng)光源設(shè)置和開啟后,就需要調(diào)用IDirect3DDevice9接口的SetRenderState函數(shù)打開渲染管道流水線的光照開關(guān)。這樣,渲染管道流水線才會(huì)真正執(zhí)行光照流程處理。

            材質(zhì)設(shè)置

            物體受到光照而呈現(xiàn)出的表面顏色,一方面是照射光源的屬性來決定,另一方面則取決于物體對(duì)光的反射屬性和物體自身的表面顏色,即由物體的材質(zhì)屬性來決定。

            物體的材質(zhì)屬性可用D3DMATERIAL9結(jié)構(gòu)體進(jìn)行設(shè)置:

            Specifies material properties.

            typedef struct D3DMATERIAL9 {
            D3DCOLORVALUE Diffuse;
            D3DCOLORVALUE Ambient;
            D3DCOLORVALUE Specular;
            D3DCOLORVALUE Emissive;
            float Power;
            } D3DMATERIAL9, *LPD3DMATERIAL9;

            Members

            Diffuse
            Value specifying the diffuse color of the material. See D3DCOLORVALUE.
            Ambient
            Value specifying the ambient color of the material. See D3DCOLORVALUE.
            Specular
            Value specifying the specular color of the material. See D3DCOLORVALUE.
            Emissive
            Value specifying the emissive color of the material. See D3DCOLORVALUE.
            Power
            Floating-point value specifying the sharpness of specular highlights. The higher the value, the sharper the highlight.

            Remarks

            To turn off specular highlights, set D3DRS_SPECULARENABLE to FALSE, using D3DRENDERSTATETYPE. This is the fastest option because no specular highlights will be calculated.

            For more information about using the lighting engine to calculate specular lighting, see Specular Lighting (Direct3D 9).

            當(dāng)材質(zhì)結(jié)構(gòu)體填充以后,就可以利用IDirect3DDevice9接口的SetMaterial函數(shù)設(shè)置渲染管道流水線進(jìn)行物體表面渲染時(shí)所應(yīng)采用的材質(zhì)參數(shù)。

            Sets the material properties for the device.

            HRESULT SetMaterial(
            CONST D3DMATERIAL9 * pMaterial
            );

            Parameters

            pMaterial
            [in] Pointer to a D3DMATERIAL9 structure, describing the material properties to set.

            Return Values

            If the method succeeds, the return value is D3D_OK. D3DERR_INVALIDCALL if the pMaterial parameter is invalid.

            頂點(diǎn)的法向量

            三維場(chǎng)景物體的渲染歸結(jié)為各個(gè)剖分三角形面的渲染,每個(gè)三角形面的頂點(diǎn)坐標(biāo)值用來確定三維物體的空間形態(tài),而頂點(diǎn)的顏色值則可根據(jù)某種插值方法而計(jì)算出物體表面各個(gè)像素的顏色值。

            在光源光的照射下,頂點(diǎn)的顏色值由光的入射方向與頂點(diǎn)的法向量的夾角來決定。為此,三維物體的光照處理必須提供頂點(diǎn)的坐標(biāo)和法向量的坐標(biāo)值,這樣渲染管道流水線執(zhí)行到光照流程這一步時(shí),就可取出頂點(diǎn)的法向量坐標(biāo)值來計(jì)算頂點(diǎn)的實(shí)際光照顏色。

            如下圖所示:每個(gè)頂點(diǎn)都有一個(gè)法線指向特定的方向,根據(jù)光線與法線之間的角度來確定光線如何在多邊形面上反彈以及如何進(jìn)行陰影計(jì)算。



            頂點(diǎn)往往是鄰接三角形面的公共交點(diǎn),它的法向量可取為這些鄰接三角形面的法向量的一個(gè)平均向量,如此渲染出來頂點(diǎn)附近的表面顏色值將會(huì)是均勻變化的。如果頂點(diǎn)法向量直接取為某個(gè)所在三角形面的法向量,那么各個(gè)面的顏色將會(huì)互不相同。

            無論頂點(diǎn)法向量采用三角形面的法向量,還是鄰接三角形面法向量的平均,都需要利用已知的三個(gè)頂點(diǎn)坐標(biāo),計(jì)算出三個(gè)頂點(diǎn)所在平面的法向量。
             



            好了,我們現(xiàn)在來看看具體的編碼。

            需要在工程中設(shè)置鏈接d3dx9.lib d3d9.lib dxguid.lib dinput8.lib winmm.lib。
            由于文件中用到了GE_APP和GE_INPUT這兩個(gè)類,它們的具體使用說明請(qǐng)參閱 主窗口和DirectInput的封裝。
            同時(shí)用到了GE_TIMER這個(gè)類,具體請(qǐng)參閱
            游戲中時(shí)間的封裝。

            若發(fā)現(xiàn)代碼中存在錯(cuò)誤,敬請(qǐng)指出。

            源碼下載

            LightMaterial.h的定義:
             
            /*************************************************************************************
             [Include File]

             PURPOSE: 
                Define for light and meterial.
            *************************************************************************************/


            #ifndef LIGHT_MATERIAL_H
            #define LIGHT_MATERIAL_H

            struct CUSTOM_VERTEX
            {
                
            float x, y, z;
                
            float nx, ny, nz;
            };

            #define CUSTOM_VERTEX_FVF (D3DFVF_XYZ | D3DFVF_NORMAL)

            class LIGHT_MATERIAL
            {
            private:
                IDirect3D9* _d3d;
                IDirect3DDevice9* _d3d_device;
                IDirect3DVertexBuffer9* _vertex_buffer;    

            public:
                LIGHT_MATERIAL();
                ~LIGHT_MATERIAL();
                
            bool Create_D3D_Device(HWND hwnd, bool full_screen = true);
                
            bool Init_Vertex_Buffer();
                
            void Compute_Triangle_Normal(D3DXVECTOR3& v1, D3DXVECTOR3& v2, D3DXVECTOR3& v3, D3DVECTOR& normal);
                
            void Set_Camera();
                
            void Set_Point_Light(D3DCOLORVALUE& dif, D3DCOLORVALUE& amb, D3DCOLORVALUE& spe, D3DVECTOR& pos);

                
            void Set_Object_Material(D3DCOLORVALUE& dif, D3DCOLORVALUE& amb, D3DCOLORVALUE& spe,
                                         D3DCOLORVALUE& emi, 
            float power);

                
            void Render();
                
                
            void Release_COM_Object();
            };

            #endif


            LightMaterial.cpp的定義:

            /*************************************************************************************
             [Implement File]

             PURPOSE: 
                Define for light and meterial.
            *************************************************************************************/


            #include "GE_COMMON.h"
            #include "LightMaterial.h"

            #define WINDOW_WIDTH    800
            #define WINDOW_HEIGHT   600

            //------------------------------------------------------------------------------------
            // Constructor, do nothing.
            //------------------------------------------------------------------------------------
            LIGHT_MATERIAL::LIGHT_MATERIAL()
            {
            }

            //------------------------------------------------------------------------------------
            // Release all com object.
            //------------------------------------------------------------------------------------
            LIGHT_MATERIAL::~LIGHT_MATERIAL()
            {
                Release_COM_Object();
            }

            //------------------------------------------------------------------------------------
            // Create direct3D interface and direct3D device.
            //------------------------------------------------------------------------------------
            bool LIGHT_MATERIAL::Create_D3D_Device(HWND hwnd, bool full_screen)
            {
                
            // Create a IDirect3D9 object and returns an interace to it.
                _d3d = Direct3DCreate9(D3D_SDK_VERSION);
                
            if(_d3d == NULL)
                    
            return false;

                
            // retrieve adapter capability
                D3DCAPS9 d3d_caps;    
                _d3d->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &d3d_caps);
                
                
            bool hardware_process_enable = (d3d_caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ? true : false);

                
            // Retrieves the current display mode of the adapter.
                D3DDISPLAYMODE display_mode;
                
            if(FAILED(_d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &display_mode)))
                    
            return false;

                
            // set present parameter for direct3D device
                D3DPRESENT_PARAMETERS present_param = {0};

                present_param.BackBufferWidth      = WINDOW_WIDTH;
                present_param.BackBufferHeight     = WINDOW_HEIGHT;
                present_param.BackBufferFormat     = display_mode.Format;
                present_param.BackBufferCount      = 1;
                present_param.hDeviceWindow        = hwnd;
                present_param.Windowed             = !full_screen;
                present_param.SwapEffect           = D3DSWAPEFFECT_FLIP;
                present_param.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;

                
            // Creates a device to represent the display adapter.
                DWORD behavior_flags;

                behavior_flags = hardware_process_enable ? 
            D3DCREATE_HARDWARE_VERTEXPROCESSING : D3DCREATE_SOFTWARE_VERTEXPROCESSING;

                
            if(FAILED(_d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, behavior_flags, 
                                             &present_param, &_d3d_device)))
                {
                    
            return false;
                }
                
                
            // create successfully
                return true;
            }

            //------------------------------------------------------------------------------------
            // Initialize vertex buffer.
            //------------------------------------------------------------------------------------
            bool LIGHT_MATERIAL::Init_Vertex_Buffer()
            {
                CUSTOM_VERTEX custom_vertex[12] = {0};

                D3DXVECTOR3 v[]={
                    D3DXVECTOR3(5.0f, 6.0f, 5.0f),    
            // left triangle
                    D3DXVECTOR3(6.0f, 0.0f, 3.0f),
                    D3DXVECTOR3(1.0f, 0.0f, 7.0f),  
                    D3DXVECTOR3(5.0f, 6.0f, 5.0f),    
            // right triangle
                    D3DXVECTOR3(10.0f, 0.0f, 8.0f),
                    D3DXVECTOR3(6.0f, 0.0f, 3.0f), 
                    D3DXVECTOR3(5.0f, 6.0f, 5.0f),    
            // back triangle
                    D3DXVECTOR3(1.0f, 0.0f, 7.0f),
                    D3DXVECTOR3(10.0f, 0.0f, 8.0f),
                    D3DXVECTOR3(1.0f, 0.0f, 7.0f),    
            // bottom triangle
                    D3DXVECTOR3(6.0f, 0.0f, 3.0f),
                    D3DXVECTOR3(10.0f, 0.0f, 8.0f)
                };

                D3DVECTOR normal;

                
            // compute all triangle normal
                for(int i = 0; i < 12; i += 3)
                {
                    
            // compute current triangle's normal
                    Compute_Triangle_Normal(v[i], v[i+1], v[i+2], normal);

                    
            // assign current vertex coordinate and current triangle normal to custom vertex array
                    for(int j = 0; j < 3; j++)
                    {
                        
            int k = i + j;

                        custom_vertex[k].x  = v[k].x;
                        custom_vertex[k].y  = v[k].y;
                        custom_vertex[k].z  = v[k].z;
                        custom_vertex[k].nx = normal.x;
                        custom_vertex[k].ny = normal.y;
                        custom_vertex[k].nz = normal.z;
                    }
                }

                BYTE* vertex_data;

                
            // create vertex buffer
                if(FAILED(_d3d_device->CreateVertexBuffer(12 * sizeof(CUSTOM_VERTEX), 0, CUSTOM_VERTEX_FVF,
                                        D3DPOOL_DEFAULT, &_vertex_buffer, NULL)))
                {
                    
            return false;
                }

                
            // get data pointer to vertex buffer
                if(FAILED(_vertex_buffer->Lock(0, 0, (void **) &vertex_data, 0)))
                    
            return false;

                
            // copy custom vertex data into vertex buffer
                memcpy(vertex_data, custom_vertex, sizeof(custom_vertex));

                
            // unlock vertex buffer
                _vertex_buffer->Unlock();

                
            return true;
            }  

            //------------------------------------------------------------------------------------
            // Set camera position.
            //------------------------------------------------------------------------------------
            void LIGHT_MATERIAL::Set_Camera()
            {
                D3DXVECTOR3 eye(-6.0, 1.5, 10.0);
                D3DXVECTOR3 at(6.0, 2.0, 3.0);
                D3DXVECTOR3 up(0.0, 1.0, 0.0);

                D3DXMATRIX view_matrix;

                
            // Builds a left-handed, look-at matrix.
                D3DXMatrixLookAtLH(&view_matrix, &eye, &at, &up);

                
            // Sets d3d device view transformation state.
                _d3d_device->SetTransform(D3DTS_VIEW, &view_matrix);

                D3DXMATRIX proj_matrix;

                
            // Builds a left-handed perspective projection matrix based on a field of view.
                D3DXMatrixPerspectiveFovLH(&proj_matrix, D3DX_PI/2, 800/600, 1.0, 1000.0);
                
                
            // Sets d3d device projection transformation state.
                _d3d_device->SetTransform(D3DTS_PROJECTION, &proj_matrix);
                
            // enable automatic normalization of vertex normals
                _d3d_device->SetRenderState(D3DRS_NORMALIZENORMALS, true);
            }

            //------------------------------------------------------------------------------------
            // Set point light.
            //------------------------------------------------------------------------------------
            void LIGHT_MATERIAL::Set_Point_Light(D3DCOLORVALUE& dif, D3DCOLORVALUE& amb, D3DCOLORVALUE& spe, D3DVECTOR& pos)
            {
                D3DLIGHT9 light;

                
            // clear memory with 0
                ZeroMemory(&light, sizeof(D3DLIGHT9));

                light.Type          = D3DLIGHT_POINT;
                light.Diffuse       = dif;
                light.Ambient       = amb;
                light.Specular      = spe;
                light.Position      = pos;
                light.Attenuation0  = 1.0;
                light.Attenuation1  = 0.0;
                light.Attenuation2  = 0.0;
                light.Range         = 1000.0;

                
            // Assigns point lighting properties for this device
                _d3d_device->SetLight(0, &light);
                
            // enable point light
                _d3d_device->LightEnable(0, TRUE);
                
            // enable light 
                _d3d_device->SetRenderState(D3DRS_LIGHTING, TRUE);
                
            // add ambient light
                _d3d_device->SetRenderState(D3DRS_AMBIENT, D3DCOLOR_XRGB(50, 50, 50));
            }

            //------------------------------------------------------------------------------------
            // Sets the material properties for the device.
            //------------------------------------------------------------------------------------
            void LIGHT_MATERIAL::Set_Object_Material(D3DCOLORVALUE& dif, D3DCOLORVALUE& amb, D3DCOLORVALUE& spe, 
                                                     D3DCOLORVALUE& emi, 
            float power)
            {
                D3DMATERIAL9 material;

                material.Diffuse  = dif;
                material.Ambient  = amb;
                material.Specular = spe;
                material.Emissive = emi;
                material.Power    = power;

                
            // Sets the material properties for the device.
                _d3d_device->SetMaterial(&material);
            }

            //------------------------------------------------------------------------------------
            // Compute triangle normal.
            //------------------------------------------------------------------------------------
            void LIGHT_MATERIAL::Compute_Triangle_Normal(D3DXVECTOR3& v1, D3DXVECTOR3& v2, D3DXVECTOR3& v3, D3DVECTOR& normal)
            {
                D3DXVECTOR3 vec1 = v1 - v2;
                D3DXVECTOR3 vec2 = v1 - v3;
                D3DXVECTOR3 normal_vec;

                D3DXVec3Cross(&normal_vec, &vec1, &vec2);
                D3DXVec3Normalize(&normal_vec, &normal_vec);

                normal = (D3DVECTOR) normal_vec;
            }

            //------------------------------------------------------------------------------------
            // Render object.
            //------------------------------------------------------------------------------------
            void LIGHT_MATERIAL::Render()
            {
                
            if(_d3d_device == NULL)
                    
            return;

                
            // clear surface with black
                _d3d_device->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0, 0);

                
            // begin scene
                _d3d_device->BeginScene();

                
            // Binds a vertex buffer to a device data stream.
                _d3d_device->SetStreamSource(0, _vertex_buffer, 0, sizeof(CUSTOM_VERTEX));

                
            // Sets the current vertex stream declaration.
                _d3d_device->SetFVF(CUSTOM_VERTEX_FVF);

                
            // Renders a sequence of nonindexed, geometric primitives of the specified type from the current 
                // set of data input streams.
                _d3d_device->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 4);

                
            // end scene
                _d3d_device->EndScene();

                
            // Presents the contents of the next buffer in the sequence of back buffers owned by the device.
                _d3d_device->Present(NULL, NULL, NULL, NULL);
            }

            //------------------------------------------------------------------------------------
            // Release vertex buffer, D3D device, D3D.
            //------------------------------------------------------------------------------------
            void LIGHT_MATERIAL::Release_COM_Object()
            {
                Safe_Release(_vertex_buffer);
                Safe_Release(_d3d_device);
                Safe_Release(_d3d);
            }

            再編寫個(gè)測(cè)試用例,main.cpp的定義如下所示:
             
            /*************************************************************************************
             [Implement File]

             PURPOSE: 
                Test for material and lighting.
            *************************************************************************************/


            #define DIRECTINPUT_VERSION 0x0800

            #include "GE_APP.h"
            #include "GE_INPUT.h"
            #include "GE_TIMER.h"
            #include "LightMaterial.h"

            #pragma warning(disable : 4305 4996)

            int WINAPI WinMain(HINSTANCE instance, HINSTANCE, LPSTR cmd_line, int cmd_show)
            {
                GE_APP ge_app;
                GE_INPUT ge_input;
                GE_TIMER ge_timer;
                LIGHT_MATERIAL light_material;

                MSG msg = {0};
                
            float last_time = 0;

                
            // set for material property
                D3DCOLORVALUE material_dif = {1.0f, 1.0f, 1.0f, 1.0f}; 
                D3DCOLORVALUE material_amb = {1.0f, 1.0f, 1.0f, 1.0f};
                D3DCOLORVALUE material_spe = {1.0f, 0.0f, 0.0f, 1.0f};
                D3DCOLORVALUE material_emi = {0.0f, 0.0f, 1.0f, 1.0f};

                
            // set for light property
                D3DCOLORVALUE light_dif = {1.0f, 0.0f, 0.0f, 1.0f}; 
                D3DCOLORVALUE light_amb = {0.0f, 0.7f, 0.0f, 1.0f};
                D3DCOLORVALUE light_spe = {0.0f, 0.0f, 0.0f, 0.0f};
                D3DVECTOR light_pos = {5.0f, 6.0f, -20.0f};

                
            // create window
                if(! ge_app.Create_Window("Material and light test", instance, cmd_show))
                    
            return false;

                HWND hwnd = ge_app.Get_Window_Handle();

                
            // create directinput
                ge_input.Create_Input(instance, hwnd);

                SetWindowPos(hwnd, 0, 0,0,0,0, SWP_NOSIZE);
                SetCursorPos(0, 0);

                
            // initialize game time
                ge_timer.Init_Game_Time();

                
            // Create direct3D interface and direct3D device.
                if(! light_material.Create_D3D_Device(hwnd, false))
                    
            return false;

                
            // Initialize vertex buffer with curstom vertex structure.
                if(! light_material.Init_Vertex_Buffer())
                    
            return false;

                
            // set camera position
                light_material.Set_Camera();

                
            // Sets the material properties for the device.
                light_material.Set_Object_Material(material_dif, material_amb, material_spe, material_emi, 0);

                
            // set point light
                light_material.Set_Point_Light(light_dif, light_amb, light_spe, light_pos);

                
            // render object
                light_material.Render();

                
            while(msg.message != WM_QUIT)
                {
                    
            if(PeekMessage(&msg, NULL, 0,0 , PM_REMOVE))
                    {
                        TranslateMessage(&msg);
                        DispatchMessage(&msg);
                    }
                    
            else
                    {
                        
            // read data from keyboard buffer
                        if(ge_input.Read_Keyboard())
                        {
                            
            // press "ESC", close window.
                            if(ge_input.Is_Key_Pressed(DIK_ESCAPE))
                                PostQuitMessage(0);
                        }   
                        
                        
            // If it is time to render, reset point light property and render it.
                        if((ge_timer.Get_Game_Play_Time() - last_time) > 70)
                        {
                            
            if(light_amb.r < 1.0f)
                                light_amb.r += 0.001f;
                            
            else
                                light_amb.r = 0.0f;

                            
            if(light_amb.g < 1.0f)
                                light_amb.g += 0.02f;
                            
            else
                                light_amb.g = 0.0f;

                            
            if(light_amb.b < 1.0f)
                                light_amb.b += 0.03f;
                            
            else
                                light_amb.b = 0.0f;

                            
            // reset point light
                            light_material.Set_Point_Light(light_dif, light_amb, light_spe, light_pos);

                            
            // render object
                            light_material.Render();
                            
                            
            // update last render time
                            last_time = ge_timer.Get_Game_Play_Time();
                        }
                    }
                }    

                UnregisterClass(WINDOW_CLASS_NAME, instance);

                
            return true;
            }
             

            該函數(shù)為了每隔一段時(shí)間改變?nèi)忮F的光照顏色,調(diào)用時(shí)鐘的Get_Game_Play_Time函數(shù)計(jì)算時(shí)間差,然后將頂點(diǎn)坐標(biāo)和頂點(diǎn)法向量坐標(biāo)倒入渲染管道流水線,架設(shè)攝影機(jī)進(jìn)行取景,設(shè)置光源和三棱錐的材質(zhì)屬性。最后,在定時(shí)器計(jì)算出的一幀時(shí)間內(nèi),改變光源的顏色屬性,完成每一幀的渲染。

            輸出效果:


             

            posted on 2007-05-12 23:28 lovedday 閱讀(2965) 評(píng)論(0)  編輯 收藏 引用 所屬分類: ■ DirectX 9 Program

            公告

            導(dǎo)航

            統(tǒng)計(jì)

            常用鏈接

            隨筆分類(178)

            3D游戲編程相關(guān)鏈接

            搜索

            最新評(píng)論

            久久久久国产精品嫩草影院| 91麻豆精品国产91久久久久久| 97久久精品国产精品青草| 欧美亚洲国产精品久久| 国产999精品久久久久久| 俺来也俺去啦久久综合网| 欧美亚洲国产精品久久久久| 亚洲国产成人久久一区久久| 99久久国产热无码精品免费久久久久 | 国产69精品久久久久777| 国产成人无码精品久久久性色 | 丰满少妇人妻久久久久久| 亚洲精品乱码久久久久久按摩| 一本综合久久国产二区| 一本一本久久a久久精品综合麻豆| 亚洲Av无码国产情品久久| 狠狠色综合久久久久尤物| 国内精品伊人久久久久影院对白| 91久久精品国产免费直播| 国产成人久久久精品二区三区| 国产精品伦理久久久久久| 国产高潮国产高潮久久久91| 国产精品内射久久久久欢欢| 狠狠人妻久久久久久综合蜜桃| 亚洲国产综合久久天堂| 久久久久久精品久久久久| 色偷偷偷久久伊人大杳蕉| 99久久国产综合精品麻豆| 久久九九全国免费| 久久久受www免费人成| 狠狠色丁香久久婷婷综合图片| 精品久久久久久久国产潘金莲| 久久久久亚洲av无码专区喷水| 国产精品久久久久久搜索| 国内精品久久久久久中文字幕| 亚洲精品国产自在久久| 久久亚洲精品成人AV| 伊人久久大香线蕉精品| 久久午夜夜伦鲁鲁片免费无码影视| 亚洲AV无码1区2区久久| 91久久国产视频|