def FitADroneToShip(self, droneTypeID, raiseError=True, sendUpdateEvent=False): shipDogmaItem = self.fittingDogmaLocation.GetShipItem() shipID = shipDogmaItem.itemID g = GhostFittingDataObject(shipID, const.flagDroneBay, droneTypeID) capacityInfo = self.fittingDogmaLocation.GetCapacity( shipID, None, const.flagDroneBay) volume = evetypes.GetVolume(droneTypeID) if capacityInfo.used + volume > capacityInfo.capacity: return counter = 0 while g.GetItemKey() in shipDogmaItem.drones: g.SetNumber(counter) counter += 1 itemKey = g.GetItemKey() dogmaItem = self.GetLoadedItem(itemKey, item=g) dogmaItem.stacksize = 1 self.fittingDogmaLocation.RegisterDroneAsActive(itemKey, raiseError=raiseError) if sendUpdateEvent: self.SendOnStatsUpdatedEvent() return dogmaItem
def GetFreeSpace(self): capacity = self.GetCapacity() usedSpace = 0 for typeID, qty in self.contents.iteritems(): usedSpace += evetypes.GetVolume(typeID) * qty return capacity - usedSpace
def LoadStorageContentScroll(self): scrolllist = [] for typeID, amount in self.pin.contents.iteritems(): data = util.KeyVal() volume = evetypes.GetVolume(typeID) * amount data.label = '<t>%s<t>%s<t>%s' % (evetypes.GetName(typeID), amount, volume) data.amount = amount data.typeID = typeID data.itemID = None data.getIcon = (True, ) data.OnDblClick = self.OnStorageEntryDblClicked sortBy = amount scrolllist.append((sortBy, listentry.Get('Item', data=data))) scrolllist = uiutil.SortListOfTuples(scrolllist) self.storageContentScroll.Load( contentList=scrolllist, noContentHint=localization.GetByLabel( 'UI/PI/Common/NoContentsPresent'), headers=[ '', localization.GetByLabel('UI/PI/Common/Type'), localization.GetByLabel('UI/Common/Amount'), localization.GetByLabel('UI/Common/Volume') ])
def GetBandwidthUsage(self): bwth = evetypes.GetVolume(self.GetType()) * self.GetQuantity() cycleTime = self.GetRouteCycleTime() if cycleTime == 0.0 or cycleTime is None: return bwth else: return planetCommon.GetBandwidth(bwth, cycleTime)
def GetCapacityForItems(self, items): capacity = 0 for typeId, quantity in items.iteritems(): typeVolume = evetypes.GetVolume(typeId) capacity += quantity * typeVolume return capacity
def _AddCommodity(self, typeID, quantity): quantityToAdd = self.CanAccept(typeID, quantity) if quantityToAdd < 1: return 0 if self.GetCapacity() is not None: self.capacityUsed += quantityToAdd * evetypes.GetVolume(typeID) if typeID not in self.contents: self.contents[typeID] = quantityToAdd else: self.contents[typeID] += quantityToAdd return quantityToAdd
def CanAccept(self, typeID, quantity): if self.activityState < STATE_IDLE: return 0 if self.GetCapacity() is not None: volume = evetypes.GetVolume(typeID) newVolume = volume * quantity capacityRemaining = max(0, self.GetCapacity() - self.capacityUsed) if newVolume > capacityRemaining or quantity == -1: return int(capacityRemaining / volume) else: return quantity else: return max(0, quantity)
def _RemoveCommodity(self, typeID, quantity): if typeID not in self.contents: return 0 qtyRemoved = 0 if self.contents[typeID] <= quantity: qtyRemoved = self.contents[typeID] del self.contents[typeID] else: qtyRemoved = quantity self.contents[typeID] -= qtyRemoved if self.GetCapacity() is not None: self.capacityUsed = max( 0, self.capacityUsed - evetypes.GetVolume(typeID) * qtyRemoved) return qtyRemoved
def IsModuleTooBig(moduleTypeID, shipTypeID, isCapitalShip=None, isStructure=None): if isCapitalShip is None: isCapitalShip = evetypes.GetGroupID( shipTypeID) in cfg.GetShipGroupByClassType()[ const.GROUP_CAPITALSHIPS] if isStructure is None: isStructure = evetypes.GetCategoryID( shipTypeID) == const.categoryStructure if not isCapitalShip and not isStructure: itemVolume = evetypes.GetVolume(moduleTypeID) if itemVolume > const.maxNonCapitalModuleSize: return True return False
def GetLineInfo(self, line): parts = SplitAndStrip(line, CHARGE_SEPARATOR) typeName = parts[0] if len(parts) > 1: chargeName = parts[1].strip().lower() else: chargeName = None parts = SplitAndStrip(typeName, MULTIPLIER_SEPARATOR) typeName = parts[0] if len(parts) > 1: numItems = int(parts[1]) else: numItems = 1 if typeName: typeName = typeName.lower() typeID = self.nameAndTypesDict.get(typeName, None) chargeTypeID = self.nameAndTypesDict.get(chargeName, None) isEmpty = True slotLocation = None if typeName in emptySlotDict: slotLocation = emptySlotDict[typeName] elif typeID: slotLocation = self.GetSlot(typeID) isEmpty = False if typeID is None and chargeTypeID is None and slotLocation is None: return categoryID = None capacity = None chargeVolume = None if evetypes.Exists(typeID): categoryID = evetypes.GetCategoryID(typeID) capacity = evetypes.GetCapacity(typeID) if evetypes.Exists(chargeTypeID): chargeVolume = evetypes.GetVolume(chargeTypeID) info = { 'typeName': typeName, 'typeID': typeID, 'categoryID': categoryID, 'capacity': capacity, 'numItems': numItems, 'chargeName': chargeName, 'chargeTypeID': chargeTypeID, 'chargeVolume': chargeVolume, 'slotLocation': slotLocation, 'isEmpty': isEmpty } return info
def __missing__(self, attributeID): for attribute in cfg.dgmtypeattribs.get(self.typeID, []): if attribute.attributeID == attributeID: return attribute.value ret = None if attributeID == const.attributeMass: ret = evetypes.GetMass(self.typeID) elif attributeID == const.attributeCapacity: ret = evetypes.GetCapacity(self.typeID) elif attributeID == const.attributeVolume: ret = evetypes.GetVolume(self.typeID) if ret is None: raise KeyError(attributeID) else: self[attributeID] = ret return ret
def _ApplyMaxAmountFilter(self, toMove): availableVolume = self.destPin.GetCapacity( ) - self.destPin.capacityUsed availableVolume -= planetCommon.GetCommodityTotalVolume( self.transferContents) transferVolume = planetCommon.GetCommodityTotalVolume(toMove) if transferVolume >= availableVolume: newToMove = {} if len(toMove) == 1: for typeID, quantity in toMove.iteritems(): commodityVolume = evetypes.GetVolume(typeID) maxAmount = int( math.floor(availableVolume / commodityVolume)) newToMove[typeID] = maxAmount eve.Message('ExpeditedTransferNotEnoughSpace') return newToMove else: return toMove
def GetItemVolume(item, qty=None): if item.typeID == typePlasticWrap and item.singleton: volume = -item.quantity / 100.0 if volume <= 0: raise RuntimeError( 'Volume of a plastic wrap should never be zero or less') elif item.categoryID == categoryShip and not item.singleton and item.groupID in shipPackagedVolumesPerGroup and item.typeID != typeBHMegaCargoShip: volume = shipPackagedVolumesPerGroup[item.groupID] elif item.typeID in packagedVolumesPerType and not item.singleton: volume = packagedVolumesPerType[item.typeID] else: volume = evetypes.GetVolume(item.typeID) if volume != -1: if qty is None: qty = item.stacksize if qty < 0: qty = 1 volume *= qty return volume
def FindRoutableQuantityOfResource(self, colony, path, typeID, quantity, cycleTime): minimumBandwidth = None prevPinID = None for pinID in path: if prevPinID is None: prevPinID = pinID continue link = colony.colonyData.GetLink(prevPinID, pinID) availableBandwidth = link.GetTotalBandwidth( ) - link.GetBandwidthUsage() if minimumBandwidth is None or availableBandwidth < minimumBandwidth: minimumBandwidth = availableBandwidth prevPinID = pinID baseVolume = evetypes.GetVolume(typeID) requiredBandwidth = planetCommon.GetBandwidth(baseVolume * quantity, cycleTime) if requiredBandwidth > minimumBandwidth: quantity = int(minimumBandwidth * float(cycleTime) / (const.HOUR * baseVolume)) return quantity
def ValidateCreateRoute(self, charID, path, typeID, quantity): if self.colonyData is None: raise RuntimeError( 'Unable to validate routing path - no colony data') self.PreValidateCreateRoute(path, typeID, quantity) if typeID is None or quantity < 1: raise UserError('CreateRouteWithoutCommodities') if len(path) < 2: raise UserError('CreateRouteTooShort') if len(path) - 2 > MAX_WAYPOINTS: raise UserError('CannotRouteTooManyWaypoints') sourcePin = self.GetPin(path[0]) destinationPin = self.GetPin(path[-1]) if sourcePin.IsStorage() and not destinationPin.IsConsumer(): raise UserError('CannotRouteStorageMustGoToConsumer') if not destinationPin.IsConsumer() and not destinationPin.IsStorage(): raise UserError('CannotRouteDestinationWillNotAccept') if sourcePin.IsProducer(): routes = self.colonyData.GetSourceRoutesForPin(sourcePin.id) totalCommodsUsed = {} for route in routes: routeTypeID = route.GetType() if routeTypeID not in totalCommodsUsed: totalCommodsUsed[routeTypeID] = route.GetQuantity() else: totalCommodsUsed[routeTypeID] += route.GetQuantity() sourceProducts = sourcePin.GetProductMaxOutput() if typeID not in sourceProducts: raise UserError('CreateRouteCommodityNotProduced', {'typeName': (const.UE_TYPEID, typeID)}) if typeID not in totalCommodsUsed: totalCommodsUsed[typeID] = quantity else: totalCommodsUsed[typeID] += quantity if totalCommodsUsed[typeID] > sourceProducts[typeID]: raise UserError('CreateRouteCommodityProductionTooSmall', {'typeName': (const.UE_TYPEID, typeID)}) if destinationPin.IsConsumer(): consumables = destinationPin.GetConsumables() if typeID not in consumables: raise UserError('CreateRouteDestinationCannotAcceptCommodity', {'typeName': (const.UE_TYPEID, typeID)}) additionalBandwidth = evetypes.GetVolume(typeID) * quantity pinCycleTime = 0.0 if sourcePin.IsProducer(): pinCycleTime = sourcePin.GetCycleTime() elif sourcePin.IsStorage() and destinationPin.IsConsumer(): pinCycleTime = destinationPin.GetCycleTime() else: pinCycleTime = max(sourcePin.GetCycleTime(), destinationPin.GetCycleTime()) if pinCycleTime is not None and pinCycleTime != 0.0: additionalBandwidth = GetBandwidth(additionalBandwidth, pinCycleTime) else: self.LogWarn( 'ValidateCreateRoute :: Calculating bandwidth on path', path, 'with invalid source/dest pins') prevID = None for pinID in path: pin = self.GetPin(pinID) if not pin: raise UserError('RouteFailedValidationPinDoesNotExist') if pin.ownerID != charID: raise UserError('RouteFailedValidationPinNotYours') if prevID is None: prevID = pinID continue link = self.GetLink(prevID, pinID) if link is None: raise UserError('RouteFailedValidationLinkDoesNotExist') if not link.CanRouteBandwidth(additionalBandwidth): raise UserError('RouteFailedValidationCannotRouteCommodities') prevID = pinID self.PostValidateCreateRoute(path, typeID, quantity)
def SetContents(self, newContents): self.contents = dict(newContents) self.capacityUsed = 0 for typeID, qty in self.contents.iteritems(): self.capacityUsed += qty * evetypes.GetVolume(typeID)
def move_items(self, items, count=0): if not isinstance(items, list): items = [items] if len(items) > 1: items = filter(self.DoesAcceptItem, items) if not items: return else: sourceLocation = items[0].locationID if self.itemID != sourceLocation and not sm.GetService('crimewatchSvc').CheckCanTakeItems(sourceLocation): sm.GetService('crimewatchSvc').SafetyActivated(const.shipSafetyLevelPartial) return if session.shipid and self.itemID == session.shipid: if self.itemID != sourceLocation and not sm.GetService('consider').ConfirmTakeIllicitGoods(items): return if len(items) == 1: item = items[0] if hasattr(item, 'flagID') and IsShipFittingFlag(item.flagID): if item.locationID == util.GetActiveShip(): if not self.CheckAndConfirmOneWayMove(): return itemKey = item.itemID locationID = item.locationID dogmaLocation = sm.GetService('clientDogmaIM').GetDogmaLocation() containerArgs = self._GetContainerArgs() if item.categoryID == const.categoryCharge: return dogmaLocation.UnloadChargeToContainer(locationID, itemKey, containerArgs, self.locationFlag) if item.categoryID == const.categoryModule: return dogmaLocation.UnloadModuleToContainer(locationID, itemKey, containerArgs, self.locationFlag) ret = add_item(self, item, sourceLocation=sourceLocation, forceQuantity=int(count)) if ret: sm.ScatterEvent('OnClientEvent_MoveFromCargoToHangar', sourceLocation, self.itemID, self.locationFlag) return ret elif not self.CheckAndConfirmOneWayMove(): return items.sort(key=lambda item: evetypes.GetVolume(item.typeID) * item.stacksize) itemIDs = [node.itemID for node in items] dogmaLocation = sm.GetService('clientDogmaIM').GetDogmaLocation() masters = dogmaLocation.GetAllSlaveModulesByMasterModule(sourceLocation) if masters: inBank = 0 for itemID in itemIDs: if dogmaLocation.IsInWeaponBank(sourceLocation, itemID): inBank = 1 break if inBank: ret = eve.Message('CustomQuestion', {'header': localization.GetByLabel('UI/Common/Confirm'), 'question': localization.GetByLabel( 'UI/Inventory/WeaponLinkUnfitMany')}, uiconst.YESNO) bot.log.warn('Какая-то проблема с переносом из конта в конт') if ret != uiconst.ID_YES: return for item in items: if item.categoryID == const.categoryCharge and IsShipFittingFlag(item.flagID): log.LogInfo('A module with a db item charge dropped from ship fitting into some container. ' 'Cannot use multimove, must remove charge first.') ret = [add_item(self, item, forceQuantity=int(count))] items.remove(item) for _item in items: ret.append(add_item(self, _item, forceQuantity=int(count))) return ret invCacheCont = self._GetInvCacheContainer() if self.locationFlag: ret = invCacheCont.MultiAdd(itemIDs, sourceLocation, flag=self.locationFlag) else: ret = invCacheCont.MultiAdd(itemIDs, sourceLocation, flag=const.flagNone) if ret: sm.ScatterEvent('OnClientEvent_MoveFromCargoToHangar', sourceLocation, self.itemID, self.locationFlag) return ret
def GetCommodityTotalVolume(commodities): totalVolume = 0.0 for typeID, quantity in commodities.iteritems(): totalVolume += evetypes.GetVolume(typeID) * quantity return totalVolume
def GetRoomLeft(self, capacity, typeID): roomTaken = 0 for typeID, qty in self.cachedStorageQuantities.iteritems(): roomTaken += qty * evetypes.GetVolume(typeID) return (capacity - roomTaken) / evetypes.GetVolume(typeID)
def get_jet_items(self, jet): carg = self.get_ore_cargo() # Трюм cont = invCtrl.ItemFloatingCargo(jet.id) # Джет if not carg or not cont or jet.surfaceDist > const.maxCargoContainerTransferDistance * 0.8: return vol = carg.GetCapacity() # Объем трюма free = vol.capacity - vol.used # Свободно в трюме items = self.get_cargo_items(cont) # Все элементы в джете vol_jet = cont.GetCapacity().used if not items: return do_action(2 + rnd_keys()) jet_free = True if not self.jet_is_busy(jet.id): try: for item in items: item_vol = evetypes.GetVolume( item.typeID) # Объем единици руды max_count = int( free / item_vol ) # Максимальное количество руды помещающееся в трюме count = min([max_count, item.stacksize ]) # Количество руды для переноса if count == 0: break self.info( 'Переносим {} кубов {} в контейнер ({})'.format( item_vol * count, evetypes.GetName(item.typeID), jet.id), self.role) do_action(1 + rnd_keys()) repl.move_items(carg, item, count) # Переносим руду из джета в трюм free -= item_vol * count vol_jet -= item_vol * count except: self.info( 'Ошибка при переносе руды из джета {}'.format(jet.id), self.role) else: return bp = sm.GetService('michelle').GetBallpark() pause(1000) ball = bp.GetBallById(jet.id) if not ball or int(vol_jet) == 0: jet_free = False self.del_jet(jet.id) self.info('Удаляем джет {} из БД'.format(jet.id), self.role) else: vol = cont.GetCapacity() query = 'UPDATE miner_jet SET volume = %s ' query += 'WHERE jet_id = %s' db_query(query, (vol.used, jet.id)) self.info('Меняем объем джета {} в БД - {}'.format( jet.id, vol.used)) if jet_free: self.jet_free(jet.id) self.update_jet_list()
def SpawnRandom(self, loc = None, flag = None, minQty = None, maxQty = None, iterations = None, categories = True, groups = False, want = None, onlyPublished = True, onlyUnpublished = False, useMultiMove = True, volume = None, *args): if loc is None: return if loc == util.GetActiveShip() and sm.GetService('clientDogmaIM').GetDogmaLocation().GetItem(loc).groupID == const.groupCapsule: eve.Message('CustomNotify', {'notify': 'You cannot spawn items into capsule.'}) return if minQty is None: minQty = 1 if maxQty is None: maxQty = 10 if iterations is None: iterations = 10 if minQty > maxQty: eve.Message('CustomNotify', {'notify': 'Min stack size is greater than max stack size.'}) return if minQty > iterations: eve.Message('CustomNotify', {'notify': 'Min stack size is greater than number of items.'}) return if want is None: categories = True want = [const.categoryCharge, const.categoryCommodity, const.categoryModule, const.categoryStructureModule] if type(want) is types.IntType: want = [want] if type(want) is not types.ListType: return selectedTypesAndQty = [] mustMove = [] possibleTypes = [] if categories: for typeID in evetypes.GetTypeIDsByCategories(want): if evetypes.GetVolume(typeID) < volume: possibleTypes.append(typeID) else: for typeID in evetypes.GetTypeIDsByGroups(want): if evetypes.GetVolume(typeID) < volume: possibleTypes.append(typeID) if len(possibleTypes) == 0: return for i in xrange(1, iterations + 1): selectedTypesAndQty.append((random.choice(possibleTypes), random.choice(xrange(minQty, maxQty + 1)))) title = 'Spawning...' idx = int() qty = len(selectedTypesAndQty) Progress(title, 'Processing', 0, qty) for t, q in selectedTypesAndQty: idx += 1 msg = 'Processing %d of %d' % (idx, qty) Progress(title, msg, idx, qty) if q == 0: q = 1 if eve.session.role & service.ROLE_WORLDMOD: itemID = sm.RemoteSvc('slash').SlashCmd('/createitem %d %d' % (t, q)) elif eve.session.role & service.ROLE_GML: try: itemID = sm.RemoteSvc('slash').SlashCmd('/load me %d %d' % (t, q))[0] except UserError: sys.exc_clear() else: return mustMove.append(itemID) Progress(title, 'Complete', 1, 1) if session.stationid is not None and loc != const.containerHangar: self.MoveItems(items=mustMove, source=session.locationid, destination=loc, flag=flag, multi=useMultiMove, suppress=True)
def _UpdateItemInfo(self, items): numItems = len(items) price = sum((self._GetAveragePrice(typeID) * ci.client for typeID, ci in itertools.chain(items.iteritems()))) volume = sum((evetypes.GetVolume(typeID) * ci.client for typeID, ci in items.iteritems())) self.outputContainer.UpdateItemInfo(price, numItems, volume)