Changing display modes from the command line - c

Way way back in the day Itried to learn C from a game programming book. If I recall correctly, one of the first things your game "engine" would do would be to switch display modes to render. This involved a bit of asm to switch to a 640x480 display mode (mode 13 maybe?) so you could draw directly to the screen. Something like that.
My question is, what is the modern equivalent of this? I'm interested in writing a command line program that does something similar; drops into some kind of raster mode for me to draw to, but, I do not assume that my program would be running under some kind of window manager like kde, unity,Aqua etc.
Would this be something that OpenGL could provide (or does OpenGL assume a window manager too). My proposed program isn't a game, but would ideally start with a basic clear screen that I can draw primitives (2d lines, circles rects etc)
Cheers!

Modern operating systems don't give programmers as convenient access to low-level graphics routines as they used to. Partially, this is due to the advent of the GPU, which makes utilizing the graphics hardware a much more significant challenge than if you only had a CPU. The other reason is as window managers have gotten more and more complex, the graphical sandbox each operating system gives a programmer is more constrained.
That being said, OpenGL is definitely worth looking at. Its cross-platform, versatile, and automatically utilizes any hardware available (including the graphics card). OpenGL itself doesn't directly provide access to a windowing context, but you can easily create that with the OpenGL utility library (GLUT). OpenGL is however very low-level, you'll have to deal with frame buffers and flushing and bit masks and all sorts of low-level nonsense that can make OpenGL development a nightmare if you haven't done it before.
If I were starting a project, I would probably want a more robust graphics environment that provides drawing functions and windowing out of the box. Both SDL and SFML provide low-level graphics APIs that will be a little more friendly to start with. They are both implemented on top of OpenGL so you can use any of the OpenGL features when you want to, but you don't have to worry about some of the more tedious details.
As a side note, C might not be the best language to get started with graphics programming these days. If you want a really simple graphics environment that is becoming more relevant every day, you might want to check out what the web has to provide. JavaScript and the HTML5Canvas provide a very simple interface for drawing primitives, images, etc.

Related

How to create a graphic canvas in pure c to display graphic figures without any libraries and platform independent

I think it must be possible to create a graphics library without any other library.
Just to draw circles and triangles and rectangles with basic math. If so, where is the point how to make the "drawable area"?
Is it possible to draw to screen in pure C or is assembly required?
Graphics programming is inherently platform dependent. Let's say, for the sake of argument, there were only two operating systems: linux and windows. You can use platform specific functions on both of them, to create windows and draw something. For your application to be "platform independent" in this context would mean to detect which OS you are running on (say, using preprocessor defines at compile time) and use different system calls based on that. However, this gets really messy, really fast.
It gets even worse when you're talking about 3D (or hardware accelerated 2D), because different graphics cards again behave differently. So, again, even if there were only two graphics cards (plus the two operating systems), you're already at four different cases for the same basic operation of, say, drawing a circle inside a window.
Can you do it?
Technically, yes. But graphics libraries exist precisely because most people wouldn't want to.
What i would personally recommend, if you don't want to rely to heavily on third party libraries, is to use OpenGL. Yes, it's a library, but it comes preinstalled on most systems.
If you actually want to create your own platform independent graphics library, i would suggest to get comfortable using the existing ones first, just to get a feel for what is involved in making something like that work.

How to directly access the display for drawing

Context
I've been programming mainly as a hobby for some time now, mostly in C# and Java. I made many application (Windows Forms or Java Forms) that required animated content. In Java I would use Graphics.drawX() and redraw in function of time. When the animations were happening frequently the resolution would diminish or the application would slow down. I never gave it thought until I played a video game on the same computer that had so much trouble rendering a simple Java app. How can my computer instantly render a complex moving environment but rush a displaying a home-made 2048 game? I figured it must be because either I am misusing the draw functions, either because those functions are not optized for real-time render.
Question :
How can I directly access the display without having to go through preprogrammed functions?
I realize this maybe hard in higher level languages so let's say in C on a Windows OS. (But I would appreciate any answer relating to any language and/or OS)
I know it's a really vague question but I can't seem to find the right words to Google it appropriatly. Thank you very much for your help!
You can't (or maybe I should say should never) try to access the graphics driver directly on Windows. You used to have write directly to video memory to do graphics prior to Windows as DOS did not support graphics or display management and the stability of those programs were always a bit dicey. On Windows, it owns the screen and you have to work through it to access it.
The very concept of a Windows-based OS is that the OS owns the display and gives application access to a virtual display so that the OS can hide it or move it around. In most cases this does not cause a speed problem; but, in certain cases like gaming you need more speed; so, DirectX allows you tor transfer some of those task to the graphics card to get you the speed you need.
For more info on DirectX, check out Microsoft's Graphics and Gaming Resources

