Advertisement
aveyo

CS2_launcher

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