How to display 3d shapes with Processing 3 - processing

I'm new to Processing 3 and I would like to display some 3d shapes. Here's what I've done so far:
void setup() {
size(600,600,P3D);
}
void draw() {
sphere(200);
}
and I got this error message :
realloc(): invalid old size
Could not run the sketch (Target VM failed to initialize).
For more information, read revisions.txt and Help → Troubleshooting.

Related

Need to send requestImage() some runtime generated URLs. Is this possible?

I'm using a remote url for a PImage. It's a jpg from a cam. I'm grabbing it and sending it to a image() every sec. Switching to a new cam every 10 secs. Every hour or so, the script crashes due to a 502 error, since the image was not successfully downloaded.
I'm attempting to setup a script that looks at the image using requestImage(), does a quick error check, and skips draw of that image if it returns a 0 or -1. Which should be simple enough. But...
How can you send a constantly updating url to requestImage() if its parameters refuse to accept anything other than a static single filename in a string and it lives in setup() / pre-process?
Anyone run into this issue before? Or am I missing something?
Here is the code. Note: cams are not active at the moment, so there are placeholders in the array...;
Thanks for looking!
PImage webImg;
PImage testImg;
int timer;
String[] camlist = {
"random_url_with_JPG_here",
"random_url_with_JPG_here",
"random_url_with_JPG_here"
};
//find length of array
int camListLength = int(random(camlist.length));
void setup() {
testImg = requestImage(webImg, "jpg");
noCursor();
fullScreen();
background(0);
}
void draw() {
if (millis() - timer >= 10000) {
camLoad();
timer = millis();
} else {
displayWebImage();
}
}
void camLoad() {
//find length of array
camListLength = int(random(camlist.length));
}
void displayWebImage() {
// load random cam url into 'webImg'
webImg = loadImage(camlist[camListLength], "jpg");
// test load
println(testImg.width);
if (testImg.width == 0) {
println("Not Loaded");
} else if (testImg.width == -1) {
println("random error");
} else {
// display 'webImage'
image(webImg, 0, 0, 800, 480);
// cache cleanup
g.removeCache(webImg);
delay(1000);
// frame count
println(frameCount+" "+g.getCache(webImg));
}
}
It's true that for 95% of people, it's a very bad idea to create images in the draw() function. Most programs should load all of the images at the beginning, in the setup() function.
But if you're loading images that you don't know ahead of time, then nothing is stopping you from creating images in the draw() function. You can absolutely call requestImage() from inside the draw() function.
But note that the requestImage() function runs in the background, so your code keeps executing while the image is requested. From the reference:
This function loads images on a separate thread so that your sketch doesn't freeze while images load during setup(). While the image is loading, its width and height will be 0. If an error occurs while loading the image, its width and height will be set to -1.
This means that the image won't be loaded until a couple second later, so you can't use your image variable right away. You're fixing this using a call to delay(), but you're probably better off just using the loadImage() function instead. From the reference:
If the file is not available or an error occurs, null will be returned and an error message will be printed to the console. The error message does not halt the program, however the null value may cause a NullPointerException if your code does not check whether the value returned is null.
...
Depending on the type of error, a PImage object may still be returned, but the width and height of the image will be set to -1. This happens if bad image data is returned or cannot be decoded properly. Sometimes this happens with image URLs that produce a 403 error or that redirect to a password prompt, because loadImage() will attempt to interpret the HTML as image data.
That function does not run in the background, so the code only continues after the image is fully loaded.

JavaFX Export Scene as PDF/SVG

I have currently developed an ultimately open source application to analyse some data in a table view and visualise the resulting data in some additional plots. A problematic thing with this is, that the generated plots could potentially be useful for end users for e.g. a presentation, further downstream informative discussion and so on. This is why I started working on an export function using ImageWriter
//adding a context menu item to the chart
final MenuItem saveAsPng = new MenuItem("Save as png");
saveAsPng.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
int scale = 6; //6x resolution should be enough, users should downscale if required
final Bounds bounds = bc.getLayoutBounds();
final SnapshotParameters spa = new SnapshotParameters();
spa.setTransform(javafx.scene.transform.Transform.scale(scale, scale));
ImageWriter imageWriter = new ImageWriter();
try {
imageWriter.saveImage(stage, bc.snapshot(spa, null));
} catch (ImageException e) {
e.printStackTrace();
}
}
});
This successfully creates a PNG file with sufficient size, but my ideal solution would be to export in vector-based format, e.g. PDF/SVG. For Swing applications, I knew how to achieve this, but for JFX I couldn't really find a proper solution for that matter. I already investigated several potential ideas, e.g. using a printer dialogue and then exporting as a PDF via virtual printer, but that does result in a bitmap inside the PDF, too.
Any ideas on this?

