Advertisement
aveyo

CS2_launcher

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