├── changes.txt ├── srcgo ├── ast_transform │ └── go.mod └── ast_to_sp │ └── go.mod ├── test_code ├── range.go ├── db_test.go ├── mantreads.go ├── kv_func.go └── joined_senses_stasis.go ├── go.mod ├── rewrite ├── sptools │ ├── smxtools │ │ └── smxtools.go │ └── sptools.go ├── LICENSE ├── test.go ├── srcgo │ ├── pass8_rename_receivers.go │ ├── pass4_mutate_andnot_exprs.go │ ├── pass3_merge_rettypes.go │ ├── pass9_mutate_ranges.go │ ├── pass1_illegal_code.go │ ├── pass6_mutate_assign_defs.go │ ├── pass7_mutate_assignments.go │ ├── pass10_mutate_no_ret_calls.go │ ├── pass2_name_anon_funcs.go │ └── pass5_mutate_ret_exprs.go ├── sourcemod │ ├── events.go │ ├── core.go │ └── files.go └── main.go ├── LICENSE ├── sourcemod ├── template.go ├── types.go ├── helpers.go ├── nextmap.go ├── handles.go ├── commandline.go ├── logging.go ├── adt_stack.go ├── lang.go ├── banning.go ├── vector.go ├── adt_trie.go ├── timers.go ├── sorting.go ├── floats.go ├── adt_array.go ├── usermessages.go ├── commandfilters.go ├── events.go ├── strings.go ├── core.go ├── bitbuffer.go ├── textparse.go ├── convars.go ├── clients.go ├── protobuf.go ├── files.go ├── keyvalues.go ├── entity.go ├── dbi.go └── functions.go ├── tf2items_stocks.go ├── datapack.go ├── clientprefs.go ├── tf2items.go ├── cfgmap.go ├── README.md ├── sourcemod.go ├── test.go ├── sdkhooks.go └── cstrike.go /changes.txt: -------------------------------------------------------------------------------- 1 | Added composite literal construction when using `:=` define operator. -------------------------------------------------------------------------------- /srcgo/ast_transform/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/assyrianic/SourceGo/srcgo/ast_transform 2 | 3 | go 1.17 4 | -------------------------------------------------------------------------------- /srcgo/ast_to_sp/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/assyrianic/SourceGo/srcgo/ast_to_sp 2 | 3 | go 1.17 4 | 5 | replace github.com/assyrianic/SourceGo/srcgo/ast_transform => ./srcgo/ast_transform 6 | -------------------------------------------------------------------------------- /test_code/range.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "sourcemod" 5 | ) 6 | 7 | 8 | func main() { 9 | var clients [MAXPLAYERS]int 10 | for i := range clients { 11 | if !IsValidClient(clients[i]) { 12 | continue 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /test_code/db_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | type Database any 5 | const ( 6 | DBCB_Connect = 0 7 | ) 8 | 9 | var hTheDB Database 10 | 11 | func (Database) Connect(conn int, n string) 12 | 13 | func main() { 14 | Database.Connect(DBCB_Connect, "maptracker") 15 | } 16 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/assyrianic/SourceGo 2 | 3 | go 1.17 4 | 5 | replace github.com/assyrianic/SourceGo/srcgo/ast_to_sp => ./srcgo/ast_to_sp 6 | 7 | replace github.com/assyrianic/SourceGo/srcgo/ast_transform => ./srcgo/ast_transform 8 | 9 | require ( 10 | github.com/assyrianic/SourceGo/srcgo/ast_to_sp v0.0.0-00010101000000-000000000000 // indirect 11 | github.com/assyrianic/SourceGo/srcgo/ast_transform v0.0.0-00010101000000-000000000000 // indirect 12 | ) 13 | -------------------------------------------------------------------------------- /rewrite/sptools/smxtools/smxtools.go: -------------------------------------------------------------------------------- 1 | package SMXTools 2 | 3 | // saving this for the future. 4 | // no affiliation with sourcepawn's smxtools. 5 | 6 | import ( 7 | "fmt" 8 | "os" 9 | "io" 10 | "io/ioutil" 11 | "strings" 12 | "bytes" 13 | ) 14 | 15 | 16 | type ( 17 | SmxNameTable struct { 18 | NameTable map[string]uint 19 | Names []string 20 | BufSize uint 21 | } 22 | ) 23 | 24 | 25 | 26 | func CompactEncodeUint32(value uint32) []byte { 27 | var out []byte 28 | for copy := value; copy > 0; copy >>= 7 { 29 | b := byte(copy & 0x7f) 30 | if copy > 0x7f { 31 | b |= 0x80 32 | } 33 | out = append(out, b) 34 | } 35 | return out 36 | } -------------------------------------------------------------------------------- /test_code/mantreads.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "sourcemod" 5 | "sdkhooks" 6 | ) 7 | 8 | func main() { 9 | for i := 1; i<=MaxClients; i++ { 10 | if IsClientInGame(i) { 11 | OnClientPutInServer(i) 12 | } 13 | } 14 | } 15 | 16 | func OnClientPutInServer(client Entity) { 17 | SDKHook(client, SDKHook_OnTakeDamage, func (victim int, attacker, inflictor *int, damage *float, damagetype, weapon *int, damageForce, damagePosition *Vec3, damagecustom int) Action { 18 | if IsValidEntity(*weapon) && GetEntProp(*weapon, Prop_Send, "m_iItemDefinitionIndex")==444 { 19 | *damage *= 5.0 20 | return Plugin_Changed 21 | } 22 | return Plugin_Continue 23 | }) 24 | } 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Kevin Yonan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /rewrite/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Nirari Technologies ~ Kevin Yonan. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /sourcemod/template.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/TEMPLATE_RENAME_HERE.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | -------------------------------------------------------------------------------- /sourcemod/types.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/types.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | type ( 17 | any interface{} 18 | Handle uintptr 19 | char byte 20 | Entity = int 21 | ) -------------------------------------------------------------------------------- /sourcemod/helpers.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/helpers.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | func FindPluginByFile(filename string) Handle 18 | func FindTarget(client Entity, target string, nobots, immunity bool) int -------------------------------------------------------------------------------- /sourcemod/nextmap.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/nextmap.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | func SetNextMap(lvl string) bool 18 | func GetNextMap(lvl []char, maxlen int) bool 19 | func ForceChangeLevel(lvl, reason string) 20 | func GetMapHistorySize() int 21 | func GetMapHistory(item int, lvl []char, mapLen int, reason []char, reasonLen int, startTime *int) -------------------------------------------------------------------------------- /sourcemod/handles.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/handles.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | import ( 17 | "sourcemod/types" 18 | ) 19 | 20 | var ( 21 | INVALID_HANDLE Handle 22 | null Handle /// in case people accidentally use 'null' in place of 'nil'. 23 | ) 24 | 25 | func (Handle) Close() 26 | func CloseHandle(h Handle) 27 | func CloneHandle(h, plugin Handle) Handle -------------------------------------------------------------------------------- /test_code/kv_func.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "sourcemod" 5 | ) 6 | 7 | func KeyValuesToStringMap(kv KeyValues, stringmap map[string][]char, hide_top bool, depth int, prefix *[]char) { 8 | type SectStr = [128]char 9 | for { 10 | var section_name SectStr 11 | kv.GetSectionName(section_name, len(section_name)) 12 | if kv.GotoFirstSubKey(false) { 13 | var new_prefix SectStr 14 | switch { 15 | case depth==0 && hide_top: 16 | new_prefix = "" 17 | case prefix[0] == 0: 18 | new_prefix = section_name 19 | default: 20 | FormatEx(new_prefix, len(new_prefix), "%s.%s", prefix, section_name) 21 | } 22 | KeyValuesToStringMap(kv, stringmap, hide_top, depth+1, new_prefix) 23 | kv.GoBack() 24 | } else { 25 | if kv.GetDataType(NULL_STRING) != KvData_None { 26 | var key SectStr 27 | if prefix[0] == 0 { 28 | key = section_name 29 | } else { 30 | FormatEx(key, len(key), "%s.%s", prefix, section_name) 31 | } 32 | 33 | // lowercaseify the key 34 | keylen := strlen(key) 35 | for i := 0; i < keylen; i++ { 36 | bytes := IsCharMB(key[i]) 37 | if bytes==0 { 38 | key[i] = CharToLower(key[i]) 39 | } else { 40 | i += (bytes - 1) 41 | } 42 | } 43 | 44 | var value SectStr 45 | kv.GetString(NULL_STRING, value, len(value), NULL_STRING) 46 | stringmap[key] = value 47 | } 48 | } 49 | 50 | if !kv.GotoNextKey(false) { 51 | break 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /sourcemod/commandline.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/commandline.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | func GetCommandLine(commandLine []char, maxlen int) bool 18 | func GetCommandLineParam(param string, value []char, maxlen int, defValue string) 19 | func GetCommandLineParamInt(param string, defValue int) int 20 | func GetCommandLineParamFloat(param string, defValue float) float 21 | func FindCommandLineParam(param string) bool -------------------------------------------------------------------------------- /rewrite/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "./sourcemod" 5 | ) 6 | 7 | var ( 8 | myself = sm.Plugin{ 9 | Name: []byte("SrcGo Plugin"), 10 | Author: []byte("Nergal"), 11 | Descript: []byte("Plugin made into SP from SrcGo."), 12 | Version: []byte("1.0a"), 13 | Url: []byte("https://github.com/assyrianic/SourceGo"), 14 | } 15 | str_array = [...]string{ 16 | "kek", 17 | "foo", 18 | "bar", 19 | "bazz", 20 | } 21 | ) 22 | 23 | const MAXPLAYERS = 34 24 | 25 | const ( 26 | a, b = "A", MAXPLAYERS 27 | c = a 28 | d = "D" 29 | e = "e1" 30 | f = 1.00 31 | MakeStrMap = "StringMap smap = new StringMap();" 32 | ) 33 | 34 | type ( 35 | Point struct{ x, y float32 } 36 | QAngle = [3]float32 37 | Name = [64]byte 38 | Color = [0x4]int 39 | 40 | PlayerInfo struct { 41 | Origin sm.Vec3 42 | Angle sm.QAngle 43 | Weaps [3]sm.Entity 44 | PutInServer func(client sm.Entity) 45 | } 46 | 47 | ClientInfo struct { 48 | Clients [2][MAXPLAYERS+1]sm.Entity 49 | } 50 | 51 | Kektus func(i, x sm.Vec3, b []byte, blocks *Name, KC *int) sm.Handle 52 | EventFunc func(event *sm.Event, name []byte, dontBroadcast bool) sm.Action 53 | VecFunc func(vec sm.Vec3) (float32, float32, float32) 54 | ) 55 | 56 | func V() (float32, float32, float32) { 57 | return 1.0, 2.0, 3.0 58 | } 59 | 60 | func V3() sm.Vec3 { 61 | return sm.Vec3{1.0, 2.0, 3.0} 62 | } 63 | 64 | func main() { 65 | t, x := func(i int) int { 66 | return 10 + i 67 | }, sm.VerifyCoreVersion() 68 | if x > t(5) { 69 | func() int { 70 | return 5 71 | }() 72 | return 73 | } 74 | } -------------------------------------------------------------------------------- /sourcemod/logging.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/logging.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | func LogMessage(format string, args ...any) 18 | func LogToFile(file, format string, args ...any) 19 | func LogToFileEx(file, format string, args ...any) 20 | func LogAction(client, target int, message string, args ...any) 21 | func LogError(format string, args ...any) 22 | 23 | 24 | type GameLogHook func(message string) Action 25 | 26 | func AddGameLogHook(hook GameLogHook) 27 | func RemoveGameLogHook(hook GameLogHook) -------------------------------------------------------------------------------- /sourcemod/adt_stack.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/adt_stack.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | type ArrayStack struct { 18 | BlockSize int 19 | Empty bool 20 | } 21 | 22 | func CreateStack(blocksize int) ArrayStack 23 | func (ArrayStack) Push(value any) 24 | func (ArrayStack) PushString(value string) 25 | func (ArrayStack) PushArray(values []any, size int) 26 | func (ArrayStack) Pop(block int) any 27 | func (ArrayStack) PopString(buffer []char, maxlength int, written *int) 28 | func (ArrayStack) PopArray(buffer[]any, size int) -------------------------------------------------------------------------------- /sourcemod/lang.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/lang.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | const LANG_SERVER = 0 18 | 19 | func LoadTranslations(file string) 20 | func SetGlobalTransTarget(client Entity) 21 | func GetClientLanguage(client Entity) int 22 | func GetServerLanguage() int 23 | func GetLanguageCount() int 24 | func GetLanguageInfo(language int, code []char, codeLen int, name []char, nameLen int) 25 | func SetClientLanguage(client, language int) 26 | func GetLanguageByCode(code string) int 27 | func GetLanguageByName(code string) int 28 | func TranslationPhraseExists(phrase string) bool 29 | func IsTranslatedForLanguage(phrase string, language int) bool -------------------------------------------------------------------------------- /tf2items_stocks.go: -------------------------------------------------------------------------------- 1 | /** 2 | * tf2items_stocks.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | import "sourcemod" 17 | 18 | 19 | type TF2Item struct { 20 | iFlags, iItemIndex, iQuality, iLevel, iNumAttribs int 21 | } 22 | 23 | func (TF2Item) GiveNamedItem(client Entity) Entity 24 | func (TF2Item) SetClassname(classname string) 25 | func (TF2Item) GetClassname(strDest []char, iDestSize int) 26 | func (TF2Item) SetAttribute(iSlotIndex, iAttribDefIndex int, flValue float) 27 | func (TF2Item) GetAttribID(iSlotIndex int) int 28 | func (TF2Item) GetAttribValue(iSlotIndex int) float 29 | 30 | func TF2Item_PrepareItemHandle(hItem TF2Item, name []char, index int, att string, dontpreserve bool) TF2Item -------------------------------------------------------------------------------- /sourcemod/banning.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/banning.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | const ( 18 | BANFLAG_AUTO = (1<<0) /**< Auto-detects whether to ban by steamid or IP */ 19 | BANFLAG_IP = (1<<1) /**< Always ban by IP address */ 20 | BANFLAG_AUTHID = (1<<2) /**< Always ban by authstring (for BanIdentity) if possible */ 21 | BANFLAG_NOKICK = (1<<3) /**< Does not kick the client */ 22 | ) 23 | 24 | 25 | func BanClient(client, time, flags int, reason, kick_message, command string, source any) bool 26 | func BanIdentity(identity string, time, flags int, reason, command string, source any) bool 27 | func RemoveBan(identity string, flags int, command string, source any) bool -------------------------------------------------------------------------------- /datapack.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datapack.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | import "sourcemod" 17 | 18 | type ( 19 | DataPackPos = int 20 | DataPack struct { 21 | Position DataPackPos 22 | } 23 | ) 24 | 25 | 26 | func CreateDataPack() DataPack 27 | 28 | func (DataPack) WriteCell(cell any, insert bool) 29 | func (DataPack) WriteFloat(val float, insert bool) 30 | func (DataPack) WriteString(val string, insert bool) 31 | func (DataPack) WriteFunction(fktptr Function, insert bool) 32 | func (DataPack) ReadCell() any 33 | func (DataPack) ReadFloat() float 34 | func (DataPack) ReadString(buffer []char, maxlen int) 35 | func (DataPack) ReadFunction() Function 36 | func (DataPack) Reset(clear bool) 37 | func (DataPack) IsReadable(unused int) bool -------------------------------------------------------------------------------- /rewrite/srcgo/pass8_rename_receivers.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Nirari Technologies. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 5 | * 6 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 9 | * 10 | */ 11 | 12 | package SrcGo 13 | 14 | 15 | import ( 16 | ///"fmt" 17 | ///"go/types" 18 | "go/ast" 19 | ///"go/token" 20 | ) 21 | 22 | func ChangeReceiverNames(file *ast.File) { 23 | ast.Inspect(file, func(n ast.Node) bool { 24 | if n != nil { 25 | switch f := n.(type) { 26 | case *ast.FuncDecl: 27 | if f.Recv != nil && f.Recv.List[0].Names != nil && len(f.Recv.List[0].Names) > 0 { 28 | recvr := f.Recv.List[0].Names[0].Name 29 | ast.Inspect(f.Body, func(n ast.Node) bool { 30 | if n != nil { 31 | switch i := n.(type) { 32 | case *ast.Ident: 33 | if recvr==i.Name { 34 | i.Name = "this" 35 | } 36 | } 37 | } 38 | return true 39 | }) 40 | } 41 | } 42 | } 43 | return true 44 | }) 45 | } -------------------------------------------------------------------------------- /sourcemod/vector.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/vector.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | import ( 17 | "sourcemod/types" 18 | ) 19 | 20 | type Vec3 = [3]float 21 | 22 | func GetVectorLength(vec Vec3, squared bool) float 23 | func GetVectorDistance(vec1, vec2 Vec3, squared bool) float 24 | func GetVectorDotProduct(vec1, vec2 Vec3) float 25 | func GetVectorCrossProduct(vec1, vec2 Vec3, result *Vec3) 26 | func NormalizeVector(vec Vec3, result *Vec3) float 27 | func GetAngleVectors(angle Vec3, fwd, right, up *Vec3) 28 | func GetVectorAngles(vec Vec3, angle *Vec3) 29 | func GetVectorVectors(vec Vec3, right, up *Vec3) 30 | func AddVectors(vec1, vec2 Vec3, result *Vec3) 31 | func SubtractVectors(vec1, vec2 Vec3, result *Vec3) 32 | func ScaleVector(vec *Vec3, scale float) 33 | func NegateVector(vec *Vec3) 34 | func MakeVectorFromPoints(pt1, pt2 Vec3, output *Vec3) -------------------------------------------------------------------------------- /sourcemod/adt_trie.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/adt_trie.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | type ( 18 | StringMap struct { 19 | Size int 20 | } 21 | 22 | StringMapSnapshot struct { 23 | Length int 24 | } 25 | ) 26 | 27 | func CreateTrie() StringMap 28 | func (StringMap) SetValue(key string, value any) bool 29 | func (StringMap) SetArray(key string, array []any, num_items int) bool 30 | func (StringMap) SetString(key, value string) bool 31 | func (StringMap) GetValue(key string, value *any) bool 32 | func (StringMap) GetArray(key string, array []any, max_size int, size *int) bool 33 | func (StringMap) GetString(key string, value []char, max_size int, size *int) bool 34 | func (StringMap) Remove(key string) 35 | func (StringMap) Clear() 36 | func (StringMap) Snapshot() StringMapSnapshot 37 | 38 | func (StringMapSnapshot) KeyBufferSize(index int) int 39 | func (StringMapSnapshot) GetKey(index int, buffer []char, maxlength int) int -------------------------------------------------------------------------------- /rewrite/srcgo/pass4_mutate_andnot_exprs.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Nirari Technologies. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 5 | * 6 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 9 | * 10 | */ 11 | 12 | package SrcGo 13 | 14 | 15 | import ( 16 | ///"fmt" 17 | "go/token" 18 | "go/ast" 19 | ) 20 | 21 | 22 | /* 23 | * Pass #4 - Mutate AND-NOT expressions. 24 | * So we basically turn `a &^ b` into `a & ^(b)` 25 | * which then becomes `a & ~(b)` in SourcePawn. 26 | * 27 | * Ditto for the `a &^= b` as well 28 | * `a &= ^(b)` becoming `a &= ~(b)` 29 | */ 30 | func MutateAndNotExpr(file *ast.File) { 31 | ast.Inspect(file, func(n ast.Node) bool { 32 | if n != nil { 33 | switch x := n.(type) { 34 | case *ast.BinaryExpr: 35 | if x.Op==token.AND_NOT { 36 | x.Op = token.AND 37 | x.Y = MakeBitNotExpr(MakeParenExpr(x.Y)) 38 | } 39 | case *ast.AssignStmt: 40 | if x.Tok==token.AND_NOT_ASSIGN { 41 | x.Tok = token.AND_ASSIGN 42 | for i := range x.Rhs { 43 | x.Rhs[i] = MakeBitNotExpr(MakeParenExpr(x.Rhs[i])) 44 | } 45 | } 46 | } 47 | } 48 | return true 49 | }) 50 | } -------------------------------------------------------------------------------- /sourcemod/timers.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/timers.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | const ( 18 | TIMER_REPEAT = (1<<0) /**< Timer will repeat until it returns Plugin_Stop */ 19 | TIMER_FLAG_NO_MAPCHANGE = (1<<1) /**< Timer will not carry over mapchanges */ 20 | TIMER_HNDL_CLOSE = (1<<9) /**< Deprecated define, replaced by below */ 21 | TIMER_DATA_HNDL_CLOSE = (1<<9) /**< Timer will automatically call CloseHandle() on its data when finished */ 22 | ) 23 | 24 | 25 | type ( 26 | Timer = Handle 27 | TimerFunc func(timer Timer, data any) Action 28 | ) 29 | 30 | func CreateTimer(interval float, tfn TimerFunc, data any, flags int) Timer 31 | func CreateDataTimer(interval float, tfn TimerFunc, datapack *any, flags int) Timer 32 | 33 | func KillTimer(timer Timer, autoClose bool) 34 | func TriggerTimer(timer Timer, reset bool) 35 | func GetTickedTime() float 36 | func GetMapTimeLeft(timeleft *int) bool 37 | func GetMapTimeLimit(time *int) bool 38 | func ExtendMapTimeLimit(time int) bool 39 | func GetTickInterval() float 40 | func IsServerProcessing() bool -------------------------------------------------------------------------------- /sourcemod/sorting.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/sorting.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | type SortOrder int 18 | const ( 19 | Sort_Ascending = SortOrder(0) /**< Ascending order */ 20 | Sort_Descending /**< Descending order */ 21 | Sort_Random /**< Random order */ 22 | ) 23 | 24 | 25 | type SortType int 26 | const ( 27 | Sort_Integer = SortType(0) 28 | Sort_Float 29 | Sort_String 30 | ) 31 | 32 | 33 | func SortIntegers(array []int, array_size int, order SortOrder) 34 | func SortFloats(array []float, array_size int, order SortOrder) 35 | func SortStrings(array [][]char, array_size int, order SortOrder) 36 | 37 | 38 | type SortFunc1D func(elem1, elem2 int, array []int, hndl Handle) int 39 | func SortCustom1D(array []int, array_size int, sorter SortFunc1D, hndl Handle) 40 | 41 | type SortFunc2D func(elem1, elem2 []any, array [][]any, hndl Handle) 42 | func SortCustom2D(array [][]any, array_size int, sorter SortFunc2D, hndl Handle) 43 | func SortADTArray(array Handle, order SortOrder, sorting SortType) 44 | 45 | type SortFuncADTArray func(index1, index2 int, array, hndl Handle) 46 | func SortADTArrayCustom(array Handle, sorter SortFuncADTArray, hndl Handle) -------------------------------------------------------------------------------- /sourcemod/floats.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/floats.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | import ( 17 | "sourcemod/types" 18 | ) 19 | 20 | type float = float64 21 | 22 | 23 | const FLOAT_PI = 3.1415926535897932384626433832795 24 | 25 | 26 | func FloatFraction(value float) float 27 | func RoundToZero(value float) int 28 | func RoundToCeil(value float) int 29 | func RoundToFloor(value float) int 30 | func RoundToNearest(value float) int 31 | func FloatCompare(fOne, fTwo float) int 32 | 33 | func SquareRoot(val float) float 34 | func Pow(val, exp float) float 35 | func Exponential(val float) float 36 | func Logarithm(val float, base float) float 37 | func Sine(val float) float 38 | func Cosine(val float) float 39 | func Tangent(val float) float 40 | func FloatAbs(val float) float 41 | func ArcTangent(val float) float 42 | func ArcCosine(val float) float 43 | func ArcSine(val float) float 44 | func ArcTangent2(x,y float) float 45 | 46 | func RoundFloat(val float) int 47 | 48 | func DegToRad(angle float) float 49 | func RadToDeg(angle float) float 50 | 51 | func GetURandomInt() int 52 | func GetURandomFloat() float 53 | func SetURandomSeed(seeds []int, numSeeds int) 54 | 55 | func SetURandomSeedSimple(seed int) -------------------------------------------------------------------------------- /sourcemod/adt_array.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/adt_array.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | func ByteCountToCells(size int) int 18 | 19 | /// new ArrayList(int blocksize=1, int startsize=0); 20 | type ArrayList struct { 21 | Length, BlockSize int 22 | } 23 | 24 | func CreateArray(blocksize, startsize int) ArrayList 25 | func (ArrayList) Clear() 26 | func (ArrayList) Clone() ArrayList 27 | func (ArrayList) Resize(newsize int) 28 | func (ArrayList) Push(value any) int 29 | func (ArrayList) PushString(value string) int 30 | func (ArrayList) PushArray(values []any, size int) int 31 | func (ArrayList) Get(index, block int, asChar bool) any 32 | func (ArrayList) GetString(index int, buffer []any, maxlength int) int 33 | func (ArrayList) GetArray(index int, buffer *[]any, size int) int 34 | func (ArrayList) Set(index int, value any, block int, asChar bool) 35 | func (ArrayList) SetString(index int, value string) 36 | func (ArrayList) SetArray(index int, values []any, size int) 37 | func (ArrayList) ShiftUp(index int) 38 | func (ArrayList) Erase(index int) 39 | func (ArrayList) SwapAt(index1, index2 int) 40 | func (ArrayList) FindString(item string) int 41 | func (ArrayList) FindValue(item any, block int) 42 | func (ArrayList) Sort(order SortOrder, sort SortType) 43 | func (ArrayList) SortCustom(sorter SortFuncADTArray, hndl Handle) 44 | -------------------------------------------------------------------------------- /rewrite/sourcemod/events.go: -------------------------------------------------------------------------------- 1 | /* 2 | * sourcemod/events.go 3 | * 4 | * Copyright 2022 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package sm 15 | 16 | 17 | type EventHookMode int 18 | const ( 19 | EventHookMode_Pre = EventHookMode(0) /* Hook callback fired before event is fired */ 20 | EventHookMode_Post = EventHookMode(1) /* Hook callback fired after event is fired */ 21 | EventHookMode_PostNoCopy = EventHookMode(2) /* Hook callback fired after event is fired, but event data won't be copied */ 22 | ) 23 | 24 | 25 | type ( 26 | EventHook func(event Event, name []byte, dontBroadcast bool) Action 27 | Event struct { 28 | BroadcastDisabled bool 29 | } 30 | ) 31 | 32 | func (*Event) Fire(dontBroadcast bool) 33 | func (*Event) FireToClient(client Entity) 34 | func (*Event) Cancel() 35 | func (*Event) GetBool(key []byte, defValue bool) bool 36 | func (*Event) SetBool(key []byte, value bool) 37 | func (*Event) GetInt(key []byte, defValue int) int 38 | func (*Event) SetInt(key []byte, value int) 39 | func (*Event) GetFloat(key []byte, defValue float32) float32 40 | func (*Event) SetFloat(key []byte, value float32) 41 | func (*Event) GetString(key []byte, value []byte, maxlength int, defvalue []byte) 42 | func (*Event) SetString(key, value []byte) 43 | func (*Event) GetName(name []byte, maxlength int) 44 | 45 | func HookEvent(name []byte, callback EventHook, mode EventHookMode) 46 | func HookEventEx(name []byte, callback EventHook, mode EventHookMode) bool 47 | func UnhookEvent(name []byte, callback EventHook, mode EventHookMode) 48 | func CreateEvent(name []byte, force bool) Event 49 | -------------------------------------------------------------------------------- /sourcemod/usermessages.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/usermessages.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | type UserMsg int 18 | const INVALID_MESSAGE_ID = UserMsg(-1) 19 | 20 | type UserMessageType int 21 | const ( 22 | UM_BitBuf = UserMessageType(0) 23 | UM_Protobuf 24 | ) 25 | 26 | const ( 27 | USERMSG_RELIABLE = (1<<2) /**< Message will be set on the reliable stream */ 28 | USERMSG_INITMSG = (1<<3) /**< Message will be considered to be an initmsg */ 29 | USERMSG_BLOCKHOOKS = (1<<7) /**< Prevents the message from triggering SourceMod and Metamod hooks */ 30 | ) 31 | 32 | 33 | func GetUserMessageType() UserMessageType 34 | func UserMessageToProtobuf(msg Handle) Protobuf 35 | func UserMessageToBfWrite(msg Handle) BfWrite 36 | func UserMessageToBfRead(msg Handle) BfRead 37 | 38 | func GetUserMessageId(msg string) UserMsg 39 | func GetUserMessageName(msg_id UserMsg, msg []char, maxlength int) bool 40 | func StartMessage(msgname string, clients []int, numClients, flags int) Handle 41 | func StartMessageEx(msg UserMsg, clients []int, numClients, flags int) Handle 42 | func EndMessage() 43 | 44 | 45 | type ( 46 | MsgHook func(msg_id UserMsg, msg Handle, players []int, playersNum int, reliable, init bool) Action 47 | MsgPostHook func(msg_id UserMsg, sent bool) 48 | ) 49 | 50 | func HookUserMessage(msg_id UserMsg, hook MsgHook, intercept bool, post MsgPostHook) 51 | func UnhookUserMessage(msg_id UserMsg, hook MsgHook, intercept bool) 52 | func StartMessageAll(msgname string, flags int) Handle 53 | func StartMessageOne(msgname string, client, flags int) Handle -------------------------------------------------------------------------------- /clientprefs.go: -------------------------------------------------------------------------------- 1 | /** 2 | * clientprefs.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | import "sourcemod" 17 | 18 | type ( 19 | CookieAccess int 20 | CookieMenu int 21 | CookieMenuAction int 22 | 23 | CookieMenuHandler func(client int, action CookieMenuAction, info any, buffer []char, maxlen int) 24 | 25 | Cookie struct { 26 | AccessLevel CookieAccess 27 | } 28 | ) 29 | 30 | const ( 31 | CookieAccess_Public /**< Visible and Changeable by users */ 32 | CookieAccess_Protected /**< Read only to users */ 33 | CookieAccess_Private /**< Completely hidden cookie */ 34 | 35 | CookieMenu_YesNo /**< Yes/No menu with "yes"/"no" results saved into the cookie */ 36 | CookieMenu_YesNo_Int /**< Yes/No menu with 1/0 saved into the cookie */ 37 | CookieMenu_OnOff /**< On/Off menu with "on"/"off" results saved into the cookie */ 38 | CookieMenu_OnOff_Int /**< On/Off menu with 1/0 saved into the cookie */ 39 | 40 | CookieMenuAction_DisplayOption = 0 41 | CookieMenuAction_SelectOption = 1 42 | ) 43 | 44 | 45 | func RegClientCookie(name, description string, access CookieAccess) Cookie 46 | func FindClientCookie(name string) Cookie 47 | 48 | func (Cookie) Set(client int, value string) 49 | func (Cookie) Get(client int, buffer []char, maxlen int) 50 | func (Cookie) SetByAuthId(authID, value string) 51 | func (Cookie) SetPrefabMenu(menutype CookieMenu, display string, handler CookieMenuHandler, info any) 52 | func (Cookie) GetClientTime(client int) int 53 | 54 | func AreClientCookiesCached(client int) bool 55 | func ShowCookieMenu(client int) -------------------------------------------------------------------------------- /sourcemod/commandfilters.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/commandfilters.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | const ( 18 | MAX_TARGET_LENGTH = 64 19 | 20 | COMMAND_FILTER_ALIVE = (1<<0) /**< Only allow alive players */ 21 | COMMAND_FILTER_DEAD = (1<<1) /**< Only filter dead players */ 22 | COMMAND_FILTER_CONNECTED = (1<<2) /**< Allow players not fully in-game */ 23 | COMMAND_FILTER_NO_IMMUNITY = (1<<3) /**< Ignore immunity rules */ 24 | COMMAND_FILTER_NO_MULTI = (1<<4) /**< Do not allow multiple target patterns */ 25 | COMMAND_FILTER_NO_BOTS = (1<<5) /**< Do not allow bots to be targetted */ 26 | 27 | COMMAND_TARGET_NONE = 0 /**< No target was found */ 28 | COMMAND_TARGET_NOT_ALIVE = -1 /**< Single client is not alive */ 29 | COMMAND_TARGET_NOT_DEAD = -2 /**< Single client is not dead */ 30 | COMMAND_TARGET_NOT_IN_GAME = -3 /**< Single client is not in game */ 31 | COMMAND_TARGET_IMMUNE = -4 /**< Single client is immune */ 32 | COMMAND_TARGET_EMPTY_FILTER = -5 /**< A multi-filter (such as @all) had no targets */ 33 | COMMAND_TARGET_NOT_HUMAN = -6 /**< Target was not human */ 34 | COMMAND_TARGET_AMBIGUOUS = -7 /**< Partial name had too many targets */ 35 | ) 36 | 37 | 38 | func ProcessTargetString(pattern string, admin int, targets []int, max_targets, filter_flags int, target_name []char, tn_maxlength int, tn_is_ml *bool) int 39 | func ReplyToTargetError(client, reason int) 40 | 41 | 42 | type MultiTargetFilter func(pattern string, clients ArrayList) bool 43 | 44 | func AddMultiTargetFilter(pattern string, filter MultiTargetFilter, phrase string, phraseIsML bool) 45 | func RemoveMultiTargetFilter(pattern string, filter MultiTargetFilter) -------------------------------------------------------------------------------- /tf2items.go: -------------------------------------------------------------------------------- 1 | /** 2 | * tf2items.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * All Credit to Asher 'Asherkin' Baker. 6 | * 7 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 8 | * 9 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 10 | * 11 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 12 | * 13 | */ 14 | 15 | package main 16 | 17 | import "sourcemod" 18 | 19 | const ( 20 | OVERRIDE_CLASSNAME = (1 << 0) // Item will override the entity's classname. 21 | OVERRIDE_ITEM_DEF = (1 << 1) // Item will override the item's definition index. 22 | OVERRIDE_ITEM_LEVEL = (1 << 2) // Item will override the entity's level. 23 | OVERRIDE_ITEM_QUALITY = (1 << 3) // Item will override the entity's quality. 24 | OVERRIDE_ATTRIBUTES = (1 << 4) // Item will override the attributes for the item with the given ones. 25 | OVERRIDE_ALL = (0b11111) // Magically enables all the other flags. 26 | 27 | PRESERVE_ATTRIBUTES = (1 << 5) 28 | FORCE_GENERATION = (1 << 6) 29 | ) 30 | 31 | 32 | func TF2Items_GiveNamedItem(Client Entity, hItem Handle) Entity 33 | func TF2Items_CreateItem(iFlags int) Handle 34 | func TF2Items_SetFlags(hItem Handle, iFlags int) 35 | func TF2Items_SetClassname(hItemOverride Handle, strClassName string) 36 | func TF2Items_SetItemIndex(hItem Handle, iItemDefIndex int) 37 | func TF2Items_SetQuality(hItem Handle, iEntityQuality int) 38 | func TF2Items_SetLevel(hItem Handle, iEntityLevel int) 39 | func TF2Items_SetNumAttributes(hItem Handle, iNumAttributes int) 40 | func TF2Items_SetAttribute(hItem Handle, iSlotIndex, iAttribDefIndex int, flValue float) 41 | func TF2Items_GetFlags(hItem Handle) int 42 | func TF2Items_GetClassname(hItem Handle, strDest []char, iDestSize int) 43 | func TF2Items_GetItemIndex(hItem Handle) int 44 | func TF2Items_GetQuality(hItem Handle) int 45 | func TF2Items_GetLevel(hItem Handle) int 46 | func TF2Items_GetNumAttributes(hItem Handle) int 47 | func TF2Items_GetAttributeId(hItem Handle, iSlotIndex int) int 48 | func TF2Items_GetAttributeValue(hItem Handle, iSlotIndex int) float -------------------------------------------------------------------------------- /cfgmap.go: -------------------------------------------------------------------------------- 1 | /** 2 | * cfgmap.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | import ( 17 | "sourcemod" 18 | "datapack" 19 | ) 20 | 21 | type KeyValType int 22 | const ( 23 | KeyValType_Null = 0 /// nil 24 | KeyValType_Section /// StringMap : char[*][*] 25 | KeyValType_Value /// char[*] 26 | ) 27 | 28 | const SEC_SCOPE_SIZE = 512 29 | 30 | type PackVal struct { 31 | data DataPack 32 | size int 33 | tag KeyValType 34 | } 35 | 36 | 37 | type ConfigMap StringMap 38 | 39 | /// __sp__(`cfg = new ConfigMap(filename);`) 40 | 41 | func (ConfigMap) GetVal(key string, valbuf *PackVal) bool 42 | func (ConfigMap) SetVal(key, val_str string, val_size int) bool 43 | func (ConfigMap) GetSize(key_path string) int 44 | func (ConfigMap) Get(key_path string, buffer []char, buf_size int) int 45 | func (ConfigMap) Set(key_path, str string) bool 46 | func (ConfigMap) GetSection(key_path string) ConfigMap 47 | func (ConfigMap) GetKeyValType(key_path string) KeyValType 48 | func (ConfigMap) GetInt(key_path string, i *int, base int) int 49 | func (ConfigMap) SetInt(key_path string, i int) bool 50 | func (ConfigMap) GetFloat(key_path string, f *float) int 51 | func (ConfigMap) SetFloat(key_path string, f float) bool 52 | func (ConfigMap) GetBool(key_path string, b *bool, simple bool) int 53 | 54 | func (ConfigMap) ExportToFile(sec_name, path string) bool 55 | func (ConfigMap) Clone(owner_pl Handle) ConfigMap 56 | func (ConfigMap) DeleteSection(key_path string) bool 57 | 58 | func (ConfigMap) GetIntKeySize(key int) int 59 | func (ConfigMap) GetIntKey(key int, buffer []char, buf_size int) int 60 | func (ConfigMap) GetIntSection(key int) ConfigMap 61 | 62 | func ParseTargetPath(key string, buffer []char, buffer_len int) bool 63 | func DeleteCfg(cfg *ConfigMap, clear_only bool) 64 | func PrintCfg(cfg ConfigMap) 65 | func ConfigMapToFile(cfg ConfigMap, sec_name string, file File, deep int) bool 66 | func CloneConfigMap(cfg, new_cfg ConfigMap, new_owner_pl Handle) bool -------------------------------------------------------------------------------- /sourcemod/events.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/events.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | type EventHookMode int 18 | const ( 19 | EventHookMode_Pre = EventHookMode(0) //< Hook callback fired before event is fired */ 20 | EventHookMode_Post //< Hook callback fired after event is fired */ 21 | EventHookMode_PostNoCopy //< Hook callback fired after event is fired, but event data won't be copied */ 22 | ) 23 | 24 | 25 | type ( 26 | EventHook func(event Event, name string, dontBroadcast bool) Action 27 | Event struct { 28 | BroadcastDisabled bool 29 | } 30 | ) 31 | 32 | func (Event) Fire(dontBroadcast bool) 33 | func (Event) FireToClient(client Entity) 34 | func (Event) Cancel() 35 | func (Event) GetBool(key string, defValue bool) bool 36 | func (Event) SetBool(key string, value bool) 37 | func (Event) GetInt(key string, defValue int) int 38 | func (Event) SetInt(key string, value int) 39 | func (Event) GetFloat(key string, defValue float) float 40 | func (Event) SetFloat(key string, value float) 41 | func (Event) GetString(key string, value []char, maxlength int, defvalue string) 42 | func (Event) SetString(key, value string) 43 | func (Event) GetName(name []char, maxlength int) 44 | 45 | func HookEvent(name string, callback EventHook, mode EventHookMode) 46 | func HookEventEx(name string, callback EventHook, mode EventHookMode) bool 47 | func UnhookEvent(name string, callback EventHook, mode EventHookMode) 48 | func CreateEvent(name string, force bool) Event 49 | func FireEvent(event Event, dontBroadcast bool) 50 | func CancelCreatedEvent(event Event) 51 | func GetEventBool(event Event, key string, defValue bool) bool 52 | func SetEventBool(event Event, key string, value bool) 53 | func GetEventInt(event Event, key string, defValue int) int 54 | func SetEventInt(event Event, key string, value int) 55 | func GetEventFloat(event Event, key string, defValue float) float 56 | func SetEventFloat(event Event, key string, value float) 57 | func GetEventString(event Event, key string, value []char, maxlength int, defvalue string) 58 | func SetEventString(event Event, key, value string) 59 | func GetEventName(event Event, name []char, maxlength int) 60 | func SetEventBroadcast(event Event, dontBroadcast bool) -------------------------------------------------------------------------------- /rewrite/srcgo/pass3_merge_rettypes.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Nirari Technologies. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 5 | * 6 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 9 | * 10 | */ 11 | 12 | package SrcGo 13 | 14 | 15 | import ( 16 | "fmt" 17 | "go/ast" 18 | ) 19 | 20 | 21 | /* 22 | * Pass #3 - Merge Return Types. 23 | */ 24 | func MergeRetTypes(file *ast.File) { 25 | ast.Inspect(file, func(n ast.Node) bool { 26 | if n != nil { 27 | switch f := n.(type) { 28 | case *ast.FuncDecl: 29 | f.Type.Params.List = MutateRetTypes(&f.Type.Results, f.Type.Params, f.Name.Name) 30 | case *ast.TypeSpec: 31 | if t, is_func_type := f.Type.(*ast.FuncType); is_func_type { 32 | t.Params.List = MutateRetTypes(&t.Results, t.Params, f.Name.Name) 33 | } 34 | } 35 | } 36 | return true 37 | }) 38 | } 39 | 40 | /* 41 | * Modifies the return values of a function by mutating them into references and moving them to the parameters. 42 | * Example Go code: func f() (int, float) {} 43 | * Result Go code: func f(f_param1 *float) int {} 44 | */ 45 | func MutateRetTypes(retvals **ast.FieldList, curr_params *ast.FieldList, obj_name string) []*ast.Field { 46 | if *retvals==nil || (*retvals).List==nil { 47 | return curr_params.List 48 | } 49 | 50 | new_params := make([]*ast.Field, 0) 51 | for _, param := range curr_params.List { 52 | new_params = append(new_params, param) 53 | } 54 | 55 | results := len((*retvals).List) 56 | 57 | // multiple different return values. 58 | if results > 1 { 59 | for i := 1; i 1 { 63 | ret.Type = PtrizeExpr(ret.Type) 64 | new_params = append(new_params, ret) 65 | } else { 66 | ///param_num := len(new_params) 67 | ret.Names = append(ret.Names, ast.NewIdent(fmt.Sprintf("%s_param%d", obj_name, i))) 68 | ret.Type = PtrizeExpr(ret.Type) 69 | new_params = append(new_params, ret) 70 | } 71 | } 72 | (*retvals).List = (*retvals).List[:1] 73 | } else if results==1 && (*retvals).List[0].Names != nil && len((*retvals).List[0].Names) > 1 { 74 | // This condition can happen if there's multiple return values of the same type but they're named! 75 | (*retvals).List[0].Type = PtrizeExpr((*retvals).List[0].Type) 76 | new_params = append(new_params, (*retvals).List[0]) 77 | *retvals = nil 78 | } 79 | return new_params 80 | } -------------------------------------------------------------------------------- /sourcemod/strings.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/strings.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | import ( 17 | "sourcemod/types" 18 | ) 19 | 20 | func strlen(str string) int 21 | func StrContains(str, substr string, caseSensitive bool) int 22 | func strcmp(str1, str2 string, caseSensitive bool) int 23 | func strncmp(str1, str2 string, chars int, caseSensitive bool) int 24 | func StrCompare(str1, str2 string, caseSensitive bool) int 25 | func StrEqual(str1, str2 string, caseSensitive bool) bool 26 | func strcopy(dest []char, destLen int, source string) int 27 | func StrCopy(dest []char, destLen int, source string) int 28 | func Format(buffer []char, maxlength int, format string, args ...any) int 29 | func FormatEx(buffer []char, maxlength int, format string, args ...any) int 30 | func VFormat(buffer []char, maxlength int, format string, varpos int) int 31 | func StringToInt(str string, nBase int) int 32 | func StringToIntEx(str string, result *int, nBase int) int 33 | func IntToString(num int, str string, maxlength int) int 34 | func StringToFloat(str string) float 35 | func StringToFloatEx(str string, result *float) int 36 | func FloatToString(num float, str []char, maxlength int) int 37 | func BreakString(source []char, arg string, argLen int) int 38 | func StrBreak(source []char, arg string, argLen int) int 39 | func TrimString(str []char) int 40 | func SplitString(source []char, split, part string, partLen int) int 41 | func ReplaceString(text []char, maxlength int, search, replace string, caseSensitive bool) int 42 | func ReplaceStringEx(text []char, maxlength int, search, replace string, searchLen, replaceLen int, caseSensitive bool) int 43 | 44 | func GetCharBytes(source string) int 45 | func IsCharAlpha(chr int) bool 46 | func IsCharNumeric(chr int) bool 47 | func IsCharSpace(chr int) bool 48 | func IsCharMB(chr int) int 49 | func IsCharUpper(chr int) bool 50 | func IsCharLower(chr int) bool 51 | func StripQuotes(text string) bool 52 | func CharToUpper(chr int) char 53 | func CharToLower(chr int) char 54 | func FindCharInString(str string, c char, reverse bool) int 55 | func StrCat(buffer string, maxlength int, source string) int 56 | func ExplodeString(text []char, split string, buffers []string, maxStrings, maxStringLength int, copyRemainder bool) int 57 | func ImplodeStrings(strings []string, numStrings int, join string, buffer []char, maxLength int) int -------------------------------------------------------------------------------- /sourcemod/core.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/core.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | import ( 17 | "sourcemod/types" 18 | ) 19 | 20 | 21 | type Plugin struct { 22 | name, description, author, version, url string 23 | } 24 | 25 | type Extension struct { 26 | name, file string 27 | autoload, required int 28 | } 29 | 30 | const ( 31 | SOURCEMOD_PLUGINAPI_VERSION = 5 32 | 33 | SOURCEMOD_V_TAG string = "manual" 34 | SOURCEMOD_V_REV = 0 35 | SOURCEMOD_V_CSET string = "0" 36 | SOURCEMOD_V_MAJOR = 1 /**< SourceMod Major version */ 37 | SOURCEMOD_V_MINOR = 10 /**< SourceMod Minor version */ 38 | SOURCEMOD_V_RELEASE = 0 /**< SourceMod Release version */ 39 | 40 | SOURCEMOD_VERSION string = "1.10.0-manual" /**< SourceMod version string (major.minor.release-tag) */ 41 | ) 42 | 43 | 44 | type Action int 45 | const ( 46 | Plugin_Continue = Action(iota) 47 | Plugin_Changed 48 | Plugin_Handled 49 | Plugin_Stop 50 | ) 51 | 52 | type Identity int 53 | const ( 54 | Identity_Core = Identity(iota) 55 | Identity_Extension 56 | Identity_Plugin 57 | ) 58 | 59 | 60 | type PluginStatus int 61 | const ( 62 | Plugin_Running = PluginStatus(iota) /**< Plugin is running */ 63 | /** All states below are "temporarily" unexecutable */ 64 | Plugin_Paused /**< Plugin is loaded but paused */ 65 | Plugin_Error /**< Plugin is loaded but errored/locked */ 66 | /** All states below do not have all natives */ 67 | Plugin_Loaded /**< Plugin has passed loading and can be finalized */ 68 | Plugin_Failed /**< Plugin has a fatal failure */ 69 | Plugin_Created /**< Plugin is created but not initialized */ 70 | Plugin_Uncompiled /**< Plugin is not yet compiled by the JIT */ 71 | Plugin_BadLoad /**< Plugin failed to load */ 72 | Plugin_Evicted /**< Plugin was unloaded due to an error */ 73 | ) 74 | 75 | 76 | type PluginInfo int 77 | const ( 78 | PlInfo_Name = PluginInfo(iota) /**< Plugin name */ 79 | PlInfo_Author /**< Plugin author */ 80 | PlInfo_Description /**< Plugin description */ 81 | PlInfo_Version /**< Plugin version */ 82 | PlInfo_URL 83 | ) 84 | 85 | const NULL_STRING string = "" 86 | var ( 87 | NULL_VECTOR Vec3 /// can't put NULL_VECTOR as 'const'. 88 | INVALID_FUNCTION __function__ 89 | ) 90 | 91 | 92 | func IsNullVector(vec Vec3) bool 93 | func IsNullString(str string) bool 94 | func VerifyCoreVersion() int 95 | func MarkNativeAsOptional(name string) -------------------------------------------------------------------------------- /sourcemod/bitbuffer.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/bitbuffer.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | type ( 18 | BfWrite Handle 19 | BfRead struct { 20 | BytesLeft int 21 | } 22 | ) 23 | func (BfWrite) WriteBool(bit bool) 24 | func (BfWrite) WriteByte(byt int) 25 | func (BfWrite) WriteChar(chr int) 26 | func (BfWrite) WriteShort(shrt int) 27 | func (BfWrite) WriteWord(w int) 28 | func (BfWrite) WriteNum(num int) 29 | func (BfWrite) WriteFloat(num float) 30 | func (BfWrite) WriteString(s string) 31 | func (BfWrite) WriteEntity(ent Entity) 32 | func (BfWrite) WriteAngle(angle float, numBits int) 33 | func (BfWrite) WriteCoord(coord float) 34 | func (BfWrite) WriteVecCoord(vec Vec3) 35 | func (BfWrite) WriteVecNormal(vec Vec3) 36 | func (BfWrite) WriteAngles(vec Vec3) 37 | 38 | func (BfRead) ReadBool() bool 39 | func (BfRead) ReadByte() int 40 | func (BfRead) ReadChar() int 41 | func (BfRead) ReadShort() int 42 | func (BfRead) ReadWord() int 43 | func (BfRead) ReadNum() int 44 | func (BfRead) ReadFloat() float 45 | func (BfRead) ReadString(buffer []char, maxlength int, line bool) int 46 | func (BfRead) ReadEntity() Entity 47 | func (BfRead) ReadAngle(numBits int) float 48 | func (BfRead) ReadCoord() float 49 | func (BfRead) ReadVecCoord(vec *Vec3) 50 | func (BfRead) ReadVecNormal(vec *Vec3) 51 | func (BfRead) ReadAngles(vec *Vec3) 52 | 53 | 54 | func BfWriteBool(bf BfWrite, bit bool) 55 | func BfWriteByte(bf BfWrite, byt int) 56 | func BfWriteChar(bf BfWrite, chr int) 57 | func BfWriteShort(bf BfWrite, num int) 58 | func BfWriteWord(bf BfWrite, num int) 59 | func BfWriteNum(bf BfWrite, num int) 60 | func BfWriteFloat(bf BfWrite, num float) 61 | func BfWriteString(bf BfWrite, str string) 62 | func BfWriteEntity(bf BfWrite, ent Entity) 63 | func BfWriteAngle(bf BfWrite, angle float, numBits int) 64 | func BfWriteCoord(bf BfWrite, coord float) 65 | func BfWriteVecCoord(bf BfWrite, vec Vec3) 66 | func BfWriteVecNormal(bf BfWrite, vec Vec3) 67 | func BfWriteAngles(bf BfWrite, vec Vec3) 68 | 69 | func BfReadBool(bf BfRead) bool 70 | func BfReadByte(bf BfRead) int 71 | func BfReadChar(bf BfRead) int 72 | func BfReadShort(bf BfRead) int 73 | func BfReadWord(bf BfRead) int 74 | func BfReadNum(bf BfRead) int 75 | func BfReadFloat(bf BfRead) float 76 | func BfReadString(bf BfRead, buffer []char, maxlength int, line bool) int 77 | func BfReadEntity(bf BfRead) int 78 | func BfReadAngle(bf BfRead, numBits int) float 79 | func BfReadCoord(bf BfRead) float 80 | func BfReadVecCoord(bf BfRead, vec *Vec3) 81 | func BfReadVecNormal(bf BfRead, vec *Vec3) 82 | func BfReadAngles(bf BfRead, vec *Vec3) 83 | func BfGetNumBytesLeft(bf BfRead) int -------------------------------------------------------------------------------- /sourcemod/textparse.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/textparse.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | type SMCResult int 18 | const ( 19 | SMCParse_Continue = SMCResult(0) /**< Continue parsing */ 20 | SMCParse_Halt /**< Stop parsing here */ 21 | SMCParse_HaltFail /**< Stop parsing and return failure */ 22 | ) 23 | 24 | 25 | type SMCError int 26 | const ( 27 | SMCError_Okay = SMCError(0) /**< No error */ 28 | SMCError_StreamOpen /**< Stream failed to open */ 29 | SMCError_StreamError /**< The stream died... somehow */ 30 | SMCError_Custom /**< A custom handler threw an error */ 31 | SMCError_InvalidSection1 /**< A section was declared without quotes, and had extra tokens */ 32 | SMCError_InvalidSection2 /**< A section was declared without any header */ 33 | SMCError_InvalidSection3 /**< A section ending was declared with too many unknown tokens */ 34 | SMCError_InvalidSection4 /**< A section ending has no matching beginning */ 35 | SMCError_InvalidSection5 /**< A section beginning has no matching ending */ 36 | SMCError_InvalidTokens /**< There were too many unidentifiable strings on one line */ 37 | SMCError_TokenOverflow /**< The token buffer overflowed */ 38 | SMCError_InvalidProperty1 /**< A property was declared outside of any section */ 39 | ) 40 | 41 | 42 | type ( 43 | SMC_ParseStart func(smc SMCParser) 44 | SMC_NewSection func(smc SMCParser, name string, opt_quotes bool) SMCResult 45 | SMC_KeyValue func (smc SMCParser, key, value string, key_quotes, value_quotes bool) SMCResult 46 | SMC_EndSection func(smc SMCParser) SMCResult 47 | SMC_ParseEnd func(smc SMCParser, halted, failed bool) 48 | SMC_RawLine func(smc SMCParser, line string, lineno int) SMCResult 49 | 50 | 51 | /// new SMCParser(); 52 | SMCParser struct { 53 | OnStart SMC_ParseStart 54 | OnEnd SMC_ParseEnd 55 | OnEnterSection SMC_NewSection 56 | OnLeaveSection SMC_EndSection 57 | OnKeyValue SMC_KeyValue 58 | OnRawLine SMC_RawLine 59 | } 60 | ) 61 | 62 | 63 | func (SMCParser) ParseFile(file string, line, col *int) SMCError 64 | func (SMCParser) GetErrorString(err SMCError, buffer []char, buf_max int) 65 | 66 | 67 | func SMC_CreateParser() SMCParser 68 | func SMC_ParseFile(smc SMCParser, file string, line, col *int) SMCError 69 | func SMC_GetErrorString(smc SMCParser, err SMCError, buffer []char, buf_max int) 70 | func SMC_SetParseStart(smc SMCParser, fn SMC_ParseStart) 71 | func SMC_SetParseEnd(smc SMCParser, fn SMC_ParseEnd) 72 | func SMC_SetReaders(smc SMCParser, ns SMC_NewSection, kv SMC_KeyValue, es SMC_EndSection) 73 | func SMC_SetRawLine(smc SMCParser, fn SMC_RawLine) -------------------------------------------------------------------------------- /rewrite/srcgo/pass9_mutate_ranges.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Nirari Technologies. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 5 | * 6 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 9 | * 10 | */ 11 | 12 | package SrcGo 13 | 14 | 15 | import ( 16 | "fmt" 17 | "go/types" 18 | "go/ast" 19 | "go/token" 20 | ) 21 | 22 | type pass9Ctxt struct { 23 | currFunc *ast.FuncDecl 24 | ti *types.Info 25 | rangeIter uint 26 | } 27 | 28 | func (a *AstTransmitter) MutateRanges(file *ast.File) { 29 | context := pass9Ctxt{ ti: a.TypeInfo } 30 | for _, decl := range file.Decls { 31 | switch d := decl.(type) { 32 | case *ast.FuncDecl: 33 | context.currFunc = d 34 | if d.Body != nil { 35 | MutateBlock(d.Body, MutateRangeStmts, &context) 36 | } 37 | context.currFunc = nil 38 | } 39 | } 40 | } 41 | 42 | func MutateRangeStmts(owner_list *[]ast.Stmt, index int, s ast.Stmt, bm BlockMutator, ctxt any) { 43 | switch n := s.(type) { 44 | case *ast.BlockStmt: 45 | bm(n, MutateRangeStmts, ctxt) 46 | 47 | case *ast.ForStmt: 48 | if n.Init != nil { 49 | MutateRangeStmts(owner_list, index, n.Init, bm, ctxt) 50 | } 51 | if n.Post != nil { 52 | MutateRangeStmts(owner_list, index, n.Post, bm, ctxt) 53 | } 54 | bm(n.Body, MutateRangeStmts, ctxt) 55 | 56 | case *ast.IfStmt: 57 | if n.Init != nil { 58 | MutateRangeStmts(owner_list, index, n.Init, bm, ctxt) 59 | } 60 | bm(n.Body, MutateRangeStmts, ctxt) 61 | if n.Else != nil { 62 | MutateRangeStmts(owner_list, index, n.Else, bm, ctxt) 63 | } 64 | 65 | case *ast.SwitchStmt: 66 | MutateRangeStmts(owner_list, index, n.Init, bm, ctxt) 67 | bm(n.Body, MutateRangeStmts, ctxt) 68 | 69 | case *ast.CaseClause: 70 | for i, stmt := range n.Body { 71 | MutateRangeStmts(&n.Body, i, stmt, bm, ctxt) 72 | } 73 | 74 | case *ast.RangeStmt: 75 | context := ctxt.(*pass9Ctxt) 76 | if n.Key != nil { 77 | if iden, ok := n.Key.(*ast.Ident); ok && iden.Name=="_" { 78 | n.Key = ast.NewIdent(fmt.Sprintf("%s_iter%d", context.currFunc.Name.Name, context.rangeIter)) 79 | context.rangeIter++ 80 | } 81 | } else { 82 | n.Key = ast.NewIdent(fmt.Sprintf("%s_iter%d", context.currFunc.Name.Name, context.rangeIter)) 83 | context.rangeIter++ 84 | } 85 | 86 | if n.Value != nil { 87 | if iden, ok := n.Value.(*ast.Ident); ok && iden.Name=="_" { 88 | n.Value = nil 89 | } else { 90 | switch n.Tok { 91 | case token.DEFINE: 92 | decl_stmt := MakeVarDecl([]*ast.Ident{n.Value.(*ast.Ident)}, n.Value, nil, context.ti) 93 | n.Body.List = InsertToIndex[ast.Stmt](n.Body.List, 0, decl_stmt) 94 | 95 | assign := MakeAssign(false) 96 | assign.Lhs = append(assign.Lhs, n.Value) 97 | 98 | get_index := MakeIndex(n.Key, n.X) 99 | assign.Rhs = append(assign.Rhs, get_index) 100 | 101 | n.Body.List = InsertToIndex[ast.Stmt](n.Body.List, 1, assign) 102 | n.Value = nil 103 | } 104 | } 105 | } 106 | bm(n.Body, MutateRangeStmts, ctxt) 107 | } 108 | } -------------------------------------------------------------------------------- /test_code/joined_senses_stasis.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sourcemod" 4 | 5 | const SLOTCOUNT = 3 6 | 7 | type Player struct { 8 | userID, pauseTick, buttons int 9 | origin, velocity Vec3 10 | nextAttackPrimary, nextAttackSecondary [SLOTCOUNT]float 11 | stasisTick float 12 | isInStasis bool 13 | } 14 | 15 | func (p *Player) get() int { 16 | return GetClientOfUserId(p.userID) 17 | } 18 | 19 | func (p *Player) set(client Entity) { 20 | if isValidClient(client) { 21 | p.userID = GetClientUserid(client) 22 | } else { 23 | p.userID = 0 24 | } 25 | } 26 | 27 | func (p *Player) toggleStasis() { 28 | if !p.isInStasis { 29 | p.enableStasis() 30 | } else { 31 | p.disableStasis() 32 | } 33 | } 34 | 35 | func (p *Player) enableStasis() { 36 | p.isInStasis = true 37 | p.freeze() 38 | p.pauseAttack() 39 | p.displayLasers() 40 | } 41 | 42 | func (p *Player) disableStasis() { 43 | p.isInStasis = false 44 | p.unfreeze() 45 | p.resumeAttack() 46 | } 47 | 48 | func (p *Player) freeze() { 49 | client := p.get() 50 | if !client { 51 | return 52 | } 53 | 54 | freezeProjectiles(client) 55 | 56 | GetClientAbsOrigin(client, p.origin) 57 | 58 | getClientAbsVelocity(client, p.velocity) 59 | 60 | SetEntityMoveType(client, MOVETYPE_NONE) 61 | 62 | p.stasisTick = GetGameTime() 63 | p.buttons = GetClientButtons(client) 64 | p.pauseTick = GetGameTickCount() 65 | } 66 | 67 | func (p *Player) unfreeze() { 68 | client := p.get() 69 | if !client { 70 | return 71 | } 72 | 73 | unfreezeProjectiles(client) 74 | SetEntityMoveType(client, MOVETYPE_WALK) 75 | TeleportEntity(client, p.origin, NULL_VECTOR, p.velocity) 76 | } 77 | 78 | func (p *Player) pauseAttack() { 79 | client := p.get() 80 | if !client { 81 | return 82 | } 83 | 84 | for slot := 0; slot < SLOTCOUNT; slot++ { 85 | var weapon int = GetPlayerWeaponSlot(client, slot) 86 | if !IsValidEntity(weapon) { 87 | continue 88 | } 89 | 90 | if HasEntProp(weapon, Prop_Send, "m_flNextPrimaryAttack") { 91 | p.nextAttackPrimary[slot] = GetEntPropFloat(weapon, Prop_Send, "m_flNextPrimaryAttack") 92 | SetEntPropFloat(weapon, Prop_Send, "m_flNextPrimaryAttack", 999999999.0) 93 | } 94 | 95 | if HasEntProp(weapon, Prop_Send, "m_flNextSecondaryAttack") { 96 | p.nextAttackSecondary[slot] = GetEntPropFloat(weapon, Prop_Send, "m_flNextSecondaryAttack") 97 | SetEntPropFloat(weapon, Prop_Send, "m_flNextSecondaryAttack", 999999999.0) 98 | } 99 | } 100 | } 101 | 102 | func (p *Player) resumeAttack() { 103 | client := p.get() 104 | if !client { 105 | return 106 | } 107 | 108 | for slot := 0; slot < SLOTCOUNT; slot++ { 109 | var weapon int = GetPlayerWeaponSlot(client, slot) 110 | if !IsValidEntity(weapon) { 111 | continue 112 | } 113 | 114 | if HasEntProp(weapon, Prop_Send, "m_flNextPrimaryAttack") { 115 | SetEntPropFloat( weapon, Prop_Send, "m_flNextPrimaryAttack", p.nextAttackPrimary[slot]+(GetGameTime()-p.stasisTick)) 116 | } 117 | if HasEntProp(weapon, Prop_Send, "m_flNextSecondaryAttack") { 118 | SetEntPropFloat(weapon, Prop_Send, "m_flNextSecondaryAttack", p.nextAttackSecondary[slot]+(GetGameTime()-p.stasisTick)) 119 | } 120 | } 121 | } 122 | 123 | func (p *Player) displayLasers() { 124 | client := p.get() 125 | if !client { 126 | return 127 | } 128 | 129 | var angles, eyePos, temp, fwrd, end Vec3 130 | GetClientEyeAngles(client, angles) 131 | GetClientEyePosition(client, eyePos) 132 | GetVectorAngles(p.velocity, &temp) 133 | 134 | GetAngleVectors(temp, &fwrd, &NULL_VECTOR, &NULL_VECTOR) 135 | ScaleVector(&fwrd, GetVectorLength(p.velocity)*0.2) 136 | AddVectors(p.origin, fwrd, &temp) 137 | doLaserBeam(client, p.origin, temp) 138 | 139 | GetAngleVectors(angles, &fwrd, &NULL_VECTOR, &NULL_VECTOR) 140 | ScaleVector(&fwrd, 80.0) 141 | 142 | AddVectors(eyePos, fwrd, &end) 143 | doLaserBeam(client, eyePos, end, 255, 20, 20) 144 | 145 | temp = eyePos 146 | temp[2] -= 30.0 147 | doLaserBeam(client, temp, end, 255, 20, 20) 148 | } 149 | -------------------------------------------------------------------------------- /rewrite/sourcemod/core.go: -------------------------------------------------------------------------------- 1 | /* 2 | * sourcemod/core.go 3 | * 4 | * Copyright 2022 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package sm 15 | 16 | 17 | // Golang has "struct tags" which we'll use to control specific transpilation. 18 | // rename: -- will rename the member when transpiled to SP. 19 | type Plugin struct { 20 | Name []byte `rename:name` 21 | Descript []byte `rename:description` 22 | Author []byte `rename:author` 23 | Version []byte `rename:version` 24 | Url []byte `rename:url` 25 | } 26 | 27 | type Extension struct { 28 | Name []byte `rename:name` 29 | File []byte `rename:file` 30 | Autoload int `rename:autoload` 31 | Required int `rename:required` 32 | } 33 | 34 | const ( 35 | SOURCEMOD_PLUGINAPI_VERSION = 5 36 | 37 | SOURCEMOD_V_TAG string = "manual" 38 | SOURCEMOD_V_REV = 0 39 | SOURCEMOD_V_CSET string = "0" 40 | SOURCEMOD_V_MAJOR = 1 /* SourceMod Major version */ 41 | SOURCEMOD_V_MINOR = 10 /* SourceMod Minor version */ 42 | SOURCEMOD_V_RELEASE = 0 /* SourceMod Release version */ 43 | 44 | SOURCEMOD_VERSION string = "1.11.0-manual" /* SourceMod version string (major.minor.release-tag) */ 45 | ) 46 | 47 | 48 | type Action int 49 | const ( 50 | Plugin_Continue = Action(iota) 51 | Plugin_Changed 52 | Plugin_Handled 53 | Plugin_Stop 54 | ) 55 | 56 | type Identity int 57 | const ( 58 | Identity_Core = Identity(iota) 59 | Identity_Extension 60 | Identity_Plugin 61 | ) 62 | 63 | 64 | type PluginStatus int 65 | const ( 66 | Plugin_Running = PluginStatus(iota) /* Plugin is running */ 67 | 68 | /* All states below are "temporarily" unexecutable */ 69 | Plugin_Paused /* Plugin is loaded but paused */ 70 | Plugin_Error /* Plugin is loaded but errored/locked */ 71 | 72 | /* All states below do not have all natives */ 73 | Plugin_Loaded /* Plugin has passed loading and can be finalized */ 74 | Plugin_Failed /* Plugin has a fatal failure */ 75 | Plugin_Created /* Plugin is created but not initialized */ 76 | Plugin_Uncompiled /* Plugin is not yet compiled by the JIT */ 77 | Plugin_BadLoad /* Plugin failed to load */ 78 | Plugin_Evicted /* Plugin was unloaded due to an error */ 79 | ) 80 | 81 | 82 | type PluginInfo int 83 | const ( 84 | PlInfo_Name = PluginInfo(iota) /* Plugin name */ 85 | PlInfo_Author /* Plugin author */ 86 | PlInfo_Description /* Plugin description */ 87 | PlInfo_Version /* Plugin version */ 88 | PlInfo_URL 89 | ) 90 | 91 | type Function uintptr 92 | type Handle uintptr 93 | type Vec3 [3]float32 94 | type QAngle [3]float32 95 | type Entity = int 96 | 97 | const INVALID_FUNCTION = Function(0) 98 | 99 | const NULL_STRING = "" 100 | var ( 101 | NULL_VECTOR Vec3 // can't put NULL_VECTOR as 'const'. 102 | ) 103 | 104 | 105 | func IsNullVector(vec Vec3) bool 106 | func IsNullString(str []byte) bool 107 | func VerifyCoreVersion() int 108 | func MarkNativeAsOptional(name []byte) 109 | -------------------------------------------------------------------------------- /sourcemod/convars.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/convars.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | type ConVarBounds int 18 | const ( 19 | ConVarBound_Upper = ConVarBounds(0) 20 | ConVarBound_Lower 21 | ) 22 | 23 | 24 | type ConVarQueryResult int 25 | const ( 26 | ConVarQuery_Okay = ConVarQueryResult(0) //< Retrieval of client convar value was successful. */ 27 | ConVarQuery_NotFound //< Client convar was not found. */ 28 | ConVarQuery_NotValid //< A console command with the same name was found, but there is no convar. */ 29 | ConVarQuery_Protected //< Client convar was found, but it is protected. The server cannot retrieve its value. */ 30 | ) 31 | 32 | 33 | type ConVarChanged func(convar ConVar, oldValue, newValue string) 34 | 35 | func CreateConVar(name, defaultValue, description string, flags int, hasMin bool, min float, hasMax bool, max float) ConVar 36 | func FindConVar(name string) ConVar 37 | 38 | type ConVar struct { 39 | BoolValue bool 40 | IntValue, Flags int 41 | FloatValue float 42 | } 43 | func (ConVar) SetBool(value, replicate, notify bool) 44 | func (ConVar) SetInt(value int, replicate, notify bool) 45 | func (ConVar) SetFloat(value float, replicate, notify bool) 46 | func (ConVar) GetString(value []char, maxlength int) 47 | func (ConVar) SetString(value string, replicate, notify bool) 48 | func (ConVar) RestoreDefault(replicate, notify bool) 49 | func (ConVar) GetDefault(value []char, maxlength int) int 50 | func (ConVar) GetBounds(bounds_type ConVarBounds, value *float) bool 51 | func (ConVar) SetBounds(bounds_type ConVarBounds, set bool, value float) 52 | func (ConVar) GetName(name []char, maxlength int) 53 | func (ConVar) ReplicateToClient(client Entity, value string) bool 54 | func (ConVar) AddChangeHook(callback ConVarChanged) 55 | func (ConVar) RemoveChangeHook(callback ConVarChanged) 56 | 57 | func HookConVarChange(cvar ConVar, callback ConVarChanged) 58 | func UnhookConVarChange(cvar ConVar, callback ConVarChanged) 59 | 60 | func GetConVarBool(cvar ConVar) bool 61 | func GetConVarInt(cvar ConVar) int 62 | func GetConVarFloat(cvar ConVar) float 63 | func GetConVarString(cvar ConVar, value []char, maxlength int) 64 | 65 | func SetConVarBool(cvar ConVar, value, replicate, notify bool) 66 | func SetConVarInt(cvar ConVar, value int, replicate, notify bool) 67 | func SetConVarFloat(cvar ConVar, value float, replicate, notify bool) 68 | func SetConVarString(cvar ConVar, value string, replicate, notify bool) 69 | 70 | func ResetConVar(cvar ConVar, replicate, notify bool) 71 | func GetConVarDefault(cvar ConVar, value []char, maxlength int) int 72 | func GetConVarFlags(cvar ConVar) int 73 | func SetConVarFlags(cvar ConVar, flags int) 74 | func GetConVarBounds(cvar ConVar, bounds_type ConVarBounds, value *float) bool 75 | func SetConVarBounds(cvar ConVar, bounds_type ConVarBounds, set bool, value float) 76 | func GetConVarName(cvar ConVar, name []char, maxlength int) 77 | func SendConVarValue(client Entity, cvar ConVar, value string) bool 78 | 79 | type ConVarQueryFinished func(cookie QueryCookie, client Entity, result ConVarQueryResult, cvarName, cvarValue string, value any) 80 | func QueryClientConVar(client Entity, cvarName string, callback ConVarQueryFinished, value any) QueryCookie 81 | func IsValidConVarChar(c int) bool -------------------------------------------------------------------------------- /rewrite/srcgo/pass1_illegal_code.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Nirari Technologies. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 5 | * 6 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 9 | * 10 | */ 11 | 12 | package SrcGo 13 | 14 | 15 | import ( 16 | "fmt" 17 | "go/token" 18 | "go/ast" 19 | ) 20 | 21 | /* 22 | * Pass #1 - Analyze Illegal Code 23 | * checks for ANY Go constructs that cannot be faithfully recreated in SourcePawn. 24 | */ 25 | func (a *AstTransmitter) AnalyzeIllegalCode(file *ast.File) bool { 26 | ast.Inspect(file, func(n ast.Node) bool { 27 | if n != nil { 28 | switch x := n.(type) { 29 | case *ast.FuncDecl: 30 | if x.Recv != nil && len(x.Recv.List) > 1 { 31 | a.PrintErr(x.Pos(), "Multiple Receivers are not allowed.") 32 | } 33 | if x.Type.Results != nil { 34 | for _, ret := range x.Type.Results.List { 35 | if ptr, is_ptr := ret.Type.(*ast.StarExpr); is_ptr { 36 | a.PrintErr(ptr.Pos(), "Returning Pointers isn't Allowed." + fmt.Sprintf(" Param %v is of pointer type", ret.Names)) 37 | } 38 | } 39 | } 40 | 41 | case *ast.FuncType: 42 | if x.Results != nil { 43 | for _, ret := range x.Results.List { 44 | if ptr, is_ptr := ret.Type.(*ast.StarExpr); is_ptr { 45 | a.PrintErr(ptr.Pos(), "Returning Pointers isn't Allowed." + fmt.Sprintf(" Param %v is of pointer type", ret.Names)) 46 | } 47 | } 48 | } 49 | 50 | case *ast.StructType: 51 | for _, f := range x.Fields.List { 52 | switch t := f.Type.(type) { 53 | case *ast.StarExpr: 54 | a.PrintErr(t.Pos(), "Pointers are not allowed in Structs.") 55 | case *ast.ArrayType: 56 | if t.Len==nil { 57 | a.PrintErr(t.Pos(), "Arrays of unknown size are not allowed in Structs.") 58 | } 59 | } 60 | } 61 | case *ast.BranchStmt: 62 | if x.Tok==token.GOTO || x.Tok==token.FALLTHROUGH { 63 | a.PrintErr(x.Pos(), fmt.Sprintf("'%s' is Illegal.", x.Tok.String())) 64 | } else if x.Label != nil { 65 | a.PrintErr(x.Pos(), "Branched Labels are Illegal.") 66 | } 67 | 68 | case *ast.CommClause: // case chan<-var 69 | a.PrintErr(x.Pos(), "Comm Select Cases are Illegal.") 70 | case *ast.DeferStmt: // defer func() 71 | a.PrintErr(x.Pos(), "Defer Statements are Illegal.") 72 | case *ast.TypeSwitchStmt: // switch a.(type) {} 73 | a.PrintErr(x.Pos(), "Type-Switches are Illegal.") 74 | case *ast.LabeledStmt: 75 | a.PrintErr(x.Pos(), "Labels are Illegal.") 76 | case *ast.GoStmt: // go func() 77 | a.PrintErr(x.Pos(), "Goroutines are Illegal.") 78 | case *ast.SelectStmt: // select { case chan<-var: } 79 | a.PrintErr(x.Pos(), "Select Statements are Illegal.") 80 | case *ast.SendStmt: // chan <- var, var = <-chan 81 | a.PrintErr(x.Pos(), "Send Statements are Illegal.") 82 | case *ast.ChanType: 83 | a.PrintErr(x.Pos(), "Channel Types are Illegal.") 84 | 85 | case *ast.BasicLit: 86 | if x.Kind==token.IMAG { 87 | a.PrintErr(x.Pos(), "Imaginary Numbers are Illegal.") 88 | } 89 | case *ast.TypeAssertExpr: // b,c := a.(type) 90 | a.PrintErr(x.Pos(), "Type Assertions are Illegal.") 91 | case *ast.SliceExpr: // a[ low : high : max ] 92 | a.PrintErr(x.Pos(), "Slice Expressions are Illegal.") 93 | case *ast.MapType: // map[K]V 94 | /// check if the key isn't 'string', only string keys are allowed. 95 | if typ, is_ident := x.Key.(*ast.Ident); !is_ident || typ.Name != "string" { 96 | a.PrintErr(x.Pos(), "Non-string Maps are Illegal.") 97 | } 98 | case *ast.UnaryExpr: 99 | if x.Op==token.ARROW { 100 | a.PrintErr(x.Pos(), "Channel Expressions are Illegal.") 101 | } 102 | } 103 | } 104 | return true 105 | }) 106 | return len(a.Errors)==0 107 | } -------------------------------------------------------------------------------- /rewrite/sourcemod/files.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/files.go 3 | * 4 | * Copyright 2022 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of bytege, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package sm 15 | 16 | 17 | type FileType int 18 | const ( 19 | FileType_Unknown = FileType(0) /* Unknown file type (device/socket) */ 20 | FileType_Directory = FileType(1) /* File is a directory */ 21 | FileType_File = FileType(2) /* File is a file */ 22 | ) 23 | 24 | type FileTimeMode int 25 | const ( 26 | FileTime_LastAccess = FileTimeMode(0) /* Last access (does not work on FAT) */ 27 | FileTime_Created = FileTimeMode(1) /* Creation (does not work on FAT) */ 28 | FileTime_LastChange = FileTimeMode(2) /* Last modification */ 29 | ) 30 | 31 | 32 | const ( 33 | PLATFORM_MAX_PATH = 256 34 | PLATFORM_MIN_PATH = 64 35 | SEEK_SET = 0 36 | SEEK_CUR = 1 37 | SEEK_END = 2 38 | ) 39 | 40 | 41 | type PathType int 42 | type PathStr = [PLATFORM_MAX_PATH]byte 43 | var Path PathType 44 | 45 | 46 | type DirectoryListing struct {} 47 | func (*DirectoryListing) GetNext(buffer []byte, maxlength int, filetype *FileType) bool 48 | 49 | 50 | type File struct { 51 | Position int 52 | } 53 | 54 | func (*File) Close() bool 55 | func (*File) ReadLine(buffer []byte, maxlength int) bool 56 | func (*File) Read(items []int, num_items, size int) int 57 | func (*File) ReadString(buffer []byte, max_size, read_count int) int 58 | 59 | func (*File) Write(items []int, num_items, size int) bool 60 | func (*File) WriteString(buffer []byte, term bool) bool 61 | func (*File) WriteLine(format []byte, args ...any) bool 62 | 63 | func (*File) ReadInt8(data *int) bool 64 | func (*File) ReadUint8(data *int) bool 65 | func (*File) ReadInt16(data *int) bool 66 | func (*File) ReadUint16(data *int) bool 67 | func (*File) ReadInt32(data *int) bool 68 | 69 | func (*File) WriteInt8(data int) bool 70 | func (*File) WriteInt16(data int) bool 71 | func (*File) WriteInt32(data int) bool 72 | 73 | func (*File) EndOfFile() bool 74 | func (*File) Seek(position, where int) bool 75 | func (*File) Flush() bool 76 | 77 | 78 | func BuildPath(path PathType, buffer []byte, maxlength int, fmt []byte, args ...any) int 79 | 80 | func OpenDirectory(path []byte, use_valve_fs bool, valve_path_id []byte) DirectoryListing 81 | func ReadDirEntry(dir Handle, buffer []byte, maxlength int, filetype *FileType) bool 82 | func OpenFile(file, mode []byte, use_valve_fs bool, valve_path_id []byte) File 83 | func DeleteFile(path []byte, use_valve_fs bool, valve_path_id []byte) bool 84 | 85 | func FileExists(path []byte, use_valve_fs bool, valve_path_id []byte) bool 86 | func RenameFile(newpath, oldpath []byte, use_valve_fs bool, valve_path_id []byte) bool 87 | func DirExists(path []byte, use_valve_fs bool, valve_path_id []byte) bool 88 | func FileSize(path []byte, use_valve_fs bool, valve_path_id []byte) int 89 | func RemoveDir(path []byte) bool 90 | 91 | 92 | const ( 93 | FPERM_U_READ = 0x0100 /* User can read. */ 94 | FPERM_U_WRITE = 0x0080 /* User can write. */ 95 | FPERM_U_EXEC = 0x0040 /* User can exec. */ 96 | FPERM_G_READ = 0x0020 /* Group can read. */ 97 | FPERM_G_WRITE = 0x0010 /* Group can write. */ 98 | FPERM_G_EXEC = 0x0008 /* Group can exec. */ 99 | FPERM_O_READ = 0x0004 /* Anyone can read. */ 100 | FPERM_O_WRITE = 0x0002 /* Anyone can write. */ 101 | FPERM_O_EXEC = 0x0001 /* Anyone can exec. */ 102 | ) 103 | 104 | func CreateDirectory(path []byte, mode int, use_valve_fs bool, valve_path_id []byte) bool 105 | func SetFilePermissions(path []byte, mode int) bool 106 | func GetFileTime(file []byte, tmode FileTimeMode) int 107 | func LogToOpenFile(file File, message []byte, args ...any) 108 | func LogToOpenFileEx(file File, message []byte, args ...any) 109 | -------------------------------------------------------------------------------- /sourcemod/clients.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/clients.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | type NetFlow int 18 | const ( 19 | NetFlow_Outgoing = NetFlow(0) /**< Outgoing traffic */ 20 | NetFlow_Incoming /**< Incoming traffic */ 21 | NetFlow_Both /**< Both values added together */ 22 | ) 23 | 24 | type AuthIdType int 25 | const ( 26 | AuthId_Engine = AuthIdType(0) /**< The game-specific auth string as returned from the engine */ 27 | 28 | // The following are only available on games that support Steam authentication. 29 | AuthId_Steam2 /**< Steam2 rendered format, ex "STEAM_1:1:4153990" */ 30 | AuthId_Steam3 /**< Steam3 rendered format, ex "[U:1:8307981]" */ 31 | AuthId_SteamID64 /**< A SteamID64 (uint64) as a String, ex "76561197968573709" */ 32 | ) 33 | 34 | 35 | const ( 36 | MAXPLAYERS = 65 37 | PLAYERS_SIZE = MAXPLAYERS + 1 38 | MAX_NAME_LENGTH = 128 39 | MAX_TF_PLAYERS = 36 40 | ) 41 | 42 | var MaxClients int 43 | 44 | 45 | func GetMaxHumanPlayers() int 46 | func GetClientCount(inGameOnly bool) int 47 | func GetClientName(client Entity, name []char, maxlen int) bool 48 | func GetClientIP(client Entity, ip []char, maxlen int, remport bool) bool 49 | func GetClientAuthId(client Entity, authtype AuthIdType, auth []char, maxlen int, validate bool) bool 50 | func GetSteamAccountID(client Entity, validate bool) int 51 | func GetClientUserId(client Entity) int 52 | func IsClientConnected(client Entity) bool 53 | func IsClientInGame(client Entity) bool 54 | func IsClientInKickQueue(client Entity) bool 55 | func IsClientAuthorized(client Entity) bool 56 | func IsFakeClient(client Entity) bool 57 | func IsClientSourceTV(client Entity) bool 58 | func IsClientReplay(client Entity) bool 59 | func IsClientObserver(client Entity) bool 60 | func IsPlayerAlive(client Entity) bool 61 | func GetClientInfo(client Entity, key string, value []char, maxlen int) bool 62 | func GetClientTeam(client Entity) int 63 | func SetUserAdmin(client Entity, id AdminId, temp bool) 64 | func GetUserAdmin(client Entity) AdminId 65 | func AddUserFlags(client Entity, flags ...AdminFlag) 66 | func RemoveUserFlags(client Entity, flags ...AdminFlag) 67 | func SetUserFlagBits(client, flags int) 68 | func GetUserFlagBits(client Entity) int 69 | func CanUserTarget(client, target int) bool 70 | func RunAdminCacheChecks(client Entity) bool 71 | func NotifyPostAdminCheck(client Entity) 72 | func CreateFakeClient(name string) int 73 | func SetFakeClientConVar(client Entity, cvar, value string) 74 | func GetClientHealth(client Entity) int 75 | func GetClientModel(client Entity, model []char, maxlen int) 76 | func GetClientWeapon(client Entity, wep []char, maxlen int) 77 | func GetClientMaxs(client Entity, vec *Vec3) 78 | func GetClientMins(client Entity, vec *Vec3) 79 | func GetClientAbsAngles(client Entity, vec *Vec3) 80 | func GetClientAbsOrigin(client Entity, vec *Vec3) 81 | func GetClientArmor(client Entity) int 82 | func GetClientDeaths(client Entity) int 83 | func GetClientFrags(client Entity) int 84 | func GetClientDataRate(client Entity) int 85 | func IsClientTimingOut(client Entity) bool 86 | func GetClientTime(client Entity) float 87 | func GetClientLatency(client Entity, flow NetFlow) float 88 | func GetClientAvgLatency(client Entity, flow NetFlow) float 89 | func GetClientAvgLoss(client Entity, flow NetFlow) float 90 | func GetClientAvgChoke(client Entity, flow NetFlow) float 91 | func GetClientAvgData(client Entity, flow NetFlow) float 92 | func GetClientAvgPackets(client Entity, flow NetFlow) float 93 | func GetClientOfUserId(userid int) int 94 | func KickClient(client Entity, format string, args ...any) 95 | func KickClientEx(client Entity, format string, args ...any) 96 | func ChangeClientTeam(client, team int) 97 | func GetClientSerial(client Entity) int 98 | func GetClientFromSerial(cl_serial int) int -------------------------------------------------------------------------------- /rewrite/srcgo/pass6_mutate_assign_defs.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Nirari Technologies. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 5 | * 6 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 9 | * 10 | */ 11 | 12 | package SrcGo 13 | 14 | 15 | import ( 16 | "go/types" 17 | "go/ast" 18 | "go/token" 19 | ) 20 | 21 | /* Case Studies of Changing assignment definitions: 22 | * 23 | * a,b,c := f() 24 | * 25 | * if not func ptr: 26 | * var a,b,c type 27 | * a = f(&b, &c) 28 | * 29 | * if func ptr: 30 | * var a,b,c type 31 | * Call_StartFunction(nil, f) 32 | * Call_PushCellRef(&b) 33 | * Call_PushCellRef(&c) 34 | * Call_Finish(&a) 35 | * 36 | */ 37 | func (a *AstTransmitter) MutateAssignDecls(file *ast.File) { 38 | for _, decl := range file.Decls { 39 | switch d := decl.(type) { 40 | case *ast.FuncDecl: 41 | if d.Body != nil { 42 | MutateBlock(d.Body, MutateAssignDefStmts, a) 43 | } 44 | } 45 | } 46 | } 47 | 48 | func MutateAssignDefStmts(owner_list *[]ast.Stmt, index int, s ast.Stmt, bm BlockMutator, ctxt any) { 49 | switch n := s.(type) { 50 | case *ast.BlockStmt: 51 | bm(n, MutateAssignDefStmts, ctxt) 52 | 53 | case *ast.ForStmt: 54 | if n.Init != nil { 55 | MutateAssignDefStmts(owner_list, index, n.Init, bm, ctxt) 56 | } 57 | if n.Post != nil { 58 | MutateAssignDefStmts(owner_list, index, n.Post, bm, ctxt) 59 | } 60 | bm(n.Body, MutateAssignDefStmts, ctxt) 61 | 62 | case *ast.IfStmt: 63 | if n.Init != nil { 64 | MutateAssignDefStmts(owner_list, index, n.Init, bm, ctxt) 65 | } 66 | bm(n.Body, MutateAssignDefStmts, ctxt) 67 | if n.Else != nil { 68 | MutateAssignDefStmts(owner_list, index, n.Else, bm, ctxt) 69 | } 70 | 71 | case *ast.SwitchStmt: 72 | MutateAssignDefStmts(owner_list, index, n.Init, bm, ctxt) 73 | bm(n.Body, MutateAssignDefStmts, ctxt) 74 | 75 | case *ast.CaseClause: 76 | for i, stmt := range n.Body { 77 | MutateAssignDefStmts(&n.Body, i, stmt, bm, ctxt) 78 | } 79 | 80 | case *ast.RangeStmt: 81 | bm(n.Body, MutateAssignDefStmts, ctxt) 82 | 83 | case *ast.AssignStmt: 84 | context := ctxt.(*AstTransmitter) 85 | left_len, rite_len := len(n.Lhs), len(n.Rhs) 86 | if rite_len==1 && left_len >= rite_len { 87 | switch e := n.Rhs[0].(type) { 88 | case *ast.CallExpr: 89 | if iden, is_ident := e.Fun.(*ast.Ident); is_ident && iden.Name=="make" { 90 | arg_len := len(e.Args) 91 | switch { 92 | case arg_len > 2: 93 | context.PrintErr(e.Pos(), "'make' has too many arguments.") 94 | case arg_len < 2: 95 | context.PrintErr(e.Pos(), "'make' has too few arguments.") 96 | case left_len > 1: 97 | context.PrintErr(e.Pos(), "'make' only returns one value.") 98 | } 99 | return 100 | } 101 | 102 | // a func call returning multiple items as a decl + init. 103 | switch n.Tok { 104 | case token.DEFINE: 105 | decl_stmt := new(ast.DeclStmt) 106 | gen_decl := new(ast.GenDecl) 107 | gen_decl.Tok = token.VAR 108 | 109 | // first we get each name of a var and then map them to a type. 110 | var_map := make(map[types.Type][]ast.Expr) 111 | for _, e := range n.Lhs { 112 | if type_expr := context.TypeInfo.TypeOf(e); type_expr != nil { 113 | var_map[type_expr] = append(var_map[type_expr], e) 114 | } else { 115 | context.PrintErr(n.TokPos, "Failed to expand assignment statement.") 116 | } 117 | } 118 | 119 | for key, val := range var_map { 120 | val_spec := new(ast.ValueSpec) 121 | for _, name := range val { 122 | val_spec.Names = append(val_spec.Names, name.(*ast.Ident)) 123 | } 124 | val_spec.Type = TypeToASTExpr(key) 125 | gen_decl.Specs = append(gen_decl.Specs, val_spec) 126 | } 127 | 128 | decl_stmt.Decl = gen_decl 129 | *owner_list = InsertToIndex[ast.Stmt](*owner_list, 0, decl_stmt) 130 | n.Tok = token.ASSIGN 131 | } 132 | } 133 | } 134 | } 135 | } -------------------------------------------------------------------------------- /rewrite/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | * main.go 3 | * 4 | * Copyright 2022 Nirari Technologies. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | import ( 17 | "fmt" 18 | "go/ast" 19 | "go/importer" 20 | "go/parser" 21 | "go/scanner" 22 | "go/token" 23 | "go/types" 24 | "io" 25 | "io/ioutil" 26 | ///"path/filepath" 27 | "os" 28 | "os/exec" 29 | "runtime" 30 | ///"strings" 31 | 32 | "./srcgo" 33 | ) 34 | 35 | 36 | 37 | func RunTypeCheck(fset *token.FileSet, file *ast.File) *types.Info { 38 | curr_dir, _ := os.Getwd() 39 | var errs []error 40 | conf := types.Config{ 41 | DisableUnusedImportCheck: true, 42 | Importer: importer.ForCompiler(fset, "source", nil), // YOU NEED THIS. 43 | Error: func(err error) { 44 | errs = append(errs, err) 45 | }, 46 | } 47 | 48 | ti := &types.Info{ 49 | Types: make(map[ast.Expr]types.TypeAndValue), 50 | Defs: make(map[*ast.Ident]types.Object), 51 | Uses: make(map[*ast.Ident]types.Object), 52 | Implicits: make(map[ast.Node]types.Object), 53 | Scopes: make(map[ast.Node]*types.Scope), 54 | Selections: make(map[*ast.SelectorExpr]*types.Selection), 55 | } 56 | _, err := conf.Check(curr_dir, fset, []*ast.File{file}, ti) 57 | if err != nil { 58 | for _, type_err := range errs { 59 | fmt.Printf("SrcGo Error: **** '%s' ****\n", type_err) 60 | } 61 | return nil 62 | } 63 | return ti 64 | } 65 | 66 | func main() { 67 | for _, arg_str := range os.Args[1:] { 68 | switch arg_str { 69 | default: 70 | fset := token.NewFileSet() 71 | code, _ := LoadFile(arg_str) 72 | file_ast, parse_err := parser.ParseFile(fset, arg_str, code, parser.AllErrors) 73 | if parse_err != nil { 74 | for _, e := range parse_err.(scanner.ErrorList) { 75 | fmt.Println(e) 76 | } 77 | return 78 | } 79 | 80 | ti := RunTypeCheck(fset, file_ast) 81 | if ti==nil { 82 | return 83 | } 84 | 85 | transmitter := SrcGo.MakeAstTransmitter(fset, ti, nil, true) 86 | if !transmitter.AnalyzeIllegalCode(file_ast) { 87 | transmitter.PrintErrs() 88 | return 89 | } 90 | 91 | // this one doesn't need transmitter data. 92 | SrcGo.NameAnonFuncs(file_ast) 93 | 94 | // do another type check just in case. 95 | ti = RunTypeCheck(fset, file_ast) 96 | if ti==nil { 97 | return 98 | } 99 | transmitter.TypeInfo = ti 100 | 101 | SrcGo.MergeRetTypes(file_ast) 102 | SrcGo.MutateAndNotExpr(file_ast) 103 | 104 | transmitter.MutateRetExprs(file_ast) 105 | transmitter.MutateAssignDecls(file_ast) 106 | transmitter.MutateAssigns(file_ast) 107 | 108 | SrcGo.ChangeReceiverNames(file_ast) 109 | transmitter.MutateRanges(file_ast) 110 | transmitter.MutateNoRetCalls(file_ast) 111 | 112 | ti = RunTypeCheck(fset, file_ast) 113 | if ti==nil { 114 | return 115 | } 116 | 117 | fmt.Printf("'%s'\nEverything Ay-Ok!\n", SrcGo.PrettyPrintAST(file_ast)) 118 | } 119 | } 120 | } 121 | 122 | func CheckErr(e error) { 123 | if e != nil { 124 | panic(e) 125 | } 126 | } 127 | 128 | func LoadFile(filename string) (string, string) { 129 | if text, read_err := ioutil.ReadFile(filename); read_err==nil { 130 | return string(text), "none" 131 | } else { 132 | return "", read_err.Error() 133 | } 134 | } 135 | 136 | func WriteToFile(filename, data string) error { 137 | file, err := os.Create(filename) 138 | if err != nil { 139 | return err 140 | } 141 | defer file.Close() 142 | 143 | if _, err = io.WriteString(file, data); err != nil { 144 | return err 145 | } 146 | return file.Sync() 147 | } 148 | 149 | func InvokeSPComp(file string) { 150 | cmd_str := "compile" 151 | if runtime.GOOS == "windows" { 152 | cmd_str += ".bat" 153 | } else { 154 | cmd_str = fmt.Sprintf("./%s.sh", cmd_str) 155 | } 156 | 157 | if msg, err := exec.Command(cmd_str).Output(); err == nil { 158 | fmt.Printf("SourceGo::SPComp Invoked:: %s\n", string(msg)) 159 | } 160 | } -------------------------------------------------------------------------------- /sourcemod/protobuf.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/protobuf.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | const PB_FIELD_NOT_REPEATED = -1 18 | 19 | type Protobuf Handle 20 | func (Protobuf) ReadInt(field string, index int) int 21 | func (Protobuf) ReadInt64(field string, value *[2]int, index int) 22 | func (Protobuf) ReadFloat(field string, index int) float 23 | func (Protobuf) ReadBool(field string, index int) bool 24 | func (Protobuf) ReadString(field string, buffer []char, maxlen int, index int) 25 | func (Protobuf) ReadColor(field string, buffer *[4]int, index int) 26 | func (Protobuf) ReadAngle(field string, buffer *Vec3, index int) 27 | func (Protobuf) ReadVector(field string, buffer *Vec3, index int) 28 | func (Protobuf) ReadVector2D(field string, buffer *[2]float, index int) 29 | func (Protobuf) GetRepeatedFieldCount(field string) int 30 | func (Protobuf) HasField(field string) bool 31 | func (Protobuf) SetInt(field string, value int, index int) 32 | func (Protobuf) SetInt64(field string, value [2]int, index int) 33 | func (Protobuf) SetFloat(field string, value float, index int) 34 | func (Protobuf) SetBool(field string, value bool, index int) 35 | func (Protobuf) SetString(field, value string, index int) 36 | func (Protobuf) SetColor(field string, color [4]int, index int) 37 | func (Protobuf) SetAngle(field string, vec Vec3, index int) 38 | func (Protobuf) SetVector(field string, vec Vec3, index int) 39 | func (Protobuf) SetVector2D(field string, vec [2]float, index int) 40 | func (Protobuf) AddInt(field string, value int) 41 | func (Protobuf) AddInt64(field string, value [2]int) 42 | func (Protobuf) AddFloat(field string, value float) 43 | func (Protobuf) AddBool(field string, value bool) 44 | func (Protobuf) AddString(field, value string) 45 | func (Protobuf) AddColor(field string, color [4]int) 46 | func (Protobuf) AddAngle(field string, vec Vec3) 47 | func (Protobuf) AddVector(field string, vec Vec3) 48 | func (Protobuf) AddVector2D(field string, vec [2]float) 49 | func (Protobuf) RemoveRepeatedFieldValue(field string, index int) 50 | func (Protobuf) ReadMessage(field string) Protobuf 51 | func (Protobuf) ReadRepeatedMessage(field string, index int) Protobuf 52 | func (Protobuf) AddMessage(field string) Protobuf 53 | 54 | 55 | func PbReadInt(pb Protobuf, field string, index int) int 56 | func PbReadFloat(pb Protobuf, field string, index int) float 57 | func PbReadBool(pb Protobuf, field string, index int) bool 58 | func PbReadString(pb Protobuf, field string, buffer []char, maxlen int, index int) 59 | func PbReadColor(pb Protobuf, field string, buffer *[4]int, index int) 60 | func PbReadAngle(pb Protobuf, field string, buffer *Vec3, index int) 61 | func PbReadVector(pb Protobuf, field string, buffer *Vec3, index int) 62 | func PbReadVector2D(pb Protobuf, field string, buffer *[2]float, index int) 63 | func PbGetRepeatedFieldCount(pb Protobuf, field string) int 64 | func PbHasField(pb Protobuf, field string) bool 65 | func PbSetInt(pb Protobuf, field string, value int, index int) 66 | func PbSetFloat(pb Protobuf, field string, value float, index int) 67 | func PbSetBool(pb Protobuf, field string, value bool, index int) 68 | func PbSetString(field, value string, index int) 69 | func PbSetColor(pb Protobuf, field string, color [4]int, index int) 70 | func PbSetAngle(pb Protobuf, field string, vec Vec3, index int) 71 | func PbSetVector(pb Protobuf, field string, vec Vec3, index int) 72 | func PbSetVector2D(pb Protobuf, field string, vec [2]float, index int) 73 | func PbAddInt(pb Protobuf, field string, value int) 74 | func PbAddFloat(pb Protobuf, field string, value float) 75 | func PbAddBool(pb Protobuf, field string, value bool) 76 | func PbAddString(field, value string) 77 | func PbAddColor(pb Protobuf, field string, color [4]int) 78 | func PbAddAngle(pb Protobuf, field string, vec Vec3) 79 | func PbAddVector(pb Protobuf, field string, vec Vec3) 80 | func PbAddVector2D(pb Protobuf, field string, vec [2]float) 81 | func PbRemoveRepeatedFieldValue(pb Protobuf, field string, index int) 82 | func PbReadMessage(pb Protobuf, field string) Protobuf 83 | func PbReadRepeatedMessage(pb Protobuf, field string, index int) Protobuf 84 | func PbAddMessage(pb Protobuf, field string) Protobuf -------------------------------------------------------------------------------- /sourcemod/files.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/files.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | type FileType int 18 | const ( 19 | FileType_Unknown = FileType(0) /* Unknown file type (device/socket) */ 20 | FileType_Directory = FileType(1) /* File is a directory */ 21 | FileType_File = FileType(2) /* File is a file */ 22 | ) 23 | 24 | type FileTimeMode int 25 | const ( 26 | FileTime_LastAccess = FileTimeMode(0) /* Last access (does not work on FAT) */ 27 | FileTime_Created = FileTimeMode(1) /* Creation (does not work on FAT) */ 28 | FileTime_LastChange = FileTimeMode(2) /* Last modification */ 29 | ) 30 | 31 | 32 | const ( 33 | PLATFORM_MAX_PATH = 256 34 | SEEK_SET = 0 35 | SEEK_CUR = 1 36 | SEEK_END = 2 37 | ) 38 | 39 | 40 | type PathType int 41 | type PathStr = [PLATFORM_MAX_PATH]char 42 | var Path_SM PathType 43 | 44 | 45 | type DirectoryListing struct { 46 | } 47 | 48 | func (DirectoryListing) GetNext(buffer []char, maxlength int, filetype *FileType) bool 49 | 50 | 51 | type File struct { 52 | Position int 53 | } 54 | 55 | func (File) Close() bool 56 | func (File) ReadLine(buffer []char, maxlength int) bool 57 | func (File) Read(items []int, num_items, size int) int 58 | func (File) ReadString(buffer []char, max_size, read_count int) int 59 | 60 | func (File) Write(items []int, num_items, size int) bool 61 | func (File) WriteString(buffer string, term bool) bool 62 | func (File) WriteLine(format string, args ...any) bool 63 | 64 | func (File) ReadInt8(data *int) bool 65 | func (File) ReadUint8(data *int) bool 66 | func (File) ReadInt16(data *int) bool 67 | func (File) ReadUint16(data *int) bool 68 | func (File) ReadInt32(data *int) bool 69 | 70 | func (File) WriteInt8(data int) bool 71 | func (File) WriteInt16(data int) bool 72 | func (File) WriteInt32(data int) bool 73 | 74 | func (File) EndOfFile() bool 75 | func (File) Seek(position, where int) bool 76 | func (File) Flush() bool 77 | 78 | 79 | func BuildPath(path PathType, buffer []char, maxlength int, fmt string, args ...any) int 80 | 81 | func OpenDirectory(path string, use_valve_fs bool, valve_path_id string) DirectoryListing 82 | func ReadDirEntry(dir Handle, buffer []char, maxlength int, filetype *FileType) bool 83 | func OpenFile(file, mode string, use_valve_fs bool, valve_path_id string) File 84 | func DeleteFile(path string, use_valve_fs bool, valve_path_id string) bool 85 | 86 | func ReadFileLine(file File, buffer []char, maxlength int) bool 87 | func ReadFile(file File, items []int, num_items, size int) int 88 | func ReadFileString(file File, buffer []char, max_size, read_count int) int 89 | 90 | func WriteFileLine(file File, format string, args ...any) bool 91 | func ReadFileCell(file File, data *int, size int) int 92 | func WriteFileCell(file File, data, size int) bool 93 | func IsEndOfFile(file File) bool 94 | func FileSeek(file File, position, where int) bool 95 | func FilePosition(file File) int 96 | func FileExists(path string, use_valve_fs bool, valve_path_id string) bool 97 | func RenameFile(newpath, oldpath string, use_valve_fs bool, valve_path_id string) bool 98 | func DirExists(path string, use_valve_fs bool, valve_path_id string) bool 99 | func FileSize(path string, use_valve_fs bool, valve_path_id string) int 100 | func FlushFile(file File) bool 101 | func RemoveDir(path string) bool 102 | 103 | 104 | const ( 105 | FPERM_U_READ = 0x0100 /* User can read. */ 106 | FPERM_U_WRITE = 0x0080 /* User can write. */ 107 | FPERM_U_EXEC = 0x0040 /* User can exec. */ 108 | FPERM_G_READ = 0x0020 /* Group can read. */ 109 | FPERM_G_WRITE = 0x0010 /* Group can write. */ 110 | FPERM_G_EXEC = 0x0008 /* Group can exec. */ 111 | FPERM_O_READ = 0x0004 /* Anyone can read. */ 112 | FPERM_O_WRITE = 0x0002 /* Anyone can write. */ 113 | FPERM_O_EXEC = 0x0001 /* Anyone can exec. */ 114 | ) 115 | 116 | func CreateDirectory(path string, mode int, use_valve_fs bool, valve_path_id string) bool 117 | func SetFilePermissions(path string, mode int) bool 118 | func GetFileTime(file string, tmode FileTimeMode) int 119 | func LogToOpenFile(file File, message string, args ...any) 120 | func LogToOpenFileEx(file File, message string, args ...any) -------------------------------------------------------------------------------- /rewrite/srcgo/pass7_mutate_assignments.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Nirari Technologies. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 5 | * 6 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 9 | * 10 | */ 11 | 12 | package SrcGo 13 | 14 | 15 | import ( 16 | "fmt" 17 | ///"go/types" 18 | "go/ast" 19 | "go/token" 20 | ) 21 | 22 | 23 | type pass7Ctxt struct { 24 | currFunc *ast.FuncDecl 25 | transmit *AstTransmitter 26 | } 27 | 28 | /* Case Studies of Changing non-defining assignments: 29 | * 30 | */ 31 | func (a *AstTransmitter) MutateAssigns(file *ast.File) { 32 | context := pass7Ctxt{ transmit: a } 33 | for _, decl := range file.Decls { 34 | switch d := decl.(type) { 35 | case *ast.FuncDecl: 36 | context.currFunc = d 37 | if d.Body != nil { 38 | MutateBlock(d.Body, MutateAssignStmts, &context) 39 | } 40 | context.currFunc = nil 41 | } 42 | } 43 | } 44 | 45 | func MutateAssignStmts(owner_list *[]ast.Stmt, index int, s ast.Stmt, bm BlockMutator, ctxt any) { 46 | switch n := s.(type) { 47 | case *ast.BlockStmt: 48 | bm(n, MutateAssignStmts, ctxt) 49 | 50 | case *ast.ForStmt: 51 | if n.Init != nil { 52 | MutateAssignStmts(owner_list, index, n.Init, bm, ctxt) 53 | } 54 | if n.Post != nil { 55 | MutateAssignStmts(owner_list, index, n.Post, bm, ctxt) 56 | } 57 | bm(n.Body, MutateAssignStmts, ctxt) 58 | 59 | case *ast.IfStmt: 60 | if n.Init != nil { 61 | MutateAssignStmts(owner_list, index, n.Init, bm, ctxt) 62 | } 63 | bm(n.Body, MutateAssignStmts, ctxt) 64 | if n.Else != nil { 65 | MutateAssignStmts(owner_list, index, n.Else, bm, ctxt) 66 | } 67 | 68 | case *ast.SwitchStmt: 69 | MutateAssignStmts(owner_list, index, n.Init, bm, ctxt) 70 | bm(n.Body, MutateAssignStmts, ctxt) 71 | 72 | case *ast.CaseClause: 73 | for i, stmt := range n.Body { 74 | MutateAssignStmts(&n.Body, i, stmt, bm, ctxt) 75 | } 76 | 77 | case *ast.RangeStmt: 78 | bm(n.Body, MutateAssignStmts, ctxt) 79 | 80 | case *ast.AssignStmt: 81 | context := ctxt.(*pass7Ctxt) 82 | left_len, rite_len := len(n.Lhs), len(n.Rhs) 83 | if rite_len==1 && left_len >= rite_len { 84 | switch n.Tok { 85 | case token.ASSIGN: 86 | switch fn := n.Rhs[0].(type) { 87 | case *ast.CallExpr: 88 | // a func call returning multiple items as a decl + init. 89 | if IsFuncPtr(fn, context.transmit.TypeInfo) { 90 | ret_tmp := ast.NewIdent(fmt.Sprintf("fptr_temp%d", context.transmit.TmpVar)) 91 | context.transmit.TmpVar++ 92 | declstmt := MakeVarDecl([]*ast.Ident{ret_tmp}, n.Lhs[0], nil, context.transmit.TypeInfo) 93 | 94 | retvals := make([]ast.Expr, 0) 95 | retvals = append(retvals, ret_tmp) 96 | for i := 1; i < left_len; i++ { 97 | retvals = append(retvals, n.Lhs[i]) 98 | } 99 | 100 | calls := ExpandFuncPtrCalls(fn, retvals, nil, context.transmit.TypeInfo, context.currFunc) 101 | calls = InsertToIndex[ast.Stmt](calls, 0, declstmt) 102 | for i := len(calls)-1; i >= 0; i-- { 103 | *owner_list = InsertToIndex[ast.Stmt](*owner_list, index, calls[i]) 104 | } 105 | 106 | n.Lhs = n.Lhs[:1] 107 | n.Rhs[0] = ret_tmp 108 | } else { 109 | // transform the tuple return into a single return + pass by ref. 110 | for i := 1; i < left_len; i++ { 111 | switch e := n.Lhs[i].(type) { 112 | case *ast.Ident: 113 | fn.Args = append(fn.Args, MakeReference(e)) 114 | } 115 | } 116 | if left_len > 1 { 117 | n.Lhs = n.Lhs[:1] 118 | } 119 | } 120 | /** 121 | case *ast.IndexExpr: 122 | /// value, found = map[str] 123 | /// Becomes: found = map.GetValue(str, &value) 124 | if typ := context.TypeInfo.TypeOf(fn.X); typ != nil { 125 | switch t := typ.(type) { 126 | case *types.Map: 127 | ret_tmp := ast.NewIdent(fmt.Sprintf("map_value%d", context.TmpVar)) 128 | context.TmpVar++ 129 | declstmt := MakeVarDecl([]*ast.Ident{ret_tmp}, nil, t.Elem()) 130 | 131 | new_stmts := make([]ast.Stmt, 0) 132 | map_access := new(ast.CallExpr) 133 | switch elem_typ := t.Elem().(type) { 134 | case 135 | map_access.Fun = ast.NewIdent("GetValue") 136 | } 137 | map_access.Args = append(Call_StartFunction.Args, ast.NewIdent("nil")) 138 | map_access.Args = append(Call_StartFunction.Args, x.Fun) 139 | } 140 | } 141 | */ 142 | } 143 | } 144 | } 145 | } 146 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SourceGo 2 | v1.4 beta 3 | 4 | ## Introduction 5 | 6 | **SourceGo** is a transpiler that transforms a subset of Golang code to equivalent SourcePawn. The rationale behind SourceGo is to automate as much of the boilerplate possible when creating SourcePawn plugins. 7 | 8 | ### Purpose 9 | 10 | To increase SourcePawn plugin development time by using Golang's streamline engineered syntax. 11 | 12 | 13 | ### Features 14 | 15 | * Abstracted common types into their own type classes such as `float[3]` aliasing as `Vec3`, etc. 16 | Here is the current types list and what params it abstracts to: 17 | ``` 18 | int => int 19 | float => float 20 | bool => bool 21 | *[]char => char[] 22 | string => const char[] 23 | *string => char[] 24 | Vec3 => const float[3] 25 | *Vec3 => float[3] 26 | ``` 27 | 28 | * Pattern matching 29 | 30 | Array/slice types will be automatically const unless passed by reference like: `*[]type`. 31 | So having parameters such as `[]int` will be generated as `const int[]` while `*[]int` will be generated as `int[]`. 32 | 33 | 34 | * relative file imports are handled by using a dot `.` as the first letter 35 | ```go 36 | import ".file" 37 | ``` 38 | 39 | Becomes: 40 | ```c 41 | #include "file" 42 | ``` 43 | 44 | * Multiple return values are supported by mutating them into variable references. 45 | 46 | * Range loops for arrays: 47 | ```go 48 | var players [MAXPLAYERS+1]Entity 49 | for index, player := range players { 50 | /// code; 51 | } 52 | ``` 53 | ```c 54 | for (int index = 0; index < sizeof(players); index++) 55 | { 56 | int player = players[index]; 57 | /// code; 58 | } 59 | ``` 60 | 61 | * Switch statements with and without an expression. 62 | ```go 63 | // Go 64 | switch x { 65 | case 1, 2: 66 | default: 67 | } 68 | 69 | switch { 70 | case x < 10, x+y < 10.0: 71 | 72 | default: 73 | } 74 | ``` 75 | ```sourcepawn 76 | /// SourcePawn 77 | switch (x) 78 | { 79 | case 1, 2: 80 | { 81 | } 82 | default: 83 | { 84 | } 85 | } 86 | 87 | if (x < 10 || x+y < 10.0) 88 | { 89 | } 90 | else 91 | { 92 | } 93 | ``` 94 | Expression-less switchs are useful for a more compact if-else-if series. 95 | 96 | 97 | * Function pointer calls are broken down into manual Function API calling: 98 | ```go 99 | func main() { 100 | CB := OnClientPutInServer 101 | for i := 1; i<=MaxClients; i++ { 102 | CB(i) 103 | } 104 | } 105 | 106 | func OnClientPutInServer(client Entity) {} 107 | ``` 108 | Becomes: 109 | ```c 110 | public void OnPluginStart() { 111 | Function CB = OnClientPutInServer; 112 | for (int i = 1; i <= MaxClients; i++) { 113 | Call_StartFunction(null, CB); 114 | Call_PushCell(i); 115 | Call_Finish(); 116 | } 117 | } 118 | 119 | public void OnClientPutInServer(int client) {} 120 | ``` 121 | 122 | * Anonymous Functions (aka Function Literals) are supported: 123 | ```go 124 | my_timer := CreateTimer(2.0, func(timer Timer, data any) Action { 125 | return Plugin_Continue 126 | }, 0, TIMER_REPEAT) 127 | ``` 128 | ```sourcepawn 129 | /// SourcePawn 130 | Handle my_timer = CreateTimer(2.0, SrcGoFuncTemp1, 0, TIMER_REPEAT); 131 | ... 132 | public Action SrcGoFuncTemp1(Handle hTimer, any data) 133 | { 134 | return Plugin_Continue; 135 | } 136 | ``` 137 | 138 | * Inline SourcePawn code using the builtin function `__sp__` - for those parts of SourcePawn that just can't be generated (like using new or making a methodmap from scratch). 139 | 140 | `__sp__` only takes a single string of raw SourcePawn code. Optionally, you can also use a named string constant (it will be generated into the resulting code file, so keep that in mind.) 141 | ```go 142 | /// using raw string quotes here so that single & double quotes don't have to be escaped. 143 | var kv KeyValues 144 | __sp__(`kv = new KeyValues("key_value", "key", "val");`) 145 | 146 | ... 147 | __sp__(`delete kv;`) 148 | ``` 149 | 150 | * `make` for _making_ dynamically sized, local arrays: 151 | ```go 152 | my_str := make([]char, size) 153 | ``` 154 | becomes: 155 | ```c 156 | char[] my_str = new char[size]; 157 | ``` 158 | 159 | ### Planned Features 160 | * Generate Natives and Forwards with an include file for them. 161 | * Abstract, type-based syntax translation for higher data types like `StringMap` and `ArrayList`. 162 | * Handle-based Data Structures are abstracted into supportive syntax such where it's `value = Map["key"]` instead of `map.GetValue("key", value);` 163 | 164 | ### Goal 165 | Generate SourcePawn source code that is compileable by `spcomp` without having to modify/assist the generate source code. 166 | 167 | 168 | ## Contributing 169 | 170 | To submit a patch, file an issue and/or hit up a pull request. 171 | 172 | ## Help 173 | 174 | Command line options: 175 | * `--debug`, `-dbg` - prints the file's modified AST and pretty-printed version to a file for later checking. 176 | 177 | * `--force`, `-f` - forcefully generates a SourcePawn source code file, even if errors/issues occurred during transpilation. 178 | 179 | * `--help`, `-h` - Prints help list. 180 | 181 | * `--version` - Prints the version of SourceGo. 182 | 183 | * `--no-spcomp`, `-n` - Generates a SourcePawn source-code file without trying to invoke the SourcePawn compiler. 184 | 185 | * `--verbose`, `-v` - prints additional warnings. 186 | 187 | If you need help or have any question, simply file an issue with **\[HELP\]** in the title. 188 | 189 | 190 | ## Installation 191 | 192 | ### Requirements 193 | Latest Golang version. 194 | 195 | ## Credits 196 | 197 | * Nergal - main dev. 198 | 199 | ## License 200 | This project is licensed under MIT License. 201 | -------------------------------------------------------------------------------- /rewrite/srcgo/pass10_mutate_no_ret_calls.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Nirari Technologies. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 5 | * 6 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 9 | * 10 | */ 11 | 12 | package SrcGo 13 | 14 | 15 | import ( 16 | "fmt" 17 | "go/types" 18 | "go/ast" 19 | ///"go/token" 20 | ) 21 | 22 | type pass10Ctxt struct { 23 | currFunc *ast.FuncDecl 24 | transmit *AstTransmitter 25 | } 26 | 27 | func (a *AstTransmitter) MutateNoRetCalls(file *ast.File) { 28 | context := pass10Ctxt{ transmit: a } 29 | for _, decl := range file.Decls { 30 | switch d := decl.(type) { 31 | case *ast.FuncDecl: 32 | context.currFunc = d 33 | if d.Body != nil { 34 | MutateBlock(d.Body, MutateNoRetCallStmts, &context) 35 | } 36 | context.currFunc = nil 37 | } 38 | } 39 | } 40 | 41 | func MutateNoRetCallStmts(owner_list *[]ast.Stmt, index int, s ast.Stmt, bm BlockMutator, ctxt any) { 42 | switch n := s.(type) { 43 | case *ast.BlockStmt: 44 | bm(n, MutateNoRetCallStmts, ctxt) 45 | 46 | case *ast.ForStmt: 47 | if n.Init != nil { 48 | MutateNoRetCallStmts(owner_list, index, n.Init, bm, ctxt) 49 | } 50 | if n.Post != nil { 51 | MutateNoRetCallStmts(owner_list, index, n.Post, bm, ctxt) 52 | } 53 | bm(n.Body, MutateNoRetCallStmts, ctxt) 54 | 55 | case *ast.IfStmt: 56 | if n.Init != nil { 57 | MutateNoRetCallStmts(owner_list, index, n.Init, bm, ctxt) 58 | } 59 | bm(n.Body, MutateNoRetCallStmts, ctxt) 60 | if n.Else != nil { 61 | MutateNoRetCallStmts(owner_list, index, n.Else, bm, ctxt) 62 | } 63 | 64 | case *ast.SwitchStmt: 65 | MutateNoRetCallStmts(owner_list, index, n.Init, bm, ctxt) 66 | bm(n.Body, MutateNoRetCallStmts, ctxt) 67 | 68 | case *ast.CaseClause: 69 | for i, stmt := range n.Body { 70 | MutateNoRetCallStmts(&n.Body, i, stmt, bm, ctxt) 71 | } 72 | 73 | case *ast.RangeStmt: 74 | bm(n.Body, MutateNoRetCallStmts, ctxt) 75 | 76 | case *ast.ExprStmt: 77 | context := ctxt.(*pass10Ctxt) 78 | if fn, is_func_call := n.X.(*ast.CallExpr); is_func_call { 79 | if typ := context.transmit.TypeInfo.TypeOf(fn); typ != nil { 80 | switch t := typ.(type) { 81 | case *types.Tuple: 82 | extra_args := t.Len() 83 | if IsFuncPtr(fn, context.transmit.TypeInfo) { 84 | if extra_args > 1 { 85 | retvals := make([]ast.Expr, 0) 86 | rettypes := make([]types.Type, 0) 87 | for i := 0; i < extra_args; i++ { 88 | ret_tmp := ast.NewIdent(fmt.Sprintf("fptr_temp%d", context.transmit.TmpVar)) 89 | context.transmit.TmpVar++ 90 | declstmt := MakeVarDecl([]*ast.Ident{ret_tmp}, nil, t.At(i).Type(), context.transmit.TypeInfo) 91 | *owner_list = InsertToIndex[ast.Stmt](*owner_list, 0, declstmt) 92 | retvals, rettypes = append(retvals, ret_tmp), append(rettypes, t.At(i).Type()) 93 | } 94 | 95 | calls := ExpandFuncPtrCalls(fn, retvals, rettypes, context.transmit.TypeInfo, context.currFunc) 96 | for i := len(calls)-1; i > 0; i-- { 97 | *owner_list = InsertToIndex[ast.Stmt](*owner_list, FindStmt(*owner_list, n)+1, calls[i]) 98 | } 99 | n.X = calls[0].(*ast.ExprStmt).X 100 | } else { 101 | calls := ExpandFuncPtrCalls(fn, nil, nil, context.transmit.TypeInfo, context.currFunc) 102 | n.X = calls[0].(*ast.ExprStmt).X 103 | for i := len(calls)-1; i > 0; i-- { 104 | *owner_list = InsertToIndex[ast.Stmt](*owner_list, FindStmt(*owner_list, n)+1, calls[i]) 105 | } 106 | } 107 | } else { 108 | if extra_args > 1 { 109 | for i := 1; i < extra_args; i++ { 110 | ret_tmp := ast.NewIdent(fmt.Sprintf("fn_temp%d", context.transmit.TmpVar)) 111 | context.transmit.TmpVar++ 112 | declstmt := MakeVarDecl([]*ast.Ident{ret_tmp}, nil, t.At(i).Type(), context.transmit.TypeInfo) 113 | *owner_list = InsertToIndex[ast.Stmt](*owner_list, 0, declstmt) 114 | fn.Args = append(fn.Args, MakeReference(ret_tmp)) 115 | } 116 | } 117 | } 118 | 119 | default: 120 | if IsFuncPtr(fn, context.transmit.TypeInfo) { 121 | ret_tmp := ast.NewIdent(fmt.Sprintf("fptr_temp%d", context.transmit.TmpVar)) 122 | context.transmit.TmpVar++ 123 | declstmt := MakeVarDecl([]*ast.Ident{ret_tmp}, nil, t, context.transmit.TypeInfo) 124 | *owner_list = InsertToIndex[ast.Stmt](*owner_list, 0, declstmt) 125 | 126 | calls := ExpandFuncPtrCalls(fn, []ast.Expr{ret_tmp}, []types.Type{t}, context.transmit.TypeInfo, context.currFunc) 127 | n.X = calls[0].(*ast.ExprStmt).X 128 | for i := len(calls)-1; i > 0; i-- { 129 | *owner_list = InsertToIndex[ast.Stmt](*owner_list, FindStmt(*owner_list, n)+1, calls[i]) 130 | } 131 | } 132 | } 133 | } 134 | } 135 | } 136 | } -------------------------------------------------------------------------------- /sourcemod/keyvalues.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/keyvalues.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | type ( 18 | KvDataTypes int 19 | KeyValues struct { 20 | ExportLength int 21 | } 22 | ) 23 | 24 | const ( 25 | KvData_None = KvDataTypes(0) /**< Type could not be identified, or no type */ 26 | KvData_String /**< String value */ 27 | KvData_Int /**< Integer value */ 28 | KvData_Float /**< Floating point value */ 29 | KvData_Ptr /**< Pointer value (sometimes called "long") */ 30 | KvData_WString /**< Wide string value */ 31 | KvData_Color /**< Color value */ 32 | KvData_UInt64 /**< Large integer value */ 33 | /* --- */ 34 | KvData_NUMTYPES 35 | ) 36 | 37 | func CreateKeyValues(name, firstKey, firstValue string) KeyValues 38 | 39 | func (KeyValues) ExportToFile(file string) bool 40 | func (KeyValues) ExportToString(buffer []char, maxlength int) int 41 | func (KeyValues) ImportFromFile(file string) bool 42 | func (KeyValues) ImportFromString(buffer, resourceName string) bool 43 | func (KeyValues) Import(other KeyValues) 44 | 45 | func (KeyValues) SetString(key, value string) string 46 | func (KeyValues) SetNum(key string, value int) 47 | func (KeyValues) SetUInt64(key string, value [2]int) 48 | func (KeyValues) SetFloat(key string, value float) 49 | func (KeyValues) SetColor(key string, r, g, b, a int) 50 | func (KeyValues) SetColor4(key string, color [4]int) 51 | func (KeyValues) SetVector(key string, vec Vec3) 52 | 53 | func (KeyValues) GetString(key string, value []char, maxlength int, defvalue string) 54 | func (KeyValues) GetNum(key string, defvalue int) int 55 | func (KeyValues) GetFloat(key string, defvalue float) float 56 | func (KeyValues) GetColor(key string, r, g, b, a *int) 57 | func (KeyValues) GetColor4(key string, color *[4]int) 58 | func (KeyValues) GetUInt64(key string, value [2]int, defvalue [2]int) 59 | func (KeyValues) GetVector(key string, vec *Vec3, defvalue Vec3) 60 | 61 | func (KeyValues) JumpToKey(key string, create bool) bool 62 | func (KeyValues) JumpToKeySymbol(id int) bool 63 | func (KeyValues) GotoFirstSubKey(keyOnly bool) bool 64 | func (KeyValues) GotoNextKey(keyOnly bool) bool 65 | func (KeyValues) SavePosition() 66 | func (KeyValues) GoBack() bool 67 | func (KeyValues) DeleteKey(key string) bool 68 | func (KeyValues) DeleteThis() int 69 | func (KeyValues) Rewind() 70 | 71 | func (KeyValues) GetSectionName(section []char, maxlength int) bool 72 | func (KeyValues) SetSectionName(section string) 73 | func (KeyValues) GetDataType(key string) KvDataTypes 74 | func (KeyValues) SetEscapeSequences(useEscapes bool) 75 | func (KeyValues) NodesInStack() int 76 | func (KeyValues) FindKeyById(id int, name []char, maxlength int) bool 77 | func (KeyValues) GetNameSymbol(key string, id *int) bool 78 | func (KeyValues) GetSectionSymbol(id *int) bool 79 | 80 | func KvSetString(kv KeyValues, key, value string) 81 | func KvSetNum(kv KeyValues, key string, value int) 82 | func KvSetUInt64(kv KeyValues, key string, value [2]int) 83 | func KvSetFloat(kv KeyValues, key string, value float) 84 | func KvSetColor(kv KeyValues, key string, r, g, b, a int) 85 | func KvSetVector(kv KeyValues, key string, vec Vec3) 86 | 87 | func KvGetString(kv KeyValues, key string, value []char, maxlength int, defvalue string) 88 | func KvGetNum(kv KeyValues, key string, defvalue int) int 89 | func KvGetFloat(kv KeyValues, key string, defvalue float) float 90 | func KvGetColor(kv KeyValues, key string, r, g, b, a *int) 91 | func KvGetUInt64(kv KeyValues, key string, value [2]int, defvalue [2]int) 92 | func KvGetVector(kv KeyValues, key string, vec *Vec3, defvalue Vec3) 93 | 94 | func KvJumpToKey(kv KeyValues, key string, create bool) bool 95 | func KvJumpToKeySymbol(kv KeyValues, id int) bool 96 | func KvGotoFirstSubKey(kv KeyValues, keyOnly bool) bool 97 | func KvGotoNextKey(kv KeyValues, keyOnly bool) bool 98 | func KvSavePosition(kv KeyValues) 99 | func KvDeleteKey(kv KeyValues, key string) bool 100 | func KvDeleteThis(kv KeyValues) int 101 | func KvGoBack(kv KeyValues) bool 102 | func KvRewind(kv KeyValues) 103 | 104 | func KvGetSectionName(kv KeyValues, section []char, maxlength int) bool 105 | func KvSetSectionName(kv KeyValues, section string) 106 | func KvGetDataType(kv KeyValues, key string) KvDataTypes 107 | func KeyValuesToFile(kv KeyValues, file string) bool 108 | func FileToKeyValues(kv KeyValues, file string) bool 109 | func StringToKeyValues(kv KeyValues, buffer, resourceName string) bool 110 | func KvSetEscapeSequences(kv KeyValues, useEscapes bool) 111 | func KvNodesInStack(kv KeyValues) int 112 | func KvCopySubkeys(origin, dest KeyValues) 113 | func KvFindKeyById(kv KeyValues, id int, name []char, maxlength int) bool 114 | func KvGetNameSymbol(kv KeyValues, key string, id *int) bool 115 | func KvGetSectionSymbol(kv KeyValues, id *int) bool -------------------------------------------------------------------------------- /sourcemod.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | import ( 18 | "sourcemod/core" 19 | "sourcemod/floats" 20 | "sourcemod/vector" 21 | "sourcemod/strings" 22 | "sourcemod/handles" 23 | "sourcemod/functions" 24 | "sourcemod/files" 25 | "sourcemod/logging" 26 | "sourcemod/timers" 27 | "sourcemod/admin" 28 | "sourcemod/keyvalues" 29 | "sourcemod/dbi" 30 | "sourcemod/lang" 31 | "sourcemod/sorting" 32 | "sourcemod/textparse" 33 | "sourcemod/clients" 34 | "sourcemod/console" 35 | "sourcemod/convars" 36 | "sourcemod/events" 37 | "sourcemod/bitbuffer" 38 | "sourcemod/protobuf" 39 | "sourcemod/usermessages" 40 | "sourcemod/menus" 41 | "sourcemod/halflife" 42 | "sourcemod/adt_array" 43 | "sourcemod/adt_trie" 44 | "sourcemod/adt_stack" 45 | "sourcemod/banning" 46 | "sourcemod/commandfilters" 47 | "sourcemod/nextmap" 48 | "sourcemod/commandline" 49 | "sourcemod/helpers" 50 | "sourcemod/entity" 51 | "sourcemod/entity_prop_stocks" 52 | ) 53 | 54 | 55 | type APLRes int 56 | const ( 57 | APLRes_Success = APLRes(0) /**< Plugin should load */ 58 | APLRes_Failure /**< Plugin shouldn't load and should display an error */ 59 | APLRes_SilentFailure /**< Plugin shouldn't load but do so silently */ 60 | ) 61 | 62 | 63 | type GameData Handle 64 | 65 | func LoadGameConfigFile(file string) GameData 66 | func (GameData) GetOffset(key string) int 67 | func (GameData) GetKeyValue(key string, buffer []char, maxlen int) bool 68 | func (GameData) GetAddress(name string) Address 69 | 70 | 71 | func GetMyHandle() Handle 72 | func GetPluginIterator() Handle 73 | func MorePlugins(iter Handle) bool 74 | func ReadPlugin(iter Handle) Handle 75 | func GetPluginStatus(plugin Handle) PluginStatus 76 | func GetPluginFilename(plugin Handle, buffer []char, maxlength int) 77 | func IsPluginDebugging(plugin Handle) bool 78 | func GetPluginInfo(plugin Handle, info PluginInfo, buffer []char, maxlength int) bool 79 | func FindPluginByNumber(order_num int) Handle 80 | func SetFailState(state string, args ...any) 81 | func ThrowError(fmt string, args ...any) 82 | func LogStackTrace(fmt string, args ...any) 83 | func GetTime(bigStamp [2]int) int 84 | func FormatTime(buffer []char, maxlength int, format string, stamp int) 85 | func GetSysTickCount() int 86 | func AutoExecConfig(autoCreate bool, name, folder string) 87 | func RegPluginLibrary(name string) 88 | func LibraryExists(name string) bool 89 | func GetExtensionFileStatus(name string, err []char, maxlength int) int 90 | 91 | 92 | const ( 93 | MAPLIST_FLAG_MAPSFOLDER = (1<<0) /**< On failure, use all maps in the maps folder. */ 94 | MAPLIST_FLAG_CLEARARRAY = (1<<1) /**< If an input array is specified, clear it before adding. */ 95 | MAPLIST_FLAG_NO_DEFAULT = (1<<2) /**< Do not read "default" or "mapcyclefile" on failure. */ 96 | ) 97 | 98 | func ReadMapList(array ArrayList, serial *int, str string, flags int) ArrayList 99 | func SetMapListCompatBind(name, file string) 100 | 101 | 102 | type FeatureType int 103 | const ( 104 | /** 105 | * A native function call. 106 | */ 107 | FeatureType_Native = FeatureType(0) 108 | 109 | /** 110 | * A named capability. This is distinctly different from checking for a 111 | * native, because the underlying functionality could be enabled on-demand 112 | * to improve loading time. Thus a native may appear to exist, but it might 113 | * be part of a set of features that are not compatible with the current game 114 | * or version of SourceMod. 115 | */ 116 | FeatureType_Capability 117 | ) 118 | 119 | 120 | type FeatureStatus int 121 | const ( 122 | /** 123 | * Feature is available for use. 124 | */ 125 | FeatureStatus_Available = FeatureStatus(0) 126 | 127 | /** 128 | * Feature is not available. 129 | */ 130 | FeatureStatus_Unavailable 131 | 132 | /** 133 | * Feature is not known at all. 134 | */ 135 | FeatureStatus_Unknown 136 | ) 137 | 138 | func CanTestFeatures() bool 139 | func GetFeatureStatus(ftr_type FeatureType, name string) FeatureStatus 140 | func RequireFeature(ftr_type FeatureType, name, fmt string, args ...any) 141 | 142 | 143 | type NumberType int 144 | const ( 145 | NumberType_Int8 = NumberType(0) 146 | NumberType_Int16 147 | NumberType_Int32 148 | ) 149 | 150 | 151 | type Address int 152 | const Address_Null = Address(0) /// a typical invalid result when an address lookup fails 153 | 154 | func LoadFromAddress(addr Address, size NumberType) int 155 | func StoreToAddress(addr Address, data int, size NumberType) 156 | 157 | 158 | type FrameIterator struct { 159 | LineNumber int 160 | } 161 | 162 | func (FrameIterator) Next() bool 163 | func (FrameIterator) Reset() 164 | func (FrameIterator) GetFunctionName(buffer []char, maxlen int) 165 | func (FrameIterator) GetFilePath(buffer []char, maxlen int) -------------------------------------------------------------------------------- /rewrite/srcgo/pass2_name_anon_funcs.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Nirari Technologies. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 5 | * 6 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 9 | * 10 | */ 11 | 12 | package SrcGo 13 | 14 | 15 | import ( 16 | "fmt" 17 | "go/token" 18 | "go/ast" 19 | ) 20 | 21 | 22 | type passTwoCtxt struct { 23 | newDecls []ast.Decl 24 | tmpFunc uint 25 | } 26 | 27 | /* 28 | * Pass #2 - Name Anonymous Functions 29 | * Any unnamed function literal is to be named so they can be generated 30 | * as an incrementally named function in SourcePawn. 31 | * 32 | * This AST pass has to be second because we later 33 | * mutate the multi-return types for functions! 34 | * 35 | * So best get to naming the lambdas before things get really serious! 36 | */ 37 | func NameAnonFuncs(file *ast.File) { 38 | /** 39 | * Function Literals can be represented in different ways: 40 | * Assigned: 41 | * f := func(params){ 42 | * code 43 | * } 44 | * f(args) 45 | * 46 | * OR 47 | * Inline-Called: 48 | * func(params){ 49 | * code 50 | * }(args) 51 | */ 52 | context := passTwoCtxt{ newDecls: make([]ast.Decl, 0) } 53 | 54 | for _, decl := range file.Decls { 55 | context.newDecls = append(context.newDecls, decl) 56 | } 57 | 58 | for _, decl := range file.Decls { 59 | switch d := decl.(type) { 60 | case *ast.FuncDecl: 61 | if d.Body != nil { 62 | MutateBlock(d.Body, MutateFuncLit, &context) 63 | } 64 | } 65 | } 66 | if len(file.Decls) < len(context.newDecls) { 67 | file.Decls = context.newDecls 68 | } 69 | context.newDecls = nil 70 | } 71 | 72 | 73 | /// func(params){code}(args) => func _srcgo_func#(params){code} ... _srcgo_func#(args) 74 | func MutateFuncLit(owner_list *[]ast.Stmt, index int, s ast.Stmt, bm BlockMutator, ctxt any) { 75 | switch n := s.(type) { 76 | case *ast.BlockStmt: 77 | bm(n, MutateFuncLit, ctxt) 78 | 79 | case *ast.ForStmt: 80 | if n.Init != nil { 81 | MutateFuncLit(owner_list, index, n.Init, bm, ctxt) 82 | } 83 | if n.Cond != nil { 84 | MutateFuncLitExprs(&n.Cond, ctxt) 85 | } 86 | if n.Post != nil { 87 | MutateFuncLit(owner_list, index, n.Post, bm, ctxt) 88 | } 89 | bm(n.Body, MutateFuncLit, ctxt) 90 | 91 | case *ast.IfStmt: 92 | if n.Init != nil { 93 | MutateFuncLit(owner_list, index, n.Init, bm, ctxt) 94 | } 95 | MutateFuncLitExprs(&n.Cond, ctxt) 96 | bm(n.Body, MutateFuncLit, ctxt) 97 | if n.Else != nil { 98 | MutateFuncLit(owner_list, index, n.Else, bm, ctxt) 99 | } 100 | 101 | case *ast.SwitchStmt: 102 | MutateFuncLit(owner_list, index, n.Init, bm, ctxt) 103 | MutateFuncLitExprs(&n.Tag, ctxt) 104 | bm(n.Body, MutateFuncLit, ctxt) 105 | 106 | case *ast.CaseClause: 107 | for j := range n.List { 108 | MutateFuncLitExprs(&n.List[j], ctxt) 109 | } 110 | for i, stmt := range n.Body { 111 | MutateFuncLit(&n.Body, i, stmt, bm, ctxt) 112 | } 113 | 114 | case *ast.RangeStmt: 115 | MutateFuncLitExprs(&n.Key, ctxt) 116 | MutateFuncLitExprs(&n.Value, ctxt) 117 | MutateFuncLitExprs(&n.X, ctxt) 118 | bm(n.Body, MutateFuncLit, ctxt) 119 | 120 | case *ast.ExprStmt: 121 | MutateFuncLitExprs(&n.X, ctxt) 122 | 123 | case *ast.ReturnStmt: 124 | for i := range n.Results { 125 | MutateFuncLitExprs(&n.Results[i], ctxt) 126 | } 127 | 128 | case *ast.AssignStmt: 129 | for i := range n.Rhs { 130 | MutateFuncLitExprs(&n.Rhs[i], ctxt) 131 | } 132 | for i := range n.Lhs { 133 | MutateFuncLitExprs(&n.Lhs[i], ctxt) 134 | } 135 | 136 | case *ast.DeclStmt: 137 | g := n.Decl.(*ast.GenDecl) 138 | for _, d := range g.Specs { 139 | switch g.Tok { 140 | case token.CONST, token.VAR: 141 | v := d.(*ast.ValueSpec) 142 | for expr := range v.Values { 143 | MutateFuncLitExprs(&v.Values[expr], ctxt) 144 | } 145 | } 146 | } 147 | } 148 | } 149 | 150 | func MutateFuncLitExprs(e *ast.Expr, ctxt any) { 151 | if e==nil || *e == nil { 152 | return 153 | } 154 | switch n := (*e).(type) { 155 | case *ast.BinaryExpr: 156 | MutateFuncLitExprs(&n.X, ctxt) 157 | MutateFuncLitExprs(&n.Y, ctxt) 158 | 159 | case *ast.CallExpr: 160 | MutateFuncLitExprs(&n.Fun, ctxt) 161 | for i := range n.Args { 162 | MutateFuncLitExprs(&n.Args[i], ctxt) 163 | } 164 | 165 | case *ast.KeyValueExpr: 166 | MutateFuncLitExprs(&n.Key, ctxt) 167 | MutateFuncLitExprs(&n.Value, ctxt) 168 | 169 | case *ast.IndexExpr: 170 | MutateFuncLitExprs(&n.X, ctxt) 171 | MutateFuncLitExprs(&n.Index, ctxt) 172 | 173 | case *ast.UnaryExpr: 174 | MutateFuncLitExprs(&n.X, ctxt) 175 | 176 | case *ast.FuncLit: 177 | context := ctxt.(*passTwoCtxt) 178 | tmp_func_name := ast.NewIdent(fmt.Sprintf("srcGoAnonFunc%d", context.tmpFunc)) 179 | context.tmpFunc++ 180 | fn_decl := new(ast.FuncDecl) 181 | fn_decl.Name = tmp_func_name 182 | fn_decl.Type = n.Type 183 | n.Type = nil 184 | fn_decl.Body = n.Body 185 | n.Body = nil 186 | *e = tmp_func_name 187 | context.newDecls = append(context.newDecls, fn_decl) 188 | } 189 | } -------------------------------------------------------------------------------- /rewrite/srcgo/pass5_mutate_ret_exprs.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 Nirari Technologies. 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 5 | * 6 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | * 8 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 9 | * 10 | */ 11 | 12 | package SrcGo 13 | 14 | 15 | import ( 16 | "fmt" 17 | "strings" 18 | "go/types" 19 | "go/ast" 20 | ///"go/token" 21 | ) 22 | 23 | 24 | type pass5Ctxt struct { 25 | funcMap map[string]*ast.FuncDecl 26 | currFunc *ast.FuncDecl 27 | tyinfo *types.Info 28 | tmpVar uint 29 | } 30 | 31 | /* Case Studies of Returning statements to transform: 32 | * 33 | * return m3() /// func m3() (type, type, type) 34 | * 35 | * return int, float, m1() /// func m1() type 36 | */ 37 | func (a *AstTransmitter) MutateRetExprs(file *ast.File) { 38 | context := pass5Ctxt{ funcMap: CollectFuncNames(file), tyinfo: a.TypeInfo, tmpVar: a.TmpVar } 39 | for _, decl := range file.Decls { 40 | switch d := decl.(type) { 41 | case *ast.FuncDecl: 42 | context.currFunc = d 43 | if d.Body != nil { 44 | MutateBlock(d.Body, MutateRetStmts, &context) 45 | } 46 | context.currFunc = nil 47 | } 48 | } 49 | a.TmpVar = context.tmpVar 50 | } 51 | 52 | func MutateRetStmts(owner_list *[]ast.Stmt, index int, s ast.Stmt, bm BlockMutator, ctxt any) { 53 | switch n := s.(type) { 54 | case *ast.BlockStmt: 55 | bm(n, MutateRetStmts, ctxt) 56 | 57 | case *ast.ForStmt: 58 | if n.Init != nil { 59 | MutateRetStmts(owner_list, index, n.Init, bm, ctxt) 60 | } 61 | if n.Post != nil { 62 | MutateRetStmts(owner_list, index, n.Post, bm, ctxt) 63 | } 64 | bm(n.Body, MutateRetStmts, ctxt) 65 | 66 | case *ast.IfStmt: 67 | if n.Init != nil { 68 | MutateRetStmts(owner_list, index, n.Init, bm, ctxt) 69 | } 70 | bm(n.Body, MutateRetStmts, ctxt) 71 | if n.Else != nil { 72 | MutateRetStmts(owner_list, index, n.Else, bm, ctxt) 73 | } 74 | 75 | case *ast.ReturnStmt: 76 | index := func(a []ast.Stmt, x ast.Stmt) int { 77 | for i, n := range a { 78 | if x==n { 79 | return i 80 | } 81 | } 82 | return -1 83 | }(*owner_list, s) 84 | 85 | res_len := len(n.Results) 86 | func_calls := make([]*ast.CallExpr, 0) 87 | for i := range n.Results { 88 | switch call := n.Results[i].(type) { 89 | case *ast.CallExpr: 90 | func_calls = append(func_calls, call) 91 | default: 92 | func_calls = append(func_calls, nil) 93 | } 94 | } 95 | 96 | res := len(n.Results) 97 | context := ctxt.(*pass5Ctxt) 98 | for i:=1; i=0; i-- { 103 | *owner_list = InsertToIndex[ast.Stmt](*owner_list, index, calls[i]) 104 | } 105 | } else { 106 | ptr_deref := PtrizeExpr(ast.NewIdent(fmt.Sprintf("%s_param%d", context.currFunc.Name.Name, i))) 107 | assign := MakeAssign(false) 108 | assign.Lhs = append(assign.Lhs, ptr_deref) 109 | assign.Rhs = append(assign.Rhs, n.Results[i]) 110 | *owner_list = InsertToIndex[ast.Stmt](*owner_list, index, assign) 111 | index++ 112 | } 113 | } 114 | 115 | if res_len > 1 { 116 | n.Results = n.Results[:1] 117 | MutateRetStmts(owner_list, index, s, bm, ctxt) 118 | } else if res_len==1 { 119 | // check for function call. 120 | ast.Inspect(n.Results[0], func(node ast.Node) bool { 121 | if node != nil { 122 | switch call := node.(type) { 123 | case *ast.CallExpr: 124 | if IsFuncPtr(call.Fun, context.tyinfo) { 125 | ret_tmp := ast.NewIdent(fmt.Sprintf("fptr_temp%d", context.tmpVar)) 126 | context.tmpVar++ 127 | declstmt := MakeVarDecl([]*ast.Ident{ret_tmp}, n.Results[0], nil, context.tyinfo) 128 | calls := ExpandFuncPtrCalls(call, []ast.Expr{ret_tmp}, nil, context.tyinfo, context.currFunc) 129 | calls = InsertToIndex[ast.Stmt](calls, 0, declstmt) 130 | for i:=len(calls)-1; i>=0; i-- { 131 | *owner_list = InsertToIndex[ast.Stmt](*owner_list, index, calls[i]) 132 | } 133 | n.Results[0] = ret_tmp 134 | } else if fn, found := context.funcMap[GetFuncName(call.Fun)]; found { 135 | if arg_count, param_count := len(call.Args), len(fn.Type.Params.List); arg_count < param_count { 136 | for _, param := range context.currFunc.Type.Params.List { 137 | for _, name := range param.Names { 138 | if strings.HasPrefix(name.Name, context.currFunc.Name.Name + "_param") { 139 | call.Args = append(call.Args, name) 140 | } 141 | } 142 | } 143 | } 144 | } 145 | } 146 | } 147 | return true 148 | }) 149 | } 150 | 151 | case *ast.SwitchStmt: 152 | MutateRetStmts(owner_list, index, n.Init, bm, ctxt) 153 | bm(n.Body, MutateRetStmts, ctxt) 154 | 155 | case *ast.CaseClause: 156 | for i, stmt := range n.Body { 157 | MutateRetStmts(&n.Body, i, stmt, bm, ctxt) 158 | } 159 | 160 | case *ast.RangeStmt: 161 | bm(n.Body, MutateRetStmts, ctxt) 162 | } 163 | } -------------------------------------------------------------------------------- /sourcemod/entity.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/entity.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | type PropType int 18 | const ( 19 | Prop_Send = PropType(0) /**< This property is networked. */ 20 | Prop_Data = PropType(1) /**< This property is for save game data fields. */ 21 | ) 22 | 23 | 24 | const ( 25 | FL_EDICT_CHANGED = (1<<0) /**< Game DLL sets this when the entity state changes 26 | Mutually exclusive with FL_EDICT_PARTIAL_CHANGE. */ 27 | FL_EDICT_FREE = (1<<1) /**< this edict if free for reuse */ 28 | FL_EDICT_FULL = (1<<2) /**< this is a full server entity */ 29 | FL_EDICT_FULLCHECK = (0<<0) /**< call ShouldTransmit() each time, this is a fake flag */ 30 | FL_EDICT_ALWAYS = (1<<3) /**< always transmit this entity */ 31 | FL_EDICT_DONTSEND = (1<<4) /**< don't transmit this entity */ 32 | FL_EDICT_PVSCHECK = (1<<5) /**< always transmit entity, but cull against PVS */ 33 | FL_EDICT_PENDING_DORMANT_CHECK = (1<<6) 34 | FL_EDICT_DIRTY_PVS_INFORMATION = (1<<7) 35 | FL_FULL_EDICT_CHANGED = (1<<8) 36 | MAXENTS = 2048 37 | ) 38 | 39 | 40 | type PropFieldType int 41 | const ( 42 | PropField_Unsupported = PropFieldType(0) /**< The type is unsupported. */ 43 | PropField_Integer /**< Valid for SendProp and Data fields */ 44 | PropField_Float /**< Valid for SendProp and Data fields */ 45 | PropField_Entity /**< Valid for Data fields only (SendProp shows as int) */ 46 | PropField_Vector /**< Valid for SendProp and Data fields */ 47 | PropField_String /**< Valid for SendProp and Data fields */ 48 | PropField_String_T /**< Valid for Data fields. Read only. 49 | Note that the size of a string_t is dynamic, and 50 | thus FindDataMapOffs() will return the constant size 51 | of the string_t container (which is 32 bits right now). */ 52 | PropField_Variant /**< Valid for Data fields only Type is not known at the field level, 53 | (for this call), but dependent on current field value. */ 54 | ) 55 | 56 | 57 | func GetMaxEntities() int 58 | func GetEntityCount() int 59 | func IsValidEntity(entity Entity) bool 60 | func IsValidEdict(edict int) bool 61 | func IsEntNetworkable(entity Entity) bool 62 | func CreateEdict() Entity 63 | func RemoveEdict(edict int) 64 | func RemoveEntity(entity Entity) 65 | func GetEdictFlags(edict int) int 66 | func SetEdictFlags(edict, flags int) 67 | func GetEdictClassname(edict int, clsname []char, maxlength int) bool 68 | func GetEntityNetClass(edict int, clsname []char, maxlength int) bool 69 | func ChangeEdictState(edict, offset int) 70 | func GetEntData(entity, offset, size int) int 71 | func SetEntData(entity, offset int, value any, size int, changeState bool) 72 | func GetEntDataFloat(entity, offset int) float 73 | func SetEntDataFloat(entity, offset int, value float, changeState bool) 74 | func GetEntDataEnt2(entity, offset int) Entity 75 | func SetEntDataEnt2(entity, offset, other int, changeState bool) 76 | func GetEntDataVector(entity, offset int, vec *Vec3) 77 | func SetEntDataVector(entity, offset int, vec Vec3, changeState bool) 78 | func GetEntDataString(entity, offset int, buffer []char, maxlen int) int 79 | func SetEntDataString(entity, offset int, buffer string, maxlen int, changeState bool) int 80 | func FindSendPropInfo(cls, prop string, fieldtype *PropFieldType, num_bits, local_offset *int) int 81 | func FindDataMapInfo(entity Entity, prop string, fieldtype *PropFieldType, num_bits, local_offset *int) int 82 | func GetEntSendPropOffs(entity Entity, prop string, actual bool) int 83 | func HasEntProp(entity Entity, prop_type PropType, prop string) bool 84 | func GetEntProp(entity Entity, prop_type PropType, prop string, size, element int) int 85 | func SetEntProp(entity Entity, prop_type PropType, prop string, value any, size, element int) 86 | func GetEntPropFloat(entity Entity, prop_type PropType, prop string, element int) float 87 | func SetEntPropFloat(entity Entity, prop_type PropType, prop string, value float, element int) 88 | func GetEntPropEnt(entity Entity, prop_type PropType, prop string, element int) Entity 89 | func SetEntPropEnt(entity Entity, prop_type PropType, prop string, other Entity, element int) 90 | func GetEntPropVector(entity Entity, prop_type PropType, prop string, vec *Vec3, element int) 91 | func SetEntPropVector(entity Entity, prop_type PropType, prop string, vec Vec3, element int) 92 | func GetEntPropString(entity Entity, prop_type PropType, prop string, buffer []char, maxlen, element int) int 93 | func SetEntPropString(entity Entity, prop_type PropType, prop, buffer string, element int) int 94 | func GetEntPropArraySize(entity Entity, prop_type PropType, prop string) int 95 | func GetEntDataArray(entity, offset int, array []int, arraySize, dataSize int) 96 | func SetEntDataArray(entity, offset int, array []int, arraySize, dataSize int, changeState bool) 97 | func GetEntityAddress(entity Entity) Address 98 | func GetEntityClassname(entity Entity, clsname []char, maxlength int) bool -------------------------------------------------------------------------------- /test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "sourcemod" 5 | "sdktools" 6 | ) 7 | 8 | 9 | var ( 10 | myself = Plugin{ 11 | name: "SrcGo Plugin", 12 | author: "Nergal", 13 | description: "Plugin made into SP from SrcGo.", 14 | version: "1.0a", 15 | url: "https://github.com/assyrianic/Go2SourcePawn", 16 | } 17 | str_array = [...]string{ 18 | "kek", 19 | "foo", 20 | "bar", 21 | "bazz", 22 | } 23 | ) 24 | 25 | const ( 26 | a, b = "A", MAXPLAYERS 27 | c = a 28 | d string = "D" 29 | e = "e1" 30 | f = 1.00 31 | MakeStrMap = "StringMap smap = new StringMap();" 32 | ) 33 | 34 | type ( 35 | Point struct{ x, y float } 36 | QAngle = Vec3 37 | Name = [64]char 38 | Color = [0x4]int 39 | 40 | PlayerInfo struct { 41 | Origin Vec3 42 | Angle QAngle 43 | Weaps [3]Entity 44 | PutInServer func(client Entity) 45 | } 46 | 47 | ClientInfo struct { 48 | Clients [2][MAXPLAYERS+1]Entity 49 | } 50 | 51 | Kektus func(i, x Vec3, b string, blocks *Name, KC *int) Handle 52 | EventFunc func(event *Event, name string, dontBroadcast bool) Action 53 | VecFunc func(vec Vec3) (float, float, float) 54 | ) 55 | 56 | func (pi PlayerInfo) GetOrigin(buffer *Vec3) (float,float,float) { 57 | *buffer = pi.Origin 58 | return pi.Origin[0], pi.Origin[1], pi.Origin[2] 59 | } 60 | 61 | func TestOrigin() (float, float, float) { 62 | var ( 63 | pi PlayerInfo 64 | o Vec3 65 | ) 66 | return pi.GetOrigin(&o) 67 | } 68 | 69 | var ( 70 | ff1 func() int 71 | ff2 func() int 72 | ff3 func() float 73 | ) 74 | 75 | func FF1() int 76 | func FF2() int 77 | func FF3() float 78 | func FF4() (int, int, float) 79 | 80 | func GG1() (int, int, float) { 81 | return FF1(), FF2(), FF3() 82 | } 83 | func GG2() (int, int, float) { 84 | return ff1(), ff2(), ff3() 85 | } 86 | func GG3() (int, int, float) { 87 | return FF4() 88 | } 89 | 90 | func main() { 91 | var cinfo ClientInfo 92 | for _, p1 := range cinfo.Clients { 93 | for _, x1 := range p1 { 94 | is_in_game := IsClientInGame(x1) 95 | } 96 | } 97 | 98 | var p PlayerInfo 99 | var origin Vec3 100 | x,y,z := p.GetOrigin(&origin) 101 | 102 | var k,l int 103 | k &^= l 104 | 105 | CB := IndirectMultiRet 106 | p.PutInServer = func(client Entity) { 107 | } 108 | for i := 1; i<=MaxClients; i++ { 109 | p.PutInServer(i) 110 | CB() 111 | j,k,l := CB() 112 | } 113 | 114 | for f := 2.0; f < 100.0; f = Pow(f, 2.0) { 115 | PrintToServer("%0.2f", f) 116 | } 117 | 118 | my_timer := CreateTimer(0.1, func(timer Timer, data any) Action { 119 | return Plugin_Continue 120 | }, 0, 0) 121 | 122 | inlined_call_res := func(a,b int) int { 123 | return a + b 124 | }(1, 2) 125 | 126 | inlined_call_res1, inlined_call_res2 := func(a,b int) (int,int) { 127 | return a + b, a*b 128 | }(1, 2) 129 | 130 | caller := func(a,b int) int { 131 | return a + b 132 | } 133 | //n := caller(1, 2) 134 | __sp__(` 135 | int n; 136 | Call_StartFunction(null, caller); 137 | Call_PushCell(1); Call_PushCell(2); 138 | Call_Finish(n);`) 139 | 140 | var kv KeyValues 141 | /// using raw string quotes so we don't have to escape double quotes. 142 | __sp__(`kv = new KeyValues("kek1", "kek_key", "kek_val"); 143 | delete kv;`) 144 | 145 | AddMultiTargetFilter("@!party", func(pattern string, clients ArrayList) bool { 146 | non := StrContains(pattern, "!", false) != -1 147 | for i:=MAX_TF_PLAYERS; i > 0; i-- { 148 | __sp__(`if( IsClientValid(i) && clients.FindValue(i) == -1 ) { 149 | if( g_cvars.enabled.BoolValue && g_dnd.IsGameMaster(i) ) { 150 | if( !non ) { 151 | clients.Push(i); 152 | } 153 | } else if( non ) { 154 | clients.Push(i); 155 | } 156 | }`) 157 | } 158 | return true 159 | }, "The D&D Quest Party", false) 160 | 161 | __sp__(MakeStrMap) 162 | 163 | new_str := make([]char, 100) 164 | new_kek := make([]int, inlined_call_res) 165 | } 166 | 167 | func IndirectMultiRet() (bool, bool, bool) { 168 | return MultiRetFn() 169 | } 170 | 171 | func MultiRetFn() (bool, bool, bool) { 172 | return true, false, true 173 | } 174 | 175 | func OnClientPutInServer(client Entity) { 176 | } 177 | 178 | func GetProjPosToScreen(client int, vecDelta Vec3) (xpos, ypos float) { 179 | var playerAngles, vecforward, right, up Vec3 180 | GetClientEyeAngles(client, playerAngles) 181 | 182 | up[2] = 1.0 183 | GetAngleVectors(playerAngles, &vecforward, &NULL_VECTOR, &NULL_VECTOR) 184 | vecforward[2] = 0.0 185 | 186 | NormalizeVector(vecforward, &vecforward) 187 | GetVectorCrossProduct(up, vecforward, &right) 188 | 189 | front, side := GetVectorDotProduct(vecDelta, vecforward), GetVectorDotProduct(vecDelta, right) 190 | 191 | xpos, ypos = 360.0 * -front, 360.0 * -side 192 | flRotation := (ArcTangent2(xpos, ypos) + FLOAT_PI) * (57.29577951) 193 | yawRadians := -flRotation * 0.017453293 194 | 195 | /// Rotate it around the circle 196 | xpos, ypos = ( 500 + (360.0 * Cosine(yawRadians)) ) / 1000.0, ( 500 - (360.0 * Sine(yawRadians)) ) / 1000.0 197 | return 198 | } 199 | 200 | func KeyValuesToStringMap(kv KeyValues, stringmap StringMap, hide_top bool, depth int, prefix *[]char) { 201 | type SectStr = [128]char 202 | for { 203 | var section_name SectStr 204 | kv.GetSectionName(section_name, len(section_name)) 205 | if kv.GotoFirstSubKey(false) { 206 | var new_prefix SectStr 207 | switch { 208 | case depth==0 && hide_top: 209 | new_prefix = "" 210 | case prefix[0] == 0: 211 | new_prefix = section_name 212 | default: 213 | FormatEx(new_prefix, len(new_prefix), "%s.%s", prefix, section_name) 214 | } 215 | KeyValuesToStringMap(kv, stringmap, hide_top, depth+1, new_prefix) 216 | kv.GoBack() 217 | } else { 218 | if kv.GetDataType(NULL_STRING) != KvData_None { 219 | var key SectStr 220 | if prefix[0] == 0 { 221 | key = section_name 222 | } else { 223 | FormatEx(key, len(key), "%s.%s", prefix, section_name) 224 | } 225 | 226 | // lowercaseify the key 227 | keylen := strlen(key) 228 | for i := 0; i < keylen; i++ { 229 | bytes := IsCharMB(key[i]) 230 | if bytes==0 { 231 | key[i] = CharToLower(key[i]) 232 | } else { 233 | i += (bytes - 1) 234 | } 235 | } 236 | 237 | var value SectStr 238 | kv.GetString(NULL_STRING, value, len(value), NULL_STRING) 239 | stringmap.SetValue(key, value) 240 | } 241 | } 242 | 243 | if !kv.GotoNextKey(false) { 244 | break 245 | } 246 | } 247 | } 248 | 249 | func GetQueryRes(dbr DBResultSet) (int, float) { 250 | return dbr.FetchInt(0, nil), dbr.FetchFloat(1, nil) 251 | } 252 | -------------------------------------------------------------------------------- /sdkhooks.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sdkhooks.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | import "sourcemod/types" 17 | 18 | const ( 19 | DMG_GENERIC = 0 /**< generic damage was done */ 20 | DMG_CRUSH = (1 << 0) /**< crushed by falling or moving object. 21 | NOTE: It's assumed crush damage is occurring as a result of physics collision, 22 | so no extra physics force is generated by crush damage. 23 | DON'T use DMG_CRUSH when damaging entities unless it's the result of a physics 24 | collision. You probably want DMG_CLUB instead. */ 25 | DMG_BULLET = (1 << 1) /**< shot */ 26 | DMG_SLASH = (1 << 2) /**< cut, clawed, stabbed */ 27 | DMG_BURN = (1 << 3) /**< heat burned */ 28 | DMG_VEHICLE = (1 << 4) /**< hit by a vehicle */ 29 | DMG_FALL = (1 << 5) /**< fell too far */ 30 | DMG_BLAST = (1 << 6) /**< explosive blast damage */ 31 | DMG_CLUB = (1 << 7) /**< crowbar, punch, headbutt */ 32 | DMG_SHOCK = (1 << 8) /**< electric shock */ 33 | DMG_SONIC = (1 << 9) /**< sound pulse shockwave */ 34 | DMG_ENERGYBEAM = (1 << 10) /**< laser or other high energy beam */ 35 | DMG_PREVENT_PHYSICS_FORCE = (1 << 11) /**< Prevent a physics force */ 36 | DMG_NEVERGIB = (1 << 12) /**< with this bit OR'd in, no damage type will be able to gib victims upon death */ 37 | DMG_ALWAYSGIB = (1 << 13) /**< with this bit OR'd in, any damage type can be made to gib victims upon death. */ 38 | DMG_DROWN = (1 << 14) /**< Drowning */ 39 | DMG_PARALYZE = (1 << 15) /**< slows affected creature down */ 40 | DMG_NERVEGAS = (1 << 16) /**< nerve toxins, very bad */ 41 | DMG_POISON = (1 << 17) /**< blood poisoning - heals over time like drowning damage */ 42 | DMG_RADIATION = (1 << 18) /**< radiation exposure */ 43 | DMG_DROWNRECOVER = (1 << 19) /**< drowning recovery */ 44 | DMG_ACID = (1 << 20) /**< toxic chemicals or acid burns */ 45 | DMG_SLOWBURN = (1 << 21) /**< in an oven */ 46 | DMG_REMOVENORAGDOLL = (1 << 22) /**< with this bit OR'd in, no ragdoll will be created, and the target will be quietly removed. 47 | use this to kill an entity that you've already got a server-side ragdoll for */ 48 | DMG_PHYSGUN = (1 << 23) /**< Hit by manipulator. Usually doesn't do any damage. */ 49 | DMG_PLASMA = (1 << 24) /**< Shot by Cremator */ 50 | DMG_AIRBOAT = (1 << 25) /**< Hit by the airboat's gun */ 51 | DMG_DISSOLVE = (1 << 26) /**< Dissolving! */ 52 | DMG_BLAST_SURFACE = (1 << 27) /**< A blast on the surface of water that cannot harm things underwater */ 53 | DMG_DIRECT = (1 << 28) 54 | DMG_BUCKSHOT = (1 << 29) /**< not quite a bullet. Little, rounder, different. */ 55 | 56 | DMG_CRIT = DMG_ACID 57 | DMG_RADIUS_MAX = DMG_ENERGYBEAM 58 | DMG_NOCLOSEDISTANCEMOD = DMG_POISON 59 | DMG_HALF_FALLOFF = DMG_RADIATION 60 | DMG_USEDISTANCEMOD = DMG_SLOWBURN 61 | DMG_IGNITE = DMG_PLASMA 62 | DMG_USE_HITLOCATIONS = DMG_AIRBOAT 63 | ) 64 | 65 | 66 | type SDKHookType int 67 | const ( 68 | SDKHook_EndTouch = SDKHookType(0) 69 | SDKHook_FireBulletsPost 70 | SDKHook_OnTakeDamage 71 | SDKHook_OnTakeDamagePost 72 | SDKHook_PreThink 73 | SDKHook_PostThink 74 | SDKHook_SetTransmit 75 | SDKHook_Spawn 76 | SDKHook_StartTouch 77 | SDKHook_Think 78 | SDKHook_Touch 79 | SDKHook_TraceAttack 80 | SDKHook_TraceAttackPost 81 | SDKHook_WeaponCanSwitchTo 82 | SDKHook_WeaponCanUse 83 | SDKHook_WeaponDrop 84 | SDKHook_WeaponEquip 85 | SDKHook_WeaponSwitch 86 | SDKHook_ShouldCollide 87 | SDKHook_PreThinkPost 88 | SDKHook_PostThinkPost 89 | SDKHook_ThinkPost 90 | SDKHook_EndTouchPost 91 | SDKHook_GroundEntChangedPost 92 | SDKHook_SpawnPost 93 | SDKHook_StartTouchPost 94 | SDKHook_TouchPost 95 | SDKHook_VPhysicsUpdate 96 | SDKHook_VPhysicsUpdatePost 97 | SDKHook_WeaponCanSwitchToPost 98 | SDKHook_WeaponCanUsePost 99 | SDKHook_WeaponDropPost 100 | SDKHook_WeaponEquipPost 101 | SDKHook_WeaponSwitchPost 102 | SDKHook_Use 103 | SDKHook_UsePost 104 | SDKHook_Reload 105 | SDKHook_ReloadPost 106 | SDKHook_GetMaxHealth /**< ep2v and later */ 107 | SDKHook_Blocked 108 | SDKHook_BlockedPost 109 | SDKHook_OnTakeDamageAlive 110 | SDKHook_OnTakeDamageAlivePost 111 | SDKHook_CanBeAutobalanced 112 | ) 113 | 114 | 115 | type UseType int 116 | const ( 117 | Use_Off = UseType(0) 118 | Use_On 119 | Use_Set 120 | Use_Toggle 121 | ) 122 | 123 | 124 | func SDKHook(entity Entity, hook SDKHookType, callback any) 125 | func SDKHookEx(entity Entity, hook SDKHookType, callback any) bool 126 | 127 | func SDKUnhook(entity Entity, hook SDKHookType, callback any) 128 | func SDKUnhookEx(entity Entity, hook SDKHookType, callback any) bool 129 | 130 | func SDKHooks_TakeDamage(entity, inflictor, attacker Entity, damage float, damageType, weapon int, damageForce, damagePosition Vec3) 131 | 132 | func SDKHooks_DropWeapon(client, weapon Entity, vecTarget, vecVelocity Vec3) -------------------------------------------------------------------------------- /cstrike.go: -------------------------------------------------------------------------------- 1 | /** 2 | * cstrike.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | import "sourcemod" 17 | 18 | 19 | type ( 20 | CSRoundEndReason int 21 | CSWeaponID int 22 | ) 23 | 24 | const ( 25 | CS_TEAM_NONE = 0 /**< No team yet. */ 26 | CS_TEAM_SPECTATOR = 1 /**< Spectators. */ 27 | CS_TEAM_T = 2 /**< Terrorists. */ 28 | CS_TEAM_CT = 3 /**< Counter-Terrorists. */ 29 | 30 | CS_SLOT_PRIMARY = 0 /**< Primary weapon slot. */ 31 | CS_SLOT_SECONDARY = 1 /**< Secondary weapon slot. */ 32 | CS_SLOT_KNIFE = 2 /**< Knife slot. */ 33 | CS_SLOT_GRENADE = 3 /**< Grenade slot (will only return one grenade). */ 34 | CS_SLOT_C4 = 4 /**< C4 slot. */ 35 | 36 | CS_DMG_HEADSHOT = (1 << 30) /**< Headshot */ 37 | 38 | 39 | CSRoundEnd_TargetBombed = CSRoundEndReason(0) /**< Target Successfully Bombed! */ 40 | CSRoundEnd_VIPEscaped /**< The VIP has escaped! - Doesn't exist on CS:GO */ 41 | CSRoundEnd_VIPKilled /**< VIP has been assassinated! - Doesn't exist on CS:GO */ 42 | CSRoundEnd_TerroristsEscaped /**< The terrorists have escaped! */ 43 | CSRoundEnd_CTStoppedEscape /**< The CTs have prevented most of the terrorists from escaping! */ 44 | CSRoundEnd_TerroristsStopped /**< Escaping terrorists have all been neutralized! */ 45 | CSRoundEnd_BombDefused /**< The bomb has been defused! */ 46 | CSRoundEnd_CTWin /**< Counter-Terrorists Win! */ 47 | CSRoundEnd_TerroristWin /**< Terrorists Win! */ 48 | CSRoundEnd_Draw /**< Round Draw! */ 49 | CSRoundEnd_HostagesRescued /**< All Hostages have been rescued! */ 50 | CSRoundEnd_TargetSaved /**< Target has been saved! */ 51 | CSRoundEnd_HostagesNotRescued /**< Hostages have not been rescued! */ 52 | CSRoundEnd_TerroristsNotEscaped /**< Terrorists have not escaped! */ 53 | CSRoundEnd_VIPNotEscaped /**< VIP has not escaped! - Doesn't exist on CS:GO */ 54 | CSRoundEnd_GameStart /**< Game Commencing! */ 55 | 56 | // The below only exist on CS:GO 57 | CSRoundEnd_TerroristsSurrender /**< Terrorists Surrender */ 58 | CSRoundEnd_CTSurrender /**< CTs Surrender */ 59 | CSRoundEnd_TerroristsPlanted /**< Terrorists Planted the bomb */ 60 | CSRoundEnd_CTsReachedHostage /**< CTs Reached the hostage */ 61 | 62 | 63 | CSWeapon_NONE = CSWeaponID(0) 64 | CSWeapon_P228 65 | CSWeapon_GLOCK 66 | CSWeapon_SCOUT 67 | CSWeapon_HEGRENADE 68 | CSWeapon_XM1014 69 | CSWeapon_C4 70 | CSWeapon_MAC10 71 | CSWeapon_AUG 72 | CSWeapon_SMOKEGRENADE 73 | CSWeapon_ELITE 74 | CSWeapon_FIVESEVEN 75 | CSWeapon_UMP45 76 | CSWeapon_SG550 77 | CSWeapon_GALIL 78 | CSWeapon_FAMAS 79 | CSWeapon_USP 80 | CSWeapon_AWP 81 | CSWeapon_MP5NAVY 82 | CSWeapon_M249 83 | CSWeapon_M3 84 | CSWeapon_M4A1 85 | CSWeapon_TMP 86 | CSWeapon_G3SG1 87 | CSWeapon_FLASHBANG 88 | CSWeapon_DEAGLE 89 | CSWeapon_SG552 90 | CSWeapon_AK47 91 | CSWeapon_KNIFE 92 | CSWeapon_P90 93 | CSWeapon_SHIELD 94 | CSWeapon_KEVLAR 95 | CSWeapon_ASSAULTSUIT 96 | CSWeapon_NIGHTVISION //Anything below is CS:GO ONLY 97 | CSWeapon_GALILAR 98 | CSWeapon_BIZON 99 | CSWeapon_MAG7 100 | CSWeapon_NEGEV 101 | CSWeapon_SAWEDOFF 102 | CSWeapon_TEC9 103 | CSWeapon_TASER 104 | CSWeapon_HKP2000 105 | CSWeapon_MP7 106 | CSWeapon_MP9 107 | CSWeapon_NOVA 108 | CSWeapon_P250 109 | CSWeapon_SCAR17 110 | CSWeapon_SCAR20 111 | CSWeapon_SG556 112 | CSWeapon_SSG08 113 | CSWeapon_KNIFE_GG 114 | CSWeapon_MOLOTOV 115 | CSWeapon_DECOY 116 | CSWeapon_INCGRENADE 117 | CSWeapon_DEFUSER 118 | CSWeapon_HEAVYASSAULTSUIT 119 | //The rest are actual item definition indexes for CS:GO 120 | CSWeapon_CUTTERS = 56 121 | CSWeapon_HEALTHSHOT = 57 122 | CSWeapon_KNIFE_T = 59 123 | CSWeapon_M4A1_SILENCER = 60 124 | CSWeapon_USP_SILENCER = 61 125 | CSWeapon_CZ75A = 63 126 | CSWeapon_REVOLVER = 64 127 | CSWeapon_TAGGRENADE = 68 128 | CSWeapon_FISTS = 69 129 | CSWeapon_BREACHCHARGE = 70 130 | CSWeapon_TABLET = 72 131 | CSWeapon_MELEE = 74 132 | CSWeapon_AXE = 75 133 | CSWeapon_HAMMER = 76 134 | CSWeapon_SPANNER = 78 135 | CSWeapon_KNIFE_GHOST = 80 136 | CSWeapon_FIREBOMB = 81 137 | CSWeapon_DIVERSION = 82 138 | CSWeapon_FRAGGRENADE = 83 139 | CSWeapon_SNOWBALL = 84 140 | CSWeapon_BUMPMINE = 85 141 | CSWeapon_MAX_WEAPONS_NO_KNIFES // Max without the knife item defs useful when treating all knives as a regular knife. 142 | CSWeapon_BAYONET = 500 143 | CSWeapon_KNIFE_FLIP = 505 144 | CSWeapon_KNIFE_GUT = 506 145 | CSWeapon_KNIFE_KARAMBIT = 507 146 | CSWeapon_KNIFE_M9_BAYONET = 508 147 | CSWeapon_KNIFE_TATICAL = 509 148 | CSWeapon_KNIFE_FALCHION = 512 149 | CSWeapon_KNIFE_SURVIVAL_BOWIE = 514 150 | CSWeapon_KNIFE_BUTTERFLY = 515 151 | CSWeapon_KNIFE_PUSH = 516 152 | CSWeapon_KNIFE_URSUS = 519 153 | CSWeapon_KNIFE_GYPSY_JACKKNIFE = 520 154 | CSWeapon_KNIFE_STILETTO = 522 155 | CSWeapon_KNIFE_WIDOWMAKER = 523 156 | CSWeapon_MAX_WEAPONS // THIS MUST BE LAST EASY WAY TO CREATE LOOPS. When looping do CS_IsValidWeaponID(i) to check. 157 | ) 158 | 159 | func CS_RespawnPlayer(client Entity) 160 | func CS_SwitchTeam(client, team int) 161 | func CS_DropWeapon(client, weaponIndex Entity, toss, blockhook bool) 162 | func CS_TerminateRound(delay float, reason CSRoundEndReason, blockhook bool) 163 | func CS_GetTranslatedWeaponAlias(alias string, weapon []char, size int) 164 | func CS_GetWeaponPrice(client Entity, id CSWeaponID, defaultprice bool) int 165 | func CS_GetClientClanTag(client Entity, buffer []char, size int) int 166 | func CS_SetClientClanTag(client Entity, tag string) 167 | func CS_GetTeamScore(team int) int 168 | func CS_SetTeamScore(team, value int) 169 | func CS_GetMVPCount(client Entity) int 170 | func CS_SetMVPCount(client, value int) 171 | func CS_GetClientContributionScore(client Entity) int 172 | func CS_SetClientContributionScore(client, value int) 173 | func CS_GetClientAssists(client int) int 174 | func CS_SetClientAssists(client, value int) 175 | func CS_AliasToWeaponID(alias string) CSWeaponID 176 | func CS_WeaponIDToAlias(id CSWeaponID, destination []char, maxlen int) int 177 | func CS_IsValidWeaponID(id CSWeaponID) bool 178 | func CS_UpdateClientModel(client int) 179 | func CS_ItemDefIndexToID(defindex int) CSWeaponID 180 | func CS_WeaponIDToItemDefIndex(id CSWeaponID) int -------------------------------------------------------------------------------- /sourcemod/dbi.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/dbi.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | 17 | type DBResult int 18 | const ( 19 | DBVal_Error = DBResult(0) /**< Column number/field is invalid. */ 20 | DBVal_TypeMismatch = 1 /**< You cannot retrieve this data with this type. */ 21 | DBVal_Null = 2 /**< Field has no data (NULL) */ 22 | DBVal_Data = 3 /**< Field has data */ 23 | ) 24 | 25 | type DBBindType int 26 | const ( 27 | DBBind_Int = DBResult(0) /**< Bind an integer. */ 28 | DBBind_Float = DBResult(1) /**< Bind a float. */ 29 | DBBind_String = DBResult(2) /**< Bind a string. */ 30 | ) 31 | 32 | type DBPriority int 33 | const ( 34 | DBPrio_High = DBPriority(0) /**< High priority. */ 35 | DBPrio_Normal = DBPriority(1) /**< Normal priority. */ 36 | DBPrio_Low = DBPriority(2) /**< Low priority. */ 37 | ) 38 | 39 | type DBDriver Handle 40 | /** 41 | * func static Find(name string) DBDriver 42 | * __sp__(`DBDriver db = DBDriver.Find(name);`) 43 | */ 44 | func (DBDriver) GetIdentifier(ident []char, maxlength int) 45 | func (DBDriver) GetProduct(ident []char, maxlength int) 46 | 47 | 48 | type DBResultSet struct { 49 | RowCount, FieldCount, AffectedRows, InsertId int 50 | HasResults, MoreRows bool 51 | } 52 | 53 | func (DBResultSet) FetchMoreResults() bool 54 | func (DBResultSet) FieldNumToName(field int, name []char, maxlength int) 55 | func (DBResultSet) FieldNameToNum(name string, field *int) bool 56 | func (DBResultSet) FetchRow() bool 57 | func (DBResultSet) Rewind() bool 58 | func (DBResultSet) FetchString(field int, name []char, maxlength int, result *DBResult) int 59 | func (DBResultSet) FetchFloat(field int, result *DBResult) float 60 | func (DBResultSet) FetchInt(field int, result *DBResult) int 61 | func (DBResultSet) IsFieldNull(field int) bool 62 | func (DBResultSet) FetchSize(field int) int 63 | 64 | 65 | type ( 66 | SQLTxnSuccess func(db Database, data any, numQueries int, results []DBResultSet, queryData []any) 67 | SQLTxnFailure func(db Database, data any, numQueries int, err string, failIndex int, queryData []any) 68 | ) 69 | 70 | type Transaction Handle 71 | /// public native Transaction(); 72 | /// __sp__(`transact = new Transaction();`) 73 | 74 | func (t Transaction) AddQuery(query string, data any) int 75 | 76 | 77 | type DBStatement Handle 78 | func (DBStatement) BindInt(param, number int, signed bool) 79 | func (DBStatement) BindFloat(param int, value float) 80 | func (DBStatement) BindString(param int, value string, copy bool) 81 | 82 | 83 | type ( 84 | SQLConnectCallback func(db Database, err string, data any) 85 | SQLQueryCallback func(db Database, results DBResultSet, err string, data any) 86 | 87 | /// static func Connect(callback SQLConnectCallback, name="default" string, data=0 any) 88 | Database struct { 89 | Driver DBDriver 90 | } 91 | ) 92 | 93 | func (Database) SetCharset(charset string) bool 94 | func (Database) Escape(str string, buffer []char, maxlength int, written *int) bool 95 | func (Database) Format(buffer string, maxlength int, format string, fmt_args ...any) int 96 | func (Database) IsSameConnection(other Database) bool 97 | func (Database) Query(callback SQLQueryCallback, query string, data any, prio DBPriority) 98 | func (Database) Execute(txn Transaction, onSuccess SQLTxnSuccess, onError SQLTxnFailure, data any, prio DBPriority) 99 | 100 | func SQL_Connect(confname string, persistent bool, err []char, maxlength int) Database 101 | func SQL_DefConnect(err []char, maxlength int, persistent bool) Database 102 | func SQL_ConnectCustom(keyvalues KeyValues, err []char, maxlength int, persistent bool) Database 103 | func SQLite_UseDatabase(database string, err []char, maxlength int) Database 104 | 105 | func SQL_CheckConfig(name string) bool 106 | func SQL_GetDriver(name string) DBDriver 107 | func SQL_ReadDriver(database Database, ident []char, ident_length int) DBDriver 108 | func SQL_SetCharset(database Database, charset string) bool 109 | 110 | func SQL_GetDriverIdent(driver DBDriver, ident []char, maxlength int) 111 | func SQL_GetDriverProduct(driver DBDriver, product []char, maxlength int) 112 | func SQL_GetAffectedRows(hndl any) int 113 | func SQL_GetInsertId(hndl any) int 114 | func SQL_GetError(hndl any, err []char, maxlength int) bool 115 | 116 | func SQL_EscapeString(database Database, str string, buffer []char, maxlength int, written *int) bool 117 | func SQL_FormatQuery(database Database, buffer string, maxlength int, format string, fmt_args ...any) int 118 | func SQL_QuoteString(database Database, str string, buffer []char, maxlength int, written *int) bool 119 | func SQL_FastQuery(database Database, query string, len int) bool 120 | func SQL_Query(database Database, query string, len int) DBResultSet 121 | func SQL_PrepareQuery(database Database, query string, err []char, maxlength int) DBStatement 122 | 123 | func SQL_FetchMoreResults(query DBResultSet) bool 124 | func SQL_HasResultSet(query any) bool 125 | func SQL_GetRowCount(query any) int 126 | func SQL_GetFieldCount(query any) int 127 | func SQL_FieldNumToName(query any, field int, name []char, maxlength int) 128 | func SQL_FieldNameToNum(query any, name string, field *int) bool 129 | func SQL_FetchRow(query any) bool 130 | func SQL_MoreRows(query any) bool 131 | func SQL_Rewind(query any) bool 132 | 133 | func SQL_FetchString(query any, field int, name []char, maxlength int, result *DBResult) int 134 | func SQL_FetchFloat(query any, field int, result *DBResult) float 135 | func SQL_FetchInt(query any, field int, result *DBResult) int 136 | func SQL_IsFieldNull(hndl any, field int) bool 137 | func SQL_FetchSize(query any, field int) int 138 | 139 | func SQL_BindParamInt(statement DBStatement, param, number int, signed bool) 140 | func SQL_BindParamFloat(statement DBStatement, param int, value float) 141 | func SQL_BindParamString(statement DBStatement, param int, value string, copy bool) 142 | 143 | func SQL_Execute(statement DBStatement) bool 144 | func SQL_LockDatabase(database Database) 145 | func SQL_UnlockDatabase(database Database) 146 | 147 | type SQLTCallback func(owner, hndl Handle, err string, data any) 148 | func SQL_IsSameConnection(hndl1, hndl2 Database) bool 149 | func SQL_TConnect(callback SQLTCallback, name string, data any); 150 | func SQL_TQuery(database Database, callback SQLTCallback, query string, data any, prio DBPriority) 151 | 152 | func SQL_CreateTransaction() Transaction 153 | func SQL_AddQuery(txn Transaction, query string, data any) int 154 | func SQL_ExecuteTransaction(db Database, txn Transaction, onSuccess SQLTxnSuccess, onError SQLTxnFailure, data any, priority DBPriority) -------------------------------------------------------------------------------- /rewrite/sptools/sptools.go: -------------------------------------------------------------------------------- 1 | package SPTools 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "io" 7 | "io/ioutil" 8 | "strings" 9 | ) 10 | 11 | // colorful strings for printing. 12 | const ( 13 | COLOR_RED = "\x1B[31m" // used for errors. 14 | COLOR_GREEN = "\x1B[32m" 15 | COLOR_YELLOW = "\x1B[33m" 16 | COLOR_BLUE = "\x1B[34m" 17 | COLOR_MAGENTA = "\x1B[35m" // used for warnings. 18 | COLOR_CYAN = "\x1B[36m" 19 | COLOR_WHITE = "\x1B[37m" 20 | COLOR_RESET = "\033[0m" // used to reset the color. 21 | ) 22 | 23 | 24 | /* Example: 25 | * {error | warning} [{ErrCode}]: {Msg} 26 | * --> {file, line, col} 27 | * Line1 | Code1 28 | * Span1 | ^^^^^ note1 29 | * Line2 | Code2 30 | * Span1 | ----- note2 31 | * ... 32 | * LineN | CodeN 33 | * SpanN | ~~~~~ noteN 34 | */ 35 | 36 | /* 37 | * compute an array of the line start offsets 38 | */ 39 | 40 | type MsgSpan struct { 41 | // TODO: have MsgSpan hold filename? 42 | spans []Span 43 | notes []string 44 | code *[]string 45 | } 46 | 47 | 48 | func MakeMsgSpan(lines *[]string) MsgSpan { 49 | return MsgSpan{ code: lines } 50 | } 51 | 52 | func (m *MsgSpan) PrepNote(span Span, note_fmt string, args ...any) { 53 | m.spans = append(m.spans, span) 54 | m.notes = append(m.notes, fmt.Sprintf(note_fmt, args...)) 55 | } 56 | 57 | func (m *MsgSpan) PurgeNotes() { 58 | m.spans = nil 59 | m.notes = nil 60 | } 61 | 62 | func (m *MsgSpan) Report(msgtype, errcode, color, msg_fmt, filename string, line, col *uint16, args ...any) string { 63 | var sb strings.Builder 64 | sb.WriteString(color) 65 | sb.WriteString(msgtype) 66 | if errcode != "" { 67 | sb.WriteRune('[') 68 | sb.WriteString(errcode) 69 | sb.WriteRune(']') 70 | } 71 | sb.WriteString(COLOR_RESET) 72 | sb.WriteString(": " + fmt.Sprintf(msg_fmt, args...)) 73 | if filename != "" { 74 | sb.WriteRune('\n') 75 | sb.WriteString("--> ") 76 | sb.WriteString(filename) 77 | if line != nil { 78 | sb.WriteString(fmt.Sprintf(":%d", *line)) 79 | } 80 | if col != nil { 81 | sb.WriteString(fmt.Sprintf(":%d", *col)) 82 | } 83 | } 84 | 85 | if len(m.spans) > 0 { 86 | sb.WriteRune('\n') 87 | largest := 0 88 | for _, l := range m.spans { 89 | if largest < int(l.LineEnd) { 90 | largest = int(l.LineEnd) 91 | } 92 | } 93 | big_line_str := fmt.Sprintf("%d", largest) 94 | largest_span := len(big_line_str) + 1 95 | span_write := func (sb *strings.Builder, span int, c rune) { 96 | for i := 0; i < span; i++ { 97 | sb.WriteRune(c) 98 | } 99 | } 100 | span_write(&sb, largest_span, ' ') 101 | sb.WriteRune('|') 102 | sb.WriteRune('\n') 103 | for i := range m.spans { 104 | span := m.spans[i] 105 | for line := span.LineStart; line <= span.LineEnd; line++ { 106 | line_num_str := fmt.Sprintf("%d", line) 107 | sb.WriteString(line_num_str) 108 | line_num_len := len(line_num_str) 109 | span_write(&sb, largest_span - line_num_len, ' ') 110 | sb.WriteRune('|') 111 | code_line := (*m.code)[line - 1] 112 | sb.WriteString(code_line) 113 | sb.WriteRune('\n') 114 | } 115 | note := m.notes[i] 116 | span_write(&sb, largest_span, ' ') 117 | sb.WriteRune('|') 118 | span_write(&sb, int(span.ColStart), ' ') 119 | span_write(&sb, int(span.ColEnd - span.ColStart), '^') 120 | sb.WriteRune(' ') 121 | sb.WriteString(COLOR_CYAN); 122 | sb.WriteString(note); 123 | sb.WriteString(COLOR_RESET) 124 | } 125 | } 126 | return sb.String() 127 | } 128 | 129 | func SpewReport(w io.Writer, message string, msg_cnt *uint32) { 130 | fmt.Fprintf(w, "%s\n", message) 131 | if msg_cnt != nil { 132 | *msg_cnt++ 133 | } 134 | } 135 | 136 | 137 | const ( 138 | // Runs preprocessor. 139 | LEXFLAG_PREPROCESS = (1 << iota) 140 | 141 | // Self explanatory, strips out all comment tokens. 142 | LEXFLAG_STRIP_COMMENTS = (1 << iota) 143 | 144 | // Keeps newlines. 145 | LEXFLAG_NEWLINES = (1 << iota) 146 | 147 | // Adds #include automatically. 148 | LEXFLAG_SM_INCLUDE = (1 << iota) 149 | 150 | // Enable ALL the above flags. 151 | LEXFLAG_ALL = -1 152 | ) 153 | 154 | 155 | func loadFile(filename string) (string, string) { 156 | if text, read_err := ioutil.ReadFile(filename); read_err==nil { 157 | code := string(text) 158 | code = strings.ReplaceAll(code, "\r\n", "\n") 159 | code = strings.ReplaceAll(code, "\r", "\n") 160 | code = strings.ReplaceAll(code, "\t", " ") 161 | return code, "none" 162 | } else { 163 | return "", read_err.Error() 164 | } 165 | } 166 | 167 | // Lexes and preprocesses a file, returning its token array. 168 | func LexFile(filename string, flags int, macros map[string]Macro) (*TokenReader, bool) { 169 | code, err_str := loadFile(filename) 170 | if len(code) <= 0 { 171 | fmt.Fprintf(os.Stdout, "sptools %sIO error%s: **** file error:: '%s'. ****\n", COLOR_RED, COLOR_RESET, err_str) 172 | return &TokenReader{}, false 173 | } 174 | if flags & LEXFLAG_SM_INCLUDE > 0 { 175 | code = "#include \n" + code 176 | } 177 | return finishLexing(Tokenize(code, filename), flags, macros) 178 | } 179 | 180 | func LexCodeString(code string, flags int, macros map[string]Macro) (*TokenReader, bool) { 181 | return finishLexing(Tokenize(code, ""), flags, macros) 182 | } 183 | 184 | func finishLexing(tr *TokenReader, flags int, macros map[string]Macro) (*TokenReader, bool) { 185 | if flags & LEXFLAG_PREPROCESS > 0 { 186 | if output, res := Preprocess(tr, flags, macros); res { 187 | *tr = *output 188 | } else { 189 | return nil, false 190 | } 191 | } 192 | tr = ConcatStringLiterals(tr) 193 | if flags & LEXFLAG_STRIP_COMMENTS > 0 { 194 | tr = RemoveComments(tr) 195 | } 196 | tr = StripSpaceTokens(tr, flags & LEXFLAG_NEWLINES > 0) 197 | return tr, true 198 | } 199 | 200 | func MakeParser(tr *TokenReader) Parser { 201 | return Parser{ TokenReader: tr } 202 | } 203 | 204 | 205 | func ParseTokens(tr *TokenReader, old bool) Node { 206 | parser := MakeParser(tr) 207 | if old { 208 | return parser.OldStart() 209 | } else { 210 | return parser.Start() 211 | } 212 | } 213 | 214 | 215 | func ParseFile(filename string, flags int, macros map[string]Macro, old bool) Node { 216 | if tr, result := LexFile(filename, flags, macros); !result { 217 | return nil 218 | } else { 219 | return ParseTokens(tr, old) 220 | } 221 | } 222 | 223 | func ParseString(code string, flags int, macros map[string]Macro, old bool) Node { 224 | output, good := finishLexing(Tokenize(code, ""), flags, macros) 225 | if good { 226 | return ParseTokens(output, old) 227 | } 228 | return nil 229 | } 230 | 231 | func ParseExpression(code string, flags int, macros map[string]Macro, old bool) Expr { 232 | output, good := finishLexing(Tokenize(code, ""), flags, macros) 233 | if good { 234 | parser := MakeParser(output) 235 | if old { 236 | return parser.OldMainExpr() 237 | } else { 238 | return parser.MainExpr() 239 | } 240 | } 241 | return nil 242 | } 243 | 244 | func ParseStatement(code string, flags int, macros map[string]Macro, old bool) Stmt { 245 | output, good := finishLexing(Tokenize(code, ""), flags, macros) 246 | if good { 247 | parser := MakeParser(output) 248 | if old { 249 | return nil 250 | } else { 251 | return parser.Statement() 252 | } 253 | } 254 | return nil 255 | } 256 | 257 | func EvalExpression(code string, flags int, macros map[string]Macro, old bool) TypeAndVal { 258 | output, good := finishLexing(Tokenize(code, ""), flags, macros) 259 | if good { 260 | parser := MakeParser(output) 261 | expr_node := Ternary[Expr](old, parser.OldMainExpr(), parser.MainExpr()) 262 | interp := MakeInterpreter(parser) 263 | return interp.EvalExpr(expr_node) 264 | } 265 | return VoidTypeAndVal{} 266 | } 267 | 268 | 269 | func Ternary[T any](cond bool, a, b T) T { 270 | if cond { 271 | return a 272 | } 273 | return b 274 | } -------------------------------------------------------------------------------- /sourcemod/functions.go: -------------------------------------------------------------------------------- 1 | /** 2 | * sourcemod/functions.go 3 | * 4 | * Copyright 2020 Nirari Technologies, Alliedmodders LLC. 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 7 | * 8 | * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 9 | * 10 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | 14 | package main 15 | 16 | import ( 17 | "sourcemod/types" 18 | ) 19 | 20 | const SP_PARAMFLAG_BYREF = 1 21 | 22 | type Function __function__ 23 | 24 | type ParamType int 25 | const ( 26 | Param_Any = ParamType(0) /**< Any data type can be pushed */ 27 | Param_Cell = ParamType(1<<1) /**< Only basic cells can be pushed */ 28 | Param_Float = ParamType(2<<1) /**< Only floats can be pushed */ 29 | Param_String = ParamType((3<<1)|SP_PARAMFLAG_BYREF) /**< Only strings can be pushed */ 30 | Param_Array = ParamType((4<<1)|SP_PARAMFLAG_BYREF) /**< Only arrays can be pushed */ 31 | Param_VarArgs = ParamType(5<<1) /**< Same as "..." in plugins, anything can be pushed, but it will always be byref */ 32 | Param_CellByRef = ParamType((1<<1)|SP_PARAMFLAG_BYREF) /**< Only a cell by reference can be pushed */ 33 | Param_FloatByRef = ParamType((2<<1)|SP_PARAMFLAG_BYREF) /**< Only a float by reference can be pushed */ 34 | ) 35 | 36 | type ExecType int 37 | const ( 38 | ET_Ignore = 0 /**< Ignore all return values, return 0 */ 39 | ET_Single /**< Only return the last exec, ignore all others */ 40 | ET_Event /**< Acts as an event with the Actions defined in core.inc, no mid-Stops allowed, returns highest */ 41 | ET_Hook /**< Acts as a hook with the Actions defined in core.inc, mid-Stops allowed, returns highest */ 42 | ) 43 | 44 | const ( 45 | SM_PARAM_COPYBACK = (1<<0) /**< Copy an array/reference back after call */ 46 | SM_PARAM_STRING_UTF8 = (1<<0) /**< String should be UTF-8 handled */ 47 | SM_PARAM_STRING_COPY = (1<<1) /**< String should be copied into the plugin */ 48 | SM_PARAM_STRING_BINARY = (1<<2) /**< Treat the string as a binary string */ 49 | ) 50 | 51 | const ( 52 | SP_ERROR_NONE = 0 /**< No error occurred */ 53 | SP_ERROR_FILE_FORMAT = 1 /**< File format unrecognized */ 54 | SP_ERROR_DECOMPRESSOR = 2 /**< A decompressor was not found */ 55 | SP_ERROR_HEAPLOW = 3 /**< Not enough space left on the heap */ 56 | SP_ERROR_PARAM = 4 /**< Invalid parameter or parameter type */ 57 | SP_ERROR_INVALID_ADDRESS = 5 /**< A memory address was not valid */ 58 | SP_ERROR_NOT_FOUND = 6 /**< The object in question was not found */ 59 | SP_ERROR_INDEX = 7 /**< Invalid index parameter */ 60 | SP_ERROR_STACKLOW = 8 /**< Not enough space left on the stack */ 61 | SP_ERROR_NOTDEBUGGING = 9 /**< Debug mode was not on or debug section not found */ 62 | SP_ERROR_INVALID_INSTRUCTION = 10 /**< Invalid instruction was encountered */ 63 | SP_ERROR_MEMACCESS = 11 /**< Invalid memory access */ 64 | SP_ERROR_STACKMIN = 12 /**< Stack went beyond its minimum value */ 65 | SP_ERROR_HEAPMIN = 13 /**< Heap went beyond its minimum value */ 66 | SP_ERROR_DIVIDE_BY_ZERO = 14 /**< Division by zero */ 67 | SP_ERROR_ARRAY_BOUNDS = 15 /**< Array index is out of bounds */ 68 | SP_ERROR_INSTRUCTION_PARAM = 16 /**< Instruction had an invalid parameter */ 69 | SP_ERROR_STACKLEAK = 17 /**< A native leaked an item on the stack */ 70 | SP_ERROR_HEAPLEAK = 18 /**< A native leaked an item on the heap */ 71 | SP_ERROR_ARRAY_TOO_BIG = 19 /**< A dynamic array is too big */ 72 | SP_ERROR_TRACKER_BOUNDS = 20 /**< Tracker stack is out of bounds */ 73 | SP_ERROR_INVALID_NATIVE = 21 /**< Native was pending or invalid */ 74 | SP_ERROR_PARAMS_MAX = 22 /**< Maximum number of parameters reached */ 75 | SP_ERROR_NATIVE = 23 /**< Error originates from a native */ 76 | SP_ERROR_NOT_RUNNABLE = 24 /**< Function or plugin is not runnable */ 77 | SP_ERROR_ABORTED = 25 /**< Function call was aborted */ 78 | ) 79 | 80 | 81 | type Forward interface{} 82 | 83 | 84 | type GlobalForward struct { 85 | FuncCount int 86 | } 87 | 88 | /// make(GlobalForward, name, exectype, param_types...) 89 | //func GlobalForward(name string, exectype ExecType, param_types ...ParamType) GlobalForward 90 | func CreateGlobalForward(name string, exectype ExecType, param_types ...ParamType) GlobalForward 91 | 92 | 93 | type PrivateForward struct { 94 | FuncCount int 95 | } 96 | /// make(PrivateForward, exectype, param_types...) 97 | //func PrivateForward(exectype ExecType, param_types ...ParamType) PrivateForward 98 | func CreateForward(exectype ExecType, param_types ...ParamType) PrivateForward 99 | 100 | func (PrivateForward) AddFunction(plugin Handle, fn Function) bool 101 | func (PrivateForward) RemoveFunction(plugin Handle, fn Function) bool 102 | func (PrivateForward) RemoveAllFunctions(plugin Handle) int 103 | 104 | func GetForwardFunctionCount(fwd Forward) int 105 | func AddToForward(fwd PrivateForward, plugin Handle, fn Function) bool 106 | func RemoveFromForward(fwd PrivateForward, plugin Handle, fn Function) bool 107 | func RemoveAllFromForward(fwd PrivateForward, plugin Handle) int 108 | 109 | func Call_StartForward(fwd Forward) 110 | func Call_StartFunction(plugin Handle, fn Function) 111 | func Call_PushCell(value any) 112 | func Call_PushCellRef(value *any) 113 | func Call_PushFloat(value float) 114 | func Call_PushFloatRef(value *float) 115 | func Call_PushArray(value []any, size int) 116 | func Call_PushArrayEx(value []any, size, cpflags int) 117 | func Call_PushNullVector() 118 | func Call_PushString(value string) 119 | func Call_PushStringEx(value string, length, szflags, cpflags int) 120 | func Call_PushNullString() 121 | func Call_Finish(result *any) int 122 | func Call_Cancel() 123 | 124 | 125 | type NativeCall func(plugin Handle, numParams int) any 126 | 127 | func GetFunctionByName(plugin Handle, name string) Function 128 | func CreateNative(name string, fn NativeCall) 129 | func ThrowNativeError(err int, fmt string, args ...any) int 130 | func GetNativeStringLength(param int, length *int) int 131 | func GetNativeString(param int, buffer string, maxlength int, bytes *int) int 132 | func SetNativeString(param int, source string, maxlength int, utf8 bool, bytes *int) int 133 | func GetNativeCell(param int) any 134 | func GetNativeFunction(param int) Function 135 | func GetNativeCellRef(param int) any 136 | func SetNativeCellRef(param int, value any) 137 | func GetNativeArray(param int, local []any, size int) int 138 | func SetNativeArray(param int, local []any, size int) int 139 | func IsNativeParamNullVector(param int) bool 140 | func IsNativeParamNullString(param int) bool 141 | func FormatNativeString(out_param, fmt_param, vararg_param, out_len int, written *int, out_string, fmt_string string) int 142 | 143 | 144 | type RequestFrameCallback func(data any) 145 | func RequestFrame(framecb RequestFrameCallback, data any) --------------------------------------------------------------------------------