Sign in to follow this  

Ambient light not working?

This topic is 3801 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi I'm trying to creat my own engine. Eveerything went well untill scene lighting. It seems that RenderScene.Ambient does not affect the scene. Here's GFX class code
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespace SharpXEngine
{
    class CSharpXGFXEngine
    {
        private Device device;       //Device
        private COnScreenFont Arial20;  //Font to display messages, Arial, 12pt
        private int frames, lastTickCount; //FPS counter vairaibles
        private string fpsText;
        private VertexBuffer vertices;

        public CSharpXGFXEngine(SharpXEngine mainEngine)
        {
            if (!CreateAppWindow(mainEngine)) return;
        }

        public void Render()
        {
            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.DarkCyan, 1.0f, 0);
            device.BeginScene();

            device.RenderState.Ambient = Color.LightGray;

            SetupMatrices();
            SetupLights(); 

            device.SetStreamSource(0, vertices, 0);
            device.DrawPrimitives(PrimitiveType.TriangleList, 0, 12);

            CalculateFrameRate();
            Arial20.DrawText("FPS:"+fpsText, 20, 20, device.RenderState.Ambient);

            device.EndScene();
            device.Present();
        }

        protected void SetupLights()
        {


            // Use a white, directional light coming from over our right shoulder
            device.Lights[0].Diffuse = Color.White;
            device.Lights[0].Type = LightType.Directional;
            device.Lights[0].Direction = new Vector3(-3, -1, 3);
            device.Lights[0].Update(); 
            device.Lights[0].Enabled = true;
        }

        protected void SetupMatrices()
        {
            float angle = Environment.TickCount / 5000.0F;
            device.Transform.World = Matrix.RotationX(angle) *Matrix.RotationY(angle / 2) * Matrix.RotationY(angle / 3);
            device.Transform.View = Matrix.LookAtLH(new Vector3(0, 0.5F, -7),
              new Vector3(0, 0.5F, 0), new Vector3(0, 1, 0));
            device.Transform.Projection =
              Matrix.PerspectiveFovLH((float)Math.PI / 4.0F, 1.0F, 1.0F, 13.25F);
        }

        protected void CalculateFrameRate()
        {
            ++frames;

            int ticks = Environment.TickCount;
            int elapsed = ticks - lastTickCount;
            if (elapsed > 1000)
            {
                fpsText = frames.ToString();
                frames = 0;
                lastTickCount = ticks;
            }
        }

        public void Init()
        {
            //this.TopMost = true;
            Arial20 = new COnScreenFont("Arial", 20, device);

            // Add a little ambient light to the scene
            device.RenderState.Lighting = true; 
            device.RenderState.CullMode = Cull.None;
            //device.RenderState.FillMode = FillMode.WireFrame;

            vertices = CreateVertexBuffer(device);
        }

        /// <summary>
        /// Creates VertexBuffer for Direct3D device
        /// </summary>
        /// <param name="device">Direct3D device for which the buffer is created</param>
        /// <returns>Newly created buffer</returns>
        protected VertexBuffer CreateVertexBuffer(Device device)
        {
            //set vertices format (FVF)
            device.VertexFormat = CustomVertex.PositionNormalColored.Format;

            //create VertexBuffer itself
            VertexBuffer buffer = new VertexBuffer(
                typeof(CustomVertex.PositionNormalColored),
                36,
                device,
                0,
                CustomVertex.PositionNormalColored.Format,
                Pool.Default);

            //create vertices array
            CustomVertex.PositionNormalColored[] vertices = (CustomVertex.PositionNormalColored[])buffer.Lock(0, 0);

            //fill the buffer with vertices
            //cube

/**************
/* Blah blah, verices data here
/*************/


            buffer.Unlock();

            //return created and populated buffer
            return buffer;
        }

        public void Release()
        {
            device.Dispose();
        }

        private bool CreateAppWindow(SharpXEngine mainEngine)
        {
            int Height = 480, Width = 640, RefreshRate = 60;
            bool Windowed = true;
            Format PixelFormat = Format.X8B8G8R8;
            if (!LoadGFXConfig(ref Height, ref Width, ref RefreshRate, ref Windowed, ref PixelFormat)) return false;

            //Prepare device creation parameters
            AdapterInformation adapter = Manager.Adapters[0];

            DisplayMode Mode = new DisplayMode();
            Mode.Width = Width;
            Mode.Height = Height;
            Mode.RefreshRate = RefreshRate;
            Mode.Format = PixelFormat;

            PresentParameters presParams = new PresentParameters();
            presParams.BackBufferFormat = PixelFormat;
            presParams.BackBufferHeight = Height;
            presParams.BackBufferWidth = Width;
            presParams.SwapEffect = SwapEffect.Flip;
            presParams.Windowed = Windowed;
            presParams.PresentationInterval = PresentInterval.Immediate;    //Vsync off
            //activate and mange z-buffer
            presParams.EnableAutoDepthStencil = true;
            presParams.AutoDepthStencilFormat = DepthFormat.D16;

            mainEngine.Height = Height;
            mainEngine.Width = Width;
            mainEngine.Text = "SharpXEngine";
            //if (Windowed) mainEngine.TopMost = true;

            //Create device
            try
            {
                device = new Device(
                    adapter.Adapter,
                    DeviceType.Hardware,
                    mainEngine,
                    CreateFlags.HardwareVertexProcessing,
                    presParams);
            }
            catch (DirectXException e)
            {
                MessageBox.Show(e.Message);
                return false;
            }

            return true;
        }
        private bool LoadGFXConfig(ref int Height, ref int Width, ref int RefreshRate, ref bool Windowed, ref Format PixelFormat)
        {
            try
            {
                //Try to open config file
                StreamReader sr = new StreamReader("MDX9.cfg");
                String line;

                //Load config file data
                while ((line = sr.ReadLine()) != null)
                {
                    switch (line[0])
                    {
                        case '[':
                            switch (line)
                            {
                                case "[Rozdzielczosc]":
                                    //next 4 lines in config file describe selected resolution
                                    //in order: Width, Height, RefreshRate, Format
                                    Width = Convert.ToInt16((sr.ReadLine()).Substring(6));
                                    Height = Convert.ToInt16((sr.ReadLine()).Substring(7));
                                    RefreshRate = Convert.ToInt16((sr.ReadLine()).Substring(12));
                                    PixelFormat = (Format)Enum.Parse(typeof(Format), (sr.ReadLine()).Substring(7));
                                    break;
                                case "[W okienku]":
                                    //next line of config file indicate window mode flag
                                    Windowed = Convert.ToBoolean((sr.ReadLine()).Substring(9));
                                    break;
                            }
                            break;
                        default:
                            continue;
                    }
                }
                sr.Close();
                return true;
            }
            catch (FileNotFoundException)
            {
                //Config file not found - run config manager
                MessageBox.Show("Nieudane wczytanie konfiguracji", "Wczytanie", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //Run config application
                return false;
            }
        }
    }
}
I tried to put RenderState.Ambient in various parts of the code, but the effect was always the same - faces away from the light are black. Please note, that here
Arial20.DrawText("FPS:"+fpsText, 20, 20, device.RenderState.Ambient);
I use ambient light color to draw FPS counter, and here it works OK. I tried also to run the app on diffrent PC, but the effect was the same. Also sample code from some tutorials I found gives same result. Anyone has the idea where the problem lies?

Share this post


Link to post
Share on other sites
Hello again

I finally managed to make it work.
In my case it seems that ambient light works only if there is a material created and its ambient color set.
Then total pixel color is an "average" of material color and light color.
I wonder why it's not working for simple colored vertices...

Share this post


Link to post
Share on other sites

This topic is 3801 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this