/* -*- coding: utf-8 -*- */ /** * Example code for the course "Tietokonegrafiikan perusteet" 2012. * Exercise 6: preliminary rendering library "draft" combining the * classes from previous exercises. */ package demo1; /** * Example code for the course "Tietokonegrafiikan perusteet" 2012 * and 2013. Likely not useful for "production use". * * Exercise 1: preliminary vector, matrix, and image classes. * * @author Paavo Nieminen * */ import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; /** My own image class. */ public class PixelImageRGB { private int width; private int height; private float[] red; private float[] green; private float[] blue; /* Black by default. */ public PixelImageRGB(int width, int height) { this.width = width; this.height = height; int arrsz = width * height; red = new float[arrsz]; green = new float[arrsz]; blue = new float[arrsz]; } /** Just a test image for debugging. */ public void testImage() { float r, g, b; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { r = -(width / 2) + x; g = (float) x * y / (width * height); b = (float) y / height; setPixel(x, y, r, g, b); } } }; /** Set a pixel at (x,y) to floating point RGB value. * FIXME: Z-buffering could be here, when implemented; needs z as parameter. * TODO: Could also do alpha blending; needs alpha as parameter in that case. */ public void setPixel(int x, int y, float r, float g, float b) { int loc = y * width + x; red[loc] = r; green[loc] = g; blue[loc] = b; } /** Return a copy of the image as a Java BufferedImage object. */ public BufferedImage asBufferedImage() { BufferedImage bim = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { bim.setRGB(x, y, rgbAt(x, y)); } } return bim; } /** Returns a color value compatible with BufferedImage.TYPE_INT_RGB */ private int rgbAt(int x, int y) { int rgb = 0; int loc = y * width + x; rgb += 0xff * clamp(red[loc]); rgb <<= 8; rgb += 0xff * clamp(green[loc]); rgb <<= 8; rgb += 0xff * clamp(blue[loc]); return rgb; } /** Clamp a float to [0,1] */ private static float clamp(float value) { return value > 1.f ? 1.f : (value < 0.f ? 0.f : value); } /** Save as PNG. */ public void saveAsPng(String fname) throws IOException { File file = new File(fname); ImageIO.write(asBufferedImage(), "png", file); } /** Reset to black. */ public void clear() { for(int i=0;i