While writing another MicroStation Python project, I needed to create a new, named, DGN model (Python DgnModel) in the active DGN file.
I couldn't find that exact solution in the delivered Python examples, so decided to roll my own. The algorithm shown here fits that requirement …
create_named_dgn_model
Function create_named_dgn_model lets you provide a name and,
optionally, a description of the new model …
def create_named_dgn_model(name: str, description: str = None)->DgnModel:
''' Find or create a named DGN model in the active DGN file.
If the model already exists, remove its graphic contents.
If description is provided, assign it to the model.
'''
dgn_file = ISessionMgr.ActiveDgnModelRef.GetDgnFile()
assert dgn_file is not None
# Get model ID by given model name, if ID is invalid then create new model with given name
model_id = dgn_file.FindModelIdByName(name)
dgn_model = None
if(INVALID_MODELID == model_id):
print(f'DGN model "{name}" not found')
error = MsPyDgnModelStatus ()
dgn_model = dgn_file.CreateNewModel(error, name, DgnModelType.eDrawing, False)
else:
print(f'Found DGN model "{name}"')
dgn_model = dgn_file.FindLoadedModelById(model_id)
assert dgn_model is not None
remove_all_elements_from_model(dgn_model)
if dgn_model and description and 0 < len(description):
info = dgn_model.GetModelInfo()
info.SetDescription(description)
dgn_model.SetModelInfo(info)
return dgn_model
remove_all_elements_from_model
Caution!
Function remove_all_elements_from_model cleans an existing model.
You should consider, in the context of your own application,
whether you want to call this function.
It could wipe out essential data in an existing DGN model.
Use with care!
def remove_all_elements_from_model(dgn_model: DgnModel):
'''
Removes all visible graphical elements from the specified DgnModel.
Returns: Count of deleted elements.
'''
graphical_elements = dgn_model.GetGraphicElements()
n_deleted = 0
for elemRef in graphical_elements:
eeh = EditElementHandle(elemRef, dgn_model)
element = eeh.GetElement()
# Delete only visible graphical elements
if element.ehdr.isGraphics and not element.hdr.dhdr.props.b.invisible:
if eeh.DeleteFromModel() == 0:
n_deleted += 1
print(f"Deleted {n_deleted} elements from the model.")
return n_deleted
Post questions about MicroStation Python programming to the MicroStation Programming Forum.