TileSurface.java 193 KB
Newer Older
1
package com.elphel.imagej.tileprocessor;
2 3
/**
 **
4
 ** TileSurface - handle tile surfaces
5 6 7 8
 **
 ** Copyright (C) 2017 Elphel, Inc.
 **
 ** -----------------------------------------------------------------------------**
9
 **
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 **  TileSurface.java 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 3 of the License, or
 **  (at your option) any later version.
 **
 **  This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 ** -----------------------------------------------------------------------------**
 **
 */
25 26 27 28 29 30 31 32
import java.awt.Point;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.concurrent.atomic.AtomicInteger;

33
import com.elphel.imagej.common.ShowDoubleFloatArrays;
Andrey Filippov's avatar
Andrey Filippov committed
34

35 36

public class TileSurface {
37
//	public
Andrey Filippov's avatar
Andrey Filippov committed
38
//		private int tileSize;
39
		private int superTileSize;
40 41
		private int imageTilesX;
		private int imageTilesY;
42 43
		private int stilesX;
		private int stilesY;
44
		private int [] st_dirs8;
45 46 47
		private int [] t_dirs8;
		private double [] window;
		private int threadsMax = 100;
48 49
		private int [][] tileLayers = null;
		private TileData [][] tileData = null;
50
		private SurfaceData [] surfaceData = null; // result surfaces
51

52 53 54 55 56 57
		static int STAT_UNASSIGNED = 0; // index of number of unassigned tiles
		static int STAT_ASSIGNED =   1; // index of number of assigned tiles
		static int STAT_PROHIBITED = 2; // index of number of initially prohibited tiles
		static int STAT_IMPOSSIBLE = 3; // index of number of impossible (like no surfaces at that location) tiles
		static int STAT_NUM_ML =     4; // index of number of measurement layers used
		static int STAT_LEN =        5; // number of stat entries
58

59 60
		static int UNASSIGNED =   0; //tile marked as invalid
		static int PROHOBITED =  -1; //tile marked as invalid
61 62
		static int IMPOSSIBLE =  -2; // give up on this tile (as no surface for it)

63 64 65 66
		static int NEW_ASSIGNED =     0; // successfully assigned to a surface
		static int NO_SURF =          1; // no surfaces for this tile cell
		static int TOO_WEAK =         2; // tile strength is too low
		static int TOO_STRONG =       3; // tile strength is too high ( for that disparity difference)
67
		static int TOO_FAR =          4; // no surface candidates within the allowed disparity range
68 69 70 71
		static int NOT_UNIQUE =       5; // multiple surfaces are within range
		static int REMOVED_TILES =    6; // number of removed tiles in weak clusters
		static int REMOVED_CLUSTERS = 7; // number of removed weak clusters
		static int NUM_STATS =        8;
72 73 74 75 76 77 78 79 80

		static int CLUST_NUM_INDEX =       0;
		static int CLUST_NUM_TILES =       1;
		static int CLUST_NUM_LAYERS =      2;
		static int CLUST_NUM_OVERLAPS =    3;
		static int CLUST_NUM_MULTI =       4;
		static int CLUST_NUM_CONFLICTS_A = 5;
		static int CLUST_NUM_CONFLICTS_B = 6;
		static int CLUST_NUM_STATS =       7;
81

82 83 84 85 86 87
		static int ASGN_DISP =     0;
		static int ASGN_A_DISP =   1;
		static int ASGN_A_NAN =    2;
		static int ASGN_INDX =     3;
		static int ASGN_STRENGTH = 4;
		static int ASGN_NG =       5;
88 89


90 91 92 93
//		private int nsTilesstSize =   0; // 8;
		GeometryCorrection   geometryCorrection = null;
		public TileSurface(
				int tileSize,
94
				int superTileSize,
95 96
				int tilesX,
				int tilesY,
97 98
				GeometryCorrection geometryCorrection,
				int threadsMax){
Andrey Filippov's avatar
Andrey Filippov committed
99
//			this.tileSize = tileSize;
100
			this.superTileSize = superTileSize;
101
			this.geometryCorrection =geometryCorrection;
102 103
			this.imageTilesX =  tilesX;
			this.imageTilesY =  tilesY;
Andrey Filippov's avatar
Andrey Filippov committed
104 105 106 107
			this.window = getWindow(2*superTileSize);
			this.threadsMax = threadsMax;
			stilesX = (tilesX + superTileSize -1)/superTileSize;
			stilesY = (tilesY + superTileSize -1)/superTileSize;
108 109
//			int [] dirs =  {-tilesX, -tilesX + 1, 1, tilesX + 1, tilesX, tilesX - 1, -1, -tilesX - 1};
			int [] dirs =  {-stilesX, -stilesX + 1, 1, stilesX + 1, stilesX, stilesX - 1, -1, -stilesX - 1};
110
			this.st_dirs8 = dirs;
111

112
			int tx = superTileSize * stilesX;
113 114
			int [] tdirs =  {-tx, -tx + 1, 1, tx + 1, tx, tx - 1, -1, -tx - 1};
			this.t_dirs8 = tdirs;
115

116
		}
117 118 119 120 121 122 123 124 125
		public int getThreadsMax(){
			return this.threadsMax;
		}
		public int getSTilesX(){
			return stilesX;
		}
		public int getSTilesY(){
			return stilesY;
		}
126

127 128 129
		public int getSuperTileSize(){
			return superTileSize;
		}
130

131 132 133 134
		public int [][] getTileLayers()
		{
			return this.tileLayers;
		}
135 136 137 138 139 140 141

		public int getImageTilesX(){
			return imageTilesX;
		}
		public int getImageTilesY(){
			return imageTilesY;
		}
142

143 144 145 146
		public 	TileData [][] getTileData(){
			return this.tileData;
		}

147

148 149 150 151 152 153 154 155 156 157 158 159 160
		public int [][] getTileLayersCopy()
		{
			if (this.tileLayers == null){
				return null;
			}
			int [][] tl = this.tileLayers.clone();
			for (int i = 0; i < tl.length; i++){
				if (tl[i] != null){
					tl[i] = tl[i].clone();
				}
			}
			return this.tileLayers;
		}
161

162 163 164
		public void setTileLayers(int [][] tileLayers){
			this.tileLayers = tileLayers;
		}
165

166
		public class TileData{
167 168 169 170
			double [] disp_strength;
			int indx =         0;
			int new_index =    0;
			boolean enable =   true;
Andrey Filippov's avatar
Andrey Filippov committed
171
			int [] neighbors = {-1,-1,-1,-1,-1,-1,-1,-1};
172 173 174
			int parent_nsTile;
			int parent_layer;
//			TilePlanes.PlaneData parent_plane;
175 176 177 178 179 180
			public TileData (
					double disparity,
					double strength)
			{
				setDisparityStrength(disparity,strength);
			}
181
/*
182
			public void setParentPlane (TilePlanes.PlaneData parent_plane)
Andrey Filippov's avatar
Andrey Filippov committed
183
			{
184
				this.parent_plane = parent_plane;
Andrey Filippov's avatar
Andrey Filippov committed
185 186
			}

187
			public TilePlanes.PlaneData getParentPlane ()
Andrey Filippov's avatar
Andrey Filippov committed
188
			{
189 190 191
				return this.parent_plane;
			}
*/
192 193 194 195 196 197 198 199 200 201
			public String getNeibString()
			{
				String s = "[";
				for (int dir = 0; dir < 8; dir++){
					s += (neighbors[dir]>=0) ? neighbors[dir]:"x";
					if (dir < 7) s += ", ";
				}
				s+= "] ";
				return s;
			}
202
			@Override
203 204
			public String toString()
			{
205

206 207 208 209 210
				String s = "          ";
				s += getNeibString();
				s += String.format( "index=%2d(%2d) parent = %3d:%1d disp=%8.5f weight=%8.5f",
						new_index, indx,
						parent_nsTile, parent_layer, disp_strength[0], disp_strength[1]);
211

212 213 214

				return s;
			}
215 216 217



218 219 220 221 222 223 224 225 226 227
			public void setParentTileLayer (int parent_nsTile, int parent_layer)
			{
				this.parent_nsTile = parent_nsTile;
				this.parent_layer =  parent_layer;
			}

			public int getParentLayer ()
			{
				return this.parent_layer;
			}
228 229


230 231 232 233 234 235 236 237
//			public void setParentNsTile(int parent_nsTile)
//			{
//				this.parent_nsTile = parent_nsTile;
//			}

			public int getParentNsTile()
			{
				return this.parent_nsTile;
Andrey Filippov's avatar
Andrey Filippov committed
238
			}
239 240 241

			public void setIndex(int indx)
			{
Andrey Filippov's avatar
Andrey Filippov committed
242 243 244 245
				this.indx = indx;
				if (indx < 0){
					System.out.println("setIndex("+indx+")");
				}
246 247 248
			}
			public int  getIndex()
			{
249
				return this.indx;
250 251 252 253 254
			}


			public void setNewIndex(int indx)
			{
255
				this.new_index = indx;
256 257 258
			}
			public int  getNewIndex()
			{
259
				return this.new_index;
260
			}
261 262


263 264
			public void setNeighbors(int [] neighbors)
			{
265
				this.neighbors = neighbors;
266 267 268
			}
			public int [] getNeighbors()
			{
269
				return this.neighbors;
270
			}
Andrey Filippov's avatar
Andrey Filippov committed
271
			public void setNeighbor(int dir,int neib)
272
			{
Andrey Filippov's avatar
Andrey Filippov committed
273
//				if (this.neighbors == null) this.neighbors = new int[8];
274
				this.neighbors[dir] = neib;
275 276 277
			}
			public int getNeighbor(int dir)
			{
Andrey Filippov's avatar
Andrey Filippov committed
278
//				if (this.neighbors == null) this.neighbors = new int[8];
279
				return this.neighbors[dir];
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
			}
			public void setEnable(boolean enable)
			{
				this.enable = enable;
			}
			public boolean getEnable()
			{
				return this.enable;
			}
			public void setDisparityStrength(
					double disparity,
					double strength)

			{
				this.disp_strength = new double[2];
				this.disp_strength[0] = disparity;
				this.disp_strength[1] =  strength;
			}
298

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
			public void setDisparity(double disparity)
			{
				if (this.disp_strength == null){
					this.disp_strength = new double[2];
				}
				this.disp_strength[0] = disparity;
			}
			public double getDisparity()
			{
				if (this.disp_strength == null){
					this.disp_strength = new double[2];
				}
				return this.disp_strength[0];
			}
			public double getDisparity(boolean useNaN)
			{
				if (useNaN && (this.disp_strength == null)) return Double.NaN;
				if (this.disp_strength == null){
					this.disp_strength = new double[2];
				}
				if (useNaN && (this.disp_strength[1] == 0.0))  return Double.NaN;
				return this.disp_strength[0];
			}

			public double getDisparityNaN()
			{
				return getDisparity(true);
			}
327

328 329 330 331 332 333 334 335 336 337 338 339 340 341
			public void setStrength(double strength)
			{
				if (this.disp_strength == null){
					this.disp_strength = new double[2];
				}
				this.disp_strength[1] = strength;
			}
			public double getStrength()
			{
				if (this.disp_strength == null){
					this.disp_strength = new double[2];
				}
				return this.disp_strength[1];
			}
342

343 344 345 346 347 348 349 350 351
		}

		public int getNStileDir(
				int nsTile,
				int dir)
		{
			if (dir < 0) return nsTile;
			int sty = nsTile / stilesX;
			int stx = nsTile % stilesX;
Andrey Filippov's avatar
Andrey Filippov committed
352
			if ((stx > 0) && (sty > 0) && (sty < (stilesY - 1)) && (stx < (stilesX - 1))) return nsTile + st_dirs8[dir]; // most likely case
353 354 355
			if ((sty == 0)             && ((dir < 2) || (dir == 7))) return -1;
			if ((sty == (stilesY - 1)) &&  (dir > 2) && (dir < 6))   return -1;
			if ((stx == 0)            &&  (dir > 4))                 return -1;
356 357 358 359 360 361 362 363 364 365 366 367 368
			if ((stx == (stilesX - 1)) &&   (dir > 0) && (dir < 4))  return -1;
			return nsTile + st_dirs8[dir];
		}

		public int getNtileDir(
				int nTile,
				int dir)
		{
			if (dir < 0) return nTile;
			int tilesX = stilesX * superTileSize;
			int tilesY = stilesY * superTileSize;
			int ty = nTile / tilesX;
			int tx = nTile % tilesX;
Andrey Filippov's avatar
Andrey Filippov committed
369
			if ((tx > 0) && (ty > 0) && (ty < (tilesY - 1)) && (tx < (tilesX - 1))) return nTile + t_dirs8[dir]; // most likely case
370 371 372
			if ((ty == 0)            && ((dir < 2) || (dir == 7))) return -1;
			if ((ty == (tilesY - 1)) &&  (dir > 2) && (dir < 6))   return -1;
			if ((tx == 0)            &&  (dir > 4))                 return -1;
373 374
			if ((tx == (tilesX - 1)) &&  (dir > 0) && (dir < 4))  return -1;
			return nTile + t_dirs8[dir];
375
		}
376 377


378 379 380 381
		public int getDirToStile(
				int nsTile,
				int nsTile1)
		{
382

383 384 385 386
			int sty =  nsTile / stilesX;
			int stx =  nsTile % stilesX;
			int sty1 = nsTile1 / stilesX;
			int stx1 = nsTile1 % stilesX;
387
			int dx = stx1 - stx;
388
			int dy = sty1 - sty;
Andrey Filippov's avatar
Andrey Filippov committed
389 390 391
//			int sdx = (dx > 0) ? 1: ( (dx < 0) ? -1 : 0);
//			int sdy = (dy > 0) ? 1: ( (dy < 0) ? -1 : 0);
			if ((dy == 0 ) && (dx == 0)) return -1; // same tile
392 393 394 395 396 397 398 399 400 401
			if (dy < 0) {
				if (dx < 0) return 7;
				if (dx > 0) return 1;
				return 0;
			}
			if (dy > 0) {
				if (dx < 0) return 5;
				if (dx > 0) return 3;
				return 4;
			}
Andrey Filippov's avatar
Andrey Filippov committed
402 403
			if (dx < 0) return 6;
			if (dx > 0) return 2;
404 405 406
			return -1;
		}

407

408 409 410 411 412 413
		/**
		 * Get tile surface number from supertile number, direction (-1 same) and the supertile plane index
		 * @param nsTile number of the supertile
		 * @param dir direction -1 - same supertile, 0 - N (up), 1 - NE, .. 7 - NW
		 * @param np number of the supertile plane
		 * @param planes array of the per-supertile, per plane plane data (each level can be null)
414
		 * @return unique tile surface index, if ((dir == 8) && (np == 0)) returns total number of tile surfaces
415 416 417 418 419
		 */
		public int getTileSurfaceNumber (
				int nsTile,
				int dir,              // direction, or -1 (same)
				int np,
420 421
				TilePlanes.PlaneData [][] planes)
		{
Andrey Filippov's avatar
Andrey Filippov committed
422 423 424 425
			if (nsTile < 0) {
				return -1;
			}
			int tsn = (planes[nsTile] == null) ? 0 : planes[nsTile].length; // nsTile = -1 when mesh goes out of the image area
426
			if (dir < 0) {
427 428 429
				if (np >= tsn){
					return -1;
				}
430
				return np;
431
			}
432
			int nsTile1 = -1;
433
			for (int d = 0; d < dir; d ++){
434 435
				nsTile1 = getNStileDir(nsTile, d);
				if ((nsTile1 >=0) && (planes[nsTile1] != null)){
436 437 438
					tsn += planes[nsTile1].length;
				}
			}
439
			if (dir < 8) {
Andrey Filippov's avatar
Andrey Filippov committed
440 441
				nsTile1 = getNStileDir(nsTile, dir);
				int last_Length = ((nsTile1< 0) || (planes[nsTile1] == null)) ? 0: planes[nsTile1].length;
442 443 444 445
				if (np >= last_Length) {
					return -1;
				}
			}
446
			return tsn + np;
447 448
		}
		/**
449
		 * Get supertile direction and the plane number that contributeted to a specific tile surface
450 451 452 453 454
		 * @param nsTile supertile index
		 * @param tp tile surface index (generated by getTileSurfaceNumber)
		 * @param planes array of the per-supertile, per plane plane data (each level can be null)
		 * @return a pair of {dir, plane index}. dir is -1 for the plane in the same supertile, 0..7 for neighbors
		 */
455

456 457 458
		public int []  getSuperTileDirPlane (
				int nsTile,
				int tp,
459
				TilePlanes.PlaneData [][] planes)
460 461 462 463 464 465
		{
			int num_planes = (planes[nsTile] == null)? 0: planes[nsTile].length;
			int [] rslt = {-1, tp};
			if (tp < num_planes) return rslt;
			tp -= num_planes;
			for (int d = 0; d < st_dirs8.length; d ++){
466 467
				int nsTile1 = getNStileDir(nsTile, d);
				num_planes = ((nsTile1 >=0) && (planes[nsTile1] != null))? planes[nsTile1].length : 0;
468 469 470 471 472
				if (tp < num_planes){
					rslt[0] = d;
					rslt[1] = tp;
					return rslt;
				}
473
				tp -= num_planes;
474 475 476 477
			}
			return null; // error - invalid input
		}

478 479 480 481 482 483
		public double [] getWindow (
				int size)
		{
			double [] wnd1d = new double [size];
			for (int i = 0; i < size/2; i++){
				wnd1d[i] = 0.5 * (1.0 - Math.cos(2*Math.PI*(i+0.5)/size));
484
				wnd1d[size - i -1] = wnd1d[i];
485 486 487 488
			}
			double [] wnd = new double [size * size];
			int indx = 0;
			for (int i = 0; i < size; i++){
489
				for (int j = 0; j < size; j++){
490 491 492 493 494
					wnd[indx++] = wnd1d[i]*wnd1d[j];
				}
			}
			return wnd;
		}
495

496 497 498 499 500 501
		public double [] getWindow()
		{
			return window;
		}

		/**
Andrey Filippov's avatar
Andrey Filippov committed
502
		 *  TODO: replace misplaced description Calculate per-tile surface data (TileData) including disparity, strength, and 8 neighbors indices
503 504
		 * @param use_sel use plane selection (this.sel_mask) to select only some part of the plane
		 * @param divide_by_area divide weights by ellipsoid area
505 506
		 * @param scale_projection use plane ellipsoid projection for weight: 0 - do not use, > 0 linearly scale ellipsoid
		 * @param fraction_uni add fraction of the total weight to each tile
507 508 509 510 511 512 513 514 515 516
		 * @param planes array of the per-supertile, per plane plane data (each level can be null)
		 * @param debugLevel debug level
		 * @param dbg_X debug supertile X coordinate
		 * @param dbg_Y debug supertile Y coordinate
		 * @return per-tile (rounded up to contain whole supertiles) sparse array of TileData instances
		 */
		public double [][][][] fuseSupertilePlanes (
				final boolean                   use_sel,
				final boolean                   divide_by_area,
				final double                    scale_projection,
517
				final double                    fraction_uni,
518
				final TilePlanes.PlaneData [][] planes, // why plane here has weighth == 0.0 ?
519 520 521 522
				final int                       debugLevel,
				final int                       dbg_X,
				final int                       dbg_Y)
		{
523 524
			final int nStiles = stilesX * stilesY;
			final int nTiles =  nStiles * superTileSize * superTileSize;
Andrey Filippov's avatar
Andrey Filippov committed
525
			final double [][][][] fused_data = new double [nStiles][][][];
526 527
//			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final Thread[] threads = ImageDtt.newThreadArray((debugLevel > 1)? 1 : threadsMax);
528
			final AtomicInteger ai = new AtomicInteger(0);
Andrey Filippov's avatar
Andrey Filippov committed
529
			final int dbg_tile = dbg_Y * stilesX + dbg_X;
530 531
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
532
					@Override
533 534 535
					public void run() {
						for (int nsTile = ai.getAndIncrement(); nsTile < nStiles; nsTile = ai.getAndIncrement()) {
							if (planes[nsTile] != null) {
536 537
//								int dl = ((debugLevel > -1) && (nsTile == dbg_tile)) ? 3:0;
	                            int dl = ((debugLevel > 1) && (nsTile == dbg_tile)) ? 3: debugLevel;
Andrey Filippov's avatar
Andrey Filippov committed
538 539 540
								if (dl > 0){
									System.out.println("fuseSupertilePlanes(), nsTile = "+nsTile);
								}
541 542
								double [][][] disp_strength = new double [planes[nsTile].length][][];
								for (int np = 0; np < disp_strength.length; np++){
543
									if ((planes[nsTile][np] != null) && (planes[nsTile][np].getWeight() > 0.0)){ // disregard 0-weight planes
Andrey Filippov's avatar
Andrey Filippov committed
544
										disp_strength[np] = planes[nsTile][np].getDoublePlaneDisparityStrength(
545 546
												getWindow(),      // double [] window,
												-1,              // int dir (-1 - center, 0- N, 1 - NE, .. 7 - NW
547
												false,           // use_sel,          // boolean   use_sel, apply selection to the result
548 549
												divide_by_area,   //boolean   divide_by_area,
												scale_projection, // double    scale_projection,
550
												fraction_uni, //				double    fraction_uni,
551 552
												debugLevel-1);   // int       debugLevel)
										// multiply disparities by strengths to calculate weighted averages
553
										double [] disp0 = disp_strength[np][0].clone(); // to use where strength == 0
554
										for (int i = 0; i < disp_strength[np][1].length; i++){
555
											disp_strength[np][0][i] *= disp_strength[np][1][i];
556
										}
Andrey Filippov's avatar
Andrey Filippov committed
557 558 559 560 561 562 563 564 565 566
										//									}
										for (int dir = 0; dir < st_dirs8.length; dir++){
											int sNeib = planes[nsTile][np].getNeibBest(dir);
											if (sNeib >= 0){
												int nsTile1 = getNStileDir(nsTile, dir); //   nsTile + ((dir < 0) ? 0: st_dirs8[dir]);
												if ((nsTile1 >= 0) && (planes[nsTile1] != null)){
//													double [][] ds = planes[nsTile1][np].getSinglePlaneDisparityStrength(
													double [][] ds = planes[nsTile1][sNeib].getDoublePlaneDisparityStrength(
															getWindow(),      // double [] window,
															dir,              // int dir (-1 - center, 0- N, 1 - NE, .. 7 - NW
567
															false,           // use_sel,          // boolean   use_sel, apply selection to the result
Andrey Filippov's avatar
Andrey Filippov committed
568 569
															divide_by_area,   //boolean   divide_by_area,
															scale_projection, // double    scale_projection,
570
															fraction_uni, //				double    fraction_uni,
Andrey Filippov's avatar
Andrey Filippov committed
571 572 573
															debugLevel-1);   // int       debugLevel)
													for (int i = 0; i < disp_strength[np][1].length; i++){
														if (ds[1][i] > 0.0){
574 575
															disp_strength[np][1][i] += ds[1][i];
															disp_strength[np][0][i] += ds[1][i] * ds[0][i];
Andrey Filippov's avatar
Andrey Filippov committed
576
														}
577
													}
578
												}
Andrey Filippov's avatar
Andrey Filippov committed
579
											}
580
										}
Andrey Filippov's avatar
Andrey Filippov committed
581
										// calculate weighted average for each tile
582
										for (int i = 0; i < disp_strength[np][1].length; i++){
Andrey Filippov's avatar
Andrey Filippov committed
583
											if (disp_strength[np][1][i] > 0.0){
584
												disp_strength[np][0][i] /= disp_strength[np][1][i];
585 586
											} else {
												disp_strength[np][0][i] = disp0[i]; // may have discontinuity
Andrey Filippov's avatar
Andrey Filippov committed
587
											}
588
										}
589 590 591 592 593
										if (use_sel){ // zero out selection after averaging, apply to this tile
											boolean [] sel = planes[nsTile][np].getSelMask();
											if (sel != null){
												for (int i = 0; i < disp_strength[np][1].length; i++){
													if (!sel[i]) disp_strength[np][1][i] = 0.0;
594
												}
595 596
											}
										}
597

598 599 600 601 602 603 604
										if ((debugLevel > -1) && (dl>0)){
											String str_neib =  "fuseSupertilePlanes_"+nsTile+":"+np;
											for (int dir = 0; dir < 8; dir++){
												str_neib += " " + planes[nsTile][np].getNeibBest(dir);
											}
											System.out.println(str_neib);
										}
605 606 607
									}
								}
								fused_data[nsTile] = disp_strength;
608
								if ((debugLevel > -1) && (dl > 0)){
609 610 611 612 613 614 615
									String[] titles = new String [3 * disp_strength.length];
									double [][] dbg_img = new double [titles.length][];
									for (int i = 0; i < disp_strength.length; i++) {
										titles [i + 0 * disp_strength.length] = "disp_" + i;
										titles [i + 1 * disp_strength.length] = "mdisp_" + i;
										titles [i + 2 * disp_strength.length] = "str_" + i;
										if (disp_strength[i] != null) {
616 617
											dbg_img[i + 0 * disp_strength.length] = disp_strength[i][0];
											dbg_img[i + 2 * disp_strength.length] = disp_strength[i][1];
618 619 620 621 622 623 624 625
											dbg_img[i + 1 * disp_strength.length] = disp_strength[i][0].clone();
											for (int j = 0; j < disp_strength[i][0].length; j++){
												if (disp_strength[i][1][j] == 0.0){
													dbg_img[i + 1 * disp_strength.length][j] = Double.NaN;
												}
											}
										}
									}
626
									ShowDoubleFloatArrays.showArrays(dbg_img,  2 * superTileSize, 2 * superTileSize, true, "surf_ds_"+nsTile, titles);
627
								}
628

629 630 631 632
							}
						}
					}
				};
633
			}
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
			ImageDtt.startAndJoin(threads);
			return fused_data;
		}


		/**
		 * Prepare topology of the supertiles connections. For each of the 4 quadrants (0, 1 / 2, 3) of each
		 * used supertile plane, get 4 plane indices that contribute to it (also in linescan (0, 1/ 2,3) order
		 * That will tell which of the overlapping 2x supertile planes can be merged
		 * @param planes array of the per-supertile, per plane plane data (each level can be null)
		 * @param debugLevel debug level
		 * @param dbg_X debug supertile X coordinate
		 * @param dbg_Y debug supertile Y coordinate
		 * @return per-tile , per plane, per quadrant, per quadrant 4 corners - index of contributing plane (or -1 if none)
		 */
		public int [][][][] getSupertilesTopology (
				final TilePlanes.PlaneData [][] planes,
				final int                       debugLevel,
				final int                       dbg_X,
				final int                       dbg_Y)
		{
655 656
			final int nStiles = stilesX * stilesY;
//			final int nTiles =  nStiles * superTileSize * superTileSize;
657 658 659 660 661 662 663
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
			final int [][] dir_corn = {
					{ 7,  0,  6, -1},  // 0 (top left)
					{ 0,  1, -1,  2},  // 1 (top right)
					{ 6, -1,  5,  4},  // 2 (bottom left)
					{-1,  2,  4,  3}}; // 3 (bottom right)
664

Andrey Filippov's avatar
Andrey Filippov committed
665 666 667
			final int [][][][] corners = new int [nStiles][][][];
			final int dbg_tile = dbg_Y * stilesX + dbg_X;

668 669
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
670
					@Override
671 672 673
					public void run() {
						for (int nsTile = ai.getAndIncrement(); nsTile < nStiles; nsTile = ai.getAndIncrement()) {
							if (planes[nsTile] != null) {
Andrey Filippov's avatar
Andrey Filippov committed
674 675 676 677
								int dl = ((debugLevel > -1) && (nsTile == dbg_tile)) ? 3:0;
								if (dl > 0){
									System.out.println("getSupertilesTopology(), nsTile = "+nsTile);
								}
678 679
								corners[nsTile] = new int [planes[nsTile].length][][];
								for (int np = 0; np < planes[nsTile].length; np++){
680 681
//									if (planes[nsTile][np] != null){
									if ((planes[nsTile][np] != null) && (planes[nsTile][np].getWeight() > 0.0)){ // disregard 0-weight planes
682
										int [] neibs = planes[nsTile][np].getNeibBest();
Andrey Filippov's avatar
Andrey Filippov committed
683 684
										if (neibs == null) {
											System.out.println("getSupertilesTopology(), nsTile = "+nsTile+" neibs= null");
685

Andrey Filippov's avatar
Andrey Filippov committed
686 687 688 689 690 691 692
										} else {
											corners[nsTile][np]= new int [4][4];
											for (int i= 0; i < 4; i++){
												for (int j = 0; j < 4; j++){
													if (dir_corn[i][j] < 0){
														corners[nsTile][np][i][j] = np;
													} else {
693
														corners[nsTile][np][i][j] = neibs[dir_corn[i][j]];
Andrey Filippov's avatar
Andrey Filippov committed
694
													}
695 696 697 698 699 700 701 702 703
												}
											}
										}
									}
								}
							}
						}
					}
				};
704
			}
705 706 707
			ImageDtt.startAndJoin(threads);
			return corners;
		}
708

709 710 711 712 713 714 715 716 717 718 719
		/**
		 * Calculate per-tile surface data (TileData) including disparity, strength, and 8 neighbors indices
		 * @param planes array of the per-supertile, per plane plane data (each level can be null)
		 * @param corners - topology data generated by getSupertilesTopology() method
		 * @param debugLevel debug level
		 * @param dbg_X debug supertile X coordinate
		 * @param dbg_Y debug supertile Y coordinate
		 * @return per-tile (rounded up to contain whole supertiles) sparse array of TileData instances
		 */
		public int [][][][][] generateOverlappingMeshes (
				final TilePlanes.PlaneData [][] planes,
720
				final int [][][][]              corners,
721 722 723 724
				final int                       debugLevel,
				final int                       dbg_X,
				final int                       dbg_Y)
		{
725 726
			final int nStiles = stilesX * stilesY;
//			final int nTiles =  nStiles * superTileSize * superTileSize;
Andrey Filippov's avatar
Andrey Filippov committed
727
			final int [][][][][] meshes = new int [nStiles][][][][];
728

729 730 731 732 733 734
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
			final int ss2 = 2 * superTileSize;
			final int ss1 =  superTileSize;
			final int sh  =  superTileSize/2;
			final int len_st2 = ss2  * ss2 ;
735

736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
			final int [][][] quad_check = { // [quadrant 01/23][dir: left, right, diagonal]{dir, quadrant}
					{ // top left quadrant
						{6, 1},  //left
						{0, 2},  //right
						{7, 3}   //diagonal
					},
					{ // top right quadrant
						{0, 3},  //left
						{2, 0},  //right
						{1, 2}   //diagonal
					},
					{ // bottom left quadrant
						{4, 0},  //left
						{6, 3},  //right
						{5, 1}   //diagonal
					},
					{ // bottom right quadrant
						{2, 2},  //left
						{4, 1},  //right
						{3, 0}}};//diagonal
			final int [][][] cut_ortho = { // [quadrant][left, right][index, width, height}
					{ // quadrant 0 - top left
						{0, sh,  ss1}, // left path
						{0, ss1, sh }  // right path
					},
					{ // quadrant 1 - top right
						{ss1,    ss1, sh},
						{3 * sh, sh,  ss1}
					},
					{ // quadrant 2 - bottom left
Andrey Filippov's avatar
Andrey Filippov committed
766 767
						{3 * ss2 * sh, ss1, sh},
						{ss1 * ss2, sh, ss1}
768 769
					},
					{ // quadrant 3 - bottom right
Andrey Filippov's avatar
Andrey Filippov committed
770 771
						{ss1 * ss2 + 3 * sh, sh, ss1},
						{3 * sh * ss2 + ss1, ss1, sh}
772 773
					},
			};
774

775
			final TileNeibs tileNeibs = new TileNeibs(2*superTileSize);
Andrey Filippov's avatar
Andrey Filippov committed
776 777

			final int dbg_tile = dbg_Y * stilesX + dbg_X;
778

779 780
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
781
					@Override
782 783 784
					public void run() {
						for (int nsTile = ai.getAndIncrement(); nsTile < nStiles; nsTile = ai.getAndIncrement()) {
							if (planes[nsTile] != null) {
Andrey Filippov's avatar
Andrey Filippov committed
785 786 787 788
								int dl = ((debugLevel > -1) && (nsTile == dbg_tile)) ? 3:0;
								if (dl > 0){
									System.out.println("generateOverlappingMeshes(), nsTile = "+nsTile);
								}
789 790
								meshes[nsTile] = new int [planes[nsTile].length][][][];
								for (int np = 0; np < planes[nsTile].length; np++){
791 792
//									if (planes[nsTile][np] != null){
									if ((planes[nsTile][np] != null) && (planes[nsTile][np].getWeight() > 0.0)){ // disregard 0-weight planes
793 794 795 796 797 798 799 800
										int [][] pre_mesh = new int [len_st2][2];
										for (int i = 0; i < len_st2; i ++){
											pre_mesh[i][0] = nsTile;
											pre_mesh[i][1] = np;
										}
										int [] neibs = planes[nsTile][np].getNeibBest();
										for (int quadrant = 0; quadrant <4; quadrant ++) {
											int [] these_corner_planes = corners[nsTile][np][quadrant];
Andrey Filippov's avatar
Andrey Filippov committed
801 802
//											int [][] neib_id = new int[3][2];
											int [][] neib_id = new int[3][];
803 804 805
											for (int arr = 0; arr < 3; arr++){
												int dir = quad_check[quadrant][arr][0];
												if (neibs[dir] >= 0) {
Andrey Filippov's avatar
Andrey Filippov committed
806
													neib_id[arr] = new int [2];
807 808 809 810 811 812 813 814 815 816 817 818 819
													int nsTile1 = nsTile + st_dirs8[dir];
													int [] other_corner_planes = corners[nsTile1][neibs[dir]][quad_check[quadrant][arr][1]];
													neib_id[arr][0] = nsTile1;
													neib_id[arr][1] = neibs[dir];
													for (int i = 0; i < these_corner_planes.length; i++){
														if (other_corner_planes[i] != these_corner_planes[i]){
															neib_id[arr] = null;
															break;
														}
													}
												}
											}
											// depending on match values, cut and join mesh with the neighbor
Andrey Filippov's avatar
Andrey Filippov committed
820
											// change diagonal first (add corner square later again
821 822
											if (neib_id[2] != null){
												switch (quadrant){
823
												case 0: // top left
824
													for (int j = 0; j < (ss1 - 1); j++){
Andrey Filippov's avatar
Andrey Filippov committed
825
														for (int i = ss1 - 2 - j; i>=0; i--){
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
															pre_mesh[i * ss2 + j] = neib_id[2];
														}
													}
													break;
												case 1: // top right
													for (int j = ss1; j < ss2; j++){
														for (int i = j - ss1; i >= 0; i--){
															pre_mesh[i * ss2 + j] = neib_id[2];
														}
													}
													break;
												case 2: // bottom left
													for (int j = 0; j < (ss1 - 1); j++){
														for (int i = ss1 + 1 + j; i < ss2; i++){
															pre_mesh[i * ss2 + j] = neib_id[2];
														}
													}
													break;
												case 3: // bottom right
													for (int j = ss1; j < ss2; j++){
Andrey Filippov's avatar
Andrey Filippov committed
846
														for (int i = ss2 + ss1 - 1 - j; i < ss2; i++){
847 848 849 850 851 852
															pre_mesh[i * ss2 + j] = neib_id[2];
														}
													}
													break;
												}
											}
Andrey Filippov's avatar
Andrey Filippov committed
853 854 855 856 857
											// change ortho - on top of diagonal
											for (int arr = 0; arr < 2; arr++) if (neib_id[arr] != null){
												for (int y = 0; y < cut_ortho[quadrant][arr][2]; y++){
													for (int x = 0; x < cut_ortho[quadrant][arr][1]; x++){
														int indx =  cut_ortho[quadrant][arr][0] + y * ss2 + x;
858
														pre_mesh[indx] = neib_id[arr];
Andrey Filippov's avatar
Andrey Filippov committed
859 860 861
													}
												}
											}
Andrey Filippov's avatar
Andrey Filippov committed
862 863 864
											// add corner square corner on top of possible ortho
											if (neib_id[2] != null){
												switch (quadrant){
865
												case 0: // top left
Andrey Filippov's avatar
Andrey Filippov committed
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
													for (int j = 0; j < sh; j++){
														for (int i =  0 ; i < sh; i++){
															pre_mesh[i * ss2 + j] = neib_id[2];
														}
													}
													break;
												case 1: // top right
													for (int j = ss1 + sh; j < ss2; j++){
														for (int i = 0; i < sh; i++){
															pre_mesh[i * ss2 + j] = neib_id[2];
														}
													}
													break;
												case 2: // bottom left
													for (int j = 0; j < sh; j++){
														for (int i = ss1 + sh; i < ss2; i++){
															pre_mesh[i * ss2 + j] = neib_id[2];
														}
													}
													break;
												case 3: // bottom right
													for (int j = ss1 + sh; j < ss2; j++){
														for (int i = ss1 + sh; i < ss2; i++){
															pre_mesh[i * ss2 + j] = neib_id[2];
														}
													}
													break;
												}
											}
895 896 897
										}
										// build mesh , then add cuts if needed
										meshes[nsTile][np] = new int [len_st2][][];
898
										int [][][] dbg_meshes = meshes[nsTile][np];
Andrey Filippov's avatar
Andrey Filippov committed
899 900 901
										if (dl > 0){
											System.out.println("generateOverlappingMeshes(), dbg_meshes.length = "+dbg_meshes.length);
										}
902

903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
										for (int i = 0; i < len_st2; i ++){
											if ((pre_mesh[i] != null) && (pre_mesh[i][0] == nsTile)){
												meshes[nsTile][np][i] = new int [8][];
												for (int dir = 0; dir < 8; dir++) {
													int ineib = tileNeibs.getNeibIndex(i, dir);
													if (ineib >= 0) meshes[nsTile][np][i][dir] = pre_mesh[ineib];
												}
											}
										}
										// add cuts
										// up
										for (int ncut = 0; ncut <8; ncut++){
											int indx, dir_go = -1, dir_start = -1;
											boolean cut_right = false;
											switch (ncut){
Andrey Filippov's avatar
Andrey Filippov committed
918 919
											case 0:	dir_go = 0; dir_start =  7;	cut_right = true;  break;
											case 1:	dir_go = 0; dir_start =  0;	cut_right = false; break;
920 921 922 923
											case 2:	dir_go = 2; dir_start =  0;	cut_right = true;  break;
											case 3:	dir_go = 2; dir_start = -1;	cut_right = false; break;
											case 4:	dir_go = 4; dir_start = -1;	cut_right = true;  break;
											case 5:	dir_go = 4; dir_start =  6;	cut_right = false; break;
Andrey Filippov's avatar
Andrey Filippov committed
924 925
											case 6:	dir_go = 6; dir_start =  6;	cut_right = true;  break;
											case 7:	dir_go = 6; dir_start =  7;	cut_right = false; break;
926
											}
927 928 929 930
											int dir_go45 =   (dir_go + (cut_right ? 1:7)) % 8;
											int dir_go90 =   (dir_go + (cut_right ? 2:6)) % 8;
											int dir_go135 =  (dir_go + (cut_right ? 3:5)) % 8;
											int dir_go180 =  (dir_go + 4) % 8;
931 932

											indx = ss1 * (ss2 + 1); // center point
933

934 935
											for (int i = 0; i < sh; i++) indx = tileNeibs.getNeibIndex(indx, dir_go);
											if (dir_start >= 0) indx = tileNeibs.getNeibIndex(indx, dir_start);
936

937
											int indx1 = tileNeibs.getNeibIndex(indx, dir_go90);
Andrey Filippov's avatar
Andrey Filippov committed
938 939 940
//											if ((pre_mesh[indx] != null) && (pre_mesh[indx1] == null)){ // there is a cut
//											if ((pre_mesh[indx][0] == nsTile) && (pre_mesh[indx1][0] != nsTile)){ // there is a cut
											if ((meshes[nsTile][np][indx] != null) && (meshes[nsTile][np][indx1] == null)){ // there is a cut
941
												for (int i = 0; i < sh; i++){
Andrey Filippov's avatar
Andrey Filippov committed
942 943 944 945 946 947 948
													int indx_back = tileNeibs.getNeibIndex(indx, dir_go180);
													if (meshes[nsTile][np][indx_back] != null) meshes[nsTile][np][indx_back][dir_go45] = null; // NE for N, right
													if (meshes[nsTile][np][indx] != null) {
														meshes[nsTile][np][indx][dir_go90] = null; // E for N, right
														if (i > 0){
															meshes[nsTile][np][indx][dir_go135] = null; // SE for N, right
														}
949 950 951
													}
													indx = tileNeibs.getNeibIndex(indx, dir_go);
												}
952
											}
953 954 955 956 957 958 959
										}
									}
								}
							}
						}
					}
				};
960
			}
961 962 963 964 965 966 967 968 969 970 971 972 973 974
			ImageDtt.startAndJoin(threads);
			return meshes;
		}

		/**
		 * Calculate per-tile surface data (TileData) including disparity, strength, and 8 neighbors indices
		 * @param planes array of the per-supertile, per plane plane data (each level can be null)
		 * @param fusedSupertilePlanes disparity/strength data generated by fuseSupertilePlanes() method
		 * @param lappingMeshes per super-tile overlapping surface meshes, generateOverlappingMeshes
		 * @param debugLevel debug level
		 * @param dbg_X debug supertile X coordinate
		 * @param dbg_Y debug supertile Y coordinate
		 * @return per-tile (rounded up to contain whole supertiles) sparse array of TileData instances
		 */
975

976 977 978
		public TileData [][] createTileShells (
				final TilePlanes.PlaneData [][] planes,
				final double [][][][]           fusedSupertilePlanes,
979
				final int [][][][][]            lappingMeshes,
980 981 982 983
				final int                       debugLevel,
				final int                       dbg_X,
				final int                       dbg_Y)
		{
984
			final int nStiles = stilesX * stilesY;
985
			final int tilesX = stilesX * superTileSize;
Andrey Filippov's avatar
Andrey Filippov committed
986
			final int tilesY = stilesY * superTileSize;
987 988 989 990 991 992 993 994
			final int nTiles =  nStiles * superTileSize * superTileSize;
			final TileData [][] tile_data = new TileData [nTiles][];
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
			final int ss2 = 2 * superTileSize;
			final int sh =  superTileSize/2;
			final int len2 = ss2  * ss2 ;
			final TileNeibs tileNeibs = new TileNeibs(2 * superTileSize);
995

Andrey Filippov's avatar
Andrey Filippov committed
996
			final int dbg_tile = dbg_Y * stilesX + dbg_X;
997

998 999 1000
			// initialize result structure
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
1001
					@Override
1002 1003
					public void run() {
						for (int nsTile = ai.getAndIncrement(); nsTile < nStiles; nsTile = ai.getAndIncrement()) {
Andrey Filippov's avatar
Andrey Filippov committed
1004 1005 1006 1007
							int dl = ((debugLevel > -1) && (nsTile == dbg_tile)) ? 3:0;
							if (dl > 0){
								System.out.println("createTileShells():1, nsTile = "+nsTile);
							}
1008 1009 1010 1011
							int num_surf = getTileSurfaceNumber ( // maximal number of surfaces in this supertile
									nsTile, // int nsTile,
									8, // int dir,              // direction, or -1 (same)
									0, // int np,
1012 1013 1014 1015
									planes); // TilePlanes.PlaneData [][] planes)
							if (num_surf > 0) { // 0 - nothing in this supertile, none around - remove
								if (num_surf > 0) { // 0 - nothing in this supertile, none around
									int stileY = nsTile / stilesX;
1016 1017 1018
									int stileX = nsTile % stilesX;
									for (int ty = 0; ty < superTileSize; ty++){
										for (int tx = 0; tx < superTileSize; tx++){
1019
											int indx = ((stileY * superTileSize) + ty) * tilesX + ((stileX * superTileSize) + tx);
1020 1021
											tile_data[indx] = new TileData[num_surf];
										}
1022

1023 1024 1025 1026 1027 1028
									}
								}
							}
						}
					}
				};
1029
			}
1030 1031 1032 1033 1034
			ImageDtt.startAndJoin(threads);

			ai.set(0);
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
1035
					@Override
1036 1037 1038
					public void run() {
						for (int nsTile = ai.getAndIncrement(); nsTile < nStiles; nsTile = ai.getAndIncrement()) {
							if (planes[nsTile] != null) {
Andrey Filippov's avatar
Andrey Filippov committed
1039 1040 1041 1042
								int dl = ((debugLevel > -1) && (nsTile == dbg_tile)) ? 3:0;
								if (dl > 0){
									System.out.println("createTileShells():2, nsTile = "+nsTile);
								}
1043
								int stileY = nsTile / stilesX;
1044
								int stileX = nsTile % stilesX;
1045 1046
//								for (int np = 0; np < planes[nsTile].length; np++) if (planes[nsTile][np] != null){
								for (int np = 0; np < planes[nsTile].length; np++) if ((planes[nsTile][np] != null) && (planes[nsTile][np].getWeight() > 0.0)){
1047

1048 1049 1050
									int [][][] src_mesh = lappingMeshes[nsTile][np];
									double [][] disp_strength = fusedSupertilePlanes[nsTile][np];
									TileData [] dual_mesh = new TileData [len2]; // full overlapping dual-sized mesh
Andrey Filippov's avatar
Andrey Filippov committed
1051 1052 1053 1054
									if ((planes == null) || (planes[nsTile] == null) || (planes[nsTile][np] == null)){
										System.out.println("createTileShells():2, *** NULL here***  nsTile = "+nsTile+" np="+np);
										continue;
									}
1055
									for (int indx = 0 ; indx < len2; indx++){
Andrey Filippov's avatar
Andrey Filippov committed
1056 1057 1058
										 // src_mesh non-null elements can only be generated by this supertile, while
										 // neighbor links can point to others (connected).
										 // others (connected) should have unique surface index based on their own planes ?
1059
										if (src_mesh[indx] != null){
Andrey Filippov's avatar
Andrey Filippov committed
1060 1061 1062
											if ((dl > 0) && ((indx & 15) == 0)){
												System.out.println("createTileShells():3, nsTile = "+nsTile+", indx="+indx);
											}
1063 1064 1065
											int [][] src_neibs = src_mesh[indx];
											if (src_neibs != null){
												int tsegm = tileNeibs.getSegment(indx);
Andrey Filippov's avatar
Andrey Filippov committed
1066 1067 1068
												int nsTile0 = getNStileDir(nsTile, tsegm);  // supertile over which this tile is
												if (    (tsegm < 0)    || // own tile (center square)
														(nsTile0 >= 0)) { // <0 - out of picture area
Andrey Filippov's avatar
Andrey Filippov committed
1069 1070 1071
													dual_mesh[indx] = new TileData( // now sets neighbors to -1
															disp_strength[0][indx],  // disparity
															disp_strength[1][indx]); // strength
1072 1073 1074
//													dual_mesh[indx].setParentNsTile(nsTile);
													dual_mesh[indx].setParentTileLayer(nsTile, np);
//													dual_mesh[indx].setParentPlane(planes[nsTile][np]);
1075

Andrey Filippov's avatar
Andrey Filippov committed
1076 1077 1078 1079 1080
													int dirThisfrom0 = getDirToStile(nsTile0, nsTile); // can be -1;
													int surf0 = getTileSurfaceNumber ( // Number of the surface for the tile itself
															nsTile0,      // int nsTile,
															dirThisfrom0, // int dir,              // direction, or -1 (same)
															np,           // int np,
1081
															planes);
Andrey Filippov's avatar
Andrey Filippov committed
1082
													dual_mesh[indx].setIndex(surf0);
1083

Andrey Filippov's avatar
Andrey Filippov committed
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
													for (int dir = 0; dir < 8; dir++) {
														if (src_neibs[dir] != null){
															int nsTile1 = src_neibs[dir][0];
															int np1 = src_neibs[dir][1];
															int indx1 = tileNeibs.getNeibIndex(indx,dir); // index of the destination tile
															// now find tile location - it may be outside of both nsTile and nsTile_1
															int segm1 = tileNeibs.getSegment(indx1);
															int nsTile2 = getNStileDir(nsTile, segm1);  // negative segm 1 is OK ?
															// now: nsTile - this supertile,
															// nsTile1 - to which supertile surface we switch
															// nsTile2 - non-overlapping supertile where the destination tile belongs
															// Unique surface number should be determined for nsTile2, generated by nsTile1,
															// for direction how nsTile1 is visible from the nsTile2
Andrey Filippov's avatar
Andrey Filippov committed
1097
															int dir1from2 = getDirToStile(nsTile2, nsTile1); // can be -1;
Andrey Filippov's avatar
Andrey Filippov committed
1098 1099 1100 1101
															int surf = getTileSurfaceNumber ( // maximal number of surfaces in this supertile
																	nsTile2,  // int nsTile,
																	dir1from2, // int dir,              // direction, or -1 (same)
																	np1, // int np,
1102
																	planes);
Andrey Filippov's avatar
Andrey Filippov committed
1103 1104
															dual_mesh[indx].setNeighbor(dir, surf);
														}
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
													}
												}
											}
										}
									}
									// Now we have a double-sized surface with all tiles set with correct absolute indices, now just split it
									//surf_number =
									for (int ty = 0; ty < ss2; ty++ ){
										for (int tx = 0; tx < ss2; tx++ ){
											int indx = ty * ss2 + tx;
Andrey Filippov's avatar
Andrey Filippov committed
1115 1116
											if (dual_mesh[indx] != null) { // some cells may be missing after merge
												int ix, iy;
Andrey Filippov's avatar
Andrey Filippov committed
1117
												ix = (stileX * superTileSize) + tx -sh; iy = (stileY * superTileSize) + ty -sh;
Andrey Filippov's avatar
Andrey Filippov committed
1118

Andrey Filippov's avatar
Andrey Filippov committed
1119 1120
												if ((ix >= 0) && (ix < tilesX) && (iy >= 0) && (iy < tilesX)) {
													int tindx = iy * tilesX + ix;
Andrey Filippov's avatar
Andrey Filippov committed
1121 1122
													tile_data[tindx][dual_mesh[indx].getIndex()] = dual_mesh[indx]; //oob
												}
1123 1124 1125 1126 1127 1128 1129 1130
											}
										}
									}
								}
							}
						}
					}
				};
1131
			}
1132 1133
			ImageDtt.startAndJoin(threads);
			return tile_data;
1134
		}
1135 1136 1137 1138 1139 1140 1141

		public TileData [][]  compactSortShells (
				final TileData [][]     tileData_src,
				final int               debugLevel,
				final int               dbg_X,
				final int               dbg_Y)
		{
1142 1143
			final int nStiles = stilesX * stilesY;
			final int nTiles =  nStiles * superTileSize * superTileSize;
1144 1145 1146
			final TileData [][] tile_data = new TileData [nTiles][];
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
Andrey Filippov's avatar
Andrey Filippov committed
1147 1148 1149
			final int dbg_stile = (dbg_Y * superTileSize) * (stilesX * superTileSize) + (dbg_X * superTileSize);
			final int dbg_tile = dbg_Y * stilesX + dbg_X;
			final int dbg_tilesX = stilesX * superTileSize;
1150 1151
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
1152
					@Override
1153 1154
					public void run() {
						for (int nTile = ai.getAndIncrement(); nTile < nTiles; nTile = ai.getAndIncrement()) {
1155
							int dbg_stX = nTile % dbg_tilesX;
Andrey Filippov's avatar
Andrey Filippov committed
1156 1157 1158 1159 1160 1161 1162
							int dbg_stY = nTile / dbg_tilesX;
							int dbg_st = (dbg_stY / superTileSize) * stilesX + (dbg_stX / superTileSize);
							int dl = ((debugLevel > -1) && (dbg_st == dbg_stile)) ? 3:0;
							if (dl > 0){
								System.out.println("compactSortShells():1, nTile = "+nTile+ ", nsTile = "+dbg_st);
							}
							int dls = ((debugLevel > -1) && (nTile == dbg_tile)) ? 3:0;
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
							if (tileData_src[nTile] != null){
								ArrayList<TileData> tdList = new ArrayList<TileData>();
								for (int nl = 0; nl < tileData_src[nTile].length; nl++){
									if (tileData_src[nTile][nl] != null){
										tdList.add(tileData_src[nTile][nl]);
									}
								}
								Collections.sort(tdList, new Comparator<TileData>() {
									@Override
									public int compare(TileData lhs, TileData rhs) {
										double lhs_d =lhs.getDisparity();
										double rhs_d =rhs.getDisparity();
										if (Double.isNaN(lhs_d) && Double.isNaN(rhs_d)) return 0;
										if (Double.isNaN(lhs_d)) return 1;
										if (Double.isNaN(rhs_d)) return -1;
										int sgn = (lhs.getDisparity() > rhs.getDisparity()) ? 1 : (lhs.getDisparity() < rhs.getDisparity() ) ? -1 : 0;
										return sgn;
									}
								});
								// increasing disparity
								for (int i = 0; i < tdList.size(); i++){
1184
									tdList.get(i).setNewIndex(i);
1185
								}
Andrey Filippov's avatar
Andrey Filippov committed
1186 1187 1188
								if (tdList.size() > 0) {
									tile_data[nTile] = tdList.toArray(new TileData[0] );
								}
1189 1190 1191 1192
							}
						}
					}
				};
1193
			}
1194 1195 1196 1197 1198
			ImageDtt.startAndJoin(threads);

			ai.set(0);
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
1199
					@Override
1200
					public void run() {
Andrey Filippov's avatar
Andrey Filippov committed
1201
						TileData [][]  tileData_src_dbg= tileData_src;
1202
						for (int nTile = ai.getAndIncrement(); nTile < nTiles; nTile = ai.getAndIncrement()) {
1203
							int dbg_stX = nTile % dbg_tilesX;
Andrey Filippov's avatar
Andrey Filippov committed
1204 1205 1206 1207 1208 1209
							int dbg_stY = nTile / dbg_tilesX;
							int dbg_st = (dbg_stY / superTileSize) * stilesX + (dbg_stX / superTileSize);
							int dl = ((debugLevel > -1) && (dbg_st == dbg_stile)) ? 3:0;
							if (dl > 0){
								System.out.println("compactSortShells():2, nTile = "+nTile+ ", nsTile = "+dbg_st);
							}
1210 1211 1212 1213 1214 1215
							if (tile_data[nTile] != null){
								for (int i = 0; i < tile_data[nTile].length; i++){
									int [] neibs = tile_data[nTile][i].getNeighbors();
									for (int dir = 0; dir < neibs.length; dir++){
										if (neibs[dir] >= 0){
											int nTile1 = getNtileDir(nTile, dir);
Andrey Filippov's avatar
Andrey Filippov committed
1216 1217
											if (nTile1 >= 0) {
												if ((tile_data[nTile1] == null) || (tileData_src[nTile1][neibs[dir]] == null)){
1218
													int dbg_sstile = tile_data[nTile][i].getParentNsTile();
1219
													int dbg_stileX = dbg_sstile % stilesX;
Andrey Filippov's avatar
Andrey Filippov committed
1220 1221 1222
													int dbg_stileY = dbg_sstile / stilesX;
													int dbg_tx = nTile % dbg_tilesX;
													int dbg_ty = nTile / dbg_tilesX;
1223 1224 1225
													int dbg_dx = dbg_tx - (superTileSize * dbg_stileX + superTileSize/2);
													int dbg_dy = dbg_ty - (superTileSize * dbg_stileY + superTileSize/2);

Andrey Filippov's avatar
Andrey Filippov committed
1226
													System.out.println("Null tile: "+nTile1+ " from "+nTile+", i="+i+", dir = "+dir+
Andrey Filippov's avatar
Andrey Filippov committed
1227 1228 1229 1230 1231
															", dbg_stX="+dbg_stX+", dbg_stY="+dbg_stY+", dbg_st="+dbg_st+", neibs[dir]="+neibs[dir]+
															" dbg_nsTile = "+dbg_sstile +" ("+dbg_stileX+":"+dbg_stileY+")"+
															" nTile="+nTile+" ("+dbg_tx+":"+dbg_ty+")"+
															", deltas from src center: "+dbg_dx+":"+dbg_dy);
													neibs[dir] = -1;
Andrey Filippov's avatar
Andrey Filippov committed
1232
												} else {
Andrey Filippov's avatar
Andrey Filippov committed
1233 1234
//													neibs[dir] = tile_data[nTile1][neibs[dir]].getNewIndex();
													neibs[dir] = tileData_src[nTile1][neibs[dir]].getNewIndex();
Andrey Filippov's avatar
Andrey Filippov committed
1235
												}
1236

1237 1238 1239 1240 1241 1242 1243 1244
											}
										}
									}
								}
							}
						}
					}
				};
1245
			}
1246 1247 1248
			ImageDtt.startAndJoin(threads);
			return tile_data;
		}
1249

1250

1251 1252 1253 1254 1255 1256
		public void  checkShellsConnections (
				final TileData [][]     tileData,
				final int               debugLevel,
				final int               dbg_X,
				final int               dbg_Y)
		{
1257 1258
			final int nStiles = stilesX * stilesY;
			final int nTiles =  nStiles * superTileSize * superTileSize;
1259 1260 1261 1262 1263 1264 1265 1266
//			final TileData [][] tile_data = new TileData [nTiles][];
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
			final int dbg_stile = (dbg_Y * superTileSize) * (stilesX * superTileSize) + (dbg_X * superTileSize);
//			final int dbg_tile = dbg_Y * stilesX + dbg_X;
			final int dbg_tilesX = stilesX * superTileSize;
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
1267
					@Override
1268 1269
					public void run() {
						for (int nTile = ai.getAndIncrement(); nTile < nTiles; nTile = ai.getAndIncrement()) {
1270 1271

							int dbg_stX = nTile % dbg_tilesX;
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
							int dbg_stY = nTile / dbg_tilesX;
							int dbg_st = (dbg_stY / superTileSize) * stilesX + (dbg_stX / superTileSize);
							int dl = ((debugLevel > -1) && (dbg_st == dbg_stile)) ? 3:0;
							if (dl > 0){
								System.out.println("checkShellsConnections(), nTile = "+nTile+ ", nsTile = "+dbg_st);
							}
							if (tileData[nTile] != null){
								for (int nl = 0; nl < tileData[nTile].length; nl++){
									if (tileData[nTile][nl] != null){
										int  [] neibs = tileData[nTile][nl].getNeighbors();
										for (int dir = 0; dir < neibs.length; dir++){
											if (neibs[dir] >= 0){
												int nTile1 = getNtileDir(nTile, dir);
												if (nTile1 >= 0) {
													if ((tileData[nTile1] == null) || (tileData[nTile1][neibs[dir]] == null)){
														if (debugLevel > -1) {
1288
															int dbg_sstile = tileData[nTile][nl].getParentNsTile();
1289
															int dbg_stileX = dbg_sstile % stilesX;
1290 1291 1292
															int dbg_stileY = dbg_sstile / stilesX;
															int dbg_tx = nTile % dbg_tilesX;
															int dbg_ty = nTile / dbg_tilesX;
1293 1294
															int dbg_dx = dbg_tx - (superTileSize * dbg_stileX + superTileSize/2);
															int dbg_dy = dbg_ty - (superTileSize * dbg_stileY + superTileSize/2);
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306

															System.out.println("Broken link: "+nTile1+ " from "+nTile+", nl="+nl+", dir = "+dir+
																	", dbg_stX="+dbg_stX+", dbg_stY="+dbg_stY+", dbg_st="+dbg_st+", neibs[dir]="+neibs[dir]+
																	" dbg_nsTile = "+dbg_sstile +" ("+dbg_stileX+":"+dbg_stileY+")"+
																	" nTile="+nTile+" ("+dbg_tx+":"+dbg_ty+")"+
																	", deltas from src center: "+dbg_dx+":"+dbg_dy);
														}
														neibs[dir] = -2; // was broken link
													} else { // check if link is mutual
														int [] neibs_other = tileData[nTile1][neibs[dir]].getNeighbors();
														if (neibs_other[(dir + 4) % 8] != nl){
															if (debugLevel > -1) {
1307
																int dbg_sstile = tileData[nTile][nl].getParentNsTile();
1308
																int dbg_stileX = dbg_sstile % stilesX;
1309 1310 1311
																int dbg_stileY = dbg_sstile / stilesX;
																int dbg_tx = nTile % dbg_tilesX;
																int dbg_ty = nTile / dbg_tilesX;
1312 1313
																int dbg_dx = dbg_tx - (superTileSize * dbg_stileX + superTileSize/2);
																int dbg_dy = dbg_ty - (superTileSize * dbg_stileY + superTileSize/2);
1314 1315 1316 1317 1318 1319 1320

																System.out.println("Link not mutual: "+nTile1+ " from "+nTile+", nl="+nl+", dir = "+dir+
																		", dbg_stX="+dbg_stX+", dbg_stY="+dbg_stY+", dbg_st="+dbg_st+", neibs[dir]="+neibs[dir]+
																		" dbg_nsTile = "+dbg_sstile +" ("+dbg_stileX+":"+dbg_stileY+")"+
																		" nTile="+nTile+" ("+dbg_tx+":"+dbg_ty+")"+
																		", deltas from src center: "+dbg_dx+":"+dbg_dy+
																		", neibs_other["+((dir + 4) % 8)+"]="+neibs_other[(dir + 4) % 8]+
1321
																		", dbg_nsTile other="+tileData[nTile1][neibs[dir]].getParentNsTile());
1322 1323 1324 1325 1326 1327 1328 1329 1330
															}
															neibs[dir] = -3; // not a mutual link (break only this side here)
														}
													}
												}
											}
										}
									}
								}
1331
							}
1332 1333 1334
						}
					}
				};
1335
			}
1336
			ImageDtt.startAndJoin(threads);
1337 1338
		}

1339 1340 1341 1342 1343 1344
		public void  addBackShellsConnections (
				final TileData [][]     tileData,
				final int               debugLevel,
				final int               dbg_X,
				final int               dbg_Y)
		{
1345 1346
			final int nStiles = stilesX * stilesY;
			final int nTiles =  nStiles * superTileSize * superTileSize;
1347 1348 1349 1350 1351 1352 1353 1354
//			final TileData [][] tile_data = new TileData [nTiles][];
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
			final int dbg_stile = (dbg_Y * superTileSize) * (stilesX * superTileSize) + (dbg_X * superTileSize);
//			final int dbg_tile = dbg_Y * stilesX + dbg_X;
			final int dbg_tilesX = stilesX * superTileSize;
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
1355
					@Override
1356 1357
					public void run() {
						for (int nTile = ai.getAndIncrement(); nTile < nTiles; nTile = ai.getAndIncrement()) {
1358 1359

							int dbg_stX = nTile % dbg_tilesX;
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
							int dbg_stY = nTile / dbg_tilesX;
							int dbg_st = (dbg_stY / superTileSize) * stilesX + (dbg_stX / superTileSize);
							int dl = ((debugLevel > -1) && (dbg_st == dbg_stile)) ? 3:0;
							if (dl > 0){
								System.out.println("checkShellsConnections(), nTile = "+nTile+ ", nsTile = "+dbg_st);
							}
							if (tileData[nTile] != null){
								for (int nl = 0; nl < tileData[nTile].length; nl++){
									if (tileData[nTile][nl] != null){
										int  [] neibs = tileData[nTile][nl].getNeighbors();
										for (int dir = 0; dir < neibs.length; dir++){
											if (neibs[dir] >= 0){
												int nTile1 = getNtileDir(nTile, dir);
												if (nTile1 >= 0) {
													if ((tileData[nTile1] == null) || (tileData[nTile1][neibs[dir]] == null)){
														if (debugLevel > 0) {
1376
															int dbg_sstile = tileData[nTile][nl].getParentNsTile();
1377
															int dbg_stileX = dbg_sstile % stilesX;
1378 1379 1380
															int dbg_stileY = dbg_sstile / stilesX;
															int dbg_tx = nTile % dbg_tilesX;
															int dbg_ty = nTile / dbg_tilesX;
1381 1382
															int dbg_dx = dbg_tx - (superTileSize * dbg_stileX + superTileSize/2);
															int dbg_dy = dbg_ty - (superTileSize * dbg_stileY + superTileSize/2);
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394

															System.out.println("Broken link: "+nTile1+ " from "+nTile+", nl="+nl+", dir = "+dir+
																	", dbg_stX="+dbg_stX+", dbg_stY="+dbg_stY+", dbg_st="+dbg_st+", neibs[dir]="+neibs[dir]+
																	" dbg_nsTile = "+dbg_sstile +" ("+dbg_stileX+":"+dbg_stileY+")"+
																	" nTile="+nTile+" ("+dbg_tx+":"+dbg_ty+")"+
																	", deltas from src center: "+dbg_dx+":"+dbg_dy);
														}
//														neibs[dir] = -2; // was broken link
													} else { // check if link is mutual
														int [] neibs_other = tileData[nTile1][neibs[dir]].getNeighbors();
														if (neibs_other[(dir + 4) % 8] != nl){
															if (debugLevel > 0) {
1395
																int dbg_sstile = tileData[nTile][nl].getParentNsTile();
1396
																int dbg_stileX = dbg_sstile % stilesX;
1397 1398 1399
																int dbg_stileY = dbg_sstile / stilesX;
																int dbg_tx = nTile % dbg_tilesX;
																int dbg_ty = nTile / dbg_tilesX;
1400 1401
																int dbg_dx = dbg_tx - (superTileSize * dbg_stileX + superTileSize/2);
																int dbg_dy = dbg_ty - (superTileSize * dbg_stileY + superTileSize/2);
1402 1403 1404 1405 1406 1407 1408

																System.out.println("Link not mutual: "+nTile1+ " from "+nTile+", nl="+nl+", dir = "+dir+
																		", dbg_stX="+dbg_stX+", dbg_stY="+dbg_stY+", dbg_st="+dbg_st+", neibs[dir]="+neibs[dir]+
																		" dbg_nsTile = "+dbg_sstile +" ("+dbg_stileX+":"+dbg_stileY+")"+
																		" nTile="+nTile+" ("+dbg_tx+":"+dbg_ty+")"+
																		", deltas from src center: "+dbg_dx+":"+dbg_dy+
																		", neibs_other["+((dir + 4) % 8)+"]="+neibs_other[(dir + 4) % 8]+
1409
																		", dbg_nsTile other="+tileData[nTile1][neibs[dir]].getParentNsTile());
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
															}
															if (neibs_other[(dir + 4) % 8] < 0 ){
																neibs_other[(dir + 4) % 8] = nl; // adding back link instead of missing one
															} else {
																int nTile2 = getNtileDir(nTile1, (dir + 4) % 8);
																if (    (nTile2 < 0) ||
																		(tileData[nTile2] == null) ||
																		(tileData[nTile2][neibs_other[(dir + 4) % 8]] == null)) {
																	neibs_other[(dir + 4) % 8] = nl; // adding back link instead of broken one
																}
															}
														}
													}
												}
											}
										}
									}
								}
1428
							}
1429 1430 1431
						}
					}
				};
1432
			}
1433
			ImageDtt.startAndJoin(threads);
1434 1435 1436 1437 1438 1439
		}





1440

1441 1442 1443 1444 1445
		public int getTileLayersNumber (
				final TileData [][] tileData)
		{
			int num = 0;
			for (int i = 0; i < tileData.length; i++){
1446
				if ((tileData[i] != null) && (tileData[i].length > num )){
1447
					num  = tileData[i].length;
1448 1449 1450 1451 1452
				}
			}
			return num;
		}

1453 1454 1455 1456 1457
		public int [] getTilesWH()
		{
			int [] wh = {stilesX*superTileSize, stilesY*superTileSize};
			return wh;
		}
1458

1459 1460 1461 1462
		public double [][][] getTileDisparityStrengths (
				final TileData [][] tileData,
				final boolean useNaN)
		{
1463 1464
			final int nStiles = stilesX * stilesY;
			final int nTiles =  nStiles * superTileSize * superTileSize;
1465 1466 1467 1468 1469 1470
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
			final int numLayers = getTileLayersNumber(tileData);
			final double [][][] disp_strength = new double [numLayers][2][tileData.length];
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
1471
					@Override
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
					public void run() {
						for (int nTile = ai.getAndIncrement(); nTile < nTiles; nTile = ai.getAndIncrement()) {
							if (tileData[nTile] != null){
								for (int nl = 0; nl < tileData[nTile].length; nl++) if (tileData[nTile][nl]!=null){ // only beforfe compacting
									disp_strength[nl][0][nTile] = tileData[nTile][nl].getDisparity(useNaN);
									disp_strength[nl][1][nTile] = tileData[nTile][nl].getStrength();
								}
								if (useNaN){
									for (int nl = tileData[nTile].length; nl < numLayers; nl++){
										disp_strength[nl][0][nTile] = Double.NaN;
									}
								}
							} else if (useNaN){
								for (int nl = 0; nl < numLayers; nl++){
									disp_strength[nl][0][nTile] = Double.NaN;
								}
							}
						}
					}
				};
1492
			}
1493 1494 1495 1496 1497 1498
			ImageDtt.startAndJoin(threads);
			return disp_strength;
		}
		public int [][][] getTileConnections (
				final TileData [][] tileData)
		{
1499 1500
			final int nStiles = stilesX * stilesY;
			final int nTiles =  nStiles * superTileSize * superTileSize;
1501 1502 1503 1504 1505 1506
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
			final int numLayers = getTileLayersNumber(tileData);
			final int [][][] connections = new int [numLayers][tileData.length][8];
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
1507
					@Override
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
					public void run() {
						for (int nTile = ai.getAndIncrement(); nTile < nTiles; nTile = ai.getAndIncrement()) {
							if (tileData[nTile] != null) {
								for (int nl = 0; nl < tileData[nTile].length; nl++) if (tileData[nTile][nl] != null) {
									for (int indx = 0 ; indx < tileData.length; indx++){
										for (int dir = 0; dir < 8; dir ++){
											if (tileData[nTile][nl].getNeighbor(dir) >= 0){
												connections[nl][nTile][dir] = tileData[nTile][nl].getNeighbor(dir)+1;
											}
										}
									}
								}
							}
						}
					}
				};
1524
			}
1525 1526 1527
			ImageDtt.startAndJoin(threads);
			return connections;
		}
1528 1529 1530 1531

		public int [][] getTileGenerator (
				final TileData [][] tileData)
		{
1532 1533
			final int nStiles = stilesX * stilesY;
			final int nTiles =  nStiles * superTileSize * superTileSize;
1534 1535 1536 1537 1538 1539
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
			final int numLayers = getTileLayersNumber(tileData);
			final int [][] generators = new int [numLayers][tileData.length];
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
1540
					@Override
1541 1542 1543 1544 1545
					public void run() {
						for (int nTile = ai.getAndIncrement(); nTile < nTiles; nTile = ai.getAndIncrement()) {
							if (tileData[nTile] != null) {
								for (int nl = 0; nl < tileData[nTile].length; nl++) if (tileData[nTile][nl] != null) {
									for (int indx = 0 ; indx < tileData.length; indx++){
1546
										generators[nl][nTile] = tileData[nTile][nl].getParentNsTile();
1547 1548 1549 1550 1551 1552
									}
								}
							}
						}
					}
				};
1553
			}
1554 1555 1556 1557 1558 1559
			ImageDtt.startAndJoin(threads);
			return generators;
		}
		public int [] getNumSurfaces (
				final TileData [][] tileData)
		{
1560 1561
			final int nStiles = stilesX * stilesY;
			final int nTiles =  nStiles * superTileSize * superTileSize;
1562 1563 1564 1565 1566
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
			final int [] surfaces = new int [tileData.length];
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
1567
					@Override
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
					public void run() {
						for (int nTile = ai.getAndIncrement(); nTile < nTiles; nTile = ai.getAndIncrement()) {
							if (tileData[nTile] != null) {
								for (int nl = 0; nl < tileData[nTile].length; nl++) if (tileData[nTile][nl] != null) {
									surfaces[nTile] ++;
								}
							}
						}
					}
				};
1578
			}
1579 1580 1581
			ImageDtt.startAndJoin(threads);
			return surfaces;
		}
1582 1583


1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
		public void showSurfaceDS (
				TileData [][] tileData,
				String title)
		{
			int [] wh = getTilesWH();
			double [][][] tds =  getTileDisparityStrengths (
					tileData,
					false); // useNaN);
			double [][][] tds_nan =  getTileDisparityStrengths (
					tileData,
					true); // useNaN);
			int [][] generators = getTileGenerator(tileData);
			int [] surfaces = getNumSurfaces (tileData);


			String [] titles = new String [5 * tds.length + 1];
			double [][] img_data = new double [titles.length][];
			for (int i = 0; i <tds.length; i++){
				titles[i + 0 * tds.length] = "disp_"+i;
				titles[i + 1 * tds.length] = "str_"+i;
				titles[i + 2 * tds.length] = "mdisp_"+i;
				titles[i + 3 * tds.length] = "mstr_"+i;
				titles[i + 4 * tds.length] = "gen_"+i;
				img_data[i + 0 * tds.length] = tds[i][0];
				img_data[i + 1 * tds.length] = tds[i][1];
				img_data[i + 2 * tds.length] = tds_nan[i][0];
				img_data[i + 3 * tds.length] = tds_nan[i][1];
				img_data[i + 4 * tds.length] = new double [generators[i].length];
				for (int j = 0; j < generators[i].length; j++){
					img_data[i + 4 * tds.length][j] = 0.01*generators[i][j];
				}
			}
			titles[5 * tds.length] = "layers";
			img_data[5 * tds.length] = new double [surfaces.length];
			for (int j = 0; j < surfaces.length; j++){
				img_data[5 * tds.length][j] =surfaces[j];
			}
1621
			ShowDoubleFloatArrays.showArrays(img_data,  wh[0], wh[1], true, title, titles);
1622
		}
1623

1624 1625 1626 1627
		/**
		 * Calculate per-tile surface data (TileData) including disparity, strength, and 8 neighbors indices
		 * @param use_sel use plane selection (this.sel_mask) to select only some part of the plane
		 * @param divide_by_area divide weights by ellipsoid area
1628
		 * @param scale_projection use plane ellipsoid projection for weight: 0 - do not use, > 0 linearly
1629
		 *                         scale ellipsoid (enlarge)
1630
		 * @param fraction_uni add fraction of the total weight to each tile
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
		 * @param planes array of the per-supertile, per plane plane data (each level can be null)
		 * @param debugLevel debug level
		 * @param dbg_X debug supertile X coordinate
		 * @param dbg_Y debug supertile Y coordinate
		 * @return per-tile (rounded up to contain whole supertiles) array of TileData instances
		 */
		public TileData [][] createTileShells (
				final boolean                   use_sel,
				final boolean                   divide_by_area,
				final double                    scale_projection,
1641
				final double                    fraction_uni,
1642 1643 1644 1645 1646 1647
				final TilePlanes.PlaneData [][] planes,
				final int                       debugLevel,
				final int                       dbg_X,
				final int                       dbg_Y)
		{

1648
			double [][][][] fused_planes = fuseSupertilePlanes ( // some planes have zero weight that still participate - should they be eliminated?
1649 1650 1651
					use_sel,           // final boolean                   use_sel,
					divide_by_area,    // final boolean                   divide_by_area,
					scale_projection,  // final double                    scale_projection,
1652
					fraction_uni,      // final double                    fraction_uni,
1653 1654 1655 1656
					planes,            // final TilePlanes.PlaneData [][] planes,
					debugLevel,        // final int                       debugLevel,
					dbg_X,             // final int                       dbg_X,
					dbg_Y);            // final int                       dbg_Y);
1657

1658 1659 1660 1661 1662 1663 1664
			int [][][][] surf_topology = getSupertilesTopology (
					planes,            // final TilePlanes.PlaneData [][] planes,
					debugLevel,        // final int                       debugLevel,
					dbg_X,             // final int                       dbg_X,
					dbg_Y);            // final int                       dbg_Y);
			int [][][][][] overlapped_meshes = generateOverlappingMeshes (
					planes,            // final TilePlanes.PlaneData [][] planes,
1665
					surf_topology ,    // final int [][][][]              corners,
1666 1667 1668 1669 1670 1671
					debugLevel,        // final int                       debugLevel,
					dbg_X,             // final int                       dbg_X,
					dbg_Y);            // final int                       dbg_Y);
			TileData [][] tileData = createTileShells (
					planes,            // final TilePlanes.PlaneData [][] planes,
					fused_planes,      // final double [][][][]           fusedSupertilePlanes,
1672
					overlapped_meshes, // final int [][][][][]            lappingMeshes,
1673 1674 1675
					debugLevel,        // final int                       debugLevel,
					dbg_X,             // final int                       dbg_X,
					dbg_Y);            // final int                       dbg_Y);
1676 1677 1678 1679 1680 1681
			System.out.println("addBackShellsConnections()");
			addBackShellsConnections (
					tileData,          // final TileData [][]     tileData_src,
					debugLevel,        // final int                       debugLevel,
					dbg_X,             // final int                       dbg_X,
					dbg_Y);            // final int                       dbg_Y);
1682
//
1683 1684 1685 1686 1687 1688
			System.out.println("checkShellsConnections()");
			checkShellsConnections (
					tileData,          // final TileData [][]     tileData_src,
					debugLevel,        // final int                       debugLevel,
					dbg_X,             // final int                       dbg_X,
					dbg_Y);            // final int                       dbg_Y);
1689 1690 1691 1692 1693
			tileData = compactSortShells (
					tileData,          // final TileData [][]     tileData_src,
					debugLevel,        // final int                       debugLevel,
					dbg_X,             // final int                       dbg_X,
					dbg_Y);            // final int                       dbg_Y);
1694
			if (debugLevel >- 2) {
1695 1696
				showSurfaceDS (tileData, "tileData");
			}
1697
			this.tileData = tileData;
1698 1699
			return tileData;
		}
1700

1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
		public int [] getTilesAssignStats(
				final int [][] tileLayers)
		{
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final int numThreads = threads.length;
			int [] stats = new int [STAT_LEN];
			final int [][] stats_all = new int [numThreads][STAT_LEN];
			final AtomicInteger ai_numThread = new AtomicInteger(0);
			final AtomicInteger ai = new AtomicInteger(0);
			for (int ml = 0; ml < tileLayers.length; ml++) if (tileLayers[ml] != null){
				final int fml = ml;
				ai_numThread.set(0);
				ai.set(0);
				for (int ithread = 0; ithread < threads.length; ithread++) {
					threads[ithread] = new Thread() {
1716
						@Override
1717 1718 1719 1720
						public void run() {
							int numThread = ai_numThread.getAndIncrement(); // unique number of thread to write to rslt_diffs[numThread]
							for (int nTile = ai.getAndIncrement(); nTile < tileLayers[fml].length; nTile = ai.getAndIncrement()) {
								if (tileLayers[fml][nTile] > 0){ // index + 1
1721
									stats_all[numThread][STAT_ASSIGNED] ++;
1722
								} else if (tileLayers[fml][nTile] == UNASSIGNED) {
1723
									stats_all[numThread][STAT_UNASSIGNED] ++;
1724
								} else if (tileLayers[fml][nTile] == PROHOBITED) {
1725
									stats_all[numThread][STAT_PROHIBITED] ++;
1726
								} else if (tileLayers[fml][nTile] == IMPOSSIBLE) {
1727
									stats_all[numThread][STAT_IMPOSSIBLE] ++;
1728 1729
								} else {
									System.out.println("Bug in getTilesAssignStats(): tileLayers["+fml+"]["+nTile+"]="+tileLayers[fml][nTile]);
1730
									stats_all[numThread][0] ++; // prohibited
1731 1732 1733 1734
								}
							}
						}
					};
1735
				}
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
				ImageDtt.startAndJoin(threads);
				stats[STAT_NUM_ML]++; // number of non-null measurement layers
			}
			for (int nt = 0; nt < numThreads; nt ++){
				for (int i = 0 ; i < stats.length; i++ ){
					stats[i] += stats_all[nt][i];
				}
			}
			return stats;
		}
1746

1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
		public double getNormDispFromSurface(
				double disp_tile,
				double disp_surf,
				double disp_norm)
		{
			double disp_avg = 0.5 * (disp_tile + disp_surf);
			if (disp_avg <= disp_norm){
				return disp_tile - disp_surf;
			} else {
				return (disp_tile - disp_surf) * disp_norm / disp_avg;
			}
		}
1759

1760
		/**
1761 1762
		 * Convert from image tile index to the surface tile index (surface tiles are all
		 * full superTileSize),
1763 1764 1765 1766 1767 1768 1769 1770 1771
		 * TODO: update/remove if surface grid will be trimmed to fit image
		 * Currently there are 324 tiles horizontally in the image and 328 in the surfaces
		 * @param nTile image tile index in scan order
		 * @return surface tile index in scan order
		 */
		public int getSurfaceTileIndex(
				int nTile)
		{
			// calculate index in tileData (has different dimensions - TODO: trim?
1772 1773
			int surfaceTilesX = stilesX * superTileSize;
			return surfaceTilesX * (nTile /  imageTilesX) + (nTile %  imageTilesX);
1774
		}
1775

1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
		/**
		 * Convert from image tile index to the surface supertile index (surface tiles are all
		 * full superTileSize),
		 * TODO: update/remove if surface grid will be trimmed to fit image
		 * Currently there are 324 tiles horizontally in the image and 328 in the surfaces
		 * @param nTile image tile index in scan order
		 * @return surface tile index in scan order
		 */
		public int getSurfaceSuperTileIndex(
				int nTile)
		{
			// calculate index in tileData (has different dimensions - TODO: trim?
//			int surfaceTilesX = stilesX * superTileSize;
//			return surfaceTilesX * (nTile /  imageTilesX) + (nTile %  imageTilesX);
			return stilesX * (nTile /  imageTilesX / superTileSize) + (nTile %  imageTilesX)/superTileSize;
		}


1794 1795


1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
		/**
		 * Convert from  surface tile index (surface tiles are all full superTileSize) to
		 * the image tile index
		 * TODO: update/remove if surface grid will be trimmed to fit image
		 * Currently there are 324 tiles horizontally in the image and 328 in the surfaces
		 * @param nSurfTile surface tile index in scan order
		 * @return image tile index in scan order or -1 if outside of the image tiles
		 */
		public int getImageTileIndex(
				int nSurfTile)
		{
			// calculate index in tileData (has different dimensions - TODO: trim?
			int surfaceTilesX = stilesX * superTileSize;
			int tx = nSurfTile %  surfaceTilesX;
			int ty = nSurfTile /  surfaceTilesX;
1811
			if ((tx >= imageTilesX) || (ty >= imageTilesY)){
1812 1813 1814 1815
				return -1; // out of image
			}
			return imageTilesX * ty + tx;
		}
1816

