Click here to Skip to main content
15,891,951 members
Articles / Programming Languages / C#

3D Basics using Silverlight-5 and XNA (Part 2)

Rate me:
Please Sign up or sign in to vote.
4.50/5 (6 votes)
12 Dec 2011CPOL8 min read 37.5K   2.4K   16  
Learn 3D programming with Silverlight-5 and XNA
using System.Windows.Controls;
using System.Windows.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Windows;

namespace Polyhedron
{
  public partial class MainPage : UserControl
  {
    private float aspectRatio = 1f;
    private VertexBuffer vb;
    private Texture2D texture;
    private BasicEffect basicEffect;

    public MainPage()
    {
      InitializeComponent();
    }

    private void drawingSurface1_Loaded(object sender, System.Windows.RoutedEventArgs e)
    {
      if (Is3dBlocked())
        return;
      if (GraphicsDeviceManager.Current.RenderMode != RenderMode.Hardware)
      {
        MessageBox.Show(GraphicsDeviceManager.Current.RenderModeReason.ToString());
        return;
      }
      
      GraphicsDevice g = GraphicsDeviceManager.Current.GraphicsDevice;

      VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[]{
        new VertexPositionNormalTexture(new Vector3(-1, -1, 0),Vector3.Forward,Vector2.Zero),
        new VertexPositionNormalTexture(new Vector3(0, 1, 0),Vector3.Forward,Vector2.Zero),
        new VertexPositionNormalTexture(new Vector3(1, -1, 0),Vector3.Forward,Vector2.Zero)};
      vb = new VertexBuffer(g, VertexPositionNormalTexture.VertexDeclaration, vertices.Length, BufferUsage.WriteOnly);
      vb.SetData(0, vertices, 0, vertices.Length, 0);

      texture = new Texture2D(g, 1, 1, false, SurfaceFormat.Color);
      texture.SetData<Color>(new Color[1] { new Color(1f, 0, 0) });

      basicEffect = new BasicEffect(g);
      basicEffect.EnableDefaultLighting();
      basicEffect.LightingEnabled = true;
      basicEffect.Texture = texture;
      basicEffect.TextureEnabled = true;
    }

    private bool Is3dBlocked()
    {
      if (GraphicsDeviceManager.Current.RenderMode == RenderMode.Hardware)
        return false;
      string message;
      switch (GraphicsDeviceManager.Current.RenderModeReason)
      {
        case RenderModeReason.Not3DCapable:
          message = "You graphics hardware is not capable of displaying this page ";
          break;
        case RenderModeReason.GPUAccelerationDisabled:
          message = "Hardware graphics acceleration has not been enabled on this web page.\n\n" +
            "Please notify the web site owner.";
          break;
        case RenderModeReason.TemporarilyUnavailable:
          message = "Your graphics hardware is temporarily unavailable.\n\n" +
            "Try reloading the web page or restarting your browser.";
          break;
        case RenderModeReason.SecurityBlocked:
          message =
            "You need to configure your system to allow this web site to display 3D graphics:\n\n" +
            "  1. Right-click the page\n" +
            "  2. Select 'Silverlight'\n" +
            "     (The 'Microsoft Silverlight Configuration' dialog will be displayed)\n" +
            "  3. Select the 'Permissions' tab\n" +
            "  4. Find this site in the list and change its 3D Graphics permission from 'Deny' to 'Allow'\n" +
            "  5. Click 'OK'\n" +
            "  6. Reload the page";
          break;
        default:
          message = "Unknown error";
          break;
      }
      MessageBox.Show(message, "3D Content Blocked", MessageBoxButton.OK);
      return true;
    }

    private void drawingSurface1_SizeChanged(object sender, System.Windows.SizeChangedEventArgs e)
    {
      aspectRatio = (float)(drawingSurface1.ActualWidth / drawingSurface1.ActualHeight);
    }

    private void drawingSurface1_Draw(object sender, DrawEventArgs e)
    {
      GraphicsDevice g = GraphicsDeviceManager.Current.GraphicsDevice;
      g.RasterizerState = RasterizerState.CullNone;
      g.SetVertexBuffer(vb);

      basicEffect.World = Matrix.CreateRotationY((float)e.TotalTime.TotalSeconds * 2);
      basicEffect.View = Matrix.CreateLookAt(new Vector3(0, 0, 5.0f), Vector3.Zero, Vector3.Up);
      basicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(0.85f, aspectRatio, 0.01f, 1000.0f);

      g.Clear(new Color(0.8f, 0.8f, 0.8f, 1.0f));
      basicEffect.CurrentTechnique.Passes[0].Apply();
      g.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);
      e.InvalidateSurface();
    }
  }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) MetaMapics Ltd.
United Kingdom United Kingdom
Freelance software developer with a focus on Microsoft technologies and specialist experience in mapping and location-based applications.

Comments and Discussions