From b3ae4e889872ca0b9ca76f1d17b2f0b961226729 Mon Sep 17 00:00:00 2001
From: Normand Briere <nbriere@noware.ca>
Date: Mon, 05 Aug 2019 21:48:55 -0400
Subject: [PATCH] Fix physics UI

---
 CameraPane.java | 1414 +++++++++++++++++++++++++++++++++++++++++++---------------
 1 files changed, 1,052 insertions(+), 362 deletions(-)

diff --git a/CameraPane.java b/CameraPane.java
index 9794f67..28e9ff5 100644
--- a/CameraPane.java
+++ b/CameraPane.java
@@ -18,7 +18,10 @@
 import javax.imageio.ImageIO;
 import javax.imageio.ImageWriteParam;
 import javax.imageio.ImageWriter;
+import javax.imageio.ImageReadParam;
+import javax.imageio.ImageReader;
 import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
+import javax.imageio.stream.ImageInputStream;
 import javax.imageio.stream.ImageOutputStream;
 import javax.imageio.ImageWriteParam;
 
@@ -30,6 +33,7 @@
 import java.nio.*;
 
 import gleem.linalg.Mat4f;
+import javax.imageio.ImageTypeSpecifier;
 
 class CameraPane extends GLCanvas implements iCameraPane, Runnable, GLEventListener, ActionListener, MouseWheelListener, MouseMotionListener, MouseListener, KeyListener
 {
@@ -37,7 +41,6 @@
     static boolean[] selectedstack = new boolean[65536];
     static int materialdepth = 0;
 
-    static boolean DEBUG = false;
     static boolean FRUSTUM = false; // still bogus true; // frustum culling
 
     // camera change fix
@@ -45,6 +48,39 @@
     static boolean ABORTED = false;
     
     static int STEP = 1;
+
+    private static BufferedImage CreateBim(byte[] bytes, int width, int height)
+    {
+        int[] pixels = new int[bytes.length/3];
+        for (int i=pixels.length; --i>=0;)
+        {
+            int i3 = i*3;
+            pixels[i] = 0xFF;
+            pixels[i] <<= 8;
+            pixels[i] |= bytes[i3+2] & 0xFF;
+            pixels[i] <<= 8;
+            pixels[i] |= bytes[i3+1] & 0xFF;
+            pixels[i] <<= 8;
+            pixels[i] |= bytes[i3] & 0xFF;
+        }
+        /*
+        int r=0,g=0,b=0,a=0;
+        for (int i=0; i<width; i++)
+        for (int j=0; j<height; j++)
+        {
+        int index = j*width+i;
+        int p = pixels[index];
+        a = ((p>>24) & 0xFF);
+        r = ((p>>16) & 0xFF);
+        g = ((p>>8) & 0xFF);
+        b = (p & 0xFF);
+        pixels[index] = (a<<24) | (b<<16) | (g<<8) | r;
+        }
+        /**/
+        BufferedImage rendImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // ImageIO.read(infile);
+        rendImage.setRGB(0,0,width,height,pixels,width*(height-1),-width);
+        return rendImage;
+    }
 
     /*static*/ private boolean CULLFACE = false; // true;
     /*static*/ boolean NEAREST = false; // true;
@@ -61,7 +97,7 @@
     //boolean REDUCETEXTURE = true;
     boolean CACHETEXTURE = true;
     boolean CLEANCACHE = false; // true;
-    boolean MIPMAP = false; // true;
+    boolean MIPMAP = false; // true; // never works...
     boolean COMPRESSTEXTURE = false;
     boolean KOMPACTTEXTURE = false; // true;
     boolean RESIZETEXTURE = false;
@@ -150,6 +186,20 @@
         defaultcaps.setAccumAlphaBits(16);
     }
     
+    private File defaultDirectory = javax.swing.filechooser.FileSystemView.getFileSystemView().getDefaultDirectory();
+
+    public void LoadSkybox(String name, String ext, boolean mipmap) throws GLException
+    {
+        try
+        {
+            cubemap = LoadCubemap(getClass().getClassLoader(), name, ext, mipmap);
+        } catch (IOException e)
+        {
+            System.out.println("NAME = " + name);
+            e.printStackTrace(); // throw new RuntimeException(e);
+        }
+    }
+    
     void SetAsGLRenderer(boolean b)
     {
         isRenderer = b;
@@ -168,7 +218,8 @@
 
         SetCamera(cam);
 
-        SetLight(new Camera(new cVector(10, 10, -20)));
+        // Warning: not used.
+        SetLight(new Camera(new cVector(15, 10, -20)));
 
         object = o;
 
@@ -325,7 +376,7 @@
                 cStatic.objectstack[materialdepth++] = obj;
                 //System.out.println("material " + material);
                 //Applet3D.tracein(this, selected);
-                display.vector2buffer = obj.projectedVertices;
+                //display.vector2buffer = obj.projectedVertices;
                 if (obj instanceof Camera)
                 {
                     display.options1[0] = material.shift;
@@ -334,14 +385,28 @@
                     display.options1[2] = material.shadowbias;
                     display.options1[3] = material.aniso;
                     display.options1[4] = material.anisoV;
+//                System.out.println("display.options1[0] " + display.options1[0]);
+//                System.out.println("display.options1[1] " + display.options1[1]);
+//                System.out.println("display.options1[2] " + display.options1[2]);
+//                System.out.println("display.options1[3] " + display.options1[3]);
+//                System.out.println("display.options1[4] " + display.options1[4]);
                     display.options2[0] = material.opacity;
                     display.options2[1] = material.diffuse;
                     display.options2[2] = material.factor;
+//                System.out.println("display.options2[0] " + display.options2[0]);
+//                System.out.println("display.options2[1] " + display.options2[1]);
+//                System.out.println("display.options2[2] " + display.options2[2]);
 
                     cColor.HSBtoRGB(material.color, material.modulation, 1, display.options3);
+//                System.out.println("display.options3[0] " + display.options3[0]);
+//                System.out.println("display.options3[1] " + display.options3[1]);
+//                System.out.println("display.options3[2] " + display.options3[2]);
                     display.options4[0] = material.cameralight/0.2f;
                     display.options4[1] = material.subsurface;
                     display.options4[2] = material.sheen;
+//                System.out.println("display.options4[0] " + display.options4[0]);
+//                System.out.println("display.options4[1] " + display.options4[1]);
+//                System.out.println("display.options4[2] " + display.options4[2]);
                     
                  //   if (display.CURRENTANTIALIAS > 0)
                  //       display.options3[3] /= 4;
@@ -357,7 +422,7 @@
                 /**/
                 } else
                 {
-                    DrawMaterial(material, selected);
+                    DrawMaterial(material, selected, obj.projectedVertices);
                 }
             } else
             {
@@ -381,8 +446,8 @@
             cStatic.objectstack[materialdepth++] = obj;
             //System.out.println("material " + material);
             //Applet3D.tracein("selected ", selected);
-            display.vector2buffer = obj.projectedVertices;
-            display.DrawMaterial(material, selected);
+            //display.vector2buffer = obj.projectedVertices;
+            display.DrawMaterial(material, selected, obj.projectedVertices);
         }
     }
     
@@ -399,8 +464,8 @@
                 materialdepth -= 1;
                 if (materialdepth > 0)
                 {
-                    display.vector2buffer = cStatic.objectstack[materialdepth - 1].projectedVertices;
-                    display.DrawMaterial(materialstack[materialdepth - 1], selectedstack[materialdepth - 1]);
+                    //display.vector2buffer = cStatic.objectstack[materialdepth - 1].projectedVertices;
+                    display.DrawMaterial(materialstack[materialdepth - 1], selectedstack[materialdepth - 1], cStatic.objectstack[materialdepth - 1].projectedVertices);
                 }
             //Applet3D.traceout("selected ", (stackdepth>0)?selectedstack[stackdepth-1]:"???");
             } else if (selected && CameraPane.flash && obj.GetMaterial() != null)
@@ -420,8 +485,8 @@
             materialdepth -= 1;
             if (materialdepth > 0)
             {
-                display.vector2buffer = cStatic.objectstack[materialdepth - 1].projectedVertices;
-                display.DrawMaterial(materialstack[materialdepth - 1], selectedstack[materialdepth - 1]);
+                //display.vector2buffer = cStatic.objectstack[materialdepth - 1].projectedVertices;
+                display.DrawMaterial(materialstack[materialdepth - 1], selectedstack[materialdepth - 1], cStatic.objectstack[materialdepth - 1].projectedVertices);
             }
         //Applet3D.traceout("selected ", (stackdepth>0)?selectedstack[stackdepth-1]:"???");
         //else
@@ -462,10 +527,12 @@
         if (!selectmode) // display.drawMode != display.SELECTION) // && display.drawMode != display.SHADOW) // (attributes & FILL) != 0)
         {
             //gl.glBegin(gl.GL_TRIANGLES);
-            boolean hasnorm = pv.norm != null; // && (pv.norm.x != 0 || pv.norm.y != 0 || pv.norm.z != 0);
+            boolean hasnorm = pv.norm != null && (pv.norm.x != 0 || pv.norm.y != 0 || pv.norm.z != 0)
+                    // TEST LIVE NORMALS && !obj.dontselect
+                    ;
             if (!hasnorm)
             {
-           //     System.out.println("FUCK!!");
+           //     System.out.println("Mesh normal");
                 LA.vecSub(pv/*.pos*/, qv/*.pos*/, obj.v0);
                 LA.vecSub(pv/*.pos*/, rv/*.pos*/, obj.v1);
                 LA.vecCross(obj.v0, obj.v1, obj.v2);
@@ -1190,10 +1257,12 @@
                                     gl.glColor4f(c[count3/3], c[count3/3 /* + 1*/], c[count3/3 /* + 2*/], 1);
                                 }
                             }
+                            
                             if (flipV)
                                 gl.glTexCoord2f(uv[count2], 1-uv[count2 + 1]);
                             else
                                 gl.glTexCoord2f(uv[count2], uv[count2 + 1]);
+                            
                             //System.out.println("vertex1 = " + v[count3] + ", " + v[count3+1] + ", " + v[count3+2]);
                             gl.glVertex3f(v[count3], v[count3 + 1], v[count3 + 2]);
 
@@ -1213,10 +1282,12 @@
                                     gl.glColor4f(c[count3/3], c[count3/3 /* + 1*/], c[count3/3 /* + 2*/], 1);
                                 }
                             }
+                            
                             if (flipV)
                                 gl.glTexCoord2f(uv[count2], 1-uv[count2 + 1]);
                             else
                                 gl.glTexCoord2f(uv[count2], uv[count2 + 1]);
+                            
                             //System.out.println("vertex2 = " + v[count3] + ", " + v[count3+1] + ", " + v[count3+2]);
                             gl.glVertex3f(v[count3], v[count3 + 1], v[count3 + 2]);
 
@@ -1244,8 +1315,10 @@
                                     gl.glTexCoord2f(uv[count2], 1-uv[count2 + 1]);
                                 else
                                     gl.glTexCoord2f(uv[count2], uv[count2 + 1]);
+                                
                                 //System.out.println("coord3 = " + uv[count2] + ", " + uv[count2+1]);
                                 gl.glVertex3f(v[count3], v[count3 + 1], v[count3 + 2]);
+                                
                                 count2 += 2;
                                 count3 += 3;
                             }
@@ -1424,6 +1497,8 @@
         gl.glVertex3f((float) pv.x, (float) pv.y, (float) pv.z);
     }
     
+    float[] colorV = new float[4];
+        
     void SetColor(Object3D obj, Vertex p0)
     {
         CameraPane display = this;
@@ -1491,8 +1566,6 @@
         {
             return;
         }
-        
-        float[] colorV = new float[3];
         
         if (false) // marked)
         {
@@ -1601,7 +1674,7 @@
 //        gl.glMaterialfv(gl.GL_BACK, gl.GL_DIFFUSE, colorV, 0);
     }
     
-    void DrawMaterial(cMaterial material, boolean selected)
+    void DrawMaterial(cMaterial material, boolean selected, Object3D.cVector2[] others)
     {
             CameraPane display = this;
         //new Exception().printStackTrace();
@@ -1636,7 +1709,7 @@
             colorV[0] = display.modelParams0[0] * material.diffuse;
             colorV[1] = display.modelParams0[1] * material.diffuse;
             colorV[2] = display.modelParams0[2] * material.diffuse;
-            colorV[3] = material.opacity;
+            colorV[3] = 1; // material.opacity;
 
             gl.glColor4f(colorV[0], colorV[1], colorV[2], material.opacity);
             //System.out.println("Opacity = " + opacity);
@@ -1744,9 +1817,9 @@
         display.modelParams7[2] = 0;
         display.modelParams7[3] = 0;
 
-        display.modelParams6[0] = 100; // criss de bug de bump
+        //display.modelParams6[0] = 100; // criss de bug de bump
         
-        Object3D.cVector2[] extparams = display.vector2buffer;
+        Object3D.cVector2[] extparams = others; // display.vector2buffer;
         if (extparams != null && extparams.length > 0 && extparams[0] != null)
         {
             display.modelParams6[0] = extparams[0].x / 1000.0f; // bump
@@ -1888,7 +1961,7 @@
     void PushMatrix(double[][] matrix)
     {
     //    GrafreeD.tracein(matrix);
-        PushMatrix(matrix,1);
+        PushMatrix(matrix, 1);
     }
     
     void PushMatrix()
@@ -2042,7 +2115,7 @@
             //System.err.println("Oeil on");
             OEIL = true;
             if ((TRACK || SHADOWTRACK) && trackedobject != null && DrawMode() == SHADOW) // && !lightMode)
-                object.editWindow.ScreenFit(trackedobject, SHADOWTRACK && !TRACK);
+                object.GetWindow().ScreenFit(trackedobject, SHADOWTRACK && !TRACK);
             //pingthread.StepToTarget(true);
         }
         
@@ -2257,7 +2330,7 @@
     
     void ToggleDebug()
     {
-        DEBUG ^= true;
+        Globals.DEBUG ^= true;
     }
 
     void ToggleLookAt()
@@ -2265,7 +2338,7 @@
         LOOKAT ^= true;
     }
 
-    void ToggleRandom()
+    void ToggleSwitch()
     {
         SWITCH ^= true;
     }
@@ -2275,10 +2348,17 @@
         HANDLES ^= true;
     }
 
+    Object3D paintFolder;
+    
     void TogglePaint()
     {
         PAINTMODE ^= true;
         paintcount = 0;
+        
+        if (PAINTMODE)
+        {
+            paintFolder = GetFolder();
+        }
     }
 
     void SwapCamera(int a, int b)
@@ -2374,7 +2454,22 @@
     {
         return currentGL;
     }
-    
+
+    static private BufferedImage CreateBim(TextureData texturedata)
+    {
+        Grafreed.Assert(texturedata != null);
+        
+        int width = texturedata.getWidth();
+        int height = texturedata.getHeight();
+        
+        Buffer buffer = texturedata.getBuffer();
+        ByteBuffer bytebuf = (ByteBuffer)buffer;
+        
+        byte[] bytes = bytebuf.array();
+        
+        return CreateBim(bytes, width, height);
+    }
+
     /**/
     class CacheTexture
     {
@@ -2383,28 +2478,31 @@
         
         int resolution;
         
-        CacheTexture(com.sun.opengl.util.texture.Texture tex, int res)
+        CacheTexture(com.sun.opengl.util.texture.TextureData texdata, int res)
         {
-            texture = tex;
+            texture = com.sun.opengl.util.texture.TextureIO.newTexture(texdata);
+            texturedata = texdata;
             resolution = res;
         }
     }
     /**/
     
 // TEXTURE	static Texture texture;
-    static public java.util.Hashtable<String, CacheTexture/*com.sun.opengl.util.texture.Texture*/> textures
-            = new java.util.Hashtable<String, CacheTexture/*com.sun.opengl.util.texture.Texture*/>();
-    static public java.util.Hashtable<String, String> usedtextures = new java.util.Hashtable<String, String>();
+    static public Hashtable<cTexture, CacheTexture> texturepigment = new Hashtable<cTexture, CacheTexture>();
+    static public Hashtable<cTexture, CacheTexture> texturebump = new Hashtable<cTexture, CacheTexture>();
+    static public Hashtable<byte[], CacheTexture> bimtextures = new Hashtable<byte[], CacheTexture>();
+    static public java.util.HashSet<cTexture> usedtextures = new java.util.HashSet<cTexture>();
+    
     int pigmentdepth = 0;
     public com.sun.opengl.util.texture.Texture[] pigmentstack = new com.sun.opengl.util.texture.Texture[65536];
     int bumpdepth = 0;
     public com.sun.opengl.util.texture.Texture[] bumpstack = new com.sun.opengl.util.texture.Texture[65536];
     //public static String DEFAULT_TEXTURE = "DEFAULT_TEXTURE";
     public static cTexture DEFAULT_TEXTURES = new cTexture("DEFAULT_TEXTURE" + ":" + "DEFAULT_TEXTURE_BUMP");
-    public static String NOISE_TEXTURE = "WHITE_NOISE";
+    public static cTexture NOISE_TEXTURE = new cTexture("WHITE_NOISE:");
  //   public static cTexture IMMORTAL_TEXTURE = new cTexture("IMMORTAL");
 
-    com.sun.opengl.util.texture.Texture GetResourceTexture(String name, boolean bump)
+    com.sun.opengl.util.texture.TextureData GetResourceTexture(String name, boolean bump)
     {
         TextureData texturedata = null;
 
@@ -2423,13 +2521,34 @@
         if (bump)
             texturedata = ConvertBump(texturedata, false);
             
-        com.sun.opengl.util.texture.Texture texture =
-                com.sun.opengl.util.texture.TextureIO.newTexture(texturedata);
+//        com.sun.opengl.util.texture.Texture texture =
+//                com.sun.opengl.util.texture.TextureIO.newTexture(texturedata);
         
-        texture.setTexParameteri(javax.media.opengl.GL.GL_TEXTURE_WRAP_S, javax.media.opengl.GL.GL_REPEAT);
-        texture.setTexParameteri(javax.media.opengl.GL.GL_TEXTURE_WRAP_T, javax.media.opengl.GL.GL_REPEAT);
+        //texture.setTexParameteri(javax.media.opengl.GL.GL_TEXTURE_WRAP_S, javax.media.opengl.GL.GL_REPEAT);
+        //texture.setTexParameteri(javax.media.opengl.GL.GL_TEXTURE_WRAP_T, javax.media.opengl.GL.GL_REPEAT);
         
-        return texture;
+        return texturedata;
+    }
+    
+    com.sun.opengl.util.texture.TextureData GetBimTexture(BufferedImage bim, boolean bump)
+    {
+        TextureData texturedata = null;
+
+        try
+        {
+            texturedata =
+                    com.sun.opengl.util.texture.TextureIO.newTextureData(
+                    bim,
+                    true);
+        } catch (Exception e)
+        {
+            throw new javax.media.opengl.GLException(e);
+        }
+
+        if (bump)
+            texturedata = ConvertBump(texturedata, false);
+                
+        return texturedata;
     }
     
     boolean HUESMOOTH = true; // wrap around bug... true;
@@ -3502,6 +3621,8 @@
 
             System.out.println("LOADING TEXTURE : " + name);
 
+            Object x = texturedata.getMipmapData(); // .getBuffer();
+            
         // 
         if (false) // compressbit > 0)
         {
@@ -7900,7 +8021,7 @@
         String pigment = Object3D.GetPigment(tex);
         String bump = Object3D.GetBump(tex);
 
-        if (!tex.equals(":") && !tex.equals(DEFAULT_TEXTURES))
+        //if (!tex.equals(":") && !tex.equals(DEFAULT_TEXTURES))
         {
         //    System.out.print("RELEASE  +++++++++++++++  pigment = " + pigment);
         //    System.out.println("; bump = " + bump);
@@ -7915,11 +8036,69 @@
             pigment = null;
         }
         
-        ReleaseTexture(bump, true);
-        ReleaseTexture(pigment, false);
+        ReleaseTexture(tex, true);
+        ReleaseTexture(tex, false);
     }
     
