FreeCAD

Форк
0
/
MaterialModels.py 
163 строки · 5.3 Кб
1
# ***************************************************************************
2
# *   Copyright (c) 2023 David Carter <dcarter@david.carter.ca>             *
3
# *                                                                         *
4
# *   This file is part of FreeCAD.                                         *
5
# *                                                                         *
6
# *   FreeCAD is free software: you can redistribute it and/or modify it    *
7
# *   under the terms of the GNU Lesser General Public License as           *
8
# *   published by the Free Software Foundation, either version 2.1 of the  *
9
# *   License, or (at your option) any later version.                       *
10
# *                                                                         *
11
# *   FreeCAD is distributed in the hope that it will be useful, but        *
12
# *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
13
# *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      *
14
# *   Lesser General Public License for more details.                       *
15
# *                                                                         *
16
# *   You should have received a copy of the GNU Lesser General Public      *
17
# *   License along with FreeCAD. If not, see                               *
18
# *   <https://www.gnu.org/licenses/>.                                      *
19
# *                                                                         *
20
# **************************************************************************/
21

22
__title__ = "material model utilities"
23
__author__ = "David Carter"
24
__url__ = "https://www.freecad.org"
25

26
import os
27
import io
28
from pathlib import Path
29
import yaml
30

31
import FreeCAD
32

33

34
unicode = str
35

36
__models = {}
37
__modelsByPath = {}
38

39
def _dereference(parent, child):
40
    # Add the child parameters to the parent
41
    parentModel = parent["model"]
42
    parentBase = parent["base"]
43
    childModel = child["model"]
44
    childBase = child["base"]
45
    for name, value in childModel[childBase].items():
46
        if name not in ["Name", "UUID", "URL", "Description", "DOI", "Inherits"] and \
47
            name not in parentModel[parentBase]: # Don't add if it's already there
48
            parentModel[parentBase][name] = value
49

50
    print("dereferenced:")
51
    print(parentModel)
52

53
def _dereferenceInheritance(data):
54
    if not data["dereferenced"]:
55
        data["dereferenced"] = True # Prevent recursion loops
56

57
        model = data["model"]
58
        base = data["base"]
59
        if "Inherits" in model[base]:
60
            print("Model '{0}' inherits from:".format(data["name"]))
61
            for parent in model[base]["Inherits"]:
62
                print("\t'{0}'".format(parent))
63
                print("\t\t'{0}'".format(parent.keys()))
64
                print("\t\t'{0}'".format(parent["UUID"]))
65

66
                # This requires that all models have already been loaded undereferenced
67
                child = __models[parent["UUID"]]
68
                if child is not None:
69
                    _dereference(data, child)
70

71
def _dereferenceAll():
72
    for data in __models.values():
73
        _dereferenceInheritance(data)
74

75
def _scanFolder(folder):
76
    print("Scanning folder '{0}'".format(folder.absolute()))
77
    for child in folder.iterdir():
78
        if child.is_dir():
79
            _scanFolder(child)
80
        else:
81
            if child.suffix.lower() == ".yml":
82
                data = getModelFromPath(child)
83

84
                if data is not None:
85
                    __models[data["uuid"]] = data
86
                    __modelsByPath[data["path"]] = data
87
                    # print(data["model"])
88
            else:
89
                print("Extension '{0}'".format(child.suffix.lower()))
90

91
def _scanModels(libraries):
92
    __models = {} # Clear the current library
93
    __modelsByPath = {}
94
    print("_scanModels")
95
    print(libraries)
96
    for library in libraries:
97
        _scanFolder(Path(library))
98

99
    # Satisfy aany inheritances
100
    _dereferenceAll()
101

102
def getPreferredSaveDirectory():
103
    pass
104

105
def getModelLibraries():
106

107
    libraries = []
108

109
    # TODO: Expand beyond the standard models as we do for material paths
110
    path = Path(FreeCAD.getResourceDir()) / "Mod/Material/Resources/Models"
111
    libraries.append(path)
112

113
    _scanModels(libraries)
114

115
    return libraries
116

117
def getModel(uuid):
118
    """
119
        Retrieve the specified model.
120
    """
121
    if len(__models) < 1:
122
        getModelLibraries()
123

124
    if uuid not in __models:
125
        return None
126
    return __models[uuid]
127

128
def getModelFromPath(filePath):
129
    """
130
        Retrieve the model at the specified path.
131

132
        This may not need public exposure?
133
    """
134
    try:
135
        path = Path(filePath)
136
        stream = open(path.absolute(), "r")
137
        model = yaml.safe_load(stream)
138

139
        base = "Model"
140
        if "AppearanceModel" in model:
141
            base = "AppearanceModel"
142

143
        uuid = model[base]["UUID"]
144
        name = model[base]["Name"]
145

146
        data = {}
147
        data["base"] = base
148
        data["name"] = name
149
        data["path"] = path.absolute()
150
        data["uuid"] = uuid
151
        data["model"] = model
152
        data["dereferenced"] = False
153
        return data
154
    except Exception as ex:
155
        print("Unable to load '{0}'".format(path.absolute()))
156
        print(ex)
157

158
    return None
159

160
def saveModel(model, path):
161
    """
162
        Write the model to the specified path
163
    """

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.