I need to display a quadrilateral mesh in javafx each mesh face having 4 points i have tried some triangle mesh examples from fxyz library, but not sure how does it work for quadrilaterals, Can someone help pointing to examples in javafx for quadrilateral mesh.
The 3DViewer project that is available at the OpenJFX repository, contains already a PolygonalMesh implementation, that allows any number of points per face, so any polygon can be a face.
You can use them that mesh implementation in a PolygonMeshView, instead of the regular MeshView.
Since a triangle is a valid polygon, any TriangleMesh can be easily used as a PolygonMesh.
For instance, the CuboidMesh from FXyz library has the following implementation assuming a PolygonMesh:
private PolygonMesh getTriangleMesh(float width, float height, float depth) {
float L = 2f * width + 2f * depth;
float H = height + 2f * depth;
float hw = width/2f, hh = height/2f, hd = depth/2f;
float[] points = new float[] {
hw, hh, hd, hw, hh, -hd,
hw, -hh, hd, hw, -hh, -hd,
-hw, hh, hd, -hw, hh, -hd,
-hw, -hh, hd, -hw, -hh, -hd
};
float[] texCoords = new float[] {
depth / L, 0f, (depth + width) / L, 0f,
0f, depth / H, depth / L, depth / H,
(depth + width) / L, depth / H, (2f * depth + width) / L, depth/H,
1f, depth / H, 0f, (depth + height) / H,
depth / L, (depth + height)/H, (depth + width) / L, (depth + height) / H,
(2f * depth + width) / L, (depth + height) / H, 1f, (depth + height) / H,
depth / L, 1f, (depth + width) / L, 1f
};
int[][] faces = new int[][] {
{0, 8, 2, 3, 1, 7}, {2, 3, 3, 2, 1, 7},
{4, 9, 5, 10, 6, 4}, {6, 4, 5, 10, 7, 5},
{0, 8, 1, 12, 4, 9}, {4, 9, 1, 12, 5, 13},
{2, 3, 6, 4, 3, 0}, {3, 0, 6, 4, 7, 1},
{0, 8, 4, 9, 2, 3}, {2, 3, 4, 9, 6, 4},
{1, 11, 3, 6, 5, 10}, {5, 10, 3, 6, 7, 5}
};
int[] smooth = new int[] {
1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6
};
PolygonMesh mesh = new PolygonMesh(points, texCoords, faces);
mesh.getFaceSmoothingGroups().addAll(smooth);
return mesh;
}
This gives the following result:
private double mouseOldX, mouseOldY = 0;
private final Rotate rotateX = new Rotate(0, Rotate.X_AXIS);
private final Rotate rotateY = new Rotate(0, Rotate.Y_AXIS);
#Override
public void start(Stage primaryStage) {
PolygonMeshView meshView = new PolygonMeshView(getTriangleMesh(100, 150, 200));
meshView.setDrawMode(DrawMode.LINE);
meshView.setCullFace(CullFace.NONE);
meshView.setMaterial(new PhongMaterial(Color.LIGHTYELLOW));
Scene scene = new Scene(new Group(meshView), 500, 300, true, SceneAntialiasing.BALANCED);
scene.setOnMousePressed(event -> {
mouseOldX = event.getSceneX();
mouseOldY = event.getSceneY();
});
scene.setOnMouseDragged(event -> {
rotateX.setAngle(rotateX.getAngle() - (event.getSceneY() - mouseOldY));
rotateY.setAngle(rotateY.getAngle() + (event.getSceneX() - mouseOldX));
mouseOldX = event.getSceneX();
mouseOldY = event.getSceneY();
});
PerspectiveCamera camera = new PerspectiveCamera(false);
camera.setNearClip(0.1);
camera.setFarClip(10000.0);
camera.getTransforms().addAll(rotateX, rotateY, new Translate(-250, -150, 0));
scene.setCamera(camera);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
But if we combine the triangles of faces in same sides of the prism, we can easily generate the quadrilateral faces. Note that points and texCoords remain the same:
private PolygonMesh getQuadrilateralMesh(float width, float height, float depth) {
float L = 2f * width + 2f * depth;
float H = height + 2f * depth;
float hw = width/2f, hh = height/2f, hd = depth/2f;
float[] points = new float[] {
hw, hh, hd, hw, hh, -hd,
hw, -hh, hd, hw, -hh, -hd,
-hw, hh, hd, -hw, hh, -hd,
-hw, -hh, hd, -hw, -hh, -hd
};
float[] texCoords = new float[] {
depth / L, 0f, (depth + width) / L, 0f,
0f, depth / H, depth / L, depth / H,
(depth + width) / L, depth / H, (2f * depth + width) / L, depth/H,
1f, depth / H, 0f, (depth + height) / H,
depth / L, (depth + height)/H, (depth + width) / L, (depth + height) / H,
(2f * depth + width) / L, (depth + height) / H, 1f, (depth + height) / H,
depth / L, 1f, (depth + width) / L, 1f
};
int[][] faces = new int[][] {
{0, 8, 2, 3, 3, 2, 1, 7},
{4, 9, 5, 10, 7, 5, 6, 4},
{0, 8, 1, 12, 5, 13, 4, 9},
{2, 3, 6, 4, 7, 1, 3, 0},
{0, 8, 4, 9, 6, 4, 2, 3},
{1, 11, 3, 6, 7, 5, 5, 10}
};
int[] smooth = new int[] {
1, 2, 3, 4, 5, 6
};
PolygonMesh mesh = new PolygonMesh(points, texCoords, faces);
mesh.getFaceSmoothingGroups().addAll(smooth);
return mesh;
}
That will be used as:
#Override
public void start(Stage primaryStage) {
PolygonMeshView meshView = new PolygonMeshView(getQuadrilateralMesh(100, 150, 200));
...
}
giving the expected result:
Note that for this sample each face is using points and texture indices, but you normal indices could be added as well.
Related
My goal is to create Boxes with individual images on each side, which I have been completing by using a TriangleMesh to create the boxes, and using a single texture to map the points over the Mesh.
The issue is that I have been experiencing heavy overhead (high ram, long load times and slowness when moving objects in the world) from creating these TriangleMesh, and I'm not sure why fully, but here are a few of my guesses.
I initially tried to use a total of 8 points and reuse the points when creating the individual faces, and wrap the textures, but for some reason the texcoords did not like using only 8 points. As I look at Box's class I see they use 24 points as well as I do, so it seems we cannot reuse points.
2.a I am loading the 3 images into an hbox and then taking a snapshot to then map the coordinates. I am wondering if somehow snapshot is causing issues, or if there is some issue with the amount of pixels.
2.b This further comes into question when I tried turning multiple boxes
that were stacked together into one large box and it still having a
ton of slowness, if not more. I would take a snapshot of x number
of images and then map them onto this one big Box. i.e., if I had
5x5x5 it would be one box with 5 images mapped on each side. Even
with 1 single mesh it still causes slowness. It speeds up if I edit
the "fitWidth/fitHeight" of the imageView which causes a quality
change. To me, it seems like the pixel amounts are the cause. The thing is, if I'm taking the same images and just multiplying them, why is it causing slowness? Especially since when doing a normal box, the single image I was using had more pixels than the other images, so I would think it would be faster by doing the trianglemesh myself.
I don't really have a working example since this was added to an already working program that has data, but I will try to create something if need be.
I'm just trying to figure out why making a TriangleMesh on my own, which has similar code to the Box's code except.
without the face smoothing group, but not sure that matters.
My face array is different, and a bit confused why they have 24 points but the face array only goes from 1-8
int[] faces = {
2, 2, 1, 1, 0, 0, //front
2, 2, 3, 3, 1, 1,
6, 6, 5, 5, 4, 4, //right
6, 6, 7, 7, 5, 5,
10, 10, 9, 9, 8, 8, //back
10, 10, 11, 11, 9, 9,
14, 14, 13, 13, 12, 12,//left
14 ,14, 15, 15, 13, 13,
18, 18, 17, 17, 16, 16,//top
18, 18, 19, 19, 17, 17,
22, 22, 21, 21, 20, 20, //bottom
22, 22, 23, 23, 21, 21`
My texCoords are 6 sets of pairs instead of the 1 set here.
static TriangleMesh createMesh(float w, float h, float d) {
// NOTE: still create mesh for degenerated box
float hw = w / 2f;
float hh = h / 2f;
float hd = d / 2f;
float points[] = {
-hw, -hh, -hd,
hw, -hh, -hd,
hw, hh, -hd,
-hw, hh, -hd,
-hw, -hh, hd,
hw, -hh, hd,
hw, hh, hd,
-hw, hh, hd};
float texCoords[] = {0, 0, 1, 0, 1, 1, 0, 1};
// Specifies hard edges.
int faceSmoothingGroups[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
int faces[] = {
0, 0, 2, 2, 1, 1,
2, 2, 0, 0, 3, 3,
1, 0, 6, 2, 5, 1,
6, 2, 1, 0, 2, 3,
5, 0, 7, 2, 4, 1,
7, 2, 5, 0, 6, 3,
4, 0, 3, 2, 0, 1,
3, 2, 4, 0, 7, 3,
3, 0, 6, 2, 2, 1,
6, 2, 3, 0, 7, 3,
4, 0, 1, 2, 5, 1,
1, 2, 4, 0, 0, 3,
};
TriangleMesh mesh = new TriangleMesh(true);
mesh.getPoints().setAll(points);
mesh.getTexCoords().setAll(texCoords);
mesh.getFaces().setAll(faces);
mesh.getFaceSmoothingGroups().setAll(faceSmoothingGroups);
return mesh;
}
I also had heard that there were improvements to 3D with Version 9. I have been trying to update the past few days to 11 with issues (I had tried 10 before but a lot of my code needed fixings), and 9 isn't downloading so I wanted to ask before trying to put in more effort to get 11 working if it will in fact improve the situation, but I am still wondering why trianglmesh is so slowed comparatively. I'm maybe making 1000 boxes max.
Thank you
EDIT:
Example of how I create the images.
public BoxMesh(width, height,depth, int stack)
{
float width = width;
float height = height;
float depth = depth
List<ImageView> imageList = new ArrayList();
imageList.add(new ImageView(new Image("file:"C:\\file1.jpg"));
HBox h = new HBox();
Image image = null;
for(int i = 0; i < stack; i++)
{
image = new Image("file:"C:\\file2.jpg");
ImageView iv = new ImageView(image);
iv.setFitWidth(image.getWidth()/2); //decreases quality to
iv.setFitHeight(image.getHeight()/2); //speed up program
h.getChildren().add(iv);
}
imageList.add(new ImageView(h.snapshot(null,null)));
VBox v = new VBox();
Image image = null;
for(int i = 0; i < stack; i++)
{
image = new Image("file:"C:\\file3.jpg");
ImageView iv = new ImageView(image);
iv.setFitWidth(image.getWidth()/2);
iv.setFitHeight(image.getHeight()/2);
v.getChildren().add(iv);
}
imageList.add(new ImageView(v.snapshot(null, null)));
PhongMaterial p = new PhongMaterial();
HBox hb = new HBox();
hb.getChildren().addAll(imageList);
WritableImage snapshot = hb.snapshot(null, null);
if(snapshot.isError())
{
System.out.println(snapshot.exceptionProperty().getValue());
}
p.setDiffuseMap(snapshot);
I have a vector a and I need to replicate a slice of this vector, say a[n..n+3], k times.
For example:
a = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
n = 2
k = 3
then I would like to generate:
b = vec![2, 3, 4, 2, 3, 4, 2, 3, 4]
With some previous help I eventually arrived at the following:
a[n..n+3].iter().cloned().cycle().take(3 * k).collect()
Would this be Rust-idiomatic? Is there a more preferred way to do this?
Okay, so after reading this Which is more idiomatic? Functional, imperative or a mix?
and running benchmarks below
#![feature(test)]
extern crate test;
use test::Bencher;
#[bench]
fn bench_target_func(b: &mut Bencher) {
let a = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let n = 2;
let k = 3;
b.iter( || {
let b: Vec = a[n..n+3].iter().cloned().cycle().take(3 * k).collect();
});
}
#[bench]
fn bench_target_imper(b: &mut Bencher) {
let a = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let n = 2;
let k = 3;
b.iter( || {
let mut b: Vec = Vec::with_capacity(k * 3);
let mut it = a[n..n+3].iter().cloned().cycle();
for _ in 0..k*3 {
b.push(it.next().unwrap());
}
});
}
#[bench]
fn bench_target_imper2(b: &mut Bencher) {
let a = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let n = 2;
let k = 3;
b.iter(|| {
let mut b = Vec::with_capacity(3 * k);
for _ in 0..k {
b.extend_from_slice(&a[n..n + 3]);
}
});
}
#[bench]
fn bench_target_func2(b: &mut Bencher) {
let a = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let n = 2;
let k = 3;
b.iter(|| {
let b : Vec = (0..k).flat_map(|_| a[n..n+3].iter().cloned()).collect();
});
}
fn main() {
println!("Hello, world!");
}
I got the following results:
test bench_target_func ... bench: 31 ns/iter (+/- 0)
test bench_target_func2 ... bench: 97 ns/iter (+/- 1)
test bench_target_imper ... bench: 37 ns/iter (+/- 0)
test bench_target_imper2 ... bench: 29 ns/iter (+/- 0)
It appears that flat_map is much slower.
To me your example seems to be Rust-idiomatic enough, but I would do this:
let a = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let n = 2;
let k = 3;
let b : Vec<_> = (0..k).flat_map(|_| a[n..n+3].iter().cloned()).collect();
println!("{:?}", b);
I also propose the following verbose approach, which might be useful in some cases.
let a = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let n = 2;
let k = 3;
let mut b = Vec::with_capacity(3 * k);
for _ in 0..k {
b.extend_from_slice(&a[n..n+3]);
}
println!("{:?}", b);
This is a followup on a previous question (see Coloring individual triangles in a triangle mesh on javafx) which I believe is another topic on its own.
Is there a way (with javafx) that I can get away from having to actually write to disk (or external device) an image file to use a texture?
In other words: can I use a specific texture without having to use Image?
Since my color map will change on runtime I don't want to have to write to disk every time I run it. Also, this might be a security issue (writing to disk) for someone using my app.(with javafx)
As #Jens-Peter-Haack suggest, with Snapshot you can create any image you want, and then apply this image as the diffusion map. For that, you need to create some nodes, fill them with the colors you require, group them in some container and then take the snapshot.
There's a straight-in approach, where you can build an image with a pattern of colors using PixelWriter.
Let's say you want 256 colors, this method will return an image of 256 pixels, where each pixel has one of these colors. For simplicity I've added two simple ways of building a palette.
public static Image colorPallete(int numColors){
int width=(int)Math.sqrt(numColors);
int height=numColors/width;
WritableImage img = new WritableImage(width, height);
PixelWriter pw = img.getPixelWriter();
AtomicInteger count = new AtomicInteger();
IntStream.range(0, height).boxed()
.forEach(y->IntStream.range(0, width).boxed()
.forEach(x->pw.setColor(x, y, getColor(count.getAndIncrement(),numColors))));
// save for testing purposes
try {
ImageIO.write(SwingFXUtils.fromFXImage(img, null), "jpg", new File("palette.jpg"));
} catch (IOException ex) { }
return img;
}
private Color getColor(int iColor, int numColors){
// nice palette of colors
java.awt.Color c = java.awt.Color.getHSBColor((float) iColor / (float) numColors, 1.0f, 1.0f);
return Color.rgb(c.getRed(), c.getGreen(), c.getBlue());
// raw palette
//return Color.rgb((iColor >> 16) & 0xFF, (iColor >> 8) & 0xFF, iColor & 0xFF);
}
Once you have the image object, you can set the diffuse map:
IcosahedronMesh mesh = new IcosahedronMesh();
PhongMaterial mat = new PhongMaterial();
mat.setDiffuseMap(colorPallete(256));
mesh.setMaterial(mat);
But you still have to provide the proper mapping to the new texture.
For this you need to map the vertices of the mesh to a pixel in the image.
First, we need a way to map colors with texture coordinates on the mesh. This method will return a pair of coordinates for a given color index:
public static float[] getTextureLocation(int iPoint, int numColors){
int width=(int)Math.sqrt(numColors);
int height=numColors/width;
int y = iPoint/width;
int x = iPoint-width*y;
return new float[]{(((float)x)/((float)width)),(((float)y)/((float)height))};
}
Finally, we add these textures to m.getTextCoords() and to the faces m.getFaces(), as shown here.
If we assign a color to every vertex in our icosahedron we pick a color from all the palette (scaling up or down according the number of colors and vertices), and then set every face with t0=p0, t1=p1, t2=p2:
IntStream.range(0,numVertices).boxed()
.forEach(i->m.getTexCoords()
.addAll(getTextureLocation(i*numColors/numVertices,numColors)));
m.getFaces().addAll(
1, 1, 11, 11, 7, 7,
1, 1, 7, 7, 6, 6,
1, 1, 6, 6, 10, 10,
1, 1, 10, 10, 3, 3,
1, 1, 3, 3, 11, 11,
4, 4, 8, 8, 0, 0,
5, 5, 4, 4, 0, 0,
9, 9, 5, 5, 0, 0,
2, 2, 9, 9, 0, 0,
8, 8, 2, 2, 0, 0,
11, 11, 9, 9, 7, 7,
7, 7, 2, 2, 6, 6,
6, 6, 8, 8, 10, 10,
10, 10, 4, 4, 3, 3,
3, 3, 5, 5, 11, 11,
4, 4, 10, 10, 8, 8,
5, 5, 3, 3, 4, 4,
9, 9, 11, 11, 5, 5,
2, 2, 7, 7, 9, 9,
8, 8, 6, 6, 2, 2
);
This will give us something like this:
EDIT
Playing around with the textures coordinates, instead of mapping node with color, you can add some function and easily create a contour plot, like this:
You might create the texture to be used for fill etc. in your code by using any graphic object and convert that into an image in memory, not touching disk.
The example below will create a texture using a green spline.
Pane testImage2(Pane pane) {
Pane inner = new Pane();
inner.prefWidthProperty().bind(pane.widthProperty());
inner.prefHeightProperty().bind(pane.heightProperty());
pane.getChildren().add(inner);
SVGPath texture = new SVGPath();
texture.setStroke(Color.GREEN);
texture.setStrokeWidth(2.5);
texture.setFill(Color.TRANSPARENT);
texture.setContent("M 10 10 C 40 10 10 70 70 20");
SnapshotParameters params = new SnapshotParameters();
params.setViewport(new Rectangle2D(-5, -5, 70, 50));
Image image = texture.snapshot(params, null);
Paint paint = new ImagePattern(image, 5,5, 20, 20, false);
inner.setBackground(new Background(new BackgroundFill(paint, new CornerRadii(0), new Insets(inset))));
return pane;
}
I'm currently working on an hex->base64 converter. How am I suppsoed to handle an odd number of hex-digits? What I did until now is that every hex-digit is an 4-bit number, so 2 hex-digits are 1 byte. If I encounter an odd number of hex-digits do I simply fill the rest of the uncomplete byte with 0? Or am I supposed to return an error?
I completed this challenge in C. I use a loop to remove leading zeroes, or 'A's in this case.
#include <stdio.h>
#include <stdlib.h>
char* hex_to_base64(char *hex, int size)
{
int size64 = (size * 2) / 3.0;
size64 += 1;
char *base64 = calloc(size64, 1);
size64 -= 1;
for (int i = size-1; i>= 0; i-=3, size64-=2) {
base64[size64] |= hex[i];
if (i > 0) {
base64[size64] |= ((hex[i - 1] << 4) & 0x3F); //0x3F is 00111111
base64[size64 - 1] |= (hex[i - 1] >> 2);
}
if (i > 1) {
base64[size64 - 1] |= ((hex[i - 2] << 2));
}
}
return base64;
}
int main(int argc, char **argv)
{
int i = 0;
//49276D206B696C6C696E6720796F757220627261696E206C696B65206120706F69736F6E6F7573206D757368726F6F6D
char input[] = { 4, 9, 2, 7, 6, 13, 2, 0, 6, 11, 6, 9, 6, 12, 6, 12, 6, 9, 6, 14, 6, 7, 2, 0, 7, 9, 6, 15, 7, 5, 7, 2, 2, 0, 6, 2, 7,
2, 6, 1, 6, 9, 6, 14, 2, 0, 6, 12, 6, 9, 6, 11, 6, 5, 2, 0, 6, 1, 2, 0, 7, 0, 6, 15, 6, 9, 7, 3, 6, 15, 6, 14, 6, 15, 7, 5, 7, 3,
2, 0, 6, 13, 7, 5, 7, 3, 6, 8, 7, 2, 6, 15, 6, 15, 6, 13 };
char *output;
int outputsize = ((sizeof(input)* 2) / 3.0) + 1;
char *text = calloc(outputsize + 1, 1);
char *formatted;
output = hex_to_base64(input, sizeof(input));
for (i = outputsize-1; i >=0; i--) {
if (output[i] < 26) {
text[i] = output[i] + 65;
}
else if (output[i] < 52) {
text[i] = output[i] + 97 - 26;
}
else if (output[i] < 62) {
text[i] = output[i] + 48 - 52;
}
else if (output[i] == 62) {
text[i] = '+';
}
else if (output[i] == 63) {
text[i] = '/';
}
}
i = 0;
formatted = text;
while (text[i++] == 'A') {
formatted++;
}
printf("%s\n", formatted);
free(text);
return 0;
}
Found this question working on cryptopals challenge myself. The answer is, according to Wikipedia:
Add padding, so that the resulting string is divisible with 3 Bytes.
Set the padded 4bit values to 0 (depending on wether you do this before or after hexstring conversion, this is an actual 0 or a '0')
In the resulting base64 string, the number of padded 4bit values is marked with the same amount of '=' at the end
The implementation of 0x41414141 seems not be a complete solution for the challenge, as the conversion from hexstring to binary is manually hardcoded. Besides, I don't understand why leading zeros should be removed.
Given two random integer generators one that generates between 1 and 7 and another that generates between 1 and 5, how do you make a random integer generator that generates between 1 and 13? I have tried solving this question in various ways but I have not been able to come up with a solution that generates numbers from 1 to 13 with equal or near equal probability.
Using the top two answers for Expand a random range from 1–5 to 1–7, I've come up with the following. There's probably a more efficient way to do this (maybe using the 1-5 generator?) but this seems to work.
Optimized for Compactness
var j;
do {
j = 7 * (rand7() - 1) + rand7(); // uniformly random between 1 and 49
} while (j > 39);
// j is now uniformly random between 1 and 39 (an even multiple of 13)
j = j % 13 + 1;
Optimized for understandability
var v = [
[1, 2, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 13, 1],
[2, 3, 4, 5, 6, 7, 8],
[9, 10, 11, 12, 13, 1, 2],
[3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]
];
var j = 0;
while (j == 0) {
j = v[rand7() - 1][rand7() - 1];
}