-    void ReleaseTexture(String tex, boolean bump)
+    public void ReleasePigmentTexture(cTexture tex) // INTERFACE
+    {
+        if (/*tex == null ||*/ ambientOcclusion ) // || !textureon)
+        {
+            return;
+        }
+
+        if (tex == null)
+        {
+            ReleaseTexture(null, false);
+            return;
+        }
+        
+        String pigment = Object3D.GetPigment(tex);
+
+        //if (!tex.equals(":") && !tex.equals(DEFAULT_TEXTURES))
+        {
+        //    System.out.print("RELEASE  +++++++++++++++  pigment = " + pigment);
+        //    System.out.println("; bump = " + bump);
+        }
+        
+        if (pigment.equals(""))
+        {
+            pigment = null;
+        }
+        
+        ReleaseTexture(tex, false);
+    }
+    
+    public void ReleaseBumpTexture(cTexture tex) // INTERFACE
+    {
+        if (/*tex == null ||*/ ambientOcclusion ) // || !textureon)
+        {
+            return;
+        }
+
+        if (tex == null)
+        {
+            ReleaseTexture(null, true);
+            return;
+        }
+        
+        String bump = Object3D.GetBump(tex);
+
+        //if (!tex.equals(":") && !tex.equals(DEFAULT_TEXTURES))
+        {
+        //    System.out.print("RELEASE  +++++++++++++++  pigment = " + pigment);
+        //    System.out.println("; bump = " + bump);
+        }
+        
+        if (bump.equals(""))
+        {
+            bump = null;
+        }
+        
+        ReleaseTexture(tex, true);
+    }
+    
+    void ReleaseTexture(cTexture tex, boolean bump)
     {
         if (// DrawMode() != 0 || /*tex == null ||*/
                 ambientOcclusion ) // || !textureon)
@@ -7930,7 +8109,7 @@
         CacheTexture/*com.sun.opengl.util.texture.Texture*/ texture = null;
         
         if (tex != null)
-            texture = textures.get(tex);
+            texture = bump ? texturebump.get(tex) : texturepigment.get(tex);
 
 //        //assert( texture != null );
 //        if (texture == null)
@@ -8024,6 +8203,54 @@
 
     /*boolean*/ public void BindTextures(cTexture tex, int resolution) throws Exception // INTERFACE
     {
+//        if (// DrawMode() != 0 || /*tex == null ||*/
+//                ambientOcclusion ) // || !textureon)
+//        {
+//            return; // false;
+//        }
+//
+//        if (tex == null)
+//        {
+//            BindTexture(null,false,resolution);
+//            BindTexture(null,true,resolution);
+//            return;
+//        }
+//        
+//        String pigment = Object3D.GetPigment(tex);
+//        String bump = Object3D.GetBump(tex);
+//
+//        usedtextures.add(pigment);
+//        usedtextures.add(bump);
+//        
+//        //if (!tex.equals(":") && !tex.equals(DEFAULT_TEXTURES))
+//        {
+//        //    System.out.print("BIND  +++++++++++++++  pigment = " + pigment);
+//        //    System.out.println("; bump = " + bump);
+//        }
+//        
+//        if (bump.equals(""))
+//        {
+//            bump = null;
+//        }
+//        if (pigment.equals(""))
+//        {
+//            pigment = null;
+//        }
+//        
+//        GetGL().glActiveTexture(GetGL().GL_TEXTURE0);
+//        BindTexture(pigment, false, resolution);
+//        GetGL().glActiveTexture(GetGL().GL_TEXTURE2);
+//        BindTexture(bump, true, resolution);
+//        GetGL().glActiveTexture(GetGL().GL_TEXTURE0);
+//            
+//        return; // true;
+        
+        BindPigmentTexture(tex, resolution);
+        BindBumpTexture(tex, resolution);
+    }
+    
+    /*boolean*/ public void BindPigmentTexture(cTexture tex, int resolution) throws Exception // INTERFACE
+    {
         if (// DrawMode() != 0 || /*tex == null ||*/
                 ambientOcclusion ) // || !textureon)
         {
@@ -8033,17 +8260,47 @@
         if (tex == null)
         {
             BindTexture(null,false,resolution);
-            BindTexture(null,true,resolution);
             return;
         }
         
         String pigment = Object3D.GetPigment(tex);
+
+        usedtextures.add(tex);
+        
+        //if (!tex.equals(":") && !tex.equals(DEFAULT_TEXTURES))
+        {
+        //    System.out.print("BIND  +++++++++++++++  pigment = " + pigment);
+        //    System.out.println("; bump = " + bump);
+        }
+        
+        if (pigment.equals(""))
+        {
+            pigment = null;
+        }
+        
+        GetGL().glActiveTexture(GetGL().GL_TEXTURE0);
+        BindTexture(tex, false, resolution);
+    }
+    
+    /*boolean*/ public void BindBumpTexture(cTexture tex, int resolution) throws Exception // INTERFACE
+    {
+        if (// DrawMode() != 0 || /*tex == null ||*/
+                ambientOcclusion ) // || !textureon)
+        {
+            return; // false;
+        }
+
+        if (tex == null)
+        {
+            BindTexture(null,true,resolution);
+            return;
+        }
+        
         String bump = Object3D.GetBump(tex);
 
-        usedtextures.put(pigment, pigment);
-        usedtextures.put(bump, bump);
+        usedtextures.add(tex);
         
-        if (!tex.equals(":") && !tex.equals(DEFAULT_TEXTURES))
+        //if (!tex.equals(":") && !tex.equals(DEFAULT_TEXTURES))
         {
         //    System.out.print("BIND  +++++++++++++++  pigment = " + pigment);
         //    System.out.println("; bump = " + bump);
@@ -8053,47 +8310,94 @@
         {
             bump = null;
         }
-        if (pigment.equals(""))
-        {
-            pigment = null;
-        }
         
-        GetGL().glActiveTexture(GetGL().GL_TEXTURE0);
-        BindTexture(pigment, false, resolution);
         GetGL().glActiveTexture(GetGL().GL_TEXTURE2);
-        BindTexture(bump, true, resolution);
+        BindTexture(tex, true, resolution);
         GetGL().glActiveTexture(GetGL().GL_TEXTURE0);
-            
-        return; // true;
     }
     
-    CacheTexture GetCacheTexture(String tex, boolean bump, int resolution) throws Exception
+    java.util.HashSet<String> missingTextures = new java.util.HashSet<String>();
+    
+    private boolean FileExists(String tex)
     {
-        CacheTexture/*com.sun.opengl.util.texture.Texture*/ texture = null;
+        if (missingTextures.contains(tex))
+        {
+            return false;
+        }
+        
+        boolean fileExists = new File(tex).exists();
+        
+        if (!fileExists)
+        {
+            // If file exists, the "new File()" is not executed sgain
+            missingTextures.add(tex);
+        }
+        
+        return fileExists;
+    }
+    
+    CacheTexture GetCacheTexture(cTexture tex, boolean bump, int resolution) throws Exception
+    {
+        CacheTexture texturecache = null;
         
         if (tex != null)
         {
-            String texname = tex;
+            String texname = bump ? Object3D.GetBump(tex) : Object3D.GetPigment(tex);
+            byte[] texdata = bump ? tex.bumpdata : tex.pigmentdata;
             
+            if (texname.equals("") && texdata == null)
+            {
+                return null;
+            }
+            
+            String fallbackTextureName = defaultDirectory + "/Textures/" + texname;
+                
 //            String[] split = tex.split("Textures");
 //            if (split.length > 1)
 //                texname = "/Users/nbriere/Textures" + split[split.length-1];
 //            else
 //                if (!texname.startsWith("/"))
 //                    texname = "/Users/nbriere/Textures/" + texname;
-            if (!new File(tex).exists())
+            if (!FileExists(texname))
             {
-                    texname = javax.swing.filechooser.FileSystemView.getFileSystemView().getDefaultDirectory() + "/Textures/" + texname;
+                    texname = fallbackTextureName;
             }
             
             if (CACHETEXTURE)
-                texture = textures.get(texname); // TEXTURE CACHE
-
-            TextureData texturedata = null;
-            
-            if (texture == null || texture.resolution < resolution)
             {
-                if (tex.equals("DEFAULT_TEXTURE")) // ||*/ tex.equals(""))
+                if (texdata == null)
+                    texturecache = bump ? texturebump.get(tex) : texturepigment.get(tex);
+                else
+                    texturecache = bimtextures.get(texdata);
+            }
+
+            if (texturecache == null || texturecache.resolution != -1 && texturecache.resolution < resolution)
+            {
+                TextureData texturedata = null;
+            
+                if (texdata != null && textureon)
+                {
+                    BufferedImage bim; // = new BufferedImage(bump?tex.bw:tex.pw, bump?tex.bh:tex.ph, BufferedImage.TYPE_INT_RGB);
+                    
+                            try
+                            {
+                                bim = DecompressJPEG(texdata, bump?tex.bw:tex.pw, bump?tex.bh:tex.ph);                                
+                            }
+                            catch (Exception e)
+                            {
+                                bim = CreateBim(texdata, bump?tex.bw:tex.pw, bump?tex.bh:tex.ph);
+                            }
+                    
+                    texturecache = new CacheTexture(GetBimTexture(bim, bump), -1);
+                    bimtextures.put(texdata, texturecache);
+                    
+                    //BufferedImage bim3 = new BufferedImage(bump?tex.bw:tex.pw, bump?tex.bh:tex.ph, BufferedImage.TYPE_INT_RGB);
+                            
+                    //Object bim2 = CreateBim(texturecache.texturedata);
+                    //bim2 = bim;
+                }
+                else
+                if (texname.endsWith("DEFAULT_TEXTURE")) // ||*/ tex.equals(""))
                 {
                     assert(!bump);
 //                    if (bump)
@@ -8104,19 +8408,23 @@
 //                    }
 //                    else
 //                    {
-                        texture = textures.get(tex);
-                        if (texture == null)
+                  //      texturecache = textures.get(texname); // suspicious
+                        if (texturecache == null)
                         {
-                            texture = new CacheTexture(GetResourceTexture("default.png", bump),resolution);
+                            texturecache = new CacheTexture(GetResourceTexture("default.png", bump),resolution);
                         }
+                        else
+                            new Exception().printStackTrace();
 //                    }
                 } else
-                if (tex.equals("DEFAULT_TEXTURE_BUMP")) // ||*/ tex.equals(""))
+                if (texname.endsWith("DEFAULT_TEXTURE_BUMP")) // ||*/ tex.equals(""))
                 {
                     assert(bump);
-                    texture = textures.get(tex);
-                    if (texture == null)
-                        texture = new CacheTexture(GetResourceTexture("default.png", bump),resolution);
+              //      texturecache = textures.get(texname); // suspicious
+                    if (texturecache == null)
+                        texturecache = new CacheTexture(GetResourceTexture("default.png", bump),resolution);
+                    else
+                        new Exception().printStackTrace();
                 } else
                 {
                     //if (tex.equals("IMMORTAL"))
@@ -8124,11 +8432,13 @@
                     //    texture = GetResourceTexture("default.png");
                     //} else
                     //{
-                        if (tex.equals("WHITE_NOISE"))
+                        if (texname.endsWith("WHITE_NOISE"))
                         {
-                            texture = textures.get(tex);
-                            if (texture == null)
-                                texture = new CacheTexture(GetResourceTexture("whitenoise.png", bump),resolution);
+                //            texturecache = textures.get(texname); // suspicious
+                            if (texturecache == null)
+                                texturecache = new CacheTexture(GetResourceTexture("whitenoise.png", bump),resolution);
+                            else
+                                new Exception().printStackTrace();
                         } else
                         {
                             if (textureon)
@@ -8153,7 +8463,7 @@
                                     }
                                 
                                     cachename = texname.substring(0, texname.length()-4)+ext+".jpg";
-                                    if (!new File(cachename).exists())
+                                    if (!FileExists(cachename))
                                         cachename = texname;
                                     else
                                         processbump = false; // don't process bump map again
@@ -8175,7 +8485,7 @@
                                     }
                                 
                                     cachename = texname.substring(0, texname.length()-4)+ext+".png";
-                                    if (!new File(cachename).exists())
+                                    if (!FileExists(cachename))
                                         cachename = texname;
                                     else
                                         processbump = false; // don't process bump map again
@@ -8187,19 +8497,19 @@
                                 if (texturedata == null)
                                     throw new Exception();
                                     
-                                    texture = new CacheTexture(com.sun.opengl.util.texture.TextureIO.newTexture(texturedata),resolution);
+                                    texturecache = new CacheTexture(texturedata,resolution);
         //texture = GetTexture(tex, bump);
                             }
                         }
                     //}
                 }
 
-                if (/*CACHETEXTURE &&*/ texture != null && textureon)
+                if (texdata == null && /*CACHETEXTURE &&*/ texturecache != null && textureon)
                 {
                     //return false;
 
              //       System.out.println("CACHE  +++++++++++++++  TEXTURE : " + texname + " (" + texture.getEstimatedMemorySize() + ")");
-                    if (texturedata != null && (texname.endsWith(".jpg") || texname.endsWith(".JPG")))
+                    if (texturedata != null && texname.toLowerCase().endsWith(".jpg"))
                     {
 //                        String ext = "_highres";
 //                        if (REDUCETEXTURE)
@@ -8216,52 +8526,17 @@
                         File cachefile = new File(texname.substring(0, texname.length()-4)+ext+".jpg");
                         if (!cachefile.exists())
                         {
-                            // cache to disk
-                            Buffer buffer = texturedata.getBuffer(); // getMipmapData();
-                        //buffers[0].
-
-                            ByteBuffer bytebuf = (ByteBuffer)buffer; // ).asIntBuffer();
-                            int[] pixels = new int[bytebuf.capacity()/3];
-                            
-                            // squared size heuristic...
-                            if ((int)Math.sqrt(pixels.length) == Math.sqrt(pixels.length))
+                            //if (texturedata.getWidth() == texturedata.getHeight())
                             {
-                                for (int i=pixels.length; --i>=0;)
-                                {
-                                    int i3 = i*3;
-                                    pixels[i] = 0xFF;
-                                    pixels[i] <<= 8;
-                                    pixels[i] |= bytebuf.get(i3+2) & 0xFF;
-                                    pixels[i] <<= 8;
-                                    pixels[i] |= bytebuf.get(i3+1) & 0xFF;
-                                    pixels[i] <<= 8;
-                                    pixels[i] |= bytebuf.get(i3) & 0xFF;
-                                }
-
-                /*
-                int r=0,g=0,b=0,a=0;
-                for (int i=0; i<width; i++)
-                for (int j=0; j<height; j++)
-                {
-                int index = j*width+i;
-                int p = pixels[index];
-                a = ((p>>24) & 0xFF);
-                r = ((p>>16) & 0xFF);
-                g = ((p>>8) & 0xFF);
-                b = (p & 0xFF);
-                pixels[index] = (a<<24) | (b<<16) | (g<<8) | r;
-                }
-                /**/
-                                int width = (int)Math.sqrt(pixels.length); // squared
-                                int height = width;
-                                BufferedImage rendImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // ImageIO.read(infile);
-                                rendImage.setRGB(0,0,width,height,pixels,width*(height-1),-width);
+                                BufferedImage rendImage = CreateBim(texturedata);
+                                
                                 ImageWriter writer = null;
                                 Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
                                 if (iter.hasNext()) {
                                     writer = (ImageWriter)iter.next();
                                 }
-                                float compressionQuality = 0.9f;
+                                
+                                float compressionQuality = 0.85f;
                                 try
                                 {
                                     ImageOutputStream ios = ImageIO.createImageOutputStream(cachefile);
@@ -8278,18 +8553,20 @@
                             }
                         }
                     }
-                            
+                    
+                    Hashtable<cTexture, CacheTexture> textures = bump ? texturebump : texturepigment;
+                    
                     //System.out.println("Texture = " + tex);
-                    if (textures.containsKey(texname))
+                    if (textures.containsKey(tex))
                     {
-                        CacheTexture thetex = textures.get(texname);
+                        CacheTexture thetex = textures.get(tex);
                         thetex.texture.disable();
                         thetex.texture.dispose();
-                        textures.remove(texname);
+                        textures.remove(tex);
                     }
                     
-                    texture.texturedata = texturedata;
-                    textures.put(texname, texture);
+                    //texture.texturedata = texturedata;
+                    textures.put(tex, texturecache);
 
            //         newtex = true;
                 }
@@ -8305,10 +8582,44 @@
             }
         }
         
-        return texture;
+        return texturecache;
     }
     
-    com.sun.opengl.util.texture.Texture GetTexture(String tex, boolean bump, int resolution) throws Exception
+    static void EmbedTextures(cTexture tex)
+    {
+        if (tex.pigmentdata == null)
+        {
+            //String texname = Object3D.GetPigment(tex);
+            
+            CacheTexture texturecache = texturepigment.get(tex);
+            
+            if (texturecache != null)
+            {
+                tex.pw = texturecache.texturedata.getWidth();
+                tex.ph = texturecache.texturedata.getHeight();
+                tex.pigmentdata = //CompressJPEG(CreateBim
+                        ((ByteBuffer)texturecache.texturedata.getBuffer()).array()
+                        ;
+                        //, tex.pw, tex.ph), 0.5f);
+            }
+        }
+        
+        if (tex.bumpdata == null)
+        {
+            //String texname = Object3D.GetBump(tex);
+            
+            CacheTexture texturecache = texturebump.get(tex);
+            
+            if (texturecache != null)
+            {
+                tex.bw = texturecache.texturedata.getWidth();
+                tex.bh = texturecache.texturedata.getHeight();
+                tex.bumpdata = CompressJPEG(CreateBim(((ByteBuffer)texturecache.texturedata.getBuffer()).array(), tex.bw, tex.bh), 0.5f);
+            }
+        }
+    }
+    
+    com.sun.opengl.util.texture.Texture GetTexture(cTexture tex, boolean bump, int resolution) throws Exception
     {
         CacheTexture texture = GetCacheTexture(tex, bump, resolution);
                 
@@ -8326,21 +8637,21 @@
         return texture!=null?texture.texture:null;
     }
     
-    public com.sun.opengl.util.texture.TextureData GetTextureData(String tex, boolean bump, int resolution) throws Exception
+    public com.sun.opengl.util.texture.TextureData GetTextureData(cTexture tex, boolean bump, int resolution) throws Exception
     {
         CacheTexture texture = GetCacheTexture(tex, bump, resolution);
                 
         return texture!=null?texture.texturedata:null;
     }
     
-    boolean BindTexture(String tex, boolean bump, int resolution) throws Exception
+    boolean BindTexture(cTexture tex, boolean bump, int resolution) throws Exception
     {
         if (/*tex == null ||*/ ambientOcclusion ) // || !textureon)
         {
             return false;
         }
 
-        boolean newtex = false;
+        //boolean newtex = false;
 
         com.sun.opengl.util.texture.Texture texture = GetTexture(tex, bump, resolution);
 
@@ -8372,9 +8683,75 @@
         texture.setTexParameteri(GetGL().GL_TEXTURE_WRAP_S, GetGL().GL_REPEAT);
         texture.setTexParameteri(GetGL().GL_TEXTURE_WRAP_T, GetGL().GL_REPEAT);
         
-        return newtex;
+        return true; // Warning: not used.
     }
     
+    public static byte[] CompressJPEG(BufferedImage image, float quality)
+    {
+        try
+        {
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
+            ImageWriter writer = writers.next();
+
+            ImageWriteParam param = writer.getDefaultWriteParam();
+            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
+            param.setCompressionQuality(quality);
+
+            ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
+            writer.setOutput(ios);
+            writer.write(null, new IIOImage(image, null, null), param);
+
+            byte[] data = baos.toByteArray();
+            writer.dispose();
+            return data;
+        }
+        catch (Exception e)
+        {
+            e.printStackTrace();
+            return null;
+        }
+    }
+
+    public static BufferedImage DecompressJPEG(byte[] image, int w, int h) throws IOException
+    {
+        ByteArrayInputStream baos = new ByteArrayInputStream(image);
+        Iterator<ImageReader> writers = ImageIO.getImageReadersByFormatName("jpg");
+        ImageReader reader = writers.next();
+        
+        BufferedImage bim = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
+        
+        ImageReadParam param = reader.getDefaultReadParam();
+        param.setDestination(bim);
+        //param.setDestinationType(ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB));
+
+        ImageInputStream ios = ImageIO.createImageInputStream(baos);
+        reader.setInput(ios);
+        BufferedImage bim2 = reader.read(0, param);
+        reader.dispose();
+        
+//        WritableRaster raster = bim2.getRaster();
+//        DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();
+//        byte[] bytes = data.getData();
+//        
+//        int[] pixels = new int[bytes.length/3];
+//        for (int i=pixels.length; --i>=0;)
+//        {
+//            int i3 = i*3;
+//            pixels[i] = 0xFF;
+//            pixels[i] <<= 8;
+//            pixels[i] |= bytes[i3+2] & 0xFF;
+//            pixels[i] <<= 8;
+//            pixels[i] |= bytes[i3+1] & 0xFF;
+//            pixels[i] <<= 8;
+//            pixels[i] |= bytes[i3] & 0xFF;
+//        }
+//        
+//        bim.setRGB(0,0,w,h, pixels, w*(h-1),-w);
+        
+        return bim;
+    }
+
     ShadowBuffer shadowPBuf;
     AntialiasBuffer antialiasPBuf;
     int MAXSTACK;
@@ -8567,7 +8944,7 @@
 
         if (cubemap == null)
         {
-            LoadEnvy(5);
+            //LoadEnvy(1);
         }
 
         //cubemap.enable();
@@ -8854,37 +9231,58 @@
                 cubemap = null;
                 return;
             case 1:
-                name = "cubemaps/box_";
-                ext = "png";
+                name = "cubemaps/rgb/";
+                ext = "jpg";
                 reverseUP = false;
                 break;
             case 2:
-                name = "cubemaps/uffizi_";
-                ext = "png";
-                break; // reverseUP = true; break;
+                name = "cubemaps/uffizi/";
+                ext = "jpg";
+                reverseUP = false;
+                break;
             case 3:
-                name = "cubemaps/CloudyHills_";
-                ext = "tga";
+                name = "cubemaps/CloudyHills/";
+                ext = "jpg";
                 reverseUP = false;
                 break;
             case 4:
-                name = "cubemaps/cornell_";
+                name = "cubemaps/cornell/";
                 ext = "png";
                 reverseUP = false;
                 break;
+            case 5:
+                name = "cubemaps/skycube/";
+                ext = "jpg";
+                reverseUP = false;
+                break;
+            case 6:
+                name = "cubemaps/SaintLazarusChurch3/";
+                ext = "jpg";
+                reverseUP = false;
+                break;
+            case 7:
+                name = "cubemaps/Sodermalmsallen/";
+                ext = "jpg";
+                reverseUP = false;
+                break;
+            case 8:
+                name = "cubemaps/Sodermalmsallen2/";
+                ext = "jpg";
+                reverseUP = false;
+                break;
+            case 9:
+                name = "cubemaps/UnionSquare/";
+                ext = "jpg";
+                reverseUP = false;
+                break;
             default:
-                name = "cubemaps/rgb_";
-                ext = "png"; /*mipmap = true;*/ reverseUP = false;
+                name = "cubemaps/box/";
+                ext = "png"; /*mipmap = true;*/
+                reverseUP = false;
                 break;
         }
