Use lights to draw polygons

Page update date :
Page creation date :

summary

Lights (light sources) are used to shade the polygons.

ライトを使用してポリゴンを描画する

Operating environment

Prerequisites

Supported XNA Versions
  • 4.0
Supported Platforms
  • Windows (XP SP2 or later, Vista, 7)
  • Xbox 360
  • Windows Phone 7
Windows Required Vertex Shader Version 2.0
Windows Required Pixel Shader Version 2.01

Operating environment

platform
  • Windows 7
  • Xbox 360
  • Windows Phone 7 Emulator

substance

About Lights

Here are a few things you can do about using the lights.

material

In simple terms, a material is the color of a substance. Materials are often used in conjunction with Lights, and BasicEffects also allow you to set material and light parameters. However, this does not apply if you are writing your own shader program, and you can adjust it freely. Also, note that the color of the material is different from the color of the vertices.

Materials generally have the following items.

Diffuse Basic colors of substances
Ambient The color of the color when exposed to ambient light (visible even if the light does not shine directly on it)
Specular Specular reflection light (glows strongly like the gloss of a car, etc.)
SpecularPower Reflective Strength (Specular Strength)
Emissive Divergent light (glows on its own)

Lights and Normals

If you want to use a light, you will need something called a "normal". The position of the light in relation to the normal determines the brightness of the object. The normal will be set as vertex data.

面の方向と明るさ

It is brighter if the face is facing the direction of the light, and darker if it is the other way around. This is also true if you replace the direction of the face with a vertex. The orientation of these faces and vertices is called the "normal".

Now, the direction of the normals is not explicitly defined, and there are two main normals to set in the box: below.

面の方向と明るさ

There is a difference between the left and the right when the light is applied.

In the case of the method on the left, the space between the faces will appear angular. This is because it is completely oriented in the same direction as the normal of the face. However, this method has the disadvantage that vertices cannot be shared.

With the method on the right, the space between the surfaces will appear slightly rounded depending on how the light is applied. Since vertices are shared, there is an advantage that the amount of data is reduced. The disadvantage is that the normal of the vertex is not the same as the direction of the face, so even if the light is shined directly from above, for example, the upper surface will not be 100% affected by the light.

It's hard to understand even if you explain it in a sentence, so check the diagram below to see the difference.

面の方向と明るさ面の方向と明るさ
It is displayed with modeling software called Metasequoia

You can see that it is quite different in appearance. In the sample, we'll create the box in the right way so that the code isn't redundant.

field

/// <summary>
/// 基本エフェクト
/// </summary>
private BasicEffect basicEffect = null;

/// <summary>
/// 頂点バッファ
/// </summary>
private VertexBuffer vertexBuffer = null;

/// <summary>
/// インデックスバッファ
/// </summary>
private IndexBuffer indexBuffer = null;

/// <summary>
/// インデックスバッファの各頂点番号配列
/// </summary>
private static readonly Int16[] vertexIndices = new Int16[] {
    2, 0, 1, 1, 3, 2, 4, 0, 2, 2, 6, 4, 5, 1, 0, 0, 4, 5,
    7, 3, 1, 1, 5, 7, 6, 2, 3, 3, 7, 6, 4, 6, 7, 7, 5, 4 };

The box is created using a vertex buffer and an index buffer.

creation

// エフェクトを作成
this.basicEffect = new BasicEffect(this.GraphicsDevice);

// エフェクトでライトを有効にする
this.basicEffect.LightingEnabled = true;

// デフォルトのライトの設定を使用する
this.basicEffect.EnableDefaultLighting();

// スペキュラーを無効
this.basicEffect.SpecularColor = Vector3.Zero;

// 2番目と3番目のライトを無効
this.basicEffect.DirectionalLight1.Enabled = false;
this.basicEffect.DirectionalLight2.Enabled = false;

There are several items in the BasicEffect that set the light.

First, set the LightingEnabled property to true to instruct the light to be calculated.

When you call the EnableDefaultLighting method, the color of the light or material is automatically set. However, using the default light on this box is too bright, so I disabled the specular color and disabled the second and third lights.

// 頂点の数
int vertexCount = 8;