1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
		/**
		 * Grow around surface tile, without going back. May still produce multi-layer result
		 * that will need to be filtered. Used to fill large flat gaps
		 * @param nsTile0
		 * @param nl0
		 * @return
		 */
		public boolean [][] growSimpleConnected(
				int nsTile0,
				int nl0)
		{
			int tilesX = stilesX * superTileSize;
			if ((tileData[nsTile0] == null) || (tileData[nsTile0][nl0] == null)){
				return null; // error
			}
			TileNeibs tnSurface = new TileNeibs(stilesX * superTileSize, stilesY * superTileSize);
			boolean [][] simple_surf = new boolean [tileData.length][];
			int x0 = nsTile0 % tilesX;
			int y0 = nsTile0 / tilesX;
			ArrayList<Point> wave_list = new ArrayList<Point>();
			simple_surf[nsTile0] = new boolean [tileData[nsTile0].length];
			simple_surf[nsTile0][nl0] = true;
			wave_list.add(new Point(nsTile0, nl0));
			while (!wave_list.isEmpty()){
				Point p = wave_list.remove(0);
				int nsTile = p.x;
				int nl = p.y;
				int x = nsTile % tilesX;
				int y = nsTile / tilesX;
				int dirs = 0xff;
				if      (x > x0) dirs &= 0x1f;
				else if (x < x0) dirs &= 0xf1;
				if      (y > y0) dirs &= 0x7c;
				else if (y < y0) dirs &= 0xc7;
				int [] neibs = tileData[nsTile][nl].getNeighbors();
				for (int dir = 0; dir < neibs.length; dir ++) {
					int nl1 = neibs[dir];
					if ((nl1 >= 0) && ((dirs & (1 << dir)) != 0)){
						int nsTile1 = tnSurface.getNeibIndex(nsTile, dir);
						if ((nsTile1 >= 0) && ((simple_surf[nsTile1] == null) || !simple_surf[nsTile1][nl1])){
							if (simple_surf[nsTile1] == null) {
								simple_surf[nsTile1] = new boolean [tileData[nsTile1].length];
							}
							simple_surf[nsTile1][nl1] = true;
							wave_list.add(new Point(nsTile1, nl1));
						}
					}
				}
			}
			return simple_surf;
		}

		public int [][] growSimpleIConnected(
				int nsTile0,
				int nl0)
		{
			int tilesX = stilesX * superTileSize;
			if ((tileData[nsTile0] == null) || (tileData[nsTile0][nl0] == null)){
				return null; // error
			}
			TileNeibs tnSurface = new TileNeibs(stilesX * superTileSize, stilesY * superTileSize);
			int [][] simple_surf = new int [tileData.length][];
			int x0 = nsTile0 % tilesX;
			int y0 = nsTile0 / tilesX;
			ArrayList<Point> wave_list = new ArrayList<Point>();
			simple_surf[nsTile0] = new int [tileData[nsTile0].length];
			simple_surf[nsTile0][nl0] = 1;
			wave_list.add(new Point(nsTile0, nl0));
			while (!wave_list.isEmpty()){
				Point p = wave_list.remove(0);
				int nsTile = p.x;
				int nl = p.y;
				int x = nsTile % tilesX;
				int y = nsTile / tilesX;
				int dirs = 0xff;
				if      (x > x0) dirs &= 0x1f;
				else if (x < x0) dirs &= 0xf1;
				if      (y > y0) dirs &= 0x7c;
				else if (y < y0) dirs &= 0xc7;
				int [] neibs = tileData[nsTile][nl].getNeighbors();
				for (int dir = 0; dir < neibs.length; dir ++) {
					int nl1 = neibs[dir];
					if ((nl1 >= 0) && ((dirs & (1 << dir)) != 0)){
						int nsTile1 = tnSurface.getNeibIndex(nsTile, dir);
						if ((nsTile1 >= 0) && ((simple_surf[nsTile1] == null) || (simple_surf[nsTile1][nl1] == 0))){
							if (simple_surf[nsTile1] == null) {
								simple_surf[nsTile1] = new int [tileData[nsTile1].length];
							}
							simple_surf[nsTile1][nl1] = simple_surf[nsTile][nl]+1;
							wave_list.add(new Point(nsTile1, nl1));
						}
					}
				}
			}
			return simple_surf;
		}
1913 1914 1915



1916 1917 1918 1919 1920 1921 1922 1923 1924
		public double [][] getShowSimpleConnected(
				int          nsTile0,
				boolean [][] simple_surf)
		{
			int numSurfaces = 1;
			for (int nsTile = 0; nsTile < simple_surf.length; nsTile++){
				if (simple_surf[nsTile] != null){
					int num_filled = 0;
					for (int i = 0; i < simple_surf[nsTile].length; i++) if (simple_surf[nsTile][i]) num_filled++;
1925
					if (num_filled > numSurfaces) numSurfaces = num_filled;
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
				}
			}
			double [][] img_data = new double [numSurfaces][tileData.length];
			for (int nsTile = 0; nsTile < tileData.length; nsTile++){
				if (simple_surf[nsTile] != null){
					int ns = 0;
					for (int nl = 0; nl < simple_surf[nsTile].length; nl++) if (simple_surf[nsTile][nl]){
						img_data[ns][nsTile] = tileData[nsTile][nl].getDisparity();
						ns++;
					}
					for (; ns < numSurfaces; ns++) img_data[ns][nsTile] = Double.NaN;
				} else {
					for (int ns = 0; ns < numSurfaces; ns++) img_data[ns][nsTile] = Double.NaN;
				}
			}
			// mark start point:
			for (int ns = 0; ns < numSurfaces; ns++) img_data[ns][nsTile0] = Double.NaN;
			return img_data;
		}
		public double [][] getShowSimpleConnected(
				int          nsTile0,
				int [][] simple_surf)
		{
			int numSurfaces = 1;
			for (int nsTile = 0; nsTile < simple_surf.length; nsTile++){
				if (simple_surf[nsTile] != null){
					int num_filled = 0;
					for (int i = 0; i < simple_surf[nsTile].length; i++) if (simple_surf[nsTile][i] !=0) num_filled++;
1954
					if (num_filled > numSurfaces) numSurfaces = num_filled;
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
				}
			}
			double [][] img_data = new double [numSurfaces][tileData.length];
			for (int nsTile = 0; nsTile < tileData.length; nsTile++){
				if (simple_surf[nsTile] != null){
					int ns = 0;
					for (int nl = 0; nl < simple_surf[nsTile].length; nl++) if (simple_surf[nsTile][nl] != 0){
						img_data[ns][nsTile] = tileData[nsTile][nl].getDisparity();
						ns++;
					}
					for (; ns < numSurfaces; ns++) img_data[ns][nsTile] = Double.NaN;
				} else {
					for (int ns = 0; ns < numSurfaces; ns++) img_data[ns][nsTile] = Double.NaN;
				}
			}
			// mark start point:
			for (int ns = 0; ns < numSurfaces; ns++) img_data[ns][nsTile0] = Double.NaN;
			return img_data;
		}

		public double [][] getShowSimpleConnectedDistanceLayer(
				boolean show_distance, // false - layer number
				int [][] simple_surf)
		{
			int numSurfaces = 1;
			for (int nsTile = 0; nsTile < simple_surf.length; nsTile++){
				if (simple_surf[nsTile] != null){
					int num_filled = 0;
					for (int i = 0; i < simple_surf[nsTile].length; i++) if (simple_surf[nsTile][i] !=0) num_filled++;
1984
					if (num_filled > numSurfaces) numSurfaces = num_filled;
1985 1986 1987 1988 1989 1990 1991
				}
			}
			double [][] img_data = new double [numSurfaces][tileData.length];
			for (int nsTile = 0; nsTile < simple_surf.length; nsTile++){
				if (simple_surf[nsTile] != null){
					int ns = 0;
					for (int nl = 0; nl < simple_surf[nsTile].length; nl++) if (simple_surf[nsTile][nl] != 0){
1992

1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
						img_data[ns][nsTile] = show_distance? simple_surf[nsTile][nl]: nl;
						ns++;
					}
					for (; ns < numSurfaces; ns++) img_data[ns][nsTile] = Double.NaN;
				} else {
					for (int ns = 0; ns < numSurfaces; ns++) img_data[ns][nsTile] = Double.NaN;
				}
			}
			return img_data;
		}

2004 2005


2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
		public void testSimpleConnected(
				int tileX,
				int tileY)
		{
			testSimpleConnected(stilesX * superTileSize * tileY+ tileX);
			printSurfaceConnections(
					tileX - 7, // int left,
					tileY - 7, // int top,
					15,        // int width,
					15,        // int height,
					1,         // int extraH,
					1);        // int extraV)
2018

2019
		}
2020 2021


2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
		public void testSimpleConnected(
				int nsTile)
		{
			double [][][] data =  new double [tileData[nsTile].length][][];
			double [][][] dist =  new double [tileData[nsTile].length][][];
			double [][][] layer = new double [tileData[nsTile].length][][];
			int [][][] simple_surf = new int [tileData[nsTile].length][][];
			int num_layers = 0;
			for (int nl = 0; nl < tileData[nsTile].length; nl++) if (tileData[nsTile][nl] != null) {
				simple_surf[nl] = growSimpleIConnected(nsTile, nl);
				data[nl] =  getShowSimpleConnected(nsTile, simple_surf[nl]);
				dist[nl] =  getShowSimpleConnectedDistanceLayer(true,simple_surf[nl]);
				layer[nl] = getShowSimpleConnectedDistanceLayer(false,simple_surf[nl]);
2035
				num_layers += data[nl].length;
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
			}
			double [][] img_data = new double [num_layers * 3][];
			String [] titles = new String [num_layers * 3];
			int indx = 0;
			for (int nl = 0; nl < data.length; nl++) if (data[nl] != null) {
				for (int i = 0; i < data[nl].length; i++){
					titles[indx + 0 * num_layers] = ""+nl+((data[nl].length>1)?(":"+i):"");
					titles[indx + 1 * num_layers] = "dist"+nl+((data[nl].length>1)?(":"+i):"");
					titles[indx + 2 * num_layers] = "layer"+nl+((data[nl].length>1)?(":"+i):"");
					img_data[indx + 0 * num_layers]= data[nl][i];
					img_data[indx + 1 * num_layers]= dist[nl][i];
					img_data[indx + 2 * num_layers]= layer[nl][i];
					indx++;
				}
			}
2051
			ShowDoubleFloatArrays.showArrays(img_data,   stilesX * superTileSize,  stilesY * superTileSize, true, "simple_"+nsTile, titles);
2052
		}
2053

2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
		public void printSurfaceConnections(
				int left,
				int top,
				int width,
				int height,
				int extraH,
				int extraV)
		{
			int tilesX = stilesX * superTileSize;
			int numSurfaces = 0;
	 			for (int tileY = top; tileY < (top + height); tileY++) {
				for (int tileX = left; tileX < (left + width); tileX++) {
					int nsTile = tileY * tilesX + tileX;
					if (tileData[nsTile] != null){
2068
						if (tileData[nsTile].length > numSurfaces) numSurfaces = tileData[nsTile].length;
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
					}
				}
			}
 			String hor_gap = "";
 			for (int i = 0; i < extraH; i++) hor_gap += " ";
 			String vert_gap = "";
 			for (int i = 0; i < extraV; i++) vert_gap += "\n";
 			for (int ns = 0; ns < numSurfaces; ns++){
 				System.out.println("\n ===== Surface number:"+ns+" =====");
 	 			for (int tileY = top; tileY < (top + height); tileY++) {
 	 				for (int l = 0; l < 3; l++){
 	 					for (int tileX = left; tileX < (left + width); tileX++) {
 	 						int nsTile = tileY * tilesX + tileX;
 	 						if ((tileData[nsTile]!= null) && (tileData[nsTile].length > ns) && (tileData[nsTile][ns] != null)){
 	 							int [] neibs = tileData[nsTile][ns].getNeighbors();
2084
 	 							int master_st = tileData[nsTile][ns].getParentNsTile();
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
 	 							switch (l){
 	 							case 0: System.out.print(" "+
 	 									((neibs[7] >= 0)?neibs[7]:" ")+
 	 									((neibs[0] >= 0)?neibs[0]:" ")+
 	 									((neibs[1] >= 0)?neibs[1]:" ")+" ");
 	 							break;
 	 							case 1: System.out.print(""+
 	 									((neibs[6] >= 0)?neibs[6]:" ")+
 	 									((master_st % stilesX) % 10)+
 	 									("*")+
 	 									((master_st / stilesX) % 10)+
 	 									((neibs[2] >= 0)?neibs[2]:" "));
 	 							break;
 	 							case 2: System.out.print(" "+
 	 									((neibs[5] >= 0)?neibs[5]:" ")+
 	 									((neibs[4] >= 0)?neibs[4]:" ")+
 	 									((neibs[3] >= 0)?neibs[3]:" ")+" ");
 	 							break;
 	 							}
 	 						} else {
 	 							switch (l){
 	 							case 0:
 	 							case 2: System.out.print("     "); break;
 	 							case 1: System.out.print("  .  "); break;
 	 							}
 	 						}
 	 						if (tileX < (left + width -1)){
 	 							System.out.print(hor_gap);
 	 						} else {
 	 							System.out.println();
 	 						}
2116
 	 					}
2117 2118 2119 2120 2121 2122 2123
 	 				}
 	 				if (tileY < (top + height -1)){
 	 					System.out.print(vert_gap);
 	 				}
 	 			}
 			}
		}
2124

2125 2126
		/**
		 * Assign tiles to a certain disparity surface if there is only one surface candidate
2127
		 * @param noEdge do not assign tiles to the surface edges (can not add border later)
2128 2129
		 * @param maxDiff maximal (normalized) disparity difference
		 * @param minDiffOther minimal disparity difference to closest 2-nd place candidate
2130
		 * @param minStrength minimal processed (floor subtracted) correlation strength of the candidate
2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
		 * @param maxStrength maximal processed (floor subtracted) correlation strength of the candidate
		 * @param moveDirs +1 - allow moving tile closer to the camera (increase disparity, +2 - allow moving away
		 * @param dispNorm disparity normalization - disparity difference with average above it will be scaled down
		 * @param tileLayers measured tiles assignment (will be modified): -1 - prohibited, 0 - unassigned,
		 * >0 - number of surface where this tile is assigned plus 1.
		 * @param tileData per-tile, per layer array of TileData objects specifying surfaces to snap to
		 * @param dispStrength per measurement layer, combined disparity and strength array ([num_ml [2][])
		 * @param debugLevel debug level
		 * @param dbg_X debug tile X coordinate
		 * @param dbg_Y debug tile Y coordinate
2141
		 * @return
2142
		 */
2143
		public int [] assignTilesToSingleCandidate_old( // not used
2144
				final boolean       noEdge,
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
				final double        maxDiff,
				final double        minDiffOther,
				final double        minStrength,
				final double        maxStrength,
				final int           moveDirs, // 1 increase disparity, 2 - decrease disparity, 3 - both directions
				final double        dispNorm, // disparity normalize (proportionally scale down disparity difference if above
				final double [][][] dispStrength,
                final int           debugLevel,
				final int           dbg_X,
				final int           dbg_Y)
		{
2156

2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
			int [] stats_new = new int [NUM_STATS];
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final int numThreads = threads.length;
			final int [][] stats_all = new int [numThreads][stats_new.length];
			final AtomicInteger ai_numThread = new AtomicInteger(0);
			final AtomicInteger ai = new AtomicInteger(0);
			final boolean en_lower =  (moveDirs & 1) != 0;
			final boolean en_higher = (moveDirs & 2) != 0;
			for (int ml = 0; ml < tileLayers.length; ml++) if (tileLayers[ml] != null){
				final int fml = ml;
				ai_numThread.set(0);
				ai.set(0);
				for (int ithread = 0; ithread < threads.length; ithread++) {
					threads[ithread] = new Thread() {
2171
						@Override
2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
						public void run() {
							int numThread = ai_numThread.getAndIncrement(); // unique number of thread to write to rslt_diffs[numThread]
							for (int nTile = ai.getAndIncrement(); nTile < tileLayers[fml].length; nTile = ai.getAndIncrement()) {
								if (tileLayers[fml][nTile] == 0){ // unassigned only
									if (dispStrength[fml][1][nTile] < minStrength){
										stats_all[numThread][TOO_WEAK] ++;
									} else	if (dispStrength[fml][1][nTile] > maxStrength){
										stats_all[numThread][TOO_STRONG] ++;
									} else {
										// calculate index in tileData (has different dimensions - TODO: trim?
										int nSurfTile = getSurfaceTileIndex(nTile);
										if ((tileData[nSurfTile] == null) || (tileData[nSurfTile].length == 0)){
											stats_all[numThread][NO_SURF] ++;
											tileLayers[fml][nTile] = IMPOSSIBLE;
										} else {
//											double [] surf_disp_diff = new double [tileData[nSurfTile].length];
											int num_fit = 0;
											int num_fit_other = 0;
											int fit = -1;
2191 2192
											// Eliminate surface edges if prohibited
											boolean [] bad_surface = new boolean [tileData[nSurfTile].length]; // has less than 8 neighbors if controlled
2193 2194 2195 2196 2197 2198
											for (int ns = 0; ns < tileData[nSurfTile].length; ns++){
												double surf_disp_diff = getNormDispFromSurface (
														dispStrength[fml][0][nTile], // double disp_tile,
														tileData[nSurfTile][ns].getDisparity(), // double disp_surf,
														dispNorm); //double disp_norm)
												if (((surf_disp_diff >= 0) && en_higher) || ((surf_disp_diff <= 0) && en_lower)){
2199 2200 2201 2202 2203 2204 2205 2206
													// Eliminate surface edges if prohibited
													if (noEdge){
														int []neibs = tileData[nSurfTile][ns].getNeighbors();
														for (int i = 0; i < neibs.length; i++){
															if (neibs[i] < 0){
																bad_surface[ns] = true;
															}
														}
2207
													}
2208 2209 2210 2211 2212 2213 2214 2215
													if (!bad_surface[ns]) {
														if (Math.abs(surf_disp_diff) <= maxDiff){
															fit = ns;   // no rating for fit "quality" here
															num_fit ++;
														}
														if (Math.abs(surf_disp_diff) <= minDiffOther){
															num_fit_other ++;
														}
2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
													}
												}
											}
											if (num_fit < 1){
												stats_all[numThread][TOO_FAR] ++;
											} else if ((num_fit == 1) && (num_fit_other <= 1)){ // assign
												tileLayers[fml][nTile] = fit + 1;
												stats_all[numThread][NEW_ASSIGNED] ++;
											} else {
												stats_all[numThread][NOT_UNIQUE] ++;
											}
										}
									}
								}
							}
						}
					};
2233
				}
2234 2235 2236 2237 2238 2239 2240 2241 2242
				ImageDtt.startAndJoin(threads);
			}
			for (int nt = 0; nt < numThreads; nt ++){
				for (int i = 0 ; i < stats_new.length; i++ ){
					stats_new[i] += stats_all[nt][i];
				}
			}
			return stats_new;
		}
2243 2244

		public void compareAssignments(
2245 2246
				final int [][][] tileAssignments,
				final int debugLevel)
2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281
		{
			final int imgTiles = imageTilesX * imageTilesY;
			final int num_in = tileAssignments.length;
			String [] titles = new String [num_in + 2];
			double [][] img_data = new double [titles.length][imgTiles];
			for (int i =0 ; i < num_in; i++){
				titles[i] = "inp_"+i;
			}
			titles[num_in] =   "consensus";
			titles[num_in+1] = "conflicts";
			int [] combo = new int [imgTiles];
			for (int nTile = 0; nTile < imgTiles; nTile++){
				int nSurfTile = getSurfaceTileIndex(nTile);
				HashSet <Integer> alts = new HashSet <Integer>();
				boolean invalid = false;
				for (int n = 0; n < num_in; n++)if (tileAssignments[n] != null){
					img_data[n][nTile] = Double.NaN;
					for (int ml = 0; ml < tileAssignments[n].length; ml++) if ((tileAssignments[n][ml] != null) && (tileAssignments[n][ml][nTile] != 0)){
						if (tileAssignments[n][ml][nTile] < 0) {
							combo[nTile] = tileAssignments[n][ml][nTile];
							invalid = true;
							break;
						}
						alts.add(tileAssignments[n][ml][nTile]);
						img_data[n][nTile] = tileData[nSurfTile][tileAssignments[n][ml][nTile] - 1].getDisparity();
						img_data[num_in][nTile] = tileData[nSurfTile][tileAssignments[n][ml][nTile] - 1].getDisparity();
					}
					if (invalid) break;
				}
				if (!invalid) {
					combo[nTile] = alts.size();
				}
				if (combo[nTile] != 1 ){
					img_data[num_in][nTile] = Double.NaN;
				}
2282

2283 2284
				img_data[num_in+1][nTile] = combo[nTile];
			}
2285
			if (debugLevel > -1) {
2286
				ShowDoubleFloatArrays.showArrays(img_data,  imageTilesX, imageTilesY, true, "consensus",titles);
2287
			}
2288
		}
2289

2290 2291
		public int [][] getConsensusAssignment(
				final int        min_agree,
2292
				int [][][]       opinions_in, // options contain 1-based surface indices
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315
				final int [][][] tileAssignments)
		{
			final int imgTiles = imageTilesX * imageTilesY;
			final int num_in = tileAssignments.length;
			final int num_ml = tileAssignments[0].length; // all should have same number of measurement layers
			final int [][] consensus = new int [num_ml][];
			final int [][][] opinions = (opinions_in != null) ? opinions_in : new int [num_ml][][];
			for (int ml = 0; ml < num_ml; ml++){
				boolean ml_exists = false;
				for (int n = 0; n < num_in; n++) {
					if ((tileAssignments[n] != null) && (tileAssignments[n][ml] != null)){
						ml_exists = true;
						break;
					}
				}
				if (ml_exists) {
					consensus[ml] = new int [imgTiles];
					opinions[ml] = new int [imgTiles][];
					for (int nTile = 0; nTile < imgTiles; nTile++){
						if (nTile== 50109){
							System.out.println("getConsensusAssignment(): nTile="+nTile);
						}
						int num_agree = 0;
2316
						ArrayList <Integer> alts = new ArrayList <Integer>(); // elements are 1-based surfaces
2317 2318 2319
						for (int n = 0; n < num_in; n++)if (tileAssignments[n] != null){
							int surf1 = tileAssignments[n][ml][nTile];
							if (surf1 != 0){
2320
								consensus[ml][nTile] = surf1;
2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
								if (surf1 < 0) { // prohibited
									break;
								} else { // surface
									if (!alts.contains(surf1)){
										alts.add(surf1);
									}
									num_agree++;
								}
							}
						}
2331
						if (((alts.size() > 1) || (num_agree < min_agree)) && (consensus[ml][nTile] > 0)){
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
							consensus[ml][nTile] = 0; // not assigned
						}
						if (!alts.isEmpty()){
							opinions[ml][nTile] = new int[alts.size()];
							int indx = 0;
							for (Integer i:alts){
								opinions[ml][nTile][indx++] = i;
							}
						}
					}
				}
2343
			}
2344 2345
			return consensus;
		}
2346 2347 2348 2349




2350 2351 2352 2353
		/**
		 * Assign tiles that were used to generate planes. Only tiles in the center (non-overlapping) part of the supertile
		 * @param force re-assign tile if it was already assigned
		 * @param tileLayers
2354
		 * @param noEdge do not assign tiles to the surface edges (can not add border later)
2355 2356 2357 2358 2359
		 * @param debugLevel
		 * @param dbg_X
		 * @param dbg_Y
		 * @return
		 */
2360

2361 2362 2363 2364
		public int [] assignPlanesTiles(
				final boolean                  force,
				final int [][]                 tileLayers,
				final TilePlanes.PlaneData[][] planes,
2365
				final boolean                  noEdge,
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
                final int                      debugLevel,
				final int                      dbg_X,
				final int                      dbg_Y)
		{
			int [] stats_new = new int [NUM_STATS];
			final int nsTiles = stilesX * stilesY;
			final int imgTiles = imageTilesX * imageTilesY;
//			final TileNeibs tnImage =   new TileNeibs(imageTilesX, imageTilesY);
//			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final int debug_stile = dbg_Y * stilesX + dbg_X;
2376
			final Thread[] threads = ImageDtt.newThreadArray((debugLevel > 1)? 1 : threadsMax);
2377 2378 2379 2380
			final int numThreads = threads.length;
			final int [][] stats_all = new int [numThreads][stats_new.length];
			final AtomicInteger ai_numThread = new AtomicInteger(0);
			final AtomicInteger ai = new AtomicInteger(0);
2381

2382 2383
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
2384
					@Override
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394
					public void run() {
						int numThread = ai_numThread.getAndIncrement(); // unique number of thread to write to rslt_diffs[numThread]
						for (int nsTile = ai.getAndIncrement(); nsTile < nsTiles; nsTile = ai.getAndIncrement()) if (planes[nsTile] != null){
							int stx = nsTile %  stilesX;
							int sty = nsTile /  stilesX;
//							int dl = ((debugLevel > 1) && (nsTile == debug_stile)) ? 3: debugLevel;
							int dl = ((debugLevel > 1) && ((nsTile == debug_stile) || (nsTile == (debug_stile + stilesX)))) ? 3: debugLevel;
							if (dl > 2){
								System.out.println("assignPlanesTiles(): nsTile = " + nsTile);
							}
2395

2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412
							for (int np = 0; np < planes[nsTile].length; np++)  if (planes[nsTile][np] != null){
								boolean [][] meas_sel = planes[nsTile][np].getMeasSelection();
								// is it needed or is tileLayers already initialized?
								for (int ml = 0; ml < meas_sel.length; ml++) if (meas_sel[ml] != null){
									if (tileLayers[ml] == null){
										tileLayers[ml] = new int [imgTiles];
									}
								}
								for (int dy = 0; dy < superTileSize; dy++){
									for (int dx = 0; dx < superTileSize; dx++){
										// center (unique) part of the supertilemask
										int st_index = superTileSize*(superTileSize + 2 * dy) +(superTileSize/2 + dx);
//										int nl = -1;
										int nTile = -1;
										int ns = -1;
										for (int ml = 0; ml < meas_sel.length; ml++) if (meas_sel[ml] != null){
											if (meas_sel[ml][st_index]){
2413
												int nSurfTile = -1;
2414 2415
												if (ns < 0){ // find for the first used ml, if there are more - they will reuse
													nTile = (superTileSize * sty + dy) * imageTilesX + (superTileSize * stx + dx);
2416
													nSurfTile = getSurfaceTileIndex(nTile);
2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430
													for (int i = 0; i < tileData[nSurfTile].length; i ++){
														if (    (tileData[nSurfTile][i].getParentNsTile() == nsTile) &&
																(tileData[nSurfTile][i].getParentLayer() == np)) {
															ns = i;
															break;
														}
													}
													if (dl > 2){
														System.out.println("assignPlanesTiles(): nsTile = " + nsTile+":"+np+
																" stx:y="+stx+":"+sty+
																" ("+ (superTileSize * stx + dx)+"/"+
																(superTileSize * sty + dy)+")" +
																" dx:y="+dx+":"+dy+" nTile="+nTile+" nSurfTile="+nSurfTile+" ns="+ns);
													}
2431

2432 2433 2434 2435 2436 2437
													if (ns < 0) {
														System.out.println("assignPlanesTiles(): BUG? Could not find a surface with parent supertile "+
																nsTile+":"+np+" for image tile = "+nTile+" ("+ (superTileSize * stx + dx)+"/"+
																(superTileSize * sty + dy)+")");
													}
												}
2438

2439
												if ((ns >= 0) && (force || (tileLayers[ml][nTile] == 0))) {
2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
													boolean bad_edge = noEdge;
													if (bad_edge) {
														bad_edge = false;
														int []neibs = tileData[nSurfTile][ns].getNeighbors();
														for (int i = 0; i < neibs.length; i++) if (neibs[i] < 0) {
															bad_edge = true;
															break;
														}
													}
													if (bad_edge) {
														stats_all[numThread][NO_SURF] ++;
														tileLayers[ml][nTile] = IMPOSSIBLE;
													} else {
														tileLayers[ml][nTile] = ns + 1;
														stats_all[numThread][NEW_ASSIGNED] ++;
													}
2456 2457 2458 2459 2460 2461 2462 2463 2464
												}
											}
										}
									}
								}
							}
						}
					}
				};
2465
			}
2466 2467 2468 2469 2470 2471 2472 2473
			ImageDtt.startAndJoin(threads);
			for (int nt = 0; nt < numThreads; nt ++){
				for (int i = 0 ; i < stats_new.length; i++ ){
					stats_new[i] += stats_all[nt][i];
				}
			}
			return stats_new;
		}
2474

2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
		/**
		 * Assign tiles to a disparity surface if there is only one surface at all
		 * @param tileLayers per measured layer, per tile: assigned index plus1, 0 - empty, or negative - prohibited
		 * @param noEdge do not assign tiles to the surface edges (can not add border later)
		 * @param debugLevel debug level
		 * @param dbg_X debug tile X coordinate
		 * @param dbg_Y debug tile Y coordinate
		 * @return statistics array
		 */
		public int [] assignTilesToSingleSurface(
				final int [][]      tileLayers,
				final boolean       noEdge,
                final int           debugLevel,
				final int           dbg_X,
				final int           dbg_Y)
		{
2491

2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
			int [] stats_new = new int [NUM_STATS];
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final int numThreads = threads.length;
			final int [][] stats_all = new int [numThreads][stats_new.length];
			final AtomicInteger ai_numThread = new AtomicInteger(0);
			final AtomicInteger ai = new AtomicInteger(0);
			for (int ml = 0; ml < tileLayers.length; ml++) if (tileLayers[ml] != null){
				final int fml = ml;
				ai_numThread.set(0);
				ai.set(0);
				for (int ithread = 0; ithread < threads.length; ithread++) {
					threads[ithread] = new Thread() {
2504
						@Override
2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539
						public void run() {
							int numThread = ai_numThread.getAndIncrement(); // unique number of thread to write to rslt_diffs[numThread]
							for (int nTile = ai.getAndIncrement(); nTile < tileLayers[fml].length; nTile = ai.getAndIncrement()) {
								if (tileLayers[fml][nTile] == 0){ // unassigned only
									// calculate index in tileData (has different dimensions - TODO: trim?
									int nSurfTile = getSurfaceTileIndex(nTile);
									if ((tileData[nSurfTile] == null) || (tileData[nSurfTile].length == 0)){
										stats_all[numThread][NO_SURF] ++;
										tileLayers[fml][nTile] = IMPOSSIBLE;
									} else {
										if (tileData[nSurfTile].length == 1) {
											boolean bad_edge = noEdge;
											if (bad_edge) {
												bad_edge = false;
												int []neibs = tileData[nSurfTile][0].getNeighbors();
												for (int i = 0; i < neibs.length; i++) if (neibs[i] < 0) {
													bad_edge = true;
													break;
												}
											}
											if (bad_edge) {
												stats_all[numThread][NO_SURF] ++;
												tileLayers[fml][nTile] = IMPOSSIBLE;
											} else {
												tileLayers[fml][nTile] = 1; // first and only surface
												stats_all[numThread][NEW_ASSIGNED] ++;
											}
										} else {
											stats_all[numThread][NOT_UNIQUE] ++;
										}
									}
								}
							}
						}
					};
2540
				}
2541 2542 2543 2544 2545 2546 2547 2548 2549
				ImageDtt.startAndJoin(threads);
			}
			for (int nt = 0; nt < numThreads; nt ++){
				for (int i = 0 ; i < stats_new.length; i++ ){
					stats_new[i] += stats_all[nt][i];
				}
			}
			return stats_new;
		}
2550

2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
		/**
		 * Grow assigned tiles while strength is below maxStrength OR normalized (dispNorm) disparity error is below
		 * maxDiff AND new tile is unassigned. Combines all measured layers, assumes same cell was not assigned to
		 * different surfaces on different measured layers (some assigned, some not is OK)
		 * @param tileLayers per measured layer, per tile: assigned index plus1, 0 - empty, or negative - prohibited
		 * @param conflicts detected conflicts while growing - both strength and disparity errors match requirements,
		 * but the cell is occupied by other assigned tile on different layer. Per tile, a pair of the surface index
		 *  plus 0 and direction to offending cell . Outer array should be initialized
		 * @param noEdge do not assign tiles to the surface edges (can not add border later)
		 *  (individual per measurement layer)
		 * @param maxStrength maximal processed (floor subtracted) correlation strength to grow over any disparity error
		 * @param minStrengthContinue minimal strength to continue growing with disparity match ( >maxStrength)
		 * if minStrengthContinue is null, any tile above maxStrength will be the last (not spawn any new neighbor ones)
		 * @param maxDiffFar maximal (normalized) disparity difference for strong tiles farther from the camera than the surface
		 * @param maxDiffNear maximal (normalized) disparity difference for strong tiles closer to the camera than the surface
		 * If any of maxDiffFar, maxDiffNear are null, they are ignored and only weak tiles are permitted
		 * TODO: Another option to expand - no valid competitor
		 * @param dispNorm disparity normalization - disparity difference with average above it will be scaled down
		 * @param dispStrength per measurement layer, combined disparity and strength array ([num_ml][2][])
		 * @param debugLevel debug level
		 * @param dbg_X debug tile X coordinate
		 * @param dbg_Y debug tile Y coordinate
		 * @return statistics array
		 */
2575

2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
		public int [] growWeakAssigned(
				final int [][]      tileLayers,
				final int [][]      conflicts,
				final boolean       noEdge,
				final double []     maxStrength,
				final double []     minStrengthContinue,
				final double []     maxDiffFar,
				final double []     maxDiffNear,
				final double        dispNorm, // disparity normalize (proportionally scale down disparity difference if above
				final double [][][] dispStrength,
                final int           debugLevel,
				final int           dbg_X,
				final int           dbg_Y)
		{
//			final int tiles = stilesX * superTileSize * stilesY * superTileSize;
			final boolean en_strong = (maxDiffFar != null) && (maxDiffNear != null); // both should be specified
			final boolean en_continue = minStrengthContinue != null;
2593

2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654
			final int img_tiles = imageTilesX * imageTilesY;
//			final TileNeibs tnSurface = new TileNeibs(stilesX * superTileSize, stilesY * superTileSize);
			final TileNeibs tnImage =   new TileNeibs(imageTilesX, imageTilesY);
			final int [] flat_assign = new int [ img_tiles];
			final int [] stats = new int [NUM_STATS];
			int [] dbg_flat_assign = null;
			ArrayList<Point> tiles_list = new ArrayList<Point>();
			for (int nTile = 0; nTile <  img_tiles; nTile++){
				for (int ml = 0; ml < tileLayers.length; ml++) if (tileLayers[ml] != null){
					if (tileLayers[ml][nTile] != 0) {
						flat_assign[nTile] = tileLayers[ml][nTile];
						break;
					}
				}
			}
			if (debugLevel > 1) {
				dbg_flat_assign = flat_assign.clone();
			}
			for (int nTile = 0; nTile <  img_tiles; nTile++){
				if (flat_assign[nTile] > 0) {
					for (int dir = 0; dir < 8; dir++){
						int nTile1 = tnImage.getNeibIndex(nTile, dir);
						if ((nTile1 >= 0) && (flat_assign[nTile1] >=0 )  && (flat_assign[nTile1] != flat_assign[nTile])){
							tiles_list.add(new Point(nTile,flat_assign[nTile]-1));
							break;
						}
					}
				}
			}
			while (!tiles_list.isEmpty()){
//				int nTile = tiles_list.remove(0);
				Point pTile = tiles_list.remove(0);
				// calculate index in tileData (has different dimensions - TODO: trim?
				int nSurfTile = getSurfaceTileIndex(pTile.x);
				boolean is_weak_start = true;
				for (int ml = 0; ml < tileLayers.length; ml ++) if (dispStrength[ml] != null) {
					double strength = dispStrength[ml][1][pTile.x];
					if (strength > maxStrength[ml]){
						is_weak_start = false;
						break;
					}
				}
				if (!is_weak_start && !en_continue) {
					continue; // only  can grow from weak single candidate planes or in continue mode
				}

				int [] neibs = tileData[nSurfTile][pTile.y].getNeighbors();
				int [] conflict = {pTile.y,0};
				for (int dir = 0; dir < 8; dir++) if (neibs[dir] >= 0){
					int nTile1 = tnImage.getNeibIndex(pTile.x, dir); // image index, not surface index
					// check it does not already belong to the same surface
					if (nTile1 == 49451) { // pTile.x==33324){
						System.out.println("growWeakAssigned() nTile1="+nTile1);
					}
					if ((nTile1 >= 0) && // (nTile1 >= 0) should always be as it is connected!
							(flat_assign[nTile1] != (neibs[dir] + 1)) && // not the same surface
							(flat_assign[nTile1] >= 0)){// not the prohibited surface
						// if noEdge, check it has all 8 neighbors
						// calculate index in tileData (has different dimensions - TODO: trim?
						int nSurfTile1 = getSurfaceTileIndex(nTile1);
						int ns1 = neibs[dir];
2655 2656 2657 2658
						if (debugLevel > 0) {
							System.out.println("growWeakAssigned(): nTile="+pTile.x+" ns="+pTile.y+" dir = "+dir+
									" nSurfTile="+nSurfTile+" nSurfTile1="+nSurfTile1+" ns1="+ns1);
						}
2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684
						boolean bad_edge = noEdge;
						if (bad_edge) {
							bad_edge = false;
							int [] neibs1 = tileData[nSurfTile1][ns1].getNeighbors(); //oob 1
							for (int i = 0; i < neibs1.length; i++) if (neibs1[i] < 0) {
								bad_edge = true;
								break;
							}
						}
						if (!bad_edge) {
							// check if it fits before looking - is it an empty or already or belongs to other surface
							// for each measurement layer separately
							double surf_disparity = tileData[nSurfTile1][ns1].getDisparity();
							boolean is_good_tile = true;
							for (int ml = 0; ml < tileLayers.length; ml ++) if (dispStrength[ml] != null) {
								double strength = dispStrength[ml][1][nTile1];
								boolean is_weak_new = strength <= maxStrength[ml];
								boolean good_disparity = false;
								if (en_strong && !is_weak_new) {
									double surf_disp_diff = getNormDispFromSurface (
											dispStrength[ml][0][nTile1], // double disp_tile,
											surf_disparity, // double disp_surf,
											dispNorm); //double disp_norm)
									good_disparity = (surf_disp_diff <= maxDiffNear[ml]) && (surf_disp_diff >= -maxDiffFar[ml]);
								}
								// Strong tiles can only be near the end of expansion - should not go back to weak after strong
2685
								// if started from weak, can add any weak or with disparity
2686 2687 2688 2689 2690
								if (is_weak_start) {
									if (!is_weak_new && !good_disparity){
										is_good_tile = false;
										break;
									}
2691
								// if started from not weak - disparity should match and the tile should be "really strong" ( > minStrengthContinue)
2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
								}else {
									if (!good_disparity || !en_continue || (strength < minStrengthContinue[ml])) {
										is_good_tile = false;
										break;
									}
								}
							}
							if (is_good_tile) {
								// here - OK to add a new tile
								// is it a conflict?
2702
								if (flat_assign[nTile1] > 0) { // yes, a conflict
2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741
									conflict[1] |= 1 << dir;
								} else { // new empty cell - add it
									flat_assign[nTile1] = ns1 + 1;
									tiles_list.add(new Point(nTile1, ns1));
									stats[NEW_ASSIGNED] ++;
								}
							}
						}
					}
				}
				if (conflict[1] != 0){
					conflicts[pTile.x] = conflict;
				}
			}
			//copy assignments to all measured layers
			for (int nTile = 0; nTile <  img_tiles; nTile++){
				for (int ml = 0; ml < tileLayers.length; ml++) if (tileLayers[ml] != null){
					if (flat_assign[nTile] != 0) {
						tileLayers[ml][nTile] = flat_assign[nTile];
					}
				}
			}
			if (debugLevel > 1){
				final String [] titles = {"surf","ini_assign", "assign", "confl_surf", "confl_dirs"};
				final double [][] dbg_img = new double [titles.length][img_tiles];
				for (int nTile = 0; nTile <  img_tiles; nTile++){
					dbg_img[1][nTile] =  dbg_flat_assign[nTile];
					dbg_img[2][nTile] =  flat_assign[nTile];
					if (flat_assign[nTile] > 0) {
						double surf_disparity = tileData[getSurfaceTileIndex(nTile)][flat_assign[nTile]-1].getDisparity();
						dbg_img[0][nTile] = surf_disparity;
					} else {
						dbg_img[0][nTile] = Double.NaN;
					}
					if (conflicts[nTile] != null){
						dbg_img[3][nTile] =  conflicts[nTile][0];
						dbg_img[4][nTile] =  conflicts[nTile][1];
					}
				}
2742
				ShowDoubleFloatArrays.showArrays(dbg_img,  imageTilesX, imageTilesY, true, "only_surface_grow",titles);
2743 2744 2745
			}
			return stats;
		}
2746 2747 2748



2749 2750
		public void printStats(int []stats)
		{
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767
			boolean nothing = true;
			for (int i = 0; nothing && (i < stats.length); i++){
				nothing &= stats[i] == 0;
			}
			if (nothing) {
				System.out.println(" -- no changes --");
			} else {
				if (stats[NEW_ASSIGNED]     > 0) System.out.print(" NEW_ASSIGNED = " +     stats[NEW_ASSIGNED]);
				if (stats[NO_SURF]          > 0) System.out.print(" NO_SURF = " +          stats[NO_SURF]);
				if (stats[TOO_WEAK]         > 0) System.out.print(" TOO_WEAK = " +         stats[TOO_WEAK]);
				if (stats[TOO_STRONG]       > 0) System.out.print(" TOO_STRONG = " +       stats[TOO_STRONG]);
				if (stats[TOO_FAR]          > 0) System.out.print(" TOO_FAR = " +          stats[TOO_FAR]);
				if (stats[NOT_UNIQUE]       > 0) System.out.print(" NOT_UNIQUE = " +       stats[NOT_UNIQUE]);
				if (stats[REMOVED_TILES]    > 0) System.out.print(" REMOVED_TILES = " +    stats[REMOVED_TILES]);
				if (stats[REMOVED_CLUSTERS] > 0) System.out.print(" REMOVED_CLUSTERS = " + stats[REMOVED_CLUSTERS]);
			}
			System.out.println();
2768
		}
2769

2770 2771 2772 2773
		public boolean makesSensToTry(int [] stats)
		{
			return ((stats[NEW_ASSIGNED] > 0) && (stats[NOT_UNIQUE] > 0));
		}
2774 2775 2776 2777
		public int newAssigned(int [] stats)
		{
			return stats[NEW_ASSIGNED];
		}
2778

2779 2780 2781
		public void showAssignment(
				String title,
				final double [][][] dispStrength)
2782 2783 2784
		{
			String [] titles =      getTitlesAssignment(dispStrength);
			double [][] img_data =  getShowAssignment(dispStrength);
2785
			ShowDoubleFloatArrays.showArrays(img_data,  imageTilesX, imageTilesY, true, title, titles);
2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832
		}

		public double [][] getShowAssignment(
				final double [][][] dispStrength)
		{
			double [][] img_data = new double [ASGN_NG * tileLayers.length][];
			for (int ml = 0; ml < tileLayers.length; ml ++){
				if (dispStrength[ml] != null) {
					img_data[ASGN_NG * ml + ASGN_DISP] =     dispStrength[ml][0];
					img_data[ASGN_NG * ml + ASGN_STRENGTH] = dispStrength[ml][1];
					img_data[ASGN_NG * ml + ASGN_A_DISP] =   new double [dispStrength[ml][0].length];
					img_data[ASGN_NG * ml + ASGN_A_NAN] =    new double [dispStrength[ml][0].length];
					img_data[ASGN_NG * ml + ASGN_INDX] =     new double [dispStrength[ml][0].length];
					for (int nTile = 0;  nTile < dispStrength[ml][0].length; nTile++){
						int nSurfTile = getSurfaceTileIndex(nTile);
						if (tileLayers[ml][nTile] > 0){
							img_data[ASGN_NG * ml + ASGN_A_DISP][nTile] = tileData[nSurfTile][tileLayers[ml][nTile]-1].getDisparity();
							img_data[ASGN_NG * ml + ASGN_A_NAN][nTile] =  tileData[nSurfTile][tileLayers[ml][nTile]-1].getDisparity();
						} else {
							img_data[ASGN_NG * ml + ASGN_A_DISP][nTile] = dispStrength[ml][0][nTile];
							img_data[ASGN_NG * ml + ASGN_A_NAN][nTile] =  Double.NaN;
						}
						img_data[ASGN_NG * ml + ASGN_INDX][nTile] = tileLayers[ml][nTile];
					}
				}
			}
			return img_data;
		}

		public String [] getTitlesAssignment(
				final double [][][] dispStrength)
		{
			int ng = 5;
			String [] titles = new String[ng * tileLayers.length];
			for (int ml = 0; ml < tileLayers.length; ml ++){
				titles[ng * ml + ASGN_DISP] =     "disp_"+ml;
				titles[ng * ml + ASGN_A_DISP] =   "a_disp_"+ml;
				titles[ng * ml + ASGN_A_NAN] =    "a_nan_"+ml;
				titles[ng * ml + ASGN_INDX] =    "index_"+ml;
				titles[ng * ml + ASGN_STRENGTH] = "strength_"+ml;
			}
			return titles;
		}

		public void showAssignment_old(
				String title,
				final double [][][] dispStrength)
2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867
		{
			int layer_disp =     0;
			int layer_a_disp =   1;
			int layer_a_nan =    2;
			int layer_index =    3;
			int layer_strength = 4;
			int ng = 5;
			String [] titles = new String[ng * tileLayers.length];
			double [][] img_data = new double [titles.length][];
			for (int ml = 0; ml < tileLayers.length; ml ++){
				titles[ng * ml + layer_disp] =     "disp_"+ml;
				titles[ng * ml + layer_a_disp] =   "a_disp_"+ml;
				titles[ng * ml + layer_a_nan] =    "a_nan_"+ml;
				titles[ng * ml + layer_index] =    "index_"+ml;
				titles[ng * ml + layer_strength] = "strength_"+ml;
			}
			for (int ml = 0; ml < tileLayers.length; ml ++){
				if (dispStrength[ml] != null) {
					img_data[ng * ml + layer_disp] =     dispStrength[ml][0];
					img_data[ng * ml + layer_strength] = dispStrength[ml][1];
					img_data[ng * ml + layer_a_disp] =   new double [dispStrength[ml][0].length];
					img_data[ng * ml + layer_a_nan] =    new double [dispStrength[ml][0].length];
					img_data[ng * ml + layer_index] =    new double [dispStrength[ml][0].length];
					for (int nTile = 0;  nTile < dispStrength[ml][0].length; nTile++){
						int nSurfTile = getSurfaceTileIndex(nTile);
						if (tileLayers[ml][nTile] > 0){
							img_data[ng * ml + layer_a_disp][nTile] = tileData[nSurfTile][tileLayers[ml][nTile]-1].getDisparity();
							img_data[ng * ml + layer_a_nan][nTile] =  tileData[nSurfTile][tileLayers[ml][nTile]-1].getDisparity();
						} else {
							img_data[ng * ml + layer_a_disp][nTile] = dispStrength[ml][0][nTile];
							img_data[ng * ml + layer_a_nan][nTile] =  Double.NaN;
						}
						img_data[ng * ml + layer_index][nTile] = tileLayers[ml][nTile];
					}
				}
2868
			}
2869
			ShowDoubleFloatArrays.showArrays(img_data,  imageTilesX, imageTilesY, true, title, titles);
2870
		}
2871

2872

2873 2874 2875
		/**
		 * Unassign tiles that have too few connected other tiles (or total weight of the cluster is too small)
		 * This is a single-threaded method
2876
		 * @param tileLayers integer array of per measurement layer, per tile of assigned surface indices (modifiesd)
2877
		 * @param minSize minimal tiles in the cluster
2878
		 * @param minStrength minimal total strength of the cluster
2879 2880 2881 2882
		 * @param dispStrength per measurement layer, combined disparity and strength array ([num_ml][2][])
		 * @param debugLevel debug level
		 * @param dbg_X debug tile X coordinate
		 * @param dbg_Y debug tile Y coordinate
2883
		 * @return {number of tiles, number of clusters} removed
2884 2885
		 */
		public int [] removeSmallClusters(
2886 2887
				final int [][]      tileLayers,

2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906
				final int           minSize,
				final double        minStrength,
				final double [][][] dispStrength,
                final int           debugLevel,
				final int           dbg_X,
				final int           dbg_Y)
		{
			boolean [][] wave_conf = new boolean [tileLayers.length][]; // true when wave or if confirmed
			int [] stats_new = new int [NUM_STATS];
			for (int ml = 0; ml < tileLayers.length; ml ++) if (tileLayers[ml] != null){
				wave_conf[ml] = new boolean[tileLayers[ml].length];
			}
			TileNeibs tnImage =   new TileNeibs(imageTilesX, imageTilesY);
//			TileNeibs tnSurface = new TileNeibs(stilesX * superTileSize, stilesY * superTileSize);

			for (int ml = 0; ml < tileLayers.length; ml ++) if (tileLayers[ml] != null){
				for (int nTile0 = 0; nTile0 < tileLayers[ml].length; nTile0++) if ((tileLayers[ml][nTile0] > 0) && !wave_conf[ml][nTile0]){
					ArrayList<Point> wave_list = new ArrayList<Point>();
					double sum_weight = 0.0;
2907
					int tailp = 0; // do not remove elements from the list while building the cluster, just advance tail pointer
2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937
					Point p = new Point(nTile0, ml);
					sum_weight += dispStrength[p.y][1][p.x];
					wave_conf[p.y][p.x] = true;
					wave_list.add(p);
					while (tailp < wave_list.size()){
						Point pt = wave_list.get(tailp++);
						int nSurfTile1 = getSurfaceTileIndex(pt.x);
						int nl1 = tileLayers[pt.y][pt.x] - 1; // zero-based from 1-based
						int [] neibs = tileData[nSurfTile1][nl1].getNeighbors();
						for (int dir  = 0; dir < tnImage.dirs; dir++) if (neibs[dir] >= 0){
							int nTile1 = tnImage.getNeibIndex(pt.x, dir);
							if (nTile1 >= 0) {
								for (int ml1 = 0; ml1 < tileLayers.length; ml1++) {
									// may be several ml tiles on the same surface - count them all
									if ((tileLayers[ml1] != null) && (tileLayers[ml1][nTile1] == (neibs[dir] +1)) && !wave_conf[ml1][nTile1]){
										Point p1 = new Point(nTile1, ml1);
										sum_weight += dispStrength[p1.y][1][p1.x];
										wave_conf[p1.y][p1.x] = true;
										wave_list.add(p1);
									}
								}
							}
						}
					}
					// See if it is a good cluster
					if ((wave_list.size() < minSize) || (sum_weight < minStrength)){
						while (wave_list.size() > 0){
							Point pt = wave_list.remove(0);
							tileLayers[pt.y][pt.x] = 0;
							wave_conf [pt.y][pt.x] = false; // not necessary
2938

2939 2940 2941 2942
							stats_new[REMOVED_TILES]++;
						}
						stats_new[REMOVED_CLUSTERS]++;
					} else { // it is a strong cluster, nothing to do here (it is already marked in wave_conf[][]
2943

2944 2945
					}
				}
2946
			}
2947 2948 2949 2950 2951 2952
			return stats_new;
		}

		/**
		 * Assign (weak) tile surrounded by assigned one to the disparity of the farthest tile (lowest disparity).
		 * This is a single-threaded method
2953
		 * @param tileLayers integer array of per measurement layer, per tile of assigned surface indices (modifiesd)
2954
		 * @param noEdge do not assign tiles to the surface edges (can not add border later)
2955 2956 2957 2958 2959 2960 2961 2962
		 * @param minNeib minimal number of occupied directions (of 8), several occupied levels count as one
		 * @param maxStrength maximal strength of the tile to assign (strong one may make trust its disparity after all)
		 * @param includeImpossible count impossible (blocked, on the image edge,...) tiles as if assigned towards
		 * the number of occupied directions
		 * @param dispStrength per measurement layer, combined disparity and strength array ([num_ml][2][])
		 * @param debugLevel debug level
		 * @param dbg_X debug tile X coordinate
		 * @param dbg_Y debug tile Y coordinate
2963
		 * @return {number of tiles, number of clusters} removed
2964
		 */
2965

2966
		public int [] assignFromFarthest(
2967
				final int [][]      tileLayers,
2968
				final boolean       noEdge,
2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990
				final int           minNeib,
				final double        maxStrength,
				final boolean       includeImpossible, // count prohibited neighbors as assigned
				final double [][][] dispStrength,
                final int           debugLevel,
				final int           dbg_X,
				final int           dbg_Y)
		{
			final int [][] tileLayers_src = tileLayers.clone();
			for (int i = 0; i < tileLayers_src.length; i++){
				if (tileLayers_src[i] != null){
					tileLayers_src[i] = tileLayers[i].clone();
				}
			}
			int [] stats_new = new int [NUM_STATS];
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final int numThreads = threads.length;
			final int [][] stats_all = new int [numThreads][stats_new.length];
			final AtomicInteger ai_numThread = new AtomicInteger(0);
			final AtomicInteger ai = new AtomicInteger(0);
			final TileNeibs tnImage =   new TileNeibs(imageTilesX, imageTilesY);
			final TileNeibs tnSurface = new TileNeibs(stilesX * superTileSize, stilesY * superTileSize);
2991

2992 2993 2994 2995 2996 2997
			for (int ml = 0; ml < tileLayers.length; ml++) if (tileLayers[ml] != null){
				final int fml = ml;
				ai_numThread.set(0);
				ai.set(0);
				for (int ithread = 0; ithread < threads.length; ithread++) {
					threads[ithread] = new Thread() {
2998
						@Override
2999 3000 3001
						public void run() {
							int numThread = ai_numThread.getAndIncrement(); // unique number of thread to write to rslt_diffs[numThread]
							for (int nTile = ai.getAndIncrement(); nTile < tileLayers_src[fml].length; nTile = ai.getAndIncrement()) {
3002
								//nTile is in image, not surface coordinates
3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031
								int dbg_tileX = nTile % imageTilesX;
								int dbg_tileY = nTile / imageTilesX;
								int dl = ((debugLevel > -1) && (dbg_tileX == dbg_X ) && (dbg_tileY == dbg_Y ))?3:0;
								if (dl > 0){
									System.out.println("assignFromFarthest, nTile = " + nTile);
								}
								if (tileLayers_src[fml][nTile] == 0){ // unassigned only
									if (dispStrength[fml][1][nTile] > maxStrength){
										stats_all[numThread][TOO_STRONG] ++;
									} else {
										// find number of tiles around (x,y) that have surface connection to this one
										// (multiple ml count as one), and which one has the lowest disparity
										int nSurfTile = getSurfaceTileIndex(nTile);
										double min_disp = Double.NaN;
										int best_nSurf = -1;
										int numNeibs = 0;
										for (int dir  = 0; dir < tnImage.dirs; dir++) {
											int nTile1 = tnImage.getNeibIndex(nTile,dir);
											boolean neib_exists = false;
											if (nTile1 >= 0){
												for (int ml_other = 0; ml_other < tileLayers_src.length; ml_other++) if (tileLayers_src[ml_other] != null){
													if (tileLayers_src[ml_other][nTile1] < 0 ) { //
														neib_exists |= includeImpossible;
													} else if (tileLayers_src[ml_other][nTile1] > 0 ){
														int nSurfTile1 = tnSurface.getNeibIndex(nSurfTile,dir);
														int nSurf = tileData[nSurfTile1][tileLayers_src[ml_other][nTile1] - 1].getNeighbor(tnSurface.opposite(dir));
														if (nSurf >= 0){
															neib_exists = true;
															double disp = tileData[nSurfTile][nSurf].getDisparity();
3032 3033 3034 3035 3036 3037 3038 3039
															boolean bad_surface = false;
															if (noEdge) {
																int [] neibs =  tileData[nSurfTile][nSurf].getNeighbors();
																for (int i = 0; i < neibs.length; i++) if (neibs[i] <0) {
																	bad_surface = true;
																	break;
																}
															}
3040

3041
															if (!(disp >= min_disp) && !bad_surface) {
3042 3043 3044 3045 3046 3047 3048
																best_nSurf = nSurf;
																min_disp = disp;
															}
														}
													}
												}
											} else {
3049
												neib_exists = includeImpossible;
3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063
											}
											if (neib_exists){
												numNeibs++;
											}
										}
										if ((numNeibs >= minNeib) && (best_nSurf >= 0)){
											tileLayers[fml][nTile] = best_nSurf + 1;
											stats_all[numThread][NEW_ASSIGNED] ++;
										}
									}
								}
							}
						}
					};
3064
				}
3065 3066 3067 3068 3069 3070 3071 3072 3073
				ImageDtt.startAndJoin(threads);
			}
			for (int nt = 0; nt < numThreads; nt ++){
				for (int i = 0 ; i < stats_new.length; i++ ){
					stats_new[i] += stats_all[nt][i];
				}
			}
			return stats_new;
		}
3074 3075