SetPixel equivalent on mac?

I'm currently writing a software renderer and after i got it to kind of work on windows I began thinking about porting it to Mac.
My Question therefore is: What's the equivalent to the Win32 GDI SetPixel function?
All I need to be able to do is plot a pixel at (x,y).
I'm new to mac development and the closest thing I found resembling an answer was to use an OpenGL Texture to which one would draw to. But that kind of defeats the point of having software rendering if i have to use OpenGL...
Is it even possible to plot single pixels in osx?
Short answer
Just use LibSDL (preferably version 2.0).
Long answer
You have to get your pixel data from system memory to graphics memory anyway. One way to do that is with OpenGL. You can think of OpenGL as a fancy API which lets you push data from system memory to graphics memory. Since that's exactly what you want to do, it makes sense to use OpenGL.
But that kind of defeats the point of having software rendering if i have to use OpenGL...
The graphics card is going to do the work of compositing your pixels on the screen whether you like it or not so you don't get any particular portability advantages by avoiding OpenGL. Back in the 90s you could just get a pointer to the framebuffer and push pixels there, but those days are gone.
LibSDL is nice because it gives you an API which lets you push pixels to a buffer, and then LibSDL takes care of putting the buffer on screen.
SetPixel() is horribly slow anyway, so you should be using LibSDL on Windows too.

Is C good for any projects beyond the command-line and learning?

