draw mandlebrot onto bitmap - java

I am currently converting java code into c# code and i have it almost working i think but I am trying to draw the mandlebrot onto the bitmap but nothing is displaying . The form pops up but nothing is drawn onto it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Assignment1
{
public partial class Form1 : Form
{
public Form1()
{
init();
start();
stop();
destroy();
InitializeComponent();
}
public struct HSBColor
{
float h;
float s;
float b;
int a;
public HSBColor(float h, float s, float b)
{
this.a = 0xff;
this.h = Math.Min(Math.Max(h, 0), 255);
this.s = Math.Min(Math.Max(s, 0), 255);
this.b = Math.Min(Math.Max(b, 0), 255);
}
public HSBColor(int a, float h, float s, float b)
{
this.a = a;
this.h = Math.Min(Math.Max(h, 0), 255);
this.s = Math.Min(Math.Max(s, 0), 255);
this.b = Math.Min(Math.Max(b, 0), 255);
}
public float H
{
get { return h; }
}
public float S
{
get { return s; }
}
public float B
{
get { return b; }
}
public int A
{
get { return a; }
}
public Color Color
{
get
{
return FromHSB(this);
}
}
public static Color FromHSB(HSBColor hsbColor)
{
float r = hsbColor.b;
float g = hsbColor.b;
float b = hsbColor.b;
if (hsbColor.s != 0)
{
float max = hsbColor.b;
float dif = hsbColor.b * hsbColor.s / 255f;
float min = hsbColor.b - dif;
float h = hsbColor.h * 360f / 255f;
if (h < 60f)
{
r = max;
g = h * dif / 60f + min;
b = min;
}
else if (h < 120f)
{
r = -(h - 120f) * dif / 60f + min;
g = max;
b = min;
}
else if (h < 180f)
{
r = min;
g = max;
b = (h - 120f) * dif / 60f + min;
}
else if (h < 240f)
{
r = min;
g = -(h - 240f) * dif / 60f + min;
b = max;
}
else if (h < 300f)
{
r = (h - 240f) * dif / 60f + min;
g = min;
b = max;
}
else if (h <= 360f)
{
r = max;
g = min;
b = -(h - 360f) * dif / 60 + min;
}
else
{
r = 0;
g = 0;
b = 0;
}
}
return Color.FromArgb
(
hsbColor.a,
(int)Math.Round(Math.Min(Math.Max(r, 0), 255)),
(int)Math.Round(Math.Min(Math.Max(g, 0), 255)),
(int)Math.Round(Math.Min(Math.Max(b, 0), 255))
);
}
}
private const int MAX = 256; // max iterations
private const double SX = -2.025; // start value real
private const double SY = -1.125; // start value imaginary
private const double EX = 0.6; // end value real
private const double EY = 1.125; // end value imaginary
private static int x1, y1, xs, ys, xe, ye;
private static double xstart, ystart, xende, yende, xzoom, yzoom;
private static bool action, rectangle, finished;
private static float xy;
private Image picture;
private Graphics g1;
private Cursor c1, c2;
//private HSB HSBcol=new HSB();
public void init() // all instances will be prepared
{
//HSBcol = new HSB();
this.Size = new Size(640,480);
finished = false;
//addMouseListener(this);
//addMouseMotionListener(this);
//c1 = new Cursor(Cursor.WAIT_CURSOR);
//c2 = new Cursor(Cursor.CROSSHAIR_CURSOR);
x1 = this.Width;
y1 = this.Height;
xy = (float)x1 / (float)y1;
Bitmap img = new Bitmap(1, 1);
g1 = Graphics.FromImage(img);
finished = true;
}
public void destroy() // delete all instances
{
if (finished)
{
//removeMouseListener(this);
//removeMouseMotionListener(this);
picture = null;
g1 = null;
c1 = null;
c2 = null;
GC.Collect(); // garbage collection
}
}
public void start()
{
action = false;
rectangle = false;
initvalues();
xzoom = (xende - xstart) / (double)x1;
yzoom = (yende - ystart) / (double)y1;
mandelbrot();
}
public void stop()
{
}
public void paint(Graphics g)
{
update(g);
}
public void update(Graphics g)
{
g.DrawImage(picture, 0, 0);
if (rectangle)
{
Pen WhitePen = new Pen(Color.White);
if (xs < xe)
{
if (ys < ye) g.DrawRectangle(WhitePen, xs, ys, (xe - xs), (ye - ys));
else g.DrawRectangle(WhitePen, xs, ye, (xe - xs), (ys - ye));
}
else
{
if (ys < ye) g.DrawRectangle(WhitePen, xe, ys, (xs - xe), (ye - ys));
else g.DrawRectangle(WhitePen, xe, ye, (xs - xe), (ys - ye));
}
}
}
private void mandelbrot() // calculate all points
{
int x, y;
float h, b, alt = 0.0f;
Pen FractalPen;
action = false;
//SetCursor(c1);
//showStatus("Mandelbrot-Set will be produced - please wait...");
for (x = 0; x < x1; x+=2)
for (y = 0; y < y1; y++)
{
h = pointcolour(xstart + xzoom * (double)x, ystart + yzoom * (double)y); // color value
if (h != alt)
{
b = 1.0f - h * h; // brightnes
///djm added
//HSBcol.fromHSB(h,0.8f,b); //convert hsb to rgb then make a Java Color
Color color = HSBColor.FromHSB(new HSBColor(h * 255, 0.8f * 255, b * 255)); // VERY IMPORTANT
//g1.setColor(col);
//djm end
//djm added to convert to RGB from HSB
//g1.setColor(Color.getHSBColor(h, 0.8f, b));
//djm test
//Color col = Color.getHSBColor(h,0.8f,b);
//int red = col.getRed();
//int green = col.getGreen();
//int blue = col.getBlue();
//djm
alt = h;
FractalPen = new Pen(color);
g1.DrawLine(FractalPen, x, y, x + 1, y);
}
}
//showStatus("Mandelbrot-Set ready - please select zoom area with pressed mouse.");
//setCursor(c2);
action = true;
}
private float pointcolour(double xwert, double ywert) // color value from 0.0 to 1.0 by iterations
{
double r = 0.0, i = 0.0, m = 0.0;
int j = 0;
while ((j < MAX) && (m < 4.0))
{
j++;
m = r * r - i * i;
i = 2.0 * r * i + ywert;
r = m + xwert;
}
return (float)j / (float)MAX;
}
private void initvalues() // reset start values
{
xstart = SX;
ystart = SY;
xende = EX;
yende = EY;
if ((float)((xende - xstart) / (yende - ystart)) != xy )
xstart = xende - (yende - ystart) * (double)xy;
}
/*public void mousePressed(MouseEvent e)
{
e.consume();
if (action)
{
xs = e.getX();
ys = e.getY();
}
}
public void mouseReleased(MouseEvent e)
{
int z, w;
e.consume();
if (action)
{
xe = e.getX();
ye = e.getY();
if (xs > xe)
{
z = xs;
xs = xe;
xe = z;
}
if (ys > ye)
{
z = ys;
ys = ye;
ye = z;
}
w = (xe - xs);
z = (ye - ys);
if ((w < 2) && (z < 2)) initvalues();
else
{
if (((float)w > (float)z * xy)) ye = (int)((float)ys + (float)w / xy);
else xe = (int)((float)xs + (float)z * xy);
xende = xstart + xzoom * (double)xe;
yende = ystart + yzoom * (double)ye;
xstart += xzoom * (double)xs;
ystart += yzoom * (double)ys;
}
xzoom = (xende - xstart) / (double)x1;
yzoom = (yende - ystart) / (double)y1;
mandelbrot();
rectangle = false;
repaint();
}
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseDragged(MouseEvent e)
{
e.consume();
if (action)
{
xe = e.getX();
ye = e.getY();
rectangle = true;
repaint();
}
}
public void mouseMoved(MouseEvent e)
{
}
public String getAppletInfo()
{
return "fractal.class - Mandelbrot Set a Java Applet by Eckhard Roessel 2000-2001";
}*/
}
}

Bitmap img = new Bitmap(1, 1);
This could be the problem. You forgot to replace it with width,height. Like this
Bitmap img = new Bitmap(x1, y1);