// 頂点バッファ作成
this.vertexBuffer = new VertexBuffer(this.GraphicsDevice,
    typeof(VertexPositionNormalTexture), vertexCount, BufferUsage.None);

// 頂点データを作成する
VertexPositionNormalTexture[] vertives = new VertexPositionNormalTexture[vertexCount];

vertives[0] = new VertexPositionNormalTexture(
    new Vector3(-2.0f, 2.0f, -2.0f),
    Vector3.Normalize(new Vector3(-1.0f, 1.0f, -1.0f)),
    Vector2.Zero);
vertives[1] = new VertexPositionNormalTexture(
    new Vector3(2.0f, 2.0f, -2.0f),
    Vector3.Normalize(new Vector3(1.0f, 1.0f, -1.0f)),
    Vector2.Zero);
vertives[2] = new VertexPositionNormalTexture(
    new Vector3(-2.0f, 2.0f, 2.0f),
    Vector3.Normalize(new Vector3(-1.0f, 1.0f, 1.0f)),
    Vector2.Zero);
vertives[3] = new VertexPositionNormalTexture(
    new Vector3(2.0f, 2.0f, 2.0f),
    Vector3.Normalize(new Vector3(1.0f, 1.0f, 1.0f)),
    Vector2.Zero);
vertives[4] = new VertexPositionNormalTexture(
    new Vector3(-2.0f, -2.0f, -2.0f),
    Vector3.Normalize(new Vector3(-1.0f, -1.0f, -1.0f)),
    Vector2.Zero);
vertives[5] = new VertexPositionNormalTexture(
    new Vector3(2.0f, -2.0f, -2.0f),
    Vector3.Normalize(new Vector3(1.0f, -1.0f, -1.0f)),
    Vector2.Zero);
vertives[6] = new VertexPositionNormalTexture(
    new Vector3(-2.0f, -2.0f, 2.0f),
    Vector3.Normalize(new Vector3(-1.0f, -1.0f, 1.0f)),
    Vector2.Zero);
vertives[7] = new VertexPositionNormalTexture(
    new Vector3(2.0f, -2.0f, 2.0f),
    Vector3.Normalize(new Vector3(1.0f, -1.0f, 1.0f)),
    Vector2.Zero);

// 頂点データを頂点バッファに書き込む
this.vertexBuffer.SetData(vertives);

It's a bit of a long piece of code, but it creates vertex data. The vertex data structure used this time is "VertexPositionNormalTexture" with "position", "normal", and "texture coordinates" data. Since the XNA Framework does not provide a structure with only "position" and "normal", "Vector2.Zero" is specified for all vertices for texture coordinates. (Of course, if you understand, you can make your own structure.)

As for the normal, as shown in the previous figure, it is set to point in an oblique direction. Since normals are data definitions that are represented only by orientation, the direction is specified and then normalized with the Vector3.Normalize method.

VertexPositionNormalTexture constructor

Create an instance of the structure "VertexPositionNormalTexture" with vertex data for the position and normal and texture coordinates.

position Vector3 Vertex Position
normal Vector3 Vertex normals
textureCoordinate Vector2 Texture coordinates of vertices

Vector3.Normalize method

Creates a unit vector from the specified vector.

value Vector3 Source vector to normalize
Return Values Vector3 Unit vector
// インデックスバッファを作成
this.indexBuffer = new IndexBuffer(this.GraphicsDevice,
    IndexElementSize.SixteenBits, 3 * 12, BufferUsage.None);

// 頂点インデックスを書き込む
this.indexBuffer.SetData(vertexIndices);

Creating an index buffer is no different.

drawing

// 描画に使用する頂点バッファをセット
this.GraphicsDevice.SetVertexBuffer(this.vertexBuffer);

// インデックスバッファをセット
this.GraphicsDevice.Indices = this.indexBuffer;

// パスの数だけ繰り替えし描画
foreach (EffectPass pass in this.basicEffect.CurrentTechnique.Passes)
{
    // パスの開始
    pass.Apply();

    // ボックスを描画する
    this.GraphicsDevice.DrawIndexedPrimitives(
        PrimitiveType.TriangleList,
        0,
        0,
        8,
        0,
        12
    );
}

Since the vertex information is set in advance, there is nothing special about the drawing code.

All Codes

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
#if WINDOWS_PHONE
using Microsoft.Xna.Framework.Input.Touch;
#endif