This is not meant to be inflammatory or anything like that, but I am in the midst of learning C, and (think) I have a good handle on most of the basics. I've done all of the various book exercises: primes generators, Fibonacci generators, string manipulation, yadda yadda, but none of this is cool.
What is the "bridge" between command line programs and something -cool-? I've heard of various games being written in C, but how?
Forgive my exasperation, but it feels like I've been learning lots but can still only do relatively little. Thanks for any insight on what to do with C.
Relevant information: OS X leopard, PHP and web development experience (which is so great because projects are immediately in a context where you recognize how they can be powerful)
C is the concrete and the steel of modern tech
There was a time when almost everything was written in C, or in something much worse.
These days, many of the advanced languages and systems are actually implemented in C or C++, and then those things implement more systems. It is standing on the shoulders of giants, as the expression goes. Almost every OS kernel, browser, and heavy-duty-web-server is written in C/C++.
So sure, you don't see the steel in the high rise, you see the beautiful interior furnishings and the sleek glass windows. You don't want a steel or concrete desk, and if you did, it would be too expensive to build for you.
Back to your GUI question: your first C graphics program should probably use the original X Window System directly. Don't spend too much time there, but then move on to one of the more advanced Widget toolkits such as GTK+ or (the C++) Qt. Be sure to investigate your OS X system, as it has one of the most advanced of them all.
I try love to write things in Ruby these days, but I happen to know there are over 100,000 200,000 lines of C code implementing that cool Ruby language system. :-)
Summary
Ok, this post got really big, so here's a quick summary before you read it: to program GUIs, there are a number of good C/C++ libraries (for example, QT). What most people do, on Windows systems at least, is to use a .NET language (like C#) when they want GUIs, and C/C++ when they want more control/speed. It's also very common to use both in combination, i.e. make a GUI in C# and speed-critical parts in C.
I still encourage you to read the longer answer, it contains a lot more information on your options.
Longer answer
I'll start with the big question, then answer (as best I can) your specific question about creating a GUI. I think you're kind of suffering from the fact that C is used to teach programming, and it's much easier to do so only using command line programs (after all, they're much simpler to write). This doesn't mean that C can't do all of the stuff you want, like GUIs specifically. It does. I don't think there's any type of software that hasn't been done in C, usually before it was done in other languages.
All right, some answers:
Is C Useful?
C, and its very close relative C++, are responsible for a huge portion of the world's code. I don't know if more code is written in C than any other language, but I'm guessing it's not far off.
Most of the really important programs you use are actually written in C/C++. Just for one example, Windows.
Where is C used today?
C/C++ are still used a lot. They're especially useful for developing low-level stuff (i.e. stuff like Operating Systems, which need a lot of speed, a lot of ability to control exactly what your code does, etc.).
But don't think it's all low level for C programmers. Even today, with many other languages available (which are arguably much better, and certainly much easier to program), C is still used to create practically everything. GUI applications, which you specifically asked about, are very often made with C, even though nowadays, lots of people are switching to other languages. Note I say switching: C used to be the standard language for writing, well, everything, really.
How do I develop GUIs with C
Alright, you specifically wanted to know how to create a GUI with C (I'm hoping C++ is ok too).
First of all, it depends on a number of factors:
What Operating System are you writing for? (Windows, Mac, and Linux are the most common).
Do you want the GUI to work on other systems as well?
The most common case is writing software to work on Windows. In that case, the "natural" solution is to write things that work with the Win32 API. That's basically the library that "comes" with Windows, letting you do any GUI work you want to do.
The big problem with this is, it's kinda hard. As in, a lot hard. This is the reason most people don't do that kind of work anymore.
So what are your other options?
The most natural is going with what's called a .NET language. Those are a bunch of languages, together with libraries, that Microsoft created. They're probably the easiest way to get a GUI on Windows. The problem is, you can't really use them from C (since it's not a .NET language).
Assuming you want to stay in C/C++ land, you can use some kind of library which makes working with the Windows API easier (since it hides all the ugly details):
One of the most common is what's called MFC (Microsoft Foundation Classes), which are a bunch of C++ classes which make it "easier" to create Windows stuff. Unfortunately, this library is very old, and is really not that easy to use.
The other way to go if you want to program in C++ is to use some kind of third-party library. This is a library that someone other than Microsoft created, which makes it easier to create a GUI.
Another option is to create only the GUI part of your software in a .NET language, and use C/C++ for the other parts (or use the .NET language to do almost everything, and use C/C++ only when you really need it, for example when you need things to go really fast). This is a very popular option.
The advantage of a third party library is that, if you pick the right one, you can use the same code to create a GUI for all the Operating Systems at the same time.
I think the most famous of these libraries is QT, and also WxWidgets, but there are a bunch of other ones. I would personally pick QT since it seems to get the most fame, but I haven't worked with either.
Every major operating system has all of its low-level libraries implemented in C. Mac OS X is a Unix-like system under the hood, which is a wonderful world if you're a C programmer.
Check out The Art of Unix Programming for some great ideas.
As for GUI stuff, you'll probably want to use X11. There is plenty of good documentation out there -- most Unix programming stuff and most deep system-level stuff just assumes you're working in C, since that's what everybody uses for it.
Well, that depends. If you want to build desktop applications, a multiplatform GUI library whose main language is C is GTK+:
http://www.gtk.org/
For games, check out SDL:
http://www.libsdl.org/
Which provides you with thinks like direct input from keyboard, 2D graphics, some audio and even threads and stuff like that. It can also open an OpenGL context if you want to get into the 3D world (however it's hard to do it in raw OpenGl). Did I mention that SDL is multiplatform?
However the real strength of C is in systems programming. For desktop applications/games maybe you are best suited with C++. Now that you have command of C, learning the basic C++ should be easy ;).
Cool stuff do with C?
Operating Systems, device drivers, and python modules for starters.
Games typically will use C++ if they're C-Based, in my experience / what I've seen.
There are many libraries for C under Unix, such as X lib, which accesses X11.
If you wanted to get into robotics you may find C to be very useful, as you will have to write low-level code with very small memory footprints, so even C++ may not be the best choice.
C and C++ are very good at writing small, fast code, but OOP is not always the best choice, so at times you will find that C is a better choice, for example if you are writing a compiler or OS.
Sure there are some impressive programs made in C !
GNOME for example, arguably the most used desktop environment used in modern unix systems is written in C (the major parts at least) and is mostly based on GTK+ gui toolkit, itself done in C.
For game, OpenGL is a C api and is the standard for 3D graphic programming in multi-platform development (not uniquely microsoft platform), and Quake 3, which the engine, Id Tech 3, is available in GPL, is also writen in C. There also is many 2D games written using SDL library.
SDL is a good library for graphics and sound, and I've seen some cool stuff done with it. If you do it in C, it'll take longer to make, but from a performance point of view, it'll be much better.
If your idea of cool is GUI apps and you want to write native GUI apps on the Mac, you'll want to look at
Carbon. This is the official C API into the Mac GUI and OS. They keep threatening to kill it, but it survives.
Personally I think GUI apps are a very narrow definition of cool. What I think is cool is implementing parallelized math algorithms using opencl.
GTK-server is REALLY easy to get started with, in C or any other language. Just click that link.
For a "cool" application that goes beyond simple GUI's, check out the OpenCV computer vision library. It provides fast real-time image processing and face recognition.
Now you can access a webcam and start writing real-time computer vision games. For applications like these that are processor intensive, C is the ideal choice.
Last I checked more Open Source projects are started in C than in any other language.
The fact that C is used by so many large and successful projects doesn't particularly make it "good". The reason C is so commonly used is because of a few factors, it's been around a long time, it's fast, it lets you access both low level and high level interfaces as needed, and it's better than the other old languages (FORTRAN etc). The "cool" thing about C is that you can make it do absolutely anything: inject itself into the kernel and add some new features or bug fixes that you couldn't convince Microsoft to do, etc.
Yes, C can be and is easily used for things beyond the command line, but it's extremely dangerous due to pointers... Not to mention development in other more modern languages is faster (and safer) by magnitudes. I never use C unless it's the last resort, ie: need to implement something low level or needs that extra performance.
By the way, when I say C, I really mean C++. I'd never choose C over C++ unless I was forced to.

How to create real-life robots?

Even before I learnt programming I've been fascinated with how robots could work. Now I know how the underlying programming instructions would be written, but what I don't understand is how those intructions are followed by the robot.
For example, if I wrote this code:
object=Robot.ScanSurroundings(300,400);
if (Objects.isEatable(object))
{
Robot.moveLeftArm(300,400);
Robot.pickObject(object);
}
How would this program be followed by the CPU in a way that would make the robot do the physical action of looking to the left, moving his arm, and such? Is it done primarily in binary language/ASM?
Lastly, where would i go if I wanted to learn how to create a robot?
In the end, something has to break down the high level commands into very low level commands. Something has to translate "Pick up the cup" to how to move the arm (what angles the joints should be at) to the hardware commands which actually turn the motors.
There are frameworks which try to provide some amount of this translation, including (but not limited to):
Player/Stage
Microsoft Robotics Studio
Carmen
CLARAty
Lego Mindstorms
However, since robotics research is interested in every layer of the system, there aren't many systems which provide the entire translation stack. If you're looking into getting into robotics, there are several systems which attempt to make this easier (again, a random sample):
Lego Mindstorms
TeRK
VEX Robotics
Failing that, sites such as Make even provide guides to building robot projects to start from. The challenge is find a project which you are excited about, and go to town!
You should check out Microsoft Robotics Studio (MRS). They have many videos/screencasts, and written tutorials. Additionally, Channel9 has many videos, interviews, etc, on the robitics subject. Including demonstrations, and interviews with developers of MRS.
In most modern robots you would have an Inverse Kinematic model of the mechanism, in this case the arm, that converts the spatial coordinates into positions for the joints of the arm. These joints are usually moved by servo motors. To smoothly move the arm, you need a series of intermediate joint positions defining the path you want the arm to follow. You also have to worry about the velocities of the joints, which together control the speed of the "hand" at the end of the arm.
While the arm is moving your servo system will be getting feedback about its actual position. Simple servo systems may use a basic PID feedback loop to adjust the motors. More complex systems will include feed-forward parameters which compensate for inertia, gravity, friction, and so on. These can become very sophisticated.
The real fun starts when you have to allow for obstacles in the space around the robot. You have to sense the obstacle and figure out how to avoid it and still reach the destination.
I just have to add something about Arduino projects to this because I dont see it mentioned above.
There is a very low bar for entry into the Arduino based robotics projects. The "sketch" programs that you write for the hardware are very easy to pick up and similar to C syntax. If you dont know your transistors from resistors these boards still allow you to do alot with plug-in hardware and additional "shields" that extend the base computer board.
Its very fun, very flexible and something to get your code interacting with the real world. Plus its "Open Hardware" very along the lines of open source software.
Robots will work by interacting with hardware. The bridge from your code is often done through different type of I/O ports. It could simply be a RS232 cable for example (you know those old COM1 ports). Hardware parts will be composed by motors (such as servo motors) and sensors (such as ultrasound to feel obstacles, lasers to get distance or switches).
You don't need to use assembler to do that, there are lots of languages (if not most) that can do it but it requires knowledge on how to interact with hardware. Like writing a driver. It requires at least basic electronics also if you want to build the robot yourself.
If you're interested, I suggest you have a look at this book which is a good primer.
Also, you could try out programming a Basic stamp, it's pretty easy following the tutorials and it will give you a good start on how to build robots. It's not too expensive and you'll be interacting with hardware in no time.
Good luck and have fun!
If you get good enough at programming, you may discover that you don't even actually need a robot to test much of the hardest code you'll need to write... (IE, making a robot see and recognize a scene always fascinated me... But at some point, I realized that the physical robot required for this problem is the easy part... The software is the hard part!)...
Is probably easier to get a more high-level language to describe the robot's behaviors and intelligence and let the low level language to the actions (move arm, walk, stop). There is a lot of research in what is called BDI architecture for intelligent agents, google for it.
You can find more about at this site, it's a DSL for describing agent behavior made in Java. It's called Jason interpreter and the language is AgentSpeak(L).
Find a local FIRST robotics team and volunteer to be a mentor. FIRST is a robotics competition for middle and high school kids. The goal is that the kids do all of the work to build, program, test, and run the robot, but you still will have lots of opportunities to dig in and really learn the software. They are using LabView by National Instruments, and, as of Feb 8, have just begun regional competition for this year. LabView is a graphical programming environment that interfaces with NI hardware to let you program motors, actuators, and sensors. The NI stuff is pretty slick and is pretty easy to use, plus it's provided free to each team, so you don't have to buy the hardware and software yourself (at least to get started.) Plus, you get the added bonus of helping a new generation of engineers get their start.
You would have to have a driver that interfaced with the hardware (most likely a STAMP or FPGA with motors etc...). You would then call the function me.moveLeftArm(x,y); and the driver would know that moveLeftArm() means to move an actuator for X seconds/milliseconds/degrees.
I'm sure that you could find a kit that does robot programming.
If you want a Java alternative, I can recommend the book Linux Robotics. It has a lot of good information about where to get kits, parts, and sensors, as well as complete source code listings in Java.
I share the same itch .. I'm about to buy my first Beagle Board and some sensors / servos that can use the I2C bus. I'm going to be using an event driven design and a crude implementation of fibers (fibrils, if you will) which are userspace threads.
Basically my design calls for one process, which launches one thread per group of servos. Each group manager thread will launch x # of fibrils, 2 per servo (likely). One fibril is used to control the servo, the other fibril handles events from that servo (i.e., an object is just too heavy to pick up, an object was dropped, etc).
The main process has the task of listening for events from everything else and making sure the 'right hand knows what the left hand is doing' while moving forward and negotiating obstacles.
Its going to take me the better part of two years to get something working to the point that I'm proud of it .. but I anticipate many enjoyable evenings getting it to that point.
I will very likely be using a Microkernel, not Linux.
I'm doing this as much to sharpen myself with event driven methods as well as my desire to make my own R2 :)
Start with Phidets if you are familiar with .Net. You can checkout TrossenRobotics.com for parts.
The Phidgets interface kit is a good place to start. From there you can get a servo controller and start building things that move.
The Trossen forums are also a good place to review other people's projects. They have a new Data Center with code/project samples too. I don't work for them...just a happy customer.
lots of good answers here. your piece of fantasy code is not far from how you'd do in a higher level language such as C# over MS Robotics Studio. Just keep in mind that even simple things (like "move arm left") are very loaded with "information bias".
down to the metal, a robotic arm is a set of links and [possibly] motorized joints. Therefore "move arm left" (or any point in coordinate) is already a very complex task to compute (look for D&H Table, forward and inverse kinematics for manipulators).
There's also the concept that move arm left assumes there's nothing in that space and a collision won't occur. If the environment is unconstrained, then you need to implement a collision detection system, often based on some sort of sensor (camera) and machine vision algorithms.
In summary, the language and the hardware interfacing are often trivial compared to modeling the system to achieve the desired behavior.
Regarding the last question "how to create a robot", I find starting from looking for a related project in online communities like [Adafruit][1], [Hackster.io][2], or even [glitch][3], or looking for blog posts of someone who have built a robot from scratch, e.g., https://burningservos.com, or a product that provides documentations & tutorials for both hardware and software e.g., http://emanual.robotis.com/docs/en/platform/openmanipulator_x/overview/.

Resources