-
-        try
-        {
-            cubemap = LoadCubemap(getClass().getClassLoader(), name, ext, mipmap);
-        } catch (IOException e)
-        {
-            throw new RuntimeException(e);
-        }
+        
+        LoadSkybox(name, ext, mipmap);
     }
 
     public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height)
@@ -8916,8 +9314,12 @@
     static double[] model = new double[16];
     double[] camera2light = new double[16];
     double[] light2camera = new double[16];
-    int newenvy = -1;
-    boolean envyoff = true; // false;
+    
+    //int newenvy = -1;
+    //boolean envyoff = false;
+    
+    String loadedskyboxname;
+    
     cVector light0 = new cVector(0, 0, 0); // 1,3,2);
     //float[] light0 = { 0,0,0 };
     cVector dirlight = new cVector(0, 0, 1); // 1,3,2);
@@ -9210,11 +9612,35 @@
         jy8[3] = 0.5f;
     }
     
-    float[] options1 = new float[]{1000, 0.00001f, 20, 0, 0}; // focus, aperture, Shadow blur, aniso, anisoV
+    float[] options1 = new float[]{100, 0.00001f, 20, 0, 0}; // focus, aperture, Shadow blur, aniso, anisoV
     float[] options2 = new float[]{0, 1, 0, 0}; // fog density, intensity, elevation
     float[] options3 = new float[]{1, 1, 1, 0}; // fog color
     float[] options4 = new float[]{1, 0, 1, 0}; // image intensity, subsurface, lightsheen
 
+    void ResetOptions()
+    {
+        options1[0] = 100;
+        options1[1] = 0.025f;
+        options1[2] = 0.01f;
+        options1[3] = 0;
+        options1[4] = 0;
+        
+        options2[0] = 0;
+        options2[1] = 0.75f;
+        options2[2] = 0;
+        options2[3] = 0;
+        
+        options3[0] = 1;
+        options3[1] = 1;
+        options3[2] = 1;
+        options3[3] = 0;
+        
+        options4[0] = 1;
+        options4[1] = 0;
+        options4[2] = 1;
+        options4[3] = 0;
+    }
+    
     static int imagecount = 0; // movie generation
     
     static int jitter = 0;
@@ -9310,8 +9736,8 @@
         assert (parentcam != renderCamera);
         
         if (renderCamera != lightCamera)
-        for (int count = parentcam.GetTransformCount(); --count>=0;)
-            LA.matConcat(matrix, parentcam.toParent, matrix);
+        //for (int count = parentcam.GetTransformCount(); --count>=0;)
+            LA.matConcat(matrix, parentcam.GlobalTransformInv(), matrix);
         
 //            LA.matConcat(renderCamera.toScreen, renderCamera.toParent, matrix);
             
@@ -9326,8 +9752,8 @@
             LA.matCopy(renderCamera.fromScreen, matrix);
             
         if (renderCamera != lightCamera)
-        for (int count = parentcam.GetTransformCount(); --count>=0;)
-            LA.matConcat(parentcam.fromParent, matrix, matrix);
+        //for (int count = parentcam.GetTransformCount(); --count>=0;)
+            LA.matConcat(parentcam.GlobalTransform(), matrix, matrix);
 
 //            LA.matConcat(renderCamera.fromParent, renderCamera.fromScreen, matrix);
             
@@ -9373,10 +9799,12 @@
                 rati = 1 / rati;
                 gl.glOrtho(-skyscale / rati, skyscale / rati, -skyscale, skyscale, 0.001, 1000);
             }
-            assert (newenvy == -1);
+            
+            //assert (newenvy == -1);
+            
             gl.glDisable(GL.GL_FRAGMENT_PROGRAM_ARB);
             gl.glDisable(GL.GL_VERTEX_PROGRAM_ARB);
-            DrawSkyBox(gl);
+            DrawSkyBox(gl, (float)rati);
             gl.glEnable(GL.GL_FRAGMENT_PROGRAM_ARB);
             gl.glEnable(GL.GL_VERTEX_PROGRAM_ARB);
             accPerspective(gl, renderCamera.shaper_fovy / ratio,
@@ -10325,6 +10753,7 @@
                     ANTIALIAS = 0;
                     //System.out.println("RESTART");
                     AAtimer.restart();
+                    Globals.TIMERRUNNING = true;
                 }
             }
         }
@@ -10392,13 +10821,14 @@
             ambientOcclusion = false;
         }
 
