commit b455eb4859ada89b837bc1b7d3c30214bb71be5d
Author: Leszek Koltunski <leszek@distorted.org>
Date:   Mon Dec 12 21:14:07 2016 +0000

    Rename various classes; fix a bug in Around the World.

diff --git a/src/main/java/org/distorted/library/Distorted.java b/src/main/java/org/distorted/library/Distorted.java
index 007f0e1..f324600 100644
--- a/src/main/java/org/distorted/library/Distorted.java
+++ b/src/main/java/org/distorted/library/Distorted.java
@@ -75,7 +75,7 @@ public class Distorted
    */
   public static final int CLONE_FRAGMENT= 0x8;
   /**
-   * When creating an instance of a DistortedNode from another instance, clone the children Nodes.
+   * When creating an instance of a DistortedObjectTree from another instance, clone the children Nodes.
    * <p>
    * This is mainly useful for creating many similar sub-trees of Bitmaps and rendering then at different places
    * on the screen, with (optionally) different effects of the top-level root Bitmap.   
@@ -355,7 +355,7 @@ public class Distorted
     GLES20.glEnableVertexAttribArray(mTextureCoordH);
    
     DistortedObject.reset();
-    DistortedNode.reset();
+    DistortedObjectTree.reset();
     EffectMessageSender.startSending();
     }
   
@@ -381,7 +381,7 @@ public class Distorted
     {
     DistortedObject.release();
     DistortedFramebuffer.release();
-    DistortedNode.release();
+    DistortedObjectTree.release();
     EffectQueue.release();
     EffectMessageSender.stopSending();
    
diff --git a/src/main/java/org/distorted/library/DistortedBitmapGrid.java b/src/main/java/org/distorted/library/DistortedBitmapGrid.java
deleted file mode 100644
index d7859f7..0000000
--- a/src/main/java/org/distorted/library/DistortedBitmapGrid.java
+++ /dev/null
@@ -1,191 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// Copyright 2016 Leszek Koltunski                                                               //
-//                                                                                               //
-// This file is part of Distorted.                                                               //
-//                                                                                               //
-// Distorted is free software: you can redistribute it and/or modify                             //
-// it under the terms of the GNU General Public License as published by                          //
-// the Free Software Foundation, either version 2 of the License, or                             //
-// (at your option) any later version.                                                           //
-//                                                                                               //
-// Distorted is distributed in the hope that it will be useful,                                  //
-// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
-// GNU General Public License for more details.                                                  //
-//                                                                                               //
-// You should have received a copy of the GNU General Public License                             //
-// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-package org.distorted.library;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-public class DistortedBitmapGrid extends DistortedObjectGrid
-  {
-  private int mCols, mRows;
-  private int remainingVert;
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// Create a flat, full grid. cols and rows is guaranteed (by DistortedBitmap constructor)
-// to be in 1,2,...,256.
-
-   private void computeNumberOfVertices(int cols, int rows)
-     {
-     mRows=rows;
-     mCols=cols;
-
-     if( cols==1 && rows==1 )
-       {
-       dataLength = 4;
-       }
-     else
-       {
-       dataLength = 2*( mRows*mCols +2*mRows - 1) +2*(mCols>=2 ? mRows:0) +
-                    (mCols>=2 && mRows>=2 ? 2*mRows-2 : 1);
-       }
-
-     //android.util.Log.e("BITMAP","vertices="+dataLength+" rows="+mRows+" cols="+mCols);
-
-     remainingVert = dataLength;
-     }
-
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-   private int addVertex(int vertex, int col, int row, float[] position, float[] normal, float[] texture)
-     {
-     remainingVert--;
-
-     float x= (float)col/mCols;
-     float y= (float)row/mRows;
-
-     position[3*vertex  ] = x-0.5f;
-     position[3*vertex+1] = 0.5f-y;
-     position[3*vertex+2] = 0;
-
-     texture[2*vertex  ]  = x;
-     texture[2*vertex+1]  = 1.0f-y;
-
-     normal[3*vertex  ]   = 0.0f;
-     normal[3*vertex+1]   = 0.0f;
-     normal[3*vertex+2]   = 1.0f;
-
-     return vertex+1;
-     }
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-   private int repeatLast(int vertex, float[] position, float[] normal, float[] texture)
-     {
-     remainingVert--;
-
-     //android.util.Log.e("BITMAP", "repeating last vertex!");
-
-     if( vertex>0 )
-       {
-       position[3*vertex  ] = position[3*vertex-3];
-       position[3*vertex+1] = position[3*vertex-2];
-       position[3*vertex+2] = position[3*vertex-1];
-
-       normal[3*vertex  ]   = normal[3*vertex-3];
-       normal[3*vertex+1]   = normal[3*vertex-2];
-       normal[3*vertex+2]   = normal[3*vertex-1];
-
-       texture[2*vertex  ]  = texture[2*vertex-2];
-       texture[2*vertex+1]  = texture[2*vertex-1];
-
-       vertex++;
-       }
-
-     return vertex;
-     }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-   private void buildGrid(float[] position, float[] normal, float[] texture)
-     {
-     boolean lastBlockIsNE = false;
-     boolean currentBlockIsNE;
-     int vertex = 0;
-
-     //android.util.Log.d("BITMAP", "buildGrid");
-
-     for(int row=0; row<mRows; row++)
-       {
-       for(int col=0; col<mCols; col++)
-         {
-         currentBlockIsNE = (2*row<=mRows-1)^(2*col<=mCols-1);
-
-         if( col==0 || (lastBlockIsNE^currentBlockIsNE) )
-           {
-           if( row!=0 && col==0 ) vertex = repeatLast(vertex,position,normal,texture);
-           vertex= addVertex( vertex, col, row+(currentBlockIsNE?0:1), position, normal, texture);
-           if( row!=0 && col==0 ) vertex = repeatLast(vertex,position,normal,texture);
-           if( lastBlockIsNE^currentBlockIsNE)  vertex = repeatLast(vertex,position,normal,texture);
-           vertex= addVertex( vertex, col, row+(currentBlockIsNE?1:0), position, normal, texture);
-           }
-         vertex= addVertex( vertex, col+1, row+(currentBlockIsNE?0:1), position, normal, texture);
-         vertex= addVertex( vertex, col+1, row+(currentBlockIsNE?1:0), position, normal, texture);
-
-         lastBlockIsNE = currentBlockIsNE;
-         }
-       }
-
-     //android.util.Log.d("BITMAP", "buildGrid done");
-     }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/*
-   private static String debug(float[] val, int stop)
-     {
-     String ret="";
-
-     for(int i=0; i<val.length; i++)
-        {
-        if( i%stop==0 ) ret+="\n";
-        ret+=(" "+val[i]);
-        }
-
-     return ret;
-     }
-*/
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// PUBLIC API
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/**
- * Creates the underlying grid of vertices, normals and texture coords.
- *
- * @param cols Number of columns in the grid.
- * @param rows Number of rows in the grid.
- */
-   public DistortedBitmapGrid(int cols, int rows)
-      {
-      computeNumberOfVertices(cols,rows);
-
-      float[] positionData= new float[POSITION_DATA_SIZE*dataLength];
-      float[] normalData  = new float[NORMAL_DATA_SIZE  *dataLength];
-      float[] textureData = new float[TEX_DATA_SIZE     *dataLength];
-
-      buildGrid(positionData,normalData,textureData);
-
-      //android.util.Log.e("CUBES","dataLen="+dataLength);
-      //android.util.Log.d("CUBES", "position: "+debug(positionData,3) );
-      //android.util.Log.d("CUBES", "normal: "  +debug(  normalData,3) );
-      //android.util.Log.d("CUBES", "texture: " +debug( textureData,2) );
-
-      if( remainingVert!=0 )
-        android.util.Log.d("BITMAP", "remainingVert " +remainingVert );
-
-      mGridPositions = ByteBuffer.allocateDirect(POSITION_DATA_SIZE*dataLength*BYTES_PER_FLOAT).order(ByteOrder.nativeOrder()).asFloatBuffer();
-      mGridPositions.put(positionData).position(0);
-
-      mGridNormals = ByteBuffer.allocateDirect(NORMAL_DATA_SIZE*dataLength*BYTES_PER_FLOAT).order(ByteOrder.nativeOrder()).asFloatBuffer();
-      mGridNormals.put(normalData).position(0);
-
-      mGridTexture = ByteBuffer.allocateDirect(TEX_DATA_SIZE*dataLength*BYTES_PER_FLOAT).order(ByteOrder.nativeOrder()).asFloatBuffer();
-      mGridTexture.put(textureData).position(0);
-      }
-  }
\ No newline at end of file
diff --git a/src/main/java/org/distorted/library/DistortedCubesGrid.java b/src/main/java/org/distorted/library/DistortedCubesGrid.java
deleted file mode 100644
index 3573f4f..0000000
--- a/src/main/java/org/distorted/library/DistortedCubesGrid.java
+++ /dev/null
@@ -1,788 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// Copyright 2016 Leszek Koltunski                                                               //
-//                                                                                               //
-// This file is part of Distorted.                                                               //
-//                                                                                               //
-// Distorted is free software: you can redistribute it and/or modify                             //
-// it under the terms of the GNU General Public License as published by                          //
-// the Free Software Foundation, either version 2 of the License, or                             //
-// (at your option) any later version.                                                           //
-//                                                                                               //
-// Distorted is distributed in the hope that it will be useful,                                  //
-// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
-// GNU General Public License for more details.                                                  //
-//                                                                                               //
-// You should have received a copy of the GNU General Public License                             //
-// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-package org.distorted.library;
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.util.ArrayList;
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-public class DistortedCubesGrid extends DistortedObjectGrid
-   {
-   private static final float R = 0.0f;//0.2f;
-   private static final float FRONTZ = 0.5f;
-   private static final float BACKZ  =-0.5f;
-   
-   private static final int NORTH = 0;
-   private static final int WEST  = 1;
-   private static final int EAST  = 2;
-   private static final int SOUTH = 3;
-
-   private static final boolean BACK  = true;
-   private static final boolean FRONT = false;
-   private static final boolean UPPER = false;
-   private static final boolean LOWER = true;
-   
-   private static final float[] mNormalX = new float[4];
-   private static final float[] mNormalY = new float[4];
-   private static final float[] mNormalZ = new float[4];
-
-   private class Edge
-     {
-     final int side; 
-     final int row;
-     final int col;
-     
-     Edge(int s, int r, int c)
-       {
-       side= s; 
-       row = r;
-       col = c;
-       }
-     }
-   
-   private int mCols, mRows;
-   private short[][] mCubes;
-   private ArrayList<Edge> mEdges = new ArrayList<>();
-
-   private int remainingVert;
-   private int mSideBends;
-   private int mEdgeNum;
-   private int mSideWalls;
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// a Block is split into two triangles along the NE-SW line iff it is in the top-right
-// or bottom-left quadrant of the grid.
-
-   private boolean isNE(int row,int col)
-     {
-     return ( (2*row<mRows)^(2*col<mCols) );
-     }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// return the number of vertices our grid will contain
-
-   private int computeDataLength(boolean frontOnly)
-      {
-      int frontWalls=0, frontSegments=0, triangleShifts=0, windingShifts=0;
-      int shiftCol = (mCols-1)/2;
-
-      boolean lastBlockIsNE=false;
-      boolean thisBlockIsNE;        // the block we are currently looking at is split into
-                                    // two triangles along the NE-SW line (rather than NW-SE)
-      for(int row=0; row<mRows; row++)
-        {
-        if( mCols>=2 && (mCubes[row][shiftCol]%2 == 1) && (mCubes[row][shiftCol+1]%2 == 1) ) triangleShifts++;
-
-        for(int col=0; col<mCols; col++)
-          {
-          if( mCubes[row][col]%2 == 1 )  // land
-            {
-            thisBlockIsNE = isNE(row,col);
-            if( thisBlockIsNE^lastBlockIsNE ) windingShifts++;
-            lastBlockIsNE = thisBlockIsNE;
-            frontWalls++;
-            if( col==mCols-1 || mCubes[row][col+1]%2 == 0 ) frontSegments++;
-            }
-          }
-        }
-
-      int frontVert = 2*( frontWalls + 2*frontSegments - 1) +2*triangleShifts + windingShifts;
-      int sideVert  = 2*( mSideWalls + mSideBends + mEdgeNum -1);
-      int firstWinding= (!frontOnly && (frontVert+1)%2==1 ) ? 1:0;
-      int dataL = frontOnly ? frontVert : (frontVert+1) +firstWinding+ (1+sideVert+1) + (1+frontVert);
-/*
-      android.util.Log.e("CUBES","triangleShifts="+triangleShifts+" windingShifts="+windingShifts+" winding1="+firstWinding+" frontVert="+frontVert+" sideVert="+sideVert);
-      android.util.Log.e("CUBES", "frontW="+frontWalls+" fSegments="+frontSegments+" sWalls="+mSideWalls+" sSegments="+mEdgeNum+" sideBends="+mSideBends+" dataLen="+dataL );
-*/
-      return dataL<0 ? 0:dataL;
-      }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/*
-   private static String debug(short[] val)
-     {
-     String ret="";j
-     
-     for(int i=0; i<val.length; i++) ret+=(" "+val[i]); 
-     
-     return ret;
-     }
-*/
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/*
-   private static String debug(float[] val, int stop)
-     {
-     String ret="";
-
-     for(int i=0; i<val.length; i++) 
-        {
-        if( i%stop==0 ) ret+="\n";
-        ret+=(" "+val[i]);
-        }
-
-     return ret;
-     }
-*/  
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/*
-   private static String debug(Edge e)
-     {
-     String d = "";
-     
-     switch(e.side)
-       {
-       case NORTH: d+="NORTH "; break;
-       case SOUTH: d+="SOUTH "; break;
-       case WEST : d+="WEST  "; break;
-       case EAST : d+="EAST  "; break;
-       }
-     
-     d+=("("+e.row+","+e.col+")");
-     
-     return d;
-     }   
-*/
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// desc is guaranteed to be padded with 0s in the end (DistortedCubes constructor does it)
-
-   private void prepareDataStructures(int cols, String desc, boolean frontOnly)
-     {
-     mRows     =0;
-     mCols     =0;
-     dataLength=0;
-     
-     if( cols>0 && desc.contains("1") )
-       {
-       mCols = cols;
-       mRows = desc.length()/cols;
-
-       mCubes = new short[mRows][mCols];
-       
-       for(int j=0; j<mCols; j++)
-         for(int i=0; i<mRows; i++)
-           mCubes[i][j] = (short)(desc.charAt(i*mCols+j) == '1' ? 1:0);
-       
-       markRegions();
-       dataLength = computeDataLength(frontOnly);
-
-       remainingVert = dataLength;
-       }
-     }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// full grid
-
-   private void prepareDataStructures(int cols, int rows, boolean frontOnly)
-     {
-     mRows     =rows;
-     mCols     =cols;
-     dataLength=   0;
-
-     if( cols>0 && rows>0 )
-       {
-       mCubes = new short[mRows][mCols];
-
-       for(int j=0; j<mCols; j++)
-         for(int i=0; i<mRows; i++)
-           mCubes[i][j] = (short)1;
-
-       markRegions();
-       dataLength = computeDataLength(frontOnly);
-
-       remainingVert = dataLength;
-       }
-     }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// Mark all the 'regions' of our grid  - i.e. separate pieces of 'land' (connected blocks that will 
-// be rendered) and 'water' (connected holes in between) with integers. Each connected block of land
-// gets a unique odd integer, each connected block of water a unique even integer.
-//
-// Water on the edges of the grid is also considered connected to itself!   
-//   
-// This function also creates a list of 'Edges'. Each Edge is a data structure from which later on we
-// will start building the side walls of each connected block of land (and sides of holes of water
-// inside). Each Edge needs to point from Land to Water (thus the '(SOUTH,i-1,j)' below) - otherwise
-// later on setting up normal vectors wouldn't work.
-   
-   private void markRegions()
-     {
-     int i, j, numWater=1, numLand=0;
-     
-     for(i=0; i<mRows;i++) if( mCubes[      i][      0]==0 ) markRegion((short)2,      i,       0);
-     for(i=0; i<mRows;i++) if( mCubes[      i][mCols-1]==0 ) markRegion((short)2,      i, mCols-1);
-     for(i=0; i<mCols;i++) if( mCubes[0      ][      i]==0 ) markRegion((short)2,      0,       i);
-     for(i=0; i<mCols;i++) if( mCubes[mRows-1][      i]==0 ) markRegion((short)2,mRows-1,       i);
-           
-     for(i=0; i<mRows; i++)
-        for(j=0; j<mCols; j++)
-           {
-           if( mCubes[i][j] == 0 ) { numWater++; markRegion( (short)(2*numWater ),i,j); mEdges.add(new Edge(SOUTH,i-1,j)); }
-           if( mCubes[i][j] == 1 ) { numLand ++; markRegion( (short)(2*numLand+1),i,j); mEdges.add(new Edge(NORTH,i  ,j)); }
-           }
-     
-     // now we potentially need to kick out some Edges . Otherwise the following does not work:
-     //
-     // 0 1 0
-     // 1 0 1
-     // 0 1 0
-     
-     mEdgeNum= mEdges.size();
-     int initCol, initRow, initSide, lastSide;
-     Edge e1,e2;
-     
-     for(i=0; i<mEdgeNum; i++)
-       {
-       e1 = mEdges.get(i);
-       initRow= e1.row;
-       initCol= e1.col;
-       initSide=e1.side;
-
-       do
-         {
-         //android.util.Log.d("CUBES", "checking edge "+debug(e1));
-
-         mSideWalls++;
-
-         if( e1.side==NORTH || e1.side==SOUTH )
-           {
-           for(j=i+1;j<mEdgeNum;j++)
-             {
-             e2 = mEdges.get(j);
-
-             if( e2.side==e1.side && e2.row==e1.row && e2.col==e1.col )
-               {
-               mEdges.remove(j);
-               mEdgeNum--;
-               j--;
-
-               //android.util.Log.e("CUBES", "removing edge "+debug(e2));
-               }
-             }
-           }
-
-         lastSide = e1.side;
-         e1 = getNextEdge(e1);
-         if( e1.side!=lastSide ) mSideBends++;
-         }
-       while( e1.col!=initCol || e1.row!=initRow || e1.side!=initSide );
-       }
-     }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// when calling, make sure that newVal != val
-   
-   private void markRegion(short newVal, int row, int col)
-     {
-     short val = mCubes[row][col];
-     mCubes[row][col] = newVal;
-     
-     if( row>0       && mCubes[row-1][col  ]==val ) markRegion(newVal, row-1, col  );
-     if( row<mRows-1 && mCubes[row+1][col  ]==val ) markRegion(newVal, row+1, col  );
-     if( col>0       && mCubes[row  ][col-1]==val ) markRegion(newVal, row  , col-1);
-     if( col<mCols-1 && mCubes[row  ][col+1]==val ) markRegion(newVal, row  , col+1);
-     }
-   
-///////////////////////////////////////////////////////////////////////////////////////////////////
-   
-   private void createNormals(boolean front, int row, int col)
-     {
-     int td,lr; 
-      
-     int nw = (col>0       && row>0      ) ? (mCubes[row-1][col-1]%2) : 0;
-     int w  = (col>0                     ) ? (mCubes[row  ][col-1]%2) : 0;
-     int n  = (               row>0      ) ? (mCubes[row-1][col  ]%2) : 0;
-     int c  =                                (mCubes[row  ][col  ]%2);
-     int sw = (col>0       && row<mRows-1) ? (mCubes[row+1][col-1]%2) : 0;
-     int s  = (               row<mRows-1) ? (mCubes[row+1][col  ]%2) : 0;
-     int ne = (col<mCols-1 && row>0      ) ? (mCubes[row-1][col+1]%2) : 0;
-     int e  = (col<mCols-1               ) ? (mCubes[row  ][col+1]%2) : 0;
-     int se = (col<mCols-1 && row<mRows-1) ? (mCubes[row+1][col+1]%2) : 0;
-
-     if(front)
-       {
-       mNormalZ[0] = 1.0f;
-       mNormalZ[1] = 1.0f;
-       mNormalZ[2] = 1.0f;
-       mNormalZ[3] = 1.0f;
-       }
-     else
-       {
-       mNormalZ[0] =-1.0f;
-       mNormalZ[1] =-1.0f;
-       mNormalZ[2] =-1.0f;
-       mNormalZ[3] =-1.0f;
-       }
-
-     td = nw+n-w-c;
-     lr = c+n-w-nw;
-     if( td<0 ) td=-1;
-     if( td>0 ) td= 1;
-     if( lr<0 ) lr=-1;
-     if( lr>0 ) lr= 1;
-     mNormalX[0] = lr*R;
-     mNormalY[0] = td*R;
-     
-     td = w+c-sw-s;
-     lr = c+s-w-sw;
-     if( td<0 ) td=-1;
-     if( td>0 ) td= 1;
-     if( lr<0 ) lr=-1;
-     if( lr>0 ) lr= 1;
-     mNormalX[1] = lr*R;
-     mNormalY[1] = td*R;
-     
-     td = n+ne-c-e;
-     lr = e+ne-c-n;
-     if( td<0 ) td=-1;
-     if( td>0 ) td= 1;
-     if( lr<0 ) lr=-1;
-     if( lr>0 ) lr= 1;
-     mNormalX[2] = lr*R;
-     mNormalY[2] = td*R;
-     
-     td = c+e-s-se;
-     lr = e+se-c-s;
-     if( td<0 ) td=-1;
-     if( td>0 ) td= 1;
-     if( lr<0 ) lr=-1;
-     if( lr>0 ) lr= 1;
-     mNormalX[3] = lr*R;
-     mNormalY[3] = td*R;
-     /*
-     android.util.Log.d("CUBES", "row="+row+" col="+col);
-     android.util.Log.d("CUBES", mNormalX[0]+" "+mNormalY[0]);
-     android.util.Log.d("CUBES", mNormalX[1]+" "+mNormalY[1]);
-     android.util.Log.d("CUBES", mNormalX[2]+" "+mNormalY[2]);
-     android.util.Log.d("CUBES", mNormalX[3]+" "+mNormalY[3]);
-     */
-     }
-   
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-   private int addFrontVertex(int vertex, int index, float vectZ, int col, int row, float[] position, float[] normal, float[] texture)
-     {
-     remainingVert--;
-
-     float x = (float)col/mCols;
-     float y = (float)row/mRows;
-
-     position[3*vertex  ] = x-0.5f;
-     position[3*vertex+1] = 0.5f-y;
-     position[3*vertex+2] = vectZ;
-     normal[3*vertex  ]   = mNormalX[index];
-     normal[3*vertex+1]   = mNormalY[index];
-     normal[3*vertex+2]   = mNormalZ[index];
-     texture[2*vertex  ]  = x;
-     texture[2*vertex+1]  = 1.0f-y;
-
-     return vertex+1;
-     }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-   private int buildFrontBackGrid(boolean front, int vertex, float[] position, float[] normal, float[] texture)
-     {
-     short last, current;
-     boolean seenLand=false;
-     boolean lastBlockIsNE = false;
-     boolean currentBlockIsNE;
-     float vectZ = front?FRONTZ:BACKZ;
-
-     //android.util.Log.d("CUBES", "buildFrontBack");
-
-     for(int row=0; row<mRows; row++)
-       {
-       last =0;
-         
-       for(int col=0; col<mCols; col++)
-         {
-         current = mCubes[row][col];
-
-         if( current%2 == 1 )
-           {
-           currentBlockIsNE = isNE(row,col);
-
-           if( !seenLand && !front && ((vertex%2==1)^currentBlockIsNE) )
-             {
-             //android.util.Log.d("CUBES","repeating winding2 vertex");
-
-             vertex = repeatLast(vertex,position,normal,texture);
-             }
-
-           createNormals(front,row,col);
-
-           if( currentBlockIsNE )
-             {
-             if( (last!=current) || !lastBlockIsNE )
-               {
-               if( seenLand  && (last != current) ) vertex = repeatLast(vertex,position,normal,texture);
-               vertex= addFrontVertex( vertex, 0, vectZ, col, row, position, normal, texture);
-               if( seenLand  && (last != current) ) vertex = repeatLast(vertex,position,normal,texture);
-               if( !lastBlockIsNE || (!front && !seenLand) ) vertex = repeatLast(vertex,position,normal,texture);
-               vertex= addFrontVertex( vertex, 1, vectZ, col, row+1, position, normal, texture);
-               }
-             vertex= addFrontVertex( vertex, 2, vectZ, col+1, row, position, normal, texture);
-             vertex= addFrontVertex( vertex, 3, vectZ, col+1, row+1, position, normal, texture);
-             }
-           else
-             {
-             if( (last!=current) || lastBlockIsNE )
-               {
-               if( seenLand  && (last != current) ) vertex = repeatLast(vertex,position,normal,texture);
-               vertex= addFrontVertex( vertex, 1, vectZ, col, row+1, position, normal, texture);
-               if( seenLand  && (last != current) ) vertex = repeatLast(vertex,position,normal,texture);
-               if( lastBlockIsNE || (!front && !seenLand) ) vertex = repeatLast(vertex,position,normal,texture);
-               vertex= addFrontVertex( vertex, 0, vectZ, col, row, position, normal, texture);
-               }
-             vertex= addFrontVertex( vertex, 3, vectZ, col+1, row+1, position, normal, texture);
-             vertex= addFrontVertex( vertex, 2, vectZ, col+1, row  , position, normal, texture);
-             }
-
-           seenLand = true;
-           lastBlockIsNE = currentBlockIsNE;
-           }
-            
-         last = current;
-         }
-       }
-     
-     return vertex;
-     }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-   private int repeatLast(int vertex, float[] position, float[] normal, float[] texture)
-     {
-     //android.util.Log.e("CUBES", "repeating last vertex!");
-
-     if( vertex>0 )
-       {
-       remainingVert--;
-
-       position[3*vertex  ] = position[3*vertex-3];
-       position[3*vertex+1] = position[3*vertex-2];
-       position[3*vertex+2] = position[3*vertex-1];
-
-       normal[3*vertex  ]   = normal[3*vertex-3];
-       normal[3*vertex+1]   = normal[3*vertex-2];
-       normal[3*vertex+2]   = normal[3*vertex-1];
-
-       texture[2*vertex  ]  = texture[2*vertex-2];
-       texture[2*vertex+1]  = texture[2*vertex-1];
-         
-       vertex++;     
-       }
-     
-     return vertex;
-     }
-   
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-   private int buildSideGrid(int vertex, float[] position, float[] normal, float[] texture)
-     {
-     //android.util.Log.d("CUBES", "buildSide");
-
-     for(int i=0; i<mEdgeNum; i++)
-       {
-       vertex = buildIthSide(mEdges.get(i), vertex, position, normal, texture);  
-       } 
-      
-     return vertex;
-     }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-   private int buildIthSide(Edge curr, int vertex, float[] position, float[] normal, float[] texture)
-     {
-     Edge prev; 
-     
-     if( curr.side==NORTH ) // water outside
-       {
-       prev = new Edge(WEST,curr.row,curr.col);
-       }
-     else                   // land outside; we need to move forward one link because we are going in opposite direction and we need to start from a bend.
-       {
-       prev = curr;
-       curr = new Edge(EAST,curr.row+1,curr.col-1);
-       }
-     
-     int col = curr.col;
-     int row = curr.row;
-     int side= curr.side;  
-     Edge next = getNextEdge(curr);
-     
-     addSideVertex(curr,BACK,LOWER,prev.side,vertex,position,normal,texture);
-     vertex++;
-     
-     do
-       {
-       if( prev.side!=curr.side )
-         {
-         addSideVertex(curr,BACK,LOWER,prev.side,vertex,position,normal,texture);
-         vertex++;
-         addSideVertex(curr,BACK,UPPER,prev.side,vertex,position,normal,texture);
-         vertex++;
-         }
-       
-       addSideVertex(curr,FRONT,LOWER,next.side,vertex,position,normal,texture);
-       vertex++;
-       addSideVertex(curr,FRONT,UPPER,next.side,vertex,position,normal,texture);
-       vertex++;
-       
-       prev = curr;
-       curr = next; 
-       next = getNextEdge(curr);
-       }
-     while( curr.col!=col || curr.row!=row || curr.side!=side );
-     
-     vertex = repeatLast(vertex,position,normal,texture);
-     
-     return vertex;
-     }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-   private Edge getNextEdge(Edge curr)
-     {
-     int col = curr.col;
-     int row = curr.row;
-      
-     //android.util.Log.e("CUBES", "row="+row+" col="+col+" mRows="+mRows+" mCols="+mCols);
-                       
-     switch(curr.side) 
-       {
-       case NORTH: if( col==mCols-1 ) 
-                     return new Edge(EAST,row,col);
-                   if( row>0 && mCubes[row-1][col+1]==mCubes[row][col] )
-                     return new Edge(WEST,row-1,col+1);
-                   if( mCubes[row][col+1]==mCubes[row][col] )
-                     return new Edge(NORTH,row,col+1);
-                   else  
-                     return new Edge(EAST,row,col);
-                   
-       case SOUTH: if( col==0 ) 
-                     return new Edge(WEST,row,col);
-                   if( (row<mRows-1) && mCubes[row+1][col-1]==mCubes[row][col] )
-                     return new Edge(EAST,row+1,col-1); 
-                   if( mCubes[row][col-1]==mCubes[row][col] )
-                     return new Edge(SOUTH,row,col-1);
-                   else
-                     return new Edge(WEST,row,col); 
-                     
-       case EAST : if( row==mRows-1 ) 
-                     return new Edge(SOUTH,row,col);
-                   if( (col<mCols-1) && mCubes[row+1][col+1]==mCubes[row][col] )
-                     return new Edge(NORTH,row+1,col+1);
-                   if( mCubes[row+1][col]==mCubes[row][col] )
-                     return new Edge(EAST,row+1,col);
-                   else 
-                     return new Edge(SOUTH,row,col);
-                   
-       default   : if( row==0 )
-                     return new Edge(NORTH,row,col);
-                   if( col>0 && mCubes[row-1][col-1]==mCubes[row][col] )
-                     return new Edge(SOUTH,row-1,col-1);
-                   if( mCubes[row-1][col]==mCubes[row][col] )
-                     return new Edge(WEST,row-1,col);
-                   else
-                     return new Edge(NORTH,row,col);     
-       }
-     }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-   
-   private void addSideVertex(Edge curr, boolean back, boolean lower,int side, int vertex, float[] position, float[] normal, float[] texture)
-     {
-     //android.util.Log.e("CUBES", "adding Side vertex!");
-
-     remainingVert--;
-
-     float x, y;
-
-     switch(curr.side)
-       {
-       case NORTH: x = (float)(back ? (curr.col  ):(curr.col+1))/mCols;
-
-                   position[3*vertex  ] = x - 0.5f;
-                   position[3*vertex+1] = 0.5f - (float)curr.row/mRows;
-                   position[3*vertex+2] = lower ? BACKZ : FRONTZ;
-
-                   normal[3*vertex  ]   = side==NORTH ? 0.0f : (side==WEST?-R:R);
-                   normal[3*vertex+1]   = 1.0f;
-                   normal[3*vertex+2]   = lower ? -R:R;
-
-                   texture[2*vertex  ]  = x;
-                   texture[2*vertex+1]  = 1.0f-(float)(lower? (curr.row-1):(curr.row  ))/mRows;
-                   break;
-       case SOUTH: x = (float)(back ? (curr.col+1):(curr.col  ))/mCols;
-
-                   position[3*vertex  ] = x - 0.5f;
-                   position[3*vertex+1] = 0.5f - (float)(curr.row+1)/mRows;
-                   position[3*vertex+2] = lower ? BACKZ : FRONTZ;  
-            
-                   normal[3*vertex  ]   = side==SOUTH ? 0.0f: (side==EAST?-R:R);
-                   normal[3*vertex+1]   =-1.0f;
-                   normal[3*vertex+2]   = lower ? -R:R;
-
-                   texture[2*vertex  ]  = x;
-                   texture[2*vertex+1]  = 1.0f-(float)(lower? (curr.row+2):(curr.row+1))/mRows;
-                   break;
-       case WEST : y = (float)(back  ? (curr.row+1):(curr.row))/mRows;
-
-                   position[3*vertex  ] = (float)curr.col/mCols -0.5f;
-                   position[3*vertex+1] = 0.5f - y;
-                   position[3*vertex+2] = lower ? BACKZ : FRONTZ;
-
-                   normal[3*vertex  ]   =-1.0f;
-                   normal[3*vertex+1]   = side==WEST ? 0.0f : (side==NORTH?-R:R);
-                   normal[3*vertex+2]   = lower ? -R:R;
- 
-                   texture[2*vertex  ]  = (float)(lower ? (curr.col-1):(curr.col  ))/mCols;
-                   texture[2*vertex+1]  = 1.0f - y;
-                   break;
-       case EAST : y = (float)(back  ? (curr.row):(curr.row+1))/mRows;
-
-                   position[3*vertex  ] = (float)(curr.col+1)/mCols -0.5f;
-                   position[3*vertex+1] = 0.5f - y;
-                   position[3*vertex+2] = lower ? BACKZ : FRONTZ;
-
-                   normal[3*vertex  ]   = 1.0f;
-                   normal[3*vertex+1]   = side==EAST ? 0.0f : (side==SOUTH?-R:R);
-                   normal[3*vertex+2]   = lower ? -R:R; 
-
-                   texture[2*vertex  ]  = (float)(lower ? (curr.col+2):(curr.col+1))/mCols;
-                   texture[2*vertex+1]  = 1.0f - y;
-                   break;
-       }
-     
-     if(texture[2*vertex  ]>1.0f) texture[2*vertex  ] =2.0f-texture[2*vertex  ];
-     if(texture[2*vertex  ]<0.0f) texture[2*vertex  ] =    -texture[2*vertex  ];
-     if(texture[2*vertex+1]>1.0f) texture[2*vertex+1] =2.0f-texture[2*vertex+1];
-     if(texture[2*vertex+1]<0.0f) texture[2*vertex+1] =    -texture[2*vertex+1];
-     }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-   private void build(boolean frontOnly)
-     {
-     int numVertices=0;
-     float[] positionData= new float[POSITION_DATA_SIZE*dataLength];
-     float[] normalData  = new float[NORMAL_DATA_SIZE  *dataLength];
-     float[] textureData = new float[TEX_DATA_SIZE     *dataLength];
-
-     //android.util.Log.d("CUBES","building front grid...");
-
-     numVertices = buildFrontBackGrid(true, numVertices,positionData,normalData,textureData);
-
-     if( !frontOnly )
-       {
-       numVertices = repeatLast(numVertices,positionData,normalData,textureData);
-       if( numVertices%2==1 )
-         {
-         //android.util.Log.d("CUBES","repeating winding1 vertex");
-
-         numVertices = repeatLast(numVertices,positionData,normalData,textureData);
-         }
-
-       //android.util.Log.d("CUBES","building side grid...");
-
-       numVertices = buildSideGrid (numVertices,positionData,normalData,textureData);
-
-       //android.util.Log.d("CUBES","building back grid...");
-
-       numVertices = buildFrontBackGrid (false,numVertices,positionData,normalData,textureData);
-       }
-
-     /*
-     android.util.Log.e("CUBES","dataLen="+dataLength+" vertex="+numVertices);
-     android.util.Log.d("CUBES", "position: "+debug(positionData,3) );
-     android.util.Log.d("CUBES", "normal: "  +debug(  normalData,3) );
-     android.util.Log.d("CUBES", "texture: " +debug( textureData,2) );
-     */
-
-     mEdges.clear();
-     mEdges = null;
-     mCubes = null;
-
-     if( remainingVert!=0 )
-       android.util.Log.d("CUBES", "remainingVert " +remainingVert );
-
-     mGridPositions = ByteBuffer.allocateDirect(POSITION_DATA_SIZE*dataLength*BYTES_PER_FLOAT).order(ByteOrder.nativeOrder()).asFloatBuffer();
-     mGridPositions.put(positionData).position(0);
-
-     mGridNormals = ByteBuffer.allocateDirect(NORMAL_DATA_SIZE*dataLength*BYTES_PER_FLOAT).order(ByteOrder.nativeOrder()).asFloatBuffer();
-     mGridNormals.put(normalData).position(0);
-
-     mGridTexture = ByteBuffer.allocateDirect(TEX_DATA_SIZE*dataLength*BYTES_PER_FLOAT).order(ByteOrder.nativeOrder()).asFloatBuffer();
-     mGridTexture.put(textureData).position(0);
-     }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// PUBLIC API
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/**
- * Creates the underlying grid of vertices, normals, texture coords and colors.
- *    
- * @param cols      Integer helping to parse the next parameter.
- * @param desc      String describing the subset of a MxNx1 cuboid that we want to create.
- *                  Its MxN characters - all 0 or 1 - decide of appropriate field is taken or not.
- *                  <p></p>
- *                  <p>
- *                  <pre>
- *                  For example, (cols=2, desc="111010") describes the following shape:
- *
- *                  XX
- *                  X
- *                  X
- *
- *                  whereas (cols=2,desc="110001") describes
- *
- *                  XX
- *
- *                   X
- *                  </pre>
- *                  </p>
- * @param frontOnly Only create the front wall or side and back as well?
- */
-   public DistortedCubesGrid(int cols, String desc, boolean frontOnly)
-      {
-      prepareDataStructures(cols,desc,frontOnly);
-      build(frontOnly);
-      }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/**
- * Creates a full, hole-less underlying grid of vertices, normals, texture coords and colors.
- *
- * @param cols      Number of columns.
- * @param rows      Number of rows.
- * @param frontOnly Only create the front wall or side and back as well?
- */
-   public DistortedCubesGrid(int cols, int rows, boolean frontOnly)
-      {
-      prepareDataStructures(cols,rows,frontOnly);
-      build(frontOnly);
-      }
-   }
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
diff --git a/src/main/java/org/distorted/library/DistortedFramebuffer.java b/src/main/java/org/distorted/library/DistortedFramebuffer.java
index b8b4735..c441f6d 100644
--- a/src/main/java/org/distorted/library/DistortedFramebuffer.java
+++ b/src/main/java/org/distorted/library/DistortedFramebuffer.java
@@ -31,7 +31,7 @@ import java.util.LinkedList;
  * <p>
  * User is able to create either Framebuffers from objects already constructed outside
  * of the library (the first constructor; primary use case: the screen) or an offscreen
