tag:blogger.com,1999:blog-50067161126628041442023-11-15T17:46:58.263+01:00Urban DžindžinovičI have experience working with C++ and DirectX.
I prefer working with C# and WPF.
In my spare time I work with HTML, JS, CSS.Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comBlogger22125tag:blogger.com,1999:blog-5006716112662804144.post-68147840987779346542012-03-19T13:31:00.000+01:002019-05-03T19:40:19.615+02:00WinToFlash - Install Windows From USB<div style="font-family: "Courier New",Courier,monospace;">
If you try to install Windows XP Pro 64-bit edition and get the following error after formatting the hard drive:<br />
<br />
"The following value in the .SIF file used by setup is corrupted or missing: Value 0 on the line in section [SourceDisksFiles] with key 'SSA.exe.' Setup cannot continue."<br />
<br />
Use the advanced mode and uncheck option "Add additional files for installation process (SSA)".<br />
<br />
If you get this message on the first reboot after installing from the USB:<br />
<br />
"Windows could not start because of a computer disk hardware configuration problem.<br />
Could not read from the selected boot disk. Check boot path and disk hardware.<br />
Please check the Windows documentation about hardware disk configuration and your hardware reference manuals for additional information."<br />
<br />
Run the recovery console and try to fix the boot.ini with "bootcfg /rebuild".<br />
<br />
And if it still does not work?<br />
<br />
My boot.ini had the following line after the "bootcfg /rebuild":<br />
<br />
multi(0)disk(0)rdisk(1)partition(1)\WINDOWS="Windows XP Professional x64 Edition" /noexecute=optin /fastdetect<br />
<br />
I found the following difference (after reinstalling Windows from the CD) when the boot worked:<br />
<br />
multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Windows XP Professional x64 Edition" /noexecute=optin /fastdetect<br />
<br />
I guess I should have tried removing the USB key before executing the "bootcfg /rebuild".</div>
<div style="font-family: "Courier New",Courier,monospace;">
<br /></div>
Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-86816503059432728032010-06-03T17:01:00.012+02:002010-06-04T12:05:20.741+02:00Measure code execution time in C#To time a part of the code in a loop, use ResetTimingValue() before you enter the loop. Than use StartTiming() and AddTimingValue() to get the combined execution time of the code in the loop.<br /><script type="syntaxhighlighter" class="brush: csharp"><![CDATA[<br />public class ExecutionTimer<br />{<br /> private static bool[] _isTiming = { false, false, false };<br /> private static Stopwatch[] _stopwatch = { new Stopwatch(), new Stopwatch(), new Stopwatch() };<br /> private static Dictionary<string, long> _elapsedTicks = new Dictionary<string, long>();<br /><br /> public static Dictionary<string, double> _elapsedTime = new Dictionary<string, double>();<br /> public static double _allExecutionTime = 0.0;<br /><br /> public static void StartTiming(int depth)<br /> {<br /> if (_isTiming[depth])<br /> throw new Exception("Timing has already started. Call StopTiming() before you start timing again.");<br /><br /> _isTiming[depth] = true;<br /> _stopwatch[depth].Start();<br /> }<br /><br /> public static void StopTiming(int depth, string key)<br /> {<br /> _stopwatch[depth].Stop();<br /> _elapsedTicks[key] = _stopwatch[depth].ElapsedTicks;<br /> _stopwatch[depth].Reset();<br /> _isTiming[depth] = false;<br /> }<br /><br /> public static void ResetTimingValue(string key)<br /> {<br /> _elapsedTicks[key] = 0;<br /> }<br /><br /> public static void AddTimingValue(int depth, string key)<br /> {<br /> _stopwatch[depth].Stop();<br /> _elapsedTicks[key] += _stopwatch[depth].ElapsedTicks;<br /> _stopwatch[depth].Reset();<br /> _isTiming[depth] = false;<br /> }<br /><br /> public static void UpdateElapsedTimes()<br /> {<br /> _allExecutionTime = 0.0;<br /> foreach (KeyValuePair<string, long> tick in _elapsedTicks)<br /> {<br /> _elapsedTime[tick.Key] = 1000.0 * (double)tick.Value / Stopwatch.Frequency;<br /> _allExecutionTime += _elapsedTime[tick.Key];<br /> }<br /> }<br />}<br />]]></script><br />This test uses all the functions of the ExecutionTimer:<br /><script type="syntaxhighlighter" class="brush: csharp"><![CDATA[<br />class Demo<br />{<br /> float time = 0.0f;<br /><br /> void Test()<br /> {<br /> while (true)<br /> {<br /> Run(0.1f);<br /> }<br /> }<br /><br /> void Run(float elapsedTime)<br /> {<br /> ExecutionTimer.StartTiming(0);<br /><br /> ExecutionTimer.ResetTimingValue("A");<br /> ExecutionTimer.ResetTimingValue("C");<br /> for (int i = 0; i < 10; ++i)<br /> {<br /> ExecutionTimer.StartTiming(1);<br /> // do A<br /> ExecutionTimer.AddTimingValue(1, "A");<br /><br /> // do B<br /><br /> ExecutionTimer.StartTiming(1);<br /> // do C<br /> ExecutionTimer.AddTimingValue(1, "C");<br /> }<br /><br /> ExecutionTimer.StopTiming(0, "ABC");<br /><br /> // do D<br /><br /> ExecutionTimer.StartTiming(0);<br /> // do E<br /> ExecutionTimer.StartTiming(1);<br /> // do F<br /> ExecutionTimer.StartTiming(2);<br /> // do G<br /> ExecutionTimer.StopTiming(2, "G");<br /> // do H<br /> ExecutionTimer.StopTiming(1, "FGH");<br /> // do I<br /> ExecutionTimer.StopTiming(0, "EFGHI");<br /><br /> time += elapsedTime;<br /> if (time > 1.0f)<br /> {<br /> time -= 1.0f;<br /><br /> ExecutionTimer.UpdateElapsedTimes();<br /><br /> foreach (KeyValuePair<string, double> executionTime in ExecutionTimer._elapsedTime)<br /> {<br /> Console.WriteLine(String.Format("{0}: {1}", executionTime.Key, executionTime.Value));<br /> }<br /> }<br /> }<br />}<br />]]></script>Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-44980368197873437672010-06-01T14:55:00.003+02:002010-06-01T15:06:23.938+02:00Hide "Extras" by default in Photoshop 7When you select the Slice tool (or press K) in Photoshop 7, it enables View->Extras and View->Show->Slices. Two small rectangles appear in the upper left corner of the image. One shows "01" and the other shows a sliced image. That becomes the default view every time you open Photoshop. To hide this by default, first uncheck View->Show->Slices and than View->Extras.<br /><br />Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-31679004079961999152010-05-22T09:14:00.005+02:002010-05-22T14:04:08.086+02:00Meta Description and Keywords Tags for Blogger<a href="http://www.bloggerplugins.org/2008/06/meta-tags-for-blogger-blogspot.html">Meta Tags For Blogger / Blogspot</a> has a good explanation on how to insert the meta tags in your blog.<br /><br /><a href="http://bloggerstop.net/2009/04/duplicate-meta-description-and-titles.html">Duplicate Meta Description and Titles Issues In Blogger</a> assumes that you already have a meta tag inserted and explains how to prevent duplicates, so that search engines (like Google) will update the indexed site more frequently.<br /><br />Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-40452502564590686752010-05-17T11:00:00.002+02:002010-05-17T11:30:42.698+02:00Save XNA mesh with Managed DirectXThere are two options you can choose:<br /><br />1. You can run the code with the OptimizeInPlace() line as it is and the mesh will be saved with the texture name in the material property. The mesh will not be valid if you load it in XNA. To correct this, open the mesh file (*.x) with <a href="http://www.righthemisphere.com/products/dexp/">Deep Exploration</a> and save it again as a mesh file (*.x) and it will work with your XNA program. Be careful when you choose the "Save As..." options in Deep Exploration.<br /><br />2. You can comment out the OptimizeInPlace() and the mesh will be saved without the texture name.<br /><pre class="brush: csharp"><br />// Disable the loader lock MDA.<br />// Debug/Exceptions (ctrl-D, E), Open the Managed Debugging Assistants tree node and uncheck Loader Lock.<br />// This setting is per solution so it will only affect this solution.<br />using Microsoft.DirectX;<br />using Microsoft.DirectX.Direct3D;<br /><br />public class MeshManager<br />{<br /> Device device = null;<br /><br /> public MeshManager()<br /> {<br /> PresentParameters presentParams = new PresentParameters();<br /><br /> presentParams.Windowed = true;<br /> presentParams.SwapEffect = SwapEffect.Discard;<br /><br /> System.Windows.Forms.Form renderWindow = new System.Windows.Forms.Form();<br /><br /> device = new Device(0, DeviceType.Hardware, renderWindow, CreateFlags.SoftwareVertexProcessing, presentParams);<br /> }<br /><br /> public void SaveMesh(Microsoft.Xna.Framework.Graphics.VertexPositionNormalTexture[] verticesXna, short[] indicesXna,<br /> int numVertices, int numFaces, string meshFilename, string textureFilename)<br /> {<br /> CustomVertex.PositionNormalTextured[] vertices = new CustomVertex.PositionNormalTextured[numVertices];<br /><br /> for (int i = 0; i < numVertices; ++i)<br /> {<br /> vertices[i].Position = new Vector3(verticesXna[i].Position.X, verticesXna[i].Position.Y, -verticesXna[i].Position.Z);<br /> vertices[i].Normal = new Vector3(verticesXna[i].Normal.X, verticesXna[i].Normal.Y, -verticesXna[i].Normal.Z);<br /> vertices[i].Tu = verticesXna[i].TextureCoordinate.X;<br /> vertices[i].Tv = verticesXna[i].TextureCoordinate.Y;<br /> }<br /><br /> short[] indices = new short[numFaces * 3];<br /><br /> for (int i = 0; i < numFaces * 3; i += 3)<br /> {<br /> indices[i + 0] = indicesXna[i + 0];<br /> indices[i + 1] = indicesXna[i + 1];<br /> indices[i + 2] = indicesXna[i + 2];<br /> }<br /><br /> Mesh mesh = new Mesh(numFaces, numVertices, MeshFlags.Managed, CustomVertex.PositionNormalTextured.Format, device);<br /><br /> mesh.SetVertexBufferData(vertices, LockFlags.None);<br /> mesh.SetIndexBufferData(indices, LockFlags.None);<br /><br /> int[] adjac = new int[mesh.NumberFaces * 3];<br /> mesh.GenerateAdjacency(0.05f, adjac);<br /> // Comment the next line to save a valid mesh. Material will not be saved.<br /> mesh.OptimizeInPlace(MeshFlags.OptimizeVertexCache, adjac);<br /><br /> int subs = mesh.GetAttributeTable().Length;<br /> ExtendedMaterial[] extmat = new ExtendedMaterial[subs];<br /><br /> Material material = new Material();<br /> material.AmbientColor = new ColorValue(1.0f, 1.0f, 1.0f);<br /> material.DiffuseColor = new ColorValue(1.0f, 1.0f, 1.0f);<br /> material.EmissiveColor = new ColorValue(0.1f, 0.1f, 0.1f);<br /> material.SpecularColor = new ColorValue(0.1f, 0.1f, 0.1f);<br /> material.SpecularSharpness = 64.0f;<br /><br /> for (int i = 0; i < subs; i++)<br /> {<br /> extmat[i] = new ExtendedMaterial();<br /> extmat[i].Material3D = material;<br /> extmat[i].TextureFilename = textureFilename;<br /> }<br /><br /> mesh.Save(meshFilename, adjac, extmat, XFileFormat.Text);<br /> }<br />}<br /></pre>Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-35109690481088933982010-05-17T10:41:00.002+02:002010-05-17T10:55:26.694+02:00XNA Split screen on 4 Viewports<pre class="brush: csharp"><br />private Viewport[] _viewports = new Viewport[5];<br /><br />private void SetupViewports()<br />{<br /> int HalfWidth = this._GraphicsDeviceManager.PreferredBackBufferWidth / 2;<br /> int HalfHeight = this._GraphicsDeviceManager.PreferredBackBufferHeight / 2;<br /><br /> // full screen viewport for full screen text:<br /> _viewports[0] = new Viewport();<br /> _viewports[0].X = 0;<br /> _viewports[0].Y = 0;<br /> _viewports[0].Width = 2 * HalfWidth;<br /> _viewports[0].Height = 2 * HalfHeight;<br /><br /> // 1/4 screen viewports:<br /> _viewports[1] = new Viewport();<br /> _viewports[1].X = 0;<br /> _viewports[1].Y = 0;<br /> _viewports[1].Width = HalfWidth;<br /> _viewports[1].Height = HalfHeight;<br /><br /> _viewports[2] = new Viewport();<br /> _viewports[2].X = HalfWidth;<br /> _viewports[2].Y = 0;<br /> _viewports[2].Width = HalfWidth;<br /> _viewports[2].Height = HalfHeight;<br /><br /> _viewports[3] = new Viewport();<br /> _viewports[3].X = 0;<br /> _viewports[3].Y = HalfHeight;<br /> _viewports[3].Width = HalfWidth;<br /> _viewports[3].Height = HalfHeight;<br /><br /> _viewports[4] = new Viewport();<br /> _viewports[4].X = HalfWidth;<br /> _viewports[4].Y = HalfHeight;<br /> _viewports[4].Width = HalfWidth;<br /> _viewports[4].Height = HalfHeight;<br />}<br /><br />public void DrawScene()<br />{<br /> for (int i = 0; i < 4; ++i)<br /> {<br /> _GraphicsDevice.Viewport = _viewports[i + 1];<br /> // TODO: set view and projection matrix<br /> // TODO: draw viewport<br /> }<br /><br /> _GraphicsDevice.Viewport = _viewports[0];<br /> // TODO: set view and projection matrix<br /> // TODO: draw full screen text<br />}<br /></pre>Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-5511441441066532722010-05-16T11:36:00.002+02:002010-05-16T11:40:23.526+02:00C# Object Serialization to XML file<pre class="brush: csharp"><br />public class XmlSerializationManager<br />{<br /> public static void SaveObjectToXmlFile(String path, Object _object, Type _type)<br /> {<br /> FileStream stream = File.Open(path, FileMode.Create, FileAccess.Write);<br /><br /> XmlSerializer serializer = new XmlSerializer(_type);<br /> serializer.Serialize(stream, _object);<br /><br /> stream.Close();<br /> }<br /><br /> public static void SaveObjectToXmlFile(String path, Object _object, Type _type, Type[] extraTypes)<br /> {<br /> FileStream stream = File.Open(path, FileMode.Create, FileAccess.Write);<br /><br /> XmlSerializer serializer = new XmlSerializer(_type, extraTypes);<br /> serializer.Serialize(stream, _object);<br /><br /> stream.Close();<br /> }<br /><br /> public static Object LoadObjectFromXmlFile(String path, Type _type)<br /> {<br /> if (!File.Exists(path))<br /> {<br /> return null;<br /> }<br /><br /> FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read);<br /><br /> if (stream.Length == 0)<br /> {<br /> return null;<br /> }<br /><br /> XmlSerializer serializer = new XmlSerializer(_type);<br /> Object _object = serializer.Deserialize(stream);<br /><br /> stream.Close();<br /><br /> return _object;<br /> }<br /><br /> public static Object LoadObjectFromXmlFile(String path, Type _type, Type[] extraTypes)<br /> {<br /> if (!File.Exists(path))<br /> {<br /> return null;<br /> }<br /><br /> FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read);<br /><br /> if (stream.Length == 0)<br /> {<br /> return null;<br /> }<br /><br /> XmlSerializer serializer = new XmlSerializer(_type, extraTypes);<br /> Object _object = serializer.Deserialize(stream);<br /><br /> stream.Close();<br /><br /> return _object;<br /> }<br />}<br /></pre>Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-4736964400228032572010-05-16T11:27:00.004+02:002010-05-16T11:34:43.903+02:00C# Logger - Write strings to log file<pre class="brush: csharp"><br />public class Logger<br />{<br /> public static bool _doLog = true;<br /><br /> public static void Log(String filename, String Message)<br /> {<br /> if (!_doLog)<br /> return;<br /><br /> if (File.Exists(filename))<br /> {<br /> using (StreamWriter sw = File.AppendText(filename))<br /> {<br /> sw.WriteLine(String.Format("{0} : {1}", DateTime.Now, Message));<br /> sw.Close();<br /> }<br /> }<br /> else<br /> {<br /> using (StreamWriter sw = File.CreateText(filename))<br /> {<br /> sw.WriteLine(String.Format("{0} : {1}", DateTime.Now, Message));<br /> sw.Close();<br /> }<br /> }<br /> }<br />}<br /></pre>Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-18212753631677448552010-05-15T10:39:00.000+02:002010-05-15T10:41:22.668+02:00XNA Set Graphics Mode<pre class="brush: csharp"><br />public bool SetGraphicsMode(int Width, int Height, bool isFullScreen)<br />{<br /> // If we aren't using a full screen mode, the height and width of the window can<br /> // be set to anything equal to or smaller than the actual screen size.<br /> if (isFullScreen == false)<br /> {<br /> if ((Width <= GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width)<br /> && (Height <= GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height))<br /> {<br /> _GraphicsDeviceManager.PreferredBackBufferWidth = Width;<br /> _GraphicsDeviceManager.PreferredBackBufferHeight = Height;<br /> _GraphicsDeviceManager.IsFullScreen = isFullScreen;<br /> _GraphicsDeviceManager.ApplyChanges();<br /><br /> return true;<br /> }<br /> }<br /> else<br /> {<br /> // If we are using full screen mode, we should check to make sure that the display<br /> // adapter can handle the video mode we are trying to set. To do this, we will<br /> // iterate thorugh the display modes supported by the adapter and check them against<br /> // the mode we want to set.<br /> foreach (DisplayMode dm in GraphicsAdapter.DefaultAdapter.SupportedDisplayModes)<br /> {<br /> // Check the width and height of each mode against the passed values<br /> if ((dm.Width == Width) && (dm.Height == Height))<br /> {<br /> // The mode is supported, so set the buffer formats, apply changes and return<br /> _GraphicsDeviceManager.PreferredBackBufferWidth = Width;<br /> _GraphicsDeviceManager.PreferredBackBufferHeight = Height;<br /> _GraphicsDeviceManager.IsFullScreen = isFullScreen;<br /> _GraphicsDeviceManager.ApplyChanges();<br /><br /> return true;<br /> }<br /> }<br /> }<br /> return false;<br />}<br /></pre>Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-73904587266778741352010-05-15T10:29:00.003+02:002010-06-04T11:46:28.135+02:00XNA Get Model vertices for BoundingBox<script type="syntaxhighlighter" class="brush: csharp"><![CDATA[<br />public BoundingBox ComputeBoundingBox()<br />{<br /> Vector3 min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);<br /> Vector3 max = new Vector3(float.MinValue, float.MinValue, float.MinValue);<br /><br /> Matrix[] bones = new Matrix[this._model.Bones.Count];<br /> this._model.CopyAbsoluteBoneTransformsTo(bones);<br /><br /> List<Vector3> vertices = new List<Vector3>();<br /><br /> foreach (ModelMesh mesh in this._model.Meshes)<br /> {<br /> //get the transform of the current mesh<br /> Matrix transform = bones[mesh.ParentBone.Index];<br /><br /> foreach (ModelMeshPart part in mesh.MeshParts)<br /> {<br /> //get the current mesh info<br /> int stride = part.VertexStride;<br /> int numVertices = part.NumVertices;<br /> byte[] verticesData = new byte[stride * numVertices];<br /><br /> mesh.VertexBuffer.GetData(verticesData);<br /><br /> for (int i = 0; i < verticesData.Length; i += stride)<br /> {<br /> float x = BitConverter.ToSingle(verticesData, i);<br /> float y = BitConverter.ToSingle(verticesData, i + sizeof(float));<br /> float z = BitConverter.ToSingle(verticesData, i + 2 * sizeof(float));<br /><br /> Vector3 vector = new Vector3(x, y, z);<br /> //apply transform to the current point<br /> vector = Vector3.Transform(vector, transform);<br /><br /> vertices.Add(vector);<br /><br /> if (vector.X < min.X) min.X = vector.X;<br /> if (vector.Y < min.Y) min.Y = vector.Y;<br /> if (vector.Z < min.Z) min.Z = vector.Z;<br /> if (vector.X > max.X) max.X = vector.X;<br /> if (vector.Y > max.Y) max.Y = vector.Y;<br /> if (vector.Z > max.Z) max.Z = vector.Z;<br /> }<br /> }<br /> }<br /><br /> this._VerticesCount = vertices.Count;<br /> this._Vertices = vertices.ToArray();<br /><br /> return new BoundingBox(min, max);<br />}<br />]]></script>Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-35160886411677178852010-05-14T10:14:00.005+02:002010-05-14T10:27:46.503+02:00XNA Pick model triangle with rayYou can find GetMouseCursorRay and RayIntersectTriangle on this blog.<br /><pre class="brush: csharp"><br />public bool PickedTriangle(Ray cursorRay, ref Vector3 intersection, ref float distance, ref int[] triangle)<br />{<br /> float pickDist = 0.0f; // distance from ray origin to intersection<br /> float pickU = 0.0f; // barycentric coordinate of intersection<br /> float pickV = 0.0f; // barycentric coordinate of intersection<br /><br /> for (int i = 0; i < (this._IndicesCount / 3); ++i)<br /> {<br /> // changed from left handed (DirectX) to right handed (XNA)<br /> Vector3 tri0 = this._transformedVertices[this._Indices[3 * i + 0]];<br /> Vector3 tri1 = this._transformedVertices[this._Indices[3 * i + 2]];<br /> Vector3 tri2 = this._transformedVertices[this._Indices[3 * i + 1]];<br /><br /> // Check if the pick ray passes through this point<br /> if (RayIntersectTriangle(cursorRay.Position, cursorRay.Direction, tri0, tri1, tri2, ref pickDist, ref pickU, ref pickV))<br /> {<br /> if (pickDist > 0.0f)<br /> {<br /> intersection = pickU * tri1 + pickV * tri2 + (1 - pickU - pickV) * tri0;<br /> distance = pickDist;<br /><br /> triangle[0] = 3 * i + 0;<br /> triangle[1] = 3 * i + 2;<br /> triangle[2] = 3 * i + 1;<br /><br /> return true;<br /> }<br /> }<br /> }<br /><br /> return false;<br />}<br /></pre>Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-466356601446891642010-05-14T10:04:00.004+02:002010-05-14T10:13:46.727+02:00XNA Get mouse cursor ray<pre class="brush: csharp"><br />public Ray GetMouseCursorRay(MouseState _CurrentMouseState, Matrix _projectionMatrix, Matrix _viewMatrix)<br />{<br /> // Create 2 positions in screenspace using the cursor position.<br /> // 0 is as close as possible to the camera, 1 is as far away as possible.<br /> Vector3 nearSource = new Vector3(_CurrentMouseState.X, _CurrentMouseState.Y, 0.0f);<br /> Vector3 farSource = new Vector3(_CurrentMouseState.X, _CurrentMouseState.Y, 1.0f);<br /><br /> // Use Viewport. Unproject to tell what those two screen space positions would be in world space. <br /> // We'll need the projection matrix and view matrix, which we have saved as member variables. <br /> // We also need a world matrix, which can just be identity.<br /> Vector3 nearPoint = _GraphicsDevice.Viewport.Unproject(nearSource, _projectionMatrix, _viewMatrix, Matrix.Identity);<br /> Vector3 farPoint = _GraphicsDevice.Viewport.Unproject(farSource, _projectionMatrix, _viewMatrix, Matrix.Identity);<br /><br /> // Find the direction vector that goes from the nearPoint to the farPoint and normalize it...<br /> Vector3 direction = farPoint - nearPoint;<br /> direction.Normalize();<br /><br /> // ... and then create a new ray using nearPoint as the source.<br /> return new Ray(nearPoint, direction);<br />}<br /></pre>Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-36437420825939247912010-05-14T10:00:00.001+02:002019-05-04T15:26:14.259+02:00XNA Ray Intersect Triangle<pre class="brush: csharp">private bool RayIntersectTriangle(Vector3 rayPosition, Vector3 rayDirection, Vector3 tri0, Vector3 tri1, Vector3 tri2,
ref float pickDistance, ref float barycentricU, ref float barycentricV)
{
// Find vectors for two edges sharing vert0
Vector3 edge1 = tri1 - tri0;
Vector3 edge2 = tri2 - tri0;
// Begin calculating determinant - also used to calculate barycentricU parameter
Vector3 pvec = Vector3.Cross(rayDirection, edge2);
// If determinant is near zero, ray lies in plane of triangle
float det = Vector3.Dot(edge1, pvec);
if (det < 0.0001f)
return false;
// Calculate distance from vert0 to ray origin
Vector3 tvec = rayPosition - tri0;
// Calculate barycentricU parameter and test bounds
barycentricU = Vector3.Dot(tvec, pvec);
if (barycentricU < 0.0f || barycentricU > det)
return false;
// Prepare to test barycentricV parameter
Vector3 qvec = Vector3.Cross(tvec, edge1);
// Calculate barycentricV parameter and test bounds
barycentricV = Vector3.Dot(rayDirection, qvec);
if (barycentricV < 0.0f || barycentricU + barycentricV > det)
return false;
// Calculate pickDistance, scale parameters, ray intersects triangle
pickDistance = Vector3.Dot(edge2, qvec);
float fInvDet = 1.0f / det;
pickDistance *= fInvDet;
barycentricU *= fInvDet;
barycentricV *= fInvDet;
return true;
}</pre>
Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-59309089080212879112010-05-13T10:27:00.005+02:002010-05-13T10:35:14.485+02:00XNA Restore SpriteBatch changes on GraphicsDeviceRestore SpriteBatch changes of RenderState and SamplerStates on GraphicsDevice to default:<br /><pre class="brush: csharp"><br />public void SetGraphicsDeviceStates()<br />{<br /> // SpriteBatch changes:<br /> //_graphicsDevice.RenderState.CullMode = CullMode.CullCounterClockwiseFace;<br /> //_graphicsDevice.RenderState.DepthBufferEnable = false;<br /> //_graphicsDevice.RenderState.AlphaBlendEnable = true;<br /> //_graphicsDevice.RenderState.AlphaBlendOperation = BlendFunction.Add;<br /> //_graphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;<br /> //_graphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;<br /> //_graphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;<br /> //_graphicsDevice.RenderState.AlphaTestEnable = true;<br /> //_graphicsDevice.RenderState.AlphaFunction = CompareFunction.Greater;<br /> //_graphicsDevice.RenderState.ReferenceAlpha = 0;<br /> //_graphicsDevice.SamplerStates[0].AddressU = TextureAddressMode.Clamp;<br /> //_graphicsDevice.SamplerStates[0].AddressV = TextureAddressMode.Clamp;<br /> //_graphicsDevice.SamplerStates[0].MagFilter = TextureFilter.Linear;<br /> //_graphicsDevice.SamplerStates[0].MinFilter = TextureFilter.Linear;<br /> //_graphicsDevice.SamplerStates[0].MipFilter = TextureFilter.Linear;<br /> //_graphicsDevice.SamplerStates[0].MipMapLevelOfDetailBias = 0.0f;<br /> //_graphicsDevice.SamplerStates[0].MaxMipLevel = 0;<br /><br /> // Correct SpriteBatch changes:<br /> _graphicsDevice.RenderState.DepthBufferEnable = true;<br /> _graphicsDevice.RenderState.AlphaBlendEnable = false;<br /><br /> _graphicsDevice.RenderState.SourceBlend = Blend.One;<br /> _graphicsDevice.RenderState.DestinationBlend = Blend.Zero;<br /><br /> _graphicsDevice.RenderState.AlphaTestEnable = false;<br /> _graphicsDevice.RenderState.AlphaFunction = CompareFunction.Always;<br /><br /> _graphicsDevice.SamplerStates[0].AddressU = TextureAddressMode.Wrap;<br /> _graphicsDevice.SamplerStates[0].AddressV = TextureAddressMode.Wrap;<br /> _graphicsDevice.SamplerStates[0].MagFilter = TextureFilter.Point;<br /> _graphicsDevice.SamplerStates[0].MinFilter = TextureFilter.Point;<br /> _graphicsDevice.SamplerStates[0].MipFilter = TextureFilter.None;<br />}<br /></pre>Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-29807028034701607282010-05-13T10:19:00.001+02:002010-05-13T10:21:45.383+02:00XNA bool IsSpecialKey(Keys key)<pre class="brush: csharp"><br />public bool IsSpecialKey(Keys key)<br />{<br /> // All keys except A-Z, 0-9 and `-\[];',./= (and space) are special keys.<br /> // With shift pressed this also results in this keys:<br /> // ~_|{}:"<>? !@#$%^&*().<br /><br /> int keyNum = (int)key;<br /><br /> if ((keyNum >= (int)Keys.A && keyNum <= (int)Keys.Z) ||<br /> (keyNum >= (int)Keys.D0 && keyNum <= (int)Keys.D9) ||<br /> key == Keys.Space || // well, space ^^<br /> key == Keys.OemTilde || // `~<br /> key == Keys.OemMinus || // -_<br /> key == Keys.OemPipe || // \|<br /> key == Keys.OemOpenBrackets || // [{<br /> key == Keys.OemCloseBrackets || // ]}<br /> key == Keys.OemQuotes || // '"<br /> key == Keys.OemQuestion || // /?<br /> key == Keys.OemPlus) // =+<br /> {<br /> return false;<br /> }<br /><br /> return true;<br />}<br /></pre>Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-38897472046776446282010-05-12T10:32:00.002+02:002010-05-15T10:21:14.414+02:00XNA Camera Direction from Orientation<pre class="brush: csharp"><br />_cameraDirection = new Vector3((float)Math.Sin(_cameraAngle.Y) * (float)Math.Cos(_cameraAngle.X),<br /> -(float)Math.Sin(_cameraAngle.X),<br /> (float)Math.Cos(_cameraAngle.Y) * (float)Math.Cos(_cameraAngle.X));<br /></pre><br />Forward vector from euler angles:<br /><pre class="brush: csharp"><br />public Vector3 _Forward<br />{<br /> get<br /> {<br /> return new Vector3((float)Math.Sin(_orientation.Y) * (float)Math.Cos(_orientation.X),<br /> -(float)Math.Sin(_orientation.X),<br /> (float)Math.Cos(_orientation.Y) * (float)Math.Cos(_orientation.X));<br /> }<br />}<br /></pre>Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-76488125555042841832010-05-12T10:27:00.003+02:002010-05-12T10:30:34.279+02:00Visual Studio Find and ReplaceLook at these file types:<br /><br />HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Find\Filter<br /><br />Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-23287781466447080002010-05-11T10:38:00.000+02:002010-05-11T10:41:14.728+02:00Reposition a console window in C++<pre class="brush: cpp"><br />void RePositionWindow(int x, int y)<br />{<br /> HWND windowHandle = GetConsoleWindow();<br /> RECT rect;<br /> GetWindowRect(windowHandle, &rect);<br /> MoveWindow(windowHandle, x, y, rect.right - rect.left, rect.bottom - rect.top, true);<br />}<br /></pre>Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-50354188624084086802010-05-11T10:29:00.002+02:002010-05-11T10:35:23.678+02:00C++ version of C# Random.Next(int minValue, int maxValue);<pre class="brush: cpp"><br />int Random(int min, int max)<br />{<br /> return (int)((double)rand() / ((double)RAND_MAX + 1.0) * (double)(max - min) + (double)min);<br />}<br /></pre>Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-23564303379133171952010-05-11T10:23:00.002+02:002010-11-28T15:18:43.251+01:00XNA Random Point On PlaneThis method generates random points in a circle with a specified radius. The circle lies on a plane defined with a position and a normal. The generated points have an uniform distribution.<br /><pre class="brush: csharp"><br />Random _random = new Random();<br /><br />private Vector3 RandomPointOnPlane(Vector3 position, Vector3 normal, float radius)<br />{<br /> Vector3 random = new Vector3();<br /> Vector3 randomPoint;<br /><br /> do<br /> {<br /> random.X = 2.0f * (float)_random.NextDouble() - 1.0f;<br /> random.Y = 2.0f * (float)_random.NextDouble() - 1.0f;<br /> random.Z = 2.0f * (float)_random.NextDouble() - 1.0f;<br /> Vector3.Cross(ref random, ref normal, out randomPoint);<br /> } while (randomPoint == Vector3.Zero);<br /><br /> randomPoint.Normalize();<br /> randomPoint *= radius * (float)Math.Sqrt(_random.NextDouble());<br /> randomPoint += position;<br /><br /> return randomPoint;<br />}<br /></pre>Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-19841198718532422662010-05-11T10:12:00.006+02:002010-05-12T10:30:48.706+02:00Code syntax highlighting<a href="http://blog.cartercole.com/2009/10/awesome-syntax-highlighting-made-easy.html">Awesome code syntax highlighting made easy</a> has instructions on how to use <a href="http://alexgorbatchev.com/wiki/SyntaxHighlighter">SyntaxHighlighter</a> on <a href="http://www.blogger.com/">Blogger</a>.<br /><br />Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.comtag:blogger.com,1999:blog-5006716112662804144.post-59687950448293243442010-05-10T20:42:00.003+02:002010-05-20T11:48:06.204+02:00XNA Random Point In CircleThe function creates a random point in a circle on the XZ plane.<br /><pre class="brush: csharp"><br />Random _random = new Random();<br /><br />private Vector3 RandomPointInCircle(Vector3 position, float radius)<br />{<br /> float randomRadius = radius * (float)Math.Sqrt(_random.NextDouble());<br /><br /> double randomAngle = _random.NextDouble() * MathHelper.TwoPi;<br /><br /> float x = randomRadius * (float)Math.Cos(randomAngle);<br /> float z = randomRadius * (float)Math.Sin(randomAngle);<br /><br /> return new Vector3(position.X + x, position.Y, position.Z + z);<br />}<br /></pre>Urban Džindžinovičhttp://www.blogger.com/profile/11275203352292847827noreply@blogger.com