File: validator.py

package info (click to toggle)
0ad 0.28.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 182,352 kB
  • sloc: cpp: 201,989; javascript: 19,730; ansic: 15,057; python: 6,597; sh: 2,046; perl: 1,232; xml: 543; java: 533; makefile: 105
file content (234 lines) | stat: -rw-r--r-- 8,731 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#!/usr/bin/env python3
import argparse
import os
import re
import sys
from logging import INFO, WARNING, Filter, Formatter, StreamHandler, getLogger
from xml.etree import ElementTree as ET


class SingleLevelFilter(Filter):
    def __init__(self, passlevel, reject):
        self.passlevel = passlevel
        self.reject = reject

    def filter(self, record):
        if self.reject:
            return record.levelno != self.passlevel
        return record.levelno == self.passlevel


class Actor:
    def __init__(self, mod_name, vfs_path):
        self.mod_name = mod_name
        self.vfs_path = vfs_path
        self.name = os.path.basename(vfs_path)
        self.textures = []
        self.material = ""
        self.logger = getLogger(__name__)

    def read(self, physical_path):
        try:
            tree = ET.parse(physical_path)
        except ET.ParseError:
            self.logger.exception(physical_path)
            return False
        root = tree.getroot()
        # Special case: particles don't need a diffuse texture.
        if len(root.findall(".//particles")) > 0:
            self.textures.append("baseTex")

        for element in root.findall(".//material"):
            self.material = element.text
        for element in root.findall(".//texture"):
            self.textures.append(element.get("name"))
        for element in root.findall(".//variant"):
            file = element.get("file")
            if file:
                self.read_variant(physical_path, os.path.join("art", "variants", file))
        return True

    def read_variant(self, actor_physical_path, relative_path):
        physical_path = actor_physical_path.replace(self.vfs_path, relative_path)
        try:
            tree = ET.parse(physical_path)
        except ET.ParseError:
            self.logger.exception(physical_path)
            return

        root = tree.getroot()
        file = root.get("file")
        if file:
            self.read_variant(actor_physical_path, os.path.join("art", "variants", file))

        for element in root.findall(".//texture"):
            self.textures.append(element.get("name"))


class Material:
    def __init__(self, mod_name, vfs_path):
        self.mod_name = mod_name
        self.vfs_path = vfs_path
        self.name = os.path.basename(vfs_path)
        self.required_textures = []

    def read(self, physical_path):
        try:
            root = ET.parse(physical_path).getroot()
        except ET.ParseError:
            self.logger.exception(physical_path)
            return False
        for element in root.findall(".//required_texture"):
            texture_name = element.get("name")
            self.required_textures.append(texture_name)
        return True


class Validator:
    def __init__(self, vfs_root, mods=None):
        if mods is None:
            mods = ["mod", "public"]

        self.vfs_root = vfs_root
        self.mods = mods
        self.materials = {}
        self.invalid_materials = {}
        self.actors = []
        self.__init_logger()

    def __init_logger(self):
        logger = getLogger(__name__)
        logger.setLevel(INFO)
        # create a console handler, seems nicer to Windows and for future uses
        ch = StreamHandler(sys.stdout)
        ch.setLevel(INFO)
        ch.setFormatter(Formatter("%(levelname)s - %(message)s"))
        f1 = SingleLevelFilter(INFO, False)
        ch.addFilter(f1)
        logger.addHandler(ch)
        errorch = StreamHandler(sys.stderr)
        errorch.setLevel(WARNING)
        errorch.setFormatter(Formatter("%(levelname)s - %(message)s"))
        logger.addHandler(errorch)
        self.logger = logger
        self.inError = False

    def get_mod_path(self, mod_name, vfs_path):
        return os.path.join(mod_name, vfs_path)

    def get_physical_path(self, mod_name, vfs_path):
        return os.path.realpath(os.path.join(self.vfs_root, mod_name, vfs_path))

    def find_mod_files(self, mod_name, vfs_path, pattern):
        physical_path = self.get_physical_path(mod_name, vfs_path)
        result = []
        if not os.path.isdir(physical_path):
            return result
        for file_name in os.listdir(physical_path):
            if file_name in (".git", ".svn"):
                continue
            vfs_file_path = os.path.join(vfs_path, file_name)
            physical_file_path = os.path.join(physical_path, file_name)
            if os.path.isdir(physical_file_path):
                result += self.find_mod_files(mod_name, vfs_file_path, pattern)
            elif os.path.isfile(physical_file_path) and pattern.match(file_name):
                result.append({"mod_name": mod_name, "vfs_path": vfs_file_path})
        return result

    def find_all_mods_files(self, vfs_path, pattern):
        result = []
        for mod_name in reversed(self.mods):
            result += self.find_mod_files(mod_name, vfs_path, pattern)
        return result

    def find_materials(self, vfs_path):
        self.logger.info("Collecting materials...")
        material_files = self.find_all_mods_files(vfs_path, re.compile(r".*\.xml"))
        for material_file in material_files:
            material_name = os.path.basename(material_file["vfs_path"])
            if material_name in self.materials:
                continue
            material = Material(material_file["mod_name"], material_file["vfs_path"])
            if material.read(
                self.get_physical_path(material_file["mod_name"], material_file["vfs_path"])
            ):
                self.materials[material_name] = material
            else:
                self.invalid_materials[material_name] = material

    def find_actors(self, vfs_path):
        self.logger.info("Collecting actors...")

        actor_files = self.find_all_mods_files(vfs_path, re.compile(r".*\.xml"))
        for actor_file in actor_files:
            actor = Actor(actor_file["mod_name"], actor_file["vfs_path"])
            if actor.read(self.get_physical_path(actor_file["mod_name"], actor_file["vfs_path"])):
                self.actors.append(actor)

    def run(self):
        self.find_materials(os.path.join("art", "materials"))
        self.find_actors(os.path.join("art", "actors"))
        self.logger.info("Validating textures...")

        for actor in self.actors:
            if not actor.material:
                continue
            if (
                actor.material not in self.materials
                and actor.material not in self.invalid_materials
            ):
                self.logger.error(
                    '"%s": unknown material "%s"',
                    self.get_mod_path(actor.mod_name, actor.vfs_path),
                    actor.material,
                )
                self.inError = True
            if actor.material not in self.materials:
                continue
            material = self.materials[actor.material]

            missing_textures = ", ".join(
                {
                    required_texture
                    for required_texture in material.required_textures
                    if required_texture not in actor.textures
                }
            )
            if len(missing_textures) > 0:
                self.logger.error(
                    '"%s": actor does not contain required texture(s) "%s" from "%s"',
                    self.get_mod_path(actor.mod_name, actor.vfs_path),
                    missing_textures,
                    material.name,
                )
                self.inError = True

            extra_textures = ", ".join(
                {
                    extra_texture
                    for extra_texture in actor.textures
                    if extra_texture not in material.required_textures
                }
            )
            if len(extra_textures) > 0:
                self.logger.warning(
                    '"%s": actor contains unnecessary texture(s) "%s" from "%s"',
                    self.get_mod_path(actor.mod_name, actor.vfs_path),
                    extra_textures,
                    material.name,
                )
                self.inError = True

        return not self.inError


if __name__ == "__main__":
    script_dir = os.path.dirname(os.path.realpath(__file__))
    default_root = os.path.join(script_dir, "..", "..", "..", "binaries", "data", "mods")
    parser = argparse.ArgumentParser(description="Actors/materials validator.")
    parser.add_argument("-r", "--root", action="store", dest="root", default=default_root)
    parser.add_argument("-m", "--mods", action="store", dest="mods", default="mod,public")
    args = parser.parse_args()
    validator = Validator(args.root, args.mods.split(","))
    if not validator.run():
        sys.exit(1)