-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRenderingPanel.java
More file actions
516 lines (463 loc) · 21.4 KB
/
RenderingPanel.java
File metadata and controls
516 lines (463 loc) · 21.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
import javax.swing.JPanel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.awt.Color;
import java.awt.Point;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
//a versatile and reletively fast 3d renderer.
public class RenderingPanel extends JPanel implements Runnable
{
//collection of all the objects that the rendering panel will render
private ArrayList<Mesh> meshes = new ArrayList<Mesh>();
private ArrayList<Triangle> triangles = new ArrayList<Triangle>();
//for rendering:
private BufferedImage renderImage; //the buffered image that triangles are drawn on
private Color backgroundColor;
private Plane renderPlane; //the plane that triangles are project to in 3d
private int[] blankImagePixelColorData; //pixel data of a blank buffered image
private ArrayList<Triangle2D> drawQeue; //the qeue of 2d triangles about to be passed to sorting
private Matrix3x3 pointRotationMatrix; //the rotation matrix for rotating points onto the xy plane
private double pixelsPerUnit; //number of pixels per unit of 3d space based on fov
private double renderPlaneWidth; //width of the render plane
private Vector3 camCenterPoint; //center of the camera on the render plane.
//Threads:
private Thread renderingThread;
private boolean threadRunning;
private int fps;
private long lastFrameTime;
//Camera:
private Camera camera;
private Vector3 camDirection; //normalized vector representing the orientation of the camera
private Vector3 camPos;
//lighting:
private Lighting lightingObject;
//fog:
private double fogStartDistance;
private double fullFogDistance; //distance at which fog is at it's full thickness
private boolean fogEnabled = false;
private Color fogColor;
//constructs a rendering panel object with the specified width and height
//this is necessary because of the buffered image
public RenderingPanel(int width, int height)
{
setPreferredSize(new Dimension(width, height));
//background color:
backgroundColor = new Color(91, 215, 252);
//innitialize fields
camera = null;
lightingObject = null;
meshes = new ArrayList<Mesh>();
triangles = new ArrayList<Triangle>();
drawQeue = new ArrayList<Triangle2D>();
camDirection = new Vector3();
camPos = new Vector3();
fps = -1;
lastFrameTime = System.nanoTime();
//creates the buffered image which will be used to render triangles.
renderImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//empty image pixel color data array is used to store the pixel data for a blank image,
//which is used to clear the buffered image before each frame is drawn.
blankImagePixelColorData = new int[width*height];
Arrays.fill(blankImagePixelColorData, convertToIntRGB(backgroundColor));
}
public void paintComponent(Graphics g)
{
//makes sure that there are triangles to render in the first place, and that the camera exists.
if (meshes.size() > 0 && camera != null)
{
computeTriangles();
sortTriangles();
drawBufferedImage();
g.drawImage(renderImage, 0, 0, this);
}
//fps counter
g.drawString("fps: " + (int)(1000000000/(System.nanoTime()-lastFrameTime)), 30, 30);
}
/**
* @param limit the fps limit for the rendering panel
*/
public void setFPSlimit(int limit)
{
fps = Math.max(0, limit);
}
//sets the lighting, which updates the lighting of all meshes.
public void setLighting(Lighting lighting)
{
if (lighting == null)
{
System.err.println("WARNING at: RenderingPanel/setLighting() method: \n\tlighting is null, lighting not set");
return;
}
lightingObject = lighting;
lightingObject.update(meshes);
}
//adds a mesh to be rendered, as well as updating it's lighting
public void addMesh(Mesh mesh)
{
if (mesh != null)
{
meshes.add(mesh);
if (lightingObject != null)
lightingObject.update(meshes);
triangles.addAll(mesh.getTriangles());
}
else
{
System.err.println("WARNING at: RenderingPanel/addMesh() method: \n\tmesh is null, triangles not added");
}
}
//sets the camera
public void setCamera(Camera camIn)
{
if (camIn == null)
{
System.err.println("WARNING at: RenderingPanel/setCamera() method: \n\tcamera is null, camera not set");
return;
}
camera = camIn;
renderPlaneWidth = camera.getRenderPlaneWidth();
renderPlane = new Plane(Vector3.add(Vector3.multiply(camDirection, camera.getRenderPlaneDistance()), camera.getPosition()), camDirection);;
}
//sets the fog with specified values
public void setFog(double fogStartDistanceIn, double fullFogDistanceIn, Color fogColorIn)
{
fogStartDistance = fogStartDistanceIn;
fullFogDistance = fullFogDistanceIn;
fogColor = fogColorIn;
fogEnabled = true;
}
public void enableFog()
{
fogEnabled = true;
}
public void dissableFog()
{
fogEnabled = false;
}
public void computeTriangles()
{
pixelsPerUnit = getWidth()/renderPlaneWidth;
renderPlaneWidth = camera.getRenderPlaneWidth();
camPos = camera.getPosition();
camDirection = camera.getDirectionVector();
camCenterPoint = Vector3.add(Vector3.multiply(camDirection, camera.getRenderPlaneDistance()), camPos);
renderPlane = new Plane(Vector3.add(Vector3.multiply(camDirection, camera.getRenderPlaneDistance()), camPos), camDirection);
pointRotationMatrix = Matrix3x3.multiply(Matrix3x3.rotationMatrixAxisX(camera.getVorientation()*0.017453292519943295), Matrix3x3.rotationMatrixAxisY(-camera.getHorientation()*0.017453292519943295));
drawQeue.clear();
for (int i = 0; i < triangles.size(); i ++)
{
calculateTriangle(triangles.get(i));
}
}
public void sortTriangles()
{
Collections.sort(drawQeue);
}
public void drawBufferedImage()
{
renderImage.getRaster().setDataElements(0, 0, renderImage.getWidth(), renderImage.getHeight(), blankImagePixelColorData);
for (int i = 0; i < drawQeue.size(); i++)
{
Triangle2D triangle2d = drawQeue.get(i);
paintTriangle(triangle2d.p1, triangle2d.p2, triangle2d.p3, triangle2d.color);
}
}
public void start()
{
validate();
revalidate();
if (renderingThread == null)
{
threadRunning = true;
renderingThread = new Thread(this, "Rendering");
renderingThread.start();
}
}
public void run()
{
while(threadRunning)
{
if (fps > 0)
{
try
{
Thread.sleep(1000/(fps));
}
catch (InterruptedException e)
{}
}
repaint();
}
}
public void stopThread()
{
try
{
threadRunning = false;
renderingThread.interrupt();
renderingThread = null;
}
catch (SecurityException e)
{
}
}
//calculates the three screen coordinates of a single triangle in world space, based off the orientation and position of the camera.
//It then adds the resulting 2d triangle into the triangle2dList for painting later.
private void calculateTriangle(Triangle triangle)
{
Vector3 triangleCenter = triangle.getCenter();
double distanceToTriangle = Vector3.subtract(triangleCenter, camPos).getMagnitude();
if
(
Vector3.dotProduct(Vector3.subtract(triangleCenter, camPos), camDirection) > 0 //is the triangle on the side that the camera is facing?
&& distanceToTriangle < camera.getFarClipDistancee() //is the triangle within the camera's render distance?
&& (Vector3.dotProduct(triangle.getPlane().normal, Vector3.subtract(triangleCenter, camPos)) < 0) //is the triangle facing away?
)
{
Plane nearClipPlane = new Plane(Vector3.add(camPos, Vector3.multiply(camDirection, camera.getNearClipDistance())), camDirection);
if
(
Vector3.dotProduct(nearClipPlane.normal, Vector3.subtract(triangle.vertex1, nearClipPlane.pointOnPlane)) < 0
|| Vector3.dotProduct(nearClipPlane.normal, Vector3.subtract(triangle.vertex1, nearClipPlane.pointOnPlane)) < 0
|| Vector3.dotProduct(nearClipPlane.normal, Vector3.subtract(triangle.vertex1, nearClipPlane.pointOnPlane)) < 0
)
return;
//create local variables:
//the screen coords of the triangle, to be determined by the rest of the method.
Point p1ScreenCoords = new Point();
Point p2ScreenCoords = new Point();
Point p3ScreenCoords = new Point();
//boolean default false, but set true if just one of the verticies is within the camera's fov.
boolean shouldDrawTriangle = false;
Vector3 triangleVertex1 = new Vector3(triangle.vertex1);
Vector3 triangleVertex2 = new Vector3(triangle.vertex2);
Vector3 triangleVertex3 = new Vector3(triangle.vertex3);
triangleVertex1 = Vector3.getIntersectionPoint(Vector3.subtract(triangleVertex1, camPos), camPos, renderPlane);
Vector3 rotatedPoint = Vector3.applyMatrix(pointRotationMatrix, Vector3.subtract(triangleVertex1, camCenterPoint));
if ((Math.abs(rotatedPoint.x) < renderPlaneWidth/2*1.2 && Math.abs(rotatedPoint.y) < renderPlaneWidth*((double)getHeight()/(double)getWidth())/2*1.2))
shouldDrawTriangle = true;
p1ScreenCoords.x = (int)(getWidth()/2 + rotatedPoint.x*pixelsPerUnit);
p1ScreenCoords.y = (int)(getHeight()/2 - rotatedPoint.y*pixelsPerUnit);
triangleVertex2 = Vector3.getIntersectionPoint(Vector3.subtract(triangleVertex2, camPos), camPos, renderPlane);
rotatedPoint = Vector3.applyMatrix(pointRotationMatrix, Vector3.subtract(triangleVertex2, camCenterPoint));
if ((Math.abs(rotatedPoint.x) < renderPlaneWidth/2*1.2 && Math.abs(rotatedPoint.y) < renderPlaneWidth*((double)getHeight()/getWidth())/2*1.2))
shouldDrawTriangle = true;
p2ScreenCoords.x = (int)(getWidth()/2 + rotatedPoint.x*pixelsPerUnit);
p2ScreenCoords.y = (int)(getHeight()/2 - rotatedPoint.y*pixelsPerUnit);
triangleVertex3 = new Vector3(triangle.vertex3);
triangleVertex3 = Vector3.getIntersectionPoint(Vector3.subtract(triangleVertex3, camPos), camPos, renderPlane);
rotatedPoint = Vector3.applyMatrix(pointRotationMatrix, Vector3.subtract(triangleVertex3, camCenterPoint));
if ((Math.abs(rotatedPoint.x) < renderPlaneWidth/2*1.2 && Math.abs(rotatedPoint.y) < renderPlaneWidth*((double)getHeight()/getWidth())/2*1.2))
shouldDrawTriangle = true;
p3ScreenCoords.x = (int)(getWidth()/2 + rotatedPoint.x*pixelsPerUnit);
p3ScreenCoords.y = (int)(getHeight()/2 - rotatedPoint.y*pixelsPerUnit);
if (shouldDrawTriangle)
{
Color colorUsed;
if (triangle.getMesh() != null && triangle.getMesh().isShaded())
{
Color litColor = triangle.getColorWithLighting();
if (fogEnabled && distanceToTriangle > fogStartDistance)
{
Color triangleColor;
if (distanceToTriangle > fullFogDistance)
triangleColor = fogColor;
else
{
//skews the triangle's color closer to the fog color as a function of distance.
double fogAmt = (distanceToTriangle-fogStartDistance)/(fullFogDistance-fogStartDistance);
int red = litColor.getRed() + (int)((fogColor.getRed()-litColor.getRed())*fogAmt*fogAmt);
int green = litColor.getGreen() + (int)((fogColor.getGreen()-litColor.getGreen())*fogAmt*fogAmt);
int blue = litColor.getBlue() + (int)((fogColor.getBlue()-litColor.getBlue())*fogAmt*fogAmt);
//clamps color values to between 0 and 255
red = Math.max(0, Math.min(255, red));
green = Math.max(0, Math.min(255, green));
blue = Math.max(0, Math.min(255, blue));
triangleColor = new Color(red, green, blue);
}
colorUsed = triangleColor;
}
else
colorUsed = litColor;
}
else
colorUsed = triangle.getBaseColor();
if (colorUsed == null)
{
colorUsed = Color.MAGENTA;
}
//adds the 2d triangle object into the triangle2d array.
drawQeue.add(new Triangle2D(p1ScreenCoords, p2ScreenCoords, p3ScreenCoords, colorUsed, distanceToTriangle));
}
}
}
//returns the integer rgb value of a color, which is used for buffered images.
private int convertToIntRGB(Color color)
{
return 65536 * color.getRed() + 256 * color.getGreen() + color.getBlue();
}
//paints a solid triangle on the buffered image with verticies at "p1", "p2" and "p3".
//rasterization algorithm starts at the top point, then draws horizontal lines from one
//edge of the triangle to the other (using a simple slope-intercept equation), first
//drawing the upper part and then the lower part of the triangle.
//This method is much faster at drawing triangles than Graphics' fillPolygon() method.
private void paintTriangle(Point p1, Point p2, Point p3, Color triangleColor)
{
Point tempPoint = new Point(); //buffer for the sorting algorithm
int rgb = convertToIntRGB(triangleColor); //the integer rgb value of the triangle color
//sorts the three points by height using a very simple bubble sort algorithm
if (p1.getY() > p2.getY())
{
tempPoint = p1;
p1 = p2;
p2 = tempPoint;
}
if (p2.getY() > p3.getY())
{
tempPoint = p2;
p2 = p3;
p3 = tempPoint;
}
if (p1.getY() > p2.getY())
{
tempPoint = p1;
p1 = p2;
p2 = tempPoint;
}
if (p2.getY() > p3.getY())
{
tempPoint = p2;
p2 = p3;
p3 = tempPoint;
}
//the y-level of the horizontal line being drawn
int yScanLine;
//the left or right bounds of the line being drawn
int edge1, edge2;
//Top part of triangle:
if (p2.y-p1.y != 0 && p3.y-p1.y != 0)
{
//conditionals to account for the cases where the slope of a line of the triangle is undefined vertical.
if (p2.x - p1.x == 0)
{
edge1 = Math.max(0, Math.min(renderImage.getWidth(), p1.x));
for (yScanLine = p1.y; yScanLine < p2.y && yScanLine < renderImage.getHeight(); yScanLine ++)
{
if (yScanLine >= 0)
{
edge2 = Math.max(0, Math.min(renderImage.getWidth(), (int)((yScanLine-p1.y)/((double)(p3.y-p1.y)/(p3.x-p1.x)) + p1.x)));
drawHorizontalLine(Math.min(edge1, edge2), Math.max(edge1, edge2), yScanLine, rgb);
}
}
}
else if (p3.x-p1.x == 0)
{
edge2 = Math.max(0, Math.min(renderImage.getWidth(), p1.x));
for (yScanLine = p1.y; yScanLine < p2.y && yScanLine < renderImage.getHeight(); yScanLine ++)
{
if (yScanLine >= 0)
{
edge1 = Math.max(0, Math.min(renderImage.getWidth(), (int)((yScanLine-p1.y)/((double)(p2.y-p1.y)/(p2.x-p1.x)) + p1.x)));
drawHorizontalLine(Math.min(edge1, edge2), Math.max(edge1, edge2), yScanLine, rgb);
}
}
}
else
{
for (yScanLine = p1.y; yScanLine < p2.y && yScanLine < renderImage.getHeight(); yScanLine ++)
{
if (yScanLine >= 0)
{
edge1 = Math.max(0, Math.min(renderImage.getWidth(), (int)((yScanLine-p1.y)/((double)(p2.y-p1.y)/(p2.x-p1.x)) + p1.x)));
edge2 = Math.max(0, Math.min(renderImage.getWidth(), (int)((yScanLine-p1.y)/((double)(p3.y-p1.y)/(p3.x-p1.x)) + p1.x)));
drawHorizontalLine(Math.min(edge1, edge2), Math.max(edge1, edge2), yScanLine, rgb);
}
}
}
}
//bottom part of triangle:
if (p3.y-p2.y != 0 && p3.y-p1.y != 0)
{
//conditionals to account for the cases where the slope of a line of the triangle is vertical.
if (p3.x-p2.x == 0)
{
edge1 = Math.max(0, Math.min(renderImage.getWidth(), p2.x));
for (yScanLine = p2.y; yScanLine < p3.y && yScanLine < renderImage.getHeight(); yScanLine ++)
{
if (yScanLine >= 0)
{
edge2 = Math.max(0, Math.min(renderImage.getWidth(), (int)((yScanLine-p3.y)/((double)(p3.y-p1.y)/(p3.x-p1.x)) + p3.x)));
drawHorizontalLine(Math.min(edge1, edge2), Math.max(edge1, edge2), yScanLine, rgb);
}
}
}
else if (p3.x - p1.x == 0)
{
edge2 = Math.max(0, Math.min(renderImage.getWidth(), p3.x));
for (yScanLine = p2.y; yScanLine < p3.y && yScanLine < renderImage.getHeight(); yScanLine ++)
{
if (yScanLine >= 0)
{
edge1 = Math.max(0, Math.min(renderImage.getWidth(), (int)((yScanLine-p3.y)/((double)(p3.y-p2.y)/(p3.x-p2.x)) + p3.x)));
drawHorizontalLine(Math.min(edge1, edge2), Math.max(edge1, edge2), yScanLine, rgb);
}
}
}
else
{
for (yScanLine = p2.y; yScanLine < p3.y && yScanLine < renderImage.getHeight(); yScanLine ++)
{
if (yScanLine >= 0)
{
edge1 = Math.max(0, Math.min(renderImage.getWidth(), (int)((yScanLine-p3.y)/((double)(p3.y-p2.y)/(p3.x-p2.x)) + p3.x)));
edge2 = Math.max(0, Math.min(renderImage.getWidth(), (int)((yScanLine-p3.y)/((double)(p3.y-p1.y)/(p3.x-p1.x)) + p3.x)));
drawHorizontalLine(Math.min(edge1, edge2), Math.max(edge1, edge2), yScanLine, rgb);
}
}
}
}
}
//draws a horizontal line with the given constraints and the specified integer rgb color.
private void drawHorizontalLine(int startOFLineX, int endOfLineX, int levelY, int rgb)
{
int[] pixelArray = new int[(Math.abs(endOfLineX-startOFLineX))];
Arrays.fill(pixelArray, rgb);
renderImage.getRaster().setDataElements(startOFLineX, levelY, Math.abs(endOfLineX-startOFLineX), 1, pixelArray);
}
//Triangle2D class stores 2d triangle data before it is painted on the buffered image.
//implements comparable to optimize sorting.
class Triangle2D implements Comparable<Triangle2D>
{
//three screen coordinate points.
public Point p1;
public Point p2;
public Point p3;
//the color
public Color color;
//the distance from this triangle's corresponding 3d triangle to the camera.
//for the sole purpose of sorting triangles by distance, but rather than wasting
//compute to sort 3d triangles before the program knows wether or not they are
//even in view, the 2d triangles store this value as a way for the algorithm to
//sort triangles by distance later in the pipeline, which is much more efficient.
private double triangle3DDistance;
//overloaded constructor.
public Triangle2D(Point p1In, Point p2In, Point p3In, Color colorIn, double triangle3DDistanceIn)
{
p1 = p1In;
p2 = p2In;
p3 = p3In;
color = colorIn;
triangle3DDistance = triangle3DDistanceIn;
}
//the compareTo method allows java.util.Collections to compare two Triangle2D
//objects with eachother. This allows the program to use java.util.Collections'
//very fast sorting algorithm to sort triangles by distance.
public int compareTo(Triangle2D o)
{
return (o.triangle3DDistance > triangle3DDistance)? 1 : ((o.triangle3DDistance < triangle3DDistance)? -1 : 0);
}
}
}