call your paint method like this (picturebox is not needed, but for me it was fastest when painting with winforms:
Rectangle r = new Rectangle();
var g = pictureBox1.CreateGraphics();
var pea = new PaintEventArgs(g, r);
yourPaintMethod(pea);
calls:
public void yourPaintMethod(PaintEventArgs e ) {
Graphics g = e.Graphics;
Pen pBlack = new Pen(Color.Black, 1);
g.DrawLine(pBlack........ etc.

Related

How change shape and size of custom drawn shader in glsurface view by getting coordinates from view class

In my application i'm having a custom graph like view firstly beneath the overlaying graph view there is a custom cameraview which extends glsurfaceview here inside camera view class i'm applying live blur filter to camera of device without any problems but however i want to change the shape and size of blur as per the coordinate of my overlay grap view here i'm attaching screenshots of my application:
Below Is the screenshot of what i'm trying to achieve:
Below Is Screenshot of What i'm actaully getting:
Here's my overlaying view class:
public class OverlayView2 extends View {
MainActivity f2396a;
double f2397b;
double f2398c;
double f2399d;
double f2400e;
double f2401f;
int f2402g = 1;
C0905a[] f2403h = {new C0905a(), new C0905a(), new C0905a(), new C0905a(), new C0905a()};
Paint f2404i = new Paint();
double f2405j = 1.0d;
double f2406k;
double f2407l;
double f2408m;
class C0905a {
double f2409a;
double f2410b;
int f2411c = -1;
double f2412d;
double f2413e;
C0905a() {
}
}
public OverlayView2(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
mo3504a();
if (!isInEditMode() && (context instanceof MainActivity)) {
this.f2396a = (MainActivity) context;
}
}
public static float m4357a(Context context, float f) {
return TypedValue.applyDimension(1, f, context.getResources().getDisplayMetrics());
}
public void mo3504a() {
this.f2397b = 0.0d;
this.f2398c = 0.0d;
this.f2399d = 0.0d;
this.f2400e = 0.4d;
this.f2401f = 0.25d;
invalidate();
}
public void mo3505a(double d, double d2, double d3, double d4, Canvas canvas) {
double width = (double) ((getWidth() + getHeight()) * 2);
canvas.drawLine((float) (d - (d3 * width)), (float) (d2 - (d4 * width)), (float) ((d3 * width) + d), (float) ((width * d4) + d2), this.f2404i);
}
public void mo3506a(double d, double d2, Canvas canvas) {
canvas.drawOval(new RectF((float) (0.0d - d), (float) (0.0d - d2), (float) (0.0d + d), (float) (0.0d + d2)), this.f2404i);
}
/* access modifiers changed from: 0000 */
/* renamed from: b */
public void mo3507b() {
double scale = getScale();
double width = (((double) getWidth()) * 0.5d) + (this.f2397b * scale);
double height = (((double) getHeight()) * 0.5d) + (this.f2398c * scale);
double cos = Math.cos(Math.toRadians(this.f2399d)) * this.f2400e * scale;
double sin = Math.sin(Math.toRadians(this.f2399d)) * this.f2400e * scale;
double d = (-Math.sin(Math.toRadians(this.f2399d))) * this.f2401f * scale;
double cos2 = Math.cos(Math.toRadians(this.f2399d)) * this.f2401f * scale;
this.f2403h[0].f2409a = width;
this.f2403h[0].f2410b = height;
this.f2403h[1].f2409a = width - cos;
this.f2403h[1].f2410b = height - sin;
this.f2403h[2].f2409a = cos + width;
this.f2403h[2].f2410b = sin + height;
this.f2403h[3].f2409a = width - d;
this.f2403h[3].f2410b = height - cos2;
this.f2403h[4].f2409a = width + d;
this.f2403h[4].f2410b = height + cos2;
Matrix matrix = new Matrix();
matrix.postScale((float) (this.f2400e * scale), (float) (this.f2401f * scale));
matrix.postRotate((float) this.f2399d);
matrix.postTranslate(((float) getWidth()) * 0.5f, ((float) getHeight()) * 0.5f);
matrix.postTranslate((float) (this.f2397b * scale), (float) (scale * this.f2398c));
matrix.postScale(1.0f / ((float) getWidth()), -1.0f / ((float) getHeight()));
matrix.postTranslate(0.0f, 1.0f);
matrix.invert(matrix);
if (this.f2396a != null && this.f2396a.cameraView != null) {
/* matrix.getValues(this.f2396a.cameraView.f2132f);*/
}
}
public void mo3508c() {
double d;
double scale = getScale();
C0905a aVar = this.f2403h[0];
if (aVar.f2411c >= 0) {
this.f2397b = (aVar.f2409a - (((double) getWidth()) * 0.5d)) / scale;
this.f2398c = (aVar.f2410b - (((double) getHeight()) * 0.5d)) / scale;
}
double d2 = 0.0d;
int i = 0;
double d3 = 0.0d;
double d4 = 0.0d;
int i2 = 0;
int i3 = 0;
for (int i4 = 1; i4 < this.f2403h.length; i4++) {
C0905a aVar2 = this.f2403h[i4];
if (aVar2.f2411c >= 0) {
if (i4 == 1) {
d2 += Math.toDegrees(Math.atan2(-(aVar2.f2410b - this.f2403h[0].f2410b), -(aVar2.f2409a - this.f2403h[0].f2409a)));
i++;
}
if (i4 == 2) {
d2 += Math.toDegrees(Math.atan2(aVar2.f2410b - this.f2403h[0].f2410b, aVar2.f2409a - this.f2403h[0].f2409a));
i++;
}
if (this.f2402g != 1) {
if (i4 == 3) {
d2 += Math.toDegrees(Math.atan2(aVar2.f2409a - this.f2403h[0].f2409a, -(aVar2.f2410b - this.f2403h[0].f2410b)));
i++;
}
if (i4 == 4) {
d2 += Math.toDegrees(Math.atan2(-(aVar2.f2409a - this.f2403h[0].f2409a), aVar2.f2410b - this.f2403h[0].f2410b));
i++;
}
}
double d5 = (this.f2403h[0].f2409a - aVar2.f2409a) / scale;
double d6 = (this.f2403h[0].f2410b - aVar2.f2410b) / scale;
if (i4 == 1 || i4 == 2) {
double cos = (Math.cos(Math.toRadians(this.f2399d)) * d5) + (Math.sin(Math.toRadians(this.f2399d)) * d6);
if (i4 == 2) {
cos = -cos;
}
d = Math.max(0.0d, cos) + d3;
i2++;
} else {
d = d3;
}
if (i4 == 3 || i4 == 4) {
double cos2 = ((-Math.sin(Math.toRadians(this.f2399d))) * d5) + (d6 * Math.cos(Math.toRadians(this.f2399d)));
if (i4 == 4) {
cos2 = -cos2;
}
d4 += Math.max(0.0d, cos2);
i3++;
d3 = d;
} else {
d3 = d;
}
}
}
if (i > 0) {
this.f2399d = d2 / ((double) i);
}
if (i2 > 0) {
this.f2400e = d3 / ((double) i2);
}
if (i3 > 0) {
this.f2401f = d4 / ((double) i3);
}
if (this.f2397b < -0.8d) {
this.f2397b = -0.8d;
}
if (this.f2398c < -0.8d) {
this.f2398c = -0.8d;
}
if (this.f2397b > 0.8d) {
this.f2397b = 0.8d;
}
if (this.f2398c > 0.8d) {
this.f2398c = 0.8d;
}
if (this.f2400e < 0.05d) {
this.f2400e = 0.05d;
}
if (this.f2401f < 0.05d) {
this.f2401f = 0.05d;
}
if (this.f2400e > 1.0d) {
this.f2400e = 1.0d;
}
if (this.f2401f > 1.0d) {
this.f2401f = 1.0d;
}
}
public double getHandleRadius() {
return (double) m4357a(getContext(), 16.0f);
}
public double getScale() {
return (double) (((float) (getWidth() + getHeight())) * 0.5f);
}
public void onDraw(Canvas canvas) {
if (this.f2402g != 0) {
this.f2404i.setColor(-1140850689);
this.f2404i.setStrokeWidth(m4357a(getContext(), 1.5f));
this.f2404i.setStyle(Style.STROKE);
this.f2404i.setAntiAlias(true);
canvas.save();
double scale = getScale();
canvas.translate(((float) getWidth()) * 0.5f, ((float) getHeight()) * 0.5f);
canvas.translate((float) (this.f2397b * scale), (float) (this.f2398c * scale));
canvas.rotate((float) this.f2399d);
mo3505a(0.0d, 0.0d, 1.0d, 0.0d, canvas);
if (this.f2402g == 1) {
mo3505a(0.0d, (this.f2401f * scale) + 0.0d, 1.0d, 0.0d, canvas);
mo3505a(0.0d, 0.0d - (this.f2401f * scale), 1.0d, 0.0d, canvas);
}
mo3505a(0.0d, 0.0d, 0.0d, 1.0d, canvas);
if (this.f2402g == 2) {
mo3506a(this.f2400e * scale, this.f2401f * scale, canvas);
}
canvas.restore();
mo3507b();
double handleRadius = getHandleRadius();
for (int i = 0; i < this.f2403h.length; i++) {
canvas.drawCircle((float) this.f2403h[i].f2409a, (float) this.f2403h[i].f2410b, (float) (this.f2403h[i].f2411c >= 0 ? 1.25d * handleRadius : handleRadius), this.f2404i);
}
}
}
public boolean onTouchEvent(MotionEvent motionEvent) {
boolean z;
C0905a[] aVarArr;
C0905a[] aVarArr2;
if (this.f2402g == 0) {
for (C0905a aVar : this.f2403h) {
aVar.f2411c = -1;
}
return super.onTouchEvent(motionEvent);
}
boolean z2 = false;
int actionMasked = motionEvent.getActionMasked();
if (actionMasked == 0 || actionMasked == 5) {
z2 = true;
double d = Double.MAX_VALUE;
C0905a aVar2 = null;
int actionIndex = motionEvent.getActionIndex();
int pointerId = motionEvent.getPointerId(actionIndex);
double x = (double) motionEvent.getX(actionIndex);
double y = (double) motionEvent.getY(actionIndex);
double handleRadius = getHandleRadius() * 2.5d;
double d2 = handleRadius * handleRadius;
C0905a[] aVarArr3 = this.f2403h;
int length = aVarArr3.length;
int i = 0;
while (i < length) {
C0905a aVar3 = aVarArr3[i];
double d3 = aVar3.f2409a - x;
double d4 = aVar3.f2410b - y;
double d5 = (d3 * d3) + (d4 * d4);
if (d5 >= d2 || d5 >= d) {
aVar3 = aVar2;
d5 = d;
}
i++;
d = d5;
aVar2 = aVar3;
}
if (aVar2 != null) {
aVar2.f2411c = pointerId;
aVar2.f2412d = x - aVar2.f2409a;
aVar2.f2413e = y - aVar2.f2410b;
}
}
if (actionMasked == 5) {
for (C0905a aVar4 : this.f2403h) {
aVar4.f2411c = -1;
}
}
if ((actionMasked == 2 || actionMasked == 5) && motionEvent.getPointerCount() == 2) {
double x2 = (double) (motionEvent.getX(0) - motionEvent.getX(1));
double y2 = (double) (motionEvent.getY(0) - motionEvent.getY(1));
double sqrt = Math.sqrt((x2 * x2) + (y2 * y2));
double degrees = Math.toDegrees(Math.atan2((double) (motionEvent.getY(0) - motionEvent.getY(1)), (double) (motionEvent.getX(0) - motionEvent.getX(1))));
if (actionMasked == 2) {
double d6 = sqrt / this.f2405j;
this.f2400e *= d6;
this.f2401f = d6 * this.f2401f;
this.f2399d += degrees - this.f2408m;
}
this.f2405j = sqrt;
this.f2408m = degrees;
}
if (actionMasked == 2 || actionMasked == 5 || actionMasked == 0 || actionMasked == 1 || actionMasked == 6) {
double d7 = 0.0d;
double d8 = 0.0d;
int i2 = 0;
for (int i3 = 0; i3 < motionEvent.getPointerCount(); i3++) {
if (actionMasked != 6 || i3 != motionEvent.getActionIndex()) {
d7 += (double) motionEvent.getX(i3);
d8 += (double) motionEvent.getY(i3);
i2++;
}
}
if (i2 > 0) {
double d9 = d7 / ((double) i2);
double d10 = d8 / ((double) i2);
if (actionMasked == 2) {
boolean z3 = true;
for (C0905a aVar5 : this.f2403h) {
if (aVar5.f2411c >= 0) {
z3 = false;
}
}
if (z3) {
double scale = 1.0d / getScale();
this.f2397b += (d9 - this.f2406k) * scale;
this.f2398c = (scale * (d10 - this.f2407l)) + this.f2398c;
}
}
this.f2406k = d9;
this.f2407l = d10;
}
}
if (actionMasked == 2) {
z = true;
int pointerCount = motionEvent.getPointerCount();
for (int i4 = 0; i4 < pointerCount; i4++) {
int pointerId2 = motionEvent.getPointerId(i4);
double x3 = (double) motionEvent.getX(i4);
double y3 = (double) motionEvent.getY(i4);
for (C0905a aVar6 : this.f2403h) {
if (aVar6.f2411c == pointerId2) {
aVar6.f2409a = x3 - aVar6.f2412d;
aVar6.f2410b = y3 - aVar6.f2413e;
}
}
}
} else {
z = z2;
}
if (actionMasked == 1 || actionMasked == 6) {
z = true;
int pointerId3 = motionEvent.getPointerId(motionEvent.getActionIndex());
for (C0905a aVar7 : this.f2403h) {
if (aVar7.f2411c == pointerId3) {
aVar7.f2411c = -1;
}
}
}
if (actionMasked == 3) {
z = true;
for (C0905a aVar8 : this.f2403h) {
aVar8.f2411c = -1;
}
}
if (z) {
mo3508c();
invalidate();
if (this.f2396a != null) {
this.f2396a.cameraView.requestRender();
}
}
return super.onTouchEvent(motionEvent) || z;
}
}
Here's my cameraview class:
public class CameraView extends GLSurfaceView implements Renderer {
public static long maxsize = 1280;
final String TAG = "CameraView";
public Bitmap bitmap = null;
public Bitmap bitmap0 = null;
int bitmaptexture = -1;
boolean bresize = true;
public float f0c;
public static Camera camera;
SurfaceTexture cameraSurface;
int cameraTexture;
boolean created = false;
boolean doloadbitmap = false;
public boolean isFrontFacing;
Framebuffer fa;
Framebuffer fb;
/* renamed from: h */
int f1h;
public static int ak;
OnPhotoListener photoListener;
Quad quad = new Quad();
public float f2r;
public float f3s;
Shader shblur;
Shader shconv;
Shader shcopy;
Shader shfina;
Shader shflip;
int f4w;
public float f5y;
public interface OnPhotoListener {
void onPhoto(Bitmap bitmap);
}
public void takePhoto(OnPhotoListener l) {
this.photoListener = l;
requestRender();
}
static Bitmap takeScreenshot(int x, int y, int w, int h) {
int[] b = new int[((y + h) * w)];
int[] bt = new int[(w * h)];
IntBuffer ib = IntBuffer.wrap(b);
ib.position(0);
GLES20.glReadPixels(x, 0, w, y + h, 6408, 5121, ib);
int i = 0;
int k = 0;
while (i < h) {
for (int j = 0; j < w; j++) {
int pix = b[(i * w) + j];
bt[(((h - k) - 1) * w) + j] = ((-16711936 & pix) | ((pix << 16) & 16711680)) | ((pix >> 16) & MotionEventCompat.ACTION_MASK);
}
i++;
k++;
}
return Bitmap.createBitmap(bt, w, h, Config.ARGB_8888);
}
public CameraView(Context context, AttributeSet attrs) {
super(context, attrs);
setEGLContextClientVersion(2);
setRenderer(this);
setRenderMode(0);
requestRender();
}
void m7x(Framebuffer src, Framebuffer dst, float dx, float dy) {
dst.bind(this.f4w, this.f1h);
this.shblur.use();
this.shblur.tex("s", src.tex());
this.shblur.set("o", (double) dx, (double) dy);
this.shblur.set("y", (double) this.f5y);
this.shblur.set("z", (double) this.f3s);
this.quad.draw();
}
void m6x() {
float radius = this.f2r;
float rx = ((radius / 8.0f) / ((float) this.f4w)) * ((float) this.f1h);
float ry = radius / 8.0f;
m7x(this.fa, this.fb, rx / 8.0f, 0.0f);
m7x(this.fb, this.fa, rx / 1.0f, 0.0f);
m7x(this.fa, this.fb, 0.0f, ry / 8.0f);
m7x(this.fb, this.fa, 0.0f, ry / 1.0f);
m7x(this.fa, this.fb, rx / 8.0f, 0.0f);
m7x(this.fb, this.fa, rx / 1.0f, 0.0f);
m7x(this.fa, this.fb, 0.0f, ry / 8.0f);
m7x(this.fb, this.fa, 0.0f, ry / 1.0f);
}
public void onDrawFrame(GL10 _gl) {
GLES20.glClear(16384);
GLES20.glDisable(2929);
GLES20.glDisable(2884);
GLES20.glDisable(3042);
GLES20.glEnableVertexAttribArray(0);
Bitmap b = this.bitmap;
if (b != null) {
this.f4w = b.getWidth();
this.f1h = b.getHeight();
if (this.doloadbitmap) {
loadbitmap();
this.doloadbitmap = false;
}
this.fa.bind(this.f4w, this.f1h);
this.shflip.use();
this.shflip.tex("s", this.bitmaptexture);
this.quad.draw();
} else if (this.camera != null && this.cameraSurface != null) {
Size cameraSize = null;
try {
this.camera.setPreviewTexture(this.cameraSurface);
this.cameraSurface.updateTexImage();
cameraSize = this.camera.getParameters().getPreviewSize();
} catch (Exception e) {
e.printStackTrace();
}
if (this.camera != null && cameraSize != null && this.cameraSurface != null) {
this.f4w = cameraSize.width;
this.f1h = cameraSize.height;
this.fa.bind(this.f4w, this.f1h);
this.shconv.use();
this.shconv.tex("s", this.cameraTexture, 0, 36197);
this.quad.draw();
} else {
return;
}
} else {
return;
}
m6x();
this.fb.bind(this.fa.f7w, this.fa.f6h);
this.shfina.use();
this.shfina.tex("s", this.fa.tex());
this.shfina.set("c", (double) this.f0c);
this.quad.draw();
OnPhotoListener l = this.photoListener;
this.photoListener = null;
if (l != null) {
Bitmap bmp = takeScreenshot(0, 0, this.f4w, this.f1h);
l.onPhoto(bmp);
bmp.recycle();
requestRender();
}
Framebuffer.reset(getWidth(), getHeight());
GLES20.glClear(16384);
if ((((double) this.f4w) * 1.0d) / ((double) this.f1h) > (((double) getWidth()) * 1.0d) / ((double) getHeight())) {
int h2 = (getWidth() * this.f1h) / this.f4w;
GLES20.glViewport(0, (getHeight() - h2) / 2, getWidth(), h2);
} else {
int w2 = (getHeight() * this.f4w) / this.f1h;
GLES20.glViewport((getWidth() - w2) / 2, 0, w2, getHeight());
}
this.shcopy.use();
this.shcopy.tex("s", this.fb.tex());
this.quad.draw();
}
public void onSurfaceChanged(GL10 _gl, int width, int height) {
}
int genTexture() {
int[] tt = new int[1];
GLES20.glGenTextures(1, tt, 0);
return tt[0];
}
public void onSurfaceCreated(GL10 _gl, EGLConfig config) {
this.fa = new Framebuffer();
this.fb = new Framebuffer();
this.shconv = new Shader(getContext(), R.raw.flip, R.raw.conv);
this.shflip = new Shader(getContext(), R.raw.flip, R.raw.copy);
this.shblur = new Shader(getContext(), R.raw.btex, R.raw.blur);
this.shfina = new Shader(getContext(), R.raw.quad, R.raw.fina);
this.shcopy = new Shader(getContext(), R.raw.quad, R.raw.copy);
this.cameraTexture = genTexture();
this.cameraSurface = new SurfaceTexture(this.cameraTexture);
this.bitmaptexture = genTexture();
this.created = true;
this.doloadbitmap = true;
}
public void createCamera(int mReqCameraId) {
Log.i(TAG, "createCamera");
requestRender();
if (this.camera == null) {
try {
if (mReqCameraId == Camera.CameraInfo.CAMERA_FACING_BACK) {
isFrontFacing = false;
} else {
isFrontFacing = true;
}
this.camera = Camera.open(mReqCameraId);
/*if(Share.back_camera){
this.camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
}else{
this.camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
}*/
Parameters params = this.camera.getParameters();
params.setRecordingHint(true);
if (params.getSupportedFocusModes().contains("continuous-picture")) {
params.setFocusMode("continuous-picture");
}
Size best = null;
for (Size s : params.getSupportedPreviewSizes()) {
if (best == null || s.width * s.height < best.width * best.height) {
best = s;
}
}
if (best != null) {
Log.i("Size", best.width + " " + best.height);
params.setPreviewSize(best.width, best.height);
}
this.camera.setParameters(params);
this.camera.startPreview();
setRenderMode(1);
} catch (final Throwable ex) {
((Activity) getContext()).runOnUiThread(new Runnable() {
class C01341 implements OnClickListener {
C01341() {
}
public void onClick(DialogInterface arg0, int arg1) {
CameraView.this.createCamera(0);
}
#Override
public void onClick(View v) {
}
}
/* renamed from: camera.tiltshift.CameraView$1$2 */
class C01352 implements OnClickListener {
C01352() {
}
public void onClick(DialogInterface arg0, int arg1) {
throw new RuntimeException(ex);
}
#Override
public void onClick(View v) {
}
}
public void run() {
}
});
}
}
}
void destroyCamera() {
Log.i("CameraView", "destroyCamera");
if (this.camera != null) {
this.camera.stopPreview();
this.camera.release();
}
this.camera = null;
setRenderMode(0);
requestRender();
}
public void setBitmap(Bitmap b) {
this.bitmap0 = b;
if (b != null && this.bresize && (((long) b.getWidth()) > maxsize || ((long) b.getHeight()) > maxsize)) {
long mx = (long) Math.max(b.getWidth(), b.getHeight());
b = createScaledBitmap2(b, (int) ((((long) b.getWidth()) * maxsize) / mx), (int) ((((long) b.getHeight()) * maxsize) / mx), true);
}
this.bitmap = b;
this.doloadbitmap = true;
requestRender();
}
static Bitmap createScaledBitmap2(Bitmap src, int dstWidth, int dstHeight, boolean filter) {
Log.i("createScaledBitmap2", dstWidth + " " + dstHeight);
Matrix m = new Matrix();
m.setScale(((float) dstWidth) / ((float) src.getWidth()), ((float) dstHeight) / ((float) src.getHeight()));
Bitmap result = Bitmap.createBitmap(dstWidth, dstHeight, Config.ARGB_8888);
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setFilterBitmap(filter);
canvas.drawBitmap(src, m, paint);
return result;
}
void loadbitmap() {
Bitmap b = this.bitmap;
if (b != null && this.created) {
GLES20.glBindTexture(3553, this.bitmaptexture);
GLES20.glTexParameteri(3553, 10241, 9728);
GLES20.glTexParameteri(3553, 10240, 9728);
GLES20.glTexParameteri(3553, 10242, 33071);
GLES20.glTexParameteri(3553, 10243, 33071);
GLUtils.texImage2D(3553, 0, b, 0);
this.doloadbitmap = false;
}
}
}

Raytracing: Dark rings appear

I am getting strange rings of black on my spheres when I render with lighting. I just added lighting and I cannot figure out why the black rings are being created.
Here is my code for my tracer.
public class Tracer {
public Camera Cam;
public int Width, Height;
public BufferedImage Image;
public Color BackGroundColor;
public int StartX, StartY, EndX, EndY,RowCount,ColCount;
public ArrayList<GeometricObject> GeoObjects;
public ArrayList<LightObject> LightObjects;
public boolean Tracing;
public double AmbientLight;
public Tracer(Camera cam, int width, int height, BufferedImage image, Color backGroundColor, int startX, int startY, int endX, int endY, int rowCount, int colCount, ArrayList<GeometricObject> Geoobjects,ArrayList<LightObject> Lightobjects,double ambientLight) {
super();
Cam = cam;
Width = width;
Height = height;
Image = image;
BackGroundColor = backGroundColor;
StartX = startX;
StartY = startY;
EndX = endX;
EndY = endY;
RowCount = rowCount;
ColCount = colCount;
GeoObjects = Geoobjects;
LightObjects = Lightobjects;
if(ambientLight > 1){
AmbientLight = 1;
}else if(ambientLight < 0){
AmbientLight = 0;
}else{
AmbientLight = ambientLight;
}
}
public void TracePixelFast(int x, int y) {
Color color = new Color(BackGroundColor.r,BackGroundColor.g,BackGroundColor.b);
for(int o = 0;o < GeoObjects.size();o++){
GeometricObject GO = GeoObjects.get(o);
Ray r = new Ray(Cam.GetRayPos(Width, Height, x, y, 1, 1, RowCount, ColCount), Cam.GetRayDir(Width, Height, x, y, 1,1, RowCount, ColCount));
double hit = GO.hit(r);
if (hit != 0.0) {
color = Cal_Pixel(x,y);
Image.setRGB(x, y, color.toInt());
break;
}
}
}
public void TracePixelSmooth(int x, int y) {
Image.setRGB(x, y,Cal_Pixel(x,y).toInt());
}
public Color Cal_Pixel(int x,int y){
Color color = new Color(BackGroundColor);
Color colorh = new Color(BackGroundColor);
Color bgc = new Color(BackGroundColor);
int HIT = 0;
int MISS = 0;
for (int row = 0; row < RowCount; row++) {
for (int col = 0; col < ColCount; col++) {
double min = Double.MAX_VALUE;
for (int o = 0; o < GeoObjects.size(); o++) {
GeometricObject GO = GeoObjects.get(o);
Ray r = new Ray(Cam.GetRayPos(Width, Height, x, y, row, col, RowCount, ColCount),Cam.GetRayDir(Width, Height, x, y, row, col, RowCount, ColCount));
double hit = GO.hit(r);
if (hit != 0.0 && hit < min) {
min = hit;
colorh = ShadePixel(GO, r, hit);
HIT++;
} else {
double min2 = Double.MAX_VALUE;
for (int o2 = 0; o2 < GeoObjects.size(); o2++) {
if(o!=o2){
GeometricObject GO2 = GeoObjects.get(o2);
double hit2 = GO2.hit(r);
if (hit2 != 0.0 && hit2 < min2) {
min2 = hit2;
bgc = ShadePixel(GO2, r, hit2);
}
}
}
MISS++;
}
}
}
}
for(int h = 0;h < HIT;h++){
color.Add(colorh);
}
for(int m = 0;m < MISS;m++){
color.Add(bgc);
}
color.Divide(RowCount * ColCount);
return color;
}
public Color ShadePixel(GeometricObject GO,Ray ray,double t){
ArrayList<Color> PixelShade = new ArrayList<Color>();
Normal normal = GO.Cal_Normal(ray, t);
for(int l = 0;l < LightObjects.size();l++){
LightObject light = LightObjects.get(l);
Vector3D r_Dir = light.Pos.Sub(normal.Origin);
r_Dir.normalize();
Ray raytolight = new Ray(normal.Origin,r_Dir);
int WAS_HIT = 0;
for(int o = 0;o < GeoObjects.size();o++){
GeometricObject NGO = GeoObjects.get(o);
double hit = NGO.hit(raytolight);
if (hit != 0.0) {
WAS_HIT = 1;
}
}
if(WAS_HIT == 0){
double Dot = normal.Direction.Dot(r_Dir);
if(Dot < 0){
Dot = 0;
}
double Diffuse = 1 - AmbientLight;
Color color = new Color(GO.Color);
double Shade = AmbientLight + Diffuse*Dot;
color.Mul(Shade);
PixelShade.add(color);
}else{
Color color = new Color(GO.Color);
double Shade = AmbientLight;
color.Mul(Shade);
PixelShade.add(color);
}
}
Color Final = new Color();
for(int s = 0;s < PixelShade.size();s++){
Final.Add(PixelShade.get(s));
}
Final.Divide(PixelShade.size());
return Final;
}
public void TraceArea(boolean SmoothTracing) {
Tracing = true;
if(SmoothTracing){
for (int x = StartX; x < EndX; x++) {
for (int y = StartY; y < EndY; y++) {
TracePixelSmooth(x,y);
}
}
}else{
for (int x = StartX; x < EndX; x++) {
for (int y = StartY; y < EndY; y++) {
TracePixelFast(x,y);
}
}
}
}
}
And here is the code for the sphere.
public class Sphere extends GeometricObject{
public Vector3D Center;
public double Radius;
public Sphere(Vector3D Center,double Radius,Color Color){
this.Center = Center;
this.Radius = Radius;
this.Color = Color;
}
public double hit(Ray ray) {
double a = ray.Direction.Dot(ray.Direction);
double b = 2 * ray.Origin.Sub(Center).Dot(ray.Direction);
double c = ray.Origin.Sub(Center).Dot(ray.Origin.Sub(Center))-Radius*Radius;
double discreminant = b*b-4*a*c;
if(discreminant < 0.0f){
return 0.0;
}else{
double t = (-b - Math.sqrt(discreminant))/(2*a);
if(t > 10E-9){
return t;
}else{
return 0.0;
}
}
}
public Normal Cal_Normal(Ray ray,double t) {
Vector3D NPos = new Vector3D(ray.Origin.x + ray.Direction.x*t,ray.Origin.y + ray.Direction.y*t,ray.Origin.z + ray.Direction.z*t);
Vector3D NDir = NPos.Sub(Center).Div(Radius);
return new Normal(NPos,NDir);
}
}
I am sure the problem is in shadepixel() but I could be wrong.
I just found out that the more objects that I add the more rings there are:
1 object no rings.
2 objects 1 ring.
3 objects 2 rings.
If you need me to post more of my code.Just ask and I will.
When I get back from school I will post my color class and fix the color problem. I still do not understand why the more objects (spheres) I add, the more rings there are. Can anyone explain to me why this is happening?
Here is my Color code.
public class Color {
public float r,g,b;
public Color(){
r = 0.0f;
g = 0.0f;
b = 0.0f;
}
public Color(float fr,float fg,float fb){
r = fr;
g = fg;
b = fb;
}
public Color(Color color){
r = color.r;
g = color.g;
b = color.b;
}
public void Add(Color color){
r += color.r;
g += color.g;
b += color.b;
}
public void Divide(int scalar){
r /= scalar;
g /= scalar;
b /= scalar;
}
public void Mul(double mul){
r *= mul;
g *= mul;
b *= mul;
}
public int toInt(){
return (int) (r*255)<<16 | (int) (g*255)<<8 | (int) (b*255);
}
There are multiple issues with this code, but the direct reason for the rings is that color component values are overflowing 0-255 range. This in turn is caused by incorrect calculations in what I take to be an attempt at antialiasing in Cal_Pixel(), as well as by no control whatsoever of numeric range in ShadePixel().
Think about how you can visually debug this scene.
First are the normals correct? Display them as the colour to see.
Taking the range for each component [-1..1] to the range [0..255]:
r = 255*(n.x + 1)/2;
g = 255*(n.y + 1)/2;
b = 255*(n.z + 1)/2;
Once you think they look correct move on to the next stage and build it up stage by stage.
e.g. you might look at if your dot product is as expected (again [-1..1] because the vectors are supposedly normalised):
r = 255*(dot + 1)/2;
g = 255*(dot + 1)/2;
b = 255*(dot + 1)/2;

elastic collision of balls

i am having a bug which i can't figure out.I tried many times,the collision detection and calculating new velocities seems fine ,but some balls seem to stuck with each other i don't why.Can you please help me out.
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.Random;
import javax.swing.JFrame;
public class ElasticCollision extends Canvas implements Runnable {
private static final int WIDTH = 300;
private static final int HEIGHT = WIDTH / 16 * 9;
private static final int SCALE = 3;
private static final String TITLE = "Elastic collision";
private boolean running = false;
private JFrame frame;
private Thread thread;
private Random random = new Random();
private Color color;
private int a, b, c;
private Ball[] ball;
private int x = 0, y = 0;
private int radius = 0;
private int speedX = 0, speedY = 0;
private int noOfBalls = 25;
private double newVelX1 = 0, newVelY1 = 0;
private double newVelX2 = 0, newVelY2 = 0;
private double angle1 = 0, angle2 = 0, angle3 = 0;
private int x1 = 0, y1 = 0, x2 = 0, y2 = 0;
public ElasticCollision() {
Dimension size = new Dimension(WIDTH * SCALE, HEIGHT * SCALE);
setPreferredSize(size);
frame = new JFrame();
ball = new Ball[noOfBalls];
}
public void start() {
for (int i = 0; i < noOfBalls; i++) {
x = random.nextInt(getWidth());
y = random.nextInt(getHeight());
radius = 25 + random.nextInt(25);
speedX = 1 + random.nextInt(2);
speedY = 1 + random.nextInt(2);
ball[i] = new Ball(x, y, radius, speedX, speedY);
}
running = true;
thread = new Thread(this);
thread.start();
}
public void stop() {
running = false;
}
public void run() {
long lastTime = System.nanoTime();
double unprocessed = 0;
double nsPerTick = 1000000000.0 / 60;
int frames = 0;
int ticks = 0;
long lastTimer = System.currentTimeMillis();
while (running) {
long now = System.nanoTime();
unprocessed += (now - lastTime) / nsPerTick;
lastTime = now;
while (unprocessed >= 1) {
ticks++;
update();
unprocessed -= 1;
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < noOfBalls; i++) {
for (int j = i + 1; j < noOfBalls; j++) {
if (ball[i].inCollision != true
|| ball[j].inCollision != true)
checkCollision(ball[i], ball[j]);
}
}
frames++;
render();
if (System.currentTimeMillis() - lastTimer > 1000) {
lastTimer += 1000;
frame.setTitle(TITLE + " | " + ticks + " ticks, " + frames
+ " fps");
frames = 0;
ticks = 0;
}
}
stop();
}
public void update() {
for (int i = 0; i < noOfBalls; i++) {
ball[i].x += ball[i].speedX;
ball[i].y += ball[i].speedY;
if (ball[i].x >= getWidth() - ball[i].radius && ball[i].speedX > 0)
ball[i].speedX = -ball[i].speedX;
if (ball[i].x <= ball[i].radius && ball[i].speedX < 0)
ball[i].speedX = -ball[i].speedX;
if (ball[i].y >= getHeight() - ball[i].radius && ball[i].speedY > 0)
ball[i].speedY = -ball[i].speedY;
if (ball[i].y <= ball[i].radius && ball[i].speedY < 0)
ball[i].speedY = -ball[i].speedY;
}
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.yellow);
g.fillRect(0, 0, getWidth(), getHeight());
for (int i = 0; i < noOfBalls; i++)
ball[i].paint(g);
g.dispose();
bs.show();
}
public void checkCollision(Ball ball1, Ball ball2) {
double distance;
if (ball1.x + ball1.radius + ball2.radius > ball2.x
&& ball1.x < ball1.x + ball1.radius + ball2.radius
&& ball1.y + ball1.radius + ball2.radius > ball2.y
&& ball1.y < ball2.y + ball1.radius + ball2.radius) {
distance = Math.sqrt(((ball1.x - ball2.x) * (ball1.x - ball2.x))
+ ((ball1.y - ball2.y) * (ball1.y - ball2.y)));
if ((int) distance < ball1.radius + ball2.radius) {
ball1.collision = true;
ball2.collision = true;
ball1.inCollision = true;
ball2.inCollision = true;
ball1.collisionX = ((ball1.x * ball2.radius) + (ball2.x * ball1.radius))
/ (ball1.radius + ball2.radius) + ball1.radius;
ball1.collisionY = ((ball1.y * ball2.radius) + (ball2.y * ball1.radius))
/ (ball1.radius + ball2.radius) + ball1.radius;
ball2.collisionX = ((ball1.x * ball2.radius) + (ball2.x * ball1.radius))
/ (ball1.radius + ball2.radius) + ball2.radius;
ball2.collisionY =
((ball1.y * ball2.radius) + (ball2.y * ball1.radius))
/ (ball1.radius + ball2.radius) + ball2.radius;
/*
* x1 = (ball1.x - getWidth()) / 2; y1 = (ball2.y - getHeight())
* / 2; angle1 = Math.toDegrees(Math.atan2(y1, x1));
*
* x2 = (ball1.x - getWidth()) / 2; y2 = (ball2.y - getHeight())
* / 2; angle2 = Math.toDegrees(Math.atan2(y2, x2));
*/
double colision_angle = Math.toDegrees(Math.atan2(
(ball2.y - ball1.y), (ball2.x - ball1.x)));
double speed1 = Math.sqrt(ball1.speedX * ball1.speedX
+ ball1.speedY * ball1.speedY);
double speed2 = Math.sqrt(ball2.speedX * ball2.speedX
+ ball2.speedY * ball2.speedY);
double direction1 = Math.atan2(ball1.speedY, ball1.speedX);
double direction2 = Math.atan2(ball2.speedY, ball2.speedX);
double vx_1 = speed1 * Math.cos(direction1 - colision_angle);
double vy_1 = speed1 * Math.sin(direction1 - colision_angle);
double vx_2 = speed2 * Math.cos(direction2 - colision_angle);
double vy_2 = speed2 * Math.sin(direction2 - colision_angle);
double final_vx_1 = ((ball1.radius - ball2.radius) * vx_1 + (ball2.radius + ball2.radius)
* vx_2)
/ (ball1.radius + ball2.radius);
double final_vx_2 = ((ball1.radius + ball1.radius) * vx_1 + (ball2.radius - ball1.radius)
* vx_2)
/ (ball1.radius + ball2.radius);
double final_vy_1 = vy_1;
double final_vy_2 = vy_2;
newVelX1 = (int) (Math.cos(colision_angle) * final_vx_1 + Math
.cos(colision_angle + Math.PI / 2) * final_vy_1);
newVelY1 = (int) (Math.sin(colision_angle) * final_vx_1 + Math
.sin(colision_angle + Math.PI / 2) * final_vy_1);
newVelX2 = (int) (Math.cos(colision_angle) * final_vx_2 + Math
.cos(colision_angle + Math.PI / 2) * final_vy_2);
newVelY2 = (int) (Math.sin(colision_angle) * final_vx_2 + Math
.sin(colision_angle + Math.PI / 2) * final_vy_2);
ball1.speedX = (int) newVelX1;
ball1.speedY = (int) newVelY1;
ball2.speedX = (int) newVelX2;
ball2.speedY = (int) newVelY2;
ball1.x = ball1.x + (int) newVelX1;
ball1.y = ball1.y + (int) newVelY1;
ball2.x = ball2.x + (int) newVelX2;
ball2.y = ball2.y + (int) newVelY2;
}
}
}
public static void main(String[] args) {
ElasticCollision balls = new ElasticCollision();
balls.frame.setResizable(false);
balls.frame.add(balls);
balls.frame.pack();
balls.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
balls.frame.setVisible(true);
balls.start();
}
}
class Ball {
protected int x = 0, y = 0;
protected int radius;
protected int speedX = 0, speedY = 0;
protected boolean collision = false;
protected int collisionX = 0, collisionY = 0;
protected boolean inCollision = false;
public Ball(int x, int y, int radius, int speedX, int speedY) {
this.x = x + radius;
this.y = y + radius;
this.radius = radius;
this.speedX = speedX;
this.speedY = speedY;
}
public void paint(Graphics g) {
if (!collision) {
g.setColor(Color.red);
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
} else {
g.setColor(Color.green);
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
g.setColor(Color.blue);
g.fillOval(collisionX - radius, collisionY - radius, 20, 20);
g.setColor(Color.black);
g.drawOval(collisionX - radius, collisionY - radius, 20, 20);
collision = false;
inCollision = false;
}
g.setColor(Color.black);
g.drawOval(x - radius, y - radius, radius * 2, radius * 2);
}
}
My guess is that your logic doesn't let the balls move apart once the collision is detected. Only change the direction of movement once and not every instant the balls are close to one another.

Restarting millis in processing error

Having a massive problem with this piece of code. I'm working with Java in processing.
I've created a game where users must guide a character away from objects.
All the objects, health system and score system are based on mills().
Once the game ends we need to reset millis(), resetting the objects, score and health system.
I have searched implemented advice from friends and previously asked questions on here but the advice differs very slightly. I'm assuming it's something that I can't see.
I would really appreciate your help with this, I only ever use this site as a last resort not just when I'm feeling lazy.
//these are used to set the times which the games increases difficulty
//int timeDelay = 30000;
int delayOne = 2000;
int delayTwo = 5000;
int delayThree = 80000;
int delayFour = 90000;
int display = 2000;
//for collisions
float[] xpos = new float[6];
float[] ypos = new float[6];
//timer counts how many millis() each game lasts for
int timeStamp = 5000;
int timer;
int timer2 = millis() - timer;
//always at zero
//outputting score at the end of a game
int score;
int start;
//trying to get lives working
boolean lost = false;
//variable to store & output gale force when giving score
int Gale = 0;
//Changing length rectangle
float rX = 350.0;
float x1 = 20;
float y1 = 20;
float w1 = 100;
float h1 = 30;
//DECLARE OBJECTS JELLY CLASS
Jelly myObject;
Jelly myObject1;
Jelly myObject2;
Jelly myObject3;
//GENTLEMAN CLASS
gentleMan mygentleMan;
//LOLLY CLASS
Lolly myCow;
Lolly myCow1;
//PImages
PImage loader;
PImage bg;
PImage uh;
PImage bg1;
PImage bolt;
PImage over;
void setup()
{
bg=loadImage("backy1.png");
bg1 = loadImage("backy.png");
over = loadImage("over.png");
PFont L = loadFont("Lobster1.3-48.vlw");
textFont( L, 16);
size(400, 600);
smooth();
//begin = millis();
imageMode(CENTER);
//INITIALISE
myObject = new Jelly(320, 500);
myObject1 = new Jelly(150, 200);
// myObject2 = new Jelly(550, 500);
//myObject3 = new Jelly(300, 100);
mygentleMan = new gentleMan(200, 300);
//myObject.run();
//myObject1.run();
//myObject2.run();
myCow = new Lolly(400, 250);
myCow1 = new Lolly(150, 350);
timer = millis();
}
void draw()
{
start = 0;
//because we have image mode set to center for collisions
//we have to divide the height & width of the screen by 2 for hte image to fit
image(bg, 200, 300);
if (millis() >= start + delayOne)
{
image(bg1, 200, 300);
}
//CALL FUNCTIONALITY
myObject.run();
myObject.put_in_array(0);
myObject1.run(); // this one is going top to bottom
myObject1.put_in_array(1);
// myObject2.run();
//myObject2.put_in_array(2);
// myObject3.run();
//myObject3.put_in_array(3);
myCow.run();
myCow.put_in_array(4);
myCow1.run();
myCow1.put_in_array(5);
mygentleMan.run();
//health bar
fill(161, 221, 16);
noStroke();
rect(10, 24, rX, 10);
if(rX <= 100)
{
fill(221, 59, 16);
rect(10, 24, rX, 10);
}
else
if(rX <= 200)
{
fill(221, 137, 16);
rect(10, 24, rX, 10);
}
if(rX == 5.0)
{
lost = true;
noLoop();
// lives = lives - 1;
image(over, width/2, height/3);
fill(255);
text("Your Score Is: " + timer, width/2.7, height/2);
text("Gale Force Is; " + Gale, width/2.7, height/1.8);
score = timer;
}
//For Loop detecting collisions between mygentleMan & objects
for (int i=0; i < 6; i++) {
if (xpos[i] > 150 && xpos[i] < 250 && ypos[i] > (mygentleMan.y-58) && ypos[i] < (mygentleMan.y+58))
{
// text("collision", 200, 300);
bolt = loadImage("bolt.png");
image(bolt, xpos[i], ypos[i]);
rX = rX - 1;
}
//outputting score on screen # at all times
fill(255);
text("Score: " + timer, 320, 20);
}
//timer which will be score counter essentially
timer = millis();
//text(timer, 20, 20);
//moving the man up the screen if button is pressed, if not he levitates downward
if (keyPressed)
{
mygentleMan.y -= mygentleMan.moveY;
mygentleMan.moveY += 0.4;
}
else
{
mygentleMan.y += mygentleMan.moveY;
mygentleMan.moveY += 0.2;
}
fill(255);
text("Health", 20, 20);
if(mousePressed)
{
if(timer2 > timeStamp)
{
println("tit");
mygentleMan.y = height/2;
loop();
}
}
}
//class for first objects that move into the screen
class Jelly
{
//GLOBAL VARIABLES
float x = 0;
float y = 0;
float speedX = 1.8;
float speedY = 1.8;
float speedX2 = 2.1;
float speedY2 = 2.1;
float speedX3 = 2.2;
float speedY3 = 2.2;
PImage jelly = loadImage("jelly.png");
PImage hat = loadImage("hat.png");
PImage gale = loadImage("g1.png");
PImage force = loadImage("force.png");
PImage news = loadImage("news.png");
//CONSTRUCTOR
Jelly(float _x, float _y)
{
x = _x;
y = _y;
}
//FUNCTIONS
void run()
{
display();
move();
bounce();
image(force, 330, 550);
if (millis() >= start + delayOne)
{
display();
moveFast();
bounceFast();
image(gale, 280, 560);
Gale = 1;
if (start + delayOne + display >= millis())
{
image(news, 200, 300);
}
}
if (millis() >= start +delayTwo)
{
display();
moveFaster();
bounceFaster();
image(gale, 310, 560);
Gale = 2;
if (start + delayTwo + display >= millis())
{
image(news, 200, 300);
}
}
}
void bounce()
{
if ( x > width)
{
speedX = speedX * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX = speedX * -1;
}
if ( y > height)
{
speedY = speedY * -1;
}
if ( y < 0)
{
speedY = speedY * -1;
}
}
void bounceFast()
{
if ( x > width)
{
speedX2 = speedX2 * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX2 = speedX2 * -1;
}
if ( y > height)
{
speedY2 = speedY2 * -1;
}
if ( y < 0)
{
speedY2 = speedY2 * -1;
}
}
void bounceFaster()
{
if ( x > width)
{
speedX3 = speedX3 * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX3 = speedX3 * -1;
}
if ( y > height)
{
speedY3 = speedY3 * -1;
}
if ( y < 0)
{
speedY3 = speedY3 * -1;
}
}
void move()
{
x = x + speedX;
y = y + speedY;
}
void moveFast()
{
x = x + speedX2;
y = y + speedY2;
}
void moveFaster()
{
x = x + speedX3;
y = y + speedY3;
}
void put_in_array(int a)
{
xpos[a] = x;
ypos[a] = y;
}
void display()
{
image(hat, x, y);
}
}
//class for gentleman that floats
class gentleMan
{
//GLOBAL VARIABLES
float y = 400;
float x = 400;
float moveY;
//PImage umbrella;
PImage umbrella = loadImage("dafuq.png");
PImage over = loadImage("over.png");
//CONSTRCUTOR --- PIECES OF INFO PROVDE TO BUILD CLASS -- INTIIALIZE VARIBALE
gentleMan(float _x, float _y)
{
y = _y;
x = _x;
moveY = 2;
}
//FUNCTIONS
void run()
{
display();
keyReleased();
bounce();
// collision();
}
void display()
{
image(umbrella, x, y);
}
void keyReleased()
{
mygentleMan.moveY = 4;
}
void bounce()
{
if ( y < 0)
{
y = 0;
}
if (y > height)
{
//score = millis();
lost = true;
noLoop();
// lives = lives - 1;
image(over, width/2, height/3);
text("Your Score Is: " + timer, width/2.7, height/2);
text("Gale Force Is; " + Gale, width/2.7, height/1.8);
}
}
}
class Lolly
{
//GLOBAL VARIABLES
float x = 0;
float y = 0;
float speedX = 2;
float speedY = 2;
float speedX1 = 2.1;
float speedY1 = 2.1;
float speedX2 = 2.3;
float speedY2 = 2.3;
PImage cow = loadImage("cow.png");
//CONSTRUCTOR
Lolly(float _x, float _y)
{
x = _x;
y = _y;
}
//FUNCTIONS
void run()
{
// display();
//move();
//bounce();
if (millis() >= start + delayThree)
{
display();
moveFast();
bounceFast();
}
if (millis() >= start +delayFour)
{
display();
moveFaster();
bounceFaster();
}
}
void put_in_array(int a)
{
xpos[a] = x;
ypos[a] = y;
}
void bounce()
{
if ( x > width)
{
speedX = speedX * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX = speedX * -1;
}
if ( y > height)
{
speedY = speedY * -1;
}
if ( y < 0)
{
speedY = speedY * -1;
}
}
void bounceFast()
{
if ( x > width)
{
speedX1 = speedX1 * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX1 = speedX1 * -1;
}
if ( y > height)
{
speedY1 = speedY1 * -1;
}
if ( y < 0)
{
speedY1 = speedY1 * -1;
}
}
void bounceFaster()
{
if ( x > width)
{
speedX2 = speedX2 * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX2 = speedX2 * -1;
}
if ( y > height)
{
speedY2 = speedY2 * -1;
}
if ( y < 0)
{
speedY2 = speedY2 * -1;
}
}
void move()
{
x = x + speedX;
y = y + speedY;
}
void moveFast()
{
x = x + speedX1;
y = y + speedY1;
}
void moveFaster()
{
x = x + speedX2;
y = y + speedY2;
}
void display()
{
image(cow, x, y);
}
}//end of cow class
void mousePressed()
{
}
Your question is not at all clear, but it sounds like you should be able to wrap System.currentTimeMillis() in an object that maintains a starting point and returns the offset. Something like
public class Millis
{
long start;
public Millis() { this.reset(); }
public void reset() { this.start = System.currentTimeMillis(); }
public long getMillis() { return System.currentTimeMillis() - start; }
}
You create an instance of this class at startup
Millis timer = new Millis();
then call reset() to set it back to zero at the beginning of each game. Everywhere in your code you currently have millis() you would have timer.getMillis()
Use a custom timer class
class Timer {
int savedTime; // When Timer started
int totalTime; // How long Timer should last
Timer(int tempTotalTime) {
totalTime = tempTotalTime;
}
// Starting the timer
void start() {
// When the timer starts it stores the current time in milliseconds.
savedTime = millis();
}
// The function isFinished() returns true if 5,000 ms have passed.
// The work of the timer is farmed out to this method.
boolean isFinished() {
// Check how much time has passed
int passedTime = millis()- savedTime;
if (passedTime > totalTime) {
return true;
} else {
return false;
}
}
}//end class
Then to call
firstTimer = new Timer(50000);
And then in the draw to check
if (firstTimer.isFinished()) {
//do sopemthing
//then restart timer
firstTimer.start();
}
else
{
// do soemthing else for the rest of the time....
}

java graphics gouraud shading

I want to fill triangles with gouraud shading
I calculated normals for each vertex and used the following code but it dosn't work correctly
I interpolated colors against y using these formulas
Ir = Ir2 - (Ir2 - Ir1)* (v2.y -y)/dy;
Ig = Ig2 - (Ig2 - Ig1)* (v2.y -y)/dy;
Ib = Ib2 - (Ib2 - Ib1)* (v2.y -y)/dy;
and against x direction using
rr = r2- (r2-r1)*(Xs2-j)/dxs;
in method drawCurrentTriangle(Graphics2D g) how can i calculate color from interpolated vertex normal.(there is no lights in the scene (only triangle color))
public boolean convert(Triangle triangle) {
ensureCapacity();
clearCurrentScan();
triangle.getVlist()[0].r = triangle.normals[0].x;
triangle.getVlist()[0].g = triangle.normals[0].y;
triangle.getVlist()[0].b = triangle.normals[0].z;
triangle.getVlist()[1].r = triangle.normals[1].x;
triangle.getVlist()[1].g = triangle.normals[1].y;
triangle.getVlist()[1].b = triangle.normals[1].z;
triangle.getVlist()[2].r = triangle.normals[2].x;
triangle.getVlist()[2].g = triangle.normals[2].y;
triangle.getVlist()[2].b = triangle.normals[2].z;
for (int i = 0; i < 3; i++) {
Vector3d v1 = triangle.getVlist()[i];
Vector3d v2;
if (i == 2) {
v2 = triangle.getVlist()[0];
} else {
v2 = triangle.getVlist()[i + 1];
}
// ensure v1.y < v2.y
if (v1.y > v2.y) {
Vector3d temp = v1;
v1 = v2;
v2 = temp;
}
double dy = v2.y - v1.y;
Ir1 = v1.r;
Ig1 = v1.g;
Ib1 = v1.b;
Ir2 = v2.r;
Ig2 = v2.g;
Ib2 = v2.b;
// ignore horizontal lines
if (dy == 0) {
continue;
}
int startY = Math.max(FastMath.ceil(v1.y), minY);
int endY = Math.min(FastMath.ceil(v2.y) - 1, maxY);
top = Math.min(top, startY);
bottom = Math.max(bottom, endY);
double dx = v2.x - v1.x;
double Ir;
double Ig;
double Ib;
double Ic;
double Ia;
double Yc;
// special case: vertical line
if (dx == 0) {
int x = FastMath.ceil(v1.x);
// ensure x within view bounds
x = Math.min(maxX + 1, Math.max(x, minX));
for (int y = startY; y <= endY; y++) {
Ir = Ir2 - (Ir2 - Ir1)* (v2.y -y)/dy;
Ig = Ig2 - (Ig2 - Ig1)* (v2.y -y)/dy;
Ib = Ib2 - (Ib2 - Ib1)* (v2.y -y)/dy;
scans[y].setBoundary(x, Ir, Ig, Ib);
}
} else {
// scan-convert this edge (line equation)
double gradient = dx / dy;
// (slower version)
for (int y = startY; y <= endY; y++) {
int x = FastMath.ceil(v1.x + (y - v1.y) * gradient);
// ensure x within view bounds
x = Math.min(maxX + 1, Math.max(x, minX));
Ir = Ir2 - (Ir2 - Ir1)* (v2.y -y)/dy;
Ig = Ig2 - (Ig2 - Ig1)* (v2.y -y)/dy;
Ib = Ib2 - (Ib2 - Ib1)* (v2.y -y)/dy;
scans[y].setBoundary(x, Ir, Ig, Ib);
}
// check if visible (any valid scans)
for (int i = top; i <= bottom; i++) {
if (scans[i].isValid()) {
return true;
}
}
return false;
}
}
}
protected void drawCurrentTriangle(Graphics2D g) {
int y = scanConverter.getTopBoundary();
double Xs1 = 0;
double Xs2 = 0;
double dxs = 0;
double r1 = 0;
double g1 = 0;
double b1 = 0;
double r2 = 0;
double g2 = 0;
double b2 = 0;
double rr = 0;
double gg = 0;
double bb = 0;
while (y <= scanConverter.getBottomBoundary()) {
GouraudTriangleScanConverter.Scan scan = scanConverter.getScan(y);
if (scan.isValid()) {
r1 = scan.rL;
g1 = scan.gL;
b1 = scan.bL;
r2 = scan.rR;
g2 = scan.gR;
b2 = scan.bR;
Xs1 = scan.left;
Xs2 = scan.right;
dxs = Xs2-Xs1;
for (int j = scan.left; j < scan.right; j++) {
rr = r2- (r2-r1)*(Xs2-j)/dxs;
gg = g2- (g2-g1)*(Xs2-j)/dxs;
bb = b2- (b2-b1)*(Xs2-j)/dxs;
if(rr > 255) rr = 255;
if(gg > 255) gg = 255;
if(bb > 255) bb = 255;
g.setColor(new Color((int)rr, (int)gg, (int)bb));
g.drawLine(j,y,j,y);
}
//g.drawLine(scan.right,y,scan.right,y);
}
y++;
}
}
public static class Scan {
public int left;
public int right;
public double rL = -1;
public double gL = -1;
public double bL = -1;
public double rR = -1;
public double gR = -1;
public double bR = -1;
/**
* Sets the left and right boundary for this scan if
* the x value is outside the current boundary.
*/
public void setBoundary(int x, double r, double g, double b) {
if (x > max)
max = x;
if (x < left) {
left = x;
rL = r;
gL = g;
bL = b;
}
if (x - 1 > right) {
right = x - 1;
rR = r;
gR = g;
bR = b;
}
}
/**
* Determines if this scan is valid (if left <= right).
*/
public boolean isValid() {
return (left <= right);
}
}
how can i apply colors to mesh.when i in
fix colors(no lighting)

Categories

Resources