-        if (Globals.lighttouched && DrawMode() == DEFAULT && !lightMode) // && !FROZEN)
+        if (//Globals.lighttouched &&
+                DrawMode() == DEFAULT) // && !lightMode) // && !FROZEN)
         {
             //if (RENDERSHADOW) // ?
             if (!IsFrozen())
             {
                 // dec 2012
-                if (!ambientOcclusion && !(!flash && !lightMode && DrawMode() == DEFAULT && ANTIALIAS > 0))
+                if (!ambientOcclusion && !(!flash && DrawMode() == DEFAULT && ANTIALIAS > 0))
                 {
             Globals.framecount++;
                     shadowbuffer.display();
@@ -10525,8 +10955,8 @@
             
 //        if (parentcam != renderCamera) // not a light
         if (cam != lightCamera)
-            for (int count = parentcam.GetTransformCount(); --count>=0;)
-                LA.matConcat(matrix, parentcam.toParent, matrix);
+            //for (int count = parentcam.GetTransformCount(); --count>=0;)
+                LA.matConcat(matrix, parentcam.GlobalTransformInv(), matrix);
             
             for (int j = 0; j < 4; j++)
             {
@@ -10540,8 +10970,8 @@
             
 //        if (parentcam != renderCamera) // not a light
         if (cam != lightCamera)
-            for (int count = parentcam.GetTransformCount(); --count>=0;)
-                LA.matConcat(parentcam.fromParent, matrix, matrix);
+            //for (int count = parentcam.GetTransformCount(); --count>=0;)
+                LA.matConcat(parentcam.GlobalTransform(), matrix, matrix);
         
             //LA.matConcat(cam.fromScreen, parentcam.fromParent, matrix);
             
@@ -10627,13 +11057,27 @@
             gl.glOrtho(-skyscale / ratio, skyscale / ratio, -skyscale, skyscale, 0.001, 1000);
         }
 
-        if (newenvy > -1)
+//        if (newenvy > -1)
+//        {
+//            LoadEnvy(newenvy);
+//        }
+//
+//        newenvy = -1;
+        
+        if (object.skyboxname != null)
         {
-            LoadEnvy(newenvy);
+            if (!object.skyboxname.equals(this.loadedskyboxname))
+            {
+                LoadSkybox(object.skyboxname + "/", object.skyboxext, false);
+                loadedskyboxname = object.skyboxname;
+            }
         }
-
-        newenvy = -1;
-
+        else
+        {
+            cubemap = null;
+            loadedskyboxname = null;
+        }
+        
         ratio = ((double) getWidth()) / getHeight();
         //System.out.println("ratio = " + ratio);
 
@@ -10649,7 +11093,7 @@
 
             if (!IsFrozen() && !ambientOcclusion)
             {
-                DrawSkyBox(gl);
+                DrawSkyBox(gl, (float)ratio);
             }
 
             //if (selection_view == -1)
@@ -10832,9 +11276,9 @@
 
             gl.glMatrixMode(GL.GL_MODELVIEW);
 
-//gl.glHint(gl.GL_POLYGON_SMOOTH_HINT, gl.GL_NICEST);
-//gl.glEnable(gl.GL_POLYGON_SMOOTH);
-//gl.glEnable(gl.GL_MULTISAMPLE);
+gl.glEnable(gl.GL_POLYGON_SMOOTH);
+gl.glHint(gl.GL_POLYGON_SMOOTH_HINT, gl.GL_NICEST);
+gl.glEnable(gl.GL_MULTISAMPLE);
         } else
         {
             //gl.glDisable(GL.GL_TEXTURE_2D);
@@ -10845,7 +11289,7 @@
         //System.out.println("BLENDING ON");
         gl.glEnable(GL.GL_BLEND);
         gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
-
+//        gl.glBlendFunc(GL.GL_SRC_ALPHA_SATURATE, GL.GL_ONE);
         gl.glMatrixMode(gl.GL_PROJECTION);
         gl.glLoadIdentity();
 
@@ -10934,8 +11378,8 @@
                 System.err.println("parentcam != renderCamera");
 
 //            if (cam != lightCamera)
-            for (int count = parentcam.GetTransformCount(); --count>=0;)
-                LA.xformDir(lightposition, parentcam.toParent, lightposition); // may 2013
+            //for (int count = parentcam.GetTransformCount(); --count>=0;)
+                LA.xformDir(lightposition, parentcam.GlobalTransformInv(), lightposition); // may 2013
         }
         
         LA.xformDir(lightposition, cam.toScreen, lightposition);
@@ -10956,8 +11400,8 @@
             if (true) // TODO
             {
                 if (cam != lightCamera)
-                for (int count = parentcam.GetTransformCount(); --count>=0;)
-                   LA.xformDir(light0, parentcam.toParent, light0); // may 2013
+                //for (int count = parentcam.GetTransformCount(); --count>=0;)
+                   LA.xformDir(light0, parentcam.GlobalTransform(), light0); // may 2013
             }
             
             LA.xformPos(light0, cam.toScreen, light0);
@@ -11094,7 +11538,7 @@
             }
         }
 
-        if (false) // fast && !IsFreezed() && DrawMode() != SELECTION && !ambientOcclusion)
+        if (false) //RENDERPROGRAM > 0 && DrawMode() == DEFAULT) // fast && !IsFreezed() && DrawMode() != SELECTION && !ambientOcclusion)
         {
             //gl.glDepthFunc(GL.GL_LEQUAL);
             //gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT);
@@ -11102,24 +11546,21 @@
 
             boolean texon = textureon;
 
-            if (RENDERPROGRAM > 0)
-            {
-                gl.glDisable(GL.GL_FRAGMENT_PROGRAM_ARB);
-                textureon = false;
-            }
+            gl.glDisable(GL.GL_FRAGMENT_PROGRAM_ARB);
+            textureon = false;
+            
             //gl.glDisable(GL.GL_VERTEX_PROGRAM_ARB);
             //System.out.println("ALLO");
             gl.glColorMask(false, false, false, false);
             DrawObject(gl);
-            if (RENDERPROGRAM > 0)
-            {
-                gl.glEnable(GL.GL_FRAGMENT_PROGRAM_ARB);
-                textureon = texon;
-            }
+            
+            gl.glEnable(GL.GL_FRAGMENT_PROGRAM_ARB);
+            textureon = texon;
+
             gl.glColorMask(true, true, true, true);
 
             gl.glDepthFunc(GL.GL_EQUAL);
-        //gl.glDepthMask(false);
+            gl.glDepthMask(false);
         }
 
         if (false) // DrawMode() == SHADOW)
@@ -11302,15 +11743,36 @@
 
     static boolean zoomonce = false;
     
