Search Results

Search found 2702 results on 109 pages for 'drawing'.

Page 6/109 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • XNA - Drawing 2D Primitives (Boxes) and Understanding Matrices in Computer Graphics

    - by MintyAnt
    I have two issues which I wish to solve by creating 2D primitives in XNA. In my game, I wish to have a "debug mode" which will draw a red box around all hitboxes in the game (Red outline, transparent inside). This would allow us to see where the hitboxes are being drawn AND still have the sprite graphics being drawn. I wish to further understand how matrices work within computer graphics. I have a basic theoretical grasp of how they work, but I really just want to apply some of my knowledge or find a good tutorial on it. To do this, I wish to draw my own 2D primitives (With Vertex3's) and apply different transormation matrices to them. I was trying to find a tutorial on drawing primitives using Direct3D, but most tutorials are only for c++, and just tell me to use XNA's Spritebatch. I wish to have more control over my program than just with Spritebatch. Any Help on using Direct3D or any other suggestions would greatly be appreciated. Thank you.

    Read the article

  • Drawing an outline around an arbitrary group of hexagons

    - by Perky
    Is there an algorithm for drawing an outline around around an arbitrary group of hexagons? The polygon outline drawn may be concave. See the images below, the green line is what I am trying to achieve. The hexagons are stored as vertices and drawn as polygons. Edit: I've uploaded images that should explain more. I want to favour convex hulls because it's conveys an area of control more quickly. Each hexagon is stored in a multidimensional array so they all have x and y coordinates, I can easily find adjacent hexagons and the opposite vertex, i.e. adjacentHexagon = getAdjacentHexagon( someHexagon, NORTHWEST ) if there isn't a hexagon immediately adjacent it will continue to search in that direction until it finds one or hits the map edges.

    Read the article

  • Drawing large 2D sidescroller level terrain

    - by Yar
    I'm a relatively good programmer but now that it comes to add some basic levels to my 2D game I'm kinda stuck. What I want to do: An acceptable, large (8000 * 1000 pixels) "green hills" test level for my game. What is the best way for me to do this? It doesn't have to look great, it just shouldn't look like it was made in MS paint with the line and paint bucket tool. Basically it should just mud with grass on top of it, shaped in some form of hills. But how should I draw it, I can't just take out the pencil tool and start drawing it pixel per pixel, can I?

    Read the article

  • Basics of drawing in 2d with OpenGL 3 shaders

    - by davidism
    I am new to OpenGL 3 and graphics programming, and want to create some basic 2d graphics. I have the following scenario of how I might go about drawing a basic (but general) 2d rectangle. I'm not sure if this is the correct way to think about it, or, if it is, how to implement it. In my head, here's how I imagine doing it: t = make_rectangle(width, height) build general VBO, centered at 0, 0 optionally: t.set_scale(2) optionally: t.set_angle(30) t.draw_at(x, y) calculates some sort of scale/rotate/translate matrix (or matrices), passes the VBO and the matrix to a shader program Something happens to clip the world to the view visible on screen. I'm really unclear on how 4 and 5 will work. The main problem is that all the tutorials I find either: use fixed function pipeline, are for 3d, or are unclear how to do something this "simple". Can someone provide me with either a better way to think of / do this, or some concrete code detailing performing the transformations in a shader and constructing and passing the data required for this shader transformation?

    Read the article

  • Drawing map tiles for iPhone game

    - by user17778
    I'm working on a turn-based strategy game for the iPhone that has a hexagon-grid based map in it. I'm in the process of drawing up the actual tiles for the different landscapes (i.e. forest, grassland, etc.) and was wondering what program to draw the tile images in. I would assume Adobe Illustrator since a vector-based image may allow for smooth images even when the user is zoomed in really close. Is this right? Thanks!

    Read the article

  • UIView drawRect: when you draw a line, the rect area will be clear so the previous drawing is gone

    - by snakewa
    It is quite hard to tell so I upload an image to show my problem: http://i42.tinypic.com/2eezamo.jpg Basically in drawRect, I will draw the line from touchesMoved as finger touches and I will call "needsDisplayInRect" for redraw. But I found that the first line is done, the second line will clear the rect part, so some previouse drawing is gone. Here is my implementation: enter code here -(void) drawRect:(CGRect)rect{ //[super drawRect: rect]; CGContextRef context = UIGraphicsGetCurrentContext(); [self drawSquiggle:squiggle at:rect inContext:context]; } - (void)drawSquiggle:(Squiggle *)squiggle at:(CGRect) rect inContext:(CGContextRef)context { CGContextSetBlendMode(context, kCGBlendModeMultiply); UIColor *squiggleColor = squiggle.strokeColor; // get squiggle's color CGColorRef colorRef = [squiggleColor CGColor]; // get the CGColor CGContextSetStrokeColorWithColor(context, colorRef); NSMutableArray *points = [squiggle points]; // get points from squiggle // retrieve the NSValue object and store the value in firstPoint CGPoint firstPoint; // declare a CGPoint [[points objectAtIndex:0] getValue:&firstPoint]; // move to the point CGContextMoveToPoint(context, firstPoint.x, firstPoint.y); // draw a line from each point to the next in order for (int i = 1; i < [points count]; i++) { NSValue *value = [points objectAtIndex:i]; // get the next value CGPoint point; // declare a new point [value getValue:&point]; // store the value in point // draw a line to the new point CGContextAddLineToPoint(context, point.x, point.y); } // end for CGContextStrokePath(context); }

    Read the article

  • Why is drawing to OnPaint graphics faster than image graphics?

    - by Tesserex
    I'm looking for a way to speed up the drawing of my game engine, which is currently the significant bottleneck, and is causing slowdowns. I'm on the verge of converting it over to XNA, but I just noticed something. Say I have a small image that I've loaded. Image img = Image.FromFile("mypict.png"); We have a picturebox on the screen we want to draw on. So we have a handler. pictureBox1.Paint += new PaintEventHandler(pictureBox1_Paint); I want our loaded image to be tiled on the picturebox (this is for a game, after all). Why on earth is this code: void pictureBox1_Paint(object sender, PaintEventArgs e) { for (int y = 0; y < 16; y++) for (int x = 0; x < 16; x++) e.Graphics.DrawImage(image, x * 16, y * 16, 16, 16); } over 25 TIMES FASTER than this code: Image buff = new Bitmap(256, 256, PixelFormat.Format32bppPArgb); // actually a form member void pictureBox1_Paint(object sender, PaintEventArgs e) { using (Graphics g = Graphics.FromImage(buff)) { for (int y = 0; y < 16; y++) for (int x = 0; x < 16; x++) g.DrawImage(image, x * 16, y * 16, 16, 16); } e.Graphics.DrawImage(buff, 0, 0, 256, 256); } To eliminate the obvious, I've tried commenting out the last e.Graphics.DrawImage (which means I don't see anything, but it gets rid a call that isn't in the first example). I've also left in the using block (needlessly) in the first example, but it's still just as blazingly fast. I've set properties of g to match e.Graphics - things like InterpolationMode, CompositingQuality, etc, but nothing I do bridges this incredible gap in performance. I can't find any difference between the two Graphics objects. What gives? My test with a System.Diagnostics.Stopwatch says that the first code snippet runs at about 7100 fps, while the second runs at a measly 280 fps. My reference image is VS2010ImageLibrary\Objects\png_format\WinVista\SecurityLock.png, which is 48x48 px, and which I modified to be 72 dpi instead of 96, but those made no difference either.

    Read the article

  • Drawing a circle in opengl es android, squiggly boundaries

    - by ladiesMan217
    I am new to OpenGL ES and facing a hard time drawing a circle on my GLSurfaceView. Here's what I have so far. the Circle Class public class MyGLBall { private int points=40; private float vertices[]={0.0f,0.0f,0.0f}; private FloatBuffer vertBuff; //centre of circle public MyGLBall(){ vertices=new float[(points+1)*3]; for(int i=3;i<(points+1)*3;i+=3){ double rad=(i*360/points*3)*(3.14/180); vertices[i]=(float)Math.cos(rad); vertices[i+1]=(float) Math.sin(rad); vertices[i+2]=0; } ByteBuffer bBuff=ByteBuffer.allocateDirect(vertices.length*4); bBuff.order(ByteOrder.nativeOrder()); vertBuff=bBuff.asFloatBuffer(); vertBuff.put(vertices); vertBuff.position(0); } public void draw(GL10 gl){ gl.glPushMatrix(); gl.glTranslatef(0, 0, 0); // gl.glScalef(size, size, 1.0f); gl.glColor4f(1.0f,1.0f,1.0f, 1.0f); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glPopMatrix(); } } I couldn't retrieve the screenshot of my image but here's what it looks like As you can see the border has crests and troughs thereby renering it squiggly which I do not want. All I want is a simple curve

    Read the article

  • Compiz not drawing window controls in ubuntu 11.10

    - by Siva Prasad Varma
    I have recently installed driver for my ATI graphic card in my Dell Studio laptop. I have also read this somewhere on the web that Ubuntu enables compiz window manager by default if your hardware can run it. Is it true ? In my case before Installing graphic card driver the window manager was Metacity, but now I have compiz as my Window manager. I found this out uisng Displex Indicator applet also confirmed by wmctrl -m. From the time I have installed graphic card drivers, the window manager(Compiz) is not drawing window control buttons for some of the windows. For example if I open a terminal I have to close it using key board shortcuts or use the File - Quit option in app-menu. Also I am not able to move the window because of this. From then when-ever I find a window without window control buttons I am restarting the window manager using Displex Indicator applet. But this is very annoying and also consumes a lot of time(when I am doing my work). Can any one suggest any solution for this. What are up's and down's of using Compiz Vs Metacity.

    Read the article

  • isometric drawing order with larger than single tile images - drawing order algorithm?

    - by Roger Smith
    I have an isometric map over which I place various images. Most images will fit over a single tile, but some images are slightly larger. For example, I have a bed of size 2x3 tiles. This creates a problem when drawing my objects to the screen as I get some tiles erroneously overlapping other tiles. The two solutions that I know of are either splitting the image into 1x1 tile segments or implementing my own draw order algorithm, for example by assigning each image a number. The image with number 1 is drawn first, then 2, 3 etc. Does anyone have advice on what I should do? It seems to me like splitting an isometric image is very non obvious. How do you decide which parts of the image are 'in' a particular tile? I can't afford to split up all of my images manually either. The draw order algorithm seems like a nicer choice but I am not sure if it's going to be easy to implement. I can't solve, in my head, how to deal with situations whereby you change the index of one image, which causes a knock on effect to many other images. If anyone has an resources/tutorials on this I would be most grateful.

    Read the article

  • Javascript Canvas Drawing Efficiency

    - by jujumbura
    I have just recently started some experiments with game development in Javascript/HTML5, and so far it has been going pretty well. I have a simple test scene running with some basic input handling, and a hundred-ish drawImage() calls with a few transforms. This all runs great on Chrome, but unfortunately, it already chugs on Firefox. I am using a very large canvas ( 1920 x 1080 ), but it doesn't seem like I should be hitting my limit already. So on that note, I was hoping to ask a few questions: 1) What exactly is done on the CPU vs. the GPU in terms of canvas and drawImage()? I'm afraid the answer is probably "it depends on the browser", but can anybody give me some rules of thumb? I naively imagined that each drawImage call results in a textured quad on the GPU with the canvas effectively being a render target, but I'm wondering if I'm pretty far off base there... 2) I have seen posts here and there with people saying not to use the translate(), rotate(), scale() functions when drawing on the canvas. Am I adding a lot of overhead just by adding a translate() call, as opposed to passing in the x,y to drawImage()? Some people suggest using "transate3d", etc., which are CSS properties, but I'm not sure how to use them within a scene. Can they be used for animated sprites within a single canvas? 3) I have also seen a lot of posts with people mentioning that pre-building canvases and then re-using them is a lot faster than issuing all the individual draw calls again. I am guessing that my background should definitely be pre-built into a canvas, but how far should I take this? Should I maintain an individual canvas for each sprite, to cache all static image data when not animating? Thank you much for your advice!

    Read the article

  • Recasting and Drawing in SDL

    - by user1078123
    I have some code that essentially draws a column on the screen of a wall in a raycasting-type 3d engine. I am trying to optimize it, as it takes about 10 milliseconds do draw a million pixels using this, and the vast majority of game time is spent in this loop. However, I don't quite understand what's occurring, particularly the recasting (I modified the "pixel manipulation" sample code from the SDL documentation). "canvas" is the surface I am drawing to, and "hello" is the surface containing the texture for the column. int c = (curcol)* canvas->format->BytesPerPixel; void *canvaspixels = canvas->pixels; Uint16 texpitch = hello->pitch; int lim = (drawheight +startdraw) * canvpitch +c + (int) canvaspixels; Uint8 *k = (Uint8 *)hello->pixels + (hit)* hello->format->BytesPerPixel; for (int j= (startdraw)*(canvpitch)+c + (int) canvaspixels; (j< lim); j+= canvpitch){ Uint8 *q = (Uint8 *) ((int(h))*(texpitch)+k); *(Uint32 *)j = *(Uint32 *)q; h += s; } We have void pointers (not sure how those are even represented), 8, 16, and 32 bit ints (h and s are floats), all being intermingled, and while it works, it is quite confusing.

    Read the article

  • XNA 2D Spritesheet drawing rendering problem

    - by user24092
    I'm making a tile-based game, using one spritesheet containing all tile graphics. Each tile has a size of 32x32 pixels. The main problem is: when I draw the tile to the screen, if the tile position x and y are not rounded or if scale is activated in spriteBatch.Draw() method (scale != 1.0f), I get some lines of adjacent tiles on the spritesheet into the current tile drawed. I already tried setting SamplerState to PointClamp, removing AntiAlias, but still doesn't work. Here I'll show images of some tests that I made, with a test sprite sheet that I've created (I made a 9x9 spritesheet, with each sprite of size 32x32 containing a unique solid color). Tests: http://img6.imageshack.us/img6/5946/testsqj.png SpriteSheet used: http://imageshack.us/a/img821/1341/tilesm.png Already tried to remove anti-alias, set PointClamp as sampler state, but still getting this issue, XNA keeps drawing part of the adjacent pixels of the texture on the screen. What I want is to get the correct area of the tilesheet texture (as seen in the first test, that gets just the yellow pixels). My question is: Is there any way that I can fix this, WITHOUT adding tile spacing or any other modification involving the tilesheet? Maybe disabling a texture filtering that is done by XNA, or something like that.

    Read the article

  • Drawing Grid in 3D view - Mathematically calculate points and draw line between them (Not working)

    - by Deukalion
    I'm trying to draw a simple grid from a starting point and expand it to a size. Doing this mathematically and drawing the lines between each point, but since the "DrawPrimitives(LineList)" doesn't work the way it should work, And this method can't even draw lines between four points to create a simple Rectangle, so how does this method work exactly? Some sort of coordinate system: [ ][ ][ ][ ][ ][ ][ ] [ ][2.2][ ][0.2][ ][2.2][ ] [ ][2.1][1.1][ ][1.1][2.1][ ] [ ][2.0][ ][0.0][ ][2.0][ ] [ ][2.1][1.1][ ][1.1][2.1][ ] [ ][2.2][ ][0.2][ ][2.2][ ] [ ][ ][ ][ ][ ][ ][ ] I've checked with my method and it's working as it should. It calculates all the points to form a grid. This way I should be able to create Points where to draw line right? This way, if I supply the method with Size = 2 it starts at 0,0 and works it through all the corners (2,2) on each side. So, I have the positions of each point. How do I draw lines between these? VerticeCount = must be number of Points in this case, right? So, tell me, if I can't supply this method with Point A, Point B, Point C, Point D to draw a four vertice rectangle (Point A - B - C - D) - how do I do it? How do I even begin to understand it? As far as I'm concered, that's a "Line list" or a list of points where to draw lines. Can anyone explain what I'm missing? I wish to do this mathematically so I can create a a custom grid that can be altered.

    Read the article

  • Spritebatch drawing sprite with jagged borders

    - by Mutoh
    Alright, I've been on the making of a sprite class and a sprite sheet manager, but have come across this problem. Pretty much, the project is acting like so; for example: Let's take this .png image, with a transparent background. Note how it has alpha-transparent pixels around it in the lineart. Now, in the latter link's image, in the left (with CornflowerBlue background) it is shown the image drawn in another project (let's call it "Project1") with a simpler sprite class - there, it works. The right (with Purple background for differentiating) shows it drawn with a different class in "Project2" - where the problem manifests itself. This is the Sprite class of Project1: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace WindowsGame2 { class Sprite { Vector2 pos = new Vector2(0, 0); Texture2D image; Rectangle size; float scale = 1.0f; // --- public float X { get { return pos.X; } set { pos.X = value; } } public float Y { get { return pos.Y; } set { pos.Y = value; } } public float Width { get { return size.Width; } } public float Height { get { return size.Height; } } public float Scale { get { return scale; } set { if (value < 0) value = 0; scale = value; if (image != null) { size.Width = (int)(image.Width * scale); size.Height = (int)(image.Height * scale); } } } // --- public void Load(ContentManager Man, string filename) { image = Man.Load<Texture2D>(filename); size = new Rectangle( 0, 0, (int)(image.Width * scale), (int)(image.Height * scale) ); } public void Become(Texture2D frame) { image = frame; size = new Rectangle( 0, 0, (int)(image.Width * scale), (int)(image.Height * scale) ); } public void Draw(SpriteBatch Desenhista) { // Desenhista.Draw(image, pos, Color.White); Desenhista.Draw( image, pos, new Rectangle( 0, 0, image.Width, image.Height ), Color.White, 0.0f, Vector2.Zero, scale, SpriteEffects.None, 0 ); } } } And this is the code in Project2, a rewritten, pretty much, version of the previous class. In this one I added sprite sheet managing and, in particular, removed Load and Become, to allow for static resources and only actual Sprites to be instantiated. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace Mobby_s_Adventure { // Actually, I might desconsider this, and instead use static AnimationLocation[] and instanciated ID and Frame; // For determining the starting frame of an animation in a sheet and being able to iterate through // the Rectangles vector of the Sheet; class AnimationLocation { public int Location; public int FrameCount; // --- public AnimationLocation(int StartingRow, int StartingColumn, int SheetWidth, int NumberOfFrames) { Location = (StartingRow * SheetWidth) + StartingColumn; FrameCount = NumberOfFrames; } public AnimationLocation(int PositionInSheet, int NumberOfFrames) { Location = PositionInSheet; FrameCount = NumberOfFrames; } public static int CalculatePosition(int StartingRow, int StartingColumn, SheetManager Sheet) { return ((StartingRow * Sheet.Width) + StartingColumn); } } class Sprite { // The general stuff; protected SheetManager Sheet; protected Vector2 Position; public Vector2 Axis; protected Color _Tint; public float Angle; public float Scale; protected SpriteEffects _Effect; // --- // protected AnimationManager Animation; // For managing the animations; protected AnimationLocation[] Animation; public int AnimationID; protected int Frame; // --- // Properties for easy accessing of the position of the sprite; public float X { get { return Position.X; } set { Position.X = Axis.X + value; } } public float Y { get { return Position.Y; } set { Position.Y = Axis.Y + value; } } // --- // Properties for knowing the size of the sprite's frames public float Width { get { return Sheet.FrameWidth * Scale; } } public float Height { get { return Sheet.FrameHeight * Scale; } } // --- // Properties for more stuff; public Color Tint { set { _Tint = value; } } public SpriteEffects Effect { set { _Effect = value; } } public int FrameID { get { return Frame; } set { if (value >= (Animation[AnimationID].FrameCount)) value = 0; Frame = value; } } // --- // The only things that will be constantly modified will be AnimationID and FrameID, anything else only // occasionally; public Sprite(SheetManager SpriteSheet, AnimationLocation[] Animations, Vector2 Location, Nullable<Vector2> Origin = null) { // Assign the sprite's sprite sheet; // (Passed by reference! To allow STATIC sheets!) Sheet = SpriteSheet; // Define the animations that the sprite has available; // (Passed by reference! To allow STATIC animation boundaries!) Animation = Animations; // Defaulting some numerical values; Angle = 0.0f; Scale = 1.0f; _Tint = Color.White; _Effect = SpriteEffects.None; // If the user wants a default Axis, it is set in the middle of the frame; if (Origin != null) Axis = Origin.Value; else Axis = new Vector2( Sheet.FrameWidth / 2, Sheet.FrameHeight / 2 ); // Now that we have the axis, we can set the position with no worries; X = Location.X; Y = Location.Y; } // Simply put, draw the sprite with all its characteristics; public void Draw(SpriteBatch Drafter) { Drafter.Draw( Sheet.Texture, Position, Sheet.Rectangles[Animation[AnimationID].Location + FrameID], // Find the rectangle which frames the wanted image; _Tint, Angle, Axis, Scale, _Effect, 0.0f ); } } } And, in any case, this is the SheetManager class found in the previous code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace Mobby_s_Adventure { class SheetManager { protected Texture2D SpriteSheet; // For storing the sprite sheet; // Number of rows and frames in each row in the SpriteSheet; protected int NumberOfRows; protected int NumberOfColumns; // Size of a single frame; protected int _FrameWidth; protected int _FrameHeight; public Rectangle[] Rectangles; // For storing each frame; // --- public int Width { get { return NumberOfColumns; } } public int Height { get { return NumberOfRows; } } // --- public int FrameWidth { get { return _FrameWidth; } } public int FrameHeight { get { return _FrameHeight; } } // --- public Texture2D Texture { get { return SpriteSheet; } } // --- public SheetManager (Texture2D Texture, int Rows, int FramesInEachRow) { // Normal assigning SpriteSheet = Texture; NumberOfRows = Rows; NumberOfColumns = FramesInEachRow; _FrameHeight = Texture.Height / NumberOfRows; _FrameWidth = Texture.Width / NumberOfColumns; // Framing everything Rectangles = new Rectangle[NumberOfRows * NumberOfColumns]; int ID = 0; for (int i = 0; i < NumberOfRows; i++) { for (int j = 0; j < NumberOfColumns; j++) { Rectangles[ID] = new Rectangle ( _FrameWidth * j, _FrameHeight * i, _FrameWidth, _FrameHeight ); ID++; } } } public SheetManager (Texture2D Texture, int NumberOfFrames): this(Texture, 1, NumberOfFrames) { } } } For even more comprehending, if needed, here is how the main code looks like (it's just messing with the class' capacities, nothing actually; the result is a disembodied feet walking in place animation on the top-left of the screen and a static axe nearby): 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; using System.Threading; namespace Mobby_s_Adventure { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; static List<Sprite> ToDraw; static Texture2D AxeSheet; static Texture2D FeetSheet; static SheetManager Axe; static Sprite Jojora; static AnimationLocation[] Hack = new AnimationLocation[1]; static SheetManager Feet; static Sprite Mutoh; static AnimationLocation[] FeetAnimations = new AnimationLocation[2]; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; this.TargetElapsedTime = TimeSpan.FromMilliseconds(100); this.IsFixedTimeStep = true; } /// <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); // Loading logic ToDraw = new List<Sprite>(); AxeSheet = Content.Load<Texture2D>("Sheet"); FeetSheet = Content.Load<Texture2D>("Feet Sheet"); Axe = new SheetManager(AxeSheet, 1); Hack[0] = new AnimationLocation(0, 1); Jojora = new Sprite(Axe, Hack, new Vector2(100, 100), new Vector2(5, 55)); Jojora.AnimationID = 0; Jojora.FrameID = 0; Feet = new SheetManager(FeetSheet, 8); FeetAnimations[0] = new AnimationLocation(1, 7); FeetAnimations[1] = new AnimationLocation(0, 1); Mutoh = new Sprite(Feet, FeetAnimations, new Vector2(0, 0)); Mutoh.AnimationID = 0; Mutoh.FrameID = 0; } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <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) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // Update logic Mutoh.FrameID++; ToDraw.Add(Mutoh); ToDraw.Add(Jojora); base.Update(gameTime); } /// <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.Purple); // Drawing logic spriteBatch.Begin(); foreach (Sprite Element in ToDraw) { Element.Draw(spriteBatch); } spriteBatch.Draw(Content.Load<Texture2D>("Sheet"), new Rectangle(50, 50, 55, 60), Color.White); spriteBatch.End(); base.Draw(gameTime); } } } Please help me find out what I'm overlooking! One thing that I have noticed and could aid is that, if inserted the equivalent of this code spriteBatch.Draw( Content.Load<Texture2D>("Image Location"), new Rectangle(X, Y, images width, height), Color.White ); in Project2's Draw(GameTime) of the main loop, it works. EDIT Ok, even if the matter remains unsolved, I have made some more progress! As you see, I managed to get the two kinds of rendering in the same project (the aforementioned Project2, with the more complex Sprite class). This was achieved by adding the following code to Draw(GameTime): protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Purple); // Drawing logic spriteBatch.Begin(); foreach (Sprite Element in ToDraw) { Element.Draw(spriteBatch); } // Starting here spriteBatch.Draw( Axe.Texture, new Vector2(65, 100), new Rectangle ( 0, 0, Axe.FrameWidth, Axe.FrameHeight ), Color.White, 0.0f, new Vector2(0, 0), 1.0f, SpriteEffects.None, 0.0f ); // Ending here spriteBatch.End(); base.Draw(gameTime); } (Supposing that Axe is the SheetManager containing the texture, sorry if the "jargons" of my code confuse you :s) Thus, I have noticed that the problem is within the Sprite class. But I only get more clueless, because even after modifying its Draw function to this: public void Draw(SpriteBatch Drafter) { /*Drafter.Draw( Sheet.Texture, Position, Sheet.Rectangles[Animation[AnimationID].Location + FrameID], // Find the rectangle which frames the wanted image; _Tint, Angle, Axis, Scale, _Effect, 0.0f );*/ Drafter.Draw( Sheet.Texture, Position, new Rectangle( 0, 0, Sheet.FrameWidth, Sheet.FrameHeight ), Color.White, 0.0f, Vector2.Zero, Scale, SpriteEffects.None, 0 ); } to make it as simple as the patch of code that works, it still draws the sprite jaggedly!

    Read the article

  • WPF, how can I optimize lines and circles drawing ?

    - by Aurélien Ribon
    Hello ! I am developping an application where I need to draw a graph on the screen. For this purpose, I use a Canvas and I put Controls on it. An example of such a draw as shown in the app can be found here : http://free0.hiboox.com/images/1610/d82e0b7cc3521071ede601d3542c7bc5.png It works fine for simple graphs, but I also want to be able to draw very large graphs (hundreds of nodes). And when I try to draw a very large graph, it takes a LOT of time to render. My problem is that the code is not optimized at all, I just wanted it to work. Until now, I have a Canvas on the one hand, and multiple Controls on the other hands. Actually, circles and lines are listed in collections, and for each item of these collections, I use a ControlTemplate, defining a red circle, a black circle, a line, etc. Here is an example, the definition of a graph circle : <!-- STYLE : DISPLAY DATA NODE --> <Style TargetType="{x:Type flow.elements:DisplayNode}"> <Setter Property="Canvas.Left" Value="{Binding X, RelativeSource={RelativeSource Self}}" /> <Setter Property="Canvas.Top" Value="{Binding Y, RelativeSource={RelativeSource Self}}" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type flow.elements:DisplayNode}"> <!--TEMPLATE--> <Grid x:Name="grid" Margin="-30,-30,0,0"> <Ellipse x:Name="selectionEllipse" StrokeThickness="0" Width="60" Height="60" Opacity="0" IsHitTestVisible="False"> <Ellipse.Fill> <RadialGradientBrush> <GradientStop Color="Black" Offset="0.398" /> <GradientStop Offset="1" /> </RadialGradientBrush> </Ellipse.Fill> </Ellipse> <Ellipse Stroke="Black" Width="30" Height="30" x:Name="ellipse"> <Ellipse.Fill> <LinearGradientBrush EndPoint="0,1"> <GradientStop Offset="0" Color="White" /> <GradientStop Offset="1.5" Color="LightGray" /> </LinearGradientBrush> </Ellipse.Fill> </Ellipse> <TextBlock x:Name="tblock" Text="{Binding NodeName, RelativeSource={RelativeSource Mode=TemplatedParent}}" Foreground="Black" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="10.667" /> </Grid> <!--TRIGGERS--> <ControlTemplate.Triggers> <!--DATAINPUT--> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="SkinMode" Value="NODETYPE" /> <Condition Property="NodeType" Value="DATAINPUT" /> </MultiTrigger.Conditions> <Setter TargetName="tblock" Property="Foreground" Value="White" /> <Setter TargetName="ellipse" Property="Fill"> <Setter.Value> <LinearGradientBrush EndPoint="0,1"> <GradientStop Offset="-0.5" Color="White" /> <GradientStop Offset="1" Color="Black" /> </LinearGradientBrush> </Setter.Value> </Setter> </MultiTrigger> <!--DATAOUTPUT--> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="SkinMode" Value="NODETYPE" /> <Condition Property="NodeType" Value="DATAOUTPUT" /> </MultiTrigger.Conditions> <Setter TargetName="tblock" Property="Foreground" Value="White" /> <Setter TargetName="ellipse" Property="Fill"> <Setter.Value> <LinearGradientBrush EndPoint="0,1"> <GradientStop Offset="-0.5" Color="White" /> <GradientStop Offset="1" Color="Black" /> </LinearGradientBrush> </Setter.Value> </Setter> </MultiTrigger> ....... THERE IS A TOTAL OF 7 MULTITRIGGERS ....... </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> Also, the lines are drawn using the Line Control. <!-- STYLE : DISPLAY LINK --> <Style TargetType="{x:Type flow.elements:DisplayLink}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type flow.elements:DisplayLink}"> <!--TEMPLATE--> <Line X1="{Binding X1, RelativeSource={RelativeSource TemplatedParent}}" X2="{Binding X2, RelativeSource={RelativeSource TemplatedParent}}" Y1="{Binding Y1, RelativeSource={RelativeSource TemplatedParent}}" Y2="{Binding Y2, RelativeSource={RelativeSource TemplatedParent}}" Stroke="Gray" StrokeThickness="2" x:Name="line" /> <!--TRIGGERS--> <ControlTemplate.Triggers> <!--BRANCH : ASSERTION--> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="SkinMode" Value="BRANCHTYPE" /> <Condition Property="BranchType" Value="ASSERTION" /> </MultiTrigger.Conditions> <Setter TargetName="line" Property="Stroke" Value="#E0E0E0" /> </MultiTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> So, I need your advices. How can I drastically improve the rendering performances ? Should I define each MultiTrigger circle rendering possibility in its own ControlTemplate instead ? Is there a better line drawing technique ? Should I open a DrawingContext and draw everything in one control, instead of having hundreds of controls ?

    Read the article

  • Refactoring an immediate drawing function into VBO, access violation error

    - by Alex
    I have a MD2 model loader, I am trying to substitute its immediate drawing function with a Vertex Buffer Object one.... I am getting a really annoying access violation reading error and I can't figure out why, but mostly I'd like an opinion as to whether this looks correct (never used VBOs before). This is the original function (that compiles ok) which calculates the keyframe and draws at the same time: glBegin(GL_TRIANGLES); for(int i = 0; i < numTriangles; i++) { MD2Triangle* triangle = triangles + i; for(int j = 0; j < 3; j++) { MD2Vertex* v1 = frame1->vertices + triangle->vertices[j]; MD2Vertex* v2 = frame2->vertices + triangle->vertices[j]; Vec3f pos = v1->pos * (1 - frac) + v2->pos * frac; Vec3f normal = v1->normal * (1 - frac) + v2->normal * frac; if (normal[0] == 0 && normal[1] == 0 && normal[2] == 0) { normal = Vec3f(0, 0, 1); } glNormal3f(normal[0], normal[1], normal[2]); MD2TexCoord* texCoord = texCoords + triangle->texCoords[j]; glTexCoord2f(texCoord->texCoordX, texCoord->texCoordY); glVertex3f(pos[0], pos[1], pos[2]); } } glEnd(); What I'd like to do is to calculate all positions before hand, store them in a Vertex array and then draw them. This is what I am trying to replace it with (in the exact same part of the program) int vCount = 0; for(int i = 0; i < numTriangles; i++) { MD2Triangle* triangle = triangles + i; for(int j = 0; j < 3; j++) { MD2Vertex* v1 = frame1->vertices + triangle->vertices[j]; MD2Vertex* v2 = frame2->vertices + triangle->vertices[j]; Vec3f pos = v1->pos * (1 - frac) + v2->pos * frac; Vec3f normal = v1->normal * (1 - frac) + v2->normal * frac; if (normal[0] == 0 && normal[1] == 0 && normal[2] == 0) { normal = Vec3f(0, 0, 1); } indices[vCount] = normal[0]; vCount++; indices[vCount] = normal[1]; vCount++; indices[vCount] = normal[2]; vCount++; MD2TexCoord* texCoord = texCoords + triangle->texCoords[j]; indices[vCount] = texCoord->texCoordX; vCount++; indices[vCount] = texCoord->texCoordY; vCount++; indices[vCount] = pos[0]; vCount++; indices[vCount] = pos[1]; vCount++; indices[vCount] = pos[2]; vCount++; } } totalVertices = vCount; glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glNormalPointer(GL_FLOAT, 0, indices); glTexCoordPointer(2, GL_FLOAT, sizeof(float)*3, indices); glVertexPointer(3, GL_FLOAT, sizeof(float)*5, indices); glDrawElements(GL_TRIANGLES, totalVertices, GL_UNSIGNED_BYTE, indices); glDisableClientState(GL_VERTEX_ARRAY); // disable vertex arrays glEnableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); First of all, does it look right? Second, I get access violation error "Unhandled exception at 0x01455626 in Graphics_template_1.exe: 0xC0000005: Access violation reading location 0xed5243c0" pointing at line 7 Vec3f pos = v1->pos * (1 - frac) + v2->pos * frac; where the two Vs seems to have no value in the debugger.... Till this point the function behaves in exactly the same way as the one above, I don't understand why this happens? Thanks for any help you may be able to provide!

    Read the article

  • Segfault when iterating over a map<string, string> and drawing its contents using SDL_TTF

    - by Michael Stahre
    I'm not entirely sure this question belongs on gamedev.stackexchange, but I'm technically working on a game and working with SDL, so it might not be entirely offtopic. I've written a class called DebugText. The point of the class is to have a nice way of printing values of variables to the game screen. The idea is to call SetDebugText() with the variables in question every time they change or, as is currently the case, every time the game's Update() is called. The issue is that when iterating over the map that contains my variables and their latest updated values, I get segfaults. See the comments in DrawDebugText() below, it specifies where the error happens. I've tried splitting the calls to it-first and it-second into separate lines and found that the problem doesn't always happen when calling it-first. It alters between it-first and it-second. I can't find a pattern. It doesn't fail on every call to DrawDebugText() either. It might fail on the third time DrawDebugText() is called, or it might fail on the fourth. Class header: #ifndef CLIENT_DEBUGTEXT_H #define CLIENT_DEBUGTEXT_H #include <Map> #include <Math.h> #include <sstream> #include <SDL.h> #include <SDL_ttf.h> #include "vector2.h" using std::string; using std::stringstream; using std::map; using std::pair; using game::Vector2; namespace game { class DebugText { private: TTF_Font* debug_text_font; map<string, string>* debug_text_list; public: void SetDebugText(string var, bool value); void SetDebugText(string var, float value); void SetDebugText(string var, int value); void SetDebugText(string var, Vector2 value); void SetDebugText(string var, string value); int DrawDebugText(SDL_Surface*, SDL_Rect*); void InitDebugText(); void Clear(); }; } #endif Class source file: #include "debugtext.h" namespace game { // Copypasta function for handling the toString conversion template <class T> inline string to_string (const T& t) { stringstream ss (stringstream::in | stringstream::out); ss << t; return ss.str(); } // Initializes SDL_TTF and sets its font void DebugText::InitDebugText() { if(TTF_WasInit()) TTF_Quit(); TTF_Init(); debug_text_font = TTF_OpenFont("LiberationSans-Regular.ttf", 16); TTF_SetFontStyle(debug_text_font, TTF_STYLE_NORMAL); } // Iterates over the current debug_text_list and draws every element on the screen. // After drawing with SDL you need to get a rect specifying the area on the screen that was changed and tell SDL that this part of the screen needs to be updated. this is done in the game's Draw() function // This function sets rects_to_update to the new list of rects provided by all of the surfaces and returns the number of rects in the list. These two parameters are used in Draw() when calling on SDL_UpdateRects(), which takes an SDL_Rect* and a list length int DebugText::DrawDebugText(SDL_Surface* screen, SDL_Rect* rects_to_update) { if(debug_text_list == NULL) return 0; if(!TTF_WasInit()) InitDebugText(); rects_to_update = NULL; // Specifying the font color SDL_Color font_color = {0xff, 0x00, 0x00, 0x00}; // r, g, b, unused int row_count = 0; string line; // The iterator variable map<string, string>::iterator it; // Gets the iterator and iterates over it for(it = debug_text_list->begin(); it != debug_text_list->end(); it++) { // Takes the first value (the name of the variable) and the second value (the value of the parameter in string form) //---------THIS LINE GIVES ME SEGFAULTS----- line = it->first + ": " + it->second; //------------------------------------------ // Creates a surface with the text on it that in turn can be rendered to the screen itself later SDL_Surface* debug_surface = TTF_RenderText_Solid(debug_text_font, line.c_str(), font_color); if(debug_surface == NULL) { // A standard check for errors fprintf(stderr, "Error: %s", TTF_GetError()); return NULL; } else { // If SDL_TTF did its job right, then we now set a destination rect row_count++; SDL_Rect dstrect = {5, 5, 0, 0}; // x, y, w, h dstrect.x = 20; dstrect.y = 20*row_count; // Draws the surface with the text on it to the screen int res = SDL_BlitSurface(debug_surface,NULL,screen,&dstrect); if(res != 0) { //Just an error check fprintf(stderr, "Error: %s", SDL_GetError()); return NULL; } // Creates a new rect to specify the area that needs to be updated with SDL_Rect* new_rect_to_update = (SDL_Rect*) malloc(sizeof(SDL_Rect)); new_rect_to_update->h = debug_surface->h; new_rect_to_update->w = debug_surface->w; new_rect_to_update->x = dstrect.x; new_rect_to_update->y = dstrect.y; // Just freeing the surface since it isn't necessary anymore SDL_FreeSurface(debug_surface); // Creates a new list of rects with room for the new rect SDL_Rect* newtemp = (SDL_Rect*) malloc(row_count*sizeof(SDL_Rect)); // Copies the data from the old list of rects to the new one memcpy(newtemp, rects_to_update, (row_count-1)*sizeof(SDL_Rect)); // Adds the new rect to the new list newtemp[row_count-1] = *new_rect_to_update; // Frees the memory used by the old list free(rects_to_update); // And finally redirects the pointer to the old list to the new list rects_to_update = newtemp; newtemp = NULL; } } // When the entire map has been iterated over, return the number of lines that were drawn, ie. the number of rects in the returned rect list return row_count; } // The SetDebugText used by all the SetDebugText overloads // Takes two strings, inserts them into the map as a pair void DebugText::SetDebugText(string var, string value) { if (debug_text_list == NULL) { debug_text_list = new map<string, string>(); } debug_text_list->erase(var); debug_text_list->insert(pair<string, string>(var, value)); } // Writes the bool to a string and calls SetDebugText(string, string) void DebugText::SetDebugText(string var, bool value) { string result; if (value) result = "True"; else result = "False"; SetDebugText(var, result); } // Does the same thing, but uses to_string() to convert the float void DebugText::SetDebugText(string var, float value) { SetDebugText(var, to_string(value)); } // Same as above, but int void DebugText::SetDebugText(string var, int value) { SetDebugText(var, to_string(value)); } // Vector2 is a struct of my own making. It contains the two float vars x and y void DebugText::SetDebugText(string var, Vector2 value) { SetDebugText(var + ".x", to_string(value.x)); SetDebugText(var + ".y", to_string(value.y)); } // Empties the list. I don't actually use this in my code. Shame on me for writing something I don't use. void DebugText::Clear() { if(debug_text_list != NULL) debug_text_list->clear(); } }

    Read the article

  • Remove Excel data link in Visio Drawing

    - by Ddono25
    I am creating a server topology for one of our SharePoint farms and thought it would be easy to just link the Excel spreadsheet with our server information to the Visio drawing to auto-populate some things. It didn't work out that well, but the drawing is finished without it now. I cannot remove the link between the Excel spreadsheet and the Visio diagram. Whenever the drawing is opened the linked excel server list opens in a pane at the very bottom of the window. How would I eliminate the data link? Or just the spreadsheet from view when being opened?

    Read the article

  • What are some good algorithms for drawing lines between graph nodes?

    - by ApplePieIsGood
    What I'm specifically grappling with is not just the layout of a graph, but when a user selects a graph node and starts to drag it around the screen area, the line has to constantly be redrawn to reflect what it would look like if the user were to release the node. I suppose this is part of the layout algorithm? Also some applications get a bit fancy and don't simply draw the line in a nice curvy way, but also bend the line around the square shaped node in almost right angles. See attached image and keep in mind that as a node is dragged, the line is drawn as marching ants, and re-arranged nicely, while retaining its curved style.

    Read the article

  • Suggested (simple) approach for drawing large numbers of visual elements in WPF?

    - by Ender
    I'm writing an interface that features a large (~50000px width) "canvas"-type area that is used to display a lot of data in a fairly novel way. This involves lots of lines, rectangles, and text. The user can scroll around to explore the entire canvas. At the moment I'm just using a standard Canvas panel with various Shapes placed on it. This is nice and easy to do: construct a shape, assign some coordinates, and attach it to the Canvas. Unfortunately, it's pretty slow (to construct the children, not to do the actual rendering). I've looked into some alternatives, it's a bit intimidating. I don't need anything fancy - just the ability to efficiently construct and place objects in a coordinate plane. If all I get are lines, colored rectangles, and text, I'll be happy. Do I need Geometry instances inside of Geometry Groups inside of GeometryDrawings inside of some Panel container? Note: I'd like to include text and graphics (i.e. colored rectangles) in the same space, if possible.

    Read the article

  • System.Drawing - bad text rendering using DrawString on top of transparent pixels.

    - by mackenir
    When rendering text into a bitmap, I find that text looks very bad when rendered on top of an area with non-opaque alpha. The problem is progressively worse as the underlying pixels become more transparent. If I had to guess I'd say that when underlying pixels are transparent, the text renderer draws any anti-aliased 'gray' pixels as solid black. Here are some screenshots: Text drawn on top of transparent pixels: Text drawn on top of semi-transparent pixels: Text drawn on opaque pixels: Here is the code used to render the text: g.SmoothingMode = SmoothingMode.HighQuality; g.DrawString("Press the spacebar", Font, Brushes.Black, textLeft, textTop);

    Read the article

  • Fast sketching tools for drawing C/C++ structs, pointers, etc...

    - by tomasorti
    Hi. I would like to know what do you use to sketch relations between different entities in C/C++. This can be a very broad issue, so I'll try to clarify a bit more my question and give an example. I'm looking for something that is simple enough as a user, and let me sketch easily containers, pointers, etc... in an informal way. The aim is to document some structs relations to pass them to junior developers. A look at the drawings is supposed to accelerate the understanding of the code. My solutions at this moment are to use: 1) Paper & pencil. 2) Microsoft PowerPoint/Word Autoshapes. 3) Freeware Dia. Other ones could be: 4) Microsoft Visio, but my company does not own licenses. 5) UML tools. I don't want to go this way. This is what I mean a more formal solution. I know tools like Rational Rose are great, and I tried boUML and violet and they are fine in some parts, but I prefer the flexibility of options 2) or 3). Finally, let me write down a more concrete example: Let's say I what to sketch a map that contains another map as the mapped value, and that one contains a struct as the mapped value, that holds a vector of pointers of a type and a pointer to other type. Also, there exist other structs that hold pointers to the objects pointed by the previous map, so there are objects pointed from different places. This is just one example I have, but you can easily come with one from you experience. What would you use to sketch this example or another similar you have dealt with? Best regards, Tomas.

    Read the article

  • Drawing Directed Acyclic Graphs: Using DAG property to improve layout/edge routing?

    - by Robert Fraser
    Hi, Laying out the verticies in a DAG in a tree form (i.e. verticies with no in-edges on top, verticies dependent only on those on the next level, etc.) is rather simple. However, is there a simple algorithm to do this that minimizes edge crossing? (For some graphs, it may be impossible to completely eliminate edge crossing.) A picture says a thousand words, so is there an algorithm that would suggest: instead of:

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >