Ticket #2881: TreeCleaner.py

File TreeCleaner.py, 2.6 KB (added by Stan, 8 years ago)

Algorithm I used to clean up the trees.

Line 
1# <Entity uid="12">
2 # <Template>skirmish/structures/default_civil_centre</Template>
3 # <Player>2</Player>
4 # <Position x="1008.30304" z="1879.43067"/>
5 # <Orientation y="2.35621"/>
6 # <Actor seed="58274"/>
7# </Entity>
8
9import sys
10import xml.etree.ElementTree as ET
11from xml.etree.ElementTree import ElementTree
12#Name of the most generic template your are looking for
13templateName = "flora_tree_cretan_date_palm"
14#Name of the map
15mapName = "Two Seas (6).xml"
16#Radius where there should not be any identical entity
17treshold = 3;
18
19def GetMatchingTemplates():
20 treeList = [];
21 for item in root[3]:
22 if templateName in item[0].text:
23 treeList.append([item.attrib.get("uid"),item[2].get("x"),item[2].get("z")])
24 return treeList
25
26def IsTooClose(tempXpos, tempYpos, itemXpos, itemYpos, treshold):
27 return abs(tempXpos - itemXpos) < treshold and abs(tempYpos - itemYpos) < treshold
28
29def PrintStatus(numberOfObjects,currentItemIndex):
30 sys.stdout.write("[ " + '{:.1f}'.format((currentItemIndex / int(numberOfObjects)) * 100) +" % done parsing templates. (" + str(currentItemIndex) + " / " + str(numberOfObjects) +") ]")
31 sys.stdout.flush()
32 sys.stdout.write("\b" * (100+2))
33
34def GetTooCloseEntities(treeList):
35 uidList = [];
36 numberOfTemplates = len(treeList)
37 currentItemIndex = 0;
38 for item in treeList:
39 itemXpos = float(item[1])
40 itemYpos = float(item[2])
41 itemIndex = int(treeList.index(item))
42 for i in range (0,numberOfTemplates,1):
43 if i != itemIndex:
44 try:
45 entityId = treeList[i][0]
46 tempXpos = float(treeList[i][1])
47 tempYpos = float(treeList[i][2])
48 except:
49 print("NoneType Error")
50 continue
51 if IsTooClose(tempXpos, tempYpos, itemXpos, itemYpos, treshold) and entityId not in uidList:
52 uidList.append(entityId)
53 PrintStatus(numberOfTemplates,currentItemIndex)
54 currentItemIndex = currentItemIndex + 1
55 sys.stdout.write("\n")
56 return uidList
57
58def DeleteTooCloseEntities(uidList):
59 numberOfTemplates = len(uidList)
60 currentItemIndex = 0;
61 for entityList in root.findall('Entities'):
62 for entity in entityList.findall('Entity'):
63 id = int(entity.attrib.get("uid"))
64 if str(id) not in uidList:
65 continue
66 entityList.remove(entity)
67 currentItemIndex = currentItemIndex + 1
68 PrintStatus(numberOfTemplates,currentItemIndex)
69 sys.stdout.write("\n")
70
71
72
73tree = ElementTree()
74tree.parse(mapName)
75root = tree.getroot()
76DeleteTooCloseEntities(GetTooCloseEntities(GetMatchingTemplates()))
77file_handle = open(mapName,"wb")
78tree.write(file_handle, "UTF-8", True)
79file_handle.close()
80
81