<<

CityEngine/SUMO Scene Construction Manual i

CityEngine/SUMO Scene Construction Manual CityEngine/SUMO Scene Construction Manual ii

Contents

1 Overview of the Manual 1 1.1 Tools...... 1 1.1.1 CityEngine [CE] ...... 2 1.1.2 SUMO ...... 2 1.1.3 OpenStreetMap [OSM] ...... 3 1.1.4 JOSM ...... 3 1.1.5 USGS National Map Viewer ...... 4 1.1.6 TERRA ...... 4 1.1.7 simpleDemViewer ...... 5 1.1.8 GIMP ...... 5 1.1.9 Quantum GIS [QGIS] ...... 6 1.2 Terminology...... 6 1.2.1 elements (nodes and edges) [CE OSM SUMO] ...... 6 1.2.2 street/sidewalk shapes [CE] ...... 7 1.2.3 blocks [CE] ...... 8 1.2.4 lot shapes [CE] ...... 8 1.2.5 models [CE DIRSIG] ...... 9 1.2.6 attributes [CE OSM SUMO] ...... 9 1.2.7 attribute sources [CE] ...... 10 1.2.8 map layers [CE] ...... 10 1.2.9 scripts [CE] ...... 11 1.2.10 CGA/rules [CE] ...... 11 1.2.11 trips [SUMO] ...... 12 1.2.12 route [SUMO] ...... 12 1.2.13 traffic simulation [SUMO] ...... 13 1.2.14 file [SUMO DIRSIG] ...... 13 1.3 Workflow...... 13 CityEngine/SUMO Scene Construction Manual iii

2 Initialization of the CityEngine Scene 15 2.1 Workflow...... 15 2.2 Create a new Project in CityEngine...... 16 2.2.1 Visual guide...... 16 2.3 Organize the CityEngine scene and input directories...... 17 2.3.1 Visual guide...... 18 2.4 Create a new Scene in CityEngine...... 19 2.4.1 Visual guide...... 19 2.5 Prepare the OSM Graph Layer...... 21 2.5.1 For segments/edges (ways in OSM)...... 22 2.5.2 For nodes/intersections (nodes in OSM)...... 23 2.5.3 Visual guide...... 24 2.6 Overwrite CE OSM import rules...... 24 2.6.1 Visual guide...... 25 2.7 Setup configuration file...... 26 2.7.1 Initialization Variables...... 26 2.7.2 Class Mappings...... 27 2.7.3 Property Objects...... 28 2.7.4 Visual guide...... 29 2.8 Load the scripts into CityEngine...... 29 2.8.1 Visual guide...... 30 2.9 existing scene and maps (script)...... 31 2.10 Import OSM street map (script)...... 31 2.11 Assign properties to edges and nodes (script)...... 32 2.11.1 Visual guide...... 32 2.12 Restart CityEngine...... 33 2.12.1 Visual guide...... 33

3 Exportation to SUMO 35 3.1 Workflow...... 35 3.2 Initialize the scene...... 35 3.3 Setup the output filenames...... 36 3.4 Select the area of the scene to export...... 36 3.5 Walk through all nodes and edges in the scene...... 37 CityEngine/SUMO Scene Construction Manual iv

4 Generating Vehicle Tracks with SUMO 39 4.1 Traffic Simulation with SUMO...... 39 4.1.1 Getting the SUMO Software...... 40 4.1.2 Importing the Road Network...... 40 4.1.3 Generating Routes...... 40 4.1.4 Populating the Road Network...... 40 4.1.5 Running the SUMO Simulation...... 41 4.1.6 SUMO Output Files...... 41 4.2 Exporting the SUMO Vehicle Tracks...... 41 4.2.1 The sumo2dirsig tool...... 42 4.2.2 Performing the Export...... 43 4.3 Importing Vehicle Tracks...... 43 4.3.1 Initial Vehicle Attributes...... 44 4.3.2 Randomizing Vehicle Attributes...... 45 4.3.3 Randomizing Vehicle Geometry...... 46 4.3.4 Dynamic Instance Import...... 47 4.3.5 Summary...... 47

5 Terrain importation and construction 48 5.1 Source Data...... 48 5.2 Importing Terrain Geometry to CityEngine...... 50 5.3 Using Terra to Facetize the Terrain...... 54 5.3.1 Building Terra...... 54 5.3.2 Preparing the Heightmap for Terra...... 54 5.3.3 Generating the Optimized OBJ with Terra...... 56

6 Constructing street geometry 59 6.1 Workflow...... 59 6.2 Initialize the scene...... 59 6.3 Import and align graph to terrain...... 60 6.4 Prepare the rule files...... 61 6.4.1 Rule ...... 61 6.4.2 Sub-division and UV-mapping...... 62 6.4.3 Assets...... 64 6.4.4 Sidewalk rules...... 65 6.4.5 Variables and functions...... 65 6.5 Transfer graph attributes to shapes and set rule file...... 66 6.6 Generate models...... 67

7 Lot Geometry 68 CityEngine/SUMO Scene Construction Manual v

8 Exporting CityEngine geometry 69 8.1 Workflow...... 69 8.2 Export CityEngine models as OBJ files...... 69 8.3 Tranforming the OBJ files...... 71 8.4 Map OBJ materials to DIRSIG materials...... 71 8.5 Replace texture maps with DIRSIG material and texture maps...... 73 8.6 reports for clutter objects...... 74

A Generating vehicle track truth 75 A.1 Instance Report Generation...... 75 A.1.1 Requesting the Report...... 75 A.1.2 Report Format...... 76 A.2 Raster Format Truth Collectors...... 76 A.2.1 Adding the "InstanceIndex" Collector...... 76 A.2.2 "InstanceIndex" Truth Map...... 77 A.3 Generating Per-Instance Tracks...... 78 A.3.1 Running the Extraction Tool...... 78 A.3.2 Track File Format...... 79 CityEngine/SUMO Scene Construction Manual

Authors: Adam Goodenough ([email protected]) Scott Brown ([email protected]) Rochester Institute of Technology ChesterF. Carlson Center for Imaging Science Digital Imaging and Remote Sensing Laboratory 54 Lomb Memorial Dr Rochester,NY 14623 CityEngine/SUMO Scene Construction Manual 1 / 82

Chapter 1

Overview of the Manual

This document describes the end-to-end process of generating a partially procedural, partially data-driven scene for use in DIRSIG (the Digital Imaging and Remote Sensing Image Generation model). CityEngine, a procedural scene generation tool, is used as the main driver for static scene geometry and SUMO (the Simulation of Urban MObility tool) is used to supply dynamic scene content (specifically vehicle movement in traffic). The framework of the scene is a data-driven description of the terrain and a street network. Both of these two inputs could be procedurally generated (as artificial terrain and/or a synthetically grown street network), but we take the approach here of using real world data. This gives us the benefit of physically realistic scenes without complex construction rules and a rich set of data that might otherwise be difficult to replicate with either model-based or statistical representations. Constructing the framework consists of obtaining these data sources and converting/importing that data into the workflow. The scene framework is coupled with user-driven descriptions of contextual information (e.g. population density) to create inputs to the procedural portion of the scene, builds the specific road/building geometry and predicts the movements of vehicles. On the geometry side, a combination of scripting and rule based decision trees are used in CityEngine to transform simple shapes into complex, three-dimensional geometry entities with material information. For the dynamic content we assume that models of vehicles are already available and we use the description of the street network (including speed limits, intersection controls, etc..) to drive a traffic model and predict the locations of vehicles as a function of . Care is taken to sure that the predicted vehicle routes match up with the three-dimensional street geometry modeled in CityEngine. Fine control over the scripting and rules in CityEngine also allow for generating non-geometric information such as the positions of trees along roadsides or the locations of street parking spots. Information about scene elements such as driveways can also be extracted and then used to drive procedural elements not generatable in the two available tools (such as vehicles driving out of parking lots). One of the overarching goals of the process described here was to have as little user interaction in the details of scene building as possible. The user is still responsible for providing a large set of input parameters and data sources, but these are meant to be high level, describing the general characteristics of a particular scene area without providing the exact details about what each component of the end product should look like. That said, the constructed scene can be seen as a starting point for very specific scene element modeling that might be relevant to the desired simulation. For instance, a generic building lot that we generate for an industrial region of the scene might be removed in favor of a specific site model. The manual is presented as a series of mostly independent, modular chapters, each focused on a particular task. This overview chapter presents a centralized list of the tools and sources of data that are in use (and what they are used for), a list of the terms and concepts that will be encountered in the rest of the manual, and a brief descriptioon of the overall workflow of generating a scene.

1.1 Tools

Though the two primary tools used in this approach to scene construction are CityEngine and SUMO, there are a number of additional tools that facilitate the workflow. Below, we list and briefly describe each of the tools used in the development of this manual and identify their main contributions. Since many of the tools were chosen for convenience rather than exclusive functionality, possible alternatives are listed as well. CityEngine/SUMO Scene Construction Manual 2 / 82

1.1.1 CityEngine [CE]

• Source: http://www.esri.com/software/cityengine [2012.1] • License: commercial ($4,000) • Usage: main scene generation driver – importation of OSM street map information – script and rule based geometry creation – script based exportation of SUMO network inputs

1.1.2 SUMO

• Source: http://sumo.sourceforge.net/ [0.16.0] • License: GPL • Usage: vehicle motion prediction – demand based modeling of vehicle trips – traffic simulation on CityEngine street network – vehicle motion for DIRSIG CityEngine/SUMO Scene Construction Manual 3 / 82

1.1.3 OpenStreetMap [OSM]

• Source: http://www.openstreetmap.org [online interface] • License: Open Data Commons Open Database License • Usage: street network information – starting point for street network graph – tagged metadata for streets and intersections • Alternatives: ESRI shapefiles with road network information, CityEngine based synthetic networks

1.1.4 JOSM

• Source: http://josm.openstreetmap.de/ [5759] • License: GPL • Usage: open street map viewer/editor – trimming raw street map data – viewing and editing tagged data • Alternatives: hand-editing OSM files, Potlatch 2 CityEngine/SUMO Scene Construction Manual 4 / 82

1.1.5 USGS National Map Viewer

• Source: http://viewer.nationalmap.gov/viewer/ [online interface] • License: public domain • Usage: digital elevation maps – moderate resolution elevation information for terrain construction • Alternatives: any other source of georeferenced elevation data

1.1.6 TERRA

• Source: http://mgarland.org/software/scape.html [0.7] • Usage: facetization of terrain elevation map • License: public domain

– transforming rasterized height data into 3D facets – optimizing the triangular mesh representation

• Alternatives: ArcGIS tools, any of many Delaunay triangulation/triangular irregular network tools CityEngine/SUMO Scene Construction Manual 5 / 82

1.1.7 simpleDemViewer

• Source: http://www.jizoh.jp/english.html [3.9.5] • License: public domain • Usage: converting DEM files for TERRA inputs • Alternatives: any convenient tool for viewing/converting georeferenced images

1.1.8 GIMP

• Source: http://www.gimp.org/ [2.8.2] • Usage: image editing • License: GPL

– synthetic property maps for driving scene attributes – layer-based editing of property maps/masks incorporating measured data

• Alternatives: Adobe Photoshop or other layer-based image editor CityEngine/SUMO Scene Construction Manual 6 / 82

1.1.9 Quantum GIS [QGIS]

• Source: http://www.qgis.org/ [1.8.0] • Usage: projecting raster data • License: GPL

– bringing raster data from different sources into the same geo-projection – property maps for scene construction

• Alternatives: ArcGIS or other GIS tool

1.2 Terminology

There are a number key terms that come into play over the course of transforming OpenStreetMap data into a final DIRSIG scene. We present those terms here to avoid giving their definitions each time they are encountered throughout the manual. The key tool(s) that use the term are given as well; one or of: OpenStreetMap (OSM), CityEngine (CE), SUMO, and DIRSIG.

1.2.1 graph elements (nodes and edges) [CE OSM SUMO] CityEngine/SUMO Scene Construction Manual 7 / 82

The street networks in all three tools (OSM, CityEngine, and SUMO) are represented by a directed graph. The nodes of the graph correspond to intersections and dead ends in the street network and, in the case of OSM and CityEngine, waypoints along a road defining its shape (SUMO has an explicit shape definition). The edges of the graph are the roads in the network and are referred to as ways, segments, and edges in OSM, CE, and SUMO, respectively. Both OSM and CE use a single edge to define a twoway road, while SUMO uses two edges for this (one in each direction). All three tools define one or more lanes for a single edge. Nodes are defined by a horizontal point in a coordinate space (possibly georeferenced), though CityEngine allows for adding vertical component that is driven by the terrain height that point. Edges are minimally defined by the two nodes that form their endpoints. Nodes and edges together are referred to as the network.

1.2.2 street/sidewalk shapes [CE]

Shapes are unique to CityEngine and convert the one-dimensional nodes and edges of the graph (geometric points and edges) into two-dimensional forms that will be used as the basis for three-dimensional models. A shape is simply a polygonal object defined by a set of two-dimensional vertices. A minimal amount of knowledge is necessary to accomplish thise, specifically CityEngine will need to know the width of the roads corresponding to each segment to generate street shapes. At nodes, where street shapes intersect, CityEngine will find a non-overlapping representation of the junction shape: CityEngine/SUMO Scene Construction Manual 8 / 82

Because sidewalks and other curb-related elements are highly correlated to the streets, it is useful to construct a parallel sidewalk shape (again, by providing the width of this area). Sidewalk shapes behave identically to street shapes, but are labeled differently and (by default) flank the street shapes.

1.2.3 blocks [CE]

When creating street shapes in CityEngine, a set of abstract blocks which explicitly define the areas corresponding to the inner- edge of the street shapes (an area that is not surrounded on all sides by a road does not create a block). Blocks are not shapes themselves, but instead can create shapes (lots), much like the graph components.

1.2.4 lot shapes [CE]

Lot shapes are generated by blocks in CityEngine and are the two-dimensional objects on which buildings may be constructed. A block is subdivided into lots based one of a handful of simple algorithms (e.g. recursive subdivision) and is not generally driven by external data. By default, lots will be generated on all blocks (even skinny blocks that might have been medians). CityEngine/SUMO Scene Construction Manual 9 / 82