- * FBOs (used by the DistortedNode, but also can be used by external users of the library)
+ * FBOs (used by the DistortedObjectTree, but also can be used by external users of the library)
  * <p>
  * Also, keep all objects created in a static LinkedList. The point: we need to be able to mark
  * Framebuffers for deletion, and delete all marked objects later at a convenient time (that's
diff --git a/src/main/java/org/distorted/library/DistortedNode.java b/src/main/java/org/distorted/library/DistortedNode.java
deleted file mode 100644
index 416df04..0000000
--- a/src/main/java/org/distorted/library/DistortedNode.java
+++ /dev/null
@@ -1,495 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// Copyright 2016 Leszek Koltunski                                                               //
-//                                                                                               //
-// This file is part of Distorted.                                                               //
-//                                                                                               //
-// Distorted is free software: you can redistribute it and/or modify                             //
-// it under the terms of the GNU General Public License as published by                          //
-// the Free Software Foundation, either version 2 of the License, or                             //
-// (at your option) any later version.                                                           //
-//                                                                                               //
-// Distorted is distributed in the hope that it will be useful,                                  //
-// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
-// GNU General Public License for more details.                                                  //
-//                                                                                               //
-// You should have received a copy of the GNU General Public License                             //
-// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-package org.distorted.library;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import android.opengl.GLES20;
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/**
- * Class which represents a Node in a Tree of DistortedObjects.
- *  
- * Having organized a set of DistortedObjects into a Tree, we can then render any Node to any Framebuffer.
- * That recursively renders the Object held in the Node and all its children, along with whatever effects
- * each one of them has. 
- */
-public class DistortedNode 
-  {
-  private static HashMap<ArrayList<Long>,NodeData> mMapNodeID = new HashMap<>();
-  private static long mNextNodeID =0;
-
-  private DistortedObjectGrid mGrid;
-  private DistortedObject mObject;
-  private NodeData mData;
-
-  private DistortedNode mParent;
-  private ArrayList<DistortedNode> mChildren;
-  private int[] mNumChildren;  // ==mChildren.length(), but we only create mChildren if the first one gets added
-
-  private class NodeData
-    {
-    long ID;
-    int numPointingNodes;
-    DistortedFramebuffer mDF;
-    boolean mRendered;
-
-    NodeData(long id)
-      {
-      ID              = id;
-      numPointingNodes= 1;
-      mDF             = null;
-      mRendered       = false;
-      }
-    }
- 
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-  static void release()
-    {
-    mNextNodeID = 0;
-    mMapNodeID.clear();
-    }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-  private void markRecursive()
-    {
-    mData.mRendered = false;
-   
-    synchronized(this)
-      {
-      for(int i=0; i<mNumChildren[0]; i++) mChildren.get(i).markRecursive();
-      }
-    }
-  
-///////////////////////////////////////////////////////////////////////////////////////////////////
-  
-  private void drawRecursive(long currTime, DistortedFramebuffer df)
-    {
-    if( mNumChildren[0]<=0 )
-      {
-      GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mObject.mTextureDataH[0]);
-      }
-    else
-      {
-      if( !mData.mRendered )
-        {
-        mData.mRendered = true;
-        mData.mDF.setAsOutput();
-
-        GLES20.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
-        GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
-      
-        if( mObject.mBitmapSet[0] )
-          {
-          GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mObject.mTextureDataH[0]);
-          mObject.drawNoEffectsPriv(mGrid, mData.mDF);
-          }
-      
-        synchronized(this)
-          {
-          for(int i=0; i<mNumChildren[0]; i++)
-            {
-            mChildren.get(i).drawRecursive(currTime, mData.mDF);
-            }
-          }
-        }
-
-      df.setAsOutput();
-      mData.mDF.setAsInput();
-      }
-    
-    mObject.drawPriv(currTime, mGrid, df);
-    }
-  
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// tree isomorphism
-  
-  private void RecomputeNodeID(ArrayList<Long> prev)
-    {
-    ArrayList<Long> curr = generateIDList();
-     
-    if( mParent==null )
-      {
-      adjustNodeData(prev,curr);
-      }
-    else
-      {
-      ArrayList<Long> parentPrev = mParent.generateIDList();
-      adjustNodeData(prev,curr);
-      mParent.RecomputeNodeID(parentPrev);
-      }
-    }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-  private ArrayList<Long> generateIDList()
-    {
-    ArrayList<Long> ret = new ArrayList<>();
-     
-    ret.add( mNumChildren[0]>0 ? mObject.getBitmapID() : mObject.getID() );
-    DistortedNode node;
-   
-    for(int i=0; i<mNumChildren[0]; i++)
-      {
-      node = mChildren.get(i);
-      ret.add(node.mData.ID);
-      }
-   
-    return ret;
-    }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-  private void adjustNodeData(ArrayList<Long> oldList, ArrayList<Long> newList)
-    {
-    boolean otherNodesPoint = (mData.numPointingNodes>1);
-
-    if( otherNodesPoint ) mData.numPointingNodes--;
-    else                  mMapNodeID.remove(oldList);
-   
-    NodeData newData = mMapNodeID.get(newList);
-    
-    if( newData==null )
-      {
-      if( otherNodesPoint )  mData = new NodeData(++mNextNodeID);
-      else                   mData.ID = ++mNextNodeID;  // numPointingNodes must be 1 already
-
-      if( newList.size()>1 )
-        {
-        if( mData.mDF==null )
-          mData.mDF = new DistortedFramebuffer(mObject.getWidth(), mObject.getHeight());
-        }
-      else
-        {
-        if( mData.mDF!=null )
-          {
-          mData.mDF.markForDeletion();
-          mData.mDF = null;
-          }
-        else
-          {
-          android.util.Log.e("DistortedNode", "adjustNodeData: impossible situation??");
-          }
-        }
-
-      mMapNodeID.put(newList, mData);
-      }
-    else
-      {
-      newData.numPointingNodes++;
-      mData = newData;
-      }
-    }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////  
-// this will be called on startup and every time OpenGL context has been lost
-// also call this from the constructor if the OpenGL context has been created already.
-    
-  static void reset()
-    {
-    NodeData tmp;   
-     
-    for(ArrayList<Long> key: mMapNodeID.keySet())
-      {
-      tmp = mMapNodeID.get(key);
-          
-      if( tmp.mDF != null )
-        {
-    	  tmp.mDF.reset();
-        tmp.mRendered  = false;
-        }
-      }
-    }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// Debug - print all the Node IDs
-/*
-  void debug(int depth)
-    {
-    String tmp="";
-    int i;
-
-    for(i=0; i<depth; i++) tmp +="   ";
-    tmp += (""+mData.ID);
-
-    android.util.Log.e("node", tmp);
-
-    for(i=0; i<mNumChildren[0]; i++)
-      mChildren.get(i).debug(depth+1);
-    }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// Debug - print contents of the HashMap
-
-  static void debugMap()
-    {
-    NodeData tmp;
-
-    for(ArrayList<Long> key: mMapNodeID.keySet())
-      {
-      tmp = mMapNodeID.get(key);
-
-      android.util.Log.e("NODE", "key="+key+" NodeID: "+tmp.ID);
-      }
-    }
-*/
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// PUBLIC API
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/**
- * Constructs new Node of the Tree.
- *     
- * @param obj DistortedObject to put into the new Node.
- */
-  public DistortedNode(DistortedObject obj, DistortedObjectGrid grid)
-    {
-    mObject = obj;
-    mGrid   = grid;
-    mParent = null;
-    mChildren = null;
-    mNumChildren = new int[1];
-    mNumChildren[0] = 0;
-   
-    ArrayList<Long> list = new ArrayList<>();
-    list.add(obj.getID());
-      
-    mData = mMapNodeID.get(list);
-   
-    if( mData!=null )
-      {
-      mData.numPointingNodes++;
-      }
-    else
-      {
-      mData = new NodeData(++mNextNodeID);   
-      mMapNodeID.put(list, mData);  
-      }
-    }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////  
-/**
- * Copy-constructs new Node of the Tree from another Node.
- *     
- * @param node The DistortedNode to copy data from.
- * @param flags bit field composed of a subset of the following:
- *        {@link Distorted#CLONE_BITMAP},  {@link Distorted#CLONE_MATRIX}, {@link Distorted#CLONE_VERTEX},
- *        {@link Distorted#CLONE_FRAGMENT} and {@link Distorted#CLONE_CHILDREN}.
- *        For example flags = CLONE_BITMAP | CLONE_CHILDREN.
- */
-  public DistortedNode(DistortedNode node, int flags)
-    {
-    mParent = null;
-    mObject = new DistortedObject(node.mObject,flags);
-    mGrid   = node.mGrid;
-
-    if( (flags & Distorted.CLONE_CHILDREN) != 0 )
-      {
-      mChildren = node.mChildren;
-      mNumChildren = node.mNumChildren;
-      }
-    else
-      {
-      mChildren = null;
-      mNumChildren = new int[1];
-      mNumChildren[0] = 0;
-      }
-   
-    ArrayList<Long> list = generateIDList();
-   
-    mData = mMapNodeID.get(list);
-   
-    if( mData!=null )
-      {
-      mData.numPointingNodes++;
-      }
-    else
-      {
-      mData = new NodeData(++mNextNodeID);   
-      mMapNodeID.put(list, mData);
-      }
-    }
-  
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/**
- * Adds a new child to the last position in the list of our Node's children.
- * 
- * @param node The new Node to add.
- */
-  public synchronized void attach(DistortedNode node)
-    {
-    ArrayList<Long> prev = generateIDList(); 
-   
-    if( mChildren==null ) mChildren = new ArrayList<>(2);
-     
-    node.mParent = this;
-    mChildren.add(node);
-    mNumChildren[0]++;
-     
-    RecomputeNodeID(prev);
-    }
-   
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/**
- * Adds a new child to the last position in the list of our Node's children.
- * 
- * @param obj DistortedObject to initialize our child Node with.
- * @return the newly constructed child Node, or null if we couldn't allocate resources.
- */
-  public synchronized DistortedNode attach(DistortedObject obj, DistortedObjectGrid grid)
-    {
-    ArrayList<Long> prev = generateIDList(); 
-      
-    if( mChildren==null ) mChildren = new ArrayList<>(2);
-    DistortedNode node = new DistortedNode(obj,grid);
-    node.mParent = this;
-    mChildren.add(node);
-    mNumChildren[0]++;
-   
-    RecomputeNodeID(prev);
-
-    return node;
-    }
-  
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/**
- * Removes the first occurrence of a specified child from the list of children of our Node.
- * 
- * @param node The Node to remove.
- * @return <code>true</code> if the child was successfully removed.
- */
-  public synchronized boolean detach(DistortedNode node)
-    {
-    if( mNumChildren[0]>0 )
-      {
-      ArrayList<Long> prev = generateIDList();  
-         
-      if( mChildren.remove(node) )
-        {
-        node.mParent = null;  
-        mNumChildren[0]--;
-     
-        RecomputeNodeID(prev);
-     
-        return true;
-        }
-      }
-   
-    return false;
-    }
-  
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/**
- * Removes the first occurrence of a specified child from the list of children of our Node.
- * 
- * @param obj DistortedObject to remove.
- * @return <code>true</code> if the child was successfully removed.
- */
-  public synchronized boolean detach(DistortedObject obj)
-    {
-    long id = obj.getID();
-    DistortedNode node;
-   
-    for(int i=0; i<mNumChildren[0]; i++)
-      {
-      node = mChildren.get(i);
-     
-      if( node.mObject.getID()==id )
-        {
-        ArrayList<Long> prev = generateIDList();   
-     
-        node.mParent = null;  
-        mChildren.remove(i);
-        mNumChildren[0]--;
-      
-        RecomputeNodeID(prev);
-      
-        return true;
-        }
-      }
-   
-    return false;
-    }
-    
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/**
- * Removes all children Nodes.
- */
-  public synchronized void detachAll()
-    {
-    for(int i=0; i<mNumChildren[0]; i++)
-      {
-      mChildren.get(i).mParent = null;
-      }
-   
-    if( mNumChildren[0]>0 )
-      {
-      ArrayList<Long> prev = generateIDList();  
-      
-      mNumChildren[0] = 0;
-      mChildren.clear();
-      RecomputeNodeID(prev);
-      }
-    }
-  
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/**
- * Draws the Node, and all its children, to the default framebuffer 0 (i.e. the screen).
- *   
- * @param currTime Current time, in milliseconds.
- */
-  public void draw(long currTime)
-    {  
-    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
-
-    markRecursive();
-    drawRecursive(currTime,Distorted.mFramebuffer);
-    }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/**
- * Draws the Node, and all its children, to the Framebuffer passed.
- *
- * @param currTime Current time, in milliseconds.
- * @param df       Framebuffer to render this to.
- */
-  public void draw(long currTime, DistortedFramebuffer df)
-    {
-    df.setAsOutput();
-    markRecursive();
-    drawRecursive(currTime,df);
-    }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-/**
- * Returns the DistortedObject object that's in the Node.
- * 
- * @return The DistortedObject contained in the Node.
- */
-  public DistortedObject getObject()
-    {
-    return mObject;
-    }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-  }
-
diff --git a/src/main/java/org/distorted/library/DistortedObject.java b/src/main/java/org/distorted/library/DistortedObject.java
index e0a854e..6130953 100644
--- a/src/main/java/org/distorted/library/DistortedObject.java
+++ b/src/main/java/org/distorted/library/DistortedObject.java
@@ -54,7 +54,7 @@ import java.util.HashMap;
  * <li> Fragment Effects, i.e. effects that change (some of) the pixels of the Bitmap (transparency, macroblock)
  * </ul>
  * <p>
