sort paths in order to shorten unproductive move distance
Stefan Schuermans

Stefan Schuermans commited on 2013-01-26 23:31:12
Showing 1 changed files, with 33 additions and 3 deletions.

... ...
@@ -26,16 +26,20 @@ Path & Layer::addPath()
26 26
  */
27 27
 void Layer::improvePaths(double eqDist)
28 28
 {
29
-  Paths::iterator path, other;
29
+  Paths::iterator path, other, best;
30 30
   bool change;
31
+  double smallest, dist;
31 32
 
32 33
   // join paths with equal begin/end points
33 34
   do {
34 35
     change = false;
36
+    // process all paths
35 37
     for (path = mPaths.begin(); path != mPaths.end(); ++path) {
38
+      // check all paths following aftet the current one
36 39
       other = path;
37 40
       ++other;
38 41
       while (other != mPaths.end()) {
42
+        // paths can be joined
39 43
         if (other->mPoints.front().equals(path->mPoints.back(),
40 44
                                           eqDist)) {
41 45
           path->appendPath(*other);
... ...
@@ -60,10 +64,11 @@ void Layer::improvePaths(double eqDist)
60 64
           other = mPaths.erase(other);
61 65
           change = true;
62 66
         }
67
+        // paths cannot be joined -> move to next one
63 68
         else
64 69
           ++other;
65
-      }
66
-    }
70
+      } // while other
71
+    } // for path
67 72
   } while (change);
68 73
 
69 74
   // remove nearby points in paths
... ...
@@ -77,6 +82,31 @@ void Layer::improvePaths(double eqDist)
77 82
       path = mPaths.erase(path);
78 83
     else
79 84
       ++path;
85
+
86
+  // sort paths to minimize unproductive move distance
87
+  for (path = mPaths.begin(); path != mPaths.end(); ++path) {
88
+    // find path starting at closest distance from current paths end
89
+    other = path;
90
+    ++other;
91
+    best = mPaths.end();
92
+    while (other != mPaths.end()) {
93
+      // calculate (squared) distance from path.end to other.begin
94
+      //   path and other are never empty here
95
+      //   empty paths have been removed before
96
+      dist = (path->mPoints.back() - other->mPoints.front()).abs_sq();
97
+      // keep path with smallest (squared) distance
98
+      if (best == mPaths.end() || dist < smallest) {
99
+        best = other;
100
+        smallest = dist;
101
+      }
102
+      ++other;
103
+    } // while other
104
+    // use best path as next one, i.e. swap best path with next one
105
+    other = path;
106
+    other++;
107
+    if (other != mPaths.end() && best != mPaths.end())
108
+      mPaths.splice(other, mPaths, best);
109
+  } // for path
80 110
 }
81 111
 
82 112
 /**
83 113