Changed license to Creative Commons Zero (CC0).
[sixth-3d.git] / src / main / java / eu / svjatoslav / sixth / e3d / renderer / raster / shapes / basic / GlowingPoint.java
1 /*
2  * Sixth 3D engine. Author: Svjatoslav Agejenko. 
3  * This project is released under Creative Commons Zero (CC0) license.
4  *
5 *
6  */
7
8 package eu.svjatoslav.sixth.e3d.renderer.raster.shapes.basic;
9
10 import eu.svjatoslav.sixth.e3d.geometry.Point3D;
11 import eu.svjatoslav.sixth.e3d.renderer.raster.Color;
12 import eu.svjatoslav.sixth.e3d.renderer.raster.texture.Texture;
13
14 import java.util.Collections;
15 import java.util.Set;
16 import java.util.WeakHashMap;
17
18 public class GlowingPoint extends ForwardOrientedTexture {
19
20     private static final int TEXTURE_SIZE = 50;
21     private static final Set<GlowingPoint> glowingPoints = Collections.newSetFromMap(new WeakHashMap<>());
22     private final Color color;
23
24     public GlowingPoint(final Point3D point, final double pointSize,
25                         final Color color) {
26         super(point, pointSize, getTexture(color));
27         this.color = color;
28
29         synchronized (glowingPoints) {
30             glowingPoints.add(this);
31         }
32     }
33
34     private static Texture getTexture(final Color color) {
35         // attempt to reuse texture from existing glowing point of the same color
36         synchronized (glowingPoints) {
37             for (GlowingPoint glowingPoint : glowingPoints)
38                 if (color.equals(glowingPoint.color))
39                     return glowingPoint.texture;
40         }
41
42         // existing texture not found, creating new one
43         return createTexture(color);
44     }
45
46     private static Texture createTexture(final Color color) {
47         final Texture texture = new Texture(TEXTURE_SIZE, TEXTURE_SIZE, 1);
48         for (int x = 0; x < TEXTURE_SIZE; x++)
49             for (int y = 0; y < TEXTURE_SIZE; y++) {
50                 int address = texture.primaryBitmap.getAddress(x, y);
51
52                 final int distance = (int) Math
53                         .sqrt((((TEXTURE_SIZE / 2) - x) * ((TEXTURE_SIZE / 2) - x))
54                                 + (((TEXTURE_SIZE / 2) - y) * ((TEXTURE_SIZE / 2) - y)));
55
56                 int alpha = 255 - ((270 * distance) / (TEXTURE_SIZE / 2));
57                 if (alpha < 0)
58                     alpha = 0;
59
60                 texture.primaryBitmap.bytes[address] = (byte) alpha;
61                 address++;
62                 texture.primaryBitmap.bytes[address] = (byte) color.b;
63                 address++;
64                 texture.primaryBitmap.bytes[address] = (byte) color.g;
65                 address++;
66                 texture.primaryBitmap.bytes[address] = (byte) color.r;
67             }
68
69         return texture;
70     }
71
72 }