1.2.5 models [CE DIRSIG]

Models are the result of applying a rule to a shape within the scene. The rule starts with the two-dimensional shape and after manipulating that shape (usually by sub-dividing and extruding) ends up with one or more three-dimensional representations. In addition to geometry, the model can contain material properties associated with surface (e.g. a texture map defining a brick surface on the side of a building). In the case of street shapes, the output model is a facetized representation of a street (including the lines, should, gutter, etc..). Sidewalk shapes are used to generate curbs, verges, sidewalks, driveways, etc..). Lots usually have the most complex rules and the outputs are facetized buildings, lawns, garages, parking lots, etc. . . The final destination of all output models is to be used as material attributed geometry in DIRSIG to construct the scene.

1.2.6 attributes [CE OSM SUMO]

Graph/block elements and shapes are defined by their geometric properties, but they also have a set of attributes attached to them that can define any number of additional properties. Since attributes are available both in the scripts and rules in CityEngine and are tied to individual scene elements, they are the primary way by which control is exerted over the scene generation process. OSM and SUMO also allow for attaching tagged information to their representation of the road network. In OSM attributes are defined as arbitrary key/value pairs (as in CE) whereas SUMO has specific properties that can be defined of relevance to the traffic simulation. When imported into CE, OSM attributes can be mapped directly to CE attributes in the graph. CityEngine/SUMO Scene Construction Manual 10 / 82

1.2.7 attribute sources [CE]

In CityEngine, there a number of ways attribute are assigned: DEFAULT (RULE), USER,OBJECT and . DEFAULT attributes are those variables that have been defined in the rule file associated with the objects but have not been defined elsewhere (i.e. they take the default value the variable was initialized with). USER attrbutes are those that have been set directly by the user, either by interacting with the object in the GUI or setting the value from a script. OBJECT attributes are inherited from the parent object (e.g. a street shape can inherit attributes from its parent segment). Finally, a attribute is connected to a map (and potentially a function that translates the map value to the attribute value).

1.2.8 map layers [CE]

Maps are images loaded into CityEngine as scene layers that associate a horizontal position in the scene with a specific property. For example, the terrain/elevation map associates a vertical position (elevation) with any point within the scene that is then used to drive the vertical postion of graph elements. In this case each grayscale pixel value value in the image is used to compute the elevation in meters. Maps are also used to drive specific attributes associated with scene elements. This can be done in a binary fashion (treating the map like a mask that might drive something like the presence of street lights). Alternatively, the pixel value can be used to drive a lookup in a table of properties, such as a region class map that describes population density and land usage. CityEngine/SUMO Scene Construction Manual 11 / 82

1.2.9 scripts [CE]

CityEngine provides a Python console and the ability to run Python modules from within the GUI. In both cases, a scripting environment provides an API to a signficant portion CityEngine’s functionality. In contrast to rules, a script is a full programming language (Python) and may be used to asynchronously build or modify the scene. While there is some functionality in place to directly work with shapes and models, a script should not replace rules and should primarily be used to edit the basic objects and apply attributes.

1.2.10 CGA/rules [CE]

The rule files in CityEngine are user-written descriptions of how two-dimensional shapes should be converted into three- dimensional models. Rules are stored in CGA, or computer generated architecture, files and every shape in the scene (that will be used) should have an associated CGA file. CGA is not a programming language in the usual sense — it can be thought of as describing how a single shape is replaced by one or more shapes and/or models (the mapping of a single shape is a rule). For procedural construction of buildings/roads, this approach is very effective since branching from one rule to the next can be randomized and/or driven by the scene context. CityEngine/SUMO Scene Construction Manual 12 / 82

1.2.11 trips [SUMO]

In SUMO, a trip describes the desire for a particular vehicle to go from node A to node B in the network, starting at a particular moment in time. It does not describe the it will take to the destination node nor is there any information about the time it will take. Trips are generated by one of many demand generation tools associated with SUMO, but not by SUMO itself.

1.2.12 route [SUMO]

A route is the specific path to be taken by a vehicle in the road network in order to complete a trip. Initial routing is usually done by considering a single criterion (such as shortest time), but may be updated after traffic simulation to take into account delays. Routes are created by an external tool called "duarouter," not by the main executable of SUMO itself. CityEngine/SUMO Scene Construction Manual 13 / 82

1.2.13 traffic simulation [SUMO]

The function of the SUMO executable (either command-line or GUI based) is to run the traffic simulation, which models what happens when all of the vehicles on the network attempt to complete their routes simultaneously. The traffic simulation is meant to be done iteratively in combination with re-generating the routes based on congestion information (i.e. the shortest route between two points may change when taking into account the amount of time spent in traffic)

1.2.14 dump file [SUMO DIRSIG]

The dump file captures the state of the street network in SUMO at a fixed sampling rate (such as every second) during the traffic simulation. This includes information about the location of every car active on the network and their speed at the time, information that is used by DIRSIG tools to produce a motion file for each vehicle in the simulation.

1.3 Workflow

The order of the modules in this manual roughly correlates to the workflow in which the scene is constructed. In general, we go from one-dimensional data (the nodes and edges of a graph network) to three-dimensional data (either vehicle movement within the scene or scene geometry). Conceptually, we can the process into street modeling (three-dimensional representations of the streets and curbs as well as the vehicles on them) and lot modeling (construction of buildings and off-street geometry in general). CityEngine/SUMO Scene Construction Manual 14 / 82

About halfway through street modeling in CityEngine we branch off a parallel process in SUMO that uses the actual street graph/shapes in CityEngine to drive the SUMO network. Once the inputs to SUMO are created, the entire traffic modeling process is independent from the rest of the scene development until the final vehicle movement files are brought into the DIRSIG simulation.

Each module is described in more detail in the coming chapters. Each module has a specific set of inputs and outputs that we list here for convenience:

inputs module tools outputs OSM data file; Initialization of the CE CE network attributed initialization script; user CityEngine Scene with street parameters configuration script; region class map attributed street Exportation to SUMO CE SUMO node and edge network; export script; files user configuration script node and edge files Generating vehicle SUMO, DIRSIG vehicle motion tracks with SUMO DIRSIG files elevation map (DEM) Terrain importation CE, Terra DIRSIG terrain and construction geometry; CE terrain-aligned graph network terrain-aligned, Constructing road and CE CE street and sidewalk attributed graph sidewalk geometry models network; street/sidewalk rule file; maps terrain-aligned, Constructing lot CE CE lot models attributed graph geometry network; lot rule file; maps scene component Exporting CityEngine CE material-attributed models (street, sidewalk, geometry DIRSIG geometry lot) material-attributed Assembling the DIRSIG DIRSIG scene geometry; vehicle DIRSIG scene motion files; external geometry CityEngine/SUMO Scene Construction Manual 15 / 82

Chapter 2

Initialization of the CityEngine Scene

Initialization of the scene involves loading and applying attributes to the scene network that are either unavailable in the CityEngine importation process or are sourced from external data (e.g. using a class map to determine sidewalk widths). This process is fully automated using the python scripting interface to CityEngine and driven by a single configuration script shared with other parts of the scripting process. One important part of initialization is to nodes to segments and segments to blocks (the basis of building lots) something that is not natively supported in CityEngine. This linking is essential for matching street specific properties (such as driveways that might act as nodes for SUMO) to the lot modeling that will be done in CityEngine.

Note Initialization of the CityEngine scene should only need to be run once to import and attribute nodes and edges from the input street map. The master script will only run the initialization module if no scene elements are selected from within CityEngine (any nodes/edges generated previously and any loaded maps will be removed prior to initialization).

Note The initialization script is wrapped with a @noUIupdate directive that indicates to the CE scripting engine should run these scripts without checking back in with the GUI (this is done to increase the speed at which the script runs). The presence of this directive means that the CityEngine interface will be non-responsive during the initialization process. To monitor what is happening as the script runs, make sure that the console window is visible in CityEngine before starting the initialization.

2.1 Workflow

• Create a new Project in CityEngine • Organize the CityEngine scene and input directories • Create a new Scene in CityEngine • Prepare the OSM graph layer • Overwrite CE OSM import rules • Create a class map • Setup configuration file • Load the scripts into CityEngine • Clear existing scene and maps (script) CityEngine/SUMO Scene Construction Manual 16 / 82

• Import OSM street map (script) • Assign properties to edges and nodes (script) • Restart CityEngine

2.2 Create a new Project in CityEngine

Action Item(s): Create a new project

A new project is started by simply selecting File > New... from the CityEngine Menu and choosing CityEngine pro ject from the list of wizards. You will have the opportunity to select a name for the new project and its location (the directory is arbitrary, but it is useful to place all of your CityEngine projects in the common CityEngine directory that was created during ).

2.2.1 Visual guide

Dialogs used in this section: CityEngine/SUMO Scene Construction Manual 17 / 82

2.3 Organize the CityEngine scene and input directories

Action Item(s): Add a sumo directory to the project tree

Each project created in CityEngine will be laid out in its own directory tree structure, to which we will add our input data. Since the SUMO output is tightly coupled to the CityEngine model, we’ll add a directory called "sumo" to the tree to hold our exported data. This directory will be referenced from the master script as: import os ... sumo_dir= top_dir+’sumo/’ if not os.path.exists(sumo_dir): os.makedirs(sumo_dir) where the top_dir variable contains the location of the project tree directory in the local file system and needs to be set by the user at the beginning of the master script.

Note While almost all user-driven parameters are provided in the configuration script, we need to modify the master script (the one loaded into CityEngine) to provide this top_dir so that the CE-based python engine knows where to look for the input scripts.

The project directory (after creating the sumo directory) is layed out as:

assets location for external data used to build the CityEngine scene (3D models that are not procedurally built, texture images, etc. . . ) data directory for arbitrary data of use in scene building — we will use it for storing the OSM street maps images standard output directory for screen snapshots CityEngine/SUMO Scene Construction Manual 18 / 82

maps storage for images that are imported as layers into CityEngine (the height map, road classification map, etc. . . ) models output directory where the street and building geometry files will be exported to rules files containing the CG language rules for building procedural scene elements scenes one or more project files containing scene states scripts Python scripts that are used from within CityEngine; we also use this directory to store modules to be imported sumo our created directory that will store the SUMO output generated from the CityEngine street network

CityEngine also creates a special directory, ce.lib, that we will modify (it should be located in the default project location, determined at install and parallel to the user-created project).

2.3.1 Visual guide

Adding a folder through the CityEngine interface. Adding a folder can be done using normal tools as well. In that case File > Refresh Workspace should be selected from the menu to display the changes in the CE interface. CityEngine/SUMO Scene Construction Manual 19 / 82

2.4 Create a new Scene in CityEngine

Action Item(s): Create a new scene

A new scene is created within a project by selecting File > New... from the CityEngine Menu and selecting CityEngine scene from the list of wizards. You will have the opportunity to select a name for the new scene and its location (use the default +scenes* directory within the project that was created). It is possible to have many scenes for a single project and this is a useful way to share data between different versions of a particular location. You also have the option of setting the coordinate system for the scene at this point. Since the interface for doing this can be rather cumbersome, you can just leave this blank for now and we’ll just automatically set it when importing the OSM data later on (under most circumstances, you’ll want to use the OSM coordinate system for all elements of the scene anyways).

Important Unless you have a reason to manually set the coordinate system by hand, just leave the Coordinate Sytem entry blank for now

You should now see an empty scene in the viewport with a default grid.

2.4.1 Visual guide

Dialogs used in this section: CityEngine/SUMO Scene Construction Manual 20 / 82 CityEngine/SUMO Scene Construction Manual 21 / 82

2.5 Prepare the OSM Graph Layer

Action Item(s): Obtain and edit (optional) an OSM data set; Place OSM file into the data directory

The easiest way to build a fully attributed and logical road network is to import external data from real world locations. Open Street Map (OSM) hosts a free, worldwide map created by its users and is supported directly by CityEngine (SUMO supports importing OSM data as well, but due to differences in importation policies we import into CE and then manually export to a format that can be digested by SUMO with minimal changes). The website provides information about how to download the OSM data, but the general idea is to provide the geodetic locations of the corner points (either by a bounding box selection or by directly inputting the corners).

Note The of data useful for scene construction (and necessary for input into CityEngine) is contained in the "OpenStreetMap XML Data" output option

The following figure shows part of an OSM file visualized in JOSM (a native OSM editor). CityEngine will use the road network (locations, number of lanes, etc. . . ) as the basis for synthesizing road geometry and generating the network that will be passed to SUMO for traffic modeling. CityEngine/SUMO Scene Construction Manual 22 / 82

Figure 2.1: OSM data visualized in JOSM

Aside from visualizing and inspecting the OSM data from JOSM, it can also be used to modify, add or remove tags from the map itself.

Important JOSM will ask you to upload any changes you make to the OSM file to the community of users before exitting. Please do not do this unless you are certain the changes are representative of the real world locations.

CityEngine can automatically convert all OSM tags to segment and node attributes, but only a small subset of tags are relevent to constructing the street network. These are:

2.5.1 For segments/edges (ways in OSM)

• highway tags (required - indicates the type of street)

– motorway – motorway_link – trunk – trunk_link – primary – primary_link – secondary – tertiary – tertiary_link – unclassified – residential – living_street – service – unsurfaced

• lanes (optional - full number or lanes in both directions or in one, if oneway) • oneway (optional - indicates that the street is oneway ""/"no") CityEngine/SUMO Scene Construction Manual 23 / 82

• maxspeed (optional - maximum speed in mph)

Note The concept of lanes is different between OSM and SUMO. In OSM the lanes tag indicates the total number of lanes along a road (in both directions), while in SUMO, lanes are given for a single direction only. Since we will be exporting the built street network to SUMO, we choose the SUMO convention (OSM lanes are automatically converted in the scripts as necessary). There is also a discrepancy between the speed in OSM and SUMO (mph vs m/s) and tags are automatically converted as needed.

In the OSM XML file these tags appear as k/v (key/value) pairs:

Note Each of the highway tags have their own default values for "lanes" and "maxspeed" (defined in the user configuration script below). The values in the OSM file will override the default values if provided.

2.5.2 For nodes/intersections (nodes in OSM)

• highway tags (indicates the type of intersection)

– traffic_signals (optional - indicates traffic lights at the intersection) – stop (optional - indicates stop signs at the intersection)

As with the non-highway tags above, the node tags can be used to override the default behavior of the road types.

Important The tags listed (with the exception of the way highway tag) are completely optional and should only be added (or kept) if the user desires to override the default characteristics of the road type.

Normally, importing the OSM data into CityEngine gives the user the option of selecting only those tags that they wish to map to CE attributes. However, the script engine version of the import does not support choosing specific tags (the OSM import options object has not been fully impolemented and the "interactive mode" alternative ignores any selections made by the user). Instead, the desired tags are listed in the configuration file and anything else is automatically deleted during initialization. Normal OSM maps usually have between ten and a hundred tags per way/node before we add our own so this cleanup is an important step. Once the OSM file is prepared it should be placed into the data subdirectory of the project tree. CityEngine/SUMO Scene Construction Manual 24 / 82

2.5.3 Visual guide

We’ll use a small section of a city grid as a running example for the Visual guide. It is shown below, visualized in JOSM (Potlatch2 style).

2.6 Overwrite CE OSM import rules

Action Item(s): Backup and edit ce.lib; Restart CityEngine

The special directory, ce.lib mentioned above, contains the rules used during the OSM importation process ("osm.ceattr"). Specif- ically, the rules are used to define a number of special attributes:

streetWidth the width used for the street segment being imported [m] sidewalkWidthLeft the width of the sidewalk (area starting with the curb) to the left of the street segment [m] sidewalkWidthRight same for the right of the street segment [m] precision a value in the range [0:1] defining the sampling precision of the bezier curve connecting street nodes minArcRadius controls the curvature around corners [m]

The CityEngine documentation can be consulted for more details. We choose to replace the default rules for OSM importation for two reasons. First, we want to drive the streetWidth parameter with a combination of class-based and mapped properties, neither of which are accessible during import. Second, minimizing the amount of curvature (Bezier curves) that CityEngine uses facilitates exportation to SUMO. CityEngine/SUMO Scene Construction Manual 25 / 82

Warning Before making any modifications to "osm.ceattr", make a backup copy of the original file

The replacement rules should be placed in the scripts subdirectory of ce.lib, replacing the file "osm.ceattr". The entire file should look like: #2012.1

//------// internal vars for the initial graph(set to preserve graph) attr streetWidth = 0.0 attr sidewalkWidthLeft=0 attr sidewalkWidthRight=0 attr precision=0 attr minArcRadius=0

Important The streetWidth is set to zero to force the vertexes of the blocks (the container shape of lots) generated by CityEngine to coincide with the nodes of the street network. This allows for finding neighboring blocks quickly and accurately regardless of orientation and attributing the streets with this information (CityEngine does not provide any way to relate roads and blocks/lots otherwise and this information is necessary for things like driveways). Without this step, an expensive distance calculation would need to be done for each check.

CityEngine will have to be restarted at this point in order for the changes to go into effect.

2.6.1 Visual guide

While not yet available, the "osm.ceattr" file in use can be visualized once the OSM data has been imported by selecting the network from the scene navigator and using the inspector. This is shown below, for the example OSM network that will be imported later: CityEngine/SUMO Scene Construction Manual 26 / 82

Important This view of the "osm.ceattr" is not yet available! Once the OSM file is imported the rules file can be verified.

2.7 Setup configuration file

Action Item(s): Place a copy of the configuration script in the scripts directory; Modify the user configuration script as needed

The configuraton script cesumo_config.py contains all of the user driven data necessary to run the initialization script as well as the other scene-building scripts in CityEngine. There are two basic types of information that are provided in this script. First, the user can set input filename information as well as some default values used to build the scene. Second, the user can modify a set of scene classification schemes that are used to modify the properties of the objects in the scene, either through their position (via a map lookup) or by their type (a tagged attribute). These two sets of information (those relevant to intialization) are described below.

2.7.1 Initialization Variables

ox, oy This is the origin of the local coordinate system along the x and z-axis in the scene coordinate system (usually UTM). All positions will be reported relative to this origin and maps are anchored relative to this point

Important CityEngine uses the X/Z axes for the horizontal coordinate system (+Y is up). The y used here references a strictly 2D coordinate system.

bbminx, bbminy, bbmaxx, bbmaxy These values define a bounding box surrounding the scene that the user desires to model. Any nodes or edges outside of CityEngine/SUMO Scene Construction Manual 27 / 82

this box will be removed from the scene. The coordinates are given in the scene coordinate system (e.g. UTM) but again the X/Y convention is used. elvation_map_filename This is a string holding the name of the image to be used as the elevation map. The filename should be given relative to the scene directory and, if the maps are stored in the "maps" subdirectory, should start with "maps/" class_map_filename Same as the elevation map filename, but this time the image should contain regional classification information osm_network_filename The OSM data to be imported (the XML file should have an ".osm" extension). The filename should also be prepended with the proper subdirectory ("data/") keep_tags This is a set of OSM tags that should not be removed from imported objects. Assuming that OSM is allowed to override road type properties, this should consist of ["highway","maxspeed","lanes","oneway"] and minimally of ["highway"] default_lane_width This is the base width (in meters) used for each lane in a road. It is suggested that the road classes (below) base their own widths off of this. 3.5 meters (about 12ft) is supplied as a default.

2.7.2 Class Mappings

The region class taxonomy describes different types of areas (areas with different lot sizes/content, different types of sidewalk- s/verges, etc..) to be found in the scene. The locations of these regions are communicated to the scripts by providing a grayscale class map (filename provided as a variable, see above). A fixed number of pixel values are associated with specific regions. The mapping from pixel value to region type is somewhat arbitrary, but follows the general scheme of white for densely populated areas and black for unpopulated areas. These associations are, by default:

pixel value region class description 250 urban_center center of a densely populated urban region (skyscrapers, financial buildings, highrises, etc. . . ) 225 urban_heavy densely packed mixed-use urban region with minimal greenspace or off-street parking areas (aside from full garages) 200 urban_light densely packed mixed-use urban region allowing for some off-street parking and greenspace 175 industrial large industrial buildings (with stacks, converters, etc..) and large parking areas 150 commercial large box stores with large parking areas and malls 125 suburban_hi high income, exclusively residential areas with large lots as well as greenspace, larger verges and sidewalks 100 suburban_md small to mid-size house lots and larger lots with condomonium/apartments complexes and greenspace CityEngine/SUMO Scene Construction Manual 28 / 82

pixel value region class description 75 suburban_lo small house lots and apartments, patchy sidewalks/verges 50 rural large house lots bordering forested areas, lack of sidewalks/verges 25 agricultural very large lots, larger buildings (barns/silos), lack of sidewalks/verges 0 park very large lots, internal paths, no buildings or other features

Important The region classes are convenient definitions to allow the variations in the scene to be described easily. A user can modify the pixel value mapping and can provide additional classifications, but only if the appropriate property objects are defined (see the next section).

2.7.3 Property Objects

Property objects are abstract containers for related properties that can be used generically in the scripts yet be tailored to specific classes obtained from the current position in the map or the particular type of a scene element. For roads, two objects are defined. First is a RoadType type that is implemented as a simple Class in Python and sets up some basic properties by using the highway tag associated with edges (e.g. "residential", "tertiary", "motorway", etc..). The properties defined by the RoadType type object are given below:

property description priority a number representing the priority of this road type; at intersections of roads of different types with no signage or lights, a lower priority yields to a higher one maxspeed the maximum speed (of a typical driver, not the speed limit) given in m/s if not overriden by the OSM tag lanes the default number of lanes (in a single direction) if not overriden by the OSM tag primary_int the intersection type to use with roads of the same type ["allway_stop", "traffic_light", "priority_stop"] secondary_int the intersection type to use with intersecting roads of lesser priority has_sidewalks flag for the possibility of sidewalks/verges (also determined by region class) has_driveways flag for the possibility of driveways (also determined by region class)

The configuration script has road objects implemented for each available highway tag and stored in a dictionary called "roads" by the tag value so they can easily be looked up by the scripts. The second type of road object is called RoadClass and it describes the general properties used to build physical roads across road types. The RoadClass object is implemented as a Python namedtuple so that a default object can be setup and specific properties can be simply replaced by name when defining objects for specific regions without having to redefine the entire set of properties. These properties are: CityEngine/SUMO Scene Construction Manual 29 / 82

property description has_lines flag for painted lines [True/False] lane_width = width of lanes [m] shoulder_width = width of the shoulder in [m] gutter_width = width of the gutter in [m] curb_height = height of the curb in [m] curb_width = width of the curb in [m] verge_width = width of the verge in [m] verge_type = type of verge [asphalt, concrete, sidewalk_width = width of the sidewalk in [m] dirt, grass, trees] sidewalk_type = type of sidewalk parking_length = length of a spot [m] (zero [asphalt,concrete,dirt] indicates no parking) driveway_spacing = space between driveway_smallest_width = smallest width of driveways/entrances [m] (zero indicates no driveways/entrances [m] (actual width might break in curb) be randomly larger)

Note All width/heights can be set to zero (except lane_with) to eliminate modeling that part of the road.

2.7.4 Visual guide

While its possible to edit Python script files from within CityEngine, it can be easier to use an external text editor to do so.

2.8 Load the scripts into CityEngine CityEngine/SUMO Scene Construction Manual 30 / 82

Action Item(s): Copy the master and initialization scripts to the scripts directory; Set the top_dir in the master script; Load the master script into the CE interface and run it

The master script is used to drive both the initialization (which occurs if no scene elements are selected) and scene construction (covered elsewhere). It should be copied to the scripts directory and then modified to have the variable top_dir point the the project directory. Some additional scripts are required as well and should be copied to the same directory. The scripts needed for initialization are:

"build_osm_streets.py" master script (top_dir should be modified) "cesumo_config.py" user configuration script (filenames should be modified) "cesumo_initialize.py" core initialization script "cesumo_image_sampler.py" class maps sampler

The master script now needs to be loaded into the CE interface which can be done through Scripts > Add Script.... Once loaded, the master script can be run from this same menu or by using the shortcut provided.

Important The Console window in CityEngine will contain any output from the scripts describing what is being done during each step. This is also the location of any messages regarding errors when running the scripts (in addition to a debug dialog provided by CityEngine). To make sure that you can see this window while the scripts are running, make sure that its visible before starting the initialization scripts.

Make sure that no scene elements are selected and run the master script from the Scripts menu item, which will begin the scripted portion of the initialization process.

2.8.1 Visual guide

Once placed in the scripts directory, the master script is added directly to the CityEngine interface: CityEngine/SUMO Scene Construction Manual 31 / 82

2.9 Clear existing scene and maps (script)

Action Item(s): Actions occur as part of the script

Before importing the OSM file and creating the new network, it is desirable to clear any existing layers that were added previously by this script. To this end, layers loaded during initialization are labeled with the name "osm graph", the class map as "class map" and the elevation map as "elevation map". During the clear phase these labels are searched for in the scene and deleted.

2.10 Import OSM street map (script)

Action Item(s): Actions occur as part of the script

Due to scripting limitations the entire OSM file must be imported and all tags mapped to attributes in the network. After this process is complete, the network is "cleaned" by removing objects outside of the bounding box and tags not in the keep_tags CityEngine/SUMO Scene Construction Manual 32 / 82

user option

Warning The import setting classes have not yet been fully implemented in CityEngine (as of 2012.1). Therefore it is not possible to efficiently automate the process of importing an OSM street map without requiring specific formatting of the OSM file.

Warning CityEngine (2012.1) will ignore tag selections made during a (scripted) interactive importation process and will instead map all OSM tags.

Warning CityEngine (2012.1) occasionally re-maps tags upon import (e.g. certain highway::tertiary tags have been seen mapped to attribute highway="pedestrian"). It is unknown why this occurs or how it is triggered and there is no known workaround aside from editing the CE scene by hand.

2.11 Assign properties to edges and nodes (script)

Action Item(s): Actions occur as part of the script

The only connection between the three basic graph objects (nodes, edges, and blocks) in the CE scripting environment is the ability to obtain the two end nodes associated is an edge. Because we need to effectively walk through streets (for SUMO exportation and other scripting processes) we need to now go through and figure out which edges are connected to each node and store this information. We do a similar attribution for the block-edge connections, this time searching the blocks for vertexes that are coincident with the end nodes of segments. Additionally, during this process we label the types of intersection (from the properties defined above) and the widths of the streets and sidewalks. Finally, CityEngine’s Cleanup graph. . . routine is called to make sure that all nodes and edges are connected appropriately.

2.11.1 Visual guide

As the scripts progress you will see messages from the scripts describing what is happening in the Console window: CityEngine/SUMO Scene Construction Manual 33 / 82

2.12 Restart CityEngine

Action Item(s): Save the CityEngine scene; Restart CityEngine

Due to apparent limitations of the scripting engine, the scene must be saved and CityEngine must be restarted before any further work can be done.

Important After running the initialization script, it is necessary (version 2012.1) to save the scene, quit CityEngine, and restart CityEngine (the scene should be loaded automatically). This is due to the fact that the shapes will only be partially loaded after the script runs and be locked in whatever form they are in. After restarting (and re-loading the scene) the shapes will be fully generated. There is no known reason for this behavior.

We now have a network that has been cleaned of unnecessary information, has been updated with new attributes and fitted with shapes based on those attributes. We are now ready to generate a SUMO network and to build geometry on our shapes.

2.12.1 Visual guide

At the end of the initialization script you should see a network that looks unfinished (shapes are partially defined and the graph has a number of red lines in it). By saving and restarting CityEngine, this problem is fixed: CityEngine/SUMO Scene Construction Manual 34 / 82 CityEngine/SUMO Scene Construction Manual 35 / 82

Chapter 3

Exportation to SUMO

While both SUMO and CityEngine have the ability to convert OSM to their own network formats, these two processes end up being slightly different. CityEngine is focused on using the OSM data to build a 3D construction of streets, sidewalks and building lots that have a physical (if virtual) presence. SUMO, on the other hand, works very well in a 2D, vectorized world in which vehicle flows can be represented in isolation. These two different goals result in two different interpretations of the input data, making it difficult, if not impossible, to match the vehicle positions predicted by SUMO to the physical models of streets generated by CityEngine. Instead of trying to force these two independent processes to match, we take the approach of developing the network as much as possible in CityEngine and then gathering the information relevant to SUMO from the CityEngine network and exporting that information as directly as possible into SUMO. That direct link takes the form of translating the nodes and segments in CityEngine to a set of nodes and edges that we can translate into a SUMO network. Because CityEngine does not normally need a lot of the information that we require to write out the SUMO input files, it is necessary to generate additional connections between scene elements and provide additional attributes representing information that is useful to SUMO. Most of this information is generated in the initialization phase (accomplished in a separate module of this manual). Once that data is in place, exporting the SUMO network is a matter of walking through the scene (or part of it) and writing out nodes and edges as required.

3.1 Workflow

• Initialize the scene • Setup the output filenames • Select the area of the scene to export • Walk through all nodes and edges in the scene

3.2 Initialize the scene

During the initialization process, all the directories are setup, OSM data is imported and the scene elements are attributed based on the user configuration script. The initialization phase creates a sumo folder in the ’top_dir" defined in the master script. This is where the exported SUMO files will be written. All of the attributes that are relevant to the exportation process were assigned to the nodes and segments in CityEngine based on the input OSM data and the user-defined road types and region classes (see the initialization documentation for details). Primarily, we need to know how nodes and segments are connected and basic properties such as the number of lanes. The exact attributes we will use are: Node attributes CityEngine/SUMO Scene Construction Manual 36 / 82

attribute description edges a comma separated list of edges that are connected to this node (edges are identified by their name, which was assigned during initialization) type a simple description of what this node represents; nodes can be connects (a sample point along a single road), intersections (where multiple roads meet), merges (points at which oneway roads become two way roads) or ends (dead end markers)

Edge attributes

attribute description oneway flag indicating if the road is oneway only ["yes"/"no"] lanes the number of lanes (in one direction) for this road maxspeed the maximum speed along the road [m/s]

Warning While the initialization process defines the needed attributes for every node and segment, occasionally some of the objects will end up not having the needed attribute. These rare cases (especially for very large, complex scenes) means that it is important to check for the validity of retrieved attributes (testing whether or not they are equal to None)

3.3 Setup the output filenames

Very little of the exportation process relies directly on user inputs, but the root name of the output files is set in the configuration script (the same configuration script as was used for initialization). This variable is labeled sumo_root in the configuration and the output files will have names ".nod.xml" and ".edg.xml" for the nodes and edges, respectively. Additionally, the origin of the local coordinate system (discussed in the initialization document) is used to translate global coordinates in CityEngine to local coordinates in the exoported SUMO files.

3.4 Select the area of the scene to export

Before the actual script that does the exportation process is called, it is necessary to select the region of the scene to be exported. This can be done simply through the CityEngine interface, either by selecting the whole scene or a portion of it.

Important The bounding box selector in CityEngine has to modes of operation. If the box is drawn from upper left to lower right, then only scene elements fully within the bounding box are included in the selection. If the box is drawn from the lower right to upper left then any scene element that intersects the box is included in the selection.

Warning If selecting via a CityEngine viewport, make sure that the graph networks are visible (other scene element types can be selected as well, but they will be ignored)

The exportation process itself is the started by running the master script (when a selection is made, no initialization is done) CityEngine/SUMO Scene Construction Manual 37 / 82

3.5 Walk through all nodes and edges in the scene

The exportation process itself is a matter of walking through the (non-connect) nodes in the scene and then walking through each connected edge. Each path between non-connect nodes only needs to be walked once so we add a simple bookkeeping attribute to the nodes to keep track of what we have finished as we go through. The output data formats are very simple XML documents. The first contains the nodes in the network (the ".nod.xml" file) and is structured like:

...

Each non-connect node in CityEngine maps directly to a node entry in the output file. The XML attributes are as follows:

attribute description id this is the name of the node in CityEngine; the number at the end is the OSM ID from the original file (this is a useful value to use for cross-referencing OSM, CityEngine and SUMO data) x the position along the x-axis in the local coordinate system (measured in meters from the user supplied origin); this corresponds to the x-axis in CityEngine y the position along the x-axis in the local coordinate system (measured in meters from the user supplied origin); this corresponds to the z-axis in CityEngine type the type of intersection (from the node attribute of the same name)

Note Oneway merges (where two oneways become a twoway road and vice versa) are modeled as nodes but are given the unreg- ulated type to make sure that there is no stopping at the merge.

The final joinExclude entry is a list of nodes that should be excluded from junction joining by the SUMO tools (normally a very important step to simplify complex intersections). This is primarily used for marking dead end nodes to ensure they are not combined with the nearest intersection. The edges are written out similarly to the ".edg.xml" file. The format of that document looks like:

...

CityEngine/SUMO Scene Construction Manual 38 / 82

The XML attributes for edge entries are:

attribute description id this is the name of the edge in CityEngine, which we assigned to an index in the initialization process, plus an a or b; because twoway streets are represented in these SUMO inputs as separate edges, the a and b are used to differentiate those directions from the node at which the edge starts (corresponds to an id in the nodes file); note that directionality matters here — cars flow from the "from" node to the "to" node to the node at which the edge ends (corresponds to an id in the nodes file) numLanes the number of lanes in the direction of the edge speed the maximum speed along the edge [m/s] shape this is a list of 2D points that the road passes through; the shape list is only necessary when the road is not straight

Warning According to the SUMO manual shapes are only supposed to be internal points (i.e. the redundant endpoints are not supposed to be included). However, there appears to be a bug where shapes that are heavily sampled on one side but not the other end up removing one of the end nodes. To workaround this situation we always write out the end nodes whenever a shape is output.

Important The only way to consistently get directionality out of CityEngine is to look at the vertices of edges (the order corresponds to the original OSM order). This is very important for determining the direction of oneway streets. CityEngine/SUMO Scene Construction Manual 39 / 82

Chapter 4

Generating Vehicle Tracks with SUMO

The goal of this document is to explain how the Simulation of Urban Mobility (SUMO) software can be used to compute the location of vehicles as a function of time (e.g. a traffic pattern) for a DIRSIG simulation. In general, the process can be broken down into a series of steps:

• Create/Import the road network for SUMO • Populating the road network with a traffic pattern • Running the SUMO simulation • Exporting the SUMO generated 2D vehicle tracks to 3D DIRSIG dynamic instance descriptions • Associating those dynamic instances with geometric vehicles

Regarding the frequency which these tasks are performed, consider the following guidelines:

• A new road network is only created and imported into SUMO when a new scene is created for DIRSIG. If you are simulating a different traffic pattern with the same scene, you reuse the existing road network. • Populating the road network is performed any time you want to simulated a new traffic pattern. The road network can be reused, but the vehicles within the pattern may be different. • A new SUMO simulation is run whenever either the road network is updated (new or updated roads, new or updated traffic control devices, etc.) or when the traffic pattern is changed (different traffic routes, different numbers of vehicles, etc.). • The SUMO vehicle tracks are only exported when a new SUMO simulation is performed. If the same SUMO simulation is used in a DIRSIG simulation, then the vehicle track export step does not need to be performed again. • The association the vehicle geometry to imported vehicle tracks in DIRSIG only needs to be performed if a new SUMO simulation has been generated, or the associations of vehicle geometry to vehicle tracks are to be changed.

4.1 Traffic Simulation with SUMO

The SUMO model is traffic simulator that utilizes an agent-based modeling (ABM) approach, where each vehicle is an individual agent attempting to navigate a supplied road network. Each agent must obey traffic rules define in the road network (stop signs, traffic lights, etc.) and it must avoid other vehicle agents. If the roads are congested (for example due to intersection slow downs), then the traffic will slow as vehicles must for each other.

Note The goal of this section is not to replace the SUMO documentation. It is supposed to highlight techniques and approaches we have utilized. For a more complete explanation of how to use SUMO, please consult the SUMO documentation. CityEngine/SUMO Scene Construction Manual 40 / 82

The following is a list of important files utilized and/or created in the context of a SUMO simulation:

• The input "network" file describes the road network that the traffic will be modeled within. This network file contains descrip- tions of the roads, intersection, traffic control devices, etc. This XML file usually has a .net.xml file extension. • The input "route" file describes specific routes for vehicle within the road network. This XML file usually has a .rou.xml file extension.

• The input "configuration" file tells SUMO which road network file to use, which routes file to use, the output state dump file to create and the time window to simulate. This XML file usually has a .sumocfg file extension. • The output state "dump" file is produced by the SUMO simulation and contains the position of each vehicle as a function of time.

4.1.1 Getting the SUMO Software

The SUMO software is available on SourceForge . The software can be downloaded precompiled and packaged for common platforms or downloaded as source code and compiled. The software includes the core agent-based simulation tool, a graphical interface for visualizing a SUMO simulation and tools to import road network data into the tool.

4.1.2 Importing the Road Network

The key input for the SUMO model is the road network that the traffic is navigating. This is a simple nodal network defined by "nodes" (waypoints along a road, intersections, etc.) and "edges" (connections between the nodes). Each "edge" can be attributed with properties including how many lanes are present, the speed limit, etc. The most common source of road network data we have used is OpenStreetMap (OSM). The SUMO software has many documented road network import methods and comes with tools to import road networks from common sources including Open Street Map (OSM). The following syntax shows how to use the netconvert tool to import a road network in OSM format (triggered by the --osm argument). netconvert--junctions.\ --remove-edges.by-vclass rail_slow,rail_fast,cityrail,lightrail,bicycle,pedestrian\ --no-turnarounds--osm salt_lake_city.osm\ -o salt_lake_city.net.xml

Note The --remove-edges option can be used to ignore classes of edges in the OSM input data that are not roads. In this case, the list includes railroads, bike ways and pedestrian paths.

4.1.3 Generating Routes

SUMO can generate random routes for vehicles, but many times we will want to define specific routes. This section will attempt to outline that process.

4.1.4 Populating the Road Network

This section will discuss methods for populating the road network with traffic. This may include discussions of the following:

• Creating specific routes • Flood filling the network with random vehicles CityEngine/SUMO Scene Construction Manual 41 / 82

4.1.5 Running the SUMO Simulation

This section will explain the basics of running the SUMO simulation. Again, this is not supposed to replace the SUMO docs. The SUMO input "configuration" file is a simple XML file:

Note A list of route-files can be supplied using a semicolon (;) as the filename token separator. For example,

The simulation can be run from the command-line by supplying the SUMO program with the input configuration file: $ sumo salt_lake_city.sumocfg

4.1.6 SUMO Output Files

This section will briefly discuss which output files from SUMO we want and maybe a little bit about what they contain.

4.2 Exporting the SUMO Vehicle Tracks

The next major step is to convert the vehicle location data generated by SUMO into a format that can be ingested by DIRSIG. In addition to forming the vehicle track data into a format that DIRSIG already reads, this step accomplishes two additional and important tasks:

• The 2D vehicle location from SUMO is converted to a 3D location by determining the the Z height in the scene at the given 2D (XY) location. This allows the vehicles to follow the terrain in the DIRSIG scene.

• The 2D vehicle location from SUMO does not include a velocity vector to define the vehicle orientation. Therefore, the vehicle orientation must be determined by linearly interpolating between known locations. This allows the vehicles to always point in the direction they are traveling.

After the tool is run, the single output file generated by SUMO containing 2D vehicle locations will have been converted into N DIRSIG format .mov files that contain the 3D location and orientation for each individual vehicle in the SUMO simulation. CityEngine/SUMO Scene Construction Manual 42 / 82

4.2.1 The sumo2dirsig tool

This section will outline the sumo2dirsig tool which converts the SUMO output file into .mov files for each vehicle modeled. The following are required inputs:

SUMO Road Network File This is the XML file that defined the road network utilized in the SUMO simulation. This file is provided via the -- sumo_network option and usually has a .net.xml extension. SUMO Simulation Output File This is the XML "dump" file produced by the SUMO, which contains the vehicle locations as a function of time. This file is provided via the --sumo_netdump option and usually has a .dump extension. Scene GLIST File In order to convert the 2D SUMO coordinates to 3D DIRSIG locations the user must provide an input GLIST file that contains the basic geometry of the terrain and roads. This is the geometry which will be used to determine the correct Z altitude for each vehicle as a function of XY location. This file is provided via the --scene_glist option. Output GLIST File The output of the tool is a set of DIRSIG .mov files and a GLIST file with all of the dynamic instances for the exported vehicle tracks setup. This file is provided via the --output_glist option.

The following options are also available:

Scene Origin The output .mov files utilize the Scene ENU coordinate system and the SUMO road network is usually in the UTM coordinate system. This scene origin allows the user to incorporate the offset of the Scene ENU coordinate system within the UTM zone for the scene. This offset is provided by the --scene_origin option. MOV File Basename By default, the exported .mov files created by this tool are named sumo_ followed by the SUMO vehicle identifier. The --mov_basename option can be used to change the output file basename to something other than sumo_. MOV File Folder By default, the exported .mov files created by this tool are placed into the folder the program is run from. If the user wishes to change the output folder name (in order to export the .mov files directly into the desired location within the scene folder hierarchy), then the --mov_folder option can be specified. MOV File Path By default, the output .glist file will not manipulate the path to the .mov file specified in each entry. This can create a problem when the .mov files are not placed in the same folder as the .glist file. The -- mov_path option lets the user specify the path to the .mov files in the output .glist file. you

The tool has the following usage message: $ sumo2dirsig

