If needed, you can create a railway network programmatically. Please note that you can do it only on model startup, and the network cannot be modified later.
In this article we study the following model:
Demo model: Create Rail Yard by Code
In this example we create a railway network that consists of four railway tracks interconnected via the all-to-all switch. The network includes the Position on track element which sets the initial position for trains. Trains enter the network on the rt1 track and then continue moving either along the rt2, rt3, or rt4 track. The choice can be regulated manually by the call of the switch's toggle() function which is placed in the Action field of the button on the model's presentation.
To create a rail yard programmatically, provide Java code in the
action of the
agent (Agent actions
properties section). In our demo model the code is the following:
We declare the
and define the tracks that will be connected by this switch as arguments of the
function of the switch. To define the type of the switch, we use the
We create a Position on track in a similar way. In the setPointOnTrack() function we provide the reference to the railway track where we put this element (rt1) and specify the offset from the track's start point (200) as the function's arguments.
We now have all the elements that are needed to create a railway network. In the RailwayNetwork constructor, we provide the reference to the agent the network will be added to (this), the name of the network ("myRailwayNetwork"), drawing mode (2D, 3D or both), and the network's Z-coordinate (which is zero in our case).
Next, we add elements to the network by calling the network's addAll() function and passing the elements that we created earlier (railway tracks, railway switch and position on track) as its arguments.
We use the Level constructor to provide reference to the agent the level will be added to (this), the name of the level ("myLevel"), drawing mode (2D, 3D or both), and the level's Z-coordinate.
Next, we add the previously created network to the level by calling the level's add() function and passing the network as its argument.
We initialize the level by calling its
initialize(). Remember, that after you initialize the level, you will not be able to make any further changes to the created rail yard.
Finally, we add the created level to the presentation group to make it visible at runtime. To do this, we call the add() function of the presentation group for the level.