3076 3077
		/**
		 * Assign tiles to a certain disparity surface if there is only one surface candidate
3078
		 * @param tileLayers integer array of per measurement layer, per tile of assigned surface indices (modifiesd)
3079
		 * @param noEdge do not assign tiles to the surface edges (can not add border later)
3080
		 * @param useCenter only assign outside of 8x8 center if no suitable alternative
3081 3082
		 * @param maxDiff maximal (normalized) disparity difference
		 * @param minDiffOther minimal disparity difference to closest 2-nd place candidate
3083
		 * @param minStrength minimal processed (floor subtracted) correlation strength of the candidate
3084
		 * @param maxStrength maximal processed (floor subtracted) correlation strength of the candidate
3085
		 * @param minSurfStrength minimal surface strength at the tile location
3086
		 * @param moveDirs +1 - allow moving tile closer to the camera (increase disparity, +2 - allow moving away
3087 3088 3089 3090 3091 3092 3093
		 * @param enMulti allow assignment when several surfaces fit
		 * @param surfStrPow raise surface strengths ratio to this power when comparing candidates
		 * @param addStrength  add to strengths when calculating pull of assigned tiles
		 * @param sigma radius of influence (in tiles) of the previously assigned tiles
		 * @param nSigma maximal relative to radius distance to calculate influence
		 * @param minPull additional pull for no-tile surfaces (to avoid division by zero)
		 * @param minAdvantage minimal ratio of the best surface candidate to the next one to make selection
3094 3095 3096 3097
		 * @param dispNorm disparity normalization - disparity difference with average above it will be scaled down
		 * @param tileLayers measured tiles assignment (will be modified): -1 - prohibited, 0 - unassigned,
		 * >0 - number of surface where this tile is assigned plus 1.
		 * @param tileData per-tile, per layer array of TileData objects specifying surfaces to snap to
3098
		 * @param dispStrength per measurement layer, combined disparity and strength array ([num_ml][2][])
3099 3100 3101
		 * @param debugLevel debug level
		 * @param dbg_X debug tile X coordinate
		 * @param dbg_Y debug tile Y coordinate
3102
		 * @return statistics array
3103
		 */
3104

3105
		public int [] assignTilesToSurfaces(
3106
				final int [][]      tileLayers,
3107
				final boolean       noEdge,
3108
				final boolean       useCenter,
3109 3110 3111 3112
				final double        maxDiff,
				final double        minDiffOther, // should be >= maxDiff
				final double        minStrength,
				final double        maxStrength,
3113
				final double        minSurfStrength, // minimal surface strength at the tile location
3114 3115
				final int           moveDirs, // 1 increase disparity, 2 - decrease disparity, 3 - both directions
				final boolean       enMulti,
3116
				final double        surfStrPow, // surface strength power
3117
				final double        addStrength, //
3118 3119
				final double        sigma,
				final double        nSigma,
3120
				final double        minPull,
3121 3122 3123 3124 3125 3126 3127
				final double        minAdvantage,
				final double        dispNorm, // disparity normalize (proportionally scale down disparity difference if above
				final double [][][] dispStrength,
                final int           debugLevel,
				final int           dbg_X,
				final int           dbg_Y)
		{
3128

3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142
			final int [][] tileLayers_src = tileLayers.clone();
			for (int i = 0; i < tileLayers_src.length; i++){
				if (tileLayers_src[i] != null){
					tileLayers_src[i] = tileLayers[i].clone();
				}
			}
			int [] stats_new = new int [NUM_STATS];
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final int numThreads = threads.length;
			final int [][] stats_all = new int [numThreads][stats_new.length];
			final AtomicInteger ai_numThread = new AtomicInteger(0);
			final AtomicInteger ai = new AtomicInteger(0);
			final boolean en_lower =  (moveDirs & 1) != 0;
			final boolean en_higher = (moveDirs & 2) != 0;
3143 3144
			final double radius = sigma * nSigma;
			final double rsigma2 = 1.0 / ( 2.0 * sigma * sigma);
3145
			final int iradius = (int) Math.round(radius + 0.001);
3146 3147 3148 3149
			final int field_size = 2 * iradius + 1;
			final int center_index = iradius * (field_size + 1);
			final double cost_start = 1.0;
			final double cost_ortho = 1.0;
3150
			final double cost_diag  = 1.5; // Math.sqrt(2.0);
3151 3152 3153 3154 3155 3156 3157 3158 3159
			final int surfTilesX = stilesX * superTileSize;
			final int [] ldirs8 = {
					-field_size,
					-field_size + 1,
					1,
					field_size + 1,
					field_size,
					field_size - 1,
					-1,
3160 3161
					-field_size - 1};

3162 3163 3164 3165 3166 3167
			for (int ml = 0; ml < tileLayers.length; ml++) if (tileLayers[ml] != null){
				final int fml = ml;
				ai_numThread.set(0);
				ai.set(0);
				for (int ithread = 0; ithread < threads.length; ithread++) {
					threads[ithread] = new Thread() {
3168
						@Override
3169 3170 3171
						public void run() {
							int numThread = ai_numThread.getAndIncrement(); // unique number of thread to write to rslt_diffs[numThread]
							for (int nTile = ai.getAndIncrement(); nTile < tileLayers_src[fml].length; nTile = ai.getAndIncrement()) {
3172
								//nTile is in image, not surface coordinates
3173 3174 3175
								int dbg_tileX = nTile % imageTilesX;
								int dbg_tileY = nTile / imageTilesX;
								int dl = ((debugLevel > -1) && (dbg_tileX == dbg_X ) && (dbg_tileY == dbg_Y ))?3:0;
3176

3177 3178 3179 3180 3181 3182 3183 3184
								if (tileLayers_src[fml][nTile] == 0){ // unassigned only
									if (dispStrength[fml][1][nTile] < minStrength){
										stats_all[numThread][TOO_WEAK] ++;
									} else	if (dispStrength[fml][1][nTile] > maxStrength){
										stats_all[numThread][TOO_STRONG] ++;
									} else {
										// calculate index in tileData (has different dimensions - TODO: trim?
										int nSurfTile = getSurfaceTileIndex(nTile);
3185
										int nSurfSuperTile = getSurfaceSuperTileIndex(nTile);
3186 3187 3188 3189 3190 3191 3192 3193
										if ((tileData[nSurfTile] == null) || (tileData[nSurfTile].length == 0)){
											stats_all[numThread][NO_SURF] ++;
											tileLayers[fml][nTile] = IMPOSSIBLE;
										} else {
//											double [] surf_disp_diff = new double [tileData[nSurfTile].length];
											int num_fit = 0;
											int num_fit_other = 0;
											int fit = -1;
3194 3195 3196
											int num_fit_center = 0;
											int num_fit_other_center = 0;
											int fit_center = -1;
3197
											boolean [] bad_surface = new boolean [tileData[nSurfTile].length]; // has less than 8 neighbors if controlled
3198
											boolean [] center_surface = new boolean [tileData[nSurfTile].length]; // is inside the center part
3199 3200 3201 3202 3203 3204
											for (int ns = 0; ns < tileData[nSurfTile].length; ns++){
												double surf_disp_diff = getNormDispFromSurface (
														dispStrength[fml][0][nTile], // double disp_tile,
														tileData[nSurfTile][ns].getDisparity(), // double disp_surf,
														dispNorm); //double disp_norm)
												if (((surf_disp_diff >= 0) && en_higher) || ((surf_disp_diff <= 0) && en_lower)){
3205 3206 3207 3208 3209 3210 3211
													// Eliminate surface edges if prohibited
													if (noEdge){
														int []neibs = tileData[nSurfTile][ns].getNeighbors();
														for (int i = 0; i < neibs.length; i++) if (neibs[i] < 0) {
															bad_surface[ns] = true;
															break;
														}
3212
													}
3213 3214 3215 3216 3217 3218 3219 3220
													if (!bad_surface[ns]) {
														if (Math.abs(surf_disp_diff) <= maxDiff){
															fit = ns;   // no rating for fit "quality" here
															num_fit ++;
														}
														if (Math.abs(surf_disp_diff) <= minDiffOther){
															num_fit_other ++;
														}
3221
														// separately calculate for center of the tiles getParentNsTile
3222
														TileData td = tileData[nSurfTile][ns];
3223
														if (tileData[nSurfTile][ns].getParentNsTile() == nSurfSuperTile){
3224 3225 3226 3227 3228 3229 3230 3231 3232
															center_surface[ns] = true;
															if (Math.abs(surf_disp_diff) <= maxDiff){
																fit_center = ns;   // no rating for fit "quality" here
																num_fit_center ++;
															}
															if (Math.abs(surf_disp_diff) <= minDiffOther){
																num_fit_other_center ++;
															}
														}
3233 3234 3235
													}
												}
											}
3236 3237 3238 3239 3240 3241 3242 3243
											if (useCenter && (num_fit_center > 0)) { // use only center if possible
												fit =           fit_center;
												num_fit =       num_fit_center;
												num_fit_other = num_fit_other_center;
												for (int i = 0; i < center_surface.length; i++){
													if (!center_surface[i]) bad_surface[i] = true;
												}
											}
3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254
											if (num_fit < 1){
												stats_all[numThread][TOO_FAR] ++;
											} else if ((num_fit == 1) && (num_fit_other <= 1)){ // assign
												tileLayers[fml][nTile] = fit + 1;
												stats_all[numThread][NEW_ASSIGNED] ++;
											} else if (!enMulti) {
												stats_all[numThread][NOT_UNIQUE] ++;
											} else { // multi, enabled
												int [] candidates =       new int     [num_fit_other];
												boolean [] close_enough = new boolean [num_fit_other];
												num_fit_other = 0;
3255
												for (int ns = 0; ns < tileData[nSurfTile].length; ns++) if (!bad_surface[ns]){ // not all 8 neighbors
3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266
													double surf_disp_diff = getNormDispFromSurface (
															dispStrength[fml][0][nTile], // double disp_tile,
															tileData[nSurfTile][ns].getDisparity(), // double disp_surf,
															dispNorm); //double disp_norm)
													if (((surf_disp_diff >= 0) && en_higher) || ((surf_disp_diff <= 0) && en_lower)){
														if (Math.abs(surf_disp_diff) <= minDiffOther){
															close_enough[num_fit_other] = (Math.abs(surf_disp_diff) <= maxDiff);
															candidates[num_fit_other++] = ns;
														}
													}
												}
3267 3268 3269
												if (dl > 0) {
													System.out.print("assignTilesToSurfaces(): nTile="+nTile+", candidates=");
													for (int ii = 0; ii < candidates.length; ii++){
3270
														System.out.print(" "+candidates[ii]);
3271
													}
3272
													System.out.println();
3273
												}
3274 3275 3276 3277
												double [][][] distances = new double [num_fit_other][field_size  * field_size ][];
												// for each local index get surface tile index
												int [] surfIndices =  new int [field_size  * field_size];
												int [] imageIndices = new int [field_size  * field_size];
3278
												int stx0 = (nTile % imageTilesX) - iradius; //
3279
												int sty0 = (nTile / imageTilesX) - iradius;
3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294
												for (int iy = 0; iy < field_size; iy++){
													for (int ix = 0; ix < field_size; ix++){
														int indx = iy * field_size + ix;
														surfIndices[indx] = (sty0 + iy)*  surfTilesX + (stx0 + ix);
														imageIndices[indx] = getImageTileIndex(surfIndices[indx]);
													}
												}
												// calculate distances from the center point for each surface with wave
												// algorithm, first regardless of who is closer.
												// later, when comparing pairs only use the same side
												for (int isurf = 0; isurf < num_fit_other; isurf++){
													ArrayList<Point> lwave = new ArrayList<Point>();
													Point p0 = new Point(center_index, candidates[isurf]);
													distances[isurf][p0.x] = new double [tileData[nSurfTile].length];
													distances[isurf][p0.x][p0.y] = cost_start;
3295 3296 3297
													if (dl > 0) {
														System.out.println("Add: p0.x="+p0.x+", p0.y="+p0.y);
													}
3298 3299 3300 3301 3302
													lwave.add(p0);
													// run wave build radius (plus 1.0) along each surface connections,
													// until next radius >= radius
													while (!lwave.isEmpty()){
														p0 = lwave.remove(0);
3303
														TileData [] dbg_tileData = tileData[surfIndices[p0.x]];
3304
														int [] neibs = tileData[surfIndices[p0.x]][p0.y].getNeighbors();
3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317
														if (dl > 0) {
															System.out.println("Remove: p0.x="+p0.x+", p0.y="+p0.y+" surfIndices[p0.x]="+surfIndices[p0.x]+
																	" neibs:"+
																	" [ "+((neibs[0] >= 0)? neibs[0]:"-")+
																	" | "+((neibs[1] >= 0)? neibs[1]:"-")+
																	" | "+((neibs[2] >= 0)? neibs[2]:"-")+
																	" | "+((neibs[3] >= 0)? neibs[3]:"-")+
																	" | "+((neibs[4] >= 0)? neibs[4]:"-")+
																	" | "+((neibs[5] >= 0)? neibs[5]:"-")+
																	" | "+((neibs[6] >= 0)? neibs[6]:"-")+
																	" | "+((neibs[7] >= 0)? neibs[7]:"-")+
																	" ]");
														}
3318 3319 3320 3321 3322 3323 3324 3325 3326
														// try ortho directions first
														double new_dist =  distances[isurf][p0.x][p0.y] + cost_ortho;
														if (new_dist <= (radius + cost_start)) {
															for (int dir = 0; dir < 8; dir +=2) if ( neibs[dir] >= 0){
																Point pn = new Point (p0.x + ldirs8[dir], neibs[dir]);
																if (distances[isurf][pn.x] == null){
																	distances[isurf][pn.x] = new double [tileData[surfIndices[pn.x]].length];
																}
																if ((distances[isurf][pn.x][pn.y] == 0) || (distances[isurf][pn.x][pn.y] > new_dist)){
3327 3328 3329 3330 3331
																	if (dl > 0) {
																		System.out.println("Add ortho: p0.x="+p0.x+", p0.y="+p0.y+
																				" distances["+isurf+"]["+pn.x+"]["+pn.y+"]="+distances[isurf][pn.x][pn.y]+
																				", new_dist="+new_dist);
																	}
3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345
																	distances[isurf][pn.x][pn.y] = new_dist;
																	lwave.add(pn);
																}
															}
														}
														// try diagonal directions second
														new_dist =  distances[isurf][p0.x][p0.y] + cost_diag;
														if (new_dist <= (radius + cost_start)) {
															for (int dir = 1; dir < 8; dir +=2) if ( neibs[dir] >= 0){
																Point pn = new Point (p0.x + ldirs8[dir], neibs[dir]);
																if (distances[isurf][pn.x] == null){
																	distances[isurf][pn.x] = new double [tileData[surfIndices[pn.x]].length];
																}
																if ((distances[isurf][pn.x][pn.y] == 0) || (distances[isurf][pn.x][pn.y] > new_dist)){
3346 3347 3348 3349 3350
																	if (dl > 0) {
																		System.out.println("Add diag: p0.x="+p0.x+", p0.y="+p0.y+
																				" distances["+isurf+"]["+pn.x+"]["+pn.y+"]="+distances[isurf][pn.x][pn.y]+
																				", new_dist="+new_dist);
																	}
3351 3352 3353 3354 3355 3356
																	distances[isurf][pn.x][pn.y] = new_dist;
																	lwave.add(pn);
																}
															}
														}
													}
3357
												}
3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382
												if (dl > 0) {
													for (int cand = 0; cand < distances.length; cand ++){
														int num_dist_layers = 0;
														for (int i = 0; i < distances[cand].length; i++){
															if ((distances[cand][i] != null) && (distances[cand][i].length > num_dist_layers)){
																num_dist_layers = distances[cand][i].length;
															}
														}
														for (int dist_l = 0; dist_l < num_dist_layers; dist_l++){
															System.out.println("Candidate #"+cand+", layer "+dist_l);
															for (int ddy = 0; ddy < field_size; ddy ++){
																for (int ddx = 0; ddx < field_size; ddx ++){
																	if ((distances[cand][ddy * field_size + ddx] == null) ||
																			(distances[cand][ddy * field_size + ddx].length <= dist_l) ||
																			(distances[cand][ddy * field_size + ddx][dist_l] == 0)){
																		System.out.print("--- ");
																	} else {
																		System.out.print(distances[cand][ddy * field_size + ddx][dist_l]+" ");
																	}
																}
																System.out.println();
															}
														}
													}
												}
3383 3384


3385 3386
												// pulls belong to pairs, not individual surfaces (difference when they cross)
												double [][] surface_pulls = new double [num_fit_other][num_fit_other];
3387 3388
												// now calculate advantage of each one surface (close_enough) to each other (as a ratio)
												// and then see if it is above minAdvantage
3389 3390 3391 3392 3393
												for (int other_ml = 0; other_ml < tileLayers.length; other_ml++) if (tileLayers[other_ml] != null){
													for (int lindx = 0; lindx < imageIndices.length; lindx ++){
														if (imageIndices[lindx] >= 0) {
															int nsurf = tileLayers_src[other_ml][imageIndices[lindx]] - 1; // assigned surface number (>=0)
															if ( nsurf >= 0){
3394
																double strength = dispStrength[other_ml][1][imageIndices[lindx]] + addStrength; // add strength so very weak count
3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413
																// see if this tile belongs to any of the considered surfaces
																int num_found = 0;
																boolean [] on_surface = new boolean [num_fit_other];
																for (int i = 0; i < num_fit_other; i++) {
																	if ((distances[i][lindx] != null) && (distances[i][lindx][nsurf] > 0.0)){
																		num_found++;
																		on_surface[i] = true;
																	}
																}
																if (num_found > 0) { // tile lies on at least one of the considered surfaces
																	for (int is1 = 0; is1 < num_fit_other; is1++) if (on_surface[is1]) {
																		// is2 can be any other candidate, just check it is on the same side
																		// of is1 as in the center (new tile)
																		for (int is2 = 0; is2 < num_fit_other; is2++) if (is2 != is1) {
																			boolean good_pair = true;
																			if (distances[is2][lindx] != null) { // otherwise OK
																				for (int i = 0; i < distances[is2][lindx].length; i++){
																					if (distances[is2][lindx][i] >= 0){
																						if (	((is2 > is1) && (i < nsurf)) ||
3414
																								((is2 < is1) && (i > nsurf))) {
3415 3416 3417 3418 3419 3420 3421 3422 3423
																							good_pair = false; // surfaces cross between
																							break;
																						}
																					}
																				}
																			}
																			if (good_pair){
																				double r = distances[is1][lindx][nsurf] - cost_start;
																				// pull to is1 when in pair with is2
3424
																				surface_pulls[is1][is2] += Math.exp(- r * r * rsigma2) * strength ;
3425 3426 3427 3428 3429
																			}
																		}
																	}
																}
															}
3430 3431 3432
														}
													}
												}
3433

3434 3435 3436
												double [][] advantages = new double [num_fit_other][num_fit_other];
												for (int is1 = 0; is1 < num_fit_other; is1++){
													for (int is2 = is1 + 1; is2 < num_fit_other; is2++){
3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453
														double ad1 = surface_pulls[is1][is2] + minPull;
														double ad2 = surface_pulls[is2][is1] + minPull;
														// normally minPull >0.0, if not - prevent div by zero
														if ((ad1 == 0) || (ad2 == 0)){
															if ((ad1 == 0) && (ad2 == 0)){
																ad1 = 1.0;
																ad2 = 1.0;
															} else if (ad1 == 0) {
																ad2 = 2.0 * minAdvantage;
																ad1 = 1.0;
															} else {
																ad1 = 2.0 * minAdvantage;
																ad2 = 1.0;
															}
														}
														advantages[is1][is2] = ad1/ad2;
														advantages[is2][is1] = ad2/ad1;
3454
														if (surfStrPow != 0.0){ // consider surface strength also
3455 3456 3457 3458 3459 3460 3461
															double str1 = tileData[nSurfTile][candidates[is1]].getStrength();
															double str2 = tileData[nSurfTile][candidates[is1]].getStrength();
															if ((str1 > 0.0) && (str2 > 0.0)){
																advantages[is1][is2] *= Math.pow(str1/str2, surfStrPow);
																advantages[is2][is1] = 1.0/advantages[is1][is2];
															} else if (str1 > 0.0) {
																advantages[is1][is2] = 2.0 * minAdvantage; // sure will win
3462
																advantages[is2][is1] = (minAdvantage > 0.0) ? (1.0/advantages[is1][is2]) : 0.0;
3463 3464 3465
																//minAdvantage
															} else if (str2 > 0.0) {
																advantages[is2][is1] = 2.0 * minAdvantage; // sure will win
3466
																advantages[is1][is2] = (minAdvantage > 0.0) ? (1.0/advantages[is2][is1]) : 0.0;
3467
															} else { // both zero - do nothing about surface strengths
3468

3469 3470 3471 3472 3473 3474 3475 3476 3477 3478
															}
														}
													}
												}
												// Now see if we have a winner that is (2 could not satisfy, look for the first:
												// a) close enough, and
												// b) sufficient advantage over all other candidates
												fit = -1;
												for (int is1 = 0; is1 < num_fit_other; is1++){
													if (close_enough[is1]){ //
3479
														boolean is_a_winner = true;
3480 3481
														for (int is2 = is1 + 1; is2 < num_fit_other; is2++){
															if (advantages[is1][is2] < minAdvantage){
3482 3483 3484
																if (dl > 0) {
																	System.out.println("assignTilesToSurfaces() advantages["+is1+"]["+is2+"]="+advantages[is1][is2]);
																}
3485
																is_a_winner = false;
3486 3487 3488
																if (dl > 0) {
																	System.out.println("assignTilesToSurfaces(): Not a winner, advantages < "+minAdvantage);
																}
3489 3490
																break;
															}
3491
														}
3492 3493
														if (is_a_winner){
															fit = is1;
3494 3495 3496
															if (dl > 0) {
																System.out.println("assignTilesToSurfaces(): "+is1+" is a winner!");
															}
3497 3498 3499 3500 3501
															break;
														}
													}
												}
												if (fit >= 0) {
3502
													tileLayers[fml][nTile] = candidates[fit] + 1;
3503 3504 3505 3506
													stats_all[numThread][NEW_ASSIGNED] ++;
												} else {
													stats_all[numThread][NOT_UNIQUE] ++;
												}
3507 3508 3509 3510 3511 3512 3513
											}
										}
									}
								}
							}
						}
					};
3514
				}
3515 3516 3517 3518 3519 3520 3521 3522 3523
				ImageDtt.startAndJoin(threads);
			}
			for (int nt = 0; nt < numThreads; nt ++){
				for (int i = 0 ; i < stats_new.length; i++ ){
					stats_new[i] += stats_all[nt][i];
				}
			}
			return stats_new;
		}
3524

3525 3526 3527 3528 3529
		boolean isInit()
		{
			return this.tileLayers != null;
		}

3530

3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543
		public int [][] combineTileLayers(
				final boolean overwrite,
				final int [][] dst,
				final int [][] src
			){
			for (int ml = 0; ml < dst.length; ml++){
				if (src[ml] != null){
					if (dst[ml] == null) {
						dst[ml] = src[ml].clone();
					} else {
						for (int i = 0; i < src[ml].length; i++) if ((src[ml][i] != 0) && (overwrite || (dst[ml][i] == 0))){
								dst[ml][i] = src[ml][i];
						}
3544

3545 3546 3547 3548
					}
				}
			}
			return dst;
3549

3550
		}
3551 3552


3553 3554 3555 3556 3557 3558 3559 3560
		public int [][] newTileLayers(
				final boolean [][]       tileSel
			){
			int [][] tileLayers = new int [tileSel.length][];
			for (int ml = 0; ml < tileSel.length; ml++){
				if (tileSel[ml] != null){
					tileLayers[ml] = new int [tileSel[ml].length];
					for (int i = 0; i < tileSel[ml].length; i++){
3561
						tileLayers[ml][i] = tileSel[ml][i] ? 0: -1; // 0 - unassigned, -1 - prohibited
3562 3563 3564 3565
					}
				}
			}
			return tileLayers;
3566

3567
		}
3568

3569 3570 3571 3572 3573 3574 3575
		public int [] InitTilesAssignment(
				final boolean            force,
				final double [][][]      dispStrength,
				final boolean [][]       tileSel,
                final int                debugLevel)
		{
			if (force || (this.tileLayers == null)) {
3576
				this.tileLayers = newTileLayers(tileSel);
3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587
			}
			int []stats = getTilesAssignStats(tileLayers);
			if (debugLevel >= -1) {
				System.out.println("sortTilesToSurfaces(): using "+stats[STAT_NUM_ML] +" measurement layers"+
						", number of assigned tiles: "+stats[STAT_ASSIGNED]+
						", number of unassigned tiles: "+stats[STAT_UNASSIGNED]+
						", number of prohibited tiles: "+stats[STAT_PROHIBITED]+
						", number of impossible tiles: "+stats[STAT_IMPOSSIBLE]);
			}
			return stats;
		}
3588

3589 3590 3591 3592
		public int [] statTileLayers(
				final int [][]      tileLayers,
				final boolean [][]       tileSel,
				final int                debugLevel)
3593
		{
3594 3595 3596 3597 3598 3599 3600 3601 3602 3603
			int []stats = getTilesAssignStats(tileLayers);
			if (debugLevel >= -1) {
				System.out.println("sortTilesToSurfaces(): using "+stats[STAT_NUM_ML] +" measurement layers"+
						", number of assigned tiles: "+stats[STAT_ASSIGNED]+
						", number of unassigned tiles: "+stats[STAT_UNASSIGNED]+
						", number of prohibited tiles: "+stats[STAT_PROHIBITED]+
						", number of impossible tiles: "+stats[STAT_IMPOSSIBLE]);
			}
			return stats;
		}
3604 3605


3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628
		public boolean [][] extractSelection(
				final int         debugLevel,
				final int         dbg_X,
				final int         dbg_Y)
		{
			//			boolean [][] wave_conf = new boolean [tileLayers.length][]; // true when wave or if confirmed
			int num_tiles = 0;
			for (int ml = 0; ml < tileLayers.length; ml++) if ((tileLayers[ml] != null) && (tileLayers[ml].length > 0)){
				num_tiles = tileLayers[ml].length;
				break;
			}
			boolean [][] assigned_tiles = new boolean [num_tiles][];
			for (int ml = 0; ml < tileLayers.length; ml ++) if (tileLayers[ml] != null){
				for (int nTile0 = 0; nTile0 < tileLayers[ml].length; nTile0++) if (tileLayers[ml][nTile0] > 0) {
					int nSurfTile = getSurfaceTileIndex(nTile0);
					if (tileData[nSurfTile] != null) {
						int l = tileData[nSurfTile].length;
						assigned_tiles[nTile0] = new boolean [l];
					}
					assigned_tiles[nTile0][tileLayers[ml][nTile0]-1] = true;
				}
			}
			return assigned_tiles;
3629 3630 3631
		}


3632 3633 3634 3635 3636
		public int [][] enumerateClusters(
				final boolean [][] selection,
				final int          debugLevel,
				final int          dbg_X,
				final int          dbg_Y)
3637
		{
3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664
			int [][] enum_clust = new int [selection.length][];
			for (int i = 0; i < enum_clust.length; i++){
				if (selection[i] != null) enum_clust[i] = new int [selection[i].length];
			}
			TileNeibs tnImage =   new TileNeibs(imageTilesX, imageTilesY);
			//			TileNeibs tnSurface = new TileNeibs(stilesX * superTileSize, stilesY * superTileSize);
			int num_cluster = 1;
			for (int nTile0 = 0; nTile0 <selection.length; nTile0++) if (selection[nTile0] != null) {
				for (int nl0 = 0; nl0 < selection[nTile0].length; nl0++) if (selection[nTile0][nl0] && ((enum_clust[nTile0][nl0] == 0))) {
					ArrayList<Point> wave_list = new ArrayList<Point>();
					Point p = new Point(nTile0, nl0); // image tile number, surface index (0-based)
					enum_clust[p.x][p.y] = num_cluster;
					wave_list.add(p);
					while (wave_list.size() > 0){
						Point pt = wave_list.remove(0);
						int [] neibs = tileData[getSurfaceTileIndex(pt.x)][pt.y].getNeighbors();
						for (int dir  = 0; dir < tnImage.dirs; dir++) if (neibs[dir] >= 0){
							int nTile1 = tnImage.getNeibIndex(pt.x, dir);
							if (nTile1 >= 0) {
								int nl1 = neibs[dir];
								if ((selection[nTile1] != null) && selection[nTile1][nl1] && (enum_clust[nTile1][nl1] == 0) ){ // exists and not yet counted
									Point p1 = new Point(nTile1, nl1);
									enum_clust[nTile1][nl1] = num_cluster;
									wave_list.add(p1);
								}
							}
						}
3665
					}
3666
					num_cluster ++;
3667 3668
				}
			}
3669 3670 3671
			num_cluster --;
			if (debugLevel > -1 ) {
				System.out.println("enumerateClusters(): found " + num_cluster + " clusters");
3672
			}
3673 3674
			return enum_clust;
		}