namespace BoxReceivedLight
{
    /// <summary>
    /// ゲームメインクラス
    /// </summary>
    public class GameMain : Microsoft.Xna.Framework.Game
    {
        /// <summary>
        /// グラフィックデバイス管理クラス
        /// </summary>
        private GraphicsDeviceManager graphics = null;

        /// <summary>
        /// スプライトのバッチ化クラス
        /// </summary>
        private SpriteBatch spriteBatch = null;

        /// <summary>
        /// 基本エフェクト
        /// </summary>
        private BasicEffect basicEffect = null;

        /// <summary>
        /// 頂点バッファ
        /// </summary>
        private VertexBuffer vertexBuffer = null;

        /// <summary>
        /// インデックスバッファ
        /// </summary>
        private IndexBuffer indexBuffer = null;

        /// <summary>
        /// インデックスバッファの各頂点番号配列
        /// </summary>
        private static readonly Int16[] vertexIndices = new Int16[] {
            2, 0, 1, 1, 3, 2, 4, 0, 2, 2, 6, 4, 5, 1, 0, 0, 4, 5,
            7, 3, 1, 1, 5, 7, 6, 2, 3, 3, 7, 6, 4, 6, 7, 7, 5, 4 };


        /// <summary>
        /// GameMain コンストラクタ
        /// </summary>
        public GameMain()
        {
            // グラフィックデバイス管理クラスの作成
            this.graphics = new GraphicsDeviceManager(this);

            // ゲームコンテンツのルートディレクトリを設定
            this.Content.RootDirectory = "Content";

#if WINDOWS_PHONE
            // Windows Phone のデフォルトのフレームレートは 30 FPS
            this.TargetElapsedTime = TimeSpan.FromTicks(333333);

            // バックバッファサイズの設定
            this.graphics.PreferredBackBufferWidth = 480;
            this.graphics.PreferredBackBufferHeight = 800;

            // フルスクリーン表示
            this.graphics.IsFullScreen = true;
#endif
        }

        /// <summary>
        /// ゲームが始まる前の初期化処理を行うメソッド
        /// グラフィック以外のデータの読み込み、コンポーネントの初期化を行う
        /// </summary>
        protected override void Initialize()
        {
            // TODO: ここに初期化ロジックを書いてください

            // コンポーネントの初期化などを行います
            base.Initialize();
        }

        /// <summary>
        /// ゲームが始まるときに一回だけ呼ばれ
        /// すべてのゲームコンテンツを読み込みます
        /// </summary>
        protected override void LoadContent()
        {
            // テクスチャーを描画するためのスプライトバッチクラスを作成します
            this.spriteBatch = new SpriteBatch(this.GraphicsDevice);

            // エフェクトを作成
            this.basicEffect = new BasicEffect(this.GraphicsDevice);

            // エフェクトでライトを有効にする
            this.basicEffect.LightingEnabled = true;

            // デフォルトのライトの設定を使用する
            this.basicEffect.EnableDefaultLighting();

            // スペキュラーを無効
            this.basicEffect.SpecularColor = Vector3.Zero;

            // 2番目と3番目のライトを無効
            this.basicEffect.DirectionalLight1.Enabled = false;
            this.basicEffect.DirectionalLight2.Enabled = false;


            // ビューマトリックスをあらかじめ設定 ((6, 6, 12) から原点を見る)
            this.basicEffect.View = Matrix.CreateLookAt(
                    new Vector3(6.0f, 6.0f, 12.0f),
                    Vector3.Zero,
                    Vector3.Up
                );

            // プロジェクションマトリックスをあらかじめ設定
            this.basicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(
                    MathHelper.ToRadians(45.0f),
                    (float)this.GraphicsDevice.Viewport.Width /
                        (float)this.GraphicsDevice.Viewport.Height,
                    1.0f,
                    100.0f
                );

            // 頂点の数
            int vertexCount = 8;

            // 頂点バッファ作成
            this.vertexBuffer = new VertexBuffer(this.GraphicsDevice,
                typeof(VertexPositionNormalTexture), vertexCount, BufferUsage.None);

            // 頂点データを作成する
            VertexPositionNormalTexture[] vertives = new VertexPositionNormalTexture[vertexCount];

            vertives[0] = new VertexPositionNormalTexture(
                new Vector3(-2.0f, 2.0f, -2.0f),
                Vector3.Normalize(new Vector3(-1.0f, 1.0f, -1.0f)),
                Vector2.Zero);
            vertives[1] = new VertexPositionNormalTexture(
                new Vector3(2.0f, 2.0f, -2.0f),
                Vector3.Normalize(new Vector3(1.0f, 1.0f, -1.0f)),
                Vector2.Zero);
            vertives[2] = new VertexPositionNormalTexture(
                new Vector3(-2.0f, 2.0f, 2.0f),
                Vector3.Normalize(new Vector3(-1.0f, 1.0f, 1.0f)),
                Vector2.Zero);
            vertives[3] = new VertexPositionNormalTexture(
                new Vector3(2.0f, 2.0f, 2.0f),
                Vector3.Normalize(new Vector3(1.0f, 1.0f, 1.0f)),
                Vector2.Zero);
            vertives[4] = new VertexPositionNormalTexture(
                new Vector3(-2.0f, -2.0f, -2.0f),
                Vector3.Normalize(new Vector3(-1.0f, -1.0f, -1.0f)),
                Vector2.Zero);
            vertives[5] = new VertexPositionNormalTexture(
                new Vector3(2.0f, -2.0f, -2.0f),
                Vector3.Normalize(new Vector3(1.0f, -1.0f, -1.0f)),
                Vector2.Zero);
            vertives[6] = new VertexPositionNormalTexture(
                new Vector3(-2.0f, -2.0f, 2.0f),
                Vector3.Normalize(new Vector3(-1.0f, -1.0f, 1.0f)),
                Vector2.Zero);
            vertives[7] = new VertexPositionNormalTexture(
                new Vector3(2.0f, -2.0f, 2.0f),
                Vector3.Normalize(new Vector3(1.0f, -1.0f, 1.0f)),
                Vector2.Zero);

            // 頂点データを頂点バッファに書き込む
            this.vertexBuffer.SetData(vertives);

            // インデックスバッファを作成
            this.indexBuffer = new IndexBuffer(this.GraphicsDevice,
                IndexElementSize.SixteenBits, 3 * 12, BufferUsage.None);

            // 頂点インデックスを書き込む
            this.indexBuffer.SetData(vertexIndices);
        }

        /// <summary>
        /// ゲームが終了するときに一回だけ呼ばれ
        /// すべてのゲームコンテンツをアンロードします
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: ContentManager で管理されていないコンテンツを
            //       ここでアンロードしてください
        }

        /// <summary>
        /// 描画以外のデータ更新等の処理を行うメソッド
        /// 主に入力処理、衝突判定などの物理計算、オーディオの再生など
        /// </summary>
        /// <param name="gameTime">このメソッドが呼ばれたときのゲーム時間</param>
        protected override void Update(GameTime gameTime)
        {
            // Xbox 360 コントローラ、Windows Phone の BACK ボタンを押したときに
            // ゲームを終了させます
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                this.Exit();
            }

            // TODO: ここに更新処理を記述してください

            // 登録された GameComponent を更新する
            base.Update(gameTime);
        }

        /// <summary>
        /// 描画処理を行うメソッド
        /// </summary>
        /// <param name="gameTime">このメソッドが呼ばれたときのゲーム時間</param>
        protected override void Draw(GameTime gameTime)
        {
            // 画面を指定した色でクリアします
            this.GraphicsDevice.Clear(Color.CornflowerBlue);

            // 描画に使用する頂点バッファをセット
            this.GraphicsDevice.SetVertexBuffer(this.vertexBuffer);

            // インデックスバッファをセット
            this.GraphicsDevice.Indices = this.indexBuffer;

            // パスの数だけ繰り替えし描画
            foreach (EffectPass pass in this.basicEffect.CurrentTechnique.Passes)
            {
                // パスの開始
                pass.Apply();

                // ボックスを描画する
                this.GraphicsDevice.DrawIndexedPrimitives(
                    PrimitiveType.TriangleList,
                    0,
                    0,
                    8,
                    0,
                    12
                );
            }

            // 登録された DrawableGameComponent を描画する
            base.Draw(gameTime);
        }
    }
}