18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-02 05:02:45 +01:00
Files
maszyna/scene/scene.h
T
maj00r 1d8fdffac5 feat(render): models with lights drawn instanced, behind gfx.instancedlights in eu07.ini (#538)
* feat(render): models with lights drawn instanced, behind gfx.instancedlights in eu07.ini

Stage 5 of the EU07M model format. A model with lights (lights, Light_On## / Light_Off##), such as a signal head, was
drawn instance by instance, a draw call for each part of each one. With gfx.instancedlights 1 the instances of such a
model go into the instanced batches like the others, in both renderers, with the culling of the GPU and without it. The
default 0 draws them as before. It applies to EU07M and E3D models alike.

- The light state of an instance is a word in the element [0][3] of its instance matrix, which an affine matrix leaves
  unused: bits 0-7 the lit parts shown, bits 8-15 the dark parts, in the mantissa of a float of exponent 128
  (0x40000000), a normal number the GPU carries through its matrix products whole. Without that marker the shader
  draws everything, as before.
- model_ubs.light_part says which part of which slot a draw is (0 none, 1 + slot lit, 9 + slot dark); a part the
  instance doesn't show gets a zero matrix in the vertex shader (instance_hides_part() and effective_modelview() in
  shaders/vk14/common.glsl and shaders/ogl46/common.glsl). The batch instance shows every light part
  (TAnimModel::RaPrepareInstanced()).
- CPU path: each instance drawn is animated (RaAnimate) and its word put in its matrix (Render_Instanced). GPU culling:
  the word is in rotationscale[0].w of the instance record, refreshed once a frame for buckets with lights
  (Refresh_Light_Records), which marks the records to send again when a word changes.
- An instance shows the whole lit part or the whole dark one: blinking and switching (ls_On / ls_Off / ls_Blink) change
  over at half the fade, where the draw instance by instance fades the lit part in over the dark one. Steady states look
  the same as before.
- The freespot lights (TP_FREESPOTLIGHT with flag 0x4000 and no animation) don't keep a model out of the instancing
  when gfx.instancedlights is on. Light parts aren't put in the ray tracing of an instance batch.

Measured on Vulkan, 200 heads s4ipcpb_dd: with gfx.gpucull 0 frame 9.2 ms -> 1.5-2.5 ms and 2400 -> 16 draw calls, with
gfx.gpucull 1 9.1 ms -> 3.0 ms and 2410 -> 26 draw calls. Steady light states pixel for pixel the same as drawn
instance by instance on all three paths in Vulkan, and on GL 4.6 where the editor panels don't cover them; blinking
checked in Vulkan on all three paths (with time let run in the editor for the test only). Not run in the driver mode,
blinking not checked on GL 4.6, not built with GCC here. Unit tests 1189/1189.

* fix(render): EU07M review of #538: an instance with light colours of its own drawn alone, the light records locked only when stale

- An instance with lightcolors of its own isn't instanced: the colours go onto the shared submodels as the instance is
  prepared, which the instances of a bucket don't each get, so they all showed the colours of one of them.
- The walk takes the exclusive lock for the light records of a bucket only when they are stale in this frame
  (Refresh_Light_Records() checks again under it): the later passes of the frame no longer stop the other walkers.
- instance_cull.comp (both renderers) puts the word of the light parts into [0][3] after the product with the view, so a
  view with a translation can't stretch the first column of a lit instance.
- The spec: ls_Dark / ls_Home switch without the fade too, and the instances with light colours of their own.
2026-12-01 18:11:53 +01:00

633 lines
29 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include <vector>
#include <deque>
#include <array>
#include <stack>
#include <unordered_set>
#include <unordered_map>
#include <map>
#include "utilities/parser.h"
#include "rendering/geometrybank.h"
#include "scene/scenenode.h"
#include "world/Track.h"
#include "world/Traction.h"
#include "audio/sound.h"
#include "input/command.h"
#include "utilities/utilities.h"
class opengl46_renderer;
namespace scene {
int constexpr EU07_CELLSIZE = 250;
int constexpr EU07_SECTIONSIZE = 1000;
int constexpr EU07_REGIONSIDESECTIONCOUNT = 500; // number of sections along a side of square region
struct scratch_data {
struct binary_data {
bool terrain{ false }; // static geometry comes from binary terrain, its text definitions are skipped
bool terrain_included{false}; // binary terrain comes from the files named by terrain directives instead of the default one
bool terrain_default{ false }; // the scenario has usable binary terrain file of its own
std::vector<std::string> terrain_files; // files named by terrain directives; each one is loaded once
std::size_t geometry_imported{ 0 }; // pieces of static geometry read from the text definitions so far
std::size_t geometry_skipped{ 0 }; // pieces of static geometry left out so far, as provided by binary terrain
std::vector<std::string> terrain_textfiles; // terrain files (.txtf with binary .btf version) named by terrain directives so far
std::vector<std::string> terrain_binaryfiles; // binary versions of these, to be put to use once the scenery is initialized
} binary;
struct location_data {
std::stack<glm::dvec3> offset;
// per-axis scale stack — mirrors `offset` for the `scale`/`endscale`
// scenario directives. Effective scale at any nesting depth is the
// component-wise product of all stack entries (outer `scale 2 2 2` ×
// inner `scale 1.5 1.5 1.5` yields (3,3,3)). Empty stack means (1,1,1).
std::stack<glm::vec3> scale;
glm::vec3 rotation;
} location;
struct trainset_data {
std::string name;
std::string track;
float offset { 0.f };
float velocity { 0.f };
std::vector<TDynamicObject *> vehicles;
std::vector<int> couplings;
TDynamicObject * driver { nullptr };
TTrack * path { nullptr }; // given directly, for a trainset placed in the editor on a path which may have no name
bool is_open { false };
bool reversed { false };
std::unordered_map<std::string, std::string> assignment;
} trainset;
std::string name;
std::string terrain_name;
bool initialized { false };
bool time_initialized { false };
};
struct terrain_source;
// piece of a binary terrain file holding geometry of a single section, waiting to be loaded
struct terrain_block {
std::shared_ptr<terrain_source> source; // the file and data shared by its pieces
std::uint64_t offset { 0 }; // location of the piece in the file
std::uint32_t size { 0 };
};
// basic element of rudimentary partitioning scheme for the section. fixed size, no further subdivision
// TBD, TODO: replace with quadtree scheme?
class basic_cell {
friend opengl46_renderer;
public:
// constructors
basic_cell() = default;
// methods
// potentially activates event handler with the same name as provided node, and within handler activation range
void
on_click( TAnimModel const *Instance );
// legacy method, finds and assigns traction piece to specified pantograph of provided vehicle
void
update_traction( TDynamicObject *Vehicle, int const Pantographindex );
// checks whether a wire, not broken, is within reach of a pantograph at specified point: the plane of the pantograph's
// movement, normal to Front, crosses it over the slide of half width Halfwidth, between Minheight and Maxheight along Up
bool
wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const;
// legacy method, polls event launchers within radius around specified point
void
update_events();
// legacy method, updates sounds within radius around specified point
void
update_sounds();
// legacy method, triggers radio-stop procedure for all vehicles located on paths in the cell
void
radio_stop();
// legacy method, adds specified path to the list of pieces undergoing state change
bool
RaTrackAnimAdd( TTrack *Track );
// legacy method, updates geometry for pieces in the animation list
void
RaAnimate( unsigned int const Framestamp );
// whether RaAnimate() has anything to update in the frame
bool
animation_pending( unsigned int const Framestamp ) const {
return ( tTrackAnim != nullptr ) && ( Framestamp != m_framestamp ); }
// sends content of the class to provided stream
void
serialize( std::ostream &Output ) const;
// restores content of the class from provided stream
void
deserialize( std::istream &Input );
// takes over the content restored from a file into another cell, as deserialize() would have added it to this one
void
merge( basic_cell &&Other );
// sends content of the class in legacy (text) format to provided stream
void
export_as_text( std::ostream &Output ) const;
// adds provided shape to the cell
void
insert( shape_node Shape );
// adds provided lines to the cell
void
insert( lines_node Lines );
// adds provided path to the cell
void
insert( TTrack *Path );
// adds provided path to the cell
void
insert( TTraction *Traction );
// adds provided model instance to the cell
void
insert( TAnimModel *Instance );
// adds provided sound instance to the cell
void
insert( sound_source *Sound );
// adds provided event launcher to the cell
void
insert( TEventLauncher *Launcher );
// adds provided memory cell to the cell
void
insert( TMemCell *Memorycell );
// registers provided path in the lookup directory of the cell
void
register_end( TTrack *Path );
// registers provided traction piece in the lookup directory of the cell
void
register_end( TTraction *Traction );
void
erase( TTrack *Path );
void
unregister_end( TTrack *Path );
// removes provided model instance from the cell
void
erase( TAnimModel *Instance );
// removes provided memory cell from the cell
void
erase( TMemCell *Memorycell );
// removes provided traction piece from the cell
void
erase( TTraction *Traction );
void
unregister_end( TTraction *Traction );
// removes provided event launcher from the cell
void
erase( TEventLauncher *Launcher );
// find a vehicle located nearest to specified point, within specified radius. reurns: located vehicle and distance
std::tuple<TDynamicObject *, float>
find( glm::dvec3 const &Point, float const Radius, bool const Onlycontrolled, bool const Findbycoupler ) const;
// finds a path with one of its ends located in specified point. returns: located path and id of the matching endpoint
std::tuple<TTrack *, int>
find( glm::dvec3 const &Point, TTrack const *Exclude ) const;
// finds a traction piece with one of its ends located in specified point. returns: located traction piece and id of the matching endpoint
std::tuple<TTraction *, int>
find( glm::dvec3 const &Point, TTraction const *Exclude ) const;
// finds a traction piece located nearest to specified point, sharing section with specified other piece and powered in specified direction. returns: located traction piece
std::tuple<TTraction *, int, float>
find( glm::dvec3 const &Point, TTraction const *Other, int const Currentdirection ) const;
// sets center point of the cell
void
center( glm::dvec3 Center );
// generates renderable version of held non-instanced geometry in specified geometry bank
void
create_geometry( gfx::geometrybank_handle const &Bank );
void
create_map_geometry(std::vector<gfx::basic_vertex> &Bank, const gfx::geometrybank_handle Extra);
void
get_map_active_paths(map_colored_paths &handles);
glm::vec3 find_nearest_track_point(const glm::dvec3 &pos);
// provides access to bounding area data
bounding_area const &
area() const {
return m_area; }
//private:
// types
using path_sequence = std::vector<TTrack *>;
using shapenode_sequence = std::vector<shape_node>;
using linesnode_sequence = std::vector<lines_node>;
using traction_sequence = std::vector<TTraction *>;
using instance_sequence = std::vector<TAnimModel *>;
// Composite key: instances of the same TModel3d sharing the same replacable
// skin set can be GPU-batched together, but instances with different skins
// must go to different buckets so each batched draw call uses one consistent
// material binding. Sub-bucketing here keeps Render_Instanced correct without
// forcing per-instance material switching inside a single batch.
struct instance_bucket_key {
TModel3d *pModel { nullptr };
std::array<material_handle, 5> skins {};
// an instance drawn on its own (not instanceable) culled on the gpu as a bucket of its own: it isn't drawn
// together with other instances of the model, as its submodel tree is prepared and walked for it alone
TAnimModel const *instance { nullptr };
bool operator==( instance_bucket_key const &other ) const {
return pModel == other.pModel && skins == other.skins && instance == other.instance;
}
};
struct instance_bucket_key_hash {
std::size_t operator()( instance_bucket_key const &k ) const {
std::size_t h = std::hash<TModel3d *>()( k.pModel );
for( auto s : k.skins ) {
// boost-style hash combine
h ^= std::hash<int>()( s ) + 0x9e3779b9 + ( h << 6 ) + ( h >> 2 );
}
h ^= std::hash<TAnimModel const *>()( k.instance ) + 0x9e3779b9 + ( h << 6 ) + ( h >> 2 );
return h;
}
};
using instance_bucket_map = std::unordered_map< instance_bucket_key, std::vector<TAnimModel *>, instance_bucket_key_hash >;
// what it takes to cull and place an instance, copied from the instance.
// a cell can hold thousands of instances, each of them large and placed wherever the memory was free, and a render
// pass rejects most of them. the renderer makes the copies and goes by them, and reads the instance itself only
// for the first one of a batch drawn. the layout follows std430, for the copies to be handed to the gpu as they are
struct instance_record {
packed_vec3 position { 0.f }; // location of the instance, relative to the origin of the records of its bucket
float radius { 0.f };
float rangesquaredmin { 0.f }; // visibility range of the instance
float rangesquaredmax { 0.f };
std::uint32_t flags { 0 }; // instance_record_flags
std::uint32_t pad { 0 }; // the copy of the gpu culling keeps there whether the instance was seen in the last frame
glm::vec4 rotationscale[ 3 ] {}; // columns of rotation and scale of the instance, w unused
};
static_assert( sizeof( instance_record ) == 80, "instance_record has to keep its std430 layout" );
static_assert( offsetof( instance_record, radius ) == 12, "instance_record has to keep its std430 layout" );
static_assert( offsetof( instance_record, flags ) == 24, "instance_record has to keep its std430 layout" );
static_assert( offsetof( instance_record, rotationscale ) == 32, "instance_record has to keep its std430 layout" );
enum instance_record_flags : std::uint32_t {
instance_visible = 1 << 0,
instance_instanceable = 1 << 1, // false once an event gave the instance animations or a skin of its own
};
struct instance_bucket {
std::vector<TAnimModel *> instances;
// caches owned by the renderer; emptied whenever the content of the bucket changes
mutable std::vector<instance_record> records; // copies for the instances, in the same order
mutable glm::dvec3 recordorigin { 0.0 }; // the records hold locations relative to it
mutable float lodrangesquared { 0.f }; // past it no submodel of the model of the bucket is drawn
mutable float rangesquared { std::numeric_limits<float>::max() }; // past it no instance of the bucket is drawn: the largest range of its instances, within lodrangesquared
// bounds of the visible instances of the records, for the tests of a whole bucket: a sphere around their locations
// (recordcenter, recordlocationradius), the radius of the sphere which holds the instances whole (negative when none
// of them is visible), and the largest radius of an instance
mutable glm::dvec3 recordcenter { 0.0 };
mutable float recordlocationradius { 0.f };
mutable float recordradius { -1.f };
mutable float recordradiusmax { 0.f };
mutable unsigned int recordsversion { 0 };
// the frame the light states of the instances of a model with lights were last put in the records (gfx.instancedlights)
mutable unsigned int lightsframe { 0 };
// place of the records in the record buffer of the gpu culling: first record, room, and the generation of
// the buffer it is good for. gpustale: the records changed since they were sent
mutable std::uint32_t gpufirst { 0 };
mutable std::uint32_t gpucapacity { 0 };
mutable unsigned int gpugeneration { 0 };
mutable bool gpustale { true };
};
using instance_bucketdata_map = std::unordered_map< instance_bucket_key, instance_bucket, instance_bucket_key_hash >;
using sound_sequence = std::vector<sound_source *>;
using eventlauncher_sequence = std::vector<TEventLauncher *>;
using memorycell_sequence = std::vector<TMemCell *>;
// methods
void
launch_event(TEventLauncher *Launcher, bool local_only);
void
enclose_area( scene::basic_node *Node );
// members
scene::bounding_area m_area { glm::dvec3(), static_cast<float>( 0.5 * M_SQRT2 * EU07_CELLSIZE ) };
bool m_active { false }; // whether the cell holds any actual data content
shapenode_sequence m_shapesopaque; // opaque pieces of geometry
shapenode_sequence m_shapestranslucent; // translucent pieces of geometry
linesnode_sequence m_lines;
path_sequence m_paths; // path pieces
instance_sequence m_instancesopaque;
// the instances of m_instancesopaque drawn each on its own (TAnimModel::m_instanceable false), in the same order: the walks
// go through these instead of reading every instance of the cell in each pass. made by the walks for the version of the
// instance records they go by and the count of the instances they were made from (gfx::scene_walk::Single_Instances())
mutable instance_sequence m_instancessingle;
mutable unsigned int m_instancessingleversion { 0 };
mutable std::size_t m_instancessinglesource { 0 };
instance_sequence m_instancetranslucent;
// batched instance buckets keyed by shared TModel3d*; populated alongside
// m_instancesopaque for nodes whose TAnimModel::m_instanceable == true.
// The renderer uses these to amortise per-model state setup across many instances.
instance_bucketdata_map m_instancebuckets_opaque;
traction_sequence m_traction;
sound_sequence m_sounds;
eventlauncher_sequence m_eventlaunchers;
memorycell_sequence m_memorycells;
// search helpers
struct lookup_data {
path_sequence paths;
traction_sequence traction;
} m_directories;
// animation of owned items (legacy code, clean up along with track refactoring)
bool m_geometrycreated { false };
unsigned int m_framestamp { 0 }; // id of last rendered gfx frame
TTrack *tTrackAnim = nullptr; // obiekty do przeliczenia animacji
command_relay m_relay;
};
// basic scene partitioning structure, holds terrain geometry and collection of cells
class basic_section {
friend opengl46_renderer;
public:
// constructors
basic_section() = default;
// methods
// potentially activates event handler with the same name as provided node, and within handler activation range
void
on_click( TAnimModel const *Instance );
// legacy method, finds and assigns traction piece to specified pantograph of provided vehicle
void
update_traction( TDynamicObject *Vehicle, int const Pantographindex );
// checks whether a wire, not broken, is within reach of a pantograph at specified point: the plane of the pantograph's
// movement, normal to Front, crosses it over the slide of half width Halfwidth, between Minheight and Maxheight along Up
bool
wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const;
// legacy method, updates sounds and polls event launchers within radius around specified point
void
update_events( glm::dvec3 const &Location, float const Radius );
// legacy method, updates sounds and polls event launchers within radius around specified point
void
update_sounds( glm::dvec3 const &Location, float const Radius );
// legacy method, triggers radio-stop procedure for all vehicles in 2km radius around specified location
void
radio_stop( glm::dvec3 const &Location, float const Radius );
// sends content of the class to provided stream
void
serialize( std::ostream &Output ) const;
// restores content of the class from provided stream
void
deserialize( std::istream &Input );
// takes over the content restored from a file into another section, as deserialize() would have added it to this one
void
merge( basic_section &&Other );
// sends content of the class in legacy (text) format to provided stream
void
export_as_text( std::ostream &Output ) const;
// adds provided shape to the section
void
insert( shape_node Shape );
// adds provided lines to the section
void
insert( lines_node Lines );
// adds provided node to the section
template <class Type_>
void
insert( Type_ *Node ) {
auto &targetcell { cell( Node->location() ) };
targetcell.insert( Node );
// some node types can extend bounding area of the target cell
m_area.radius = std::max(
m_area.radius,
static_cast<float>( glm::length( m_area.center - targetcell.area().center ) + targetcell.area().radius ) ); }
// erases provided node from the section
template <class Type_>
void
erase( Type_ *Node ) {
auto &targetcell { cell( Node->location() ) };
// TODO: re-calculate bounding area after removal
targetcell.erase( Node ); }
// registers provided node in the lookup directory of the section enclosing specified point
template <class Type_>
void
register_node( Type_ *Node, glm::dvec3 const &Point ) {
cell( Point ).register_end( Node ); }
template <class Type_>
void
unregister_node( Type_ *Node, glm::dvec3 const &Point ) {
cell( Point ).unregister_end( Node ); }
// find a vehicle located nearest to specified point, within specified radius. reurns: located vehicle and distance
std::tuple<TDynamicObject *, float>
find( glm::dvec3 const &Point, float const Radius, bool const Onlycontrolled, bool const Findbycoupler );
// finds a path with one of its ends located in specified point. returns: located path and id of the matching endpoint
std::tuple<TTrack *, int>
find( glm::dvec3 const &Point, TTrack const *Exclude );
// finds a traction piece with one of its ends located in specified point. returns: located traction piece and id of the matching endpoint
std::tuple<TTraction *, int>
find( glm::dvec3 const &Point, TTraction const *Exclude );
// finds a traction piece located nearest to specified point, sharing section with specified other piece and powered in specified direction. returns: located traction piece
std::tuple<TTraction *, int, float>
find( glm::dvec3 const &Point, TTraction const *Other, int const Currentdirection );
// sets center point of the section
void
center( glm::dvec3 Center );
// generates renderable version of held non-instanced geometry
void
create_geometry();
// whether create_geometry() has anything to make or to load
bool
geometry_pending() const {
return ( false == m_terrain.empty() ) || ( false == m_geometrycreated ); }
// loads geometry of the section kept in binary terrain files, if any is waiting
void
load_terrain();
void
create_map_geometry(const gfx::geometrybank_handle handle);
void
get_map_active_paths(map_colored_paths &handles);
// provides access to bounding area data
bounding_area const &
area() const {
return m_area; }
const gfx::geometrybank_handle get_map_geometry()
{ return m_map_geometryhandle;}
glm::vec3 find_nearest_track_point(const glm::dvec3 &point);
//private:
// types
using cell_array = std::array<basic_cell, EU07_SECTIONSIZE / EU07_CELLSIZE * (EU07_SECTIONSIZE / EU07_CELLSIZE)>;
using shapenode_sequence = std::vector<shape_node>;
// methods
// provides access to section enclosing specified point
basic_cell &
cell(glm::dvec3 const &Location, const glm::ivec2 &offset = glm::ivec2(0));
// members
// placement and visibility
scene::bounding_area m_area { glm::dvec3(), static_cast<float>( 0.5 * M_SQRT2 * EU07_SECTIONSIZE ) };
// content
cell_array m_cells; // partitioning scheme
shapenode_sequence m_shapes; // large pieces of opaque geometry and (legacy) terrain
std::vector<terrain_block> m_terrain; // geometry in binary terrain files, loaded when the section comes into use
// TODO: implement dedicated, higher fidelity, fixed resolution terrain mesh item
// gfx renderer data
gfx::geometrybank_handle m_geometrybank;
bool m_geometrycreated { false };
gfx::geometrybank_handle m_map_geometryhandle;
};
// top-level of scene spatial structure, holds collection of sections
class basic_region {
friend opengl46_renderer;
public:
// constructors
basic_region();
// destructor
~basic_region();
// methods
// potentially activates event handler with the same name as provided node, and within handler activation range
void
on_click( TAnimModel const *Instance );
// legacy method, finds and assigns traction piece to specified pantograph of provided vehicle
void
update_traction( TDynamicObject *Vehicle, int const Pantographindex );
// checks whether there's a contact wire, not broken, over specified point of a track with heading Front, within reach of
// a pantograph there: over its slide of half width Halfwidth, between Minheight and Maxheight above the point. the
// geometry is the one the pantographs find their wire with (ai_wire::span_contact), with the vertical up
bool
wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, double const Halfwidth, double const Minheight, double const Maxheight ) const;
// legacy method, polls event launchers around camera
void
update_events();
// legacy method, updates sounds around camera
void
update_sounds();
// checks whether specified file is a valid region data file
bool
is_scene( std::string const &Scenariofile ) const;
// stores content of the class in file with specified name
void
serialize( std::string const &Scenariofile ) const;
// restores content of the class from file with specified name. returns: true on success, false otherwise
bool
deserialize( std::string const &Scenariofile );
// removes the region file of specified scenario file, which turned out to be damaged, so the next start writes it anew
void
discard_scene( std::string const &Scenariofile ) const;
// sends content of the class in legacy (text) format to provided stream
void
export_as_text( std::ostream &Output ) const;
// legacy method, links specified path piece with potential neighbours
void
TrackJoin( TTrack *Track );
// legacy method, triggers radio-stop procedure for all vehicles in 2km radius around specified location
void
RadioStop( glm::dvec3 const &Location );
// inserts provided shape in the region
void
insert( shape_node Shape, scratch_data &Scratchpad, bool const Transform );
// inserts provided lines in the region
void
insert( lines_node Lines, scratch_data &Scratchpad );
// inserts provided node in the region
template <class Type_>
void
insert( Type_ *Node ) {
auto const location { Node->location() };
if( false == point_inside( location ) ) {
// NOTE: nodes placed outside of region boundaries are discarded
// TBD, TODO: clamp coordinates to region boundaries?
return; }
section( location ).insert( Node ); }
// inserts provided node in the region and registers its ends in lookup directory
template <class Type_>
void
insert_and_register( Type_ *Node ) {
insert( Node );
for( auto const &point : Node->endpoints() ) {
if( point_inside( point ) ) {
section( point ).register_node( Node, point ); } } }
// removes specified node from the region
template <class Type_>
void
erase( Type_ *Node ) {
auto const location{ Node->location() };
if( point_inside( location ) ) {
section( location ).erase( Node ); } }
template <class Type_>
void
erase_and_unregister( Type_ *Node ) {
for( auto const &point : Node->endpoints() ) {
if( point_inside( point ) ) {
section( point ).unregister_node( Node, point ); } }
erase( Node ); }
// find a vehicle located nearest to specified point, within specified radius. reurns: located vehicle and distance
std::tuple<TDynamicObject *, float>
find_vehicle( glm::dvec3 const &Point, float const Radius, bool const Onlycontrolled, bool const Findbycoupler );
// finds a path with one of its ends located in specified point. returns: located path and id of the matching endpoint
std::tuple<TTrack *, int>
find_path( glm::dvec3 const &Point, TTrack const *Exclude );
// finds a traction piece with one of its ends located in specified point. returns: located traction piece and id of the matching endpoint
std::tuple<TTraction *, int>
find_traction( glm::dvec3 const &Point, TTraction const *Exclude );
// finds a traction piece located nearest to specified point, sharing section with specified other piece and powered in specified direction. returns: located traction piece
std::tuple<TTraction *, int>
find_traction( glm::dvec3 const &Point, TTraction const *Other, int const Currentdirection );
// finds sections inside specified sphere. returns: list of sections
std::vector<basic_section *> const &
sections( glm::dvec3 const &Point, float const Radius );
// finds sections inside specified sphere, put in the list given in place of what it held. unlike the one above it shares no list
// of its own, so it's safe while other threads look for sections too
void
sections( glm::dvec3 const &Point, float const Radius, std::vector<basic_section *> &Sections ) const;
void
create_map_geometry();
void
update_poi_geometry();
// loads all geometry kept in binary terrain files which wasn't needed so far
void
load_terrain();
basic_section* get_section(size_t section)
{ return m_sections[section]; }
gfx::geometrybank_handle
get_map_poi_geometry() { return m_map_poipoints; }
glm::vec3 find_nearest_track_point(const glm::dvec3 &pos)
{ return section(pos).find_nearest_track_point(pos); }
//private:
// types
using section_array = std::array<basic_section *, sq(EU07_REGIONSIDESECTIONCOUNT)>;
struct region_scratchpad {
std::vector<basic_section *> sections;
};
gfx::geometrybank_handle m_map_geometrybank;
gfx::geometrybank_handle m_map_poipoints;
// methods
// checks whether specified point is within boundaries of the region
bool
point_inside( glm::dvec3 const &Location );
// legacy method, trims provided shape to fit into a section. adds trimmed part at the end of provided list, returns true if changes were made
static
bool
RaTriangleDivider( shape_node &Shape, std::deque<shape_node> &Shapes );
// provides access to section enclosing specified point
basic_section &
section( glm::dvec3 const &Location );
// members
section_array m_sections;
region_scratchpad m_scratchpad;
};
// global hierarchy map for scene nodes
extern std::map<std::string, basic_node *> Hierarchy;
} // scene
//---------------------------------------------------------------------------