3675

3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687
		public int getNumClusters(
				int [][] clusters)
		{
			int max_number = 0;
			for (int nTile = 0; nTile <clusters.length; nTile++) if (clusters[nTile] != null) {
				for (int nl = 0; nl < clusters[nTile].length; nl ++){
					if (clusters[nTile][nl] > max_number){
						max_number = clusters[nTile][nl];
					}
				}
			}
			return max_number;
3688

3689
		}
3690

3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747
		public int [][] clusterStats(
				int [][]           clusters,
				final int          debugLevel,
				final int          dbg_X,
				final int          dbg_Y)
		{
			TileNeibs tnImage =   new TileNeibs(imageTilesX, imageTilesY);
			int max_number = getNumClusters(clusters);
			if (debugLevel > -1){
				System.out.println("clusterStats(): number of clusters: "+max_number);
			}
			int [][] stats0 = new int[max_number][CLUST_NUM_STATS]; // number of tiles, overlaps (each pair), conflicts-a (in dir, but connected to dif.), conflicts-b (no link)
			for (int nTile = 0; nTile <clusters.length; nTile++) if (clusters[nTile] != null) {
				for (int nl = 0; nl < clusters[nTile].length; nl ++){
					int nclust = clusters[nTile][nl];
					if (nclust > 0) {
						stats0[nclust - 1][CLUST_NUM_TILES]++;
						int num_same = 0;
						for (int nl1 = 0; nl1 < clusters[nTile].length; nl1 ++){
							if ((nl1 != nl) && (clusters[nTile][nl1] == nclust)){
								num_same ++;
							}
						}
						if (stats0[nclust - 1][CLUST_NUM_LAYERS] < (num_same + 1)){
							stats0[nclust - 1][CLUST_NUM_LAYERS] = (num_same + 1);
						}
						if (num_same > 0) {
							stats0[nclust - 1][CLUST_NUM_OVERLAPS]++;
							if (num_same > 1) {
								stats0[nclust - 1][CLUST_NUM_MULTI]++;
							}
						}
						if (num_same == 0) { // do not bother with overlapping tiles
							if (stats0[nclust - 1][CLUST_NUM_LAYERS] == 0){
								stats0[nclust - 1][CLUST_NUM_LAYERS] = 1;
							}
							int [] neibs = tileData[getSurfaceTileIndex(nTile)][nl].getNeighbors();
							for (int dir  = 0; dir < tnImage.dirs; dir++) if (neibs[dir] >= 0){
								int nTile1 = tnImage.getNeibIndex(nTile, dir);
								if ((nTile1 >= 0) && (clusters[nTile1] != null)) {
									int num_same1 = 0;
									for (int nl1 = 0; nl1 < clusters[nTile1].length; nl1 ++){
										if (clusters[nTile1][nl1] == nclust){
											num_same1 ++;
										}
									}
									if (num_same1 > 0){
										if (neibs[dir] <0 ){
											stats0[nclust - 1][CLUST_NUM_CONFLICTS_B]++;
										} else if (clusters[nTile1][neibs[dir]] != nclust){
											stats0[nclust - 1][CLUST_NUM_CONFLICTS_A]++;
										}
									}
								}
							}
						}
					}
3748
				}
3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780
			}
			// now sort tiles by the number of tiles in it
			ArrayList<Point> sort_list = new ArrayList<Point>(max_number);
			for (int nclust = 0 ; nclust < max_number; nclust++) {
				sort_list.add(new Point(stats0[nclust][CLUST_NUM_TILES], nclust));
			}
			Collections.sort(sort_list, new Comparator<Point>() {
				@Override
				public int compare(Point lhs, Point rhs) {
					// -1 - less than, 1 - greater than, 0 - equal, all inverted for descending
					return (lhs.x > rhs.x) ? -1 : (lhs.x < rhs.x) ? 1 : 0;
				}
			});
			int [][] stats = new int[max_number][CLUST_NUM_STATS]; // number of tiles, overlaps (each pair), conflicts-a (in dir, but connected to dif.), conflicts-b (no link)
			for (int i = 0; i < max_number; i++){
				stats[i] = stats0[sort_list.get(i).y];
				stats[i][CLUST_NUM_INDEX] = sort_list.get(i).y + 1; // zero-based -> 1-based
			}
			return stats;
		}

		public void showClusterStats(
				int [][] cluster_stats,
				int max_clusters){
			System.out.println("Detected "+cluster_stats.length+" clusters");
			if (max_clusters == 0){
				max_clusters = cluster_stats.length;
			}
			for (int i = 0; (i < cluster_stats.length) && (i < max_clusters); i++){
				System.out.print(i+": #"+ cluster_stats[i][CLUST_NUM_INDEX]);
				System.out.print(  " tiles: "+          cluster_stats[i][CLUST_NUM_TILES]);
				System.out.print(  " layers: "+         cluster_stats[i][CLUST_NUM_LAYERS]);
3781

3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819
				System.out.print(  " overlaps: "+       cluster_stats[i][CLUST_NUM_OVERLAPS]);
				System.out.print(  " multi-overlaps: "+ cluster_stats[i][CLUST_NUM_MULTI]);
				System.out.print(  " coflicts A: "+ cluster_stats[i][CLUST_NUM_CONFLICTS_A]);
				System.out.print(  " coflicts B: "+ cluster_stats[i][CLUST_NUM_CONFLICTS_B]);
				System.out.println();
			}
		}

		public void showClusters(
				String title,
				int [][] cluster_stats,
				int max_clusters,
				int [][] clusters)
		{
			System.out.println("showClusters("+title+"," +max_clusters+"), numClusters = "+cluster_stats.length);

//			TileNeibs tnImage =   new TileNeibs(imageTilesX, imageTilesY);
			int num_slices = 0;
			int num_tiles = clusters.length;
			if (max_clusters == 0){
				max_clusters = cluster_stats.length;
			}
			if (max_clusters > cluster_stats.length){
				max_clusters = cluster_stats.length;
			}
			for (int i = 0; i < max_clusters; i++){
				num_slices += cluster_stats[i][CLUST_NUM_LAYERS];
			}
			double [][] img_clust = new double [num_slices][num_tiles];
			for (int i = 0; i < num_slices; i ++){
				for (int j = 0; j < num_tiles; j ++){
					img_clust[i][j] = Double.NaN;
				}
			}
			int [] rev_clust = new int [cluster_stats.length];
			for (int i = 0; i < cluster_stats.length; i ++){
				rev_clust[cluster_stats[i][CLUST_NUM_INDEX] - 1] = i;
			}
3820

3821 3822 3823 3824 3825 3826 3827 3828 3829
			String [] titles = new String [num_slices];
			int [] slice_first = new int [num_slices];
			int nslice = 0;
			for (int i = 0; i < max_clusters; i++){
				slice_first[i]=nslice;
				for (int j = 0; j < cluster_stats[i][CLUST_NUM_LAYERS]; j++){
					titles[nslice++] = "cluster-"+i+((cluster_stats[i][CLUST_NUM_LAYERS]>1)?("_"+j):"");
				}
			}
3830

3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850
			for (int nTile = 0; nTile < num_tiles; nTile++) if (clusters[nTile] != null){
				int nSurfTile = getSurfaceTileIndex(nTile);
				boolean [] rend = new boolean [clusters[nTile].length];
				for (int i = 0; i < rend.length; i++) if (!rend[i] && (clusters[nTile][ i] > 0)) { // if (!rend[i] && (rev_clust[clusters[nTile][ i]] < max_clusters)){
					if (((clusters[nTile][ i] -1) >= rev_clust.length) || ((clusters[nTile][ i] -1) < 0)){
						System.out.println("showClusters() BUG:, clusters["+nTile+"]["+ i+"]-1 ("+(clusters[nTile][ i] -1)+") >= "+rev_clust.length);

					} else {
						if (rev_clust[clusters[nTile][ i] - 1] < max_clusters){
							int clust_index = clusters[nTile][ i] -1;
							int clust_layer = 0;
							for (int j = i; j < rend.length; j++) if ((clusters[nTile][ j] -1) == clust_index) {
								rend[j] = true;
								img_clust[slice_first[rev_clust[clust_index]] + clust_layer][nTile] = tileData[nSurfTile][j].getDisparity();
								clust_layer++;
							}
						}
					}
				}
			}
3851
			ShowDoubleFloatArrays.showArrays(img_clust,  imageTilesX, imageTilesY, true, title, titles);
3852 3853
		}

3854 3855 3856
		public boolean [][] growClusterOnce( // used from inside threads
				final boolean [][] cluster_local_pure,
				final int []       window,
3857 3858
				final int []       img_indices,
				final int []       surf_indices,
3859 3860 3861
				final int          debugLevel,
				final int          dbg_X,
				final int          dbg_Y)
3862

3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890
		{
			int num_tiles = img_indices.length;
			int width =  window[2];
			int height = window[3];
			boolean [][] grown_cluster = new boolean [num_tiles][];
			for (int neTile = 0; neTile < num_tiles; neTile++){
				if (cluster_local_pure[neTile] != null){
					grown_cluster[neTile] = cluster_local_pure[neTile].clone();
				}
			}
			int dbg_ntiles1 = 0;

			if (debugLevel > 0) {
				for (int neTile = 0; neTile < num_tiles; neTile++){
					if (grown_cluster[neTile] != null){
						for (int nl = 0; nl < grown_cluster[neTile].length; nl++){
							if (grown_cluster[neTile][nl]) dbg_ntiles1 ++;
						}
					}
				}
				System.out.println("growClusterOnce(): number of tiles = "+dbg_ntiles1);
			}
			final TileNeibs tnWindow =   new TileNeibs(width,height);

			for (int neTile0 = 0; neTile0 < num_tiles; neTile0++) if (cluster_local_pure[neTile0] != null){
				for (int nl0 = 0; nl0 < cluster_local_pure[neTile0].length; nl0++){
					if (cluster_local_pure[neTile0][nl0]){ // source should be single-layer, but ...
						int nSurfTile0 = surf_indices[neTile0];
3891
						int [] neibs = tileData[nSurfTile0][nl0].getNeighbors();
3892 3893

						for (int dir = 0; dir <  tnWindow.dirs; dir++) {
3894
							int nl1 = neibs[dir];
3895 3896 3897
							if (nl1 < 0){
								if (debugLevel >-1) {
									System.out.println("growClusterOnce(): Expected 8 neighbors for tile nSurfTile0="+
3898
											nSurfTile0+":"+nl0+" neibs["+dir+"] = "+nl1);
3899 3900 3901 3902 3903 3904 3905 3906 3907
								}
							} else {
								int neTile1 = tnWindow.getNeibIndex(neTile0, dir);
								if (neTile1 >= 0) {
									if (	((cluster_local_pure[neTile1] == null) || !cluster_local_pure[neTile1][nl1]) &&
											((grown_cluster[neTile1] == null) || !grown_cluster[neTile1][nl1])) {
										if (grown_cluster[neTile1] == null) {
											int nSurfTile1 = surf_indices[neTile1];
											// should never be null as it is connected from nSurfTile0
3908 3909 3910 3911 3912 3913
											if (nSurfTile1 >=0) {
												grown_cluster[neTile1] = new boolean [tileData[nSurfTile1].length]; // out_of_bounds
											}
										}
										if(grown_cluster[neTile1] != null){
											grown_cluster[neTile1][nl1] = true;
3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932
										}
									}
								}
							}
						}
					}
				}
			}
			if (debugLevel > 0) {
				int dbg_ntiles2 = 0;
				for (int neTile = 0; neTile < num_tiles; neTile++){
					if (grown_cluster[neTile] != null){
						for (int nl = 0; nl < grown_cluster[neTile].length; nl++){
							if (grown_cluster[neTile][nl]) dbg_ntiles2 ++;
						}
					}
				}
				System.out.println("growClusterOnce(): new number of tiles = "+dbg_ntiles2+" (was "+dbg_ntiles1+")");
			}
3933

3934 3935
			return grown_cluster;
		}
3936

3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952
		public void setSurfaceData(
				final int [][] cluster_groups,
				final int [][] clusters_pure, // each tile/layer belongs to a single pure cluster
				final int      debugLevel,
				final int      dbg_X,
				final int      dbg_Y)
		{
			if (debugLevel >-1){
				System.out.println("setSurfaceData(): groups: "+cluster_groups.length);
			}
			final SurfaceData [] sdata = new SurfaceData[cluster_groups.length];
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
			final int [] tilesWH = {imageTilesX, imageTilesY};
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
3953
					@Override
3954 3955
					public void run() {
						for (int iGClust = ai.getAndIncrement(); iGClust < sdata.length; iGClust = ai.getAndIncrement()) {
3956 3957
							int dl = ((debugLevel > -1) && (iGClust == dbg_X)) ? 1:0;

3958 3959 3960 3961
							int [] window = getClusterBBox(
									cluster_groups[iGClust], // final int []   nClust, // 1-based
									1,                       // final int      border,
									clusters_pure);          // final int [][] clusters)
3962

3963 3964 3965
							int [][] tile_indices =  getClusterBBoxIndices(
									window,                  // final int [] window,
									0);                      // border); // final int    border) // maybe 0, actual value just saves time
3966
							int [] img_tile_indices = tile_indices[0];
3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983
							int [] surf_tile_indices = tile_indices[1];
							boolean [][] combined = new boolean [img_tile_indices.length][];
							if (dl > 0){
								String dbg_s = "";
								for (int indxClust = 0; indxClust < cluster_groups[iGClust].length; indxClust++){
									dbg_s += " " +cluster_groups[iGClust][indxClust];
								}
								System.out.println("setSurfaceData(): iGClust = "+iGClust+" window = [ "+window[0]+", "+window[1]+", "+window[2]+", "+window[3]+" ],  clusters: ["+dbg_s+"]");
							}
							for (int indxClust = 0; indxClust< cluster_groups[iGClust].length; indxClust++){
								if (dl > 0){
									System.out.println("setSurfaceData():  cluster_groups["+iGClust+"]["+indxClust+"] = "+cluster_groups[iGClust][indxClust]);
								}
								boolean [][] extracted_cluster = extractCluster(
										cluster_groups[iGClust][indxClust],   // final int      numToSplit, // 1-based
										clusters_pure,       // final int [][] clusters,
										window,              // final int []   window,
3984
										img_tile_indices,    // final int []   bbox_indices,
3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007
										debugLevel,          // final int      debugLevel,
										dbg_X,               // final int      dbg_X,
										dbg_Y);              // final int      dbg_Y)
								for (int neTile = 0; neTile < combined.length; neTile++){
									if (extracted_cluster[neTile] != null){
										if (combined[neTile] == null){
											combined[neTile] = extracted_cluster[neTile].clone();
										} else {
											for (int nl = 0; nl < extracted_cluster[neTile].length; nl++){
												combined[neTile][nl] |= extracted_cluster[neTile][nl];
											}
										}
									}
								}
							}
							boolean [] pure_sel = new boolean [combined.length];
							for (int neTile = 0; neTile < combined.length; neTile++){
								if (combined[neTile] != null){
									for (int nl = 0; nl < combined[neTile].length; nl++){
										if (combined[neTile][nl]) {
											pure_sel[neTile] = true;
											break;
										}
4008
									}
4009 4010 4011 4012 4013
								}
							}
							boolean [][] grown_combined = growClusterOnce( // used from inside threads
									combined,   // final boolean [][] cluster_local_pure,
									window,            // final int []   window,
4014 4015
									img_tile_indices,  // final int []   bbox_indices,
									surf_tile_indices, // final int []       surf_indices,
4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030
									0, // dl, // debugLevel,       // final int      debugLevel,
									dbg_X,            // final int      dbg_X,
									dbg_Y);           // final int      dbg_Y)
							boolean [] selected = new boolean [combined.length];
							boolean [] border  =  new boolean [combined.length];
							for (int neTile = 0; neTile < grown_combined.length; neTile++){
								if (grown_combined[neTile] != null){
									for (int nl = 0; nl < grown_combined[neTile].length; nl++){
										if (grown_combined[neTile][nl]) {
											selected[neTile] = true;
											if (!pure_sel[neTile]){
												border[neTile] = true;
											}
											break;
										}
4031
									}
4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056
								}
							}
							sdata[iGClust] = new 	SurfaceData(
									tilesWH,
									window);
							sdata[iGClust].setSelected(selected);
							sdata[iGClust].setBorder(border);
							sdata[iGClust].setCluster(cluster_groups[iGClust]);
							for (int neTile = 0; neTile < grown_combined.length; neTile++){
								if (selected[neTile]){
									for (int nl = 0; nl < grown_combined[neTile].length; nl++){
										if (grown_combined[neTile][nl]){
											sdata[iGClust].setDisparity(
													neTile,
													tileData[surf_tile_indices[neTile]][nl].getDisparity());
										}
									}
								}
							}
							if (dl > 0){
								System.out.println("setSurfaceData(): sdata ["+iGClust+"] prepared");
							}
						}
					}
				};
4057
			}
4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083
			ImageDtt.startAndJoin(threads);
			ArrayList<SurfaceData> sdata_list = new ArrayList<SurfaceData>();
			for (int i = 0; i < sdata.length; i++){
				sdata_list.add(sdata[i]);
			}
			Collections.sort(sdata_list, new Comparator<SurfaceData>() {
				@Override
				public int compare(SurfaceData lhs, SurfaceData rhs) {
					// -1 - less than, 1 - greater than, 0 - equal, all inverted for descending
					return (lhs.getSize(true) > rhs.getSize(true)) ? -1 : (lhs.getSize(true) < rhs.getSize(true)) ? 1 : 0;
				}
			});
			this.surfaceData = 	sdata_list.toArray(new SurfaceData[0] );
			if (debugLevel >-1){
				if (debugLevel > 0){
					for (int i = 0; i < this.surfaceData.length; i++) {
						System.out.print(i+": "+this.surfaceData[i].getSize(true)+" ("+this.surfaceData[i].getSize(false)+") [");
						for (int j = 0; j < this.surfaceData[i].getCluster().length; j++){
							System.out.print(this.surfaceData[i].getCluster()[j] +", ");
						}
						System.out.println("]");
					}
				}
				System.out.println("setSurfaceData(): DONE");
			}
 		}
4084

4085 4086 4087 4088 4089 4090 4091
		public SurfaceData getSurfaceData(int indx){
			return this.surfaceData[indx];
		}

		public int getSurfaceDataLength(){
			return this.surfaceData.length;
		}
4092

4093 4094 4095 4096 4097 4098 4099 4100
		public int [][] mergeNoConflict(
				final int [][] matchedGrown,
				final int [][] clusters_grown,
				final int [][] clusters_pure,
				final int      debugLevel,
				final int      dbg_X,
				final int      dbg_Y)
		{
4101
			if (debugLevel > 0){
4102 4103 4104 4105
				System.out.println("mergeNoConflict(): groups: "+matchedGrown.length);
			}
			final int num_grown = matchedGrown.length;
			final int [][][] pre_merged_subs = new int [num_grown][][];
4106

4107 4108 4109 4110
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
4111
					@Override
4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122
					public void run() {
						for (int iGClust = ai.getAndIncrement(); iGClust < num_grown; iGClust = ai.getAndIncrement()) {
							int num_subs = matchedGrown[iGClust].length;
							if (num_subs < 2){ // nothing to split
								pre_merged_subs[iGClust] = new int [num_subs][];
								if (num_subs > 0) { // should always be so?
									pre_merged_subs[iGClust][0] = matchedGrown[iGClust].clone();
								}
							} else { //>= 2 clusters
								int nGClust = iGClust + 1;
								int dl = ((debugLevel > -1) && (num_subs > 3)) ? 3: 0;
4123
								if (dl > 3){
4124 4125
									System.out.println("mergeNoConflict(): nGClust: "+nGClust+" num_subs= "+num_subs);
								}
4126

4127 4128 4129 4130 4131 4132 4133 4134 4135
								// create window for the grown cluster, it will include all subs
								int [] window = getClusterBBox(
										nGClust, // 1-based
										0, // border,
										clusters_grown);

								int [][] tile_indices =  getClusterBBoxIndices(
										window,  // final int [] window,
										0);      // border); // final int    border) // maybe 0, actual value just saves time
4136
								int [] img_tile_indices = tile_indices[0];
4137 4138 4139 4140 4141 4142 4143 4144 4145 4146
								int [] surf_tile_indices = tile_indices[1];
								int num_tiles = img_tile_indices.length;
								int [] clust_sizes = new int [num_subs];
								boolean [][][] subs_pure =  new boolean [num_subs][][];
								boolean [][][] subs_grown = new boolean [num_subs][][];
								for (int nSub = 0; nSub < num_subs; nSub++){
									subs_pure[nSub] = extractCluster(
											matchedGrown[iGClust][nSub],   // final int      numToSplit, // 1-based
											clusters_pure,    // final int [][] clusters,
											window,           // final int []   window,
4147
											img_tile_indices, // final int []   bbox_indices,
4148 4149 4150
											debugLevel,       // final int      debugLevel,
											dbg_X,            // final int      dbg_X,
											dbg_Y);           // final int      dbg_Y)
4151

4152 4153 4154
									subs_grown[nSub] = growClusterOnce( // used from inside threads
											subs_pure[nSub],   // final boolean [][] cluster_local_pure,
											window,            // final int []   window,
4155 4156
											img_tile_indices,  // final int []   bbox_indices,
											surf_tile_indices, // final int []       surf_indices,
4157 4158 4159 4160 4161 4162 4163
											0, // dl, // debugLevel,       // final int      debugLevel,
											dbg_X,            // final int      dbg_X,
											dbg_Y);           // final int      dbg_Y)
								}
								// now build sets of clusters
								// a) connected to current (and having higher number)
								// b) conflicting with current (and having higher number)
4164
								ArrayList<HashSet<Integer>> touching_list = new ArrayList<HashSet<Integer>>();
4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193
								ArrayList<HashSet<Integer>> conflict_list = new ArrayList<HashSet<Integer>>();
								for (int nSub = 0; nSub < num_subs; nSub++){
									touching_list.add(new HashSet<Integer>());
									conflict_list.add(new HashSet<Integer>());
								}
								for (int neTile = 0; neTile < num_tiles; neTile++){
									for (int nSub = 0; nSub < num_subs; nSub++){
										if (subs_grown[nSub][neTile] != null){
											for (int nl1 = 0; nl1 < subs_grown[nSub][neTile].length; nl1++){
												if (subs_grown[nSub][neTile][nl1]){
													clust_sizes[nSub] ++;
													for (int nSub2 = nSub+1; nSub2 < num_subs; nSub2++) if (subs_grown[nSub2][neTile] != null){
														for (int nl2 = 0; nl2 < subs_grown[nSub2][neTile].length; nl2++){ //*
															if (subs_grown[nSub2][neTile][nl2]){
																if (nl1 == nl2) {
																	touching_list.get(nSub).add(new Integer(nSub2));
																	touching_list.get(nSub2).add(new Integer(nSub)); // both ways
																} else {
																	conflict_list.get(nSub).add(new Integer(nSub2));
																	conflict_list.get(nSub2).add(new Integer(nSub)); // both ways
																}
															}
														}
													}
												}
											}
										}
									}
								}
4194

4195 4196 4197 4198 4199 4200 4201 4202 4203 4204
								ArrayList<HashSet<Integer>> groups_list = new ArrayList<HashSet<Integer>>();
								HashSet<Integer> clusters_left = new HashSet<Integer>();
								for (int nSub = 0; nSub < num_subs; nSub++){
									clusters_left.add(new Integer(nSub));
								}
								while (!clusters_left.isEmpty()){
									HashSet<Integer> new_group = new HashSet<Integer>();
									HashSet<Integer> candidates = new HashSet<Integer>();
									HashSet<Integer> conflicts = new HashSet<Integer>();
//									HashSet<Integer> touching = new HashSet<Integer>();
4205

4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219
									// start with the largest of the remaining clusters
									Integer best_sub = -1;
									for (Integer sc:clusters_left){
										if ((best_sub < 0) || (clust_sizes[best_sub] < clust_sizes[sc])){
											best_sub = sc;
										}
									}
									if ( !clusters_left.remove(best_sub)) {
										System.out.println("mergeNoConflict() bug: can not remove"+best_sub);
									}
									new_group.add(best_sub);
									conflicts.addAll(conflict_list.get(best_sub));    // keep track of all accumulated conflicts
									candidates.addAll(touching_list.get(best_sub));   // add all clusters that are touching the current selection
									candidates.removeAll(conflicts);                  // remove all conflicts
4220

4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243
									while (!candidates.isEmpty()) { // add more clusters if possible
										// Find the largest one
										best_sub = -1;
										for (Integer sc:candidates){
											if ((best_sub < 0) || (clust_sizes[best_sub] < clust_sizes[sc])){
												best_sub = sc;
											}
										}
										// add that new cluster
										clusters_left.remove(best_sub);
										new_group.add(best_sub);
										conflicts.addAll(conflict_list.get(best_sub));    // keep track of all accumulated conflicts
										candidates.addAll(touching_list.get(best_sub));   // add all clusters that are touching the current selection
										candidates.removeAll(conflicts);                  // remove all conflicts
										candidates.removeAll(new_group);                  // remove all what is already included
									}
									groups_list.add(new_group);
								}
								pre_merged_subs[iGClust] = new int [groups_list.size()][];
								for (int ng = 0; ng < groups_list.size(); ng++) {
									pre_merged_subs[iGClust][ng] = new int [groups_list.get(ng).size()];
									int nc = 0;
									for (Integer cl: groups_list.get(ng)){
4244
										pre_merged_subs[iGClust][ng][nc++] = matchedGrown[iGClust][cl]; // cl;
4245 4246 4247 4248 4249 4250
									}
								}
							}
						}
					}
				};
4251
			}
4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267
			ImageDtt.startAndJoin(threads);
			// "flatten" pre_merged_subs
			int num_new_groups = 0;
			for (int ng = 0; ng < pre_merged_subs.length; ng ++) {
				num_new_groups += pre_merged_subs[ng].length;
			}
			if (debugLevel >-1){
				System.out.println("mergeNoConflict(): groups: " + num_new_groups + " (was : "+matchedGrown.length+")");
			}
			final int [][] merged_subs = new int [num_new_groups][];
			int indx = 0;
			for (int ng = 0; ng < pre_merged_subs.length; ng ++) {
				for (int nc = 0; nc < pre_merged_subs[ng].length; nc ++){
					merged_subs[indx++] = pre_merged_subs[ng][nc];
				}
			}
4268

4269
			if (debugLevel > 0) {
4270 4271 4272 4273 4274 4275 4276 4277 4278
				for (int i = 0; i < num_new_groups; i++){
					System.out.print("mergeNoConflict(): "+ (i+1)+" [");
					for (int j = 0; j < merged_subs[i].length; j++) {
						if (j > 0) System.out.print(", ");
						System.out.print(merged_subs[i][j]);
					}
					System.out.println(" ]");
				}
			}
4279

4280
			return merged_subs;
4281

4282
		}
4283 4284


