chiark / gitweb /
63b1d0ede24f1e7661119b7246fb261089a298be
[cura.git] / Cura / util / objectScene.py
1 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
2 import random
3 import numpy
4
5 from Cura.util import profile
6 from Cura.util import polygon
7
8 class _objectOrder(object):
9         def __init__(self, order, todo):
10                 self.order = order
11                 self.todo = todo
12
13 class _objectOrderFinder(object):
14         def __init__(self, scene, leftToRight, frontToBack, gantryHeight):
15                 self._scene = scene
16                 self._objs = scene.objects()
17                 self._leftToRight = leftToRight
18                 self._frontToBack = frontToBack
19                 initialList = []
20                 for n in xrange(0, len(self._objs)):
21                         if scene.checkPlatform(self._objs[n]):
22                                 initialList.append(n)
23                 for n in initialList:
24                         if self._objs[n].getSize()[2] > gantryHeight and len(initialList) > 1:
25                                 self.order = None
26                                 return
27                 if len(initialList) == 0:
28                         self.order = []
29                         return
30
31                 self._hitMap = [None] * (max(initialList)+1)
32                 for a in initialList:
33                         self._hitMap[a] = [False] * (max(initialList)+1)
34                         for b in initialList:
35                                 self._hitMap[a][b] = self._checkHit(a, b)
36
37                 #Check if we have 2 files that overlap so that they can never be printed one at a time.
38                 for a in initialList:
39                         for b in initialList:
40                                 if a != b and self._hitMap[a][b] and self._hitMap[b][a]:
41                                         self.order = None
42                                         return
43
44                 initialList.sort(self._objIdxCmp)
45
46                 n = 0
47                 self._todo = [_objectOrder([], initialList)]
48                 while len(self._todo) > 0:
49                         n += 1
50                         current = self._todo.pop()
51                         #print len(self._todo), len(current.order), len(initialList), current.order
52                         for addIdx in current.todo:
53                                 if not self._checkHitFor(addIdx, current.order) and not self._checkBlocks(addIdx, current.todo):
54                                         todoList = current.todo[:]
55                                         todoList.remove(addIdx)
56                                         order = current.order[:] + [addIdx]
57                                         if len(todoList) == 0:
58                                                 self._todo = None
59                                                 self.order = order
60                                                 return
61                                         self._todo.append(_objectOrder(order, todoList))
62                 self.order = None
63
64         def _objIdxCmp(self, a, b):
65                 scoreA = sum(self._hitMap[a])
66                 scoreB = sum(self._hitMap[b])
67                 return scoreA - scoreB
68
69         def _checkHitFor(self, addIdx, others):
70                 for idx in others:
71                         if self._hitMap[addIdx][idx]:
72                                 return True
73                 return False
74
75         def _checkBlocks(self, addIdx, others):
76                 for idx in others:
77                         if addIdx != idx and self._hitMap[idx][addIdx]:
78                                 return True
79                 return False
80
81         #Check if printing one object will cause printhead colission with other object.
82         def _checkHit(self, addIdx, idx):
83                 obj = self._scene._objectList[idx]
84                 addObj = self._scene._objectList[addIdx]
85                 return polygon.polygonCollision(obj._boundaryHull + obj.getPosition(), addObj._headAreaHull + addObj.getPosition())
86
87 class Scene(object):
88         def __init__(self):
89                 self._objectList = []
90                 self._sizeOffsets = numpy.array([0.0,0.0], numpy.float32)
91                 self._machineSize = numpy.array([100,100,100], numpy.float32)
92                 self._headSizeOffsets = numpy.array([18.0,18.0], numpy.float32)
93                 self._extruderOffset = [numpy.array([0,0], numpy.float32)] * 4
94
95                 #Print order variables
96                 self._leftToRight = False
97                 self._frontToBack = True
98                 self._gantryHeight = 60
99                 self._oneAtATime = True
100
101         # update the physical machine dimensions
102         def updateMachineDimensions(self):
103                 self._machineSize = numpy.array([profile.getMachineSettingFloat('machine_width'), profile.getMachineSettingFloat('machine_depth'), profile.getMachineSettingFloat('machine_height')])
104                 self._machinePolygons = profile.getMachineSizePolygons()
105                 self.setHeadSize(profile.getMachineSettingFloat('extruder_head_size_min_x'), profile.getMachineSettingFloat('extruder_head_size_max_x'), profile.getMachineSettingFloat('extruder_head_size_min_y'), profile.getMachineSettingFloat('extruder_head_size_max_y'), profile.getMachineSettingFloat('extruder_head_size_height'))
106
107         # Size offsets are offsets caused by brim, skirt, etc.
108         def updateSizeOffsets(self, force=False):
109                 newOffsets = numpy.array(profile.calculateObjectSizeOffsets(), numpy.float32)
110                 if not force and numpy.array_equal(self._sizeOffsets, newOffsets):
111                         return
112                 self._sizeOffsets = newOffsets
113
114                 extends = [numpy.array([[-newOffsets[0],-newOffsets[1]],[ newOffsets[0],-newOffsets[1]],[ newOffsets[0], newOffsets[1]],[-newOffsets[0], newOffsets[1]]], numpy.float32)]
115                 for n in xrange(1, 4):
116                         headOffset = numpy.array([[0, 0], [-profile.getMachineSettingFloat('extruder_offset_x%d' % (n)), -profile.getMachineSettingFloat('extruder_offset_y%d' % (n))]], numpy.float32)
117                         extends.append(polygon.minkowskiHull(extends[n-1], headOffset))
118
119                 for obj in self._objectList:
120                         obj.setPrintAreaExtends(extends[len(obj._meshList) - 1])
121
122         #size of the printing head.
123         def setHeadSize(self, xMin, xMax, yMin, yMax, gantryHeight):
124                 self._leftToRight = xMin < xMax
125                 self._frontToBack = yMin < yMax
126                 self._headSizeOffsets[0] = min(xMin, xMax)
127                 self._headSizeOffsets[1] = min(yMin, yMax)
128                 self._gantryHeight = gantryHeight
129                 self._oneAtATime = self._gantryHeight > 0
130
131                 headArea = numpy.array([[-xMin,-yMin],[ xMax,-yMin],[ xMax, yMax],[-xMin, yMax]], numpy.float32)
132
133                 for obj in self._objectList:
134                         obj.setHeadArea(headArea, self._headSizeOffsets)
135
136         def setExtruderOffset(self, extruderNr, offsetX, offsetY):
137                 self._extruderOffset[extruderNr] = numpy.array([offsetX, offsetY], numpy.float32)
138
139         def objects(self):
140                 return self._objectList
141
142         #Add new object to print area
143         def add(self, obj):
144                 if numpy.max(obj.getSize()[0:2]) > numpy.max(self._machineSize[0:2]) * 2.5:
145                         scale = numpy.max(self._machineSize[0:2]) * 2.5 / numpy.max(obj.getSize()[0:2])
146                         matrix = [[scale,0,0], [0, scale, 0], [0, 0, scale]]
147                         obj.applyMatrix(numpy.matrix(matrix, numpy.float64))
148                 self._findFreePositionFor(obj)
149                 self._objectList.append(obj)
150                 self.updateSizeOffsets(True)
151                 self.pushFree()
152
153         def remove(self, obj):
154                 self._objectList.remove(obj)
155
156         #Dual(multiple) extrusion merge
157         def merge(self, obj1, obj2):
158                 self.remove(obj2)
159                 obj1._meshList += obj2._meshList
160                 for m in obj2._meshList:
161                         m._obj = obj1
162                 obj1.processMatrix()
163                 obj1.setPosition((obj1.getPosition() + obj2.getPosition()) / 2)
164                 self.pushFree()
165
166         def pushFree(self):
167                 n = 10
168                 while self._pushFree():
169                         n -= 1
170                         if n < 0:
171                                 return
172
173         def arrangeAll(self):
174                 oldList = self._objectList
175                 self._objectList = []
176                 for obj in oldList:
177                         obj.setPosition(numpy.array([0,0], numpy.float32))
178                         self.add(obj)
179
180         def centerAll(self):
181                 minPos = numpy.array([9999999,9999999], numpy.float32)
182                 maxPos = numpy.array([-9999999,-9999999], numpy.float32)
183                 for obj in self._objectList:
184                         pos = obj.getPosition()
185                         size = obj.getSize()
186                         minPos[0] = min(minPos[0], pos[0] - size[0] / 2)
187                         minPos[1] = min(minPos[1], pos[1] - size[1] / 2)
188                         maxPos[0] = max(maxPos[0], pos[0] + size[0] / 2)
189                         maxPos[1] = max(maxPos[1], pos[1] + size[1] / 2)
190                 offset = -(maxPos + minPos) / 2
191                 for obj in self._objectList:
192                         obj.setPosition(obj.getPosition() + offset)
193
194         def printOrder(self):
195                 if self._oneAtATime:
196                         order = _objectOrderFinder(self, self._leftToRight, self._frontToBack, self._gantryHeight).order
197                 else:
198                         order = None
199                 return order
200
201         def _pushFree(self):
202                 for a in self._objectList:
203                         for b in self._objectList:
204                                 if a == b or not self.checkPlatform(a) or not self.checkPlatform(b):
205                                         continue
206                                 if self._oneAtATime:
207                                         v = polygon.polygonCollisionPushVector(a._headAreaMinHull + a.getPosition(), b._boundaryHull + b.getPosition())
208                                 else:
209                                         v = polygon.polygonCollisionPushVector(a._boundaryHull + a.getPosition(), b._boundaryHull + b.getPosition())
210                                 if type(v) is bool:
211                                         continue
212                                 a.setPosition(a.getPosition() + v * 0.4)
213                                 b.setPosition(b.getPosition() - v * 0.6)
214                                 return True
215                 return False
216
217         #Check if two objects are hitting each-other (+ head space).
218         def _checkHit(self, a, b):
219                 if a == b:
220                         return False
221                 if self._oneAtATime:
222                         return polygon.polygonCollision(a._headAreaMinHull + a.getPosition(), b._boundaryHull + b.getPosition())
223                 else:
224                         return polygon.polygonCollision(a._boundaryHull + a.getPosition(), b._boundaryHull + b.getPosition())
225
226         def checkPlatform(self, obj):
227                 area = obj._printAreaHull + obj.getPosition()
228                 if not polygon.fullInside(area, self._machinePolygons[0]):
229                         return False
230                 #Check the "no go zones"
231                 for poly in self._machinePolygons[1:]:
232                         if polygon.polygonCollision(poly, area):
233                                 return False
234                 return True
235
236         def _findFreePositionFor(self, obj):
237                 posList = []
238                 for a in self._objectList:
239                         p = a.getPosition()
240                         if self._oneAtATime:
241                                 s = (a.getSize()[0:2] + obj.getSize()[0:2]) / 2 + self._sizeOffsets + self._headSizeOffsets + numpy.array([3,3], numpy.float32)
242                         else:
243                                 s = (a.getSize()[0:2] + obj.getSize()[0:2]) / 2 + numpy.array([3,3], numpy.float32)
244                         posList.append(p + s * ( 1.0, 1.0))
245                         posList.append(p + s * ( 0.0, 1.0))
246                         posList.append(p + s * (-1.0, 1.0))
247                         posList.append(p + s * ( 1.0, 0.0))
248                         posList.append(p + s * (-1.0, 0.0))
249                         posList.append(p + s * ( 1.0,-1.0))
250                         posList.append(p + s * ( 0.0,-1.0))
251                         posList.append(p + s * (-1.0,-1.0))
252
253                 best = None
254                 bestDist = None
255                 for p in posList:
256                         obj.setPosition(p)
257                         ok = True
258                         for a in self._objectList:
259                                 if self._checkHit(a, obj):
260                                         ok = False
261                                         break
262                         if not ok:
263                                 continue
264                         dist = numpy.linalg.norm(p)
265                         if not self.checkPlatform(obj):
266                                 dist *= 3
267                         if best is None or dist < bestDist:
268                                 best = p
269                                 bestDist = dist
270                 if best is not None:
271                         obj.setPosition(best)