DIRSIG4 Release: 4.6.0 (r12530) Build Date: Jun 12 2013 17:00:09 Copyright 2005-2013 Rochester Institute of Technology usage: sumo2dirsig[options] --sumo_network= --sumo_netdump= --scene_glist= --output_glist= where: The input SUMO road network file The input SUMO simulation status dump file The input GLIST file that contains the scene terrain The output GLIST file that will contain instances CityEngine/SUMO Scene Construction Manual 43 / 82

Options: --scene_origin= TheX,Y origin of the Scene ENU coordinate --mov_basename= An alternate base for the output mov files --mov_folder= An alternate folder for the output mov files --mov_path= The path to the MOV files used in the output GLIST

4.2.2 Performing the Export

Consider the following example syntax for exporting the vehicle tracks from the SUMO output "dump" file to a set of DIRSIG inputs. Note that the line continuation characters (\) have been introduced for clarity. The argument list can be supplied as a single line. $ sumo2dirsig--sumo_network=salt_lake_city.net.xml\ --sumo_netdump=salt_lake_city.dump\ --scene_origin=422469.1724,4516185.784 \ --scene_glist=roads.glist\ --output_glist=/home/dirsig/salt_lake_city/geometry/cars.glist\ --mov_folder=/home/dirsig/salt_lake_city/geometry/motion\ --mov_path=motion

The first two arguments (the SUMO road network and SUMO output dump file) should not require additional explanation. The --scene_origin supplied here is the same origin that is used throughout the scene construction process. For example, this same offset is used in CityEngine when the scene is exported from the UTM coordinate system inside CE to the Scene ENU coordinate system used in DIRSIG. The --scene_glist file points to a GLIST file that contains the terrain and the roadway geometry created by CityEngine. The --output_glist was given the absolute path the where we want the GLIST file to be placed, which is directly inside the scene folder hierarchy for this example. The --mov_folder option was used here to say that we want the output .mov files to be placed directly inside the scene folder hierarchy as well. The --mov_path option was used so that the GLIST file instances have the correct relative path to the .mov files.

Important The output GLIST file (cars.glist, in this example) only contains instance information at this time. The next step will be to describe what geometry is used with these instances.

This example shows one way of running the tool with regard to where the output GLIST and MOV files are placed. The user can choose to not include some of these options and output the files into the folder where the sumo2dirsig tool is run and relocate the files later.

4.3 Importing Vehicle Tracks

This section outlines the process for importing the vehicle tracks that were exported from SUMO and utilize a a pair of mech- anisms to simplify the assignment of various vehicle geometries and geometry attributions to those tracks. Specifically, this section will describe new mechanisms added to the GLIST file to facilitate rapid scene development based on (1) performing initial material attributions on base geometry objects without using Bulldozer or Blender, (2) introducing random variations in those initial material attributions on base geometry objects and (3) randomly selecting a base object (and material attribution set) for each instance in the scene. These mechanisms were introduced to significantly streamline the process of creating large populations of geometrically similar objects with defined sets of material variations. It should be noted that these mechanisms can be used separately or in combination.

Note These GLIST file features were added to DIRSIG in Release 4.6.

Note The GlistOptions1 demonstration focuses on these advanced GLIST file mechanisms. CityEngine/SUMO Scene Construction Manual 44 / 82

4.3.1 Initial Vehicle Attributes

In the past, the attribution of a geometry object (for example, a "car") in an /Wavefront OBJ file required that the file be loaded into an interactive editor such as Bulldozer (distributed with DIRSIG) or Blender (an open-source geometry authoring tool). Although this workflow has worked for years, it required a man-in-the-loop to perform this key step in preparing geometry for use in DIRSIG. A new attribution mechanism has been added to DIRSIG that allows this process to be accomplished on-the-fly when the object is loaded into the simulation. The mechanism relies on making material assignments based on facet "groups" in an Alias/Wavefront OBJ file. A "group" is an optional mechanism in the OBJ file format to associate a group of facets (polygons). For example, the facets that compose the windshield of a car can be associated under a group named "windshield". Consider the following example from the vw_beetle.glist file: Cars/vw_beetle.obj default windows hubcap chrome CHROME.001 rubber rubber_seal RUBBER RUBBER.001 RUBBER_TRIM tyre LEATHER ...

The various elements associate the given material ID (specified via the id attribute) to a given group name. The first is important because it is applied to the special group name default, which means that any facets not associated with a group or any groups that are not specified later will be assigned this material ID (in this case, material ID #500). Each subsequent element specifies the material ID to be associated with facets in the specified group. Note that in this example, there are multiple groups (with slightly different names) that all get material ID #512 (the DIRSIG material describing a rubber tire).

How do you find the group names in an OBJ file? The groups in an OBJ file are defined by a block of facets preceded by a line starting with the "g" tag. For example, the following line: g wheel starts a group named "wheel" and all the facets following it will be associated with this group until a new group is defined.

Important The key benefit of this new material assignment mechanism is that it does not require graphical interaction with the model in a tool like Bulldozer or Blender. Furthermore, the material to group assignments could be automated at a later time if the OBJ group names are carefully managed by the object geometry author. CityEngine/SUMO Scene Construction Manual 45 / 82

4.3.2 Randomizing Vehicle Attributes

The last section described making initial material assignments to surfaces for a "base geometry" read in from an OBJ file. For a given "base geometry", it is many times desirable to have each instance reflect a different combination of material attributes for that "base geometry". The user must still provide a list of instances (either static or dynamic) but the model will choose which material attributes to apply to the "base geometry" for each instance based on a set of weightings. This mechanism can be used for a variety of applications, including:

• Quickly introduce material variations within a forest of trees of a given species. For example, the weightings for the materials could be setup so that some percentage of all the instances get assigned "sick tree" material properties. • Quickly populate a traffic pattern with material variants of the same "base geometry". For example, each "Honda Civic" could be randomly assigned a different paint color from a pool of allowable colors. The weightings of those materials combination can be manipulated to reflect observed distributions (for example, "white" is perhaps more common than "black").

The ability to randomly reassign material properties to each instance is performed via the element within an element. The element defines which original material ID will be reassigned and the weighted distribution of assignable material IDs. In the example below, the model looks for surfaces attributed with material ID #500 (the default material ID for our car, which is primarily associated with the body of the vehicle). These surfaces will be reassigned either material ID #501, #502, #503,#504 or #505 based on the respective weight for each ID. In this case, these material IDs correspond to different vehicle body paints in the DIRSIG material database: Cars/vw_beetle.obj default ... 500 501 502 503 504 505

Note If the weight attribute is not include, the default weight is 1.

Important The material ID weight values are summed and normalized to produce the relative fractions of material ID in the overall population.

In this case, material ID #501 and #505 have larger weights than the other materials, reflecting that these body colors are more likely to be chosen. The weights add up to 9, which means #501 and #505 will be assigned to 2/9ths (each) of the vehicles and the remaining materials will be assigned to 1/9th (each) of the vehicles. CityEngine/SUMO Scene Construction Manual 46 / 82

Note To reassign another material ID, the user just needs to add another element within the element.

4.3.3 Randomizing Vehicle Geometry

The final mechanism allows the user to specify a pool of "base geometry" objects that will be randomly selected from for each instance in the instance list. The different "base geometry" objects can be weighted to create populations that reflect different proportions. The user must still provide a list of instances (either static or dynamic) but the model will choose which "base geometry" is used with each instance based on the weightings. This mechanism can be used for a variety of applications, including:

• Quickly populate a forest (the user supplies tree locations as static instances) so that the final forest reflects the supplied proportions of each tree species (provided as the set of "base geometry" objects). • Quickly populate a traffic pattern (the user supplies the vehicle tracks as dynamic instances) with many different types of cars. If a car of a certain make or type is more or less common, the base geometry weightings can be manipulated to reflect this.

The different base geometries are defined by creating multiple elements within an element. Consider the following example from the `cars.glist file: cars/vw_beetle.glist cars/generic_pickup.glist cars/generic_suv.glist cars/infiniti_g35.glist ...

The weight attribute is used to manipulate the relative proportion of that base geometry in the overall population.

Note If the weight attribute is not include, the default weight is 1.

Important The base geometry weight values are summed and normalized to produce the relative fractions of each base geom- etry in the overall population.

In this example, we have defined a pool of four different cars that will be randomly selected from as each instance is defined. Note that the various weight values in this case have the Volkswagen Beetle (vw_beetle.glist) appearing less often than the other vehicles in the scene. It is important to realize that since the vw_beetle.glist file (and the other 3 vehicle GLIST files) include randomized material attributions (discussed in the previous section) that each instance will get a random base geometry (which vehicle type) and a random attribution of that base geometry (which paint type on that vehicle). CityEngine/SUMO Scene Construction Manual 47 / 82

Note To add another base geometry to the pool, the user just needs to add another to the section.

4.3.4 Dynamic Instance Import

The export of the SUMO vehicle tracks produces a large set of DIRSIG Delta Movement (.mov) files. These files need to be used to define a set of dynamic instances for cars objects in the scene inputs for DIRSIG. The example below shows part of the cars.glist file, where all of the .mov files extracted from the SUMO output are used to create elements for the a cars in the scene: ... motion/sumo_car_a0.mov motion/sumo_car_a1.mov ... motion/sumo_car_a999.mov

Since the set of .mov files used to drive the dynamic instances is created by the SUMO export step, we know how many dynamic instances can be created. Therefore, the process of generating all these elements can be automated at a later time.

4.3.5 Summary

This section focused on how to import the N vehicle tracks that were exported from a SUMO simulation and quickly asso- ciate different vehicle geometries and material variations of these geometries with each instance. Although these topics were introduced and discussed in the reverse order, it might be helpful to summarize the process here:

• The SUMO vehicle tracks are exported from a single file into individual vehicle .mov files for use in DIRSIG. • A GLIST file is created that describes all the vehicles in the traffic pattern, where each dynamic instance is associated with one of the .mov files exported from SUMO. • As DIRSIG constructs each instance in the scene, it figures out which "base geometry" to use. The user can supply one or more "base geometry" choices in a list, each with a weighting. The model will randomly choose a "base geometry" (using those weightings) to associated with a given instance. • Once a given "base geometry" has been selected, the model checks to see if that object has material variants setup. If so, the materials used for that object, for that instance are randomly chosen from the weighted list of material remappings defined in the object configuration. CityEngine/SUMO Scene Construction Manual 48 / 82

Chapter 5

Terrain importation and construction

Terrain geometry describes the scene-local topographic relief at the ground level. DIRSIG versions through 4.x do not provide default global topography so it is important to make sure that the entire scene is covered by a "watertight" surface — otherwise you will see through the virtual earth to the atmosphere on the other side. For a scene with topographic variation, it is useful to start with a heightfield describing the elevation of the ground surface over a limited area (the heightfield can be from any number of measured sources or synthetically generated). This module describes how to construct a three-dimensional, facetized representation of a heightfield that starts as a 2D image. This is demonstrated using using a triangulation code called Terra though any triangulation routine may be used

Note Terra is used to produce an "OBJ" file as the final geometry representation. This is the Alias/Wavefront geometry format and is close to a universally accepted 3D geometry file format and is supported by DIRSIG. It is an ASCII data file and, at its simplest, contains lists of vertices, information on how to connect those vertices to make facets, and associations between those facets and material information (the format is capable of much more, but this is the subset of its definition that is important to DIRSIG). All geometry produced and visualized in this manual has been generated in the OBJ format.

5.1 Source Data

While any type of grayscale image can be used as an elevation map, the GeoTIFF (a Tagged Image File Format [TIFF] file with embedded geo-referencing information) is particularly useful. For the Terrain construction demonstrated here, we’ll obtain the data from the USGS National Elevation Dataset (NED) available from the viewer and download platform found at the National Map website. The scene that we are building is based on downtown Salt Lake City (SLC) and surrounding areas to the North. Specifically, the coincident NED data covers the region:

West_Bounding_Coordinate -111.91901234455 [deg] East_Bounding_Coordinate -111.838981480353 [deg] North_Bounding_Coordinate 40.7930246913642 [deg] South_Bounding_Coordinate 40.7579938271667 [deg] CityEngine/SUMO Scene Construction Manual 49 / 82

at a 1/9 arc second resolution (approximately 3m spacing between elevation points) and was originally obtained from LiDAR data sources.

Figure 5.1: Bounds of the Salt Lake City region to be constructed from the NED shapefile and visualized in Google Earth.

Figure 5.2: Download request from the National Map viewer.

After downloading the digital elevation map (DEM) you will have a number of files that provide the elevation data and numerous metadata products. For the purposes of importing the data into CityEngine and creating the geometry we’ll need the GeoTIFF CityEngine/SUMO Scene Construction Manual 50 / 82

(ending in ".tif") and the world file (ending in ".tfw"). If the world file is not provided we will be able to create our own later on.

5.2 Importing Terrain Geometry to CityEngine

While we do not encourage using CityEngine directly to generate the facetized geometric surface, it will be useful to bring the Terrain into CityEngine to align the road network in three dimensions. Assuming that we have already imported the road network into CityEngine (see Street Construction), we have already setup the projection we will be using for constructing the scene. In the case of the SLC scene, the projection is UTM Zone 12N:

Figure 5.3: Salt Lake City scene road network in UTM Zone 12N

The elevation data stored in the GeoTIFF can be imported directly into CityEngine as follows: CityEngine/SUMO Scene Construction Manual 51 / 82

Figure 5.4: Terrain map importation in CityEngine (1)

Figure 5.5: Terrain map importation in CityEngine (2)

The NED data is stored natively in geodetic (latitude, longitude, altitude) coordinates. If we try to load the GeoTIFF directly into CityEngine it incorrectly assumes that the Terrain map is geo-referenced in the scene projection (UTM 12N) resulting in a poorly sized and positioned Terrain: CityEngine/SUMO Scene Construction Manual 52 / 82

Figure 5.6: Terrain map imported in image native units.

The predicted "X" and "Z" sizes are derived from the number of pixels along each axis (the image is 2593 x 1135) multiplied by the presumed width of each pixel in native units (0.0000308642 x 0.0000308642 degrees). The offset reflects an image origin at the upper left.

Note It is not clear why CityEngine would not support loading geo-referenced maps from one projection/coordinate system into another. It seems likely that support for this may be added in the future, but it is not present as of version 2012.1.

To be able to use the heightmap in our existing scene and projection, we need to first convert the geodetic geo-referencing information to UTM 12N. We could do this by editing the GeoTIFF file itself (modifying the embedded geo-referencing tags). Or, more simply, we can add or modify an Esri world file (a file ending in ".tfw" and with the same prefix as the GeoTIFF), which overrides any geo-referencing information in the map itself. The world file is an ASCII file with 6 entries (lines):

• Line 1: pixel size in the x-direction in map units/pixel • Line 2: rotation about y-axis (z-axis in CityEngine)

• Line 3: rotation about x-axis • Line 4: pixel size in the y-direction in map units, almost always negative (z-direction in CityEngine) • Line 5: x-coordinate of the center of the upper left pixel • Line 6: y-coordinate of the center of the upper left pixel (z-coordinate in CityEngine)

After creating/converting the lines in the world file, the import into CityEngine will be successful. CityEngine/SUMO Scene Construction Manual 53 / 82

Figure 5.7: Terrain map importation in CityEngine after TFW conversion (3). The TFW file (in UTM 12N Easting and Northing) is shown at the bottom.

Note Due to potentially non-uniform projections, pixel sizes should be representative of the center of the map or the region of the scene that is most important to the simulation.

Once the Terrain is loaded into CityEngine, it can be used to align the street network in three dimensions by simply selecting the graph layer and using the "Align Graph to Terrain. . . " wizard . The image below shows the result of this process: CityEngine/SUMO Scene Construction Manual 54 / 82

Figure 5.8: Terrain map imported into CityEngine with an aligned street map.

5.3 Using Terra to Facetize the Terrain

The Terra code (and its predecessor, Scape) are the creations of Michael Garland (http://mgarland.org/software/scape.html). The algorithms are well documented in the form of published papers (available on the site) and the code has been released for public use as source code. While Terra has a cleaner code base than Scape and some nicer features, the project was unfinished and some of the advertised features are not working in the most recent (and mostly likely final) version (0.7). It is more than sufficient for our needs, however, and is a very powerful tool. Terra produces an optimized mesh from a heightfield.

5.3.1 Building Terra

No known source of pre-built Terra (or Scape) binaries exists so it is incumbent on the user to compile the tool from the source code downloaded from the website above. The code is fairly straightforward and a Makefile is provided (note that this should be edited to reflect locations of compilers and libraries as well as compiler options on the user’s system). After updating the Makefile, the tool can be built by simply running "make terra" on the command line of a *nix system (the GUI based Terra tool, xterra, which is also included in the Makefile requires a very outdated version of the glut libraries and is not recommended to be built). Since the code base is quite old, it may be necessary to update the names of some system include files in individual files (about a half dozen) as necessary.

5.3.2 Preparing the Heightmap for Terra

Terra takes a PGM (Portable Gray Map) image as input for the heightfield. The PGM format is a simple, open format for grayscale images and can consist of either binary ("raw") or ascii ("plain") data for the pixels. In contrast to the floating point elevation data contained in the GeoTIFF file, PGM pixels are stored as integral values. Therefore we must quantize the range of the elevation data to a fixed range of values. CityEngine/SUMO Scene Construction Manual 55 / 82

Important Terra’s limited support for binary ("raw") PGM images is very sensitive to format, therefore it is recommended that the ASCII ("plain") format is used (the temporary image file representing the height field will be significantly larger, but the effect on runtime is insignificant).

For our purposes it is useful to use a 16-bit PGM (pixel values ranging from 0 to 65535). Our SLC terrain, which has a total elevation displacement of about 617 meters would therefore be quantized to 0.0094 meter steps (which is more than sufficient). In contrast, using an 8-bit PGM would only give us 2.42 meter fidelity — not enough for a partly urban and complex terrain. Note that we will have to post process the terrain to return to useful elevations at vertices, offsetting by scaling by the total range and offsetting by the minimum height. The PGM will also throw away any geo-referencing information and we will only know the pixel indices in the output geometry — these will need to be re-scaled and offset to move the scene into the appropriate coordinate system as well (though in this case we will partly use DIRSIG’s local coordinate system — see the final section). There are a number of ways to convert the SLC GeoTIFF heightmap to a 16-bit PGM image. For simplicity we suggest using the SimpleDemViewer (freely available for the Mac platform at http://www.jizoh.jp/english.html) to generate a correctly scaled TIFF file followed by a conversion (using tifftopnm, part of the Netpbm tools, http://netpbm.sourceforge.net/) to a 16-bit PGM, though the GDAL library and toolset (http://www.gdal.org/) can be used effectively as well. Assuming the use of SimpleDemViewer, we load the GeoTIFF heightmap into the viewer, select the "Create Grayscale Map. . . " option from the "Tools" menu and fill out the options as follows:

Figure 5.9: Grayscale image generation in SimpleDemViewer.

Note that we are maintaining the full size of the original heightmap (2593x1135) and expanding the full range of the elevation data from minimum to maximum in the 16-bits available. Once generated, the graymap can be saved out (as a regular, 16-bit CityEngine/SUMO Scene Construction Manual 56 / 82

TIFF file). Once we have our graymap TIFF, the last step to prepare for use with Terra is to convert the file using tifftopnm: > tifftopnm-plain-byrow slc_terrain.tif> slc_terrain.pgm where the "-plain" option indicates that we want the ASCII format (see warning earlier about using binary images with Terra) while "-byrow" helps maintain the 16-bit output. Our input image to Terra now looks like:

Figure 5.10: PGM heightmap prepared for Terra. where the brightest pixels have a value of 65535 and the darkest a value of 0.

5.3.3 Generating the Optimized OBJ with Terra

Once our input PGM is prepared, using Terra is a matter of choosing the required characteristics of the OBJ file (either an error threshold or a maximum number of vertices). If we want to get as good a representation as possible for a given allowable geometry size, we might set the number of vertices for a high and low quality mesh (relative to the fixed CityEngine optimization), running the code as: > terra-p 50000 -o slc_terrain_lowq.obj obj slc_terrain.pgm > terra-p 400000 -o slc_terrain_highq.obj obj slc_terrain.pgm

The output meshes from each run is shown below: CityEngine/SUMO Scene Construction Manual 57 / 82

Figure 5.11: Low quality (50k vertices) optimized SLC Terrain mesh from Terra and visualized in MeshLab.

Figure 5.12: High quality (400k vertices) optimized SLC Terrain mesh from Terra and visualized in MeshLab.

Note The height scaling option mentioned in the terra usage documentation is non-functional and will be ignored. This is fine as we will need to tranform all of the data during the post-processing step. CityEngine/SUMO Scene Construction Manual 58 / 82

At this point we have a valid geometry file for the terrain, but we still need to attribute it with the materials we’ll want to use in DIRSIG. Since this process is the same for all geometry generated for the scene, we’ll discuss it later on in the manual. CityEngine/SUMO Scene Construction Manual 59 / 82

Chapter 6

Constructing street geometry

The process of constructing geometry in CityEngine is to start with one of the various shape types (e.g. Street, Crossing, Sidewalk, Lot, etc..) and to use the outline of the shape to drive 3D models (geometry). A rule describes the operations that should occur on a single shape. This is an iterative process so that the rule acting on an initial shape might subdivide it into smaller shapes which each get passed to different rules (which may then further subdivide the shape, and so on). In contrast to lot geometry, which requires building volumes out of the two dimensional shapes, street geometry stays mostly two-dimensional (though there is usually a relative small vertical offset at curbs. The main objective here is to subdivide a roughly rectangular shape representing a section of street into lanes, shoulder, curb, and so forth in the cross-direction and into street segments, stop lines, arrows and crosswalks in the along-direction.

6.1 Workflow

• Initialize the scene • Import and align graph to terrain • Prepare the rule files

• Transfer graph attributes to shapes • Assign rule files to shapes and set rule file • Generate models

6.2 Initialize the scene

During scene initialization (see that section of the manual) the graph network (nodes and segments) were attributed to include all of the information necessary to build geometry from the shapes. In particular, we’ll use the roadClass attribute to map each street to the appropriate street metrics.

Note Because we can’t directly access the Python based road classes defined in the user configuration file, we have to map the necessary information to the shapes as USER attributes

We also setup a number of subdirectories that we’ll used to store information for model building. Specifically, CityEngine/SUMO Scene Construction Manual 60 / 82

subdirectory usage assets storage for geometry components including texture maps used to map material properties onto the created geomtry (street assets are placed in assets/streets for convenience) rules location of the CGA rules used for constructing street and sidewalks models eventual output directory for exported geometry (in the OBJ file format)

6.3 Import and align graph to terrain

Since the end goal of this process is to have a facetized representation of street geometry located in the scene we want to make sure that the streets are constructed on the terrain that will also be used in the final DIRSIG scene. The terrain should have already been imported into CityEngine (and converted into an OBJ file for DIRSIG). This process was already covered in the terrain construction module of this manual. The final step of importation was to align the street graph with the terrain which essentially replaces the vertical coordinate of the node positions with the elevation (from the terrain map) at that particular point. It is not necessary to have the graph network follow the terrain exactly. In practice with any moderately undulating terrain the road network will appear to pass through the ground in CityEngine:

These artifacts are due to the fact that nodes are connected by straight segments and will not follow the relief of the terrain. One way around this would be to add a node every time a road segment encounters the edge of a node facet. However, that kind of brute force fix drastically increases the size of the street geometry, does not handle the cross-track extent of the roads, and does not account for the fact that the terrain in CityEngine might not exactly match the terrain geometry used for the final DIRSIG scene. Instead we will handle the final alignment of the street geometry and the terrain in DIRSIG. This is done by treating the streets as if it was a property map (called a decal map in DIRSIG) where instead of draping an image over the scene geometry, we drape geometry. It is still important to get pretty close to the correct position which is why the graph should still be aligned in CityEngine.

Important The street network geometry that is created here should not be used like other geometry in DIRSIG. Instead it is provided as a parameter to a "decal" map with drapes it onto the terrain. CityEngine/SUMO Scene Construction Manual 61 / 82

6.4 Prepare the rule files

Every shape in the scene will be connected to a start rule that determines how that two-dimensional polygon is converted into geometry with associated material information. Each rule consists of a number of operations that should be taken on the current shape, usually a modification of that shape to create new shapes such as a split subdivision, or the assigning of mapped material properties to the existing This module of the manual is concerned with the street shapes, or the Street, Crossing, Junction, Junction Entry, and Sidewalk starting rules (starting rule names can be any existing rule within the assigned CGA file, but these are the auto-generated types). We won’t bother describing the crossing and junction rules and instead assume that the initial, unchanged shape can be mapped to an asphalt material property. The remaining two rules for the streets and sidewalks require subdividing the initial shape into distinct areas with their own properties. It is convenient to use separate files for the two start rules and it is assumed here that one CGA file handles the streets (i.e. a start rule of "Street") and another handles the curb to the sidewalk (i.e. a start rule of "Sidewalk"). There is no reason why all the start rules can’t be in the same file, but separating them out can help make complex rule trees more manageable.

6.4.1 Rule tree

All rules are either direct mappings (i.e. rule A maps to rule B) or branched mappings where mappings to the next rule/operation can take more than path. The choice of path is usually driven either by a property of the shape itself (one of the shape atttributes) or by and random draw (e.g. there might be a 5% chance that an surburban lot might become a park, and a 95% chance that it is residential). Since all possibilities must be described in the rule file, we can think about all the possibilities arising out of a single start rule as being a decision tree, such as the one visualized below.

The rules themselves follow a simple syntax where a direct mapping would look like: RuleA --> RuleB and a branched mapping is described as: RuleGenericRoad --> case regionClass == "rural": RuleDirtRoad else: RulePavedRoad CityEngine/SUMO Scene Construction Manual 62 / 82

Important Like Python, the CGA language enforces strict indentation rules,

6.4.2 Sub-division and UV-mapping

If all we had to work with was the original shape at the start rule then there wouldn’t be much modeling that could be done. Instead we have the ability to take any shape and split it into smaller sub-shapes, each of which can be passed on to different rules. For example: StreetWithSides( roadType, useGutter, useShoulder ) --> alignScopeToAxes(y) split(v,unitSpace,0){ useGutter * hasLeftShoulder * ( gutter_width): Gutter | useShoulder * hasLeftShoulder * ( shoulder_width): Shoulder | ~1 : StreetCenter( roadType) | useShoulder * hasRightShoulder * ( shoulder_width): Shoulder | useGutter * hasRightShoulder * ( gutter_width): Gutter }

The first operation in the mapping just aligns the local and global coordinate spaces so that we can use the same rule for all shapes, regardless of their scene orientation. After that, we take the shape and split it along one dimension (the "cross" dimension of the street). Since shapes are two-dimensional entities, we use a seperate "UV" coordinate system (i.e. two new axes, u and v to describe that space). The original road shape is then separated into up to 5 new shapes, with a maximum of 2 gutters, 2 shoulders, and the lanes portion of the street itself. The original road shape had a width (which was set during the initialization phase) and the gutters and shoulders have fixed widths as well (which may be zero) that were set by shape-associated attributes. Whatever remains after dividing out the gutters and shoulder is given to the street center, which will be turned into lanes (the indication to use the remainder is given by the "~"; the number refers to a relative weighting if there was more than one subdivision that used the remainder). The flags for the gutter and shoulder allow reuse of the same rule even if those rules shouldn’t be called. The UV space that we work with on a shape (and later on the surfaces of 3D objects) can be visualized like this:

where the lower left corresponds to [0,0] and the upper right as [1,1]. For simple rectangular objects like streets,

it is easy to see how the UV space is defined by simply stretching to match the size of the rectangle shape: CityEngine/SUMO Scene Construction Manual 63 / 82

Furthermore it is easy to change the orientation of the the UV space by scaling it. For instance, if we have one side of the road being mapped in UV space going in one direction, the other side of a road is reversed (i.e. uv-mapped in the opposite direction) by applying a scale to the uv-space: scaleUV(0,-1,-1)

This will flip the directionality of the subdivided street segment appropriately so that the same rules can be used as the other side of the street (the same UV-mapped textures will be pointing in the flipped direction).

Important CityEngine has 6 different UV spaces (maps) available for each surface. The first argument in scaleUV indicates which map should be used (in this case, 0, corresponding to the color map). Since we’ll be converting the CE maps to DIRSIG appropriate ones, it is only necessary to work with the first space

After initialization, twoway streets will have one shape for the street itself (space for the painted area, shoulder, and gutter) and two shapes for "sidewalk" areas on either side (curb, verge, and sidewalk). The widths of sidewalks may be zero. Oneway streets have the street shape and a single sidewalk shape to the right of the road. Crossings and junctions consist of a single shape (the intersection) and can be simply treated. The shapes at a typical intersection of a few roads typically looks like:

Modeling the streets is just a matter of passing the road shapes through the rule we created for it. First subdividing along-track to separate out a shape for a crosswalk (if present) plus some padding and then subdividing the cross-track axis for the lanes, shoulder and gutter: CityEngine/SUMO Scene Construction Manual 64 / 82

where the subdivided shapes also have mapped assets applied to them that describe the material variation across the surfaces.

6.4.3 Assets

Texture maps are 2D images describing the spatial distribution of material properties in UV-space, such as painted lines and asphalt. These of maps are considered to be assets that are added to the geometry models in CityEngine (and eventually exported along with the facetized geometry). In the section above we chose a particular subdivision of streets that gives us distinct areas to apply the texture map assets. However, even for something as simple as streets, there are many ways in which we might map out material information onto the constructed geometry. The street texture assets being used here are:

where the general idea is to map textures across the full witdth of the (laned) road, choosing the texture based on the number of lanes in one direction (e.g. the three arrow texture is chosen for the end of a road when the number of lanes is uqual to three). Alternatively we could have further divided each multi-lane road shape into single lane shapes and mapped out textures that only have one lane. Even more control could have been added to the procedural rules by then subdividing each lane shape into painted and unpainted components, basically turning the texture maps into small decals applied for things like stripes and arrows. However, unless there was a desire to add in variation at that level (e.g. controlling the width/shape/presence of street markings or perhaps adding in randomly placed potholes/manhole covers), increasing the level of detail by subdividing shapes will make the final geometry much larger (each new subdivision means many more facets in the geometry), which is not a desired effect. CityEngine/SUMO Scene Construction Manual 65 / 82

Important The concept of texture maps in DIRSIG is a bit different than the one in CityEngine. Instead of just mapping an RGB image directly onto geometry, DIRSIG uses two grayscale maps. The first, a material map separates out the surface into different material classes (e.g. grass and dirt) while a second texture map describes the spatial variation within those classes (e.g. use measured reflectance curve 7/100 for this area of the grass). Constructing material and texture maps for dirsig will be discussed in more depth in the exportation module of the manual.

6.4.4 Sidewalk rules

The sidewalk models are generated from the "sidewalk" shapes in exactly the same way as we created the street models. This time we sub-divide the original shape in the cross-track direction into a curb, a verge (the non-sidewalk area between the curb and the sidewalk, usually grass in residential areas), and the sidewalk itself. There is one slight difference however, where we actually want to model the fact that the curb is (usually) higher than the road itself. Adding a simple height difference like this can be done simply in CityEngine by extruding a shape in one dimension much like metal is extruded through a die (the die here is the shape itself and the metal is the volume formed after extrusion). For the curb, we want to take the original shape and extrude it into a three-dimensional box with a height equal to a curb height we’ve already defined. In fact, we can extrude each of the sidewalk components slightly different amounts if desired to generate a slight lip on the inside of the curb, for instance. The syntax for extrusion looks like: Curb --> extrude( curbheight) Concrete which simply takes the original curb shape, extrudes it to the appropriate height and that passes it onto another rule to finish the model (in this case, assigning concrete material properties to it).

6.4.5 Variables and functions

While the CGA language is not a traditional programming language, there is the ability to define both variable and functions to facilitate writing rules. Both are essentially what would be called "macros" in another language like C++, in that they essentially replace the calling text with new text. The only difference between a variable and a function is that the function can take (auto- typed) arguments. The scope of variables and functions are global (within the rule file) and can be defined before or after they are used. The syntax for general variables and functions is: concrete_tex ="assets/streets/textures/asphalt.jpg" getStreetTexture(type,lanes) = case lanes >= 4 : "assets/streets/textures/street_4lanes_" + type + ".jpg" case lanes <= 1 : "assets/streets/textures/street_1lanes_" + type + ".jpg" else:"assets/streets/textures/street_" + lanes+"lanes_" + type + ". ←- jpg"

In addition to convenience variables (such as the filename above), there are also attribute variables that are automatically hooked to the CityEngine attribution engine. These variables will be listed in the attribution panel of the shape with a "Rule" tag applied if they have not been hand-edited by the user (or modified via a script). There are also internal attributes (with an "Object" tag) that can be accessed from within the rule file by adding an attribute variable of the same name, including connectionEnd, connectionStart, and shapeType which give information about the shape and its connectors. Attribute variables are declared like normal variables, but with an attr tag, attr curb_width=0

The assigned value is the default and will be used if no other value is assigned In the case of internal, object attributes the default value is ignored and automatically connected to the internal attribute. CityEngine/SUMO Scene Construction Manual 66 / 82

Important Even though many of the attributes we defined for the graph are technically "Object" attributes, they will not be auto- matically connected to rule attributes of the same name. This is only done for a limited set of internal attributes. Instead we have to connect useful attributes ourselves (see next section).

6.5 Transfer graph attributes to shapes and set rule file

Many of the parameters that we want to use to drive street construction are set in the user-defined configuration Python script and therefore not directly accessible to us in the rule file. To get around this we’ll use the attributed variable mechanism to gain access to these variables in the rule file and then run a script that sets the values of each attribute (setting the source to "User"). This is equivalent to going through the attribution interface for each shape and manually setting each attribute. The script to do this is simple and looks like: edges= ce.getObjectsFrom( selection, ce.isGraphSegment) for edge in edges:

shapes= ce.getObjectsFrom( edge, ce.isShape) for shape in shapes:

# handle different types of shapes stype= ce.getAttribute( shape,"shapeType")

if( stype == "Street"):

# have this shape use the street rule ce.setRuleFile( shape, cfg.street_rules)

roadType= ce.getAttribute( edge,"highway") roadClass= ce.getAttribute( edge,"road_class")

ce.setAttributeSource( shape,"lanes", "OBJECT") ce.setAttributeSource( shape,"oneway", "OBJECT") ce.setAttributeSource( shape,"has_lines", "OBJECT")

ce.setAttribute( shape, "/ce/rule/lane_width", cfg.road_classes[ roadClass].lane_width) ce.setAttributeSource( shape, "/ce/rule/lane_width", "USER")

...

ce.setAttribute( shape, "/ce/rule/curb_width", cfg.road_classes[ roadClass].curb_width) ce.setAttributeSource( shape, "/ce/rule/curb_width", "USER") nodes= ce.getObjectsFrom( selection, ce.isGraphNode) for node in nodes:

shapes= ce.getObjectsFrom( node, ce.isShape) for shape in shapes:

# handle different types of shapes stype= ce.getAttribute( shape,"shapeType")

if( stype == "Crossing"):

# have this shape use the street rule CityEngine/SUMO Scene Construction Manual 67 / 82

ce.setRuleFile( shape, cfg.street_rules) it should be run with the user interface disabled (i.e. wrapped with "@noUIupdate") so that the scene isn’t constantly updated after each change. We also set the rule file at this time (a separate ".cga" file for streets and sidewalks defined by the user in the configuration file) After this step the attribution interface for a street shape will look something like:

6.6 Generate models

Once everything is setup, generating the actual models is simply a matter of selecting a portion (or all) of the scene and running "Generate Models" from CityEngine. This will create all of the models that we need for exporting out to DIRSIG compatible geometry (this process is covered in a different module). CityEngine/SUMO Scene Construction Manual 68 / 82

Chapter 7

Lot Geometry

The lot geometry module is still under construction. CityEngine/SUMO Scene Construction Manual 69 / 82

Chapter 8

Exporting CityEngine geometry

Once we’ve created models in CityEngine, we still need to get them out of CityEngine and into a form that can be used in DIRSIG. Luckily, the tools for doing this are mostly built into CityEngine and we just need to run an export operation on the models followed by a small amount of file wrapping and map manipulation.

8.1 Workflow

• Export CityEngine models as OBJ files

• Transforming the OBJ files • Map OBJ materials to DIRSIG materials • Replace texture maps with DIRSIG material and texture maps

• Write reports for clutter objects

8.2 Export CityEngine models as OBJ files

The first thing we must do is to select the models through the CityEngine interace that we want to export. These will be the street and lot models that we selected earlier. It is recommended that the building models are exported on a per block basis (to optimize the geometry as much as possible and to keep things as organized as possible) though this is not necessary.

Note There are export tools available in the Python scripting interface that can facilitate breaking up the scene into parts.

Since the street network is not as easily partitioned, it is suggested that the entire network is exported at the same time. Regardless of the size and type of models selected the process is the same. For simplicity, CityEngine has a "Export Models. . . " command available from the "File" menu which should be selected. This gives a choice of a wide range of geometry formats to export to, but the one we want is Wavefront OBJ which will write the geometry in the ASCII based Alias Wavefront OBJ format. This format is DIRSIG’s interface to third party geometry and supports all of the features that we need. CityEngine/SUMO Scene Construction Manual 70 / 82

After selecting the type of file to export to, we are presented with a number of options:

Of these many choices there are a few that are important to us:

option description set to Exported what we are actually exporting Export generatable models Content (models) Terrain Layers option to also write out terrain Do not export any terrain layers (which we don’t need) CityEngine/SUMO Scene Construction Manual 71 / 82

option description set to Include should material information be checked (yes) Materials provided in the OBJ file (we will modify this) Normals Type include smoothing information for Use vertex normals (smooth surfaces (helps with modeling shading) curvature) Global Offset values that are added to model x and z-offset set to the center of the coordinates (need this to place the DIRSIG scene (in the CityEngine scene in the local coordinate system scene coordinate system, usually the same as the terrain offset) Triangulate force facets to have three sides (this checked (yes) Meshes is the format DIRSIG expects)

Once finished, the exported geometry files will be in the models subdirectory (unless the output directory was changed).

8.3 Tranforming the OBJ files

Both CityEngine and DIRSIG use a right-hand-rule coordinate system, however, CityEngine used the y-axis as the up/vertical axis and DIRSIG uses the z-axis as the up axis. This means that the OBJ files coming out of the CityEngine export need to be modified in order to match DIRSIG’s coordinate system as shown below:

currently looking for the best tool for this (aside from just providing another one in dirsig) that doesn’t remove necessary information from the OBJ file

8.4 Map OBJ materials to DIRSIG materials

The OBJ format associates materials with facets by a simple, string-based ID system. At the start of each group of geometric facets that will have the same material, you will see something like the following: g Pavement s off usemtl Pavement f 2/1/1 1/2/1 49/3/1 f 50/4/2 51/5/2 52/6/2 f 1/7/3 2/8/3 51/9/3 f 1/7/3 51/9/3 50/10/3 CityEngine/SUMO Scene Construction Manual 72 / 82

Each line starting with an f is a facet definition (the numbers separated by ’/’s refer to vertexes, vertex texture, and vertex normal indexes, respectively). There are three vertexes for each facet since they should all be triangles after choosing that option in the export. The line with a g indicates that all the facets in this section are part of the same group and the usemtl entry indicates that all of the same facets should have the material with an ID of "Pavement". The name of both the group and the material are set to the last rule that was called in the CGA file before that portion of the model was finished. If there are multiple variants within the same rule then the ID will have an index appended to it (e.g. "Asphalt_3").

Note The s entry in the example is suppposed to indicate whether smooth shading (interpolated vertex normals) should be used for the set of facets that follow. However, as is the case for the CityEngine output, this OBJ feature is rarely used as intended (e.g. CityEngine seems to always turn it off, even when smooth shading is selected in the export options). For this reason DIRSIG ignores the value and will just include smooth shading if vertex normals are provided for those facets and flat shading if they are not.

While the group can be useful for organizing large, multi-component OBJ files, we are only interested in the material ID here (groups and materials happen to always correspond to the same facet set in CityEngine geometry, but this is not required). This material ID can be used to look up the exact material in use from an accompanying OBJ material file (the file ending with ".mtl" which was exported along with the ".obj" file). For example, the "Pavement" entry in the material file looks like: newmtl Pavement Kd111 Ka000 d1 Tf 1.0 1.0 1.0 Ni 1.0 illum3 Ks000 Ns0 map_Kd/Users/aagpci/CityEngine/SaltLake/assets/streets/textures/pavemnt.jpg

The only value of interest to us here is map_Kd (the other values describe how the material should be rendered in an RGB system and are not of use to us). The map_Kd value on the other hand tells us which image was mapped to the UV space of these facets (i.e. the image containing spatial information about painted lines, texture, etc. . . ). We won’t use the ".mtl" file directly, but it does tell us which material in DIRSIG we should use (in this case an asphalt material with spatial variance resembling the given texture map). DIRSIG’s own material ID mechanism piggybacks on the OBJ material ID system, with the restriction that all DIRSIG IDs must be numeric (DIRSIG uses a simple lookup between the numeric ID from the OBJ file and numeric IDs in a material list that covers the whole scene). If the corresponding material ID for pavement is 322, then we could replace all instances of "usemtl Pavement" with "usemtl 322" or "usemtl 322_Pavement" (DIRSIG will ignore the underscore and anything that follows it). However, this can be a tedious process especially if it has to be done more than once. Instead we can also provide the mappings in the DIRSIG geometry list (which provides the OBj filename and information about where to place it in the scene) using an "" element in the XML file:

abi_streets_d2_2.obj default Asphalt_1 Asphalt_5 Asphalt_7 Asphalt_8 Asphalt_6 Asphalt_9 Asphalt_3 Asphalt_4 CityEngine/SUMO Scene Construction Manual 73 / 82

Asphalt_2 Pavement Lawn CrosswlTexQuad

Here the "id" in the attribute is the DIRSIG material ID to be mapped to and the text in the tag is the string ID from the OBJ file (the first is simply swapped in for the second as the file is read in).

Important The street network geometry will not be used like normal geometry (it is mapped to the surface of the terrain via a "decal" map), but it can still be wrapped inside of a geometry list (glist) to allow for mapping IDs.

8.5 Replace texture maps with DIRSIG material and texture maps

Since DIRSIG is not an RGB renderer (its focus is producing spectral radiance) and uses data driven optical properties, it does not support the type of traditional texture maps that CityEngine can export (the map_Kd image above). Instead DIRSIG uses a two-step process for assigning texture. The first applies a map containing general material class spatial variations (e.g. white paint, asphalt) and a second actually adds the textural information within a class (by selecting data based on complimentary statistical descriptions of the map image and the data available). To use this process for the CE generated geometry, we simply need to replace the single texture map in the ".mtl" file with two types of maps, a material map and a texture map for each material in that map. These maps are provided to DIRSIG in its ".scene" file (maps are also associated with a surface by the numeric material ID discussed earlier). For something like a painted road we can use the texture map from CityEngine to produce the material map by thresholding the RGB texture map in grayscale to generate an image with two material classes (white paint and asphalt). Then we can crop a section of the asphalt to use for the texture map or use another image to fulfill that role (for simplicity we can assume no spatial variation in the painted lines themselves): CityEngine/SUMO Scene Construction Manual 74 / 82

Note For visualization purposes it is useful to use a material or texture map image that will be used in DIRSIG as the texture map in CityEngine, but this is not required.

Note Materials in the material map do not have to be then mapped to a texture — they can simply be spatially uniform (in which case the ID just corresponds to an entry in the material list).

Note If the map iamges are not larger than the surface they are being mapped onto they may be repeated in some way (see DIRSIG options for this). To minimize the amount of visible artifacting that this may cause at the seams, it is suggested that maps are made as seamless as possible (many image editing programs have tools for this, including GIMP).

8.6 Write reports for clutter objects

Aside from lot and street geometry, there are geometric elements in the scene that we want to generate based on CityEngine rules, but not necessarily construct (or even visualize) in CityEngine itself. These can be objects like street lights, fire hydrants, trees/bushes, signs, parked cars, and general clutter that makes a scene more realistic. CityEngine has the ability to bring in pre-constructed objects (i.e. OBJ-type geometry files) and include them in the scene. However, this really doesn’t help us and we simply need to get enough information out of CityEngine to place the objects ourselves in DIRSIG (i.e. position and orientation). The mechanism for doing this is using the report operator that is provided in the CGA language. For example, we could use the following in a lot rule: LotPerimeter --> comp(f){ bottom= comp(e){ all: comp(v) { 0 : report("vx", convert(x, object, world, pos, pivot.px, pivot.py, ←- pivot.pz)-ox) report("vz", convert(z, object, world, pos, pivot.px, pivot.py, ←- pivot.pz)-oz) }} } where the comp operations splits the object (the perimeter of a lot) into component faces, then edges, then vertexes. Then we use the report operator to create or add to a "report" entry for the x and z components of each vertex (the ox and oz offset to local space). Report statistics can be viewed in the GUI by selecting scene element, but they can also be written out by passing them to a script during a special "script" export (one of the "Misc Options" in the dialog shown earlier. The reported values can then be accessed from within the Python script and output in any desired format (such as instancing information for DIRSIG). For instance, the following grabs a distance report from the reports if it exists (finishModel is a special function that is called for every exported model): def finishModel(exportContextUUID, shapeUUID, modelUUID): ctx= ScriptExportModelSettings(exportContextUUID) shape= Shape(shapeUUID) model= Model(modelUUID)

reports= model.getReports()

dist=0 if’distance’ in reports.keys(): dist= reports[’distance’][0] CityEngine/SUMO Scene Construction Manual 75 / 82

Appendix A

Generating vehicle track truth

An important aspect of simulation image data with moving objects for testing tracking algorithms is providing users with accurate truth with which to validate those algorithms. The inputs to the simulation include the location of each moving object in the scene coordinate space (which can be easily converted to a geolocation). However, the request was to have these object locations in image coordinates. This document attempts to explain the process for generating this data for a DIRSIG simulation. Specifically, it focuses on a workflow to produce an ASCII "track" file for each moving instance within the frames computed by the simulation. Each "track" file has the location of that object in each frame that it appears. To generate a comprehensive set of truth for moving instances, the user must utilize three specific components:

• An "instance report" must be generated during the simulation

– This report describes all the instances of objects within the scene, and includes information about what their unique run-time ID or "index" is as well as any variant material assignments made to that instance.

• The "instance index" truth must be generated during the simulation

– This truth is a single "band" in the raster truth data cube that marks pixels with which dynamic (moving) instance is contained within it.

• The "track extraction" tool must be run to generate per-instance tracks

– This tool converts the dynamic instance information in the raster truth image data to a "track" file that describes which pixel the centroid of the object appeared in for each frame.

A.1 Instance Report Generation

The "instance report" is an important document that helps the end user correlate moving object tracks with the origin object (both the geometry and the material assignments) associated with that track.

A.1.1 Requesting the Report

The request for the instance report can be added by hand-editing the section of the .options file. The name of the option is simulation.instancereport and it is assigned a string that is the name of the file the instance report will be placed in: simulation.instancereport string instance_report.txt CityEngine/SUMO Scene Construction Manual 76 / 82

A.1.2 Report File Format

The "instance report" file is a simple, multi-column file (an example is shown below). Each line in the file describes a single instance of a piece of geometry in the scene. An "instance" is a virtual copy of a geometry model. In many scenes, the same tree, building, car, etc. is used repeatedly by making a virtual copy of the geometry at a series of locations. An instance can be either "static" (fixed location and orientation vs. time) or "dynamic" (changing location and/or orientation vs. time). Instances can also be modified at load time to use an alternate material attribution scheme compared to the original geometry. For example, a car geometry might be setup to be "red" for some instances and "blue" others. The "instance report" file includes this information about each instance. It also includes the "instance index" for each instance.

Note The "instance index" is simply a unique index associated with each instanced object within a scene. This index is the primary mechanism used to track a given instance in the output raster truth frames.

The excerpt below shows the output of an "instance report" file. The first column will indicate if the instance is "static" or "dynamic". The second column is the "instance index". The third column is the "name" associated with the object in the input object database file (these names are optional in that input file, so some instanced may not have a name). If the object is "dynamic" then, the third column is the path to the file describing that dynamic motion. Finally, if the instance used any variant attributions, they will be listed as "original" vs. "modified" pairs: static id: 0000000000000000000 terrain static id: 0000000000000000001 buildings static id: 0000000000000000002 tree static id: 0000000000000000003 tree ... dynamic id: 0000000000000017397 ../../scenes/motion/sumo_car_0.mov var: 500:503 dynamic id: 0000000000000017398 ../../scenes/motion/sumo_car_1.mov var: 500:501 dynamic id: 0000000000000017399 ../../scenes/motion/sumo_car_2.mov var: 500:501 ... dynamic id: 0000000000000020585 ../../scenes/motion/sumo_car_3188.mov var: 500:504 dynamic id: 0000000000000020586 ../../scenes/motion/sumo_car_3189.mov var: 500:505 dynamic id: 0000000000000020587 ../../scenes/motion/sumo_car_3190.mov var: 500:504 static id: 0000000000000020588 unnamed static id: 0000000000000020589 original infiniti static id: 0000000000000020590 original suv static id: 0000000000000020591 original pickup static id: 0000000000000020592 roads

A.2 Raster Format Truth Collectors

The DIRSIG model has a truth collection system that is focused on providing raster format truth on a per pixel basis. Users can request truth categories such as "materials", which results in a handful of raster bands, which each band corresponds to a different metric such as "most popular material ID", "fraction of most popular", etc. Each pixel in those bands stores a value for that metric. In the preceding example, a given pixel might contain 73% asphalt, 16% grass and 11% gravel. The corresponding pixel for the "most popular material ID" band would contain the material ID for asphalt and the "fraction of most popular" band would contain the value 0.73. In order to produce the ASCII "track" file described earlier, we needed to develop a mechanism to utilize the existing raster format truth collection mechanism as part of an overall solution. The first component of our solution is provided by a new "moving instance index" truth collector, which creates a single band in the truth collection raster image cube. This band contains the unique instance index for any moving objects that are attributed with one of the user-supplied materials.

A.2.1 Adding the "InstanceIndex" Collector

The truth collectors are normally configured through the GUI interface, but the new "InstanceIndex" collector is experimental and hasn’t been added to the interface yet. Therefore, the .platform file needs to be hand-edited to enable this experimental CityEngine/SUMO Scene Construction Manual 77 / 82

feature. The truth collectors are described within the .platform file, and each focal plane can have it’s own set of truth col- lections, with each collection having one or more collectors. The .platform file is an XML file that is fairly self-documenting with regards to the format. Below is an example of a section for a given focal plane: true truth img capture InstanceIndex 500

Obviously, it is important for the collection to be enabled, otherwise no truth data will be generated. The section outlines the naming scheme that is used for the output truth image files. In this example, the base of the filename will be truth, the file extension will be img and files will be generated on a "file per capture" schedule. This "file per capture" schedule is important because the tool that processes these raster truth image files assumes this schedule. In general, the "file per capture" schedule means that a separate file is created for each frame (capture) in the simulation. This schedule also results in a specific file naming scheme, such that the filename for capture #0 will be truth-t0000-c0000.img, capture #1 will be truth-t0000-c0001.img, etc. The section contains the list of descriptions. The InstanceIndex collector takes a comma separated list. This list contains the material IDs of moving objects we are interested. In this case 500 is the material ID of the body paint on a car we are interested in. However, the user can specify as many material IDs as they would like. If they want to track the "red" cars (which is, as an example, material ID #500), and the "blue" cars (which is, as an example, material ID #600), then the user should supply the list as 500,600.

A.2.2 "InstanceIndex" Truth Map

If you look at the "InstanceIndex" band in the raster truth image, you will see something like the following: CityEngine/SUMO Scene Construction Manual 78 / 82

Figure A.1: A look at the "instance index" raster image truth.

The zoom shows two cars passing each other in one section of the scene. Although the two cars in the zoom region look to be the same color, it is an artifact of scaling the large index values to fit into the 8-bit display for visualization. The actual data value for each pixel is the unique instance index for each respective car (which happened to be 21994 and 22018, in this example). The next step in the tool chain will identify these cluster of pixels containing specific instances, compute the center of that cluster (as a pixel coordinate) and record that center for output in a per-object report that documents the location of each instance in each frame.

A.3 Generating Per-Instance Tracks

When the simulation has run, the user will have a set of radiance image and truth image files (one for each frame of data simulated). The second part of the "track" file generation process is to extract per-object tracks from the "instance index" raster truth data. To accomplish this, a new tool was created called track_extract. It is a command line tool that will drive through a sequence of truth image files and generate a separate "track" file for each moving instance in the simulation.

A.3.1 Running the Extraction Tool

$ track_extract 0 199 truth CityEngine/SUMO Scene Construction Manual 79 / 82

The arguments to the tool are as follows:

• The 0 argument indicates the index of the "instance index" truth band in the raster truth image file. In this case, we only had the "InstanceIndex" collector configured, so the output truth image has a single band containing the data for that collector. • The 199 argument is the maximum capture index to be processed by the tool. In this example, the simulation produced 199 frames (captures) and we want the tool to process all of them. • The truth argument is the basename of the truth image files generated by the simulation.

Note The tool currently assumes there was a single task in the simulation.

Note The tool currently assumes the truth image filename extension was img.

When the tool starts, it will then start looking for the file sequence:

• truth-t0000-c0000.img • truth-t0000-c0001.img • truth-t0000-c0002.img •... • truth-t0000-c0199.img

While the tool is processing the truth raster image files, it will report the number of instances it has found within the current frame (capture). At the end of processing the current frame (capture), the tool computes the centroid of all the pixels that contained the object. After all the truth raster image files are processed, the tool will generate the track files for each instance it found during processing. The output filename is currently N_track.txt, where N is the unique instance index number for the object. The format of this file is described in the next section.

A.3.2 Track File Format

Each moving object instance that was flagged via the material ID indicator in the raster truth collector will have the image-space location written to a unique file. The format of this file is a very simple 3-column format:

• The truth image filename (which will have a similar naming convention as the radiance images produced during the simulation). • The average X location of the object in image space. • The average Y location of the object in image space.

Below is an example "track" file: truth-t0000-c0000.img 396.857 63.9286 truth-t0000-c0001.img 392 63.75 truth-t0000-c0002.img 387.733 63.8 ... truth-t0000-c0083.img 9.05882 58.8235 truth-t0000-c0084.img 4.17647 58.7647 truth-t0000-c0085.img 1.375 58.875 CityEngine/SUMO Scene Construction Manual 80 / 82

Note If a "track" file does not contain a record for a specific frame (capture), then the object is completely obscured by another object within the scene or is not within the FOV of the frame (it has not entered the FOV yet, or has left the FOV).

Note that the record for this instance stops at frame (capture) #85 because the vehicle has left the field-of-view (FOV). In other cases, a given object may not come into the FOV of the sensor until later in the collection. In this case, the first record in the file will indicate during which frame the object first appears. The following plot illustrates how this data can be quickly visualized in a plotting program (gnuplot was used in this example):

Figure A.2: A simple visualization of seven (7) tracks by plotting columns #2 and #3. CityEngine/SUMO Scene Construction Manual 81 / 82

Figure A.3: A single radiance frame from the simulation to help visualize the road placement and the plotted tracks.

Figure A.4: An overlay of tracks onto a radiance image frame. CityEngine/SUMO Scene Construction Manual 82 / 82

Note To correlate an instance "track" files with the original object (both the geometry and the material assignments), simply look up the "instance index" in the "instance report" generated for the simulation.