Advertisement
aveyo

CS2_launcher

Feb 19th, 2024 (edited)
4,528
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Batch 46.35 KB | Gaming | 0 0
  1. @(set ^ "0=%~f0" -d ') & start "cmd" powershell -nop -c . ([scriptblock]::Create((gc $env:0)-join[char]13)) & exit /b ')
  2. <#
  3.   Counter-Strike 2 launcher - AveYo, 2024.06.11                                               click copy raw or download
  4.   sets screen resolution before starting the game, to alleviate input lag, alt-tab & windows on secondary screens issues
  5.   when res matches, both Desktop-friendly and Exclusive Fullscreen have low input lag and fast alt-tab / win-tab
  6.   once the game is closed, restores the resolution to previous one, or max if using option further below
  7.   + automatically fallback to max available if the chosen res is not yet defined or invalid
  8.   + game starts on screen with mouse pointer on and can seamlessly move between displays even if not set as primary & left
  9.   + clears steam verify game integrity after a crash to relaunch quicker, hopefully preventing a timeout; toggles fso
  10.   + alleviates missing settings under connection problems / cloud conflicts / roaming profiles via cloud.cfg
  11.   + ensure specific video settings are applied at every launch  
  12. #>
  13.  
  14. #:: override resolution, no: -1 max: 0 |  if not appearing in res list, create the custom res in gpu driver settings / cru
  15. #:: best custom res for [4:3] = 1080x810  1280x960  1440x1080   [16:10] = 1296x810  1440x900   [16:9] = 1440x810  1632x918
  16. $force_width     = -1
  17. $force_height    = -1
  18. $force_refresh   = -1
  19.  
  20. #:: override video settings with the preset below: yes 1; no -1 or 0  
  21. $force_settings  =  1
  22.  
  23. #:: override specific video settings - prefix with # lines to remain unchanged (adjust those in-game and relaunch)
  24. $video = @{                                                           #        Shadow of a Potato preset RIP    more jpeg:
  25. # "setting.mat_vsync"                                = "0"            #  0     vsync 1 should be avoided
  26. # "setting.msaa_samples"                             = "2"            #  2     should enable AA when using FSR           0
  27. # "setting.r_csgo_cmaa_enable"                       = "0"            #  0     use msaa 2 instead                        
  28. # "setting.videocfg_shadow_quality"                  = "0"            #  0     shadows high: 2 | med: 1 | low: 0          
  29. # "setting.videocfg_dynamic_shadows"                 = "1"            #  1     must have for competitive play            0
  30. # "setting.videocfg_texture_detail"                  = "0"            #  0     texture high: 2 | med: 1 | low: 0          
  31. # "setting.r_texturefilteringquality"                = "3"            #  3     anyso16x: 5 | trilinear: 1                0
  32. # "setting.shaderquality"                            = "0"            #  0     smooth shadows fps--                      
  33. # "setting.videocfg_particle_detail"                 = "0"            #  0     smooth smokes fps--
  34. # "setting.videocfg_ao_detail"                       = "0"            #  0     ambient oclussion fps--
  35. # "setting.videocfg_hdr_detail"                      = "-1"           #  -1    HDR quality: -1 | performance 8bit noise: 3
  36. # "setting.videocfg_fsr_detail"                      = "2"            #  0     FSR quality: 2 | balanced: 3 | minecraft: 4
  37. # "setting.r_low_latency"                            = "1"            #  1
  38. }
  39. $machine = @{
  40. # "r_player_visibility_mode"                         = "0"            #  0     not in cs2_video.txt
  41. # "r_fullscreen_gamma"                               = "2.2"          #  2.2   not in cs2_video.txt
  42. }
  43. $extra_launch_options = '-favor_consistent_framerate '  #  my placebo is smoother than yours
  44. #$extra_launch_options+= '-allow_third_party_software ' #  uncomment if recording via obs window capture
  45.  
  46. #:: gather freshest keys / user / machine .vcfg into cloud.cfg for applying settings when offline: 1  no: 0
  47. $cloud_cfg       =  1
  48.  
  49. #:: override fullscreen mode, exclusive: 1 desktop-friendly: 0
  50. $force_exclusive =  1
  51.  
  52. #:: override fullscreen optimizations (FSO), enable: 1 disable: 0
  53. $enable_fso      =  0
  54.  
  55. #:: override screen or use current -1 | this is 1st number in the screen list; second number is for -sdl_displayindex
  56. $force_screen    = -1
  57.  
  58. #:: override script handling or use default 0
  59. $do_not_set_desktop_res_to_match_game = 0
  60. $do_not_restore_res_use_max_available = 0
  61. $do_not_hide_script_window_on_waiting = 0
  62.  
  63. # main script section ---------------------------------------------------------------------- switch syntax highlight to powershell
  64. $APPID    = 730
  65. $APPNAME  = "cs2"
  66. $GAMENAME = "Counter-Strike Global Offensive"
  67. $GAMEMOD  = "csgo"
  68. $GAMEBIN  = "bin\win64"
  69. $M_CONFIG = "${APPNAME}_machine_convars.vcfg"
  70. $U_CONFIG = "${APPNAME}_user_convars_0_slot0.vcfg"
  71. $K_CONFIG = "${APPNAME}_user_keys_0_slot0.vcfg"
  72. $V_CONFIG = "${APPNAME}_video.txt"
  73.  
  74. # check if already opened
  75. sp HKCU:\Console\cmd ScreenColors 0x0b -type dword -ea 0; sp HKCU:\Console\cmd QuickEdit 0 -type dword -ea 0
  76. ps | where {$_.MainWindowTitle -eq "$APPNAME launcher"} | kill; $host.ui.RawUI.WindowTitle = "$APPNAME launcher"
  77. if (ps $APPNAME -ea 0) { write-host " $APPNAME is running " -fore Black -back Yellow; sleep 3; exit 0 }
  78.  
  79. # detect STEAM and specific APP
  80. $STEAM = resolve-path (gpv "HKCU:\SOFTWARE\Valve\Steam" SteamPath)
  81. gc "$STEAM\steamapps\libraryfolders.vdf" |foreach  {$_ -split '"',5} |where {$_ -like '*:\\*'} |foreach {
  82.   $lib = resolve-path "$_\steamapps" ; $GAMEROOT = "$lib\common\$GAMENAME\game"; if (test-path "$GAMEROOT\$GAMEMOD\steam.inf") {
  83.     $STEAMAPPS = "$lib"; $GAMEDIR = "$GAMEROOT\$GAMEMOD"; $LAUNCHER = "$GAMEROOT\$GAMEBIN\$APPNAME.exe"
  84. }}
  85.  
  86. #:: detect per-user data path
  87. pushd "$STEAM\userdata"
  88. $USRCLOUD = split-path (dir "localconfig.vdf" -File -Recurse | sort LastWriteTime -Descending | Select -First 1).DirectoryName
  89. $USRLOCAL = "$USRCLOUD\$APPID\local"
  90. popd
  91.  
  92. # detect roaming profile path
  93. if ($env:USRLOCALCSGO -and (test-path "$env:USRLOCALCSGO\cfg\$M_CONFIG")) { $USRLOCAL = "$env:USRLOCALCSGO" }
  94.  
  95. #:: use freshest config across supported locations
  96. if ($cloud_cfg -gt 0) {
  97.   robocopy "$GAMEDIR\cfg/" "$USRLOCAL\cfg/" *convars*.vcfg *keys*.vcfg *video*.txt /XO >''
  98.   robocopy "$USRCLOUD\$APPID\local\cfg/" "$USRLOCAL\cfg/" *convars*.vcfg *keys*.vcfg *video*.txt /XO >''
  99.   robocopy "$env:USRLOCALCSGO\cfg/" "$USRLOCAL\cfg/" *convars*.vcfg *keys*.vcfg *video*.txt /XO >''
  100. }
  101.  
  102. #:: export steam userdata configs to cfg\cloud.cfg - then can exec cloud to restore missing settings
  103. if ($cloud_cfg -gt 0) {
  104.   sc "$GAMEDIR\cfg\cloud.cfg" "// steam cloud settings from $K_CONFIG & $U_CONFIG & $M_CONFIG`r`n" -force -ea 0
  105.   $keys_vcfg = "$USRLOCAL\cfg\$K_CONFIG"; $cfg = new-object System.Text.StringBuilder
  106.   if (test-path $keys_vcfg) {
  107.     gc $keys_vcfg |foreach { $l = $_ -split '"'; if ($l.count -eq 5) { # -and $l[3] -ne '<unbound>'
  108.       $cfg.Append('bind "')>''; $cfg.Append($l[1])>''; $cfg.Append('" "')>''; $cfg.Append($l[3])>''
  109.     $cfg.AppendLine('" | grep %%')>'' } }
  110.     if ($cfg.length -gt 0) { ac -Literal "$GAMEDIR\cfg\cloud.cfg" -Value $cfg.ToString() }
  111.   }
  112.   $user_vcfg = "$USRLOCAL\cfg\$U_CONFIG"; $cfg = new-object System.Text.StringBuilder
  113.   if (test-path $user_vcfg) {
  114.     gc $user_vcfg |foreach { $l = $_ -split '"'; if ($l.count -eq 5) {
  115.       $cfg.Append($l[1])>''; $cfg.Append(' "')>''; $cfg.Append($l[3])>''; $cfg.AppendLine('"')>'' } }
  116.     if ($cfg.length -gt 0) { ac -Literal "$GAMEDIR\cfg\cloud.cfg" -Value $cfg.ToString() }
  117.   }
  118.   $machine_vcfg = "$USRLOCAL\cfg\$M_CONFIG"; $cfg = new-object System.Text.StringBuilder
  119.   if (test-path $machine_vcfg) {
  120.     gc $machine_vcfg |foreach { $l = $_ -split '"'; if ($l.count -eq 5) {
  121.       $cfg.Append($l[1].Split('$')[0])>''; $cfg.Append(' "')>''; $cfg.Append($l[3])>''; $cfg.AppendLine('"')>'' } }
  122.     if ($cfg.length -gt 0) { ac -Literal "$GAMEDIR\cfg\cloud.cfg" -Value $cfg.ToString() }
  123.   }
  124.   ac -Literal "$GAMEDIR\cfg\cloud.cfg" -Value "execifexists autoexec.cfg";
  125. }
  126.  
  127. #:: generate a blank autoexec.cfg if not already found
  128. if (-not (test-path "$GAMEDIR\cfg\autoexec.cfg")) { sc "$GAMEDIR\cfg\autoexec.cfg" "" }
  129.  
  130. #:: clear verify integrity flags after a crash for quicker relaunch
  131. $appmanifest="$STEAMAPPS\appmanifest_$APPID.acf"
  132. if (test-path $appmanifest) {
  133.   $ACF = [io.file]::ReadAllText($appmanifest)
  134.   if ($ACF -match '"FullValidateAfterNextUpdate"\s+"1"' -or $ACF -notmatch '"StateFlags"\s+"4"') {
  135.     " update or verify integrity flags detected, will clear them and restart Steam...`n"
  136.     'dota2','cs2','steamwebhelper','steam' |foreach {kill -name $_ -force -ea 0} ; sleep 3; del "$STEAM\.crash" -force -ea 0
  137.     $ACF = $ACF -replace '("FullValidateAfterNextUpdate"\s+)("\d+")',"`$1`"0`"" -replace '("StateFlags"\s+)("\d+")',"`$1`"4`""
  138.     [io.file]::WriteAllText($appmanifest, $ACF)
  139.   }
  140. } else {
  141.   sc $appmanifest @"
  142. "AppState"
  143. {
  144.   "AppID"  "$APPID"
  145.   "Universe" "1"
  146.   "installdir" "$GAMENAME"
  147.   "StateFlags" "4"
  148. }
  149. "@ -force; " $appmanifest missing or wrong lib path detected! continuing with a default manifest...`n";
  150. }
  151.  
  152. #:: toggle fullscreen optimizations for game launcher - FSO as a concept is an abomination - ofc it causes input lag
  153. $flags = 'HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers'
  154. $found = (gi $flags -ea Ignore).Property -contains $LAUNCHER
  155. $valid = $found -and (gpv $flags $LAUNCHER) -like '*DISABLEDXMAXIMIZEDWINDOWEDMODE*'
  156. if ($enable_fso -eq 0 -and (!$found -or !$valid)) {
  157.   " disabling per app os fullscreen (un)optimizations"
  158.   ni $flags -ea 0; sp $flags $LAUNCHER '~ DISABLEDXMAXIMIZEDWINDOWEDMODE HIGHDPIAWARE' -force -ea 0
  159. }
  160. if ($enable_fso -eq 1 -and $valid) {rp $flags $LAUNCHER -force -ea 0}
  161.  
  162. #:: warn if steam not already running
  163. if ($null -eq (ps 'steam' -ea 0)) { " steam not running, will take a bit longer...`n" }
  164.  
  165. #:: parse game launch options
  166. $lo = (gc "$USRCLOUD\config\localconfig.vdf") -join "`n"
  167. $lo = (($lo -split '\n\s{5}"' + $APPID + '"\n\s{5}{\n')[1] -split '\n\s{5}}\n')[0]
  168. $lo = (($lo -split '\n\s{6}"LaunchOptions"\s+"')[1] -split '"\n')[0]
  169. $launcher_width = -1; $launcher_height = -1; $launcher_refresh = -1; $launcher_exclusive = -1; $launcher_screen = -1
  170. if ($lo -match '-w(idth)?\s+(\d+)')         { $launcher_width     = [int]$matches[2] }
  171. if ($lo -match '-h(eight)?\s+(\d+)')        { $launcher_height    = [int]$matches[2] }
  172. if ($lo -match '-r(efresh)?\s+([\d.]+)')    { $launcher_refresh   = [decimal]$matches[2] }
  173. if ($lo -match '-fullscreen\s+')            { $launcher_exclusive = 1 }
  174. if ($lo -match '-sdl_displayindex\s+(\d+)') { $launcher_screen    = [int]$matches[1] }
  175.  
  176. #:: parse video txt file - must account for sdl display index
  177. pushd "$USRLOCAL\cfg"
  178. $video_config = "$((dir '*video*.txt' -File -Recurse | sort LastWriteTime -Descending | Select -First 1).FullName)"
  179. popd
  180. $cfg_width = -1; $cfg_height = -1; $cfg_refresh = -1; $cfg_numer = -1; $cfg_denom = -1; $cfg_exclusive = -1
  181. if ($video_config -ne '') {
  182.   $lines = (gc $video_config); $txt = $lines -join "`n"
  183.   if ($txt -match '"setting.defaultres"\s+"([^"]*)"')              { $cfg_width     = [int]$matches[1] }
  184.   if ($txt -match '"setting.defaultresheight"\s+"([^"]*)"')        { $cfg_height    = [int]$matches[1] }
  185.   if ($txt -match '"setting.refreshrate_numerator"\s+"([^"]*)"')   { $cfg_numer     = [int]$matches[1] }
  186.   if ($txt -match '"setting.refreshrate_denominator"\s+"([^"]*)"') { $cfg_denom     = [int]$matches[1] }
  187.   if ($txt -match '"setting.fullscreen"\s+"([^"]*)"')              { $cfg_exclusive = [int]$matches[1] }
  188.   #:: compute numerator / denominator = refresh for video txt file
  189.   if ($cfg_numer -gt 0 -and $cfg_denom -gt 0) { $cfg_refresh = [decimal]$cfg_numer / $cfg_denom } else { $cfg_refresh = 0 }
  190. }
  191.  
  192. #:: decide which sets of video options overrides to use: script has priority, then launch options, then cfg
  193. $width   = (0,$cfg_width)[$cfg_width -gt 0];   $height = (0,$cfg_height)[$cfg_height -gt 0]
  194. $refresh = 0;  $exclusive = $cfg_exclusive
  195. if ($launcher_width -ge 0)     {$width = $launcher_width}         ; if ($force_width -ge 0)     {$width = $force_width}
  196. if ($launcher_height -ge 0)    {$height = $launcher_height}       ; if ($force_height -ge 0)    {$height = $force_height}
  197. if ($launcher_refresh -ge 0)   {$refresh = $launcher_refresh}     ; if ($force_refresh -ge 0)   {$refresh = $force_refresh}
  198. if ($launcher_exclusive -ge 0) {$exclusive = $launcher_exclusive} ; if ($force_exclusive -ge 0) {$exclusive = $force_exclusive}
  199. if ($launcher_screen -ge 0)    {$screen_sdr = $launcher_screen}   ; if ($force_screen -ge 0)    {$screen = $force_screen}
  200. if ($refresh -gt 0) {
  201.   $hz = ([string]$refresh).Split('.'); $denom = 1000
  202.   if ($hz.length -eq 2) { $numer = [int]($hz[0] + $hz[1].PadRight(3,'0')) } else { $numer = [int]($hz[0] + "000") }
  203. }
  204.  
  205. #:: set screen resolution via SetRes before launching the game, to alleviate input lag, alt-tab and secondary screens issues
  206. $library1 = "SetRes"; $version1 = "2024.3.10.0"; $about1 = "set screen resolution"; $path1 = "$env:APPDATA\AveYo\$library1.dll"
  207. <# usage:
  208.   [SetRes.Displays]::Change(output=[0:none 1:def], screen, width, height, refresh=[0:def], test=[0:change 1:test])
  209.   [SetRes.Displays]::List(output=[0:none 1:filter 2:all], screen, minw=[1024], maxw=[16384], maxh=[16384])
  210.   returns array of: sdl_idx, screen, current_width, current_height, current_refresh, max_width, max_height, max_refresh
  211.   the c# typefinition at the end of the script gets pre-compiled rather than let powershell do it slowly every launch #>
  212. if ((gi $path1 -force -ea 0).VersionInfo.FileVersion -ne $version1) { del $path1 -force -ea 0 } ; if (-not (test-path $path1)) {
  213.   mkdir "$env:APPDATA\AveYo" -ea 0 >'' 2>''; pushd $env:APPDATA\AveYo; " one-time initialization of $library1 library..."
  214.   [io.file]::WriteAllText("$env:APPDATA\AveYo\$library1.cs", ([io.file]::ReadAllText($env:0) -split '<#[:]LIBRARY1[:].*')[1])
  215.   $csc = join-path $([Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()) 'csc.exe'
  216.   start $csc -args "/out:$library1.dll /target:library /platform:anycpu /optimize /nologo $library1.cs" -nonew -wait; popd
  217. }
  218. Import-Module $path1
  219. $display = [SetRes.Displays]::Init($screen)
  220. $sdl_idx = $display[0];  $screen = $display[1];  $primary = $display[2] -gt 0;  $multimon = $display[3] -gt 1
  221.  
  222. #:: restore previous resolution if game was not gracefully closed last time
  223. if ($do_not_set_desktop_res_to_match_game -le 0 -and (test-path "$GAMEDIR\cfg\SetRes.cfg")) {
  224.   $restore = (gc "$GAMEDIR\cfg\SetRes.cfg") -split ','
  225.   if ($null -eq (ps $APPNAME -ea 0)) {
  226.     $c = [SetRes.Displays]::Change(0, $restore[1], $restore[2], $restore[3], $restore[4])
  227.   }
  228. }
  229.  
  230. #:: SetRes automatically picks a usable mode if the change is invalid so result might differ from the request
  231. $oldres  = [SetRes.Displays]::List(1, $screen)
  232. if ($width   -le 0) { $width  = $oldres[2] }
  233. if ($height  -le 0) { $height = $oldres[3] }
  234. if ($refresh -le 0) { $max_refresh = [SetRes.Displays]::List(0, $screen, $width, $width, $height); $refresh = $max_refresh[7] }
  235. $newres  = [SetRes.Displays]::Change(1, $screen, $width, $height, $refresh, 1)
  236. $width   = $newres[5]; $restore_width   = $newres[2]
  237. $height  = $newres[6]; $restore_height  = $newres[3]
  238. $refresh = $newres[7]; $restore_refresh = $newres[4]
  239. function max {$r = [SetRes.Displays]::Change(1, $oldres[1], $oldres[5], $oldres[6], $oldres[7])} # console command to set max res
  240. function min {$r = [SetRes.Displays]::Change(1, $oldres[1], 1024,       768,        $oldres[7])} # console command to set min res
  241. if ($do_not_restore_res_use_max_available -ge 1) {
  242.   $restore_width = $oldres[5]; $restore_height = $oldres[6]; $restore_refresh = $oldres[7]
  243. }
  244. $sameres = $width -eq $restore_width -and $height -eq $restore_height -and $refresh -eq $restore_refresh
  245. $ratio   = $width / $height
  246. if ($ratio -le 4/3) {$ar = 0} elseif ($ratio -le 16/10) {$ar = 2} elseif ($ratio -le 16/8.9) {$ar = 1} else {$ar = 3}
  247. $mode = "{0,4} x {1,4} {2,3}Hz" -f ($width, $height, $refresh)
  248. $rend = ('Desktop-friendly','Exclusive')[$exclusive -gt 0] + (' + FSO','')[$enable_fso -eq 0]
  249.  
  250. #::  many thanks to /u/wazernet for testing and suggestions
  251. write-host " $screen $mode $rend mode requested" -fore Yellow
  252.  
  253. #:: update video overrides in case the initial mode was invalid and SetRes applied a fallback
  254. if ($force_settings -le 0) { $video = @{} }
  255. $video["setting.defaultres"]                   = $width
  256. $video["setting.defaultresheight"]             = $height
  257. $video["setting.refreshrate_numerator"]        = $refresh
  258. $video["setting.refreshrate_denominator"]      = 1
  259. $video["setting.fullscreen"]                   = (0,1)[$exclusive -eq 1]
  260. $video["setting.coop_fullscreen"]              = (0,1)[$exclusive -ne 1]
  261. $video["setting.nowindowborder"]               = 1
  262. $video["setting.fullscreen_min_on_focus_loss"] = 0
  263. $video["setting.aspectratiomode"]              = $ar
  264.  
  265. #:: update cfg files with the overrides
  266. $video_config = ("$USRLOCAL\cfg\$V_CONFIG","$USRLOCAL\cfg\$($V_CONFIG.Replace('.txt',''))_0${sdl_idx}.txt")[$sdl_idx -gt 0]
  267. if (-not (test-path $video_config)) {sc $video_config "`"video.cfg`"`n{`n`t`"Version`"`t`t`"13`"`n}`n" -force -ea 0 }
  268. if ((test-path $video_config) -and $force_settings -ge 1) {
  269.   $lines = (gc $video_config); $txt = $lines -join "`n"; $cfg = new-object System.Text.StringBuilder # dos line-endings
  270.   foreach ($k in $video.Keys) {
  271.     if ($k -like 'setting.*' -and $txt -notmatch "`"$k`"") { $cfg.Append("`r`n`t`"$k`"`t`t`"$($video.$k)`"")>'' }
  272.   }
  273.   if ($cfg.length -gt 0) { -1..-10 |foreach { if ($lines[$_] -match "^}$") { $lines[$_ - 1] += $cfg.ToString(); return } } }
  274.   if ($cfg.length -gt 0) {sc $video_config $lines -force -ea 0 }
  275.   (gc $video_config) |foreach {
  276.     foreach ($k in $video.Keys) { if ($_ -like "*$k`"*") {
  277.       $_ = $_ -replace "(`"$k`"\s+)(`"[^`"]*`")","`$1`"$($video.$k)`"" } }; $_ } | sc $video_config -force -ea 0
  278. }
  279. $machine_config = "$USRLOCAL\cfg\$M_CONFIG"
  280. if (-not (test-path $machine_config)) {sc $machine_config "`"config`"`n{`n`t`"convars`"`n`t{`n`t`t`n`t}`n}`n" -force -ea 0 }
  281. if ((test-path $machine_config) -and $force_settings -ge 1) {
  282.   $lines = (gc $machine_config); $txt = $lines -join "`n"; $cfg = new-object System.Text.StringBuilder # unix line-endings
  283.   foreach ($k in $machine.Keys) { if ($txt -notmatch "`"$k`"") { $cfg.Append("`n`t`t`"$k`"`t`t`"$($machine.$k)`"")>'' } }
  284.   if ($cfg.length -gt 0) { -1..-10 |foreach { if ($lines[$_] -match "^\s}$") { $lines[$_ - 1] += $cfg.ToString(); return } } }
  285.   if ($cfg.length -gt 0) { sc $machine_config (($lines -join "`n") + "`n") -noNewLine -force -ea 0 }
  286.   (gc $machine_config) |foreach {
  287.     foreach ($k in $machine.Keys) { if ($_ -like "*$k`"*") {
  288.       $_ = $_ -replace "(`"$k`"\s+)(`"[^`"]*`")","`$1`"$($machine.$k)`"" } }; $_ } | sc $machine_config -force -ea 0
  289. }
  290.  
  291. #:: prepare video launch options
  292. $window = @("-force_allow_coop_fullscreen -coop_fullscreen", "-force_allow_excl_fullscreen -fullscreen")[$exclusive -ge 1]
  293. $video_options = "$window -noborder -width $width -height $height -refresh $refresh -sdl_displayindex $sdl_idx "
  294. if ($cloud_cfg -gt 0) { $extra_launch_options += "+exec_async cloud "}
  295. write-host " $video_options`n" -fore Green
  296. write-host " $LAUNCHER" -fore Gray
  297. write-host " $GAMEDIR\cfg\autoexec.cfg" -fore Gray
  298. write-host " $video_config" -fore Gray
  299. #pause
  300.  
  301. #:: prepare steam quick options
  302. $quick = '-quicklogin -skipinitialbootstrap -skipstreamingdrivers -vrdisable -nofriendsui -oldtraymenu -cef-disable-gpu -silent'
  303. $steam_options = "$QUICK -applaunch $APPID $video_options $extra_launch_options "
  304.  
  305. #:: start game (and steam if not already running)
  306. powershell.exe -nop -c "Start-Process \`"$STEAM\steam.exe\`" \`"$steam_options\`""
  307.  
  308. #:: restore res after game closes if it was changed
  309. if ($do_not_set_desktop_res_to_match_game -le 0 -and -not $sameres) {
  310.   sc "$GAMEDIR\cfg\SetRes.cfg" "$sdl_idx,$screen,$restore_width,$restore_height,$restore_refresh,`r`n" -force -ea 0
  311.   "`n will restore res to $restore_width x $restore_height ${restore_refresh}Hz after $($APPNAME.ToUpper()) closes..."
  312.   while ($null -eq ($wait = ps $APPNAME -ea 0)) { sleep -m 250 }
  313.   $change  = [SetRes.Displays]::Change(1, $screen, $width, $height, $refresh)
  314.   if ($do_not_hide_script_window_on_waiting -le 0) { sleep 3; powershell -win 1 -nop -c ';' }
  315.   while (-not $wait.HasExited) { sleep 5 }
  316.   $restore = [SetRes.Displays]::Change(1, $screen, $restore_width, $restore_height, $restore_refresh)
  317.   del "$GAMEDIR\cfg\SetRes.cfg" -force -ea 0
  318. } else {
  319.   #:: change even if res matches, to address a rare bug where game starts in a blank window and can only \ q-tab enter out of it
  320.   $change  = [SetRes.Displays]::Change(1, $screen, $restore_width, $restore_height, $restore_refresh)
  321. }
  322. " can enter: max for $($oldres[5])x$($oldres[6]) or: min for 1024x768 if needed"
  323.  
  324. #:: done, script closes
  325. if ($do_not_hide_script_window_on_waiting -ge 1) { return }
  326. [Environment]::Exit(0)
  327.  
  328. <#:LIBRARY1: start <# ------------------------------------------------------------------------------ switch syntax highlight to C#
  329. /// SetRes - loosely based on code by Rick Strahl
  330. using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Linq; using System.Reflection;
  331. [assembly:AssemblyVersion("2024.3.10.0")] [assembly: AssemblyTitle("AveYo")]
  332. namespace SetRes
  333. {
  334.   public static class Displays
  335.   {
  336.     private const short CCDEVICENAME = 32,  CCFORMNAME  = 32;
  337.  
  338.     public const int SUCCESS       = 0,  ENUM_CURRENT  = -1,  MONITOR_DEFAULTTONEAREST = 0x00000002;
  339.     public const int DMDFO_DEFAULT = 0,  DMDFO_STRETCH =  1,  DMDFO_CENTER = 2;
  340.     public const int DMDO_DEFAULT  = 0,  DMDO_90       =  1,  DMDO_180     = 2,  DMDO_270 = 3;
  341.  
  342.     [Flags()]
  343.     private enum EdsFlags : int
  344.     {
  345.       EDS_ATTACHEDTODESKTOP = 0x00000001,  EDS_MULTIDRIVER   = 0x00000002,  EDS_PRIMARYDEVICE = 0x00000004,
  346.       EDS_MIRRORINGDRIVER   = 0x00000008,  EDS_VGACOMPATIBLE = 0x00000010,  EDS_REMOVABLE     = 0x00000020,
  347.       EDS_MODESPRUNED       = 0x08000000,  EDS_REMOTE        = 0x04000000,  EDS_DISCONNECT    = 0x02000000
  348.     }
  349.  
  350.     [Flags()]
  351.     private enum CdsFlags : uint
  352.     {
  353.       CDS_NONE            = 0x00000000,  CDS_UPDATEREGISTRY      = 0x00000001,  CDS_TEST                 = 0x00000002,
  354.       CDS_FULLSCREEN      = 0x00000004,  CDS_GLOBAL              = 0x00000008,  CDS_SET_PRIMARY          = 0x00000010,
  355.       CDS_VIDEOPARAMETERS = 0x00000020,  CDS_ENABLE_UNSAFE_MODES = 0x00000100,  CDS_DISABLE_UNSAFE_MODES = 0x00000200,
  356.       CDS_RESET           = 0x40000000,  CDS_RESET_EX            = 0x20000000,  CDS_NORESET             = 0x10000000
  357.     }
  358.  
  359.     [Flags()]
  360.     private enum DmFlags : int
  361.     {
  362.       DM_ORIENTATION   = 0x00000001,  DM_PAPERSIZE          = 0x00000002,  DM_PAPERLENGTH        = 0x00000004,
  363.       DM_PAPERWIDTH    = 0x00000008,  DM_SCALE              = 0x00000010,  DM_POSITION           = 0x00000020,
  364.       DM_NUP           = 0x00000040,  DM_DISPLAYORIENTATION = 0x00000080,  DM_COPIES             = 0x00000100,
  365.       DM_DEFAULTSOURCE = 0x00000200,  DM_PRINTQUALITY       = 0x00000400,  DM_COLOR              = 0x00000800,
  366.       DM_DUPLEX        = 0x00001000,  DM_YRESOLUTION        = 0x00002000,  DM_TTOPTION           = 0x00004000,
  367.       DM_COLLATE       = 0x00008000,  DM_FORMNAME           = 0x00010000,  DM_LOGPIXELS          = 0x00020000,
  368.       DM_BITSPERPEL    = 0x00040000,  DM_PELSWIDTH          = 0x00080000,  DM_PELSHEIGHT         = 0x00100000,
  369.       DM_DISPLAYFLAGS  = 0x00200000,  DM_DISPLAYFREQUENCY   = 0x00400000,  DM_ICMMETHOD          = 0x00800000,
  370.       DM_ICMINTENT     = 0x01000000,  DM_MEDIATYPE          = 0x02000000,  DM_DITHERTYPE         = 0x04000000,
  371.       DM_PANNINGWIDTH  = 0x08000000,  DM_PANNINGHEIGHT      = 0x10000000,  DM_DISPLAYFIXEDOUTPUT = 0x20000000
  372.     }
  373.  
  374.     [StructLayout(LayoutKind.Sequential)]
  375.     public struct POINTL { public int x; public int y; }
  376.  
  377.     [StructLayout(LayoutKind.Sequential)]
  378.     public struct RECT { public int left; public int top; public int right; public int bottom; }
  379.  
  380.     [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
  381.     private struct DISPLAY_DEVICE
  382.     {
  383.       [MarshalAs(UnmanagedType.U4)]                       public int      cb;
  384.       [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)]  public string   DeviceName;
  385.       [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string   DeviceString;
  386.       [MarshalAs(UnmanagedType.U4)]                       public EdsFlags StateFlags;
  387.       [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string   DeviceID;
  388.       [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string   DeviceKey;
  389.       public void Initialize()
  390.       {
  391.         this.DeviceName   = new string(new char[32]);
  392.         this.DeviceString = new string(new char[128]);
  393.         this.DeviceID     = new string(new char[128]);
  394.         this.DeviceKey    = new string(new char[128]);
  395.         this.cb           = Marshal.SizeOf(this);
  396.       }
  397.     }
  398.  
  399.     [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
  400.     private struct DEVMODE
  401.     {
  402.       [MarshalAs(UnmanagedType.ByValTStr, SizeConst=CCDEVICENAME)]
  403.                                     public string  dmDeviceName;
  404.       [MarshalAs(UnmanagedType.U2)] public ushort  dmSpecVersion;
  405.       [MarshalAs(UnmanagedType.U2)] public ushort  dmDriverVersion;
  406.       [MarshalAs(UnmanagedType.U2)] public ushort  dmSize;
  407.       [MarshalAs(UnmanagedType.U2)] public ushort  dmDriverExtra;
  408.       [MarshalAs(UnmanagedType.U4)] public DmFlags dmFields;
  409.                                     public POINTL  dmPosition;
  410.       [MarshalAs(UnmanagedType.U4)] public uint    dmDisplayOrientation;
  411.       [MarshalAs(UnmanagedType.U4)] public uint    dmDisplayFixedOutput;
  412.       [MarshalAs(UnmanagedType.I2)] public short   dmColor;
  413.       [MarshalAs(UnmanagedType.I2)] public short   dmDuplex;
  414.       [MarshalAs(UnmanagedType.I2)] public short   dmYResolution;
  415.       [MarshalAs(UnmanagedType.I2)] public short   dmTTOption;
  416.       [MarshalAs(UnmanagedType.I2)] public short   dmCollate;
  417.       [MarshalAs(UnmanagedType.ByValTStr, SizeConst=CCFORMNAME)]
  418.                                     public string  dmFormName;
  419.       [MarshalAs(UnmanagedType.U2)] public ushort  dmLogPixels;
  420.       [MarshalAs(UnmanagedType.U4)] public uint    dmBitsPerPel;
  421.       [MarshalAs(UnmanagedType.U4)] public uint    dmPelsWidth;
  422.       [MarshalAs(UnmanagedType.U4)] public uint    dmPelsHeight;
  423.       [MarshalAs(UnmanagedType.U4)] public uint    dmDisplayFlags;
  424.       [MarshalAs(UnmanagedType.U4)] public uint    dmDisplayFrequency;
  425.       [MarshalAs(UnmanagedType.U4)] public uint    dmICMMethod;
  426.       [MarshalAs(UnmanagedType.U4)] public uint    dmICMIntent;
  427.       [MarshalAs(UnmanagedType.U4)] public uint    dmMediaType;
  428.       [MarshalAs(UnmanagedType.U4)] public uint    dmDitherType;
  429.       [MarshalAs(UnmanagedType.U4)] public uint    dmReserved1;
  430.       [MarshalAs(UnmanagedType.U4)] public uint    dmReserved2;
  431.       [MarshalAs(UnmanagedType.U4)] public uint    dmPanningWidth;
  432.       [MarshalAs(UnmanagedType.U4)] public uint    dmPanningHeight;
  433.       public void Initialize()
  434.       {
  435.         this.dmDeviceName = new string(new char[CCDEVICENAME]);
  436.         this.dmFormName   = new string(new char[CCFORMNAME]);
  437.         this.dmSize       = (ushort)Marshal.SizeOf(this);
  438.       }
  439.     }
  440.  
  441.     [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
  442.     private struct MONITORINFOEX
  443.     {
  444.       public uint cbSize;
  445.       public RECT rcMonitor;
  446.       public RECT rcWork;
  447.       public int dwFlags;
  448.       [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string szDevice;
  449.       public void Initialize()
  450.       {
  451.         this.rcMonitor = new RECT();
  452.         this.rcWork    = new RECT();
  453.         this.szDevice  = new string(new char[32]);
  454.         this.cbSize    = (uint)Marshal.SizeOf(this);
  455.       }
  456.     }
  457.  
  458.     [DllImport("kernel32", ExactSpelling = true)] private static extern IntPtr
  459.     GetConsoleWindow();
  460.  
  461.     [DllImport("user32")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool
  462.     GetWindowRect(IntPtr hWnd, out RECT lpRect);
  463.  
  464.     [DllImport("user32")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool
  465.     MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
  466.  
  467.     [DllImport("user32")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool
  468.     GetCursorPos(out POINTL lpPoint);
  469.  
  470.     [DllImport("user32", SetLastError = true)] private static extern IntPtr
  471.     MonitorFromPoint(POINTL pt, int dwFlags);
  472.  
  473.     [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)]
  474.     [return: MarshalAs(UnmanagedType.Bool)] private static extern bool
  475.     GetMonitorInfo(IntPtr hMonitor, [In, Out] ref MONITORINFOEX lpmi);
  476.  
  477.     [DllImport("user32", CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool
  478.     EnumDisplayMonitors(IntPtr hdc, IntPtr lpRect, EnumDisplayMonitorsDelegate lpfnEnum, IntPtr dwData);
  479.  
  480.     [DllImport("user32")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool
  481.     EnumDisplayDevices(string lpDevice, uint iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, uint dwFlags);
  482.  
  483.     [DllImport("user32", SetLastError=true, BestFitMapping=false, ThrowOnUnmappableChar=true)]
  484.     [return: MarshalAs(UnmanagedType.Bool)] private static extern bool
  485.     EnumDisplaySettings(byte[] lpszDeviceName, [param: MarshalAs(UnmanagedType.U4)] int iModeNum, [In,Out] ref DEVMODE lpDevMode);
  486.  
  487.     [DllImport("user32")] private static extern int
  488.     ChangeDisplaySettingsEx(string lpszDeviceName, ref DEVMODE lpDevMode, IntPtr hwnd, CdsFlags dwflags, IntPtr lParam);
  489.  
  490.     //[DllImport("user32")] private static extern int
  491.     //ChangeDisplaySettingsEx(IntPtr lpszDeviceName, IntPtr lpDevMode, IntPtr hwnd, int dwflags, IntPtr lParam);
  492.  
  493.     [DllImport("user32")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool
  494.     SetProcessDPIAware();
  495.  
  496.     private delegate bool EnumDisplayMonitorsDelegate(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData);
  497.  
  498.     private static IntPtr consolehWnd = GetConsoleWindow();
  499.  
  500.     public static class StringExtensions
  501.     {
  502.       public static byte[] ToLPTStr(string str)
  503.       {
  504.         return (str == null) ? null : Array.ConvertAll((str + '\0').ToCharArray(), Convert.ToByte);
  505.       }
  506.     }
  507.  
  508.     public class DisplayInfo
  509.     {
  510.       public int    Index      { get; set; }
  511.       public int    SDLIndex   { get; set; }
  512.       public string DeviceName { get; set; }
  513.       public int    Height     { get; set; }
  514.       public int    Width      { get; set; }
  515.       public RECT   Bounds     { get; set; }
  516.       public RECT   WorkArea   { get; set; }
  517.       public bool   IsPrimary  { get; set; }
  518.       public bool   IsCurrent  { get; set; }
  519.  
  520.       public override string ToString()
  521.       {
  522.         return string.Format("{0} {1} {2} {3} {4} ({5},{6},{7},{8}){9}{10}", Index, SDLIndex, DeviceName,
  523.           Height, Width, Bounds.left, Bounds.top, Bounds.right, Bounds.bottom,
  524.           IsPrimary ? " [primary]" : "", IsCurrent ? " [current]" : !!)
  525.       }
  526.     }
  527.  
  528.     public class DisplayDevice
  529.     {
  530.       public int    Index        { get; set; }
  531.       public int    MonitorIndex { get; set; }
  532.       public int    SDLIndex     { get; set; }
  533.       public string Id           { get; set; }
  534.       public string DriverName   { get; set; }
  535.       public string DisplayName  { get; set; }
  536.       public string AdapterName  { get; set; }
  537.       public RECT   Bounds       { get; set; }
  538.       public bool   IsPrimary    { get; set; }
  539.       public bool   IsCurrent    { get; set; }
  540.  
  541.       public override string ToString()
  542.       {
  543.         return ToString(false);
  544.       }
  545.       public string ToString(bool Detail)
  546.       {
  547.         if (Detail)
  548.         {
  549.           var sb = new System.Text.StringBuilder(9);
  550.           sb.AppendFormat(" Index:        {0}\n", Index);
  551.           sb.AppendFormat(" MonitorIndex: {0}\n", MonitorIndex);
  552.           sb.AppendFormat(" SDLIndex:     {0}\n", SDLIndex);
  553.           sb.AppendFormat(" Id:           {0}\n", Id);
  554.           sb.AppendFormat(" DriverName:   {0}\n", DriverName);
  555.           sb.AppendFormat(" DisplayName:  {0}\n", DisplayName);
  556.           sb.AppendFormat(" AdapterName:  {0}\n", AdapterName);
  557.           sb.AppendFormat(" Resolution:   {0} x {1}\n", Bounds.right - Bounds.left, Bounds.bottom - Bounds.top);
  558.           sb.AppendFormat(" Bounds:       {0},{1},{2},{3}\n", Bounds.left, Bounds.top, Bounds.right, Bounds.bottom);
  559.           sb.AppendFormat(" IsPrimary:    {0}\n", IsPrimary);
  560.           sb.AppendFormat(" IsCurrent:    {0}\n", IsCurrent);
  561.           return sb.ToString();
  562.         }
  563.         return string.Format(" {0} {1} {2} - {3}{4}{5}", MonitorIndex, SDLIndex, AdapterName, DisplayName,
  564.           IsPrimary ? " [primary]" : "", IsCurrent ? " [current]" : !!)
  565.       }
  566.     }
  567.  
  568.     public class DisplaySettings
  569.     {
  570.       public int  Index       { get; set; }
  571.       public uint Width       { get; set; }
  572.       public uint Height      { get; set; }
  573.       public uint Refresh     { get; set; }
  574.       public uint Orientation { get; set; }
  575.       public uint FixedOutput { get; set; }
  576.  
  577.       public override string ToString()
  578.       {
  579.         return ToString(false);
  580.       }
  581.  
  582.       public string ToString(bool Detail)
  583.       {
  584.         var culture = System.Globalization.CultureInfo.CurrentCulture;
  585.         if (!Detail)
  586.           return string.Format(culture, "   {0,4} x {1,4}", Width, Height);
  587.  
  588.         var degrees = Orientation == DMDO_90  ? " 90\u00b0" : Orientation == DMDO_180 ? " 180\u00b0" :
  589.           Orientation == DMDO_270 ? " 270\u00b0" : !!
  590.         var scaling = FixedOutput == DMDFO_CENTER ? " C" : FixedOutput == DMDFO_STRETCH ? " F" : !!
  591.         return string.Format(culture, "   {0,4} x {1,4} {2,3}Hz {3}{4}", Width, Height, Refresh, degrees, scaling);
  592.       }
  593.  
  594.       public override bool Equals(object d)
  595.       {
  596.         var disp = d as DisplaySettings;
  597.         return (disp.Width == Width && disp.Height == Height && disp.Refresh == Refresh && disp.Orientation == Orientation);
  598.       }
  599.  
  600.       public override int GetHashCode()
  601.       {
  602.         return (string.Format("W{0}H{1}R{2}O{3}", Width, Height, Refresh, Orientation)).GetHashCode();
  603.       }
  604.     }
  605.  
  606.     private static DEVMODE GetDeviceMode(string deviceName = null)
  607.     {
  608.       var mode = new DEVMODE();
  609.       mode.Initialize();
  610.  
  611.       if (EnumDisplaySettings(StringExtensions.ToLPTStr(deviceName), ENUM_CURRENT, ref mode))
  612.         return mode;
  613.       else
  614.         throw new InvalidOperationException(":(");
  615.     }
  616.  
  617.     private static DisplaySettings CreateDisplaySettingsObject(int idx, DEVMODE mode)
  618.     {
  619.       return new DisplaySettings()
  620.       {
  621.         Index       = idx,
  622.         Width       = mode.dmPelsWidth,
  623.         Height      = mode.dmPelsHeight,
  624.         Refresh     = mode.dmDisplayFrequency,
  625.         Orientation = mode.dmDisplayOrientation,
  626.         FixedOutput = mode.dmDisplayFixedOutput
  627.       };
  628.     }
  629.  
  630.     public static List<DisplayDevice> GetAllDisplayDevices()
  631.     {
  632.       var list = new List<DisplayDevice>();
  633.       uint idx = 0;
  634.       uint size = 256;
  635.       var device = new DISPLAY_DEVICE();
  636.       device.Initialize();
  637.  
  638.       /// AveYo: detect current monitor via cursor pointer and save Bounds rect for all
  639.       var currentCursorP = new POINTL();
  640.       GetCursorPos(out currentCursorP);
  641.       var currentMonitor = MonitorFromPoint(currentCursorP, MONITOR_DEFAULTTONEAREST);
  642.       var currentMonInfo = new MONITORINFOEX();
  643.       currentMonInfo.Initialize();
  644.       var currentDevice = GetMonitorInfo(currentMonitor, ref currentMonInfo) ? currentMonInfo.szDevice : !!
  645.  
  646.       var monitors = new List<DisplayInfo>();
  647.       EnumDisplayMonitors( IntPtr.Zero, IntPtr.Zero,
  648.         delegate (IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor,  IntPtr dwData)
  649.         {
  650.           var mi = new MONITORINFOEX();
  651.           mi.Initialize();
  652.           var success = GetMonitorInfo(hMonitor, ref mi);
  653.           if (success)
  654.           {
  655.             var di = new DisplayInfo();
  656.             di.Index      = monitors.Count + 1;
  657.             di.SDLIndex   = monitors.Count + 1;
  658.             di.DeviceName = mi.szDevice;
  659.             di.Width      = mi.rcMonitor.right - mi.rcMonitor.left;
  660.             di.Height     = mi.rcMonitor.bottom - mi.rcMonitor.top;
  661.             di.Bounds     = mi.rcMonitor;
  662.             di.WorkArea   = mi.rcWork;
  663.             di.IsPrimary  = (mi.dwFlags > 0);
  664.             di.IsCurrent  = (mi.szDevice == currentDevice);
  665.             monitors.Add(di);
  666.           }
  667.           return true;
  668.         }, IntPtr.Zero
  669.       );
  670.  
  671.       /// AveYo: calculate equivalent for sdl_displayindex to use as game launch option
  672.       var primary = monitors.FirstOrDefault(d => d.IsPrimary == true);
  673.       primary.SDLIndex = 0;
  674.       if (primary.Index == 1) {
  675.         for (var i = 1; i < monitors.Count; i++) { monitors[i].SDLIndex = i; }
  676.       }
  677.       else if (primary.Index <= monitors.Count - 1) {
  678.         for (var i = primary.Index; i <= monitors.Count - 1; i++) { monitors[i].SDLIndex = i; }
  679.       }
  680.       //foreach (var mon in monitors) Console.WriteLine(mon.ToString());
  681.  
  682.       while (EnumDisplayDevices(null, idx, ref device, size) )
  683.       {
  684.         if (device.StateFlags.HasFlag(EdsFlags.EDS_ATTACHEDTODESKTOP))
  685.         {
  686.           var isPrimary  = device.StateFlags.HasFlag(EdsFlags.EDS_PRIMARYDEVICE);
  687.           var isCurrent  = currentDevice != "" ? (device.DeviceName == currentDevice) : !REG3XP0!>isPrimary;
  688.           var monitor = monitors.FirstOrDefault(d => d.DeviceName == device.DeviceName);
  689.           var deviceName = device.DeviceName; var deviceString = device.DeviceString;
  690.  
  691.           EnumDisplayDevices(device.DeviceName, 0, ref device, 0);
  692.           var dev = new DisplayDevice()
  693.           {
  694.             Index        = list.Count + 1,
  695.             MonitorIndex = monitor.Index > 0 ? monitor.Index : list.Count + 1,
  696.             SDLIndex     = monitor.Index > 0 ? monitor.SDLIndex : list.Count + 1,
  697.             Id           = device.DeviceID,
  698.             DriverName   = deviceName,
  699.             DisplayName  = device.DeviceString,
  700.             AdapterName  = deviceString,
  701.             Bounds       = monitor.Bounds,
  702.             IsPrimary    = isPrimary,
  703.             IsCurrent    = isCurrent
  704.           };
  705.           list.Add(dev);
  706.         }
  707.         idx++;
  708.         device = new DISPLAY_DEVICE();
  709.         device.Initialize();
  710.       }
  711.       return list;
  712.     }
  713.  
  714.     public static List<DisplaySettings> GetAllDisplaySettings(string deviceName = null)
  715.     {
  716.       var list = new List<DisplaySettings>();
  717.       DEVMODE mode = new DEVMODE();
  718.       mode.Initialize();
  719.       int idx = 0;
  720.  
  721.       while (EnumDisplaySettings(StringExtensions.ToLPTStr(deviceName), idx, ref mode))
  722.         list.Add(CreateDisplaySettingsObject(idx++, mode));
  723.       return list;
  724.     }
  725.  
  726.     public static DisplaySettings GetCurrentSettings(string deviceName = null)
  727.     {
  728.       return CreateDisplaySettingsObject(-1, GetDeviceMode(deviceName));
  729.     }
  730.  
  731.     public static DisplaySettings GetCurrentDisplaySetting(string deviceName = null)
  732.     {
  733.       var mode = GetDeviceMode(deviceName);
  734.       return CreateDisplaySettingsObject(0, mode);
  735.     }
  736.  
  737.     public static int[] List(int Output = 1, int Screen = -1, int MinWidth = 1024, int MaxWidth = 16384, int MaxHeight = 16384)
  738.     {
  739.       var devices = GetAllDisplayDevices();
  740.       var monitor = devices.FirstOrDefault(d => d.IsCurrent);
  741.       if (Screen > 0 && Screen <= devices.Count) monitor = devices.FirstOrDefault(d => d.MonitorIndex == Screen);
  742.  
  743.       if (Output != 0) foreach (var display in devices) Console.WriteLine(display.ToString());
  744.  
  745.       var displayModes = GetAllDisplaySettings(monitor.DriverName);
  746.       var current      = GetCurrentDisplaySetting(monitor.DriverName);
  747.       IList<DisplaySettings> filtered = displayModes;
  748.  
  749.       /// AveYo: MaxWidth & MaxHeight are used to aggregate the list further by Refresh rate
  750.       if (Output == 1)
  751.       {
  752.         filtered = displayModes
  753.           .Where(d => d.Width >= MinWidth && d.Width <= MaxWidth && d.Height <= MaxHeight && d.Orientation == current.Orientation)
  754.           .OrderByDescending(d => d.Width).ThenByDescending(d => d.Refresh)
  755.           .GroupBy(d => new {d.Width, d.Height}).Select(g => g.First()).ToList();
  756.       }
  757.       else if (Output == 2 || Output == 0 && MaxWidth != 16384)
  758.       {
  759.         filtered = displayModes
  760.           .Where(d => d.Width >= MinWidth && d.Width <= MaxWidth && d.Height <= MaxHeight)
  761.           .OrderByDescending(d => d.Width).ThenByDescending(d => d.Refresh).ToList();
  762.       }
  763.  
  764.       if (filtered.Count == 0)
  765.         filtered.Add(current);
  766.  
  767.       var max = filtered.Aggregate((top, atm) => {
  768.           return atm.Width > top.Width || atm.Height > top.Height ? atm :
  769.             atm.Width == top.Width && atm.Height == top.Height && atm.Refresh > top.Refresh ? atm : !!
  770.       });
  771.  
  772.       foreach (var set in filtered)
  773.       {
  774.         if (set.Equals(current))
  775.         {
  776.           if (Output != 0) Console.WriteLine(set.ToString(true) + " [current]");
  777.         }
  778.         else
  779.         {
  780.           if (Output != 0) Console.WriteLine(set.ToString(true));
  781.         }
  782.       }
  783.       if (Output != 0) Console.WriteLine();
  784.       return new int[] { monitor.SDLIndex, monitor.MonitorIndex,
  785.         (int)current.Width, (int)current.Height, (int)current.Refresh, (int)max.Width, (int)max.Height, (int)max.Refresh };
  786.     }
  787.  
  788.     public static int[] Change(int Output = 1, int Screen = -1, int Width = 0, int Height = 0, decimal Refresh = 0, int Test = 0)
  789.     {
  790.       var devices = GetAllDisplayDevices();
  791.       var monitor = devices.FirstOrDefault(d => d.IsCurrent);
  792.       if (Screen > 0 && Screen <= devices.Count) monitor = devices.FirstOrDefault(d => d.MonitorIndex == Screen);
  793.  
  794.       var deviceName = monitor.DriverName;
  795.       var current    = GetCurrentDisplaySetting(deviceName);
  796.       //var position = new POINTL(); position.x = monitor.Bounds.left; position.y = monitor.Bounds.top;
  797.  
  798.       if (Width == 0 || Height == 0)
  799.       {
  800.         if (Output != 0) Console.WriteLine(" Width and Height parameters required.\n");
  801.         return new int[] { monitor.SDLIndex, monitor.MonitorIndex,
  802.           (int)current.Width, (int)current.Height, (int)current.Refresh, 0, 0, 0, 1 };
  803.       }
  804.  
  805.       /// AveYo: Refresh fallback from fractional ex: 59.976 - to nearest integer ex: 60 - to highest supported
  806.       uint Orientation = 0, FixedOutput = 0, Temporary = 0; /// for testing
  807.       var displayModes = GetAllDisplaySettings(deviceName);
  808.       var filtered = displayModes
  809.         .Where(d => d.Width == Width && d.Height == Height && d.Orientation == current.Orientation)
  810.         .OrderByDescending(d => d.Width).ThenByDescending(d => d.Refresh).ToList();
  811.  
  812.       var ref1 = filtered.FirstOrDefault(d => d.Refresh == (uint)Decimal.Truncate(Refresh));
  813.       var ref2 = filtered.FirstOrDefault(d => d.Refresh == (uint)Decimal.Truncate(Refresh + 1));
  814.       var set = Refresh == 0 ? filtered.FirstOrDefault() : ref1 != null ? ref1 : class="re0">ref2 != null ? ref2 : !REG3XP0!>filtered.FirstOrDefault();
  815.       if (set == null)
  816.       {
  817.         /// AveYo: Resolution fallback to current
  818.         if (Output != 0) Console.WriteLine(" No matching display mode!\n");
  819.         set = current;
  820.         return new int[] { monitor.SDLIndex, monitor.MonitorIndex,
  821.           (int)set.Width, (int)set.Height, (int)set.Refresh, (int)set.Width, (int)set.Height, (int)set.Refresh, 2 };
  822.       }
  823.  
  824.       try
  825.       {
  826.         DEVMODE mode = GetDeviceMode(deviceName);
  827.         //mode.dmPosition           = position;
  828.         mode.dmPelsWidth          = set.Width;
  829.         mode.dmPelsHeight         = set.Height;
  830.         mode.dmDisplayFrequency   = set.Refresh;
  831.         mode.dmDisplayOrientation = Orientation > 0 ? Orientation : set.Orientation;
  832.         mode.dmDisplayFixedOutput = FixedOutput > 0 ? FixedOutput : set.FixedOutput;
  833.         mode.dmFields             = DmFlags.DM_PELSWIDTH | DmFlags.DM_PELSHEIGHT; //DmFlags.DM_POSITION
  834.         if (Refresh > 0)     mode.dmFields |= DmFlags.DM_DISPLAYFREQUENCY;
  835.         if (FixedOutput > 0) mode.dmFields |= DmFlags.DM_DISPLAYORIENTATION;
  836.         if (Temporary > 0)   mode.dmFields |= DmFlags.DM_DISPLAYFIXEDOUTPUT;
  837.  
  838.         /// AveYo: test and apply the target res even if it's the same as the current one
  839.         CdsFlags flags = CdsFlags.CDS_TEST | CdsFlags.CDS_RESET | CdsFlags.CDS_UPDATEREGISTRY; //CdsFlags.CDS_NORESET
  840.         if (Temporary > 0) flags |= CdsFlags.CDS_FULLSCREEN;
  841.  
  842.         int result = ChangeDisplaySettingsEx(deviceName, ref mode, IntPtr.Zero, flags, IntPtr.Zero);
  843.         if (Test != 0)
  844.           return new int[] { monitor.SDLIndex, monitor.MonitorIndex,
  845.             (int)current.Width, (int)current.Height, (int)current.Refresh, (int)set.Width, (int)set.Height, (int)set.Refresh, 0 };
  846.         if (result != SUCCESS)
  847.           throw new InvalidOperationException(string.Format("{0} : {1} = N/A", set.ToString(true), monitor.DisplayName));
  848.         flags &= ~CdsFlags.CDS_TEST;
  849.         result = ChangeDisplaySettingsEx(deviceName, ref mode, IntPtr.Zero, flags, IntPtr.Zero);
  850.         if (result != SUCCESS)
  851.           throw new InvalidOperationException(string.Format("{0} : {1} = FAIL", set.ToString(true), monitor.DisplayName));
  852.  
  853.         //ChangeDisplaySettingsEx(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero);
  854.         if (Output != 0) Console.WriteLine(string.Format("{0} : class="re0">{1} = OK", set.ToString(true), monitor.DisplayName));
  855.         return new int[] { monitor.SDLIndex, monitor.MonitorIndex,
  856.           (int)current.Width, (int)current.Height, (int)current.Refresh, (int)set.Width, (int)set.Height, (int)set.Refresh, 0 };
  857.       }
  858.       catch(Exception ex)
  859.       {
  860.         if (Output != 0) Console.WriteLine(ex.Message);
  861.         return new int[] { monitor.SDLIndex, monitor.MonitorIndex,
  862.           (int)current.Width, (int)current.Height, (int)current.Refresh, 0, 0, 0, 3 };
  863.       }
  864.     }
  865.  
  866.     public static int[] Init(int Screen = -1)
  867.     {
  868.       SetProcessDPIAware(); /// AveYo: calculate using real screen values, not windows dpi scaling ones
  869.       var devices = GetAllDisplayDevices();
  870.       var monitor = devices.FirstOrDefault(d => d.IsCurrent);
  871.       if (Screen > 0 && Screen <= devices.Count) monitor = devices.FirstOrDefault(d => d.MonitorIndex == Screen);
  872.       RECT cR = new RECT(), mR = monitor.Bounds;
  873.       GetWindowRect(consolehWnd, out cR);
  874.       /// AveYo: move console window to Screen index or currently active
  875.       MoveWindow(consolehWnd, mR.left + 100, mR.top + 100, cR.right - cR.left, cR.bottom - cR.top, true);
  876.       return new int[] { monitor.SDLIndex, monitor.MonitorIndex, monitor.IsPrimary ? 1 : 0, devices.Count };
  877.     }
  878.   }
  879. }
  880. <#:LIBRARY1: end -------------------------------------------------------------------------------------------------------------- #>
  881. $_press_enter_if_copy_pasted_to_powershell
  882.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement