8042b7714a87e4f8c052f7943275e55f4fee087b
[sixth-3d.git] /
1 /*
2  * Sixth 3D engine. Author: Svjatoslav Agejenko.
3  * This project is released under Creative Commons Zero (CC0) license.
4  */
5 package eu.svjatoslav.sixth.e3d.renderer.raster.shapes.basic.texturedpolygon;
6
7 import eu.svjatoslav.sixth.e3d.geometry.Point2D;
8 import eu.svjatoslav.sixth.e3d.gui.RenderingContext;
9 import eu.svjatoslav.sixth.e3d.math.Vertex;
10 import eu.svjatoslav.sixth.e3d.renderer.raster.shapes.AbstractCoordinateShape;
11 import eu.svjatoslav.sixth.e3d.renderer.raster.texture.Texture;
12 import eu.svjatoslav.sixth.e3d.renderer.raster.texture.TextureBitmap;
13
14 import java.awt.Color;
15
16 import static eu.svjatoslav.sixth.e3d.geometry.Polygon.pointWithinPolygon;
17
18 /**
19  * A textured triangle renderer with perspective-correct texture mapping.
20  *
21  * <p>This class renders triangles with UV-mapped textures. For large triangles,
22  * the rendering may be sliced into smaller pieces for better perspective correction.</p>
23  *
24  * <p><b>Perspective-correct texture rendering:</b></p>
25  * <ul>
26  *   <li>Small polygons are rendered without perspective correction</li>
27  *   <li>Larger polygons are sliced into smaller pieces for accurate perspective</li>
28  * </ul>
29  *
30  * @see Texture
31  * @see Vertex#textureCoordinate
32  */
33 public class TexturedPolygon extends AbstractCoordinateShape {
34
35     private static final ThreadLocal<PolygonBorderInterpolator[]> INTERPOLATORS =
36             ThreadLocal.withInitial(() -> new PolygonBorderInterpolator[]{
37                     new PolygonBorderInterpolator(), new PolygonBorderInterpolator(), new PolygonBorderInterpolator()
38             });
39
40     /**
41      * The texture to apply to this polygon.
42      */
43     public final Texture texture;
44
45     private boolean backfaceCulling = false;
46
47     private double totalTextureDistance = -1;
48
49     /**
50      * Creates a textured triangle with the specified vertices and texture.
51      *
52      * @param p1      the first vertex (must have textureCoordinate set)
53      * @param p2      the second vertex (must have textureCoordinate set)
54      * @param p3      the third vertex (must have textureCoordinate set)
55      * @param texture the texture to apply
56      */
57     public TexturedPolygon(Vertex p1, Vertex p2, Vertex p3, final Texture texture) {
58
59         super(p1, p2, p3);
60         this.texture = texture;
61     }
62
63     /**
64      * Computes the total UV distance between all texture coordinate pairs.
65      * Used to determine appropriate mipmap level.
66      */
67     private void computeTotalTextureDistance() {
68         // compute total texture distance
69         totalTextureDistance = coordinates[0].textureCoordinate.getDistanceTo(coordinates[1].textureCoordinate);
70         totalTextureDistance += coordinates[0].textureCoordinate.getDistanceTo(coordinates[2].textureCoordinate);
71         totalTextureDistance += coordinates[1].textureCoordinate.getDistanceTo(coordinates[2].textureCoordinate);
72     }
73
74     /**
75      * Draws a horizontal scanline between two edge interpolators with texture sampling.
76      *
77      * @param line1         the left edge interpolator
78      * @param line2         the right edge interpolator
79      * @param y             the Y coordinate of the scanline
80      * @param renderBuffer  the rendering context to draw into
81      * @param textureBitmap the texture bitmap to sample from
82      */
83     private void drawHorizontalLine(final PolygonBorderInterpolator line1,
84                                     final PolygonBorderInterpolator line2, final int y,
85                                     final RenderingContext renderBuffer,
86                                     final TextureBitmap textureBitmap) {
87
88         line1.setCurrentY(y);
89         line2.setCurrentY(y);
90
91         int x1 = line1.getX();
92         int x2 = line2.getX();
93
94         final double tx2, ty2;
95         final double tx1, ty1;
96
97         if (x1 <= x2) {
98
99             tx1 = line1.getTX() * textureBitmap.multiplicationFactor;
100             ty1 = line1.getTY() * textureBitmap.multiplicationFactor;
101
102             tx2 = line2.getTX() * textureBitmap.multiplicationFactor;
103             ty2 = line2.getTY() * textureBitmap.multiplicationFactor;
104
105         } else {
106             final int tmp = x1;
107             x1 = x2;
108             x2 = tmp;
109
110             tx1 = line2.getTX() * textureBitmap.multiplicationFactor;
111             ty1 = line2.getTY() * textureBitmap.multiplicationFactor;
112
113             tx2 = line1.getTX() * textureBitmap.multiplicationFactor;
114             ty2 = line1.getTY() * textureBitmap.multiplicationFactor;
115         }
116
117         final double realWidth = x2 - x1;
118         final double realX1 = x1;
119
120         if (x1 < 0)
121             x1 = 0;
122
123         if (x2 >= renderBuffer.width)
124             x2 = renderBuffer.width - 1;
125
126         int renderBufferOffset = (y * renderBuffer.width) + x1;
127         final int[] renderBufferPixels = renderBuffer.pixels;
128
129         final double twidth = tx2 - tx1;
130         final double theight = ty2 - ty1;
131
132         for (int x = x1; x < x2; x++) {
133
134             final double distance = x - realX1;
135
136             final double tx = tx1 + ((twidth * distance) / realWidth);
137             final double ty = ty1 + ((theight * distance) / realWidth);
138
139             final int textureOffset = textureBitmap.getAddress((int) tx,
140                     (int) ty);
141
142             textureBitmap.drawPixel(textureOffset, renderBufferPixels,
143                     renderBufferOffset);
144
145             renderBufferOffset++;
146         }
147
148     }
149
150     /**
151      * Renders this textured triangle to the screen.
152      *
153      * <p>This method performs:</p>
154      * <ul>
155      *   <li>Backface culling check (if enabled)</li>
156      *   <li>Mouse interaction detection</li>
157      *   <li>Mipmap level selection based on screen coverage</li>
158      *   <li>Scanline rasterization with texture sampling</li>
159      * </ul>
160      *
161      * @param renderBuffer the rendering context containing the pixel buffer
162      */
163     @Override
164     public void paint(final RenderingContext renderBuffer) {
165
166         final Point2D projectedPoint1 = coordinates[0].onScreenCoordinate;
167         final Point2D projectedPoint2 = coordinates[1].onScreenCoordinate;
168         final Point2D projectedPoint3 = coordinates[2].onScreenCoordinate;
169
170         if (backfaceCulling) {
171             final double signedArea = (projectedPoint2.x - projectedPoint1.x)
172                     * (projectedPoint3.y - projectedPoint1.y)
173                     - (projectedPoint3.x - projectedPoint1.x)
174                     * (projectedPoint2.y - projectedPoint1.y);
175             if (signedArea >= 0)
176                 return;
177         }
178
179         projectedPoint1.roundToInteger();
180         projectedPoint2.roundToInteger();
181         projectedPoint3.roundToInteger();
182
183         if (mouseInteractionController != null)
184             if (renderBuffer.getMouseEvent() != null)
185                 if (pointWithinPolygon(
186                         renderBuffer.getMouseEvent().coordinate, projectedPoint1,
187                         projectedPoint2, projectedPoint3))
188                     renderBuffer.setCurrentObjectUnderMouseCursor(mouseInteractionController);
189
190         // Show polygon boundaries (for debugging)
191         if (renderBuffer.developerTools != null && renderBuffer.developerTools.showPolygonBorders)
192             showBorders(renderBuffer);
193
194         // find top-most point
195         int yTop = (int) projectedPoint1.y;
196
197         if (projectedPoint2.y < yTop)
198             yTop = (int) projectedPoint2.y;
199
200         if (projectedPoint3.y < yTop)
201             yTop = (int) projectedPoint3.y;
202
203         if (yTop < 0)
204             yTop = 0;
205
206         // find bottom-most point
207         int yBottom = (int) projectedPoint1.y;
208
209         if (projectedPoint2.y > yBottom)
210             yBottom = (int) projectedPoint2.y;
211
212         if (projectedPoint3.y > yBottom)
213             yBottom = (int) projectedPoint3.y;
214
215         if (yBottom >= renderBuffer.height)
216             yBottom = renderBuffer.height - 1;
217
218         // clamp to render Y bounds
219         yTop = Math.max(yTop, renderBuffer.renderMinY);
220         yBottom = Math.min(yBottom, renderBuffer.renderMaxY);
221         if (yTop >= yBottom)
222             return;
223
224         // paint
225         double totalVisibleDistance = projectedPoint1.getDistanceTo(projectedPoint2);
226         totalVisibleDistance += projectedPoint1.getDistanceTo(projectedPoint3);
227         totalVisibleDistance += projectedPoint2.getDistanceTo(projectedPoint3);
228
229         if (totalTextureDistance == -1)
230             computeTotalTextureDistance();
231         final double scaleFactor = (totalVisibleDistance / totalTextureDistance) * 1.2d;
232
233         final TextureBitmap zoomedBitmap = texture.getZoomedBitmap(scaleFactor);
234
235         final PolygonBorderInterpolator[] interp = INTERPOLATORS.get();
236         final PolygonBorderInterpolator polygonBorder1 = interp[0];
237         final PolygonBorderInterpolator polygonBorder2 = interp[1];
238         final PolygonBorderInterpolator polygonBorder3 = interp[2];
239
240         polygonBorder1.setPoints(projectedPoint1, projectedPoint2,
241                 coordinates[0].textureCoordinate,
242                 coordinates[1].textureCoordinate);
243         polygonBorder2.setPoints(projectedPoint1, projectedPoint3,
244                 coordinates[0].textureCoordinate,
245                 coordinates[2].textureCoordinate);
246         polygonBorder3.setPoints(projectedPoint2, projectedPoint3,
247                 coordinates[1].textureCoordinate,
248                 coordinates[2].textureCoordinate);
249
250         // Inline sort for 3 elements to avoid array allocation
251         PolygonBorderInterpolator a = polygonBorder1;
252         PolygonBorderInterpolator b = polygonBorder2;
253         PolygonBorderInterpolator c = polygonBorder3;
254         PolygonBorderInterpolator t;
255         if (a.compareTo(b) > 0) { t = a; a = b; b = t; }
256         if (b.compareTo(c) > 0) { t = b; b = c; c = t; }
257         if (a.compareTo(b) > 0) { t = a; a = b; b = t; }
258
259         for (int y = yTop; y < yBottom; y++)
260             if (a.containsY(y)) {
261                 if (b.containsY(y))
262                     drawHorizontalLine(a, b, y, renderBuffer, zoomedBitmap);
263                 else if (c.containsY(y))
264                     drawHorizontalLine(a, c, y, renderBuffer, zoomedBitmap);
265             } else if (b.containsY(y))
266                 if (c.containsY(y))
267                     drawHorizontalLine(b, c, y, renderBuffer, zoomedBitmap);
268
269     }
270
271     /**
272      * Checks if backface culling is enabled for this polygon.
273      *
274      * @return {@code true} if backface culling is enabled
275      */
276     public boolean isBackfaceCullingEnabled() {
277         return backfaceCulling;
278     }
279
280     /**
281      * Enables or disables backface culling for this polygon.
282      *
283      * @param backfaceCulling {@code true} to enable backface culling
284      */
285     public void setBackfaceCulling(final boolean backfaceCulling) {
286         this.backfaceCulling = backfaceCulling;
287     }
288
289     /**
290      * Draws the polygon border edges in yellow (for debugging).
291      *
292      * @param renderBuffer the rendering context
293      */
294     private void showBorders(final RenderingContext renderBuffer) {
295
296         final Point2D projectedPoint1 = coordinates[0].onScreenCoordinate;
297         final Point2D projectedPoint2 = coordinates[1].onScreenCoordinate;
298         final Point2D projectedPoint3 = coordinates[2].onScreenCoordinate;
299
300         final int x1 = (int) projectedPoint1.x;
301         final int y1 = (int) projectedPoint1.y;
302         final int x2 = (int) projectedPoint2.x;
303         final int y2 = (int) projectedPoint2.y;
304         final int x3 = (int) projectedPoint3.x;
305         final int y3 = (int) projectedPoint3.y;
306
307         renderBuffer.executeWithGraphics(g -> {
308             g.setColor(Color.YELLOW);
309             g.drawLine(x1, y1, x2, y2);
310             g.drawLine(x3, y3, x2, y2);
311             g.drawLine(x1, y1, x3, y3);
312         });
313     }
314
315 }