4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307
		/**
		 * Grow each of the clusters (encoded as positive cluster numbers per tile per layer) by 1 in each
		 * of 8 directions. As they now may overlap they are encoded in boolean array [cluster][tile][layer]
		 * @param clusters_pure cluster numbers (>0) for each tile, each layer
		 * @param debugLevel
		 * @param dbg_X
		 * @param dbg_Y
		 * @return boolean array [cluster-1][tile][layer]
		 */
		public boolean [][][] growEachCluster (
				final int [][] clusters_pure,
				final int      debugLevel,
				final int      dbg_X,
				final int      dbg_Y)
		{
			final int num_clusters = getNumClusters(clusters_pure);
			final boolean [][][] clusters = new boolean [num_clusters][clusters_pure.length][];
			final TileNeibs tnImage =   new TileNeibs(imageTilesX, imageTilesY);

			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
4308
					@Override
4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319
					public void run() {
						for (int iClust = ai.getAndIncrement(); iClust < num_clusters; iClust = ai.getAndIncrement()) {
							int nClust = iClust + 1; // 1-based
							for (int nTile0 = 0; nTile0 < clusters_pure.length; nTile0++) if (clusters_pure[nTile0] != null){
								for (int nl0 = 0; nl0 < clusters_pure[nTile0].length; nl0++){
									if (clusters_pure[nTile0][nl0] == nClust){ // source should be single-layer, but ...
										if (clusters[iClust][nTile0]==null) {
											clusters[iClust][nTile0] = new boolean [clusters_pure[nTile0].length];
										}
										clusters[iClust][nTile0][nl0] = true;
										int nSurfTile0 = getSurfaceTileIndex(nTile0);
4320
										int [] neibs = tileData[nSurfTile0][nl0].getNeighbors();
4321 4322

										for (int dir = 0; dir <  tnImage.dirs; dir++) {
4323
											int nl1 = neibs[dir];
4324 4325 4326
											if (nl1 < 0){
												if (debugLevel >-1) {
													System.out.println("growEachCluster(): Expected 8 neighbors for tile nSurfTile0="+
4327
															nSurfTile0+":"+nl0+" neibs["+dir+"] = "+nl1);
4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347
												}
												int nTile1 = tnImage.getNeibIndex(nTile0, dir);
												if (nTile1 >= 0) {
													if (	((clusters_pure[nTile1] == null) || (clusters_pure[nTile1][nl1] != nClust)) &&
															((clusters[iClust][nTile1] == null) || !clusters[iClust][nTile1][nl1])) {
														if (clusters[iClust][nTile1] == null) {
															int nSurfTile1 = getSurfaceTileIndex(nTile1);
															clusters[iClust][nTile1] =  new boolean [tileData[nSurfTile1].length];
														}
														clusters[iClust][nTile1][nl1] = true;
													}
												}
											}
										}
									}
								}
							}
						}
					}
				};
4348
			}
4349
			ImageDtt.startAndJoin(threads);
4350 4351


4352 4353
			return clusters;
		}
4354 4355


4356 4357 4358 4359 4360 4361 4362 4363 4364
		/**
		 * Match grown/merged clusters to the ones they were made of
		 * @param clusters_grown per-tile, per layer array of positive merged cluster numbers (0 - empty)
		 * @param clusters_pure per-tile, per layer array of positive pure cluster numbers (0 - empty)
		 * @param debugLevel
		 * @param dbg_X
		 * @param dbg_Y
		 * @return array for each of the merged clusters array of pure cluster numbers it is made of
		 */
Andrey Filippov's avatar
Andrey Filippov committed
4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377
		public int [][] matchPureGrown (
				final int [][] clusters_grown,
				final int [][] clusters_pure,
				final int      debugLevel,
				final int      dbg_X,
				final int      dbg_Y)
		{
			final int num_grown = getNumClusters(clusters_grown);
			final int [][] grown_subs = new int [num_grown][];
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
4378
					@Override
Andrey Filippov's avatar
Andrey Filippov committed
4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401
					public void run() {
						for (int iparent = ai.getAndIncrement(); iparent < num_grown; iparent = ai.getAndIncrement()) {
							int num_parent = iparent + 1; // 1-based
							HashSet<Integer> subs_set = new HashSet<Integer>();
							for (int nTile = 0; nTile < clusters_grown.length; nTile++) if (clusters_grown[nTile] != null) {
								for (int nl = 0; nl < clusters_grown[nTile].length; nl++) if (clusters_grown[nTile][nl] == num_parent){
									if (clusters_pure[nTile] != null){
										int iclust = clusters_pure[nTile][nl];
										if (iclust > 0){
											subs_set.add(new Integer(iclust));
										}
									}
								}
							}
							grown_subs[iparent] = new int [subs_set.size()];
							int indx = 0;
							for (Integer s:subs_set){
								grown_subs[iparent][indx++] = s;
							}
							Arrays.sort(grown_subs[iparent]);
						}
					}
				};
4402
			}
Andrey Filippov's avatar
Andrey Filippov committed
4403
			ImageDtt.startAndJoin(threads);
4404
			if (debugLevel > 0) {
Andrey Filippov's avatar
Andrey Filippov committed
4405 4406 4407 4408 4409 4410 4411 4412 4413
				for (int i = 0; i < num_grown; i++){
					System.out.print("matchPureGrown(): "+ (i+1)+" [");
					for (int j = 0; j < grown_subs[i].length; j++) {
						if (j > 0) System.out.print(", ");
						System.out.print(grown_subs[i][j]);
					}
					System.out.println(" ]");
				}
			}
4414
			return grown_subs;
Andrey Filippov's avatar
Andrey Filippov committed
4415
		}
4416 4417


4418
		public int [] getClusterBBox(
4419
				final int      nClust, // 1-based
4420 4421 4422
				final int      border,
				final int [][] clusters)
		{
4423 4424 4425
//			if (numToSplit == 74) { //177){
//				System.out.println("getClusterBBox() numToSplit="+numToSplit);
//			}
4426 4427 4428
			int x_max = -1, y_max = -1, x_min = imageTilesX, y_min = imageTilesY;
			for (int nTile = 0; nTile < clusters.length; nTile++) if (clusters[nTile] != null){
				for (int nl = 0; nl < clusters[nTile].length; nl++){
4429
					if (clusters[nTile][nl] == nClust){
4430
						int tX = nTile % imageTilesX;
4431

4432 4433 4434 4435 4436 4437 4438 4439 4440 4441
						int tY = nTile / imageTilesX;
						if (tX < x_min) x_min = tX;
						if (tX > x_max) x_max = tX;
						if (tY < y_min) y_min = tY;
						if (tY > y_max) y_max = tY;
					}
				}
			}
			int x0 = x_min - border; // may be negative
			int y0 = y_min - border; // may be negative
4442
			int width = x_max +1 + border - x0;
4443 4444 4445
			int height = y_max +1 + border - y0;
			int [] bbox = {x0, y0, width, height};
			return bbox;
4446
		}
4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473
		public int [] getClusterBBox(
				final int []   nClust, // 1-based
				final int      border,
				final int [][] clusters)
		{
			int x_max = -1, y_max = -1, x_min = imageTilesX, y_min = imageTilesY;
			for (int nTile = 0; nTile < clusters.length; nTile++) if (clusters[nTile] != null){
				for (int nl = 0; nl < clusters[nTile].length; nl++){
					boolean sel = false;
					for (int i = 0; i < nClust.length; i++){
						if (clusters[nTile][nl] == nClust[i]){
							sel = true;
							break;
						}
					}
					if (sel){
						int tX = nTile % imageTilesX;
						int tY = nTile / imageTilesX;
						if (tX < x_min) x_min = tX;
						if (tX > x_max) x_max = tX;
						if (tY < y_min) y_min = tY;
						if (tY > y_max) y_max = tY;
					}
				}
			}
			int x0 = x_min - border; // may be negative
			int y0 = y_min - border; // may be negative
4474
			int width = x_max +1 + border - x0;
4475 4476 4477
			int height = y_max +1 + border - y0;
			int [] bbox = {x0, y0, width, height};
			return bbox;
4478 4479 4480 4481
		}



4482

4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493
		public int [][] getClusterBBoxIndices(
				final int [] window,
				final int    border) // maybe 0, actual value just saves time
		{
			int x0 =     window[0];
			int y0 =     window[1];
			int width =  window[2];
			int height = window[3];
			int [][] bbox_indices = new int [2][width*height]; // [0] - image index, [1] - surface index
			int wb = width - border;
			int hb = height - border;
4494 4495


4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506
			for (int neTile = 0; neTile < bbox_indices[0].length; neTile++){
				bbox_indices[0][neTile] = -1;
				bbox_indices[1][neTile] = -1;
				int bx = neTile % width;
				int by = neTile / width;
				if ((by >= border) && (bx >= border) && (by < hb) && (bx < wb)){
					int tx = bx + x0;
					int ty = by + y0;
					if ((tx >= 0) && (ty >= 0) && (tx < imageTilesX) && (ty < imageTilesY)){
						bbox_indices[0][neTile] = ty * imageTilesX + tx;
						bbox_indices[1][neTile] = ty * stilesX *superTileSize + tx;
4507
					}
4508 4509 4510 4511
				}
			}
			return bbox_indices;
		}
4512 4513 4514



4515 4516 4517 4518
		public boolean [][] extractCluster(
				final int      numToSplit, // 1-based
				final int [][] clusters,
				final int []   window,
4519
				final int []   bbox_indices,
4520 4521 4522 4523 4524 4525 4526 4527
				final int      debugLevel,
				final int      dbg_X,
				final int      dbg_Y)
		{
			boolean [][] extracted_cluster = new boolean [bbox_indices.length][];
			if (numToSplit == 74) { //177){
				System.out.println("extractCluster() numToSplit="+numToSplit);
			}
4528

4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542
			for (int neTile = 0; neTile < extracted_cluster.length; neTile++){
				int nTile = bbox_indices[neTile];
				if (nTile >= 0){
					if (clusters[nTile] != null) {
						boolean has_cluster = false;
						for (int nl = 0; nl< clusters[nTile].length; nl++){
							if (clusters[nTile][nl] == numToSplit){
								has_cluster =true;
								break;
							}
						}
						if (has_cluster){
							extracted_cluster[neTile] = new boolean[clusters[nTile].length];
							for (int nl = 0; nl< clusters[nTile].length; nl++){
4543
								extracted_cluster[neTile][nl] = (clusters[nTile][nl] == numToSplit);
4544 4545 4546
							}
						}
					}
4547

4548 4549 4550 4551
				}
			}
			return extracted_cluster;
		}
4552

4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563

		public int [][] spitConflictClusters(
				final int [][] clusters,
				final int      debugLevel,
				final int      dbg_X,
				final int      dbg_Y)
		{
			final int num_clusters = getNumClusters(clusters);
			if (debugLevel > -1){
				System.out.println("spitConflictClusters(): number of original clusters = " + num_clusters);
			}
4564
//			final int [][]   split_windows =  new int [num_clusters][];   // x,y,w,h for the cluster that is split
4565 4566 4567 4568 4569 4570 4571
			final int [][][]   split_indices =  new int [num_clusters][2][];   // for each tile in the window - number of the corresponding image tile or -1
			final int [][][] split_clusters = new int [num_clusters][][]; // for each tile in the window, a stack of layers, each number of a subcluster or 0
			final int []     split_number =   new int [num_clusters];     // number of sublusters the parent was split to
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
4572
					@Override
4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591
					public void run() {
						for (int numToSplit = ai.getAndIncrement(); numToSplit < num_clusters; numToSplit = ai.getAndIncrement()) {
							if ((numToSplit + 1) == 74) { //177){
								System.out.println("extractCluster() numToSplit="+numToSplit);
							}

							int [] window = getClusterBBox(
									numToSplit + 1, // 1-based
									0, // border,
									clusters);

							split_indices[numToSplit] =  getClusterBBoxIndices(
									window,  // final int [] window,
									0);      // border); // final int    border) // maybe 0, actual value just saves time

							boolean [][] extracted_cluster = extractCluster(
									numToSplit + 1,   // final int      numToSplit, // 1-based
									clusters,     // final int [][] clusters,
									window,       // final int []   window,
4592
									split_indices[numToSplit][0], // final int []   bbox_indices,
4593 4594 4595 4596 4597 4598 4599 4600
									debugLevel,   // final int      debugLevel,
									dbg_X,        // final int      dbg_X,
									dbg_Y);       // final int      dbg_Y)

							split_clusters[numToSplit] =  splitCluster(
									numToSplit + 1,        // final int      numToSplit, // 1-based
									clusters,          // final int [][] clusters,
									window,            // final int []   window,
4601 4602
									split_indices[numToSplit][0],      // final int []   bbox_indices,
									split_indices[numToSplit][1],      // final int []   bbox_surf_indices,
4603 4604 4605 4606
									extracted_cluster, // final boolean [][] extracted_cluster,
									debugLevel,        // final int      debugLevel,
									dbg_X,             // final int      dbg_X,
									dbg_Y);            // final int      dbg_Y)
4607

4608 4609 4610 4611
							split_number[numToSplit] = 	getNumClusters(split_clusters[numToSplit]);
						}
					}
				};
4612
			}
4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624
			ImageDtt.startAndJoin(threads);
			final int [] new_cluster_index = new int [num_clusters];
			for (int i = 0; i < num_clusters; i++) {
				if (i == 0) new_cluster_index[i] = 0;
				else new_cluster_index[i] = new_cluster_index[i-1] + split_number[i-1];
			}
			int num_new = new_cluster_index[num_clusters - 1] + split_number[num_clusters - 1];
			if (debugLevel > -1){
				System.out.println("spitConflictClusters(): number of new clusters = " + num_new + " ( was " + num_clusters + ")");
			}
			final int [][] new_clusters = new int [clusters.length][];
			for (int i = 0; i < new_clusters.length; i++) if (clusters[i] != null) new_clusters[i] = new int [clusters[i].length];
4625

4626 4627 4628
			ai.set(0);
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
4629
					@Override
4630 4631 4632 4633 4634 4635
					public void run() {
						for (int numToSplit = ai.getAndIncrement(); numToSplit < num_clusters; numToSplit = ai.getAndIncrement()) {
							int numToSplit1 = numToSplit+1;
							if (numToSplit1 == 74) { //177){
								System.out.println("extractCluster() numToSplit1="+numToSplit1);
							}
4636

4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649
							for (int neTile = 0; neTile < split_indices[numToSplit][0].length; neTile++) {
								int nTile = split_indices[numToSplit][0][neTile] ;
								if ((nTile >= 0) && (clusters[nTile] != null)){
									for (int nl = 0; nl < clusters[nTile].length; nl++){
										if (clusters[nTile][nl] == numToSplit1) {
											new_clusters[nTile][nl] = new_cluster_index[numToSplit] + split_clusters[numToSplit][neTile][nl];
										}
									}
								}
							}
						}
					}
				};
4650
			}
4651 4652 4653 4654 4655 4656
			ImageDtt.startAndJoin(threads);
			if (debugLevel > -1){
				System.out.println("spitConflictClusters(): DONE");
			}
			return new_clusters;
		}
4657

4658
		/**
4659
		 *
4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700
		 * @param numToSplit
		 * @param clusters
		 * @param window
		 * @param bbox_indices
		 * @param bbox_surf_indices
		 * @param extracted_cluster
		 * @param debugLevel
		 * @param dbg_X
		 * @param dbg_Y
		 * @return for each tile in the window,for each layer in that location number of a subcluster (1-based) or 0
		 */
		public int [][] splitCluster(
				final int      numToSplit, // 1-based
				final int [][] clusters,
				final int []   window,
				final int []   bbox_indices,
				final int []   bbox_surf_indices,
				final boolean [][] extracted_cluster,
				final int      debugLevel,
				final int      dbg_X,
				final int      dbg_Y)
		{

			int width =  window[2];
			int height = window[3];
			int [][] split_cluster = new int [extracted_cluster.length][];
			for (int neTile = 0; neTile < extracted_cluster.length; neTile++){
				if (extracted_cluster[neTile] != null){
					split_cluster[neTile] = new int [extracted_cluster[neTile].length];
				}
			}
			final TileNeibs tnCluster =   new TileNeibs(width, height);
			if (numToSplit == 74) { //177){
				int num_tiles = 0;
				for (int neTile = 0; neTile < extracted_cluster.length; neTile++){
					if (extracted_cluster[neTile] != null){
						for (int i = 0; i < extracted_cluster[neTile].length; i++) {
							if (extracted_cluster[neTile][i]) num_tiles++;
						}
					}
				}
4701

4702
				System.out.println("splitCluster() numToSplit="+numToSplit+" num tiles = "+ num_tiles);
4703

4704
			}
4705

4706 4707
			int num_cluster = 1;
			while (true) {
4708

4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736
				int neTile0 = 0;
				int nl0 = 0;
				label_loop : {
					for (; neTile0 < extracted_cluster.length; neTile0++){
						if (extracted_cluster[neTile0] != null){
							for (nl0 = 0; nl0 < extracted_cluster[neTile0].length; nl0++) if (extracted_cluster[neTile0][nl0]){
								break label_loop;
							}
						}
					}
				}
				if (neTile0 >= extracted_cluster.length){
					break; // nothing left
				}
				// run wave from neTile0, nl0 checking for conflicts, filling
				ArrayList<Point> clust_list = new ArrayList<Point>();
				{
					Point p = new Point(neTile0, nl0);
					split_cluster[p.x][p.y] = num_cluster;
					extracted_cluster[p.x][p.y] = false;
					clust_list.add(p);
				}
				int dbg_size = 1;
				while (!clust_list.isEmpty()){
					Point p = clust_list.remove(0);
					int neTile = p.x;
					int nl = p.y;
					int nSurfTile = bbox_surf_indices[neTile]; // WRONG - fixed
4737
					int [] neibs = tileData[nSurfTile][nl].getNeighbors();
4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752
					for (int dir = 0; dir < tnCluster.numNeibs(); dir++) {
						int neTile1 = tnCluster.getNeibIndex(neTile,dir);
						if ((neTile1 >= 0) && (extracted_cluster[neTile1] != null)) { // it should have original tile there, not yet assigned to a new
							// check it is empty on all levels
							boolean tileEmpty = true;
							if (split_cluster[neTile1] != null) {
								for (int i = 0; i < split_cluster[neTile1].length; i++ ){
									if (split_cluster[neTile1][i] == num_cluster){
										tileEmpty = false;
										break;
									}
								}
							}
							if (tileEmpty) {
								if (neibs[dir] < 0){ // should not happen
Andrey Filippov's avatar
Andrey Filippov committed
4753 4754 4755
									if (debugLevel > 0) {
										System.out.println("splitCluster(): existing nSurfTile="+nSurfTile+" surface is not connected in direction "+dir);
									}
4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784
								} else {
									int nl1 = neibs[dir];
									if (extracted_cluster[neTile1][nl1]) {
										// verify it does not have connections from assigned tiles to different levels
										label_no_conflict: {
											for (int dir1 = 0; dir1 < tnCluster.numNeibs(); dir1++) {
												int neTile2 = tnCluster.getNeibIndex(neTile1,dir1);
												if ((neTile2 >= 0) && (split_cluster[neTile2] != null)) {
													for (int nl2 = 0; nl2 < split_cluster[neTile2].length; nl2++){
														if (split_cluster[neTile2][nl2] == num_cluster){
															int nl_this = tileData[bbox_surf_indices[neTile2]][nl2].getNeighbor(tnCluster.opposite(dir1));
															if ((nl_this >= 0) && (nl_this != nl1)){
																break label_no_conflict;
															}
														}
													}
												}
											}
											// no conflicts found, add this tile
											extracted_cluster[neTile1][nl1] = false;
											split_cluster[neTile1][nl1] = num_cluster;
											clust_list.add(new Point(neTile1, nl1));
											dbg_size ++;
										}
									}
								}
							}
						}
					}
4785

4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805
				}
				if (numToSplit == 74) { //177){
					System.out.println("splitCluster() numToSplit="+numToSplit+" num_cluster="+num_cluster+" num tiles="+dbg_size);
				}

				num_cluster++;
			}
			if (numToSplit == 74) { //177){
				int num_tiles = 0, num_tiles1= 0;
				for (int neTile = 0; neTile < extracted_cluster.length; neTile++){
					if (extracted_cluster[neTile] != null){
						for (int i = 0; i < extracted_cluster[neTile].length; i++) {
							if (extracted_cluster[neTile][i]) num_tiles++;
							if (split_cluster[neTile][i] > 0) num_tiles1++;
							if (extracted_cluster[neTile][i]) {
								System.out.println("neTile="+neTile+", nl = "+i);
							}
						}
					}
				}
4806

4807 4808 4809 4810
				System.out.println("splitCluster() return  numToSplit="+numToSplit + " num tiles = "+ num_tiles+ " num tiles1 = "+ num_tiles1);
			}
			return split_cluster;
		}
4811

4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827
		public boolean [][] growSelectionOnce(
//				int grow,
				final boolean [][] sel_in,
				final int          debugLevel,
				final int          dbg_X,
				final int          dbg_Y)
		{
			final boolean [][] selection =  new boolean [sel_in.length][];
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
			final TileNeibs tnImage =   new TileNeibs(imageTilesX, imageTilesY);
			//			final TileNeibs tnSurface = new TileNeibs(stilesX * superTileSize, stilesY * superTileSize);
			ai.set(0);
			// make sure even empty tiles have surface selection arrays defined
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
4828
					@Override
4829 4830 4831 4832 4833
					public void run() {
						for (int nTile = ai.getAndIncrement(); nTile < sel_in.length; nTile = ai.getAndIncrement()) {
							boolean not_empty = false;
							boolean [] stack = null;
							if (sel_in[nTile] != null) {
4834
								stack = sel_in[nTile].clone();
4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855
							}
							int nSurfTile = getSurfaceTileIndex(nTile);
							if (tileData[nSurfTile] != null) {
								if (stack == null) {
									stack = new boolean[tileData[nSurfTile].length];
								}
								for (int nl = 0; nl < stack.length; nl++){
									if (stack[nl]) {
										not_empty = true;
									} else {
										int [] neibs = tileData[nSurfTile][nl].getNeighbors();
										for (int dir = 0; dir < neibs.length; dir++){
											if (neibs[dir] >= 0){
												int nTile1 = tnImage.getNeibIndex(nTile, dir);
												if ((nTile1 >= 0) && (sel_in[nTile1] != null) && sel_in[nTile1][neibs[dir]]){
													stack[nl] = true;
													not_empty = true;
												}
											}
										}
									}
4856
								}
4857 4858 4859 4860 4861 4862 4863
							}
							if (not_empty){
								selection[nTile] = stack;
							}
						}
					}
				};
4864
			}
4865 4866 4867 4868
			ImageDtt.startAndJoin(threads);
			return selection;
		}

4869 4870


4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881
		public boolean [][] growSelection(
				int grow,
				final boolean [][] sel_in,
				final int          debugLevel,
				final int          dbg_X,
				final int          dbg_Y)
		{
			final int DIR_RIGHT = 2;
			final int DIR_LEFT =  6;
			final int DIR_UP =    0;
			final int DIR_DOWN =  4;
4882
			final int [] DIRS = {DIR_LEFT, DIR_RIGHT, DIR_UP, DIR_DOWN};
4883 4884 4885 4886 4887 4888 4889 4890 4891 4892
			final boolean [][] selection =   sel_in.clone();
			final boolean [][] selection_tmp = sel_in.clone();
			final Thread[] threads = ImageDtt.newThreadArray(threadsMax);
			final AtomicInteger ai = new AtomicInteger(0);
			final TileNeibs tnImage =   new TileNeibs(imageTilesX, imageTilesY);
			//			final TileNeibs tnSurface = new TileNeibs(stilesX * superTileSize, stilesY * superTileSize);
			ai.set(0);
			// make sure even empty tiles have surface selection arrays defined
			for (int ithread = 0; ithread < threads.length; ithread++) {
				threads[ithread] = new Thread() {
4893
					@Override
4894 4895 4896 4897 4898 4899 4900 4901 4902 4903
					public void run() {
						for (int nTile = ai.getAndIncrement(); nTile < sel_in.length; nTile = ai.getAndIncrement()) {
							int nSurfTile = getSurfaceTileIndex(nTile);
							if (tileData[nSurfTile] != null) {
								if (sel_in[nTile] != null){
									selection[nTile] = sel_in[nTile].clone();
								} else {
									selection[nTile] = new boolean[tileData[nSurfTile].length];
								}
								//								selection_tmp[nTile] = new boolean[tileData[nSurfTile].length];
4904
							}
4905 4906 4907
						}
					}
				};
4908
			}
4909 4910 4911 4912 4913 4914 4915 4916
			ImageDtt.startAndJoin(threads);
			for (; grow > 0; grow -=2){
				for (int dri = 0; dri < DIRS.length; dri++ ){
					final int fdri = dri;
					ai.set(0);
					// extend to the right
					for (int ithread = 0; ithread < threads.length; ithread++) {
						threads[ithread] = new Thread() {
4917
							@Override
4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946
							public void run() {
								for (int nTile = ai.getAndIncrement(); nTile < sel_in.length; nTile = ai.getAndIncrement()) {
									if (selection[nTile] != null) {
										if (fdri == 0) selection_tmp[nTile] = new boolean[selection[nTile].length]; // new, empty
										int nTile1 = tnImage.getNeibIndex(nTile, DIRS[fdri]);
										if (nTile1 >= 0){
											int nSurfTile = getSurfaceTileIndex(nTile);
											for (int nl = 0; nl < selection_tmp[nTile].length; nl ++) {
												if (tileData[nSurfTile][nl] != null){
													int nl1 = tileData[nSurfTile][nl].getNeighbor(DIRS[fdri]);
													if ((nl1 >=0 ) && selection[nTile1][nl1]){
														selection_tmp[nTile][nl] = true;
													}
												}
											}
										}
									}
								}
							}
						};
					}
					ImageDtt.startAndJoin(threads);

					if (((dri == 1) &&  (grow > 1)) || (dri == 3)){ // always after both directions, after horizontal if diagonal is enabled
						// copy results back
						ai.set(0);
						// extend to the left
						for (int ithread = 0; ithread < threads.length; ithread++) {
							threads[ithread] = new Thread() {
4947
								@Override
4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966
								public void run() {
									for (int nTile = ai.getAndIncrement(); nTile < sel_in.length; nTile = ai.getAndIncrement()) {
										if (selection_tmp[nTile] != null){
											for (int nl = 0; nl < selection_tmp[nTile].length; nl ++) {
												if (selection_tmp[nTile][nl]) {
													selection[nTile][nl] = true;
												}
											}
										}
									}
								}
							};
						}
						ImageDtt.startAndJoin(threads);
					}
				}
			}
			return selection;
		}
4967

Andrey Filippov's avatar
Andrey Filippov committed
4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978
		public void mergeAndGrow( // TODO: add result
				final boolean [][] sel_in,
				final int          debugLevel,
				final int          dbg_X,
				final int          dbg_Y)
		{
			System.out.println("mergeAndGrow() start");
			boolean [][] assigned_sel = extractSelection(
					debugLevel,
					dbg_X,
					dbg_Y);
4979

Andrey Filippov's avatar
Andrey Filippov committed
4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990
			int [][] clusters_pure = enumerateClusters(
					assigned_sel, //final boolean [][] selection,
					debugLevel,
					dbg_X,
					dbg_Y);
			clusters_pure = spitConflictClusters(
					clusters_pure, // final int [][] clusters,
					debugLevel,
					dbg_X,
					dbg_Y);

4991 4992
			boolean [][] grown_sel = growSelectionOnce(
//					2,              // int grow,
Andrey Filippov's avatar
Andrey Filippov committed
4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007
					assigned_sel,   // final boolean [][] sel_in,
					debugLevel,
					dbg_X,
					dbg_Y);
			int [][] clusters_grown = enumerateClusters(
					grown_sel, //final boolean [][] selection,
					debugLevel,
					dbg_X,
					dbg_Y);
			int [][] grown_sub_clusters = matchPureGrown (
					clusters_grown,
					clusters_pure,
					debugLevel,
					dbg_X,
					dbg_Y);
5008

5009 5010 5011 5012 5013 5014 5015
			int [][] merged_no_conflict = mergeNoConflict(
					grown_sub_clusters,
					clusters_grown,
					clusters_pure,
					debugLevel,
					dbg_X,
					dbg_Y);
5016 5017 5018 5019 5020 5021 5022

			setSurfaceData(
					merged_no_conflict, // final int [][] cluster_groups,
					clusters_pure, // final int [][] clusters_pure, // each tile/layer belongs to a single pure cluster
					0, // final int      debugLevel,
					dbg_X,
					dbg_Y);
5023

Andrey Filippov's avatar
Andrey Filippov committed
5024
			System.out.println("mergeAndGrow() done");
5025

Andrey Filippov's avatar
Andrey Filippov committed
5026 5027

		}
5028 5029


5030
}