How to draw in J2ME with float or double point? - java-me

I draw in J2ME with Canvas, but graphics support only integer. So how can I draw with float or double point ?

convert your points to relative integer. or, if your double points is 0<= points<1,
then, get the screen size say, width and height, then x = xx * width and y = yy * height

Related

How do you limit the number of decimal places in the output of multiple numbers?

I've recently started learning Python and have made a simple program to calculate the area of a circle, however, I don't like the output of the answer and wanted to know how it would be possible to limit the number of decimal places in the output for multiple variables.
Example code:
import numpy as np
rad = input("Insert the radius of your circle: ")
radius = float(rad)
area = np.pi*(radius**2)
per=2*np.pi*radius
print("The area and perimeter of your chosen circle of radius "+str(radius)+" are: "+str(area)+" and "+str(per)+" respectively")
Output I get:
Insert the radius of your circle: 56.3
The area and perimeter of your chosen circle of radius 56.3 are: 9957.87481815703 and 353.7433327942107 respectively
Output I would like:
Insert the radius of your circle: 56.3
The area and perimeter of your chosen circle of radius 56.3 are: 9957.87 and 353.74 respectively
Many thanks!
Use f-strings
f-Strings: A New and Improved Way to Format Strings in Python
PEP 498: Literal String Interpolation
Formatted string literals
no need to use +
no need to convert the type
set the number of decimal places shown, with :.0xf, where x is the number of places to the right of the decimal, that will be shown.
Your last line should be:
print(f'The area and perimeter of your chosen circle of radius {radius:.03f} are: {area:.03f} and {per:.03f} respectively')
Output from you code with new f-string:
Insert the radius of your circle: 6
The area and perimeter of your chosen circle of radius 6.000 are: 113.097 and 37.699 respectively

Drawing a circle without using a function for it

So I was wondering how does a circle() function work, and how can I draw to circle without using it (wanted to do something related to it). Does anyone know this stuff?
A classic way of rasterizing a circle is using the Midpoint Circle Algorithm.
It works by tracking the pixels which are as close to the x2 + y2 = r2 isoline as possible. This can even be done with purely integer calculations, which is particularly suitable for low-computation power devices.
A circle is the set of points located at a constant distance from another point, called the center.
If you can draw lines defined by two points, you can draw the representation of a circle on a canvas, knowing its center, and its radius.
The approach is to determine a set of consecutive points located on the circumference, then join them with lines.
for instance, in python (which reads like pseudocode):
import math
def make_circle(center, radius, num_points=40):
"""returns a sequence of points on the circumference
"""
points = [center]
d_theta = 2 * math.pi / num_points
cx, cy = center
for idx in range(num_points + 1):
theta = idx * d_theta
points.append((cx + math.cos(theta) * radius, cy + math.sin(theta) * radius))
return points
And if you want to try it, here it is: circles codeskulptor.
You will see that for display purposes, 40 points on the circumference is enough to give an acceptable rendition.

Positioning digital signatures on pdfs using custom coordinates (using bouncy castle framework)

Following is the code I am using to place digital signatures on standard four coordinates ie top left, top right, bottom left, bottom right. However, its not working correctly for top left.
PdfReader reader = new PdfReader(src);//src being file path of pdf being signed
Rectangle cropBox = reader.getCropBox(1);
if(signaturePosition.equalsIgnoreCase("bottom-left"))
appearance.setVisibleSignature(new Rectangle(cropBox.getLeft(), cropBox.getBottom(),
cropBox.getLeft(width), cropBox.getBottom(height)), 1, "first");
if(signaturePosition.equalsIgnoreCase("bottom-right"))
appearance.setVisibleSignature(new Rectangle(cropBox.getRight(width), cropBox.getBottom(),
cropBox.getRight(), cropBox.getBottom(height)), 1, "first");
if(signaturePosition.equalsIgnoreCase("top-left"))
appearance.setVisibleSignature(new Rectangle(72, 732, 144, 780), 1, "first");
if(signaturePosition.equalsIgnoreCase("top right"))
appearance.setVisibleSignature(new Rectangle(cropBox.getRight(width), cropBox.getTop(height),
cropBox.getRight(), cropBox.getTop()), 1, "first");
Its required to position the signature anywhere on pdf depending upon coordinates provided by the user. To get user's coordinates, we are using a pdf xpro template with a textbox placed over it(user will upload the template and place the textbox where he requires signature to be placed), using that textbox coordinates with its height and width as reference we will position the signature on the pdf.
I need help on understanding how appearance.setVisibleSignature() method works wrt the Rectangle object passed to it, because for each quadrant of the page(considering the center of the page as origin) the parameters are being passed differently for top left, top right, bottom left and bottom right respectively.
The OP clarified in a (meanwhile deleted) comment:
I am asking for explanation of passing height width as parameter to getTop(),getLeft() etc functions. Its not being clear.
Those methods are defined as:
// Returns the lower left y-coordinate, considering a given margin.
public float getBottom(final float margin) {
return lly + margin;
}
// Returns the lower left x-coordinate, considering a given margin.
public float getLeft(final float margin) {
return llx + margin;
}
// Returns the upper right x-coordinate, considering a given margin.
public float getRight(final float margin) {
return urx - margin;
}
// Returns the upper right y-coordinate, considering a given margin.
public float getTop(final float margin) {
return ury - margin;
}
(Rectangle.java)
I.e. these methods return the maximum or minimum x or y coordinate moved inwards by the given margin distance. In the calculations you copied above these methods were used merely as a replacement of some additions or subtractions.
ideally rectangle is top left coordinate as first two coords and height and width as other 2 coords,
What one considers ideal depends on circumstances. What we have here is the constructor
/**
* Constructs a <CODE>Rectangle</CODE> -object.
*
* #param llx lower left x
* #param lly lower left y
* #param urx upper right x
* #param ury upper right y
*/
public Rectangle(final float llx, final float lly, final float urx, final float ury)
(ibidem)
So, first you have the lower left x and y, then the upper right x and y. In other words, you have left x, bottom y, right x, top y.
but its being done differently. Request insights into this.
If you have the upper left coordinates and the width and height, those required coordinates are easy to calculate.
BTW, I hope you are aware that in PDF the default user space coordinate system can have its origin anywhere on or off the page (check the crop box), and that (as common in mathematics) x coordinates are increasing to the right and y coordinates are increasing upwards.

shade border of 2D polygon differently

we are programming a 2D game in XNA. Now we have polygons which define our level elements. They are triangulated such that we can easily render them. Now I would like to write a shader which renders the polygons as outlined textures. So in the middle of the polygon one would see the texture and on the border it should somehow glow.
My first idea was to walk along the polygon and draw a quad on each line segment with a specific texture. This works but looks strange for small corners where the textures are forced to overlap.
My second approach was to mark all border vertices with some kind of normal pointing out of the polygon. Passing this to the shader would interpolate the normals across edges of the triangulation and I could use the interpolated "normal" as a value for shading. I could not test it yet but would that work? A special property of the triangulation is that all vertices are on the border so there are no vertices inside the polygon.
Do you guys have a better idea for what I want to achieve?
Here A picture of what it looks right now with the quad solution:
You could render your object twice. A bigger stretched version behind the first one. Not that ideal since a complex object cannot be streched uniformly to create a border.
If you have access to your screen buffer you can render your glow components into a rendertarget and align a full-screen quad to your viewport and add a fullscreen 2D silhouette filter to it.
This way you gain perfect control over the edge by defining its radius, colour, blur. With additional output values such as the RGB values from the object render pass you can even have different advanced glows.
I think rendermonkey had some examples in their shader editor. Its definetly a good starting point to work with and try out things.
Propaply you want calclulate new border vertex list (easy fill example with triangle strip with originals). If you use constant border width and convex polygon its just:
B_new = B - (BtoA.normalised() + BtoC.normalised()).normalised() * width;
If not then it can go more complicated, there is my old but pretty universal solution:
//Helper function. To working right, need that v1 is before v2 in vetex list and vertexes are going to (anti???) cloclwise!
float vectorAngle(Vector2 v1, Vector2 v2){
float alfa;
if (!v1.isNormalised())
v1.normalise();
if (!v2.isNormalised())
v2.normalise();
alfa = v1.dotProduct(v2);
float help = v1.x;
v1.x = v1.y;
v1.y = -help;
float angle = Math::ACos(alfa);
if (v1.dotProduct(v2) < 0){
angle = -angle;
}
return angle;
}
//Normally dont use directly this!
Vector2 calculateBorderPoint(Vector2 vec1, Vector2 vec2, float width1, float width2){
vec1.normalise();
vec2.normalise();
float cos = vec1.dotProduct(vec2); //Calculates actually cosini of two (normalised) vectors (remember math lessons)
float csc = 1.0f / Math::sqrt(1.0f-cos*cos); //Calculates cosecant of angle, This return NaN if angle is 180!!!
//And rest of the magic
Vector2 difrence = (vec1 * csc * width2) + (vec2 * csc * width1);
//If you use just convex polygons (all angles < 180, = 180 not allowed in this case) just return value, and if not you need some more magic.
//Both of next things need ordered vertex lists!
//Output vector is always to in side of angle, so if this angle is.
if (Math::vectorAngle(vec1, vec2) > 180.0f) //Note that this kind of function can know is your function can know that angle is over 180 ONLY if you use ordered vertexes (all vertexes goes always (anti???) cloclwise!)
difrence = -difrence;
//Ok and if angle was 180...
//Note that this can fix your situation ONLY if you use ordered vertexes (all vertexes goes always (anti???) cloclwise!)
if (difrence.isNaN()){
float width = (width1 + width2) / 2.0; //If angle is 180 and border widths are difrent, you cannot get perfect answer ;)
difrence = vec1 * width;
//Just turn vector -90 degrees
float swapHelp = difrence.y
difrence.y = -difrence.x;
difrence.x = swapHelp;
}
//If you don't want output to be inside of old polygon but outside, just: "return -difrence;"
return difrence;
}
//Use this =)
Vector2 calculateBorderPoint(Vector2 A, Vector2 B, Vector2 C, float widthA, float widthB){
return B + calculateBorderPoint(A-B, C-B, widthA, widthB);
}
Your second approach can be possible...
mark the outer vertex (in border) with 1 and the inner vertex (inside) with 0.
in the pixel shader you can choose to highlight, those that its value is greater than 0.9f or 0.8f.
it should work.

Normalized Device Coordinates to window coordinates

I just read some stuff about the theory behind 3d graphics. As I understand it, normalized device coordinates (NDC) are coordinates that describe a point in the interval from -1 to 1 on both the horizontal and vertical axis. On the other hand window coordinates describe a point somewhere between (0,0) and (width,height) of the window.
So my formula to convert a point from the NDC coordinate system to the window system would be
xwin = width + xndc * 0.5 * width
ywin = height + ynfv * 0.5 * height
The problem now is that in the OpenGL documentation for glViewport there is an other formula:
xwin = ( xndc + 1 ) * width * 0.5 + x
ywin = ( yndc + 1 ) * height * 0.5 + y
Now I'm wondering what I am getting wrong. Especially I'm wondering what the additional "x" and "y" mean.
Hope the question isn't too "not programming related", but I thought somehow it is related to graphics programming.
Viewport doesn't necessarily start at (0; 0), so 'x' and 'y' in OpenGL documentation refers to viewport starting position.
To see what's wrong with your equation, try transforming (0; 0) normalized position, and you will get (width; height) instead of (width / 2; height / 2).

Resources