/**
* Выполняет растеризацию треугольника и обновляет графический контекст.
* Добавлено простейшее диффузное освещение.
*
* @param points Координаты точек треугольника на экране.
* @param normals Нормали для каждой вершины треугольника.
* @param zValues Значения глубины для каждой вершины.
* @param zBuffer Z-буфер для отслеживания глубины пикселей.
* @param graphicsContext Графический контекст для рисования.
*/
private void rasterizeTriangle(Point2f[] points, Vector3f[] normals, float[] zValues, float[][] zBuffer, GraphicsContext graphicsContext) {
Color colorA = Color.RED;
Color colorB = Color.BLACK;
Color colorC = Color.BLUE;
code
Assistant
int minX = clamp((int) Math.floor(Math.min(points[0].getX(), Math.min(points[1].getX(), points[2].getX()))), 0, zBuffer.length - 1);
int maxX = clamp((int) Math.ceil(Math.max(points[0].getX(), Math.max(points[1].getX(), points[2].getX()))), 0, zBuffer.length - 1);
int minY = clamp((int) Math.floor(Math.min(points[0].getY(), Math.min(points[1].getY(), points[2].getY()))), 0, zBuffer[0].length - 1);
int maxY = clamp((int) Math.ceil(Math.max(points[0].getY(), Math.max(points[1].getY(), points[2].getY()))), 0, zBuffer[0].length - 1);
for (int x = minX; x <= maxX; x++) {
for (int y = minY; y <= maxY; y++) {
float[] barycentric = calculateBarycentricCoordinates(points, x, y);
float lambda0 = barycentric[0];
float lambda1 = barycentric[1];
float lambda2 = barycentric[2];
if (isInsideTriangle(lambda0, lambda1, lambda2)) {
float depth = interpolate(lambda0, lambda1, lambda2, zValues);
if (depth < zBuffer[x][y]) {
zBuffer[x][y] = depth;
// Интерполяция нормалей
Vector3f interpolatedNormal = new Vector3f(
lambda0 * normals[0].getX() + lambda1 * normals[1].getX() + lambda2 * normals[2].getX(),
lambda0 * normals[0].getY() + lambda1 * normals[1].getY() + lambda2 * normals[2].getY(),
lambda0 * normals[0].getZ() + lambda1 * normals[1].getZ() + lambda2 * normals[2].getZ()
);
// Вычисление освещенности
double l = Math.max(0.0, -interpolatedNormal.dot(lightDirection));
double brightness = (1 - lightingCoefficient) + lightingCoefficient * l;
// Интерполируем цвет на основе барицентрических координат
// Color interpolatedColor = interpolateColor(lambda0, lambda1, lambda2, colorA, colorB, colorC);
Color interpolatedColor = Color.AQUA;
// Применение освещения к интерполированному цвету
Color finalColor = new Color(
clamp(interpolatedColor.getRed() * brightness),
clamp(interpolatedColor.getGreen() * brightness),
clamp(interpolatedColor.getBlue() * brightness),
interpolatedColor.getOpacity()
);
graphicsContext.getPixelWriter().setColor(x, y, finalColor);
}
}
}
}
}
добавь примитивное освещение на основе сглаживания нормалей. если надо допиши доп методы
To enhance your rasterization process with primitive lighting based on normal smoothing, we can refine your existing implementation by ensuring that interpolated normals are properly normalized and by optionally interpolating colors across the triangle's surface. Additionally, I'll provide the necessary helper methods that your rasterizeTriangle function relies on.
Here's the updated rasterizeTriangle method along with the required helper methods:
java
import javafx.scene.paint.Color;
import javafx.scene.canvas.GraphicsContext;
import javafx.geometry.Point2D;
public class TriangleRasterizer {
// Define your light direction and lighting coefficient
private Vector3f lightDirection = new Vector3f(0, 0, -1).normalize();
private float lightingCoefficient = 0.8f;
/**
* Rasterizes a triangle with diffuse lighting based on smoothed normals.
*
* @param points Coordinates of the triangle's vertices on the screen.
* @param normals Normals for each vertex of the triangle.
* @param zValues Depth values for each vertex.
* @param zBuffer Z-buffer for tracking pixel depths.
* @param graphicsContext Graphics context for drawing.
*/
private void rasterizeTriangle(Point2f[] points, Vector3f[] normals, float[] zValues, float[][] zBuffer, GraphicsContext graphicsContext) {
// Define vertex colors (you can modify these or pass them as parameters)
Color colorA = Color.RED;
Color colorB = Color.BLACK;
Color colorC = Color.BLUE;
// Determine the bounding box of the triangle
int minX = clamp((int) Math.floor(Math.min(points[0].getX(), Math.min(points[1].getX(), points[2].getX()))), 0, zBuffer.length - 1);
int maxX = clamp((int) Math.ceil(Math.max(points[0].getX(), Math.max(points[1].getX(), points[2].getX()))), 0, zBuffer.length - 1);
int minY = clamp((int) Math.floor(Math.min(points[0].getY(), Math.min(points[1].getY(), points[2].getY()))), 0, zBuffer[0].length - 1);
int maxY = clamp((int) Math.ceil(Math.max(points[0].getY(), Math.max(points[1].getY(), points[2].getY()))), 0, zBuffer[0].length - 1);
// Iterate over each pixel within the bounding box
for (int x = minX; x <= maxX; x++) {
for (int y = minY; y <= maxY; y++) {
float[] barycentric = calculateBarycentricCoordinates(points, x + 0.5f, y + 0.5f);
float lambda0 = barycentric[0];
float lambda1 = barycentric[1];
float lambda2 = barycentric[2];
if (isInsideTriangle(lambda0, lambda1, lambda2)) {
float depth = interpolate(lambda0, lambda1, lambda2, zValues);
if (depth < zBuffer[x][y]) {
zBuffer[x][y] = depth;
// Interpolate normals
Vector3f interpolatedNormal = new Vector3f(
lambda0 * normals[0].getX() + lambda1 * normals[1].getX() + lambda2 * normals[2].getX(),
lambda0 * normals[0].getY() + lambda1 * normals[1].getY() + lambda2 * normals[2].getY(),
lambda0 * normals[0].getZ() + lambda1 * normals[1].getZ() + lambda2 * normals[2].getZ()
).normalize(); // Ensure the interpolated normal is normalized
// Compute lighting (diffuse)
double lightIntensity = Math.max(0.0, interpolatedNormal.dot(lightDirection));
double brightness = (1 - lightingCoefficient) + lightingCoefficient * lightIntensity;
// Optionally interpolate vertex colors
Color interpolatedColor = interpolateColor(lambda0, lambda1, lambda2, colorA, colorB, colorC);
// Apply lighting to the interpolated color
Color finalColor = new Color(
clamp(interpolatedColor.getRed() * brightness),
clamp(interpolatedColor.getGreen() * brightness),
clamp(interpolatedColor.getBlue() * brightness),
interpolatedColor.getOpacity()
);
graphicsContext.getPixelWriter().setColor(x, y, finalColor);
}
}
}
}
}
/**
* Clamps a value between a minimum and maximum range.
*
* @param value The value to clamp.
* @param min The minimum allowed value.
* @param max The maximum allowed value.
* @return The clamped value.
*/
private int clamp(int value, int min, int max) {
return Math.max(min, Math.min(max, value));
}
/**
* Calculates the barycentric coordinates of a point (px, py) with respect to a triangle.
*
* @param points The vertices of the triangle.
* @param px The x-coordinate of the point.
* @param py The y-coordinate of the point.
* @return An array containing the barycentric coordinates (lambda0, lambda1, lambda2).
*/
private float[] calculateBarycentricCoordinates(Point2f[] points, float px, float py) {
float x0 = points[0].getX();
float y0 = points[0].getY();
float x1 = points[1].getX();
float y1 = points[1].getY();
float x2 = points[2].getX();
float y2 = points[2].getY();
float denominator = ((y1 - y2)*(x0 - x2) + (x2 - x1)*(y0 - y2));
if (denominator == 0) {
return new float[]{-1, -1, -1}; // Degenerate triangle
}
float lambda0 = ((y1 - y2)*(px - x2) + (x2 - x1)*(py - y2)) / denominator;
float lambda1 = ((y2 - y0)*(px - x2) + (x0 - x2)*(py - y2)) / denominator;
float lambda2 = 1.0f - lambda0 - lambda1;
return new float[]{lambda0, lambda1, lambda2};
}
/**
* Determines if a point is inside the triangle based on its barycentric coordinates.
*
* @param lambda0 Barycentric coordinate for the first vertex.
* @param lambda1 Barycentric coordinate for the second vertex.
* @param lambda2 Barycentric coordinate for the third vertex.
* @return True if the point is inside the triangle; otherwise, false.
*/
private boolean isInsideTriangle(float lambda0, float lambda1, float lambda2) {
// Allow a small epsilon for edge cases
float epsilon = -0.0001f;
return lambda0 >= epsilon && lambda1 >= epsilon && lambda2 >= epsilon;
}
/**
* Linearly interpolates a value based on barycentric coordinates.
*
* @param lambda0 Barycentric coordinate for the first vertex.
* @param lambda1 Barycentric coordinate for the second vertex.
* @param lambda2 Barycentric coordinate for the third vertex.
* @param values The values at each vertex.
* @return The interpolated value.
*/
private float interpolate(float lambda0, float lambda1, float lambda2, float[] values) {
return lambda0 * values[0] + lambda1 * values[1] + lambda2 * values[2];
}
/**
* Linearly interpolates a Color based on barycentric coordinates.
*
* @param lambda0 Barycentric coordinate for the first vertex.
* @param lambda1 Barycentric coordinate for the second vertex.
* @param lambda2 Barycentric coordinate for the third vertex.
* @param colorA Color at the first vertex.
* @param colorB Color at the second vertex.
* @param colorC Color at the third vertex.
* @return The interpolated Color.
*/
private Color interpolateColor(float lambda0, float lambda1, float lambda2, Color colorA, Color colorB, Color colorC) {
double red = lambda0 * colorA.getRed() + lambda1 * colorB.getRed() + lambda2 * colorC.getRed();
double green = lambda0 * colorA.getGreen() + lambda1 * colorB.getGreen() + lambda2 * colorC.getGreen();
double blue = lambda0 * colorA.getBlue() + lambda1 * colorB.getBlue() + lambda2 * colorC.getBlue();
double opacity = lambda0 * colorA.getOpacity() + lambda1 * colorB.getOpacity() + lambda2 * colorC.getOpacity();
return new Color(clamp(red), clamp(green), clamp(blue), clamp(opacity));
}
/**
* Clamps a double value between 0 and 1.
*
* @param value The value to clamp.
* @return The clamped value.
*/
private double clamp(double value) {
return Math.max(0.0, Math.min(1.0, value));
}
/**
* A simple 2D point class with float coordinates.
*/
private static class Point2f {
private float x;
private float y;
public Point2f(float x, float y) {
this.x = x;
this.y = y;
}
public float getX() {
return x;
}
public float getY() {
return y;
}
}
/**
* A simple 3D vector class with float components.
*/
private static class Vector3f {
private float x;
private float y;
private float z;
public Vector3f(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector3f normalize() {
float length = (float) Math.sqrt(x * x + y * y + z * z);
if (length != 0) {
return new Vector3f(x / length, y / length, z / length);
}
return this;
}
public float dot(Vector3f other) {
return this.x * other.x + this.y * other.y + this.z * other.z;
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public float getZ() {
return z;
}
}
}
Explanation of Enhancements
Normalization of Interpolated Normals:
After interpolating the normals using barycentric coordinates, it's crucial to normalize the resulting vector. This ensures accurate lighting calculations.
The diffuse lighting is calculated using the dot product between the interpolated normal and the light direction. The brightness is then adjusted based on a lightingCoefficient to control the influence of the lighting.
Instead of using a hardcoded color (Color.AQUA), the colors at the vertices (colorA, colorB, colorC) are interpolated based on barycentric coordinates. This results in a smooth gradient across the triangle.
java
Color interpolatedColor = interpolateColor(lambda0, lambda1, lambda2, colorA, colorB, colorC);
Helper Methods:
clamp(int value, int min, int max): Ensures that pixel coordinates stay within the bounds of the z-buffer.
calculateBarycentricCoordinates(Point2f[] points, float px, float py): Computes the barycentric coordinates of a point with respect to the triangle.
Usage Example
To use the rasterizeTriangle method, you need to set up the necessary data structures and provide the vertex information:
java
// Example usage
public void draw(GraphicsContext gc) {
// Define the triangle vertices on the screen
Point2f[] points = new Point2f[]{
new Point2f(100, 100),
new Point2f(200, 100),
new Point2f(150, 200)
};
// Define normals at each vertex
Vector3f[] normals = new Vector3f[]{
new Vector3f(0, 0, 1),
new Vector3f(0, 0, 1),
new Vector3f(0, 0, 1)
};
// Define depth values for each vertex
float[] zValues = new float[]{0.5f, 0.5f, 0.5f};
// Initialize a simple z-buffer (assuming a canvas size of 300x300)
float[][] zBuffer = new float[300][300];
for (int i = 0; i < 300; i++) {
for (int j = 0; j < 300; j++) {
zBuffer[i][j] = Float.POSITIVE_INFINITY;
}
}
// Rasterize the triangle
rasterizeTriangle(points, normals, zValues, zBuffer, gc);
}
Notes
Optimizations: This implementation uses a straightforward approach for clarity. For performance-critical applications, consider optimizing the bounding box calculations and exploring more efficient rasterization algorithms.
Additional Lighting Models: You can extend this basic diffuse lighting model by incorporating other lighting components such as ambient, specular, or even implementing more advanced shading techniques like Phong or Gouraud shading.
Handling Degenerate Triangles: The calculateBarycentricCoordinates method returns invalid barycentric coordinates for degenerate triangles (where the area is zero). You might want to handle such cases separately depending on your application's requirements.
Vertex Attributes: If your vertices have additional attributes (e.g., texture coordinates, multiple normals for different lighting effects), you can extend the interpolation methods accordingly.
Feel free to modify and extend this implementation to suit the specific needs of your rendering engine or graphical application!
Not yet included in a published release.
isInsideTriangle(float lambda0, float lambda1, float lambda2): Determines if a point lies inside the triangle based on its barycentric coordinates.
interpolate(float lambda0, float lambda1, float lambda2, float[] values): Performs linear interpolation for depth values.
interpolateColor(float lambda0, float lambda1, float lambda2, Color colorA, Color colorB, Color colorC): Performs linear interpolation for colors.
Supporting Classes:
Point2f: Represents a 2D point with float coordinates.
Vector3f: Represents a 3D vector with float components, including methods for normalization and dot product calculation.