Slashdot Mirror


Writing Code for Surface Plots?

MySchizoBuddy asks: "In what ways can you code plots of surface charts using a z(x,y) function or a cloud of points? I'm looking for a tutorial that explains this that doesn't use DirectX or OpenGL libraries (the language I'm using cannot use either framework anyway). How is the 3D mess generated and how can the 2D contour plots be generated as well? I'm assuming once I know that I can also use it to make torus plots as well. Remember, I'm asking for the explanation of the underlying math and an example code that does that. The GNUPlot gallery has some examples that I find helpful, but are there similar examples out there? (Remember, I am writing the plotting code as well)? Can anyone help or point me in the right direction?"

81 comments

  1. first plot by McGiraf · · Score: 2, Funny

    first plot

    hum ...

  2. How about ... by Anonymous Coward · · Score: 0

    Just read your TI-82's manual. Jeebus, man, get a clue.

  3. Graph3 by The+MAZZTer · · Score: 1, Informative

    http://www.detachedsolutions.com/graph3/

    This is software that does what you need, written for the TI-83 (should work fine on an 84 too). Since it's open source, you can peek at the source code to get an idea of how its 3d rendering works.

    Unfortunately, most TI calculator apps are coded in assembly...

  4. Another view by Knights+who+say+'INT · · Score: 3, Interesting

    You could plot graphics that represent levels as colours. I think I invented a kind of R^2->R function plot that represents a Z value as the degree of grey (0 being black, 255 being white) corresponding to Z mod 255. The result is that the more frequent "cuts" (sudden changes from white to black) are, the highest is the derivative.

    Looky here, here and here.

    1. Re:Another view by Anonymous Coward · · Score: 0
      I think I invented a kind of R^2->R function plot that represents a Z value as the degree of grey (0 being black, 255 being white) corresponding to Z mod 255.


      How original! Congratulations on your invention.

    2. Re:Another view by Anonymous Coward · · Score: 0

      How exactly do you expect to get a value of 255 from mod 255?

    3. Re:Another view by Knights+who+say+'INT · · Score: 1

      Yeah, it should have been mod 256.

      I actually didn't even use the mod function in my code. I produced the images in PPM format, and color 257 = color 1 in that format. It was an accidental "invention". (I wonder if it's been done properly before me).

    4. Re:Another view by Anonymous Coward · · Score: 1, Insightful

      Totally cock-sure of the fallacy that no one has ever thought up of your superb ideas before you, eh? I used to be like that. Especially with anything as 'brilliant' as using group theory in place of floating point values. Whoopie.

      Okay, so I don't mean to be that harsh - we still need people like you with that sort of talent ... but only after you get a fresh perspective on exactly what constitutes originality. It appears you're still learning, so we shan't be too hard on your optimism. We'll be waiting when someone asks Slashdot about Bayesian networks and associative memory.

      "Brilliant!" cried I.
      "Elementary," said Holmes.
      Ah, Sir AC Doyle.

      My point - this user who asked the question wanted to re-invent the wheel, but at least he knows he's re-inventing it.

      Give the world of programming some credit, young Tiger.

      Yours truly,
      Mr Trolley of Trolls Inc.

    5. Re:Another view by Schraegstrichpunkt · · Score: 1
      Give the world of programming some credit, young Tiger.

      Pff. According to the U.S. courts, the VFAT long filename shortening algorithm is non-obvious to the world of programming. Programmers must all be idiots.

    6. Re:Another view by Anonymous Coward · · Score: 0

      Pfft, you're spouting bullshit that I, as a programmer who has no use for the VFAT-shortening algorithm (5.3/5~#) really don't care about. You must be a statistically larger idiot for using a court ruling to determine what other people think, not to mention you're both claiming something; you need to be specific on exactly what you think the world of programming is. All I'm saying is that yes, we know there are a whole lot of fuckers dumber than you. What the fuck do you want, a cookie? There are a whole lot more motherfuckers a hell of a lot smarter than you, too. Why don't you go hardcode a Bayesian Network into a robotic arm with a glove and wire sound inputs and outputs into it so you can train it to jerk you off while you type, because that way, at least you'd be getting off privately rather than this public mess left all over the board... err, hey, now that's a good idea, minus the hardcoding! Pardon me as I scamper off to check which interrupts the drivers will use. I've got better shit to do than rant about your hubris, you arrogant fucks, although I must admit that trolling is rather addicting ...

    7. Re:Another view by Schraegstrichpunkt · · Score: 1
      What the fuck do you want, a cookie?

      Yes, actually. Peanut butter, if possible.

    8. Re:Another view by Knights+who+say+'INT · · Score: 1

      That seems to be a troll, but just for the note: I said I think I invented something. If I was cock-sure of superb originality and power, I'd be off trying to publish in academic journal, not discounting a nifty visualization trick over in a /. comment.

    9. Re:Another view by Anonymous Coward · · Score: 0

      You are a total douche.

    10. Re:Another view by Anonymous Coward · · Score: 0

      Best peanut butter recipe I could find, Tiger. Now go play while we big kids throw rocks at Microsoft's Redmond office-windows in disgust at the new DRM-infested OS.

      And to Knights who say 'INT: regarding your reply below, despite my somewhat troll-like replies, I'm glad to see that you understand. I guess at some point I just got so sick of seeing people have the same "aha" moments that I did, that I projected my own self-embarrassment onto you and others with that spark, and for this I humbly apologize.

      (You guys have to try trolling! It's so much fun!)


      Sincerely,
      Mr Trolley
      Trolls, Inc.

  5. Re:I just hacked something up myself by Anonymous Coward · · Score: 0

    Stupidest post I've seen in a long time. Doesn't answer the question, uses a dumb solution, and require "hundreds of line of C" (!) to then pipe the result in an external file. Come on.

  6. reminds me of mathematica by thedogcow · · Score: 1

    I generated solutions to partial differential equations in Mathematica that looked similiar to those plots. You can animate them (Bessel Functions, Heat Equation, and harmonic motion). I personally would use Mathematica. If you're a student you can get that application for cheap.

    --
    Yes! I listen to NYC Speedcore and do math at 3AM. I suggest you try it too.
  7. That depends by Anonymous Coward · · Score: 0

    Since you'll probably want to write it as an orthogonic plot, you never bothered to mention how much experience you have with matrices. With that in mind, it's actually much easier than you think, unless you'll want to look at the graph from multiple angles rather than just one, but even that's fairly simple. What bothers me is why in the world you'd need to re-invent the wheel, when it'd be so much faster to use a pre-existing library (such as Dx,SDL,OGL,GnuPlots, etc. But that's on you. You may also find it easier to utilize a matrix-solving program if you'd rather not bother coding up the algebraic formulas you'll have to use. My question still remains - what's the hangup? Where's your difficulty? At best, it's just a matter of slicing up multiple chunks of data and offsetting 2D graphs in two directions, and at worst, (unless you want it fancy-shmancy and pretty-like) it's just a matter of keeping track of 3d points and the closest point to the viewport - which is a matter of pretending the drawing surface (a 2d square) is a camera, and placing it somewhere in your 3D space where you'd set the camera to view the graph; at which point you'd create a second square parallel with the first, between the camera and the 3d graph, but whose size is variable(you still haven't really "drawn" anything yet, but really have only data points) and use a tad bit of algebra to determine lines of some particular size with points in both squares that would be the same point relative to the square sizes, (imagine one of two images, a sideways pyramid, or a cube/block)
    then run through your list of data points and determine which line it falls on, and sort that list by which line they fall upon, and grab each point that's closest to the "camera square" in your 3D world (this is where matrix transformation functions are so handy, they literally describe how the world goes 'round ... :-p ) and use your camera square (translating the point locations to the proper square-size as necessary) as the drawing surface on the screen, being sure to keep the data sets separated by some method, such as color and whatnot. Jeebus, Mister.

    1. Re:That depends by Anonymous Coward · · Score: 0

      Re: "then run through your list of data points and determine which line it falls on, and sort that list by which line they fall upon,"

      My bad; I meant it as:
      Then iterate through your list of points, and determine which line each point falls on, (because you will most likely have fewer graph points than lines), and sort each resultant list of points on each line by their proximity to the camera, drawing only the closest point. But still; this isn't a good question for Ask Slashdot. It really isn't. A better question would have been "What 3D plotting/graphing utilities or matrix utilities are available to me that aren't dependent upon OS's and hardware-acceleration besides the Java SDK? (which is a child's action-figure language that comes free with real adult non-toy heavy-duty artillery (the SDK), in my opinion - of all things, this should've made programming accessible to more people, but it didn't. Why? Is it because it wasn't as child-friendly as Visual Basic? Who knows? Not me, I've never lost control, when face - to -face ... with *BLAM!*)

  8. You sure you want to do the math? by perlionex · · Score: 3, Informative

    I looked at 3D rendering quite a while back (about 15 years ago). Believe me -- you probably don't really want to built this up from scratch.

    It sounds like you just need some sample code that doesn't rely on OpenGL or DirectX. To that end, the following (open-source) projects may be useful:

    1. Re:You sure you want to do the math? by Solra+Bizna · · Score: 1

      Simple 3D rendering like this is easy. It's just stringing a bunch of math end to end.

      Now, doing it fast...

      -:sigma.SB

      --
      WARN
      THERE IS ANOTHER SYSTEM
    2. Re:You sure you want to do the math? by squidfrog · · Score: 1

      A while back, I made a surface-plot generator for POV-Ray. A bit of overkill, perhaps, but effective.

  9. Nested for loops are your friend by Nyall · · Score: 1

    Meshes ? OMG data structures to manage lines. My brain just froze.
    So what is you're API that lets you turn pixels on and off? Its not that hard to go from a cloud of points in openGL to a cloud of points in another api.

    Contour lines can be harder. you need to connect points on the same elevation without drawing a line through higher/lower elevation. I'd say don't bother connecting lines. just draw a lot of points (of certain colors for certain heights) with a fine enough granularity that they bleed into each other.

    --
    http://en.wikipedia.org/wiki/Jury_nullification
    1. Re:Nested for loops are your friend by mwvdlee · · Score: 1

      He isn't asking for meshes, he's asking for a 3D mess.
      Though I don't think that would be much harder.

      --
      Slashdot social media options: AIM, ICQ, Yahoo, Jabber and Mobile Text. Why no MySpace?
    2. Re:Nested for loops are your friend by LiquidCoooled · · Score: 1

      This is slashdot, there is no built in spell checking.

      Reading the quote as "3d mesh" sounds plausable, I've never heard of a 3d mess (although some games come close).

      --
      liqbase :: faster than paper
  10. MATLAB by Bob_Geldof · · Score: 4, Interesting

    just a thought, but why not use MATLAB. You can sometimes use it to make stand-alone programs and maybe even DLLs. then add it to your code. I help develop code for a Cray X1 and all visualization (for my project) is done locally using MATLAB. It's pretty beefy, but it'll make a contour plot.

    --
    887321 = 337*2633
    1. Re:MATLAB by Anonymous Coward · · Score: 0

      Here is a quick tutorial on 3D plotting with Matlab:

      Step 1: Copy and paste the following code into the Matlab command window.
      Step 2: Change the equation and parameters to suit your needs.
      Step 3: Profit!

      [x,y] = meshgrid(-25:0.1:25, -25:0.1:25);
      z = cos(sqrt(x.^2 + y.^2)) + cos(sqrt(x.^2 + y.^2));
      surf(x,y,z);
      view([45 85]);
      shading interp;

      Here is what each line of code does:
      1) Sets up the grid: min = -25, max = 25, step size = 0.1
      2) Calculates z. This example is a wave equation.
      3) Creates surface plot.
      4) Sets the Azimuth and Elevation.
      5) Gets rid of the mesh outlines.

    2. Re:MATLAB by LihTox · · Score: 1

      Of course, MATLAB costs several hundred dollars, if you don't happen to own it already....

    3. Re:MATLAB by Anonymous Coward · · Score: 0

      Another option is IDL. Although the built-in function to do what you want (contour) is sluggish at best on large data sets, I have worked with code that does something very similar in a fraction of the time. Unfortuanately I can't provide code, as I wasn't the one to write it. What I can say is that the program creates a spectrogram of a .wav file, and the bulk of the processing is in computing the FFTs and not the plotting.

  11. 2D contouring by jmac880n · · Score: 4, Informative

    Good 2D contour plotting is not easy (I know!!!).

    If you are not afraid of coding, then the best reference that I know of is:

    • Computing Contours by Successive Solution of Quintic Polynomial Equations
      by Albrecht Preusser, ACM TOMS V10#4

    The code (in FORTRAN, unfortunately) is also in TOMS as:

    • Algorithm 626 TRICP: A Contour Plot Program Triangular Meshes

    You can get ACM TOMS (Transaction on Mathematical Software) from any reasonable college library.

    This might be a bit of overkill, as it is designed for irregular data sets (versus regular datasets - grids). However, the code can be separated into a separate Delaunay Triangulation step. If you have a grid (or in your case, a function f(x,y)), it is easy to generate fixed triangles.

    If anybody knows of a better algorithm, I'm all ears!!!

    1. Re:2D contouring by Anonymous Coward · · Score: 0
      Good 2D contour plotting is not easy (I know!!!).

      Pardon me, I'd like to make a correction. Good 2D contour plotting from scattered point data is not easy. For contour plotting from a regular grid, the marching squares algorithm is simple, easy to implement, and works pretty well. Run it several times with different reference values to get all the contours you want.

      The only problem I can think of is that it generates polygonal contours, but that shouldn't be a problem if you use a fine enough grid resolution. Now if the data itself has low spatial resolution, you could still create a denser grid using, say, cubic interpolation.

    2. Re:2D contouring by Anonymous Coward · · Score: 0

      If you take a look at the GNUplot example linked in the blurb, one could conclude that the original question is not about such elaborate contours, but rather simple plots evaluating a function at a fixed spacing x,y raster and drawing the surface of the interconnecting quadrilaterals. For clouds of points, the gnuplot examples just show clouds of crosses in 3d space, not a surface that connects them. The examples that show 3d objects in gnuplot all come with a predefined list defining which surface spans which point.

      Maybe the original question can even be answered by a link about 3d projection, or if he wants to get away easier isometric projection.

    3. Re:2D contouring by jmac880n · · Score: 2, Informative

      Pardon me, I'd like to make a correction. Good 2D contour plotting from scattered point data is not easy. For contour plotting from a regular grid, the marching squares algorithm is simple, easy to implement, and works pretty well. Run it several times with different reference values to get all the contours you want.

      Uhhh... I said good 2D contouring is hard. Marching squares is by NO stretch of the imagination good, even with regular data. Easy, yes. Good, no.

      It has discontinuities. Good contouring will have smoothness at least to the 2nd derivative. TRICP uses fifth order equations to fit the derivatives on all sides of the triangulation so that the resulting curves are smooth at all points. As I pointed out, triangulation is trivial with regular gridded data.

      And subsampling using cubic interpolation will not help the discontinuities that appear with marching squares. Unless you use an algorithm that fits the derivatives at the region boundaries, you will get noticable jagged lines.

  12. Why not OpenGL? by SanityInAnarchy · · Score: 2, Interesting

    I know this doesn't help you, but I'm still curious -- under what circumstances can you not use OpenGL for this? Under what circumstances would it be easier to implement it yourself than to find/create a decent GL binding? Or maybe you could just read the software implementation from Mesa?

    --
    Don't thank God, thank a doctor!
    1. Re:Why not OpenGL? by MySchizoBuddy · · Score: 1

      Well for languages like actionscript. when u want to create a online plotter in flash

      --
      Yes go ahead click the link. Its kosher
    2. Re:Why not OpenGL? by SanityInAnarchy · · Score: 1

      ... And you could still read the Mesa implementation.

      --
      Don't thank God, thank a doctor!
  13. R-project by Anonymous Coward · · Score: 3, Insightful

    Check out the R-project at www.r-project.org. It is very good for that sort of thing.

    1. Re:R-project by infolib · · Score: 2, Informative

      I'm out of mod points, but this is insightful. The R programming language is GPL'ed and works on lin/win/osx (packages for major distros). It is an interpreted language (except for a few internal commands), and so the source code for the several different 3D plotters is included with the program. Some you might have to install yourself, but this can be done by the install.packages command.

      You might want to have a quick look at output from different 3D commands (persp, scatterplot3d and wireframe).

      The introductory documentation might be a bit confusing - especially since it's often written for and by statisticians, but there's a mailinglist with a huge googleable archive and I've often found that "google:r-project search term" will get me what I need.

      --
      Any sufficiently advanced libertarian utopia is indistinguishable from government.
    2. Re:R-project by Anonymous Coward · · Score: 0

      Yes, R is definitely what you should be looking at, unless you already know MATLAB and have a copy of it available (if you know MATLAB but *don't* have a copy, then check out OCTAVE instead).

      I used to be a gnuplot hacker until I discovered R. R is great for experimental data processing and visualization. And since its free, anywhere you end up you can just grab a tar-ball and in a few minutes you can be up and running.

      It also supports easy importing/exporting from a database, which in some cases can be a really big deal.

      One problem I've had wrt finding documentation is that not all posts have the term "R-Project", in them. Finding pages dealing with "R" is sometimes a bit of a pain. This is a prime example of where adaptive, personalized search will make my life better.

  14. Been there, done that. by Animats · · Score: 1

    I wrote a program to do that in 1968, for a UNIVAC 1108 with a pen plotter. Even did hidden surface elimination. We even ran it on a display a few times during really slow periods. But I don't have the ALGOL code any more.

    The algorithm was in JACM around 1967, but you wouldn't do it that way today.

  15. Basic Rundown by The+boojum · · Score: 4, Informative

    My advice would be to pick up a decent intro book on graphics. The Foley and Van Dam is a classic, but nearly any good book on the topic tends to have a review of the basic math involved in 3d: linear algebra with 3- or 4-value vectors and 3x3 or 4x4 matrices, the perspective divide, etc. Knowing the basics will help you have a lot better idea of what to do. But for anyone curious about the most basic 3d, here's a simple way to do it that should work decently for simple wireframe plots.

    1) Take each 3d point of interest and apply some set of rotations around the X, Y, and Z axis to get the view angle right. You'll probably want to just do one rotation around each axis. e.g.:

    x2 = x * cos( z_angle ) + y * sin( z_angle );
    y2 = x * -sin( z_angle ) + y * cos( z_angle );

    x3 = x2 * cos( y_angle ) + z * sin( y_angle );
    z2 = x2 * -sin( y_angle ) + z * cos( y_angle );

    y3 = y2 * cos( x_angle ) + z2 * sin( x_angle );
    z3 = y2 * -sin( x_angle ) + z2 * cos( x_angle );

    At this point, you'll have rotated your original coordinate (x,y,z) by some angle around some axis to get (x3,y3,z3)

    (To my fellow graphics geeks: yes, yes, I know full well that matrices and quaternions are better -- I'm trying keep this simple.)

    2) Maybe add some distance to the z value, to move ("translate") it away from the "camera" at the origin. You'll need to add enough to make sure that all of your z-values are positive and non-zero before step 3:

    z4 = z3 + z_translate

    3) Do what's called the "perspective divide" to find the two dimensional coordinate of this point. e.g.:

    px = x3 / z4 * scale + center_x;
    py = y3 / z4 * scale + center_y;

    4) Either plot a point at the (px,py) that you just got, or compute steps 1 and 2 twice for the end points of lines and then use your system's graphics primitives to draw lines between (px1,py1) and (px2,py2). If you're not using a language or a library that can do simple 2d graphics, then I'd suggest writing out a file with the lines in SVG format (and then rasterize to bitmap with a program like Batik, Inkscape, Illustrator, etc.) e.g.:

    <?xml version="1.0" standalone="no"?>
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
    <svg width="4cm" height="4cm" viewBox="0 0 400 400" xmlns="http://www.w3.org/2000/svg" version="1.1">
        <path d="M px1 py1 L px2 py2" fill="none" stroke="black" stroke-width="1" /> <!-- First line to draw -->
        <path d="M px1 py1 L px2 py2" fill="none" stroke="black" stroke-width="1" /> <!-- Second line to draw -->
        <path d="M px1 py1 L px2 py2" fill="none" stroke="black" stroke-width="1" /> <!-- Third line to draw, etc... -->
    </svg>

    5) If you want more than wireframe, things will be a lot more complicated. At the very least, you'll need to be able to fill polygons and sort back to front by the z-value after the rotation so that everything gets drawn in the correct order. Z-buffers would be even better.

    Well, I hope all that helps. Again, if anyone's really interested, I'd suggest getting a real book on the topic. But I hope this's enough to get the curious started.

    1. Re:Basic Rundown by Profane+MuthaFucka · · Score: 4, Interesting

      Regarding point #2 and #3, if he's just plotting points to make a graph, fancy perspective may not be needed. Just throw away the Z coordinate after rotation, and plot the X and Y in 2D.

      Also, if you're rotating the graph in real-time, don't rotate the points a degree, plot, and rotate another degree and plot, and so on.

      Save the original set of points. Rotate them one degree and plot. Throw those results away, start with the original set and rotate them two degrees and plot. Repeat, rotating only the original set each time. You'll save a lot of trouble from accumulating floating point errors.

      --
      Fascism trolls keeping me up every night. When I starts a preachin', he HITS ME WITH HIS REICH!
    2. Re:Basic Rundown by Mac+Degger · · Score: 1

      I take it that 3rd point is the equivalent of projecting 'the 3d' to the 2d plane of the monitor?

      --
      -- Waht? Tehr's a preveiw buottn?
    3. Re:Basic Rundown by Snyper1000 · · Score: 0

      What are you writing in that there are no 3-D api's out there? Its really silly to reinvent the wheel. A surface plot is not trivial to implement from scratch (Depending on what you want it to be able to do...) You will need to manage 3 matrices. A projection, a View, and a World Matrix. For a surface plot, an Orthographic projection is what you want. You can find millions of examples of orthographic projection matrices online. The view matrix sets the position of the "Camera" and the direction it looks in. Again millions of examples are available online. The world matrix is generally an affine transformation matrix, made up of Scaling, Rotation, and Translation functions (each of which can be represented by individual matrices, and again, millions of examples are available online for each) So now you have your matrices, how do you use them? Well to get the point on the screen that corresponds to your 3-D point, you multiply the point (in terms of a vector) by the matrix that you obtain by multiplying the World, View, and Projection matrices togather, then homogenizing it (Dividing x, y, z, and w by w) That will give you the XY point on the screen. Ok, so now what, All you have is a bunch of points, we want filled polygons, or at least lines right?! For single color lines, there are several formulas available. Unfortunatly the equation escapes me, but the fastest one managed to remove all floating point math from the equation. I believe it was a variation on the midpoint formula, but it has been nearly 2 years since I took my graphics algorithms class, and I don't have my notebook here. Want to color the line, like for some sort of shading? Now you have a linear interpolation to do btw the 2 points. Thats not so bad though, linear is fairly simple. But you said you wanted a surface plot, and some more complex plots. So we will probably need filled triangles. You can use gouraud shading, or Barycentric coordinates to figure out what color to use at each point inside the triangle. BTW, you also need to get which points are inside that triangle, using the edges as lines, and those as a system of linear equations, but again, this can be found online with the various keywords in this post.... Ok, so now you have a software renderer. Sweet....but its running a little slow...What can be done to speed this puppy up? Well, we have some things we can do. First off, overdraw is our enemy. Unfortunatly, on a surface plot, there probably will not be much, but it won't hurt to implement some of these techniques anyways. First off, a relativly simple thing we can do is backface culling. Again, you can look this up, but its basically the dot product of the surface, with your gaze vector. if its negative, is back is facing the camera, don't draw it. Next, Z buffering. You keep a list of the depths of points drawn on the screen, if its closer, allow it to be drawn, if its farther, skip it. Simple really. Again, tons can be found about this online. Draw Order. If you implement Z buffering, and order your polygons to be drawn front to back, most of your polygons will be skipped. This is just a sort, so it should be self explanitory. To top it all off, you can introduce frustum culling. For a surface plot, this won't do much until you zoom waaaaay in, but will speed it up when that happens. Again, you can look this up... Most of these are indivudual lessons, and therefore, you'll find them as individual tutorials. You can see a software renderer is not trivial. This has said nothing about lighting, or perspective, since your application didn't seem to need it. Have fun if you decide to implement this. We had to for our graphics algorithms class. It was fun, and wasn't too much work, but we didn't implement all of this. We skipped all the optimizations other than backface culling. However, without the instructional time, this could all get very frustrating, especially if you aren't a linear algebra geek and want to understand why these matrices do what they do. This is why most people, including myself, say try to find some other pre-written API unless you have a fair amount of time on your hands, and/or a really stubborn boss who wants closed source, free, maintained by his company code to do this...

  16. If you're willing to have a wire-frame look... by Jamey · · Score: 2, Interesting

    dim ymax(screenwidth),ymin(screenwidth)
    For xtemp = xlower to xupper step xincr
    for ytemp = ylower to yupper step yincr
    compute z=f(xtemp,ytemp)
    (x,y)=transform(xtemp,ytemp,z)
    if yymax(x) then plot x,y : ymax(x) = y
    next ytemp, xtemp

    Adjust your viewpoint for your 3D to 2D matrix so it plots from front to back.

    Algorithm comes from an old book on doing 3D on an Apple ][ - it wasn't too hard to convert it to work on a TRS-80 Model I or a CoCo.

  17. Graph3-Old Skool. by Anonymous Coward · · Score: 0

    "Unfortunately, most TI calculator apps are coded in assembly..."

    Well according to slashdot. That's a good thing.

  18. Shouldn't be too tough... by ClassMyAss · · Score: 2, Informative

    I just looked at the GNUPlot page, and regardless of what anyone else says, I don't think it should be too difficult to code at all, at least the grid stuff like near the top of that page. The reason - it's all drawn without perspective, which means a little vector math tells you where to put each point. You might be a bit foolish to try to hand-code something substantial with perspective, but orthogonal projections are straightforward.

    Here's what you need to do. First, figure out what a unit in the X, Y, and Z axes corresponds to in screen coordinates. In the examples on the GNUPlot page, I'd estimate that a unit in the X direction is about 10 pixels to the right and 2 pixels down in screen coordinates, or (10, -2). Similarly, a unit in the Y direction is about (3, 3), and a unit in the Z direction is (0, 1). Now, to find the screen location of a point given in 3D, say (x,y,z), we start at the screen coordinate of the origin (wherever you want to put (0,0,0)). To this, we add x times the vector (10, -2), y times the vector (3, 3), and z times the vector (0, 1). For example, the point (10, 3, 6), with an origin at (100, 100), would show up at (100, 100) + (100, -20) + (9, 9) + (0, 6) = (209, 95).

    In other words, if we call the unit vectors in the X, Y and Z directions (given in screen coordinates) Xhat, Yhat, and Zhat, then the point (x,y,z) should be plotted at (origin + x*Xhat+y*Yhat+z*Zhat).

    I presume that from here you should be able to figure out how to draw the grid lines - just sample a bunch of points, and draw straight lines between neighbors. If you want to fill in the tiles (like the pictures near the bottom of the GNUPlot page), you'll need to be clever about the order you fill them in so that the ones in front are filled last. For this, you can sort the tiles by the appropriate combination of x and y coordinates (in "real" space, not screen space) - in our example, Xhat - 3.333Yhat points straight down, so you would sort by the combination x - 3.333y and draw in that order.

    This should at least get you on your way. I'm sure there are subtleties to consider, but hey - it's your project, not mine, so I'll leave it at that!

  19. Use R by Anonymous Coward · · Score: 0

    r-project.org

  20. Re:I just hacked something up myself by Anonymous Coward · · Score: 0

    Ok, granted he directly answer the question. So sue.

    But the advice he's giving is usually good advice. jmac880n gave an excellent answer, but it may be completely overkill for the askers needs. The base problem is that the math for doing plots of n-ything, can be truly daunting and thoroughly frustrate the beginner.

    However, given that the oversimplified answer has now been stated. I learned this skill while exploring fractals. They are mathematically simple and the authors of books on the subject often include all the source code for doing great looking plots for the various forms of them.

    The books I learned on are out of print, but this one looked good, and if I were pursuing this again, I'd browse through a couple similar titles at my local expensive book store and find an author who explains the source code in a way I connect with and pay his/her exhorbitant fee for the book.

  21. Read a book by jlarocco · · Score: 4, Informative

    Hate to disappoint you, but you're probably not going to find a tutorial and code that conveniently meets your requirements. For starters, eliminating OpenGL and D3D is going to remove a large number of tutorials, simply because it doesn't make sense for most people to roll their own rendering code.

    Your best bet would be to look through "Computer Graphics: Principles and Practice" by Foley, van Dam, Feiner and Hughes. It covers a large number of topics, in enough detail to get a good idea of how to get started and where to look for more information. Also "Real-Time Rendering" by Tomas Möller and Eric Haines. Despite the name, a large portion of the book is applicable to almost all computer graphics, not just real-time. Also, a book on linear algebra would probably be helpful.

    1. Re:Read a book by sglow · · Score: 2, Informative

      Here's the best book on the subject that I've come across.

      Mathematical Elements for Computer Graphics
      http://www.nar-associates.com/nar-publishing/mecg2 nd.htm

  22. Re:I just hacked something up myself by Anonymous Coward · · Score: 0

    Ooops. %s/he directly/he didn't directly/

  23. Drawing. by Vo0k · · Score: 1

    The actual code for such a plot, pixel cloud or such, is easy. 5-10 lines, nicely covered elsewhere in the comments already. Most difficulty lies in putting the first pixel on the screen, the right way.

      In times of Amiga, it would be like typing "ScreenOpen 320,256,32", then a line defining the palette in equally simple terms, then you can start the drawing stuff. On PCs there are dozens of graphics libraries and each one more difficult to use than another. Microsoft Visual someshit have this pretty easy to make in a crappy way, not too difficult in a bit harder way. SVGALib, currently considered obsolete, is quite friendly, SDL is a bit of a bitch to initialize, though both require you to roll your own gfx function libraries (another 10 lines of code like #define plot(x,y,c) SCREEN[(y)*WIDTH+(x)]=(c) ). Stay far away from QT, GTK and alikes. They are a true hell to draw arbitrary stuff. ImageMagick is very nice for generating gfx files, but sucks at displaying stuff. Matlab makes ploting a breese, but that's not really a product you can ship to a customer or deploy in production environment. You could actually take GNUplot sources and plug your piece into them, or use some sockets or scripts to launch GNUplot. Or take one of the ancient languages like Turbo C, Turbo Pascal, Fortran, and write that program in them, it's much easier.

    --
    Anagram("United States of America") == "Dine out, taste a Mac, fries"
    1. Re: Drawing. by Black+Parrot · · Score: 1

      > Stay far away from QT, GTK and alikes. They are a true hell to draw arbitrary stuff

      There's a GTK+ add-on called "GTK Extra", which directly supports 2D and 3D plots. It was created as the infrastructure for SciGraphica.

      --
      Sheesh, evil *and* a jerk. -- Jade
    2. Re: Drawing. by Vo0k · · Score: 1

      But getting any program to run using GTK requires several hours of digging through tutorials. Drawing a 2D/3D plot even if you have access just to a single "put pixel" function, is easy. Getting from opening the C editor to first pixel correctly drawn a'la hello world in your program is the trick - using GTK the first time you do it is pure hell, if changing current drawing color consists of three lines of obscure invocations.
      Drawingarea is horrible. No idea about this GTK Extra but I seriously doubt if it's much easier.

      Setting current drawing color in GTK:

              $fgcolor = Gtk::Gdk::Color->parse_color( 'white' );
              $fgcolor = $drawing_area->window->get_colormap()->color_alloc ( $fgcolor );
              $drawing_area->window->set_foreground( $fgcolor );

      Same in SVGAlib:

              $svga->setrgbcolor(255,255,255);

      --
      Anagram("United States of America") == "Dine out, taste a Mac, fries"
  24. Re:I just hacked something up myself by Anonymous Coward · · Score: 0

    Bloody buggery moderation box.

    I've just tried to mod this down (as it's garbage) only for it to pop up as "+1 insightful"

    Sorry chums.

  25. Java by philipmather · · Score: 1

    As part of some final year course thing I wrote a 3D rendering engine in Java based on implicit surface rendering, I did it in two stages. The first was simply an engine that converted the surface equation (f(x) + f(y) + f(z) = whatever) and then plotted it everything into a spacial array then dumpped everything into java's 3d library for scaling and rotation. Then I knocked out the Java 3D API and replaced it with my own so that everything worked all the way back to java 1 with no extra libraries. It was God aweful slow but it did everything, translation, rotation, scaling, specular highlighting, Phong and Gourond(sp?) shading as I remember.

    I could probably dig that out.

    --
    Regards, Phil
  26. algorithms for surface plots by Zork+the+Almighty · · Score: 1

    The idea behind plotting z = f(x,y) is to sample the function on a grid of points (x,y). You then interpolate linearly between adjacent points to get a polygon. For example, if my grid contains (x,y) = {(0,0), (0,1), (1,0), (1,1)} then my polygon in 3-space has corners (0,0,f(0,0)), (0,1,f(0,1)), etc. Project this polygon onto the screen using the standard 3d transformations.

    There are a couple of things to watch out for. First, all polygons should be convex. This is usually not a problem, but you can guarantee it by making sure that the 2D grid is composed of convex polygons - typically rectangles or triangles are used. It might be best to use a grid of rectangles first because that is easier to understand and debug, but when that is working move to a grid of triangles because everything will be much faster.

    Second, if the function changes rapidly between the grid points then your plot will probably be wrong. One solution which works in most cases is to use an adaptive grid. For each polygon in 3D, average all the corner points to obtain the center. Compute the actual function value using the x and y coordinates of the center, and compare with the center's z-value. If they differ significantly then you split the polygon up, using the center point (with the real function value) as a new vertex, and repeat. A rectangle will split into 4 smaller rectangles, a triangle into 3 smaller triangles, etc. To determine if the values differ significantly, project them onto the view screen and see if they map to the same pixel. There are ways to optimize all of this significantly.

    For plotting a cloud of points you are really screwed unless you know the function is of the form z = f(x,y). In that case, each (x,y) point has two closest neighbours which should give you a triangle. Sort the values by x and then by y, and as you construct each triangle remove the initial point (but not the neighbours) from the list. This will give you a triangular mesh. There are a few weird things which can happen, but you can mostly solve these problems by throwing away bad points.

    --

    In Soviet America the banks rob you!
    1. Re:algorithms for surface plots by Zork+the+Almighty · · Score: 1

      Sorry, I forgot to mention how to get contours from your plot. Basically, you intersect planes (z=1, z=2, etc) with each polygon and draw all the resulting lines. To determine if a polygon intersects z=t, subtract t from all the z-values and see if you have both positive and negative signs. If not, then the polygon is entirely on one side of z=t and you don't get a line from it. You can speed this up by sorting the polygons by minimal z-value (among all the vertices), then breaking ties by maximal z-value. To draw the part of a contour resulting from a polygon, it helps a lot of have triangles. Then two points will be on one side of z=t and one point will be on the other (or touching) z=t. Draw a picture of this on paper, and compute the approriate (x,y) values on the sides of the triangle that cross z=t. Then project the line segment connecting them to the view screen to get a piece of the contour.

      --

      In Soviet America the banks rob you!
  27. Re:I just hacked something up myself by Anonymous Coward · · Score: 0

    I agree - he didn't answer the question at all-
    #1 - the asker stated an inability to use gnuplots
    #2 - the asker never gave us the damn language he's using
    #3 - this 'answer' isn't even talking about a 'true' 3D graph much less anything a person could create a torus out of! RTFA!

    Oh, and to whomever it is that keeps offering alternate math engines as an end-all-be-all solution: no, he can't fucking use R or Mathematica, so for the sake of /. stop saying so!

  28. See what you can come up with by Geccie · · Score: 2, Insightful

    If its a very small part of a larger program, then look for some good examples and try to trudge through getting it to work. Otherwise, start writing code and examine the visual output of the screen. Look for algorithms and methods for producing the output you want. When you begin to understand them, you can integrate the concepts into your solution.

    Unfortunately, even if you have an API, you still have to understand what it does and how to interact with it. Many people believe that modular programming simply means using code alrealy written. This is a false premise as there is no substitute for some degree of understanding.

    In the end, you may wish to use a public library because it is highly accurate, optimized, well researched, or portable, but by that time you will have the knowledge to understand why you are selecting the particular library.

  29. Statistics and Data Analysis in Geology by Davis by Anonymous Coward · · Score: 1, Insightful

    I actually understand your question and the first place to look is a book Statistics and Data Analysis in Geology" by Davis. I used it in graduate school back in the 80's. It has understandable code for generating this output. It starts with line printer plots to get you running, first with trend fitting the data, and then actually machine contouring the data. I used their examples to program my C64 do draw contour maps on the 1526 plotter. I have tried surface plots with Excel off and on and it is frustrating because the mindset of the Excel developers is in a different universe. Google around for COGS Computer Oriented Geological Society, they may have some of the source as FORTRAN in their archives.

    If you have $$$$.00 to through at the problem use IDL from Research Systems Inc. They just got bought by someone so you will have to Google for their new digs. Expect to pay three kilo-bucks.

    Gridding is a cool problem. Basically, you start at (0,0) and calculate the distance of each point to (0,0) and then sort by that distance. Then you take the nearest every how many points and fit a trend and get the value at (0,0),. next you do (0,1) and calculate distances, sort, estimate the value, move to (0,2) ... (0,n) and then start with the next row, (1,0), (1,1),(1,2)...(1,N). Keep going down the rows.

    Next you have to decide bottom contour line value, top contour line value, and contour interval. Code as if you are a pen plotter. Look at the values of each corner of each grid cell, one at a time, and if a contour line goes through that side connect it to where it crosses the other side. This requires a lot of logic that is beyond this scope but reply to me and we can get deeper if you need.

    The Commodore 64 would grid all weekend, but did a decent job of making plots and maps. Core was cheep back then.

  30. A relatively simple way by Jeff+DeMaagd · · Score: 1

    One thng I can think of is for each Z value chosen, to make lines between adjacent points and test if any point on that line segment crosses that Z. It's pretty iterative but you'll get your point cloud. That's relatively straightforward, provided you have a fairly regular series of points.

    Another way was to use vector math, make a triangle between three terrain points and try to see if it intersects with your Z plane. Maybe ten years ago I made an algorithm that returns a line segment if there was such an intersection.

    If you wanted to do curve fitting and see where that curve passes your z plane, that could be done, but that's beyond my education.

  31. Generic Mapping Tools? by Anonymous Coward · · Score: 0

    Better known as GMT, might be helpful, or overkill.

    I'm not sure what your exact application is, and that affects the strategy greatly. A consistent grid of sample points (as input or generated from a function) can use a great many optimizations that a generalized and often uneven cloud of sample points can not (without ugly results). People have suggested a variety of algorithms and open-source tools, but if you go the next logical steps -- dealing with unevenly distributed sample points, making the contours pretty with highlighted intervals, filled shading with colour palette gradients, and labels, it just gets trickier. Fortunately, GMT has tools for most of that, and, as a bonus, it deals with it all in regular orthogonal X,Y,Z coordinates, and also with map projections (e.g., if you are plotting positions on the surface of a spheroid like the Earth or some other planet).

    The program for contours is pscontour or the similar grdcontour (which works on gridded data). There are various ways to generate a surface to be plotted, but the surface program is probably the best. It uses an algorithm -- continuous curvature surfaces -- that is especially effective for real-world data.

    GMT has a steep learning curve. It is all command-line, and the number of command-line options is dizzying, but that arrangement makes it particularly suitable for batch processing of large datasets, and the output is in Postscript, which can be adapted for all sorts of uses.

    If all you want is something simple and fast, this ain't it. Don't bother. The whole system is elaborate, huge (it contains many tools and the compile takes quite a while), and they are built for high quality output rather than cutting corners for performance sake. But if you are working towards something that will handle arbitrary, real-world data and give a decent-looking publication-quality plot, and for which the source code is available (all C), GMT might help you.

  32. Re:I just hacked something up myself by gumbi+west · · Score: 1

    R is OSS and has the commands he wants (image, countour, and wireframe) it sounds like exactly what he wants: code that makes these plots that he can look at.

  33. Marching cubes by Hillman · · Score: 2, Informative

    You can use the marching cubes algorithm. You can go from a cloud of points to a 3d object that you can transform like you want. I think they use that in MRI imaging. I used the 2d version (marching squares) to optimize a metablob routine a long time ago.

    see: http://www.exaflop.org/docs/marchcubes/index.html

  34. Generic Mapping Tool by budgenator · · Score: 2, Interesting

    Generic Mapping Tool, will do everything you want, and a lot you have not even thought of yet. GMT produces postscript and encapsuleated postscript, so if you have a postscript viewer your good to go, runs on unix/linux, is GPL'd so there source code to analyse. There are lots of examples with generating scripts such as time-series collected along a track or a 3D perspective, artificialy illuminated, greyscale image; just reading and understanding the accompanying ducumentation should be good for college credit in cartography.

    --
    Apocalypse Cancelled, Sorry, No Ticket Refunds
  35. It's a combination of two simple issues... by mengel · · Score: 1
    Basically, there are two issues:
    1. the 3d to 2d mapping from a viewpoint
    2. dealing with hidden points
    The 3d to 2d mapping is actually pretty easy, with a little Linear Algebra. If you don't know any, grab a Linear algebra textbook and read up on vectors, dot products, cross products, etc.

    You pick a viewpoint V = (x_v, y_v, z_v) and a direction vector D = (d_x, d_y, d_z) ( D is a unit vector, it's length should be 1). and an "up" vector U (which way is up, also a unit vector, perpendicular to D). Next we need a "right" vector, R, which is always D x U (vector cross product) So now our mapped coordinates for any location P are:
    z = (V - P)*D [where * is the dot product]
    x = ((V - P)*R) / z
    y = ((V - P)*U) / z

    So next we need to deal with hidden lines. There's an old trick for this, make a list of line endpoints, and compute z, above, for the center of each line. Sort the lines by increasing z. Now start at the first positive z value, and draw each line that would not cross an existing line.

    --
    - "History shows again and again how nature points out the folly of men" -- Blue Oyster Cult, 'Godzilla'
  36. Graphing Calculator by metamatic · · Score: 1
    --
    GCHQ Quantum Insert installed. If only our tongues were made of glass, how much more careful we would be when we speak
  37. Only a single Z output? by Anonymous Coward · · Score: 0

    I'm not a computer graphics expert, however, it seems rather limiting that not a single cliff has ledges that can stick out past the base of the cliff. Just food for thought.

  38. Re:I just hacked something up myself by Anonymous Coward · · Score: 0

    He deliberately implied that he already had a language he was working with, otherwise he would've simply used OpenGL or DirectX! READ THAT FUCKING ARTICLE! Yes, R rocks, but SHUT the FUCK UP! You're whoring it out like some wannabe know-it-all who thinks he's god's gift to the collegiate crowd or just an idiot who's out trying to make a wonderful OSS project look like a two-bit whore; what the fuck is your fucking head trip about?!

  39. Marching Cubes Algorithmhttp://www.exaflop.org/doc by jdigital · · Score: 1

    The standard way of doing this is to use the Marching Cubes algorithm. Google it --> http://www.exaflop.org/docs/marchcubes/

    --
    :wq ~ ~ ~ ~ ~
  40. Reinventing the wheel by Anonymous Coward · · Score: 0

    In what ways can you code plots of surface charts using a z(x,y) function or a cloud of points?

    These are really two separate questions. Plotting a surface for z=f(x,y) requires evaluating the function over the domain and constructing a tesselated mesh with vertices at each point. Once you have the mesh, you need to render it, which involves issues like hidden surface removal, shading, perspective and so on. Not a small undertaking to write all that from scratch.

    There are several algorithms for rendering clouds of points, depending on the nature of the data. First you have to cluster the points, then you have to mesh them, then render. It's not trivial by any stretch. Have a search through ACM SIGGRAPH for a few of the top algorithms.

    I'm looking for a tutorial that explains this that doesn't use DirectX or OpenGL libraries (the language I'm using cannot use either framework anyway).

    The vast majority of books that would cover this kind of thing will be either be: a) practically oriented and use OpenGL (or equivalent) for the rendering, or b) be highly theoretical and written in dense mathematics. It is unlikely that you will find a book that fits your description. The best you can probably hope for is to find an OpenGL book and abstract away the algorithms you need (after all, OpenGL is really just the lowest rendering stage).

    (Now of course, one must ask the question: why are you restricting yourself to using a language or environment that is clearly not appropriate to solving the problem at hand?)

    Others have suggested the classic Foley & Van Dam book, which is excellent and provides much useful material. But the one you really want is the Visualisation Toolkit book. It describes the algorithms and implementation behind VTK, and covers precisely the algorithms that your are asking about (clouds, surfaces, etc etc). VTK is implemented using OpenGL, but the book focuses on the algorithms, and includes comprehensive citations to the original papers where these algorithms are published. It is one of the best books available on Viz and 3D.

    (It can also be ordered from Amazon, but they're on backorder.)

    Now go read it, and tell me you still want to re-implement all that yourself from scratch.

    How is the 3D mess generated and how can the 2D contour plots be generated as well?

    Contour plots involve yet another class of algorithm, producing isocurve from data cells. Others have mentioned marching cubes, there's also marching squares and a few others that are used. Note that marching cubes is patented, so you need a license for commercial use! (Others who blindly suggested this might also want to take note.)

    I'm assuming once I know that I can also use it to make torus plots as well.

    I wouldn't. What the hell is a torus plot?

    Remember, I'm asking for the explanation of the underlying math and an example code that does that. The GNUPlot gallery has some examples that I find helpful, but are there similar examples out there? (Remember, I am writing the plotting code as well)? Can anyone help or point me in the right direction?"

    The VTK book will provide all the maths and algorithms you require, if you insist on going forward and reimplimenting all this yourself. But why? Methinks you are drastically underestimating the complexity of the task you are asking. Especially if you aren't already experienced in the areas of 3D rendering, vectors, linear algebra, (and it appears you are not) you are going to be climbing a massive

  41. what about PLOT10? by beowulf01 · · Score: 1

    Pardon me if I missed seeing a reference to the PLOT10 library in this discussion. Used to be THE lib for TEKTRONIX terminals (line perinter then color CRT) for graphics anything. Wrote some stuff for plots in C and fortran for data surfaces way back (Z80 CP/M, and later IBM PC), as it was ported as a general purpose lib, to graph on a flat bed pen plotter and CRT (Hercules monochrome graphics adapter). Also, I seem to recall a few geeks simulation Rubik's Cube and Enterprise (Dammit Jim, the Original Series!) on a Tektronix Color CRT when I was a wee lad in college (pre IBM PC). You should be able to google for the source or for a compatible port.

    http://www.gaeinc.com/plot10.htm
    http://www.cvrti.utah.edu/~macleod/docs/pscont.htm l
    http://www.ill.fr/Computing/pgplotSS.html

    and then there's http://plplot.sourceforge.net/ as well. (includs the classic "Lena" demo pic)
    I've got some code here somwhere's....hmm.....now what did I do with those 8 inch floppies and drive.....
    --
    "The most exciting phrase to hear in science, the one that heralds new discoveries, is not 'Eureka!' (I found it!) but 'That's funny...'" -Isaac Asimov

    1. Re:what about PLOT10? by TheLoneGundam · · Score: 1

      We had some code here designed for Textronics _vector_ terminals (basically an oscilloscope modified to plot). When they surplused those in the early 80s I wanted to buy one - however the electric bill made it a non-starter.

  42. If you are looking at creating a 3d Renderer... by SporkLand · · Score: 1
  43. Use the classic CONREC routine by Anonymous Coward · · Score: 0

    Check out http://astronomy.swin.edu.au/~pbourke/projection/c onrec. Originally written by Paul Bourke and published in Byte magazine (back when it actually contained code). I've used it very succesfully in the past. It does assume that the input function has been sampled on a rectangular grid. If you don't have such a grid, you'll have to use a different technique.

  44. Maxima by Anonymous Coward · · Score: 0

    Maxima is a decent package.See http://maxima.sourceforge.net/

  45. Re:I just hacked something up myself by Anonymous Coward · · Score: 0

    Seriously man, R is such a fucking slut.

  46. Octave by waxigloo · · Score: 1

    You could look into Octave, which is an OS version of MATLAB released under GPL. You could either use it directly or look into the source for some helpful ideas.