我已经建立了自己的基本光线跟踪器。 我试图优化其性能,所以我考虑使用线程。 当我不使用线程进行渲染时-一切看起来都不错,但是当我尝试使用线程时-我的画面上有一个带有黑色条纹的嘈杂图片。
这是代码。对于每行像素,我创建了一个新的执行程序来计算该行中的像素颜色:
public void renderImage(){
Camera camera = _scene.get_camera();
for (int i = 0; i < _imageWriter.getWidth(); ++i){
final int iFinal = i;
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
for (int j = 0; j < _imageWriter.getHeight(); ++j){
ArrayList<Ray> rays = camera.constructRaysThroughPixel(
_imageWriter.getNx(), _imageWriter.getNy(),
iFinal, j, _scene.get_screenDistance(),
_imageWriter.getWidth(), _imageWriter.getHeight()
);
Color color = new Color();
for (Ray ray: rays) {
ArrayList<GeoPoint> intersectionPoints = _scene.get_geometries().findIntersections(ray);
if (intersectionPoints.isEmpty() == true) {
color = color.add(_scene.get_background());
}
else {
GeoPoint closestPoint = getClosestPoint(intersectionPoints);
color = color.add(new Color(calcColor(closestPoint, new Ray(camera.get_origin(), closestPoint.point.subtract(camera.get_origin())))));
}
}
int length = rays.size();
color = color.scale(1.0/length);
_imageWriter.writePixel(iFinal, j, color.getColor());
}
});
}
}