How to draw in C#/WinForms with decent speed? - c#

I'm trying to visualise a graph and allow people to play with it. I found the excellent Graph# library that can create an initial layout so that part is covered. Now I need to make a control that actually draws it and provides the necessary interactivity.
Graph# comes with a nice visualiser itself, however I don't like it because it is written in WPF (while my app is WinForms), and because I want to add some more interactivity options, which would require quite a remake of it anyway.
The graphs I'm drawing will routinely be pretty large, at about 100 vertices and the same amount of edges (the graphs will be trees 99% of time). That means that the resulting rendering can be up to 2000px by 2000px and even more. The users should be able to zoom in and out, scroll, highlight and drag vertices and edges, and get some popups with additional info when hovering the cursor above a vertex.
I'm worried that the standard System.Drawing might not be able to deliver a decent speed for this. I would like the dragging/zooming/scrolling operations to be smooth, and the popups should open with a little animation as well. Something like 20fps should be a necessity.
I know I can try to speed things up by pre-rendering a lot of the elements and keeping them as bitmaps in memory - but that would probably take up lots of RAM, and I'm still not sure if it would deliver the necessary performance.
What are your thoughts?

"Premature optimization is the root of all evil"
GDI+ can be great for your needs. Don't go and buy 3rd party libraries before you know you even need them.
I've done a thousand polygons on a 1000x800 pixel bitmap and redrawn it completely at over 100 frames per second, using just GDI+
That being said, if you have a lot of drawing to do, and your resolution is big.. Some of the 3rd party drawing libraries can go WAY beyond what managed GDI is capable of.

I recommend leaving Graph# alone, and just hosting it in your Windows Forms application.
The performance you will receive will be much better than trying to reimplement it in System.Drawing.

GDI+ will be plenty fast enough for what you're doing, especially if (as it sounds from your description) everything you're drawing is rectangles and vertical/horizontal lines. Polygons and non-linear shapes are a bit slower, but not much (the speed difference is partially dependent on the SmoothingMode of your Graphics object). Drawing cached Bitmaps with resizing is also quite fast, although it can slow down significantly if you use a high-quality InterpolationMode setting.
As a benchmark, I wrote a .Net Compact Framework GPS application for Windows Mobile that rendered about 10,000 lines on the screen in realtime. This only achieved a frame rate of a few frames per second, but the processing power on a Smartphone is, of course, way less than a modern PC.

Related

How much improvement can I expect with SharpDX over heavily optimized GDI code in C#/WinForms?

I've been working on a C#/GDI graphical app for a couple years. I've spent a lot of time optimizing the drawing code. I am drawing to the screen by invalidating a PictureBox control about 10 times a second, and by leveraging subsequent OnPaint event that occurs when Windows triggers it. The OnPaint event gives me access to the Graphics object via the PaintEventArgs param.
Per frame: I draw hundreds of lines, hundreds of rectangles, and I call the Graphics.DrawString() method hundreds of times as well.
I started putting together a SharpDX project in hopes I could draw more 2D elements, and draw faster to the screen. I set up 2 test projects that draw the same 2D elements on the screen using GDI and using SharpDX. I used a C# StopWatch object to detect how long it was taking to draw all the 2D elements. So far, I have not noticed any speed improvement when drawing with SharpDX. Both GDI and SharpDX average about 20millis per draw.
How much of a speed improvement should I expect by using SharpDX? And which portion of the rasterization is supposed to make it faster than GDI?
I worked on a Windows Forms app where the "rendering system" was pluggable, and I initially wrote two rendering systems: one in GDI+, and one in Managed DirectX (a .NET wrapper around DirectX, similar to SharpDX). Because I was doing a lot of drawing of images at arbitrary scales, Managed DirectX blew GDI+ out of the water for our use case. Drawing code that used 1-pixel-wide lines was also very fast in Managed DirectX. Thick lines were much slower than single-pixel lines, because they were actually rendered as triangle strips (which can be drawn quickly by the GPU) whose coordinates had to be calculated by the CPU, and the geometry was complicated by segment joints (which were rounded, if I remember right). Fortunately, in our application we didn't need to draw curves, but those would have to be approximated by small line segments (for single-pixel widths) and triangles (for anything thicker).
It's things like CPU-based approximation and triangulation that slow a Direct3D app down. 3D games use pre-calculated meshes and make use of vertex buffers on the GPU to avoid moving data back and forth from the CPU to GPU. I don't have any data comparing speeds between GDI+ and DirectX, but these are some things to consider.
Direct2D takes a bit of getting used to, but once you get it up and running properly I can promise that you will never look back. I used it to migrate a very large project which was based on DirectDraw with GDI+ Interop and saw a huge performance increase as well as better stability and a more satisfying development experience.
It has received a lot of negative press about performance, particularly when it was first introduced but if you hook it up to a DXGI swap chain (which is very easy to do) and keep your code sensible, the benefits will be most clear.
SharpDX is the right choice and it will only get faster in the near future, with SSE/SIMD driven primitives just around the corner.

Hardware Acceleration in MFC

I am currently developing a software that involves real-time rendering of performance metrics in graph and chart forms. I need to acquire data, process data and render an image as fast as possible. My backend is in C++, and I am at a point where I have to make a choice regarding the front end.
Given my backend is in C++, I was inclined to go with MFC. The other alternative is to go with WPF C# for frontend and interop with my C++ backend. I read recently that WPF provides for hardware acceleration, this should help me achieve a high frame rate. Does MFC hardware accelerate its graphics too? Does hardware acceleration even matter?
Given WPF's hardware acceleration, does that make WPF the most efficient alternative for graphics in my case?
WPF provides hardware acceleration using DirectX 9 I believe. However for line graphs the limiting factor is the amount of interface elements. We are creating a program in WPF that displays sEMG data real-time using Telerik charts. These can be configured to use direct2d acceleration under the hood which cranks up the performance a bit if you have a lot of datapoints. It's still jerky though because you cannot control the render thread of WPF.
It kind of depends on the amount of features you need in the graph. If the priority is to have silky smooth real-time display don't go with WPF.
Visual Studio 2010 added classes to MFC to support using Direct2D rendering from MFC programs.
To use Direct2D, you start by calling EnableD2DSupport() in your View's OnCreate (technically, I suppose it doesn't have to be in OnCreate, but that's the usual place). Then you'll receive AFX_WM_DRAW2D messages when the D2D display context needs updating, so you'll normally want to add a handler for that, and respond to it by rendering your content as needed.
Another possibility to consider would be to use an existing control to draw your graphs. There are quite a few around, including some that are free with quite liberal licensing. Just for example, CodeProject has a number of Charting controls, a few of which use D2D for their drawing, and quite a few more that don't.
Honestly, I'd be a little surprised at charts having information being updated fast enough for drawing speed to make a huge difference as a rule though. In most typical cases, the real limit will be the user's ability to comprehend what you're drawing. A user simply can't watch 100 different graphs each being updated at (say) 60 Hz, and have much hope of deriving much real meaning from most of them. In most cases, the real challenge isn't to draw more data faster, but to provide better ways for the user to focus on the few things they can follow at a time, and (for example) draw their attention to important changes when needed.

Trying to figure out how to match aspect ratio on mac to android

I'm making a shape matching game for toddlers.
I drew the shapes using gimp on my mac.
The images all seemed stretched out on the android devices.
Is there some mathematical way i could figure out how much shorter I have to make the images on the mac computer so they look correctly on the android devices?
This is a tough question. I have made several Apps for iOS and have pretty much the same problem with graphics for buttons and backgrounds when going between iPhone and iPad, which have different aspect ratios (which I suspect is the problem you are having). Throw orientation into the mix as well.
I use Gimp, Inkscape, Spine, Cocos2d-x, and lots of other tools for reference (see here).
As far as I know, the general options for "different screen geometry" issues are (if there are others, let me know):
Different graphics for each geometry.
Scaling the graphics proportionally for the geometry (I suspect you have this).
Same graphics for all, scale proportionally based on one dimension and then place graphics on screen using percentages for fixed stuff.
Option 1 means extra work...not acceptable for a hobbyist or indie (like me) developer.
Option 2 usually looks like junk. Frustration and sadness usually ensue.
Option 3 is the option I use most often. I find that occasionally I have to add small changes (read: hacks) based on the device or geometry. In the case of iOS, it is not too bad, because there are only two geometries to deal with. In the case of Android, where there are lots of different tablet geometries, you could cut it down by working with ranges of geometries and picking a fixed orientation for your application.
At the end of the day, proportional scaling by a single dimension (height or width) has gotten me the most bang for the buck.
I usually make the graphics a little "bigger" than I will need so I only have to scale down. This consumes a bit more memory, but I re-use a lot, use sprite sheets, etc. There is a definite tradeoff with managing every bit of memory (which you have to do in a large AAA rated game) and what you can get away with in a small independent application. I am not encouraging sloppiness or memory mismanagement; I'm encouraging balancing the resources against the developmental needs of simplicity...making the same graphics for different situations burns a lot of daylight.
ONE MORE NOTE:
For applications where I use a framework for the graphics (i.e. games), I use a "viewport" to let me match up the physics with the graphics...that is to say, dynamically scale the size of the graphics based on how much of the total scene I want the user to see. This lets me put the graphic for the "body" on top of it and match up the size statically or dynamically as needed. The code is in C++ and is only loosely tied to the framework...and the concept is applicable to general situations for games (i.e. scaling the graphics as needed). You can find some description and code here, if you are interested.
Was this helpful?
You need to design your application so that it can function correctly regardless of device resolution as many mobile devices have many different aspect ratios and resolutions.
If your images are being stretched then you need to change the ui design so that they are enlarged and spaced out to make use of whatever space there is.

