Search Results

Search found 3160 results on 127 pages for 'nomad zero'.

Page 18/127 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Stencil mask with AlphaTestEffect

    - by Brendan Wanlass
    I am trying to pull off the following effect in XNA 4.0: http://eng.utah.edu/~brendanw/question.jpg The purple area has 50% opacity. I have gotten pretty close with the following code: public static DepthStencilState AlwaysStencilState = new DepthStencilState() { StencilEnable = true, StencilFunction = CompareFunction.Always, StencilPass = StencilOperation.Replace, ReferenceStencil = 1, DepthBufferEnable = false, }; public static DepthStencilState EqualStencilState = new DepthStencilState() { StencilEnable = true, StencilFunction = CompareFunction.Equal, StencilPass = StencilOperation.Keep, ReferenceStencil = 1, DepthBufferEnable = false, }; ... if (_alphaEffect == null) { _alphaEffect = new AlphaTestEffect(_spriteBatch.GraphicsDevice); _alphaEffect.AlphaFunction = CompareFunction.LessEqual; _alphaEffect.ReferenceAlpha = 129; Matrix projection = Matrix.CreateOrthographicOffCenter(0, _spriteBatch.GraphicsDevice.PresentationParameters.BackBufferWidth, _spriteBatch.GraphicsDevice.PresentationParameters.BackBufferHeight, 0, 0, 1); _alphaEffect.Projection = world.SystemManager.GetSystem<RenderSystem>().Camera.View * projection; } _mask = new RenderTarget2D(_spriteBatch.GraphicsDevice, _spriteBatch.GraphicsDevice.PresentationParameters.BackBufferWidth, _spriteBatch.GraphicsDevice.PresentationParameters.BackBufferHeight, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8); _spriteBatch.GraphicsDevice.SetRenderTarget(_mask); _spriteBatch.GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.Stencil, Color.Transparent, 0, 0); _spriteBatch.Begin(SpriteSortMode.Immediate, null, null, AlwaysStencilState, null, _alphaEffect); _spriteBatch.Draw(sprite.Texture, position, sprite.SourceRectangle,Color.White, 0f, sprite.Origin, 1f, SpriteEffects.None, 0); _spriteBatch.End(); _spriteBatch.Begin(SpriteSortMode.Immediate, null, null, EqualStencilState, null, null); _spriteBatch.Draw(_maskTex, new Vector2(x * _maskTex.Width, y * _maskTex.Height), null, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0); _spriteBatch.End(); _spriteBatch.GraphicsDevice.SetRenderTarget(null); _spriteBatch.GraphicsDevice.Clear(Color.Black); _spriteBatch.Begin(); _spriteBatch.Draw((Texture2D)_mask, Vector2.Zero, null, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, layer/max_layer); _spriteBatch.End(); My problem is, I can't get the AlphaTestEffect to behave. I can either mask over the semi-transparent purple junk and fill it in with the green design, or I can draw over the completely opaque grassy texture. How can I specify the exact opacity that needs to be replace with the green design?

    Read the article

  • Correct For Loop Design

    - by Yttrill
    What is the correct design for a for loop? Felix currently uses if len a > 0 do for var i in 0 upto len a - 1 do println a.[i]; done done which is inclusive of the upper bound. This is necessary to support the full range of values of a typical integer type. However the for loop shown does not support zero length arrays, hence the special test, nor will the subtraction of 1 work convincingly if the length of the array is equal to the number of integers. (I say convincingly because it may be that 0 - 1 = maxval: this is true in C for unsigned int, but are you sure it is true for unsigned char without thinking carefully about integral promotions?) The actual implementation of the for loop by my compiler does correctly handle 0 but this requires two tests to implement the loop: continue: if not (i <= bound) goto break body if i == bound goto break ++i goto continue break: Throw in the hand coded zero check in the array example and three tests are needed. If the loop were exclusive it would handle zero properly, avoiding the special test, but there'd be no way to express the upper bound of an array with maximum size. Note the C way of doing this: for(i=0; predicate(i); increment(i)) has the same problem. The predicate is tested after the increment, but the terminating increment is not universally valid! There is a general argument that a simple exclusive loop is enough: promote the index to a large type to prevent overflow, and assume no one will ever loop to the maximum value of this type.. but I'm not entirely convinced: if you promoted to C's size_t and looped from the second largest value to the largest you'd get an infinite loop!

    Read the article

  • Red Dot Scope Makes Sighting In Long Lenses a Snap

    - by Jason Fitzpatrick
    If you’ve ever used a high power lens, you know how tricky it can be to sight a distant subject as the field of view through the lens is so tiny. This hack takes care of that problem by using a zero-magnification red dot rifle scope. Chris Malcolm enjoys photographing birds and other wildlife with high power lenses. The problem, when shooting with huge 500mm lens and other high power lenses, is that they’re practically telescopes and acquiring a fast moving target like a bird using a through-the-lens technique is very tricky. Malcolm’s solution hinges on mounting a zero-magnification red dot rifle scope in parallel with the lens. His mock up is a bit unpolished (although we can understand not wanting to run out and buy a brand new black scope just for the experiment) but works great to get him on target. Hit up the link below to read more about his build, how be created the rail mount for the scope, and why he opted to mount it to the barrel of the lens and not the hot shoe mount on the camera. 500mm Reflex Lens with Red Dot Sight [via DIY Photography] Make Your Own Windows 8 Start Button with Zero Memory Usage Reader Request: How To Repair Blurry Photos HTG Explains: What Can You Find in an Email Header?

    Read the article

  • "Accumulate" buffer results in XNA4?

    - by Utkarsh Sinha
    I'm trying to simulate a "heightmap" buffer in XNA4.0 but the results don't look correct. Here's what I'm hoping to achieve: http://www.youtube.com/watch?feature=player_detailpage&v=-Q6ISVaM5Ww#t=517s (8:38). From what I understand, here are the steps to reach there: Pass height buffer + current entity's heightmap Generate a stencil and update the height buffer Render sprite+stencil For now, I'm just trying to get the height buffer thing to work. So here's the problem. Inside the draw loop, I do the following: Create a new render target & set it Draw the heightmap with a sprite batch(no shaders) graphicsDevice.SetRenderTarget(null) Draw the rendertarget with SpriteBatch I expected to see all entities' heightmaps. But only the last entity's heightmap is visible. Any hints on what I'm doing wrong? Here's the code inside the draw loop: RenderTarget2D tempDepthStencil = new RenderTarget2D(graphicsDevice, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height, false, graphicsDevice.DisplayMode.Format, DepthFormat.None); graphicsDevice.SetRenderTarget(tempDepthStencil); // Gather depth information SpriteBatch depthStencilSpriteBatch = new SpriteBatch(graphicsDevice); depthStencilSpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise); depthStencilSpriteBatch.Draw(texHeightmap, pos, null, Color.White, 0, Vector2.Zero, 1, spriteEffects, 1); depthStencilSpriteBatch.End(); graphicsDevice.SetRenderTarget(null); SpriteBatch b1 = new SpriteBatch(graphicsDevice); b1.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null); b1.Draw((Texture2D)tempDepthStencil, Vector2.Zero, null, Color.White, 0, Vector2.Zero, 1, spriteEffects, 1); b1.End();

    Read the article

  • Upgrading Oracle Siebel CRM Application Without Downtime

    - by Doug Reid
    Oracle’s Siebel Customer Relationship Management (CRM) software helps organizations differentiate their businesses to achieve top- and bottom-line growth. Siebel CRM delivers comprehensive solutions that are tailored to more than 20 different industries. As Siebel CRM implementations have evolved into mission critical, operational business processes that must operate 24/7, companies are finding it increasingly difficult to afford the downtime typically required to perform an in-place upgrade. Without these upgrades, businesses loose out on critical new features and functionality. With Oracle GoldenGate, customers don’t have to choose between upgrades and outages. Oracle GoldenGate allows Siebel CRM customers to perform upgrades with zero downtime. Now Siebel customers can always take advantages of the latest innovations in customer relationship management without having to worry about potential lost revenue due to downtime. Oracle GoldenGate provides three different deployment models for Siebel CRM zero downtime upgrades that are designed to meet differing customer requirements. These range from a basic unidirectional model, which is designed to work out-of-the-box, to the most sophisticated active-active model for phased migrations. If you have mission-critical Siebel CRM implementations I recommend that you watch the screencast below to learn how you can begin taking advantage of all the latest Siebel enhancements without having any downtime. This screencast is also available on Oracle Media Network and Oracle's YouTube channel. For even more details I recommend reading the whitepaper Upgrading Siebel CRM with Zero Downtime .

    Read the article

  • How do I implement SkyBox in xna 4.0 Reach Profile (for Windows Phone 7)?

    - by Biny
    I'm trying to Implement SkyBox in my phone game. Most of the samples in the web are for HiDef profile, and they are using custom effects (that not supported on Windows Phone). I've tried to follow this guide. But for some reason my SkyBox is not rendered. This is my SkyBox class: using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Rocuna.Core; using Rocuna.GameEngine.Graphics; using Rocuna.GameEngine.Graphics.Components; namespace Rocuna.GameEngine.Extension.WP7.Graphics { /// <summary> /// Sky box element for phone games. /// </summary> public class SkyBox : SkyBoxBase { /// <summary> /// Initializes a new instance of the <see cref="SkyBoxBase"/> class. /// </summary> /// <param name="game">The Game that the game component should be attached to.</param> public SkyBox(TextureCube cube, Game game) : base(game) { Cube = cube; CubeFaces = new Texture2D[6]; PositionOffset = new Vector3(20, 20, 20); CreateGraphic(512); StripTexturesFromCube(); InitializeData(Game.GraphicsDevice); } #region Properties /// <summary> /// Gets or sets the position offset. /// </summary> /// <value> /// The position offset. /// </value> public Vector3 PositionOffset { get; set; } /// <summary> /// Gets or sets the position. /// </summary> /// <value> /// The position. /// </value> public Vector3 Position { get; set; } /// <summary> /// Gets or sets the cube. /// </summary> /// <value> /// The cube. /// </value> public TextureCube Cube { get; set; } /// <summary> /// Gets or sets the pixel array. /// </summary> /// <value> /// The pixel array. /// </value> public Color[] PixelArray { get; set; } /// <summary> /// Gets or sets the cube faces. /// </summary> /// <value> /// The cube faces. /// </value> public Texture2D[] CubeFaces { get; set; } /// <summary> /// Gets or sets the vertex buffer. /// </summary> /// <value> /// The vertex buffer. /// </value> public VertexBuffer VertexBuffer { get; set; } /// <summary> /// Gets or sets the index buffer. /// </summary> /// <value> /// The index buffer. /// </value> public IndexBuffer IndexBuffer { get; set; } /// <summary> /// Gets or sets the effect. /// </summary> /// <value> /// The effect. /// </value> public BasicEffect Effect { get; set; } #endregion protected override void LoadContent() { } public override void Update(GameTime gameTime) { var camera = Game.GetService<GraphicManager>().CurrentCamera; this.Position = camera.Position + PositionOffset; base.Update(gameTime); } public override void Draw(GameTime gameTime) { DrawOrder = int.MaxValue; var graphics = Effect.GraphicsDevice; graphics.DepthStencilState = new DepthStencilState() { DepthBufferEnable = false }; graphics.RasterizerState = new RasterizerState() { CullMode = CullMode.None }; graphics.BlendState = new BlendState(); graphics.SamplerStates[0] = SamplerState.AnisotropicClamp; graphics.SetVertexBuffer(VertexBuffer); graphics.Indices = IndexBuffer; Effect.Texture = CubeFaces[0]; Effect.CurrentTechnique.Passes[0].Apply(); graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 0, 2); Effect.Texture = CubeFaces[1]; Effect.CurrentTechnique.Passes[0].Apply(); graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 6, 2); Effect.Texture = CubeFaces[2]; Effect.CurrentTechnique.Passes[0].Apply(); graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 12, 2); Effect.Texture = CubeFaces[3]; Effect.CurrentTechnique.Passes[0].Apply(); graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 18, 2); Effect.Texture = CubeFaces[4]; Effect.CurrentTechnique.Passes[0].Apply(); graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 24, 2); Effect.Texture = CubeFaces[5]; Effect.CurrentTechnique.Passes[0].Apply(); graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 30, 2); base.Draw(gameTime); } #region Fields private List<VertexPositionNormalTexture> _vertices = new List<VertexPositionNormalTexture>(); private List<ushort> _indices = new List<ushort>(); #endregion #region Private methods private void InitializeData(GraphicsDevice graphicsDevice) { VertexBuffer = new VertexBuffer(graphicsDevice, typeof(VertexPositionNormalTexture), _vertices.Count, BufferUsage.None); VertexBuffer.SetData<VertexPositionNormalTexture>(_vertices.ToArray()); // Create an index buffer, and copy our index data into it. IndexBuffer = new IndexBuffer(graphicsDevice, typeof(ushort), _indices.Count, BufferUsage.None); IndexBuffer.SetData<ushort>(_indices.ToArray()); // Create a BasicEffect, which will be used to render the primitive. Effect = new BasicEffect(graphicsDevice); Effect.TextureEnabled = true; Effect.EnableDefaultLighting(); } private void CreateGraphic(float size) { Vector3[] normals = { Vector3.Right, Vector3.Left, Vector3.Up, Vector3.Down, Vector3.Backward, Vector3.Forward, }; Vector2[] textureCoordinates = { Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, }; var index = 0; foreach (var normal in normals) { var side1 = new Vector3(normal.Z, normal.X, normal.Y); var side2 = Vector3.Cross(normal, side1); AddIndex(CurrentVertex + 0); AddIndex(CurrentVertex + 1); AddIndex(CurrentVertex + 2); AddIndex(CurrentVertex + 0); AddIndex(CurrentVertex + 2); AddIndex(CurrentVertex + 3); AddVertex((normal - side1 - side2) * size / 2, normal, textureCoordinates[index++]); AddVertex((normal - side1 + side2) * size / 2, normal, textureCoordinates[index++]); AddVertex((normal + side1 + side2) * size / 2, normal, textureCoordinates[index++]); AddVertex((normal + side1 - side2) * size / 2, normal, textureCoordinates[index++]); } } protected void StripTexturesFromCube() { PixelArray = new Color[Cube.Size * Cube.Size]; for (int s = 0; s < CubeFaces.Length; s++) { CubeFaces[s] = new Texture2D(Game.GraphicsDevice, Cube.Size, Cube.Size, false, SurfaceFormat.Color); switch (s) { case 0: Cube.GetData<Color>(CubeMapFace.PositiveX, PixelArray); CubeFaces[s].SetData<Color>(PixelArray); break; case 1: Cube.GetData(CubeMapFace.NegativeX, PixelArray); CubeFaces[s].SetData(PixelArray); break; case 2: Cube.GetData(CubeMapFace.PositiveY, PixelArray); CubeFaces[s].SetData(PixelArray); break; case 3: Cube.GetData(CubeMapFace.NegativeY, PixelArray); CubeFaces[s].SetData(PixelArray); break; case 4: Cube.GetData(CubeMapFace.PositiveZ, PixelArray); CubeFaces[s].SetData(PixelArray); break; case 5: Cube.GetData(CubeMapFace.NegativeZ, PixelArray); CubeFaces[s].SetData(PixelArray); break; } } } protected void AddVertex(Vector3 position, Vector3 normal, Vector2 textureCoordinates) { _vertices.Add(new VertexPositionNormalTexture(position, normal, textureCoordinates)); } protected void AddIndex(int index) { if (index > ushort.MaxValue) throw new ArgumentOutOfRangeException("index"); _indices.Add((ushort)index); } protected int CurrentVertex { get { return _vertices.Count; } } #endregion } }

    Read the article

  • How to determine if a 3D voxel-based room is sealed, efficiently

    - by NigelMan1010
    I've been having some issues with efficiently determining if large rooms are sealed in a voxel-based 3D rooms. I'm at a point where I have tried my hardest to solve the problem without asking for help, but not tried enough to give up, so I'm asking for help. To clarify, sealed being that there are no holes in the room. There are oxygen sealers, which check if the room is sealed, and seal depending on the oxygen input level. Right now, this is how I'm doing it: Starting at the block above the sealer tile (the vent is on the sealer's top face), recursively loop through in all 6 adjacent directions If the adjacent tile is a full, non-vacuum tile, continue through the loop If the adjacent tile is not full, or is a vacuum tile, check if it's adjacent blocks are, recursively. Each time a tile is checked, decrement a counter If the count hits zero, if the last block is adjacent to a vacuum tile, return that the area is unsealed If the count hits zero and the last block is not a vacuum tile, or the recursive loop ends (no vacuum tiles left) before the counter is zero, the area is sealed If the area is not sealed, run the loop again with some changes: Checking adjacent blocks for "breathable air" tile instead of a vacuum tile Instead of using a decrementing counter, continue until no adjacent "breathable air" tiles are found. Once loop is finished, set each checked block to a vacuum tile. Here's the code I'm using: http://pastebin.com/NimyKncC The problem: I'm running this check every 3 seconds, sometimes a sealer will have to loop through hundreds of blocks, and a large world with many oxygen sealers, these multiple recursive loops every few seconds can be very hard on the CPU. I was wondering if anyone with more experience with optimization can give me a hand, or at least point me in the right direction. Thanks a bunch.

    Read the article

  • How to handle circle penetration

    - by Kaertserif
    I've been working on cirlce to circle collision and have gotten the intersection method working correctly, but I'm having problems using the returned values to actually seperate the circles from one another. This is the method which calculates the depth of the circle collision public static Vector2 GetIntersectionDepth(Circle a, Circle b) { float xValue = a.Center.X - b.Center.X; float yValue = a.Center.Y - b.Center.Y; Vector2 depth = Vector2.Zero; float distance = Vector2.Distance(a.Center, b.Center); if (a.Radius + b.Radius > distance) { float result = (a.Radius + b.Radius) - distance; depth.X = (float)Math.Cos(result); depth.Y = (float)Math.Sin(result); } return depth; } This is where I'm trying to apply the values to actually seperate the circles. Vector2 depth = Vector2.Zero; for (int i = 0; i < circlePositions.Count; i++) { for (int j = 0; j < circlePositions.Count; j++) { Circle bounds1 = new Circle(circlePositions[i], circle.Width / 2); Circle bounds2 = new Circle(circlePositions[j], circle.Width / 2); if(i != j) depth = CircleToCircleIntersection.GetIntersectionDepth(bounds1, bounds2); if (depth != Vector2.Zero) { circlePositions[i] = new Vector2(circlePositions[i].X + depth.X, circlePositions[i].Y + depth.Y); } } } If you can offer any help in this I would really appreciate it.

    Read the article

  • mciSendString cannot save to directory path

    - by robUK
    Hello, VS C# 2008 SP1 I have a created a small application that records and plays audio. However, my application needs to save the wave file to the application data directory on the users computer. The mciSendString takes a C style string as a parameter and has to be in 8.3 format. However, my problem is I can't get it to save. And what is strange is sometime it does and sometimes it doesn't. Howver, most of the time is failes. However, if I save directly to the C drive it works first time everything. I have used 3 different methods that I have coded below. The error number that I get when it fails is 286."The file was not saved. Make sure your system has sufficient disk space or has an intact network connection" Many thanks for any suggestins, [DllImport("winmm.dll",CharSet=CharSet.Auto)] private static extern uint mciSendString([MarshalAs(UnmanagedType.LPTStr)] string command, StringBuilder returnValue, int returnLength, IntPtr winHandle); [DllImport("winmm.dll", CharSet = CharSet.Auto)] private static extern int mciGetErrorString(uint errorCode, StringBuilder errorText, int errorTextSize); [DllImport("Kernel32.dll", CharSet=CharSet.Auto)] private static extern int GetShortPathName([MarshalAs(UnmanagedType.LPTStr)] string longPath, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder shortPath, int length); // Stop recording private void StopRecording() { // Save recorded voice string shortPath = this.shortPathName(); string formatShortPath = string.Format("save recsound \"{0}\"", shortPath); uint result = 0; StringBuilder errorTest = new StringBuilder(256); // C:\DOCUME~1\Steve\APPLIC~1\Test.wav // Fails result = mciSendString(string.Format("{0}", formatShortPath), null, 0, IntPtr.Zero); mciGetErrorString(result, errorTest, errorTest.Length); // command line convention - fails result = mciSendString("save recsound \"C:\\DOCUME~1\\Steve\\APPLIC~1\\Test.wav\"", null, 0, IntPtr.Zero); mciGetErrorString(result, errorTest, errorTest.Length); // 8.3 short format - fails result = mciSendString(@"save recsound C:\DOCUME~1\Steve\APPLIC~1\Test.wav", null, 0, IntPtr.Zero); mciGetErrorString(result, errorTest, errorTest.Length); // Save to C drive works everytime. result = mciSendString(@"save recsound C:\Test.wav", null, 0, IntPtr.Zero); mciGetErrorString(result, errorTest, errorTest.Length); mciSendString("close recsound ", null, 0, IntPtr.Zero); } // Get the short path name so that the mciSendString can save the recorded wave file private string shortPathName() { string shortPath = string.Empty; long length = 0; StringBuilder buffer = new StringBuilder(256); // Get the length of the path length = GetShortPathName(this.saveRecordingPath, buffer, 256); shortPath = buffer.ToString(); return shortPath; }

    Read the article

  • Releasing an OLE IStorage file handle in C#

    - by Bernard Darnton
    I'm trying to embed a PDF file into a Word document using the OLE technique described here: http://blogs.msdn.com/brian_jones/archive/2009/07/21/embedding-any-file-type-like-pdf-in-an-open-xml-file.aspx I've tried to implement to C++ code provided in C# so that the whole project's in one place and am almost there except for one roadblock. When I try to feed the generated OLE object binary data into the Word document I get an IOException. IOException: The process cannot access the file 'C:\Wherever\Whatever.pdf.bin' because it is being used by another process. There is a file handle open the .bin file and I don't know how to get rid of it. I don't know a huge amount about COM - I'm winging it here - and I don't know where the file handle is or how to release it. Here's what my C#-ised code looks like. What am I missing? public void ExportOleFile(string oleOutputFileName, string emfOutputFileName) { OLE32.IStorage storage; var result = OLE32.StgCreateStorageEx( oleOutputFileName, OLE32.STGM.STGM_READWRITE | OLE32.STGM.STGM_SHARE_EXCLUSIVE | OLE32.STGM.STGM_CREATE | OLE32.STGM.STGM_TRANSACTED, OLE32.STGFMT.STGFMT_DOCFILE, 0, IntPtr.Zero, IntPtr.Zero, ref OLE32.IID_IStorage, out storage ); var CLSID_NULL = Guid.Empty; OLE32.IOleObject pOle; result = OLE32.OleCreateFromFile( ref CLSID_NULL, _inputFileName, ref OLE32.IID_IOleObject, OLE32.OLERENDER.OLERENDER_NONE, IntPtr.Zero, null, storage, out pOle ); result = OLE32.OleRun(pOle); IntPtr unknownFromOle = Marshal.GetIUnknownForObject(pOle); IntPtr unknownForDataObj; Marshal.QueryInterface(unknownFromOle, ref OLE32.IID_IDataObject, out unknownForDataObj); var pdo = Marshal.GetObjectForIUnknown(unknownForDataObj) as IDataObject; var fetc = new FORMATETC(); fetc.cfFormat = (short)OLE32.CLIPFORMAT.CF_ENHMETAFILE; fetc.dwAspect = DVASPECT.DVASPECT_CONTENT; fetc.lindex = -1; fetc.ptd = IntPtr.Zero; fetc.tymed = TYMED.TYMED_ENHMF; var stgm = new STGMEDIUM(); stgm.unionmember = IntPtr.Zero; stgm.tymed = TYMED.TYMED_ENHMF; pdo.GetData(ref fetc, out stgm); var hemf = GDI32.CopyEnhMetaFile(stgm.unionmember, emfOutputFileName); storage.Commit((int)OLE32.STGC.STGC_DEFAULT); pOle.Close(0); GDI32.DeleteEnhMetaFile(stgm.unionmember); GDI32.DeleteEnhMetaFile(hemf); }

    Read the article

  • How do I get SSIS Data Flow to put '0.00' in a flat file?

    - by theog
    I have an SSIS package with a Data Flow that takes an ADO.NET data source (just a small table), executes a select * query, and outputs the query results to a flat file (I've also tried just pulling the whole table and not using a SQL select). The problem is that the data source pulls a column that is a Money datatype, and if the value is not zero, it comes into the text flat file just fine (like '123.45'), but when the value is zero, it shows up in the destination flat file as '.00'. I need to know how to get the leading zero back into the flat file. I've tried various datatypes for the output (in the Flat File Connection Manager), including currency and string, but this seems to have no effect. I've tried a case statement in my select, like this: CASE WHEN columnValue = 0 THEN '0.00' ELSE columnValue END (still results in '.00') I've tried variations on that like this: CASE WHEN columnValue = 0 THEN convert(decimal(12,2), '0.00') ELSE convert(decimal(12,2), columnValue) END (Still results in '.00') and: CASE WHEN columnValue = 0 THEN convert(money, '0.00') ELSE convert(money, columnValue) END (results in '.0000000000000000000') This silly little issue is killin' me. Can anybody tell me how to get a zero Money datatype database value into a flat file as '0.00'?

    Read the article

  • MIPS return address in main

    - by Alexander
    I am confused why in the code below I need to decrement the stack pointer and store the return address again. If I don't do that... then PCSpim keeps on looping.. Why is that? ######################################################################################################################## ### main ######################################################################################################################## .text .globl main main: addi $sp, $sp, -4 # Make space on stack sw $ra, 0($sp) # Save return address # Start test 1 ############################################################ la $a0, asize1 # 1st parameter: address of asize1[0] la $a1, frame1 # 2nd parameter: address of frame1[0] la $a2, window1 # 3rd parameter: address of window1[0] jal vbsme # call function # Printing $v0 add $a0, $v0, $zero # Load $v0 for printing li $v0, 1 # Load the system call numbers syscall # Print newline. la $a0, newline # Load value for printing li $v0, 4 # Load the system call numbers syscall # Printing $v1 add $a0, $v1, $zero # Load $v1 for printing li $v0, 1 # Load the system call numbers syscall # Print newline. la $a0, newline # Load value for printing li $v0, 4 # Load the system call numbers syscall # Print newline. la $a0, newline # Load value for printing li $v0, 4 # Load the system call numbers syscall ############################################################ # End of test 1 lw $ra, 0($sp) # Restore return address addi $sp, $sp, 4 # Restore stack pointer jr $ra # Return ######################################################################################################################## ### vbsme ######################################################################################################################## #.text .globl vbsme vbsme: addi $sp, $sp, -4 # create space on the stack pointer sw $ra, 0($sp) # save return address exit: add $v1, $t5, $zero # (v1) x coordinate of the block in the frame with the minimum SAD add $v0, $t4, $zero # (v0) y coordinate of the block in the frame with the minimum SAD lw $ra, 0($sp) # restore return address addi $sp, $sp, 4 # restore stack pointer jr $ra # return If I delete: addi $sp, $sp, -4 # create space on the stack pointer sw $ra, 0($sp) # save return address and lw $ra, 0($sp) # restore return address addi $sp, $sp, 4 # restore stack pointer on vbsme: PCSpim keeps on running... Why??? I shouldn't have to increment/decrement the stack pointer on vbsme and then do the jr again right? The jal in main is supposed to handle that

    Read the article

  • Modular Inverse and BigInteger division

    - by dano82
    I've been working on the problem of calculating the modular inverse of an large integer i.e. a^-1 mod n. and have been using BigInteger's built in function modInverse to check my work. I've coded the algorithm as shown in The Handbook of Applied Cryptography by Menezes, et al. Unfortunately for me, I do not get the correct outcome for all integers. My thinking is that the line q = a.divide(b) is my problem as the divide function is not well documented (IMO)(my code suffers similarly). Does BigInteger.divide(val) round or truncate? My assumption is truncation since the docs say that it mimics int's behavior. Any other insights are appreciated. This is the code that I have been working with: private static BigInteger modInverse(BigInteger a, BigInteger b) throws ArithmeticException { //make sure a >= b if (a.compareTo(b) < 0) { BigInteger temp = a; a = b; b = temp; } //trivial case: b = 0 => a^-1 = 1 if (b.equals(BigInteger.ZERO)) { return BigInteger.ONE; } //all other cases BigInteger x2 = BigInteger.ONE; BigInteger x1 = BigInteger.ZERO; BigInteger y2 = BigInteger.ZERO; BigInteger y1 = BigInteger.ONE; BigInteger x, y, q, r; while (b.compareTo(BigInteger.ZERO) == 1) { q = a.divide(b); r = a.subtract(q.multiply(b)); x = x2.subtract(q.multiply(x1)); y = y2.subtract(q.multiply(y1)); a = b; b = r; x2 = x1; x1 = x; y2 = y1; y1 = y; } if (!a.equals(BigInteger.ONE)) throw new ArithmeticException("a and n are not coprime"); return x2; }

    Read the article

  • Why is the operation address incremented by two?

    - by Gavin Jones
    I am looking at a Javascript emulator of a NES to try and understand how it works. On this line: addr = this.load(opaddr+2); The opcode is incremented by two. However, the documentation (see appendix E) I'm reading says: Zero page addressing uses a single operand which serves as a pointer to an address in zero page ($0000-$00FF) where the data to be operated on can be found. By using zero page addressing, only one byte is needed for the operand, so the instruction is shorter and, therefore, faster to execute than with addressing modes which take two operands. An example of a zero page instruction is AND $12. So if the operand's argument is only one byte, shouldn't it appear directly after it, and be + 1 instead of + 2? Why +2? This is how I think it works, which may be incorrect. Suppose our memory looks like: ------------------------- | 0 | 1 | 2 | 3 | 4 | 5 | <- index ------------------------- | a | b | c | d | e | f | <- memory ------------------------- ^ \ PC and our PC is 0, pointing to a. For this cycle, we say that the opcode: var pc= 0; //for example's sake var opcode= memory[pc]; //a So shouldn't the first operand be the next slot, i.e. b? var first_operand = memory[pc + 1]; //b

    Read the article

  • 3D Ball Physics Theory: collision response on ground and against walls?

    - by David
    I'm really struggling to get a strong grasp on how I should be handling collision response in a game engine I'm building around a 3D ball physics concept. Think Monkey Ball as an example of the type of gameplay. I am currently using sphere-to-sphere broad phase, then AABB to OBB testing (the final test I am using right now is one that checks if one of the 8 OBB points crosses the planes of the object it is testing against). This seems to work pretty well, and I am getting back: Plane that object is colliding against (with a point on the plane, the plane's normal, and the exact point of intersection. I've tried what feels like dozens of different high-level strategies for handling these collisions, without any real success. I think my biggest problem is understanding how to handle collisions against walls in the x-y axes (left/right, front/back), which I want to have elasticity, and the ground (z-axis) where I want an elastic reaction if the ball drops down, but then for it to eventually normalize and be kept "on the ground" (not go into the ground, but also not continue bouncing). Without kluging something together, I'm positive there is a good way to handle this, my theories just aren't getting me all the way there. For physics modeling and movement, I am trying to use a Euler based setup with each object maintaining a position (and destination position prior to collision detection), a velocity (which is added onto the position to determine the destination position), and an acceleration (which I use to store any player input being put on the ball, as well as gravity in the z coord). Starting from when I detect a collision, what is a good way to approach the response to get the expected behavior in all cases? Thanks in advance to anyone taking the time to assist... I am grateful for any pointers, and happy to post any additional info or code if it is useful. UPDATE Based on Steve H's and eBusiness' responses below, I have adapted my collision response to what makes a lot more sense now. It was close to right before, but I didn't have all the right pieces together at the right time! I have one problem left to solve, and that is what is causing the floor collision to hit every frame. Here's the collision response code I have now for the ball, then I'll describe the last bit I'm still struggling to understand. // if we are moving in the direction of the plane (against the normal)... if (m_velocity.dot(intersection.plane.normal) <= 0.0f) { float dampeningForce = 1.8f; // eventually create this value based on mass and acceleration // Calculate the projection velocity PVRTVec3 actingVelocity = m_velocity.project(intersection.plane.normal); m_velocity -= actingVelocity * dampeningForce; } // Clamp z-velocity to zero if we are within a certain threshold // -- NOTE: this was an experimental idea I had to solve the "jitter" bug I'll describe below float diff = 0.2f - abs(m_velocity.z); if (diff > 0.0f && diff <= 0.2f) { m_velocity.z = 0.0f; } // Take this object to its new destination position based on... // -- our pre-collision position + vector to the collision point + our new velocity after collision * time // -- remaining after the collision to finish the movement m_destPosition = m_position + intersection.diff + (m_velocity * intersection.tRemaining * GAMESTATE->dt); The above snippet is run after a collision is detected on the ball (collider) with a collidee (floor in this case). With a dampening force of 1.8f, the ball's reflected "upward" velocity will eventually be overcome by gravity, so the ball will essentially be stuck on the floor. THIS is the problem I have now... the collision code is running every frame (since the ball's z-velocity is constantly pushing it a collision with the floor below it). The ball is not technically stuck, I can move it around still, but the movement is really goofy because the velocity and position keep getting affected adversely by the above snippet. I was experimenting with an idea to clamp the z-velocity to zero if it was "close to zero", but this didn't do what I think... probably because the very next frame the ball gets a new gravity acceleration applied to its velocity regardless (which I think is good, right?). Collisions with walls are as they used to be and work very well. It's just this last bit of "stickiness" to deal with. The camera is constantly jittering up and down by extremely small fractions too when the ball is "at rest". I'll keep playing with it... I like puzzles like this, especially when I think I'm close. Any final ideas on what I could be doing wrong here? UPDATE 2 Good news - I discovered I should be subtracting the intersection.diff from the m_position (position prior to collision). The intersection.diff is my calculation of the difference in the vector of position to destPosition from the intersection point to the position. In this case, adding it was causing my ball to always go "up" just a little bit, causing the jitter. By subtracting it, and moving that clamper for the velocity.z when close to zero to being above the dot product (and changing the test from <= 0 to < 0), I now have the following: // Clamp z-velocity to zero if we are within a certain threshold float diff = 0.2f - abs(m_velocity.z); if (diff > 0.0f && diff <= 0.2f) { m_velocity.z = 0.0f; } // if we are moving in the direction of the plane (against the normal)... float dotprod = m_velocity.dot(intersection.plane.normal); if (dotprod < 0.0f) { float dampeningForce = 1.8f; // eventually create this value based on mass and acceleration? // Calculate the projection velocity PVRTVec3 actingVelocity = m_velocity.project(intersection.plane.normal); m_velocity -= actingVelocity * dampeningForce; } // Take this object to its new destination position based on... // -- our pre-collision position + vector to the collision point + our new velocity after collision * time // -- remaining after the collision to finish the movement m_destPosition = m_position - intersection.diff + (m_velocity * intersection.tRemaining * GAMESTATE->dt); UpdateWorldMatrix(m_destWorldMatrix, m_destOBB, m_destPosition, false); This is MUCH better. No jitter, and the ball now "rests" at the floor, while still bouncing off the floor and walls. The ONLY thing left is that the ball is now virtually "stuck". He can move but at a much slower rate, likely because the else of my dot product test is only letting the ball move at a rate multiplied against the tRemaining... I think this is a better solution than I had previously, but still somehow not the right idea. BTW, I'm trying to journal my progress through this problem for anyone else with a similar situation - hopefully it will serve as some help, as many similar posts have for me over the years.

    Read the article

  • Failure with LogonUser in MC++

    - by Alikar
    After fighting with this for a week I have not really gotten anywhere in why it constantly fails in my code, but not in other examples. My code, which while it compiles, will not log into a user that I know has the correct login information. Where it fails is the following line: wi = gcnew WindowsIdentity(token); It fails here because the token is zero, meaning that it was never set to a user token. Here is my full code: #ifndef UNCAPI_H #define UNCAPI_H #include <windows.h> #pragma once using namespace System; using namespace System::Runtime::InteropServices; using namespace System::Security::Principal; using namespace System::Security::Permissions; namespace UNCAPI { public ref class UNCAccess { public: //bool Logon(String ^_srUsername, String ^_srDomain, String ^_srPassword); [PermissionSetAttribute(SecurityAction::Demand, Name = "FullTrust")] bool Logon(String ^_srUsername, String ^_srDomain, String ^_srPassword) { bool bSuccess = false; token = IntPtr(0); bSuccess = LogonUser(_srUsername, _srDomain, _srPassword, 8, 0, &tokenHandle); if(bSuccess) { wi = gcnew WindowsIdentity(token); wic = wi->Impersonate(); } return bSuccess; } void UNCAccess::Logoff() { if (wic != nullptr ) { wic->Undo(); } CloseHandle((int*)token.ToPointer()); } private: [DllImport("advapi32.dll", SetLastError=true)]//[DllImport("advapi32.DLL", EntryPoint="LogonUserW", SetLastError=true, CharSet=CharSet::Unicode, ExactSpelling=true, CallingConvention=CallingConvention::StdCall)] bool static LogonUser(String ^lpszUsername, String ^lpszDomain, String ^lpszPassword, int dwLogonType, int dwLogonProvider, IntPtr *phToken); [DllImport("KERNEL32.DLL", EntryPoint="CloseHandle", SetLastError=true, CharSet=CharSet::Unicode, ExactSpelling=true, CallingConvention=CallingConvention::StdCall)] bool static CloseHandle(int *handle); IntPtr token; WindowsIdentity ^wi; WindowsImpersonationContext ^wic; };// End of Class UNCAccess }// End of Name Space #endif UNCAPI_H Now using this slightly modified example from Microsoft I was able to get a login and a token: #using <mscorlib.dll> #using <System.dll> using namespace System; using namespace System::Runtime::InteropServices; using namespace System::Security::Principal; using namespace System::Security::Permissions; [assembly:SecurityPermissionAttribute(SecurityAction::RequestMinimum, UnmanagedCode=true)] [assembly:PermissionSetAttribute(SecurityAction::RequestMinimum, Name = "FullTrust")]; [DllImport("advapi32.dll", SetLastError=true)] bool LogonUser(String^ lpszUsername, String^ lpszDomain, String^ lpszPassword, int dwLogonType, int dwLogonProvider, IntPtr* phToken); [DllImport("kernel32.dll", CharSet=System::Runtime::InteropServices::CharSet::Auto)] int FormatMessage(int dwFlags, IntPtr* lpSource, int dwMessageId, int dwLanguageId, String^ lpBuffer, int nSize, IntPtr *Arguments); [DllImport("kernel32.dll", CharSet=CharSet::Auto)] bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", CharSet=CharSet::Auto, SetLastError=true)] bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, IntPtr* DuplicateTokenHandle); // GetErrorMessage formats and returns an error message // corresponding to the input errorCode. String^ GetErrorMessage(int errorCode) { int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; //int errorCode = 0x5; //ERROR_ACCESS_DENIED //throw new System.ComponentModel.Win32Exception(errorCode); int messageSize = 255; String^ lpMsgBuf = ""; int dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; IntPtr ptrlpSource = IntPtr::Zero; IntPtr prtArguments = IntPtr::Zero; int retVal = FormatMessage(dwFlags, &ptrlpSource, errorCode, 0, lpMsgBuf, messageSize, &prtArguments); if (0 == retVal) { throw gcnew Exception(String::Format( "Failed to format message for error code {0}. ", errorCode)); } return lpMsgBuf; } // Test harness. // If you incorporate this code into a DLL, be sure to demand FullTrust. [PermissionSetAttribute(SecurityAction::Demand, Name = "FullTrust")] int main() { IntPtr tokenHandle = IntPtr(0); IntPtr dupeTokenHandle = IntPtr(0); try { String^ userName; String^ domainName; // Get the user token for the specified user, domain, and password using the // unmanaged LogonUser method. // The local machine name can be used for the domain name to impersonate a user on this machine. Console::Write("Enter the name of the domain on which to log on: "); domainName = Console::ReadLine(); Console::Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName); userName = Console::ReadLine(); Console::Write("Enter the password for {0}: ", userName); const int LOGON32_PROVIDER_DEFAULT = 0; //This parameter causes LogonUser to create a primary token. const int LOGON32_LOGON_INTERACTIVE = 2; const int SecurityImpersonation = 2; tokenHandle = IntPtr::Zero; dupeTokenHandle = IntPtr::Zero; // Call LogonUser to obtain a handle to an access token. bool returnValue = LogonUser(userName, domainName, Console::ReadLine(), LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &tokenHandle); Console::WriteLine("LogonUser called."); if (false == returnValue) { int ret = Marshal::GetLastWin32Error(); Console::WriteLine("LogonUser failed with error code : {0}", ret); Console::WriteLine("\nError: [{0}] {1}\n", ret, GetErrorMessage(ret)); int errorCode = 0x5; //ERROR_ACCESS_DENIED throw gcnew System::ComponentModel::Win32Exception(errorCode); } Console::WriteLine("Did LogonUser Succeed? {0}", (returnValue?"Yes":"No")); Console::WriteLine("Value of Windows NT token: {0}", tokenHandle); // Check the identity. Console::WriteLine("Before impersonation: {0}", WindowsIdentity::GetCurrent()->Name); bool retVal = DuplicateToken(tokenHandle, SecurityImpersonation, &dupeTokenHandle); if (false == retVal) { CloseHandle(tokenHandle); Console::WriteLine("Exception thrown in trying to duplicate token."); return -1; } // The token that is passed to the following constructor must // be a primary token in order to use it for impersonation. WindowsIdentity^ newId = gcnew WindowsIdentity(dupeTokenHandle); WindowsImpersonationContext^ impersonatedUser = newId->Impersonate(); // Check the identity. Console::WriteLine("After impersonation: {0}", WindowsIdentity::GetCurrent()->Name); // Stop impersonating the user. impersonatedUser->Undo(); // Check the identity. Console::WriteLine("After Undo: {0}", WindowsIdentity::GetCurrent()->Name); // Free the tokens. if (tokenHandle != IntPtr::Zero) CloseHandle(tokenHandle); if (dupeTokenHandle != IntPtr::Zero) CloseHandle(dupeTokenHandle); } catch(Exception^ ex) { Console::WriteLine("Exception occurred. {0}", ex->Message); } Console::ReadLine(); }// end of function Why should Microsoft's code succeed, where mine fails?

    Read the article

  • XNA 3D model collision is inaccurate

    - by Daniel Lopez
    I am creating a classic game in 3d that deals with asteriods and you have to shoot them and avoid being hit from them. I can generate the asteroids just fine and the ship can shoot bullets just fine. But the asteroids always hit the ship even it doesn't look they are even close. I know 2D collision very well but not 3D so can someone please shed some light to my problem. Thanks in advance. Code For ModelRenderer: 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; namespace _3D_Asteroids { class ModelRenderer { private float aspectratio; private Model model; private Vector3 camerapos; private Vector3 modelpos; private Matrix rotationy; float radiansy = 0; private bool isalive; public ModelRenderer(Model m, float AspectRatio, Vector3 initial_pos, Vector3 initialcamerapos) { isalive = true; model = m; if (model.Meshes.Count == 0) { throw new Exception("Invalid model because it contains zero meshes!"); } modelpos = initial_pos; camerapos = initialcamerapos; aspectratio = AspectRatio; return; } public float RadiusOfSphere { get { return model.Meshes[0].BoundingSphere.Radius; } } public BoundingBox BoxBounds { get { return BoundingBox.CreateFromSphere(model.Meshes[0].BoundingSphere); } } public BoundingSphere SphereBounds { get { return model.Meshes[0].BoundingSphere; } } public Vector3 CameraPosition { set { camerapos = value; } get { return camerapos; } } public bool IsAlive { get { return isalive; } } public Vector3 ModelPosition { set { modelpos = value; } get { return modelpos; } } public void RotateY(float radians) { radiansy += radians; rotationy = Matrix.CreateRotationY(radiansy); } public Matrix RotationY { set { rotationy = value; } get { return rotationy; } } public float AspectRatio { set { aspectratio = value; } get { return aspectratio; } } public void Kill() { isalive = false; } public void Draw(float scale) { Matrix world; if (rotationy == new Matrix(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) { world = Matrix.CreateScale(scale) * Matrix.CreateTranslation(modelpos); } else { world = rotationy * Matrix.CreateScale(scale) * Matrix.CreateTranslation(modelpos); } Matrix view = Matrix.CreateLookAt(camerapos, Vector3.Zero, Vector3.Up); Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), this.AspectRatio, 1f, 100000f); foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.World = world; effect.View = view; effect.Projection = projection; } mesh.Draw(); } } public void Draw() { Matrix world; if (rotationy == new Matrix(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) { world = Matrix.CreateTranslation(modelpos); } else { world = rotationy * Matrix.CreateTranslation(modelpos); } Matrix view = Matrix.CreateLookAt(camerapos, Vector3.Zero, Vector3.Up); Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), this.AspectRatio, 1f, 100000f); foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.World = world; effect.View = view; effect.Projection = projection; } mesh.Draw(); } } } Code For Game1: 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; namespace _3D_Asteroids { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; int score = 0, lives = 5; SpriteBatch spriteBatch; GameState gstate = GameState.OnMenuScreen; Menu menu = new Menu(Color.Yellow, Color.White); SpriteFont font; Texture2D background; ModelRenderer ship; Model b, a; List<ModelRenderer> bullets = new List<ModelRenderer>(); List<ModelRenderer> asteriods = new List<ModelRenderer>(); float time = 0.0f; int framecount = 0; SoundEffect effect; public Game1() { graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = 1280; graphics.PreferredBackBufferHeight = 796; graphics.ApplyChanges(); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); font = Content.Load<SpriteFont>("Fonts\\Lucida Console"); background = Content.Load<Texture2D>("Textures\\B1_stars"); Model p1 = Content.Load<Model>("Models\\p1_wedge"); b = Content.Load<Model>("Models\\pea_proj"); a = Content.Load<Model>("Models\\asteroid1"); effect = Content.Load<SoundEffect>("Audio\\tx0_fire1"); ship = new ModelRenderer(p1, GraphicsDevice.Viewport.AspectRatio, new Vector3(0, 0, 0), new Vector3(0, 0, 9000)); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { KeyboardState state = Keyboard.GetState(PlayerIndex.One); switch (gstate) { case GameState.OnMenuScreen: { if (state.IsKeyDown(Keys.Enter)) { switch (menu.SelectedChoice) { case MenuChoices.Play: { gstate = GameState.GameStarted; break; } case MenuChoices.Exit: { this.Exit(); break; } } } if (state.IsKeyDown(Keys.Down)) { menu.MoveSelectedMenuChoiceDown(gameTime); } else if(state.IsKeyDown(Keys.Up)) { menu.MoveSelectedMenuChoiceUp(gameTime); } else { menu.KeysReleased(); } break; } case GameState.GameStarted: { foreach (ModelRenderer bullet in bullets) { if (bullet.ModelPosition.X < (ship.ModelPosition.X + 4000) && bullet.ModelPosition.Z < (ship.ModelPosition.X + 4000) && bullet.ModelPosition.X > (ship.ModelPosition.Z - 4000) && bullet.ModelPosition.Z > (ship.ModelPosition.Z - 4000)) { bullet.ModelPosition += (bullet.RotationY.Forward * 120); } else if (collidedwithasteriod(bullet)) { bullet.Kill(); } else { bullet.Kill(); } } foreach (ModelRenderer asteroid in asteriods) { if (ship.SphereBounds.Intersects(asteroid.BoxBounds)) { lives -= 1; asteroid.Kill(); // This always hits no matter where the ship goes. } else { asteroid.ModelPosition -= (asteroid.RotationY.Forward * 50); } } for (int index = 0; index < asteriods.Count; index++) { if (asteriods[index].IsAlive == false) { asteriods.RemoveAt(index); } } for (int index = 0; index < bullets.Count; index++) { if (bullets[index].IsAlive == false) { bullets.RemoveAt(index); } } if (state.IsKeyDown(Keys.Left)) { ship.RotateY(0.1f); if (state.IsKeyDown(Keys.Space)) { if (time < 17) { firebullet(); //effect.Play(); } } else { time = 0; } } else if (state.IsKeyDown(Keys.Right)) { ship.RotateY(-0.1f); if (state.IsKeyDown(Keys.Space)) { if (time < 17) { firebullet(); //effect.Play(); } } else { time = 0; } } else if (state.IsKeyDown(Keys.Up)) { ship.ModelPosition += (ship.RotationY.Forward * 50); if (state.IsKeyDown(Keys.Space)) { if (time < 17) { firebullet(); //effect.Play(); } } else { time = 0; } } else if (state.IsKeyDown(Keys.Space)) { time += gameTime.ElapsedGameTime.Milliseconds; if (time < 17) { firebullet(); //effect.Play(); } } else { time = 0.0f; } if ((framecount % 60) == 0) { createasteroid(); framecount = 0; } framecount++; break; } } base.Update(gameTime); } void firebullet() { if (bullets.Count < 3) { ModelRenderer bullet = new ModelRenderer(b, GraphicsDevice.Viewport.AspectRatio, ship.ModelPosition, new Vector3(0, 0, 9000)); bullet.RotationY = ship.RotationY; bullets.Add(bullet); } } void createasteroid() { if (asteriods.Count < 2) { Random random = new Random(); float z = random.Next(-13000, -11000); float x = random.Next(-9000, -8000); Random random2 = new Random(); int degrees = random.Next(0, 45); float radians = MathHelper.ToRadians(degrees); ModelRenderer asteroid = new ModelRenderer(a, GraphicsDevice.Viewport.AspectRatio, new Vector3(x, 0, z), new Vector3(0,0, 9000)); asteroid.RotateY(radians); asteriods.Add(asteroid); } } /// <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) { GraphicsDevice.Clear(Color.CornflowerBlue); switch (gstate) { case GameState.OnMenuScreen: { spriteBatch.Begin(); spriteBatch.Draw(background, Vector2.Zero, Color.White); menu.DrawMenu(ref spriteBatch, font, new Vector2(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2) - new Vector2(50f), 100f); spriteBatch.End(); break; } case GameState.GameStarted: { spriteBatch.Begin(); spriteBatch.Draw(background, Vector2.Zero, Color.White); spriteBatch.DrawString(font, "Score: " + score.ToString() + "\nLives: " + lives.ToString(), Vector2.Zero, Color.White); spriteBatch.End(); ship.Draw(); foreach (ModelRenderer bullet in bullets) { bullet.Draw(); } foreach (ModelRenderer asteroid in asteriods) { asteroid.Draw(0.1f); } break; } } base.Draw(gameTime); } bool collidedwithasteriod(ModelRenderer bullet) { foreach (ModelRenderer asteroid in asteriods) { if (bullet.SphereBounds.Intersects(asteroid.BoxBounds)) { score += 10; asteroid.Kill(); return true; } } return false; } } } }

    Read the article

  • Conditional Formatting of a Cell Based on Color Value in that Cell in Excel

    - by Otaku
    Is is possible to format a cell based on one component of the RGB value inside of it. For example, let's say I have 3 cells - A1, A2, A3. In A1, I want the cell color to be the shade of red anywhere between 0 and 255 of the number in the cell (so if it is 128, it should be like half red). For that given cell, the other values will just be 0, 0 (so in this case, zero green and zero blue). Is this possible?

    Read the article

  • Problems with Windows XP Plug and Play devices, maybe relating to MSVCR71.dll

    - by Richard
    I believe this question is unanswered as of now so I appologize if I've overlooked it. I have been having trouble some external devices with windows recently and I'm trying my darnedest to get to the bottom of it. At first, my Zero Tension USB mouse would stop working...as in the laser in the bottom of it would be on and would register movement, but the mouse on the screen wouldn't budge even an inch. At first this would happen randomly and then it would correct itself. As time went on, it became more and more frequent. At some point, the computer would make the "doo doo" sound of plugging or unplugging a USB device when the mouse stopped/started working. I dealt with it for a while and usually if I rebooted my machine, the mouse would work again for a day or two. As more time has gone on, the computer fully does not recognize the mouse AT ALL...I have another mouse that I use with the computer that works just fine and cannot seem to figure out why my Zero Tension mouse has failed. I tried plugging the Zero Tension mouse into my Mac and low and behold, it works without hesitation and never stops on me... Needless to say, I am stumped about this. I figured because I had another mouse I could deal with the loss of my fancy one for now...until my speakers stopped being recognized. I have a set of Logitec speakers that I have plugged into my sound card. Again, every now and again the audio devices would cease to be recognized by my computer, but a reboot would fix the problem. Now my speakers do not work at all with my computer and I feel like it's time to ask for help. My computer seems to be having a neural shutdown...where I can plug in devices and the computer doesn't seem to notice anything wrong, but none of the devices work. I hope this doesn't get any worse! Please help! Also, on a potentially (un)related note, when I start up my machine I get the message "This application has failed to start because Msvcp71.dll was not found. Re-installing the application may fix this problem." in reference to qbupdate.exe I don't know if that DLL being messed up has anything to do with my mouse or speakers, but I figure it might...anyway, thanks in advance for an answer and let me know if I need to clarify anything. Let me sum up: Zero Tension Mouse gradually stopped working Logitec Speakers gradually stopped working MSVCR71.dll seems to be messed up I don't know if any of those are related but any help would be much appreciated

    Read the article

  • What does the directory-name: '~MntWIM' on my Windows 7 / C:\ drive mean?

    - by J Puk
    This '~MntWIM' on my Windows 7 / C:\ drive, is sized: 694 MB (728.418.589 bytes) on harddrive. It contains 3 subdirectories. 1st = Program Files, containg zero volume 2nd = Users, containing zero volume 3rd = Windows, containing 693 MB (726.823.197 bytes) on harddrive It all looks a bit useless to me, so question is: Is it safe to delete the lot? Or does it have an important function there? Hoping for an answer from which I could lern something. B.R. JP

    Read the article

  • Handling nmake errorlevel/return codes

    - by tlianza
    Hi all, I have an nmake-based project which in turn calls the asp compiler, which can throw an error, which nmake seems to recognize: NMAKE : fatal error U1077: 'C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler.exe' : return code '0x1' However, when I call nmake from within a batch file, the environment variable %ERRORLEVEL% remains set at zero: nmake /NOLOGO echo BUILD RETURNING: %ERRORLEVEL% If I control-c the nmake task, I do end up getting a non-zero ERRORLEVEL (it's set to 2) so my assumption is that I'm able to catch errors okay, but nmake isn't bubbling up the non-zero exit code from it's task. Or, at least, I'm mis-trapping it. Any help would be appreciated.

    Read the article

  • Problem setting output flags for ALU in "Nand to Tetris" course

    - by MahlerFive
    Although I tagged this homework, it is actually for a course which I am doing on my own for free. Anyway, the course is called "From Nand to Tetris" and I'm hoping someone here has seen or taken the course so I can get some help. I am at the stage where I am building the ALU with the supplied hdl language. My problem is that I can't get my chip to compile properly. I am getting errors when I try to set the output flags for the ALU. I believe the problem is that I can't subscript any intermediate variable, since when I just try setting the flags to true or false based on some random variable (say an input flag), I do not get the errors. I know the problem is not with the chips I am trying to use since I am using all builtin chips. Here is my ALU chip so far: /** * The ALU. Computes a pre-defined set of functions out = f(x,y) * where x and y are two 16-bit inputs. The function f is selected * by a set of 6 control bits denoted zx, nx, zy, ny, f, no. * The ALU operation can be described using the following pseudocode: * if zx=1 set x = 0 // 16-bit zero constant * if nx=1 set x = !x // Bit-wise negation * if zy=1 set y = 0 // 16-bit zero constant * if ny=1 set y = !y // Bit-wise negation * if f=1 set out = x + y // Integer 2's complement addition * else set out = x & y // Bit-wise And * if no=1 set out = !out // Bit-wise negation * * In addition to computing out, the ALU computes two 1-bit outputs: * if out=0 set zr = 1 else zr = 0 // 16-bit equality comparison * if out<0 set ng = 1 else ng = 0 // 2's complement comparison */ CHIP ALU { IN // 16-bit inputs: x[16], y[16], // Control bits: zx, // Zero the x input nx, // Negate the x input zy, // Zero the y input ny, // Negate the y input f, // Function code: 1 for add, 0 for and no; // Negate the out output OUT // 16-bit output out[16], // ALU output flags zr, // 1 if out=0, 0 otherwise ng; // 1 if out<0, 0 otherwise PARTS: // Zero the x input Mux16( a=x, b=false, sel=zx, out=x2 ); // Zero the y input Mux16( a=y, b=false, sel=zy, out=y2 ); // Negate the x input Not16( in=x, out=notx ); Mux16( a=x, b=notx, sel=nx, out=x3 ); // Negate the y input Not16( in=y, out=noty ); Mux16( a=y, b=noty, sel=ny, out=y3 ); // Perform f Add16( a=x3, b=y3, out=addout ); And16( a=x3, b=y3, out=andout ); Mux16( a=andout, b=addout, sel=f, out=preout ); // Negate the output Not16( in=preout, out=notpreout ); Mux16( a=preout, b=notpreout, sel=no, out=out ); // zr flag Or8way( in=out[0..7], out=zr1 ); // PROBLEM SHOWS UP HERE Or8way( in=out[8..15], out=zr2 ); Or( a=zr1, b=zr2, out=zr ); // ng flag Not( in=out[15], out=ng ); } So the problem shows up when I am trying to send a subscripted version of 'out' to the Or8Way chip. I've tried using a different variable than 'out', but with the same problem. Then I read that you are not able to subscript intermediate variables. I thought maybe if I sent the intermediate variable to some other chip, and that chip subscripted it, it would solve the problem, but it has the same error. Unfortunately I just can't think of a way to set the zr and ng flags without subscripting some intermediate variable, so I'm really stuck! Just so you know, if I replace the problematic lines with the following, it will compile (but not give the right results since I'm just using some random input): // zr flag Not( in=zx, out=zr ); // ng flag Not( in=zx, out=ng ); Anyone have any ideas? Edit: Here is the appendix of the book for the course which specifies how the hdl works. Specifically look at section 5 which talks about buses and says: "An internal pin (like v above) may not be subscripted". Edit: Here is the exact error I get: "Line 68, Can't connect gate's output pin to part". The error message is sort of confusing though, since that does not seem to be the actual problem. If I just replace "Or8way( in=out[0..7], out=zr1 );" with "Or8way( in=false, out=zr1 );" it will not generate this error, which is what lead me to look up in the appendix and find that the out variable, since it was derived as intermediate, could not be subscripted.

    Read the article

  • How to get scrollTop of page afer browser scrolled such page?

    - by Marco Demaio
    I know how to get the scrollTop of a page, I use this simple JS function (code copied around): function GetScrolledTop() { //I never work in IE quirkmode, I always use DOCTYPE as 1st line, so I don't need to test for document.body.scrollTop return self['pageYOffset'] || document.documentElement.scrollTop; } This works and my problem is the following: I tried to add it in the page onload event <body onload="alert(GetScrolledTop());"> On page load I get ZERO (which make sense), but the problem is that I get ZERO even if I scroll the page and then reload it without touching the scrollbar. It seems like the browser does: loads page calls my GetScrolledTop() (so obviously shows ZERO) then scrolls the page to where it was before. Do you know how to get the scolledTop after the step 3? I mean how to get the scrolledTop AFTER the browser scrolled the page? (maybe without using a timer) Thanks!

    Read the article

  • Display continuous dates in Pivot Chart

    - by Douglas
    I have a set of data in a pivot table with date times and events. I've made a pivot chart with this data, and grouped the data by day and year, then display a count of events for each day. So, my horizontal axis goes from 19 March 2007 to 11 May 2010, and my vertical axis is numeric, going from zero to 140. For some days, I have zero events. These days don't seem to be shown on the horizontal axis, so 2008 is narrower than 2009. How do I display a count of zero for days with no events? I'd like my horizontal axis to be continuous, so that it does not miss any days, and every month ends up taking up the same amount of horizontal space. (This question is similar to the unanswered question here, but I'd rather not generate a table of all the days in the last x number of years just to get a smooth plot!)

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >