SharpGL Animation Questions - performance

So I am writing a program that parses files with xyz points and makes a bunch of connected lines. What I am trying to do is animate each line being drawn. I have tried to use VBO's and Display Lists in order to increase performance (as I am dealing with large amount of data points i.e. 1,000,000 points) but I could not figure out how to use them in SharpGL. So the code I am using to draw right now is as follows:
private void drawInput(OpenGL gl)
{
gl.Begin(OpenGL.GL_LINE_STRIP);
for (int i = 0; i < parser.dataSet.Count; i++)
{
gl.Color((float) i, 3.0f, 0.0f);
gl.Vertex(parser.dataSet[i].X, parser.dataSet[i].Y, parser.dataSet[i].Z);
gl.Flush();
}
gl.End();
}
I know immediate mode is super noobzore5000 of me, but I can't find any SharpGL examples of VBO's or Display Lists. So know what I want to do is to 'redraw' the picture after each line is drawn. I thought when the flush method is called, it draws everything up to that point. But it still 'batches' it, and displays all the data at once, how can I animate this? I am incredibly desperate, I don't think thoroughly learning OpenGL or DirectX is practical for such a simple task.

After lots of tinkering, I chose to go with OpenTK because I did end up figuring out VBO's for SharpGL and the performance is AWFUL compared to OpenTK. I will give an answer as to how to animate in the way that I wanted.
My solution works with Immediate Mode and using VBO's. The main concept is making a member integer (animationCount) that you increase every time your paint function gets called, and paint up to that number.
Immediate Mode:
private void drawInput(OpenGL gl)
{
gl.Begin(OpenGL.GL_LINE_STRIP);
for (int i = 0; i < animationCount; i++)
{
gl.Color((float) i, 3.0f, 0.0f);
gl.Vertex(parser.dataSet[i].X, parser.dataSet[i].Y, parser.dataSet[i].Z);
}
gl.End();
animationCount++;
}
or
VBO:
private void glControl1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
GL.DrawArrays(PrimitiveType.LineStrip, 0, animationCount);
animationCount++;
}

Related

Processing: Using rollover with text from table

I have a CSV file that was created from a plain text file. In column A there is a list of unique words and in column B it lists their frequency within that text.
I am using Processing and loadTable to draw a list of the words. I would like to use rollover so that when the mouse hovers over them, an ellipse appears that has a size relative to the integer associated with that word's frequency.
I am having a hard time finding a good example of the syntax for using rollover() while in a loop that includes data from a CSV file.
Any help is appreciated!
void setup() {
table = loadTable("tabletest.csv", "header");
size(600,1000);
}
void draw() {
background(252, 245, 224);
for (int i = 0; i < table.getRowCount(); i++) {
TableRow row = table.getRow(i);
String w = row.getString("Word");
int f = row.getInt("Frequency");
textSize(10);
text(w, width/2, 15*i);
fill(8, 114, 105);
textAlign(CENTER);
}
}
There is no built-in rollover() function that I know of. You're going to have to write this functionality yourself.
You can check whether the cursor is inside a given rectangle. See this guide for more info, but basically you check whether mouseX is between the left and right and whether mouseY is between the top and bottom of the rectangle.
If so, then you know the mouse is inside that table cell and you can take the appropriate action. I recommend breaking your problem down into smaller steps and taking those steps on one at a time. For example, start over with a basic sketch that shows a single rectangle that changes color when the mouse is inside it. Get that working perfectly before trying to make it work with multiple rectangles.
Then if you get stuck, you can post a MCVE along with a more specific technical question. Good luck.

How can I make window smaller than 100 pixels

I try to make a status bar on the bottom of my screen, but the window can not be made less than 100 pixels. I'm working on Processing 3.0.1.
I use the following code
void setup() {
surface.setResizable(true);
surface.setSize(300, 20);
surface.setLocation(displayWidth-300, displayHeight-50);
}
void draw() {
background(128);
}
any ideas??
Thank you all in advance
J!
If you remove the surface.setResizable(true); statement, you can see the canvas is 300x20, but the window is not:
Processing 3.0 has a lot of changes including refactoring the windowing code, which previously relied on Java's AWT package.
Going through the current source code, you can see:
static public final int MIN_WINDOW_WIDTH = 128;
static public final int MIN_WINDOW_HEIGHT = 128;
defined in PSurface.java line 34
and used through out PSurfaceAWT.java to ensure these minimum window dimensions.
Trying to access the Surface's canvas (println(surface.getNative());) I can it's listed as processing.awt.PSurfaceAWT$SmoothCanvas and I can see a SmoothCanvas class with a getFrame() method which looks promising, but that doesn't seem to be accessible (even though it's a public method of a public class).
So by default, at this time, I'd say resizing the window to be smaller than 128x128 in Processing 3.x is a no go.
If Processing 3.x and smaller window is a must it might be possible to tweak the source code yourself and recompile the core library, but this may bite you later on when having multiple Processing project with multiple versions of the Processing core library. I wouldn't recommend tinkering with the core library normally.
If you can use Processing 2.x for your project, making the window size smaller than 100 pixels is achievable:
import java.awt.Dimension;
int w = 300;
int h = 20;
int appBarHeight = 23;//this is on OSX, on Windows/Linux this may be different
void setup() {
size(w, h);
frame.setResizable(true);
}
void draw() {
if (frame.getHeight() != h+appBarHeight){//wait for Processing to finish setting up it's window dimensions (including minimum window dimensions)
frame.setSize(w,h+appBarHeight);//set your dimensions
}
background(128);
}

libGDX- Exact collision detection - Polygon creation?

I've got a question about libGDX collision detection. Because it's a rather specific question I have not found any good solution on the internet yet.
So, I already created "humans" that consist of different body parts, each with rectangle-shaped collision detection.
Now I want to implement weapons and skills, which for example look like this:
Skill example image
Problem
Working with rectangles in collision detections would be really frustrating for players when there are skills like this: They would dodge a skill successfully but the collision detector would still damage them.
Approach 1:
Before I started working with Libgdx I have created an Android game with a custom engine and similar skills. There I solved the problem following way:
Detect rectangle collision
Calculate overlapping rectangle section
Check every single pixel of the overlapping part of the skill for transparency
If there is any non-transparent pixel found -> Collision
That's a kind of heavy way, but as only overlapping pixels are checked and the rest of the game is really light, it works completely fine.
At the moment my skill images are loaded as "TextureRegion", where it is not possible to access single pixels.
I have found out that libGDX has a Pixmap class, which would allow such pixel checks. Problem is: having them loaded as Pixmaps additionally would 1. be even more heavy and 2. defeat the whole purpose of the Texture system.
An alternative could be to load all skills as Pixmap only. What do you think: Would this be a good way? Is it possible to draw many Pixmaps on the screen without any issues and lag?
Approach 2:
An other way would be to create Polygons with the shape of the skills and use them for the collision detection.
a)
But how would I define a Polygon shape for every single skill (there are over 150 of them)? Well after browsing a while, I found this useful tool: http://www.aurelienribon.com/blog/projects/physics-body-editor/
it allows to create Polygon shapes by hand and then save them as JSON files, readable by the libGDX application. Now here come the difficulties:
The Physics Body Editor is connected to Box2d (which I am not using). I would either have to add the whole Box2d physics engine (which I do not need at all) just because of one tiny collision detection OR I would have to write a custom BodyEditorLoader which would be a tough, complicated and time-intensive task
Some images of the same skill sprite have a big difference in their shapes (like the second skill sprite example). When working with the BodyEditor tool, I would have to not only define the shape of every single skill, but I would have to define the shape of several images (up to 12) of every single skill. That would be extremely time-intensive and a huge mess when implementing these dozens of polygon shapes
b)
If there is any smooth way to automatically generate Polygons out of images, that could be the solution. I could simply connect every sprite section to a generated polygon and check for collisions that way. There are a few problems though:
Is there any smooth tool which can generate Polygon shapes out of an image (and does not need too much time therefor)?
I don't think that a tool like this (if one exists) can directly work with Textures. It would probably need Pixmaps. It would not be needed to keep te Pixmaps loaded after the Polygon creation though. Still an extremely heavy task!
My current thoughts
I'm stuck at this point because there are several possible approaches but all of them have their difficulties. Before I choose one path and continue coding, it would be great if you could leave some of your ideas and knowledge.
There might be helpful classes and code included in libGDX that solve my problems within seconds - as I am really new at libGDX I just don't know a lot about it yet.
Currently I think I would go with approach 1: Work with pixel detection. That way I made exact collision detections possible in my previous Android game.
What do you think?
Greetings
Felix
I, personally, would feel like pixel-to-pixel collision would be overkill on performance and provide some instances where I would still feel cheated - (I got hit by the handle of the axe?)
If it were me, I would add a "Hitbox" to each skill. StreetFighter is a popular game which uses this technique. (newer versions are in 3D, but hitbox collision is still 2D) Hitboxes can change frame-by-frame along with the animation.
Empty spot here to add example images - google "Streetfighter hitbox" in the meantime
For your axe, there could be a defined rectangle hitbox along the edge of one or both ends - or even over the entire metal head of the axe.
This keeps it fairly simple, without having to mess with exact polygons, but also isn't overly performance heavy like having every single pixel being its own hitbox.
I've used that exact body editor you referenced and it has the ability to generate polygons and/or circles for you. I also made a loader for the generated JSON with the Jackson library. This may not be the answer for you since you'd have to implement box2d. But here's how how I did it anyway.
/**
* Adds all the fixtures defined in jsonPath with the name'lookupName', and
* attach them to the 'body' with the properties defined in 'fixtureDef'.
* Then converts to the proper scale with 'width'.
*
* #param body the body to attach fixtures to
* #param fixtureDef the fixture's properties
* #param jsonPath the path to the collision shapes definition file
* #param lookupName the name to find in jsonPath json file
* #param width the width of the sprite, used to scale fixtures and find origin.
* #param height the height of the sprite, used to find origin.
*/
public void addFixtures(Body body, FixtureDef fixtureDef, String jsonPath, String lookupName, float width, float height) {
JsonNode collisionShapes = null;
try {
collisionShapes = json.readTree(Gdx.files.internal(jsonPath).readString());
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for (JsonNode node : collisionShapes.findPath("rigidBodies")) {
if (node.path("name").asText().equals(lookupName)) {
Array<PolygonShape> polyShapes = new Array<PolygonShape>();
Array<CircleShape> circleShapes = new Array<CircleShape>();
for (JsonNode polygon : node.findPath("polygons")) {
Array<Vector2> vertices = new Array<Vector2>(Vector2.class);
for (JsonNode vector : polygon) {
vertices.add(new Vector2(
(float)vector.path("x").asDouble() * width,
(float)vector.path("y").asDouble() * width)
.sub(width/2, height/2));
}
polyShapes.add(new PolygonShape());
polyShapes.peek().set(vertices.toArray());
}
for (final JsonNode circle : node.findPath("circles")) {
circleShapes.add(new CircleShape());
circleShapes.peek().setPosition(new Vector2(
(float)circle.path("cx").asDouble() * width,
(float)circle.path("cy").asDouble() * width)
.sub(width/2, height/2));
circleShapes.peek().setRadius((float)circle.path("r").asDouble() * width);
}
for (PolygonShape shape : polyShapes) {
Vector2 vectors[] = new Vector2[shape.getVertexCount()];
for (int i = 0; i < shape.getVertexCount(); i++) {
vectors[i] = new Vector2();
shape.getVertex(i, vectors[i]);
}
shape.set(vectors);
fixtureDef.shape = shape;
body.createFixture(fixtureDef);
}
for (CircleShape shape : circleShapes) {
fixtureDef.shape = shape;
body.createFixture(fixtureDef);
}
}
}
}
And I would call it like this:
physics.addFixtures(body, fixtureDef, "ship/collision_shapes.json", shipType, width, height);
Then for collision detection:
public ContactListener shipsExplode() {
ContactListener listener = new ContactListener() {
#Override
public void beginContact(Contact contact) {
Body bodyA = contact.getFixtureA().getBody();
Body bodyB = contact.getFixtureB().getBody();
for (Ship ship : ships) {
if (ship.body == bodyA) {
ship.setExplode();
}
if (ship.body == bodyB) {
ship.setExplode();
}
}
}
};
return listener;
}
then you would add the listener to the world:
world.setContactListener(physics.shipsExplode());
my sprites' width and height were small since you're dealing in meters not pixels once you start using box2d. One sprite height was 0.8f and width was 1.2f for example. If you made the sprites width and height in pixels the physics engine hits speed limits that are built in http://www.iforce2d.net/b2dtut/gotchas
Don't know if this still matter to you guys, but I built a small python script that returns the pixels positions of the points in the edges of the image. There is room to improve the script, but for me, for now its ok...
from PIL import Image, ImageFilter
filename = "dship1"
image = Image.open(filename + ".png")
image = image.filter(ImageFilter.FIND_EDGES)
image.save(filename + "_edge.png")
cols = image.width
rows = image.height
points = []
w = 1
h = 1
i = 0
for pixel in list(image.getdata()):
if pixel[3] > 0:
points.append((w, h))
if i == cols:
w = 0
i = 0
h += 1
w += 1
i += 1
with open(filename + "_points.txt", "wb") as nf:
nf.write(',\n'.join('%s, %s' % x for x in points))
In case of updates you can find them here: export positions

How to animate data visualization in Processing?

I'm trying to create an animated data visualization and currently only know how to do the following "static" code, which puts a string of dots in a straight line. How do I make them jump up and down? Also, if there is anyone in Dublin, Ireland, who wouldn't mind giving a few tutorial sessions to a couple of college students working on a data visualization project in Processing, we have a small budget to compensate you for your time. Thanks very much!
For now, here's the code I was talking about...
SimpleSpreadsheetManager sm;
String sUrl = "t6mq_WLV5c5uj6mUNSryBIA";
String googleUser = "USERNAME";
String googlePass = "PASSWORD";
void setup() {
//This code happens once, right when our sketch is launched
size(800,800);
background(0);
smooth();
//Ask for the list of numbers
int[] numbers = getNumbers();
fill(255,40);
noStroke();
for (int i = 0; i < numbers.length; i++) {
ellipse(numbers[i] * 8, width/2, 8,8);
};
};
void draw() {
//This code happens once every frame.
};
Essentially the x position you use for drawing the ellipse is a number value you get from external data. You need a variable that changes value. Redrawing the ellipse at the updated value should get things animated.
Take this basic example:
float x,y;//position variables for the ellipse
void setup(){
size(800,800);
smooth();
fill(255,40);
noStroke();
y = 400;
}
void draw(){
//update values
x = mouseX + (sin(frameCount * .05) * 30);//update x to an arbitrary value
//draw
background(0);//clear the screen for the new frame
ellipse(x,y,8,8);//draw the ellipse at the new position
}
the x variable is a bit like numbers[i] - just a value that chances.
Nothing special happens in draw() other than clearing the screen(by calling background()) and drawing. The example above uses an arbitrary value, but with your setup that might be something else, maybe a certain value in a data set that changes in time (like the population of a country, etc.)
Another handy thing to keep in mind is the separation between the data and visuals code wise. If values in the data set are higher than what can be displayed on screen as raw values, you can map() values so they can be viewer, add some sort of navigation controls, etc. The values analysed will not be affected by what's being displayed. In programming terms this separation between the data/model, the visuals/view (how the data is rendered) and the controls/controller is known as the Model-View-Controller pattern.
This might be a bit much for people just starting with code, but just being aware of the separation without worrying to much on the specific implementation can be helpful.
Here's a very basic example having the width of the sketch mapped to the size of the data (numbers)
SimpleSpreadsheetManager sm;
String sUrl = "t6mq_WLV5c5uj6mUNSryBIA";
String googleUser = "USERNAME";
String googlePass = "PASSWORD";
int[] numbers;//data used for visualisation
void setup() {
//sketch setup
size(800,800);
smooth();
fill(255,40);
noStroke();
//retrieve data
numbers = getNumbers();
}
void draw() {
background(0);
int numId = int(map(mouseX,0,width,0,numbers.length));//map mouse x position based on sketch width and data size
ellipse(numbers[numId] * 8, height/2, 8,8);
}
For an animation you need one or more parameters that their values changed in time, currently there is a library for processing which do such things: Ani
For more information see the site and provided examples.

XNA: Identifying identical sprites created with for loop

G'day all,
In short, I'm using a for loop to create a bunch of identical sprites that I want to bounce around the screen. The problem is how do I write a collision detection process for the sprites. I have used the process of placing rectangles around sprites and using the .intersects method for rectangles but in that case I created each sprite separately and could identify each one uniquely. Now I have a bunch of sprites but no apparent way to pick one from another.
In detail, if I create an object called Bouncer.cs and give it the movement instructions in it's update() method then create a bunch of sprites using this in Game.cs:
for (int i = 1; i < 5; ++i)
{
Vector2 position = new Vector2(i * 50, i * 50);
Vector2 direction = new Vector2(i * 10, i * 10);
Vector2 velocity = new Vector2(10);
Components.Add(new Bouncer(this, position, direction, velocity, i));
}
base.Initialize();
I can draw a rectangle around each one using:
foreach (Bouncer component1 in Components)
{
Bouncer thing = (Bouncer)component1;
Rectangle thingRectangle;
thingRectangle = new Rectangle((int)thing.position.X, (int)thing.position.Y, thing.sprite.Width, thing.sprite.Height);
But now, how do I check for a collision? I can hardly use:
if (thingRectangle.Intersects(thingRectangle))
I should point out I'm a teacher by trade and play with coding to keep my brain from turning to mush. Recently I have been working with Python and with Python I could just put all the sprites into a list:
sprites[];
Then I could simply refer to each as sprite[1] or sprite[2] or whatever its index in the list is. Does XNA have something like this?
Please let me know if any more code needs to be posted.
Thanks,
Andrew.
One solution, which I use in my game engine, is to have a Logic code run inside the objects for every game Update, ie. every frame. It seems you already do this, according to the variable names, which indicate you run some physics code in the objects to update their positions.
You might also want to create the collision rectangle inside the Bouncer's constructor so it's more accessible and you make good use of object oriented programming, maybe even make it an accessor, so you can make it update every time you call it instead of manually updating the bounding/collision box. For example:
public Rectangle #BoundingBox {
get { return new Rectangle(_Position.X, _Position.Y, width, height); }
}
Whichever way works, but the collision checks can be run inside the Bouncer object. You can either make the reference list of the Bouncer objects static or pass it to the objects itself. The code for collisions is very simply:
foreach(Bouncer bouncer in Components) //Components can be a static List or you can pass it on in the constructor of the Bouncer object
{
if (bouncer.BoundingBox.Intersects(this.BoundingBox))
{
//they collided
}
}

Resources