Native WPF vs. Custom DirectX for displaying large images

I need to speed up my image viewer, and wondering if I should be looking into creating my own DirectX control to do so.
My image viewer displays medical images. They can be pretty large. We're talking 55mb when it comes to mammography. The pixel data is 16bit greyscale stored in a ushort array. Without getting into the gory details, my current approach is loading the pixel data into an ImageSource, and using the WPF Image control.
I've never done anything with DirectX. Is it worth diving into it? Would it be any faster than the native WPF stuff? If so how significantly? Or, should I just forget about DirectX and look into areas where I can improve my current approach?
Before somebody says so, I know WPF utilize DirectX. I'm wondering If removing the WPF layer and writing the DirectX myself will improve performance.
I have some experience drawing multi-gigabyte satellite and chart imagery. Working with imagery around 55MB should probably work okay even without trying to optimize it too much. You haven't really given enough detail to recommend one alternative over the other, so I will give my opinion on the pros and cons.
Using 2D windows APIs will be the simplest to implement and should always be fast enough if you don't need to rotate and simply want to display an image and zoom and pan around. If you treat it as one large image the performance will not be as good when you zoom out if you are drawing with halftoning to give a nice smooth image. This is because it will effectively have to read all 55mb of image every time it draws.
To get around this performance issue you can make multiple bitmaps, effectively mip-mapping your image. As you zoom out you can pick the reduced resolution image closest to the resolution you are trying to draw . If you are not familiar with mip-mapping here is a Wikipedia link:
http://en.wikipedia.org/wiki/Mipmap
Implementing it with DirectX will be 10x as difficult. Different graphics hardware has different maximum texture sizes. Most likely you will need to break your image up in to multiple textures to draw and you will also have to keep track of render states, viewing matrices, etc.
However, if you do use DirectX, you can implement lots of real-time photo adjustments You can do real-time rotation by simply adjusting view matrices. You can do real-time contrast, brightness, gamma, and sharpness easily in a pixel shader.
There are two other API's I might suggest. If you are willing to limit yourself to Vista or later then Direct2D would be a little simpler than Direct3D. Also if you ever will need to implement it on a non-windows platform I would suggest using OpenGL instead. My current project is in Direct3D because a few years ago when we started it OpenGL was falling behind and I didn't forsee the popularity of Android devices. I now wish we had used OpenGL instead.
Try profiling to see where WPF is spending its time. Are you displaying the images at their native resolution? If not it might be worthwhile to do some preprocessing and create 1/2 resolution versions.

C# GDI+/System.Drawing.Graphics - creating a buffer and manually blitting?

I'm creating a cad viewer which deals with very large image files and I am trying to optimise it for as high a framerate and low a memory footprint as possible.
It uses GDI+ for rendering onto a panel.
It's current flaw is with image rendering. Some of the files I'm using reference images which are particularly big (8000x8000 pixels). I've optimised the memory usage by only loading them when they become visible and disposing of them when they're not. This reduces the chance of the program running out of memory but prevents the images from being loaded and unloaded too often; however rendering the images themselves (context.DrawImage) still carries a very large overhead.
I'm now exploring ways of blitting the images into a smaller buffer of some sort, rendering this (generally much smaller) buffer, and then refreshing/rebuilding it when the zoom level changes significantly.
The problem is, I can't find any provision for this in GDI whatsoever. Can anyone suggest how I could achieve it?
I don't think GDI is designed for such high-speed updates of images. If you are trying to scroll the image, and tracking the mouse with each move, try to shift sections of the image and fill in the space opened up by the shift. Essentially reuse the tricks that programmers used when smoothly scrolling/panning graphics at a time when CPU's are slow and RAM is small.
If you're creating a new graphics application that needs a high framerate and are looking for suggestions, then I suggest abandoning GDI+ and using WPF. WPF uses hardware acceleration and supports retained-mode graphics; this has much better performance for less work than GDI+.
If there is some limitation that forbids WPF, please explain it in your question. This is relevant because such limitations can also impact GDI+ drawing.
GDI Binned in favour of Direct3D as 3D elements came into the equation anyway. Images turned into single thumbnails and larger tiles that are loaded in/out as required.
I faced a similar problem when developing my own GIS application. The best solution I found for this (even when using WPF) is to tile big images and display only the portions that are visible. This is being said, I would switch to WPF not only for the reasons given in the above answers but also for the good imaging support offered. See this link for more information

Categories

Resources