Jump to content
  • Advertisement

MatsK

Member
  • Content count

    157
  • Joined

  • Last visited

Everything posted by MatsK

  1. I'm learning HLSL, and my VertexShader is compiling fine, but it isn't displaying anything. Why? Here's my shader: float4x4 BoneMatrix; float4x4 World; float4x4 View; float4x4 Projection; float4 AmbientColor = float4(1, 1, 1, 1); float AmbientIntensity = 0.1; struct VertexShaderHeadInput { float4 Position : POSITION0; float4 Normal : NORMAL0; float4 TexPosition : TEXCOORD0; }; struct VertexShaderHeadOutput { float4 Position : POSITION0; float4 Normal : NORMAL0; float4 TexPosition : TEXCOORD0; }; VertexShaderHeadOutput TransformHead(VertexShaderHeadInput Input) { VertexShaderHeadOutput Output; float4 WorldPosition = mul(Input.Position, World); float4 ViewPosition = mul(WorldPosition, View); Output.Position = mul(ViewPosition, Projection); Output.Normal = mul(ViewPosition, Projection); Output.TexPosition = mul(ViewPosition, Projection); Output.Position *= mul(Input.Position, BoneMatrix); Output.Normal *= mul(Input.Normal, BoneMatrix); Output.TexPosition *= Input.TexPosition; return Output; } float4 PixelShaderFunction(VertexShaderHeadOutput Input) : COLOR0 { return AmbientColor * AmbientIntensity; } technique TransformHeadTechnique { pass Pass1 { VertexShader = compile vs_3_0 TransformHead(); PixelShader = compile ps_3_0 PixelShaderFunction(); } } Here's my usage code: m_HeadShader.Parameters["World"].SetValue(WorldMatrix); m_HeadShader.Parameters["View"].SetValue(ViewMatrix); m_HeadShader.Parameters["Projection"].SetValue(ProjectionMatrix); m_HeadShader.Parameters["BoneMatrix"].SetValue(Skel.Bones[16].AbsoluteMatrix); foreach(EffectPass Pass in m_HeadShader.CurrentTechnique.Passes) { Pass.Apply(); foreach (Vector3 Fce in HeadMesh.Faces) { VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0] = HeadMesh.RealVertices[(int)Fce.X]; Vertex[1] = HeadMesh.RealVertices[(int)Fce.Y]; Vertex[2] = HeadMesh.RealVertices[(int)Fce.Z]; Vertex[0].TextureCoordinate = HeadMesh.RealVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = HeadMesh.RealVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = HeadMesh.RealVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = HeadMesh.RealVertices[(int)Fce.X].Normal; Vertex[1].Normal = HeadMesh.RealVertices[(int)Fce.Y].Normal; Vertex[2].Normal = HeadMesh.RealVertices[(int)Fce.Z].Normal; m_Devc.DrawUserPrimitives(PrimitiveType.TriangleList, Vertex, 0, 1); } } My worldmatrix: /// <summary> /// This avatar's world matrix. Used for rendering. /// </summary> public Matrix WorldMatrix { get { if (m_WorldIsDirty) { m_World = Matrix.CreateRotationX(m_RotateX) * Matrix.CreateRotationY(m_RotateY) * Matrix.CreateRotationZ(m_RotateZ) * Matrix.CreateScale(m_Scale) * Matrix.CreateTranslation(m_Position); m_WorldIsDirty = false; } return m_World; } } This is the code I've been trying to convert to HLSL (High Level Shader Language): case MeshType.Head: for (int i = 0; i < Msh.TotalVertexCount; i++) { //Transform the head vertices' position by the absolute transform //for the headbone (which is always bone 17) to render the head in place. Msh.TransformedVertices[i].Position = Vector3.Transform(Msh.RealVertices[i].Position, Skel.Bones[16].AbsoluteMatrix); Msh.TransformedVertices[i].TextureCoordinate = Msh.RealVertices[i].TextureCoordinate; //Transform the head normals' position by the absolute transform //for the headbone (which is always bone 17) to render the head in place. Msh.TransformedVertices[i].Normal = Vector3.Transform(Msh.RealVertices[i].Normal, Skel.Bones[16].AbsoluteMatrix); } return; I might add that I tried to debug the shader using RenderDoc, but it actually crashed as it was loading its log. :|
  2. Doing this: m_World = Matrix.CreateScale(m_Scale) * Matrix.CreateRotationX(m_RotateX) * Matrix.CreateRotationY(m_RotateY) * Matrix.CreateRotationZ(m_RotateZ) /** Matrix.CreateScale(m_Scale)*/ * Matrix.CreateTranslation(m_Position); doesn't seem to have any effect. :( Does the fact that I'm sending my world matrix to the shader as such have anything to do with it? m_VitaboyShader.Parameters["World"].SetValue(WorldMatrix * Skel.Bones[Skel.FindBone("HEAD")].AbsoluteMatrix); Also, how would I create a single rotation matrix by using quats?
  3. I managed to make the model render right side up. I also added a very basic pixel shader to render the texture. I extended the shader to include hands and accessories; float4x4 World; float4x4 View; float4x4 Projection; float4 AmbientColor = float4(1, 1, 1, 1); float AmbientIntensity = 0.1; texture HeadTexture; sampler HeadTextureSampler = sampler_state { Texture = <HeadTexture>; }; texture AccessoryTexture; sampler AccessoryTextureSampler = sampler_state { Texture = <AccessoryTexture>; }; texture LeftHandTexture; sampler LeftHandTextureSampler = sampler_state { Texture = <LeftHandTexture>; }; texture RightHandTexture; sampler RightHandTextureSampler = sampler_state { Texture = <RightHandTexture>; }; struct VertexShaderHeadInput { float4 Position : POSITION0; float4 Normal : NORMAL0; float4 TexPosition : TEXCOORD0; }; struct VertexShaderHeadOutput { float4 Position : POSITION0; float4 Normal : NORMAL0; float4 TexPosition : TEXCOORD0; }; VertexShaderHeadOutput TransformHead(VertexShaderHeadInput Input) { VertexShaderHeadOutput Output; float4 WorldPosition = mul(Input.Position, World); float4 ViewPosition = mul(WorldPosition, View); Output.Position = mul(ViewPosition, Projection); Output.Normal = mul(ViewPosition, Projection); Output.TexPosition = Input.TexPosition; return Output; } VertexShaderHeadOutput TransformAccessory(VertexShaderHeadInput Input) { VertexShaderHeadOutput Output; float4 WorldPosition = mul(Input.Position, World); float4 ViewPosition = mul(WorldPosition, View); Output.Position = mul(ViewPosition, Projection); Output.Normal = mul(ViewPosition, Projection); Output.TexPosition = Input.TexPosition; return Output; } VertexShaderHeadOutput TransformLeftHand(VertexShaderHeadInput Input) { VertexShaderHeadOutput Output; float4 WorldPosition = mul(Input.Position, World); float4 ViewPosition = mul(WorldPosition, View); Output.Position = mul(ViewPosition, Projection); Output.Normal = mul(ViewPosition, Projection); Output.TexPosition = Input.TexPosition; return Output; } VertexShaderHeadOutput TransformRightHand(VertexShaderHeadInput Input) { VertexShaderHeadOutput Output; float4 WorldPosition = mul(Input.Position, World); float4 ViewPosition = mul(WorldPosition, View); Output.Position = mul(ViewPosition, Projection); Output.Normal = mul(ViewPosition, Projection); Output.TexPosition = Input.TexPosition; return Output; } float4 HeadPixelShaderFunction(VertexShaderHeadOutput Input) : COLOR0 { float4 Color = tex2D(HeadTextureSampler, Input.TexPosition); return Color; } float4 AccessoryPixelShaderFunction(VertexShaderHeadOutput Input) : COLOR0 { float4 Color = tex2D(AccessoryTextureSampler, Input.TexPosition); return Color; } float4 LeftHandPixelShaderFunction(VertexShaderHeadOutput Input) : COLOR0 { float4 Color = tex2D(LeftHandTextureSampler, Input.TexPosition); return Color; } float4 RightHandPixelShaderFunction(VertexShaderHeadOutput Input) : COLOR0 { float4 Color = tex2D(RightHandTextureSampler, Input.TexPosition); return Color; } technique TransformHeadTechnique { pass HeadPass { VertexShader = compile vs_3_0 TransformHead(); PixelShader = compile ps_3_0 HeadPixelShaderFunction(); } } technique TransformAccessoryTechnique { pass HeadPass { VertexShader = compile vs_3_0 TransformAccessory(); PixelShader = compile ps_3_0 AccessoryPixelShaderFunction(); } } technique TransformLeftHandTechnique { pass HeadPass { VertexShader = compile vs_3_0 TransformLeftHand(); PixelShader = compile ps_3_0 LeftHandPixelShaderFunction(); } } technique TransformRightHandTechnique { pass HeadPass { VertexShader = compile vs_3_0 TransformRightHand(); PixelShader = compile ps_3_0 RightHandPixelShaderFunction(); } } Now, the head, hands and accessory renders in place, but also seems to be bobbing up and down along the X-axis in addition to going around the Y-axis (which it is supposed to do). Here's how I create my rotation: /// <summary> /// This avatar's world matrix. Used for rendering. /// </summary> public Matrix WorldMatrix { get { if (m_WorldIsDirty) { m_World = Matrix.CreateRotationX(m_RotateX) * Matrix.CreateRotationY(m_RotateY) * Matrix.CreateRotationZ(m_RotateZ) * Matrix.CreateScale(m_Scale) * Matrix.CreateTranslation(m_Position); m_WorldIsDirty = false; } return m_World; } } /// <summary> /// Gets or sets the angle (in degrees) of the rotation axis for this Avatar. /// </summary> public float RotationY { get { return m_RotateY; } set { m_RotateY = value; m_WorldIsDirty = true; } } /// <summary> /// Converts an angle given in degrees to radians. /// </summary> /// <param name="Angle">The angle to convert.</param> /// <returns>The angle in radians.</returns> private double DegreesToRadians(double Angle) { return (Math.PI / 180) * Angle; } /// <summary> /// Updates this avatar's rotation. /// </summary> /// <param name="GTime">A GameTime instance.</param> public void Update(GameTime GTime) { if (ShouldRotate) { float Time = GTime.TotalGameTime.Ticks; float Phase = (Time % RotationSpeed) / RotationSpeed; double Multiplier = Math.Sin((Math.PI * 2) * Phase); double NewAngle = RotationStartAngle + (RotationRange * Multiplier); RotationY = (float)DegreesToRadians(NewAngle); } } Also, does anyone know how I can use the normals with my texture in the pixel shader??
  4. Auskennfuchs: No, it's plainly visible :) I found out that I could do:  m_HeadShader.Parameters["World"].SetValue(WorldMatrix * Skel.Bones[16].AbsoluteMatrix); in my program in order to render the model in place. That means I didn't have to do: Output.Position *= mul(Input.Position, BoneMatrix); Output.Normal *= mul(Input.Normal, BoneMatrix); Output.TexPosition *= Input.TexPosition; in my shader. Here's the result: So how do I make sure that the model is rendered right side up? :)
  5. Ah! Thanks! Changing to bright red gave me this: It seems like my shader is rendering exactly what it's supposed to be rendering, but in the wrong place. So what's wrong with my vertex shader calculations? :\ I don't understand your sample. What is gWorldInverseTranspose?
  6. MatsK

    My favorite essay

    https://github.com/Droogans/unmaintainable-code
  7. MatsK

    Rendering 3D Over 2D

    Solved it! :D Turns out that the Depth parameter in GraphicsDevice.Clear works exactly like the one in SpriteBatch.Draw :)
  8. I'm trying to render 3D over 2D in Monogame, but can't figure out why it won't work!   Here's the drawing callback: /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { Resolution.BeginDraw(); spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, DepthStencilState.Default, RasterizerState.CullCounterClockwise, null, Resolution.getTransformationMatrix()); m_ScrManager.Draw(); spriteBatch.End(); //Reset device to defaults before rendering... GraphicsDevice.BlendState = BlendState.Opaque; GraphicsDevice.DepthStencilState = DepthStencilState.Default; GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise; GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap; GraphicsDevice.Viewport = new Viewport(0, 0, GlobalSettings.Default.ScreenWidth, GlobalSettings.Default.ScreenHeight); m_ScrManager.Draw3D(); HitVM.Step(); base.Draw(gameTime); } } Here is Resolution.cs: ////////////////////////////////////////////////////////////////////////// ////License: The MIT License (MIT) ////Copyright (c) 2010 David Amador (http://www.david-amador.com) //// ////Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: //// ////The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. //// ////THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Gonzo { public static class Resolution { static private GraphicsDeviceManager _Device = null; //From: http://www.discussiongenerator.com/2012/09/15/resolution-independent-2d-rendering-in-xna-4/ static private int virtualViewportX; static private int virtualViewportY; static private int _Width = 800; static private int _Height = 600; static private int _VWidth = 1024; static private int _VHeight = 768; static private Matrix _ScaleMatrix; static private bool _FullScreen = false; static private bool _dirtyMatrix = true; public static int VirtualViewportX { get { return virtualViewportX; } } public static int VirtualViewportY { get { return virtualViewportY; } } static public void Init(ref GraphicsDeviceManager device) { _Width = device.PreferredBackBufferWidth; _Height = device.PreferredBackBufferHeight; _Device = device; _dirtyMatrix = true; ApplyResolutionSettings(); } static public Matrix getTransformationMatrix() { if (_dirtyMatrix) RecreateScaleMatrix(); return _ScaleMatrix; } static public void SetResolution(int Width, int Height, bool FullScreen) { _Width = Width; _Height = Height; _FullScreen = FullScreen; ApplyResolutionSettings(); } static public void SetVirtualResolution(int Width, int Height) { _VWidth = Width; _VHeight = Height; _dirtyMatrix = true; } static private void ApplyResolutionSettings() { #if XBOX360 _FullScreen = true; #endif // If we aren't using a full screen mode, the height and width of the window can // be set to anything equal to or smaller than the actual screen size. if (_FullScreen == false) { if ((_Width <= GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width) && (_Height <= GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height)) { _Device.PreferredBackBufferWidth = _Width; _Device.PreferredBackBufferHeight = _Height; _Device.IsFullScreen = _FullScreen; _Device.ApplyChanges(); } } else { // If we are using full screen mode, we should check to make sure that the display // adapter can handle the video mode we are trying to set. To do this, we will // iterate through the display modes supported by the adapter and check them against // the mode we want to set. foreach (DisplayMode dm in GraphicsAdapter.DefaultAdapter.SupportedDisplayModes) { // Check the width and height of each mode against the passed values if ((dm.Width == _Width) && (dm.Height == _Height)) { // The mode is supported, so set the buffer formats, apply changes and return _Device.PreferredBackBufferWidth = _Width; _Device.PreferredBackBufferHeight = _Height; _Device.IsFullScreen = _FullScreen; _Device.ApplyChanges(); } } } _dirtyMatrix = true; _Width = _Device.PreferredBackBufferWidth; _Height = _Device.PreferredBackBufferHeight; } /// <summary> /// Sets the device to use the draw pump /// Sets correct aspect ratio /// </summary> static public void BeginDraw() { // Start by reseting viewport to (0,0,1,1) FullViewport(); // Clear to Black _Device.GraphicsDevice.Clear(Color.Black); // Calculate Proper Viewport according to Aspect Ratio ResetViewport(); // and clear that // This way we are gonna have black bars if aspect ratio requires it and // the clear color on the rest _Device.GraphicsDevice.Clear(Color.CornflowerBlue); } static private void RecreateScaleMatrix() { _dirtyMatrix = false; _ScaleMatrix = Matrix.CreateScale( (float)_Device.GraphicsDevice.Viewport.Width / _VWidth, (float)_Device.GraphicsDevice.Viewport.Width / _VWidth, 1f); } static public void FullViewport() { Viewport vp = new Viewport(); vp.X = vp.Y = 0; vp.Width = _Width; vp.Height = _Height; _Device.GraphicsDevice.Viewport = vp; } /// <summary> /// Get virtual Mode Aspect Ratio /// </summary> /// <returns>aspect ratio</returns> static public float getVirtualAspectRatio() { return (float)_VWidth / (float)_VHeight; } static public void ResetViewport() { float targetAspectRatio = getVirtualAspectRatio(); // figure out the largest area that fits in this resolution at the desired aspect ratio int width = _Device.PreferredBackBufferWidth; int height = (int)(width / targetAspectRatio + .5f); bool changed = false; if (height > _Device.PreferredBackBufferHeight) { height = _Device.PreferredBackBufferHeight; // PillarBox width = (int)(height * targetAspectRatio + .5f); changed = true; } // set up the new viewport centered in the backbuffer Viewport viewport = new Viewport(); viewport.X = (_Device.PreferredBackBufferWidth / 2) - (width / 2); viewport.Y = (_Device.PreferredBackBufferHeight / 2) - (height / 2); viewport.Width = width; viewport.Height = height; viewport.MinDepth = 0; viewport.MaxDepth = 1; virtualViewportX = viewport.X; virtualViewportY = viewport.Y; if (changed) { _dirtyMatrix = true; } _Device.GraphicsDevice.Viewport = viewport; } } } Here is the 3D rendering: public void Render(Matrix ViewMatrix, Matrix WorldMatrix, Matrix ProjectionMatrix) { //This sets DepthBufferEnable and DepthBufferWriteEnable. m_Devc.DepthStencilState = DepthStencilState.Default; m_Devc.BlendState = BlendState.AlphaBlend; m_Devc.RasterizerState = RasterizerState.CullNone; // Configure effects m_HeadEffect.World = WorldMatrix; m_HeadEffect.View = ViewMatrix; m_HeadEffect.Projection = ProjectionMatrix; m_HeadEffect.EnableDefaultLighting(); if (HeadTexture != null) { m_HeadEffect.Texture = HeadTexture; m_HeadEffect.TextureEnabled = true; } m_BodyEffect.World = WorldMatrix; m_BodyEffect.View = ViewMatrix; m_BodyEffect.Projection = ProjectionMatrix; m_BodyEffect.EnableDefaultLighting(); if (m_BodyEffect != null) { m_BodyEffect.Texture = BodyTexture; m_BodyEffect.TextureEnabled = true; } // Configure effects m_LeftHandEffect.World = WorldMatrix; m_LeftHandEffect.View = ViewMatrix; m_LeftHandEffect.Projection = ProjectionMatrix; m_LeftHandEffect.EnableDefaultLighting(); if (LeftHandTexture != null) { m_LeftHandEffect.Texture = LeftHandTexture; m_LeftHandEffect.TextureEnabled = true; } if (HeadMesh != null) { foreach (EffectPass Pass in m_HeadEffect.CurrentTechnique.Passes) { Pass.Apply(); foreach (Vector3 Fce in HeadMesh.Faces) { // Draw VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0] = HeadMesh.TransformedVertices[(int)Fce.X]; Vertex[1] = HeadMesh.TransformedVertices[(int)Fce.Y]; Vertex[2] = HeadMesh.TransformedVertices[(int)Fce.Z]; Vertex[0].TextureCoordinate = HeadMesh.TransformedVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = HeadMesh.TransformedVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = HeadMesh.TransformedVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = HeadMesh.TransformedVertices[(int)Fce.X].Normal; Vertex[1].Normal = HeadMesh.TransformedVertices[(int)Fce.Y].Normal; Vertex[2].Normal = HeadMesh.TransformedVertices[(int)Fce.Z].Normal; m_Devc.DrawUserPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList, Vertex, 0, 1); } TransformVertices(HeadMesh, null, MeshType.Head); } } if (BodyMesh != null) { foreach (EffectPass Pass in m_BodyEffect.CurrentTechnique.Passes) { Pass.Apply(); foreach (Vector3 Fce in BodyMesh.Faces) { // Draw VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0] = BodyMesh.TransformedVertices[(int)Fce.X]; Vertex[1] = BodyMesh.TransformedVertices[(int)Fce.Y]; Vertex[2] = BodyMesh.TransformedVertices[(int)Fce.Z]; Vertex[0].TextureCoordinate = BodyMesh.TransformedVertices[(int)Fce.X].TextureCoordinate; Vertex[1].TextureCoordinate = BodyMesh.TransformedVertices[(int)Fce.Y].TextureCoordinate; Vertex[2].TextureCoordinate = BodyMesh.TransformedVertices[(int)Fce.Z].TextureCoordinate; Vertex[0].Normal = BodyMesh.TransformedVertices[(int)Fce.X].Normal; Vertex[1].Normal = BodyMesh.TransformedVertices[(int)Fce.Y].Normal; Vertex[2].Normal = BodyMesh.TransformedVertices[(int)Fce.Z].Normal; m_Devc.DrawUserPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList, Vertex, 0, 1); } TransformVertices(BodyMesh, Skel.Bones[0], MeshType.Body); } } if (LeftHandMesh != null) { foreach (EffectPass Pass in m_LeftHandEffect.CurrentTechnique.Passes) { Pass.Apply(); foreach (Vector3 Fce in LeftHandMesh.Faces) { // Draw VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0] = LeftHandMesh.TransformedVertices[(int)Fce.X]; Vertex[1] = LeftHandMesh.TransformedVertices[(int)Fce.Y]; Vertex[2] = LeftHandMesh.TransformedVertices[(int)Fce.Z]; m_Devc.DrawUserPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList, Vertex, 0, 1); } TransformVertices(LeftHandMesh, null, MeshType.LHand); } } if (RightHandMesh != null) { foreach (EffectPass Pass in m_LeftHandEffect.CurrentTechnique.Passes) { Pass.Apply(); foreach (Vector3 Fce in RightHandMesh.Faces) { // Draw VertexPositionNormalTexture[] Vertex = new VertexPositionNormalTexture[3]; Vertex[0] = RightHandMesh.TransformedVertices[(int)Fce.X]; Vertex[1] = RightHandMesh.TransformedVertices[(int)Fce.Y]; Vertex[2] = RightHandMesh.TransformedVertices[(int)Fce.Z]; m_Devc.DrawUserPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList, Vertex, 0, 1); } TransformVertices(RightHandMesh, null, MeshType.RHand); } } } /// <summary> /// Transforms all vertices in a given mesh to their correct positions. /// </summary> /// <param name="Msh">The mesh to transform.</param> /// <param name="bone">The bone to transform to.</param> private void TransformVertices(Mesh Msh, Bone bone, MeshType MshType) { switch (MshType) { case MeshType.Head: for (int i = 0; i < Msh.TotalVertexCount; i++) { //Transform the head vertices' position by the absolute transform //for the headbone (which is always bone 17) to render the head in place. Msh.TransformedVertices[i].Position = Vector3.Transform(Msh.RealVertices[i].Position, Skel.Bones[16].AbsoluteMatrix); Msh.TransformedVertices[i].TextureCoordinate = Msh.RealVertices[i].TextureCoordinate; //Transform the head normals' position by the absolute transform //for the headbone (which is always bone 17) to render the head in place. Msh.TransformedVertices[i].Normal = Vector3.Transform(Msh.RealVertices[i].Normal, Skel.Bones[16].AbsoluteMatrix); } return; case MeshType.Body: BoneBinding boneBinding = Msh.BoneBindings.FirstOrDefault(x => Msh.Bones[(int)x.BoneIndex] == bone.Name); if (boneBinding != null) { for (int i = 0; i < boneBinding.RealVertexCount; i++) { int vertexIndex = (int)boneBinding.FirstRealVertexIndex + i; VertexPositionNormalTexture relativeVertex = Msh.RealVertices[vertexIndex]; Matrix translatedMatrix = Matrix.CreateTranslation(new Vector3(relativeVertex.Position.X, relativeVertex.Position.Y, relativeVertex.Position.Z)) * bone.AbsoluteMatrix; Msh.TransformedVertices[vertexIndex].Position = Vector3.Transform(Vector3.Zero, translatedMatrix); Msh.TransformedVertices[vertexIndex].TextureCoordinate = relativeVertex.TextureCoordinate; //Normals... translatedMatrix = Matrix.CreateTranslation(new Vector3(relativeVertex.Normal.X, relativeVertex.Normal.Y, relativeVertex.Normal.Z)) * bone.AbsoluteMatrix; Msh.TransformedVertices[vertexIndex].Normal = Vector3.Transform(Vector3.Zero, translatedMatrix); } } foreach (var child in bone.Children) TransformVertices(Msh, child, MshType); break; case MeshType.LHand: for (int i = 0; i < Msh.TotalVertexCount; i++) { //Transform the left hand vertices' position by the absolute transform //for the left handbone (which is always bone 10) to render the left hand in place. Msh.TransformedVertices[i].Position = Vector3.Transform(Msh.RealVertices[i].Position, Skel.Bones[9].AbsoluteMatrix); //Transform the left hand normals' position by the absolute transform //for the left handbone (which is always bone 10) to render the left hand in place. Msh.TransformedVertices[i].Normal = Vector3.Transform(Msh.RealVertices[i].Normal, Skel.Bones[9].AbsoluteMatrix); } return; case MeshType.RHand: for (int i = 0; i < Msh.TotalVertexCount; i++) { //Transform the right hand vertices' position by the absolute transform //for the right handbone (which is always bone 15) to render the right hand in place. Msh.TransformedVertices[i].Position = Vector3.Transform(Msh.RealVertices[i].Position, Skel.Bones[14].AbsoluteMatrix); //Transform the right hand normals' position by the absolute transform //for the right handbone (which is always bone 15) to render the right hand in place. Msh.TransformedVertices[i].Normal = Vector3.Transform(Msh.RealVertices[i].Normal, Skel.Bones[14].AbsoluteMatrix); } return; } } The 3D rendering works fine when I comment out the 2D rendering from the drawing callback. Why? :\
  9. I enabled SpriteSortMode.FrontToBack in my drawing callback: /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { Resolution.BeginDraw(); spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, null, null, RasterizerState.CullCounterClockwise, null, Resolution.getTransformationMatrix()); m_ScrManager.Draw(); spriteBatch.End(); //Reset device to defaults before rendering... GraphicsDevice.BlendState = BlendState.Opaque; GraphicsDevice.DepthStencilState = DepthStencilState.Default; GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise; GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap; GraphicsDevice.Viewport = new Viewport(0, 0, GlobalSettings.Default.ScreenWidth, GlobalSettings.Default.ScreenHeight); GraphicsDevice.Clear(ClearOptions.DepthBuffer, Color.Black, 0.5f, 1); m_ScrManager.Draw3D(); HitVM.Step(); base.Draw(gameTime); } Then, in my UIScreen.Draw method, I did: public virtual void Draw() { foreach (KeyValuePair<string, UIElement> KVP in m_Elements) { try { if (KVP.Value is UIDialog || KVP.Value is WillWrightDiag) KVP.Value.Draw(m_SBatch, UIElement.GetLayerDepth(LayerDepth.DialogLayer)); else if (KVP.Value is UIButton) KVP.Value.Draw(m_SBatch, UIElement.GetLayerDepth(LayerDepth.ButtonLayer)); else if (KVP.Value is UIImage) KVP.Value.Draw(m_SBatch, UIElement.GetLayerDepth(LayerDepth.ImageLayer)); else KVP.Value.Draw(m_SBatch, UIElement.GetLayerDepth(LayerDepth.Default)); } catch(Exception) { continue; } } } Here is UIElement.GetLayerDepth: /// <summary> /// Gets the value of the corresponding layer depth. /// </summary> /// <param name="Depth">The depth for which to retrieve a value.</param> /// <returns>The value of the specified depth.</returns> public static float GetLayerDepth(LayerDepth Depth) { switch(Depth) { case LayerDepth.Default: return 0.0f; case LayerDepth.ImageLayer: return 0.8f; case LayerDepth.ButtonLayer: return 0.9f; case LayerDepth.DialogLayer: return 0.10f; default: return 0.0f; } } Then in Credits.cs, I added the WillWrightDiag to my list of elements to be drawn by UIScreen.Elements, as such: m_WillWrightDiag = new WillWrightDiag(WillImage, this, new Vector2(100, 100)); m_WillWrightDiag.IsDrawn = false; m_Elements.Add("WillWrightDiag", m_WillWrightDiag); Here's how I draw a UIDialog: public override void Draw(SpriteBatch SBatch, float? LayerDepth) { float Depth; if (LayerDepth != null) Depth = (float)LayerDepth; else Depth = 0.10f; if (IsDrawn) { Image.DrawTextureTo(SBatch, null, Image.Slicer.TLeft, Image.Position + Vector2.Zero, Depth); Image.DrawTextureTo(SBatch, Image.Slicer.TCenter_Scale, Image.Slicer.TCenter, Image.Position + new Vector2(Image.Slicer.LeftPadding, 0), Depth); Image.DrawTextureTo(SBatch, null, Image.Slicer.TRight, Image.Position + new Vector2(Image.Slicer.Width - Image.Slicer.RightPadding, 0), Depth); Image.DrawTextureTo(SBatch, Image.Slicer.CLeft_Scale, Image.Slicer.CLeft, Image.Position + new Vector2(0, Image.Slicer.TopPadding), null); Image.DrawTextureTo(SBatch, Image.Slicer.CCenter_Scale, Image.Slicer.CCenter, Image.Position + new Vector2(Image.Slicer.LeftPadding, Image.Slicer.TopPadding), Depth); Image.DrawTextureTo(SBatch, Image.Slicer.CRight_Scale, Image.Slicer.CRight, Image.Position + new Vector2(Image.Slicer.Width - Image.Slicer.RightPadding, Image.Slicer.TopPadding), Depth); int BottomY = Image.Slicer.Height - Image.Slicer.BottomPadding; Image.DrawTextureTo(SBatch, null, Image.Slicer.BLeft, Image.Position + new Vector2(0, BottomY), null); Image.DrawTextureTo(SBatch, Image.Slicer.BCenter_Scale, Image.Slicer.BCenter, Image.Position + new Vector2(Image.Slicer.LeftPadding, BottomY), Depth); Image.DrawTextureTo(SBatch, null, Image.Slicer.BRight, Image.Position + new Vector2(Image.Slicer.Width - Image.Slicer.RightPadding, BottomY), Depth); if (m_HasExitBtn) { m_CloseBtnBack.Draw(SBatch, null, Depth); m_CloseButton.Draw(SBatch, Depth); } } } And here's how I draw a WillWrightDiag, which inherits from UIDialog: public override void Draw(SpriteBatch SBatch, float? LayerDepth) { float Depth; if (LayerDepth != null) Depth = (float)LayerDepth; else Depth = 0.10f; if (IsDrawn) SBatch.Draw(m_WillWrightImg.Texture, m_WillWrightImg.Position, null, null, new Vector2(0.0f, 0.0f), 0.0f, null, Color.White, SpriteEffects.None, Depth); base.Draw(SBatch, LayerDepth); } Despite this, I still get this weird case where the Maxis-button is drawn on top of the dialog and the exit button is occasionally not drawn. Why? :\   [attachment=32955:tsocredits.png]   Is there a better, less error-prone way to achieve depth sorting? Here is the entire code for Credits.cs if it helps: using System; using System.Timers; using System.Collections.Generic; using System.Text; using Gonzo; using Gonzo.Elements; using Files.Manager; using Files.IFF; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace GonzoTest { public class CreditsScreen : UIScreen { private UIImage BackgroundImg, TSOLogoImage, BackButtonIndentImage, WillImage; private UIButton MaxisButton; private Iff m_Credits; private List<string> m_CreditsStrings = new List<string>(); private UIControl m_CreditsArea; private float m_CreditsY = 0; //Upwards position of credits text. private float m_CreditsCenterX = 0; //Center of credits area. private Timer m_CreditsTimer; //Timer for controlling text scroll. private WillWrightDiag m_WillWrightDiag; public CreditsScreen(ScreenManager Manager, SpriteBatch SBatch) : base(Manager, "Credits", SBatch, new Vector2(0, 0), new Vector2(GlobalSettings.Default.ScreenWidth, GlobalSettings.Default.ScreenHeight), GlobalSettings.Default.StartupPath + "\\" + "gamedata\\uiscripts\\credits.uis") { BackgroundImg = (UIImage)m_Elements["\"BackgroundImage\""]; TSOLogoImage = m_Controls["\"TSOLogoImage\""].Image; BackButtonIndentImage = m_Controls["\"BackButtonIndentImage\""].Image; WillImage = (UIImage)m_Elements["\"WillImage\""]; MaxisButton = (UIButton)m_Elements["\"MaxisButton\""]; MaxisButton.OnButtonClicked += MaxisButton_OnButtonClicked; m_WillWrightDiag = new WillWrightDiag(WillImage, this, new Vector2(100, 100)); m_WillWrightDiag.IsDrawn = false; m_Elements.Add("WillWrightDiag", m_WillWrightDiag); m_Credits = FileManager.GetIFF("credits.iff"); m_CreditsArea = (UIControl)m_Controls["\"CreditsArea\""]; m_CreditsY = m_CreditsArea.Size.Y; foreach(TranslatedString TStr in m_Credits.GetSTR(163).GetStringList(LanguageCodes.EngUS)) { foreach (string Str in TStr.TranslatedStr.Split('\n')) m_CreditsStrings.Add(Str); } m_CreditsTimer = new Timer(300); m_CreditsTimer.Elapsed += M_CreditsTimer_Elapsed; m_CreditsTimer.Start(); } private void M_CreditsTimer_Elapsed(object sender, ElapsedEventArgs e) { m_CreditsY -= 1.5f; } private void MaxisButton_OnButtonClicked(UIButton ClickedButton) { m_WillWrightDiag.IsDrawn = true; } public override void Update(InputHelper Input) { m_WillWrightDiag.Update(Input); base.Update(Input); } public override void Draw() { BackgroundImg.Draw(m_SBatch, null, 0.0f); TSOLogoImage.Draw(m_SBatch, null, 0.0f); BackButtonIndentImage.Draw(m_SBatch, null, 0.0f); float Separation = 1.0f; foreach (string Str in m_CreditsStrings) { m_CreditsCenterX = (m_CreditsArea.Size.X / 2) - (Manager.Font12px.MeasureString(Str).X / 2); if ((m_CreditsY + Separation) > m_CreditsArea.Position.Y && (m_CreditsY + Separation) < m_CreditsArea.Size.Y) { m_SBatch.DrawString(Manager.Font12px, Str, new Vector2(m_CreditsArea.Position.X + m_CreditsCenterX, m_CreditsY + Separation), Color.Wheat); } Separation += 15.0f; } base.Draw(); } } } Also, why is the chat down? :\ There's a much higher signal to noise ratio in the chat.
  10. MatsK

    Rendering 3D Over 2D

    That didn't work either :( But thanks for pointing out that SpriteSortMode.Deferred actually ignores depth! :D
  11. MatsK

    Rendering 3D Over 2D

    Ok, I changed my drawing callback to: /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { Resolution.BeginDraw(); spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, DepthStencilState.Default, RasterizerState.CullCounterClockwise, null, Resolution.getTransformationMatrix()); m_ScrManager.Draw(); spriteBatch.End(); //Reset device to defaults before rendering... GraphicsDevice.BlendState = BlendState.Opaque; GraphicsDevice.DepthStencilState = DepthStencilState.Default; GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise; GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap; GraphicsDevice.Viewport = new Viewport(0, 0, GlobalSettings.Default.ScreenWidth, GlobalSettings.Default.ScreenHeight); GraphicsDevice.Clear(ClearOptions.DepthBuffer, Color.Black, 0.5f, 1); m_ScrManager.Draw3D(); HitVM.Step(); base.Draw(gameTime); } Still doesn't work. :( Are the parameters correct? They're not exactly very well explained on MSDN, so I just put something...
  12. MatsK

    Rendering 3D Over 2D

    Yes. As is I only see the 2D. How do I clear the depth buffer?
  13. MatsK

    Rendering 3D Over 2D

    Yeah, I believe it does. Here's how I'm drawing a button to the UI, for instance: public override void Draw(SpriteBatch SBatch, float? LayerDepth) { if (Visible) { float Depth; if (LayerDepth != null) Depth = (float)LayerDepth; else Depth = 0.0f; if (Image != null && Image.Loaded) { Image.Draw(SBatch, new Rectangle((int)m_SourcePosition.X, (int)m_SourcePosition.Y, (int)m_Size.X, (int)m_Size.Y), Depth); } if (m_IsTextButton) SBatch.DrawString(m_Font, m_Text, m_TextPosition, TextColor); } } Notice how I'm passing Depth to Image.Draw: public override void Draw(SpriteBatch SBatch, Rectangle? SourceRect, float? LayerDepth) { float Depth; if (LayerDepth != null) Depth = (float)LayerDepth; else Depth = 0.0f; if (Visible) { if (SourceRect != null) { SBatch.Draw(Texture, Position, null, SourceRect, new Vector2(0.0f, 0.0f), 0.0f, null, Color.White, SpriteEffects.None, Depth); } else { SBatch.Draw(Texture, Position, null, null, new Vector2(0.0f, 0.0f), 0.0f, null, Color.White, SpriteEffects.None, Depth); } } } But in my drawing callback in the OP, I'm resetting the DepthStencilState before rendering 3D... I thought that should do the trick! 
  14. Hi! I'm trying to create a parser for a custom UI language. I thought I was done with it, as it has successfully parsed other scripts, but all of a sudden I found a script that caused GrammarExplorer to say "expected alignments". I searched for that syntax error on these boards, and I couldn't find it. Is this possibly a bug with Irony? <a href="http://pastebin.com/Qpz8ANgj">Here's my grammar</a> <a href="http://pastebin.com/6M9SFrcz">Here's the script I'm trying to parse</a> <a href="http://pastebin.com/tuLPkaUw">Here's my parser conflicts.</a> Grammar Explorer is complaining about line 204, character 17. Please tell me what I can do to correct this, thanks!
  15. I'm trying to use GetData() on a Texture2D, as such: /// <summary> /// Manually replaces a specified color in a texture with transparent black, /// thereby masking it. /// </summary> /// <param name="Texture">The texture on which to apply the mask.</param> /// <param name="ColorFrom">The color to mask away.</param> private static uint[] SINGLE_THREADED_TEXTURE_BUFFER = new uint[MaxResampleBufferSize]; public static void ManualTextureMaskSingleThreaded(Texture2D Texture, uint[] ColorsFrom) { var ColorTo = Color.TransparentBlack.PackedValue; var size = Texture.Width * Texture.Height; uint[] buffer = SINGLE_THREADED_TEXTURE_BUFFER; Texture.GetData<uint>(buffer); var didChange = false; for (int i = 0; i < size; i++) { if (ColorsFrom.Contains(buffer[i])) { didChange = true; buffer[i] = ColorTo; } } if (didChange) { Texture.SetData(buffer, 0, size); } else return; } But it always returns an array of 0s. Why? :\
  16. It seems the solution was closer than I thought it would be. All I had to do was call Bitmap.MakeTransparent() on my bitmaps :)
  17. Thanks! :) The problem is, I'm working with old data that uses color masks rather than alpha. Seems like the most reliable way to make masking work on all GPUs, then, is to write an extension that will run before the game starts and converts all the BMPs to PNGs with alpha. However, this is slightly worrying, because the reason I was looking into this problem again (I had originally ignored it for the time being) was that I was trying to set a RenderTarget2D on the GraphicsDevice, and it was failing with an InvalidOperationException. I wonder if this is also a Monogame bug 
  18. Texture.Format is Color. Color as the type for GetData doesn't change anything, I get a bunch of colors with 0,0,0,0 :(   And yes, they render correctly.
  19. MaxResampleBufferSize is 1024 * 768. I tried changing it to the size of the texture, it doesn't seem to have made a difference. As far as I can tell, the format is Color. Here's how I'm loading it: /// <summary> /// Gets an Texture2D instance from the FileManager. /// </summary> /// <param name="AssetID">The FileID/InstanceID of the texture to get.</param> /// <returns>A Texture2D instance.</returns> public static Texture2D GetTexture(ulong AssetID) { Stream Data = GrabItem(AssetID); using (MemoryStream PNGStream = new MemoryStream()) { if (IsBMP(Data)) { Bitmap BMap = new Bitmap(Data); BMap.Save(PNGStream, System.Drawing.Imaging.ImageFormat.Png); PNGStream.Seek(0, SeekOrigin.Begin); } else { Paloma.TargaImage TGA = new Paloma.TargaImage(Data); TGA.Image.Save(PNGStream, System.Drawing.Imaging.ImageFormat.Png); PNGStream.Seek(0, SeekOrigin.Begin); } return Texture2D.FromStream(m_Game.GraphicsDevice, PNGStream); } } /// <summary> /// Checks if the supplied data is a BMP. /// </summary> /// <param name="Data">The data as a Stream.</param> /// <returns>True if data was BMP, false otherwise.</returns> private static bool IsBMP(Stream Data) { BinaryReader Reader = new BinaryReader(Data, Encoding.UTF8, true); byte[] data = Reader.ReadBytes(2); byte[] magic = new byte[] { (byte)'B', (byte)'M' }; return data.SequenceEqual(magic); }
  20. Thought I'd stick my library here like muchaho. GonzoNet is a library designed for large scale distributed networking (think MMO.) It currently only supports TCP, UDP might be added in the future (UDP is uncommon for MMOs and so wasn't considered important when designing) Unlike a lot of other libraries out there, GonzoNet does not impose a protocol on an application, and so is more like a high level wrapper on top of .NETs asynchronous sockets. The code hasn't been cross compiled, but it uses no special namespaces that you shouldn't be able to find in Mono. It has been tested with up to 300 concurrent users in a real setting (Though no actual "gameplay" was involved, as the project it is used for hasn't progressed further than the character creation/selection/login stage.) GonzoNet supports authentication and encryption using Diffie Hellman EC, which was actually suggested to me on these boards!
  21. So I rewrote GonzoNet and my servers to use BlockingCollection instead of ArrayList and ConcurrentDictionary instead of Dictionary. However, I'm pretty sure I read on MSDN somewhere (I can't find the article right now) that I should be using BlockingCollection.GetConsumingEnumerable() when doing a foreach loop, because the standard foreach iterator will block threads. So... how would I then readd items into the collection after I'm done consuming them? Could I add them to a temp collection and replace the original one with the temp? Would that be safe?
  22. Josh Petrie, thanks for pointing out the license issues. I updated the headers for the files that were missing it, and sent a couple mails to the people who wrote the code for the ones where I deliberately didn't put a license. If they don't reply, can I put in License.md that these files are NOT covered by the license?   As for your MMO question, Project Dollhouse is an MMO - or rather a remake of one. The userbase is such that the I'll probably never get above 1000 simultaneous players, but I'm absolutely confident that GonzoNet could handle more. I'm going to write a test case to prove that.
  23.   1. Easy - because using straight async sockets means you're probably going to end up writing some kind of wrapper on your own anyway. I already did that! :) 2. GonzoNet has already been used in Project Dollhouse, which has 331,180 LOC (including GonzoNet) and been found to work quite nicely. However, I need to write more test cases to come up with more hard data! PS: Thanks for guiding me onto lock free queues! :)
  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!