Конечно! Вот ваш код, переписанный с использованием PixelBuffer (а точнее WritableImage и PixelWriter) вместо Canvas.
RenderEngine.java
package com.cgvsu.render_engine;
import com.cgvsu.math.Matrix4f;
import com.cgvsu.math.Point2f;
import com.cgvsu.math.Vector2f;
import com.cgvsu.math.Vector3f;
import com.cgvsu.model.Model;
import com.cgvsu.model.Polygon;
import com.cgvsu.model.Texture;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import static com.cgvsu.render_engine.GraphicConveyor.multiplyMatrix4ByVector3;
import static com.cgvsu.render_engine.GraphicConveyor.scaleRotateTranslate;
/**
* Класс для рендеринга 3D моделей с использованием PixelWriter.
*/
public class RenderEngine {
private boolean enableFill = true; // Заливка полигона
private boolean enableWireframe = false; // Отрисовка каркаса
private boolean enableTexture = false; // Наложение текстур
private boolean enableLighting = false;
private Vector3f lightDirection;
private double lightingCoefficient = 0.5; // Коэффициент освещения
// Методы для установки параметров рендеринга
public void setEnableFill(boolean enableFill) {
this.enableFill = enableFill;
}
public void setEnableWireframe(boolean enableWireframe) {
this.enableWireframe = enableWireframe;
}
public void setEnableTexture(boolean enableTexture) {
this.enableTexture = enableTexture;
}
public void setEnableLighting(boolean enableLighting) {
this.enableLighting = enableLighting;
}
private Matrix4f calculateModelViewProjectionMatrix(Camera camera, Vector3f rotate, Vector3f scale, Vector3f translate) {
Matrix4f modelMatrix = scaleRotateTranslate(rotate, scale, translate);
Matrix4f viewMatrix = camera.getViewMatrix();
Matrix4f projectionMatrix = camera.getProjectionMatrix();
modelMatrix.transposition();
viewMatrix.transposition();
projectionMatrix.transposition();
Matrix4f mvpMatrix = new Matrix4f(projectionMatrix);
mvpMatrix.multiply(viewMatrix);
mvpMatrix.multiply(modelMatrix);
return mvpMatrix;
}
private float[][] initializeZBuffer(int width, int height) {
float[][] zBuffer = new float[width][height];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
zBuffer[x][y] = Float.MAX_VALUE;
}
}
return zBuffer;
}
/**
* Выполняет рендеринг 3D модели в WritableImage.
*
* @param camera Объект камеры, определяющий вид и проекцию.
* @param model Модель для рендеринга.
* @param width Ширина области рендеринга.
* @param height Высота области рендеринга.
* @return WritableImage с отрендеренной моделью.
*/
public WritableImage render(Camera camera, Model model, int width, int height) {
float[][] zBuffer = initializeZBuffer(width, height);
Matrix4f mvpMatrix = calculateModelViewProjectionMatrix(camera, model.getRotate(), model.getScale(), model.getTranslate());
lightDirection = new Vector3f(camera.getPosition().getX(), camera.getPosition().getY(), camera.getPosition().getZ());
Texture texture = model.getTexture();
WritableImage image = new WritableImage(width, height);
PixelWriter pixelWriter = image.getPixelWriter();
// Заполняем изображение фоновым цветом (белым)
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
pixelWriter.setColor(x, y, Color.WHITE);
}
}
for (Polygon polygon : model.getPolygons()) {
renderPolygon(pixelWriter, polygon, mvpMatrix, width, height, zBuffer, model, texture);
}
if (enableWireframe) {
renderWireframe(pixelWriter, model, mvpMatrix, width, height, zBuffer);
}
return image;
}
private void renderPolygon(PixelWriter pixelWriter, Polygon polygon, Matrix4f mvpMatrix,
int width, int height, float[][] zBuffer, Model model, Texture texture) {
int[] vertexIndices = polygon.getVertexIndices().stream().mapToInt(Integer::intValue).toArray();
int[] textureIndices = polygon.getTextureVertexIndices().stream().mapToInt(Integer::intValue).toArray();
Point2f[] screenPoints = new Point2f[3];
float[] zValues = new float[3];
Vector2f[] textureCoords = new Vector2f[3];
Vector3f[] vertexNormals = new Vector3f[3]; // Массив для нормалей каждой вершины
for (int i = 0; i < 3; i++) {
Vector3f transformedVertex = transformVertex(model, vertexIndices[i], mvpMatrix);
screenPoints[i] = vertexToPoint(transformedVertex, width, height);
zValues[i] = transformedVertex.getZ();
// Получаем нормаль для текущей вершины
vertexNormals[i] = model.getNormals().get(vertexIndices[i]);
if (enableTexture && textureIndices.length == 3 && texture != null) {
Vector2f texCoord = model.getTextureVertices().get(textureIndices[i]);
textureCoords[i] = texCoord;
}
}
if (enableTexture && textureCoords[0] != null) {
rasterizeTriangleWithTexture(screenPoints, zValues, textureCoords, zBuffer, pixelWriter, texture);
} else if (enableFill) {
rasterizeTriangle(screenPoints, vertexNormals, zValues, zBuffer, pixelWriter);
}
}
private void rasterizeTriangleWithTexture(Point2f[] points, float[] zValues, Vector2f[] textureCoords,
float[][] zBuffer, PixelWriter pixelWriter, Texture texture) {
if (texture == null) {
System.err.println("Текстура не задана для модели.");
return;
}
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;
float u = interpolate(lambda0, lambda1, lambda2, new float[]{
textureCoords[0].getX(),
textureCoords[1].getX(),
textureCoords[2].getX()});
float v = interpolate(lambda0, lambda1, lambda2, new float[]{
textureCoords[0].getY(),
textureCoords[1].getY(),
textureCoords[2].getY()});
Color color = texture.getColor(u, v);
pixelWriter.setColor(x, y, color);
}
}
}
}
}
private void rasterizeTriangle(Point2f[] points, Vector3f[] normals, float[] zValues, float[][] zBuffer, PixelWriter pixelWriter) {
lightDirection.normalize();
// Находим границы треугольника
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);
if (isInsideTriangle(barycentric[0], barycentric[1], barycentric[2])) {
float depth = interpolate(barycentric[0], barycentric[1], barycentric[2], zValues);
if (depth < zBuffer[x][y]) {
// Интерполируем нормаль на основе барицентрических координат
Vector3f interpolatedNormal = new Vector3f();
Vector3f temp1 = new Vector3f(normals[0]);
temp1.multiply(barycentric[0]);
Vector3f temp2 = new Vector3f(normals[1]);
temp2.multiply(barycentric[1]);
Vector3f temp3 = new Vector3f(normals[2]);
temp3.multiply(barycentric[2]);
interpolatedNormal = temp1.add(temp2).add(temp3);
interpolatedNormal.normalize();
float diffuse = Math.max(0, interpolatedNormal.dot(lightDirection));
float brightness = 0.9f * diffuse;
Color baseColor = Color.LIGHTGRAY;
Color shadedColor = new Color(
clamp(baseColor.getRed() * brightness),
clamp(baseColor.getGreen() * brightness),
clamp(baseColor.getBlue() * brightness),
baseColor.getOpacity()
);
zBuffer[x][y] = depth;
pixelWriter.setColor(x, y, shadedColor);
}
}
}
}
}
private void renderWireframe(PixelWriter pixelWriter, Model model, Matrix4f mvpMatrix, int width, int height, float[][] zBuffer) {
for (Polygon polygon : model.getPolygons()) {
int[] vertexIndices = polygon.getVertexIndices().stream().mapToInt(Integer::intValue).toArray();
Point2f[] screenPoints = new Point2f[vertexIndices.length];
float[] zValues = new float[vertexIndices.length];
for (int i = 0; i < vertexIndices.length; i++) {
Vector3f transformedVertex = transformVertex(model, vertexIndices[i], mvpMatrix);
screenPoints[i] = vertexToPoint(transformedVertex, width, height);
zValues[i] = transformedVertex.getZ();
}
for (int i = 0; i < vertexIndices.length; i++) {
int next = (i + 1) % vertexIndices.length;
drawLine(pixelWriter, screenPoints[i], screenPoints[next], zValues[i], zValues[next], zBuffer);
}
}
}
private void drawLine(PixelWriter pixelWriter, Point2f p1, Point2f p2, float z1, float z2, float[][] zBuffer) {
int x0 = (int) p1.getX();
int y0 = (int) p1.getY();
int x1 = (int) p2.getX();
int y1 = (int) p2.getY();
int dx = Math.abs(x1 - x0);
int dy = Math.abs(y1 - y0);
int sx = x0 < x1 ? 1 : -1;
int sy = y0 < y1 ? 1 : -1;
int err = dx - dy;
while (true) {
if (x0 >= 0 && x0 < zBuffer.length && y0 >= 0 && y0 < zBuffer[0].length) {
float depth = interpolateDepth(x0, y0, p1, p2, z1, z2);
if (depth < zBuffer[x0][y0]) {
zBuffer[x0][y0] = depth;
pixelWriter.setColor(x0, y0, Color.BLACK);
}
}
if (x0 == x1 && y0 == y1) break;
int e2 = 2 * err;
if (e2 > -dy) {
err -= dy;
x0 += sx;
}
if (e2 < dx) {
err += dx;
y0 += sy;
}
}
}
private Vector3f transformVertex(Model model, int vertexIndex, Matrix4f mvpMatrix) {
Vector3f vertex = model.getVertices().get(vertexIndex);
return multiplyMatrix4ByVector3(mvpMatrix, vertex);
}
private Point2f vertexToPoint(Vector3f vertex, int width, int height) {
float x = (vertex.getX() + 1) * 0.5f * width;
float y = (1 - (vertex.getY() + 1) * 0.5f) * height; // Инвертирование Y
return new Point2f(x, y);
}
// Остальные вспомогательные методы остаются без изменений
private float[] calculateBarycentricCoordinates(Point2f[] points, int x, int y) {
float denom = ((points[1].getY() - points[2].getY()) * (points[0].getX() - points[2].getX()) +
(points[2].getX() - points[1].getX()) * (points[0].getY() - points[2].getY()));
float lambda0 = ((points[1].getY() - points[2].getY()) * (x - points[2].getX()) +
(points[2].getX() - points[1].getX()) * (y - points[2].getY())) / denom;
float lambda1 = ((points[2].getY() - points[0].getY()) * (x - points[2].getX()) +
(points[0].getX() - points[2].getX()) * (y - points[2].getY())) / denom;
float lambda2 = 1.0f - lambda0 - lambda1;
return new float[]{lambda0, lambda1, lambda2};
}
private boolean isInsideTriangle(float lambda0, float lambda1, float lambda2) {
return lambda0 >= 0 && lambda1 >= 0 && lambda2 >= 0;
}
private float interpolate(float lambda0, float lambda1, float lambda2, float[] values) {
return lambda0 * values[0] + lambda1 * values[1] + lambda2 * values[2];
}
private float interpolateDepth(int x, int y, Point2f p1, Point2f p2, float z1, float z2) {
float totalDistance = (float) Math.hypot(p2.getX() - p1.getX(), p2.getY() - p1.getY());
float currentDistance = (float) Math.hypot(x - p1.getX(), y - p1.getY());
return z1 + (z2 - z1) * (currentDistance / totalDistance);
}
private double clamp(double value) {
return Math.max(0.0, Math.min(1.0, value));
}
private int clamp(int value, int min, int max) {
return Math.max(min, Math.min(max, value));
}
}
GuiController.java
В вашем классе GuiController заменим использование Canvas на ImageView и скорректируем код соответствующим образом.
package com.cgvsu;
import com.cgvsu.math.Matrix4f;
import com.cgvsu.math.Vector3f;
import com.cgvsu.model.Model;
import com.cgvsu.objreader.ObjReader;
import com.cgvsu.render_engine.Camera;
import com.cgvsu.render_engine.GraphicConveyor;
import com.cgvsu.render_engine.RenderEngine;
import com.cgvsu.render_engine.TransformationParameters;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
// Удаляем import javafx.scene.canvas.Canvas;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
// Добавляем необходимые импорты
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class GuiController {
final private float TRANSLATION = 0.5F;
@FXML
private AnchorPane anchorPane;
// Заменяем Canvas на ImageView
@FXML
private ImageView imageView; // Новый ImageView для отображения изображения
// Остальные поля и методы остаются без изменений
@FXML
private VBox modelsManager;
@FXML
private TextField textFieldScaleX;
@FXML
private TextField textFieldScaleY;
@FXML
private TextField textFieldScaleZ;
@FXML
private TextField textFieldRotationX;
@FXML
private TextField textFieldRotationY;
@FXML
private TextField textFieldRotationZ;
@FXML
private TextField textFieldTranslationX;
@FXML
private TextField textFieldTranslationY;
@FXML
private TextField textFieldTranslationZ;
@FXML
private VBox camerasManager;
@FXML
private TextField textFieldCameraPositionX;
@FXML
private TextField textFieldCameraPositionY;
@FXML
private TextField textFieldCameraPositionZ;
@FXML
private TextField textFieldCameraPointOfDirectionX;
@FXML
private TextField textFieldCameraPointOfDirectionY;
@FXML
private TextField textFieldCameraPointOfDirectionZ;
@FXML
private VBox lightingModelsManager;
@FXML
private CheckBox checkBoxDrawPolygonalGrid;
@FXML
private CheckBox checkBoxUseTexture;
@FXML
private CheckBox checkBoxUseLighting;
@FXML
private CheckBox fillPolygons;
@FXML
private TextField textFieldLightingModelDirectionX;
@FXML
private TextField textFieldLightingModelDirectionY;
@FXML
private TextField textFieldLightingModelDirectionZ;
private Model mesh = null;
private int counterModels = 0;
private int counterCameras = 0;
private int counterLightingModels = 0;
private Camera camera = new Camera(
new Vector3f(0, 0, 100),
new Vector3f(0, 0, 0),
1.0F, 1, 0.01F, 100);
private Timeline timeline;
// ... (Другие методы остаются без изменений)
private void startRendering() {
if (timeline == null) {
timeline = new Timeline(new KeyFrame(Duration.millis(15), event -> render()));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
}
private void render() {
double width = imageView.getFitWidth();
double height = imageView.getFitHeight();
// Убеждаемся, что ширина и высота установлены
if (width <= 0 || height <= 0) {
width = imageView.getImage() != null ? imageView.getImage().getWidth() : 800;
height = imageView.getImage() != null ? imageView.getImage().getHeight() : 600;
imageView.setFitWidth(width);
imageView.setFitHeight(height);
}
camera.setAspectRatio((float) (width / height));
if (mesh != null) {
RenderEngine renderEngine = new RenderEngine();
// Обновляем настройки рендеринга на основе чекбоксов
renderEngine.setEnableFill(fillPolygons.isSelected());
renderEngine.setEnableWireframe(checkBoxDrawPolygonalGrid.isSelected());
renderEngine.setEnableTexture(checkBoxUseTexture.isSelected());
renderEngine.setEnableLighting(checkBoxUseLighting.isSelected());
WritableImage image = renderEngine.render(camera, mesh, (int) width, (int) height);
imageView.setImage(image);
}
}
// Остальные методы остаются без изменений
@FXML
public void onClickImageView() {
imageView.requestFocus();
}
// Убедитесь, что имя этого метода соответствует новому ImageView
}
FXML файл (Main Scene)
В вашем FXML-файле замените элемент Canvas на ImageView. Вот скорректированный фрагмент вашего FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.input.*?>
<?import javafx.scene.layout.*?>
<AnchorPane fx:id="anchorPane" xmlns="http://javafx.com/javafx/17.0.2-ea" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="com.cgvsu.GuiController">
<!-- MenuBar остается без изменений -->
<!-- Заменяем Canvas на ImageView -->
<ImageView fx:id="imageView" fitWidth="1600" fitHeight="870" onMouseClicked="#onClickImageView"
AnchorPane.rightAnchor="420.0" AnchorPane.topAnchor="30.0"/>
<!-- Остальная часть вашего FXML остается без изменений -->
</AnchorPane>
Важно: Убедитесь, что fx:id в вашем FXML и в контроллере соответствует новому ImageView. Также обновите обработчики событий (например, onClickCanvas на onClickImageView) соответствующим образом.
Примечания
- Теперь
RenderEngine возвращает WritableImage, которую GuiController устанавливает как изображение для ImageView.
- Мы используем
PixelWriter для непосредственной манипуляции пикселями в WritableImage.
- В методе
render() класса GuiController мы обновляем настройки рендеринга (такие как заливка полигонов, использование текстур и т.д.) на основе элементов управления пользовательского интерфейса.
- Убедитесь, что все импорты корректно настроены, и удалите любые ссылки на
Canvas или GraphicsContext.
- FXML-файл обновлен, чтобы отразить использование
ImageView вместо Canvas.
Если у вас возникнут вопросы или понадобится дополнительная помощь, дайте знать!