How can I get touch input on Android Wear with OpenGL (Gles2WatchFaceService)?

I am developing a watch face for Android Wear. In order to have smooth graphics, I switched from conventional canvas drawing to OpenGL (i. e., from CanvasWatchFaceService to Gles2WatchFaceService). For touch input, I was using
#Override
public void onTapCommand(int tapType, int x, int y, long eventTime) { ... }
That doesn't seem to work under Gles2WatchFaceService. How can I still get touch input?
I found it. The style of the face watch needs to be set accordingly (setAcceptsTapEvents) in the onCreate function:
#Override
public void onCreate(SurfaceHolder surfaceHolder) {
super.onCreate(surfaceHolder);
setWatchFaceStyle(new WatchFaceStyle.Builder(CronosurfGLWatchFace.this)
...
.setAcceptsTapEvents(true) // <== HERE!!
...
.build());
...
}
It is the same as for CanvasWatchFaceService. For some reason, I lost that style setting while I changed my code from canvas to OpenGL.

Rajawali get object center of gravity point

Using Rajawali library i loaded object from obj file
LoaderOBJ objParser = new LoaderOBJ(mContext.getResources(),
mTextureManager, R.raw.fridge_obj);
loadModel(objParser, new IAsyncLoaderCallback() {
#Override
public void onModelLoadComplete(ALoader loader) {
Log.d(TAG, "Model load complete: " + loader);
final LoaderOBJ obj = (LoaderOBJ) loader;
mObjectGroup = obj.getParsedObject();
getCurrentScene().addChild(mObjectGroup);
}
#Override
public void onModelLoadFailed(ALoader loader) {
Log.e(TAG, "Model load failed: " + loader);
}
}, R.raw.fridge_obj);
now i want get object center of gravity point to set it on world zero point and rotate over that point. I try to get data from Geometry3D how ever i BoundingBox is null same as Vertices field.
How can i get object center of gravity without change object file?
Rajawali currently includes no method for calculating the centroid of an object. If you create a well formatted and worded issue on the github page, we can mark it as a feature request and work on adding it as it would be a useful addition.
You can load your .obj into blender and change the pivot with CTRL + ALT + SHIFT + C. Rajawali will then use the new pivot.

How to get location of mouse in JavaFX?

I am a beginner in java(fx).
How do you get the mouse location in x and y in JavaFX? I tried using AWT's MouseInfo(also imported it), but it's not working. I also saw the code for it in Ensembles(that dragging the ball-window in "advanced stage", that's what I need to do, drag my undecorated JavaFX stage), but it also doesn't work. I am using FXML with controller, and I guess that's the main problem. Should I switch back to the single-file simple JavaFX? I know FXML is better for laying out the UI, but I can't get many of such codes to work. Or do I need some other sort of code for my controller? Please give proper codes with comments wherever possible.
If you need a bit of my code to inspect, feel free to ask.
There are a few items in your question - I'll tackle them one at a time.
How do you get the mouse location in x and y in JavaFX?
Add a mouse event handler to the appropriate JavaFX component that you want to track the mouse location in. A JavaFX mouse event will report multiple different kinds of co-ordinates. The x and y co-ordinates are relative to the top left corner of the node whose location is being monitored. The sceneX and sceneY co-ordinates are relative to the scene's top left 0,0 co-ordinates. The screenX and screenY co-ordinates are relative to the top left 0,0 co-ordinates of the current screen.
These co-ordinates are documented in the MouseEvent documentation. There is extra information in understanding co-ordinate systems in the Node and Scene documentation.
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.*;
public class MouseLocationReporter extends Application {
private static final String OUTSIDE_TEXT = "Outside Label";
public static void main(String[] args) { launch(args); }
#Override public void start(final Stage stage) {
final Label reporter = new Label(OUTSIDE_TEXT);
Label monitored = createMonitoredLabel(reporter);
VBox layout = new VBox(10);
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 10px;");
layout.getChildren().setAll(
monitored,
reporter
);
layout.setPrefWidth(500);
stage.setScene(
new Scene(layout)
);
stage.show();
}
private Label createMonitoredLabel(final Label reporter) {
final Label monitored = new Label("Mouse Location Monitor");
monitored.setStyle("-fx-background-color: forestgreen; -fx-text-fill: white; -fx-font-size: 20px;");
monitored.setOnMouseMoved(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent event) {
String msg =
"(x: " + event.getX() + ", y: " + event.getY() + ") -- " +
"(sceneX: " + event.getSceneX() + ", sceneY: " + event.getSceneY() + ") -- " +
"(screenX: " + event.getScreenX()+ ", screenY: " + event.getScreenY() + ")";
reporter.setText(msg);
}
});
monitored.setOnMouseExited(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent event) {
reporter.setText(OUTSIDE_TEXT);
}
});
return monitored;
}
}
I tried using AWT's MouseInfo(also imported it), but it's not working.
Don't do this. Mixing different graphical toolkits (for example Swing/AWT and JavaFX) is an advanced topic. In general, if you are writing a JavaFX application, avoid importing anything from the java.awt namespace and the javax.swing namespace. You only really need to use those if you have a large, existing Swing based application or framework that you need to inter-operate with your JavaFX application. In this case, you don't have that situation.
I also saw the code for it in Ensembles(that dragging the ball-window in "advanced stage", that's what I need to do, drag my undecorated JavaFX stage), but it also doesn't work.
I tried the Ensemble Advanced Stage sample and dragging that stage around worked for me.
Another sample for dragging an undecorated stage in JavaFX is in the answer to How to draw a clock with JavaFX 2? which has associated sample code. The method used to make the undecorated stage draggable for the clock sample is:
/** makes a stage draggable using a given node */
public static void makeDraggable(final Stage stage, final Node byNode) {
final Delta dragDelta = new Delta();
byNode.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
// record a delta distance for the drag and drop operation.
dragDelta.x = stage.getX() - mouseEvent.getScreenX();
dragDelta.y = stage.getY() - mouseEvent.getScreenY();
byNode.setCursor(Cursor.MOVE);
}
});
byNode.setOnMouseReleased(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
byNode.setCursor(Cursor.HAND);
}
});
byNode.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
stage.setX(mouseEvent.getScreenX() + dragDelta.x);
stage.setY(mouseEvent.getScreenY() + dragDelta.y);
}
});
byNode.setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
if (!mouseEvent.isPrimaryButtonDown()) {
byNode.setCursor(Cursor.HAND);
}
}
});
byNode.setOnMouseExited(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
if (!mouseEvent.isPrimaryButtonDown()) {
byNode.setCursor(Cursor.DEFAULT);
}
}
});
}
I am using FXML with controller, and I guess that's the main problem. Should I switch back to the single-file simple JavaFX? I know FXML is better for laying out the UI, but I can't get many of such codes to work.
Lack of understanding and familiarity with the underlying JavaFX APIs is probably your main problem rather than use of FXML. However the additional complexity fxml implies together with the lighter documentation and samples for it on the web may be contributing to your hardships. If use of FXML is making it difficult for you to understand how to get some JavaFX functions to work, I advise to stop using FXML for now. Code the logic by hand using the Java APIs and refer to the Oracle JavaFX tutorials and the Ensemble sample code when you encounter things which are difficult for you.
Once you are comfortable coding directly to the JavaFX API, switch back to using FXML for larger projects which contain many GUI elements. The FXML elements and attributes themselves are built almost completely upon reflection of the standard JavaFX APIs. So, if you understand the core JavaFX APIs, you also understand almost everything about FXML.
Please do not post follow up comments to this answer (as this answer is long enough as it is). If you have new questions, create a new question (one question per question).
What about using Robot for that purpose ?
http://docs.oracle.com/javase/1.5.0/docs/api/java/awt/Robot.html
Using Robots, it is different from posting event to AWT event queue. Events are generated in the native event queue. Actually, with Robot.mouseMove you will not only set mouse position and not only get position.
For getting mouse position, you may stick to MouseInfo
import java.awt.MouseInfo;
// get the mouse's position
Point p = MouseInfo.getPointerInfo().getLocation();
It's not working: are you with Mac ? Which is your version of JavaFX ? seems to be issues corrected for FX8. For mac only, you may use
com.sun.glass.ui.Robot robot =
com.sun.glass.ui.Application.GetApplication().createRobot();
// getPosition of the mouse in Mac
int x = robot.getMouseX();
int y = robot.getMouseY();
JavaFx 8 WindowEvent doesn't provide the (x,y) location of the mouse, unfortunately. I solved this (and it works fine) by using the AWT MouseInfo like this:
Tooltip t = new Tooltip();
Tooltip.install(yournode, t);
t.setOnShowing(ev -> {// called just prior to being shown
Point mouse = java.awt.MouseInfo.getPointerInfo().getLocation();
Point2D local = yournode.screenToLocal(mouse.x, mouse.y);
// my app-specific code to get the chart's yaxis value
// then set the text as I want
double pitch = yaxis.getValueForDisplay(local.getY()).doubleValue();
double freq = AudioUtil.pitch2frequency(pitch);
t.setText(String.format("Pitch %.1f: %.1f Hz %.1f samples", pitch, freq, audio.rate / freq));
});

Resources