- * Just like in DistortedNode and DistortedFramebuffer, we need to have a static list of all
+ * Just like in DistortedObjectTree and DistortedFramebuffer, we need to have a static list of all
  * DistortedObjects currently created by the application so that we can implement the 'mark for
  * deletion now - actually delete on next render' thing.
  * We need to be able to quickly retrieve an Object by its ID, thus a HashMap.
@@ -70,8 +70,8 @@ public class DistortedObject
 
   private boolean matrixCloned, vertexCloned, fragmentCloned;
   private long mID;
-  private int mSizeX, mSizeY, mSizeZ; // in screen space
-  private float mHalfX, mHalfY, mHalfZ; // halfs of the above
+  private int mSizeX, mSizeY, mSizeZ;   // in screen space
+  private float mHalfX, mHalfY, mHalfZ; // halves of the above
 
   private Bitmap[] mBmp= null; //
   int[] mTextureDataH;         // have to be shared among all the cloned Objects
@@ -84,7 +84,7 @@ public class DistortedObject
 // upper-left corner. Everywhere else the origin is in the lower-left corner. Thus we have to flip.
 // The alternative solution, namely inverting the y-coordinate of the TexCoord does not really work-
 // i.e. it works only in case of rendering directly to the screen, but if we render to an FBO and
