mirror of
https://github.com/MaSzyna-EU07/maszyna.git
synced 2026-11-19 23:55:00 +01:00
* feat(track): the rail code split by concern, the blades of the switches with the key frogs shaped from their templates The rails are laid by code of their own instead of inside Track.cpp: gauge lines (GaugeLine), knot lines (Knots.h), crossings and check rails (RailCrossings), rail materials (RailMaterials), measuring the rail profile (RailProfile), planning the cuts (RailPlan), the carving scan (RailCarve) and laying the geometry (RailLayer). A switch with the key frogs draws its blades from the tip where their planed nose ends to the heel, bent as they're thrown, and the rail behind them from the heel on, where they were laid from the start of the switch before; on a switch of the catalogue they start at the cut tip of the tables, 1.248 m from the joint at R 190, 1.5 m at R 300 (track_features::blades). The frogs cut from the rails, the wing and the check rails are built but switched off (track_features::crossings), the rails laid whole as before. The switches without the key keep the blades they had. A switch path can be a chain of pieces: pieces1 and pieces2 keep the parts of each path after the classic bezier, which stays as the approximation older versions read. A path with its radius given is a curve however gently it bends, a plain track a straight only where both of its control vectors lie along it. A vehicle trailing through a switch with a movable nose set the other way runs off the rails at it (TRAILED_SWITCH). * feat(render): the shared treads of the rails and their cut faces drawn, the cut faces in the matte variants of the rail materials Both renderers draw the treads a track shares with the rails it crosses, in the pick pass too, and a pass of their own for the faces where the rails are cut, the ends of the blades among them, in the matte variants of the rail materials, so the cut faces don't shine like the head the wheels polish. * feat(vehicle): an axle on a switch keeps to the path it came on, and coming from the frog end trails the switch through where the wheels reach the blades The switch thrown under an axle no longer moves it over onto the other path; it runs on along the one it entered. Coming from the frog end, where the blades are shaped or the frog has a movable nose, the switch set the other way is trailed through (rozprucie) only where the wheels get to the blades or to the nose, not as the axle enters the track; the other switches are trailed through as it enters, as before. * fix(track): the tracks drawn straight before, which their second control vector bends now, written to the log The simulator told a straight by the first control vector of a path alone, so a track whose second control vector bent it was drawn straight; now it's a curve. Such a track is named in the log as it loads, so a scenery made counting on the straight can be found: 25 tracks of lk357. Paths with both control vectors along them bend a centimetre or so at most and aren't named. * feat(track): 3D sleepers and switch timbers laid where the simulator makes the ballast, switched off in the build The sleepers of a track running alone are laid square to it, the timbers of the switches and crossings across the tracks running over them, shared by them, of the models set with sleepers3d and sleepers3dplain in eu07.ini; sleepers3dbed tells whether the ballast is laid under them too, lowered so they stick out of it. The layout of a cluster of tracks is worked out once and kept till a track of it changes, in a thread of its own while the simulation runs. timbermodel of a track, read and written back before, takes the place of the model of sleepers3d there. All of it is off whatever eu07.ini sets (track_features::sleepers), the tracks keeping their ballast and their sleeper models. * feat(render): the 3D sleepers and switch timbers drawn in instanced batches Render_Timbers lays the beams of the tracks in range where they're out of date and draws those of a run of tracks of a cell gathered by the model and its part or its level of detail, in as few instanced batches as they fit in; in the shadow pass only those near the camera. A track with them leaves its old sleeper model out. OpenGL 3.3 renderer only. * fix(track): the counts of what's wrong with the sleepers kept safe from the thread laying them, and that thread stopped before what it works with goes The counts of the beams clipped, dropped and off the plane, of the slowest and the biggest cluster, are counted by the thread working out the layouts in the background as well as by the simulation laying a cluster itself, and were plain values written by both; they're atomic now. What the thread keeps the clusters in, their version and the counts were made after the worker, as it first asked for them, and so destroyed before it at the exit while its thread could still be laying a cluster; they're made first now, the worker stopping and joining its thread before they go. The tracks go with the paths of the simulation, made before the worker. * revert(track): a tributary and a track of an unknown type load as before They came in with the rail code from the guards of the editor against crashing, and don't belong with the blades: a track of an unknown type loaded as a normal track of the railway could be joined to it and run on, and a tributary loaded as a river with its first path lost the second one when the editor saved the scenery. Both load as on master again; the place where the editor crashed on them is to be guarded where it is. * fix(track): the tracks drawn straight before named in the log once, as they load, and the paths of the switches with no radius told a straight as before in one term The log of the tracks the second control vector bends now was written each time the segments of a track were made again, as a track with its unevenness loads and as the editor changes or drags a track; it's written only the first time, as the track loads. The paths of a switch or a crossing with no radius keep the rule of master, a straight told by the first control vector alone, its two terms being the same length; they're one term now, with the comment saying so. * fix(track): the thread laying the sleepers stopped as the application exits, and loading no models itself The thread reads the scenery, which the application deletes as it exits well before the statics go: it's stopped and joined first thing in exit() now, the worker destroyed with the statics only where the application exits some other way, and not started again after. The models the beams are made of were loaded by the thread where it didn't find them, through the renderer, out of the thread of the renderer, into a map read by the simulation meanwhile: they're found under a lock now and loaded only by the threads other than it, again for all the tracks whenever a track changed since, before a layout is asked of it. With the 3D sleepers off in the build their settings aren't exported, and a track changed doesn't look for the tracks around to lay their beams again. * feat(track): the 3D sleepers turned on with sleepers3d in eu07.ini, no longer switched off in the build track_features::sleepers is gone: sleepers3d <model> in eu07.ini lays them, none (the default) lays nothing and the tracks keep their ballast, as before. The sleepers3d settings are written back with the others. The editor changes the tracks, so while it's open their sleepers are worked out on the main thread as they're needed, not in the background. * fix(render): only the part of a timber model drawn, not what else the model holds A timber model of parts may hold more than its begin, main and end, as the kits with the fastenings of the rails do. Those were drawn with each part of each timber, in the middle of the track; they aren't laid, so they're skipped now. * fix(track): the 3D sleepers laid only for a renderer which draws them Only the OpenGL 3.3 renderer draws the beams. With another one a track set to them lost its ballast to them, lowered or not laid at all with sleepers3dbed no, and nothing was drawn in its place. Draws_Timbers() of the renderer tells now, and where it's false the tracks keep their ballast, as with sleepers3d none. * fix(render): the submodels of a timber model left as they were after its parts are drawn They were all made visible after a part was drawn, the ones the model hides itself too, like Light_On, while the same model may stand in the scenery. The submodels of the top level besides the parts are listed as the model is loaded, hidden while a part is drawn and given back their own visibility after. The parts have to be at the top level of the model for that; a model with them deeper is logged and drawn whole. Render_Timbers no longer looks the model up under the lock for every run of tracks, the name set is enough there. * fix(render): a vertex whose faces give its texture no direction gets a tangent across its normal, not a NaN one The cut ends of the rails have one spot of the texture on all their corners, so their tangent came out of normalize() as NaN. The normal-mapped shaders then shaded them with a NaN normal: about half of the vertices of the cuts and frogs, and the end faces of the rails. * feat(track): the frogs cut from the rails turned on with frogs in eu07.ini, no longer switched off in the build frogs yes cuts the rails of the plain tracks and of the switches with the key frogs where they cross other rails, into frogs, wing rails and check rails. It's off by default: the rails are laid whole as before, the blades of the switches with the key are shaped still. * refactor(editor): the track mode file split into the files of its tools, the code as it was A pure move, so that the commits after it show what changes in each tool rather than a 4800-line file rewritten. The member functions of editor_mode go to the file the editor of this branch has them in: route, straights, lay, switchplace, switchdrive, switchtool, trackgizmo, and the rest stays in editormodetrack.cpp. The helpers of its anonymous namespace go to editormodetrackshared.h, as they were but inline, in namespace track_mode, which the files use. No line of code changes; the files add only their license, includes and the using line. * feat(editor): the groundwork the tools of the editor share - The tool interface (editortool.h), the gestures of the mouse (editorgestures.h) and what the modes share (editormodeshared.h); the projection, viewport, selection and texture picking taking them up. - Scripted input (scriptedinput): the input of a selftest script fed to the editor as if typed and clicked, the real mouse and keyboard ignored meanwhile; EU07_EDITOR_SELFTEST_HIDDEN draws into a window never shown nor focused. - The ui layers and panels of the editor, its settings, icons and the info of the includes; the layers of the scenery and their saving; the launcher mode. - utilities: user_cache_path (the cache folder of the system for the user) and the helpers of the translations. - stb_image: the gif loader takes the frame two back from the frames it decoded, not from before its buffer. - tools/editor: the scripts making the headers of the drives, the turntables, the editor and its usage. - Unit tests: test_area and the stubs of the editor the tests link. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tracks laid along an alignment, to the PKP PLK norms, with their grade line and the ground - The alignment of the laying (editorAlignment, editorAlignmentStore): straights, transition curves and arcs with the cant of the norms for the speed, the radius below the minimum for it a warning; the lay, route and straights tools build on it, the route plan reading the curves going on from the tracks adjoining. - The grade line (editorProfile, the profile and gradeline tools): fitted to the terrain model or edited by hand, the tracks fitted marked in the scenery (//$f), the shared grade lines of nearly parallel tracks (//$n). - The ground under the tracks (editorGroundFollow, trackbed): the terrain drawn to the tracks and restored, the tracks put onto the terrain. - Connections between tracks (editorConnections, the connection and connection curve tools), the track presets, the shape of a track (editorTrackShape), digitizing tracks from the orthophoto, the properties sheet of the tracks (trackprops) and the track ux. - Unit tests: alignment, ground fit, heights, with the data of two fits. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the switches placed, slid and designed from their templates - The switch templates (editorSwitchStore, the template tool): the catalogue switches and the user's own, kept with the settings; the designer (editorSwitchDesign) with a drawing of the dimensions, a and b typed in with the shape making up the rest, a switch clicked off the orthophoto. - The curve of a switch laid into a curve (editorSwitchCurve), placement on a straight or into a curve, slide along it, crossovers and double slips (switchplace, switchslide), the drives of the switches (switchdrive) and the records of the switches placed (records). - Unit tests: test_switch_curve. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tools of the infrastructure beside the tracks The gauge, speed, joints, lineside, parallel tracks, vehicles, signals, turntables, sweep and road tools with headers of their own; the kilometrage of the lines (editorKilometrage, the km tool); the infrastructure, roads and speeds behind them (editorInfra, editorRoad, editorSpeed). Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the terrain model of geoportal.gov.pl and the orthophoto downloaded for the editor - editorNmt: the squares of the terrain model at 1 m (NMT GRID1, the WCS service of geoportal.gov.pl) fetched by two workers, kept in editor/cache/nmt/grid1 of the game folder, the heights of the scenery taken from them; the nmt mode loads it along the tracks or around the camera. - editorHttp: the HTTP client of both, WinHTTP on Windows, libcurl elsewhere where it's built with it; without it the caches only. - The orthophoto: its cache moved to the cache folder of the system for the user, the download area a polygon on the topo map (//$a) filled in the background, the 4K imagery, the tiles waiting outlined on the ground. - editorGeoMap: the topo map of the top view; heightmapterrain and the terrain streamer grow the terrain made from the model around the camera. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(launcher): the scenery wizard picks the place of a new scenery on the topo map the editor shares The wizard drops its own map download and decoding for the topo map widget of the editor (editorGeoMap). The place clicked becomes the geographic reference of the new scenery (//$g PUWG1992), and the scenery starts with the orthophoto of the editor on (//$o), lying under it in place. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the tools wired into the editor mode and the build editor_mode takes the tools of the commits before: its header declares them, editormode.cpp and the track mode drive them, and the renderers draw their overlays (opengl33 and legacy). CMakeLists lists the new sources and adds WITH_EDITOR_SELFTESTS (off by default); the unit tests build the new test files. Not built on its own: the tree builds again with the selftests commit, the one before the translation. * feat(editor): the selftests of the editor split by what they test The scripts of EU07_EDITOR_SELFTEST run the commands of editormodeselftest*.cpp: scene, track, rails, join, switch, signal, sleepers, sweep, terrain, monkey. The code is in every build; only with WITH_EDITOR_SELFTESTS=ON does the editor read the variables and run a script. The selftests of master now need the option too. The tree builds again with this commit. * feat(editor): the Polish texts of the editor, all of them in one update of editor_pl.po * fix(editor): the marks of the editor moved off the letters the starters read, and its lines told by their words The starters read some letters in a scenery file: the Starter the title //$n, the attachments //$f and the old scenery //$a, StarterNG and the launcher of the game the attachments //$f and the title //$n. The editor wrote its download area, shared grade lines and fitted tracks under them, and took every line of those marks as its own: saved, a scenery lost its title and attachments, and the starters showed the lines of the editor as them. - The download area is //$z, the shared grade lines //$w, the fitted tracks //$t. - Their lines and those of //$o are told by their first words, as //$h, //$r and //$k were: //$o only as "on 0" or "on 1", the origin or the settings of older builds after it, so a trainset described as "on ..." isn't taken. - The lines older builds wrote under //$a, //$n and //$f are read only by the words the editor wrote in them, or by its own comment line before them, under the new mark. Each save writes them again with it, also when the editor didn't change them; the lines of the starters stay. * fix(editor): a square of the terrain model cut short isn't read, and the squares are kept in the user's cache The service puts the directory of its GeoTIFF before the pixels, so a file cut short by a write or a fetch broken off was read whole, the pixels missing coming out as heights of 0 m, for good. - The reader (editorGeoTiff.hpp, with unit tests) wants all the strips the rows need, each within the file. - A square is written under a name of its own and renamed. - The squares are kept in the user's cache folder (nmt/grid1), as the orthophoto, since the game folder may not be writable; without one, in the game folder as before. The ones older builds kept there are moved over as each is asked for, a damaged one deleted. - Capabilities that didn't come aren't kept as the fallback name for the session: the next square asks again. * chore(editor): the http client said to serve the terrain model and the topo map too, the gif fix of stb_image marked local - CMake names the orthophoto, the terrain model and the topo map as what goes without libcurl. - The fix of the gif frame two back in stb_image is ours, not upstream's (v2.30 still has the old line): a comment at the line says so, for an update of stb_image to keep it. * fix(editor): the lines moved off the letters of the starters in a merged layer written once, not again with each save A merged layer's text goes into the file of its target on save, and the target is read again; the marked lines of the merged layer were dropped only for the marks the editor had changed. The lines moved to the new letters stayed with their old places, and the next save of the session wrote them into the target once more. - After a save, the marked lines of every merged layer are dropped; those of its target are read again from its file. - The lines of a dead layer aren't written again. - The selftest layermerge merges the layer of one file into another's, as the layers panel does. * feat(editor): the station as the signalling sees it, found from a switch of it, and its schematic editorStation: the switches joined by plain track no longer than 1.5 km, the tracks between them and the lines leading out, 400 m of each beyond the outermost switch; laid out as a schematic along the main track through the station. The track circuits, the signals and their lights, the lengths of the station tracks and the lines to the next stations are worked out from it for the signalling tool. Nothing uses it yet: the signalling tool, wired in the next commit, does. It builds on its own. * feat(editor): the signalling of a station in the Signalling tab, laid out from a switch of it as on the lines of PKP PLK LMB on a switch in the Signalling tab opens its station: the schematic in a window of its own, the name, the code, the line and the km of the station, and the steps of its signalling, each one step of undo: - the switches numbered along the station after its code, bpd_1, the parts of a slip bpd_15a..d; the drives and the objects naming a switch follow it, events written by hand keep the old names; - the tracks cut at the joints of the track circuits, Ie-4, and the circuits named, bpd_iz1, bpd_it1; - the entry, exit and shunting signals placed and named, A, F1, Tm1, from the templates chosen; - the signals of the lines out: the automatic block of three or four aspects, the block sections no shorter than the braking distance, or the semi-automatic one with a warning disc; block boundaries drawn by hand; - the lights each signal needs for its routes, Ie-1 and Ie-4 § 8, its template fitted to them; - the SHP track resonators the signals lack, rezonator.inc; - the lengths of the station tracks as a table, and what the station and its lines still lack, with Repair. The stations described are kept as //$s lines in the files of their layers. * fix(editor): the signals of a station and of its lines not placed with no template for a kind, no track cut for them first - Set the signals and Set the line signals cut the tracks first, and only then found no template for a kind. They stopped there, but the cuts stayed as a step of undo. Now they ask for the templates first, by the lookup signal_batch() uses (signal_template_for(), behind editor_signals::signal_templates_missing()). Without one nothing is cut. - Set the signals and Set the track circuits again under Track lengths had the ids of the buttons of the steps above them. ImGui flagged them when hovered. Each now has an id of its own. * fix(utilities): win1250_to_utf8 turns the polish letters into utf-8, not into themselves utilities.cpp starts with a byte order mark, so the compiler reads it as utf-8. The game's targets don't get /utf-8, though: set_target_properties(... COMPILE_OPTIONS ...) in the MSVC block of CMakeLists.txt replaces the options add_compile_options gave them. So the string literals went into the program in the code page of the system, windows-1250 on a polish one, and the map of win1250_to_utf8 turned each letter into itself. What read windows-1250 through it got no utf-8: the names, descriptions and categories of the sceneries and the names of the textures in the launcher, and the descriptions of the templates in the editor. The editor writes such a description back through utf8_to_win1250, which makes a question mark of each byte that doesn't start a utf-8 sequence, so the letters it had read unchanged didn't come back. The utf-8 sequences are written as bytes now, the way utf8_to_win1250 has them, so they don't depend on the options. The options stay as they are: with /utf-8 other literals of the files with a byte order mark would change, the "±" of the table of Bezogonkow would take two bytes and move the letters after it. The unit tests check the letters and that the text given is valid utf-8. (cherry picked from commit9ffed96ec1) * fix(editor): the switches renamed only after the events by their old names are shown, the station records in windows-1250 and in the file the scenery had Number the switches renames the switches and what the editor writes along with them, but not the events written by hand: a switch event aiming at a switch, or <name>:event0 and the others named after it, would keep the old name and lose its switch. Now the first click lists them in the status, up to six and how many more, and renames nothing. A second click with the same renames goes ahead. The name of a station is written in windows-1250, like the rest of the scenery file. A name read that isn't valid utf-8 is taken for windows-1250; the utf-8 the earlier builds wrote is read as it is. utf8_to_win1250 moves from editorIncludeInfo.cpp to the utilities, beside win1250_to_utf8, and the unit tests check both ways. The record of a station that had none goes beside the records of the other stations, in the file marked with them, so a scenery saved under another name keeps them in one file. output_layer takes, after <scenery>_<part>.scm, an included file of the part of another name, the one of the scenery it was copied from, before it makes a new one. The comments: the joints of the track circuits stand 4.2 m beyond the fouling points, where the axes are 3.5 m apart, as joints() counts them; the regulation of the lengths is cited with its date and title. * fix(editor): a scenery saved under another name keeps one file of the keys by the movable noses, not the old one beside its own The editor writes the keys by the movable noses on each save to <scenery>_dzioby.scm and includes it. A copy of a scenery, saved under another name, still included the file of the scenery it came from, and its save wrote a file of its own and included it too, so each key stood twice. Now the save leaves out of the scenery the other files of such keys it includes, told by the line the editor writes at their start. Their files stay on the disk, for the scenery they were made for. A file made by hand, without that line, stays included. The turntable controls had the same, fixed the same way on their own. * fix(editor): a file of the scenery named like a part of a tool isn't taken for the one the tool made output_layer took, after <scenery>_<part>.scm, any included file named *_<part>.scm, so that a scenery saved under another name goes on with the file of the scenery it was copied from. A file of the scenery named alike, written by hand, such as rejon_teren.scm, got the terrain directive, the hectometre posts or the new signals too. The files output_layer makes start with a line of their own now, "// scenery layer created in the editor for its <part> part", and a file of another name is taken only with that line. A layer gets it through the new parameter of scene::node_layers::create(); the others start with the general line as before. <scenery>_<part>.scm of the scenery itself is taken without the line, as it was. A file made for a part by an earlier build has only the general line, so a copy saved from it gets a file of its own. * feat(editor): a player of GIF clips for the windows of the editor editor_clips::clip plays a GIF in an ImGui window, looped, from the time given. stb_image decodes the whole file on a thread of its own, so the window isn't held up; until then the clip says it's loading. The frames are kept as stb_image decoded them, and the one shown is a texture of the ImGui renderer (Create_Image), made again only when the frame changes. A file that isn't there is told missing at once, with no thread started. Nothing uses it yet; the tutorial of the next commit shows its clips with it. * feat(editor): Help > Tutorial, fifteen short lessons of the editor The lessons: looking around, laying track, curves, the radius of the curves at the bends, correcting a curve, joining tracks, switches, switch templates, signals and posts, selecting and fixing, editing with the gizmo, the grade line, terrain from the terrain model, sceneries made before, saving and driving. Each lesson has: - in eight lessons, a looping clip from lang/editor_tutorial/<lesson>.gif, played from the start on a click; in six others, a moving drawing (the radius at a bend, a switch template clicked, the signals, the grade line, the terrain, a trainset); - the mouse buttons and keys drawn as pictures beside what they do; - ticks that fill in as the user does it, told by the tools through editor_guide::first_step_done(); - a button that turns the tool of the lesson on; - Back / Next and a dot per lesson, green when the lesson is done. The window follows the work: when the tool in use changes, it turns to the first lesson of that tool not done yet, and a page turned by hand stays until then. In a lesson of laying it warns when there's no ground under the cursor. Where it opens: - by itself when an editor session starts, until "Show when the editor opens" is unticked (first_steps in the editor's settings); - from the Help menu; - from a Tutorial button beside Lay a track in the hint of an empty scenery, which isn't drawn while the tutorial is open; - at its lesson, from a "?" by the radius at the bends in the lay panel. A lesson whose clip isn't there is shown without it; the clips aren't in this commit. editor_guide is a new role of the editor, given to the hekto-post and trainset tools. Selftest command tutorial <page>: opens the tutorial at a lesson, from 0; -1 closes it. * fix(editor): the lessons of the tutorial say what the editor does The lesson texts checked one by one against the tools; the ones that told otherwise: - Switches: a connection isn't chosen at the top of the panel, its kind comes from where the drag is let go (a crossover onto the other track, over a crossover the other way a double one, or scissors where they overlap). - Switches: a ladder leads onto the parallel tracks it's dragged across, let go on the farthest, with the straights up to where they start; it lays no missing tracks. - Terrain: there is no step 3. Step 1 is Location, step 2 is Load around the camera while there are no tracks and Tracks and terrain with its three ways once there are. The rows had the step numbers in the keys column, and 1, 2 and 3 switch the edit modes in the Terrain field. Now the steps show the mouse, the terrain under some tracks only is a row of F3 (the line the terrain panel shows), and the rows that only tell what the fit does have no key. - Sceneries made before: a plain include can be changed; the row lists what can't: an include template (.inc), the binary terrain cache, a file included twice or with parameters, a locked or hidden layer. - Laying: the second Esc drops the points only within 3 s. - The radius at the bends: two transition curves from 6000 m down to 2000 m while they're long enough for the speed, then an arc; a label turns orange where the curve breaks the norms, not because it came out smaller; two transitions meeting read 2xL and R; the labels of each transition curve are on laid tracks, close up. - Signals and posts: the W17 markers go by the selected switch, around the camera or the whole scenery, not along a line. - Selecting and fixing: E lengthens the track, the control vectors bend it. - The gizmo: at a point Q moves the point alone, W turns the whole track about it. The tooltip of Help > Tutorial no longer speaks of clips: the tutorial goes without them. lang/editor_pl.po has the new texts. * fix(editor): the lessons of the tutorial in plain words Every row, goal and warning of the tutorial is said again for someone who has never laid a track, in English and in Polish: - the words of the railway and of the editor are said in everyday ones, or explained where they come: the radius (how big the curve is), the transition curve (the easing into it), the cant (the outer rail raised), the gizmo (handles on the track), the control vectors (points that bend it), the grade line (how the line goes up and down), the terrain model (the real ground), the orthophoto (the aerial photo), the hectometre posts (every 100 m), W17 (how far a wagon may stand); - what only a designer needs is left out: the 6000 and 2000 m of the radius ladder, the compound curve, the hump, the kinds of include that can't be changed; - the buttons are named as the panels name them: Apply to the scenery, Template editor..., the tiles of the switch tool; - the Polish names of three lessons say what they are about ("Uchwyty na torze (gizmo)", "Wzniesienia i spadki", "Prawdziwy teren"). Their English titles stay, the lessons are found by them; - the warning of no ground under the cursor tells what happens to the track; - two captions of the drawings say what they show (the tracks inside a box, posts every 100 m), and in Polish the button of the top view is "Widok z góry (O)", without "ortogonalny". What each row tells of is the same as before. The msgid of the length typed while laying stays, the window of the keys (F1) uses it. * feat(editor): the semaphores and the warning discs chosen by what their descriptions say they show The descriptions of the signal templates can now say what a semaphore shows and what a disc repeats, and the editor reads it: - signal: {arms: 2, aspects: {Sr1: ..., Sr2: ..., Sr3: ..., Sz: ...}, repeats: {stop: ..., vmax: ..., "40": ...}} is kept with the template, the events named for each aspect - the palette shows a template with arms as a semaphore of its arms, with 1 arm / 2 arms and Sz picking the template of the same tile that has them - the signals of SRK take a semaphore whose aspects cover what the signal needs (Sr3 where a speed is reduced, Sz on the main signals), the fewest arms that do it, and say which one does when the placed one hasn't them or has more than it needs - the warning disc before a semaphore is one whose repeats cover stop, the highest speed and 40 km/h when the semaphore shows Sr3; SRK writes no events of the routes, so this only chooses and checks the disc - the linked signal (parameter 7) is read for the role link as well as text - signal_headers.py keeps the keys written by hand in a description (arms, aspects, repeats, the description and the parameters from 6 on) when it writes the guessed ones again - signaltemplates of the self test lists what the templates say and the heads made of them * feat(editor): the shaped discs swapped and set by hand, the warning discs checked by what they repeat The shaped shunting and stop discs (mk1, tzm, z1) are known to the signalling, but it doesn't place them by itself: - a shaped disc chosen in the palette for the shunting or the stop signals is placed by hand only; the signalling of a station takes the light template of the kind there, and says so when there is none - the template of a shunting or a stop signal standing can be swapped for a light or a shaped one of another mount as well (dwarf and mast, not gantry) - a signal whose description lists its aspects shows a button for each under its card: it sets the signal to that aspect in the editor, by the animations, the lights and the submodels its event sets off, the time standing still; nothing of it is saved. TAnimContainer::Finish takes an animation to its end at once, giving the submodel its angles, multi_event::branches tells the events set off when the condition isn't met From the review of the descriptions: - a shaped warning disc standing before a semaphore described is checked by the events it repeats: stop, the highest speed and 40 km/h of a second arm told apart; one which doesn't is offered the disc which does, and Fit swaps it - the disc offered is of the mount of the disc chosen, taken from the template even when it isn't described - 1 arm / 2 arms / Sz of the palette pick the template leaning as the chosen one and most like it by its name - a semaphore described with its arms but not its aspects has Sr1, Sr2 and with a second arm Sr3 - Fit leaves a semaphore having what it needs with its arms, for the events written by hand to the aspects of a second one; the messages of the fitting speak of what the signals need, not of their lights - signal_headers.py warns of a signal map written as a block, whose keys it can't keep * fix(editor): an aspect shown by hand doesn't name a vehicle that may be gone The Show button runs the events of the aspect outside the queue. run() writes the vehicle that set the event off last into the log, and nothing clears that pointer, so a train deleted since would have been read after it was freed. The queue sets the activator anew each time, so it is cleared before the run. * fix(editor): a disc not described is only offered the one that tells, a light stand-in of the mount of the shaped one - A shaped warning disc whose template doesn't say what it repeats may tell all its semaphore shows as well. It is no longer marked as not fitting: the disc described is offered as a hint, and Fit leaves it be. A disc whose template isn't among the scanned, its mount not known, is offered nothing rather than discs of any mount. - A shaped disc chosen for shunting or stop is stood in for by a light template of its own mount first, a dwarf for a dwarf. - The tooltip of the aspect buttons says the trains read the signal as its events set it last, in a run started from the editor too. - The Polish texts of the fitting speak of signals, not semaphores, since it takes the discs too. * refactor: the Sonar remarks on the switch blades taken care of - the big functions of the rails split into helpers with one job each: the carving, the laying and the planning of the rails, their crossings, the blades, the lofted spans of a segment, the profile of a rail measured piece by piece, the joining of the switches - the floating-point loop counters are while loops doing the same additions, so the samples come out where they did - C arrays are std::array, the two sides of the paths path_sides; the ends of a cut are two parts of one struct, ending and starting - the rail laid by a course of its own, not eleven parameters - the globals kept in functions, the nested ternaries taken apart, one declaration per statement, explicit captures, ranges algorithms, std::format, std::numbers, emplace_back, structured bindings - the region finds the sections around a point into a list the caller gives, so the search for the rails around a track shares no list with another thread - check_rails and create_track_rail_profile are const, the pool of the reused chunks can't be copied The geometry of every chunk of lk357 and td_fog, with the frogs on and off, comes out the same as before. * refactor: the Sonar remarks on the 3D sleepers taken care of - the big functions of the sleepers split into helpers with one job each: the clusters and the lines of timbers, the gaps under the rails, the models and their parts, the check of the layout, the drawing of the timbers in instanced batches - the tracks near a track found into a list of their own, the region searched into a list the caller keeps, not the one the region shares with the main thread; the callbacks are templates, not std::function - the layout of a cluster takes a span of its tracks - the globals kept in functions, the parts of a beam int constants, beam_overhang no longer hidden by a field of the same name - scoped_lock, jthread, contains, ranges algorithms, std::format, emplace_back, structured bindings, explicit captures, upper-case literal suffixes, one declaration per statement - the uniform buffer takes a span of bytes * fix(editor): the editor core builds with GCC again - kCrossoverStraights is constexpr, so the connection curve can take it into a constant expression; GCC refused a double that was only const there. - the track_hover alias inside editor_mode dropped: declared after hovered_track had already used the name, it changed what the name meant in the class (-Wchanges-meaning); the definitions name the shared track_hover. - <cstring> included where the rail self-test uses std::memcpy, which MSVC reached through other headers. * refactor: the second round of Sonar remarks on the switch blades - the carve of a throwable part takes the cut before it only where there is one, as only that cut makes it throwable - the splitting of a grooved profile by the floor of its groove moved out of the rail layer into a class of its own, which is given the profile, the size of the rail, the texture of the plates and the side - the rail drawing is made by a const function - the triangles of an ear-clipped outline go in as the arrays they are, the search for a corner within an ear is an any_of, the loop pruning thin corners keeps the count it started with, as it stops at the first - the bytes of the blocks of a texture are taken off the file through its buffer, with no cast of their storage - the log of a carved part takes the tracks around it as a span - the joint length of a switch, a constant, isn't captured, and the directions at the ends of a crossroads are tested in one condition each * refactor: the Sonar remarks on the tutorial - the window of the tutorial in smaller pieces: the steps reached, the lesson followed and its clip, the clip or the sketch of a lesson, its keys and steps, the button under it and the buttons of the pages; the lessons are a table of their own, the button of each kind of lesson picked from a switch - a clip whose delays add up to nothing shows no frame instead of dividing by them - the frames of a clip are decoded by a function of their own, on a thread kept with them and joined once it's done, or as the editor closes, instead of a detached one - the sleepers of the signal sketch counted by a whole number, the texts of the sketches made by std::format, their points kept in std::array, the whole numbers turned into floats where it's meant * fix: the bugs and vulnerabilities Sonar found in the editor core - the loops stepping along a track, a curve or the view count their steps by a whole number and take the station as so many steps from the first, instead of adding a fraction up, which drifts - the self-test of the guard rails keeps the plan of the rails of the track against while it goes through them: the range of the loop was in a plan made for it and gone before the loop began - the generators of the self-tests and of a unit test are seeded on purpose, so a run can be repeated: marked for Sonar as such - the tool writing the descriptions of the templates takes the names out of its tables only where they stay in the data folder * fix: the loops of the signalling stepping by a whole number the places of the block signals along a line and the marks of the chainage under the plan of a station are counted by a whole number and taken as so many steps from the first, instead of adding a fraction up, which drifts; Sonar took the counters of floats for bugs * refactor: the checks of the signal heads and the signal sheet in smaller pieces the remarks Sonar made on the signal descriptions: the warning about a disc on the mount of a signal is worked out by a function of its own, the fit and the aspects of a head, the swap of a template and its aspects in the sheet of a signal are drawn by members of their own, the walk over the events of a signal is a free function instead of a std::function held by a lambda, and the description of an include is read a part at a time; the names of the kinds are kept in a std::array and looked up by the algorithms of ranges, a name is taken as a std::string_view where it is only compared, and the locals named event, which hid the enumerator, are renamed * style: a space after a comma in the join self-test * style: a space after the question mark in the terrain sketch * style: a space after the question mark in the status of the fitting * refactor: the last Sonar remarks on the small fixes the opening of a scenario catches the exception the scenery throws when it can't be read, not any runtime error; the vehicle moved between trainsets keeps its source by a reference to const; the messages of a track of an unknown type and of a tributary are raw string literals; the parser opens a file by a std::filesystem::path, and the log of a file it can't open still names its folder and its name * refactor: the crossings of a track found without casting its const away the radius of a node can be read off a const one: radius_() is const across the nodes, the ones of the tracks and the models marked override, and a const radius() gives the radius worked out already, or works it out anew without keeping it; the helpers finding the crossings of a track only read it and take it const, its own run of rails typed apart from the ones of the tracks it crosses, which the crossings found name; the triangles of a filled outline are pushed as named corners * refactor: the paths around a track sampled without casting its const away the sampling of the paths and the clusters of tracks laid together only read the tracks, so they take and keep them const: the path sampled points at a const track, the tracks near one are found from a const one by its const radius, and a cluster holds const tracks; the shared zones of the timbers no longer cast the const of their track away * fix(editor): the Sonar blocker remarks on the stack, no side effects in the operands of && and ||, no local named final (S912, S1669) Counting the leftover signals, the pieces of a station walk, the places with nothing beside a run and the joints and fouling points logged by the self-tests no longer counts inside a condition; the last span of a straight is named tail. The counts and what they log are the same. * revert(vehicle): an axle on a switch follows the switch as it is set, as before the stack The axle kept to the path it came on, so a switch thrown under a moving train no longer sent the rest of it onto the other branch, and coming from the frog end it trailed shaped blades only where the wheels reached them. That changed the running of every switch in every scenery, and the AI still scans its route by the switch as set. TrkFoll is as on master again, and the trailing point of the blades it used is gone. * revert(track): a path is told a straight by its first control vector alone again, as the sceneries are made for A plain track was drawn bent where its second control vector was off the chord though the first lay along it, and a path with a radius given was never straightened. Tracks of existing sceneries drawn straight before would have been drawn bent, with their length, cant and the models along them. TTrack::straightened is the rule of master, for plain tracks and the paths of switches. The editor keeps a bend dragged with the second control vector, or set by joining the tangents, by moving the first one 2.5 cm off the chord to the side of the bend, past the tolerance, so the track is drawn, saved and read back bent, by older builds too; the second one dragged back along the chord takes the first one back onto it. * feat(track): the switches joined directly to other switches at load told in the log A switch right after another one is joined to it as the sceneries load, where its end was left open before and vehicles came off the track there. Each switch joined so is logged with its place and the number of ends, and the whole number once, so a scenery can be checked for places that run differently now. * fix(editor): a bend kept by lengthening the first control vector, not turning it keep_bent moved the first control vector 2.5 cm sideways, which turned the start tangent: a kink of 0.29 deg on a 15 m track, flagged by the joints check, and against the fixed direction at a switch or a locked track. Now the vector keeps its direction and gets 2.5 cm longer than a third of the chord, which the simulator no longer takes for a straight. It is also applied after an end is moved or snapped, since a new chord or a snap onto a neighbour could bring the vector back within the tolerance. With the second vector back on the chord, the first goes back to a third of it. * fix(track): each switch joined directly to another one logged with both names join_switches counted ends, while one join links both switches, and only the first switch of a pair was named. It now returns the switches joined to, and the log names both of each joint and gives the number of joints. * fix(editor): a path drawn bent is kept bent through every edit, one drawn straight is left as it is The first control vector is made longer past the 2 cm tolerance only where the path was drawn bent before the edit, or where the edit itself sets the second vector: the end of the path moved, its first vector, its second one, a neighbour followed or its grade taken, the controls aligned at a joint, an end snapped. A path drawn straight keeps being straight when its ends move, and the paths of a track that the edit doesn't bend aren't changed. Moving the second vector back along the chord takes the first one back to a third of the chord where it was made longer here. * fix(app): a scenery that can't be opened takes the game back to the launcher whatever the file system throws Catches std::runtime_error again, as master did: invalid_scenery_exception is one of them, and so is what the file system throws while the scenery is opened. * fix(track): the beams worked out in the background don't read the ends a switch is set to The ballast a switch trackbed takes is asked of the tracks joined to its main path, as the trackbed is made at the load, not of the ends the switch is set to now, which change as it's thrown while the thread runs. What the thread reads with no lock against the main thread is written down where it runs, with the two things driving can change: a switch thrown and a turntable turned. * perf(render): the cut faces of a track drawn with nothing put on the heap, a track with none passed over at once * chore(track): the switch drawing the cut faces in the unrolled material read only in the builds with the self-tests * docs(track): the blades flag said to be switched on, and what frogs in eu07.ini changes of it * fix(editor): a response over 64 MB is refused, curl kept to http and https, the address read as UTF-8 The body of a map or of a service the user typed is read into memory up to 64 MB and fails above that, with WinHTTP and with curl. curl follows at most 10 redirects and only to http or https. WinHTTP gets the address widened from UTF-8, so a pasted one with letters past ASCII isn't turned into garbage. * fix(editor): only the orthophoto an older editor kept is deleted from the settings folder, not all its cache The geoportal folder of the old cache is removed, and the cache folder itself only where nothing else is left in it. * fix(editor): the square metre of the outlined area written as its UTF-8 bytes, shown right where /utf-8 doesn't reach * docs(track): why the velocity read for a switch is put back after its segments are made * fix(track): the blade tips and the open ends of a track take the dark of the rail, not the colour of a worn tread No wheel runs over them, so their cut faces aren't drawn as worn: the beige the matte material gives a worn face is left to the cut faces of the frogs. * fix(editor): a neighbour followed or given its grade is bent only where its second vector really changed follow() and follow_grade() write the second vector of a track joined at its end back as it was when the joint didn't turn or keep its grade; a track the simulator draws straight with that vector off the chord was made bent then, though the edit never touched it. Its first vector is lengthened now only where the path was drawn bent or the second vector took another direction or grade. * fix(track): the open ends of a track laid with cuts take the dark of the rail too The rails a frog or a crossing cuts are laid piece by piece; the caps of their pieces at the open ends of the track were drawn worn with the cuts of the frogs. They aren't worn now, as the open ends of the other tracks. * fix(editor): a neighbour drawn straight is bent only where the edit took its second vector off the chord follow_grade() sets the height of the second vector anew on every graded joint, a fraction of a millimetre off the height the scenery has, so a change of the vector bent a track whose second vector stood off the chord sideways already, though the simulator draws it straight. follow() and follow_grade() keep a path drawn straight bent now only where its second vector lay along the chord before the edit and stands off it after; a path drawn bent is kept bent as before. How far the vector stands off the chord is measured in one place, keep_bent() uses it too. * docs(editor): the comment of keep_bent above keep_bent again, not above the measure of the chord * Editor: signal reads kept by the signal, level crossing discs, signals out of the gauge, indicators, the signalling tools split (#307) * fix(editor): the read of a signal stays by it as its track is split, on a switch and when it is moved, and a level crossing disc is placed The trains find a signal by its read, a passive event in a list of the track, and measure the way to the cell it reads along three tracks further at most. The editor let the read drift away from the signal, or put it where trains of another path read it. - A track split in two: a read the trains scan for (a passive event) goes to the piece by the point it reads, whatever its list; before, those of the runs towards the end stayed on the first piece. Five splits left the reads of A, B, C and J on the first piece while the signals stood on the sixth, out of the reach of the trains. The reads of signals placed since the scenery was opened, not bound to an event yet, go to the piece by their signal the same way. - A signal moved off its track jumped back to that track's end once the track was changed: the track had taken it up as its object and measured it again along itself. A moved signal is let go by the track it stood by, and an object of a single point moved off the side of its track no longer follows it. - A switch reads its events to the trains of both its paths. A signal past the frog of a path, where the axes are a gauge apart, is passed by the trains of that path only, so its read goes to the track joined to the far end of the path, in the list of the trains running from the switch onto it or the other way. Before the frog it stays on the switch. Moving the signal across the frog takes the read between the two. - A signal by a switch on the side of its other path stood on that path, in the way of its trains (0.45 m from its axis); it is refused there, placed or moved, with the reason. - The kind crossing of the descriptions (tsosp, tsospn) is known: the level crossing disc is listed in the palette and placed with its read. Checked in the editor on a hidden desktop: five splits of a track with bound and fresh reads, a signal moved to another track and the old one raised, signals placed before and past the frog of a switch on both paths, turned and moved across the frog, saved and opened again with the reads bound, the tracks raised, shifted and bent with the signals following. Unit tests pass. * fix(editor): a split keeps reads far off the path and bound objects up to 30 m by their pieces A read the trains scan for moves to the piece by the point it reads only from event1 and event2, only when it isn't ignored and only when that point is within 50 m of one of the pieces; a read at the station building stays in its list. An object bound by hand keeps its binding as its path moves up to 30 m from it, an adopted one up to 12 m as before. * feat(editor): the tracks that read a signal are drawn and can be picked, flipped or dropped The selected signal shows each read of its _sem_info as a thick band over the reading track, arrows in the way the read is scanned, a line from the foot of the signal and a plate with the list and the track; the hovered one shows them thinner and placing or moving a signal shows where it will be read. The panel lists the reads: each can be turned the other way or removed, "Pick the path" takes a click on a track (with Shift one read more or less) and "By the path it stands by" puts back the read the signal gets when it is placed. Each change is one step of the undo. The self-test gets signalread, signalreadflip, signalreaddrop and signalreaddefault, and the probe lists every read of a signal. * fix(editor): a moved or turned signal keeps the reads picked by hand, and a read set again isn't an undo step Moving a signal, taking it across the track or turning it put back only the read by the track it stands by and dropped the others: those stay on their tracks now, on the other list when the signal is turned. Setting the reads the signal has already says so and adds no step to the undo. Picking a reading track disarms the template, so a click after Esc doesn't place a signal, and the signals are listed again after any change of the history, also once it is full. * feat(editor): a signal is placed out of the gauge of the tracks around it As a signal is placed, moved, taken across or turned, its models are measured against the gauge chosen in the Gauge window along every path near it. One that enters it is taken sideways, away from the axis of the track whose gauge it enters, as deep as it went in and 3 cm more, in the same step of the undo; between two tracks too close for it, it stays where it was put and the status tells which gauge it enters and how deep. A gantry is only measured. The panel of the selected signal tells when it stands in the gauge, with a button to move it out, and the view marks the deepest place. The gauge tool measures any models against the paths around them for it. The self-test places a signal at a given offset and its probe tells the gauge. * fix(editor): a moved signal leaves only the read of the track it stood by, and the gauge is checked on its level The reads a moved signal keeps were all but the first one listed, which is the first track of the scenery having it, not the one the signal stood by: a read picked by hand could go and the track it left could keep it. It is the read of the track it stood by that goes with it now, and turned, eventall1 and eventall2 swap as well. A track more than 2 m above or below the foot doesn't push the signal aside, the status tells the real distance it went, the gauge is measured again when the signal follows a dragged track, and the marker in the view shows only what is up to date. * feat(editor): indicators put on a signal from the panel, they move and go with it The indicators of scenery/pkp/wskazniki described as "category: indicator" are offered under the selected signal, grouped by their sign. One is put in as an include named after the signal, on the srk layer: - a lit one (place: head) under the lowest lamp of the signal, 0.73 m below it and 5 cm ahead of the mast, each next one 0.45 m lower; a dwarf signal is refused, it has no mast for one; - a plate (place: foot) at the foot of the signal, its model has its place by the mast built in. The panel lists the indicators standing by the signal with a Remove button. They are found as the includes whose first parameter is the signal's name, within 1 m of it in plan. When the signal is flipped, turned or moved, they keep their place in its frame, in the same undo step; deleting the signal deletes them too. If the signal and the indicator both define an event, the status says so, since the scenery keeps only one of them. The self-test gets signalindicator and signalindicatordrop, and its signalprobe gives each indicator's height and the height of the lowest lamp. * feat(tools): indicator descriptions and the indicators taken out of the signal templates indicator_headers.py writes //$e descriptions into the LED indicators of scenery/pkp/wskazniki (W19, W20, W21, W24, W26) with the events each shows. It also makes the indicators that were so far only built into the signal templates: - W1 of the warning discs, new, old and with the light strip; - W1 and W18 (new and old) of the block signals; - the I, II and III plates of the repeaters. The plates fixed flat to the mast are moved 4 cm ahead. Their back is 5 cm from the mast's axis, while the mast is 6.1 cm thick and its clamp under them 8.3 cm, so the mast went through the plate, in the templates too. * fix(editor): a signal turned or moved by the gizmo is read and kept out of the gauge, its indicators go with it everywhere The gizmo of an include only rewrote the numbers of a signal. Its read stayed on the event it had, even when the signal was turned to the trains of the other direction. Its indicators stayed behind, its height could be dragged off the ground, and the gauge wasn't checked. Now: - the gizmo moves a signal in the plan only, at the height it has; - while it is dragged, its indicators keep their place by it; - once it is let go, the drag is made again as a move of the signal tool, one step of the history: the read goes to the event of the trains it faces on the path it stands by, and it is taken out of the gauge; - dropped away from every track, it goes back where it stood. The indicators of a signal are found in the scenery now, not in the list the signal tool keeps up only while it is open: - deleted from another tab, the signal takes them with it; - a signal renamed in the node properties gives its new name to them in the same step of the history; - in the station and line batches, a renamed signal renames them, and a removed one removes them; - the binding of objects to tracks puts them on the path reading their signal, not on the one nearest to them, and a signal moved by hand lets go of them too. Also: - a signal on a gantry takes no indicator from the list; - an indicator a signal has already isn't put on it twice; - the signals and their indicators are found in one pass over the includes, the indicators by the name of their signal; - a step of the history with tracks is always one of their edit, so they are taken back with the includes. The self-test gets signalgizmo, which turns and moves a signal as the gizmo does. * fix(tools): indicator_headers.py keeps the files it replaces, writes beside the data on request - An indicator it made, found changed, is put into a tar in editor_backup before it's written again. - --sidecar writes the descriptions of the lit indicators into editor/templates, as the other header scripts do, the files of the game left alone. - The indicators it makes are copies: the signal templates keep their own, and the docstring and the files say so. * fix(editor): a signal moved by the gizmo by another track is read by it, the templates known without the signal tool - At the end of a gizmo move the nearest track takes the signal when it is nearer than its own by more than 0.5 m; a track it was dropped onto, within 1.2 m of its axis, doesn't, so a signal only turned between two tracks or dropped onto one in a switch keeps its own. - The signal templates and indicators are looked for when a signal is renamed or its gizmo shown, so its indicators follow without the signal tool opened first. - A drop refused puts the gizmo and the node properties back where the signal stands. - The indicators follow only once the gizmo made its step, and the ones not changed are left alone: grabbed and let go it changes nothing. * fix(editor): a signal dropped by the gizmo onto a track keeps its own, the gizmo doesn't wait for the template scan - When the nearest path to the drop is within 1.2 m of its axis, the signal keeps its own track, instead of only that path being left out: dropped onto a middle track it no longer goes to the track beyond it. - The gizmo starts the signal template scan without waiting for it, so a rescan with a signal selected doesn't stop the editor; renaming a signal still waits. * feat(editor): the signalling split into Signals, Station, Station signals and Line block The one Signalling tool held the signals placed by hand, the whole wizard of a station and its checks; each is now a tool of its own in the toolbar: - Signals (I): the palette, a signal placed by a track, dragged along it, selected; a click on a switch no longer opens a station. - Station: LMB on a switch lays the station out; its name, code, line, km, speed and braking distance, the numbers of the switches, the track circuits, the number of the selected track, the list of the switches. - Station signals: the signals of the whole station placed at once, the template of each of their kinds (main, shunt) chosen in a table, and below what the signalling lacks: the repairs, the SHP resonators, the track lengths, the signal heads. - Line block: the block of each line, the block boundaries drawn by hand, the line signals, the templates of the block signals and warning discs. The station tools share the open station and its schematic; Station signals and Line block show what the Station tool set for it, the line and the km in red where the line block needs them. The template table replaces the palette in the station tools, so choosing a template there no longer arms placing. Two icons drawn for the new tools, in editor_icons.py too; the png is drawn by the same shapes, Pillow wasn't at hand. The tracktab self-test takes a tool by its name, and srkopen shows the Station tool. * feat(editor): a signal shows its distance from the track axis and to the switch ahead, and goes to 50, 100 m... from it - editor/editorTrackTrace: the track followed the way a train runs, shared by the W17 markers and the signals. The fouling point of a switch (where the axes of its tracks are 3.5 m apart) moved here from the lineside tool, and danger_ahead finds where a train first comes to a switch: the start of one it runs onto from its start, or the fouling point of one it runs onto from behind, which may lie behind the point (a signal in the fouling zone). - The card of the selected signal: its distance from the axis of its track, and along it to the start or the fouling point of the switch ahead, in red when it stands inside the fouling zone. The overlay draws the same as a dimension line beside the track on the side of the signal, with the distance at the place. - Placed, dragged along or moved with the gizmo, a signal goes to a round distance to the switch ahead (50 m steps) when within 2.5 m of one; Alt keeps it where it is. The drag of a new one is measured from where it was pressed. - The fixes of the review of the split: the click label of the station tools in their own branch and a plain select in Signals, the card of a signal picked from the check lists shown in Station signals, and the help texts naming the Templates table and the Signals tool. - Self-tests: signalprobe logs the distance from the axis and to the switch ahead, signal snap=1 snaps as placing does. * feat(editor): the fouling point widened in the curves under 250 m, as the standard of the gauge says Standardy techniczne PKP PLK, tom II (from 2025-07-17), 6.5-6.6: the W17 marker stands where the axes of the tracks are nominally 3.50 m apart; where one of the tracks lies there in a curve under 250 m that spacing grows by the widening of the gauge from its radius (annex 1, table 1), the widenings of both summed when both lie in curves. - editor/editorFouling: the fouling point found along the axes of the main track and the branch, standing on its own: at each point of the branch the spacing wanted is the nominal one plus, for each track, the widening on the side of the other track from its radius there (taken over 5 m each way): 50000/R - 185 mm towards the centre of the curve, 60000/R - 225 mm away from it, none from 250 m up. - gauge::curve_widening gives table 1 of the gauge the editor checks already. - The W17 tool and the distance of a signal to the switch ahead both use it; the card of a signal shows how far apart the axes are at the fouling point, the help of the W17 tool says where the figures come from. - Unit tests: a straight branch at 1:9, a branch in a curve of 300 m (no widening) and of 200 m (outer widening), both tracks in curves (both widenings summed) and a straight branch off a curving track. * feat(editor): the cant leans the cars into the fouling point, and the fixes of the review of the metre - The fouling point takes the cant in, as Ie-1 wants it placed "with the gauge, the cant and the widening in the curves": the cars of a track on a cant lean towards the inside of its curve by D Hi / 1500 (bD of table 1 of the standard of the gauge), so when the other track lies on that side the spacing wanted grows by it, taken at 3.05 m over the rail top, the top of the widest part of GPL-1. The cant of each point comes from the roll of its path as the gauge tool takes it. At any radius, as the table has it; the track leaning away adds nothing. - Below 150 m, where table 1 ends, the widening from the radius is that of 150 m rather than the formula run on. - A switch run onto from behind has its fouling point looked for once its own path is walked too, so one lying on that path is found rather than skipped for a farther switch. - A point behind a signal lies on the track of the farther end of its segment, so a signal snapped back over a joint lands at the round distance rather than at the joint. - Alt keeping a signal off the round distances reads the key from ImGui, which Global.altState misses while ImGui holds the keyboard. The gizmo doesn't snap a signal:a1d10bb0says it does, it's placing and dragging with the tool only. - The help of the distance on the card stays on the distance, the spacing of the axes under it. The unused track_trace::nearest_on is gone. - Unit tests: the cant leaning towards the other track in a curve and at 300 m, nothing when leaning away, and the table ending at 150 m. * fix(editor): the cars lean the way the cant of their track tips them, taken 3.25 m up - The cant along the trace keeps its sign: a roll above 0 lowers the left rail of the path (as the editor lifts its terrain by it), turned to the way the track is walked. A track adds the leaning of its cars to the spacing wanted at the fouling point when the other track lies on the side its lower rail is, whichever way it curves: a branch on a cant against its own curve leans towards the main track on its outer side, whichd70f189cmissed, and a cant on the straight counts too. - The leaning is taken 3.25 m over the rail top, the top of the widest part of the cars, rather than 3.05 m of GPL-1. - Unit tests: a cant against the curve, a cant on the straight, and the leaning away still adding nothing. * fix(editor): the station tools tell by the mouse what a button came to, and the fields of a station read as empty What a button of the Station, Station signals and Line block tools came to was written at the foot of the panel, under the lists, scrolled away: a click which refused for want of the code of the station looked as if nothing happened. It's told now by the mouse which clicked, a refusal in red as the other tools do, and in the status bar. The fields of a station still empty show their examples as such, "e.g. BPd", not as values typed in; the Station tool says above its steps that the code is to be typed first, Station signals that the code and the track circuits are wanted, the code marked there as needed. The check of a warning disc and of a block section went by the braking distance of the station, while Set the line signals places them by the one of their line: on lk357 a disc placed 700 m before Z, the line run at 100 km/h, was marked as standing nearer than the 1000 m of the station. A signal of a line out is checked by the braking distance of its line now. * feat(editor): the joints of the track circuits put, moved and taken away by hand, kept by the station The Station tool gets Edit the joints by hand: LMB on a plain track of the station puts a joint there, LMB on a joint takes it, then on a track moves it, on it again takes it away. The circuits are set again at once, one step of undo each. The joints so changed are kept in the //$s record of the station (joints +x/y/z for one put, -x/y/z for a planned one taken away), so Set the track circuits keeps them; As planned forgets them. The undo step carries the hand joints of the station with the tracks. srkjoint drives it in the self-tests. * feat(editor): the indicators under the lights reordered, a signal set from the axis and raised, standing on the ground by default The indicators under the lights of the selected signal get arrows up and down: one changes places with the indicator above or below it, a plate at the foot keeps its own. One step of undo each. The distance of the selected signal from the axis of its track is typed in the panel, it moves across as far along the track as it stands, the gauge pushing it out again where it comes too near. Its height is set the same way, raised over where it stands by default, over the rail heads on a gantry. A signal is put on the ground by default, the zero of its model 0.38 m under the rail heads: the ground lies 0.35 m under them as Ie-102 draws it (Lx), the foot of the mast stands on the foundation 3 cm over it in the models of pctga, and the sceneries made by hand (Wrzosy, Baltyk) stand their signals 0.20 m under the rail foot so. It stood on the rail heads. signalindicatorswap and signalacross drive it in the self-tests. * fix(editor): the hand joints of a station without a record, of its ends and of another station; a dragged signal keeps its place across and its height - Edit the joints by hand on a station not described yet read the record of index -1: the hand joints are shown only for a station with one. - The joint between the station and a line out of it can't be taken: taken away, the circuit of the switch ran on over the tracks of the line. - A joint held is let go when another station opens, a move by less than half a metre lets it go, and a change no step of the history takes is undone, so the undo knows every change of the joints. - A signal dragged or snapped along its track keeps its distance from the axis and its height over the default, set by hand or standing so before. * fix(editor): a dragged signal carries what it had by its own track; As planned forgets the hand joints that change nothing The distance from the axis and the height of a dragged signal were taken against the track it was dropped onto: dropped on the next piece of its line, on a grade or by a parallel track it came out too far, in the gauge or off the ground. They are taken as it stood by its own track at the start of the drag. As planned clears the hand joints even where the circuits come out the same. * fix(editor): a signal stands as high over the rail heads as its include gives, lowered only where its bottom would hang over the ground The default height of a signal was 0.38 m under the rail heads for every model. It is now read from the description of its include, `//$e signal: {..., height: <m>, depth: <m>}`: height is where the zero of the model stands over the rail heads (by Ie-117 § 15 the top of the foundation of a mast 0.10 m under them, of a dwarf 0.20 m), depth how far the model reaches under its zero. With a depth, a signal whose bottom would hang over the ground, down an embankment, goes down onto it, by at most 3 m (more is taken for a bridge). Without a height the zero stands at the rail heads. "Raised" in the panel, a signal moved across or dragged, all count from that default height. * fix(editor): a signal flipped, given another template or its variant for the other side stays as raised as it was The default height now depends on the template and on the ground under the signal, so keeping the height as it was no longer keeps the raise. Flipped to the other side of the track, the signal is raised over the default there as it was over the default on its own side. Given another template (Swap), or the variant of its template for the other side when moved or placed, it goes up or down by how much the default height of the new template differs from the old one. * fix(editor): As planned forgetting hand joints that change nothing is a step of undo of its own With nothing in the circuits to change no step of the history took the forgotten joints, so they went with no undo for it: Ctrl+Z took back the step before. The anchor of the station as it is now carries them in a step of their own. The signalmove selftest gets its carry indented with the block it is in. * feat(editor): an indicator under the lights goes in its place by Ie-117, from the top W21, W24, W20, W19, W26 Put on a signal, an indicator under its lights was put below the ones there. It now goes in its place by Ie-117 section 12.1 among them, under the last one it doesn't go above, the others (W18 and the rest) below these; the ones under it move a place down, in the same step of undo. * fix(editor): the signal card and the move of a signal keep no pointer across a refresh of the signals - The card of the selected signal went on after "To the other side" or "Turn around" with found pointing into the list of the signals standing, which their refresh had just replaced: the indicators and the gauge of the card read freed memory. It now ends that frame there. - signal_move_to read the mount of the template after the refresh, which may scan the templates again; it is taken before it. signal_place takes a copy of the template given for the same reason. - The fouling test counts its metres with an int, and the search of the middle point of the radius is a while loop (no floating loop counter). * fix(editor): the dimension line to the danger point counts its metres with an int (Sonar S2193) The line drawn by the track from a signal to the switch or fouling point ahead stepped a double by 1 m. It now counts the whole metres with an int from the same first one: the points are the same, since adding 1 to a whole double and adding a whole int to it give the same values. --------- Co-authored-by: maj00r <maj00r@host> * feat(editor): ride the camera along the tracks, and a minimap with stations by their W4 (#317) * feat(editor): the camera rides along the tracks, over the joints and switches and over to the tracks alongside Y puts the camera onto the track under the cursor (or the nearest one), looking along it 3 m over the rails. W/S drive it ahead and back the way the camera looks, Shift and Ctrl faster (20, 60, 250 m/s); A/D take it over to the track alongside, a click to any track; E/Q and the wheel raise and lower it; the mouse looks around as when flying. At a switch entered from its blades it goes straight on, Z picks the turnout for the camera alone: no switch is thrown, no track learns of the ride. The bar over the view shows the track, the km, the speed, the height and the switch ahead. Y or Esc ends it. Self-test commands ride, ridewalk, ridejump, rideahead, rideprobe and rideleave. * feat(editor): a minimap of the tracks with the camera on them, and the stations found by the names of their W4 View / Minimap and stations (W4), Ctrl+M: a window with the rail tracks seen from above, the camera as a triangle the way it looks, the track ridden along in orange and the stops of passenger trains as dots with the names of their stations. It follows the camera, or is dragged and zoomed apart from it; a click takes the camera there, riding along the track onto the track there. Above it the stations the PassengerStopPoint memory cells and events name, searched by a part of the name with or without the polish letters; a click (or Enter for the first found) flies the camera over to the stop looking along the track, riding it rides on from there, each click to the next W4 of the station. Self-test commands minimap, stations, station and minimapclick. * fix(editor): the ride and the minimap after the review, with fewer words on the screen - Ctrl+S, Ctrl+Z and the other shortcuts reach the editor while riding; Esc closes an open popup first - no key stays held when a window takes the keyboard, the place is kept within a path that got shorter, a release of the mouse goes where its press went - the minimap keeps under the vertex limit of a draw list, Enter in the search goes round the stops of the station, the marked station stays marked - the bar of the ride is one line: the track, km, speed and height; the switch ahead under it, the keys only while standing - the minimap in the Map menu, opening over the view, with short texts; the context menu of a track rides along it * feat(editor): the ride drives with the right button held, as the camera flies, and the editor works on along it - W/S, A/D and Q/E drive the ride only with the right button held; without it they're the editor's keys again (Q/W/E the gizmo) - the left button and Esc go to the tools while riding: tracks and objects are laid and selected from where the ride took the camera; Y leaves, a flight of the camera to a framing leaves too - after the review: the help names Ctrl+W/Ctrl+Down as the much faster drive, the stops of the minimap stay within the vertex limit, the search field lets the keys go after Enter * fix(editor): the tools keep their wheel and the menu of a track its click while riding, a pan or the view from above ends the ride --------- Co-authored-by: maj00r <maj00r@host> * feat(editor): signals placed by the editor get a name plate drawn by python (#316) * feat: Elf emergency brake position in the master controller (eu07/maszyna#413) The Elf's master controller (EIMCtrlType 2) gets an optional emergency brake position below its position 0, turned on by the new .fiz key EIMCtrlMainEmergency=Yes in Cntrl (default No, no change without it). With it the old positions move up by one (MCPN 5, neutral at 4): the emergency position brakes fully at once and vents the brake pipe, like the alarm chain or the Impuls's EIMCtrlEmergency. The loader raises a too small MCPN to 5 and logs it. The Elf code with hard-coded positions (CheckEIMIC, the MED full braking, the AI) takes the shift into account. SVN data to change afterwards (dynamic/pkp/elf_v1, needs this exe): - every .fiz with EIMCtrlType=2: EIMCtrlMainEmergency=Yes, MCPN=5, DirChangeMaxPos=4 where present; - the cab .mmd mainctrl entries: offset one notch lower (-0.06 -> -0.09), sounds shifted one index up, new sound0 with 26284_elf_nastawnik_nagle_*.wav. Issue: (eu07/maszyna#413) * fix: Elf emergency brake position vents the pipe only from the driven vehicle, coupled units agree on the controller position The emergency position of the master controller vented the brake pipe from every vehicle whose controller stood there, and "MainCtrl" reached the coupled vehicles raw, so an Elf with EIMCtrlMainEmergency and one without it disagreed by one notch (the full braking of one was the emergency brake of the other, neutral of one a power position of the other). The pipe is now vented only from the vehicle driven from (IsCabMaster()), and the position goes to the coupled vehicles in the positions without the key (MainCtrlPosForCoupled(), the emergency one as the full braking), each adding its own shift on receiving it (MainCtrlPosFromCoupled()). The loader's fix-up for the old MCPN=4 raises DirChangeMaxPos by the same shift, so the reverser keeps working at the new neutral. * feat(editor): the signals the editor places get a plate with their name, drawn by python A signal placed with the signal tool used to get the plate texture of textures/tabl named like it, or none at all. Now, unless a texture is picked, its plate is made by python/local/signal_plate.py: "make:signal_plate?name=<name>", a light plate with a dark edge, four screws and the name in black, the way the plates of textures/tabl look. Renaming the signal in its properties renames a drawn plate with it; a picked texture stays. The templates put the plate after a folder, "tabl/(p6)", so material_data::assign() takes the folder off a skin which names a texture made by a script. * fix(editor): a drawn signal plate keeps following a cleared name, and isn't made for a name it can't carry Clearing the name of a signal in its properties made its plate the drawn plate of no name, which then never followed the name again. A drawn plate now follows any rename to a name, and keeps the last one while the name is cleared. A name with '|', '&' or '?', or one longer than 64 characters, gets no plate (0_nothing) instead of a broken one: '|' splits the skin, '&' and '?' the query of the script, and a very long name made a path too long for the file system when the skin was looked for on the disk. * fix(editor): a signal plate keeps its last name through a name it can't carry, and a plate named by hand stays Renaming a signal to a name its plate can't carry turned the drawn plate into 0_nothing, and it stopped following the name for good. Such a name now leaves the plate with the last usable one, like a cleared name does, and the plate follows again once a usable name is typed. A drawn plate whose name was given by hand, different from the name of the signal, is no longer replaced on a rename: only the drawn plate of the signal's own name follows it. * feat(editor): the drawn signal plates come in three looks, plain, toned and aged The plate drawn by python/local/signal_plate.py looked too clean. It now takes a look in its query, "make:signal_plate?look=toned&name=Tm12": plain is the bright plate it was, toned a greyish field with a little grain and dust towards the bottom and the sides, a thinner edge, smaller screws and graphite letters, aged a darker, grainier and dustier one. Toned is drawn when no look is given. The signal tool picks the look under the plate, kept in the settings of the editor. A rename of the signal in its properties keeps the look of its plate. * perf(editor): the grain and the dust of a drawn signal plate are made on whole images The toned and aged plates shaded their field a pixel at a time in python, about 34 ms a plate with the interpreter held, so a station of a hundred signals in view kept the python queue, and the screens of the cabs, waiting for seconds. The dust is now made once per look, and the grain from random bytes of the name, both put on the field with ImageChops: about 2 ms a plate. The mean colour of the plates stays the same; only the grain falls differently. * fix(editor): the station signalling draws the plates of its signals as their schematic names them The plates the station signalling places and renames say what its schematic shows (Tm3, F1, ToA, a block signal without the stem), and a template swapped in for a signal without a plate draws that text too rather than the small letters of the name. A signal left for removal gets a plate of no text again, not one saying "_old". No plate, 0_nothing, or the texture named like the signal, what the editor gave before the plates were drawn, become the drawn plate when the signal is renamed, in the properties panel as by the station signalling, in the look set in the editor. * fix(editor): a plate of a scenery named like the end of the name of its signal stays through a rename in the properties A texture pzs_a was given by its scenery as a, its real plate: a rename in the properties panel keeps it. Only the station signalling, which looked its plates up that way, takes such a one for its own. * feat(editor): the drawn signal plates are 256 pixels across, sharp up close The edge, the screws and the blur are drawn bigger by as much as the plate is, and the grain is as coarse as before, so the three looks stay as they were. The smallest letters tried grow with the plate too. * feat(editor): a drawn signal plate takes a speed index and the m of shunting signals, typed in the signal tool signal_plate.py draws the speed index after the name, one digit up at its right or two as a fraction across the height of the letters (index=4, index=12 for 1/2), and with m=1 an "m" on a strip of its own under the name, as Ie-1 marks a semaphore giving shunting signals and as the textures/tabl a-12m plates show it. The signal tool has a field for the index and a box for the m under the look of the plate; the hint of the plate names them (B 1/2 m). The style of a drawn plate, its look with the index and the m, stays with it through a rename, in the properties panel and by the station signalling, which sets neither. The signal selftest takes index= and m=. * fix(editor): the speed index of a plate takes only digits as they are typed The decimal field let in signs and dots, which stayed shown while the index held only the digits, and filled the two places before a second digit could go in. * fix(sonar): the remarks on the drawn signal plates, to pass the quality gate The new code of the plates was 5.2% technical debt against the 5% of the gate. Fixed the small remarks; the big functions stay as they are: - the speed index field and the plate looks are std::arrays, the index is copied without snprintf, the combo of the looks has a function of its own - ranges algorithms, a string_view for signal_plate_drawn, emplace_back - signal_plate.py: dict literals, a cache of fonts not named like FONTS, no unused local, the name and the m drawn by methods of their own; the plates drawn are byte for byte the same as before --------- Co-authored-by: jerrrrycho <jurek.pakula@gmail.com> Co-authored-by: maj00r <maj00r@host> * fix(editor): the tutorial and the hints tell of the kilometrage, and the first lesson takes O either way The kilometrage (X) was in no hint, no shortcut list and no lesson, though the hectometre posts and the block signals are numbered after it. The row of the track tools now reads L T G N U I X B P V J, the turntable with it, and F1 lists I / X / B. The lesson of the signals and the posts says what X does and where the posts take their numbers from, the km of the line or the km typed in their panel for the place clicked, and it opens with the kilometrage tool too. The first lesson asked to switch to the view from above, which a scenery made in the wizard opens in already: O either way does it now. * fix(editor): master's road lifting texts translated, and the panning by the wheel told of in 3D too The merge of master left the status and the label of the lifting of the road points in English: both go through the translations now. Master pans the 3D view by the wheel as well, so the lesson, the hint row and its line say it works in both views. <cstring>, dropped from the road tool before, came back in the merge and is gone again. * fix(editor): the tools of a plain line in sight, the km of a line set once, a lesson of a whole line and of the ride along a track What a layman building a line with signals and posts couldn't find: - The Signals, Kilometrage and Posts tools are in the main row of Tracks, after the tools of laying; the stations, their signals, the line block, the turntable, the trainset and the checks stay behind More. - "Objects" was where the hectometre posts are: the tool is Posts now (Słupki), its hints say the line the posts go along. - The km of a line could be typed in three places that didn't lead to each other. The panel of the posts and the one of a station, where the line has no km set, say the typed km is theirs alone and have Set the km of the line (X), opening the Kilometrage tool; that tool says first that one known point serves the posts, the stations and the block signals. - The hint of the Signals tool says to pick a signal in the list, then click beside a track; with no templates the panel says so in plain words. - A new lesson, A whole line, step by step: the tracks and switches, the km, the station, its signals, the line block, the posts and the drive, with a button to the station tool, and opened with the station tools. - The first lesson shows the ride of the camera along a track (Y, then W S A D and Z) and has it as a step to try. - lang/editor_pl.po: "Restore the terrain" and "Drag an end" were there twice, the second copies are gone. Checked: MSVC build, unit tests 459/459; editor run on a small scenery, screenshots of the toolbar, the new lesson, the first lesson with the ride ticked after Y, the panels of the posts, the kilometrage and the signals. The station panel with no km of the line wasn't seen, the scenery had no station. * fix(editor): the posts open expanded from the trainset, and the Polish of the whole-line lesson reads right B or the Posts button pressed while the trainset tab is shown opens the hectometre posts with their panel expanded. The Tracks area tooltip names the kilometrage and the posts. The station step names the shunting signals, the station button says Narzędzie Stacja, and the ride rows and the lesson list read smoother in Polish. * fix(editor): a bent model is lengthened along the tracks joined to its own, laid along another track after the bending, and set by fewer settings The ends of a bent model have handles in the view: dragged, the model goes on along the tracks joined there, at a switch the way it's dragged to. Its length, a drag of the whole model and a drag of an end all follow the joined tracks; before, they went on straight past the end of the track under the model. The panel of a bent model picks its track: another one picked, the model stays where it stands, a platform turns its edge to the new track and keeps its length. On top stay the track, the length, the offset and the height, bent or repeated, and the platform edge; the reference point, the position along, turned, mirrored, the cant and the gauge widening went under More settings. The buttons of the model's own length and of the whole track are gone: the length field and the handles do it. The links of a model to its tracks are counted anew when its pieces change, undo and redo included. * fix(editor): the bends of straights laid from the end of a curve begin with a straight, not a compound curve In the mode of straights the curve of a plain track's free end no longer goes on into the curve of the first bend as a compound curve. The line comes out of the end's curve by a transition onto a straight, and each bend gets a curve of its own. Only a curve traced in the mode of a curve goes on from the curve of the end, as it already did at a switch. * fix(editor): the bent model keeps its links and its line to what it reaches, and drags without rebuilding at each track - the links of a bent model are matched anew whenever any of its pieces change, not only the first - the line is lengthened by the plan lengths of the joined tracks and built once a round; a drag reuses the line made at its start while it doesn't grow - the tracks of one name are told apart in the track lists, and a deleted track leaves them - the tracks at the ends the copies no longer reach are left out of the line after an edit or a drag * fix(editor): a click on a bent model's handles changes nothing, and the track picked stays picked - the line is trimmed on a drag's release only when the drag changed the model, and an edit that trimming undoes makes no undo step - the track picked for the bending is kept by the track, not its place in the list, when the list is gathered anew * fix(lang): a stray line taken out of editor_pl.po A single "r" between two entries, left by an edit of the switch texts: msgfmt refuses the file with it. * feat(launcher): the range of the aerial photos of a new real scenery given on the map, changed later in the editor (#328) * feat(launcher): the new real scenery gets the range of its aerial photos on the map, changed later in the editor The wizard of a new scenery asked only for the centre; the editor then downloaded the photos around the camera wherever it went, and a scenery had no range of them until one was drawn in the orthophoto settings. The realistic scenery is made in three steps: the name, the place (a click on the map or the place typed, degrees or PUWG 1992), and the range of the aerial photos: a square of 1, 2, 5 or 10 km around the centre, or an area of the user's, its corners clicked on the map. The range is drawn on the map with its size and the number of the tiles, and it's written to the scenery as the download area (//$z), so the editor downloads the photos and the terrain model inside it only. What a beginner gets wrong is told before the scenery is made: the button stays off with the reason under it (no name, the name taken, no centre, the centre outside Poland, an area being drawn or crossing itself), and a warning comes with the centre outside the area, a large area and a centre clicked on the map of the whole country (the map zooms to the place after the first click). In the editor the download area says in plain words what it does, a square around the camera replaces it in one click, and with the camera outside it a note at the bottom of the view says there are no photos there, with the way to the range. * fix(launcher): the range of the photos asked for after the centre, the drawing given up as with Cancel, the square named by its sides The review of the range of the aerial photos found: - with My own area chosen before the centre, the clicks meant for the centre went to the corners of the area: step 3 waits for the centre; - switching to Fictional while drawing dropped the area there was before, and an unfinished one of three corners counted as done: it's given up as with Cancel now, also with Esc; Enter ends it, Backspace takes the last corner back, as in the editor; - the error of a place mistyped stayed after a click on the map; - the largest square was told to be large or not by the rounding: the warning comes from 50 sq km on; - "2 km" read as a radius: the squares say "2 x 2 km", the tooltip how far each edge is; - a place typed with an area of the user's fitted the map to the area, not to the place. In the editor the note of the camera outside the range says the terrain model isn't there either, its button says it opens the settings, it stands above the strip of the profile and the keys of the tools, and it can be closed until the camera is back inside. The squares around the camera want the place of the scenery on the map, and replace an area there is, or start one of 10 x 10 km, only with a yes. * fix(editor): one note of the empty scenery in the middle of the view, the warnings of an area told once it's drawn A new scenery opened in the editor showed two notes of the same over each other in the middle of the view: the panel of the track tools ("The scenery has no tracks yet") and the line of the terrain ("This scenery is still empty"). The line gives way to the panel now. In the wizard the centre outside the area and the crossing edges were told while the area was still being drawn; they're told once it's done. * fix(editor): the note of the camera outside the range of the photos hidden while the camera rides a track Its lines at the bottom of the view are where the camera riding a track writes the next switch and its keys. --------- Co-authored-by: maj00r <maj00r@host> --------- Co-authored-by: maj00r <maj00r@host> Co-authored-by: Hirek193 <polomarket73@gmail.com> Co-authored-by: jerrrrycho <jurek.pakula@gmail.com>
4789 lines
197 KiB
C++
4789 lines
197 KiB
C++
/*
|
|
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/.
|
|
*/
|
|
|
|
#include "stdafx.h"
|
|
#include "rendering/openglrenderer.h"
|
|
|
|
#include "utilities/color.h"
|
|
#include "utilities/Globals.h"
|
|
#include "vehicle/Camera.h"
|
|
#include "utilities/Timer.h"
|
|
#include "simulation/simulation.h"
|
|
#include "simulation/simulationtime.h"
|
|
#include "vehicle/Train.h"
|
|
#include "vehicle/DynObj.h"
|
|
#include "model/AnimModel.h"
|
|
#include "world/Traction.h"
|
|
#include "application/application.h"
|
|
#include "utilities/Logs.h"
|
|
#include "rendering/openglgeometrybank.h"
|
|
#include "rendering/openglcolor.h"
|
|
#include "rendering/screenshot.h"
|
|
#include <imgui/imgui_impl_opengl2.h>
|
|
|
|
int constexpr EU07_PICKBUFFERSIZE { 1024 }; // size of (square) textures bound with the pick framebuffer
|
|
int constexpr EU07_ENVIRONMENTBUFFERSIZE { 256 }; // size of (square) environmental cube map texture
|
|
int constexpr EU07_REFLECTIONFIDELITYOFFSET { 250 }; // artificial increase of range for reflection pass detail reduction
|
|
|
|
namespace {
|
|
|
|
// the top view of the editor shows everything this close to the camera, the corners of the screen included
|
|
float
|
|
editor_ortho_reach()
|
|
{
|
|
auto const aspect{ Global.window_size.x / std::max( 1.f, static_cast<float>( Global.window_size.y ) ) };
|
|
return Global.EditorOrthoExtent * std::sqrt( 1.f + aspect * aspect ) + 500.f;
|
|
}
|
|
|
|
float
|
|
editor_track_view_range(float const Range, bool const Apply)
|
|
{
|
|
if( false == Apply || false == Global.editor_tracks )
|
|
return Range;
|
|
float extra = 50000.0f;
|
|
if( Global.EditorOrtho )
|
|
extra = editor_ortho_reach();
|
|
return Range > extra ? Range : extra;
|
|
}
|
|
|
|
// far off the camera the tracks of the editor are drawn alone, the terrain, the models and the rest only as far as the
|
|
// scenery reaches in the game; the top view measures it off its centre on the ground, its camera being high above it
|
|
bool
|
|
editor_far_tracks_only(bool const Apply, scene::bounding_area const &Area, glm::dvec3 const &Camera, double const SceneryLimit)
|
|
{
|
|
if( false == Apply )
|
|
return false;
|
|
auto offset{ Area.center - Camera };
|
|
if( Global.EditorOrtho )
|
|
offset.y = 0.0;
|
|
double nearest = glm::length( offset ) - static_cast<double>( Area.radius );
|
|
if( nearest < 0.0 )
|
|
nearest = 0.0;
|
|
return nearest > SceneryLimit;
|
|
}
|
|
|
|
// returns material assigned to the submodel, resolving replacable skins. null_handle if no skin set is bound
|
|
material_handle
|
|
submodel_material( TSubModel const *Submodel ) {
|
|
|
|
if( Submodel->m_material >= 0 ) {
|
|
return Submodel->m_material;
|
|
}
|
|
return (
|
|
TSubModel::ReplacableSkinId != nullptr ?
|
|
TSubModel::ReplacableSkinId[ -Submodel->m_material ] :
|
|
null_handle );
|
|
}
|
|
|
|
bool
|
|
is_scaled( glm::vec3 const &Scale ) {
|
|
|
|
return ( Scale.x != 1.0f ) || ( Scale.y != 1.0f ) || ( Scale.z != 1.0f );
|
|
}
|
|
|
|
// pushes the placement of a scaled model instance: the translation and rotation of Render( TModel3d *, ..., Position, Angle ),
|
|
// followed by the scale of the instance, applied before the submodel transforms (as in the opengl 3.3 renderer)
|
|
void
|
|
push_scaled_instance_transform( glm::dvec3 const &Position, glm::vec3 const &Angle, glm::vec3 const &Scale ) {
|
|
|
|
::glPushMatrix();
|
|
::glTranslated( Position.x, Position.y, Position.z );
|
|
if( Angle.y != 0.0 )
|
|
::glRotatef( Angle.y, 0.f, 1.f, 0.f );
|
|
if( Angle.x != 0.0 )
|
|
::glRotatef( Angle.x, 1.f, 0.f, 0.f );
|
|
if( Angle.z != 0.0 )
|
|
::glRotatef( Angle.z, 0.f, 0.f, 1.f );
|
|
::glScalef( Scale.x, Scale.y, Scale.z );
|
|
}
|
|
|
|
} // namespace
|
|
|
|
float const EU07_OPACITYDEFAULT { 0.5f };
|
|
|
|
bool
|
|
opengl_renderer::Init( GLFWwindow *Window ) {
|
|
|
|
glClearColor( 0.f, 0.f, 0.f, 1.f );
|
|
glClear( GL_COLOR_BUFFER_BIT );
|
|
glfwSwapBuffers( Window );
|
|
|
|
if( false == Init_caps() ) { return false; }
|
|
|
|
m_window = Window;
|
|
|
|
::glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
|
|
::glPixelStorei( GL_PACK_ALIGNMENT, 1 );
|
|
|
|
glClearDepth( 1.0f );
|
|
glClearColor( 51.0f / 255.0f, 102.0f / 255.0f, 85.0f / 255.0f, 1.0f ); // initial background Color
|
|
|
|
glPolygonMode( GL_FRONT, GL_FILL );
|
|
glFrontFace( GL_CCW ); // Counter clock-wise polygons face out
|
|
glEnable( GL_CULL_FACE ); // Cull back-facing triangles
|
|
glShadeModel( GL_SMOOTH ); // Enable Smooth Shading
|
|
|
|
m_geometry.units().texture = (
|
|
Global.BasicRenderer ?
|
|
std::vector<GLint>{ m_diffusetextureunit } :
|
|
std::vector<GLint>{ m_normaltextureunit, m_diffusetextureunit } );
|
|
ui_layer::set_unit( m_diffusetextureunit );
|
|
select_unit( m_diffusetextureunit );
|
|
|
|
::glDepthFunc( GL_LEQUAL );
|
|
glEnable( GL_DEPTH_TEST );
|
|
glAlphaFunc( GL_GREATER, 0.f );
|
|
glEnable( GL_ALPHA_TEST );
|
|
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
|
|
glEnable( GL_BLEND );
|
|
glEnable( GL_TEXTURE_2D ); // Enable Texture Mapping
|
|
|
|
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ); // Really Nice Perspective Calculations
|
|
glHint( GL_POLYGON_SMOOTH_HINT, GL_NICEST );
|
|
glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
|
|
glLineWidth( 1.0f );
|
|
glPointSize( 3.0f );
|
|
glEnable( GL_POINT_SMOOTH );
|
|
|
|
::glLightModeli( GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR );
|
|
::glMaterialf( GL_FRONT, GL_SHININESS, 15.0f );
|
|
if( true == Global.ScaleSpecularValues ) {
|
|
m_specularopaquescalefactor = 0.25f;
|
|
m_speculartranslucentscalefactor = 1.5f;
|
|
}
|
|
::glEnable( GL_COLOR_MATERIAL );
|
|
::glColorMaterial( GL_FRONT, GL_AMBIENT_AND_DIFFUSE );
|
|
|
|
// setup lighting
|
|
::glLightModelfv( GL_LIGHT_MODEL_AMBIENT, glm::value_ptr(m_baseambient) );
|
|
::glEnable( GL_LIGHTING );
|
|
::glEnable( opengl_renderer::sunlight );
|
|
|
|
// rgb value for 5780 kelvin
|
|
Global.DayLight.diffuse[0] = 1.0f; // 255 / 255
|
|
Global.DayLight.diffuse[1] = 0.9490196f; // 242 / 255
|
|
Global.DayLight.diffuse[2] = 0.9058824f; // 231 / 255
|
|
Global.DayLight.is_directional = true;
|
|
m_sunlight.id = opengl_renderer::sunlight;
|
|
// ::glLightf( opengl_renderer::sunlight, GL_SPOT_CUTOFF, 90.0f );
|
|
|
|
// create dynamic light pool
|
|
for( int idx = 0; idx < Global.DynamicLightCount; ++idx ) {
|
|
|
|
opengl_light light;
|
|
light.id = GL_LIGHT1 + idx;
|
|
|
|
light.is_directional = false;
|
|
::glEnable( light.id ); // experimental intel chipset fix
|
|
::glLightf( light.id, GL_SPOT_CUTOFF, 7.5f );
|
|
::glLightf( light.id, GL_SPOT_EXPONENT, 7.5f );
|
|
::glLightf( light.id, GL_CONSTANT_ATTENUATION, 0.0f );
|
|
::glLightf( light.id, GL_LINEAR_ATTENUATION, 0.035f );
|
|
::glDisable( light.id ); // experimental intel chipset fix
|
|
|
|
m_lights.emplace_back( light );
|
|
}
|
|
// preload some common textures
|
|
m_glaretexture = Fetch_Texture( "fx/lightglare" );
|
|
m_suntexture = Fetch_Texture( "fx/sun" );
|
|
m_moontexture = Fetch_Texture( "fx/moon" );
|
|
if( m_helpertextureunit >= 0 ) {
|
|
m_reflectiontexture = Fetch_Texture( "fx/reflections" );
|
|
}
|
|
m_smoketexture = Fetch_Texture( "fx/smoke" );
|
|
m_invalid_material = Fetch_Material( "fx/invalid" );
|
|
|
|
#ifdef EU07_USE_PICKING_FRAMEBUFFER
|
|
// pick buffer resources
|
|
if( true == m_framebuffersupport ) {
|
|
// try to create the pick buffer. RGBA8 2D texture, 24 bit depth texture, 1024x1024 (height of 512 would suffice but, eh)
|
|
// texture
|
|
::glGenTextures( 1, &m_picktexture );
|
|
::glBindTexture( GL_TEXTURE_2D, m_picktexture );
|
|
::glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, EU07_PICKBUFFERSIZE, EU07_PICKBUFFERSIZE, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
|
|
// depth buffer
|
|
::glGenRenderbuffersEXT( 1, &m_pickdepthbuffer );
|
|
::glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, m_pickdepthbuffer );
|
|
::glRenderbufferStorageEXT( GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, EU07_PICKBUFFERSIZE, EU07_PICKBUFFERSIZE );
|
|
// create and assemble the framebuffer
|
|
::glGenFramebuffersEXT( 1, &m_pickframebuffer );
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, m_pickframebuffer );
|
|
::glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, m_picktexture, 0 );
|
|
::glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_pickdepthbuffer );
|
|
// check if we got it working
|
|
GLenum status = ::glCheckFramebufferStatusEXT( GL_FRAMEBUFFER_EXT );
|
|
if( status == GL_FRAMEBUFFER_COMPLETE_EXT ) {
|
|
WriteLog( "Picking framebuffer setup complete" );
|
|
}
|
|
else{
|
|
ErrorLog( "Picking framebuffer setup failed" );
|
|
m_framebuffersupport = false;
|
|
}
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 ); // switch back to primary render target for now
|
|
}
|
|
#endif
|
|
// shadowmap resources
|
|
if( ( true == Global.RenderShadows )
|
|
&& ( true == m_framebuffersupport ) ) {
|
|
// primary shadow map
|
|
{
|
|
// texture:
|
|
::glGenTextures( 1, &m_shadowtexture );
|
|
::glBindTexture( GL_TEXTURE_2D, m_shadowtexture );
|
|
// allocate memory
|
|
::glTexImage2D( GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, m_shadowbuffersize, m_shadowbuffersize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL );
|
|
// setup parameters
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
|
|
// enable shadow comparison: true (ie not in shadow) if r<=texture...
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE );
|
|
::glBindTexture( GL_TEXTURE_2D, 0 );
|
|
#ifdef EU07_USE_DEBUG_SHADOWMAP
|
|
::glGenTextures( 1, &m_shadowdebugtexture );
|
|
::glBindTexture( GL_TEXTURE_2D, m_shadowdebugtexture );
|
|
// allocate memory
|
|
::glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, m_shadowbuffersize, m_shadowbuffersize, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL );
|
|
// setup parameters
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
|
|
::glBindTexture( GL_TEXTURE_2D, 0 );
|
|
#endif
|
|
// create and assemble the framebuffer
|
|
::glGenFramebuffersEXT( 1, &m_shadowframebuffer );
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, m_shadowframebuffer );
|
|
#ifdef EU07_USE_DEBUG_SHADOWMAP
|
|
::glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, m_shadowdebugtexture, 0 );
|
|
#else
|
|
::glDrawBuffer( GL_NONE ); // we won't be rendering colour data, so can skip the colour attachment
|
|
::glReadBuffer( GL_NONE );
|
|
#endif
|
|
::glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, m_shadowtexture, 0 );
|
|
// check if we got it working
|
|
GLenum const status{ ::glCheckFramebufferStatusEXT( GL_FRAMEBUFFER_EXT ) };
|
|
if( status == GL_FRAMEBUFFER_COMPLETE_EXT ) {
|
|
WriteLog( "Shadows framebuffer setup complete" );
|
|
}
|
|
else {
|
|
ErrorLog( "Shadows framebuffer setup failed" );
|
|
Global.RenderShadows = false;
|
|
}
|
|
// switch back to primary render target for now
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 );
|
|
}
|
|
// cab shadow map
|
|
{
|
|
// NOTE: using separate framebuffer as more efficient arrangement than swapping attachments on a single one
|
|
// TODO: for shader-based implementation use instead a quarter of the CSM
|
|
// texture:
|
|
::glGenTextures( 1, &m_cabshadowtexture );
|
|
::glBindTexture( GL_TEXTURE_2D, m_cabshadowtexture );
|
|
// allocate memory
|
|
::glTexImage2D( GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, m_shadowbuffersize / 2, m_shadowbuffersize / 2, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL );
|
|
// setup parameters
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
|
|
// enable shadow comparison: true (ie not in shadow) if r<=texture...
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE );
|
|
::glBindTexture( GL_TEXTURE_2D, 0 );
|
|
#ifdef EU07_USE_DEBUG_CABSHADOWMAP
|
|
::glGenTextures( 1, &m_cabshadowdebugtexture );
|
|
::glBindTexture( GL_TEXTURE_2D, m_cabshadowdebugtexture );
|
|
// allocate memory
|
|
::glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, m_shadowbuffersize / 2, m_shadowbuffersize / 2, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL );
|
|
// setup parameters
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
|
|
::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
|
|
::glBindTexture( GL_TEXTURE_2D, 0 );
|
|
#endif
|
|
// create and assemble the framebuffer
|
|
::glGenFramebuffersEXT( 1, &m_cabshadowframebuffer );
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, m_cabshadowframebuffer );
|
|
#ifdef EU07_USE_DEBUG_CABSHADOWMAP
|
|
::glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, m_cabshadowdebugtexture, 0 );
|
|
#else
|
|
::glDrawBuffer( GL_NONE ); // we won't be rendering colour data, so can skip the colour attachment
|
|
::glReadBuffer( GL_NONE );
|
|
#endif
|
|
::glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, m_cabshadowtexture, 0 );
|
|
// check if we got it working
|
|
GLenum const status{ ::glCheckFramebufferStatusEXT( GL_FRAMEBUFFER_EXT ) };
|
|
if( status == GL_FRAMEBUFFER_COMPLETE_EXT ) {
|
|
WriteLog( "Cab shadows framebuffer setup complete" );
|
|
}
|
|
else {
|
|
ErrorLog( "Cab shadows framebuffer setup failed" );
|
|
Global.RenderShadows = false;
|
|
}
|
|
}
|
|
// switch back to primary render target for now
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 );
|
|
}
|
|
// environment cube map resources
|
|
if( ( false == Global.BasicRenderer )
|
|
&& ( true == m_framebuffersupport ) ) {
|
|
// texture:
|
|
::glGenTextures( 1, &m_environmentcubetexture );
|
|
::glBindTexture( GL_TEXTURE_CUBE_MAP, m_environmentcubetexture );
|
|
// allocate space
|
|
for( GLuint faceindex = GL_TEXTURE_CUBE_MAP_POSITIVE_X; faceindex < GL_TEXTURE_CUBE_MAP_POSITIVE_X + 6; ++faceindex ) {
|
|
::glTexImage2D( faceindex, 0, GL_RGBA8, EU07_ENVIRONMENTBUFFERSIZE, EU07_ENVIRONMENTBUFFERSIZE, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL );
|
|
}
|
|
// setup parameters
|
|
::glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
|
|
::glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
|
|
::glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
|
|
::glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
|
|
::glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
|
|
// depth buffer
|
|
::glGenRenderbuffersEXT( 1, &m_environmentdepthbuffer );
|
|
::glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, m_environmentdepthbuffer );
|
|
::glRenderbufferStorageEXT( GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, EU07_ENVIRONMENTBUFFERSIZE, EU07_ENVIRONMENTBUFFERSIZE );
|
|
// create and assemble the framebuffer
|
|
::glGenFramebuffersEXT( 1, &m_environmentframebuffer );
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, m_environmentframebuffer );
|
|
::glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_CUBE_MAP_POSITIVE_X, m_environmentcubetexture, 0 );
|
|
::glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_environmentdepthbuffer );
|
|
// check if we got it working
|
|
GLenum status = ::glCheckFramebufferStatusEXT( GL_FRAMEBUFFER_EXT );
|
|
if( status == GL_FRAMEBUFFER_COMPLETE_EXT ) {
|
|
WriteLog( "Reflections framebuffer setup complete" );
|
|
m_environmentcubetexturesupport = true;
|
|
}
|
|
else {
|
|
ErrorLog( "Reflections framebuffer setup failed" );
|
|
m_environmentcubetexturesupport = false;
|
|
}
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 ); // switch back to primary render target for now
|
|
}
|
|
// prepare basic geometry chunks
|
|
auto const geometrybank = Create_Bank();
|
|
float const size = 2.5f;
|
|
gfx::vertex_array billboard_array{
|
|
{ { -size, size, 0.f }, glm::vec3(), { 1.f, 1.f } },
|
|
{ { size, size, 0.f }, glm::vec3(), { 0.f, 1.f } },
|
|
{ { -size, -size, 0.f }, glm::vec3(), { 1.f, 0.f } },
|
|
{ { size, -size, 0.f }, glm::vec3(), { 0.f, 0.f } } };
|
|
gfx::userdata_array userdata{};
|
|
m_billboardgeometry = m_geometry.create_chunk(billboard_array, userdata, geometrybank, GL_TRIANGLE_STRIP);
|
|
// prepare debug mode objects
|
|
//m_quadric = ::gluNewQuadric();
|
|
//::gluQuadricNormals( m_quadric, GLU_FLAT );
|
|
|
|
WriteLog( "Gfx Renderer: setup complete" );
|
|
|
|
return true;
|
|
}
|
|
|
|
bool
|
|
opengl_renderer::Render() {
|
|
|
|
Timer::subsystem.gfx_total.stop();
|
|
Timer::subsystem.gfx_total.start(); // note: gfx_total is actually frame total, clean this up
|
|
Timer::subsystem.gfx_color.start();
|
|
// fetch simulation data
|
|
if( simulation::is_ready ) {
|
|
m_sunlight = Global.DayLight;
|
|
// quantize sun angle to reduce shadow crawl
|
|
auto const quantizationstep { 0.004f };
|
|
m_sunlight.direction = glm::normalize( quantizationstep * glm::roundEven( m_sunlight.direction * ( 1.f / quantizationstep ) ) );
|
|
}
|
|
// generate new frame
|
|
opengl_texture::reset_unit_cache();
|
|
m_renderpass.draw_mode = rendermode::none; // force setup anew
|
|
m_renderpass.draw_stats = debug_stats();
|
|
m_geometry.primitives_count() = 0;
|
|
Render_pass( rendermode::color );
|
|
Timer::subsystem.gfx_color.stop();
|
|
// add user interface
|
|
setup_units( true, false, false );
|
|
::glPushClientAttrib( GL_CLIENT_VERTEX_ARRAY_BIT );
|
|
::glClientActiveTexture( GL_TEXTURE0 + m_diffusetextureunit );
|
|
|
|
// clear state for ui
|
|
::glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
|
|
::glBindBuffer( GL_ARRAY_BUFFER, 0 );
|
|
Application.render_ui();
|
|
::glPopClientAttrib();
|
|
if( Global.bUseVBO ) {
|
|
// swapbuffers() will unbind current buffers so we prepare for it on our end
|
|
gfx::opengl_vbogeometrybank::reset();
|
|
}
|
|
++m_framestamp;
|
|
|
|
return true; // for now always succeed
|
|
}
|
|
|
|
void
|
|
opengl_renderer::SwapBuffers() {
|
|
|
|
Timer::subsystem.gfx_swap.start();
|
|
glfwSwapBuffers( m_window );
|
|
Timer::subsystem.gfx_swap.stop();
|
|
|
|
m_debugtimestext.clear();
|
|
m_debugtimestext =
|
|
"cpu frame total: " + to_string( Timer::subsystem.gfx_color.average() + Timer::subsystem.gfx_shadows.average() + Timer::subsystem.gfx_swap.average(), 2 ) + " ms\n"
|
|
+ " color: " + to_string( Timer::subsystem.gfx_color.average(), 2 ) + " ms (" + std::to_string( m_cellqueue.size() ) + " sectors)\n";
|
|
if( Global.RenderShadows ) {
|
|
m_debugtimestext +=
|
|
" shadows: " + to_string( Timer::subsystem.gfx_shadows.average(), 2 ) + " ms\n";
|
|
}
|
|
m_debugtimestext += " swap: " + to_string( Timer::subsystem.gfx_swap.average(), 2 ) + " ms\n";
|
|
m_debugtimestext += "uilayer: " + to_string( Timer::subsystem.gfx_gui.average(), 2 ) + " ms\n";
|
|
|
|
m_debugstatstext =
|
|
"triangles: " + to_string( static_cast<int>(m_geometry.primitives_count()), 7 ) + "\n"
|
|
+ "vehicles: " + to_string( m_colorpass.draw_stats.dynamics, 7 ) + " +" + to_string( m_shadowpass.draw_stats.dynamics, 7 )
|
|
+ " =" + to_string( m_colorpass.draw_stats.dynamics + m_shadowpass.draw_stats.dynamics, 7 ) + "\n"
|
|
+ "models: " + to_string( m_colorpass.draw_stats.models, 7 ) + " +" + to_string( m_shadowpass.draw_stats.models, 7 )
|
|
+ " =" + to_string( m_colorpass.draw_stats.models + m_shadowpass.draw_stats.models, 7 ) + "\n"
|
|
+ "drawcalls: " + to_string( m_colorpass.draw_stats.drawcalls, 7 ) + " +" + to_string( m_shadowpass.draw_stats.drawcalls, 7 )
|
|
+ " =" + to_string( m_colorpass.draw_stats.drawcalls + m_shadowpass.draw_stats.drawcalls, 7 ) + "\n"
|
|
+ " submodels:" + to_string( m_colorpass.draw_stats.submodels, 7 ) + " +" + to_string( m_shadowpass.draw_stats.submodels, 7 )
|
|
+ " =" + to_string( m_colorpass.draw_stats.submodels + m_shadowpass.draw_stats.submodels, 7 ) + "\n"
|
|
+ " paths: " + to_string( m_colorpass.draw_stats.paths, 7 ) + " +" + to_string( m_shadowpass.draw_stats.paths, 7 )
|
|
+ " =" + to_string( m_colorpass.draw_stats.paths + m_shadowpass.draw_stats.paths, 7 ) + "\n"
|
|
+ " shapes: " + to_string( m_colorpass.draw_stats.shapes, 7 ) + " +" + to_string( m_shadowpass.draw_stats.shapes, 7 )
|
|
+ " =" + to_string( m_colorpass.draw_stats.shapes + m_shadowpass.draw_stats.shapes, 7 ) + "\n"
|
|
+ " traction: " + to_string( m_colorpass.draw_stats.traction, 7 ) + "\n"
|
|
+ " lines: " + to_string( m_colorpass.draw_stats.lines, 7 ) + "\n"
|
|
+ "particles: " + to_string( m_colorpass.draw_stats.particles, 7 );
|
|
}
|
|
|
|
// runs jobs needed to generate graphics for specified render pass
|
|
void
|
|
opengl_renderer::Render_pass( rendermode const Mode ) {
|
|
|
|
#ifdef EU07_USE_DEBUG_CAMERA
|
|
// setup world camera for potential visualization
|
|
setup_pass(
|
|
m_worldcamera,
|
|
rendermode::color,
|
|
0.f,
|
|
1.0,
|
|
true );
|
|
#endif
|
|
setup_pass( m_renderpass, Mode );
|
|
switch( m_renderpass.draw_mode ) {
|
|
|
|
case rendermode::color: {
|
|
|
|
m_colorpass = m_renderpass;
|
|
|
|
if( ( !simulation::is_ready ) || ( Global.gfx_skiprendering ) ) {
|
|
::glClearColor( 51.0f / 255.f, 102.0f / 255.f, 85.0f / 255.f, 1.f ); // initial background Color
|
|
::glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
|
|
break;
|
|
}
|
|
|
|
if (Global.bWireFrame)
|
|
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
|
|
else
|
|
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
|
|
|
|
if( ( true == Global.RenderShadows )
|
|
&& ( false == Global.bWireFrame )
|
|
&& ( m_shadowcolor != colors::white ) ) {
|
|
|
|
// run shadowmaps pass before color
|
|
Timer::subsystem.gfx_shadows.start();
|
|
if( false == FreeFlyModeFlag ) {
|
|
Render_pass( rendermode::cabshadows );
|
|
}
|
|
Render_pass( rendermode::shadows );
|
|
Timer::subsystem.gfx_shadows.stop();
|
|
#ifdef EU07_USE_DEBUG_SHADOWMAP
|
|
UILayer.set_texture( m_shadowdebugtexture );
|
|
#endif
|
|
#ifdef EU07_USE_DEBUG_CABSHADOWMAP
|
|
UILayer.set_texture( m_cabshadowdebugtexture );
|
|
#endif
|
|
setup_pass( m_renderpass, Mode ); // restore draw mode. TBD, TODO: render mode stack
|
|
// setup shadowmap matrices
|
|
m_shadowtexturematrix =
|
|
glm::mat4 { 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f } // bias from [-1, 1] to [0, 1]
|
|
* m_shadowpass.camera.projection()
|
|
// during colour pass coordinates are moved from camera-centric to light-centric, essentially the difference between these two origins
|
|
* glm::translate(
|
|
glm::mat4{ glm::mat3{ m_shadowpass.camera.modelview() } },
|
|
glm::vec3{ m_renderpass.camera.position() - m_shadowpass.camera.position() } );
|
|
|
|
if( false == FreeFlyModeFlag ) {
|
|
m_cabshadowtexturematrix =
|
|
glm::mat4{ 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f } // bias from [-1, 1] to [0, 1]
|
|
* m_cabshadowpass.camera.projection()
|
|
// during colour pass coordinates are moved from camera-centric to light-centric, essentially the difference between these two origins
|
|
* glm::translate(
|
|
glm::mat4{ glm::mat3{ m_cabshadowpass.camera.modelview() } },
|
|
glm::vec3{ m_renderpass.camera.position() - m_cabshadowpass.camera.position() } );
|
|
}
|
|
}
|
|
|
|
if( true == m_environmentcubetexturesupport ) {
|
|
// potentially update environmental cube map
|
|
m_renderpass.draw_stats = {};
|
|
if( true == Render_reflections() ) {
|
|
setup_pass( m_renderpass, Mode ); // restore draw mode. TBD, TODO: render mode stack
|
|
}
|
|
}
|
|
|
|
::glViewport( 0, 0, Global.fb_size.x, Global.fb_size.y );
|
|
|
|
auto const skydomecolour = simulation::Environment.m_skydome.GetAverageColor();
|
|
::glClearColor( skydomecolour.x, skydomecolour.y, skydomecolour.z, 0.f ); // kolor nieba
|
|
::glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
|
|
|
|
// setup
|
|
setup_matrices();
|
|
// render
|
|
setup_drawing( true );
|
|
setup_units( true, false, false );
|
|
m_renderpass.draw_stats = {};
|
|
Render( &simulation::Environment );
|
|
// opaque parts...
|
|
setup_drawing( false );
|
|
setup_units( true, true, true );
|
|
#ifdef EU07_USE_DEBUG_CAMERA
|
|
if( DebugModeFlag ) {
|
|
// draw light frustum
|
|
::glLineWidth( 2.f );
|
|
::glColor4f( 1.f, 0.9f, 0.8f, 1.f );
|
|
::glDisable( GL_LIGHTING );
|
|
::glDisable( GL_TEXTURE_2D );
|
|
if( ( true == Global.RenderShadows ) && ( false == Global.bWireFrame ) ) {
|
|
m_shadowpass.camera.draw( m_renderpass.camera.position() - m_shadowpass.camera.position() );
|
|
}
|
|
if( DebugCameraFlag ) {
|
|
::glColor4f( 0.8f, 1.f, 0.9f, 1.f );
|
|
m_worldcamera.camera.draw( m_renderpass.camera.position() - m_worldcamera.camera.position() );
|
|
}
|
|
::glLineWidth( 1.f );
|
|
::glEnable( GL_LIGHTING );
|
|
::glEnable( GL_TEXTURE_2D );
|
|
}
|
|
#endif
|
|
// without rain/snow we can render the cab early to limit the overdraw
|
|
if( ( false == FreeFlyModeFlag )
|
|
&& ( Global.Overcast <= 1.f ) ) { // precipitation happens when overcast is in 1-2 range
|
|
#ifdef EU07_DISABLECABREFLECTIONS
|
|
switch_units( true, true, false );
|
|
#endif
|
|
setup_shadow_map( m_cabshadowtexture, m_cabshadowtexturematrix );
|
|
// cache shadow colour in case we need to account for cab light
|
|
auto const shadowcolor { m_shadowcolor };
|
|
auto const *vehicle{ simulation::Train->Dynamic() };
|
|
if( vehicle->InteriorLightLevel > 0.f ) {
|
|
setup_shadow_color( glm::min( colors::white, shadowcolor + glm::vec4( vehicle->InteriorLight * vehicle->InteriorLightLevel, 1.f ) ) );
|
|
}
|
|
Render_cab( vehicle, vehicle->InteriorLightLevel, false );
|
|
if( vehicle->InteriorLightLevel > 0.f ) {
|
|
setup_shadow_color( shadowcolor );
|
|
}
|
|
}
|
|
switch_units( true, true, true );
|
|
setup_shadow_map( m_shadowtexture, m_shadowtexturematrix );
|
|
Render( simulation::Region );
|
|
// ...translucent parts
|
|
setup_drawing( true );
|
|
Render_Alpha( simulation::Region );
|
|
// particles
|
|
Render_particles();
|
|
// precipitation; done at the end, only before cab render
|
|
Render_precipitation();
|
|
// cab render
|
|
if( false == FreeFlyModeFlag ) {
|
|
#ifdef EU07_DISABLECABREFLECTIONS
|
|
switch_units( true, true, false );
|
|
#endif
|
|
setup_shadow_map( m_cabshadowtexture, m_cabshadowtexturematrix );
|
|
// cache shadow colour in case we need to account for cab light
|
|
auto const shadowcolor{ m_shadowcolor };
|
|
auto *vehicle { simulation::Train->Dynamic() };
|
|
if( vehicle->InteriorLightLevel > 0.f ) {
|
|
setup_shadow_color( glm::min( colors::white, shadowcolor + glm::vec4( vehicle->InteriorLight * vehicle->InteriorLightLevel, 1.f ) ) );
|
|
}
|
|
if( Global.Overcast > 1.f ) {
|
|
// with active precipitation draw the opaque cab parts here to mask rain/snow placed 'inside' the cab
|
|
setup_drawing( false );
|
|
Render_cab( vehicle, vehicle->InteriorLightLevel, false );
|
|
Render_interior( false);
|
|
setup_drawing( true );
|
|
Render_interior( true );
|
|
}
|
|
Render_cab( vehicle, vehicle->InteriorLightLevel, true );
|
|
if( vehicle->InteriorLightLevel > 0.f ) {
|
|
setup_shadow_color( shadowcolor );
|
|
}
|
|
// with the cab in place we can (finally) safely draw translucent part of the occupied vehicle
|
|
Render_Alpha( vehicle );
|
|
}
|
|
|
|
if( m_environmentcubetexturesupport ) {
|
|
// restore default texture matrix for reflections cube map
|
|
select_unit( m_helpertextureunit );
|
|
::glMatrixMode( GL_TEXTURE );
|
|
// ::glPopMatrix();
|
|
::glLoadIdentity();
|
|
select_unit( m_diffusetextureunit );
|
|
::glMatrixMode( GL_MODELVIEW );
|
|
}
|
|
// store draw stats
|
|
m_colorpass.draw_stats = m_renderpass.draw_stats;
|
|
|
|
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
|
|
|
|
break;
|
|
}
|
|
|
|
case rendermode::shadows: {
|
|
|
|
if( simulation::is_ready ) {
|
|
// setup
|
|
::glEnable( GL_POLYGON_OFFSET_FILL ); // alleviate depth-fighting
|
|
::glPolygonOffset( 1.f, 1.f );
|
|
|
|
// main shadowmap
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, m_shadowframebuffer );
|
|
::glViewport( 0, 0, m_shadowbuffersize, m_shadowbuffersize );
|
|
|
|
#ifdef EU07_USE_DEBUG_SHADOWMAP
|
|
::glClearColor( 0.f / 255.f, 0.f / 255.f, 0.f / 255.f, 1.f ); // initial background Color
|
|
::glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
|
|
#else
|
|
::glClear( GL_DEPTH_BUFFER_BIT );
|
|
#endif
|
|
::glScissor( 1, 1, m_shadowbuffersize - 2, m_shadowbuffersize - 2 );
|
|
::glEnable( GL_SCISSOR_TEST );
|
|
|
|
setup_matrices();
|
|
// render
|
|
// opaque parts...
|
|
setup_drawing( false );
|
|
#ifdef EU07_USE_DEBUG_SHADOWMAP
|
|
setup_units( true, false, false );
|
|
#else
|
|
setup_units( false, false, false );
|
|
#endif
|
|
Render( simulation::Region );
|
|
m_shadowpass = m_renderpass;
|
|
|
|
// post-render restore
|
|
::glDisable( GL_SCISSOR_TEST );
|
|
::glDisable( GL_POLYGON_OFFSET_FILL );
|
|
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 ); // switch back to primary render target
|
|
}
|
|
break;
|
|
}
|
|
|
|
case rendermode::cabshadows: {
|
|
|
|
if( ( simulation::is_ready )
|
|
&& ( false == FreeFlyModeFlag ) ) {
|
|
// setup
|
|
::glEnable( GL_POLYGON_OFFSET_FILL ); // alleviate depth-fighting
|
|
::glPolygonOffset( 1.f, 1.f );
|
|
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, m_cabshadowframebuffer );
|
|
::glViewport( 0, 0, m_shadowbuffersize / 2, m_shadowbuffersize / 2 );
|
|
|
|
#ifdef EU07_USE_DEBUG_CABSHADOWMAP
|
|
::glClearColor( 0.f / 255.f, 0.f / 255.f, 0.f / 255.f, 1.f ); // initial background Color
|
|
::glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
|
|
#else
|
|
::glClear( GL_DEPTH_BUFFER_BIT );
|
|
#endif
|
|
::glScissor( 1, 1, m_shadowbuffersize / 2 - 2, m_shadowbuffersize / 2 - 2 );
|
|
::glEnable( GL_SCISSOR_TEST );
|
|
|
|
setup_matrices();
|
|
// render
|
|
// opaque parts...
|
|
setup_drawing( false );
|
|
#ifdef EU07_USE_DEBUG_CABSHADOWMAP
|
|
setup_units( true, false, false );
|
|
#else
|
|
setup_units( false, false, false );
|
|
#endif
|
|
::glDisable( GL_CULL_FACE );
|
|
|
|
if( Global.RenderCabShadowsRange > 0 ) {
|
|
Render( simulation::Region );
|
|
}
|
|
Render_cab( simulation::Train->Dynamic(), 0.f, false );
|
|
Render_cab( simulation::Train->Dynamic(), 0.f, true );
|
|
m_cabshadowpass = m_renderpass;
|
|
|
|
// post-render restore
|
|
::glDisable( GL_SCISSOR_TEST );
|
|
::glEnable( GL_CULL_FACE );
|
|
::glDisable( GL_POLYGON_OFFSET_FILL );
|
|
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 ); // switch back to primary render target
|
|
}
|
|
break;
|
|
}
|
|
|
|
case rendermode::reflections: {
|
|
// NOTE: buffer and viewport setup in this mode is handled by the wrapper method
|
|
::glClearColor( 0.f, 0.f, 0.f, 1.f );
|
|
::glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
|
|
|
|
if( simulation::is_ready ) {
|
|
|
|
::glColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE );
|
|
// setup
|
|
setup_matrices();
|
|
// render
|
|
setup_drawing( true );
|
|
setup_units( true, false, false );
|
|
Render( &simulation::Environment );
|
|
// opaque parts...
|
|
setup_drawing( false );
|
|
setup_units( true, true, true );
|
|
setup_shadow_map( m_shadowtexture, m_shadowtexturematrix );
|
|
Render( simulation::Region );
|
|
/*
|
|
// reflections are limited to sky and ground only, the update rate is too low for anything else
|
|
// ...translucent parts
|
|
setup_drawing( true );
|
|
Render_Alpha( &World.Ground );
|
|
// cab render is performed without shadows, due to low resolution and number of models without windows :|
|
|
switch_units( true, false, false );
|
|
// cab render is done in translucent phase to deal with badly configured vehicles
|
|
if( World.Train != nullptr ) { Render_cab( World.Train->Dynamic() ); }
|
|
*/
|
|
::glColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE );
|
|
}
|
|
break;
|
|
}
|
|
|
|
case rendermode::pickcontrols: {
|
|
if( simulation::is_ready ) {
|
|
// setup
|
|
#ifdef EU07_USE_PICKING_FRAMEBUFFER
|
|
::glViewport( 0, 0, EU07_PICKBUFFERSIZE, EU07_PICKBUFFERSIZE );
|
|
#endif
|
|
::glClearColor( 0.f, 0.f, 0.f, 1.f );
|
|
::glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
|
|
|
|
m_pickcontrolsitems.clear();
|
|
setup_matrices();
|
|
// render
|
|
// opaque parts...
|
|
setup_drawing( false );
|
|
setup_units( false, false, false );
|
|
// cab render skips translucent parts, so we can do it here
|
|
if( simulation::Train != nullptr ) {
|
|
Render_cab( simulation::Train->Dynamic(), 0.f );
|
|
Render( simulation::Train->Dynamic() );
|
|
}
|
|
// post-render cleanup
|
|
}
|
|
break;
|
|
}
|
|
|
|
case rendermode::pickscenery: {
|
|
if( simulation::is_ready ) {
|
|
// setup
|
|
m_picksceneryitems.clear();
|
|
#ifdef EU07_USE_PICKING_FRAMEBUFFER
|
|
::glViewport( 0, 0, EU07_PICKBUFFERSIZE, EU07_PICKBUFFERSIZE );
|
|
#endif
|
|
::glClearColor( 0.f, 0.f, 0.f, 1.f );
|
|
::glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
|
|
|
|
setup_matrices();
|
|
// render
|
|
// opaque parts...
|
|
setup_drawing( false );
|
|
setup_units( false, false, false );
|
|
Render( simulation::Region );
|
|
// post-render cleanup
|
|
}
|
|
break;
|
|
}
|
|
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
bool opengl_renderer::Render_interior( bool const Alpha ) {
|
|
// NOTE: legacy renderer doesn't need to repaint translucent parts
|
|
// TODO: investigate reasons (depth writing?) and duplicate in opengl33 branch
|
|
if( Alpha ) { return false; }
|
|
// TODO: early frustum based cull, camera might be pointing elsewhere
|
|
std::vector< std::pair<float, TDynamicObject *> > dynamics;
|
|
auto *dynamic { simulation::Train->Dynamic() };
|
|
// draw interiors of the occupied vehicle, and all vehicles behind it with permanent coupling, in case they're open-ended
|
|
while( dynamic != nullptr ) {
|
|
|
|
glm::dvec3 const originoffset { dynamic->vPosition - m_renderpass.camera.position() };
|
|
float const squaredistance{ glm::length2( glm::vec3{ originoffset } / Global.ZoomFactor ) };
|
|
dynamics.emplace_back( squaredistance, dynamic );
|
|
dynamic = dynamic->Next( coupling::permanent );
|
|
}
|
|
// draw also interiors of permanently coupled vehicles in front, if there's any
|
|
dynamic = simulation::Train->Dynamic()->Prev( coupling::permanent );
|
|
while( dynamic != nullptr ) {
|
|
|
|
glm::dvec3 const originoffset { dynamic->vPosition - m_renderpass.camera.position() };
|
|
float const squaredistance{ glm::length2( glm::vec3{ originoffset } / Global.ZoomFactor ) };
|
|
dynamics.emplace_back( squaredistance, dynamic );
|
|
dynamic = dynamic->Prev( coupling::permanent );
|
|
}
|
|
if( Alpha ) {
|
|
std::sort(
|
|
std::begin( dynamics ), std::end( dynamics ),
|
|
[]( std::pair<float, TDynamicObject *> const &Left, std::pair<float, TDynamicObject *> const &Right ) {
|
|
return ( Left.first ) > ( Right.first ); } );
|
|
}
|
|
for( auto &dynamic : dynamics ) {
|
|
Render_lowpoly( dynamic.second, dynamic.first, true, Alpha );
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
bool opengl_renderer::Render_lowpoly( TDynamicObject *Dynamic, float const Squaredistance, bool const Setup, bool const Alpha ) {
|
|
|
|
if( Dynamic->mdLowPolyInt == nullptr ) { return false; }
|
|
|
|
// low poly interior
|
|
glm::dvec3 const originoffset { Dynamic->vPosition - m_renderpass.camera.position() };
|
|
|
|
if( Setup ) {
|
|
|
|
TSubModel::iInstance = reinterpret_cast<std::uintptr_t>( Dynamic ); //żeby nie robić cudzych animacji
|
|
TSubModel::iVariantSeed = Dynamic->variant_seed();
|
|
Dynamic->ABuLittleUpdate( Squaredistance ); // ustawianie zmiennych submodeli dla wspólnego modelu
|
|
::glPushMatrix();
|
|
|
|
::glTranslated( originoffset.x, originoffset.y, originoffset.z );
|
|
::glMultMatrixd( glm::value_ptr(Dynamic->mMatrix) );
|
|
|
|
m_renderspecular = true; // vehicles are rendered with specular component. static models without, at least for the time being
|
|
}
|
|
// HACK: reduce light level for vehicle interior if there's strong global lighting source
|
|
if( false == Alpha ) {
|
|
auto const luminance{ static_cast<float>(
|
|
0.5
|
|
* ( std::max(
|
|
0.3,
|
|
( Global.fLuminance - Global.Overcast )
|
|
* ( Dynamic->fShade > 0.0 ?
|
|
Dynamic->fShade :
|
|
1.0 ) ) ) ) };
|
|
m_sunlight.apply_intensity(
|
|
std::clamp( (
|
|
Dynamic->fShade > 0.f ?
|
|
Dynamic->fShade :
|
|
1.f )
|
|
- luminance,
|
|
0.f, 1.f ) );
|
|
Render( Dynamic->mdLowPolyInt, Dynamic->Material(), Squaredistance );
|
|
// HACK: if the model has low poly interior, we presume the load is placed inside and also affected by reduced light level
|
|
if( Dynamic->mdLoad ) {
|
|
// renderowanie nieprzezroczystego ładunku
|
|
Render( Dynamic->mdLoad, Dynamic->Material(), Squaredistance, { 0.f, Dynamic->LoadOffset, 0.f }, {} );
|
|
}
|
|
m_sunlight.apply_intensity( Dynamic->fShade > 0.f ? Dynamic->fShade : 1.f );
|
|
}
|
|
else {
|
|
// Render_Alpha( Dynamic->mdLowPolyInt, Dynamic->Material(), Squaredistance );
|
|
// HACK: some models have windows included as part of the main model instead of lowpoly
|
|
if( Dynamic->mdModel ) {
|
|
// main model
|
|
Render_Alpha( Dynamic->mdModel, Dynamic->Material(), Squaredistance );
|
|
}
|
|
}
|
|
|
|
if( Setup ) {
|
|
|
|
m_renderspecular = false;
|
|
if( Dynamic->fShade > 0.0f ) {
|
|
// restore regular light level
|
|
m_sunlight.apply_intensity();
|
|
}
|
|
|
|
::glPopMatrix();
|
|
|
|
// TODO: check if this reset is needed. In theory each object should render all parts based on its own instance data anyway?
|
|
if( Dynamic->btnOn ) {
|
|
Dynamic->TurnOff(); // przywrócenie domyślnych pozycji submodeli
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
bool opengl_renderer::Render_coupler_adapter( TDynamicObject *Dynamic, float const Squaredistance, int const End, bool const Alpha ) {
|
|
|
|
if( Dynamic->m_coupleradapters[ End ] == nullptr ) { return false; }
|
|
|
|
auto const position { glm::dvec3 {
|
|
0.f,
|
|
Dynamic->MoverParameters->Couplers[ End ].adapter_height,
|
|
( Dynamic->MoverParameters->Couplers[ End ].adapter_length + Dynamic->MoverParameters->Dim.L * 0.5 ) * ( End == end::front ? 1 : -1 ) } };
|
|
|
|
auto const angle{ glm::vec3{ 0, ( End == end::front ? 0 : 180 ), 0 } };
|
|
|
|
if( Alpha ) {
|
|
Render_Alpha( Dynamic->m_coupleradapters[ End ], Dynamic->Material(), Squaredistance, position, angle );
|
|
}
|
|
else {
|
|
Render( Dynamic->m_coupleradapters[ End ], Dynamic->Material(), Squaredistance, position, angle );
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
// creates dynamic environment cubemap
|
|
bool
|
|
opengl_renderer::Render_reflections() {
|
|
|
|
if( Global.reflectiontune.update_interval == 0 ) { return false; }
|
|
// the top view of the editor shows nothing the reflections would be seen on: the cube map stays as it was
|
|
if( EditorModeFlag && Global.EditorOrtho ) { return false; }
|
|
|
|
auto const timestamp { Timer::GetRenderTime() };
|
|
if( ( timestamp - m_environmentupdatetime < Global.reflectiontune.update_interval )
|
|
&& ( glm::length2( m_renderpass.camera.position() - m_environmentupdatelocation ) < sq(1000.0)) ) {
|
|
// run update every 5+ mins of simulation time, or at least 1km from the last location
|
|
return false;
|
|
}
|
|
m_environmentupdatetime = timestamp;
|
|
m_environmentupdatelocation = m_renderpass.camera.position();
|
|
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, m_environmentframebuffer );
|
|
::glViewport( 0, 0, EU07_ENVIRONMENTBUFFERSIZE, EU07_ENVIRONMENTBUFFERSIZE );
|
|
for( m_environmentcubetextureface = GL_TEXTURE_CUBE_MAP_POSITIVE_X;
|
|
m_environmentcubetextureface < GL_TEXTURE_CUBE_MAP_POSITIVE_X + 6;
|
|
++m_environmentcubetextureface ) {
|
|
|
|
::glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, m_environmentcubetextureface, m_environmentcubetexture, 0 );
|
|
Render_pass( rendermode::reflections );
|
|
}
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 );
|
|
|
|
return true;
|
|
}
|
|
|
|
void
|
|
opengl_renderer::setup_pass( renderpass_config &Config, rendermode const Mode, float const Znear, float const Zfar, bool const Ignoredebug ) {
|
|
|
|
Config.draw_mode = Mode;
|
|
|
|
if( false == simulation::is_ready ) { return; }
|
|
// setup draw range
|
|
switch( Mode ) {
|
|
case rendermode::color: { Config.draw_range = Global.BaseDrawRange * Global.fDistanceFactor; break; }
|
|
case rendermode::shadows: { Config.draw_range = Global.shadowtune.range; break; }
|
|
case rendermode::cabshadows: { Config.draw_range = ( Global.RenderCabShadowsRange > 0 ? std::clamp( Global.RenderCabShadowsRange, 5, 100 ) : simulation::Train->Occupied()->Dim.L ); break; }
|
|
case rendermode::reflections: { Config.draw_range = Global.BaseDrawRange; break; }
|
|
case rendermode::pickcontrols: { Config.draw_range = 50.f; break; }
|
|
case rendermode::pickscenery: { Config.draw_range = Global.BaseDrawRange * 0.5f; break; }
|
|
default: { Config.draw_range = 0.f; break; }
|
|
}
|
|
// setup camera
|
|
auto &camera = Config.camera;
|
|
|
|
camera.projection() = glm::mat4( 1.f );
|
|
glm::dmat4 viewmatrix( 1.0 );
|
|
|
|
switch( Mode ) {
|
|
case rendermode::color: {
|
|
// modelview
|
|
if( ( false == DebugCameraFlag ) || ( true == Ignoredebug ) ) {
|
|
camera.position() = Global.pCamera.Pos;
|
|
Global.pCamera.SetMatrix( viewmatrix );
|
|
}
|
|
else {
|
|
camera.position() = Global.pDebugCamera.Pos;
|
|
Global.pDebugCamera.SetMatrix( viewmatrix );
|
|
}
|
|
// optimization: don't bother drawing things completely blended with the background
|
|
// but ensure at least 2 km range to account for signals and lights
|
|
Config.draw_range = std::min( Config.draw_range, m_fogrange * 2 );
|
|
Config.draw_range = std::max( 2000.f, Config.draw_range );
|
|
// projection
|
|
auto const zfar = ( Zfar > 1.f ? Zfar : Config.draw_range * Zfar );
|
|
auto const znear = ( Znear > 1.f ? Znear : Znear > 0.f ? Znear * zfar : 0.1f * Global.ZoomFactor);
|
|
camera.projection() *=
|
|
glm::perspective(
|
|
glm::radians( Global.FieldOfView / Global.ZoomFactor ),
|
|
std::max( 1.f, (float)Global.window_size.x ) / std::max( 1.f, (float)Global.window_size.y ),
|
|
znear,
|
|
zfar );
|
|
/*
|
|
m_sunandviewangle =
|
|
glm::dot(
|
|
m_sunlight.direction,
|
|
glm::vec3( 0.f, 0.f, -1.f ) * glm::mat3( viewmatrix ) );
|
|
*/
|
|
break;
|
|
}
|
|
case rendermode::shadows: {
|
|
// calculate lightview boundaries based on relevant area of the world camera frustum:
|
|
// ...setup chunk of frustum we're interested in...
|
|
// auto const zfar = std::min( 1.f, Global.shadowtune.range / ( Global.BaseDrawRange * Global.fDistanceFactor ) * std::max( 1.f, Global.ZoomFactor * 0.5f ) );
|
|
// auto const zfar = Global.shadowtune.range * std::max( Zfar, Global.ZoomFactor * 0.5f );
|
|
auto const zfar = ( Zfar > 1.f ? Zfar : Zfar * Global.shadowtune.range * std::max( Zfar, Global.ZoomFactor * 0.5f ) );
|
|
renderpass_config worldview;
|
|
setup_pass( worldview, rendermode::color, Znear, zfar, true );
|
|
auto &frustumchunkshapepoints = worldview.camera.frustum_points();
|
|
// ...modelview matrix: determine the centre of frustum chunk in world space...
|
|
glm::vec3 frustumchunkmin, frustumchunkmax;
|
|
bounding_box( frustumchunkmin, frustumchunkmax, std::begin( frustumchunkshapepoints ), std::end( frustumchunkshapepoints ) );
|
|
auto const frustumchunkcentre = ( frustumchunkmin + frustumchunkmax ) * 0.5f;
|
|
// ...cap the vertical angle to keep shadows from getting too long...
|
|
auto const lightvector =
|
|
glm::normalize( glm::vec3{
|
|
m_sunlight.direction.x,
|
|
std::min( m_sunlight.direction.y, Global.gfx_shadow_angle_min ),
|
|
m_sunlight.direction.z } );
|
|
// ...place the light source at the calculated centre and setup world space light view matrix...
|
|
camera.position() = worldview.camera.position() + glm::dvec3{ frustumchunkcentre };
|
|
viewmatrix *= glm::lookAt(
|
|
camera.position(),
|
|
camera.position() + glm::dvec3{ lightvector },
|
|
glm::dvec3{ 0.f, 1.f, 0.f } );
|
|
// ...projection matrix: calculate boundaries of the frustum chunk in light space...
|
|
auto const lightviewmatrix =
|
|
glm::translate(
|
|
glm::mat4{ glm::mat3{ viewmatrix } },
|
|
-frustumchunkcentre );
|
|
for( auto &point : frustumchunkshapepoints ) {
|
|
point = lightviewmatrix * point;
|
|
}
|
|
bounding_box( frustumchunkmin, frustumchunkmax, std::begin( frustumchunkshapepoints ), std::end( frustumchunkshapepoints ) );
|
|
// quantize the frustum points and add some padding, to reduce shadow shimmer on scale changes
|
|
auto const frustumchunkdepth { zfar - ( Znear > 1.f ? Znear : 0.f ) };
|
|
auto const quantizationstep{std::min(frustumchunkdepth, 50.f)};
|
|
frustumchunkmin = quantizationstep * glm::floor( frustumchunkmin * ( 1.f / quantizationstep ) );
|
|
frustumchunkmax = quantizationstep * glm::ceil( frustumchunkmax * ( 1.f / quantizationstep ) );
|
|
// ...use the dimensions to set up light projection boundaries...
|
|
// NOTE: since we only have one cascade map stage, we extend the chunk forward/back to catch areas normally covered by other stages
|
|
camera.projection() *=
|
|
glm::ortho(
|
|
frustumchunkmin.x, frustumchunkmax.x,
|
|
frustumchunkmin.y, frustumchunkmax.y,
|
|
frustumchunkmin.z - 500.f, frustumchunkmax.z + 500.f );
|
|
// ... and adjust the projection to sample complete shadow map texels:
|
|
// get coordinates for a sample texel...
|
|
auto shadowmaptexel = glm::vec2 { camera.projection() * glm::mat4{ viewmatrix } * glm::vec4{ 0.f, 0.f, 0.f, 1.f } };
|
|
// ...convert result from clip space to texture coordinates, and calculate adjustment...
|
|
shadowmaptexel *= m_shadowbuffersize * 0.5f;
|
|
auto shadowmapadjustment = glm::round( shadowmaptexel ) - shadowmaptexel;
|
|
// ...transform coordinate change back to homogenous light space...
|
|
shadowmapadjustment /= m_shadowbuffersize * 0.5f;
|
|
// ... and bake the adjustment into the projection matrix
|
|
camera.projection() =
|
|
glm::translate(
|
|
glm::mat4{ 1.f },
|
|
glm::vec3{ shadowmapadjustment, 0.f } )
|
|
* camera.projection();
|
|
|
|
break;
|
|
}
|
|
case rendermode::cabshadows: {
|
|
// fixed size cube large enough to enclose a vehicle compartment
|
|
// modelview
|
|
auto const lightvector =
|
|
glm::normalize( glm::vec3{
|
|
m_sunlight.direction.x,
|
|
std::min( m_sunlight.direction.y, Global.gfx_shadow_angle_min ),
|
|
m_sunlight.direction.z } );
|
|
camera.position() = Global.pCamera.Pos - glm::dvec3 { lightvector };
|
|
viewmatrix *= glm::lookAt(
|
|
camera.position(),
|
|
Global.pCamera.Pos,
|
|
glm::dvec3 { 0, 1, 0 } );
|
|
// projection
|
|
auto const maphalfsize { std::min( 10.f, Config.draw_range * 0.5f ) };
|
|
camera.projection() *=
|
|
glm::ortho(
|
|
-maphalfsize, maphalfsize,
|
|
-maphalfsize, maphalfsize,
|
|
-Config.draw_range, Config.draw_range );
|
|
/*
|
|
// adjust the projection to sample complete shadow map texels
|
|
auto shadowmaptexel = glm::vec2 { camera.projection() * glm::mat4{ viewmatrix } * glm::vec4{ 0.f, 0.f, 0.f, 1.f } };
|
|
shadowmaptexel *= ( m_shadowbuffersize / 2 ) * 0.5f;
|
|
auto shadowmapadjustment = glm::round( shadowmaptexel ) - shadowmaptexel;
|
|
shadowmapadjustment /= ( m_shadowbuffersize / 2 ) * 0.5f;
|
|
camera.projection() = glm::translate( glm::mat4{ 1.f }, glm::vec3{ shadowmapadjustment, 0.f } ) * camera.projection();
|
|
*/
|
|
break;
|
|
}
|
|
case rendermode::reflections: {
|
|
// modelview
|
|
camera.position() = (
|
|
( ( true == DebugCameraFlag ) && ( false == Ignoredebug ) ) ?
|
|
Global.pDebugCamera.Pos :
|
|
Global.pCamera.Pos );
|
|
glm::dvec3 const cubefacetargetvectors[ 6 ] = { { 1.0, 0.0, 0.0 }, { -1.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0 }, { 0.0, -1.0, 0.0 }, { 0.0, 0.0, 1.0 }, { 0.0, 0.0, -1.0 } };
|
|
glm::dvec3 const cubefaceupvectors[ 6 ] = { { 0.0, -1.0, 0.0 }, { 0.0, -1.0, 0.0 }, { 0.0, 0.0, 1.0 }, { 0.0, 0.0, -1.0 }, { 0.0, -1.0, 0.0 }, { 0.0, -1.0, 0.0 } };
|
|
auto const cubefaceindex = m_environmentcubetextureface - GL_TEXTURE_CUBE_MAP_POSITIVE_X;
|
|
viewmatrix *=
|
|
glm::lookAt(
|
|
camera.position(),
|
|
camera.position() + cubefacetargetvectors[ cubefaceindex ],
|
|
cubefaceupvectors[ cubefaceindex ] );
|
|
// projection
|
|
camera.projection() *=
|
|
glm::perspective(
|
|
glm::radians( 90.f ),
|
|
1.f,
|
|
0.1f * Global.ZoomFactor,
|
|
Config.draw_range * Global.fDistanceFactor );
|
|
break;
|
|
}
|
|
|
|
case rendermode::pickcontrols:
|
|
case rendermode::pickscenery: {
|
|
// TODO: scissor test for pick modes
|
|
// modelview
|
|
camera.position() = Global.pCamera.Pos;
|
|
Global.pCamera.SetMatrix( viewmatrix );
|
|
// projection
|
|
camera.projection() *=
|
|
glm::perspective(
|
|
glm::radians( Global.FieldOfView / Global.ZoomFactor ),
|
|
std::max( 1.f, (float)Global.window_size.x ) / std::max( 1.f, (float)Global.window_size.y ),
|
|
0.1f * Global.ZoomFactor,
|
|
Config.draw_range * Global.fDistanceFactor );
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
camera.modelview() = viewmatrix;
|
|
camera.update_frustum();
|
|
}
|
|
|
|
void
|
|
opengl_renderer::setup_matrices() {
|
|
|
|
::glMatrixMode( GL_PROJECTION );
|
|
OpenGLMatrices.load_matrix( m_renderpass.camera.projection() );
|
|
|
|
if( ( m_renderpass.draw_mode == rendermode::color )
|
|
&& ( m_environmentcubetexturesupport ) ) {
|
|
// special case, for colour render pass setup texture matrix for reflections cube map
|
|
select_unit( m_helpertextureunit );
|
|
::glMatrixMode( GL_TEXTURE );
|
|
// ::glPushMatrix();
|
|
::glLoadIdentity();
|
|
::glMultMatrixf( glm::value_ptr( glm::inverse( glm::mat4{ glm::mat3{ m_renderpass.camera.modelview() } } ) ) );
|
|
select_unit( m_diffusetextureunit );
|
|
}
|
|
|
|
// trim modelview matrix just to rotation, since rendering is done in camera-centric world space
|
|
::glMatrixMode( GL_MODELVIEW );
|
|
OpenGLMatrices.load_matrix( glm::mat4( glm::mat3( m_renderpass.camera.modelview() ) ) );
|
|
}
|
|
|
|
void
|
|
opengl_renderer::setup_drawing( bool const Alpha ) {
|
|
|
|
if( true == Alpha ) {
|
|
|
|
::glEnable( GL_BLEND );
|
|
::glAlphaFunc( GL_GREATER, 0.f );
|
|
}
|
|
else {
|
|
::glDisable( GL_BLEND );
|
|
::glAlphaFunc( GL_GREATER, EU07_OPACITYDEFAULT );
|
|
}
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::color:
|
|
case rendermode::reflections: {
|
|
::glEnable( GL_LIGHTING );
|
|
::glShadeModel( GL_SMOOTH );
|
|
if( Global.iMultisampling ) {
|
|
::glEnable( GL_MULTISAMPLE );
|
|
}
|
|
// setup fog
|
|
if( Global.fFogEnd > 0 ) {
|
|
// fog setup
|
|
m_fogrange = Global.fFogEnd / std::max( 1.f, Global.Overcast * 2.f );
|
|
::glFogfv( GL_FOG_COLOR, glm::value_ptr( Global.FogColor ) );
|
|
::glFogf( GL_FOG_DENSITY, static_cast<GLfloat>( 1.0 / m_fogrange ) );
|
|
::glEnable( GL_FOG );
|
|
}
|
|
else { ::glDisable( GL_FOG ); }
|
|
|
|
break;
|
|
}
|
|
case rendermode::pickcontrols:
|
|
case rendermode::pickscenery:
|
|
::glAlphaFunc( GL_ALWAYS, 0.0f );
|
|
[[ fallthrough ]];
|
|
case rendermode::shadows:
|
|
case rendermode::cabshadows: {
|
|
::glColor4fv( glm::value_ptr( colors::white ) );
|
|
::glDisable( GL_LIGHTING );
|
|
::glShadeModel( GL_FLAT );
|
|
if( Global.iMultisampling ) {
|
|
::glDisable( GL_MULTISAMPLE );
|
|
}
|
|
::glDisable( GL_FOG );
|
|
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
// configures, enables and disables specified texture units
|
|
void
|
|
opengl_renderer::setup_units( bool const Diffuse, bool const Shadows, bool const Reflections ) {
|
|
// helper texture unit.
|
|
// darkens previous stage, preparing data for the shadow texture unit to select from
|
|
if( m_helpertextureunit >= 0 ) {
|
|
|
|
select_unit( m_helpertextureunit );
|
|
|
|
if( ( true == Reflections )
|
|
|| ( ( true == Global.RenderShadows ) && ( true == Shadows ) && ( false == Global.bWireFrame ) ) ) {
|
|
// we need to have texture on the helper for either the reflection and shadow generation (or both)
|
|
if( true == m_environmentcubetexturesupport ) {
|
|
// bind dynamic environment cube if it's enabled...
|
|
// NOTE: environment cube map isn't part of regular texture system, so we use direct bind call here
|
|
::glBindTexture( GL_TEXTURE_CUBE_MAP, m_environmentcubetexture );
|
|
::glEnable( GL_TEXTURE_CUBE_MAP );
|
|
}
|
|
else {
|
|
// ...otherwise fallback on static spherical image
|
|
m_textures.bind( textureunit::helper, m_reflectiontexture );
|
|
::glEnable( GL_TEXTURE_2D );
|
|
}
|
|
}
|
|
else {
|
|
if( true == m_environmentcubetexturesupport ) {
|
|
::glDisable( GL_TEXTURE_CUBE_MAP );
|
|
}
|
|
else {
|
|
::glDisable( GL_TEXTURE_2D );
|
|
}
|
|
}
|
|
|
|
if( ( true == Global.RenderShadows ) && ( true == Shadows ) && ( false == Global.bWireFrame ) ) {
|
|
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE );
|
|
::glTexEnvfv( GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, glm::value_ptr( m_shadowcolor ) );
|
|
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE ); // darken the previous stage
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PREVIOUS );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_CONSTANT );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR );
|
|
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE ); // pass the previous stage alpha down the chain
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PREVIOUS );
|
|
}
|
|
else {
|
|
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE ); // pass the previous stage colour down the chain
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PREVIOUS );
|
|
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE ); // pass the previous stage alpha down the chain
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PREVIOUS );
|
|
}
|
|
|
|
if( true == Reflections ) {
|
|
if( true == m_environmentcubetexturesupport ) {
|
|
::glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP );
|
|
::glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP );
|
|
::glTexGeni( GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP );
|
|
::glEnable( GL_TEXTURE_GEN_S );
|
|
::glEnable( GL_TEXTURE_GEN_T );
|
|
::glEnable( GL_TEXTURE_GEN_R );
|
|
}
|
|
else {
|
|
// fixed texture fall back
|
|
::glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP );
|
|
::glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP );
|
|
::glEnable( GL_TEXTURE_GEN_S );
|
|
::glEnable( GL_TEXTURE_GEN_T );
|
|
}
|
|
}
|
|
else {
|
|
if( true == m_environmentcubetexturesupport ) {
|
|
::glDisable( GL_TEXTURE_GEN_S );
|
|
::glDisable( GL_TEXTURE_GEN_T );
|
|
::glDisable( GL_TEXTURE_GEN_R );
|
|
}
|
|
else {
|
|
::glDisable( GL_TEXTURE_GEN_S );
|
|
::glDisable( GL_TEXTURE_GEN_T );
|
|
}
|
|
}
|
|
}
|
|
// shadow texture unit.
|
|
// interpolates between primary colour and the previous unit, which should hold darkened variant of the primary colour
|
|
if( m_shadowtextureunit >= 0 ) {
|
|
if( ( true == Global.RenderShadows )
|
|
&& ( true == Shadows )
|
|
&& ( false == Global.bWireFrame )
|
|
&& ( m_shadowcolor != colors::white ) ) {
|
|
|
|
select_unit( m_shadowtextureunit );
|
|
// NOTE: texture and transformation matrix setup are done through separate call
|
|
::glEnable( GL_TEXTURE_2D );
|
|
// s
|
|
::glEnable( GL_TEXTURE_GEN_S );
|
|
// t
|
|
::glEnable( GL_TEXTURE_GEN_T );
|
|
// r
|
|
::glEnable( GL_TEXTURE_GEN_R );
|
|
// q
|
|
::glEnable( GL_TEXTURE_GEN_Q );
|
|
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE ); // choose between lit and lit * shadow colour, based on depth test
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PRIMARY_COLOR );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_PREVIOUS );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_TEXTURE );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_COLOR );
|
|
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE ); // pass the previous stage alpha down the chain
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PREVIOUS );
|
|
}
|
|
else {
|
|
// turn off shadow map tests
|
|
select_unit( m_shadowtextureunit );
|
|
|
|
::glDisable( GL_TEXTURE_2D );
|
|
::glDisable( GL_TEXTURE_GEN_S );
|
|
::glDisable( GL_TEXTURE_GEN_T );
|
|
::glDisable( GL_TEXTURE_GEN_R );
|
|
::glDisable( GL_TEXTURE_GEN_Q );
|
|
}
|
|
}
|
|
// reflections/normals texture unit
|
|
// NOTE: comes after diffuse stage in the operation chain
|
|
if( m_normaltextureunit >= 0 ) {
|
|
|
|
select_unit( m_normaltextureunit );
|
|
|
|
if( true == Reflections ) {
|
|
::glEnable( GL_TEXTURE_2D );
|
|
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE ); // blend between object colour and env.reflection
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_TEXTURE0 );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE1_RGB, GL_PREVIOUS );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_TEXTURE ); // alpha channel of the normal map controls reflection strength
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA );
|
|
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE ); // pass the previous stage alpha down the chain
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_PREVIOUS );
|
|
}
|
|
else {
|
|
::glDisable( GL_TEXTURE_2D );
|
|
}
|
|
}
|
|
// diffuse texture unit.
|
|
// NOTE: diffuse texture mapping is never fully disabled, alpha channel information is always included
|
|
select_unit( m_diffusetextureunit );
|
|
::glEnable( GL_TEXTURE_2D );
|
|
if( true == Diffuse ) {
|
|
// default behaviour, modulate with previous stage
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_TEXTURE );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR );
|
|
/*
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA );
|
|
*/
|
|
}
|
|
else {
|
|
// solid colour with texture alpha
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_REPLACE );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB, GL_PREVIOUS );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR );
|
|
/*
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, GL_TEXTURE );
|
|
::glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA );
|
|
*/
|
|
}
|
|
// update unit state
|
|
m_unitstate.diffuse = Diffuse;
|
|
m_unitstate.shadows = Shadows;
|
|
m_unitstate.reflections = Reflections;
|
|
}
|
|
|
|
// configures shadow texture unit for specified shadow map and conersion matrix
|
|
void
|
|
opengl_renderer::setup_shadow_map( GLuint const Texture, glm::mat4 const &Transformation ) {
|
|
|
|
if( ( m_shadowtextureunit == -1 )
|
|
|| ( false == Global.RenderShadows )
|
|
|| ( true == Global.bWireFrame )
|
|
|| ( m_shadowcolor == colors::white ) ) {
|
|
// shadows are off
|
|
return;
|
|
}
|
|
|
|
select_unit( m_shadowtextureunit );
|
|
// NOTE: shadowmap isn't part of regular texture system, so we use direct bind call here
|
|
::glBindTexture( GL_TEXTURE_2D, Texture );
|
|
// s
|
|
::glTexGenfv( GL_S, GL_EYE_PLANE, glm::value_ptr( glm::row( Transformation, 0 ) ) );
|
|
// t
|
|
::glTexGenfv( GL_T, GL_EYE_PLANE, glm::value_ptr( glm::row( Transformation, 1 ) ) );
|
|
// r
|
|
::glTexGenfv( GL_R, GL_EYE_PLANE, glm::value_ptr( glm::row( Transformation, 2 ) ) );
|
|
// q
|
|
::glTexGenfv( GL_Q, GL_EYE_PLANE, glm::value_ptr( glm::row( Transformation, 3 ) ) );
|
|
|
|
select_unit( m_diffusetextureunit );
|
|
}
|
|
|
|
// enables and disables specified texture units
|
|
void
|
|
opengl_renderer::switch_units( bool const Diffuse, bool const Shadows, bool const Reflections ) {
|
|
// helper texture unit.
|
|
if( m_helpertextureunit >= 0 ) {
|
|
|
|
select_unit( m_helpertextureunit );
|
|
if( ( true == Reflections )
|
|
|| ( ( true == Global.RenderShadows )
|
|
&& ( true == Shadows )
|
|
&& ( false == Global.bWireFrame )
|
|
&& ( m_shadowcolor != colors::white ) ) ) {
|
|
if( true == m_environmentcubetexturesupport ) {
|
|
::glEnable( GL_TEXTURE_CUBE_MAP );
|
|
}
|
|
else {
|
|
::glEnable( GL_TEXTURE_2D );
|
|
}
|
|
}
|
|
else {
|
|
if( true == m_environmentcubetexturesupport ) {
|
|
::glDisable( GL_TEXTURE_CUBE_MAP );
|
|
}
|
|
else {
|
|
::glDisable( GL_TEXTURE_2D );
|
|
}
|
|
}
|
|
}
|
|
// shadow texture unit.
|
|
if( m_shadowtextureunit >= 0 ) {
|
|
if( ( true == Global.RenderShadows ) && ( true == Shadows ) && ( false == Global.bWireFrame ) ) {
|
|
|
|
select_unit( m_shadowtextureunit );
|
|
::glEnable( GL_TEXTURE_2D );
|
|
}
|
|
else {
|
|
|
|
select_unit( m_shadowtextureunit );
|
|
::glDisable( GL_TEXTURE_2D );
|
|
}
|
|
}
|
|
// normal/reflection texture unit
|
|
if( m_normaltextureunit >= 0 ) {
|
|
if( true == Reflections ) {
|
|
|
|
select_unit( m_normaltextureunit );
|
|
::glEnable( GL_TEXTURE_2D );
|
|
}
|
|
else {
|
|
select_unit( m_normaltextureunit );
|
|
::glDisable( GL_TEXTURE_2D );
|
|
}
|
|
}
|
|
// diffuse texture unit.
|
|
// NOTE: toggle actually disables diffuse texture mapping, unlike setup counterpart
|
|
if( true == Diffuse ) {
|
|
|
|
select_unit( m_diffusetextureunit );
|
|
::glEnable( GL_TEXTURE_2D );
|
|
}
|
|
else {
|
|
|
|
select_unit( m_diffusetextureunit );
|
|
::glDisable( GL_TEXTURE_2D );
|
|
}
|
|
// update unit state
|
|
m_unitstate.diffuse = Diffuse;
|
|
m_unitstate.shadows = Shadows;
|
|
m_unitstate.reflections = Reflections;
|
|
}
|
|
|
|
void
|
|
opengl_renderer::setup_shadow_color( glm::vec4 const &Shadowcolor ) {
|
|
|
|
select_unit( m_helpertextureunit );
|
|
::glTexEnvfv( GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, glm::value_ptr( Shadowcolor ) ); // in-shadow colour multiplier
|
|
select_unit( m_diffusetextureunit );
|
|
}
|
|
|
|
void
|
|
opengl_renderer::setup_environment_light( TEnvironmentType const Environment ) {
|
|
|
|
switch( Environment ) {
|
|
case e_flat: {
|
|
m_sunlight.apply_intensity();
|
|
// m_environment = Environment;
|
|
break;
|
|
}
|
|
case e_canyon: {
|
|
m_sunlight.apply_intensity( 0.4f );
|
|
// m_environment = Environment;
|
|
break;
|
|
}
|
|
case e_tunnel: {
|
|
m_sunlight.apply_intensity( 0.2f );
|
|
// m_environment = Environment;
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
bool
|
|
opengl_renderer::Render( world_environment *Environment ) {
|
|
|
|
// calculate shadow tone, based on positions of celestial bodies
|
|
m_shadowcolor = glm::mix(
|
|
glm::vec4{ colors::shadow },
|
|
glm::vec4{ colors::white },
|
|
std::clamp( -Environment->m_sun.getAngle(), 0.f, 6.f ) / 6.f );
|
|
if( ( Environment->m_sun.getAngle() < -18.f )
|
|
&& ( Environment->m_moon.getAngle() > 0.f ) ) {
|
|
// turn on moon shadows after nautical twilight, if the moon is actually up
|
|
m_shadowcolor = colors::shadow;
|
|
}
|
|
// soften shadows depending on sky overcast factor
|
|
m_shadowcolor = glm::min(
|
|
colors::white,
|
|
m_shadowcolor + ( ( colors::white - colors::shadow ) * Global.Overcast ) );
|
|
|
|
if( Global.bWireFrame ) {
|
|
// bez nieba w trybie rysowania linii
|
|
return false;
|
|
}
|
|
|
|
Bind_Material( null_handle );
|
|
::glDisable( GL_LIGHTING );
|
|
::glDisable( GL_DEPTH_TEST );
|
|
::glDepthMask( GL_FALSE );
|
|
// skydome
|
|
// drawn with 500m radius to blend in if the fog range is low
|
|
::glPushMatrix();
|
|
::glScalef( 500.f, 500.f, 500.f );
|
|
m_skydomerenderer.render();
|
|
if( Global.bUseVBO ) {
|
|
gfx::opengl_vbogeometrybank::reset();
|
|
}
|
|
::glPopMatrix();
|
|
// stars
|
|
if( Environment->m_stars.m_stars != nullptr ) {
|
|
// setup
|
|
::glPushMatrix();
|
|
::glRotatef( Environment->m_stars.m_latitude, 1.f, 0.f, 0.f ); // ustawienie osi OY na północ
|
|
::glRotatef( -std::fmod( (float)Global.fTimeAngleDeg, 360.f ), 0.f, 1.f, 0.f ); // obrót dobowy osi OX
|
|
::glPointSize( 2.f );
|
|
// render
|
|
Render( Environment->m_stars.m_stars, nullptr, 1.0 );
|
|
// post-render cleanup
|
|
::glPointSize( 3.f );
|
|
::glPopMatrix();
|
|
}
|
|
// celestial bodies
|
|
if( DebugModeFlag == true ) {
|
|
// mark sun position for easier debugging
|
|
Environment->m_sun.render();
|
|
Environment->m_moon.render();
|
|
}
|
|
// render actual sun and moon
|
|
::glPushAttrib( GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT );
|
|
|
|
::glDisable( GL_LIGHTING );
|
|
::glDisable( GL_ALPHA_TEST );
|
|
::glEnable( GL_BLEND );
|
|
::glBlendFunc( GL_SRC_ALPHA, GL_ONE );
|
|
|
|
auto const &modelview = OpenGLMatrices.data( GL_MODELVIEW );
|
|
|
|
auto const fogfactor { std::clamp( Global.fFogEnd / 2000.f, 0.f, 1.f ) }; // closer/denser fog reduces opacity of the celestial bodies
|
|
float const duskfactor = 1.0f - std::clamp( std::abs( Environment->m_sun.getAngle() ), 0.0f, 12.0f ) / 12.0f;
|
|
glm::vec3 suncolor = glm::mix(
|
|
glm::vec3( 1.0f, 242.0f / 255.0f, 231.0f / 255.0f ),
|
|
glm::vec3( 235.0f / 255.0f, 140.0f / 255.0f, 36.0f / 255.0f ),
|
|
duskfactor );
|
|
// sun
|
|
if (!m_isATI)
|
|
{
|
|
Bind_Texture( m_suntexture );
|
|
::glColor4f( suncolor.x, suncolor.y, suncolor.z, std::clamp( 1.5f - Global.Overcast, 0.f, 1.f ) * fogfactor );
|
|
auto const sunvector = Environment->m_sun.getDirection();
|
|
auto const sunposition = modelview * glm::vec4( sunvector.x, sunvector.y, sunvector.z, 1.0f );
|
|
|
|
::glPushMatrix();
|
|
::glLoadIdentity(); // macierz jedynkowa
|
|
::glTranslatef( sunposition.x, sunposition.y, sunposition.z ); // początek układu zostaje bez zmian
|
|
|
|
float const size = std::lerp( // TODO: expose distance/scale factor from the moon object
|
|
0.0325f,
|
|
0.0275f,
|
|
std::clamp( Environment->m_sun.getAngle(), 0.f, 90.f ) / 90.f );
|
|
::glBegin( GL_TRIANGLE_STRIP );
|
|
::glMultiTexCoord2f( m_diffusetextureunit, 1.f, 1.f ); ::glVertex3f( -size, size, 0.f );
|
|
::glMultiTexCoord2f( m_diffusetextureunit, 1.f, 0.f ); ::glVertex3f( -size, -size, 0.f );
|
|
::glMultiTexCoord2f( m_diffusetextureunit, 0.f, 1.f ); ::glVertex3f( size, size, 0.f );
|
|
::glMultiTexCoord2f( m_diffusetextureunit, 0.f, 0.f ); ::glVertex3f( size, -size, 0.f );
|
|
::glEnd();
|
|
|
|
::glPopMatrix();
|
|
}
|
|
// moon
|
|
if (!m_isATI)
|
|
{
|
|
Bind_Texture( m_moontexture );
|
|
glm::vec3 mooncolor(1.0f, 0.9490196f, 0.9058824f);
|
|
::glColor4f(
|
|
mooncolor.r, mooncolor.g, mooncolor.b,
|
|
// fade the moon if it's near the sun in the sky, especially during the day
|
|
std::max<float>(
|
|
0.f,
|
|
1.0
|
|
- 0.5 * Global.fLuminance
|
|
- 0.65 * std::max( 0.f, glm::dot( Environment->m_sun.getDirection(), Environment->m_moon.getDirection() ) ) )
|
|
* fogfactor );
|
|
|
|
auto const moonposition = modelview * glm::vec4( Environment->m_moon.getDirection(), 1.0f );
|
|
::glPushMatrix();
|
|
::glLoadIdentity(); // macierz jedynkowa
|
|
::glTranslatef( moonposition.x, moonposition.y, moonposition.z );
|
|
|
|
float const size = std::lerp( // TODO: expose distance/scale factor from the moon object
|
|
0.0160f,
|
|
0.0135f,
|
|
std::clamp( Environment->m_moon.getAngle(), 0.f, 90.f ) / 90.f );
|
|
// choose the moon appearance variant, based on current moon phase
|
|
// NOTE: implementation specific, 8 variants are laid out in 3x3 arrangement
|
|
// from new moon onwards, top left to right bottom (last spot is left for future use, if any)
|
|
auto const moonphase = Environment->m_moon.getPhase();
|
|
float moonu, moonv;
|
|
if( moonphase < 1.84566f ) { moonv = 1.0f - 0.0f; moonu = 0.0f; }
|
|
else if( moonphase < 5.53699f ) { moonv = 1.0f - 0.0f; moonu = 0.333f; }
|
|
else if( moonphase < 9.22831f ) { moonv = 1.0f - 0.0f; moonu = 0.667f; }
|
|
else if( moonphase < 12.91963f ) { moonv = 1.0f - 0.333f; moonu = 0.0f; }
|
|
else if( moonphase < 16.61096f ) { moonv = 1.0f - 0.333f; moonu = 0.333f; }
|
|
else if( moonphase < 20.30228f ) { moonv = 1.0f - 0.333f; moonu = 0.667f; }
|
|
else if( moonphase < 23.99361f ) { moonv = 1.0f - 0.667f; moonu = 0.0f; }
|
|
else if( moonphase < 27.68493f ) { moonv = 1.0f - 0.667f; moonu = 0.333f; }
|
|
else if( moonphase == 50 ) { moonv = 1.0f - 0.667f; moonu = 0.66f; } //9th slot used for easter egg
|
|
else { moonv = 1.0f - 0.0f; moonu = 0.0f; }
|
|
|
|
::glBegin( GL_TRIANGLE_STRIP );
|
|
::glMultiTexCoord2f( m_diffusetextureunit, moonu, moonv ); ::glVertex3f( -size, size, 0.0f );
|
|
::glMultiTexCoord2f( m_diffusetextureunit, moonu, moonv - 0.333f ); ::glVertex3f( -size, -size, 0.0f );
|
|
::glMultiTexCoord2f( m_diffusetextureunit, moonu + 0.333f, moonv ); ::glVertex3f( size, size, 0.0f );
|
|
::glMultiTexCoord2f( m_diffusetextureunit, moonu + 0.333f, moonv - 0.333f ); ::glVertex3f( size, -size, 0.0f );
|
|
::glEnd();
|
|
|
|
::glPopMatrix();
|
|
}
|
|
::glPopAttrib();
|
|
|
|
m_sunlight.apply_angle();
|
|
m_sunlight.apply_intensity();
|
|
|
|
// clouds
|
|
if( Environment->m_clouds.mdCloud ) {
|
|
// setup
|
|
Disable_Lights();
|
|
::glEnable( GL_LIGHTING );
|
|
::glEnable( GL_LIGHT0 ); // other lights will be enabled during lights update
|
|
::glLightModelfv(
|
|
GL_LIGHT_MODEL_AMBIENT,
|
|
glm::value_ptr(
|
|
glm::mix( Environment->m_skydome.GetAverageColor(), suncolor, duskfactor * 0.25f )
|
|
* std::lerp( 1.f, 0.35f, Global.Overcast / 2.f ) // overcast darkens the clouds
|
|
* 0.5f // arbitrary adjustment factor
|
|
) );
|
|
// render
|
|
Render( Environment->m_clouds.mdCloud, nullptr, 100.0 );
|
|
Render_Alpha( Environment->m_clouds.mdCloud, nullptr, 100.0 );
|
|
// post-render cleanup
|
|
::glLightModelfv( GL_LIGHT_MODEL_AMBIENT, glm::value_ptr( colors::none ) );
|
|
::glDisable( GL_LIGHTING );
|
|
}
|
|
|
|
::glDepthMask( GL_TRUE );
|
|
::glEnable( GL_DEPTH_TEST );
|
|
::glEnable( GL_LIGHTING );
|
|
|
|
return true;
|
|
}
|
|
|
|
// geometry methods
|
|
// creates a new geometry bank. returns: handle to the bank or NULL
|
|
gfx::geometrybank_handle
|
|
opengl_renderer::Create_Bank() {
|
|
if (Global.bUseVBO)
|
|
return m_geometry.register_bank(std::make_unique<gfx::opengl_vbogeometrybank>());
|
|
else
|
|
return m_geometry.register_bank(std::make_unique<gfx::opengl_dlgeometrybank>());
|
|
}
|
|
|
|
// creates a new indexed geometry chunk of specified type from supplied data, in specified bank. returns: handle to the chunk or NULL
|
|
gfx::geometry_handle opengl_renderer::Insert(gfx::index_array &Indices, gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type)
|
|
{
|
|
|
|
return m_geometry.create_chunk( Indices, Vertices, Userdata, Geometry, Type );
|
|
}
|
|
|
|
// creates a new geometry chunk of specified type from supplied data, in specified bank. returns: handle to the chunk or NULL
|
|
gfx::geometry_handle opengl_renderer::Insert(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometrybank_handle const &Geometry, int const Type)
|
|
{
|
|
|
|
return m_geometry.create_chunk( Vertices, Userdata, Geometry, Type );
|
|
}
|
|
|
|
// replaces data of specified chunk with the supplied vertex data, starting from specified offset
|
|
bool opengl_renderer::Replace(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometry_handle const &Geometry, int const Type, const std::size_t Offset)
|
|
{
|
|
|
|
return m_geometry.replace( Vertices, Userdata, Geometry, Offset );
|
|
}
|
|
|
|
// adds supplied vertex data at the end of specified chunk
|
|
bool opengl_renderer::Append(gfx::vertex_array &Vertices, gfx::userdata_array &Userdata, gfx::geometry_handle const &Geometry, int const Type)
|
|
{
|
|
|
|
return m_geometry.append( Vertices, Userdata, Geometry );
|
|
}
|
|
|
|
void opengl_renderer::Erase( gfx::geometry_handle const &Geometry )
|
|
{
|
|
m_geometry.erase( Geometry );
|
|
}
|
|
|
|
// provides direct access to vertex data of specfied chunk
|
|
gfx::index_array const &
|
|
opengl_renderer::Indices( gfx::geometry_handle const &Geometry ) const {
|
|
|
|
return m_geometry.indices( Geometry );
|
|
}
|
|
|
|
// provides direct access to vertex data of specfied chunk
|
|
gfx::vertex_array const &
|
|
opengl_renderer::Vertices( gfx::geometry_handle const &Geometry ) const {
|
|
|
|
return m_geometry.vertices( Geometry );
|
|
}
|
|
|
|
gfx::userdata_array const &opengl_renderer::UserData(const gfx::geometry_handle &Geometry) const
|
|
{
|
|
return m_geometry.userdata( Geometry );
|
|
}
|
|
|
|
// material methods
|
|
material_handle
|
|
opengl_renderer::Fetch_Material( std::string const &Filename, bool const Loadnow ) {
|
|
|
|
return m_materials.create( Filename, Loadnow );
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Bind_Material( material_handle const Material, TSubModel const *sm, lighting_data const *lighting ) {
|
|
|
|
if( Material != null_handle ) {
|
|
|
|
auto const &material { m_materials.material( Material ) };
|
|
|
|
if( false == material.is_good ) {
|
|
// use failure indicator instead
|
|
if( Material != m_invalid_material ) {
|
|
Bind_Material( m_invalid_material );
|
|
}
|
|
return;
|
|
}
|
|
|
|
// materials which declare texture variants provide a different texture set per model instance,
|
|
// picked from the seed of the rendered instance and the variant group of the submodel
|
|
auto const &materialtextures {
|
|
material.texture_variants.empty() ?
|
|
material.textures :
|
|
material.GetTextures( TSubModel::VariantId( sm ) ) };
|
|
|
|
if( false == Global.BasicRenderer ) {
|
|
m_textures.bind( m_normaltextureunit, materialtextures[1] );
|
|
}
|
|
m_textures.bind( m_diffusetextureunit, materialtextures[0] );
|
|
}
|
|
else {
|
|
// null material, unbind all textures
|
|
if( false == Global.BasicRenderer ) {
|
|
m_textures.bind( m_normaltextureunit, null_handle );
|
|
}
|
|
m_textures.bind( m_diffusetextureunit, null_handle );
|
|
}
|
|
}
|
|
|
|
IMaterial const *
|
|
opengl_renderer::Material( material_handle const Material ) const {
|
|
|
|
return &m_materials.material( Material );
|
|
}
|
|
|
|
opengl_material const &
|
|
opengl_renderer::Material( TSubModel const * Submodel ) const {
|
|
|
|
return m_materials.material( submodel_material( Submodel ) );
|
|
}
|
|
|
|
// shader methods
|
|
std::shared_ptr<gl::program>
|
|
opengl_renderer::Fetch_Shader( std::string const &name ) {
|
|
|
|
return std::shared_ptr<gl::program>();
|
|
}
|
|
|
|
// texture methods
|
|
void
|
|
opengl_renderer::select_unit( GLint const Textureunit ) {
|
|
|
|
return m_textures.unit( Textureunit );
|
|
}
|
|
|
|
texture_handle
|
|
opengl_renderer::Fetch_Texture( std::string const &Filename, bool const Loadnow, GLint format_hint ) {
|
|
|
|
return m_textures.create( Filename, Loadnow, GL_RGBA );
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Bind_Texture( texture_handle const Texture ) {
|
|
|
|
m_textures.bind( m_diffusetextureunit, Texture );
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Bind_Texture( std::size_t const Unit, texture_handle const Texture ) {
|
|
|
|
m_textures.bind( Unit, Texture );
|
|
}
|
|
|
|
ITexture &
|
|
opengl_renderer::Texture( texture_handle const Texture ) {
|
|
|
|
return m_textures.texture( Texture );
|
|
}
|
|
|
|
ITexture const &
|
|
opengl_renderer::Texture( texture_handle const Texture ) const {
|
|
|
|
return m_textures.texture( Texture );
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Pick_Control_Callback( std::function<void( TSubModel const *, const glm::vec2 )> Callback ) {
|
|
|
|
m_control_pick_requests.emplace_back( Callback );
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Pick_Node_Callback( std::function<void( scene::basic_node * )> Callback ) {
|
|
|
|
m_node_pick_requests.emplace_back( Callback );
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Forget_Node( scene::basic_node const *Node ) {
|
|
|
|
if( m_picksceneryitem == Node ) {
|
|
m_picksceneryitem = nullptr;
|
|
}
|
|
std::ranges::replace_if( m_picksceneryitems, [Node]( scene::basic_node const *Item ) { return Item == Node; }, nullptr );
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Render( scene::basic_region *Region ) {
|
|
|
|
m_sectionqueue.clear();
|
|
m_cellqueue.clear();
|
|
// build a list of region sections to render
|
|
glm::vec3 const cameraposition { m_renderpass.camera.position() };
|
|
auto const camerax = static_cast<int>( std::floor( cameraposition.x / scene::EU07_SECTIONSIZE + scene::EU07_REGIONSIDESECTIONCOUNT / 2 ) );
|
|
auto const cameraz = static_cast<int>( std::floor( cameraposition.z / scene::EU07_SECTIONSIZE + scene::EU07_REGIONSIDESECTIONCOUNT / 2 ) );
|
|
float section_range = m_renderpass.draw_range * Global.fDistanceFactor;
|
|
section_range = editor_track_view_range( section_range, EditorModeFlag && ( m_renderpass.draw_mode == rendermode::color || m_renderpass.draw_mode == rendermode::pickscenery ) );
|
|
int const segmentcount = 2 * static_cast<int>( std::ceil( section_range / scene::EU07_SECTIONSIZE ) );
|
|
int const originx = camerax - segmentcount / 2;
|
|
int const originz = cameraz - segmentcount / 2;
|
|
|
|
for( int row = originz; row <= originz + segmentcount; ++row ) {
|
|
if( row < 0 ) { continue; }
|
|
if( row >= scene::EU07_REGIONSIDESECTIONCOUNT ) { break; }
|
|
for( int column = originx; column <= originx + segmentcount; ++column ) {
|
|
if( column < 0 ) { continue; }
|
|
if( column >= scene::EU07_REGIONSIDESECTIONCOUNT ) { break; }
|
|
auto *section { Region->m_sections[ row * scene::EU07_REGIONSIDESECTIONCOUNT + column ] };
|
|
if( ( section != nullptr )
|
|
&& ( m_renderpass.camera.visible( section->m_area ) ) ) {
|
|
m_sectionqueue.emplace_back( section );
|
|
}
|
|
}
|
|
}
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::color: {
|
|
|
|
Update_Lights( simulation::Lights );
|
|
|
|
Render( std::begin( m_sectionqueue ), std::end( m_sectionqueue ) );
|
|
if( EditorModeFlag ) {
|
|
// when editor mode is active calculate world position of the cursor
|
|
// at this stage the z-buffer is filled with only ground geometry
|
|
Update_Mouse_Position();
|
|
}
|
|
// draw queue is filled while rendering sections
|
|
Render( std::begin( m_cellqueue ), std::end( m_cellqueue ) );
|
|
break;
|
|
}
|
|
case rendermode::shadows:
|
|
case rendermode::cabshadows:
|
|
case rendermode::pickscenery: {
|
|
// these render modes don't bother with lights
|
|
Render( std::begin( m_sectionqueue ), std::end( m_sectionqueue ) );
|
|
// they can also skip queue sorting, as they only deal with opaque geometry
|
|
// NOTE: there's benefit from rendering front-to-back, but is it significant enough? TODO: investigate
|
|
Render( std::begin( m_cellqueue ), std::end( m_cellqueue ) );
|
|
break;
|
|
}
|
|
case rendermode::reflections: {
|
|
Render( std::begin( m_sectionqueue ), std::end( m_sectionqueue ) );
|
|
if( Global.reflectiontune.fidelity >= 1 ) {
|
|
Render(std::begin(m_cellqueue), std::end(m_cellqueue));
|
|
}
|
|
break;
|
|
}
|
|
case rendermode::pickcontrols:
|
|
default: {
|
|
// no need to render anything ourside of the cab in control picking mode
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Render( section_sequence::iterator First, section_sequence::iterator Last ) {
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::color:
|
|
case rendermode::reflections: {
|
|
|
|
break;
|
|
}
|
|
case rendermode::shadows:
|
|
case rendermode::cabshadows: {
|
|
// experimental, for shadows render both back and front faces, to supply back faces of the 'forest strips'
|
|
::glDisable( GL_CULL_FACE );
|
|
break; }
|
|
case rendermode::pickscenery: {
|
|
// non-interactive scenery elements get neutral colour
|
|
::glColor3fv( glm::value_ptr( colors::none ) );
|
|
break;
|
|
}
|
|
default: {
|
|
break; }
|
|
}
|
|
|
|
// the ground of the sections far off, the terrain of the editor among it, isn't drawn with the tracks reaching there
|
|
auto const scenery_limit{ static_cast<double>( Global.BaseDrawRange ) * Global.fDistanceFactor + 250.0 };
|
|
bool const far_paths{ EditorModeFlag && Global.editor_tracks && ( m_renderpass.draw_mode == rendermode::color || m_renderpass.draw_mode == rendermode::pickscenery ) };
|
|
glm::dvec3 const camera{ m_renderpass.camera.position() };
|
|
|
|
while( First != Last ) {
|
|
|
|
auto *section = *First;
|
|
section->create_geometry();
|
|
|
|
// render shapes held by the section
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::color:
|
|
case rendermode::reflections:
|
|
case rendermode::shadows:
|
|
case rendermode::cabshadows:
|
|
case rendermode::pickscenery: {
|
|
if( false == section->m_shapes.empty() && false == editor_far_tracks_only( far_paths, section->m_area, camera, scenery_limit ) ) {
|
|
// since all shapes of the section share center point we can optimize out a few calls here
|
|
::glPushMatrix();
|
|
auto const originoffset { section->m_area.center - m_renderpass.camera.position() };
|
|
::glTranslated( originoffset.x, originoffset.y, originoffset.z );
|
|
// render
|
|
for( auto const &shape : section->m_shapes ) { Render( shape, true ); }
|
|
// post-render cleanup
|
|
::glPopMatrix();
|
|
}
|
|
break;
|
|
}
|
|
case rendermode::pickcontrols:
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
|
|
// add the section's cells to the cell queue
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::color:
|
|
case rendermode::shadows:
|
|
case rendermode::cabshadows:
|
|
case rendermode::pickscenery: {
|
|
// TBD, TODO: refactor into a method to reuse below?
|
|
for( auto &cell : section->m_cells ) {
|
|
if( ( true == cell.m_active )
|
|
&& ( m_renderpass.camera.visible( cell.m_area ) ) ) {
|
|
// store visible cells with content as well as their current distance, for sorting later
|
|
m_cellqueue.emplace_back(
|
|
glm::length2( m_renderpass.camera.position() - cell.m_area.center ),
|
|
&cell );
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case rendermode::reflections: {
|
|
// we can skip filling the cell queue if reflections pass isn't going to use it
|
|
if( Global.reflectiontune.fidelity == 0 ) { break; }
|
|
for( auto &cell : section->m_cells ) {
|
|
if( ( true == cell.m_active ) && ( m_renderpass.camera.visible( cell.m_area ) ) ) {
|
|
// store visible cells with content as well as their current distance, for sorting later
|
|
m_cellqueue.emplace_back( glm::length2( m_renderpass.camera.position() - cell.m_area.center ), &cell );
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case rendermode::pickcontrols:
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
// proceed to next section
|
|
++First;
|
|
}
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::shadows:
|
|
case rendermode::cabshadows: {
|
|
// restore standard face cull mode
|
|
::glEnable( GL_CULL_FACE );
|
|
break; }
|
|
default: {
|
|
break; }
|
|
}
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Render( cell_sequence::iterator First, cell_sequence::iterator Last ) {
|
|
|
|
// cache initial iterator for the second sweep
|
|
auto first { First };
|
|
auto const scenery_limit{ static_cast<double>( Global.BaseDrawRange ) * Global.fDistanceFactor + 250.0 };
|
|
bool const far_paths{ EditorModeFlag && Global.editor_tracks && ( m_renderpass.draw_mode == rendermode::color || m_renderpass.draw_mode == rendermode::pickscenery ) };
|
|
glm::dvec3 const camera{ m_renderpass.camera.position() };
|
|
// first pass draws elements which we know are located in section banks, to reduce vbo switching
|
|
while( First != Last ) {
|
|
|
|
auto *cell = First->second;
|
|
// przeliczenia animacji torów w sektorze
|
|
cell->RaAnimate( m_framestamp );
|
|
bool const tracks_only{ editor_far_tracks_only( far_paths, cell->m_area, camera, scenery_limit ) };
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::color: {
|
|
// since all shapes of the section share center point we can optimize out a few calls here
|
|
::glPushMatrix();
|
|
auto const originoffset { cell->m_area.center - m_renderpass.camera.position() };
|
|
::glTranslated( originoffset.x, originoffset.y, originoffset.z );
|
|
|
|
// render
|
|
// opaque non-instanced shapes
|
|
if( false == tracks_only ) {
|
|
for( auto const &shape : cell->m_shapesopaque ) { Render( shape, false ); }
|
|
}
|
|
// tracks
|
|
// TODO: update after path node refactoring
|
|
Render( std::begin( cell->m_paths ), std::end( cell->m_paths ) );
|
|
#ifdef EU07_USE_DEBUG_CULLING
|
|
// debug
|
|
::glLineWidth( 2.f );
|
|
float const width = cell->m_area.radius;
|
|
float const height = cell->m_area.radius * 0.2f;
|
|
glDisable( GL_LIGHTING );
|
|
glDisable( GL_TEXTURE_2D );
|
|
glColor3ub( 255, 128, 128 );
|
|
glBegin( GL_LINE_LOOP );
|
|
glVertex3f( -width, height, width );
|
|
glVertex3f( -width, height, -width );
|
|
glVertex3f( width, height, -width );
|
|
glVertex3f( width, height, width );
|
|
glEnd();
|
|
glBegin( GL_LINE_LOOP );
|
|
glVertex3f( -width, 0, width );
|
|
glVertex3f( -width, 0, -width );
|
|
glVertex3f( width, 0, -width );
|
|
glVertex3f( width, 0, width );
|
|
glEnd();
|
|
glBegin( GL_LINES );
|
|
glVertex3f( -width, height, width ); glVertex3f( -width, 0, width );
|
|
glVertex3f( -width, height, -width ); glVertex3f( -width, 0, -width );
|
|
glVertex3f( width, height, -width ); glVertex3f( width, 0, -width );
|
|
glVertex3f( width, height, width ); glVertex3f( width, 0, width );
|
|
glEnd();
|
|
glColor3ub( 255, 255, 255 );
|
|
glEnable( GL_TEXTURE_2D );
|
|
glEnable( GL_LIGHTING );
|
|
glLineWidth( 1.f );
|
|
#endif
|
|
// post-render cleanup
|
|
::glPopMatrix();
|
|
|
|
break;
|
|
}
|
|
case rendermode::reflections:
|
|
{
|
|
// since all shapes of the section share center point we can optimize out a few calls here
|
|
::glPushMatrix();
|
|
auto const originoffset{ cell->m_area.center - m_renderpass.camera.position() };
|
|
::glTranslated( originoffset.x, originoffset.y, originoffset.z );
|
|
|
|
// render
|
|
// opaque non-instanced shapes
|
|
for( auto const &shape : cell->m_shapesopaque ) { Render( shape, false ); }
|
|
|
|
// post-render cleanup
|
|
::glPopMatrix();
|
|
|
|
break;
|
|
}
|
|
case rendermode::shadows: {
|
|
// since all shapes of the section share center point we can optimize out a few calls here
|
|
::glPushMatrix();
|
|
auto const originoffset { cell->m_area.center - m_renderpass.camera.position() };
|
|
::glTranslated( originoffset.x, originoffset.y, originoffset.z );
|
|
|
|
// render
|
|
// opaque non-instanced shapes
|
|
for( auto const &shape : cell->m_shapesopaque ) {
|
|
Render( shape, false );
|
|
}
|
|
// tracks
|
|
Render( std::begin( cell->m_paths ), std::end( cell->m_paths ) );
|
|
|
|
// post-render cleanup
|
|
::glPopMatrix();
|
|
|
|
break;
|
|
}
|
|
case rendermode::cabshadows: {
|
|
// since all shapes of the section share center point we can optimize out a few calls here
|
|
::glPushMatrix();
|
|
auto const originoffset { cell->m_area.center - m_renderpass.camera.position() };
|
|
::glTranslated( originoffset.x, originoffset.y, originoffset.z );
|
|
|
|
// render
|
|
// opaque non-instanced shapes
|
|
for( auto const &shape : cell->m_shapesopaque ) {
|
|
Render( shape, false );
|
|
}
|
|
// NOTE: tracks aren't likely to cast shadows into the cab, so we skip them in this pass
|
|
|
|
// post-render cleanup
|
|
::glPopMatrix();
|
|
|
|
break;
|
|
}
|
|
case rendermode::pickscenery: {
|
|
// same procedure like with regular render, but editor-enabled nodes receive custom colour used for picking
|
|
// since all shapes of the section share center point we can optimize out a few calls here
|
|
::glPushMatrix();
|
|
auto const originoffset { cell->m_area.center - m_renderpass.camera.position() };
|
|
::glTranslated( originoffset.x, originoffset.y, originoffset.z );
|
|
// render
|
|
// opaque non-instanced shapes
|
|
// non-interactive scenery elements get neutral colour
|
|
if( false == tracks_only ) {
|
|
::glColor3fv( glm::value_ptr( colors::none ) );
|
|
for( auto const &shape : cell->m_shapesopaque ) { Render( shape, false ); }
|
|
}
|
|
// tracks
|
|
for( auto *path : cell->m_paths ) {
|
|
::glColor3fv( glm::value_ptr( pick_color( m_picksceneryitems.size() + 1 ) ) );
|
|
Render( path );
|
|
}
|
|
|
|
// post-render cleanup
|
|
::glPopMatrix();
|
|
|
|
break;
|
|
}
|
|
case rendermode::pickcontrols:
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
|
|
++First;
|
|
}
|
|
// second pass draws elements with their own vbos
|
|
while( first != Last ) {
|
|
|
|
auto const *cell = first->second;
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::color:
|
|
case rendermode::shadows:
|
|
case rendermode::cabshadows: {
|
|
if( editor_far_tracks_only( far_paths, cell->m_area, camera, scenery_limit ) )
|
|
break;
|
|
// TBD, TODO: refactor in to a method to reuse in branch below?
|
|
// opaque parts of instanced models
|
|
for( auto *instance : cell->m_instancesopaque ) {
|
|
Render( instance );
|
|
}
|
|
// opaque parts of vehicles
|
|
for( auto *path : cell->m_paths ) {
|
|
for( auto *dynamic : path->Dynamics ) {
|
|
Render( dynamic );
|
|
}
|
|
}
|
|
// memcells
|
|
if( ( EditorModeFlag )
|
|
&& ( DebugModeFlag ) ) {
|
|
::glPushAttrib( GL_ENABLE_BIT );
|
|
::glDisable( GL_TEXTURE_2D );
|
|
::glColor3f( 0.36f, 0.75f, 0.35f );
|
|
for( auto *memorycell : cell->m_memorycells ) {
|
|
Render( memorycell );
|
|
}
|
|
::glPopAttrib();
|
|
}
|
|
break;
|
|
}
|
|
case rendermode::reflections: {
|
|
if( Global.reflectiontune.fidelity >= 1 ) {
|
|
// opaque parts of instanced models
|
|
for( auto *instance : cell->m_instancesopaque ) {
|
|
Render( instance );
|
|
}
|
|
}
|
|
if( Global.reflectiontune.fidelity >= 2 ) {
|
|
// opaque parts of vehicles
|
|
for( auto *path : cell->m_paths ) {
|
|
for( auto *dynamic : path->Dynamics ) {
|
|
Render( dynamic );
|
|
}
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case rendermode::pickscenery: {
|
|
if( editor_far_tracks_only( far_paths, cell->m_area, camera, scenery_limit ) )
|
|
break;
|
|
// opaque parts of instanced models
|
|
// same procedure like with regular render, but each node receives custom colour used for picking
|
|
for( auto *instance : cell->m_instancesopaque ) {
|
|
::glColor3fv( glm::value_ptr( pick_color( m_picksceneryitems.size() + 1 ) ) );
|
|
Render( instance );
|
|
}
|
|
// memcells
|
|
if( ( EditorModeFlag )
|
|
&& ( DebugModeFlag ) ) {
|
|
for( auto *memorycell : cell->m_memorycells ) {
|
|
::glColor3fv( glm::value_ptr( pick_color( m_picksceneryitems.size() + 1 ) ) );
|
|
Render( memorycell );
|
|
}
|
|
}
|
|
// vehicles aren't included in scenery picking for the time being
|
|
break;
|
|
}
|
|
case rendermode::pickcontrols:
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
|
|
++first;
|
|
}
|
|
#ifdef EU07_USE_DEBUG_SOUNDEMITTERS
|
|
// sound emitters
|
|
if( DebugModeFlag ) {
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::color: {
|
|
|
|
::glPushAttrib( GL_ENABLE_BIT );
|
|
::glDisable( GL_TEXTURE_2D );
|
|
::glColor3f( 0.36f, 0.75f, 0.35f );
|
|
|
|
for( auto const &audiosource : audio::renderer.m_sources ) {
|
|
|
|
::glPushMatrix();
|
|
auto const position = audiosource.properties.location - m_renderpass.camera.position();
|
|
::glTranslated( position.x, position.y, position.z );
|
|
|
|
::gluSphere( m_quadric, 0.1, 4, 2 );
|
|
|
|
::glPopMatrix();
|
|
}
|
|
|
|
::glPopAttrib();
|
|
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
#endif
|
|
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Render( scene::shape_node const &Shape, bool const Ignorerange ) {
|
|
|
|
auto const &data { Shape.data() };
|
|
|
|
if( false == Ignorerange ) {
|
|
double distancesquared;
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::shadows:
|
|
case rendermode::cabshadows: {
|
|
// 'camera' for the light pass is the light source, but we need to draw what the 'real' camera sees
|
|
distancesquared = glm::length2( ( data.area.center - Global.pCamera.Pos ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor;
|
|
break;
|
|
}
|
|
case rendermode::reflections: {
|
|
// reflection mode draws simplified version of the shapes, by artificially increasing view range
|
|
distancesquared =
|
|
// TBD, TODO: bind offset value with setting variable?
|
|
sq(EU07_REFLECTIONFIDELITYOFFSET)
|
|
// TBD: take into account distance multipliers?
|
|
+ glm::length2( ( data.area.center - m_renderpass.camera.position() ) ) /* / Global.fDistanceFactor */;
|
|
break;
|
|
}
|
|
default: {
|
|
distancesquared = glm::length2( ( data.area.center - m_renderpass.camera.position() ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor;
|
|
break;
|
|
}
|
|
}
|
|
if( ( distancesquared < data.rangesquared_min )
|
|
|| ( distancesquared >= data.rangesquared_max ) ) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
// setup
|
|
Bind_Material( data.material );
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::color:
|
|
case rendermode::reflections: {
|
|
::glColor3fv( glm::value_ptr( data.lighting.diffuse ) );
|
|
/*
|
|
// NOTE: ambient component is set by diffuse component
|
|
// NOTE: for the time being non-instanced shapes are rendered without specular component due to wrong/arbitrary values set in legacy scenarios
|
|
// TBD, TODO: find a way to resolve this with the least amount of tears?
|
|
::glMaterialfv( GL_FRONT, GL_SPECULAR, glm::value_ptr( data.lighting.specular * m_sunlight.specular.a * m_specularopaquescalefactor ) );
|
|
*/
|
|
break;
|
|
}
|
|
// pick modes are painted with custom colours, and shadow pass doesn't use any
|
|
case rendermode::shadows: {
|
|
// skip if the shadow caster rank is too low for currently set threshold
|
|
if( Material( data.material )->GetShadowRank() > Global.gfx_shadow_rank_cutoff ) {
|
|
return;
|
|
}
|
|
}
|
|
[[ fallthrough ]];
|
|
case rendermode::cabshadows:
|
|
case rendermode::pickscenery:
|
|
case rendermode::pickcontrols:
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
// render
|
|
m_geometry.draw( data.geometry );
|
|
// debug data
|
|
++m_renderpass.draw_stats.shapes;
|
|
++m_renderpass.draw_stats.drawcalls;
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Render( TAnimModel *Instance ) {
|
|
|
|
if( false == Instance->m_visible ) { return; }
|
|
if( false == m_renderpass.camera.visible( Instance->m_area ) ) { return; }
|
|
|
|
double distancesquared;
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::shadows:
|
|
case rendermode::cabshadows: {
|
|
// 'camera' for the light pass is the light source, but we need to draw what the 'real' camera sees
|
|
distancesquared = glm::length2((Instance->location() - m_renderpass.camera.position()) / (double)Global.ZoomFactor) / Global.fDistanceFactor;
|
|
break;
|
|
}
|
|
case rendermode::reflections: {
|
|
// reflection mode draws simplified version of the shapes, by artificially increasing view range
|
|
// it also ignores zoom settings and distance multipliers
|
|
// TBD: take into account distance multipliers?
|
|
distancesquared = glm::length2( ( Instance->location() - m_renderpass.camera.position() ) ) /* / Global.fDistanceFactor */;
|
|
// NOTE: arbitrary draw range limit
|
|
if( distancesquared > Global.reflectiontune.range_instances * Global.reflectiontune.range_instances ) {
|
|
return;
|
|
}
|
|
// TBD, TODO: bind offset value with setting variable?
|
|
distancesquared += sq(EU07_REFLECTIONFIDELITYOFFSET);
|
|
break;
|
|
}
|
|
default: {
|
|
distancesquared = glm::length2((Instance->location() - m_renderpass.camera.position()) / (double)Global.ZoomFactor) / Global.fDistanceFactor;
|
|
break;
|
|
}
|
|
}
|
|
if( ( distancesquared < Instance->m_rangesquaredmin )
|
|
|| ( distancesquared >= Instance->m_rangesquaredmax ) ) {
|
|
return;
|
|
}
|
|
// crude way to reject early items too far to affect the output (mostly relevant for shadow passes)
|
|
auto const drawdistancethreshold{ m_renderpass.draw_range + 250 };
|
|
if( distancesquared > sq(drawdistancethreshold) ) {
|
|
return;
|
|
}
|
|
// second stage visibility cull, reject modelstoo far away to be noticeable
|
|
auto const radiussquared { Instance->radius() * Instance->radius() };
|
|
if( radiussquared * Global.ZoomFactor / distancesquared < 0.003 * 0.003 ) {
|
|
return;
|
|
}
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::pickscenery: {
|
|
// add the node to the pick list
|
|
m_picksceneryitems.emplace_back( Instance );
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
|
|
Instance->RaAnimate( m_framestamp ); // jednorazowe przeliczenie animacji
|
|
Instance->RaPrepare();
|
|
if( Instance->pModel ) {
|
|
// renderowanie rekurencyjne submodeli
|
|
auto const position { Instance->location() - m_renderpass.camera.position() };
|
|
if( is_scaled( Instance->Scale() ) ) {
|
|
// the scale stretches the normals too, they're normalized again for the lighting
|
|
push_scaled_instance_transform( position, Instance->vAngle, Instance->Scale() );
|
|
m_normalizenormals = true;
|
|
Render( Instance->pModel, Instance->Material(), distancesquared );
|
|
m_normalizenormals = false;
|
|
::glPopMatrix();
|
|
}
|
|
else {
|
|
Render(
|
|
Instance->pModel,
|
|
Instance->Material(),
|
|
distancesquared,
|
|
position,
|
|
Instance->vAngle );
|
|
}
|
|
// debug data
|
|
++m_renderpass.draw_stats.models;
|
|
}
|
|
}
|
|
|
|
bool
|
|
opengl_renderer::Render( TDynamicObject *Dynamic ) {
|
|
|
|
Dynamic->renderme = (
|
|
( Global.pCamera.m_owner == Dynamic && !FreeFlyModeFlag )
|
|
|| ( m_renderpass.camera.visible( Dynamic ) ) );
|
|
|
|
if( false == Dynamic->renderme ) { return false; }
|
|
|
|
// lod visibility ranges are defined for base (x 1.0) viewing distance. for render we adjust them for actual range multiplier and zoom
|
|
float squaredistance;
|
|
glm::dvec3 const originoffset = Dynamic->vPosition - m_renderpass.camera.position();
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::shadows: {
|
|
squaredistance = glm::length2( glm::vec3{ glm::dvec3{ Dynamic->vPosition - Global.pCamera.Pos } } / Global.ZoomFactor );
|
|
if( false == FreeFlyModeFlag ) {
|
|
// filter out small details if we're in vehicle cab
|
|
squaredistance = std::max( sq(100.f), squaredistance );
|
|
}
|
|
break;
|
|
}
|
|
case rendermode::cabshadows: {
|
|
squaredistance = glm::length2( glm::vec3{ glm::dvec3{ Dynamic->vPosition - Global.pCamera.Pos } } / Global.ZoomFactor );
|
|
// filter out small details
|
|
squaredistance = std::max( sq(100.f), squaredistance );
|
|
break;
|
|
}
|
|
case rendermode::reflections: {
|
|
// reflection mode draws simplified version of the shapes, by artificially increasing view range
|
|
// it also ignores zoom settings and distance multipliers
|
|
squaredistance =
|
|
std::max(
|
|
sq(100.f),
|
|
// TBD: take into account distance multipliers?
|
|
glm::length2( glm::vec3{ originoffset } ) /* / Global.fDistanceFactor */ );
|
|
// NOTE: arbitrary draw range limit
|
|
if( squaredistance > Global.reflectiontune.range_vehicles * Global.reflectiontune.range_vehicles ) {
|
|
return false;
|
|
}
|
|
// TBD, TODO: bind offset value with setting variable?
|
|
// NOTE: combined 'squared' distance doesn't equal actual squared (distance + offset) but, eh
|
|
squaredistance += sq(EU07_REFLECTIONFIDELITYOFFSET);
|
|
break;
|
|
}
|
|
default: {
|
|
squaredistance = glm::length2( glm::vec3{ originoffset } / Global.ZoomFactor );
|
|
// TODO: filter out small details based on fidelity setting
|
|
break;
|
|
}
|
|
}
|
|
// crude way to reject early items too far to affect the output (mostly relevant for shadow and reflection passes)
|
|
auto const drawdistancethreshold{ m_renderpass.draw_range + 250 };
|
|
if( squaredistance > sq(drawdistancethreshold) ) {
|
|
return false;
|
|
}
|
|
// second stage visibility cull, reject vehicles too far away to be noticeable
|
|
Dynamic->renderme = ( Dynamic->radius() * Global.ZoomFactor / std::sqrt( squaredistance ) > 0.003 );
|
|
if( false == Dynamic->renderme ) {
|
|
return false;
|
|
}
|
|
|
|
// debug data
|
|
++m_renderpass.draw_stats.dynamics;
|
|
|
|
|
|
// setup
|
|
TSubModel::iInstance = reinterpret_cast<std::uintptr_t>( Dynamic ); //żeby nie robić cudzych animacji
|
|
TSubModel::iVariantSeed = Dynamic->variant_seed();
|
|
Dynamic->ABuLittleUpdate( squaredistance ); // ustawianie zmiennych submodeli dla wspólnego modelu
|
|
::glPushMatrix();
|
|
|
|
::glTranslated( originoffset.x, originoffset.y, originoffset.z );
|
|
::glMultMatrixd( glm::value_ptr(Dynamic->mMatrix) );
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
|
|
case rendermode::color: {
|
|
if( Dynamic->fShade > 0.0f ) {
|
|
// change light level based on light level of the occupied track
|
|
m_sunlight.apply_intensity( Dynamic->fShade );
|
|
}
|
|
m_renderspecular = true; // vehicles are rendered with specular component. static models without, at least for the time being
|
|
// render
|
|
if( Dynamic->mdLowPolyInt ) {
|
|
Render_lowpoly( Dynamic, squaredistance, false );
|
|
}
|
|
else {
|
|
// HACK: if the model lacks low poly interior, we presume the load is placed outside
|
|
if( Dynamic->mdLoad ) {
|
|
// renderowanie nieprzezroczystego ładunku
|
|
Render( Dynamic->mdLoad, Dynamic->Material(), squaredistance, { 0.f, Dynamic->LoadOffset, 0.f }, {} );
|
|
}
|
|
}
|
|
if( Dynamic->mdModel ) {
|
|
// main model
|
|
Render( Dynamic->mdModel, Dynamic->Material(), squaredistance );
|
|
}
|
|
// optional attached models
|
|
for( auto *attachment : Dynamic->mdAttachments ) {
|
|
Render( attachment, Dynamic->Material(), squaredistance );
|
|
}
|
|
// optional coupling adapters
|
|
Render_coupler_adapter( Dynamic, squaredistance, end::front );
|
|
Render_coupler_adapter( Dynamic, squaredistance, end::rear );
|
|
// post-render cleanup
|
|
m_renderspecular = false;
|
|
if( Dynamic->fShade > 0.0f ) {
|
|
// restore regular light level
|
|
m_sunlight.apply_intensity();
|
|
}
|
|
break;
|
|
}
|
|
case rendermode::shadows:
|
|
case rendermode::cabshadows: {
|
|
if( Dynamic->mdLowPolyInt ) {
|
|
// low poly interior
|
|
// if( FreeFlyModeFlag ? true : !Dynamic->mdKabina || !Dynamic->bDisplayCab ) {
|
|
Render( Dynamic->mdLowPolyInt, Dynamic->Material(), squaredistance );
|
|
// }
|
|
}
|
|
if( Dynamic->mdModel ) {
|
|
// main model
|
|
Render( Dynamic->mdModel, Dynamic->Material(), squaredistance );
|
|
}
|
|
// optional attached models
|
|
for( auto *attachment : Dynamic->mdAttachments ) {
|
|
Render( attachment, Dynamic->Material(), squaredistance );
|
|
}
|
|
// optional coupling adapters
|
|
Render_coupler_adapter( Dynamic, squaredistance, end::front );
|
|
Render_coupler_adapter( Dynamic, squaredistance, end::rear );
|
|
if( Dynamic->mdLoad ) {
|
|
// renderowanie nieprzezroczystego ładunku
|
|
Render( Dynamic->mdLoad, Dynamic->Material(), squaredistance, { 0.f, Dynamic->LoadOffset, 0.f }, {} );
|
|
}
|
|
// post-render cleanup
|
|
break;
|
|
}
|
|
case rendermode::pickcontrols: {
|
|
if( Dynamic->mdLowPolyInt ) {
|
|
// low poly interior
|
|
Render( Dynamic->mdLowPolyInt, Dynamic->Material(), squaredistance );
|
|
}
|
|
break;
|
|
}
|
|
case rendermode::pickscenery:
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
|
|
::glPopMatrix();
|
|
|
|
// TODO: check if this reset is needed. In theory each object should render all parts based on its own instance data anyway?
|
|
if( Dynamic->btnOn )
|
|
Dynamic->TurnOff(); // przywrócenie domyślnych pozycji submodeli
|
|
|
|
return true;
|
|
}
|
|
|
|
// rendering kabiny gdy jest oddzielnym modelem i ma byc wyswietlana
|
|
bool
|
|
opengl_renderer::Render_cab( TDynamicObject const *Dynamic, float const Lightlevel, bool const Alpha ) {
|
|
|
|
if( Dynamic == nullptr ) {
|
|
|
|
TSubModel::iInstance = 0;
|
|
TSubModel::iVariantSeed = 0;
|
|
return false;
|
|
}
|
|
|
|
TSubModel::iInstance = reinterpret_cast<std::uintptr_t>( Dynamic );
|
|
TSubModel::iVariantSeed = Dynamic->variant_seed();
|
|
|
|
if( ( true == FreeFlyModeFlag )
|
|
|| ( false == Dynamic->bDisplayCab )
|
|
|| ( Dynamic->mdKabina == Dynamic->mdModel ) ) {
|
|
// ABu: Rendering kabiny jako ostatniej, zeby bylo widac przez szyby, tylko w widoku ze srodka
|
|
return false;
|
|
}
|
|
|
|
if( Dynamic->mdKabina ) { // bo mogła zniknąć przy przechodzeniu do innego pojazdu
|
|
// setup shared by all render paths
|
|
::glPushMatrix();
|
|
|
|
auto const originoffset = Dynamic->GetPosition() - m_renderpass.camera.position();
|
|
::glTranslated( originoffset.x, originoffset.y, originoffset.z );
|
|
::glMultMatrixd( glm::value_ptr(Dynamic->mMatrix) );
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::color: {
|
|
// render path specific setup:
|
|
if( Dynamic->fShade > 0.0f ) {
|
|
// change light level based on light level of the occupied track
|
|
m_sunlight.apply_intensity( Dynamic->fShade );
|
|
}
|
|
if( Lightlevel > 0.f ) {
|
|
// crude way to light the cabin, until we have something more complete in place
|
|
auto const luminance { Global.fLuminance * ( Dynamic->fShade > 0.0f ? Dynamic->fShade : 1.0f ) };
|
|
::glLightModelfv(
|
|
GL_LIGHT_MODEL_AMBIENT,
|
|
glm::value_ptr(
|
|
glm::vec3( m_baseambient )
|
|
+ ( Dynamic->InteriorLight * Lightlevel ) * static_cast<float>( std::clamp( 1.25 - luminance, 0.0, 1.0 ) ) ) );
|
|
}
|
|
// render
|
|
if( true == Alpha ) {
|
|
// translucent parts
|
|
Render_Alpha( Dynamic->mdKabina, Dynamic->Material(), 0.0 );
|
|
}
|
|
else {
|
|
// opaque parts
|
|
Render( Dynamic->mdKabina, Dynamic->Material(), 0.0 );
|
|
}
|
|
// post-render restore
|
|
if( Dynamic->fShade > 0.0f ) {
|
|
// change light level based on light level of the occupied track
|
|
m_sunlight.apply_intensity();
|
|
}
|
|
if( Lightlevel > 0.f ) {
|
|
// reset the overall ambient
|
|
::glLightModelfv( GL_LIGHT_MODEL_AMBIENT, glm::value_ptr(m_baseambient) );
|
|
}
|
|
break;
|
|
}
|
|
case rendermode::cabshadows: {
|
|
// cab shadowmap mode skips lighting setup and translucent parts
|
|
// render
|
|
if( true == Alpha ) {
|
|
// translucent parts
|
|
Render_Alpha( Dynamic->mdKabina, Dynamic->Material(), 0.0 );
|
|
}
|
|
else {
|
|
// opaque parts
|
|
Render( Dynamic->mdKabina, Dynamic->Material(), 0.0 );
|
|
}
|
|
// since the setup is simpler, there's nothing to reset afterwards
|
|
break;
|
|
}
|
|
case rendermode::pickcontrols: {
|
|
// control picking mode skips lighting setup and translucent parts
|
|
// render
|
|
Render( Dynamic->mdKabina, Dynamic->Material(), 0.0 );
|
|
// since the setup is simpler, there's nothing to reset afterwards
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
// post-render restore
|
|
::glPopMatrix();
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
bool
|
|
opengl_renderer::Render( TModel3d *Model, material_data const *Material, float const Squaredistance ) {
|
|
|
|
auto alpha =
|
|
( Material != nullptr ?
|
|
Material->textures_alpha :
|
|
0x30300030 );
|
|
alpha ^= 0x0F0F000F; // odwrócenie flag tekstur, aby wyłapać nieprzezroczyste
|
|
if( 0 == ( alpha & Model->iFlags & 0x1F1F001F ) ) {
|
|
// czy w ogóle jest co robić w tym cyklu?
|
|
return false;
|
|
}
|
|
|
|
Model->Root->fSquareDist = Squaredistance; // zmienna globalna!
|
|
|
|
// setup
|
|
Model->Root->ReplacableSet(
|
|
( Material != nullptr ?
|
|
Material->replacable_skins :
|
|
nullptr ),
|
|
alpha );
|
|
|
|
Model->Root->pRoot = Model;
|
|
|
|
// render
|
|
Render( Model->Root );
|
|
|
|
// post-render cleanup
|
|
|
|
return true;
|
|
}
|
|
|
|
bool
|
|
opengl_renderer::Render( TModel3d *Model, material_data const *Material, float const Squaredistance, glm::dvec3 const &Position, glm::vec3 const &Angle ) {
|
|
|
|
::glPushMatrix();
|
|
::glTranslated( Position.x, Position.y, Position.z );
|
|
if( Angle.y != 0.0 )
|
|
::glRotatef( Angle.y, 0.f, 1.f, 0.f );
|
|
if( Angle.x != 0.0 )
|
|
::glRotatef( Angle.x, 1.f, 0.f, 0.f );
|
|
if( Angle.z != 0.0 )
|
|
::glRotatef( Angle.z, 0.f, 0.f, 1.f );
|
|
|
|
auto const result = Render( Model, Material, Squaredistance );
|
|
|
|
::glPopMatrix();
|
|
|
|
return result;
|
|
}
|
|
|
|
// opaque characters of a text display, laid out in a row the same way as the translucent ones
|
|
void
|
|
opengl_renderer::Render_text( TSubModel *Submodel ) {
|
|
|
|
if( TSubModel::pasText == nullptr ) { return; }
|
|
|
|
::glPushMatrix();
|
|
for( auto *p : Submodel->text_letters( *TSubModel::pasText ) ) {
|
|
Render( p );
|
|
if( p->fMatrix )
|
|
::glMultMatrixf( p->fMatrix->readArray() ); // move on to the place of the next character
|
|
}
|
|
::glPopMatrix();
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Render( TSubModel *Submodel ) {
|
|
|
|
if( ( Submodel->iVisible )
|
|
&& ( TSubModel::fSquareDist >= Submodel->fSquareMinDist )
|
|
&& ( TSubModel::fSquareDist < Submodel->fSquareMaxDist ) ) {
|
|
|
|
if( Submodel->iFlags & 0xC000 ) {
|
|
::glPushMatrix();
|
|
if( Submodel->fMatrix )
|
|
::glMultMatrixf( Submodel->fMatrix->readArray() );
|
|
if( Submodel->b_Anim != TAnimType::at_None )
|
|
Submodel->RaAnimation( Submodel->b_Anim );
|
|
}
|
|
|
|
if( Submodel->eType < TP_ROTATOR ) {
|
|
// renderowanie obiektów OpenGL
|
|
if( Submodel->iAlpha & Submodel->iFlags & 0x1F ) {
|
|
// rysuj gdy element nieprzezroczysty
|
|
|
|
// debug data
|
|
++m_renderpass.draw_stats.submodels;
|
|
++m_renderpass.draw_stats.drawcalls;
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::color:
|
|
case rendermode::reflections: {
|
|
// NOTE: code disabled as normalization marking doesn't take into account scaling propagation down hierarchy chains
|
|
// for the time being we'll do with enforced worst-case scaling method, when speculars are enabled
|
|
#ifdef EU07_USE_OPTIMIZED_NORMALIZATION
|
|
switch( Submodel->m_normalizenormals ) {
|
|
case TSubModel::normalize: {
|
|
::glEnable( GL_NORMALIZE ); break; }
|
|
case TSubModel::rescale: {
|
|
::glEnable( GL_RESCALE_NORMAL ); break; }
|
|
default: {
|
|
break; }
|
|
}
|
|
#else
|
|
if( ( true == m_renderspecular ) || ( true == m_normalizenormals ) ) {
|
|
::glEnable( GL_NORMALIZE );
|
|
}
|
|
#endif
|
|
// material configuration:
|
|
auto const material{ submodel_material( Submodel ) }; // zmienialne skóry, również 0
|
|
// textures...
|
|
Bind_Material( material );
|
|
// ...colors and opacity...
|
|
auto const opacity { std::clamp( Material( material )->get_or_guess_opacity(), 0.f, 1.f ) };
|
|
if( Submodel->fVisible < 1.f ) {
|
|
// setup
|
|
::glAlphaFunc( GL_GREATER, 0.f );
|
|
::glEnable( GL_BLEND );
|
|
::glColor4f(
|
|
Submodel->f4Diffuse.r,
|
|
Submodel->f4Diffuse.g,
|
|
Submodel->f4Diffuse.b,
|
|
Submodel->fVisible );
|
|
}
|
|
else {
|
|
::glColor3fv( glm::value_ptr( Submodel->f4Diffuse ) ); // McZapkie-240702: zamiast ub
|
|
if( ( opacity != 0.f )
|
|
&& ( opacity != EU07_OPACITYDEFAULT ) ) {
|
|
::glAlphaFunc( GL_GREATER, opacity );
|
|
}
|
|
}
|
|
// ...specular...
|
|
if( ( true == m_renderspecular ) && ( m_sunlight.specular.a > 0.01f ) ) {
|
|
// specular strength in legacy models is set uniformly to 150, 150, 150 so we scale it down for opaque elements
|
|
::glMaterialfv( GL_FRONT, GL_SPECULAR, glm::value_ptr( Submodel->f4Specular * m_sunlight.specular.a * m_specularopaquescalefactor ) );
|
|
::glEnable( GL_RESCALE_NORMAL );
|
|
}
|
|
// ...luminance
|
|
auto const unitstate = m_unitstate;
|
|
auto const isemissive { ( Submodel->f4Emision.a > 0.f ) && ( Global.fLuminance < Submodel->fLight ) };
|
|
if( isemissive ) {
|
|
// zeby swiecilo na kolorowo
|
|
::glMaterialfv( GL_FRONT, GL_EMISSION, glm::value_ptr( /* Submodel->f4Emision */ Submodel->f4Diffuse * Submodel->f4Emision.a ) );
|
|
// disable shadows so they don't obstruct self-lit items
|
|
/*
|
|
setup_shadow_color( colors::white );
|
|
*/
|
|
switch_units( unitstate.diffuse, false, false );
|
|
}
|
|
|
|
// main draw call
|
|
m_geometry.draw( Submodel->m_geometry.handle );
|
|
/*
|
|
if( DebugModeFlag ) {
|
|
auto const & vertices { m_geometry.vertices( Submodel->m_geometry ) };
|
|
::glBegin( GL_LINES );
|
|
for( auto const &vertex : vertices ) {
|
|
::glVertex3fv( glm::value_ptr( vertex.position ) );
|
|
::glVertex3fv( glm::value_ptr( vertex.position + vertex.normal * 0.2f ) );
|
|
}
|
|
::glEnd();
|
|
}
|
|
*/
|
|
// post-draw reset
|
|
if( Submodel->fVisible < 1.f ) {
|
|
::glAlphaFunc( GL_GREATER, EU07_OPACITYDEFAULT );
|
|
::glDisable( GL_BLEND );
|
|
}
|
|
else if( ( opacity != 0.f )
|
|
&& ( opacity != EU07_OPACITYDEFAULT ) ) {
|
|
::glAlphaFunc( GL_GREATER, EU07_OPACITYDEFAULT );
|
|
}
|
|
if( ( true == m_renderspecular ) && ( m_sunlight.specular.a > 0.01f ) ) {
|
|
::glMaterialfv( GL_FRONT, GL_SPECULAR, glm::value_ptr( colors::none ) );
|
|
}
|
|
if( isemissive ) {
|
|
// restore default (lack of) brightness
|
|
::glMaterialfv( GL_FRONT, GL_EMISSION, glm::value_ptr( colors::none ) );
|
|
/*
|
|
setup_shadow_color( m_shadowcolor );
|
|
*/
|
|
switch_units( unitstate.diffuse, unitstate.shadows, unitstate.reflections );
|
|
}
|
|
#ifdef EU07_USE_OPTIMIZED_NORMALIZATION
|
|
switch( Submodel->m_normalizenormals ) {
|
|
case TSubModel::normalize: {
|
|
::glDisable( GL_NORMALIZE ); break; }
|
|
case TSubModel::rescale: {
|
|
::glDisable( GL_RESCALE_NORMAL ); break; }
|
|
default: {
|
|
break; }
|
|
}
|
|
#else
|
|
if( ( true == m_renderspecular ) || ( true == m_normalizenormals ) ) {
|
|
::glDisable( GL_NORMALIZE );
|
|
}
|
|
#endif
|
|
break;
|
|
}
|
|
case rendermode::shadows: {
|
|
// skip if the shadow caster rank is too low for currently set threshold
|
|
// or if the submodel is hidden (colour pass only fades it out, e.g. inactive seasonal variant)
|
|
if( ( Material( Submodel ).shadow_rank > Global.gfx_shadow_rank_cutoff )
|
|
|| ( Submodel->fVisible <= 0.f ) )
|
|
{
|
|
--m_renderpass.draw_stats.submodels;
|
|
--m_renderpass.draw_stats.drawcalls;
|
|
break;
|
|
}
|
|
}
|
|
[[fallthrough]];
|
|
case rendermode::cabshadows:
|
|
case rendermode::pickscenery: {
|
|
// scenery picking and shadow both use enforced colour and no frills
|
|
// material configuration:
|
|
// textures...
|
|
if( Submodel->m_material < 0 ) { // zmienialne skóry
|
|
Bind_Material( submodel_material( Submodel ), Submodel );
|
|
}
|
|
else {
|
|
// również 0
|
|
Bind_Material( Submodel->m_material, Submodel );
|
|
}
|
|
// main draw call
|
|
m_geometry.draw( Submodel->m_geometry.handle );
|
|
// post-draw reset
|
|
break;
|
|
}
|
|
case rendermode::pickcontrols: {
|
|
// material configuration:
|
|
// control picking applies individual colour for each submodel
|
|
m_pickcontrolsitems.emplace_back( Submodel );
|
|
::glColor3fv( glm::value_ptr( pick_color( m_pickcontrolsitems.size() ) ) );
|
|
// textures...
|
|
if( Submodel->m_material < 0 ) { // zmienialne skóry
|
|
Bind_Material( submodel_material( Submodel ), Submodel );
|
|
}
|
|
else {
|
|
// również 0
|
|
Bind_Material( Submodel->m_material, Submodel );
|
|
}
|
|
// main draw call
|
|
m_geometry.draw( Submodel->m_geometry.handle );
|
|
// post-draw reset
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
else if( Submodel->eType == TP_FREESPOTLIGHT ) {
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
// spotlights are only rendered in colour mode(s)
|
|
case rendermode::color:
|
|
case rendermode::reflections: {
|
|
auto const &modelview = OpenGLMatrices.data( GL_MODELVIEW );
|
|
auto const lightcenter =
|
|
modelview
|
|
* glm::mix(
|
|
glm::vec4( 0.f, 0.f, -0.05f, 1.f ),
|
|
glm::vec4( 0.f, 0.f, -0.25f, 1.f ),
|
|
static_cast<float>( TSubModel::fSquareDist / Submodel->fSquareMaxDist ) ); // pozycja punktu świecącego względem kamery
|
|
Submodel->fCosViewAngle = glm::dot( glm::normalize( modelview * glm::vec4( 0.f, 0.f, -1.f, 1.f ) - lightcenter ), glm::normalize( -lightcenter ) );
|
|
|
|
if( Submodel->fCosViewAngle > Submodel->fCosFalloffAngle ) {
|
|
// kąt większy niż maksymalny stożek swiatła
|
|
float lightlevel = 1.f; // TODO, TBD: parameter to control light strength
|
|
// view angle attenuation
|
|
float const anglefactor = std::clamp(
|
|
( Submodel->fCosViewAngle - Submodel->fCosFalloffAngle ) / ( Submodel->fCosHotspotAngle - Submodel->fCosFalloffAngle ),
|
|
0.f, 1.f );
|
|
lightlevel *= anglefactor;
|
|
// distance attenuation. NOTE: since it's fixed pipeline with built-in gamma correction we're using linear attenuation
|
|
// we're capping how much effect the distance attenuation can have, otherwise the lights get too tiny at regular distances
|
|
float const distancefactor { std::max( 0.5f, ( Submodel->fSquareMaxDist - TSubModel::fSquareDist ) / Submodel->fSquareMaxDist ) };
|
|
auto const pointsize { std::max( 3.f, 5.f * distancefactor * anglefactor ) };
|
|
|
|
// additionally reduce light strength for farther sources in rain or snow
|
|
if( Global.Overcast > 0.75f ) {
|
|
float const precipitationfactor{
|
|
std::lerp(
|
|
std::lerp( 1.f, 0.25f, std::clamp( Global.Overcast * 0.75f - 0.5f, 0.f, 1.f ) ),
|
|
1.f,
|
|
distancefactor ) };
|
|
lightlevel *= precipitationfactor;
|
|
}
|
|
|
|
if( lightlevel > 0.f ) {
|
|
// material configuration:
|
|
Bind_Material( null_handle );
|
|
// limit impact of dense fog on the lights
|
|
auto const lightrange { std::max<float>( 500, m_fogrange * 2 ) }; // arbitrary, visibility at least 500m
|
|
::glFogf( GL_FOG_DENSITY, static_cast<GLfloat>( 1.0 / lightrange ) );
|
|
|
|
::glPushAttrib( GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_POINT_BIT );
|
|
::glDisable( GL_LIGHTING );
|
|
::glEnable( GL_BLEND );
|
|
::glAlphaFunc( GL_GREATER, 0.f );
|
|
|
|
::glPushMatrix();
|
|
::glLoadIdentity();
|
|
::glTranslatef( lightcenter.x, lightcenter.y, lightcenter.z ); // początek układu zostaje bez zmian
|
|
|
|
auto const unitstate = m_unitstate;
|
|
switch_units( m_unitstate.diffuse, false, false );
|
|
|
|
glm::vec3 const lightcolor {
|
|
Submodel->DiffuseOverride.r < 0.f ? // -1 indicates no override
|
|
glm::vec3( Submodel->f4Diffuse ) :
|
|
Submodel->DiffuseOverride };
|
|
|
|
// main draw call
|
|
if( Global.Overcast > 1.f ) {
|
|
// fake fog halo
|
|
float const fogfactor {
|
|
std::lerp(
|
|
2.f, 1.f,
|
|
std::clamp( Global.fFogEnd / 2000, 0.f, 1.f ) )
|
|
* std::max( 1.f, Global.Overcast ) };
|
|
|
|
::glPointSize( pointsize * fogfactor );
|
|
::glColor4f(
|
|
lightcolor.r,
|
|
lightcolor.g,
|
|
lightcolor.b,
|
|
Submodel->fVisible * std::min( 1.f, lightlevel ) * 0.5f );
|
|
::glDepthMask( GL_FALSE );
|
|
m_geometry.draw( Submodel->m_geometry.handle );
|
|
::glDepthMask( GL_TRUE );
|
|
}
|
|
::glPointSize( pointsize );
|
|
::glColor4f(
|
|
lightcolor.r,
|
|
lightcolor.g,
|
|
lightcolor.b,
|
|
Submodel->fVisible * std::min( 1.f, lightlevel ) );
|
|
m_geometry.draw( Submodel->m_geometry.handle );
|
|
|
|
// post-draw reset
|
|
switch_units( unitstate.diffuse, unitstate.shadows, unitstate.reflections );
|
|
|
|
::glPopMatrix();
|
|
::glPopAttrib();
|
|
::glFogf( GL_FOG_DENSITY, static_cast<GLfloat>( 1.0 / m_fogrange ) );
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
else if( Submodel->eType == TP_STARS ) {
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
// colour points are only rendered in colour mode(s)
|
|
case rendermode::color:
|
|
case rendermode::reflections: {
|
|
if( Global.fLuminance < Submodel->fLight ) {
|
|
|
|
// material configuration:
|
|
::glPushAttrib( GL_ENABLE_BIT );
|
|
|
|
Bind_Material( null_handle );
|
|
::glDisable( GL_LIGHTING );
|
|
|
|
// main draw call
|
|
m_geometry.draw( Submodel->m_geometry.handle, gfx::color_streams );
|
|
|
|
// post-draw reset
|
|
::glPopAttrib();
|
|
}
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if( Submodel->Child != nullptr
|
|
&& ( TSubModel::iAlpha & Submodel->iFlags & 0x001F0000 ) ) {
|
|
if( Submodel->eType == TP_TEXT ) {
|
|
Render_text( Submodel );
|
|
}
|
|
else {
|
|
Render( Submodel->Child );
|
|
}
|
|
}
|
|
|
|
if( Submodel->iFlags & 0xC000 )
|
|
::glPopMatrix();
|
|
}
|
|
/*
|
|
if( Submodel->b_Anim < at_SecondsJump )
|
|
Submodel->b_Anim = at_None; // wyłączenie animacji dla kolejnego użycia subm
|
|
*/
|
|
if( Submodel->Next )
|
|
if( Submodel->iAlpha & Submodel->iFlags & 0x1F000000 )
|
|
Render( Submodel->Next ); // dalsze rekurencyjnie
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Render( TTrack *Track ) {
|
|
|
|
if( ( Track->m_material1 == 0 )
|
|
&& ( Track->m_material2 == 0 )
|
|
&& ( ( Track->eType != tt_Switch )
|
|
|| ( Track->SwitchExtension->m_material3 == 0 ) ) ) {
|
|
return;
|
|
}
|
|
if( false == Track->m_visible ) {
|
|
return;
|
|
}
|
|
|
|
++m_renderpass.draw_stats.paths;
|
|
++m_renderpass.draw_stats.drawcalls;
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
// single path pieces are rendererd in pick scenery mode only
|
|
case rendermode::pickscenery: {
|
|
// add the node to the pick list
|
|
m_picksceneryitems.emplace_back( Track );
|
|
|
|
if( Track->m_material1 != 0 ) {
|
|
Bind_Material( Track->m_material1 );
|
|
m_geometry.draw( std::begin( Track->Geometry1 ), std::end( Track->Geometry1 ) );
|
|
}
|
|
if( Track->m_material2 != 0 ) {
|
|
Bind_Material( Track->m_material2 );
|
|
m_geometry.draw( std::begin( Track->Geometry2 ), std::end( Track->Geometry2 ) );
|
|
}
|
|
for( auto const &tread : Track->GeometryTreads ) {
|
|
Bind_Material( tread.material );
|
|
m_geometry.draw( std::begin( tread.geometry ), std::end( tread.geometry ) );
|
|
}
|
|
if( ( Track->eType == tt_Switch )
|
|
&& ( Track->SwitchExtension->m_material3 != 0 ) ) {
|
|
Bind_Material( Track->SwitchExtension->m_material3 );
|
|
m_geometry.draw( Track->SwitchExtension->Geometry3 );
|
|
}
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
// the cut faces of the rails of a track and the treads of the wheels on them, in the matte variants of the rail materials
|
|
void
|
|
opengl_renderer::Render_cuts( TTrack const *Track ) {
|
|
|
|
std::vector<std::pair<material_handle, TTrack::geometryhandle_sequence const *>> parts { { Track->m_materialcut1, &Track->GeometryCut1 }, { Track->m_materialcut2, &Track->GeometryCut2 } };
|
|
for( auto const &tread : Track->GeometryTreads ) {
|
|
parts.emplace_back( tread.material, &tread.geometry );
|
|
parts.emplace_back( tread.matte, &tread.cuts );
|
|
}
|
|
for( auto const &[ material, geometry ] : parts ) {
|
|
if( ( material == null_handle )
|
|
|| ( geometry->empty() ) ) {
|
|
continue;
|
|
}
|
|
if( Track->eEnvironment != e_flat ) {
|
|
setup_environment_light( Track->eEnvironment );
|
|
}
|
|
Bind_Material( material );
|
|
m_geometry.draw( std::begin( *geometry ), std::end( *geometry ) );
|
|
if( Track->eEnvironment != e_flat ) {
|
|
setup_environment_light();
|
|
}
|
|
}
|
|
}
|
|
|
|
// experimental, does track rendering in two passes, to take advantage of reduced texture switching
|
|
void
|
|
opengl_renderer::Render( scene::basic_cell::path_sequence::const_iterator First, scene::basic_cell::path_sequence::const_iterator Last ) {
|
|
|
|
::glColor3fv( glm::value_ptr( colors::white ) );
|
|
// setup
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::shadows:
|
|
case rendermode::cabshadows: {
|
|
// NOTE: roads-based platforms tend to miss parts of shadows if rendered with either back or front culling
|
|
::glDisable( GL_CULL_FACE );
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
|
|
// TODO: render auto generated trackbeds together with regular trackbeds in pass 1, and all rails in pass 2
|
|
// first pass, material 1
|
|
for( auto first { First }; first != Last; ++first ) {
|
|
|
|
auto const track { *first };
|
|
|
|
if( track->m_material1 == 0 ) {
|
|
continue;
|
|
}
|
|
if( false == track->m_visible ) {
|
|
continue;
|
|
}
|
|
|
|
++m_renderpass.draw_stats.paths;
|
|
++m_renderpass.draw_stats.drawcalls;
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::color:
|
|
case rendermode::reflections: {
|
|
if( track->eEnvironment != e_flat ) {
|
|
setup_environment_light( track->eEnvironment );
|
|
}
|
|
Bind_Material( track->m_material1 );
|
|
m_geometry.draw( std::begin( track->Geometry1 ), std::end( track->Geometry1 ) );
|
|
if( track->eEnvironment != e_flat ) {
|
|
// restore default lighting
|
|
setup_environment_light();
|
|
}
|
|
break;
|
|
}
|
|
case rendermode::shadows:
|
|
case rendermode::cabshadows: {
|
|
if( ( std::abs( track->fTexHeight1 ) < 0.35f )
|
|
|| ( track->iCategoryFlag != 2 ) ) {
|
|
// shadows are only calculated for high enough roads, typically meaning track platforms
|
|
continue;
|
|
}
|
|
if( Material( track->m_material1 )->GetShadowRank() > Global.gfx_shadow_rank_cutoff )
|
|
{
|
|
// skip if the shadow caster rank is too low for currently set threshold
|
|
continue;
|
|
}
|
|
Bind_Material( track->m_material1 );
|
|
m_geometry.draw( std::begin( track->Geometry1 ), std::end( track->Geometry1 ) );
|
|
break;
|
|
}
|
|
case rendermode::pickscenery: // pick scenery mode uses piece-by-piece approach
|
|
case rendermode::pickcontrols:
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
// second pass, material 2
|
|
for( auto first { First }; first != Last; ++first ) {
|
|
|
|
auto const track { *first };
|
|
|
|
if( track->m_material2 == 0 ) {
|
|
continue;
|
|
}
|
|
if( false == track->m_visible ) {
|
|
continue;
|
|
}
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::color:
|
|
case rendermode::reflections: {
|
|
if( track->eEnvironment != e_flat ) {
|
|
setup_environment_light( track->eEnvironment );
|
|
}
|
|
Bind_Material( track->m_material2 );
|
|
m_geometry.draw( std::begin( track->Geometry2 ), std::end( track->Geometry2 ) );
|
|
if( track->eEnvironment != e_flat ) {
|
|
// restore default lighting
|
|
setup_environment_light();
|
|
}
|
|
break;
|
|
}
|
|
case rendermode::shadows:
|
|
case rendermode::cabshadows: {
|
|
if( ( std::abs( track->fTexHeight1 ) < 0.35f )
|
|
|| ( ( track->iCategoryFlag == 1 )
|
|
&& ( track->eType != tt_Normal ) ) ) {
|
|
// shadows are only calculated for high enough trackbeds
|
|
continue;
|
|
}
|
|
if( Material( track->m_material2 )->GetShadowRank() > Global.gfx_shadow_rank_cutoff )
|
|
{
|
|
// skip if the shadow caster rank is too low for currently set threshold
|
|
continue;
|
|
}
|
|
Bind_Material( track->m_material2 );
|
|
m_geometry.draw( std::begin( track->Geometry2 ), std::end( track->Geometry2 ) );
|
|
break;
|
|
}
|
|
case rendermode::pickscenery: // pick scenery mode uses piece-by-piece approach
|
|
case rendermode::pickcontrols:
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
// third pass, material 3
|
|
for( auto first { First }; first != Last; ++first ) {
|
|
|
|
auto const track { *first };
|
|
|
|
if( track->eType != tt_Switch ) {
|
|
continue;
|
|
}
|
|
if( track->SwitchExtension->m_material3 == 0 ) {
|
|
continue;
|
|
}
|
|
if( false == track->m_visible ) {
|
|
continue;
|
|
}
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::color:
|
|
case rendermode::reflections: {
|
|
if( track->eEnvironment != e_flat ) {
|
|
setup_environment_light( track->eEnvironment );
|
|
}
|
|
Bind_Material( track->SwitchExtension->m_material3 );
|
|
m_geometry.draw( track->SwitchExtension->Geometry3 );
|
|
if( track->eEnvironment != e_flat ) {
|
|
// restore default lighting
|
|
setup_environment_light();
|
|
}
|
|
break;
|
|
}
|
|
case rendermode::shadows:
|
|
case rendermode::cabshadows: {
|
|
if( ( std::abs( track->fTexHeight1 ) < 0.35f )
|
|
|| ( ( track->iCategoryFlag == 1 )
|
|
&& ( track->eType != tt_Normal ) ) ) {
|
|
// shadows are only calculated for high enough trackbeds
|
|
continue;
|
|
}
|
|
if( Material( track->SwitchExtension->m_material3 )->GetShadowRank() > Global.gfx_shadow_rank_cutoff )
|
|
{
|
|
// skip if the shadow caster rank is too low for currently set threshold
|
|
continue;
|
|
}
|
|
Bind_Material( track->SwitchExtension->m_material3 );
|
|
m_geometry.draw( track->SwitchExtension->Geometry3 );
|
|
break;
|
|
}
|
|
case rendermode::pickscenery: // pick scenery mode uses piece-by-piece approach
|
|
case rendermode::pickcontrols:
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
// cut faces of rails
|
|
if( ( m_renderpass.draw_mode == rendermode::color )
|
|
|| ( m_renderpass.draw_mode == rendermode::reflections ) ) {
|
|
for( auto first { First }; first != Last; ++first ) {
|
|
|
|
auto const track { *first };
|
|
|
|
if( false == track->m_visible ) {
|
|
continue;
|
|
}
|
|
Render_cuts( track );
|
|
}
|
|
}
|
|
// post-render reset
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::shadows:
|
|
case rendermode::cabshadows: {
|
|
::glEnable( GL_CULL_FACE );
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Render( TMemCell *Memcell ) {
|
|
|
|
::glPushMatrix();
|
|
auto const position = Memcell->location() - m_renderpass.camera.position();
|
|
::glTranslated( position.x, position.y + 0.5, position.z );
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::color:
|
|
case rendermode::shadows:
|
|
case rendermode::cabshadows: {
|
|
//::gluSphere( m_quadric, 0.35, 4, 2 );
|
|
break;
|
|
}
|
|
case rendermode::pickscenery: {
|
|
// add the node to the pick list
|
|
m_picksceneryitems.emplace_back( Memcell );
|
|
|
|
//::gluSphere( m_quadric, 0.35, 4, 2 );
|
|
break;
|
|
}
|
|
case rendermode::reflections:
|
|
case rendermode::pickcontrols: {
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
|
|
::glPopMatrix();
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Render_particles() {
|
|
|
|
switch_units( true, false, false );
|
|
|
|
Bind_Material( null_handle ); // TODO: bind smoke texture
|
|
|
|
// TBD: leave lighting on to allow vehicle lights to affect it?
|
|
::glDisable( GL_LIGHTING );
|
|
// momentarily disable depth write, to allow vehicle cab drawn afterwards to mask it instead of leaving it 'inside'
|
|
::glDepthMask( GL_FALSE );
|
|
|
|
Bind_Texture( m_smoketexture );
|
|
m_renderpass.draw_stats.particles = m_particlerenderer.render( m_diffusetextureunit );
|
|
if( Global.bUseVBO ) {
|
|
gfx::opengl_vbogeometrybank::reset();
|
|
}
|
|
::glDepthMask( GL_TRUE );
|
|
::glEnable( GL_LIGHTING );
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Render_precipitation() {
|
|
|
|
if( Global.Overcast <= 1.f ) { return; }
|
|
|
|
switch_units( true, false, false );
|
|
|
|
// ::glColor4fv( glm::value_ptr( glm::vec4( glm::min( glm::vec3( Global.fLuminance ), glm::vec3( 1 ) ), 1 ) ) );
|
|
::glColor4fv(
|
|
glm::value_ptr(
|
|
glm::mix(
|
|
0.5f * ( Global.DayLight.diffuse + Global.DayLight.ambient ),
|
|
colors::white,
|
|
0.5f * std::clamp( (float)Global.fLuminance, 0.f, 1.f ) ) ) );
|
|
::glPushMatrix();
|
|
// tilt the precipitation cone against the camera movement vector for crude motion blur
|
|
// include current wind vector while at it
|
|
auto const velocity {
|
|
simulation::Environment.m_precipitation.m_cameramove * -1.0
|
|
+ glm::dvec3{ simulation::Environment.wind() } * 0.5 };
|
|
if( glm::length2( velocity ) > 0.0 ) {
|
|
auto const forward{ glm::normalize( velocity ) };
|
|
auto left { glm::cross( forward, {0.0,1.0,0.0} ) };
|
|
auto const rotationangle {
|
|
std::min(
|
|
45.0,
|
|
( FreeFlyModeFlag ?
|
|
5 * glm::length( velocity ) :
|
|
simulation::Train->Dynamic()->GetVelocity() * 0.2 ) ) };
|
|
::glRotated( rotationangle, left.x, 0.0, left.z );
|
|
}
|
|
if( false == FreeFlyModeFlag ) {
|
|
// counter potential vehicle roll
|
|
auto const roll { 0.5 * glm::degrees( simulation::Train->Dynamic()->Roll() ) };
|
|
if( roll != 0.0 ) {
|
|
auto const forward { simulation::Train->Dynamic()->VectorFront() };
|
|
auto const vehicledirection = simulation::Train->Dynamic()->DirectionGet();
|
|
::glRotated( roll, forward.x, 0.0, forward.z );
|
|
}
|
|
}
|
|
if( Global.Weather == "rain:" ) {
|
|
// oddly enough random streaks produce more natural looking rain than ones the eye can follow
|
|
::glRotated( LocalRandom() * 360, 0.0, 1.0, 0.0 );
|
|
}
|
|
|
|
// TBD: leave lighting on to allow vehicle lights to affect it?
|
|
::glDisable( GL_LIGHTING );
|
|
// momentarily disable depth write, to allow vehicle cab drawn afterwards to mask it instead of leaving it 'inside'
|
|
::glDepthMask( GL_FALSE );
|
|
|
|
m_precipitationrenderer.render( m_diffusetextureunit );
|
|
if( Global.bUseVBO ) {
|
|
gfx::opengl_vbogeometrybank::reset();
|
|
}
|
|
|
|
::glDepthMask( GL_TRUE );
|
|
::glEnable( GL_LIGHTING );
|
|
::glPopMatrix();
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Render_Alpha( scene::basic_region *Region ) {
|
|
|
|
// sort the nodes based on their distance to viewer
|
|
std::sort(
|
|
std::begin( m_cellqueue ),
|
|
std::end( m_cellqueue ),
|
|
[]( distancecell_pair const &Left, distancecell_pair const &Right ) {
|
|
return ( Left.first ) < ( Right.first ); } );
|
|
|
|
Render_Alpha( std::rbegin( m_cellqueue ), std::rend( m_cellqueue ) );
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Render_Alpha( cell_sequence::reverse_iterator First, cell_sequence::reverse_iterator Last ) {
|
|
|
|
// NOTE: this method is launched only during color pass therefore we don't bother with mode test here
|
|
// the cells far off with the tracks alone drawn there have nothing translucent drawn either
|
|
auto const scenery_limit{ static_cast<double>( Global.BaseDrawRange ) * Global.fDistanceFactor + 250.0 };
|
|
bool const far_paths{ EditorModeFlag && Global.editor_tracks };
|
|
glm::dvec3 const camera{ m_renderpass.camera.position() };
|
|
auto const distant = [&]( scene::basic_cell const *Cell ) { return editor_far_tracks_only( far_paths, Cell->m_area, camera, scenery_limit ); };
|
|
// first pass draws elements which we know are located in section banks, to reduce vbo switching
|
|
{
|
|
auto first { First };
|
|
while( first != Last ) {
|
|
|
|
auto const *cell = first->second;
|
|
|
|
if( false == cell->m_shapestranslucent.empty() && false == distant( cell ) ) {
|
|
// since all shapes of the cell share center point we can optimize out a few calls here
|
|
::glPushMatrix();
|
|
auto const originoffset{ cell->m_area.center - m_renderpass.camera.position() };
|
|
::glTranslated( originoffset.x, originoffset.y, originoffset.z );
|
|
// render
|
|
// NOTE: we can reuse the method used to draw opaque geometry
|
|
for( auto const &shape : cell->m_shapestranslucent ) { Render( shape, false ); }
|
|
// post-render cleanup
|
|
::glPopMatrix();
|
|
}
|
|
|
|
++first;
|
|
}
|
|
}
|
|
// second pass draws elements with their own vbos
|
|
{
|
|
auto first { First };
|
|
while( first != Last ) {
|
|
|
|
auto const *cell = first->second;
|
|
if( distant( cell ) ) {
|
|
++first;
|
|
continue;
|
|
}
|
|
|
|
// translucent parts of instanced models
|
|
for( auto *instance : cell->m_instancetranslucent ) { Render_Alpha( instance ); }
|
|
// translucent parts of vehicles
|
|
for( auto *path : cell->m_paths ) {
|
|
for( auto *dynamic : path->Dynamics ) {
|
|
if( ( false == FreeFlyModeFlag )
|
|
&& ( simulation::Train->Dynamic() == dynamic ) ) {
|
|
// delay drawing translucent parts of occupied vehicle until after the cab was drawn
|
|
continue;
|
|
}
|
|
Render_Alpha( dynamic );
|
|
}
|
|
}
|
|
|
|
++first;
|
|
}
|
|
}
|
|
// third pass draws the wires;
|
|
// wires use section vbos, but for the time being we want to draw them at the very end
|
|
{
|
|
::glDisable( GL_LIGHTING ); // linie nie powinny świecić
|
|
|
|
auto first{ First };
|
|
while( first != Last ) {
|
|
|
|
auto const *cell = first->second;
|
|
|
|
if( ( false == cell->m_traction.empty()
|
|
|| ( false == cell->m_lines.empty() ) )
|
|
&& false == distant( cell ) ) {
|
|
// since all shapes of the cell share center point we can optimize out a few calls here
|
|
::glPushMatrix();
|
|
auto const originoffset { cell->m_area.center - m_renderpass.camera.position() };
|
|
::glTranslated( originoffset.x, originoffset.y, originoffset.z );
|
|
if( !Global.bSmoothTraction ) {
|
|
// na liniach kiepsko wygląda - robi gradient
|
|
::glDisable( GL_LINE_SMOOTH );
|
|
}
|
|
Bind_Material( null_handle );
|
|
// render
|
|
for( auto *traction : cell->m_traction ) { Render_Alpha( traction ); }
|
|
for( auto &lines : cell->m_lines ) { Render_Alpha( lines ); }
|
|
// post-render cleanup
|
|
::glLineWidth( 1.0 );
|
|
if( !Global.bSmoothTraction ) {
|
|
::glEnable( GL_LINE_SMOOTH );
|
|
}
|
|
::glPopMatrix();
|
|
}
|
|
|
|
++first;
|
|
}
|
|
|
|
::glEnable( GL_LIGHTING );
|
|
}
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Render_Alpha( TAnimModel *Instance ) {
|
|
|
|
if (false == Instance->m_visible) { return; }
|
|
if( false == m_renderpass.camera.visible( Instance->m_area ) ) { return; }
|
|
|
|
double distancesquared;
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::shadows: {
|
|
// 'camera' for the light pass is the light source, but we need to draw what the 'real' camera sees
|
|
distancesquared = glm::length2( ( Instance->location() - Global.pCamera.Pos ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor;
|
|
break;
|
|
}
|
|
default: {
|
|
distancesquared = glm::length2( ( Instance->location() - m_renderpass.camera.position() ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor;
|
|
break;
|
|
}
|
|
}
|
|
if( ( distancesquared < Instance->m_rangesquaredmin )
|
|
|| ( distancesquared >= Instance->m_rangesquaredmax ) ) {
|
|
return;
|
|
}
|
|
// crude way to reject early items too far to affect the output (mostly relevant for shadow passes)
|
|
auto const drawdistancethreshold{ m_renderpass.draw_range + 250 };
|
|
if( distancesquared > sq(drawdistancethreshold) ) {
|
|
return;
|
|
}
|
|
// second stage visibility cull, reject modelstoo far away to be noticeable
|
|
auto const radiussquared { Instance->radius() * Instance->radius() };
|
|
if( radiussquared * Global.ZoomFactor / distancesquared < 0.003 * 0.003 ) {
|
|
return;
|
|
}
|
|
|
|
Instance->RaAnimate( m_framestamp ); // jednorazowe przeliczenie animacji
|
|
Instance->RaPrepare();
|
|
if( Instance->pModel ) {
|
|
// renderowanie rekurencyjne submodeli
|
|
auto const position { Instance->location() - m_renderpass.camera.position() };
|
|
if( is_scaled( Instance->Scale() ) ) {
|
|
// the scale stretches the normals too, they're normalized again for the lighting
|
|
push_scaled_instance_transform( position, Instance->vAngle, Instance->Scale() );
|
|
m_normalizenormals = true;
|
|
Render_Alpha( Instance->pModel, Instance->Material(), distancesquared );
|
|
m_normalizenormals = false;
|
|
::glPopMatrix();
|
|
}
|
|
else {
|
|
Render_Alpha(
|
|
Instance->pModel,
|
|
Instance->Material(),
|
|
distancesquared,
|
|
position,
|
|
Instance->vAngle );
|
|
}
|
|
}
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Render_Alpha( TTraction *Traction ) {
|
|
/*
|
|
// NOTE: test disabled as this call is only executed as part of the colour pass
|
|
double distancesquared;
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::shadows: {
|
|
// 'camera' for the light pass is the light source, but we need to draw what the 'real' camera sees
|
|
distancesquared = glm::length2( ( Traction->location() - Global.pCamera.Pos ) / Global.ZoomFactor ) / Global.fDistanceFactor;
|
|
break;
|
|
}
|
|
default: {
|
|
distancesquared = glm::length2( ( Traction->location() - m_renderpass.camera.position() ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor;
|
|
break;
|
|
}
|
|
}
|
|
*/
|
|
auto const distancesquared { glm::length2( ( Traction->location() - m_renderpass.camera.position() ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor };
|
|
if( ( distancesquared < Traction->m_rangesquaredmin )
|
|
|| ( distancesquared >= Traction->m_rangesquaredmax ) ) {
|
|
return;
|
|
}
|
|
|
|
if( false == Traction->m_visible ) {
|
|
return;
|
|
}
|
|
// rysuj jesli sa druty i nie zerwana
|
|
if( ( Traction->Wires == 0 )
|
|
|| ( true == TestFlag( Traction->DamageFlag, 128 ) ) ) {
|
|
return;
|
|
}
|
|
// setup
|
|
/*
|
|
float const linealpha = static_cast<float>(
|
|
std::min(
|
|
1.25,
|
|
5000 * Traction->WireThickness / ( distancesquared + 1.0 ) ) ); // zbyt grube nie są dobre
|
|
::glLineWidth( linealpha );
|
|
*/
|
|
auto const distance { static_cast<float>( std::sqrt( distancesquared ) ) };
|
|
auto const linealpha {
|
|
20.f * Traction->WireThickness
|
|
/ std::max(
|
|
0.5f * Traction->radius() + 1.f,
|
|
distance - ( 0.5f * Traction->radius() ) ) };
|
|
::glLineWidth(
|
|
std::clamp(
|
|
0.5f * linealpha + Traction->WireThickness * Traction->radius() / 1000.f,
|
|
1.f, 1.75f ) );
|
|
// McZapkie-261102: kolor zalezy od materialu i zasniedzenia
|
|
::glColor4fv(
|
|
glm::value_ptr(
|
|
glm::vec4{
|
|
Traction->wire_color() /* * ( DebugModeFlag ? 1.f : std::clamp( m_sunandviewangle, 0.25f, 1.f ) ) */,
|
|
linealpha } ) );
|
|
// render
|
|
m_geometry.draw( Traction->m_geometry );
|
|
// debug data
|
|
++m_renderpass.draw_stats.traction;
|
|
++m_renderpass.draw_stats.drawcalls;
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Render_Alpha( scene::lines_node const &Lines ) {
|
|
|
|
auto const &data { Lines.data() };
|
|
/*
|
|
// NOTE: test disabled as this call is only executed as part of the colour pass
|
|
double distancesquared;
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::shadows: {
|
|
// 'camera' for the light pass is the light source, but we need to draw what the 'real' camera sees
|
|
distancesquared = glm::length2( ( data.area.center - Global.pCamera.Pos ) / Global.ZoomFactor ) / Global.fDistanceFactor;
|
|
break;
|
|
}
|
|
default: {
|
|
distancesquared = glm::length2( ( data.area.center - m_renderpass.camera.position() ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor;
|
|
break;
|
|
}
|
|
}
|
|
*/
|
|
auto const distancesquared { glm::length2( ( data.area.center - m_renderpass.camera.position() ) / (double)Global.ZoomFactor ) / Global.fDistanceFactor };
|
|
if( ( distancesquared < data.rangesquared_min )
|
|
|| ( distancesquared >= data.rangesquared_max ) ) {
|
|
return;
|
|
}
|
|
// setup
|
|
auto const distance { static_cast<float>( std::sqrt( distancesquared ) ) };
|
|
auto const linealpha = (
|
|
data.line_width > 0.f ?
|
|
10.f * data.line_width
|
|
/ std::max(
|
|
0.5f * data.area.radius + 1.f,
|
|
distance - ( 0.5f * data.area.radius ) ) :
|
|
1.f ); // negative width means the lines are always opague
|
|
::glLineWidth(
|
|
std::clamp(
|
|
0.5f * linealpha + data.line_width * data.area.radius / 1000.f,
|
|
1.f, 8.f ) );
|
|
::glColor4fv(
|
|
glm::value_ptr(
|
|
glm::vec4{
|
|
glm::vec3{ data.lighting.diffuse * m_sunlight.ambient }, // w zaleznosci od koloru swiatla
|
|
std::min( 1.f, linealpha ) } ) );
|
|
// render
|
|
m_geometry.draw( data.geometry );
|
|
++m_renderpass.draw_stats.lines;
|
|
++m_renderpass.draw_stats.drawcalls;
|
|
}
|
|
|
|
bool
|
|
opengl_renderer::Render_Alpha( TDynamicObject *Dynamic ) {
|
|
|
|
if( false == Dynamic->renderme ) { return false; }
|
|
|
|
// setup
|
|
TSubModel::iInstance = ( size_t )Dynamic; //żeby nie robić cudzych animacji
|
|
TSubModel::iVariantSeed = Dynamic->variant_seed();
|
|
glm::dvec3 const originoffset = Dynamic->vPosition - m_renderpass.camera.position();
|
|
// lod visibility ranges are defined for base (x 1.0) viewing distance. for render we adjust them for actual range multiplier and zoom
|
|
float squaredistance;
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::shadows: {
|
|
squaredistance = glm::length2( glm::vec3{ glm::dvec3{ Dynamic->vPosition - Global.pCamera.Pos } } / Global.ZoomFactor );
|
|
break;
|
|
}
|
|
default: {
|
|
squaredistance = glm::length2( glm::vec3{ originoffset } / Global.ZoomFactor );
|
|
break;
|
|
}
|
|
}
|
|
Dynamic->ABuLittleUpdate( squaredistance ); // ustawianie zmiennych submodeli dla wspólnego modelu
|
|
::glPushMatrix();
|
|
|
|
::glTranslated( originoffset.x, originoffset.y, originoffset.z );
|
|
::glMultMatrixd( glm::value_ptr(Dynamic->mMatrix) );
|
|
|
|
if( Dynamic->fShade > 0.0f ) {
|
|
// change light level based on light level of the occupied track
|
|
m_sunlight.apply_intensity( Dynamic->fShade );
|
|
}
|
|
m_renderspecular = true;
|
|
|
|
// render
|
|
if( Dynamic->mdLowPolyInt ) {
|
|
// low poly interior
|
|
// if( FreeFlyModeFlag ? true : !Dynamic->mdKabina || !Dynamic->bDisplayCab ) {
|
|
/*
|
|
// enable cab light if needed
|
|
if( Dynamic->InteriorLightLevel > 0.0f ) {
|
|
|
|
// crude way to light the cabin, until we have something more complete in place
|
|
::glLightModelfv( GL_LIGHT_MODEL_AMBIENT, glm::value_ptr( Dynamic->InteriorLight * Dynamic->InteriorLightLevel ) );
|
|
}
|
|
*/
|
|
Render_Alpha( Dynamic->mdLowPolyInt, Dynamic->Material(), squaredistance );
|
|
/*
|
|
if( Dynamic->InteriorLightLevel > 0.0f ) {
|
|
// reset the overall ambient
|
|
::glLightModelfv( GL_LIGHT_MODEL_AMBIENT, glm::value_ptr( m_baseambient ) );
|
|
}
|
|
*/
|
|
// }
|
|
}
|
|
|
|
if( Dynamic->mdModel ) {
|
|
// main model
|
|
Render_Alpha( Dynamic->mdModel, Dynamic->Material(), squaredistance );
|
|
}
|
|
// optional attached models
|
|
for( auto *attachment : Dynamic->mdAttachments ) {
|
|
Render_Alpha( attachment, Dynamic->Material(), squaredistance );
|
|
}
|
|
// optional coupling adapters
|
|
Render_coupler_adapter( Dynamic, squaredistance, end::front, true );
|
|
Render_coupler_adapter( Dynamic, squaredistance, end::rear, true );
|
|
if( Dynamic->mdLoad ) {
|
|
// renderowanie nieprzezroczystego ładunku
|
|
Render_Alpha( Dynamic->mdLoad, Dynamic->Material(), squaredistance, { 0.f, Dynamic->LoadOffset, 0.f }, {} );
|
|
}
|
|
|
|
// post-render cleanup
|
|
m_renderspecular = false;
|
|
if( Dynamic->fShade > 0.0f ) {
|
|
// restore regular light level
|
|
m_sunlight.apply_intensity();
|
|
}
|
|
|
|
::glPopMatrix();
|
|
|
|
if( Dynamic->btnOn )
|
|
Dynamic->TurnOff(); // przywrócenie domyślnych pozycji submodeli
|
|
|
|
return true;
|
|
}
|
|
|
|
bool
|
|
opengl_renderer::Render_Alpha( TModel3d *Model, material_data const *Material, float const Squaredistance ) {
|
|
|
|
auto alpha =
|
|
( Material != nullptr ?
|
|
Material->textures_alpha :
|
|
0x30300030 );
|
|
|
|
if( 0 == ( alpha & Model->iFlags & 0x2F2F002F ) ) {
|
|
// nothing to render
|
|
return false;
|
|
}
|
|
|
|
Model->Root->fSquareDist = Squaredistance; // zmienna globalna!
|
|
|
|
// setup
|
|
Model->Root->ReplacableSet(
|
|
( Material != nullptr ?
|
|
Material->replacable_skins :
|
|
nullptr ),
|
|
alpha );
|
|
|
|
Model->Root->pRoot = Model;
|
|
|
|
// render
|
|
Render_Alpha( Model->Root );
|
|
|
|
// post-render cleanup
|
|
|
|
return true;
|
|
}
|
|
|
|
bool
|
|
opengl_renderer::Render_Alpha( TModel3d *Model, material_data const *Material, float const Squaredistance, glm::dvec3 const &Position, glm::vec3 const &Angle ) {
|
|
|
|
::glPushMatrix();
|
|
::glTranslated( Position.x, Position.y, Position.z );
|
|
if( Angle.y != 0.0 )
|
|
::glRotatef( Angle.y, 0.f, 1.f, 0.f );
|
|
if( Angle.x != 0.0 )
|
|
::glRotatef( Angle.x, 1.f, 0.f, 0.f );
|
|
if( Angle.z != 0.0 )
|
|
::glRotatef( Angle.z, 0.f, 0.f, 1.f );
|
|
|
|
auto const result = Render_Alpha( Model, Material, Squaredistance ); // position is effectively camera offset
|
|
|
|
::glPopMatrix();
|
|
|
|
return result;
|
|
}
|
|
|
|
// characters of a text display, laid out in a row. the text can be encoded in utf-8 or in windows-1250
|
|
void
|
|
opengl_renderer::Render_Alpha_text( TSubModel *Submodel ) {
|
|
|
|
if( TSubModel::pasText == nullptr ) { return; }
|
|
|
|
for( auto *p : Submodel->text_letters( *TSubModel::pasText ) ) { // translucent only, for the time being
|
|
Render_Alpha( p );
|
|
if( p->fMatrix )
|
|
::glMultMatrixf( p->fMatrix->readArray() ); // move on to the place of the next character
|
|
}
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Render_Alpha( TSubModel *Submodel ) {
|
|
// renderowanie przezroczystych przez DL
|
|
if( ( Submodel->iVisible )
|
|
&& ( TSubModel::fSquareDist >= Submodel->fSquareMinDist )
|
|
&& ( TSubModel::fSquareDist < Submodel->fSquareMaxDist ) ) {
|
|
|
|
if( Submodel->iFlags & 0xC000 ) {
|
|
::glPushMatrix();
|
|
if( Submodel->fMatrix )
|
|
::glMultMatrixf( Submodel->fMatrix->readArray() );
|
|
if( Submodel->b_aAnim != TAnimType::at_None )
|
|
Submodel->RaAnimation( Submodel->b_aAnim );
|
|
}
|
|
|
|
if( Submodel->eType < TP_ROTATOR ) {
|
|
// renderowanie obiektów OpenGL
|
|
if( Submodel->iAlpha & Submodel->iFlags & 0x2F ) {
|
|
// rysuj gdy element przezroczysty
|
|
|
|
// debug data
|
|
++m_renderpass.draw_stats.submodels;
|
|
++m_renderpass.draw_stats.drawcalls;
|
|
|
|
switch( m_renderpass.draw_mode ) {
|
|
case rendermode::color: {
|
|
|
|
// NOTE: code disabled as normalization marking doesn't take into account scaling propagation down hierarchy chains
|
|
// for the time being we'll do with enforced worst-case scaling method, when speculars are enabled
|
|
#ifdef EU07_USE_OPTIMIZED_NORMALIZATION
|
|
switch( Submodel->m_normalizenormals ) {
|
|
case TSubModel::normalize: {
|
|
::glEnable( GL_NORMALIZE ); break; }
|
|
case TSubModel::rescale: {
|
|
::glEnable( GL_RESCALE_NORMAL ); break; }
|
|
default: {
|
|
break; }
|
|
}
|
|
#else
|
|
if( ( true == m_renderspecular ) || ( true == m_normalizenormals ) ) {
|
|
::glEnable( GL_NORMALIZE );
|
|
}
|
|
#endif
|
|
// material configuration:
|
|
// textures...
|
|
auto const material { submodel_material( Submodel ) }; // zmienialne skóry, również 0
|
|
// textures...
|
|
Bind_Material( material );
|
|
// ...colors and opacity...
|
|
auto const opacity { std::clamp( Material( material )->get_or_guess_opacity(), 0.f, 1.f ) };
|
|
if( Submodel->fVisible < 1.f ) {
|
|
::glColor4f(
|
|
Submodel->f4Diffuse.r,
|
|
Submodel->f4Diffuse.g,
|
|
Submodel->f4Diffuse.b,
|
|
Submodel->fVisible );
|
|
}
|
|
else {
|
|
::glColor3fv( glm::value_ptr( Submodel->f4Diffuse ) ); // McZapkie-240702: zamiast ub
|
|
}
|
|
if( opacity != 0.f ) {
|
|
// discard fragments with opacity exceeding the threshold
|
|
::glAlphaFunc( GL_LEQUAL, opacity );
|
|
}
|
|
if( ( true == m_renderspecular ) && ( m_sunlight.specular.a > 0.01f ) ) {
|
|
::glMaterialfv( GL_FRONT, GL_SPECULAR, glm::value_ptr( Submodel->f4Specular * m_sunlight.specular.a * m_speculartranslucentscalefactor ) );
|
|
}
|
|
// ...luminance
|
|
auto const unitstate = m_unitstate;
|
|
auto const isemissive { ( Submodel->f4Emision.a > 0.f ) && ( Global.fLuminance < Submodel->fLight ) };
|
|
if( isemissive ) {
|
|
// zeby swiecilo na kolorowo
|
|
::glMaterialfv( GL_FRONT, GL_EMISSION, glm::value_ptr( /* Submodel->f4Emision */ Submodel->f4Diffuse * Submodel->f4Emision.a ) );
|
|
// disable shadows so they don't obstruct self-lit items
|
|
/*
|
|
setup_shadow_color( colors::white );
|
|
*/
|
|
switch_units( unitstate.diffuse, false, false );
|
|
}
|
|
|
|
// main draw call
|
|
m_geometry.draw( Submodel->m_geometry.handle );
|
|
|
|
// post-draw reset
|
|
if( opacity != 0.f ) {
|
|
// discard fragments with opacity exceeding the threshold
|
|
::glAlphaFunc( GL_GREATER, 0.0f );
|
|
}
|
|
if( ( true == m_renderspecular ) && ( m_sunlight.specular.a > 0.01f ) ) {
|
|
::glMaterialfv( GL_FRONT, GL_SPECULAR, glm::value_ptr( colors::none ) );
|
|
}
|
|
if( isemissive ) {
|
|
// restore default (lack of) brightness
|
|
::glMaterialfv( GL_FRONT, GL_EMISSION, glm::value_ptr( colors::none ) );
|
|
/*
|
|
setup_shadow_color( m_shadowcolor );
|
|
*/
|
|
switch_units( unitstate.diffuse, unitstate.shadows, unitstate.reflections );
|
|
}
|
|
#ifdef EU07_USE_OPTIMIZED_NORMALIZATION
|
|
switch( Submodel->m_normalizenormals ) {
|
|
case TSubModel::normalize: {
|
|
::glDisable( GL_NORMALIZE ); break; }
|
|
case TSubModel::rescale: {
|
|
::glDisable( GL_RESCALE_NORMAL ); break; }
|
|
default: {
|
|
break; }
|
|
}
|
|
#else
|
|
if( ( true == m_renderspecular ) || ( true == m_normalizenormals ) ) {
|
|
::glDisable( GL_NORMALIZE );
|
|
}
|
|
#endif
|
|
break;
|
|
}
|
|
case rendermode::cabshadows: {
|
|
// scenery picking and shadow both use enforced colour and no frills
|
|
// material configuration:
|
|
// textures...
|
|
if( Submodel->m_material < 0 ) { // zmienialne skóry
|
|
Bind_Material( submodel_material( Submodel ), Submodel );
|
|
}
|
|
else {
|
|
// również 0
|
|
Bind_Material( Submodel->m_material, Submodel );
|
|
}
|
|
// main draw call
|
|
m_geometry.draw( Submodel->m_geometry.handle );
|
|
// post-draw reset
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
else if( Submodel->eType == TP_FREESPOTLIGHT ) {
|
|
|
|
if( ( Global.fLuminance < Submodel->fLight ) || ( Global.Overcast > 1.f ) ) {
|
|
// NOTE: we're forced here to redo view angle calculations etc, because this data isn't instanced but stored along with the single mesh
|
|
// TODO: separate instance data from reusable geometry
|
|
auto const &modelview = OpenGLMatrices.data( GL_MODELVIEW );
|
|
auto const lightcenter =
|
|
modelview
|
|
* glm::mix(
|
|
glm::vec4( 0.f, 0.f, -0.05f, 1.f ),
|
|
glm::vec4( 0.f, 0.f, -0.10f, 1.f ),
|
|
static_cast<float>( TSubModel::fSquareDist / Submodel->fSquareMaxDist ) ); // pozycja punktu świecącego względem kamery
|
|
Submodel->fCosViewAngle = glm::dot( glm::normalize( modelview * glm::vec4( 0.f, 0.f, -1.f, 1.f ) - lightcenter ), glm::normalize( -lightcenter ) );
|
|
|
|
if( Submodel->fCosViewAngle > Submodel->fCosFalloffAngle ) {
|
|
// only bother if the viewer is inside the visibility cone
|
|
// luminosity at night is at level of ~0.1, so the overall resulting transparency in clear conditions is ~0.5 at full 'brightness'
|
|
auto glarelevel { std::clamp(
|
|
std::max<float>(
|
|
0.6f - Global.fLuminance, // reduce the glare in bright daylight
|
|
Global.Overcast - 1.f ), // ensure some glare in rainy/foggy conditions
|
|
0.f, 1.f ) };
|
|
// view angle attenuation
|
|
float const anglefactor { std::clamp(
|
|
( Submodel->fCosViewAngle - Submodel->fCosFalloffAngle ) / ( Submodel->fCosHotspotAngle - Submodel->fCosFalloffAngle ),
|
|
0.f, 1.f ) };
|
|
glarelevel *= anglefactor;
|
|
|
|
if( glarelevel > 0.0f ) {
|
|
// setup
|
|
::glPushAttrib( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_ENABLE_BIT );
|
|
|
|
Bind_Texture( m_glaretexture );
|
|
::glDisable( GL_LIGHTING );
|
|
::glDisable( GL_FOG );
|
|
::glDepthMask( GL_FALSE );
|
|
::glBlendFunc( GL_SRC_ALPHA, GL_ONE );
|
|
|
|
::glPushMatrix();
|
|
::glLoadIdentity(); // macierz jedynkowa
|
|
::glTranslatef( lightcenter.x, lightcenter.y, lightcenter.z ); // początek układu zostaje bez zmian
|
|
::glRotated( std::atan2( lightcenter.x, lightcenter.z ) * 180.0 / M_PI, 0.0, 1.0, 0.0 ); // jedynie obracamy w pionie o kąt
|
|
// disable shadows so they don't obstruct self-lit items
|
|
auto const unitstate = m_unitstate;
|
|
switch_units( unitstate.diffuse, false, false );
|
|
|
|
glm::vec3 const lightcolor {
|
|
Submodel->DiffuseOverride.r < 0.f ? // -1 indicates no override
|
|
glm::vec3( Submodel->f4Diffuse ) :
|
|
Submodel->DiffuseOverride };
|
|
::glColor4f(
|
|
lightcolor.r,
|
|
lightcolor.g,
|
|
lightcolor.b,
|
|
Submodel->fVisible * glarelevel );
|
|
|
|
// main draw call
|
|
m_geometry.draw( m_billboardgeometry );
|
|
/*
|
|
// NOTE: we could do simply...
|
|
vec3 vertexPosition_worldspace =
|
|
particleCenter_wordspace
|
|
+ CameraRight_worldspace * squareVertices.x * BillboardSize.x
|
|
+ CameraUp_worldspace * squareVertices.y * BillboardSize.y;
|
|
// ...etc instead IF we had easy access to camera's forward and right vectors. TODO: check if Camera matrix is accessible
|
|
*/
|
|
// post-render cleanup
|
|
switch_units( unitstate.diffuse, unitstate.shadows, unitstate.reflections );
|
|
|
|
::glPopMatrix();
|
|
::glPopAttrib();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if( Submodel->Child != nullptr ) {
|
|
if( Submodel->eType == TP_TEXT ) { // tekst renderujemy w specjalny sposób, zamiast submodeli z łańcucha Child
|
|
Render_Alpha_text( Submodel );
|
|
}
|
|
else if( Submodel->iAlpha & Submodel->iFlags & 0x002F0000 )
|
|
Render_Alpha( Submodel->Child );
|
|
}
|
|
|
|
if( Submodel->iFlags & 0xC000 )
|
|
::glPopMatrix();
|
|
}
|
|
/*
|
|
if( Submodel->b_aAnim < at_SecondsJump )
|
|
Submodel->b_aAnim = at_None; // wyłączenie animacji dla kolejnego użycia submodelu
|
|
*/
|
|
if( Submodel->Next != nullptr )
|
|
if( Submodel->iAlpha & Submodel->iFlags & 0x2F000000 )
|
|
Render_Alpha( Submodel->Next );
|
|
};
|
|
|
|
|
|
|
|
// utility methods
|
|
void
|
|
opengl_renderer::Update_Pick_Control() {
|
|
|
|
#ifdef EU07_USE_PICKING_FRAMEBUFFER
|
|
if( true == m_framebuffersupport ) {
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, m_pickframebuffer );
|
|
}
|
|
#endif
|
|
Render_pass( rendermode::pickcontrols );
|
|
// determine point to examine
|
|
glm::vec2 mousepos = Global.cursor_pos;
|
|
mousepos.y = Global.window_size.y - mousepos.y; // cursor coordinates are flipped compared to opengl
|
|
|
|
#ifdef EU07_USE_PICKING_FRAMEBUFFER
|
|
glm::ivec2 pickbufferpos;
|
|
if( true == m_framebuffersupport ) {
|
|
// ::glReadBuffer( GL_COLOR_ATTACHMENT0_EXT );
|
|
pickbufferpos = mousepos * glm::vec2(EU07_PICKBUFFERSIZE) / glm::vec2(Global.window_size);
|
|
}
|
|
else {
|
|
// ::glReadBuffer( GL_BACK );
|
|
pickbufferpos = mousepos * glm::vec2(Global.fb_size) / glm::vec2(Global.window_size);
|
|
}
|
|
#else
|
|
// ::glReadBuffer( GL_BACK );
|
|
glm::ivec2 pickbufferpos{ mousepos };
|
|
#endif
|
|
unsigned char pickreadout[4];
|
|
::glReadPixels( pickbufferpos.x, pickbufferpos.y, 1, 1, GL_BGRA, GL_UNSIGNED_BYTE, pickreadout );
|
|
auto const controlindex = pick_index( glm::ivec3{ pickreadout[ 2 ], pickreadout[ 1 ], pickreadout[ 0 ] } );
|
|
TSubModel *control { nullptr };
|
|
if( ( controlindex > 0 )
|
|
&& ( controlindex <= m_pickcontrolsitems.size() ) ) {
|
|
control = m_pickcontrolsitems[ controlindex - 1 ];
|
|
}
|
|
#ifdef EU07_USE_PICKING_FRAMEBUFFER
|
|
if( true == m_framebuffersupport ) {
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 );
|
|
}
|
|
#endif
|
|
m_pickcontrolitem = control;
|
|
// return control;
|
|
for( auto& callback : m_control_pick_requests ) {
|
|
callback( m_pickcontrolitem, glm::vec2() );
|
|
}
|
|
m_control_pick_requests.clear();
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Update_Pick_Node() {
|
|
|
|
#ifdef EU07_USE_PICKING_FRAMEBUFFER
|
|
if( true == m_framebuffersupport ) {
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, m_pickframebuffer );
|
|
}
|
|
#endif
|
|
Render_pass( rendermode::pickscenery );
|
|
// determine point to examine
|
|
glm::vec2 mousepos = Global.cursor_pos;
|
|
mousepos.y = Global.window_size.y - mousepos.y; // cursor coordinates are flipped compared to opengl
|
|
|
|
#ifdef EU07_USE_PICKING_FRAMEBUFFER
|
|
glm::ivec2 pickbufferpos;
|
|
if( true == m_framebuffersupport ) {
|
|
// ::glReadBuffer( GL_COLOR_ATTACHMENT0_EXT );
|
|
pickbufferpos = mousepos * glm::vec2(EU07_PICKBUFFERSIZE) / glm::vec2(Global.window_size);
|
|
}
|
|
else {
|
|
// ::glReadBuffer( GL_BACK );
|
|
pickbufferpos = mousepos * glm::vec2(Global.fb_size) / glm::vec2(Global.window_size);
|
|
}
|
|
#else
|
|
// ::glReadBuffer( GL_BACK );
|
|
glm::ivec2 pickbufferpos{ mousepos };
|
|
#endif
|
|
|
|
unsigned char pickreadout[4];
|
|
::glReadPixels( pickbufferpos.x, pickbufferpos.y, 1, 1, GL_BGRA, GL_UNSIGNED_BYTE, pickreadout );
|
|
auto const nodeindex = pick_index( glm::ivec3{ pickreadout[ 2 ], pickreadout[ 1 ], pickreadout[ 0 ] } );
|
|
scene::basic_node *node { nullptr };
|
|
if( ( nodeindex > 0 )
|
|
&& ( nodeindex <= m_picksceneryitems.size() ) ) {
|
|
node = m_picksceneryitems[ nodeindex - 1 ];
|
|
}
|
|
#ifdef EU07_USE_PICKING_FRAMEBUFFER
|
|
if( true == m_framebuffersupport ) {
|
|
::glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 );
|
|
}
|
|
#endif
|
|
m_picksceneryitem = node;
|
|
// return node;
|
|
for( auto& callback : m_node_pick_requests ) {
|
|
callback( m_picksceneryitem );
|
|
}
|
|
m_node_pick_requests.clear();
|
|
}
|
|
|
|
// converts provided screen coordinates to world coordinates of most recent color pass
|
|
glm::dvec3
|
|
opengl_renderer::Update_Mouse_Position() {
|
|
|
|
glm::ivec2 mousepos = Global.cursor_pos * Global.fb_size / Global.window_size;
|
|
mousepos.x = std::clamp( mousepos.x, 0, Global.fb_size.x - 1 );
|
|
mousepos.y = std::clamp(Global.fb_size.y - mousepos.y, 0, Global.fb_size.y - 1);
|
|
GLfloat pointdepth;
|
|
::glReadPixels( mousepos.x, mousepos.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &pointdepth );
|
|
|
|
m_mousehit = pointdepth < 1.0;
|
|
if( m_mousehit ) {
|
|
m_worldmousecoordinates =
|
|
glm::unProject(
|
|
glm::vec3{ mousepos, pointdepth },
|
|
glm::mat4{ glm::mat3{ m_colorpass.camera.modelview() } },
|
|
m_colorpass.camera.projection(),
|
|
glm::vec4{ 0, 0, Global.fb_size.x, Global.fb_size.y } );
|
|
}
|
|
|
|
return m_colorpass.camera.position() + glm::dvec3{ m_worldmousecoordinates };
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Update( double const Deltatime ) {
|
|
|
|
// per frame updates
|
|
if( simulation::is_ready ) {
|
|
// update particle subsystem
|
|
renderpass_config renderpass;
|
|
setup_pass( renderpass, rendermode::color );
|
|
m_skydomerenderer.update();
|
|
m_precipitationrenderer.update();
|
|
m_particlerenderer.update( renderpass.camera );
|
|
}
|
|
|
|
// fixed step updates
|
|
/*
|
|
m_pickupdateaccumulator += Deltatime;
|
|
|
|
if( m_updateaccumulator > 0.5 ) {
|
|
|
|
m_pickupdateaccumulator = 0.0;
|
|
|
|
if( ( true == Global.ControlPicking )
|
|
&& ( false == FreeFlyModeFlag ) ) {
|
|
Update_Pick_Control();
|
|
}
|
|
else {
|
|
m_pickcontrolitem = nullptr;
|
|
}
|
|
// temporary conditions for testing. eventually will be coupled with editor mode
|
|
if( ( true == Global.ControlPicking )
|
|
&& ( true == DebugModeFlag )
|
|
&& ( true == FreeFlyModeFlag ) ) {
|
|
Update_Pick_Node();
|
|
}
|
|
else {
|
|
m_picksceneryitem = nullptr;
|
|
}
|
|
}
|
|
*/
|
|
m_updateaccumulator += Deltatime;
|
|
|
|
if( ( true == Global.ControlPicking )
|
|
&& ( false == FreeFlyModeFlag ) ) {
|
|
if( ( false == m_control_pick_requests.empty() )
|
|
|| ( m_updateaccumulator >= 1.0 ) ) {
|
|
Update_Pick_Control();
|
|
}
|
|
}
|
|
else {
|
|
m_pickcontrolitem = nullptr;
|
|
}
|
|
// temporary conditions for testing. eventually will be coupled with editor mode
|
|
if( ( true == Global.ControlPicking )
|
|
&& ( true == FreeFlyModeFlag )
|
|
&& ( ( true == DebugModeFlag )
|
|
|| ( true == EditorModeFlag ) ) ) {
|
|
if( ( false == m_node_pick_requests.empty() )
|
|
|| ( m_updateaccumulator >= 1.0 ) ) {
|
|
Update_Pick_Node();
|
|
}
|
|
}
|
|
else {
|
|
m_picksceneryitem = nullptr;
|
|
}
|
|
|
|
if( m_updateaccumulator < 1.0 ) {
|
|
// too early for any work
|
|
return;
|
|
}
|
|
|
|
m_updateaccumulator = 0.0;
|
|
// the frames actually shown, the wait for fpslimit included (eu07/maszyna#416)
|
|
m_framerate = 1000.f / ( Timer::subsystem.mainloop_period.average() );
|
|
// the draw ranges follow the time spent on drawing alone, as before
|
|
auto const drawframerate { 1000.f / ( Timer::subsystem.gfx_total.average() ) };
|
|
|
|
// adjust draw ranges etc, based on recent performance
|
|
// TODO: it doesn't make much sense with vsync
|
|
if( Global.targetfps != 0.f ) {
|
|
auto const fps_diff = drawframerate - Global.targetfps;
|
|
if( fps_diff < -0.5f ) {
|
|
Global.fDistanceFactor = std::min( std::max( 1.0f, Global.fDistanceFactor - 0.05f ), Global.gfx_distance_factor_max );
|
|
}
|
|
else if( fps_diff > 0.5f ) {
|
|
Global.fDistanceFactor = std::min( std::min( 3.0f, Global.fDistanceFactor + 0.05f ), Global.gfx_distance_factor_max );
|
|
}
|
|
}
|
|
// legacy framerate parameters
|
|
else if( Global.fFpsAverage != 0.f ) {
|
|
auto const fps_diff = drawframerate - Global.fFpsAverage;
|
|
if( fps_diff < -Global.fFpsDeviation ) {
|
|
Global.fDistanceFactor = std::min( std::max( 1.0f, Global.fDistanceFactor - 0.05f ), Global.gfx_distance_factor_max );
|
|
}
|
|
else if( fps_diff > Global.fFpsDeviation ) {
|
|
Global.fDistanceFactor = std::min( std::min( 3.0f, Global.fDistanceFactor + 0.05f ), Global.gfx_distance_factor_max );
|
|
}
|
|
}
|
|
|
|
if( Global.UpdateMaterials ) {
|
|
// update resources if there was environmental change
|
|
simulation_state simulationstate{
|
|
Global.Weather,
|
|
Global.Season
|
|
};
|
|
std::swap( m_simulationstate, simulationstate );
|
|
if( ( m_simulationstate.season != simulationstate.season ) && ( false == simulationstate.season.empty() ) ) {
|
|
m_materials.on_season_change();
|
|
}
|
|
if( ( m_simulationstate.weather != simulationstate.weather ) && ( false == simulationstate.weather.empty() ) ) {
|
|
m_materials.on_weather_change();
|
|
}
|
|
}
|
|
|
|
if( ( true == Global.ResourceSweep )
|
|
&& ( true == simulation::is_ready ) ) {
|
|
// garbage collection
|
|
m_geometry.update();
|
|
m_textures.update();
|
|
}
|
|
|
|
if( true == DebugModeFlag ) {
|
|
m_debugtimestext += m_textures.info();
|
|
}
|
|
|
|
// dump last opengl error, if any
|
|
auto const glerror = ::glGetError();
|
|
if( glerror != GL_NO_ERROR ) {
|
|
std::string glerrorstring;
|
|
win1250_to_ascii( glerrorstring );
|
|
Global.LastGLError = std::to_string( glerror ) + " (" + glerrorstring + ")";
|
|
}
|
|
}
|
|
|
|
// debug performance string
|
|
std::string const &
|
|
opengl_renderer::info_times() const {
|
|
|
|
return m_debugtimestext;
|
|
}
|
|
|
|
std::string const &
|
|
opengl_renderer::info_stats() const {
|
|
|
|
return m_debugstatstext;
|
|
}
|
|
|
|
void opengl_renderer::MakeScreenshot()
|
|
{
|
|
screenshot_manager::make_screenshot();
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Update_Lights( light_array &Lights ) {
|
|
// arrange the light array from closest to farthest from current position of the camera
|
|
auto const &camera = m_renderpass.camera.position();
|
|
std::sort(
|
|
std::begin( Lights.data ),
|
|
std::end( Lights.data ),
|
|
[&camera]( light_array::light_record const &Left, light_array::light_record const &Right ) {
|
|
// move lights which are off at the end...
|
|
if( Left.intensity == 0.f ) { return false; }
|
|
if( Right.intensity == 0.f ) { return true; }
|
|
// ...otherwise prefer closer and/or brigher light sources
|
|
return ( glm::length2( camera - Left.position ) / Left.intensity ) < ( glm::length2( camera - Right.position ) / Right.intensity ); } );
|
|
|
|
size_t const count = std::min( m_lights.size(), Lights.data.size() );
|
|
if( count == 0 ) { return; }
|
|
|
|
auto renderlight = m_lights.begin();
|
|
|
|
for( auto const &scenelight : Lights.data ) {
|
|
|
|
if( renderlight == m_lights.end() ) {
|
|
// we ran out of lights to assign
|
|
break;
|
|
}
|
|
if( scenelight.intensity == 0.f ) {
|
|
// all lights past this one are bound to be off
|
|
break;
|
|
}
|
|
auto const lightoffset = glm::vec3{ scenelight.position - camera };
|
|
// length2 is better than length for comparing because it does not require sqrt function
|
|
if( glm::length2( lightoffset ) > sq(1000.f)) {
|
|
// we don't care about lights past arbitrary limit of 1 km.
|
|
// but there could still be weaker lights which are closer, so keep looking
|
|
continue;
|
|
}
|
|
// if the light passed tests so far, it's good enough
|
|
renderlight->position = lightoffset;
|
|
renderlight->direction = scenelight.direction;
|
|
|
|
auto luminance = static_cast<float>( Global.fLuminance );
|
|
// adjust luminance level based on vehicle's location, e.g. tunnels
|
|
auto const environment = scenelight.owner->fShade;
|
|
if( environment > 0.f ) {
|
|
luminance *= environment;
|
|
}
|
|
renderlight->diffuse =
|
|
glm::vec4{
|
|
glm::max( glm::vec3{ colors::none }, scenelight.color - glm::vec3{ luminance } ),
|
|
renderlight->diffuse[ 3 ] };
|
|
renderlight->ambient =
|
|
glm::vec4{
|
|
glm::max( glm::vec3{ colors::none }, scenelight.color * glm::vec3{ scenelight.intensity } - glm::vec3{ luminance } ),
|
|
renderlight->ambient[ 3 ] };
|
|
|
|
::glLightf( renderlight->id, GL_LINEAR_ATTENUATION, static_cast<GLfloat>( (0.25 * scenelight.count) / std::pow( scenelight.count, 2 ) * (scenelight.owner->DimHeadlights ? 1.25 : 1.0) ) );
|
|
::glEnable( renderlight->id );
|
|
|
|
renderlight->apply_intensity();
|
|
renderlight->apply_angle();
|
|
|
|
++renderlight;
|
|
}
|
|
|
|
while( renderlight != m_lights.end() ) {
|
|
// if we went through all scene lights and there's still opengl lights remaining, kill these
|
|
::glDisable( renderlight->id );
|
|
++renderlight;
|
|
}
|
|
}
|
|
|
|
void
|
|
opengl_renderer::Disable_Lights() {
|
|
|
|
for( size_t idx = 0; idx < m_lights.size() + 1; ++idx ) {
|
|
|
|
::glDisable( GL_LIGHT0 + (int)idx );
|
|
}
|
|
}
|
|
|
|
bool
|
|
opengl_renderer::Init_caps() {
|
|
|
|
std::string gl_renderer((char *)glGetString(GL_RENDERER));
|
|
std::string gl_vendor((char *)glGetString(GL_VENDOR));
|
|
std::string gl_version((char *)glGetString(GL_VERSION));
|
|
|
|
crashreport_add_info("gl_renderer", gl_renderer);
|
|
crashreport_add_info("gl_vendor", gl_vendor);
|
|
crashreport_add_info("gl_version", gl_version);
|
|
crashreport_add_info("gl_mode", Global.bUseVBO ? "vbo" : "dl");
|
|
|
|
WriteLog(
|
|
"Gfx Renderer: " + gl_renderer
|
|
+ " Vendor: " + gl_vendor
|
|
+ " OpenGL Version: " + gl_version );
|
|
|
|
if( !GLAD_GL_VERSION_2_1 ) {
|
|
ErrorLog( "Requires openGL >= 2.1" );
|
|
return false;
|
|
}
|
|
|
|
m_isATI = (gl_vendor.find("ATI") != -1);
|
|
|
|
char* extensions = (char*)glGetString( GL_EXTENSIONS );
|
|
if (extensions)
|
|
WriteLog( "Supported extensions: \n" + std::string(extensions));
|
|
|
|
WriteLog( std::string("render path: ") + ( Global.bUseVBO ? "VBO" : "Display lists" ) );
|
|
if( GL_EXT_framebuffer_object ) {
|
|
m_framebuffersupport = true;
|
|
WriteLog( "framebuffer objects enabled" );
|
|
}
|
|
else {
|
|
WriteLog( "framebuffer objects not supported, resorting to back buffer rendering where possible" );
|
|
}
|
|
// ograniczenie maksymalnego rozmiaru tekstur - parametr dla skalowania tekstur
|
|
{
|
|
GLint texturesize;
|
|
::glGetIntegerv( GL_MAX_TEXTURE_SIZE, &texturesize );
|
|
Global.iMaxTextureSize = std::min(Global.iMaxTextureSize, texturesize);
|
|
Global.iMaxCabTextureSize = std::min( Global.iMaxCabTextureSize, texturesize );
|
|
WriteLog( "texture sizes capped at " + std::to_string(Global.iMaxTextureSize) + "p (" + std::to_string( Global.iMaxCabTextureSize ) + "p for cab textures)" );
|
|
Global.CurrentMaxTextureSize = Global.iMaxTextureSize;
|
|
m_shadowbuffersize = Global.shadowtune.map_size;
|
|
m_shadowbuffersize = std::min( m_shadowbuffersize, texturesize );
|
|
WriteLog( "shadows map size capped at " + std::to_string( m_shadowbuffersize ) + "p" );
|
|
}
|
|
// cap the number of supported lights based on hardware
|
|
{
|
|
GLint maxlights;
|
|
::glGetIntegerv( GL_MAX_LIGHTS, &maxlights );
|
|
Global.DynamicLightCount = std::min( Global.DynamicLightCount, maxlights - 1 );
|
|
WriteLog( "dynamic light amount capped at " + std::to_string( Global.DynamicLightCount ) + " (" + std::to_string(maxlights) + " lights total supported by the gfx card)" );
|
|
}
|
|
// select renderer mode
|
|
if( true == Global.BasicRenderer ) {
|
|
WriteLog( "basic renderer selected, shadow and reflection mapping will be disabled" );
|
|
Global.RenderShadows = false;
|
|
m_diffusetextureunit = 0;
|
|
m_helpertextureunit = -1;
|
|
m_shadowtextureunit = -1;
|
|
m_normaltextureunit = -1;
|
|
}
|
|
else {
|
|
GLint maxtextureunits;
|
|
::glGetIntegerv( GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxtextureunits );
|
|
if( maxtextureunits < 4 ) {
|
|
WriteLog( "less than 4 texture units, shadow and reflection mapping will be disabled" );
|
|
Global.BasicRenderer = true;
|
|
Global.RenderShadows = false;
|
|
m_diffusetextureunit = 0;
|
|
m_helpertextureunit = -1;
|
|
m_shadowtextureunit = -1;
|
|
m_normaltextureunit = -1;
|
|
}
|
|
}
|
|
|
|
if( Global.iMultisampling ) {
|
|
WriteLog( "using multisampling x" + std::to_string( 1 << Global.iMultisampling ) );
|
|
}
|
|
|
|
WriteLog( "main window size: " + std::to_string( Global.fb_size.x ) + "x" + std::to_string( Global.fb_size.y ) );
|
|
|
|
return true;
|
|
}
|
|
|
|
glm::vec3
|
|
opengl_renderer::pick_color( std::size_t const Index ) {
|
|
/*
|
|
// pick colours are set with step of 4 for some slightly easier visual debugging. not strictly needed but, eh
|
|
int const colourstep = 4;
|
|
int const componentcapacity = 256 / colourstep;
|
|
auto const redgreen = std::div( Index, componentcapacity * componentcapacity );
|
|
auto const greenblue = std::div( redgreen.rem, componentcapacity );
|
|
auto const blue = Index % componentcapacity;
|
|
return
|
|
glm::vec3 {
|
|
redgreen.quot * colourstep / 255.0f,
|
|
greenblue.quot * colourstep / 255.0f,
|
|
greenblue.rem * colourstep / 255.0f };
|
|
*/
|
|
// alternatively
|
|
return
|
|
glm::vec3{
|
|
( ( Index & 0xff0000 ) >> 16 ) / 255.0f,
|
|
( ( Index & 0x00ff00 ) >> 8 ) / 255.0f,
|
|
( Index & 0x0000ff ) / 255.0f };
|
|
|
|
}
|
|
|
|
std::size_t
|
|
opengl_renderer::pick_index( glm::ivec3 const &Color ) {
|
|
/*
|
|
return (
|
|
std::floor( Color.b / 4 )
|
|
+ std::floor( Color.g / 4 ) * 64
|
|
+ std::floor( Color.r / 4 ) * 64 * 64 );
|
|
*/
|
|
// alternatively
|
|
return
|
|
Color.b
|
|
+ ( Color.g * 256 )
|
|
+ ( Color.r * 256 * 256 );
|
|
|
|
}
|
|
|
|
std::unique_ptr<gfx_renderer> opengl_renderer::create_func()
|
|
{
|
|
return std::unique_ptr<gfx_renderer>(new opengl_renderer());
|
|
}
|
|
|
|
bool opengl_renderer::renderer_register = gfx_renderer_factory::get_instance()->register_backend("legacy", opengl_renderer::create_func);
|
|
|
|
bool opengl_renderer::opengl_imgui_renderer::Init()
|
|
{
|
|
crashreport_add_info("imgui_ver", "gl2");
|
|
return ImGui_ImplOpenGL2_Init();
|
|
}
|
|
|
|
void opengl_renderer::opengl_imgui_renderer::Shutdown()
|
|
{
|
|
ImGui_ImplOpenGL2_Shutdown();
|
|
}
|
|
|
|
void opengl_renderer::opengl_imgui_renderer::BeginFrame()
|
|
{
|
|
ImGui_ImplOpenGL2_NewFrame();
|
|
}
|
|
|
|
void opengl_renderer::opengl_imgui_renderer::Render()
|
|
{
|
|
gl::buffer::unbind(gl::buffer::ARRAY_BUFFER);
|
|
ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData());
|
|
}
|
|
|
|
std::uint64_t opengl_renderer::opengl_imgui_renderer::Create_Image(std::uint8_t const *Rgba, int const Width, int const Height)
|
|
{
|
|
// the ui of this renderer works on srgb colours as they are. the binding the renderer keeps track of is put back as it was
|
|
GLint texture{0}, alignment{4};
|
|
glGetIntegerv(GL_TEXTURE_BINDING_2D, &texture);
|
|
glGetIntegerv(GL_UNPACK_ALIGNMENT, &alignment);
|
|
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
|
|
GLuint image{0};
|
|
glGenTextures(1, &image);
|
|
glBindTexture(GL_TEXTURE_2D, image);
|
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
|
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
|
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, Width, Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, Rgba);
|
|
glBindTexture(GL_TEXTURE_2D, static_cast<GLuint>(texture));
|
|
glPixelStorei(GL_UNPACK_ALIGNMENT, alignment);
|
|
return image;
|
|
}
|
|
|
|
void opengl_renderer::opengl_imgui_renderer::Release_Image(std::uint64_t const Image)
|
|
{
|
|
auto const image{static_cast<GLuint>(Image)};
|
|
glDeleteTextures(1, &image);
|
|
}
|
|
|