+    static void CreateSelectedPoint()
+    {
+        if (selectedpoint == null)
+        {
+            debugpointG = new Sphere();
+            debugpointP = new Sphere();
+            debugpointC = new Sphere();
+            debugpointR = new Sphere();
+            
+            selectedpoint = new Superellipsoid();
+            
+            for (int i=0; i<8; i++)
+            {
+                debugpoints[i] = new Sphere();
+            }
+        }
+    }
+    
     void DrawObject(GL gl, boolean draw)
     {
+        // To clear camera values
+        ResetOptions();
+        
         //System.out.println("DRAW OBJECT " + mouseDown);
 //        DrawMode() = SELECTION;
         //GL gl = getGL();
         if ((TRACK || SHADOWTRACK) || zoomonce)
         {
             if ((TRACK || SHADOWTRACK) && trackedobject != null && DrawMode() == SHADOW) // && !lightMode)
-                object.editWindow.ScreenFit(trackedobject, SHADOWTRACK && !TRACK);
+                object.GetWindow().ScreenFit(trackedobject, SHADOWTRACK && !TRACK);
             pingthread.StepToTarget(true); // true);
        //     zoomonce = false;
         }
@@ -11382,8 +11844,9 @@
             
             if (DrawMode() == DEFAULT)
             {
-                if (DEBUG)
+                if (Globals.DEBUG)
                 {
+                    CreateSelectedPoint();
                     float radius = 0.05f;
                     if (selectedpoint.radius != radius)
                     {
@@ -11437,20 +11900,32 @@
                 ReleaseTextures(DEFAULT_TEXTURES);
 
                 if (CLEANCACHE)
-                for (java.util.Enumeration<String> e = textures.keys() ; e.hasMoreElements();)
+                for (java.util.Enumeration<cTexture> e = texturepigment.keys() ; e.hasMoreElements();)
                 {
-                    String tex = e.nextElement();
+                    cTexture tex = e.nextElement();
 
            //     System.out.println("Texture --------- " + tex);
 
-                    if (tex.equals("WHITE_NOISE"))
+                    if (tex.equals("WHITE_NOISE:"))
                         continue;
 
-                    if (!usedtextures.containsKey(tex))
+                    if (!usedtextures.contains(tex))
                     {
+                        CacheTexture gettex = texturepigment.get(tex);
                //         System.out.println("DISPOSE  +++++++++++++++  " + tex);
-                        textures.get(tex).texture.dispose();
-                        textures.remove(tex);
+                        if (gettex != null)
+                        {
+                            gettex.texture.dispose();
+                            texturepigment.remove(tex);
+                        }
+                        
+                        gettex = texturebump.get(tex);
+               //         System.out.println("DISPOSE  +++++++++++++++  " + tex);
+                        if (gettex != null)
+                        {
+                            gettex.texture.dispose();
+                            texturebump.remove(tex);
+                        }
                     }
                 }
             }
@@ -11552,7 +12027,7 @@
             return;
         }
 
-        String string = obj.GetToolTip();
+        String string = obj.toString(); //.GetToolTip();
         
         GL gl = GetGL();
         
@@ -11869,8 +12344,8 @@
             //obj.TransformToWorld(light, light);
             for (int i = tp.size(); --i >= 0;)
             {
-                for (int count = tp.get(i).GetTransformCount(); --count>=0;)
-                    LA.xformPos(light, tp.get(i).toParent, light);
+                //for (int count = tp.get(i).GetTransformCount(); --count>=0;)
+                    LA.xformPos(light, tp.get(i).GlobalTransformInv(), light);
             }
 
 
@@ -11887,8 +12362,8 @@
                 parentcam = cameras[0];
             }
             
-        for (int count = parentcam.GetTransformCount(); --count>=0;)
-            LA.xformPos(light, parentcam.toParent, light); // may 2013
+        //for (int count = parentcam.GetTransformCount(); --count>=0;)
+            LA.xformPos(light, parentcam.GlobalTransform(), light); // may 2013
 
             LA.xformPos(light, renderCamera.toScreen, light);
             
@@ -11978,8 +12453,76 @@
 
         //gl.glProgramEnvParameter4fvARB(GL.GL_FRAGMENT_PROGRAM_ARB, 127, lightParams, 0);
 
-        String program =
+        String programmin =
+                // Min shader
                 "!!ARBfp1.0\n" +
+                "PARAM zero123      = { 0.0, 1.0, 2, 1.25 };" +
+                "PARAM pow2      = { 0.5, 0.25, 0.125, 0.0 };" +
+                "PARAM one      = { 1.0, 1.0, 1.0, 1.0 };" +
+                "PARAM eps      = { 0.001, 0.001, 0.001, 1.0 };" +
+                "PARAM infinity  = { 100000000, 100000000, 100000000, 1.0 };" +
+                "PARAM light2cam0   = program.env[10];" +
+                "PARAM light2cam1   = program.env[11];" +
+                "PARAM light2cam2   = program.env[12];" +
+                "TEMP temp;" +
+                "TEMP light;" +
+                "TEMP ndotl;" +
+                "TEMP normal;" +
+                "TEMP depth;" +
+                "TEMP eye;" +
+                "TEMP pos;" +
+                
+                "MAD normal, fragment.color, zero123.z, -zero123.y;" +
+                Normalize("normal") +
+                "MOV light, state.light[0].position;" +
+                "DP3 ndotl.x, light, normal;" +
+
+                // shadow
+                "MOV pos, fragment.texcoord[1];" +
+                "MOV temp, pos;" +
+                ShadowTextureFetch("depth", "temp", "1") +
+                //"TEX depth, fragment.texcoord[1], texture[1], 2D;" +
+                "SLT ndotl.z, fragment.texcoord[1].z, depth.z;" +
+
+                // No shadow when out of frustum
+                //"SGE temp.y, depth.z, zero123.y;" +
+                //"LRP temp.x, temp.y, zero123.y, temp.x;" +
+                
+                "MUL ndotl.x, ndotl.x, ndotl.z;" + // Shadow
+                
+                // Backlit
+                "MOV pos.w, zero123.y;" +
+                "DP4 eye.x, pos, light2cam0;" +
+                "DP4 eye.y, pos, light2cam1;" +
+                "DP4 eye.z, pos, light2cam2;" +
+                Normalize("eye") +
+                
+                "DP3 ndotl.y, -eye, normal;" +
+                //"MUL ndotl.y, ndotl.y, pow2.x;" +
+                "POW ndotl.y, ndotl.y, pow2.z;" + // backlit
+                "SUB ndotl.y, zero123.y, ndotl.y;" +
+                //"SUB ndotl.y, zero123.y, ndotl.y;" +
+                //"MUL ndotl.y, ndotl.y, pow2.z;" +
+                
+                //"MAX ndotl.x, ndotl.x, ndotl.y;" + // Ambient
+                //"MAX ndotl.x, ndotl.x, pow2.y;" + // Ambient
+                
+                // Pigment
+                "TEX temp, fragment.texcoord[0], texture[0], 2D;" +
+                "LRP temp, zero123.w, temp, one;" + // texture proportion
+                "MUL temp, temp, ndotl.x;" +
+                
+                "MUL temp, temp, zero123.z;" +
+                
+                //"MUL temp, temp, ndotl.y;" +
+                
+                "MOV temp.w, zero123.y;" + // reset alpha
+                "MOV result.color, temp;" +
+                "END";
+        
+        String programmax =
+                "!!ARBfp1.0\n" +
+                
                 //"OPTION ARB_fragment_program_shadow;" +
                 "PARAM light2cam0   = program.env[10];" +
                 "PARAM light2cam1   = program.env[11];" +
@@ -12094,8 +12637,7 @@
                 "TEMP shininess;" +
                 "\n" +
                 "MOV texSamp, one;" +
-                //"TEX texSamp, fragment.texcoord[0], texture[0], 2D;" +
-
+                
                 "MOV mapgrid.x, one2048th.x;" +
                 "MOV temp, fragment.texcoord[1];" +
                 /*
@@ -12116,20 +12658,20 @@
                 "MUL temp, floor, mapgrid.x;" +
                 //"TEX depth0, temp, texture[1], 2D;" +
                 (((mode & FP_SOFTSHADOW) == 0) ? "" :
-                TextureFetch("depth0", "temp", "1") +
+                ShadowTextureFetch("depth0", "temp", "1") +
                 "") +
                 "ADD temp.x, temp.x, mapgrid.x;" +
                 //"TEX depth1, temp, texture[1], 2D;" +
                 (((mode & FP_SOFTSHADOW) == 0) ? "" :
-                TextureFetch("depth1", "temp", "1") +
+                ShadowTextureFetch("depth1", "temp", "1") +
                 "") +
                 "ADD temp.y, temp.y, mapgrid.x;" +
                 //"TEX depth2, temp, texture[1], 2D;" +
-                TextureFetch("depth2", "temp", "1") +
+                ShadowTextureFetch("depth2", "temp", "1") +
                 "SUB temp.x, temp.x, mapgrid.x;" +
                 //"TEX depth3, temp, texture[1], 2D;" +
                 (((mode & FP_SOFTSHADOW) == 0) ? "" :
-                TextureFetch("depth3", "temp", "1") +
+                ShadowTextureFetch("depth3", "temp", "1") +
                 "") +
                 //"MUL texSamp0, texSamp0, state.material.front.diffuse;" +
                 //"MOV params, material;" +
@@ -12500,10 +13042,10 @@
                 "MAD shadow.x, buffer.x, frac.y, shadow.x;" +
                 "") +
 
-           // display shadow only (bump == 0)
+           // display shadow only (fakedepth == 0)
          "SUB temp.x, half.x, shadow.x;" +
          "MOV temp.y, -params5.z;" + // params6.x;" +
-         "SLT temp.z, temp.y, -one2048th.x;" +
+         "SLT temp.z, temp.y, -c256i.x;" +
          "SUB temp.y, one.x, temp.z;" +
          "MUL temp.x, temp.x, temp.y;" +
          "KIL temp.x;" +
@@ -12834,6 +13376,13 @@
             //once = true;
         }
 
+        String program = programmax;
+        
+        if (Globals.MINSHADER)
+        {
+            program = programmin;
+        }
+        
         System.out.print("Program #" + mode + "; instructions = " + program.split(";").length + "; length = " + program.length());
         System.out.println(" - " + (mode >> 3) + " lights; " + ((mode & 2) == 2 ? "anisoUV " : "") + ((mode & 4) == 4 ? "SoftShadow " : ""));
         loadProgram(gl, GL.GL_FRAGMENT_PROGRAM_ARB, program);
@@ -12927,25 +13476,26 @@
         return out;
     }
 
-    String TextureFetch(String dest, String src, String unit)
+    // Also does frustum culling
+    String ShadowTextureFetch(String dest, String src, String unit)
     {
         return "TEX " + dest + ", " + src + ", texture[" + unit + "], 2D;" +
                 "SGE " + src + ".w, " + src + ".x, eps.x;" +
                 "SGE " + src + ".z, " + src + ".y, eps.x;" +
+                "SLT " + dest + ".x, " + src + ".x, one.x;" +
+                "SLT " + dest + ".y, " + src + ".y, one.x;" +
                 "MUL " + src + ".w, " + src + ".z, " + src + ".w;" +
-                "SLT " + src + ".z, " + src + ".x, one.x;" +
-                "MUL " + src + ".w, " + src + ".z, " + src + ".w;" +
-                "SLT " + src + ".z, " + src + ".y, one.x;" +
-                "MUL " + src + ".w, " + src + ".z, " + src + ".w;" +
+                "MUL " + src + ".w, " + dest + ".x, " + src + ".w;" +
+                "MUL " + src + ".w, " + dest + ".y, " + src + ".w;" +
                 //"SWZ buffer, temp, w,w,w,w;";
-                "MUL " + dest + ".z, " + dest + ".z, " + src + ".w;" +
+                //"MUL " + dest + ".z, " + dest + ".z, " + src + ".w;" +
                 "SUB " + src + ".z, " + "one.x, " + src + ".w;" +
                 //"MUL " + src + ".z, " + src + ".z, infinity.x;" +
                 //"ADD " + dest + ".z, " + dest + ".z, " + src + ".z;";
-                "MAD " + dest + ".z, " + src + ".z, infinity.x," + dest + ".z;";
+                //"MAD " + dest + ".z, " + src + ".z, infinity.x," + dest + ".z;";
 
-    //"LRP " + dest + ".z, " + src + ".w," + dest + ".z, infinity.x;";
-    //"LRP " + dest + ".z" + ", " + src + ".w, infinity.x," + dest + ".z;";
+    //?? "LRP " + dest + ".z, " + src + ".w," + dest + ".z, infinity.x;";
+    "LRP " + dest + ".z, " + src + ".z, infinity.x," + dest + ".z;";
     }
 
     String Shadow(String depth, String shadow)
@@ -12992,7 +13542,7 @@
                 "SLT temp.x, temp.x, zero.x;" + // shadoweps
                 "LRP " + shadow + ", temp.x, one, " + shadow + ";" +
 
-                // No shadow when out of frustrum
+                // No shadow when out of frustum
                 "SGE temp.x, " + depth + ".z, one.z;" +
                 "LRP " + shadow + ", temp.x, one, " + shadow + ";" +
                 "";
@@ -13140,7 +13690,8 @@
     /*static*/ float[] modelParams5 = new float[]{0, 0, 0, 0}; // texture, opacity, fakedepth, shadowbias
     /*static*/ float[] modelParams6 = new float[]{0, 0, 0, 0}; // bump, noise, borderfade, fog punchthrough
     /*static*/ float[] modelParams7 = new float[]{0, 0, 0, 0}; // noise power, opacity power
-    Object3D.cVector2[] vector2buffer;
+    
+    //Object3D.cVector2[] vector2buffer;
 
     // IN : ndotl, ndoth, xxx, NdotL //, snininess, lightarea
     // OUT : diff, spec
@@ -13156,9 +13707,10 @@
                 "DP3 " + dest + ".z," + "normals," + "eye;" +
                 "MAX " + dest + ".w," + dest + ".z," + "eps.x;" +
                 //"MOV " + dest + ".w," + "normal.z;" +
-                "MUL " + dest + ".z," + "params2.w," + dest + ".x;" +
-                "MUL " + dest + ".z," + dest + ".z," + dest + ".x;" +
-                //"MOV " + dest + ".z," + "params2.w;" + 
+//            "MUL " + dest + ".z," + "params2.w," + dest + ".x;" + // PRETTY HEURISTIC FOR VELVET
+//            "MUL " + dest + ".z," + dest + ".z," + dest + ".x;" +
+                
+                "MOV " + dest + ".z," + "params2.w;" + // EXACT
                 "POW " + dest + ".w," + dest + ".w," + dest + ".z;" +
                 "RCP " + dest + ".w," + dest + ".w;" +
                 //"RSQ " + dest + ".w," + dest + ".w;" +
@@ -13663,6 +14215,7 @@
         else
         if (evt.getSource() == AAtimer)
         {
+                    Globals.TIMERRUNNING = false;
             if (mouseDown)
             {
             //new Exception().printStackTrace();
@@ -13722,7 +14275,7 @@
             
 // fev 2014???
             if ((TRACK || SHADOWTRACK) && trackedobject != null) // && DrawMode() == SHADOW) // && !lightMode)
-                object.editWindow.ScreenFit(trackedobject, SHADOWTRACK && !TRACK);
+                object.GetWindow().ScreenFit(trackedobject, SHADOWTRACK && !TRACK);
             pingthread.StepToTarget(true); // true);
         }
     //    if (!LIVE)
@@ -13737,6 +14290,7 @@
             return;
         
         AAtimer.restart(); // 
+        Globals.TIMERRUNNING = true;
 
 //        waslive = LIVE;
 //        LIVE = false;
@@ -13786,14 +14340,15 @@
             drag = false;
             //System.out.println("Mouse DOWN");
             editObj = false;
-            ClickInfo info = new ClickInfo();
-            info.bounds.setBounds(0, 0, (int) (getBounds().width * zoom), (int) (getBounds().height * zoom));
-            info.pane = this;
-            info.camera = renderCamera;
-            info.x = x;
-            info.y = y;
-            info.modifiers = modifiersex;
-            editObj = object.doEditClick(info, 0);
+            //ClickInfo info = new ClickInfo();
+            object.clickInfo.bounds.setBounds(0, 0, (int) (getBounds().width * zoom), (int) (getBounds().height * zoom));
+            object.clickInfo.pane = this;
+            object.clickInfo.camera = renderCamera;
+            object.clickInfo.x = x;
+            object.clickInfo.y = y;
+            object.clickInfo.modifiers = modifiersex;
+            editObj = object.doEditClick(//info,
+                    0);
             if (!editObj)
             {
                 hasMarquee = true;
@@ -13809,9 +14364,12 @@
     
     public void mouseDragged(MouseEvent e)
     {
+        Globals.MOUSEDRAGGED = true;
+        
         //System.out.println("mouseDragged: " + e);
         if (isRenderer)
             movingcamera = true;
+        
         //if (drawing)
         //return;
         if ((e.getModifiersEx() & CTRL) != 0
@@ -14072,12 +14630,12 @@
     void GoDown(int mod)
     {
         MODIFIERS |= COMMAND;
-        /*
+        /**/
         if((mod&SHIFT) == SHIFT)
-        manipCamera.RotatePosition(0, -speed);
+        manipCamera.BackForth(0, -speed*delta, 0); // getWidth());
         else
-        manipCamera.BackForth(0, -speed*delta, getWidth());
-         */
+        manipCamera.RotatePosition(0, -speed);
+        /**/
         if ((mod & SHIFT) == SHIFT)
         {
             mouseMode = mouseMode; // VR??
@@ -14093,12 +14651,12 @@
     void GoUp(int mod)
     {
         MODIFIERS |= COMMAND;
-        /*
+        /**/
         if((mod&SHIFT) == SHIFT)
-        manipCamera.RotatePosition(0, speed);
+        manipCamera.BackForth(0, speed*delta, 0); // getWidth());
         else
-        manipCamera.BackForth(0, speed*delta, getWidth());
-         */
+        manipCamera.RotatePosition(0, speed);
+        /**/
         if ((mod & SHIFT) == SHIFT)
         {
             mouseMode = mouseMode;
@@ -14114,12 +14672,12 @@
     void GoLeft(int mod)
     {
         MODIFIERS |= COMMAND;
-        /*
+        /**/
         if((mod&SHIFT) == SHIFT)
-        manipCamera.RotatePosition(speed, 0);
-        else
         manipCamera.Translate(speed*delta, 0, getWidth());
-         */
+        else
+        manipCamera.RotatePosition(speed, 0);
+        /**/
         if ((mod & SHIFT) == SHIFT)
         {
             mouseMode = mouseMode;
@@ -14135,12 +14693,12 @@
     void GoRight(int mod)
     {
         MODIFIERS |= COMMAND;
-        /*
+        /**/
         if((mod&SHIFT) == SHIFT)
-        manipCamera.RotatePosition(-speed, 0);
-        else
         manipCamera.Translate(-speed*delta, 0, getWidth());
-         */
+        else
+        manipCamera.RotatePosition(-speed, 0);
+        /**/
         if ((mod & SHIFT) == SHIFT)
         {
             mouseMode = mouseMode;
@@ -14190,14 +14748,16 @@
             if (editObj)
             {
                 drag = true;
-                ClickInfo info = new ClickInfo();
-                info.bounds.setBounds(0, 0,
+                //ClickInfo info = new ClickInfo();
+                object.clickInfo.bounds.setBounds(0, 0,
                         (int) (getBounds().width * zoom), (int) (getBounds().height * zoom));
-                info.pane = this;
-                info.camera = renderCamera;
-                info.x = x;
-                info.y = y;
-                object.editWindow.copy.doEditDrag(info, (modifiers & MouseEvent.BUTTON3_MASK) != 0);
+                object.clickInfo.pane = this;
+                object.clickInfo.camera = renderCamera;
+                object.clickInfo.x = x;
+                object.clickInfo.y = y;
+                object //.GetWindow().copy
+                        .doEditDrag(//info,
+                                (modifiers & MouseEvent.BUTTON3_MASK) != 0);
             } else
             {
                 if (x < startX)
@@ -14346,22 +14906,27 @@
         }
     }
 
+//        ClickInfo clickInfo = new ClickInfo();
+        
     public void mouseMoved(MouseEvent e)
     {
         //System.out.println("mouseMoved: " + e);
         if (isRenderer)
             return;
         
-        ClickInfo ci = new ClickInfo();
-        ci.x = e.getX();
-        ci.y = e.getY();
-        ci.modifiers = e.getModifiersEx();
-        ci.bounds.setBounds(0, 0, (int) (getBounds().width * zoom), (int) (getBounds().height * zoom));
-        ci.pane = this;
-        ci.camera = renderCamera;
+        // Mouse cursor feedback
+        object.clickInfo.x = e.getX();
+        object.clickInfo.y = e.getY();
+        object.clickInfo.modifiers = e.getModifiersEx();
+        object.clickInfo.bounds.setBounds(0, 0, (int) (getBounds().width * zoom), (int) (getBounds().height * zoom));
+        object.clickInfo.pane = this;
+        object.clickInfo.camera = renderCamera;
         if (!isRenderer)
         {
-            if (object.editWindow.copy.doEditClick(ci, 0))
+            //ObjEditor editWindow = object.editWindow;
+            //Object3D copy = editWindow.copy;
+            if (object.doEditClick(//clickInfo,
+                                0))
             {
                 setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
             } else
@@ -14373,8 +14938,11 @@
 
     public void mouseReleased(MouseEvent e)
     {
+        Globals.MOUSEDRAGGED = false;
+        
         movingcamera = false;
-        X = Y = 0;
+        X = 0; // getBounds().width/2;
+        Y = 0; // getBounds().height/2;
         //System.out.println("mouseReleased: " + e);
         clickEnd(e.getX(), e.getY(), e.getModifiersEx());
     }
@@ -14630,7 +15198,8 @@
 //                break;
             case 'T':
                 CACHETEXTURE ^= true;
-                textures.clear();
+                texturepigment.clear();
+                texturebump.clear();
             //    repaint();
                 break;
             case 'Y':
@@ -14715,7 +15284,9 @@
             case 'E' : COMPACT ^= true;
                 repaint();
                 break;
-            case 'W' : DEBUGHSB ^= true;
+            case 'W' : // Wide Window (fullscreen)
+                //DEBUGHSB ^= true;
+                ObjEditor.theFrame.ToggleFullScreen();
                 repaint();
                 break;
             case 'u' : Udebug ^= true; Vdebug = false; NORMALdebug = false; programInitialized = false; repaint(); break;
@@ -14740,8 +15311,8 @@
                 RevertCamera();
                 repaint();
                 break;
-            case 'L':
             case 'l':
+            //case 'L':
                 if (lightMode)
                 {
                     lightMode = false;
@@ -14805,20 +15376,24 @@
                 OCCLUSION_CULLING ^= true;
                 System.out.println("OCCLUSION CULLING = " + OCCLUSION_CULLING);
                 break;
-            case '0': envyoff ^= true; repaint(); break;
+            //case '0': envyoff ^= true; repaint(); break;
             case '1':
             case '2':
             case '3':
             case '4':
             case '5':
-                newenvy = Character.getNumericValue(key);
-                repaint();
-                break;
             case '6':
             case '7':
             case '8':
             case '9':
-                BGcolor = (key - '6')/3.f;
+                if (true) // envyoff)
+                {
+                    BGcolor = (key - '1')/8.f;
+                }
+                else
+                {
+                    //newenvy = Character.getNumericValue(key);
+                }
                 repaint();
                 break;
             case '!':
@@ -14884,9 +15459,9 @@
             case '_':
                 kompactbit = 5;
                 break;
-            case '+':
-                kompactbit = 6;
-                break;
+//            case '+':
+//                kompactbit = 6;
+//                break;
             case ' ':
                 lightMode ^= true;
                 Globals.lighttouched = true;
@@ -14898,6 +15473,7 @@
             case ESC:
                 RENDERPROGRAM += 1;
                 RENDERPROGRAM %= 3;
+
                 repaint();
                 break;
             case 'Z':
@@ -14937,8 +15513,9 @@
             case DELETE:
                 ClearSelection();
                 break;
-                /*
             case '+':
+                
+                /*
                 //fontsize += 1;
                 bbzoom *= 2;
                 repaint();
@@ -14955,17 +15532,17 @@
             case '=':
                 IncDepth();
                 //fontsize += 1;
-                object.editWindow.refreshContents(true);
+                object.GetWindow().refreshContents(true);
                 maskbit = 6;
                 break;
             case '-': //if (PixelThreshold>1) PixelThreshold /= 2;
                 DecDepth();
                 maskbit = 5;
                 //if(fontsize > 1) fontsize -= 1;
-                if (object.editWindow == null)
-                    new Exception().printStackTrace();
-                else
-                    object.editWindow.refreshContents(true);
+//                if (object.editWindow == null)
+//                    new Exception().printStackTrace();
+//                else
+                    object.GetWindow().refreshContents(true);
                 break;
             case '{':
                 manipCamera.shaper_fovy /= 1.1;
@@ -15189,7 +15766,7 @@
         }
          */
 
-        object.editWindow.EditSelection();
+        object.GetWindow().EditSelection(false);
     }
 
     void SelectParent()
@@ -15206,10 +15783,10 @@
             {
                 //selectees.remove(i);
                 System.out.println("select parent of " + elem);
-                group.editWindow.Select(elem.parent.GetTreePath(), first, true);
+                group.GetWindow().Select(elem.parent.GetTreePath(), first, true);
             } else
             {
-                group.editWindow.Select(elem.GetTreePath(), first, true);
+                group.GetWindow().Select(elem.GetTreePath(), first, true);
             }
 
             first = false;
@@ -15251,12 +15828,12 @@
                 for (int j = 0; j < group.children.size(); j++)
                 {
                     elem = (Object3D) group.children.elementAt(j);
-                    object.editWindow.Select(elem.GetTreePath(), first, true);
+                    object.GetWindow().Select(elem.GetTreePath(), first, true);
                     first = false;
                 }
             } else
             {
-                object.editWindow.Select(elem.GetTreePath(), first, true);
+                object.GetWindow().Select(elem.GetTreePath(), first, true);
             }
 
             first = false;
@@ -15267,21 +15844,21 @@
     {
         //Composite group = (Composite) object;
         Object3D group = object;
-        group.editWindow.loadClipboard(true); // ClearSelection(false);
+        group.GetWindow().loadClipboard(true); // ClearSelection(false);
     }
 
     void ResetTransform(int mask)
     {
         //Composite group = (Composite) object;
         Object3D group = object;
-        group.editWindow.ResetTransform(mask);
+        group.GetWindow().ResetTransform(mask);
     }
 
     void FlipTransform()
     {
         //Composite group = (Composite) object;
         Object3D group = object;
-        group.editWindow.FlipTransform();
+        group.GetWindow().FlipTransform();
 //        group.editWindow.ReduceMesh(true);
     }
 
@@ -15289,7 +15866,7 @@
     {
         //Composite group = (Composite) object;
         Object3D group = object;
-        group.editWindow.PrintMemory();
+        group.GetWindow().PrintMemory();
 //        group.editWindow.ReduceMesh(true);
     }
     
@@ -15297,7 +15874,7 @@
     {
         //Composite group = (Composite) object;
         Object3D group = object;
-        group.editWindow.ResetCentroid();
+        group.GetWindow().ResetCentroid();
     }
 
     void IncDepth()
@@ -15379,8 +15956,6 @@
 
         int width = getBounds().width;
         int height = getBounds().height;
-        ClickInfo info = new ClickInfo();
-        info.bounds.setBounds(0, 0, (int) (width * zoom), (int) (height * zoom));
         //Image img = CreateImage(width, height);
         //System.out.println("width = " + width + "; height = " + height + "\n");
         
@@ -15457,43 +16032,77 @@
         }
         if (object != null && !hasMarquee)
         {
+            if (object.clickInfo == null)
+                object.clickInfo = new ClickInfo();
+            ClickInfo info = object.clickInfo;
+            //ClickInfo info = new ClickInfo();
+            info.bounds.setBounds(0, 0, (int) (width * zoom), (int) (height * zoom));
+        
             if (isRenderer)
             {
-                info.flags++;
+                object.clickInfo.flags++;
                 double frameAspect = (double) width / (double) height;
                 if (frameAspect > renderCamera.aspect)
                 {
                     int desired = (int) ((double) height * renderCamera.aspect);
-                    info.bounds.width -= width - desired;
-                    info.bounds.x += (width - desired) / 2;
+                    object.clickInfo.bounds.width -= width - desired;
+                    object.clickInfo.bounds.x += (width - desired) / 2;
                 } else
                 {
                     int desired = (int) ((double) width / renderCamera.aspect);
-                    info.bounds.height -= height - desired;
-                    info.bounds.y += (height - desired) / 2;
+                    object.clickInfo.bounds.height -= height - desired;
+                    object.clickInfo.bounds.y += (height - desired) / 2;
                 }
             }
-            info.g = gr;
-            info.camera = renderCamera;
+            
+            object.clickInfo.g = gr;
+            object.clickInfo.camera = renderCamera;
             /* 
             // Memory intensive (brep.verticescopy)
             if (!(object instanceof Composite))
             object.draw(info, 0, false); // SLOW : 
              */
-            if (!isRenderer)
+            if (!isRenderer) // && drag)
             {
-                object.drawEditHandles(info, 0);
-                
-                if (drag && (X != 0 || Y != 0) && object.selection.Size() > 0)
+                Grafreed.Assert(object != null);
+                Grafreed.Assert(object.selection != null);
+                if (object.selection.Size() > 0)
                 {
-                    switch (object.selection.get(0).hitSomething)
+                    int hitSomething = object.selection.get(0).hitSomething;
+
+                    object.clickInfo.DX = 0;
+                    object.clickInfo.DY = 0;
+                    object.clickInfo.W = 1;
+                    if (hitSomething == Object3D.hitCenter)
                     {
-                        case Object3D.hitCenter: gr.setColor(Color.pink); break;
-                        case Object3D.hitRotate: gr.setColor(Color.green); break;
-                        case Object3D.hitScale: gr.setColor(Color.cyan); break;
+                        info.DX = X;
+                        if (X != 0)
+                            info.DX -= info.bounds.width/2;
+
+                        info.DY = Y;
+                        if (Y != 0)
+                            info.DY -= info.bounds.height/2;
                     }
-                    
-                    gr.drawLine(X, Y, info.bounds.width/2, info.bounds.height/2);
+
+                    object.drawEditHandles(//info,
+                                            0);
+
+                    if (drag && (X != 0 || Y != 0))
+                    {
+                        switch (hitSomething)
+                        {
+                            case Object3D.hitCenter: gr.setColor(Color.pink);
+                                gr.drawLine(X, Y, info.bounds.width/2, info.bounds.height/2);
+                                break;
+                            case Object3D.hitRotate: gr.setColor(Color.yellow);
+                                gr.drawLine(X, Y, info.bounds.width/2, info.bounds.height/2);
+                            break;
+                            case Object3D.hitScale: gr.setColor(Color.cyan);
+                                gr.drawLine(X, Y, info.bounds.width/2, info.bounds.height/2);
+                            break;
+                        }
+
+                    }
                 }
             }
         }
@@ -15911,7 +16520,7 @@
     Object3D object;
     static Object3D trackedobject;
     Camera renderCamera; // Light or Eye (or Occlusion)
-    /*static*/ Camera manipCamera; // Light or Eye
+    /*static*/ Camera manipCamera; // Light or Eye. Can be Light when Eye, not Eye when Light
 	/*static*/ Camera eyeCamera;
     /*static*/ Camera lightCamera;
     int cameracount;
@@ -15975,6 +16584,8 @@
     private /*static*/ boolean firstime;
     private /*static*/ cVector newView = new cVector();
     private static final String[] suffixes = {"posx", "negx", "posy", "negy", "posz", "negz"};
+    private static final String[] suffixes2 = {"east", "west", "top", "bottom", "north", "south"};
+    private static final String[] suffixes3 = {"ft", "bk", "up", "dn", "rt", "lf"};
     private static final int[] targets = {GL.GL_TEXTURE_CUBE_MAP_POSITIVE_X,
                                              GL.GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
                                              GL.GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
@@ -15987,29 +16598,66 @@
     {
         com.sun.opengl.util.texture.Texture cubemap = TextureIO.newTexture(GL.GL_TEXTURE_CUBE_MAP);
 
+        int usedsuf = 0;
+        
         for (int i = 0; i < suffixes.length; i++)
         {
-            String resourceName = basename + suffixes[i] + "." + suffix;
-            TextureData data = TextureIO.newTextureData(scope.getResourceAsStream(resourceName),
-                    mipmapped,
-                    FileUtil.getFileSuffix(resourceName));
-            if (data == null)
+            String[] suffixe = suffixes;
+            String[] fallback = suffixes2;
+            String[] fallfallback = suffixes3;
+            
+            for (int c=usedsuf; --c>=0;)
             {
-                throw new IOException("Unable to load texture " + resourceName);
+//                String[] temp = suffixe;
+//                suffixe = fallback;
+//                fallback = fallfallback;
+//                fallfallback = temp;
             }
+            
+            String resourceName = basename + suffixe[i] + "." + suffix;
+            TextureData data;
+            
+            try
+            {
+                data = TextureIO.newTextureData(scope.getResourceAsStream(resourceName),
+                        mipmapped,
+                        FileUtil.getFileSuffix(resourceName));
+            }
+            catch (Exception e)
+            {
+                try
+                {
+                    resourceName = basename + fallback[i] + "." + suffix;
+                    data = TextureIO.newTextureData(scope.getResourceAsStream(resourceName),
+                            mipmapped,
+                            FileUtil.getFileSuffix(resourceName));
+                }
+                catch (Exception e2)
+                {
+                    resourceName = basename + fallfallback[i] + "." + suffix;
+                    data = TextureIO.newTextureData(scope.getResourceAsStream(resourceName),
+                            mipmapped,
+                            FileUtil.getFileSuffix(resourceName));
+                }
+            }
+            
             //System.out.println("Target = " + targets[i]);
             cubemap.updateImage(data, targets[i]);
         }
 
         return cubemap;
     }
+    
     int bigsphere = -1;
 
     float BGcolor = 0.5f;
     
-    private void DrawSkyBox(GL gl)
+    float ambientLight[] = {1f, 1f, 1f, 1.0f};
+    
+    private void DrawSkyBox(GL gl, float ratio)
     {
-        if (envyoff || cubemap == null)
+        if (//envyoff ||
+                cubemap == null)
         {
             gl.glClearColor(BGcolor, BGcolor, BGcolor, 1);
             gl.glClear(gl.GL_COLOR_BUFFER_BIT);
@@ -16024,7 +16672,17 @@
         // Compensates for ExaminerViewer's modification of modelview matrix
         gl.glMatrixMode(GL.GL_MODELVIEW);
         gl.glLoadIdentity();
+        gl.glScalef(1,ratio,1);
 
+//        colorV[0] = 2;
+//        colorV[1] = 2;
+//        colorV[2] = 2;
+//        colorV[3] = 1;
+//        gl.glDisable(gl.GL_COLOR_MATERIAL);
+//        gl.glMaterialfv(gl.GL_FRONT_AND_BACK, gl.GL_AMBIENT, colorV, 0);
+//        
+//        gl.glLightModelfv(gl.GL_LIGHT_MODEL_AMBIENT, ambientLight, 0);
+        
         //gl.glActiveTexture(GL.GL_TEXTURE1);
         //gl.glDisable(GL.GL_TEXTURE_CUBE_MAP);
 
@@ -16056,6 +16714,7 @@
         {
             gl.glScalef(1.0f, -1.0f, 1.0f);
         }
+        gl.glScalef(-1.0f, 1.0f, 1.0f);
         gl.glMultMatrixd(viewrot_1, 0);
         gl.glTranslatef(0, 0, 0.5f); // (float)lightCamera.Distance());  // 0.5f);
         //viewer.updateInverseRotation(gl);
@@ -16196,16 +16855,16 @@
                 cStatic.objectstack[materialdepth++] = checker;
                 //System.out.println("material " + material);
                 //Applet3D.tracein(this, selected);
-                vector2buffer = checker.projectedVertices;
+                //vector2buffer = checker.projectedVertices;
 
         //checker.GetMaterial().Draw(this, false); // true);
-        DrawMaterial(checker.GetMaterial(), false); // true);
+        DrawMaterial(checker.GetMaterial(), false, checker.projectedVertices); // true);
 
                 materialdepth -= 1;
                 if (materialdepth > 0)
                 {
-                    vector2buffer = cStatic.objectstack[materialdepth - 1].projectedVertices;
-                    DrawMaterial(materialstack[materialdepth - 1], selectedstack[materialdepth - 1]);
+                    //vector2buffer = cStatic.objectstack[materialdepth - 1].projectedVertices;
+                    DrawMaterial(materialstack[materialdepth - 1], selectedstack[materialdepth - 1], cStatic.objectstack[materialdepth - 1].projectedVertices);
                 }
         //checker.GetMaterial().opacity = 1f;
         ////checker.GetMaterial().ambient = 1f;
@@ -16291,6 +16950,14 @@
         }
     }
     
+    private Object3D GetFolder()
+    {
+        Object3D folder = object.GetWindow().copy;
+        if (object.GetWindow().copy.selection.Size() > 0)
+            folder = object.GetWindow().copy.selection.elementAt(0);
+        return folder;
+    }
+
     class SelectBuffer implements GLEventListener
     {
 
@@ -16306,7 +16973,7 @@
             //new Exception().printStackTrace();
             System.out.println("select buffer init");
             // Use debug pipeline
-            drawable.setGL(new DebugGL(drawable.getGL()));
+            //drawable.setGL(new DebugGL(drawable.getGL()));
 
             GL gl = drawable.getGL();
 
@@ -16370,6 +17037,17 @@
 
             //gl.glDisable(GL.GL_POLYGON_OFFSET_FILL);
 
+                if (PAINTMODE)
+                {
+                    if (object.GetWindow().copy.selection.Size() > 0)
+                    {
+                        Object3D paintobj = object.GetWindow().copy.selection.elementAt(0);
+
+                        // Make what you paint not selectable.
+                        paintobj.ResetSelectable();
+                    }
+                }
+                
             //int tmp = selection_view;
             //selection_view = -1;
             int temp = DrawMode();
@@ -16381,6 +17059,17 @@
             //    temp = DEFAULT; // patch for selection debug
             Globals.drawMode = temp; // WARNING
 
+                if (PAINTMODE)
+                {
+                    if (object.GetWindow().copy.selection.Size() > 0)
+                    {
+                        Object3D paintobj = object.GetWindow().copy.selection.elementAt(0);
+
+                        // Revert.
+                        paintobj.RestoreSelectable();
+                    }
+                }
+                
             //gl.glBindTexture(GL.GL_TEXTURE_2D, selection_view);
 
             // trying different ways of getting the depth info over
@@ -16428,6 +17117,8 @@
 //                System.err.println("view = " + view[4] + " " + view[5] + " " + view[6] + " " + view[7]);
 //                System.err.println("view = " + view[8] + " " + view[9] + " " + view[10] + " " + view[11]);
 //                System.err.println("view = " + view[12] + " " + view[13] + " " + view[14] + " " + view[15]);
+                
+                CreateSelectedPoint();
                 
                 // Will fit the mesh !!!
                 selectedpoint.toParent[0][0] = 0.0001;
@@ -16482,29 +17173,31 @@
                 }
                 
                 if (!movingcamera && !PAINTMODE)
-                    object.editWindow.ScreenFitPoint(); // fev 2014
+                    object.GetWindow().ScreenFitPoint(); // fev 2014
                 
-                if (PAINTMODE && Grafreed.clipboard.size() == 1) // object.editWindow.copy.selection.Size() > 0)
+                if (PAINTMODE) // && Grafreed.clipboard.size() == 1) // object.editWindow.copy.selection.Size() > 0)
                 {
-                    Object3D paintobj = Grafreed.clipboard.get(0); // object.editWindow.copy.selection.elementAt(0);
+                    //Object3D paintobj; // = Grafreed.clipboard.get(0); // object.editWindow.copy.selection.elementAt(0);
                     
-                    Object3D group = new Object3D("inst" + paintcount++);
+                    if (object.GetWindow().copy.selection.Size() > 0)
+                    {
+                        Object3D paintobj = object.GetWindow().copy.selection.elementAt(0);
                     
-                    group.CreateMaterial(); // use a void leaf to select instances
-                    
-                    group.add(paintobj); // link
-                    
-                    object.editWindow.SnapObject(group);
-                    
-                    Object3D folder = object.editWindow.copy;
-                    
-                    if (object.editWindow.copy.selection.Size() > 0)
-                        folder = object.editWindow.copy.selection.elementAt(0);
-                    
-                    folder.add(group);
-                    
-                    object.editWindow.ResetModel();
-                    object.editWindow.refreshContents();
+                        Object3D inst = new Object3D("inst" + paintcount++);
+
+                        inst.CreateMaterial(); // use a void leaf to select instances
+
+                        inst.add(paintobj); // link
+
+                        object.GetWindow().SnapObject(inst);
+
+                        Object3D folder = paintFolder; // GetFolder();
+
+                        folder.add(inst);
+
+                        object.GetWindow().ResetModel();
+                        object.GetWindow().refreshContents();
+                    }
                 }
                 else
                     paintcount = 0;
@@ -16543,6 +17236,11 @@
                 //System.out.println("objects[color] = " + objects[color]);
                 //objects[color].Select();
                 indexcount = 0;
+                    ObjEditor window = object.GetWindow();
+                    if (window != null && deselect)
+                    {
+                        window.Select(null, deselect, true);
+                    }
                 object.Select(color, deselect);
             }
 
@@ -17068,23 +17766,15 @@
     int AAbuffersize = 0;
     
     //double[] selectedpoint = new double[3];
-    static Superellipsoid selectedpoint = new Superellipsoid();
+    static Superellipsoid selectedpoint;
     static Sphere previousselectedpoint = null;
-    static Sphere debugpointG = new Sphere();
-    static Sphere debugpointP = new Sphere();
-    static Sphere debugpointC = new Sphere();
-    static Sphere debugpointR = new Sphere();
+    static Sphere debugpointG;
+    static Sphere debugpointP;
+    static Sphere debugpointC;
+    static Sphere debugpointR;
     
     static Sphere debugpoints[] = new Sphere[8];
  
-    static
-    {
-        for (int i=0; i<8; i++)
-        {
-            debugpoints[i] = new Sphere();
-        }
-    }
-    
     static void InitPoints(float radius)
     {
         for (int i=0; i<8; i++)

--
Gitblit v1.6.2