-// then take the FBO and render to screen, (DistortedNode does so!) things get inverted as textures
+// then take the FBO and render to screen, (DistortedObjectTree does so!) things get inverted as textures
 // created from FBO have their origins in the lower-left... Mindfuck!
 
   private static Bitmap flipBitmap(Bitmap src)
@@ -184,7 +184,7 @@ public class DistortedObject
   
 ///////////////////////////////////////////////////////////////////////////////////////////////////
    
-  void drawPriv(long currTime, DistortedObjectGrid grid, DistortedFramebuffer df)
+  void drawPriv(long currTime, GridObject grid, DistortedFramebuffer df)
     {
     DistortedFramebuffer.deleteAllMarked();
 
@@ -204,7 +204,7 @@ public class DistortedObject
 
 ///////////////////////////////////////////////////////////////////////////////////////////////////
    
-  void drawNoEffectsPriv(DistortedObjectGrid grid, DistortedFramebuffer df)
+  void drawNoEffectsPriv(GridObject grid, DistortedFramebuffer df)
     {
     GLES20.glViewport(0, 0, df.mWidth, df.mHeight);
 
@@ -324,7 +324,7 @@ public class DistortedObject
  *        This gets passed on to Dynamics inside the Effects that are currently applied to the
  *        Object.
  */
-  public void draw(long currTime, DistortedObjectGrid grid)
+  public void draw(long currTime, GridObject grid)
     {
     GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
     GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureDataH[0]);
@@ -338,7 +338,7 @@ public class DistortedObject
  * @param currTime Current time, in milliseconds.
  * @param df       Framebuffer to render this to.
  */
-  public void draw(long currTime, DistortedObjectGrid grid, DistortedFramebuffer df)
+  public void draw(long currTime, GridObject grid, DistortedFramebuffer df)
     {
     df.setAsOutput();
     GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureDataH[0]);
diff --git a/src/main/java/org/distorted/library/DistortedObjectGrid.java b/src/main/java/org/distorted/library/DistortedObjectGrid.java
deleted file mode 100644
index 62edd03..0000000
--- a/src/main/java/org/distorted/library/DistortedObjectGrid.java
+++ /dev/null
@@ -1,51 +0,0 @@
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// Copyright 2016 Leszek Koltunski                                                               //
-//                                                                                               //
-// This file is part of Distorted.                                                               //
-//                                                                                               //
-// Distorted is free software: you can redistribute it and/or modify                             //
-// it under the terms of the GNU General Public License as published by                          //
-// the Free Software Foundation, either version 2 of the License, or                             //
-// (at your option) any later version.                                                           //
-//                                                                                               //
-// Distorted is distributed in the hope that it will be useful,                                  //
-// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
-// GNU General Public License for more details.                                                  //
-//                                                                                               //
-// You should have received a copy of the GNU General Public License                             //
-// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-package org.distorted.library;
-
-import java.nio.FloatBuffer;
-
-import android.opengl.GLES20;
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-public abstract class DistortedObjectGrid
-   {
-   protected static final int BYTES_PER_FLOAT   = 4; //
-   protected static final int POSITION_DATA_SIZE= 3; // Size of the position data in elements
-   protected static final int NORMAL_DATA_SIZE  = 3; // Size of the normal data in elements.
-   protected static final int TEX_DATA_SIZE     = 2; // Size of the texture coordinate data in elements. 
-
-   protected int dataLength;                       
-      
-   protected FloatBuffer mGridPositions,mGridNormals,mGridTexture;
- 
-///////////////////////////////////////////////////////////////////////////////////////////////////
-   
-   void draw()
-     { 
-     GLES20.glVertexAttribPointer(Distorted.mPositionH    , POSITION_DATA_SIZE, GLES20.GL_FLOAT, false, 0, mGridPositions);          
-     GLES20.glVertexAttribPointer(Distorted.mNormalH      , NORMAL_DATA_SIZE  , GLES20.GL_FLOAT, false, 0, mGridNormals  );
-     GLES20.glVertexAttribPointer(Distorted.mTextureCoordH, TEX_DATA_SIZE     , GLES20.GL_FLOAT, false, 0, mGridTexture  );  
-
-     GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, dataLength); 
-     }
-   }
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
diff --git a/src/main/java/org/distorted/library/DistortedObjectTree.java b/src/main/java/org/distorted/library/DistortedObjectTree.java
new file mode 100644
index 0000000..83af6e7
--- /dev/null
+++ b/src/main/java/org/distorted/library/DistortedObjectTree.java
@@ -0,0 +1,494 @@
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Copyright 2016 Leszek Koltunski                                                               //
+//                                                                                               //
+// This file is part of Distorted.                                                               //
+//                                                                                               //
+// Distorted is free software: you can redistribute it and/or modify                             //
+// it under the terms of the GNU General Public License as published by                          //
+// the Free Software Foundation, either version 2 of the License, or                             //
+// (at your option) any later version.                                                           //
+//                                                                                               //
+// Distorted is distributed in the hope that it will be useful,                                  //
+// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
+// GNU General Public License for more details.                                                  //
+//                                                                                               //
+// You should have received a copy of the GNU General Public License                             //
+// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+package org.distorted.library;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+
+import android.opengl.GLES20;
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/**
+ * Class which represents a Node in a Tree of DistortedObjects.
+ *  
+ * Having organized a set of DistortedObjects into a Tree, we can then render any Node to any Framebuffer.
+ * That recursively renders the Object held in the Node and all its children, along with whatever effects
+ * each one of them has. 
+ */
+public class DistortedObjectTree
+  {
+  private static HashMap<ArrayList<Long>,NodeData> mMapNodeID = new HashMap<>();
+  private static long mNextNodeID =0;
+
+  private GridObject mGrid;
+  private DistortedObject mObject;
+  private NodeData mData;
+
+  private DistortedObjectTree mParent;
+  private ArrayList<DistortedObjectTree> mChildren;
+  private int[] mNumChildren;  // ==mChildren.length(), but we only create mChildren if the first one gets added
+
+  private class NodeData
+    {
+    long ID;
+    int numPointingNodes;
+    DistortedFramebuffer mDF;
+    boolean mRendered;
+
+    NodeData(long id)
+      {
+      ID              = id;
+      numPointingNodes= 1;
+      mDF             = null;
+      mRendered       = false;
+      }
+    }
+ 
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+  static void release()
+    {
+    mNextNodeID = 0;
+    mMapNodeID.clear();
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+  private void markRecursive()
+    {
+    mData.mRendered = false;
+   
+    synchronized(this)
+      {
+      for(int i=0; i<mNumChildren[0]; i++) mChildren.get(i).markRecursive();
+      }
+    }
+  
+///////////////////////////////////////////////////////////////////////////////////////////////////
+  
+  private void drawRecursive(long currTime, DistortedFramebuffer df)
+    {
+    if( mNumChildren[0]<=0 )
+      {
+      GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mObject.mTextureDataH[0]);
+      }
+    else
+      {
+      if( !mData.mRendered )
+        {
+        mData.mRendered = true;
+        mData.mDF.setAsOutput();
+
+        GLES20.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
+        GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
+      
+        if( mObject.mBitmapSet[0] )
+          {
+          GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mObject.mTextureDataH[0]);
+          mObject.drawNoEffectsPriv(mGrid, mData.mDF);
+          }
+      
+        synchronized(this)
+          {
+          for(int i=0; i<mNumChildren[0]; i++)
+            {
+            mChildren.get(i).drawRecursive(currTime, mData.mDF);
+            }
+          }
+        }
+
+      df.setAsOutput();
+      mData.mDF.setAsInput();
+      }
+    
+    mObject.drawPriv(currTime, mGrid, df);
+    }
+  
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// tree isomorphism
+  
+  private void RecomputeNodeID(ArrayList<Long> prev)
+    {
+    ArrayList<Long> curr = generateIDList();
+     
+    if( mParent==null )
+      {
+      adjustNodeData(prev,curr);
+      }
+    else
+      {
+      ArrayList<Long> parentPrev = mParent.generateIDList();
+      adjustNodeData(prev,curr);
+      mParent.RecomputeNodeID(parentPrev);
+      }
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+  private ArrayList<Long> generateIDList()
+    {
+    ArrayList<Long> ret = new ArrayList<>();
+     
+    ret.add( mNumChildren[0]>0 ? mObject.getBitmapID() : mObject.getID() );
+    DistortedObjectTree node;
+   
+    for(int i=0; i<mNumChildren[0]; i++)
+      {
+      node = mChildren.get(i);
+      ret.add(node.mData.ID);
+      }
+   
+    return ret;
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+  private void adjustNodeData(ArrayList<Long> oldList, ArrayList<Long> newList)
+    {
+    boolean otherNodesPoint = (mData.numPointingNodes>1);
+
+    if( otherNodesPoint ) mData.numPointingNodes--;
+    else                  mMapNodeID.remove(oldList);
+   
+    NodeData newData = mMapNodeID.get(newList);
+    
+    if( newData==null )
+      {
+      if( otherNodesPoint )  mData = new NodeData(++mNextNodeID);
+      else                   mData.ID = ++mNextNodeID;  // numPointingNodes must be 1 already
+
+      if( newList.size()>1 )
+        {
+        if( mData.mDF==null )
+          mData.mDF = new DistortedFramebuffer(mObject.getWidth(), mObject.getHeight());
+        }
+      else
+        {
+        if( mData.mDF!=null )
+          {
+          mData.mDF.markForDeletion();
+          mData.mDF = null;
+          }
+        else
+          {
+          android.util.Log.e("DistortedObjectTree", "adjustNodeData: impossible situation??");
+          }
+        }
+
+      mMapNodeID.put(newList, mData);
+      }
+    else
+      {
+      newData.numPointingNodes++;
+      mData = newData;
+      }
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////  
+// this will be called on startup and every time OpenGL context has been lost
+// also call this from the constructor if the OpenGL context has been created already.
+    
+  static void reset()
+    {
+    NodeData tmp;   
+     
+    for(ArrayList<Long> key: mMapNodeID.keySet())
+      {
+      tmp = mMapNodeID.get(key);
+          
+      if( tmp.mDF != null )
+        {
+    	  tmp.mDF.reset();
+        tmp.mRendered  = false;
+        }
+      }
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Debug - print all the Node IDs
+/*
+  void debug(int depth)
+    {
+    String tmp="";
+    int i;
+
+    for(i=0; i<depth; i++) tmp +="   ";
+    tmp += (""+mData.ID);
+
+    android.util.Log.e("node", tmp);
+
+    for(i=0; i<mNumChildren[0]; i++)
+      mChildren.get(i).debug(depth+1);
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Debug - print contents of the HashMap
+
+  static void debugMap()
+    {
+    NodeData tmp;
+
+    for(ArrayList<Long> key: mMapNodeID.keySet())
+      {
+      tmp = mMapNodeID.get(key);
+
+      android.util.Log.e("NODE", "key="+key+" NodeID: "+tmp.ID);
+      }
+    }
+*/
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// PUBLIC API
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/**
+ * Constructs new Node of the Tree.
+ *     
+ * @param obj DistortedObject to put into the new Node.
+ */
+  public DistortedObjectTree(DistortedObject obj, GridObject grid)
+    {
+    mObject = obj;
+    mGrid   = grid;
+    mParent = null;
+    mChildren = null;
+    mNumChildren = new int[1];
+    mNumChildren[0] = 0;
+   
+    ArrayList<Long> list = new ArrayList<>();
+    list.add(obj.getID());
+      
+    mData = mMapNodeID.get(list);
+   
+    if( mData!=null )
+      {
+      mData.numPointingNodes++;
+      }
+    else
+      {
+      mData = new NodeData(++mNextNodeID);   
+      mMapNodeID.put(list, mData);  
+      }
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////  
+/**
+ * Copy-constructs new Node of the Tree from another Node.
+ *     
+ * @param node The DistortedObjectTree to copy data from.
+ * @param flags bit field composed of a subset of the following:
+ *        {@link Distorted#CLONE_BITMAP},  {@link Distorted#CLONE_MATRIX}, {@link Distorted#CLONE_VERTEX},
+ *        {@link Distorted#CLONE_FRAGMENT} and {@link Distorted#CLONE_CHILDREN}.
+ *        For example flags = CLONE_BITMAP | CLONE_CHILDREN.
+ */
+  public DistortedObjectTree(DistortedObjectTree node, int flags)
+    {
+    mParent = null;
+    mObject = new DistortedObject(node.mObject,flags);
+    mGrid   = node.mGrid;
+
+    if( (flags & Distorted.CLONE_CHILDREN) != 0 )
+      {
+      mChildren = node.mChildren;
+      mNumChildren = node.mNumChildren;
+      }
+    else
+      {
+      mChildren = null;
+      mNumChildren = new int[1];
+      mNumChildren[0] = 0;
+      }
+   
+    ArrayList<Long> list = generateIDList();
+   
+    mData = mMapNodeID.get(list);
+   
+    if( mData!=null )
+      {
+      mData.numPointingNodes++;
+      }
+    else
+      {
+      mData = new NodeData(++mNextNodeID);   
+      mMapNodeID.put(list, mData);
+      }
+    }
+  
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/**
+ * Adds a new child to the last position in the list of our Node's children.
+ * 
+ * @param node The new Node to add.
+ */
+  public synchronized void attach(DistortedObjectTree node)
+    {
+    ArrayList<Long> prev = generateIDList(); 
+   
+    if( mChildren==null ) mChildren = new ArrayList<>(2);
+     
+    node.mParent = this;
+    mChildren.add(node);
+    mNumChildren[0]++;
+     
+    RecomputeNodeID(prev);
+    }
+   
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/**
+ * Adds a new child to the last position in the list of our Node's children.
+ * 
+ * @param obj DistortedObject to initialize our child Node with.
+ * @return the newly constructed child Node, or null if we couldn't allocate resources.
+ */
+  public synchronized DistortedObjectTree attach(DistortedObject obj, GridObject grid)
+    {
+    ArrayList<Long> prev = generateIDList(); 
+      
+    if( mChildren==null ) mChildren = new ArrayList<>(2);
+    DistortedObjectTree node = new DistortedObjectTree(obj,grid);
+    node.mParent = this;
+    mChildren.add(node);
+    mNumChildren[0]++;
+   
+    RecomputeNodeID(prev);
+
+    return node;
+    }
+  
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/**
+ * Removes the first occurrence of a specified child from the list of children of our Node.
+ * 
+ * @param node The Node to remove.
+ * @return <code>true</code> if the child was successfully removed.
+ */
+  public synchronized boolean detach(DistortedObjectTree node)
+    {
+    if( mNumChildren[0]>0 )
+      {
+      ArrayList<Long> prev = generateIDList();  
+         
+      if( mChildren.remove(node) )
+        {
+        node.mParent = null;  
+        mNumChildren[0]--;
+     
+        RecomputeNodeID(prev);
+     
+        return true;
+        }
+      }
+   
+    return false;
+    }
+  
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/**
+ * Removes the first occurrence of a specified child from the list of children of our Node.
+ * 
+ * @param obj DistortedObject to remove.
+ * @return <code>true</code> if the child was successfully removed.
+ */
+  public synchronized boolean detach(DistortedObject obj)
+    {
+    long id = obj.getID();
+    DistortedObjectTree node;
+   
+    for(int i=0; i<mNumChildren[0]; i++)
+      {
+      node = mChildren.get(i);
+     
+      if( node.mObject.getID()==id )
+        {
+        ArrayList<Long> prev = generateIDList();   
+     
+        node.mParent = null;  
+        mChildren.remove(i);
+        mNumChildren[0]--;
+      
+        RecomputeNodeID(prev);
+      
+        return true;
+        }
+      }
+   
+    return false;
+    }
+    
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/**
+ * Removes all children Nodes.
+ */
+  public synchronized void detachAll()
+    {
+    for(int i=0; i<mNumChildren[0]; i++)
+      {
+      mChildren.get(i).mParent = null;
+      }
+   
+    if( mNumChildren[0]>0 )
+      {
+      ArrayList<Long> prev = generateIDList();  
+      
+      mNumChildren[0] = 0;
+      mChildren.clear();
+      RecomputeNodeID(prev);
+      }
+    }
+  
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/**
+ * Draws the Node, and all its children, to the default framebuffer 0 (i.e. the screen).
+ *   
+ * @param currTime Current time, in milliseconds.
+ */
+  public void draw(long currTime)
+    {  
+    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
+    markRecursive();
+    drawRecursive(currTime,Distorted.mFramebuffer);
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/**
+ * Draws the Node, and all its children, to the Framebuffer passed.
+ *
+ * @param currTime Current time, in milliseconds.
+ * @param df       Framebuffer to render this to.
+ */
+  public void draw(long currTime, DistortedFramebuffer df)
+    {
+    df.setAsOutput();
+    markRecursive();
+    drawRecursive(currTime,df);
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/**
+ * Returns the DistortedObject object that's in the Node.
+ * 
+ * @return The DistortedObject contained in the Node.
+ */
+  public DistortedObject getObject()
+    {
+    return mObject;
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+  }
+
diff --git a/src/main/java/org/distorted/library/GridCubes.java b/src/main/java/org/distorted/library/GridCubes.java
new file mode 100644
index 0000000..e0ebd4c
--- /dev/null
+++ b/src/main/java/org/distorted/library/GridCubes.java
@@ -0,0 +1,788 @@
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Copyright 2016 Leszek Koltunski                                                               //
+//                                                                                               //
+// This file is part of Distorted.                                                               //
+//                                                                                               //
+// Distorted is free software: you can redistribute it and/or modify                             //
+// it under the terms of the GNU General Public License as published by                          //
+// the Free Software Foundation, either version 2 of the License, or                             //
+// (at your option) any later version.                                                           //
+//                                                                                               //
+// Distorted is distributed in the hope that it will be useful,                                  //
+// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
+// GNU General Public License for more details.                                                  //
+//                                                                                               //
+// You should have received a copy of the GNU General Public License                             //
+// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+package org.distorted.library;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.util.ArrayList;
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+public class GridCubes extends GridObject
+   {
+   private static final float R = 0.0f;//0.2f;
+   private static final float FRONTZ = 0.5f;
+   private static final float BACKZ  =-0.5f;
+   
+   private static final int NORTH = 0;
+   private static final int WEST  = 1;
+   private static final int EAST  = 2;
+   private static final int SOUTH = 3;
+
+   private static final boolean BACK  = true;
+   private static final boolean FRONT = false;
+   private static final boolean UPPER = false;
+   private static final boolean LOWER = true;
+   
+   private static final float[] mNormalX = new float[4];
+   private static final float[] mNormalY = new float[4];
+   private static final float[] mNormalZ = new float[4];
+
+   private class Edge
+     {
+     final int side; 
+     final int row;
+     final int col;
+     
+     Edge(int s, int r, int c)
+       {
+       side= s; 
+       row = r;
+       col = c;
+       }
+     }
+   
+   private int mCols, mRows;
+   private short[][] mCubes;
+   private ArrayList<Edge> mEdges = new ArrayList<>();
+
+   private int remainingVert;
+   private int mSideBends;
+   private int mEdgeNum;
+   private int mSideWalls;
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// a Block is split into two triangles along the NE-SW line iff it is in the top-right
+// or bottom-left quadrant of the grid.
+
+   private boolean isNE(int row,int col)
+     {
+     return ( (2*row<mRows)^(2*col<mCols) );
+     }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// return the number of vertices our grid will contain
+
+   private int computeDataLength(boolean frontOnly)
+      {
+      int frontWalls=0, frontSegments=0, triangleShifts=0, windingShifts=0;
+      int shiftCol = (mCols-1)/2;
+
+      boolean lastBlockIsNE=false;
+      boolean thisBlockIsNE;        // the block we are currently looking at is split into
+                                    // two triangles along the NE-SW line (rather than NW-SE)
+      for(int row=0; row<mRows; row++)
+        {
+        if( mCols>=2 && (mCubes[row][shiftCol]%2 == 1) && (mCubes[row][shiftCol+1]%2 == 1) ) triangleShifts++;
+
+        for(int col=0; col<mCols; col++)
+          {
+          if( mCubes[row][col]%2 == 1 )  // land
+            {
+            thisBlockIsNE = isNE(row,col);
+            if( thisBlockIsNE^lastBlockIsNE ) windingShifts++;
+            lastBlockIsNE = thisBlockIsNE;
+            frontWalls++;
+            if( col==mCols-1 || mCubes[row][col+1]%2 == 0 ) frontSegments++;
+            }
+          }
+        }
+
+      int frontVert = 2*( frontWalls + 2*frontSegments - 1) +2*triangleShifts + windingShifts;
+      int sideVert  = 2*( mSideWalls + mSideBends + mEdgeNum -1);
+      int firstWinding= (!frontOnly && (frontVert+1)%2==1 ) ? 1:0;
+      int dataL = frontOnly ? frontVert : (frontVert+1) +firstWinding+ (1+sideVert+1) + (1+frontVert);
+/*
+      android.util.Log.e("CUBES","triangleShifts="+triangleShifts+" windingShifts="+windingShifts+" winding1="+firstWinding+" frontVert="+frontVert+" sideVert="+sideVert);
+      android.util.Log.e("CUBES", "frontW="+frontWalls+" fSegments="+frontSegments+" sWalls="+mSideWalls+" sSegments="+mEdgeNum+" sideBends="+mSideBends+" dataLen="+dataL );
+*/
+      return dataL<0 ? 0:dataL;
+      }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/*
+   private static String debug(short[] val)
+     {
+     String ret="";j
+     
+     for(int i=0; i<val.length; i++) ret+=(" "+val[i]); 
+     
+     return ret;
+     }
+*/
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/*
+   private static String debug(float[] val, int stop)
+     {
+     String ret="";
+
+     for(int i=0; i<val.length; i++) 
+        {
+        if( i%stop==0 ) ret+="\n";
+        ret+=(" "+val[i]);
+        }
+
+     return ret;
+     }
+*/  
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/*
+   private static String debug(Edge e)
+     {
+     String d = "";
+     
+     switch(e.side)
+       {
+       case NORTH: d+="NORTH "; break;
+       case SOUTH: d+="SOUTH "; break;
+       case WEST : d+="WEST  "; break;
+       case EAST : d+="EAST  "; break;
+       }
+     
+     d+=("("+e.row+","+e.col+")");
+     
+     return d;
+     }   
+*/
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// desc is guaranteed to be padded with 0s in the end (DistortedCubes constructor does it)
+
+   private void prepareDataStructures(int cols, String desc, boolean frontOnly)
+     {
+     mRows     =0;
+     mCols     =0;
+     dataLength=0;
+     
+     if( cols>0 && desc.contains("1") )
+       {
+       mCols = cols;
+       mRows = desc.length()/cols;
+
+       mCubes = new short[mRows][mCols];
+       
+       for(int j=0; j<mCols; j++)
+         for(int i=0; i<mRows; i++)
+           mCubes[i][j] = (short)(desc.charAt(i*mCols+j) == '1' ? 1:0);
+       
+       markRegions();
+       dataLength = computeDataLength(frontOnly);
+
+       remainingVert = dataLength;
+       }
+     }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// full grid
+
+   private void prepareDataStructures(int cols, int rows, boolean frontOnly)
+     {
+     mRows     =rows;
+     mCols     =cols;
+     dataLength=   0;
+
+     if( cols>0 && rows>0 )
+       {
+       mCubes = new short[mRows][mCols];
+
+       for(int j=0; j<mCols; j++)
+         for(int i=0; i<mRows; i++)
+           mCubes[i][j] = (short)1;
+
+       markRegions();
+       dataLength = computeDataLength(frontOnly);
+
+       remainingVert = dataLength;
+       }
+     }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Mark all the 'regions' of our grid  - i.e. separate pieces of 'land' (connected blocks that will 
+// be rendered) and 'water' (connected holes in between) with integers. Each connected block of land
+// gets a unique odd integer, each connected block of water a unique even integer.
+//
+// Water on the edges of the grid is also considered connected to itself!   
+//   
+// This function also creates a list of 'Edges'. Each Edge is a data structure from which later on we
+// will start building the side walls of each connected block of land (and sides of holes of water
+// inside). Each Edge needs to point from Land to Water (thus the '(SOUTH,i-1,j)' below) - otherwise
+// later on setting up normal vectors wouldn't work.
+   
+   private void markRegions()
+     {
+     int i, j, numWater=1, numLand=0;
+     
+     for(i=0; i<mRows;i++) if( mCubes[      i][      0]==0 ) markRegion((short)2,      i,       0);
+     for(i=0; i<mRows;i++) if( mCubes[      i][mCols-1]==0 ) markRegion((short)2,      i, mCols-1);
+     for(i=0; i<mCols;i++) if( mCubes[0      ][      i]==0 ) markRegion((short)2,      0,       i);
+     for(i=0; i<mCols;i++) if( mCubes[mRows-1][      i]==0 ) markRegion((short)2,mRows-1,       i);
+           
+     for(i=0; i<mRows; i++)
+        for(j=0; j<mCols; j++)
+           {
+           if( mCubes[i][j] == 0 ) { numWater++; markRegion( (short)(2*numWater ),i,j); mEdges.add(new Edge(SOUTH,i-1,j)); }
+           if( mCubes[i][j] == 1 ) { numLand ++; markRegion( (short)(2*numLand+1),i,j); mEdges.add(new Edge(NORTH,i  ,j)); }
+           }
+     
+     // now we potentially need to kick out some Edges . Otherwise the following does not work:
+     //
+     // 0 1 0
+     // 1 0 1
+     // 0 1 0
+     
+     mEdgeNum= mEdges.size();
+     int initCol, initRow, initSide, lastSide;
+     Edge e1,e2;
+     
+     for(i=0; i<mEdgeNum; i++)
+       {
+       e1 = mEdges.get(i);
+       initRow= e1.row;
+       initCol= e1.col;
+       initSide=e1.side;
+
+       do
+         {
+         //android.util.Log.d("CUBES", "checking edge "+debug(e1));
+
+         mSideWalls++;
+
+         if( e1.side==NORTH || e1.side==SOUTH )
+           {
+           for(j=i+1;j<mEdgeNum;j++)
+             {
+             e2 = mEdges.get(j);
+
+             if( e2.side==e1.side && e2.row==e1.row && e2.col==e1.col )
+               {
+               mEdges.remove(j);
+               mEdgeNum--;
+               j--;
+
+               //android.util.Log.e("CUBES", "removing edge "+debug(e2));
+               }
+             }
+           }
+
+         lastSide = e1.side;
+         e1 = getNextEdge(e1);
+         if( e1.side!=lastSide ) mSideBends++;
+         }
+       while( e1.col!=initCol || e1.row!=initRow || e1.side!=initSide );
+       }
+     }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// when calling, make sure that newVal != val
+   
+   private void markRegion(short newVal, int row, int col)
+     {
+     short val = mCubes[row][col];
+     mCubes[row][col] = newVal;
+     
+     if( row>0       && mCubes[row-1][col  ]==val ) markRegion(newVal, row-1, col  );
+     if( row<mRows-1 && mCubes[row+1][col  ]==val ) markRegion(newVal, row+1, col  );
+     if( col>0       && mCubes[row  ][col-1]==val ) markRegion(newVal, row  , col-1);
+     if( col<mCols-1 && mCubes[row  ][col+1]==val ) markRegion(newVal, row  , col+1);
+     }
+   
+///////////////////////////////////////////////////////////////////////////////////////////////////
+   
+   private void createNormals(boolean front, int row, int col)
+     {
+     int td,lr; 
+      
+     int nw = (col>0       && row>0      ) ? (mCubes[row-1][col-1]%2) : 0;
+     int w  = (col>0                     ) ? (mCubes[row  ][col-1]%2) : 0;
+     int n  = (               row>0      ) ? (mCubes[row-1][col  ]%2) : 0;
+     int c  =                                (mCubes[row  ][col  ]%2);
+     int sw = (col>0       && row<mRows-1) ? (mCubes[row+1][col-1]%2) : 0;
+     int s  = (               row<mRows-1) ? (mCubes[row+1][col  ]%2) : 0;
+     int ne = (col<mCols-1 && row>0      ) ? (mCubes[row-1][col+1]%2) : 0;
+     int e  = (col<mCols-1               ) ? (mCubes[row  ][col+1]%2) : 0;
+     int se = (col<mCols-1 && row<mRows-1) ? (mCubes[row+1][col+1]%2) : 0;
+
+     if(front)
+       {
+       mNormalZ[0] = 1.0f;
+       mNormalZ[1] = 1.0f;
+       mNormalZ[2] = 1.0f;
+       mNormalZ[3] = 1.0f;
+       }
+     else
+       {
+       mNormalZ[0] =-1.0f;
+       mNormalZ[1] =-1.0f;
+       mNormalZ[2] =-1.0f;
+       mNormalZ[3] =-1.0f;
+       }
+
+     td = nw+n-w-c;
+     lr = c+n-w-nw;
+     if( td<0 ) td=-1;
+     if( td>0 ) td= 1;
+     if( lr<0 ) lr=-1;
+     if( lr>0 ) lr= 1;
+     mNormalX[0] = lr*R;
+     mNormalY[0] = td*R;
+     
+     td = w+c-sw-s;
+     lr = c+s-w-sw;
+     if( td<0 ) td=-1;
+     if( td>0 ) td= 1;
+     if( lr<0 ) lr=-1;
+     if( lr>0 ) lr= 1;
+     mNormalX[1] = lr*R;
+     mNormalY[1] = td*R;
+     
+     td = n+ne-c-e;
+     lr = e+ne-c-n;
+     if( td<0 ) td=-1;
+     if( td>0 ) td= 1;
+     if( lr<0 ) lr=-1;
+     if( lr>0 ) lr= 1;
+     mNormalX[2] = lr*R;
+     mNormalY[2] = td*R;
+     
+     td = c+e-s-se;
+     lr = e+se-c-s;
+     if( td<0 ) td=-1;
+     if( td>0 ) td= 1;
+     if( lr<0 ) lr=-1;
+     if( lr>0 ) lr= 1;
+     mNormalX[3] = lr*R;
+     mNormalY[3] = td*R;
+     /*
+     android.util.Log.d("CUBES", "row="+row+" col="+col);
+     android.util.Log.d("CUBES", mNormalX[0]+" "+mNormalY[0]);
+     android.util.Log.d("CUBES", mNormalX[1]+" "+mNormalY[1]);
+     android.util.Log.d("CUBES", mNormalX[2]+" "+mNormalY[2]);
+     android.util.Log.d("CUBES", mNormalX[3]+" "+mNormalY[3]);
+     */
+     }
+   
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+   private int addFrontVertex(int vertex, int index, float vectZ, int col, int row, float[] position, float[] normal, float[] texture)
+     {
+     remainingVert--;
+
+     float x = (float)col/mCols;
+     float y = (float)row/mRows;
+
+     position[3*vertex  ] = x-0.5f;
+     position[3*vertex+1] = 0.5f-y;
+     position[3*vertex+2] = vectZ;
+     normal[3*vertex  ]   = mNormalX[index];
+     normal[3*vertex+1]   = mNormalY[index];
+     normal[3*vertex+2]   = mNormalZ[index];
+     texture[2*vertex  ]  = x;
+     texture[2*vertex+1]  = 1.0f-y;
+
+     return vertex+1;
+     }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+   private int buildFrontBackGrid(boolean front, int vertex, float[] position, float[] normal, float[] texture)
+     {
+     short last, current;
+     boolean seenLand=false;
+     boolean lastBlockIsNE = false;
+     boolean currentBlockIsNE;
+     float vectZ = front?FRONTZ:BACKZ;
+
+     //android.util.Log.d("CUBES", "buildFrontBack");
+
+     for(int row=0; row<mRows; row++)
+       {
+       last =0;
+         
+       for(int col=0; col<mCols; col++)
+         {
+         current = mCubes[row][col];
+
+         if( current%2 == 1 )
+           {
+           currentBlockIsNE = isNE(row,col);
+
+           if( !seenLand && !front && ((vertex%2==1)^currentBlockIsNE) )
+             {
+             //android.util.Log.d("CUBES","repeating winding2 vertex");
+
+             vertex = repeatLast(vertex,position,normal,texture);
+             }
+
+           createNormals(front,row,col);
+
+           if( currentBlockIsNE )
+             {
+             if( (last!=current) || !lastBlockIsNE )
+               {
+               if( seenLand  && (last != current) ) vertex = repeatLast(vertex,position,normal,texture);
+               vertex= addFrontVertex( vertex, 0, vectZ, col, row, position, normal, texture);
+               if( seenLand  && (last != current) ) vertex = repeatLast(vertex,position,normal,texture);
+               if( !lastBlockIsNE || (!front && !seenLand) ) vertex = repeatLast(vertex,position,normal,texture);
+               vertex= addFrontVertex( vertex, 1, vectZ, col, row+1, position, normal, texture);
+               }
+             vertex= addFrontVertex( vertex, 2, vectZ, col+1, row, position, normal, texture);
+             vertex= addFrontVertex( vertex, 3, vectZ, col+1, row+1, position, normal, texture);
+             }
+           else
+             {
+             if( (last!=current) || lastBlockIsNE )
+               {
+               if( seenLand  && (last != current) ) vertex = repeatLast(vertex,position,normal,texture);
+               vertex= addFrontVertex( vertex, 1, vectZ, col, row+1, position, normal, texture);
+               if( seenLand  && (last != current) ) vertex = repeatLast(vertex,position,normal,texture);
+               if( lastBlockIsNE || (!front && !seenLand) ) vertex = repeatLast(vertex,position,normal,texture);
+               vertex= addFrontVertex( vertex, 0, vectZ, col, row, position, normal, texture);
+               }
+             vertex= addFrontVertex( vertex, 3, vectZ, col+1, row+1, position, normal, texture);
+             vertex= addFrontVertex( vertex, 2, vectZ, col+1, row  , position, normal, texture);
+             }
+
+           seenLand = true;
+           lastBlockIsNE = currentBlockIsNE;
+           }
+            
+         last = current;
+         }
+       }
+     
+     return vertex;
+     }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+   private int repeatLast(int vertex, float[] position, float[] normal, float[] texture)
+     {
+     //android.util.Log.e("CUBES", "repeating last vertex!");
+
+     if( vertex>0 )
+       {
+       remainingVert--;
+
+       position[3*vertex  ] = position[3*vertex-3];
+       position[3*vertex+1] = position[3*vertex-2];
+       position[3*vertex+2] = position[3*vertex-1];
+
+       normal[3*vertex  ]   = normal[3*vertex-3];
+       normal[3*vertex+1]   = normal[3*vertex-2];
+       normal[3*vertex+2]   = normal[3*vertex-1];
+
+       texture[2*vertex  ]  = texture[2*vertex-2];
+       texture[2*vertex+1]  = texture[2*vertex-1];
+         
+       vertex++;     
+       }
+     
+     return vertex;
+     }
+   
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+   private int buildSideGrid(int vertex, float[] position, float[] normal, float[] texture)
+     {
+     //android.util.Log.d("CUBES", "buildSide");
+
+     for(int i=0; i<mEdgeNum; i++)
+       {
+       vertex = buildIthSide(mEdges.get(i), vertex, position, normal, texture);  
+       } 
+      
+     return vertex;
+     }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+   private int buildIthSide(Edge curr, int vertex, float[] position, float[] normal, float[] texture)
+     {
+     Edge prev; 
+     
+     if( curr.side==NORTH ) // water outside
+       {
+       prev = new Edge(WEST,curr.row,curr.col);
+       }
+     else                   // land outside; we need to move forward one link because we are going in opposite direction and we need to start from a bend.
+       {
+       prev = curr;
+       curr = new Edge(EAST,curr.row+1,curr.col-1);
+       }
+     
+     int col = curr.col;
+     int row = curr.row;
+     int side= curr.side;  
+     Edge next = getNextEdge(curr);
+     
+     addSideVertex(curr,BACK,LOWER,prev.side,vertex,position,normal,texture);
+     vertex++;
+     
+     do
+       {
+       if( prev.side!=curr.side )
+         {
+         addSideVertex(curr,BACK,LOWER,prev.side,vertex,position,normal,texture);
+         vertex++;
+         addSideVertex(curr,BACK,UPPER,prev.side,vertex,position,normal,texture);
+         vertex++;
+         }
+       
+       addSideVertex(curr,FRONT,LOWER,next.side,vertex,position,normal,texture);
+       vertex++;
+       addSideVertex(curr,FRONT,UPPER,next.side,vertex,position,normal,texture);
+       vertex++;
+       
+       prev = curr;
+       curr = next; 
+       next = getNextEdge(curr);
+       }
+     while( curr.col!=col || curr.row!=row || curr.side!=side );
+     
+     vertex = repeatLast(vertex,position,normal,texture);
+     
+     return vertex;
+     }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+   private Edge getNextEdge(Edge curr)
+     {
+     int col = curr.col;
+     int row = curr.row;
+      
+     //android.util.Log.e("CUBES", "row="+row+" col="+col+" mRows="+mRows+" mCols="+mCols);
+                       
+     switch(curr.side) 
+       {
+       case NORTH: if( col==mCols-1 ) 
+                     return new Edge(EAST,row,col);
+                   if( row>0 && mCubes[row-1][col+1]==mCubes[row][col] )
+                     return new Edge(WEST,row-1,col+1);
+                   if( mCubes[row][col+1]==mCubes[row][col] )
+                     return new Edge(NORTH,row,col+1);
+                   else  
+                     return new Edge(EAST,row,col);
+                   
+       case SOUTH: if( col==0 ) 
+                     return new Edge(WEST,row,col);
+                   if( (row<mRows-1) && mCubes[row+1][col-1]==mCubes[row][col] )
+                     return new Edge(EAST,row+1,col-1); 
+                   if( mCubes[row][col-1]==mCubes[row][col] )
+                     return new Edge(SOUTH,row,col-1);
+                   else
+                     return new Edge(WEST,row,col); 
+                     
+       case EAST : if( row==mRows-1 ) 
+                     return new Edge(SOUTH,row,col);
+                   if( (col<mCols-1) && mCubes[row+1][col+1]==mCubes[row][col] )
+                     return new Edge(NORTH,row+1,col+1);
+                   if( mCubes[row+1][col]==mCubes[row][col] )
+                     return new Edge(EAST,row+1,col);
+                   else 
+                     return new Edge(SOUTH,row,col);
+                   
+       default   : if( row==0 )
+                     return new Edge(NORTH,row,col);
+                   if( col>0 && mCubes[row-1][col-1]==mCubes[row][col] )
+                     return new Edge(SOUTH,row-1,col-1);
+                   if( mCubes[row-1][col]==mCubes[row][col] )
+                     return new Edge(WEST,row-1,col);
+                   else
+                     return new Edge(NORTH,row,col);     
+       }
+     }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+   
+   private void addSideVertex(Edge curr, boolean back, boolean lower,int side, int vertex, float[] position, float[] normal, float[] texture)
+     {
+     //android.util.Log.e("CUBES", "adding Side vertex!");
+
+     remainingVert--;
+
+     float x, y;
+
+     switch(curr.side)
+       {
+       case NORTH: x = (float)(back ? (curr.col  ):(curr.col+1))/mCols;
+
+                   position[3*vertex  ] = x - 0.5f;
+                   position[3*vertex+1] = 0.5f - (float)curr.row/mRows;
+                   position[3*vertex+2] = lower ? BACKZ : FRONTZ;
+
+                   normal[3*vertex  ]   = side==NORTH ? 0.0f : (side==WEST?-R:R);
+                   normal[3*vertex+1]   = 1.0f;
+                   normal[3*vertex+2]   = lower ? -R:R;
+
+                   texture[2*vertex  ]  = x;
+                   texture[2*vertex+1]  = 1.0f-(float)(lower? (curr.row-1):(curr.row  ))/mRows;
+                   break;
+       case SOUTH: x = (float)(back ? (curr.col+1):(curr.col  ))/mCols;
+
+                   position[3*vertex  ] = x - 0.5f;
+                   position[3*vertex+1] = 0.5f - (float)(curr.row+1)/mRows;
+                   position[3*vertex+2] = lower ? BACKZ : FRONTZ;  
+            
+                   normal[3*vertex  ]   = side==SOUTH ? 0.0f: (side==EAST?-R:R);
+                   normal[3*vertex+1]   =-1.0f;
+                   normal[3*vertex+2]   = lower ? -R:R;
+
+                   texture[2*vertex  ]  = x;
+                   texture[2*vertex+1]  = 1.0f-(float)(lower? (curr.row+2):(curr.row+1))/mRows;
+                   break;
+       case WEST : y = (float)(back  ? (curr.row+1):(curr.row))/mRows;
+
+                   position[3*vertex  ] = (float)curr.col/mCols -0.5f;
+                   position[3*vertex+1] = 0.5f - y;
+                   position[3*vertex+2] = lower ? BACKZ : FRONTZ;
+
+                   normal[3*vertex  ]   =-1.0f;
+                   normal[3*vertex+1]   = side==WEST ? 0.0f : (side==NORTH?-R:R);
+                   normal[3*vertex+2]   = lower ? -R:R;
+ 
+                   texture[2*vertex  ]  = (float)(lower ? (curr.col-1):(curr.col  ))/mCols;
+                   texture[2*vertex+1]  = 1.0f - y;
+                   break;
+       case EAST : y = (float)(back  ? (curr.row):(curr.row+1))/mRows;
+
+                   position[3*vertex  ] = (float)(curr.col+1)/mCols -0.5f;
+                   position[3*vertex+1] = 0.5f - y;
+                   position[3*vertex+2] = lower ? BACKZ : FRONTZ;
+
+                   normal[3*vertex  ]   = 1.0f;
+                   normal[3*vertex+1]   = side==EAST ? 0.0f : (side==SOUTH?-R:R);
+                   normal[3*vertex+2]   = lower ? -R:R; 
+
+                   texture[2*vertex  ]  = (float)(lower ? (curr.col+2):(curr.col+1))/mCols;
+                   texture[2*vertex+1]  = 1.0f - y;
+                   break;
+       }
+     
+     if(texture[2*vertex  ]>1.0f) texture[2*vertex  ] =2.0f-texture[2*vertex  ];
+     if(texture[2*vertex  ]<0.0f) texture[2*vertex  ] =    -texture[2*vertex  ];
+     if(texture[2*vertex+1]>1.0f) texture[2*vertex+1] =2.0f-texture[2*vertex+1];
+     if(texture[2*vertex+1]<0.0f) texture[2*vertex+1] =    -texture[2*vertex+1];
+     }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+   private void build(boolean frontOnly)
+     {
+     int numVertices=0;
+     float[] positionData= new float[POSITION_DATA_SIZE*dataLength];
+     float[] normalData  = new float[NORMAL_DATA_SIZE  *dataLength];
+     float[] textureData = new float[TEX_DATA_SIZE     *dataLength];
+
+     //android.util.Log.d("CUBES","building front grid...");
+
+     numVertices = buildFrontBackGrid(true, numVertices,positionData,normalData,textureData);
+
+     if( !frontOnly )
+       {
+       numVertices = repeatLast(numVertices,positionData,normalData,textureData);
+       if( numVertices%2==1 )
+         {
+         //android.util.Log.d("CUBES","repeating winding1 vertex");
+
+         numVertices = repeatLast(numVertices,positionData,normalData,textureData);
+         }
+
+       //android.util.Log.d("CUBES","building side grid...");
+
+       numVertices = buildSideGrid (numVertices,positionData,normalData,textureData);
+
+       //android.util.Log.d("CUBES","building back grid...");
+
+       numVertices = buildFrontBackGrid (false,numVertices,positionData,normalData,textureData);
+       }
+
+     /*
+     android.util.Log.e("CUBES","dataLen="+dataLength+" vertex="+numVertices);
+     android.util.Log.d("CUBES", "position: "+debug(positionData,3) );
+     android.util.Log.d("CUBES", "normal: "  +debug(  normalData,3) );
+     android.util.Log.d("CUBES", "texture: " +debug( textureData,2) );
+     */
+
+     mEdges.clear();
+     mEdges = null;
+     mCubes = null;
+
+     if( remainingVert!=0 )
+       android.util.Log.d("CUBES", "remainingVert " +remainingVert );
+
+     mGridPositions = ByteBuffer.allocateDirect(POSITION_DATA_SIZE*dataLength*BYTES_PER_FLOAT).order(ByteOrder.nativeOrder()).asFloatBuffer();
+     mGridPositions.put(positionData).position(0);
+
+     mGridNormals = ByteBuffer.allocateDirect(NORMAL_DATA_SIZE*dataLength*BYTES_PER_FLOAT).order(ByteOrder.nativeOrder()).asFloatBuffer();
+     mGridNormals.put(normalData).position(0);
+
+     mGridTexture = ByteBuffer.allocateDirect(TEX_DATA_SIZE*dataLength*BYTES_PER_FLOAT).order(ByteOrder.nativeOrder()).asFloatBuffer();
+     mGridTexture.put(textureData).position(0);
+     }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// PUBLIC API
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/**
+ * Creates the underlying grid of vertices, normals, texture coords and colors.
+ *    
+ * @param cols      Integer helping to parse the next parameter.
+ * @param desc      String describing the subset of a MxNx1 cuboid that we want to create.
+ *                  Its MxN characters - all 0 or 1 - decide of appropriate field is taken or not.
+ *                  <p></p>
+ *                  <p>
+ *                  <pre>
+ *                  For example, (cols=2, desc="111010") describes the following shape:
+ *
+ *                  XX
+ *                  X
+ *                  X
+ *
+ *                  whereas (cols=2,desc="110001") describes
+ *
+ *                  XX
+ *
+ *                   X
+ *                  </pre>
+ *                  </p>
+ * @param frontOnly Only create the front wall or side and back as well?
+ */
+   public GridCubes(int cols, String desc, boolean frontOnly)
+      {
+      prepareDataStructures(cols,desc,frontOnly);
+      build(frontOnly);
+      }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/**
+ * Creates a full, hole-less underlying grid of vertices, normals, texture coords and colors.
+ *
+ * @param cols      Number of columns.
+ * @param rows      Number of rows.
+ * @param frontOnly Only create the front wall or side and back as well?
+ */
+   public GridCubes(int cols, int rows, boolean frontOnly)
+      {
+      prepareDataStructures(cols,rows,frontOnly);
+      build(frontOnly);
+      }
+   }
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
diff --git a/src/main/java/org/distorted/library/GridFlat.java b/src/main/java/org/distorted/library/GridFlat.java
new file mode 100644
index 0000000..f46caf8
--- /dev/null
+++ b/src/main/java/org/distorted/library/GridFlat.java
@@ -0,0 +1,191 @@
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Copyright 2016 Leszek Koltunski                                                               //
+//                                                                                               //
+// This file is part of Distorted.                                                               //
+//                                                                                               //
+// Distorted is free software: you can redistribute it and/or modify                             //
+// it under the terms of the GNU General Public License as published by                          //
+// the Free Software Foundation, either version 2 of the License, or                             //
+// (at your option) any later version.                                                           //
+//                                                                                               //
+// Distorted is distributed in the hope that it will be useful,                                  //
+// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
+// GNU General Public License for more details.                                                  //
+//                                                                                               //
+// You should have received a copy of the GNU General Public License                             //
+// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+package org.distorted.library;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+public class GridFlat extends GridObject
+  {
+  private int mCols, mRows;
+  private int remainingVert;
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Create a flat, full grid. cols and rows is guaranteed (by DistortedBitmap constructor)
+// to be in 1,2,...,256.
+
+   private void computeNumberOfVertices(int cols, int rows)
+     {
+     mRows=rows;
+     mCols=cols;
+
+     if( cols==1 && rows==1 )
+       {
+       dataLength = 4;
+       }
+     else
+       {
+       dataLength = 2*( mRows*mCols +2*mRows - 1) +2*(mCols>=2 ? mRows:0) +
+                    (mCols>=2 && mRows>=2 ? 2*mRows-2 : 1);
+       }
+
+     //android.util.Log.e("BITMAP","vertices="+dataLength+" rows="+mRows+" cols="+mCols);
+
+     remainingVert = dataLength;
+     }
+
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+   private int addVertex(int vertex, int col, int row, float[] position, float[] normal, float[] texture)
+     {
+     remainingVert--;
+
+     float x= (float)col/mCols;
+     float y= (float)row/mRows;
+
+     position[3*vertex  ] = x-0.5f;
+     position[3*vertex+1] = 0.5f-y;
+     position[3*vertex+2] = 0;
+
+     texture[2*vertex  ]  = x;
+     texture[2*vertex+1]  = 1.0f-y;
+
+     normal[3*vertex  ]   = 0.0f;
+     normal[3*vertex+1]   = 0.0f;
+     normal[3*vertex+2]   = 1.0f;
+
+     return vertex+1;
+     }
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+   private int repeatLast(int vertex, float[] position, float[] normal, float[] texture)
+     {
+     remainingVert--;
+
+     //android.util.Log.e("BITMAP", "repeating last vertex!");
+
+     if( vertex>0 )
+       {
+       position[3*vertex  ] = position[3*vertex-3];
+       position[3*vertex+1] = position[3*vertex-2];
+       position[3*vertex+2] = position[3*vertex-1];
+
+       normal[3*vertex  ]   = normal[3*vertex-3];
+       normal[3*vertex+1]   = normal[3*vertex-2];
+       normal[3*vertex+2]   = normal[3*vertex-1];
+
+       texture[2*vertex  ]  = texture[2*vertex-2];
+       texture[2*vertex+1]  = texture[2*vertex-1];
+
+       vertex++;
+       }
+
+     return vertex;
+     }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+   private void buildGrid(float[] position, float[] normal, float[] texture)
+     {
+     boolean lastBlockIsNE = false;
+     boolean currentBlockIsNE;
+     int vertex = 0;
+
+     //android.util.Log.d("BITMAP", "buildGrid");
+
+     for(int row=0; row<mRows; row++)
+       {
+       for(int col=0; col<mCols; col++)
+         {
+         currentBlockIsNE = (2*row<=mRows-1)^(2*col<=mCols-1);
+
+         if( col==0 || (lastBlockIsNE^currentBlockIsNE) )
+           {
+           if( row!=0 && col==0 ) vertex = repeatLast(vertex,position,normal,texture);
+           vertex= addVertex( vertex, col, row+(currentBlockIsNE?0:1), position, normal, texture);
+           if( row!=0 && col==0 ) vertex = repeatLast(vertex,position,normal,texture);
+           if( lastBlockIsNE^currentBlockIsNE)  vertex = repeatLast(vertex,position,normal,texture);
+           vertex= addVertex( vertex, col, row+(currentBlockIsNE?1:0), position, normal, texture);
+           }
+         vertex= addVertex( vertex, col+1, row+(currentBlockIsNE?0:1), position, normal, texture);
+         vertex= addVertex( vertex, col+1, row+(currentBlockIsNE?1:0), position, normal, texture);
+
+         lastBlockIsNE = currentBlockIsNE;
+         }
+       }
+
+     //android.util.Log.d("BITMAP", "buildGrid done");
+     }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/*
+   private static String debug(float[] val, int stop)
+     {
+     String ret="";
+
+     for(int i=0; i<val.length; i++)
+        {
+        if( i%stop==0 ) ret+="\n";
+        ret+=(" "+val[i]);
+        }
+
+     return ret;
+     }
+*/
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// PUBLIC API
+///////////////////////////////////////////////////////////////////////////////////////////////////
+/**
+ * Creates the underlying grid of vertices, normals and texture coords.
+ *
+ * @param cols Number of columns in the grid.
+ * @param rows Number of rows in the grid.
+ */
+   public GridFlat(int cols, int rows)
+      {
+      computeNumberOfVertices(cols,rows);
+
+      float[] positionData= new float[POSITION_DATA_SIZE*dataLength];
+      float[] normalData  = new float[NORMAL_DATA_SIZE  *dataLength];
+      float[] textureData = new float[TEX_DATA_SIZE     *dataLength];
+
+      buildGrid(positionData,normalData,textureData);
+
+      //android.util.Log.e("CUBES","dataLen="+dataLength);
+      //android.util.Log.d("CUBES", "position: "+debug(positionData,3) );
+      //android.util.Log.d("CUBES", "normal: "  +debug(  normalData,3) );
+      //android.util.Log.d("CUBES", "texture: " +debug( textureData,2) );
+
+      if( remainingVert!=0 )
+        android.util.Log.d("BITMAP", "remainingVert " +remainingVert );
+
+      mGridPositions = ByteBuffer.allocateDirect(POSITION_DATA_SIZE*dataLength*BYTES_PER_FLOAT).order(ByteOrder.nativeOrder()).asFloatBuffer();
+      mGridPositions.put(positionData).position(0);
+
+      mGridNormals = ByteBuffer.allocateDirect(NORMAL_DATA_SIZE*dataLength*BYTES_PER_FLOAT).order(ByteOrder.nativeOrder()).asFloatBuffer();
+      mGridNormals.put(normalData).position(0);
+
+      mGridTexture = ByteBuffer.allocateDirect(TEX_DATA_SIZE*dataLength*BYTES_PER_FLOAT).order(ByteOrder.nativeOrder()).asFloatBuffer();
+      mGridTexture.put(textureData).position(0);
+      }
+  }
\ No newline at end of file
diff --git a/src/main/java/org/distorted/library/GridObject.java b/src/main/java/org/distorted/library/GridObject.java
new file mode 100644
index 0000000..aaf1428
--- /dev/null
+++ b/src/main/java/org/distorted/library/GridObject.java
@@ -0,0 +1,51 @@
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Copyright 2016 Leszek Koltunski                                                               //
+//                                                                                               //
+// This file is part of Distorted.                                                               //
+//                                                                                               //
+// Distorted is free software: you can redistribute it and/or modify                             //
+// it under the terms of the GNU General Public License as published by                          //
+// the Free Software Foundation, either version 2 of the License, or                             //
+// (at your option) any later version.                                                           //
+//                                                                                               //
+// Distorted is distributed in the hope that it will be useful,                                  //
+// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
+// GNU General Public License for more details.                                                  //
+//                                                                                               //
+// You should have received a copy of the GNU General Public License                             //
+// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+package org.distorted.library;
+
+import java.nio.FloatBuffer;
+
+import android.opengl.GLES20;
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+public abstract class GridObject
+   {
+   protected static final int BYTES_PER_FLOAT   = 4; //
+   protected static final int POSITION_DATA_SIZE= 3; // Size of the position data in elements
+   protected static final int NORMAL_DATA_SIZE  = 3; // Size of the normal data in elements.
+   protected static final int TEX_DATA_SIZE     = 2; // Size of the texture coordinate data in elements. 
+
+   protected int dataLength;                       
+      
+   protected FloatBuffer mGridPositions,mGridNormals,mGridTexture;
+ 
+///////////////////////////////////////////////////////////////////////////////////////////////////
+   
+   void draw()
+     { 
+     GLES20.glVertexAttribPointer(Distorted.mPositionH    , POSITION_DATA_SIZE, GLES20.GL_FLOAT, false, 0, mGridPositions);          
+     GLES20.glVertexAttribPointer(Distorted.mNormalH      , NORMAL_DATA_SIZE  , GLES20.GL_FLOAT, false, 0, mGridNormals  );
+     GLES20.glVertexAttribPointer(Distorted.mTextureCoordH, TEX_DATA_SIZE     , GLES20.GL_FLOAT, false, 0, mGridTexture  );  
+
+     GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, dataLength); 
+     }
+   }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
