Advertisement
Guest User

Untitled

a guest
Sep 17th, 2017
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.       _itemsChanged(items) {
  2.         /*
  3.           items[n]
  4.           {
  5.             x: xi,
  6.             y: yi,
  7.             w: wi,
  8.             h: hi
  9.           }
  10.         */
  11.  
  12.         let maxW = 1,
  13.             maxH = 1;
  14.         for ( let i = 0, e; e = items[i]; ++i ) {
  15.           if (e.h > maxH) maxH = e.h;
  16.           if (e.w > maxW) maxW = e.w;
  17.         }
  18.         if (maxW > this.columns) this.columns = maxW;
  19.  
  20.         let szmp = [];
  21.         for ( let i = 1; i <= maxH; ++i ) {
  22.           szmp.push([]);
  23.           for ( let j = 0; j <= maxW; ++j ) {
  24.             szmp[i-1].push([1,1]);
  25.           }
  26.         }
  27.  
  28.         /* Moongom Algorithm */
  29.         for ( let i = 0,e; e = items[i]; ++i ) {
  30.           items[i].index = i;
  31.  
  32.           let [px1,py1] = szmp[e.h-1][e.w-1];
  33.           let px2 = px1 + e.w - 1;
  34.           let py2 = py1 + e.h - 1;
  35.  
  36.           seeking:
  37.           while (true) {
  38.  
  39.             while ( px2 <= this.columns ) {
  40.  
  41.               let hasCollision = false;
  42.               for ( let j = i-1; j >= 0 && !hasCollision; --j) {
  43.  
  44.                 let x1 = items[j].x,
  45.                 x2 = items[j].x + items[j].w - 1,
  46.                 y1 = items[j].y,
  47.                 y2 = items[j].y + items[j].h - 1;
  48.  
  49.                 hasCollision = (px1 > x2 || px2 < x1 || py1 > y2 || py2 < y1) ? false : true;
  50.               }
  51.               if (!hasCollision) {
  52.                 szmp[e.h-1][e.w-1] = [px2+1,py1];
  53.                 e.x = px1;
  54.                 e.y = py1;
  55.                 e.szmpX = px2+1;
  56.                 e.szmpY = py1;
  57.  
  58.                 break seeking;
  59.               }
  60.  
  61.               ++px1;
  62.               ++px2;
  63.             }
  64.  
  65.             px1 = 1;
  66.             ++py1;
  67.  
  68.             px2 = px1 + e.w -1;
  69.             ++py2;
  70.           }
  71.  
  72.         }
  73.       }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement