content
stringlengths
5
1.05M
--[[ Copyright (c) 2009 Peter "Corsix" Cawley 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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. --]] --! Lua extensions to the C++ THMap class class "Map" local pathsep = package.config:sub(1, 1) local math_floor, tostring, table_concat = math.floor, tostring, table.concat local thMap = require"TH".map function Map:Map(app) self.width = false self.height = false self.th = thMap() self.app = app self.debug_text = false self.debug_flags = false self.debug_font = false self.debug_tick_timer = 1 self:setTemperatureDisplayMethod(app.config.warmth_colors_display_default) end local flag_cache = {} function Map:getCellFlag(x, y, flag) return self.th:getCellFlags(x, y, flag_cache)[flag] end function Map:getRoomId(x, y) return self.th:getCellFlags(x, y).roomId end function Map:setTemperatureDisplayMethod(method) if method ~= 1 and method ~= 2 and method ~= 3 then method = 1 end self.temperature_display_method = method self.app.config.warmth_colors_display_default = method self.th:setTemperatureDisplay(method) end function Map:registerTemperatureDisplayMethod() if not self.temperature_display_method then self:setTemperatureDisplayMethod(self.app.config.warmth_colors_display_default) end self.th:setTemperatureDisplay(self.temperature_display_method) end -- Convert between world co-ordinates and screen co-ordinates -- World co-ordinates are (at least for standard maps) in the range [1, 128) -- for both x and y, with the floor of the values giving the cell index. -- Screen co-ordinates are pixels relative to the map origin - NOT relative to -- the top-left corner of the screen (use UI:WorldToScreen and UI:ScreenToWorld -- for this). function Map:WorldToScreen(x, y) if x == nil then x = 0 end if y == nil then y = 0 end -- Adjust origin from (1, 1) to (0, 0) and then linear transform by matrix: -- 32 -32 -- 16 16 return 32 * (x - y), 16 * (x + y - 2) end function Map:ScreenToWorld(x, y) -- Transform by matrix: (inverse of the WorldToScreen matrix) -- 1/64 1/32 -- -1/64 1/32 -- And then adjust origin from (0, 0) to (1, 1) y = (y / 32) + 1 x = x / 64 return y + x, y - x end local function bits(n) local vals = {} local m = 256 while m >= 1 do if n >= m then vals[#vals + 1] = m n = n - m end m = m / 2 end if vals[1] then return unpack(vals) else return 0 end end --[[! Loads the specified level. If a string is passed it looks for the file with the same name in the "Levels" folder of CorsixTH, if it is a number it tries to load that level from the original game. !param level The name (or number) of the level to load. If this is a number the game assumes the original game levels are considered. !param level_name The name of the actual map/area/hospital as written in the config file. !param level_file The path to the map file as supplied by the config file. ]] function Map:load(level, difficulty, level_name, level_file, level_intro) local objects, i if not difficulty then difficulty = "full" end -- Load CorsixTH base configuration for all levels. -- We want to load the file a new each time. local function file (filename) local f = assert(loadfile(filename)) return f() end local path = debug.getinfo(1, "S").source:sub(2, -8) local result = file(path .. "base_config.lua") local base_config = result local errors if type(level) == "number" then -- Playing the original campaign. -- Add TH's base config if possible, otherwise our own config -- roughly corresponds to "full". errors, base_config = self:loadMapConfig(difficulty .. "00.SAM", base_config) -- If it couldn't be loaded the new difficulty level is full no matter what. if errors then difficulty = "full" end self.difficulty = difficulty self.level_number = level local data data, errors = self:getRawData(level_file) if data then i, objects = self.th:load(data) else return nil, errors end self.level_name = _S.level_names[level]:upper() -- Check if we're using the demo files. If we are, that special config should be loaded. if self.app.using_demo_files then -- Try to load our own configuration file for the demo. local p = debug.getinfo(1, "S").source:sub(2, -12) .. "Levels" .. pathsep .. "demo.level" errors, result = self:loadMapConfig(p, base_config, true) if errors then print("Warning: Could not find the demo configuration, try reinstalling the game") end self.level_config = result else local level_no = level if level_no < 10 then level_no = "0" .. level end -- Override with the specific configuration for this level errors, result = self:loadMapConfig(difficulty .. level_no .. ".SAM", base_config) -- Finally load additional CorsixTH config per level (currently only for level 5) local p = debug.getinfo(1, "S").source:sub(2, -12) .. "Levels" .. pathsep .. "original" .. level_no .. ".level" errors, result = self:loadMapConfig(p, result, true) self.level_config = result end elseif _MAP_EDITOR then -- We're being fed data by the map editor. self.level_name = "MAP EDITOR" self.level_number = "MAP EDITOR" if level == "" then i, objects = self.th:loadBlank() else i, objects = self.th:load(level) end assert(base_config, "No base config has been loaded!") self.level_config = base_config else -- We're loading a custom level. self.level_name = level_name self.level_intro = level_intro self.level_number = level self.level_file = level_file local data, errors = self:getRawData(level_file) if data then i, objects = self.th:load(data) else return nil, errors end assert(base_config, "No base config has been loaded!") errors, result = self:loadMapConfig(level, base_config, true) self.level_config = result end self.width, self.height = self.th:size() self.parcelTileCounts = {} for plot = 1, self.th:getPlotCount() do self.parcelTileCounts[plot] = self.th:getParcelTileCount(plot) if plot > 1 and not _MAP_EDITOR then -- TODO: On multiplayer maps, assign plots 2-N to players 2-N self.th:setPlotOwner(plot, 0) end end return objects end --[[! Loads map configurations from files. Returns nil as first result if no configuration could be loaded and config as second result no matter what. !param filename !param config If a base config already exists and only some values should be overridden this is the base config !param custom If true The configuration file is searched for where filename points, otherwise it is assumed that we're looking in the theme_hospital_install path. ]] function Map:loadMapConfig(filename, config, custom) local function iterator() if custom then return io.lines(filename) else return self.app.fs:readContents("Levels", filename):gmatch"[^\r\n]+" end end if self.app.fs:readContents("Levels", filename) or io.open(filename) then for line in iterator() do if line:sub(1, 1) == "#" then local parts = {} local nkeys = 0 for part in line:gmatch"%.?[-?a-zA-Z0-9%[_%]]+" do if part:sub(1, 1) == "." and #parts == nkeys + 1 then nkeys = nkeys + 1 end parts[#parts + 1] = part end if nkeys == 0 then parts[3] = parts[2] parts[2] = ".Value" nkeys = 1 end for i = 2, nkeys + 1 do local key = parts[1] .. parts[i] local t, n for name in key:gmatch"[^.%[%]]+" do name = tonumber(name) or name if t then if not t[n] then t[n] = {} end t = t[n] else t = config end n = name end t[n] = tonumber(parts[nkeys + i]) or parts[nkeys + i] end end end return nil, config else return "Error: Could not find the configuration file", config end end local temp_debug_text local temp_debug_flags local temp_updateDebugOverlay local temp_thData -- Keep debug information in temporary local vars, do not save them function Map:prepareForSave() temp_debug_text = self.debug_text self.debug_text = false temp_debug_flags = self.debug_flags self.debug_flags = false temp_updateDebugOverlay = self.updateDebugOverlay self.updateDebugOverlay = nil temp_thData = self.thData self.thData = nil end -- Restore the temporarily stored debug information after saving function Map:afterSave() self.debug_text = temp_debug_text temp_debug_text = nil self.debug_flags = temp_debug_flags temp_debug_flags = nil self.updateDebugOverlay = temp_updateDebugOverlay temp_updateDebugOverlay = nil self.thData = temp_thData temp_thData = nil end function Map:clearDebugText() self.debug_text = false self.debug_flags = false self.updateDebugOverlay = nil end function Map:getRawData(level_file) if not self.thData then local data, errors if not level_file then data, errors = self.app:readDataFile("Levels", "Level.L".. self.level_number) else data, errors = self.app:readDataFile("Levels", level_file) end if data then self.thData = data else return nil, errors end end return self.thData end function Map:updateDebugOverlayFlags() for x = 1, self.width do for y = 1, self.height do local xy = (y - 1) * self.width + x - 1 self.th:getCellFlags(x, y, self.debug_flags[xy]) end end end function Map:updateDebugOverlayHeat() for x = 1, self.width do for y = 1, self.height do local xy = (y - 1) * self.width + x - 1 self.debug_text[xy] = ("%02.1f"):format(self.th:getCellTemperature(x, y) * 50) end end end function Map:loadDebugText(base_offset, xy_offset, first, last, bits_) self.debug_text = false self.debug_flags = false self.updateDebugOverlay = nil if base_offset == "flags" then self.debug_flags = {} for x = 1, self.width do for y = 1, self.height do local xy = (y - 1) * self.width + x - 1 self.debug_flags[xy] = {} end end self.updateDebugOverlay = self.updateDebugOverlayFlags self:updateDebugOverlay() elseif base_offset == "positions" then self.debug_text = {} for x = 1, self.width do for y = 1, self.height do local xy = (y - 1) * self.width + x - 1 self.debug_text[xy] = x .. "," .. y end end elseif base_offset == "heat" then self.debug_text = {} self.updateDebugOverlay = self.updateDebugOverlayHeat self:updateDebugOverlay() else local thData = self:getRawData() for x = 1, self.width do for y = 1, self.height do local xy = (y - 1) * self.width + x - 1 local offset = base_offset + xy * xy_offset if bits_ then self:setDebugText(x, y, bits(thData:byte(offset + first, offset + last))) else self:setDebugText(x, y, thData:byte(offset + first, offset + last)) end end end end end function Map:onTick() if self.debug_tick_timer == 1 then if self.updateDebugOverlay then self:updateDebugOverlay() end self.debug_tick_timer = 10 else self.debug_tick_timer = self.debug_tick_timer - 1 end end function Map:setBlocks(blocks) self.blocks = blocks self.th:setSheet(blocks) end function Map:setCellFlags(...) self.th:setCellFlags(...) end function Map:setDebugFont(font) self.debug_font = font self.cell_outline = TheApp.gfx:loadSpriteTable("Bitmap", "aux_ui", true) end function Map:setDebugText(x, y, msg, ...) if not self.debug_text then self.debug_text = {} end local text if ... then text = {msg, ...} for i, v in ipairs(text) do text[i] = tostring(v) end text = table_concat(text, ",") else text = msg ~= 0 and msg or nil end self.debug_text[(y - 1) * self.width + x - 1] = text end --[[! @arguments canvas, screen_x, screen_y, screen_width, screen_height, destination_x, destination_y Draws the rectangle of the map given by (sx, sy, sw, sh) at position (dx, dy) on the canvas --]] function Map:draw(canvas, sx, sy, sw, sh, dx, dy) -- All the heavy work is done by C code: self.th:draw(canvas, sx, sy, sw, sh, dx, dy) -- Draw any debug overlays if self.debug_font and (self.debug_text or self.debug_flags) then local startX = 0 local startY = math_floor((sy - 32) / 16) if startY < 0 then startY = 0 elseif startY >= self.height then startX = startY - self.height + 1 startY = self.height - 1 if startX >= self.width then startX = self.width - 1 end end local baseX = startX local baseY = startY while true do local x = baseX local y = baseY local screenX = 32 * (x - y) - sx local screenY = 16 * (x + y) - sy if screenY >= sh + 70 then break elseif screenY > -32 then repeat if screenX < -32 then elseif screenX < sw + 32 then local xy = y * self.width + x local x = dx + screenX - 32 local y = dy + screenY if self.debug_flags then local flags = self.debug_flags[xy] if flags.passable then self.cell_outline:draw(canvas, 3, x, y) end if flags.hospital then self.cell_outline:draw(canvas, 8, x, y) end if flags.buildable then self.cell_outline:draw(canvas, 9, x, y) end if flags.travelNorth and self.debug_flags[xy - self.width].passable then self.cell_outline:draw(canvas, 4, x, y) end if flags.travelEast and self.debug_flags[xy + 1].passable then self.cell_outline:draw(canvas, 5, x, y) end if flags.travelSouth and self.debug_flags[xy + self.width].passable then self.cell_outline:draw(canvas, 6, x, y) end if flags.travelWest and self.debug_flags[xy - 1].passable then self.cell_outline:draw(canvas, 7, x, y) end if flags.thob ~= 0 then self.debug_font:draw(canvas, "T"..flags.thob, x, y, 64, 16) end if flags.roomId ~= 0 then self.debug_font:draw(canvas, "R"..flags.roomId, x, y + 16, 64, 16) end else local msg = self.debug_text[xy] if msg and msg ~= "" then self.cell_outline:draw(canvas, 2, x, y) self.debug_font:draw(canvas, msg, x, y, 64, 32) end end else break end x = x + 1 y = y - 1 screenX = screenX + 64 until y < 0 or x >= self.width end if baseY == self.height - 1 then baseX = baseX + 1 if baseX == self.width then break end else baseY = baseY + 1 end end end end function Map:getParcelPrice(parcel) local conf = self.level_config conf = conf and conf.gbv conf = conf and conf.LandCostPerTile return self:getParcelTileCount(parcel) * (conf or 25) end function Map:getParcelTileCount(parcel) return self.parcelTileCounts[parcel] or 0 end function Map:afterLoad(old, new) if old < 6 then self.parcelTileCounts = {} for plot = 1,self.th:getPlotCount() do self.parcelTileCounts[plot] = self.th:getParcelTileCount(plot) end end if old < 18 then self.difficulty = "full" end if old < 44 then self.level_config.expertise[2].MaxDiagDiff = 700 self.level_config.expertise[3].MaxDiagDiff = 250 self.level_config.expertise[4].MaxDiagDiff = 250 self.level_config.expertise[5].MaxDiagDiff = 250 self.level_config.expertise[6].MaxDiagDiff = 250 self.level_config.expertise[7].MaxDiagDiff = 250 self.level_config.expertise[8].MaxDiagDiff = 350 self.level_config.expertise[9].MaxDiagDiff = 250 self.level_config.expertise[10].MaxDiagDiff = 250 self.level_config.expertise[11].MaxDiagDiff = 700 self.level_config.expertise[12].MaxDiagDiff = 1000 self.level_config.expertise[13].MaxDiagDiff = 700 self.level_config.expertise[14].MaxDiagDiff = 400 self.level_config.expertise[15].MaxDiagDiff = 350 self.level_config.expertise[16].MaxDiagDiff = 350 self.level_config.expertise[17].MaxDiagDiff = 1000 self.level_config.expertise[18].MaxDiagDiff = 350 self.level_config.expertise[19].MaxDiagDiff = 700 self.level_config.expertise[20].MaxDiagDiff = 700 self.level_config.expertise[21].MaxDiagDiff = 700 self.level_config.expertise[22].MaxDiagDiff = 350 self.level_config.expertise[23].MaxDiagDiff = 350 self.level_config.expertise[24].MaxDiagDiff = 700 self.level_config.expertise[25].MaxDiagDiff = 700 self.level_config.expertise[26].MaxDiagDiff = 700 self.level_config.expertise[27].MaxDiagDiff = 350 self.level_config.expertise[28].MaxDiagDiff = 700 self.level_config.expertise[29].MaxDiagDiff = 1000 self.level_config.expertise[30].MaxDiagDiff = 700 self.level_config.expertise[31].MaxDiagDiff = 1000 self.level_config.expertise[32].MaxDiagDiff = 700 self.level_config.expertise[33].MaxDiagDiff = 1000 self.level_config.expertise[34].MaxDiagDiff = 700 self.level_config.expertise[35].MaxDiagDiff = 700 end if old < 57 then local flags_to_set = {buildableNorth = true, buildableSouth = true, buildableWest = true, buildableEast = true} for x = 1, self.width do for y = 1, self.height do self:setCellFlags(x, y, flags_to_set) end end end end
local Class = require 'lib.hump.class' local Event = getClass 'wyx.event.Event' -- LightingStatusRequest -- local LightingStatusRequest = Class{name='LightingStatusRequest', inherits=Event, function(self, entityID, x, y) if type(entityID) ~= 'string' then entityID = entityID:getID() end verify('string', entityID) verify('number', x, y) assert(EntityRegistry:exists(entityID), 'LightingStatusRequest: entityID %q does not exist', entityID) Event.construct(self, 'Lighting Status Request') self._entityID = entityID self._x = x self._y = y end } -- destructor function LightingStatusRequest:destroy() self._entityID = nil Event.destroy(self) end function LightingStatusRequest:getEntity() return self._entityID end function LightingStatusRequest:getPosition() return self._x, self._y end function LightingStatusRequest:__tostring() return self:_msg('{%08s} (%d,%d)', self._entityID, self._x, self._y) end -- the class return LightingStatusRequest
local class = require'luna' local queue = class { Size = {get = function (this) return #this.stack end}; __construct = function (this, ...) this.stack = {...} end; Push = function (this, value) table.insert(this.stack, value) end; Pop = function (this) local value = this.stack[1] table.remove(this.stack, 1) return value end; Peak = function (this) local value = this.stack[1] return value end; ToArray = function (this) return this.stack end }
local opts = { command_on_first_image_loaded="", command_on_image_loaded="", command_on_non_image_loaded="", } local options = require 'mp.options' local msg = require 'mp.msg' options.read_options(opts, nil, function() end) function run_maybe(str) if str ~= "" then mp.command(str) end end local was_image = false function set_image(is_image) if is_image and not was_image then msg.info("First image detected") run_maybe(opts.command_on_first_image_loaded) end if is_image then msg.info("Image detected") run_maybe(opts.command_on_image_loaded) end if not is_image and was_image then msg.info("Non-image detected") run_maybe(opts.command_on_non_image_loaded) end was_image = is_image end local properties = {} function properties_changed() local dwidth = properties["dwidth"] local tracks = properties["track-list"] local path = properties["path"] local framecount = properties["estimated-frame-count"] if not path or path == "" then return end if not tracks or #tracks == 0 then return end local audio_tracks = 0 for _, track in ipairs(tracks) do if track.type == "audio" then audio_tracks = audio_tracks + 1 end end -- only do things when state is consistent if not framecount and audio_tracks > 0 then set_image(false) elseif framecount and dwidth and dwidth > 0 then -- png have 0 frames, jpg 1 ¯\_(ツ)_/¯ set_image((framecount == 0 or framecount == 1) and audio_tracks == 0) end end function observe(propname) mp.observe_property(propname, "native", function(_, val) if val ~= properties[propname] then properties[propname] = val msg.verbose("Property " .. propname .. " changed") properties_changed() end end) end observe("estimated-frame-count") observe("track-list") observe("dwidth") observe("path")
local date = require 'date' local cjson = require 'cjson.safe' local basexx = require 'basexx' return function(app) assert(app, "App missing") local sys = app:sys_api() local host_name = sys:id() return { log = function(app, procid, lvl, timestamp, content) local content = content:gsub('\n', '\\\\n') return cjson.encode({ host = host_name, app = 'FREEIOE.'..app, procid = procid, level = lvl, timestamp = timestamp, content = content }) end, comm = function(app, sn, dir, timestamp, base64, ...) local lvl = Log.LVL.TRACE local args = { } local data = {} for _, v in ipairs({...}) do if base64 then data[#data + 1] = basexx.to_base64(v) else data[#data + 1] = v:gsub('\n', '\\\\n') end end local content = table.concat(data, '\t') return cjson.encode({ host = host_name, app = 'FREEIOE.'..app, format = base64 and 'BASE64' or 'PLAIN', sn = sn, dir = dir timestamp = timestamp, content = content }) end, } end
-- -- Copyright (c) 2005 Pandemic Studios, LLC. All rights reserved. -- -- Tuning values for the game, broken off into a lua script so that -- people can muck with them easily w/o editing the game exe directly. -- Note: items in here are just shoved in lua globals. Items added -- will require the exe to be modified to do something with them. -- TwoPI = 6.28318 5307179586476925286766559 --Current anim times: (goes by the lockinput time --Land = .5 --ProneToStand = 1.33 --Dive (needs adjusting, its too fast right now) = .5f --crouchToProne = 1.33 local __SCRIPT_NAME = "ME5_globals"; local debug = true local function PrintLog(...) if debug == true then print("["..__SCRIPT_NAME.."]", unpack(arg)); end end PrintLog("Entered") RollLeft = { Size = 3, --number of points interpolated between current math.max is 6, each point MUST have a vec,slop,ore,rslope and time associated with it Vec = { {-0.1,-0.2,0.0}, -- x y z, offset from the camera's position (keep in mind the camera's position moves on its own as well) {0.0,-0.3,0.0}, {0.1,0.0,0.0}, }, Slope = { {0.4, 0.3, 0.0}, --x y z the slope of the points, adjusts the curve {0.2, -0.3, 0.0}, {0.0, 0.0, 0.0}, }, Ore = { {0.0, 0.0, 0.0}, --euler angles, x y z {0.0, 0.0, 0.0}, --two pi {0.0, 0.0, 0.0}, }, RSlope = { {0.0, 0.0, 0.0}, -- slope of the rotation, adjusts the rotation interpolation {0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, }, Time = { .15, .25, .15 -- .3, .5, .3 -- times, in magical floating point frontline time. }, } RollRight = { Size = 3, Vec = { {0.1,-0.2,0.0}, {0.0,-0.3,0.0}, {-0.1,0.0,0.0}, }, Slope = { {0.4, 0.3, 0.0}, {0.2, -0.3, 0.0}, {0.0, 0.0, 0.0}, }, Ore = { {0.0, 0.0, 0.0}, {0.0, 0.0, -0.0}, {0.0, 0.0, -0.0}, }, RSlope = { {0.0, 0.0, 0.0}, -- slope of the rotation, adjusts the rotation interpolation {0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, }, Time = { .15, .25, .15 }, } Crouch = { Size = 3, Vec = { {0.0, -1.0, 0.0}, {0.0, -0.0, 0.0}, {0.0, 0.0, 0.0}, }, Slope = { {0.0, 0.2, 0.0}, {0.0, -0.2, 0.0}, {0.0, 0.0, 0.0}, }, Ore = { {0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, }, RSlope = { {0.0, 0.0, 0.5}, {0.0, 0.0, 0.3}, {0.0, 0.0, 0.4}, }, Time = { .2, .1, .2 }, } CrouchToProne = { Size = 3, Vec = { {0.0,-0.0,0.4}, {0.0, 0.0, 0.2}, {0.0, 0.0, 0.0}, }, Slope = { {0.0, 0.0, 0.0}, {0.0, -0.0, 0.0}, {0.0, 0.0, 0.0}, }, Ore = { {-0.4, 0.0, 0.0}, {-0.2, 0.0, 0.0}, {0.0, 0.0, 0.0}, }, RSlope = { {0.0, 0.0, 0.3}, {0.0, 0.0, -0.3}, {0.0, 0.0, 0.0}, }, Time = { .6, .5, .5 }, } Land = { Size = 3, -- number of points interpolated between current math.max is 6, each point MUST have a vec,slop,ore,rslope and time associated with it Vec = { {0.0,-1.0,0.0}, -- x y z, offset from the camera's position (keep in mind the camera's position moves on its own as well) {0.0, 0.2, 0.0}, {0.0, 0.0, 0.0}, }, Slope = { {0.0, 0.2, 0.0}, -- 0.0, 0.2, 0.0 --x y z the slope of the points, adjusts the curve {0.0, -0.4, 0.0}, -- 0.0, -0.2, 0.0 {0.0, 0.0, 0.0}, -- 0.0, 0.0, 0.0 }, Ore = { {0.0, 0.0, 0.0}, --euler angles, x y z {0.0, 0.0, 0.0}, --two pi {0.0, 0.0, 0.0}, }, RSlope = { {0.0, 0.0, 0.0}, -- slope of the rotation, adjusts the rotation interpolation {0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, }, Time = { .10, .10, .10 -- .17, .17, .17 -- times, in magical floating point frontline time. }, } StandToProne = { -- Note this never actually gets called, game logic currently has the person jump to the crouch state b4 going prone Size = 3, Vec = { {0.0,-0.0,0.4}, {0.0, 0.0, 0.2}, {0.0, 0.0, 0.0}, }, Slope = { {0.0, 0.0, 0.0}, {0.0, -0.0, 0.0}, {0.0, 0.0, 0.0}, }, Ore = { {-0.4, 0.0, 0.0}, {-0.2, 0.0, 0.0}, {0.0, 0.0, 0.0}, }, RSlope = { {0.0, 0.0, 0.3}, {0.0, 0.0, -0.3}, {0.0, 0.0, 0.0}, }, Time = { .6, .5, .5 }, } ProneToStand = { Size = 3, Vec = { {0.0,-0.2,0.4}, {0.0, 0.0, 0.2}, {0.0, 0.0, 0.0}, }, Slope = { {0.0, 0.0, 0.0}, {0.0, -0.2, 0.0}, {0.0, 0.0, 0.0}, }, Ore = { {-0.6, 0.0, 0.0}, {-0.2, 0.0, 0.0}, {0.0, 0.0, 0.0}, }, RSlope = { {0.0, 0.0, 0.3}, {0.0, 0.0, -0.3}, {0.0, 0.0, 0.0}, }, Time = { .6, .5, .4 }, } CrouchToStand = { Size = 3, Vec = { {0.0,0.2,0.0}, {0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, }, Slope = { {0.0, -0.1, 0.0}, {0.0, 0.1, 0.0}, {0.0, 0.0, 0.0}, }, Ore = { {0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, }, RSlope = { {0.0, 0.0, -0.5}, {0.0, 0.0, -0.3}, {0.0, 0.0, -0.4}, }, Time = { .12, .12, .12 }, } --Rumble Region Junk RumbleSmall = { --In A math.min/math.max string.format Interval = { 4.0 , 15.0 }, --how often the rumble gets set off Light = {1.0, 1.0}, Heavy = {0.0,.2}, HeavyDecay = { .5,.5 }, LightDecay = {.5, .5 }, DelayLight = {0.0, 0.0 }, DelayHeavy = { 0.0, 0.0 }, TimeLeftHeavy = {1.0, 1.0}, --how long each rumble lasts TimeLeftLight = {0.5, 1.0}, ShakeAmt = { 0.5 , 1.0 }, ShakeLen = { 0.5, 1.5 }, --Camera shake length FXName = "Doesn'tWorkYet", --the particle effect that gets triggered, is read in, but not used yet. } RumbleMedium = { --In A math.min/math.max string.format Interval = { 4.0 , 15.0 }, --how often the rumble gets set off Light = {1.0, 1.0}, Heavy = {.2,.4}, HeavyDecay = { .5,.5 }, LightDecay = {.5, .5 }, DelayLight = {0.0, 0.0 }, DelayHeavy = { 0.0, 0.0 }, TimeLeftHeavy = {1.0, 1.0}, --how long each rumble lasts TimeLeftLight = {1.0, 1.0}, ShakeAmt = { 1.5 , 2.5 }, ShakeLen = { 0.5, 1.5 }, --Camera shake length FXName = "Doesn'tWorkYet", --the particle effect that gets triggered, is read in, but not used yet. } RumbleLarge = { --In A math.min/math.max string.format Interval = { 4.0 , 15.0 }, --how often the rumble gets set off Light = {1.0, 1.0}, Heavy = {.6,.8}, HeavyDecay = { .5,.5 }, LightDecay = {.5, .5 }, DelayLight = {0.0, 0.0 }, DelayHeavy = { 0.0, 0.0 }, TimeLeftHeavy = {1.0, 1.0}, --how long each rumble lasts TimeLeftLight = {1.0, 1.0}, ShakeAmt = { 3.0 , 4.0 }, ShakeLen = { 0.5, 1.5 }, --Camera shake length FXName = "Doesn'tWorkYet", --the particle effect that gets triggered, is read in, but not used yet. } PrintLog("Exited")
--[[ An implementation of a simple numerical gradient checker. ARGS: - `opfunc` : a function that takes a single input (X), the point of evaluation, and returns f(X) and df/dX - `x` : the initial point - `eps` : the epsilon to use for the numerical check (default is 1e-7) RETURN: - `diff` : error in the gradient, should be near tol - `dC` : exact gradient at point - `dC_est` : numerically estimates gradient at point ]]-- -- function that numerically checks gradient of NCA loss: function optim.checkgrad_list(opfunc, y, eps) print (y) for i = 1, #y do print ('----------') print (i) if y[i] ~= nil and i == 7 then print ('*******----------') local x = y[i] -- compute true gradient: local Corg,dD = opfunc(y) dC = dD[i] dC:resize(x:size()) local Ctmp -- temporary value local isTensor = torch.isTensor(Corg) if isTensor then Ctmp = Corg.new(Corg:size()) end -- compute numeric approximations to gradient: local eps = eps or 1e-7 local dC_est = torch.Tensor():typeAs(dC):resizeAs(dC) for i = 1,dC:size(1) do local tmp = x[i] x[i] = x[i] + eps local C1 = opfunc(y) if isTensor then Ctmp:copy(C1) C1 = Ctmp end x[i] = x[i] - 2 * eps local C2 = opfunc(y) x[i] = tmp dC_est[i] = (C1 - C2) / (2 * eps) print (dC[i]) print (dC_est[i]) end -- estimate error of gradient: local diff = torch.norm(dC - dC_est) / torch.norm(dC + dC_est) print (string.format('i: %d, diff: %f', i, diff)) end end end
local systemTime = hs and hs.timer.secondsSinceEpoch or os.time local t = systemTime() local MAX = 28123 local d = function(n) local max = math.sqrt(n) local sum = 0 for i = 1, max, 1 do if n % i == 0 then sum = sum + i if i ~= max and i ~= 1 then sum = sum + (n // i) end end end return sum end abundantNumbers = {} sums = {} local idx = 12 while true do local ans = d(idx) if ans > idx then if idx + 12 > MAX then break end table.insert(abundantNumbers, idx) end idx = idx + 1 end print(systemTime() - t) -- not sure this can be optimized more or not... it's the slowest part taking almost -- 20 seconds, but not below about assignment... small, but noticable for i = 1, #abundantNumbers, 1 do local n = abundantNumbers[i] for j = i, #abundantNumbers, 1 do local possible = n + abundantNumbers[j] if possible <= MAX then -- apparently assignment, if it is already assigned is -- expensive, this shaves 1.5 seconds off if not sums[possible] then sums[possible] = true end else break end end end print(systemTime() - t) wantedSum = 0 for i = 1, MAX, 1 do if not sums[i] then wantedSum = wantedSum + i end end print(wantedSum) print(systemTime() - t)
local pb = require"pb" local utils = require"utils" -- load .proto file. local media = require"protos.media" --print(utils.dump(media)) local MediaContent = media.MediaContent local data = { media = { uri = "http://javaone.com/keynote.mpg", title = "Javaone Keynote", width = 640, height = 480, format = "video/mpg4", duration = 18000000, -- half hour in milliseconds size = 58982400, -- bitrate * duration in seconds / 8 bits per byte bitrate = 262144, -- 256k person = {"Bill Gates", "Steve Jobs"}, player = 'JAVA', copyright = nil, }, image = { { uri = "http://javaone.com/keynote_large.jpg", title = "Javaone Keynote", width = 1024, height = 768, size = 'LARGE', }, { uri = "http://javaone.com/keynote_small.jpg", title = "Javaone Keynote", width = 320, height = 240, size = 'SMALL', }, }, } -- -- Check MediaContent record -- local function check_MediaContent_media(media) assert(media ~= nil) assert(media.uri == "http://javaone.com/keynote.mpg") assert(media.title == "Javaone Keynote") assert(media.width == 640) assert(media.height == 480) assert(media.format == "video/mpg4") assert(media.duration == 18000000) -- half hour in milliseconds assert(media.size == 58982400) -- bitrate * duration in seconds / 8 bits per byte assert(media.bitrate == 262144) -- 256k local person = media.person assert(person[1] == "Bill Gates") assert(person[2] == "Steve Jobs") assert(media.player == 'JAVA') assert(media.copyright == nil) end local function check_MediaContent(content) assert(content ~= nil) -- check media record check_MediaContent_media(content.media) -- check image records. local image = content.image local img img = image[1] assert(img ~= nil) assert(img.uri == "http://javaone.com/keynote_large.jpg") assert(img.title == "Javaone Keynote") assert(img.width == 1024) assert(img.height == 768) assert(img.size == 'LARGE') img = image[2] assert(img ~= nil) assert(img.uri == "http://javaone.com/keynote_small.jpg") assert(img.title == "Javaone Keynote") assert(img.width == 320) assert(img.height == 240) assert(img.size == 'SMALL') end local msg = MediaContent(data) check_MediaContent(msg) pb.print(msg) local bin = msg:Serialize() print("--- encoded message: bytes", #bin) local file = assert(io.open(arg[1] or 'media.bin', 'w')) assert(file:write(bin)) assert(file:close()) print("--- decode message") local msg1, off = MediaContent():Parse(bin) check_MediaContent(msg1) print(utils.dump(msg1)) pb.print(msg1) print("Valid .proto file")
require("which-key").setup({ popup_mappings = { scroll_down = "<Down>", -- binding to scroll down inside the popup scroll_up = "<Up>", -- binding to scroll up inside the popup }, window = { border = "single", -- none, single, double, shadow position = "bottom", -- bottom, top margin = { 1, 0, 1, 0 }, -- extra window margin [top, right, bottom, left] padding = { 2, 2, 2, 2 }, -- extra window padding [top, right, bottom, left] winblend = 0, }, ignore_missing = false, })
--*********************************************************** --** ROBERT JOHNSON ** --*********************************************************** require "ISUI/ISUIElement" ---@class ISWeather : ISPanel ISWeather = ISPanel:derive("ISWeather"); --************************************************************************-- --** ISPanel:initialise --** --************************************************************************-- function ISWeather:initialise() ISPanel.initialise(self); end function ISWeather:addImage(image) table.insert(self.images,getTexture(image)); end function ISWeather:addMoon(moonImage) self.moon = getTexture(moonImage); end function ISWeather:removeMoon() self.moon = nil; end function ISWeather:removeImages() self.images = {}; end --************************************************************************-- --** ISPanel:render --** --************************************************************************-- function ISWeather:prerender() local width = 43; local x = 43; if self.moon then width = 88; x = 0; end self:drawRect((Core:getInstance():getOffscreenWidth() - 208) + x, 0, width, self.height, self.backgroundColor.a, self.backgroundColor.r, self.backgroundColor.g, self.backgroundColor.b); self:drawRectBorder((Core:getInstance():getOffscreenWidth() - 208) + x, 0, width, self.height, self.borderColor.a, self.borderColor.r, self.borderColor.g, self.borderColor.b); for i,v in pairs(self.images) do self:drawTexture(v, (Core:getInstance():getOffscreenWidth() - 208) + x + 1, (self.height / 2) - (v:getHeight() / 2), 1, 1, 1, 1); end if self.moon then self:drawTexture(self.moon, (Core:getInstance():getOffscreenWidth() - 173) + x + 1, (self.height / 2) - (self.moon:getHeight() / 2), 1, 1, 1, 1); end -- turned it off until can reposition it. self:setVisible(false); end --************************************************************************-- --** ISPanel:new --** --************************************************************************-- function ISWeather:new (x, y, width, height) local o = {} --o.data = {} o = ISPanel:new(x, y, width, height); setmetatable(o, self) self.__index = self o.x = x; o.y = y; o.borderColor = {r=0.4, g=0.4, b=0.4, a=1}; o.backgroundColor = {r=0, g=0, b=0, a=0.5}; o.width = width; o.images = {}; o.moon = nil; o.height = height; o.anchorLeft = true; o.anchorRight = false; o.anchorTop = true; o.anchorBottom = false; return o end
--[[ Project: SA Memory (Available from https://blast.hk/) Developers: LUCHARE, FYP Special thanks: plugin-sdk (https://github.com/DK22Pac/plugin-sdk) for the structures and addresses. Copyright (c) 2018 BlastHack. ]] local shared = require 'SAMemory.shared' shared.require 'CAEAudioEntity' shared.require 'CAESound' shared.ffi.cdef[[ typedef struct CAETwinLoopSoundEntity : CAEAudioEntity { short nBankSlotId; short nSoundType[2]; char _pad1[2]; CAEAudioEntity *pBaseAudio; short field_88; short field_8A; short field_8C; short nPlayTimeMin; short nPlayTimeMax; char _pad2[2]; unsigned int nTimeToSwapSounds; bool bPlayingFirstSound; char _pad3; short anStartingPlayPercentage[2]; short field_9E; CAESound *apSounds[2]; } CAETwinLoopSoundEntity; ]] shared.validate_size('CAETwinLoopSoundEntity', 0xA8)
local tap = require('tap') local utils = require('utils') local test = tap.test('gh-6084-missed-carg1-in-bctsetr-fallback') test:plan(2) -- XXX: Bytecode TSETR appears only in built-ins libraries, when -- doing fixups for fast function written in Lua (i.e. -- `table.move()`), by replacing all TSETV bytecodes with -- the TSETR. See <src/host/genlibbc.lua> for more details. -- This test checks that fallback path, when the index of the new -- set element is greater than the table's asize, doesn't lead -- to a crash. -- XXX: We need to make sure the bytecode is present in the chosen -- built-in to make sure our test is still valid. assert(utils.hasbc(table.move, 'TSETR')) -- `t` table asize equals 1. Just copy its first element (1) -- to the field by index 2 > 1, to fallback inside TSETR. local t = {1} local res = table.move(t, 1, 1, 2) test:ok(t == res, 'table.move returns the same table') test:ok(t[1] == t[2], 'table.move is correct') os.exit(test:check() and 0 or 1)
local isFunc = require(script.Parent:WaitForChild("isFunc")) return function (tbl,funcName,...) assert(type(tbl) == "table", "expected table in arg 1") assert(type(funcName) == "string", "expected function in arg 2") for _,module in pairs(tbl) do if isFunc(module[funcName]) then module[funcName](module,...) end end end
--Thanks to SinisterRectus for this script. local pp = require('pretty-print') local function prettyLine(...) local ret = {} for i = 1, select('#', ...) do local arg = pp.strip(pp.dump(select(i, ...))) table.insert(ret, arg) end return table.concat(ret, '\t') end local function printLine(...) local ret = {} for i = 1, select('#', ...) do local arg = tostring(select(i, ...)) table.insert(ret, arg) end return table.concat(ret, '\t') end local function code(str) return string.format('```lua\n%s```', str) end local sandbox = { math = math, string = string, coroutine = coroutine, os = os, pairs = pairs, table = table, type = type, collectgarbage = collectgarbage } local codedLines = {} local function executeLua(arg, msg) if not arg then return end if msg.author.id ~= "260157417445130241" then return end arg = arg:gsub('```\n?', '') -- strip markdown codeblocks local lines = {} sandbox.message = msg sandbox.channel = msg.channel sandbox.guild = msg.guild sandbox.print = function(...) table.insert(lines, printLine(...)) end sandbox.p = function(...) table.insert(lines, prettyLine(...)) end table.insert(codedLines,arg) local fn, syntaxError = load(table.concat(codedLines," "), 'Tiger 2.0', 't', sandbox) if not fn then return msg:reply(code(syntaxError)) end local success, runtimeError = pcall(fn) if not success then return msg:reply(code(runtimeError)) end lines = table.concat(lines, '\n') if #lines > 1990 then -- truncate long messages lines = lines:sub(1, 1990) end if #lines ~= 0 then return msg:reply(code(lines)) end end return { description = locale("code.description"), permissions = { ids = {"260157417445130241"} }, category = "dev" }, function(message,args,flags) if #args.stringArgs == 0 then --REPL MODE message:reply("**REPL MODE ENABLED.** Say **quit()** or **q()** to disable REPL.") while true do local arg = respond:args { { prompt = "", type = "string", name = "code", } } if arg.code == "quit()" or arg.code == "q()" then respond:quit() message:reply("**REPL MODE DISABLED.**") return end executeLua(arg.code,message) end else local code = table.concat(args.stringArgs," ") executeLua(code,message) end end
local image = require('../image') return { name = "Merlin", description = "He keeps going on about 'programming' and 'algorithms'. Just what are those?", image = image.merlin }
-- Vehicle Data local VD = ts_vehicles.get ts_vehicles.handle_rightclick = function(self, player, def) local player_name = player:get_player_name() local wielded_item = player:get_wielded_item() local item_name = wielded_item:get_name() local control = player:get_player_control() local vd = VD(self._id) local refill_tanks = { "techage:ta3_barrel_gasoline", "techage:ta3_canister_gasoline", "techage:cylinder_small_hydrogen", "techage:cylinder_large_hydrogen", "techage:ta3_akku" } if control.sneak then ts_vehicles.show_formspec(self, player, def) elseif ts_vehicles.registered_parts[item_name] and ts_vehicles.registered_compatibilities[self.name][item_name] then if ts_vehicles.helpers.contains(vd.owners, player_name) then local got_added, reason = ts_vehicles.add_part(self, wielded_item, player) if not got_added then minetest.chat_send_player(player_name, minetest.colorize("#f00", "[Vehicle] Can't add part: "..reason)) end else minetest.chat_send_player(player_name, minetest.colorize("#f00", "[Vehicle] You don't have access to this vehicle.")) end elseif item_name == "ts_vehicles_common:universal_key" and minetest.check_player_privs(player_name, ts_vehicles.priv) and not ts_vehicles.helpers.contains(vd.owners, player_name) then table.insert(vd.owners, player_name) elseif ts_vehicles.helpers.contains(refill_tanks, item_name) then if ts_vehicles.helpers.contains(vd.owners, player_name) then if item_name == "techage:ta3_barrel_gasoline" or item_name == "techage:ta3_canister_gasoline" then local amount = item_name == "techage:ta3_barrel_gasoline" and 10 or 1 local free = ts_vehicles.helpers.get_total_value(self, "gasoline_capacity") - (vd.data.gasoline or 0) if amount <= free then vd.data.gasoline = (vd.data.gasoline or 0) + amount player:set_wielded_item(item_name == "techage:ta3_barrel_gasoline" and "techage:ta3_barrel_empty" or "techage:ta3_canister_empty") end elseif item_name == "techage:cylinder_large_hydrogen" or item_name == "techage:cylinder_small_hydrogen" then local amount = item_name == "techage:cylinder_large_hydrogen" and 6 or 1 local free = ts_vehicles.helpers.get_total_value(self, "hydrogen_capacity") - (vd.data.hydrogen or 0) if amount <= free then vd.data.hydrogen = (vd.data.hydrogen or 0) + amount player:set_wielded_item(item_name == "techage:cylinder_large_hydrogen" and "techage:ta3_cylinder_large" or "techage:ta3_cylinder_small") end elseif item_name == "techage:ta3_akku" then local meta = wielded_item:get_meta() local count = wielded_item:get_count() local free = ts_vehicles.helpers.get_total_value(self, "electricity_capacity") - (vd.data.electricity or 0) local capa = meta:get_int("capa") * count local amount = math.min(free, capa) vd.data.electricity = (vd.data.electricity or 0) + amount local new_capa = math.floor(((capa - amount) / count) / 5) * 5 meta:set_int("capa", new_capa) meta:set_string("description", techage.S("TA3 Accu Box").." ("..new_capa.." %)") player:set_wielded_item(wielded_item) end else minetest.chat_send_player(player_name, minetest.colorize("#f00", "[Vehicle] You don't have access to this vehicle.")) end elseif ts_vehicles.passengers.is_passenger(self, player) then ts_vehicles.passengers.up(self, player) elseif vd.driver == nil and ts_vehicles.helpers.contains(vd.owners, player_name) then local is_driveable, reason = def.is_driveable(self) if is_driveable then local pos = self.object:get_pos() vd.driver = player_name ts_vehicles.sit(pos, player, def.driver_pos) player:set_attach(self.object, nil, def.driver_pos, {x=0,y=0,z=0}) player:set_look_horizontal(self.object:get_yaw() % (math.pi * 2)) ts_vehicles.hud.create(player) else minetest.chat_send_player(player_name, minetest.colorize("#f00", "[Vehicle] "..reason)) end elseif vd.driver == player_name then ts_vehicles.up(player) vd.driver = nil player:set_detach() ts_vehicles.hud.remove(player) elseif ts_vehicles.passengers.get_num_free_seats(self, def) > 0 then if not vd.passengers_closed or ts_vehicles.helpers.contains(vd.owners, player_name) then local is_driveable, reason = def.is_driveable(self) if is_driveable then ts_vehicles.passengers.sit(self, player, def) else minetest.chat_send_player(player_name, minetest.colorize("#f00", "[Vehicle] "..reason)) end else minetest.chat_send_player(player_name, minetest.colorize("#f00", "[Vehicle] You don't have access to this vehicle.")) end end end ts_vehicles.handle_leftclick = function(self, player, def) local player_name = player:get_player_name() local vd = VD(self._id) if ts_vehicles.helpers.contains(vd.owners, player_name) then if #vd.parts == 0 then local inv = player:get_inventory() local leftover = inv:add_item("main", self.name) if leftover:get_count() > 0 then minetest.add_item(player:get_pos(), self.name) end self.object:remove() else ts_vehicles.storage.add_by_player(self, player) end else minetest.chat_send_player(player_name, minetest.colorize("#f00", "[Vehicle] You don't have access to this vehicle.")) end end ts_vehicles.handle_timing = function(vd, dtime) local is_full_second = false vd.dtime = vd.dtime + dtime if vd.last_light_time ~= nil then vd.last_light_time = vd.last_light_time + dtime if vd.last_light_time > 0.5 then vd.last_light_time = nil end end if vd.dtime > 1 then is_full_second = true vd.even_step = not vd.even_step vd.dtime = 0 end return is_full_second end ts_vehicles.handle_turn = function(self, driver, control, dtime) local vehicle = self.object local yaw = vehicle:get_yaw() % (math.pi * 2) if control and (control.left or control.right) then local vd = VD(self._id) if (vd.data.turn_snap or 0) > 0 then vd.data.turn_snap = (vd.data.turn_snap or 0) - dtime else local delta = dtime * math.log(math.abs(vd.v) + 1) * ts_vehicles.helpers.sign(vd.v) / 2 if control.right then delta = -delta end local snap_delta = (yaw + (math.pi / 8)) % (math.pi / 4) - math.pi / 8 if math.abs(snap_delta) < math.abs(delta * .9) and math.abs(snap_delta) > 0.001 then delta = -snap_delta vd.data.turn_snap = .4 end yaw = yaw + delta ts_vehicles.helpers.turn_player(driver, delta) ts_vehicles.passengers.turn(self, delta) vehicle:set_yaw(yaw) end end return yaw end ts_vehicles.handle_car_light_controls = function(self, control) local vd = VD(self._id) if control then if not control.sneak then vd.last_light_time = nil elseif vd.last_light_time == nil then if control.aux1 then vd.lights.special = not vd.lights.special vd.tmp.light_textures_set = false vd.last_light_time = 0 elseif control.down then vd.lights.warn = not vd.lights.warn vd.tmp.light_textures_set = false vd.last_light_time = 0 elseif control.up then vd.lights.front = not vd.lights.front vd.tmp.light_textures_set = false vd.last_light_time = 0 elseif control.left then vd.lights.left = not vd.lights.left vd.tmp.light_textures_set = false vd.lights.right = false vd.last_light_time = 0 elseif control.right then vd.lights.right = not vd.lights.right vd.tmp.light_textures_set = false vd.lights.left = false vd.last_light_time = 0 end end local stop_lights = false if control.jump then stop_lights = true elseif control.up then stop_lights = vd.v < 0 and true or stop_lights elseif control.down then stop_lights = vd.v > 0 and true or stop_lights end if vd.lights.stop ~= stop_lights then vd.lights.stop = stop_lights vd.tmp.light_textures_set = false end elseif vd.lights.stop then vd.lights.stop = false vd.tmp.light_textures_set = false end local back = vd.v < 0 if vd.lights.back ~= back then vd.lights.back = back vd.tmp.light_textures_set = false end end ts_vehicles.car_on_step = function(self, dtime, moveresult, def, is_full_second) local vehicle = self.object local vd = VD(self._id) local player = vd.driver and minetest.get_player_by_name(vd.driver) or nil local control = player and player:get_player_control() or nil if player and is_full_second then ts_vehicles.hud.car_update(player, self) end local velocity = vehicle:get_velocity() if velocity.y < -20 then ts_vehicles.disperse(self) return end local new_velocity = player and ts_vehicles.get_car_velocity(self, dtime, control, moveresult, def, is_full_second) or 0 vd.data.total_distance = (vd.data.total_distance or 0) + dtime * vd.v vd.v = new_velocity local yaw = ts_vehicles.handle_turn(self, player, control, dtime) local dir = minetest.yaw_to_dir(yaw) vehicle:set_velocity({x = dir.x * new_velocity, y = velocity.y, z = dir.z * new_velocity}) ts_vehicles.handle_car_light_controls(self, control) if not vd.tmp.base_textures_set then ts_vehicles.apply_textures(self, ts_vehicles.build_textures(def.name, def.textures, vd.parts, self)) vd.tmp.base_textures_set = true end if not vd.tmp.light_textures_set then ts_vehicles.apply_light_textures(self, ts_vehicles.build_light_textures(def.name, def.lighting_textures, vd.parts, self)) vd.tmp.light_textures_set = true end if is_full_second then ts_vehicles.car_light_beam(self) local tire_pos, car_length = ts_vehicles.helpers.get_rotated_collisionbox_corners(self) local max_depth = def.stepheight * car_length * 1.5 local front_downwards_space = math.max(ts_vehicles.helpers.downwards_space(tire_pos[1], max_depth), ts_vehicles.helpers.downwards_space(tire_pos[2], max_depth)) local back_downwards_space = math.max(ts_vehicles.helpers.downwards_space(tire_pos[3], max_depth), ts_vehicles.helpers.downwards_space(tire_pos[4], max_depth)) local delta_y = front_downwards_space - back_downwards_space ts_vehicles.helpers.pitch_vehicle(self, delta_y, car_length, def) vd.last_seen_pos = vehicle:get_pos() end end ts_vehicles.remove_part = function(self, part_name, player) local vehicle_def = ts_vehicles.registered_vehicle_bases[self.name] local can_remove, reason, drop = true, "", part_name if vehicle_def.can_remove_part then can_remove, reason = vehicle_def.can_remove_part(self, part_name) end if not can_remove then return false, reason end drop = vehicle_def.get_part_drop(self, part_name) if drop == nil then return false, "Cannot remove part!" end ts_vehicles.helpers.part_get_property("after_part_remove", part_name, self.name, function(...) end)(self, drop) local inv = player:get_inventory() local leftover = inv:add_item("main", drop) if leftover:get_count() > 0 then minetest.add_item(player:get_pos(), leftover) end local vd = VD(self._id) table.remove(vd.parts, ts_vehicles.helpers.index_of(vd.parts, part_name)) vd.tmp.base_textures_set = false vd.tmp.light_textures_set = false return true end ts_vehicles.add_part = function(self, item, player) local vehicle_def = ts_vehicles.registered_vehicle_bases[self.name] local can_add, reason, leftover = true, "", ItemStack(item) local part_name = item:get_name() if vehicle_def.can_add_part then can_add, reason, leftover = vehicle_def.can_add_part(self, ItemStack(item)) else leftover:take_item() end if not can_add then return false, reason end player:set_wielded_item(leftover) local vd = VD(self._id) table.insert(vd.parts, part_name) ts_vehicles.helpers.part_get_property("after_part_add", part_name, self.name, function(...) end)(self, ItemStack(item)) vd.tmp.base_textures_set = false vd.tmp.light_textures_set = false return true end ts_vehicles.ensure_is_driveable = function(self) local vd = VD(self._id) local def = ts_vehicles.registered_vehicle_bases[self.name] local is_driveable, reason = def.is_driveable(self) if not is_driveable then if vd.driver then local player = minetest.get_player_by_name(vd.driver) if player then minetest.chat_send_player(vd.driver, minetest.colorize("#f00", "[Vehicle] "..reason)) ts_vehicles.up(player) vd.driver = nil player:set_detach() ts_vehicles.hud.remove(player) end end ts_vehicles.passengers.throw_all_out(self, reason) end end ts_vehicles.ensure_attachments = function(self) local children = self.object:get_children() local attached_players = {} for _,child in ipairs(children) do if child.get_player_name and child:get_player_name() and child:get_player_name() ~= "" then attached_players[child:get_player_name()] = true end end local vd = VD(self._id) if vd.driver and not attached_players[vd.driver] then local player = minetest.get_player_by_name(vd.driver) if player then ts_vehicles.up(player) player:set_detach() ts_vehicles.hud.remove(player) end vd.driver = nil end for _,passenger in ipairs(ts_vehicles.passengers.get_passenger_list(self)) do if passenger and not attached_players[passenger] then ts_vehicles.passengers.up_by_name(self, passenger) end end end ts_vehicles.disperse = function(entity) local pos = entity.object:get_pos() for _,part_name in ipairs(entity._parts) do local vehicle_def = ts_vehicles.registered_vehicle_bases[entity.name] local drop = vehicle_def.get_part_drop(entity, part_name) if drop ~= nil then ts_vehicles.helpers.part_get_property("after_part_remove", part_name, entity.name, function(...) end)(entity, drop) minetest.add_item(pos, drop) end end while #entity._storage > 0 do local stack = ts_vehicles.storage.take(entity, 1) minetest.add_item(pos, stack) end if entity._driver then local player = minetest.get_player_by_name(entity._driver) if player then minetest.chat_send_player(entity._driver, minetest.colorize("#f00", "[Vehicle] The vehicle got destroyed")) ts_vehicles.up(player) entity._driver = nil player:set_detach() ts_vehicles.hud.remove(player) end end ts_vehicles.passengers.throw_all_out(entity, "[Vehicle] The vehicle got destroyed") entity.object:remove() end
local webviewLib = require('webview') -- This module allows to launch a web page that could executes custom Lua code. -- The webview library may change locale to native and thus mislead the JSON libraries. if os.setlocale() == 'C' then -- Default locale is 'C' at startup, set native locale os.setlocale('') end -- Load JSON module local status, jsonLib = pcall(require, 'cjson') if not status then status, jsonLib = pcall(require, 'dkjson') if not status then -- provide a basic JSON implementation suitable for basic types local escapeMap = { ['\b'] = '\\b', ['\f'] = '\\f', ['\n'] = '\\n', ['\r'] = '\\r', ['\t'] = '\\t', ['"'] = '\\"', ['\\'] = '\\\\', ['/'] = '\\/', } local revertMap = {}; for c, s in pairs(escapeMap) do revertMap[s] = c; end jsonLib = { null = {}, decode = function(value) if string.sub(value, 1, 1) == '"' and string.sub(value, -1, -1) == '"' then return string.gsub(string.gsub(string.sub(value, 2, -2), '\\u(%x%x%x%x)', function(s) return string.char(tonumber(s, 16)) end), '\\.', function(s) return revertMap[s] or '' end) elseif string.match(value, '^%s*[%-%+]?%d[%d%.%s]*$') then return tonumber(value) elseif (value == 'true') or (value == 'false') then return value == 'true' elseif value == 'null' then return jsonLib.null end return nil end, encode = function(value) local valueType = type(value) if valueType == 'boolean' then return value and 'true' or 'false' elseif valueType == 'number' then return (string.gsub(tostring(value), ',', '.', 1)) elseif valueType == 'string' then return '"'..string.gsub(value, '[%c"/\\]', function(c) return escapeMap[c] or string.format('\\u%04X', string.byte(c)) end)..'"' elseif value == jsonLib.null then return 'null' end return 'undefined' end } end end -- OS file separator local fileSeparator = string.sub(package.config, 1, 1) or '/' -- Load file system module local fsLib status, fsLib = pcall(require, 'luv') if status then local uvLib = fsLib fsLib = { currentdir = uvLib.cwd, attributes = uvLib.fs_stat, } else status, fsLib = pcall(require, 'lfs') if not status then -- provide a basic file system implementation fsLib = { currentdir = function() local f = io.popen(fileSeparator == '\\' and 'cd' or 'pwd') if f then local d = f:read() f:close() return d end return '.' end, attributes = function(p) local f = io.open(p) if f then f:close() return {} end return nil end, } end end -- Lua code injected to provide default local variables local localContextLua = 'local evalJs, callJs, expose = context.evalJs, context.callJs, context.expose; ' local function exposeFunctionJs(name, remove) local nameJs = "'"..name.."'" if remove then return 'delete webview['..nameJs..'];\n'; end return 'webview['..nameJs..'] = function(value, callback) {'.. 'webview.invokeLua('..nameJs..', value, callback);'.. '};\n' end -- Initializes the web view and provides a global JavaScript webview object local function initializeJs(webview, functionMap, options) local jsContent = [[ if (typeof window.webview === 'object') { console.log('webview object already exists'); } else { console.log('initialize webview object'); var webview = {}; window.webview = webview; var refs = {}; var callbackToRef = function(callback, delay) { if (typeof callback === 'function') { var ref; var id = setTimeout(function() { var cb = refs[ref]; if (cb) { delete refs[ref]; cb('timeout'); } }, delay); ref = id.toString(36); refs[ref] = callback; return ref; } return null; }; webview.callbackRef = function(ref, reason, result) { var id = parseInt(ref, 36); clearTimeout(id); var callback = refs[ref]; if (callback) { delete refs[ref]; callback(reason, result); } }; webview.invokeLua = function(name, value, callback, delay) { var kind = ':', data = ''; if (typeof value === 'string') { data = value; } else if (typeof value === 'function') { delay = callback; callback = value; } else if (value !== undefined) { kind = ';'; data = JSON.stringify(value); } var message; var ref = callbackToRef(callback, delay || 30000); if (ref) { message = '#' + name + kind + ref + ';' + data; } else { message = name + kind + data; } window.external.invoke(message); }; ]] if options and options.captureError then jsContent = jsContent..[[ window.onerror = function(message, source, lineno, colno, error) { var message = '' + message; // Just "Script error." when occurs in different origin if (source) { message += '\n source: ' + source + ', line: ' + lineno + ', col: ' + colno; } if (error) { message += '\n error: ' + error; } window.external.invoke(':error:' + message); return true; }; ]] end if options and options.useJsTitle then jsContent = jsContent..[[ if (document.title) { window.external.invoke('title:' + document.title); } ]] end if functionMap then for name in pairs(functionMap) do jsContent = jsContent..exposeFunctionJs(name) end end if options and options.luaScript then jsContent = jsContent..[[ var evalLuaScripts = function() { var scripts = document.getElementsByTagName('script'); for (var i = 0; i < scripts.length; i++) { var script = scripts[i]; if (script.getAttribute('type') === 'text/lua') { var src = script.getAttribute('src'); if (src) { window.external.invoke('evalLuaSrc:' + src); } else { window.external.invoke('evalLua:' + script.text); } } } }; if (document.readyState !== 'loading') { evalLuaScripts(); } else { document.addEventListener('DOMContentLoaded', evalLuaScripts); } ]] end jsContent = jsContent..[[ var completeInitialization = function() { if (typeof window.onWebviewInitalized === 'function') { webview.evalJs("window.onWebviewInitalized(window.webview);"); } }; if (document.readyState === 'complete') { completeInitialization(); } else { window.addEventListener('load', completeInitialization); } } ]] webviewLib.eval(webview, jsContent, true) end -- Prints error message to the error stream local function printError(value) io.stderr:write('WebView Launcher - '..tostring(value)..'\n') end local function callbackJs(webview, ref, reason, result) webviewLib.eval(webview, 'if (webview) {'.. 'webview.callbackRef("'..ref..'", '..jsonLib.encode(reason)..', '..jsonLib.encode(result)..');'.. '}', true) end local function handleCallback(callback, reason, result) if callback then callback(reason, result) elseif reason then printError(reason) end end -- Executes the specified Lua code local function evalLua(value, callback, context, webview) local f, err = load('local callback, context, webview = ...; '..localContextLua..value) if f then f(callback, context, webview) else handleCallback(callback, 'Error '..tostring(err)..' while loading '..tostring(value)) end end -- Toggles the web view full screen on/off local function fullscreen(value, callback, _, webview) webviewLib.fullscreen(webview, value == 'true') handleCallback(callback) end -- Sets the web view title local function setTitle(value, callback, _, webview) webviewLib.title(webview, value) handleCallback(callback) end -- Terminates the web view local function terminate(_, callback, _, webview) webviewLib.terminate(webview, true) handleCallback(callback) end -- Executes the specified Lua file relative to the URL local function evalLuaSrc(value, callback, context, webview) local content if context.luaSrcPath then local path = context.luaSrcPath..fileSeparator..string.gsub(value, '[/\\]+', fileSeparator) local file = io.open(path) if file then content = file:read('a') file:close() end end if content then evalLua(content, callback, context, webview) else handleCallback(callback, 'Cannot load Lua file from src "'..tostring(value)..'"') end end -- Evaluates the specified JS code local function evalJs(value, callback, _, webview) webviewLib.eval(webview, value, true) handleCallback(callback) end -- Calls the specified JS function name, -- the arguments are JSON encoded then passed to the JS function local function callJs(webview, functionName, ...) local argCount = select('#', ...) local args = {...} for i = 1, argCount do args[i] = jsonLib.encode(args[i]) end local jsString = functionName..'('..table.concat(args, ',')..')' webviewLib.eval(webview, jsString, true) end -- Creates the webview context and sets the callback and default functions local function createContext(webview, options) local initialized = false -- Named requests callable from JS using window.external.invoke('name:value') -- Custom request can be registered using window.external.invoke('+name:Lua code') -- The Lua code has access to the string value, the evalJs() and callJs() functions local functionMap = { fullscreen = fullscreen, title = setTitle, terminate = terminate, evalLua = evalLua, evalLuaSrc = evalLuaSrc, evalJs = evalJs, } -- Defines the context that will be shared across Lua calls local context = { expose = function(name, fn) functionMap[name] = fn if initialized then webviewLib.eval(webview, exposeFunctionJs(name, not fn), true) end end, exposeAll = function(fnMap) local jsContent = '' for name, fn in pairs(fnMap) do functionMap[name] = fn jsContent = jsContent..exposeFunctionJs(name, not fn) end if initialized then webviewLib.eval(webview, jsContent, true) end end, -- Setup a Lua function to evaluates JS code evalJs = function(value) webviewLib.eval(webview, value, true) end, callJs = function(functionName, ...) callJs(webview, functionName, ...) end, callbackJs = function(ref, reason, result) callbackJs(webview, ref, reason, result) end, terminate = function() webviewLib.terminate(webview, true) end, } if options and type(options.expose) == 'table' then context.exposeAll(options.expose) end if options and type(options.context) == 'table' then for name, value in pairs(options.context) do context[name] = value end end -- Creates the web view callback that handles the JS requests coming from window.external.invoke() local handler = function(request) local flag, name, kind, value = string.match(request, '^(%A?)(%a%w*)([:;])(.*)$') if name then if flag == '' or flag == '#' then -- Look for the specified function local fn = functionMap[name] local callback, cbRef if fn then if flag == '#' then local ref, val = string.match(value, '^(%w+);(.*)$') if ref and val then value = val cbRef = ref callback = function(reason, result) callbackJs(webview, ref, reason, result) end else printError('Invalid reference request '..request) return end end local s, r if kind == ';' then s, r = pcall(jsonLib.decode, value) if s then value = r else handleCallback(callback, 'Fail to parse '..name..' JSON value "'..tostring(value)..'" due to '..tostring(r)) return end end s, r = pcall(fn, value, callback, context, webview, cbRef) if not s then handleCallback(callback, 'Fail to execute '..name..' due to '..tostring(r)) end else printError('Unknown function '..name) end elseif flag == '-' then context.expose(name) elseif flag == '+' then -- Registering the new function using the specified Lua code local injected = 'local value, callback, context, webview = ...; ' local fn, err = load(injected..localContextLua..value) if fn then context.expose(name, fn) else printError('Error '..tostring(err)..' while loading '..tostring(value)) end elseif name == 'error' and flag == ':' then printError(value) elseif name == 'init' and flag == ':' then initialized = true initializeJs(webview, functionMap, options) else printError('Invalid flag '..flag..' for name '..name) end else printError('Invalid request #'..tostring(request and #request)..' "'..tostring(request)..'"') end end if options and options.initialize then initialized = true initializeJs(webview, functionMap, options) end return handler end local function escapeUrl(value) return string.gsub(value, "[ %c!#$%%&'()*+,/:;=?@%[%]]", function(c) return string.format('%%%02X', string.byte(c)) end) end local function parseArgs(args) -- Default web content local url = 'data:text/html,'..escapeUrl([[<!DOCTYPE html> <html> <head> <title>Welcome WebView</title> </head> <script type="text/lua"> print('You could specify an HTML file to launch as a command line argument.') </script> <body> <h1>Welcome !</h1> <p>You could specify an HTML file to launch as a command line argument.</p> <button onclick="window.external.invoke('terminate:')">Close</button> </body> </html> ]]) local title local width = 800 local height = 600 local resizable = true local debug = false local eventMode = nil local initialize = true local luaScript = true local captureError = true local luaPath = false -- Parse command line arguments args = args or arg or {} local ctxArgs = {} local luaSrcPath = nil local urlArg for i = 1, #args do local name, value = string.match(args[i], '^%-%-wv%-([^=]+)=?(.*)$') if not name then if urlArg then table.insert(ctxArgs, args[i]) else urlArg = args[i] end elseif name == 'size' and value then local w, h = string.match(value, '^(%d+)[xX-/](%d+)$') width = tonumber(w) height = tonumber(h) elseif name == 'title' and value then title = value elseif name == 'width' and tonumber(value) then width = tonumber(value) elseif name == 'height' and tonumber(value) then height = tonumber(value) elseif name == 'resizable' then resizable = value ~= 'false' elseif name == 'debug' then debug = value == 'true' elseif name == 'event' and (value == 'open' or value == 'main' or value == 'thread' or value == 'http') then eventMode = value elseif name == 'initialize' then initialize = value ~= 'false' elseif name == 'script' then luaScript = value ~= 'false' elseif name == 'captureError' then captureError = value ~= 'false' elseif name == 'luaPath' then luaPath = value == 'true' else print('Invalid argument', args[i]) os.exit(22) end end -- Process URL argument if urlArg and urlArg ~= '' then if urlArg == '-h' or urlArg == '/?' or urlArg == '--help' then print('Launchs a WebView using the specified URL') print('Optional arguments: url --wv-title= --wv-width='..tostring(width)..' --wv-height='..tostring(height)..' --wv-resizable='..tostring(resizable)) os.exit(0) end local protocol = string.match(urlArg, '^([^:]+):.+$') if protocol == 'http' or protocol == 'https' or protocol == 'file' or protocol == 'data' then url = urlArg else local filePath if string.match(urlArg, '^.:\\.+$') or string.match(urlArg, '^/.+$') then filePath = urlArg elseif fsLib then filePath = fsLib.currentdir()..fileSeparator..urlArg end if not filePath then print('Invalid URL, to launch a file please use an absolute path') os.exit(22) end luaSrcPath = string.match(filePath, '^(.*)[/\\][^/\\]+$') url = 'file://'..filePath end end if luaSrcPath and luaPath then package.path = package.path..';'..luaSrcPath..'/?.lua' end return url, { title = title or 'Web View', width = width, height = height, resizable = resizable, debug = debug }, { eventMode = eventMode, initialize = initialize, useJsTitle = not title, luaScript = luaScript, luaPath = luaPath, captureError = captureError, context = { args = ctxArgs, luaSrcPath = luaSrcPath, }, } end local function createContextAndPath(wv, opts) if opts.luaPath and opts.context and opts.context.luaSrcPath then package.path = package.path..';'..opts.context.luaSrcPath..'/?.lua' end return createContext(wv, opts) end local function launchWithOptions(url, wvOptions, options) wvOptions = wvOptions or {} options = options or wvOptions if options.eventMode then local event = require('jls.lang.event') local WebView = require('jls.util.WebView') if options.eventMode == 'thread' then --webviewLib.open('data:text/html,<html><body>Close to start</body></thread>', 'Close to start', 320, 200) WebView.open(url, wvOptions):next(function(webview) local callback = createContextAndPath(webview._webview, options) webview:callback(callback) end) elseif options.eventMode == 'http' then if not options.context.luaSrcPath then error('Please specify a file path as URL') end local FileHttpHandler = require('jls.net.http.handler.FileHttpHandler') options.callback = true options.contexts = { ['/(.*)'] = FileHttpHandler:new(options.context.luaSrcPath or '.') } local filename = string.match(url, '^.*[/\\]([^/\\]+)$') WebView.open('http://localhost:0/'..filename, options):next(function(webview) local callback = createContextAndPath(webview._webview, options) webview:callback(callback) end) else local open = options.eventMode == 'main' and WebView.openSync or WebView.open wvOptions.fn = function(webview, data) local webviewLauncher = require('webview-launcher') local opts = webviewLauncher.jsonLib.decode(data) local callback = webviewLauncher.createContextAndPath(webview._webview, opts) webview:callback(callback) end wvOptions.data = jsonLib.encode(options) open(url, wvOptions) end event:loop() else local webview = webviewLib.new(url, wvOptions.title, wvOptions.width, wvOptions.height, wvOptions.resizable, wvOptions.debug) local callback = createContext(webview, options) webviewLib.callback(webview, callback) webviewLib.loop(webview) end end return { initializeJs = initializeJs, createContext = createContext, createContextAndPath = createContextAndPath, escapeUrl = escapeUrl, launchFromArgs = function(args, ...) if type(args) == 'string' then args = {args, ...} elseif type(args) ~= 'table' then args = arg end launchWithOptions(parseArgs(args)) end, launchWithOptions = launchWithOptions, jsonLib = jsonLib, fsLib = fsLib, }
object_ship_nova_orion_pirate_light_tier1 = object_ship_shared_nova_orion_pirate_light_tier1:new { } ObjectTemplates:addTemplate(object_ship_nova_orion_pirate_light_tier1, "object/ship/nova_orion_pirate_light_tier1.iff")
--[[ 说明: 根据分隔符(或者分隔符的正则式)来切分字符串 返回值: table 包含各个被切分的字符串的数组 参数: s string 源字符串 sep string 分隔符或者分隔符的正则表达式 ]] function string.split(s, sep) s = tostring(s) sep = tostring(sep) assert(sep ~= '') if string.len(s) == 0 then return {} end local pos, r = 0, {} local iterator = function() return string.find(s, sep, pos) end -- 这里采用非朴素搜索,即sep可以是类似正则表达式子的东西 for pos_b, pos_e in iterator do table.insert(r, string.sub(s, pos, pos_b - 1)) pos = pos_e + 1 end s = string.sub(s, pos) if string.len(s) > 0 then table.insert(r, s) end return r end --[[ 说明: 将数组转化成字符串(只能是数组,不能是hash表) 返回值: string 字符串 参数: t table 源数组 sep string 可选参数 分隔字符 默认为',' 注意:数组中的元素如果是字符串,则可能包含sep,这将会影响strtoarr的转换,因此需要处理下 ]] local tRepChars = { [","] = ",", [";"] = ";", } function string.arrtostr(t, sep) if #t == 0 then return "" end sep = sep or ',' local r = {} for _, v in ipairs(t) do if type(v) == "string" then v = string.gsub(v, sep, tRepChars) end table.insert(r, v) end return table.concat(r, sep) .. sep end --[[ 说明: 将字符串转换成数组 返回值: table 数组 参数: s string 源字符串 sep string 可选参数 分隔字符 默认为',' fconvert function 可选参数 分隔后的数组中的元素全是字符串,可以传个转换函数将其转成所需要的类型 ]] function string.strtoarr(s, sep, fconvert) sep = sep or ',' if fconvert then assert(type(fconvert) == "function") end local r = string.split(s, sep) if fconvert then for i, v in ipairs(r) do r[i] = fconvert(v) end end return r end --[[ 说明: 将二维的数据转换成字符串 返回值: string 字符串 参数: t table 源数组 sep1 string 可选参数 内层数组的分隔符 sep2 string 可选参数 外层数组的分隔符 注意:数组中的元素如果是字符串,则可能包含sep,这将会影响strtomultiarr的转换,因此需要处理下 ]] function string.multiarrtostr(t, sep1, sep2) if #t == 0 then return "" end sep1 = sep1 or ',' sep2 = sep2 or ';' local rep = "[" .. sep1 .. sep2 .. "]" local r = {} for _, v in ipairs(t) do for ii, vv in ipairs(v) do if type(vv) == "string" then v[ii] = string.gsub(vv, rep, tRepChars) end end table.insert(r, table.concat(v, sep1) .. sep1) end return table.concat(r, sep2) .. sep2 end --[[ 说明: 将字符串转换成二维数组 返回值: table 数组 参数: s string 源字符串 sep1 string 可选参数 内层数组的分隔符 sep2 string 可选参数 外层数组的分隔符 fconvert function 可选参数 分隔后的数组中的元素全是字符串,可以传个转换函数将其转成所需要的类型 ]] function string.strtomultiarr(s, sep1, sep2, fconvert) sep1 = sep1 or ',' sep2 = sep2 or ';' local r = {} local t = strtoarr(s, sep2) for i, v in ipairs(t) do table.insert(r, strtoarr(v, sep1, fconvert)) end return r end --[[ 说明: 将hash表转换成字符串 返回值: string 字符串 参数: t table 源hash表 注意: t中的key和value中可能包含','和';',这将扰乱strtotbl,所以函数内部直接将其转换成中文中的字符 ]] function string.tbltostr(t, sep1, sep2) sep1 = sep1 or ',' sep2 = sep2 or ';' local rep = "[" .. sep1 .. sep2 .. "]" local r for k, v in pairs(t) do if type(k) == "string" then k = string.gsub(k, rep, tRepChars) end if type(v) == "string" then v = string.gsub(v, rep, tRepChars) end r = not r and string.format("%s%s%s", k, sep1, v) or string.format("%s%s%s%s%s", r, sep2, k, sep1, v) end return r or "" end --[[ 说明: 将字符串转换为hash表 返回值: table hash表 参数: s string 源字符串 kconvert function 可选参数 key的类型转换函数(字符串-->想要的类型) vconvert function 可选参数 value的类型转换函数(字符串-->想要的类型) ]] function string.strtotbl(s, sep1, sep2, kconvert, vconvert) sep1 = sep1 or ',' sep2 = sep2 or ';' local t = strtomultiarr(s, sep1, sep2) local r = {} for _, v in ipairs(t) do local kk, vv = unpack(v) if kk and vv then if kconvert then kk = kconvert(kk) end if vconvert then vv = vconvert(vv) end r[kk] = vv end end return r end --[[ 说明: 序列化整个tabel(可被直接反序列化),可以嵌套table,可以是hash表和数组或者两者的混合 返回值: string 字符串 参数: t table 源table ]] function string.serialize(t) local names = {} local assigns = {} local function ser(t1, name) names[t1] = name local items = {} for k, v in pairs(t1) do local tp = type(k) local key if tp == "string" then key = string.format("[%q]", k) elseif tp == "number" or tp == "boolean" then key = string.format("[%s]", tostring(k)) else assert(false, "the key of serializable type only support 'string', 'number' and 'boolean'") end tp = type(v) if tp == "string" then table.insert(items, string.format("%s=%q", key, v)) elseif tp == "number" or tp == "boolean" then table.insert(items, string.format("%s=%s", key, tostring(v))) elseif tp == "table" then local tbl_name = string.format("%s%s", name, key) if names[v] then table.insert(assigns, string.format("%s=%s", tbl_name, names[v])) else table.insert(items, string.format("%s=%s", key, ser(v, tbl_name))) end else assert(false, "the value of serializable type only support 'string', 'number', 'boolean' and 'table'") end end return string.format("{%s}", table.concat(items, ",")) end local ret_str = ser(t, "ret") local assign_str = table.concat(assigns, " ") return string.format("do local ret = %s %s return ret end", ret_str, assign_str) end --[[ 说明: 反序列化字符串为table 返回值: table hashb表 参数: s string 源字符串 ]] function string.unserialize(s) local f = load(s) assert(f, string.format("string unserialize to table error. string:%s", s)) return f() end --[[ 说明: 获取hash表的打印排版后的字符串,专门用于打印输出 返回值: string 经过排版后的字符串 参数: t table 源hash表 maxlevel number 可选参数 hash表展开的层数 默认全部展开 ]] function string.toprint(t, maxlevel) if not IsTable(t) then return tostring(t) end maxlevel = maxlevel or 0 local names = {} local function ser(t1, name, level) if maxlevel > 0 and level > maxlevel then return "{...}" end names[t1] = name local items = {} for k, v in pairs(t1) do local key local tp = type(k) if tp == "string" then key = string.format("[%q]", k) elseif tp == "number" or tp == "boolean" or tp == "table" or tp == "function" then key = string.format("[%s]", tostring(k)) else assert(false, "key type unsupported") end tp = type(v) local str if tp == "string" then str = string.format("%s = %q,", key, v) elseif tp == "number" or tp == "boolean" or tp == "function" then str = string.format("%s = %s,", key, tostring(v)) elseif tp == "table" then if names[v] then str = string.format("%s = %s,", key, names[v]) else str = string.format("%s = %s,", key, ser(v, string.format("%s%s", name, key), level+1)) end else assert(false, "value type unsupported") end str = string.format("%s%s", string.rep("\t", level), str) table.insert(items, str) end if #items == 0 then return "{}" end local tabs = string.rep("\t", level - 1) local ret if level ~= 1 then ret = string.format("\n%s{\n%s\n%s}", tabs, table.concat(items, "\n"), tabs) else ret = string.format("%s{\n%s\n%s}", tabs, table.concat(items, "\n"), tabs) end return ret end return ser(t, "$self", 1) end function string.utf8len(input) AssertString(input) local lengthList = {} local len = string.len(input) local left = len local cnt = 0 local arr = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc} while left ~= 0 do local tmp = string.byte(input, -left) local i = #arr while arr[i] do if tmp >= arr[i] then left = left - i local tempLength = i if tempLength > 4 then tempLength = 4 end table.insert(lengthList, tempLength) break end i = i - 1 end cnt = cnt + 1 end return cnt, lengthList end function string.utf8sub(input, nStart, nEnd) AssertString(input) AssertNumber(nStart) AssertNumber(nEnd) local len = string.len(input) local left = len local cnt = 0 local arr = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc} local nStrStart = 1 local nStrEnd = len while left ~= 0 do local tmp = string.byte(input, -left) local i = #arr while arr[i] do if tmp >= arr[i] then left = left - i break end i = i - 1 end cnt = cnt + 1 if nStart == cnt then nStrStart = -left elseif nEnd == cnt then nStrEnd = -(left + 1) end end return string.sub(input, nStrStart, nStrEnd) end function string.unicode_to_utf8(convertStr) if type(convertStr) ~= "string" then return convertStr end local resultStr="" local i=1 while true do local num1=string.byte(convertStr,i) local unicode if num1~=nil and string.sub(convertStr,i,i+1)=="\\u" then unicode=tonumber("0x"..string.sub(convertStr,i+2,i+5)) i=i+6 elseif num1~=nil then unicode=num1 i=i+1 else break end if unicode <= 0x007f then resultStr=resultStr..string.char(bit.band(unicode,0x7f)) elseif unicode >= 0x0080 and unicode <= 0x07ff then resultStr=resultStr..string.char(bit.bor(0xc0,bit.band(bit.rshift(unicode,6),0x1f))) resultStr=resultStr..string.char(bit.bor(0x80,bit.band(unicode,0x3f))) elseif unicode >= 0x0800 and unicode <= 0xffff then resultStr=resultStr..string.char(bit.bor(0xe0,bit.band(bit.rshift(unicode,12),0x0f))) resultStr=resultStr..string.char(bit.bor(0x80,bit.band(bit.rshift(unicode,6),0x3f))) resultStr=resultStr..string.char(bit.bor(0x80,bit.band(unicode,0x3f))) end end return resultStr end --获取名字的长度, 一个中文算两个字符的特殊处理 function string.get_spec_length(str) AssertString(str) local _, lenghtList = string.utf8len(str) local nLenght = 0 for i, v in ipairs(lenghtList) do if v >= 2 then nLenght = nLenght + 2 else nLenght = nLenght + v end end return nLenght end --把utf8 字符串拆分出来 function string.utf8_StringToChars( str ) local begin_index = 0 local end_index = 0 local list = {} for k = 1, #str do local c = string.byte(str, k) end_index = end_index + 1 if bit.band(c, 0xc0) ~= 0x80 then if end_index > 1 then table.insert(list, string.sub(str, begin_index, end_index-1)) begin_index = end_index end end if k == #str then table.insert(list, string.sub(str, begin_index, #str)) end end return list end -- 聊天相关'#'字符处理 function string.FiltByChatWnd(str) AssertString(str) str = string.gsub(str, "#", "##") return str end --获取richText文本的长度,暂时支持文字(无样式)和表情 function string.getLengthOfRichText(str) --过滤非法,方便计数 local length = 0 local waitExpression = false local i = 1 while i <= string.len(str) do local c = string.byte(str, i) if bit.band(c, 0xc0) ~= 0x80 then length = length + 1 end i = i + 1 end return length end -- 在utf8字符串的每一个字符之间插入一个字符 function string.InsertCharBetweenStr(szStr, szChar) AssertString(szStr) AssertString(szChar) local szRet = "" local nPreIndex = 1 local i = 1 local nLen = string.len(szStr) while i <= nLen do local c = string.byte(szStr, i) if bit.band(c, 0xc0) ~= 0x80 and i > 1 then szRet = szRet .. string.sub(szStr, nPreIndex, i - 1) .. szChar nPreIndex = i end i = i + 1 end szRet = szRet .. string.sub(szStr, nPreIndex, nLen) return szRet end --删除一个richText,暂时支持文字(无样式)和表情 function string.deleteOneRichChar( str ) --最后一个是表情 local new_str, num = string.gsub(str, "#IS%([^()]*%)$", "") if num > 0 then return new_str end for i = string.len(str), 1, -1 do local c = string.byte(str, i) if bit.band(c, 0xc0) ~= 0x80 then return string.sub(str, 1, i-1) end end end --暂时支持文字(无样式)和表情 function string.deleteRichChar( str, count ) count = count or 1 local newStr = str for i = 1, count do newStr = deleteOneRichChar(newStr) end return newStr end --限制richChar的长度 function string.limitRichChar( str , limit) local curLength = getLengthOfRichText(str) if curLength > limit then return deleteRichChar(str, curLength - limit).."..." else return str end end function string.rtrim(str, chs) local chs_val = {} for _, v in ipairs({string.byte(chs, 1, #chs)}) do chs_val[v] = true end local idx = 0 for i = #str,1,-1 do if not chs_val[string.byte(str, i)] then idx = i break end end return idx < 1 and "" or string.sub(str,1, idx) end --去除前面的空格,换行 function string.ltrim(str, chs) local chs_val = {} for _, v in ipairs({string.byte(chs, 1, #chs)}) do chs_val[v] = true end local idx = #str + 1 for i = 1, #str do if not chs_val[string.byte(str, i)] then idx = i break end end return idx > #str and "" or string.sub(str,idx) end --去除前后的空格和换行 function string.lrtrim( str ) return string.rtrim(string.ltrim(str)) end function string.contains(str, pattern, plain) plain = plain or false local pos_begin, pos_end = string.find(str, pattern, 1, plain) return pos_begin ~= nil end function string.startswith(str, pattern, plain) plain = plain or false local pos_begin, pos_end = string.find(str, pattern, 1, plain) return pos_begin == 1 end function string.endswith(str, pattern, plain) plain = plain or false local pos_begin, pos_end = string.find(str, pattern, -#pattern, plain) return pos_end == #str end CHAR_VAL_a = string.byte('a') CHAR_VAL_z = string.byte('z') CHAR_VAL_A = string.byte('A') CHAR_VAL_Z = string.byte('Z') CHAR_VAL_0 = string.byte('0') CHAR_VAL_9 = string.byte('9') function string.isalnum(str) local ret = false if str then ret = true for _, v in ipairs({string.byte(str, 1, #str)}) do local in_range = false if not in_range and CHAR_VAL_a <= v and v <= CHAR_VAL_z then in_range = true end if not in_range and CHAR_VAL_A <= v and v <= CHAR_VAL_Z then in_range = true end if not in_range and CHAR_VAL_0 <= v and v <= CHAR_VAL_9 then in_range = true end if not in_range then ret = false break end end end return ret end function string.isalpha(str) local ret = false if str then ret = true for _, v in ipairs({string.byte(str, 1, #str)}) do local in_range = false if not in_range and CHAR_VAL_a <= v and v <= CHAR_VAL_z then in_range = true end if not in_range and CHAR_VAL_A <= v and v <= CHAR_VAL_Z then in_range = true end if not in_range then ret = false break end end end return ret end function string.isnum(str) local ret = false if str then ret = true for _, v in ipairs({string.byte(str, 1, #str)}) do if v < CHAR_VAL_0 or v > CHAR_VAL_9 then ret = false break end end end return ret end
ITEM.name = "The Communist Manifesto" ITEM.desc = "" ITEM.contents = [[ <h1>Manifesto of the Communist Party</h1> <h3>By Friedrich Engels and Karl Marx</h3> <p> A spectre is haunting Europe — the spectre of communism. All the powers of old Europe have entered into a holy alliance to exorcise this spectre: Pope and Tsar, Metternich and Guizot, French Radicals and German police-spies. Where is the party in opposition that has not been decried as communistic by its opponents in power? Where is the opposition that has not hurled back the branding reproach of communism, against the more advanced opposition parties, as well as against its reactionary adversaries? Two things result from this fact: I. Communism is already acknowledged by all European powers to be itself a power. II. It is high time that Communists should openly, in the face of the whole world, publish their views, their aims, their tendencies, and meet this nursery tale of the Spectre of Communism with a manifesto of the party itself. To this end, Communists of various nationalities have assembled in London and sketched the following manifesto, to be published in the English, French, German, Italian, Flemish and Danish languages. </p> <h2>Chapter I. Bourgeois and Proletarians</h2> <p> The history of all hitherto existing society(2) is the history of class struggles. Freeman and slave, patrician and plebeian, lord and serf, guild-master(3) and journeyman, in a word, oppressor and oppressed, stood in constant opposition to one another, carried on an uninterrupted, now hidden, now open fight, a fight that each time ended, either in a revolutionary reconstitution of society at large, or in the common ruin of the contending classes. In the earlier epochs of history, we find almost everywhere a complicated arrangement of society into various orders, a manifold gradation of social rank. In ancient Rome we have patricians, knights, plebeians, slaves; in the Middle Ages, feudal lords, vassals, guild-masters, journeymen, apprentices, serfs; in almost all of these classes, again, subordinate gradations. The modern bourgeois society that has sprouted from the ruins of feudal society has not done away with class antagonisms. It has but established new classes, new conditions of oppression, new forms of struggle in place of the old ones. Our epoch, the epoch of the bourgeoisie, possesses, however, this distinct feature: it has simplified class antagonisms. Society as a whole is more and more splitting up into two great hostile camps, into two great classes directly facing each other — Bourgeoisie and Proletariat. From the serfs of the Middle Ages sprang the chartered burghers of the earliest towns. From these burgesses the first elements of the bourgeoisie were developed. The discovery of America, the rounding of the Cape, opened up fresh ground for the rising bourgeoisie. The East-Indian and Chinese markets, the colonisation of America, trade with the colonies, the increase in the means of exchange and in commodities generally, gave to commerce, to navigation, to industry, an impulse never before known, and thereby, to the revolutionary element in the tottering feudal society, a rapid development. The feudal system of industry, in which industrial production was monopolised by closed guilds, now no longer sufficed for the growing wants of the new markets. The manufacturing system took its place. The guild-masters were pushed on one side by the manufacturing middle class; division of labour between the different corporate guilds vanished in the face of division of labour in each single workshop. Meantime the markets kept ever growing, the demand ever rising. Even manufacturer no longer sufficed. Thereupon, steam and machinery revolutionised industrial production. The place of manufacture was taken by the giant, Modern Industry; the place of the industrial middle class by industrial millionaires, the leaders of the whole industrial armies, the modern bourgeois. Modern industry has established the world market, for which the discovery of America paved the way. This market has given an immense development to commerce, to navigation, to communication by land. This development has, in its turn, reacted on the extension of industry; and in proportion as industry, commerce, navigation, railways extended, in the same proportion the bourgeoisie developed, increased its capital, and pushed into the background every class handed down from the Middle Ages. We see, therefore, how the modern bourgeoisie is itself the product of a long course of development, of a series of revolutions in the modes of production and of exchange. Each step in the development of the bourgeoisie was accompanied by a corresponding political advance of that class. An oppressed class under the sway of the feudal nobility, an armed and self-governing association in the medieval commune(4): here independent urban republic (as in Italy and Germany); there taxable “third estate” of the monarchy (as in France); afterwards, in the period of manufacturing proper, serving either the semi-feudal or the absolute monarchy as a counterpoise against the nobility, and, in fact, cornerstone of the great monarchies in general, the bourgeoisie has at last, since the establishment of Modern Industry and of the world market, conquered for itself, in the modern representative State, exclusive political sway. The executive of the modern state is but a committee for managing the common affairs of the whole bourgeoisie. The bourgeoisie, historically, has played a most revolutionary part. The bourgeoisie, wherever it has got the upper hand, has put an end to all feudal, patriarchal, idyllic relations. It has pitilessly torn asunder the motley feudal ties that bound man to his “natural superiors”, and has left remaining no other nexus between man and man than naked self-interest, than callous “cash payment”. It has drowned the most heavenly ecstasies of religious fervour, of chivalrous enthusiasm, of philistine sentimentalism, in the icy water of egotistical calculation. It has resolved personal worth into exchange value, and in place of the numberless indefeasible chartered freedoms, has set up that single, unconscionable freedom — Free Trade. In one word, for exploitation, veiled by religious and political illusions, it has substituted naked, shameless, direct, brutal exploitation. The bourgeoisie has stripped of its halo every occupation hitherto honoured and looked up to with reverent awe. It has converted the physician, the lawyer, the priest, the poet, the man of science, into its paid wage labourers. The bourgeoisie has torn away from the family its sentimental veil, and has reduced the family relation to a mere money relation. The bourgeoisie has disclosed how it came to pass that the brutal display of vigour in the Middle Ages, which reactionaries so much admire, found its fitting complement in the most slothful indolence. It has been the first to show what man’s activity can bring about. It has accomplished wonders far surpassing Egyptian pyramids, Roman aqueducts, and Gothic cathedrals; it has conducted expeditions that put in the shade all former Exoduses of nations and crusades. The bourgeoisie cannot exist without constantly revolutionising the instruments of production, and thereby the relations of production, and with them the whole relations of society. Conservation of the old modes of production in unaltered form, was, on the contrary, the first condition of existence for all earlier industrial classes. Constant revolutionising of production, uninterrupted disturbance of all social conditions, everlasting uncertainty and agitation distinguish the bourgeois epoch from all earlier ones. All fixed, fast-frozen relations, with their train of ancient and venerable prejudices and opinions, are swept away, all new-formed ones become antiquated before they can ossify. All that is solid melts into air, all that is holy is profaned, and man is at last compelled to face with sober senses his real conditions of life, and his relations with his kind. The need of a constantly expanding market for its products chases the bourgeoisie over the entire surface of the globe. It must nestle everywhere, settle everywhere, establish connexions everywhere. The bourgeoisie has through its exploitation of the world market given a cosmopolitan character to production and consumption in every country. To the great chagrin of Reactionists, it has drawn from under the feet of industry the national ground on which it stood. All old-established national industries have been destroyed or are daily being destroyed. They are dislodged by new industries, whose introduction becomes a life and death question for all civilised nations, by industries that no longer work up indigenous raw material, but raw material drawn from the remotest zones; industries whose products are consumed, not only at home, but in every quarter of the globe. In place of the old wants, satisfied by the production of the country, we find new wants, requiring for their satisfaction the products of distant lands and climes. In place of the old local and national seclusion and self-sufficiency, we have intercourse in every direction, universal inter-dependence of nations. And as in material, so also in intellectual production. The intellectual creations of individual nations become common property. National one-sidedness and narrow-mindedness become more and more impossible, and from the numerous national and local literatures, there arises a world literature. The bourgeoisie, by the rapid improvement of all instruments of production, by the immensely facilitated means of communication, draws all, even the most barbarian, nations into civilisation. The cheap prices of commodities are the heavy artillery with which it batters down all Chinese walls, with which it forces the barbarians’ intensely obstinate hatred of foreigners to capitulate. It compels all nations, on pain of extinction, to adopt the bourgeois mode of production; it compels them to introduce what it calls civilisation into their midst, i.e., to become bourgeois themselves. In one word, it creates a world after its own image. The bourgeoisie has subjected the country to the rule of the towns. It has created enormous cities, has greatly increased the urban population as compared with the rural, and has thus rescued a considerable part of the population from the idiocy of rural life. Just as it has made the country dependent on the towns, so it has made barbarian and semi-barbarian countries dependent on the civilised ones, nations of peasants on nations of bourgeois, the East on the West. The bourgeoisie keeps more and more doing away with the scattered state of the population, of the means of production, and of property. It has agglomerated population, centralised the means of production, and has concentrated property in a few hands. The necessary consequence of this was political centralisation. Independent, or but loosely connected provinces, with separate interests, laws, governments, and systems of taxation, became lumped together into one nation, with one government, one code of laws, one national class-interest, one frontier, and one customs-tariff. The bourgeoisie, during its rule of scarce one hundred years, has created more massive and more colossal productive forces than have all preceding generations together. Subjection of Nature’s forces to man, machinery, application of chemistry to industry and agriculture, steam-navigation, railways, electric telegraphs, clearing of whole continents for cultivation, canalisation of rivers, whole populations conjured out of the ground — what earlier century had even a presentiment that such productive forces slumbered in the lap of social labour? We see then: the means of production and of exchange, on whose foundation the bourgeoisie built itself up, were generated in feudal society. At a certain stage in the development of these means of production and of exchange, the conditions under which feudal society produced and exchanged, the feudal organisation of agriculture and manufacturing industry, in one word, the feudal relations of property became no longer compatible with the already developed productive forces; they became so many fetters. They had to be burst asunder; they were burst asunder. Into their place stepped free competition, accompanied by a social and political constitution adapted in it, and the economic and political sway of the bourgeois class. A similar movement is going on before our own eyes. Modern bourgeois society, with its relations of production, of exchange and of property, a society that has conjured up such gigantic means of production and of exchange, is like the sorcerer who is no longer able to control the powers of the nether world whom he has called up by his spells. For many a decade past the history of industry and commerce is but the history of the revolt of modern productive forces against modern conditions of production, against the property relations that are the conditions for the existence of the bourgeois and of its rule. It is enough to mention the commercial crises that by their periodical return put the existence of the entire bourgeois society on its trial, each time more threateningly. In these crises, a great part not only of the existing products, but also of the previously created productive forces, are periodically destroyed. In these crises, there breaks out an epidemic that, in all earlier epochs, would have seemed an absurdity — the epidemic of over-production. Society suddenly finds itself put back into a state of momentary barbarism; it appears as if a famine, a universal war of devastation, had cut off the supply of every means of subsistence; industry and commerce seem to be destroyed; and why? Because there is too much civilisation, too much means of subsistence, too much industry, too much commerce. The productive forces at the disposal of society no longer tend to further the development of the conditions of bourgeois property; on the contrary, they have become too powerful for these conditions, by which they are fettered, and so soon as they overcome these fetters, they bring disorder into the whole of bourgeois society, endanger the existence of bourgeois property. The conditions of bourgeois society are too narrow to comprise the wealth created by them. And how does the bourgeoisie get over these crises? On the one hand by enforced destruction of a mass of productive forces; on the other, by the conquest of new markets, and by the more thorough exploitation of the old ones. That is to say, by paving the way for more extensive and more destructive crises, and by diminishing the means whereby crises are prevented. The weapons with which the bourgeoisie felled feudalism to the ground are now turned against the bourgeoisie itself. But not only has the bourgeoisie forged the weapons that bring death to itself; it has also called into existence the men who are to wield those weapons — the modern working class — the proletarians. In proportion as the bourgeoisie, i.e., capital, is developed, in the same proportion is the proletariat, the modern working class, developed — a class of labourers, who live only so long as they find work, and who find work only so long as their labour increases capital. These labourers, who must sell themselves piecemeal, are a commodity, like every other article of commerce, and are consequently exposed to all the vicissitudes of competition, to all the fluctuations of the market. Owing to the extensive use of machinery, and to the division of labour, the work of the proletarians has lost all individual character, and, consequently, all charm for the workman. He becomes an appendage of the machine, and it is only the most simple, most monotonous, and most easily acquired knack, that is required of him. Hence, the cost of production of a workman is restricted, almost entirely, to the means of subsistence that he requires for maintenance, and for the propagation of his race. But the price of a commodity, and therefore also of labour, is equal to its cost of production. In proportion, therefore, as the repulsiveness of the work increases, the wage decreases. Nay more, in proportion as the use of machinery and division of labour increases, in the same proportion the burden of toil also increases, whether by prolongation of the working hours, by the increase of the work exacted in a given time or by increased speed of machinery, etc. Modern Industry has converted the little workshop of the patriarchal master into the great factory of the industrial capitalist. Masses of labourers, crowded into the factory, are organised like soldiers. As privates of the industrial army they are placed under the command of a perfect hierarchy of officers and sergeants. Not only are they slaves of the bourgeois class, and of the bourgeois State; they are daily and hourly enslaved by the machine, by the overlooker, and, above all, by the individual bourgeois manufacturer himself. The more openly this despotism proclaims gain to be its end and aim, the more petty, the more hateful and the more embittering it is. The less the skill and exertion of strength implied in manual labour, in other words, the more modern industry becomes developed, the more is the labour of men superseded by that of women. Differences of age and sex have no longer any distinctive social validity for the working class. All are instruments of labour, more or less expensive to use, according to their age and sex. No sooner is the exploitation of the labourer by the manufacturer, so far, at an end, that he receives his wages in cash, than he is set upon by the other portions of the bourgeoisie, the landlord, the shopkeeper, the pawnbroker, etc. The lower strata of the middle class — the small tradespeople, shopkeepers, and retired tradesmen generally, the handicraftsmen and peasants — all these sink gradually into the proletariat, partly because their diminutive capital does not suffice for the scale on which Modern Industry is carried on, and is swamped in the competition with the large capitalists, partly because their specialised skill is rendered worthless by new methods of production. Thus the proletariat is recruited from all classes of the population. The proletariat goes through various stages of development. With its birth begins its struggle with the bourgeoisie. At first the contest is carried on by individual labourers, then by the workpeople of a factory, then by the operative of one trade, in one locality, against the individual bourgeois who directly exploits them. They direct their attacks not against the bourgeois conditions of production, but against the instruments of production themselves; they destroy imported wares that compete with their labour, they smash to pieces machinery, they set factories ablaze, they seek to restore by force the vanished status of the workman of the Middle Ages. At this stage, the labourers still form an incoherent mass scattered over the whole country, and broken up by their mutual competition. If anywhere they unite to form more compact bodies, this is not yet the consequence of their own active union, but of the union of the bourgeoisie, which class, in order to attain its own political ends, is compelled to set the whole proletariat in motion, and is moreover yet, for a time, able to do so. At this stage, therefore, the proletarians do not fight their enemies, but the enemies of their enemies, the remnants of absolute monarchy, the landowners, the non-industrial bourgeois, the petty bourgeois. Thus, the whole historical movement is concentrated in the hands of the bourgeoisie; every victory so obtained is a victory for the bourgeoisie. But with the development of industry, the proletariat not only increases in number; it becomes concentrated in greater masses, its strength grows, and it feels that strength more. The various interests and conditions of life within the ranks of the proletariat are more and more equalised, in proportion as machinery obliterates all distinctions of labour, and nearly everywhere reduces wages to the same low level. The growing competition among the bourgeois, and the resulting commercial crises, make the wages of the workers ever more fluctuating. The increasing improvement of machinery, ever more rapidly developing, makes their livelihood more and more precarious; the collisions between individual workmen and individual bourgeois take more and more the character of collisions between two classes. Thereupon, the workers begin to form combinations (Trades’ Unions) against the bourgeois; they club together in order to keep up the rate of wages; they found permanent associations in order to make provision beforehand for these occasional revolts. Here and there, the contest breaks out into riots. Now and then the workers are victorious, but only for a time. The real fruit of their battles lies, not in the immediate result, but in the ever expanding union of the workers. This union is helped on by the improved means of communication that are created by modern industry, and that place the workers of different localities in contact with one another. It was just this contact that was needed to centralise the numerous local struggles, all of the same character, into one national struggle between classes. But every class struggle is a political struggle. And that union, to attain which the burghers of the Middle Ages, with their miserable highways, required centuries, the modern proletarian, thanks to railways, achieve in a few years. This organisation of the proletarians into a class, and, consequently into a political party, is continually being upset again by the competition between the workers themselves. But it ever rises up again, stronger, firmer, mightier. It compels legislative recognition of particular interests of the workers, by taking advantage of the divisions among the bourgeoisie itself. Thus, the ten-hours’ bill in England was carried. Altogether collisions between the classes of the old society further, in many ways, the course of development of the proletariat. The bourgeoisie finds itself involved in a constant battle. At first with the aristocracy; later on, with those portions of the bourgeoisie itself, whose interests have become antagonistic to the progress of industry; at all time with the bourgeoisie of foreign countries. In all these battles, it sees itself compelled to appeal to the proletariat, to ask for help, and thus, to drag it into the political arena. The bourgeoisie itself, therefore, supplies the proletariat with its own elements of political and general education, in other words, it furnishes the proletariat with weapons for fighting the bourgeoisie. Further, as we have already seen, entire sections of the ruling class are, by the advance of industry, precipitated into the proletariat, or are at least threatened in their conditions of existence. These also supply the proletariat with fresh elements of enlightenment and progress. Finally, in times when the class struggle nears the decisive hour, the progress of dissolution going on within the ruling class, in fact within the whole range of old society, assumes such a violent, glaring character, that a small section of the ruling class cuts itself adrift, and joins the revolutionary class, the class that holds the future in its hands. Just as, therefore, at an earlier period, a section of the nobility went over to the bourgeoisie, so now a portion of the bourgeoisie goes over to the proletariat, and in particular, a portion of the bourgeois ideologists, who have raised themselves to the level of comprehending theoretically the historical movement as a whole. Of all the classes that stand face to face with the bourgeoisie today, the proletariat alone is a really revolutionary class. The other classes decay and finally disappear in the face of Modern Industry; the proletariat is its special and essential product. The lower middle class, the small manufacturer, the shopkeeper, the artisan, the peasant, all these fight against the bourgeoisie, to save from extinction their existence as fractions of the middle class. They are therefore not revolutionary, but conservative. Nay more, they are reactionary, for they try to roll back the wheel of history. If by chance, they are revolutionary, they are only so in view of their impending transfer into the proletariat; they thus defend not their present, but their future interests, they desert their own standpoint to place themselves at that of the proletariat. The “dangerous class”, [lumpenproletariat] the social scum, that passively rotting mass thrown off by the lowest layers of the old society, may, here and there, be swept into the movement by a proletarian revolution; its conditions of life, however, prepare it far more for the part of a bribed tool of reactionary intrigue. In the condition of the proletariat, those of old society at large are already virtually swamped. The proletarian is without property; his relation to his wife and children has no longer anything in common with the bourgeois family relations; modern industry labour, modern subjection to capital, the same in England as in France, in America as in Germany, has stripped him of every trace of national character. Law, morality, religion, are to him so many bourgeois prejudices, behind which lurk in ambush just as many bourgeois interests. All the preceding classes that got the upper hand sought to fortify their already acquired status by subjecting society at large to their conditions of appropriation. The proletarians cannot become masters of the productive forces of society, except by abolishing their own previous mode of appropriation, and thereby also every other previous mode of appropriation. They have nothing of their own to secure and to fortify; their mission is to destroy all previous securities for, and insurances of, individual property. All previous historical movements were movements of minorities, or in the interest of minorities. The proletarian movement is the self-conscious, independent movement of the immense majority, in the interest of the immense majority. The proletariat, the lowest stratum of our present society, cannot stir, cannot raise itself up, without the whole superincumbent strata of official society being sprung into the air. Though not in substance, yet in form, the struggle of the proletariat with the bourgeoisie is at first a national struggle. The proletariat of each country must, of course, first of all settle matters with its own bourgeoisie. In depicting the most general phases of the development of the proletariat, we traced the more or less veiled civil war, raging within existing society, up to the point where that war breaks out into open revolution, and where the violent overthrow of the bourgeoisie lays the foundation for the sway of the proletariat. Hitherto, every form of society has been based, as we have already seen, on the antagonism of oppressing and oppressed classes. But in order to oppress a class, certain conditions must be assured to it under which it can, at least, continue its slavish existence. The serf, in the period of serfdom, raised himself to membership in the commune, just as the petty bourgeois, under the yoke of the feudal absolutism, managed to develop into a bourgeois. The modern labourer, on the contrary, instead of rising with the process of industry, sinks deeper and deeper below the conditions of existence of his own class. He becomes a pauper, and pauperism develops more rapidly than population and wealth. And here it becomes evident, that the bourgeoisie is unfit any longer to be the ruling class in society, and to impose its conditions of existence upon society as an over-riding law. It is unfit to rule because it is incompetent to assure an existence to its slave within his slavery, because it cannot help letting him sink into such a state, that it has to feed him, instead of being fed by him. Society can no longer live under this bourgeoisie, in other words, its existence is no longer compatible with society. The essential conditions for the existence and for the sway of the bourgeois class is the formation and augmentation of capital; the condition for capital is wage-labour. Wage-labour rests exclusively on competition between the labourers. The advance of industry, whose involuntary promoter is the bourgeoisie, replaces the isolation of the labourers, due to competition, by the revolutionary combination, due to association. The development of Modern Industry, therefore, cuts from under its feet the very foundation on which the bourgeoisie produces and appropriates products. What the bourgeoisie therefore produces, above all, are its own grave-diggers. Its fall and the victory of the proletariat are equally inevitable. </p> ]]
fiber = require('fiber') -- -- gh-2784: do not validate space formatted but not indexed fields -- in surrogate statements. -- -- At first, test simple surrogate delete generated from a key. format = {{name = 'a', type = 'unsigned'}, {name = 'b', type = 'unsigned'}} s = box.schema.space.create('test', {engine = 'vinyl', format = format}) _ = s:create_index('pk') s:insert{1, 1} -- Type of a second field in a surrogate tuple must be NULL but -- with UNSIGNED type, specified in a tuple_format. It is -- possible, because only indexed fields are used in surrogate -- tuples. s:delete(1) s:drop() -- Test select after snapshot. This select gets surrogate -- tuples from a disk. Here NULL also can be stored in formatted, -- but not indexed field. format = {} format[1] = {name = 'a', type = 'unsigned'} format[2] = {name = 'b', type = 'unsigned'} format[3] = {name = 'c', type = 'unsigned'} s = box.schema.space.create('test', {engine = 'vinyl', format = format}) _ = s:create_index('pk') _ = s:create_index('sk', {parts = {2, 'unsigned'}}) s:insert{1, 1, 1} box.snapshot() s:delete(1) box.snapshot() s:select() s:drop() -- -- gh-2983: ensure the transaction associated with a fiber -- is automatically rolled back if the fiber stops. -- s = box.schema.create_space('test', { engine = 'vinyl' }) _ = s:create_index('pk') tx1 = box.stat.vinyl().tx ch = fiber.channel(1) _ = fiber.create(function() box.begin() s:insert{1} ch:put(true) end) ch:get() tx2 = box.stat.vinyl().tx tx2.commit - tx1.commit -- 0 tx2.rollback - tx1.rollback -- 1 s:drop() -- -- gh-3158: check of duplicates is skipped if the index -- is contained by another unique index which is checked. -- s = box.schema.create_space('test', {engine = 'vinyl'}) i1 = s:create_index('i1', {unique = true, parts = {1, 'unsigned', 2, 'unsigned'}}) i2 = s:create_index('i2', {unique = true, parts = {2, 'unsigned', 1, 'unsigned'}}) i3 = s:create_index('i3', {unique = true, parts = {3, 'unsigned', 4, 'unsigned', 5, 'unsigned'}}) i4 = s:create_index('i4', {unique = true, parts = {5, 'unsigned', 4, 'unsigned'}}) i5 = s:create_index('i5', {unique = true, parts = {4, 'unsigned', 5, 'unsigned', 1, 'unsigned'}}) i6 = s:create_index('i6', {unique = true, parts = {4, 'unsigned', 6, 'unsigned', 5, 'unsigned'}}) i7 = s:create_index('i7', {unique = true, parts = {6, 'unsigned'}}) s:insert{1, 1, 1, 1, 1, 1} i1:stat().lookup -- 1 i2:stat().lookup -- 0 i3:stat().lookup -- 0 i4:stat().lookup -- 1 i5:stat().lookup -- 0 i6:stat().lookup -- 0 i7:stat().lookup -- 1 s:drop()
TOOL.AddToMenu = false TOOL.ClientConVar["train"] = 1 TOOL.ClientConVar["wagnum"] = 3 TOOL.ClientConVar["lighter"] = 0 TOOL.ClientConVar["texture"] = "" TOOL.ClientConVar["passtexture"] = "" TOOL.ClientConVar["cabtexture"] = "" TOOL.ClientConVar["adv"] = 1 TOOL.ClientConVar["ars"] = 1 TOOL.ClientConVar["skin"] = 1 TOOL.ClientConVar["cran"] = 1 TOOL.ClientConVar["prom"] = 1 TOOL.ClientConVar["mask"] = 1 TOOL.ClientConVar["pitermsk"] = 1 TOOL.ClientConVar["bpsn"] = 2 TOOL.ClientConVar["led"] = 0 TOOL.ClientConVar["kvsnd"] = 1 TOOL.ClientConVar["oldkvpos"] = 0 TOOL.ClientConVar["horn"] = 0 TOOL.ClientConVar["nm"] = 8.2 TOOL.ClientConVar["battery"] = 0 TOOL.ClientConVar["switches"] = 1 TOOL.ClientConVar["switchesr"] = 0 TOOL.ClientConVar["doorsl"] = 0 TOOL.ClientConVar["doorsr"] = 0 TOOL.ClientConVar["gv"] = 1 TOOL.ClientConVar["pb"] = 0 TOOL.ClientConVar["oldt"] = "" TOOL.ClientConVar["oldw"] = "" TOOL.ClientConVar["seat"] = 1 TOOL.ClientConVar["hand"] = 1 TOOL.ClientConVar["mvm"] = 1 TOOL.ClientConVar["bort"] = 1 TOOL.ClientConVar["lamp"] = 1 TOOL.ClientConVar["breakers"] = 0 TOOL.ClientConVar["blok"] = 1 TOOL.ClientConVar["pnm"] = 0 TOOL.ClientConVar["bloken"] = 0 local Trains = {{"81-717_mvm","81-714_mvm"},{"81-717_lvz","81-714_lvz"},{"E","E"},{"Ema","Em"},{"Ezh3","Ema508T"},{"81-7036","81-7037"}} local Switches = { "A61","A55","A54","A56","A27","A21","A10","A53","A43","A45","A42","A41", "VU","A64","A63","A50","A51","A23","A14","A1","A2","A3","A17", "A62","A29","A5","A6","A8","A20","A25","A22","A30","A39","A44","A80" ,"A65","A24","A32","A31","A16","A13","A12","A7","A9","A46","A47"} if CLIENT then language.Add("Tool.train_spawner.name", "Train Spawner") language.Add("Tool.train_spawner.desc", "Spawn a train") language.Add("Tool.train_spawner.0", "Primary: Spawns a full train. Secondary: self.Reverse facing (yellow ed when facing the opposite side).") language.Add("Undone_81-7036", "Undone 81-7036 (does not work)") language.Add("Undone_81-7037", "Undone 81-7037 (does not work)") language.Add("Undone_81-717", "Undone 81-717") language.Add("Undone_81-714", "Undone 81-714") language.Add("Undone_Ezh3", "Undone Ezh3") language.Add("Undone_Ema508T", "Undone Em508T") end local function Trace(ply,tr) local verticaloffset = 5 -- Offset for the train model local distancecap = 2000 -- When to ignore hitpos and spawn at set distanace local pos, ang = nil local inhibitrerail = false --TODO: Make this work better for raw base ent if tr.Hit then -- Setup trace to find out of this is a track local tracesetup = {} tracesetup.start=tr.HitPos tracesetup.endpos=tr.HitPos+tr.HitNormal*80 tracesetup.filter=ply local tracedata = util.TraceLine(tracesetup) if tracedata.Hit then -- Trackspawn pos = (tr.HitPos + tracedata.HitPos)/2 + Vector(0,0,verticaloffset) ang = tracedata.HitNormal ang:Rotate(Angle(0,90,0)) ang = ang:Angle() -- Bit ugly because Rotate() messes with the orthogonal vector | Orthogonal? I wrote "origional?!" :V else -- Regular spawn if tr.HitPos:Distance(tr.StartPos) > distancecap then -- Spawnpos is far away, put it at distancecap instead pos = tr.StartPos + tr.Normal * distancecap inhibitrerail = true else -- Spawn is near pos = tr.HitPos + tr.HitNormal * verticaloffset end ang = Angle(0,tr.Normal:Angle().y,0) end else -- Trace didn't hit anything, spawn at distancecap pos = tr.StartPos + tr.Normal * distancecap ang = Angle(0,tr.Normal:Angle().y,0) end return {pos,ang,inhibitrerail} end function TOOL:GetCurrentModel(trNum,head,pr) if trNum == 1 or trNum == 2 then if not pr then return "models/metrostroi_train/81/81-717.mdl" else return "models/metrostroi/81/81-714.mdl" end elseif trNum == 3 then return "models/metrostroi_train/e/e.mdl" elseif trNum == 4 then return "models/metrostroi_train/em/em.mdl" elseif trNum == 5 then return "models/metrostroi/e/"..(pr and "ema508t" or "em508")..".mdl" else return "models/metrostroi/81/81-703"..(pr and 7 or 6)..".mdl" end end function TOOL:GetConvar() local tbl = {} tbl.Train = self:GetClientNumber("train") tbl.WagNum = self:GetClientNumber("wagnum") tbl.Texture = self:GetClientInfo("texture") tbl.PassTexture = self:GetClientInfo("passtexture") tbl.CabTexture = self:GetClientInfo("cabtexture") tbl.Adv = self:GetClientNumber("adv") tbl.ARS = self:GetClientNumber("ars") tbl.Skin = self:GetClientNumber("skin") tbl.Cran = self:GetClientNumber("cran") tbl.Prom = self:GetClientNumber("prom") tbl.Mask = self:GetClientNumber("mask") tbl.PiterMsk = self:GetClientNumber("pitermsk") tbl.LED = self:GetClientNumber("led") tbl.Horn = self:GetClientNumber("horn") tbl.KVSnd = math.max(1,self:GetClientNumber("kvsnd")) tbl.OldKVPos = self:GetClientNumber("oldkvpos") tbl.BPSN = self:GetClientNumber("bpsn") tbl.NM = self:GetClientNumber("nm") tbl.Battery = self:GetClientNumber("battery") tbl.Lighter = self:GetClientNumber("lighter") tbl.Switches = self:GetClientNumber("switches") tbl.SwitchesR = self:GetClientNumber("switchesr") tbl.DoorsL = self:GetClientNumber("doorsl") tbl.DoorsR = self:GetClientNumber("doorsr") tbl.GV = self:GetClientNumber("gv") tbl.PB = self:GetClientNumber("pb") tbl.Bort = self:GetClientNumber("bort") tbl.MVM = self:GetClientNumber("mvm") tbl.Hand = self:GetClientNumber("hand") tbl.Seat = self:GetClientNumber("seat") tbl.Lamp = self:GetClientNumber("lamp") tbl.Breakers = self:GetClientNumber("breakers") tbl.Blok = self:GetClientNumber("blok") tbl.PNM = self:GetClientNumber("pnm") tbl.BlokEN = self:GetClientNumber("bloken") return tbl end local CLpos,CLang = Vector(0,0,0),Angle(0,0,0) function UpdateGhostPos(pl) local trace = util.TraceLine(util.GetPlayerTrace(pl)) local tbl = Metrostroi.RerailGetTrackData(trace.HitPos,pl:GetAimVector()) if not tbl then tbl = Trace(pl, trace) end local pos,ang = Vector(0,0,0),Angle(0,0,0) if tbl[3] ~= nil then pos = tbl[1]+Vector(0,0,55) ang = tbl[2] else pos = tbl.centerpos + Vector(0,0,112) ang = tbl.right:Angle()+Angle(0,90,0) end return pos,ang end function TOOL:UpdateGhost(pl, ent) local pos,ang if SERVER then pos, ang = UpdateGhostPos(pl) self:GetOwner():SetNW2Vector("metrostroi_train_spawner_pos",pos) self:GetOwner():SetNW2Angle("metrostroi_train_spawner_angle",ang + Angle(0,self.Rev and 180 or 0,0)) else pos, ang = self:GetOwner():GetNW2Vector("metrostroi_train_spawner_pos"), self:GetOwner():GetNW2Angle("metrostroi_train_spawner_angle") end if not ent then return end if self.tbl.Train == 4 then --[[ local path = Metrostroi.Skins["ezh3"][self.tbl.Texture].path if path == "RND" then path = Metrostroi.Skins["ezh3"][math.random(1,#Metrostroi.Skins["ezh3"])].path end for k,v in pairs(ent:GetMaterials()) do if v:find("ewagon") then ent:SetSubMaterial(k-1,path) else ent:SetSubMaterial(k-1,"") end end ]] else --ent:SetSkin(self.tbl.Paint == 1 and math.random(0,2) or self.tbl.Paint-2) ent:SetBodygroup(1,(self.tbl.ARS or 1)-1) ent:SetBodygroup(2,(self.tbl.Lamp or 1)-1) ent:SetBodygroup(3,(self.tbl.Mask or 1)-1) ent:SetBodygroup(4,(self.tbl.Seat or 1)-1) ent:SetBodygroup(5,(self.tbl.Hand or 1)-1) ent:SetBodygroup(6,(self.tbl.MVM > 0 and ((self.tbl.Mask > 2 and self.tbl.Mask ~= 6) and 1 or 0) or 2)) ent:SetBodygroup(7,(self.tbl.Bort or 1)-1) ent:SetBodygroup(9,(self.tbl.Breakers or 0)) ent:SetBodygroup(14,self.tbl.ARS == 3 and 1 or 0) --[[ for k,v in pairs(ent:GetMaterials()) do if v == "models/metrostroi_train/81/b01a" then ent:SetSubMaterial(k-1,Metrostroi.Skins["717"][self.tbl.Texture].path) elseif v == "models/metrostroi_train/81/int01" then local path = Metrostroi.Skins["717_pass"][self.tbl.PassTexture].path if path == "RND" then path = Metrostroi.Skins["717_pass"][math.random(1,#Metrostroi.Skins["717_pass"])].path end ent:SetSubMaterial(k-1,path) else ent:SetSubMaterial(k-1,"") end end ]] --ent:SetSkin(self.tbl.Paint-1) end ent:SetColor(self.Rev and Color(255 ,255,0) or Color(255,255,255)) ent:SetPos(pos) ent:SetAngles(ang + Angle(0,self.Rev and 180 or 0,0)) end local owner function TOOL:Think() owner = self:GetOwner() self.tbl = self:GetConvar() self.int = self.tbl.Prom > 0 or !Trains[self.tbl.Train][1]:find("Ezh") if not self.Spawned then if (!IsValid(self.GhostEntity) or self.GhostEntity:GetModel() ~= self:GetCurrentModel(self.tbl.Train)) then self:MakeGhostEntity(self:GetCurrentModel(self.tbl.Train), Vector( 0, 0, 0 ), Angle( 0, 0, 0 )) end self:UpdateGhost(self:GetOwner(), self.GhostEntity) end ---if SERVER then self.Rev = self.Rev end end local function SendCodeToCL() local pos,ang = UpdateGhostPos(owner) net.Start("metrostroi_train_spawner_ghost") net.WriteVector(pos) net.WriteAngle(ang) net.WriteBit(self.Rev) net.Send(owner) end function TOOL:Spawn(ply, tr, clname, i) local rot = false if i > 1 then rot = i == self.tbl.WagNum and true or math.random() > 0.5 end local pos,ang = Vector(0,0,0),Angle(0,0,0) if i == 1 then local tbl = Trace(ply, tr) pos = tbl[1] ang = tbl[2] rerail = tbl[3] else local dir = self.fent:GetAngles():Forward() * -1 local add = clname:find("714") local wagheg = math.abs(self.oldent:OBBMaxs().x - self.oldent:OBBMins().x)+ 30 + ((rot or self.Rev) and 30 or 0) pos = self.oldent:GetPos() + dir*wagheg - Vector(0,0,140) ang = self.fent:GetAngles() + Angle(0,rot and 180 or 0,0) end local ent = ents.Create(clname) ent:SetPos(pos) ent:SetAngles(ang + Angle(0,(self.Rev and !rot) and 180 or 0,0)) ent.Owner = ply ent:Spawn() ent:Activate() if IsValid(ent) then Metrostroi.RerailTrain(ent) end self.rot = rot return ent end function TOOL:SetSettings(ent, ply, i,inth) local rot = false if i > 1 then rot = i == self.tbl.WagNum and true or math.random() > 0.5 end undo.Create(Trains[self.tbl.Train][i>1 and i<self.tbl.WagNum and self.int and 2 or 1]) undo.AddEntity(ent) undo.SetPlayer(ply) undo.Finish() if ent.SubwayTrain.Name ~= "81-7036" then if ent.SubwayTrain.Type == "81" then --ent:SetSkin(self.tbl.Paint-1) if ent.SubwayTrain.Manufacturer == "MVM" then ent.ARSType = self.tbl.ARS ent.MaskType = self.tbl.Mask ent:SetNW2Int("ARSType", ent.ARSType) else ent.Blok = self.tbl.Blok ent.BlokEN = self.tbl.BlokEN > 0 ent.MaskType = self.tbl.PiterMsk end ent.Pneumatic.ValveType = self.tbl.Cran end ent.Pneumatic.TrainLinePressure = self.tbl.NM ent.BPSNType = self.tbl.BPSN+1 ent:SetNW2Int("BPSNType",ent.BPSNType) for k,v in pairs(Switches) do if (i == 1 or i == self.tbl.WagNum or !self.int) and v ~= "A5" then ent:TriggerInput(v.."Set", self.tbl.Switches > 0 and (math.random() > math.random(0.1,0.4) or self.tbl.SwitchesR == 0)) end end local rot = (self.fent:GetAngles().yaw - ent:GetAngles().yaw) ~= 0 --local rot = --print local DoorsL = self.tbl.DoorsL local DoorsR = self.tbl.DoorsR for I=1,4 do ent.Pneumatic.LeftDoorState[I] = ((DoorsL > 0 and !rot) or (DoorsR > 0 and rot)) and 1 or 0 ent.Pneumatic.RightDoorState[I] = ((DoorsL > 0 and rot) or (DoorsR > 0 and !rot)) and 1 or 0 end if i > 1 and i < self.tbl.WagNum then ent.Pneumatic.UAVA = true --ent.UAVA:TriggerInput("Set",1) --ent:TriggerInput("A5Set",1) else --ent:TriggerInput("A5Set",0) end ent.Lighter = self.tbl.Lighter ent.LampType = self.tbl.Lamp ent.SeatType = self.tbl.Seat ent.HandRail = self.tbl.Hand ent.Adverts = self.tbl.Adv ent.MVM = self.tbl.MVM > 0 ent.BortLampType = self.tbl.Bort ent.LED = self.tbl.LED > 0 ent.Breakers= self.tbl.Breakers ent.PNM= self.tbl.PNM > 0 ent:SetNW2Bool("Breakers",(ent.Breakers or 1) > 0) ent:TriggerInput("VBSet", self.tbl.Battery) ent:TriggerInput("GVSet", self.tbl.GV) ent:TriggerInput("ParkingBrakeSet", self.tbl.PB) ent:TriggerInput("ParkingBrakeSignSet", self.tbl.PB) for k,v in pairs(ent.SoundNames) do if type(v) ~= "string" then continue end if not k:find("kv_") then continue end if k:find("ezh") then continue end ent.SoundNames[k] = string.gsub(v,"kv%d","kv"..self:GetClientNumber("kvsnd")) ent.KVSnd = self:GetClientNumber("kvsnd") ent.NewKV = self:GetClientNumber("kvsnd") > 1 ent:SetNW2Bool("NewKV",ent.NewKV) end ent.OldKVPos = self.tbl.OldKVPos > 0 if ent.Horn then ent.Horn:TriggerInput("NewType",self.tbl.Horn) end if ent.A45 then ent.A45:TriggerInput("Set",0) --ent.A5:TriggerInput("Block",0) --ent.A5:TriggerInput("Set",0) --ent.A5:TriggerInput("Block",1) end if inth and ent.UAVA then ent.UAVA:TriggerInput("Set",1) if ent.VU and (not self.Plombs or not self.Plombs.VU) then ent.VU:TriggerInput("Set",0) ent.VU:TriggerInput("Block",1) end end end if ent.UpdateTextures then local tex = Metrostroi.Skins["train"][self.tbl.Texture] local ptex = Metrostroi.Skins["pass"][self.tbl.PassTexture] local ctex = Metrostroi.Skins["cab"][self.tbl.CabTexture] if tex and (ent:GetClass() == "gmod_subway_"..tex.typ or Metrostroi.NameConverter[tex.typ] and ent:GetClass() == "gmod_subway_"..Metrostroi.NameConverter[tex.typ]) then ent.Texture = self.tbl.Texture end if ptex and (ent:GetClass() == "gmod_subway_"..ptex.typ or Metrostroi.NameConverter[ptex.typ] and ent:GetClass() == "gmod_subway_"..Metrostroi.NameConverter[ptex.typ]) then ent.PassTexture = self.tbl.PassTexture end if ctex and (ent:GetClass() == "gmod_subway_"..ctex.typ or Metrostroi.NameConverter[ctex.typ] and ent:GetClass() == "gmod_subway_"..Metrostroi.NameConverter[ctex.typ]) then ent.CabTexture = self.tbl.CabTexture end ent:SetNW2String("NW2Fix",string.rep(" ",math.random()*5)) ent:UpdateTextures() end end function TOOL:SpawnWagon(trace) if CLIENT then return end local ply = self:GetOwner() self.oldent = NULL local FIXFIXFIX = {} for i=1,math.random(12) do FIXFIXFIX[i] = ents.Create("env_sprite") end for i=1,self.tbl.WagNum do local ent = self:Spawn(ply, trace, "gmod_subway_"..Trains[self.tbl.Train][i>1 and i<self.tbl.WagNum and self.int and 2 or 1]:lower(), i) self.fent = i == 1 and ent or self.fent if ent and ent:IsValid() then self:SetSettings(ent,ply,i,i>1 and i<self.tbl.WagNum) end self.oldent = ent end self.rot = false for k,v in pairs(FIXFIXFIX) do SafeRemoveEntity(v) end end function TOOL:Finish() if not self then return end if IsValid(self.GhostEntity) then self.GhostEntity:Remove() end self.Spawned = false if SERVER then self:GetOwner():SelectWeapon(self:GetClientInfo("oldW")) else RunConsoleCommand("gmod_toolmode", self:GetClientInfo("oldT")) end end function TOOL:LeftClick(trace) self.Spawned = true --[[ if CLIENT then [ timer.Simple(0.5, function() if self.GhostEntity then RunConsoleCommand("gmod_toolmode", self:GetClientInfo("oldT")) self.GhostEntity:Remove() end end )] return true end ]] --timer.Create(0.5, function() if self.GhostEntity then self.GhostEntity:Remove() end) if SERVER then if self.tbl.WagNum > GetConVarNumber("metrostroi_maxwagons") then self.tbl.WagNum = GetConVarNumber("metrostroi_maxwagons") end if Metrostroi.TrainCountOnPlayer(self:GetOwner()) + self.tbl.WagNum > GetConVarNumber("metrostroi_maxtrains_onplayer")*GetConVarNumber("metrostroi_maxwagons") or Metrostroi.TrainCount() + self.tbl.WagNum > GetConVarNumber("metrostroi_maxtrains")*GetConVarNumber("metrostroi_maxwagons") then Metrostroi.LimitMessage(self:GetOwner()) return true end end self:SpawnWagon(trace) timer.Simple(0,function() self:Finish() end) return end function TOOL:RightClick(trace) if CLIENT then return end self.Rev = not self.Rev --SendCodeToCL() end function TOOL.BuildCPanel(panel) panel:AddControl("Header", { Text = "#Tool.train_spawner.name", Description = "#Tool.train_spawner.desc" }) end if SERVER then --util.AddNetworkString "metrostroi_train_spawner_ghost" --[[ timer.Create("metrostroi_train_spawner_ghost",0.3,0, function() if owner and IsValid(owner) then SendCodeToCL() end end )]] return end --[[ function TOOL:Think() self.tbl = self:GetConvar() if (!IsValid(self.GhostEntity) or self.GhostEntity:GetModel() ~= self:GetCurrentModel(self.tbl.Train,self.tbl.Mask)) then self:MakeGhostEntity(self:GetCurrentModel(self.tbl.Train,self.tbl.Mask), Vector( 0, 0, 0 ), Angle( 0, 0, 0 )) end if not self.GhostEntity then return end self.GhostEntity:SetPos(pos) self.GhostEntity:SetAngles(ang) end]] local function CLGhost() CLpos = net.ReadVector() CLang = net.ReadAngle() self.Rev = net.ReadBit() > 0 end --net.Receive("metrostroi_train_spawner_ghost",CLGhost)
local BonusItem = GetFileConfig("server/setting/bonus/bonus_item_config.lua").RuleData -- local BonusGold = GetFileConfig("server/setting/bonus/bonus_gold_config.lua").RuleData -- local BonusExp = GetFileConfig("server/setting/bonus/bonus_exp_config.lua").BonusRule return function(Data) local DataTbl = Split(Data, ",") for _, data in pairs(DataTbl) do assert(BonusItem[data], "在奖励表中找不到".. Data .. "这个奖励模板") end return DataTbl end
require "scripts/settings" require "scripts/protocol" function Main() Protocol:Connect(server, port) end function ErrorInfo(code) if code == 0x03 then Console:Error("Incorrect account name or password") elseif code == 0x08 then Console:Error("Server network error") elseif code == 0x20 then Console:Error("You have been booted") end end function AuthSuccess() Console:Success("Successful authorization") end function RoleList_Re(roleid, gender, race, occupation, level, level2, name) Console:Log(string.format("%s - %s %s %s", #Roles, name, GetOccupation(occupation), level)) end function GetOccupation(occupation) if occupation == 0 then return "Blademaster" elseif occupation == 1 then return "Wizard" elseif occupation == 2 then return "Psychic" elseif occupation == 3 then return "Venomancer" elseif occupation == 4 then return "Barbarian" elseif occupation == 5 then return "Assassin" elseif occupation == 6 then return "Archer" elseif occupation == 7 then return "Cleric" elseif occupation == 8 then return "Seeker" elseif occupation == 9 then return "Mystic" else return "Unknown" end end function RoleList_End() Console:Print("Type index: ", false) while true do local index = tonumber(Console:ReadLine()) if index ~= nil then if index < 1 or index > #Roles then Console:Print(string.format("You must type index between 1 and %s: ", #Roles), false) else SelectRole(index) break end else Console:Print("Invalid index: ", false) end end end
if (redis.call('set', KEYS[1], ARGV[1], 'ex', ARGV[2], 'nx')) then return true end return false
function dorelease() end
local platform = require 'bee.platform' local config = require 'config' local glob = require 'glob' local furi = require 'file-uri' local parser = require 'parser' local lang = require 'language' local await = require 'await' local timer = require 'timer' local util = require 'utility' local guide = require 'parser.guide' local smerger = require 'string-merger' local progress = require "progress" local unicode if platform.OS == 'Windows' then unicode = require 'bee.unicode' end ---@class files local m = {} m.openMap = {} m.libraryMap = {} m.fileMap = {} m.dllMap = {} m.watchList = {} m.notifyCache = {} m.visible = {} m.assocVersion = -1 m.assocMatcher = nil m.globalVersion = 0 m.fileCount = 0 m.astCount = 0 m.astMap = {} -- setmetatable({}, { __mode = 'v' }) --- 打开文件 ---@param uri uri function m.open(uri) m.openMap[uri] = { cache = {}, } m.onWatch('open', uri) end --- 关闭文件 ---@param uri uri function m.close(uri) m.openMap[uri] = nil local file = m.fileMap[uri] if file then file.trusted = false end m.onWatch('close', uri) end --- 是否打开 ---@param uri uri ---@return boolean function m.isOpen(uri) return m.openMap[uri] ~= nil end function m.getOpenedCache(uri) local data = m.openMap[uri] if not data then return nil end return data.cache end --- 标记为库文件 function m.setLibraryPath(uri, libraryPath) m.libraryMap[uri] = libraryPath end --- 是否是库文件 function m.isLibrary(uri) return m.libraryMap[uri] ~= nil end --- 获取库文件的根目录 function m.getLibraryPath(uri) return m.libraryMap[uri] end function m.flushAllLibrary() m.libraryMap = {} end --- 是否存在 ---@return boolean function m.exists(uri) return m.fileMap[uri] ~= nil end local function pluginOnSetText(file, text) local plugin = require 'plugin' file._diffInfo = nil local suc, result = plugin.dispatch('OnSetText', file.uri, text) if not suc then if DEVELOP and result then util.saveFile(LOGPATH .. '/diffed.lua', tostring(result)) end return text end if type(result) == 'string' then return result elseif type(result) == 'table' then local diffs suc, result, diffs = xpcall(smerger.mergeDiff, log.error, text, result) if suc then file._diffInfo = diffs file.originLines = parser.lines(text) return result else if DEVELOP and result then util.saveFile(LOGPATH .. '/diffed.lua', tostring(result)) end end end return text end --- 设置文件文本 ---@param uri uri ---@param text string function m.setText(uri, text, isTrust, instance) if not text then return end --log.debug('setText', uri) local create if not m.fileMap[uri] then m.fileMap[uri] = { uri = uri, version = 0, } m.fileCount = m.fileCount + 1 create = true m._pairsCache = nil end local file = m.fileMap[uri] if file.trusted and not isTrust then return end if not isTrust and unicode then if config.get 'Lua.runtime.fileEncoding' == 'ansi' then text = unicode.a2u(text) end end if file.originText == text then return end local newText = pluginOnSetText(file, text) file.text = newText file.trusted = isTrust file.originText = text file.words = nil m.astMap[uri] = nil file.cache = {} file.cacheActiveTime = math.huge file.version = file.version + 1 m.globalVersion = m.globalVersion + 1 await.close('files.version') m.onWatch('version') if create then m.onWatch('create', uri) end if DEVELOP then if text ~= newText then util.saveFile(LOGPATH .. '/diffed.lua', newText) end end --if instance or TEST then m.onWatch('update', uri) --else -- await.call(function () -- await.close('update:' .. uri) -- await.setID('update:' .. uri) -- await.sleep(0.1) -- if m.exists(uri) then -- m.onWatch('update', uri) -- end -- end) --end end function m.resetText(uri) local file = m.fileMap[uri] local originText = file.originText file.originText = nil m.setText(uri, originText, file.trusted) end function m.setRawText(uri, text) if not text then return end local file = m.fileMap[uri] file.text = text file.originText = text m.astMap[uri] = nil end function m.getCachedRows(uri) local file = m.fileMap[uri] if not file then return nil end return file.rows end function m.setCachedRows(uri, rows) local file = m.fileMap[uri] if not file then return end file.rows = rows end function m.getWords(uri) local file = m.fileMap[uri] if not file then return end if file.words then return file.words end local words = {} file.words = words local text = file.text if not text then return end local mark = {} for word in text:gmatch '([%a_][%w_]+)' do if #word >= 3 and not mark[word] then mark[word] = true local head = word:sub(1, 2) if not words[head] then words[head] = {} end words[head][#words[head]+1] = word end end return words end function m.getWordsOfHead(uri, head) local file = m.fileMap[uri] if not file then return nil end local words = m.getWords(uri) if not words then return nil end return words[head] end --- 获取文件版本 function m.getVersion(uri) local file = m.fileMap[uri] if not file then return nil end return file.version end --- 获取文件文本 ---@param uri uri ---@return string text function m.getText(uri) local file = m.fileMap[uri] if not file then return nil end return file.text end --- 获取文件原始文本 ---@param uri uri ---@return string text function m.getOriginText(uri) local file = m.fileMap[uri] if not file then return nil end return file.originText end --- 获取文件原始行表 ---@param uri uri ---@return integer[] function m.getOriginLines(uri) local file = m.fileMap[uri] if not file then return nil end return file.originLines end function m.getChildFiles(uri) local results = {} local uris = m.getAllUris() for _, curi in ipairs(uris) do if #curi > #uri and curi:sub(1, #uri) == uri and curi:sub(#uri+1, #uri+1):match '[/\\]' then results[#results+1] = curi end end return results end --- 移除文件 ---@param uri uri function m.remove(uri) local originUri = uri local file = m.fileMap[uri] if not file then return end m.fileMap[uri] = nil m.astMap[uri] = nil m._pairsCache = nil m.flushFileCache(uri) m.fileCount = m.fileCount - 1 m.globalVersion = m.globalVersion + 1 await.close('files.version') m.onWatch('version') m.onWatch('remove', originUri) end --- 移除所有文件 function m.removeAll() local ws = require 'workspace.workspace' m.globalVersion = m.globalVersion + 1 await.close('files.version') m.onWatch('version') m._pairsCache = nil for uri in pairs(m.fileMap) do if not m.libraryMap[uri] then m.fileCount = m.fileCount - 1 m.fileMap[uri] = nil m.astMap[uri] = nil m.onWatch('remove', uri) end end ws.flushCache() --m.notifyCache = {} end --- 移除所有关闭的文件 function m.removeAllClosed() m.globalVersion = m.globalVersion + 1 await.close('files.version') m.onWatch('version') m._pairsCache = nil for uri in pairs(m.fileMap) do if not m.openMap[uri] and not m.libraryMap[uri] then m.fileCount = m.fileCount - 1 m.fileMap[uri] = nil m.astMap[uri] = nil m.onWatch('remove', uri) end end --m.notifyCache = {} end --- 获取一个包含所有文件uri的数组 ---@return uri[] function m.getAllUris() local files = m._pairsCache local i = 0 if not files then files = {} m._pairsCache = files for uri in pairs(m.fileMap) do i = i + 1 files[i] = uri end table.sort(files) end return m._pairsCache end --- 遍历文件 function m.eachFile() local files = m.getAllUris() local i = 0 return function () i = i + 1 local uri = files[i] while not m.fileMap[uri] do i = i + 1 uri = files[i] if not uri then return nil end end return files[i] end end --- Pairs dll files ---@return function function m.eachDll() local map = {} for uri, file in pairs(m.dllMap) do map[uri] = file end return pairs(map) end function m.compileState(uri, text) local ws = require 'workspace' local client = require 'client' if not m.isOpen(uri) and not m.isLibrary(uri) and #text >= config.get 'Lua.workspace.preloadFileSize' * 1000 then if not m.notifyCache['preloadFileSize'] then m.notifyCache['preloadFileSize'] = {} m.notifyCache['skipLargeFileCount'] = 0 end if not m.notifyCache['preloadFileSize'][uri] then m.notifyCache['preloadFileSize'][uri] = true m.notifyCache['skipLargeFileCount'] = m.notifyCache['skipLargeFileCount'] + 1 local message = lang.script('WORKSPACE_SKIP_LARGE_FILE' , ws.getRelativePath(uri) , config.get 'Lua.workspace.preloadFileSize' , #text / 1000 ) if m.notifyCache['skipLargeFileCount'] <= 1 then client.showMessage('Info', message) else client.logMessage('Info', message) end end return nil end local prog <close> = progress.create(lang.script.WINDOW_COMPILING, 0.5) prog:setMessage(ws.getRelativePath(uri)) local clock = os.clock() local state, err = parser.compile(text , 'Lua' , config.get 'Lua.runtime.version' , { special = config.get 'Lua.runtime.special', unicodeName = config.get 'Lua.runtime.unicodeName', nonstandardSymbol = config.get 'Lua.runtime.nonstandardSymbol', } ) local passed = os.clock() - clock if passed > 0.1 then log.warn(('Compile [%s] takes [%.3f] sec, size [%.3f] kb.'):format(uri, passed, #text / 1000)) end --await.delay() if state then state.uri = uri state.ast.uri = uri local clock = os.clock() parser.luadoc(state) local passed = os.clock() - clock if passed > 0.1 then log.warn(('Parse LuaDoc of [%s] takes [%.3f] sec, size [%.3f] kb.'):format(uri, passed, #text / 1000)) end m.astCount = m.astCount + 1 local removed setmetatable(state, {__gc = function () if removed then return end removed = true m.astCount = m.astCount - 1 end}) return state else log.error('Compile failed:', uri, err) return nil end end --- 获取文件语法树 ---@param uri uri ---@return table state function m.getState(uri) local file = m.fileMap[uri] if not file then return nil end local ast = m.astMap[uri] if not ast then ast = m.compileState(uri, file.text) m.astMap[uri] = ast --await.delay() end file.cacheActiveTime = timer.clock() return ast end ---设置文件的当前可见范围 ---@param uri uri ---@param ranges range[] function m.setVisibles(uri, ranges) m.visible[uri] = ranges m.onWatch('updateVisible', uri) end ---获取文件的当前可见范围 ---@param uri uri ---@return table[] function m.getVisibles(uri) local file = m.fileMap[uri] if not file then return nil end local ranges = m.visible[uri] if not ranges or #ranges == 0 then return nil end local visibles = {} for i, range in ipairs(ranges) do local startRow = range.start.line local finishRow = range['end'].line visibles[i] = { start = guide.positionOf(startRow, 0), finish = guide.positionOf(finishRow, 0), } end return visibles end function m.getFile(uri) return m.fileMap[uri] or m.dllMap[uri] end ---@param text string local function isNameChar(text) if text:match '^[\xC2-\xFD][\x80-\xBF]*$' then return true end if text:match '^[%w_]+$' then return true end return false end --- 将应用差异前的offset转换为应用差异后的offset ---@param uri uri ---@param offset integer ---@return integer start ---@return integer finish function m.diffedOffset(uri, offset) local file = m.getFile(uri) if not file then return offset, offset end if not file._diffInfo then return offset, offset end return smerger.getOffset(file._diffInfo, offset) end --- 将应用差异后的offset转换为应用差异前的offset ---@param uri uri ---@param offset integer ---@return integer start ---@return integer finish function m.diffedOffsetBack(uri, offset) local file = m.getFile(uri) if not file then return offset, offset end if not file._diffInfo then return offset, offset end return smerger.getOffsetBack(file._diffInfo, offset) end function m.hasDiffed(uri) local file = m.getFile(uri) if not file then return false end return file._diffInfo ~= nil end --- 获取文件的自定义缓存信息(在文件内容更新后自动失效) function m.getCache(uri) local file = m.fileMap[uri] if not file then return nil end --file.cacheActiveTime = timer.clock() return file.cache end --- 获取文件关联 function m.getAssoc() if m.assocVersion == config.get 'version' then return m.assocMatcher end m.assocVersion = config.get 'version' local patt = {} for k, v in pairs(config.get 'files.associations') do if v == 'lua' then patt[#patt+1] = k end end m.assocMatcher = glob.glob(patt) return m.assocMatcher end --- 判断是否是Lua文件 ---@param uri uri ---@return boolean function m.isLua(uri) local ext = uri:match '%.([^%.%/%\\]+)$' if not ext then return false end if ext == 'lua' then return true end local matcher = m.getAssoc() local path = furi.decode(uri) return matcher(path) end --- Does the uri look like a `Dynamic link library` ? ---@param uri uri ---@return boolean function m.isDll(uri) local ext = uri:match '%.([^%.%/%\\]+)$' if not ext then return false end if platform.OS == 'Windows' then if ext == 'dll' then return true end else if ext == 'so' then return true end end return false end --- Save dll, makes opens and words, discard content ---@param uri uri ---@param content string function m.saveDll(uri, content) if not content then return end local file = { uri = uri, opens = {}, words = {}, } for word in content:gmatch 'luaopen_([%w_]+)' do file.opens[#file.opens+1] = word:gsub('_', '.') end if #file.opens == 0 then return end local mark = {} for word in content:gmatch '(%a[%w_]+)\0' do if word:sub(1, 3) ~= 'lua' then if not mark[word] then mark[word] = true file.words[#file.words+1] = word end end end m.dllMap[uri] = file m.onWatch('dll', uri) end --- ---@param uri uri ---@return string[]|nil function m.getDllOpens(uri) local file = m.dllMap[uri] if not file then return nil end return file.opens end --- ---@param uri uri ---@return string[]|nil function m.getDllWords(uri) local file = m.dllMap[uri] if not file then return nil end return file.words end --- 注册事件 function m.watch(callback) m.watchList[#m.watchList+1] = callback end function m.onWatch(ev, ...) for _, callback in ipairs(m.watchList) do callback(ev, ...) end end function m.flushCache() for uri, file in pairs(m.fileMap) do file.cacheActiveTime = math.huge m.astMap[uri] = nil file.cache = {} end end function m.flushFileCache(uri) local file = m.fileMap[uri] if not file then return end file.cacheActiveTime = math.huge m.astMap[uri] = nil file.cache = {} end function m.init() --TODO 可以清空文件缓存,之后看要不要启用吧 --timer.loop(10, function () -- local list = {} -- for _, file in pairs(m.fileMap) do -- if timer.clock() - file.cacheActiveTime > 10.0 then -- file.cacheActiveTime = math.huge -- file.ast = nil -- file.cache = {} -- list[#list+1] = file.uri -- end -- end -- if #list > 0 then -- log.info('Flush file caches:', #list, '\n', table.concat(list, '\n')) -- collectgarbage() -- end --end) end return m
local M = {} function M.config() local status_ok, toggleterm = pcall(require, "toggleterm") if not status_ok then return end toggleterm.setup(require("core.utils").user_plugin_opts("plugins.toggleterm", { size = 10, open_mapping = [[<c-\>]], hide_numbers = true, shade_filetypes = {}, shade_terminals = true, shading_factor = 2, start_in_insert = true, insert_mappings = true, persist_size = true, direction = "float", close_on_exit = true, shell = vim.o.shell, float_opts = { border = "curved", winblend = 0, highlights = { border = "Normal", background = "Normal", }, }, })) end return M
---@meta ---@class cc.TransitionFlipAngular :cc.TransitionSceneOriented local TransitionFlipAngular={ } cc.TransitionFlipAngular=TransitionFlipAngular ---@overload fun(float:float,cc.Scene:cc.Scene):self ---@overload fun(float:float,cc.Scene:cc.Scene,int:int):self ---@param t float ---@param s cc.Scene ---@param o int ---@return self function TransitionFlipAngular:create (t,s,o) end ---* ---@return self function TransitionFlipAngular:TransitionFlipAngular () end
--------- -- CLI for the make module. ---- local make = require 'luapak.make' local optparse = require 'luapak.optparse' local utils = require 'luapak.utils' local concat = table.concat local fmt = string.format local is_empty = utils.is_empty local reject = utils.reject local split = utils.split local tableize = utils.tableize local help_msg = [[ . Usage: ${PROG_NAME} make [options] [PACKAGE...] ${PROG_NAME} make --help Makes a standalone executable from Lua package(s). This is the main Luapak command that handles entire process from installing dependencies to compiling executable. Arguments: PACKAGE Lua package to build specified as <source-dir>:<rockspec>. :<rockspec> may be omitted if the <source-dir> or <source-dir>/rockspec(s) contains single rockspec, or multiple rockspecs for the same package (i.e. with different version). In the further case rockspec with the highest version is used. <source-dir>: may be omitted if the <rockspec> is in the project's source directory or rockspec(s) subdirectory. If no argument is given, the current directory is used as <source-dir>. Options: -s, --entry-script=FILE The entry point of your program, i.e. the main Lua script. If not specified and the last PACKAGE defines exactly one CLI script, then it's used. -e, --exclude-modules=PATTERNS Module(s) to exclude from dependencies analysis and the generated binary. PATTERNS is one or more glob patterns matching module name in dot notation (e.g. "pl.*"). Patterns may be delimited by comma or space. This option can be also specified multiple times. -g, --debug Enable debug mode, i.e. preserve line numbers, module names and local variable names for error messages and backtraces. -i, --include-modules=PATTERNS Extra module(s) to include in dependencies analysis and add to the generated binary. PATTERNS has the same format as in "--exclude-module". --lua-impl=NAME The Lua implementation that should be used - "PUC" (default), or "LuaJIT". This is currently used only as a hint to find the correct library and headers when auto-detection is used (i.e. --lua-incdir or --lua-lib is not specified). --lua-incdir=DIR The directory that contains Lua (or LuaJIT) headers. If not specified, luapak will look for the lua.h (and luajit.h) file inside: Luarock's LUA_INCDIR, ./vendor/lua, ./deps/lua, /usr/local/include, and /usr/include. If --lua-version is specified, then it will also try subdirectories lua<version> and lua-<version> of each of the named directories and verify that the found lua.h (or luajit.h) is for the specified Lua (or LuaJIT) version. --lua-lib=FILE The library of Lua interpreter to include in the binary. If not specified, luapak will try to find library with version corresponding to the headers inside Luarock's LUA_LIBDIR, ./vendor/lua, ./deps/lua, /usr/local/lib, /usr/local/lib64, /usr/lib, and /usr/lib64. --lua-version=VERSION The version number of Lua (or LuaJIT) headers and library to try to find (e.g. "5.3", "2.0"). -o, --output=FILE Output file name or path. Defaults to base name of the main script with stripped .lua extension. -C, --no-compress Disable BriefLZ compression of Lua sources. -M, --no-minify Disable minification of Lua sources. -t, --rocks-tree=DIR The prefix where to install required modules. Default is ".luapak" in the current directory. -q, --quiet Be quiet, i.e. print only errors. -v, --verbose Be verbose, i.e. print debug messages. -h, --help Display this help message and exit. Environment Variables: AR Archive-maintaining program; default is "ar". CC Command for compiling C; default is "gcc". CMAKE Command for processing CMakeLists.txt files; default is "cmake". CFLAGS Extra flags to give to the C compiler; default is "-Os -fPIC". LD Command for linking object files and archive files; default is "ld". LDFLAGS Extra flags to give to compiler when they are supposed to invoke the linker; default on macOS is "-pagezero_size 10000 -image_base 100000000". MAKE Command for executing Makefile; default is "make". RANLIB Command for generating index to the contents of an archive; default is "ranlib". STRIP Command for discarding symbols from an object file; default is "strip". ]] -- @tparam {string,...}|string|nil value The option value(s). -- @treturn {string,...} local function split_repeated_option (value) if not value then return {} else -- TODO: This is inefficient, use iterator-based functions. return reject(is_empty, split('[,\n]%s*', concat(tableize(value), ','))) end end --- Runs the make command. -- -- @function __call -- @tparam table arg List of CLI arguments. -- @raise if some error occured. return function (arg) local optparser = optparse(help_msg) local args, opts = optparser:parse(arg, { lua_impl = 'PUC' }) if #args == 0 then args = { '.' } end if not ({ puc = 1, luajit = 1 })[opts.lua_impl:lower()] then optparser:opterr(fmt('--lua-impl="%s" is invalid, must be "PUC", or "LuaJIT"', opts.lua_impl)) end local make_opts = { compress = not opts.no_compress, debug = opts.debug, exclude_modules = split_repeated_option(opts.exclude_modules), extra_modules = split_repeated_option(opts.include_modules), lua_impl = opts.lua_impl:lower(), lua_incdir = opts.lua_incdir, lua_lib = opts.lua_lib, lua_version = opts.lua_version, minify = not opts.no_minify, } make(args, opts.entry_script, opts.output, opts.rocks_tree, make_opts) end
AddCSLuaFile( "cl_init.lua" ); AddCSLuaFile( "shared.lua" ); include( "shared.lua" ); util.AddNetworkString("hsholoemitter_datamsg") // wire debug and overlay crap. ENT.WireDebugName = "High speed Holographic Emitter" ENT.OverlayDelay = 0; ENT.LastClear = 0; // init. function ENT:Initialize( ) // set model util.PrecacheModel( "models/jaanus/wiretool/wiretool_range.mdl" ); self:SetModel( "models/jaanus/wiretool/wiretool_range.mdl" ); // setup physics self:PhysicsInit( SOLID_VPHYSICS ); self:SetMoveType( MOVETYPE_VPHYSICS ); self:SetSolid( SOLID_VPHYSICS ); // vars self:SetNWBool( "UseGPS", false ); self:SetNWInt( "LastClear", 0 ); self:SetNWEntity( "grid", self ); // create inputs. self.Inputs = Wire_CreateInputs( self, { "Active", "Reset" } ) self.Outputs = Wire_CreateOutputs( self, { "Memory" } ) self:Setup() end function ENT:Setup() self.Memory = {} self.packetStartAddr = 0 self.lastWrittenAddr = 0 self.packetLen = 0 self.lastThinkChange = false -- Memory: -- 0 - Active -- 1 - readonly: point that is interacted with -- 2 - point size -- 3 - bitmask: 1: show beam 2: global positions 4: individual colors for points -- 4 - number of points -- 5... - points list, format: X,Y,Z, X,Y,Z -- or X,Y,Z,R,G,B,A, X,Y,Z,R,G,B,A with individual color bit set for i = 0, 2047 do self.Memory[i] = 0 end self:ShowOutput() end // link to grid function ENT:LinkToGrid( ent ) self:SetNWEntity( "grid", ent ); end function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} grid = self:GetNWEntity( "grid" ) if grid and (grid:IsValid()) then info.holoemitter_grid = grid:EntIndex() end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) local grid = nil if (info.holoemitter_grid) then grid = GetEntByID(info.holoemitter_grid) if (!grid) then grid = ents.GetByIndex(info.holoemitter_grid) end end if (grid && grid:IsValid()) then self:LinkToGrid(grid) end end function ENT:ShowOutput() local txt = "High Speed Holoemitter\nNumber of points: " .. self.Memory[4] self:SetOverlayText(txt) end function ENT:TriggerInput( inputname, value ) if(not value) then return; end if (inputname == "Reset" and value != 0) then self:WriteCell(4,0) elseif (inputname == "Active") then self:WriteCell(0,value) end end function ENT:SendData() if ( self.packetLen > 0 ) then local rp = RecipientFilter() rp:AddAllPlayers() net.Start("hsholoemitter_datamsg") net.WriteInt(self:EntIndex(), 32) net.WriteInt(self.packetStartAddr, 32) net.WriteInt(self.packetLen, 32) for i = 0, self.packetLen-1 do net.WriteFloat(self.Memory[self.packetStartAddr + i]) end net.Send(rp) end self.packetLen = 0 self.packetStartAddr = 0 end function ENT:ReadCell( Address ) if(!self.Memory) then return; end if ( Address >= 0 and Address <= 4 + 3*GetConVar("hsholoemitter_max_points"):GetInt() ) then return self.Memory[Address] end end function ENT:WriteCell( Address, Value ) if ( Address >= 0 and Address <= 4 + 3*GetConVar("hsholoemitter_max_points"):GetInt() ) then self.Memory[Address] = Value self.lastThinkChange = true if( self.packetLen == 0 ) then self.packetLen = 1 self.packetStartAddr = Address elseif( (Address - self.lastWrittenAddr) == 1 ) then self.packetLen = self.packetLen + 1 if( self.packetLen >= 30 ) then self:SendData() end else self:SendData() self.packetLen = 1 self.packetStartAddr = Address end self.lastWrittenAddr = Address return true end return false end function ENT:Think() if( not self.lastThinkChange ) then self:SendData() end self.lastThinkChange = false end function ENT:UpdateTransmitState() return TRANSMIT_ALWAYS end function HSHoloInteract(ply,cmd,args) local entid = tonumber(args[1]) local num = tonumber(args[2]) if (!entid || entid <= 0) then return end ent = ents.GetByIndex(entid) if (!ent || !ent:IsValid()) then return end if (ent:GetClass() != "gmod_wire_hsholoemitter") then return end if (num < 0 || num > 680) then return end if ( !gamemode.Call( "PlayerUse", ply, ent ) ) then return end ent:WriteCell(1,num) end concommand.Add("HSHoloInteract",HSHoloInteract)
local _M = {} local app = require('lib.app') function _M:loadAudio() local stream = audio.loadStream('music/fire.mp3') local c = audio.play(stream, {loops = -1}) audio.setVolume(0, {channel = c}) audio.fade{channel = c, time = 3000, volume = 0.4} end return _M
local Plugin = {} function Plugin:Initialise() self.Enabled = true TGNS.ScheduleAction(10, function() local originalStatusFunc = Shine.Commands.sh_status and Shine.Commands.sh_status.Func or nil if originalStatusFunc then Shine.Commands.sh_status.Func = function(client) originalStatusFunc(client) ServerAdminPrint(client, string.format("Server address: %s", TGNS.Config.ServerAddress)) ServerAdminPrint(client, "This is a TacticalGamer.com server. http://rr.tacticalgamer.com/Community") end end end) return true end function Plugin:Cleanup() --Cleanup your extra stuff like timers, data etc. self.BaseClass.Cleanup( self ) end Shine:RegisterExtension("statusextended", Plugin )
--[[ Name: cl_menu_actmenu.lua For: TalosLife By: TalosLife Push and hold "T" to view the taunt menu, mouse over an action and release "T". ]]-- local MAT_BLUR = Material( "pp/blurscreen.png", "noclamp" ) local Actions = { "Cheer", "Laugh", "Muscle", "Zombie", "Robot", "Disagree", "Agree", "Dance", "Becon", "Salute", "Wave", "Forward", "Pers", } local Panel = {} function Panel:Init() self:Build() end function Panel:Build() if self.m_tblButtons then for k, v in pairs( self.m_tblButtons ) do if ValidPanel( v ) then v:Remove() end end end self.m_strSndHover = Sound( "garrysmod/ui_hover.wav" ) self.m_matBlur = MAT_BLUR self.m_texWhite = surface.GetTextureID( "vgui/white" ) self.m_int360 = math.pi *2 self.m_intCurAngle = 90 self.m_intTargetAngle = 90 self:InitializeButtons() end function Panel:InitializeButtons() self.m_tblButtons = {} for k, v in ipairs( Actions ) do self.m_tblButtons[k] = { Name = v, Cmd = v:lower(), } end local count = #self.m_tblButtons self.m_intBtnAng = math.pi *2 /count for k, v in pairs( self.m_tblButtons ) do v.Angle = (k -2) *self.m_intBtnAng -math.pi /2 while v.Angle < 0 do v.Angle = v.Angle +math.pi *2 end end end local MOUSE_CHECK_DIST = 120 local MOUSE_CUR_DIST = 0 function Panel:Think() if IsValid( LocalPlayer() ) and LocalPlayer().HandsUp and self:IsVisible() then self:SetVisible( false ) return end local mx, my = gui.MousePos() local cx, cy = ScrW() /2, ScrH() /2 MOUSE_CUR_DIST = math.Distance( mx, my, cx, cy ) if MOUSE_CUR_DIST > 48 then local norm = Vector( mx -cx, cy -my, 0 ):GetNormal() self.m_intTargetAngle = norm:Angle().y if MOUSE_CUR_DIST > MOUSE_CHECK_DIST then gui.SetMousePos( cx +norm.x *MOUSE_CHECK_DIST, cy -norm.y *MOUSE_CHECK_DIST ) end end self.m_intCurAngle = math.ApproachAngle( self.m_intCurAngle, self.m_intTargetAngle, 55 *(math.AngleDifference(self.m_intCurAngle, self.m_intTargetAngle) /180) ) self.m_intCurSelection, _ = self:GetCurrentSelection() if self.m_intLastSelection and self.m_intCurSelection ~= self.m_intLastSelection then surface.PlaySound( self.m_strSndHover ) end self.m_intLastSelection = self.m_intCurSelection end function Panel:GetCurrentSelection() local selectionAngle, selection = -1, nil local selectedAng = -1 for k, v in pairs( self.m_tblButtons ) do local ang = math.deg( v.Angle -self.m_intBtnAng /2 ) local diff = math.AngleDifference( self.m_intCurAngle, ang ) if selectionAngle == -1 or diff < selectionAngle then selectionAngle = diff selection = k selectedAng = math.deg( v.Angle ) +180 end end return selection, math.NormalizeAngle( selectedAng ) end function Panel:BuildPoly( x, y, radius, count ) self.m_tblCurrentPoly = { x = x, y = y, radius = radius, count = count } local delta = self.m_int360 /count local verts = {} for n = 0, self.m_int360, delta do local c, s = math.cos( n ), math.sin( n ) table.insert( verts, { x = x +c *radius, y = y +s *radius, u = 0.5 +c *0.5, v = 0.5 +s *0.5 } ) end self.m_tblCurrentPoly.Verts = verts end function Panel:DrawCircle( x, y, radius, count ) local cur = self.m_tblCurrentPoly if not cur or cur.x ~= x or cur.y ~= y or cur.radius ~= radius or cur.count ~= count then self:BuildPoly( x, y, radius, count ) end if self.m_tblCurrentPoly and self.m_tblCurrentPoly.Verts then surface.SetTexture( self.m_texWhite ) surface.DrawPoly( self.m_tblCurrentPoly.Verts ) end end function Panel:PaintBackground( intW, intH ) local bgRadius = intW /2 local bgPolyCount = 38 surface.SetDrawColor( 30, 30, 30, 125 ) self:DrawCircle( intW -bgRadius, bgRadius, bgRadius, bgPolyCount ) render.ClearStencil() render.SetStencilEnable( true ) render.SetStencilReferenceValue( 1 ) render.SetStencilTestMask( 1 ) render.SetStencilWriteMask( 1 ) render.SetStencilCompareFunction( STENCILCOMPARISONFUNCTION_NEVER ) render.SetStencilFailOperation( STENCILOPERATION_REPLACE ) render.SetStencilPassOperation( STENCILOPERATION_REPLACE ) render.SetStencilZFailOperation( STENCILOPERATION_REPLACE ) surface.SetDrawColor( 255, 255, 255, 255 ) self:DrawCircle( intW -bgRadius, bgRadius, bgRadius, bgPolyCount ) render.SetStencilCompareFunction( STENCILCOMPARISONFUNCTION_EQUAL ) render.SetStencilFailOperation( STENCILOPERATION_KEEP ) render.SetStencilPassOperation( STENCILOPERATION_KEEP ) render.SetStencilZFailOperation( STENCILOPERATION_KEEP ) surface.SetMaterial( self.m_matBlur ) surface.SetDrawColor( 255, 255, 255, 255 ) for i = 0, 1, 0.33 do self.m_matBlur:SetFloat( '$blur', 5 *i ) self.m_matBlur:Recompute() render.UpdateScreenEffectTexture() local x, y = self:GetPos() surface.DrawTexturedRect( -x, -y, ScrW(), ScrH() ) end render.SetStencilEnable( false ) end function Panel:Paint( intW, intH ) local sx, sy = intW /2, intH /2 local size, size_half, center = intW, intW /2, intW /2.66 self:PaintBackground( intW, intH ) surface.SetDrawColor( 255, 255, 255, 255 ) for k, v in pairs( self.m_tblButtons ) do local brightness = (k == self.m_intCurSelection and 255 or 125) local ang = v.Angle local vx, vy = math.cos( ang ), math.sin( ang ) local x, y = sx -vx *center, sy +vy *(center -1) local lx, ly = math.cos( ang +self.m_intBtnAng /2 ), math.sin( ang +self.m_intBtnAng /2 ) surface.SetDrawColor( 80, 80, 80, 200 ) surface.DrawLine( sx +lx *74, sy +ly *74, sx +lx *128, sy +ly *128 ) surface.SetFont( "DermaDefaultBold" ) local tw, th = surface.GetTextSize( v.Name ) surface.SetTextColor( 0, 0, 0, 255 ) for _x = -1, 1 do for _y = -1, 1 do surface.SetTextPos( (x -tw /2) +_x, (y -th /2) +_y ) surface.DrawText( v.Name ) end end surface.SetTextColor( brightness, brightness, brightness, 220 ) surface.SetTextPos( x -tw /2, y -th /2 ) surface.DrawText( v.Name ) end end function Panel:Open() if IsValid( LocalPlayer() ) and LocalPlayer().HandsUp then return end self:SetVisible( true ) self:MakePopup() self:SetKeyBoardInputEnabled( false ) local selection, ang = self:GetCurrentSelection() self.m_intTargetAngle = ang self.m_intCurAngle = ang end function Panel:Close() local selection, _ = self:GetCurrentSelection() local action = self.m_tblButtons[selection] if action then RunConsoleCommand( "act", action.Cmd ) end self:SetVisible( false ) end vgui.Register( "SRPActRadialMenu", Panel, "EditablePanel" )
local plugin = {} plugin.name = "Change Swap Timers Live" plugin.author = "SushiKishi" plugin.settings = { { name="timerFile", type="file", label="What file to use?" }, } plugin.description = [[ NOTE: Using this plugin will render the Minimum and Maximum swap times on the setup window useless, as they are overwritten by the plugin. Make sure the setup file contains the times you want to start with before clicking on Start or Resume Session! This plugin allows you to use a separate .TXT file to update your minimum and maximum swap timers on the fly. This replicates a (probably unintended) feature of the first Bizhawk Shuffler where you could change these on the fly and they would apply without restarting the entire session. You can use this to offer, say, a donation incentive to speed up your swap timers. You'll need to modify this .TXT file yourself -- any sort of Twitch or chat interaction is beyond the scope of what I'm willing to deal with. There's a default settings file with the plugin, but the file can go wherever you choose. The format has to be specific, however. In case you lose the default file, the only two lines it contains are: config.min_swap=1 config.max_swap=3 Adjust your minimum/maximum times, in seconds, accordingly. Any kind of check to make sure you've put valid integers there that won't goof up the works is also beyond the scope of what I'm willing to learn -- I just wanted this feature quickly without having to learn how to code beyond the basics. Finally -- this directly changes the configuation of your Shuffler settings. This is only worth mentinoing because they won't go back to "default" at the start of a new session -- you'll have to modify the plugin's settings file directly every time you load this plugin if you need to revert them back. ]] -- called once at the start -- This makes sure the first game swap of the new/resumed session -- has the same timers as the plugin's configuation file. -- Otherwise, it uses the numbers on the Shuffler's set-up screen. function plugin.on_setup(data, settings) local liveTimers = loadfile(settings.timerFile) --load the settings file as set in Plugin config if liveTimers ~= nil then -- if it exists / is not empty liveTimers() -- execute the code inside -- which updates the config.[VARIABLES] liveTimers = nil -- remove the file from memory; I mean, yeah, it's a small file, but no sense in it hanging around end -- Ends the If/Then statement end -- Ends the On_Setup part of the plugin -- called each time a game/state is saved (before swap) function plugin.on_game_save(data, settings) local liveTimers = loadfile(settings.timerFile) --load the settings file as set in Plugin config if liveTimers ~= nil then -- if it exists / is not empty liveTimers() -- execute the code inside -- which updates the config.[VARIABLES] liveTimers = nil -- remove the file from memory; I mean, yeah, it's a small file, but no sense in it hanging around end -- Ends the If/Then statement end -- Ends the on_game_Save part of the plugin return plugin
local modularStationUtil = {}
WireToolSetup.setCategory( "Vehicle Control" ) WireToolSetup.open( "vehicle", "Vehicle Controller", "gmod_wire_vehicle", nil, "Vehicle Controllers" ) if CLIENT then language.Add("Tool.wire_vehicle.name", "Vehicle Controller Tool (Wire)") language.Add("Tool.wire_vehicle.desc", "Spawn/link a Wire Vehicle controller.") end WireToolSetup.BaseLang() WireToolSetup.SetupMax( 20 ) TOOL.ClientConVar[ "model" ] = "models/jaanus/wiretool/wiretool_siren.mdl" WireToolSetup.SetupLinking(true, "vehicle") function TOOL.BuildCPanel(panel) WireDermaExts.ModelSelect(panel, "wire_vehicle_model", list.Get( "Wire_Misc_Tools_Models" ), 1) end
/*--------------------------------------------------------------------------- Vector2 class Author: Oskar ---------------------------------------------------------------------------*/ do local meta = {} meta.__index = meta function meta:__add( other ) return Vector2( self.x + other.x, self.y + other.y ) end function meta:__sub( other ) return Vector2( self.x - other.x, self.y - other.y ) end function meta:__mul( other ) return Vector2( self.x * other.x, self.y * other.y ) end function meta:__div( other ) return Vector2( self.x / other.x, self.y / other.y ) end function meta:__mod( other ) return Vector2( self.x % other.x, self.y % other.y ) end function meta:__pow( other ) return Vector2( self.x ^ other.x, self.y ^ other.y ) end function meta:__unm( ) return self * -1 end function meta:__len( ) -- Garry has broken this =( return math.sqrt( self.x * self.x + self.y * self.y ) end function meta:__eq( other ) return self.x == other.x and self.y == other.y end function meta:__lt( other ) return self.x < other.x and self.y < other.y end function meta:__le( other ) return self.x <= other.x and self.y <= other.y end function meta:__call( x, y ) return self.x + (x or 0), self.y + (y or 0) end function meta:__tostring( ) return "Vector2: " .. self.x .. " " .. self.y end function meta:Dot( other ) return self.x * other.x + self.y * other.y end function meta:Normalize( ) return Vector2( self.x / Len, self.y / Len ) end function meta:Round( dec ) return Vector2( math.Round( self.x, dec ), math.Round( self.y, dec ) ) end function meta:Length( ) return math.sqrt( self.x * self.x + self.y * self.y ) end function meta:Cross( other ) return setmetatable( { x = ( self.y * other.z ) - ( other.y * self.z ), y = ( self.z * other.x ) - ( other.z * self.x ) }, meta ) end -- RevouluPowered function meta:Distance( other ) return ( self - other ):Length() end -- RevouluPowered function meta:Set( x, y ) self.x = x self.y = y return self end function meta:Add( x, y ) self.x = self.x + x self.y = self.y + y return self end function meta:Sub( x, y ) self.x = self.x - x self.y = self.y - y return self end function meta:Clone( ) return Vector2( self.x, self.y ) end local setmetatable = setmetatable local Vec2 = { Zero = setmetatable({ x = 0, y = 0 }, meta) } Vec2.__index = Vec2 function Vec2:__call( a, b ) return setmetatable({x = a or 0, y = b or 0}, meta) end Vector2 = { } setmetatable( Vector2, Vec2 ) debug.getregistry().Vector2 = meta end
----------------------------------------- -- ID: 5178 -- Item: plate_of_dorado_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- Dexterity 5 -- Accuracy % 15 -- Accuracy Cap 72 -- Ranged ACC % 15 -- Ranged ACC Cap 72 -- Sleep Resist 1 -- Enmity 4 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(tpz.effect.FOOD) or target:hasStatusEffect(tpz.effect.FIELD_SUPPORT_FOOD) then result = tpz.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(tpz.effect.FOOD,0,0,1800,5178) end function onEffectGain(target,effect) target:addMod(tpz.mod.ENMITY, 4) target:addMod(tpz.mod.DEX, 5) target:addMod(tpz.mod.FOOD_ACCP, 15) target:addMod(tpz.mod.FOOD_ACC_CAP, 72) target:addMod(tpz.mod.FOOD_RACCP, 15) target:addMod(tpz.mod.FOOD_RACC_CAP, 72) target:addMod(tpz.mod.SLEEPRES, 1) end function onEffectLose(target, effect) target:delMod(tpz.mod.ENMITY, 4) target:delMod(tpz.mod.DEX, 5) target:delMod(tpz.mod.FOOD_ACCP, 15) target:delMod(tpz.mod.FOOD_ACC_CAP, 72) target:delMod(tpz.mod.FOOD_RACCP, 15) target:delMod(tpz.mod.FOOD_RACC_CAP, 72) target:delMod(tpz.mod.SLEEPRES, 1) end
local getSeagull = require("entity/seagull") local camera = require("core/camera") local function getSeagullSpawner(player) seagullSpawner = {} seagullSpawner.spawncounter = 1 seagullSpawner.player = player function seagullSpawner:update(dt) -- Spawn random seagulls. self.spawncounter = self.spawncounter - dt if self.spawncounter <= 0 then state = stack:current() local sw = settings.resolution.width local sh = settings.resolution.height local relativeHeight = math.random(camera.y - 200, camera.y - 50) if (relativeHeight < 0 and relativeHeight >= -sh * 0.5) or relativeHeight >= 0 then y = relativeHeight x = camera.x + sw/2 + math.random(sw * 0.1, sw * 0.3) else x = camera.x + sw + math.random(sw * 0.1, sw * 0.3) y = -sh * 0.5 end local randomspawn = { x = x, y = y, } local new_seagull = getSeagull(randomspawn.x, randomspawn.y, player) --print("Spawning seagull at ", randomspawn.x, randomspawn.y) table.insert(state.entities, new_seagull) self.spawncounter = math.random(8, 12) end end return seagullSpawner end return getSeagullSpawner
local item = require("../item"); local image = require("../image") return { name = "A ratty proposal", amount = 5, weight = 0.5, condition = function (state) return state.coins >= 5 and state.ratLevel == 0 end, description = "A sketchy man in a trenchcoat approaches you. For only $5, you may join the Rat Club and get 4 wonderful rats you can sell.", heads = { effectDescription = "+4 rats", effect = function (state) for i = 1,4 do table.insert(state.items, item.rat) end state.ratLevel = 1 return { description = "The man hands you a rat insigna and 4 rats. You are part of Rat Club! Now go and sell these rats", image = image.rat4, } end }, tails = { effectDescription = "+10 coins", effect = function (state) state.coins = state.coins + 10 return { description = [["I will NOT join your rat scheme!" you say as you punch the guy. He runs away, but leaves 10 coins behind in his confusion.]], image = image.plus10, } end }, beg = { effectDescription = "-5 hp", effect = function (state) state.hp = state.hp - 5 return { description = [[You stare at the man, unanswering. Suddenly a rat jumps out of his trenchcoat and bites you. You lose 5 hp.]], image = image.blood, } end } }
require("enet") local class = require("libs.class") local utils = require("utils") local netUtils = require("net.utils") local GameObject = require("gameobject") local mp = require("libs.MessagePack") local Client = class("Client") function Client:initialize(server_host) self.host = enet.host_create() self.server = self.host:connect(server_host) end function Client:handlePackage(type, data) netUtils.netLog("handle", type, utils.inspect(data)) if type == "update" then for _, object in ipairs(data.updates) do -- update world end end end function Client:processPackage(eventData) local package = mp.unpack(eventData) self:handlePackage(package.type, package.data) end function Client:receive() local event = self.host:service() while event do if event.type == "receive" then self:processPackage(event.data) elseif event.type == "connect" then error("Invalid state: only just connected") elseif event.type == "disconnect" then return "Server disconnected" end event = self.host:service() end return nil end function Client:sendUpdate() local updates = {} for _, object in pairs(GameObject.world) do if object.owned then if object.serialize then table.insert(updates, object:serialize()) else table.insert(updates, object) end end end netUtils.sendPackage(self.server, "update", { updates = updates }) return nil end function Client:checkConnected() if self.server:state() == "connected" then return {connected = true} else local event = self.host:service() while event do if event.type == "receive" then error("Invalid state: Got message while waiting for a connection") elseif event.type == "connect" then return {connected = true} elseif event.type == "disconnect" then return {failed = true} end event = self.host:service() end return {connected = false} end end function Client:close() if self.server:state() == "connected" then self.server:disconnect() self.host:flush() end end return Client
function min(x, y) if x >= y then return y else return x end end function max(x, y) if x <= y then return y else return x end end
local Class = require "smee.libs.middleclass" local GameComponent = Class "GameComponent" function GameComponent:initialize() end function GameComponent:update(dt) end function GameComponent:draw(dt) end return GameComponent
nadmin.config.adverts = nadmin.config.adverts or {} local adverts = nadmin.config.adverts util.AddNetworkString("nadmin_add_advert") util.AddNetworkString("nadmin_req_adverts") util.AddNetworkString("nadmin_resend_advert") net.Receive("nadmin_resend_advert", function(len, ply) if not ply:HasPerm("manage_server_settings") then nadmin:Notify(ply, nadmin.colors.red, "You aren't allowed to manage server settings.") return end local ind = net.ReadInt(32) if istable(adverts[ind]) then adverts[ind].lastRan = 0 end end) net.Receive("nadmin_add_advert", function(len, ply) local msg = net.ReadString() local rep = net.ReadInt(32) local col = net.ReadTable() local ind = net.ReadInt(32) if not ply:HasPerm("manage_server_settings") then nadmin:Notify(ply, nadmin.colors.red, "You aren't allowed to manage server settings.") return end if msg == "" then if istable(adverts[ind]) then table.remove(adverts, ind) end else if istable(adverts[ind]) then adverts[ind] = { text = msg, repeatAfter = rep, color = Color(col[1], col[2], col[3]), lastRan = adverts[ind].lastRan } else table.insert(adverts, { text = msg, repeatAfter = rep, color = Color(col[1], col[2], col[3]), lastRan = 0 }) end end net.Start("nadmin_req_adverts") net.WriteTable(adverts) net.Send(ply) file.Write("nadmin/config/adverts.txt", util.TableToJSON(adverts)) end) local loaded = file.Read("nadmin/config/adverts.txt", "DATA") if isstring(loaded) then loaded = util.JSONToTable(loaded) table.Merge(adverts, loaded) for i = 1, #adverts do local adv = adverts[i] if not IsColor(adv.color) and istable(adv.color) then local col = adv.color adv.color = Color(col.r, col.g, col.b) end end end net.Receive("nadmin_req_adverts", function(len, ply) net.Start("nadmin_req_adverts") net.WriteTable(adverts) net.Send(ply) end) hook.Add("Think", "nadmin_adverts", function() local now = os.time() for i = 1, #adverts do local adv = adverts[i] -- Validate the advert is setup correctly if not isstring(adv.text) then continue end if not isnumber(adv.repeatAfter) then continue end if not IsColor(adv.color) then continue end if not isnumber(adv.lastRan) then adv.lastRan = 0 end if now - adv.lastRan >= (adv.repeatAfter * nadmin.time.m) then nadmin:Notify(adv.color, adv.text) adv.lastRan = now end end end)
--Localization.enUS.lua TomTomLocals = { ["%d yards"] = "%d yards", ["%s (%.2f, %.2f)"] = "%s (%.2f, %.2f)", ["%s yards away"] = "%s yards away", ["%s%s - %s %s %s %s"] = "%s%s - %s %s %s %s", ["%s%s - %s (map: %d)"] = "%s%s - %s (map: %d)", ["%s: No coordinate information found for '%s' at this map level"] = "%s: No coordinate information found for '%s' at this map level", ["%sNo waypoints in this zone"] = "%sNo waypoints in this zone", ["Accept waypoints from guild and party members"] = "Accept waypoints from guild and party members", ["Allow closest waypoint to be outside current zone"] = "Allow closest waypoint to be outside current zone", ["Allow control-right clicking on map to create new waypoint"] = "Allow control-right clicking on map to create new waypoint", ["Allow the corpse arrow to override other waypoints"] = "Allow the corpse arrow to override other waypoints", ["Alpha"] = "Alpha", ["Announce new waypoints when they are added"] = "Announce new waypoints when they are added", ["Are you sure you would like to remove ALL TomTom waypoints?"] = "Are you sure you would like to remove ALL TomTom waypoints?", ["Arrow colors"] = "Arrow colors", ["Arrow display"] = "Arrow display", ["Arrow locked"] = "Arrow locked", ["Ask for confirmation on \"Remove All\""] = "Ask for confirmation on \"Remove All\"", ["Automatically set a waypoint when I die"] = "Automatically set a waypoint when I die", ["Automatically set to next closest waypoint"] = "Automatically set to next closest waypoint", ["Automatically set waypoint arrow"] = "Automatically set waypoint arrow", ["Background color"] = "Background color", ["Bad color"] = "Bad color", ["Block height"] = "Block height", ["Block width"] = "Block width", ["Border color"] = "Border color", ["Channel to play the ping through"] = "Channel to play the ping through", ["Clear waypoint distance"] = "Clear waypoint distance", ["Clear waypoint from crazy arrow"] = "Clear waypoint from crazy arrow", ["Controls the frequency of updates for the coordinate LDB feed."] = "Controls the frequency of updates for the coordinate LDB feed.", ["Controls the frequency of updates for the coordinate block."] = "Controls the frequency of updates for the coordinate block.", ["Controls the frequency of updates for the crazy arrow LDB feed."] = "Controls the frequency of updates for the crazy arrow LDB feed.", ["Coordinate Accuracy"] = "Coordinate Accuracy", ["Coordinate Block"] = "Coordinate Block", ["Coordinate feed accuracy"] = "Coordinate feed accuracy", ["Coordinate feed throttle"] = "Coordinate feed throttle", ["Coordinates can be displayed as simple XX, YY coordinate, or as more precise XX.XX, YY.YY. This setting allows you to control that precision"] = "Coordinates can be displayed as simple XX, YY coordinate, or as more precise XX.XX, YY.YY. This setting allows you to control that precision", ["Coordinates can be slid from the default location, to accomodate other addons. This setting allows you to control that offset"] = "Coordinates can be slid from the default location, to accomodate other addons. This setting allows you to control that offset", ["Could not find any matches for zone %s."] = "Could not find any matches for zone %s.", ["Crazy Arrow feed throttle"] = "Crazy Arrow feed throttle", ["Create note modifier"] = "Create note modifier", ["Cursor Coordinates"] = "Cursor Coordinates", ["Cursor coordinate accuracy"] = "Cursor coordinate accuracy", ["Cursor coordinate offset"] = "Cursor coordinate offset", ["Data Feed Options"] = "Data Feed Options", ["Disable all mouse input"] = "Disable all mouse input", ["Disables the crazy taxi arrow for mouse input, allowing all clicks to pass through"] = "Disables the crazy taxi arrow for mouse input, allowing all clicks to pass through", ["Display Settings"] = "Display Settings", ["Display waypoints from other zones"] = "Display waypoints from other zones", ["Enable automatic quest objective waypoints"] = "Enable automatic quest objective waypoints", ["Enable coordinate block"] = "Enable coordinate block", ["Enable floating waypoint arrow"] = "Enable floating waypoint arrow", ["Enable minimap waypoints"] = "Enable minimap waypoints", ["Enable mouseover tooltips"] = "Enable mouseover tooltips", ["Enable quest objective click integration"] = "Enable quest objective click integration", ["Enable showing cursor coordinates"] = "Enable showing cursor coordinates", ["Enable showing player coordinates"] = "Enable showing player coordinates", ["Enable the right-click contextual menu"] = "Enable the right-click contextual menu", ["Enable world map waypoints"] = "Enable world map waypoints", ["Enables a floating block that displays your current position in the current zone"] = "Enables a floating block that displays your current position in the current zone", ["Enables a menu when right-clicking on a waypoint allowing you to clear or remove waypoints"] = "Enables a menu when right-clicking on a waypoint allowing you to clear or remove waypoints", ["Enables a menu when right-clicking on the waypoint arrow allowing you to clear or remove waypoints"] = "Enables a menu when right-clicking on the waypoint arrow allowing you to clear or remove waypoints", ["Enables the automatic setting of quest objective waypoints based on which objective is closest to your current location. This setting WILL override the setting of manual waypoints."] = "Enables the automatic setting of quest objective waypoints based on which objective is closest to your current location. This setting WILL override the setting of manual waypoints.", ["Enables the setting of waypoints when modified-clicking on quest objectives"] = "Enables the setting of waypoints when modified-clicking on quest objectives", ["Exact color"] = "Exact color", ["Font size"] = "Font size", ["Found %d possible matches for zone %s. Please be more specific"] = "Found %d possible matches for zone %s. Please be more specific", ["Found multiple matches for zone '%s'. Did you mean: %s"] = "Found multiple matches for zone '%s'. Did you mean: %s", ["From: %s"] = "From: %s", ["General Options"] = "General Options", ["Good color"] = "Good color", ["Hide the crazy arrow display during pet battles"] = "Hide the crazy arrow display during pet battles", ["Icon Control"] = "Icon Control", ["If you have changed the waypoint display settings (minimap, world), this will re-set all waypoints to the current options."] = "If you have changed the waypoint display settings (minimap, world), this will re-set all waypoints to the current options.", ["If your arrow is covered up by something else, try this to bump it up a layer."] = "If your arrow is covered up by something else, try this to bump it up a layer.", ["Lock coordinate block"] = "Lock coordinate block", ["Lock waypoint arrow"] = "Lock waypoint arrow", ["Locks the coordinate block so it can't be accidentally dragged to another location"] = "Locks the coordinate block so it can't be accidentally dragged to another location", ["Locks the waypoint arrow, so it can't be moved accidentally"] = "Locks the waypoint arrow, so it can't be moved accidentally", ["Middle color"] = "Middle color", ["Minimap"] = "Minimap", ["Minimap Icon"] = "Minimap Icon", ["Minimap Icon Size"] = "Minimap Icon Size", ["My Corpse"] = "My Corpse", ["No"] = "No", ["Normally when TomTom sets the closest waypoint it chooses the waypoint in your current zone. This option will cause TomTom to search for any waypoints on your current continent. This may lead you outside your current zone, so it is disabled by default."] = "Normally when TomTom sets the closest waypoint it chooses the waypoint in your current zone. This option will cause TomTom to search for any waypoints on your current continent. This may lead you outside your current zone, so it is disabled by default.", ["Options profile"] = "Options profile", ["Options that alter quest objective integration"] = "Options that alter quest objective integration", ["Options that alter the coordinate block"] = "Options that alter the coordinate block", ["Place the arrow in the HIGH strata"] = "Place the arrow in the HIGH strata", ["Play a sound when arriving at a waypoint"] = "Play a sound when arriving at a waypoint", ["Player Coordinates"] = "Player Coordinates", ["Player coordinate accuracy"] = "Player coordinate accuracy", ["Player coordinate offset"] = "Player coordinate offset", ["Profile Options"] = "Profile Options", ["Prompt before accepting sent waypoints"] = "Prompt before accepting sent waypoints", ["Provide a LDB data source for coordinates"] = "Provide a LDB data source for coordinates", ["Provide a LDB data source for the crazy-arrow"] = "Provide a LDB data source for the crazy-arrow", ["Quest Objectives"] = "Quest Objectives", ["Remove all waypoints"] = "Remove all waypoints", ["Remove all waypoints from this zone"] = "Remove all waypoints from this zone", ["Remove waypoint"] = "Remove waypoint", ["Removed %d waypoints from %s"] = "Removed %d waypoints from %s", ["Reset Position"] = "Reset Position", ["Reset waypoint display options to current"] = "Reset waypoint display options to current", ["Resets the position of the waypoint arrow if its been dragged off screen"] = "Resets the position of the waypoint arrow if its been dragged off screen", ["Save new waypoints until I remove them"] = "Save new waypoints until I remove them", ["Save profile for TomTom waypoints"] = "Save profile for TomTom waypoints", ["Save this waypoint between sessions"] = "Save this waypoint between sessions", ["Saved profile for TomTom options"] = "Saved profile for TomTom options", ["Scale"] = "Scale", ["Send to battleground"] = "Send to battleground", ["Send to guild"] = "Send to guild", ["Send to party"] = "Send to party", ["Send to raid"] = "Send to raid", ["Send waypoint to"] = "Send waypoint to", ["Set as waypoint arrow"] = "Set as waypoint arrow", ["Show estimated time to arrival"] = "Show estimated time to arrival", ["Show the distance to the waypoint"] = "Show the distance to the waypoint", ["Shows an estimate of how long it will take you to reach the waypoint at your current speed"] = "Shows an estimate of how long it will take you to reach the waypoint at your current speed", ["Shows the distance (in yards) to the waypoint"] = "Shows the distance (in yards) to the waypoint", ["The color to be displayed when you are halfway between the direction of the active waypoint and the completely wrong direction"] = "The color to be displayed when you are halfway between the direction of the active waypoint and the completely wrong direction", ["The color to be displayed when you are moving in the direction of the active waypoint"] = "The color to be displayed when you are moving in the direction of the active waypoint", ["The color to be displayed when you are moving in the exact direction of the active waypoint"] = "The color to be displayed when you are moving in the exact direction of the active waypoint", ["The color to be displayed when you are moving in the opposite direction of the active waypoint"] = "The color to be displayed when you are moving in the opposite direction of the active waypoint", ["The display of the coordinate block can be customized by changing the options below."] = "The display of the coordinate block can be customized by changing the options below.", ["The floating waypoint arrow can change color depending on whether or nor you are facing your destination. By default it will display green when you are facing it directly, and red when you are facing away from it. These colors can be changed in this section. Setting these options to the same color will cause the arrow to not change color at all"] = "The floating waypoint arrow can change color depending on whether or nor you are facing your destination. By default it will display green when you are facing it directly, and red when you are facing away from it. These colors can be changed in this section. Setting these options to the same color will cause the arrow to not change color at all", ["There were no waypoints to remove in %s"] = "There were no waypoints to remove in %s", ["These options let you customize the size and opacity of the waypoint arrow, making it larger or partially transparent, as well as limiting the size of the title display."] = "These options let you customize the size and opacity of the waypoint arrow, making it larger or partially transparent, as well as limiting the size of the title display.", ["This option will not remove any waypoints that are currently set to persist, but only effects new waypoints that get set"] = "This option will not remove any waypoints that are currently set to persist, but only effects new waypoints that get set", ["This option will toggle whether or not you are asked to confirm removing all waypoints. If enabled, a dialog box will appear, requiring you to confirm removing the waypoints"] = "This option will toggle whether or not you are asked to confirm removing all waypoints. If enabled, a dialog box will appear, requiring you to confirm removing the waypoints", ["This setting allows you to change the opacity of the title text, making it transparent or opaque"] = "This setting allows you to change the opacity of the title text, making it transparent or opaque", ["This setting allows you to change the opacity of the waypoint arrow, making it transparent or opaque"] = "This setting allows you to change the opacity of the waypoint arrow, making it transparent or opaque", ["This setting allows you to change the scale of the waypoint arrow, making it larger or smaller"] = "This setting allows you to change the scale of the waypoint arrow, making it larger or smaller", ["This setting allows you to control the default size of the minimap icon. "] = "This setting allows you to control the default size of the minimap icon. ", ["This setting allows you to control the default size of the world map icon"] = "This setting allows you to control the default size of the world map icon", ["This setting allows you to select the default icon for the minimap"] = "This setting allows you to select the default icon for the minimap", ["This setting allows you to select the default icon for the world map"] = "This setting allows you to select the default icon for the world map", ["This setting allows you to specify the maximum height of the title text. Any titles that are longer than this height (in game pixels) will be truncated."] = "This setting allows you to specify the maximum height of the title text. Any titles that are longer than this height (in game pixels) will be truncated.", ["This setting allows you to specify the maximum width of the title text. Any titles that are longer than this width (in game pixels) will be wrapped to the next line."] = "This setting allows you to specify the maximum width of the title text. Any titles that are longer than this width (in game pixels) will be wrapped to the next line.", ["This setting allows you to specify the scale of the title text."] = "This setting allows you to specify the scale of the title text.", ["This setting changes the modifier used by TomTom when right-clicking on a quest objective POI to create a waypoint"] = "This setting changes the modifier used by TomTom when right-clicking on a quest objective POI to create a waypoint", ["This setting changes the modifier used by TomTom when right-clicking on the world map to create a waypoint"] = "This setting changes the modifier used by TomTom when right-clicking on the world map to create a waypoint", ["This setting will control the distance at which the waypoint arrow switches to a downwards arrow, indicating you have arrived at your destination"] = "This setting will control the distance at which the waypoint arrow switches to a downwards arrow, indicating you have arrived at your destination", ["Title Alpha"] = "Title Alpha", ["Title Height"] = "Title Height", ["Title Scale"] = "Title Scale", ["Title Width"] = "Title Width", ["TomTom Waypoint Arrow"] = "TomTom Waypoint Arrow", ["TomTom can announce new waypoints to the default chat frame when they are added"] = "TomTom can announce new waypoints to the default chat frame when they are added", ["TomTom can automatically set a waypoint when you die, guiding you back to your corpse"] = "TomTom can automatically set a waypoint when you die, guiding you back to your corpse", ["TomTom can be configured to set waypoints for the quest objectives that are shown in the watch frame and on the world map. These options can be used to configure these options."] = "TomTom can be configured to set waypoints for the quest objectives that are shown in the watch frame and on the world map. These options can be used to configure these options.", ["TomTom can display a tooltip containing information abouto waypoints, when they are moused over. This setting toggles that functionality"] = "TomTom can display a tooltip containing information abouto waypoints, when they are moused over. This setting toggles that functionality", ["TomTom can display multiple waypoint arrows on the minimap. These options control the display of these waypoints"] = "TomTom can display multiple waypoint arrows on the minimap. These options control the display of these waypoints", ["TomTom can display multiple waypoints on the world map. These options control the display of these waypoints"] = "TomTom can display multiple waypoints on the world map. These options control the display of these waypoints", ["TomTom can hide waypoints in other zones, this setting toggles that functionality"] = "TomTom can hide waypoints in other zones, this setting toggles that functionality", ["TomTom is capable of providing data sources via LibDataBroker, which allows them to be displayed in any LDB compatible display. These options enable or disable the individual feeds, but will only take effect after a reboot."] = "TomTom is capable of providing data sources via LibDataBroker, which allows them to be displayed in any LDB compatible display. These options enable or disable the individual feeds, but will only take effect after a reboot.", ["TomTom provides an arrow that can be placed anywhere on the screen. Similar to the arrow in \"Crazy Taxi\" it will point you towards your next waypoint"] = "TomTom provides an arrow that can be placed anywhere on the screen. Similar to the arrow in \"Crazy Taxi\" it will point you towards your next waypoint", ["TomTom provides you with a floating coordinate display that can be used to determine your current position. These options can be used to enable or disable this display, or customize the block's display."] = "TomTom provides you with a floating coordinate display that can be used to determine your current position. These options can be used to enable or disable this display, or customize the block's display.", ["TomTom waypoint"] = "TomTom waypoint", ["TomTom's saved variables are organized so you can have shared options across all your characters, while having different sets of waypoints for each. These options sections allow you to change the saved variable configurations so you can set up per-character options, or even share waypoints between characters"] = "TomTom's saved variables are organized so you can have shared options across all your characters, while having different sets of waypoints for each. These options sections allow you to change the saved variable configurations so you can set up per-character options, or even share waypoints between characters", ["Unknown distance"] = "Unknown distance", ["Unknown waypoint"] = "Unknown waypoint", ["Update throttle"] = "Update throttle", ["Wayback"] = "Wayback", ["Waypoint Arrow"] = "Waypoint Arrow", ["Waypoint Options"] = "Waypoint Options", ["Waypoint communication"] = "Waypoint communication", ["Waypoint from %s"] = "Waypoint from %s", ["Waypoints can be automatically cleared when you reach them. This slider allows you to customize the distance in yards that signals your \"arrival\" at the waypoint. A setting of 0 turns off the auto-clearing feature\n\nChanging this setting only takes effect after reloading your interface."] = "Waypoints can be automatically cleared when you reach them. This slider allows you to customize the distance in yards that signals your \"arrival\" at the waypoint. A setting of 0 turns off the auto-clearing feature\n\nChanging this setting only takes effect after reloading your interface.", ["Waypoints profile"] = "Waypoints profile", ["When a 'ping' is played, use the indicated sound channel so the volume can be controlled."] = "When a 'ping' is played, use the indicated sound channel so the volume can be controlled.", ["When a new waypoint is added, TomTom can automatically set the new waypoint as the \"Crazy Arrow\" waypoint."] = "When a new waypoint is added, TomTom can automatically set the new waypoint as the \"Crazy Arrow\" waypoint.", ["When a pet battle begins, the crazy arrow will be hidden from view. When you exit the pet battle, it will be re-shown."] = "When a pet battle begins, the crazy arrow will be hidden from view. When you exit the pet battle, it will be re-shown.", ["When the current waypoint is cleared (either by the user or automatically) and this option is set, TomTom will automatically set the closest waypoint in the current zone as active waypoint."] = "When the current waypoint is cleared (either by the user or automatically) and this option is set, TomTom will automatically set the closest waypoint in the current zone as active waypoint.", ["When the player is dead and has a waypoint towards their corpse, it will prevent other waypoints from changing the crazy arrow"] = "When the player is dead and has a waypoint towards their corpse, it will prevent other waypoints from changing the crazy arrow", ["When you 'arrive' at a waypoint (this distance is controlled by the 'Arrival Distance' setting in this group) a sound can be played to indicate this. You can enable or disable this sound using this setting."] = "When you 'arrive' at a waypoint (this distance is controlled by the 'Arrival Distance' setting in this group) a sound can be played to indicate this. You can enable or disable this sound using this setting.", ["World Map"] = "World Map", ["World Map Icon"] = "World Map Icon", ["World Map Icon Size"] = "World Map Icon Size", ["Yes"] = "Yes", ["You are at (%s) in '%s' (map: %s)"] = "You are at (%s) in '%s' (map: %s)", ["\"Arrival Distance\""] = "\"Arrival Distance\"", ["is"] = "is", ["not"] = "not", ["set waypoint modifier"] = "set waypoint modifier", ["|cffffff78/cway |r - Activate the closest waypoint"] = "|cffffff78/cway |r - Activate the closest waypoint", ["|cffffff78/tomtom |r - Open the TomTom options panel"] = "|cffffff78/tomtom |r - Open the TomTom options panel", ["|cffffff78/way /tway /tomtomway |r - Commands to set a waypoint: one should work."] = "|cffffff78/way /tway /tomtomway |r - Commands to set a waypoint: one should work.", ["|cffffff78/way <x> <y> [desc]|r - Adds a waypoint at x,y with descrtiption desc"] = "|cffffff78/way <x> <y> [desc]|r - Adds a waypoint at x,y with descrtiption desc", ["|cffffff78/way <zone> <x> <y> [desc]|r - Adds a waypoint at x,y in zone with description desc"] = "|cffffff78/way <zone> <x> <y> [desc]|r - Adds a waypoint at x,y in zone with description desc", ["|cffffff78/way arrow|r - Prints status of the Crazy Arrow"] = "|cffffff78/way arrow|r - Prints status of the Crazy Arrow", ["|cffffff78/way block|r - Prints status of the Coordinate Block"] = "|cffffff78/way block|r - Prints status of the Coordinate Block", ["|cffffff78/way list|r - Lists all active waypoints"] = "|cffffff78/way list|r - Lists all active waypoints", ["|cffffff78/way local|r - Lists active waypoints in current zone"] = "|cffffff78/way local|r - Lists active waypoints in current zone", ["|cffffff78/way reset <zone>|r - Resets all waypoints in zone"] = "|cffffff78/way reset <zone>|r - Resets all waypoints in zone", ["|cffffff78/way reset all|r - Resets all waypoints"] = "|cffffff78/way reset all|r - Resets all waypoints", ["|cffffff78/way reset away|r - Resets all waypoints not in current zone"] = "|cffffff78/way reset away|r - Resets all waypoints not in current zone", ["|cffffff78/way reset not <zone>|r - Resets all waypoints not in zone"] = "|cffffff78/way reset not <zone>|r - Resets all waypoints not in zone", ["|cffffff78TomTom |r/way /tway /tomtomway /cway /tomtom |cffffff78Usage:|r"] = "|cffffff78TomTom |r/way /tway /tomtomway /cway /tomtom |cffffff78Usage:|r", ["|cffffff78TomTom:|r Added a waypoint (%s%s%s) in %s"] = "|cffffff78TomTom:|r Added a waypoint (%s%s%s) in %s", ["|cffffff78TomTom:|r CoordBlock %s visible"] = "|cffffff78TomTom:|r CoordBlock %s visible", ["|cffffff78TomTom:|r Could not find a closest waypoint in this continent."] = "|cffffff78TomTom:|r Could not find a closest waypoint in this continent.", ["|cffffff78TomTom:|r Could not find a closest waypoint in this zone."] = "|cffffff78TomTom:|r Could not find a closest waypoint in this zone.", ["|cffffff78TomTom:|r CrazyArrow %s hijacked"] = "|cffffff78TomTom:|r CrazyArrow %s hijacked", ["|cffffff78TomTom:|r CrazyArrow %s visible"] = "|cffffff78TomTom:|r CrazyArrow %s visible", ["|cffffff78TomTom:|r Selected waypoint (%s%s%s) in %s"] = "|cffffff78TomTom:|r Selected waypoint (%s%s%s) in %s", ["|cffffff78TomTom:|r Waypoint %s valid"] = "|cffffff78TomTom:|r Waypoint %s valid", ["|cffffff78TomTom|r: Added '%s' (sent from %s) to zone %s"] = "|cffffff78TomTom|r: Added '%s' (sent from %s) to zone %s", } setmetatable(TomTomLocals, {__index=function(t,k) rawset(t, k, k); return k; end})
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Lageegee -- Type: Assault Mission Giver -- !pos 120.808 0.161 -30.435 ----------------------------------- local ID = require("scripts/zones/Aht_Urhgan_Whitegate/IDs") require("scripts/globals/besieged") require("scripts/globals/keyitems") require("scripts/globals/missions") require("scripts/globals/npc_util") ----------------------------------- function onTrade(player,npc,trade) end function onTrigger(player,npc) local rank = tpz.besieged.getMercenaryRank(player) local haveimperialIDtag local assaultPoints = player:getAssaultPoint(PERIQIA_ASSAULT_POINT) if player:hasKeyItem(tpz.ki.IMPERIAL_ARMY_ID_TAG) then haveimperialIDtag = 1 else haveimperialIDtag = 0 end --[[ if (rank > 0) then player:startEvent(276,rank,haveimperialIDtag,assaultPoints,player:getCurrentAssault()) else]] player:startEvent(282) -- no rank --end end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) if csid == 276 then local selectiontype = bit.band(option, 0xF) if selectiontype == 1 then -- taken assault mission player:addAssault(bit.rshift(option,4)) player:delKeyItem(tpz.ki.IMPERIAL_ARMY_ID_TAG) npcUtil.giveKeyItem(player, tpz.ki.PERIQIA_ASSAULT_ORDERS) elseif (selectiontype == 2) then -- purchased an item local item = bit.rshift(option,14) local items = { [1] = {itemid = 15973, price = 3000}, [2] = {itemid = 15778, price = 5000}, [3] = {itemid = 15524, price = 8000}, [4] = {itemid = 15887, price = 10000}, [5] = {itemid = 15493, price = 10000}, [6] = {itemid = 18025, price = 15000}, [7] = {itemid = 18435, price = 15000}, [8] = {itemid = 18686, price = 15000}, [9] = {itemid = 16062, price = 20000}, [10] = {itemid = 15695, price = 20000}, [11] = {itemid = 14527, price = 20000}, } local choice = items[item] if choice and npcUtil.giveItem(player, choice.itemid) then player:delCurrency("PERIQIA_ASSAULT_POINT", choice.price) end end end end
object_tangible_furniture_all_frn_diner_counter_corner = object_tangible_furniture_all_shared_frn_diner_counter_corner:new { } ObjectTemplates:addTemplate(object_tangible_furniture_all_frn_diner_counter_corner, "object/tangible/furniture/all/frn_diner_counter_corner.iff")
return function() local strrLine = "Turn,Scroll,7,8,9,10" if GAMESTATE:GetCurrentGame():GetName() == "gh" then strrLine = strrLine .. ",GH" end strrLine = strrLine .. ",11,12,125,13,14" if ThemePrefs.Get("OptionStyle") == 0 then strrLine = strrLine .. ",NextScreen" elseif ThemePrefs.Get("OptionStyle") == 1 then TP.Global.ScreenAfter.PlayerOptions2 = "ScreenSongOptions" elseif ThemePrefs.Get("OptionStyle") == 2 then TP.Global.ScreenAfter.PlayerOptions2 = "ScreenStageInformation" end return strrLine end
local fn = vim.fn local lsp = vim.lsp local M = {} -- Credit https://github.com/kosayoda/nvim-lightbulb/blob/master/lua/nvim-lightbulb.lua local function _update_sign(new_line) local bufnr = vim.api.nvim_get_current_buf() or '%' local old_line = vim.b.code_action_line if old_line then fn.sign_unplace('code_action', { id = old_line, buffer = bufnr }) vim.b.code_action_line = nil end if new_line and (vim.b.code_action_line ~= new_line) then fn.sign_place(new_line, 'code_action', 'CodeActionSign', bufnr, { lnum = new_line, priority = 10 }) vim.b.code_action_line = new_line end end -- Credit https://github.com/kosayoda/nvim-lightbulb/blob/master/lua/nvim-lightbulb.lua function M.code_action() local context = { diagnostics = lsp.diagnostic.get_line_diagnostics() } local params = lsp.util.make_range_params() params.context = context lsp.buf_request(0, 'textDocument/codeAction', params, function(err, actions) if err then return end if actions == nil or vim.tbl_isempty(actions) then _update_sign(nil) else _update_sign(params.range.start.line + 1) end end) end return M
---------------------------------------------------------------- -- EVTCalendar English Localization -- Author: Reed -- -- ---------------------------------------------------------------- EVT_SLASH = "/evt"; EVT_CALENDAR = "EVTCalendar"; EVT_HELP = "help"; EVT_ABOUT = "about"; --MONTHS EVT_JAN = "January"; EVT_FEB = "Feburary"; EVT_MAR = "March"; EVT_APR = "April"; EVT_MAY = "May"; EVT_JUN = "June"; EVT_JUL = "July"; EVT_AUG = "August"; EVT_SEP = "September"; EVT_OCT = "October"; EVT_NOV = "November"; EVT_DEC = "December"; --DAYS EVT_SUN = "Sunday"; EVT_MON = "Monday"; EVT_TUE = "Tuesday"; EVT_WED = "Wednesday"; EVT_THU = "Thursday"; EVT_FRI = "Friday"; EVT_SAT = "Saturday"; --Chat EVT_INVITE_QUEUE = "has invited you to an event. Do you accept?" evtSubMenu = { [1] = {"Blackfathom Depths", "Blackrock Depths", "Blackrock Spire", "The Deadmines", "Dire Maul", "Gnomeregan", "Maraudon", "Ragefire Chasm", "Razorfen Downs", "Razorfen Kraul", "Scarlet Monastery", "Scholomance", "Shadowfang Keep", "The Stockades", "Stratholome", "The Sunken Temple", "Uldaman", "Wailing Caverns", "Zul'Farak" }, [2] = {"Blackwing Lair", "Molten Core", "Naxxramas", "Onyxia's Lair", "Ruins of Ahn'Qiraj", "Temple of Ahn'Qiraj", "Zul'Gurub"}, [3] = {"Warsong Gultch", "Arathi Basin", "Alterac Valley", "World"} }; evtTypes = {"Dungeon", "Raid", "PvP", "Quests", "Meeting", "Event", "Other" }; evtInvites = {"Party", "Raid", "Guild", "Guild Officers"}; evtInviteLock = {"None", "Officers", "Self"};
local assert = require('assert') local sched = require('sched') local fs = require('fs') local testing = require('testing') -- the return value of this require() call is a top-level TestSuite -- object predefined by the testing module (root_suite) -- we can either add our tests directly to the root suite or create -- child suites and add tests to those local markers = {} testing:add('add a test directly to the root suite', function() assert.equals(1,1) markers.oneisone = true end) -- if we do not pass a function, testing:add() creates a child suite local child = testing:add('adding a child suite') child:add('add a test to the child suite', function() assert.equals(2,2) markers.twoistwo = true end) child:add('add another test to the child suite', function() assert.equals(-2,-2) markers.minustwoisminustwo = true end) -- testing(...) is shorthand for testing:add(...) -- (this also works on a child suite) testing('the testing() shorthand', function() assert.equals(3,3) markers.threeisthree = true end) -- tests within a suite are not guaranteed to run sequentially -- -- the only thing we can guarantee (for the current implementation) is -- that tests in child suites are _scheduled_ later than tests of the -- parent suite testing(function() assert.equals(markers, { oneisone = true, threeisthree = true }) end) -- if you want to do something after all tests in a suite finished, -- use an after hook: testing:after(function() assert.equals(markers, { oneisone = true, twoistwo = true, minustwoisminustwo = true, threeisthree = true }) end) -- tests marked as `exclusive` own the CPU until they finish (i.e. the -- scheduler won't schedule another thread until they finish) -- -- note: use this feature sparingly as it can easily lead to lockups local normal_results = {} testing('normal 123', function() table.insert(normal_results, 1) sched.yield() table.insert(normal_results, 2) sched.yield() table.insert(normal_results, 3) sched.yield() end) testing('normal 456', function() table.insert(normal_results, 4) sched.yield() table.insert(normal_results, 5) sched.yield() table.insert(normal_results, 6) sched.yield() assert.equals(normal_results, { 1,4,2,5,3,6 }) end) local exclusive_results = {} testing:exclusive('exclusive 123', function() table.insert(exclusive_results, 1) sched.yield() table.insert(exclusive_results, 2) sched.yield() table.insert(exclusive_results, 3) sched.yield() end) testing:exclusive('exclusive 456', function() table.insert(exclusive_results, 4) sched.yield() table.insert(exclusive_results, 5) sched.yield() table.insert(exclusive_results, 6) sched.yield() assert.equals(exclusive_results, { 1,2,3,4,5,6 }) end) -- tests marked as `nosched` are executed upfront in a separate round, -- when the scheduler has not yet been created -- -- this feature is mostly (only?) useful for testing the scheduler -- itself testing('running under a scheduler', function() assert(sched.running()) end) testing:nosched('not running under a scheduler', function() assert(not sched.running()) end) -- `before` hooks are executed once, before all tests within a suite local suite = testing('before hooks') suite:before(function(ctx) -- the passed table is a test context which can be used to store -- arbitrary objects -- -- these objects are accessible in all descendants of the suite ctx.conn = 'this could be a database connection mock' end) suite:before(function(ctx) -- :before() can be used several times to add any number of hooks ctx.http_client = 'http client' end) suite:add('check test context', function(ctx) assert.equals(ctx.conn, 'this could be a database connection mock') assert.equals(ctx.http_client, 'http client') -- context modifications are scoped to the running test ctx.http_client = 'https client' ctx.checked = true end) suite('context modifications cannot escape their scope', function(ctx) assert.equals(ctx.http_client, 'http client') assert.is_nil(ctx.checked) end) -- after hooks are executed once, after all tests within a suite suite:after(function(ctx) assert.equals(ctx.conn, 'this could be a database connection mock') assert.equals(ctx.http_client, 'http client') end) -- after hooks do not see context modifications made by children suite:after(function(ctx) assert.is_nil(ctx.checked) end) -- child suites see context modifications of their parent local child = suite:add('child') child('child suites inherit context modifications', function(ctx) assert.equals(ctx.conn, 'this could be a database connection mock') assert.equals(ctx.http_client, 'http client') end) -- before_each and after_each hooks are run before and after each test local counter = 0 suite:before(function() assert.equals(counter, 0) end) suite:before_each(function() counter = counter + 1 end) suite('inside a test, counter should be 1', function() assert.equals(counter, 1) end) suite:after_each(function() counter = counter - 1 end) suite:after(function() assert.equals(counter, 0) end) -- nosched tests cannot use before/after hooks suite:nosched('nosched tests cannot use before/after hooks', function(ctx) assert.is_nil(ctx.conn) assert.is_nil(ctx.http_client) end) -- but they can use before_each and after_each suite:nosched('nosched tests can use before_each/after_each hooks', function(ctx) assert.equals(counter, 1) end) -- the test context provides a nextid() method which can be used to -- generate an integer guaranteed to be unique within the current test -- run testing('nextid', function(ctx) local id1 = ctx:nextid() assert.type(id1, 'number') local id2 = ctx:nextid() assert.type(id2, 'number') assert(id1 ~= id2) end) -- tests marked as `with_tmpdir` get a temporary directory which is -- automatically removed when the root suite exits -- -- the path of the temp directory is available as ctx.tmpdir testing:with_tmpdir('with_tmpdir', function(ctx) -- the temp directory path is at ctx.tmpdir assert.type(ctx.tmpdir, "string") assert(fs.is_dir(ctx.tmpdir)) end) -- tests may be skipped by specifying the `skip` option local nomod = 1 testing:skip('this is skipped', function() nomod = 2 end) testing:after(function() assert.equals(nomod, 1) end) -- test options (i.e. `exclusive`, `nosched`, `with_tmpdir`, `skip`) -- may be also passed after the test function in an opts table testing('opts table', function(ctx) assert(not sched.running()) assert(fs.is_dir(ctx.tmpdir)) end, { nosched = true, exclusive = true, with_tmpdir = true }) -- the two ways of setting options can be mixed testing:nosched('opts table 2', function(ctx) assert(not sched.running()) assert(fs.is_dir(ctx.tmpdir)) end, { exclusive = true, with_tmpdir = true })
-- luacheck: globals unpack vim local curry2 = function(fn) return function(fst, snd) if snd ~= nil then return fn(fst, snd) end return function(new) return fn(fst, new) end end end local view = {} view.openfloat = function(config, buff) return vim.api.nvim_open_win(buff, false, config) end view.openwin = function(nvim_cmd, buff) vim.api.nvim_command(nvim_cmd) vim.api.nvim_set_current_buf(buff) local winid = vim.fn.win_getid(vim.fn.bufwinnr(buff)) vim.api.nvim_win_set_option(winid, "winfixwidth", true) return winid end view.top = function(size, buff) local width = vim.o.columns return view.openfloat({ relative = "editor", width = width, height = size, row = 0, col = 0 }, buff) end view.bottom = function(size, buff) local width = vim.o.columns local height = vim.o.lines return view.openfloat({ relative = "editor", width = width, height = size, row = height - size, col = 0 }, buff) end view.right = function(size, buff) local width = vim.o.columns local height = vim.o.lines return view.openfloat({ relative = "editor", width = size, height = height, row = 0, col = width - size }, buff) end view.left = function(size, buff) local height = vim.o.lines return view.openfloat({ relative = "editor", width = size, height = height, row = 0, col = 0 }, buff) end view.center = function(size, buff) local width = vim.o.columns local height = vim.o.lines return view.openfloat({ relative = "editor", width = math.ceil(width * 0.5), height = size, row = math.ceil(height * 0.5) - math.ceil(size * 0.5), col = math.ceil(width * 0.25) }, buff) end return setmetatable({}, {__index = function(_, key) return curry2(view[key]) end})
-- Awesome theme for esonov distro. local gears = require("gears") local naughty_config = require("naughty").config local xresources = require("beautiful.xresources") local beautiful = require("beautiful") local gtk = beautiful.gtk.get_theme_variables() local dpi = xresources.apply_dpi local theme = {} -- General look and feel. theme.font = "Roboto 10" theme.bg_normal = "#2e293a" theme.bg_focus = "#3d354b" theme.bg_urgent = "#481565" theme.bg_minimize = "#2e293a" theme.bg_systray = "#2e293a" theme.fg_normal = "#cac8d1" theme.fg_focus = "#dcdae0" theme.fg_urgent = "#dcdae0" theme.fg_minimize = "#cac8d1" -- Client settings theme.useless_gap = 0 theme.border_width = 0 theme.border_normal = theme.bg_normal theme.border_focus = theme.bg_focus theme.border_marked = theme.bg_focus theme.tasklist_plain_task_name = true -- Titlebar (for dialogs) theme.titlebar_bg = "#313131cc" theme.titlebar_height = dpi(18) theme.titlebar_font = "Roboto 9" theme.titlebar_shape = function(cr, w, h) gears.shape.partially_rounded_rect(cr, w, h, true, true, false, false, theme.titlebar_height) end -- Prompt box theme. theme.prompt_font = "Hack 11" -- Variables set for theming notifications: theme.notification_font = "Droid Sans 12" theme.notification_bg = "#685f77" theme.notification_fg = "#e0dfe2" theme.notification_width = nil theme.notification_height = nil theme.notification_margin = nil theme.notification_border_color = "#685f77" theme.notification_border_width = dpi(3) theme.notification_shape = function(cr, w, h) gears.shape.rounded_rect(cr, w, h, 4) end theme.notification_icon_size = 48 theme.notification_opacity = 0.92 -- Fix colors of presets notification styles. naughty_config.presets.critical.bg = "#961528" naughty_config.presets.critical.fg = theme.notification_fg naughty_config.presets.ok.bg = "#206128" naughty_config.presets.ok.fg = theme.notification_fg naughty_config.presets.info.bg = "#2015a2" naughty_config.presets.info.fg = theme.notification_fg naughty_config.presets.warn.bg = "#965a28" naughty_config.presets.warn.fg = theme.notification_fg -- Variables set for theming the menu: -- menu_[bg|fg]_[normal|focus] -- menu_[border_color|border_width] theme.menu_submenu_icon = icons_path .. "outline_arrow_right.png" -- Mostly irrelevant. theme.menu_height = dpi(16) theme.menu_width = dpi(128) -- Wallpaper. gears.wallpaper.set(theme.bg_normal) -- Define the icon theme for application icons. -- If not set then the icons from /usr/share/icons and /usr/share/icons/hicolor will be used. -- Used only by the menubar as far as I know. theme.icon_theme = "Papirus-Dark" -- Bar layout. theme.bar_layout = { close_image = icons_path.."close.png", close_hover_image = icons_path.."close_hover.png", tasklist_height = dpi(14), tasklist_icon_margin = {left = dpi(2), right = dpi(3), up = 1, bottom = 1}, tasklist_title_margin = {left = dpi(3), right = dpi(4), up = 0, bottom = dpi(2)}, tasklist_close_margin = {left = dpi(4), right = dpi(2), up = 0, bottom = 0}, tasklist_close_button_image = icons_path.."tasklist_close.png", tasklist_close_button_hover_image = icons_path.."tasklist_close_hover.png", tasklist_close_button_size = dpi(14) } -- Tag colors and layout theme.tag = {layout = {}, colors = {inactive = {}, active = {}, highlight = {}, bubble = {}}} theme.tag.layout.icon_size = dpi(24) theme.tag.layout.padding = 1 theme.tag.layout.spacing = dpi(8) theme.tag.layout.halo_scale = 1.08 theme.tag.layout.bubble_offset_x = dpi(20) theme.tag.layout.bubble_offset_y = dpi(20) theme.tag.layout.bubble_text_offset_x = dpi(17) theme.tag.layout.bubble_text_offset_y = dpi(15) theme.tag.layout.bubble_radius = 5 theme.tag.layout.bubble_font = "Hack Bold 6" theme.tag.layout.default_cursor = "left_ptr" theme.tag.layout.hover_cursor = "hand1" theme.tag.layout.invalid_cursor = "left_ptr" theme.tag.layout.locked_cursor = "circle" -- Same as the background. theme.tag.colors.inactive["000000"] = "#2e293a" theme.tag.colors.active["000000"] = "#2e293a" theme.tag.colors.highlight["000000"] = "#2e293a" -- The base color. theme.tag.colors.inactive["ffffff"] = "#8c80a4" theme.tag.colors.active["ffffff"] = "#cac8d1" theme.tag.colors.highlight["ffffff"] = "#cac8d1" -- Highlight color pattern #1. -- It is invisible when inactive, and pulsating when urgent. theme.tag.colors.inactive["ff0000"] = "#2e293a" theme.tag.colors.active["ff0000"] = "#4629bb" theme.tag.colors.highlight["ff0000"] = "#2a00c1" -- Highlight color pattern #2. -- Visible even when inactive, but darker. theme.tag.colors.inactive["00ff00"] = "#292089" theme.tag.colors.active["00ff00"] = "#4629bb" theme.tag.colors.highlight["00ff00"] = "#2a00c1" -- Highlight color pattern #3. -- Constant color(may add blur when urgent), just a bit darker when inactive. theme.tag.colors.inactive["0000ff"] = "#292089" theme.tag.colors.active["0000ff"] = "#4629bb" theme.tag.colors.highlight["0000ff"] = "#4629bb" theme.tag.colors.bubble.locked = "#ffd700aa" theme.tag.colors.bubble.waiting = "#d6820699" theme.tag.colors.bubble.inactive = "#2e293a66" theme.tag.colors.bubble.active = "#5b4965cc" theme.tag.colors.bubble.selected = "#362f43ff" theme.tag.colors.bubble.font = { active="#ffffffaa", selected="#ffffff99" } theme.tag.colors.halo = { inactive="#8c80a4cc", active="#cac8d1aa" } return theme
--------------------------------------------------------------- -- Copyright 2020 Deviap (https://deviap.com/) -- --------------------------------------------------------------- -- Made available under the MIT License: -- -- https://github.com/deviap/sample-apps/blob/master/LICENSE -- --------------------------------------------------------------- return function(params) -- Create a square in the centre of the parent object -- We'll rotate this square to pivot the hand, easy! local pivot = core.construct("guiFrame", { parent = params.parent, position = guiCoord(0.5, -1, 0.5, -1), size = guiCoord(0, 2, 0, 2), backgroundAlpha = 0 }) -- The actual hand the user sees core.construct("guiFrame", { parent = pivot, position = guiCoord(0.5, -params.width / 2, 0, -params.length + (params.width / 2)), size = guiCoord(0, params.width, 0, params.length), backgroundColour = params.colour }) return pivot end
--- lexer for etlua. -- Uses embeddings of lua and html. -- @author [Alejandro Baez](https://twitter.com/a_baez) -- @copyright 2015 -- @license MIT (see LICENSE) -- @module etlua local l = require("lexer") local token, word_match = l.token, l.word_match local P, R, S = lpeg.P, lpeg.R, lpeg.S local M = {_NAME = 'etlua'} local html = l.load("html") local lual = l.load("lua") -- Embed lua to html. local escapes = S('=-') local lual_start_rule = token('etlua_tag', '<%' + '<%' * escapes^-1) local lual_end_rule = token('etlua_tag', '%>' + P('-')^-1 * '%>') l.embed_lexer(html, lual, lual_start_rule, lual_end_rule) M._tokenstyles = { etlua_tag = l.STYLE_EMBEDDED } local _foldsymbols = html._foldsymbols _foldsymbols._patterns[#_foldsymbols._patterns + 1] = '<%%' _foldsymbols._patterns[#_foldsymbols._patterns + 1] = '%%>' _foldsymbols.rhtml_tag = {['<%'] = 1, ['%>'] = -1} M._foldsymbols = _foldsymbols return M
insulate("log setup", function() it("check default channel registration", function() require("tmux.log").setup() local channels = require("tmux.log.channels") assert.is_true(channels.current["file"] ~= nil) end) end) describe("log", function() local log local message = "" setup(function() log = require("tmux.log") require("tmux.log.time").now = function() return "1234" end require("tmux.configuration.logging").set({ file = "disabled", nvim = "disabled", }) require("tmux.log.channels").add("busted", function(sev, msg) message = sev .. " - " .. msg end) end) it("check severity and disables", function() require("tmux.configuration.logging").set({ busted = "disabled", }) log.debug("test") assert.are.same("", message) log.information("test") assert.are.same("", message) log.warning("test") assert.are.same("", message) log.error("test") assert.are.same("", message) require("tmux.configuration.logging").set({ busted = "debug", }) message = "" log.debug("test") assert.are.same("debug - test", message) log.information("test") assert.are.same("information - test", message) log.warning("test") assert.are.same("warning - test", message) log.error("test") assert.are.same("error - test", message) require("tmux.configuration.logging").set({ busted = "information", }) message = "" log.debug("test") assert.are.same("", message) log.information("test") assert.are.same("information - test", message) log.warning("test") assert.are.same("warning - test", message) log.error("test") assert.are.same("error - test", message) require("tmux.configuration.logging").set({ busted = "warning", }) message = "" log.debug("test") assert.are.same("", message) log.information("test") assert.are.same("", message) log.warning("test") assert.are.same("warning - test", message) log.error("test") assert.are.same("error - test", message) require("tmux.configuration.logging").set({ busted = "error", }) message = "" log.debug("test") assert.are.same("", message) log.information("test") assert.are.same("", message) log.warning("test") assert.are.same("", message) log.error("test") assert.are.same("error - test", message) end) it("check object arguments", function() require("tmux.configuration.logging").set({ busted = "debug", }) message = "" log.debug("test: ", nil) assert.are.same("debug - test: ", message) log.debug("test: ", true) assert.are.same("debug - test: true", message) log.information("test: ", true) assert.are.same("information - test: true", message) log.warning("test: ", true) assert.are.same("warning - test: true", message) log.error("test: ", true) assert.are.same("error - test: true", message) end) end)
local trainingStartMarker = createMarker(2237.94, -1720.32, 12.61, "cylinder", 2, 255, 255, 0) function trainingMarkerHit(hitElement, dimensions) if (getElementType(hitElement) ~= "player") then return false end if (not dimensions) then return false end if (not isPedOnGround(hitElement)) then exports.NGCdxmsg:createNewDxMessage("You must be on ground to open the GUI!", hitElement, 255, 25, 25) return false end if (getElementModel(hitElement) ~= 0) then exports.NGCdxmsg:createNewDxMessage("You must have the CJ skin!", hitElement, 255, 25, 25) return false end triggerClientEvent(hitElement, "AURgymtraining.open", resourceRoot) end addEventHandler("onMarkerHit", trainingStartMarker, trainingMarkerHit) function resetMuscle() setPedStat(client, 23, 0) exports.NGCdxmsg:createNewDxMessage("Your muscle was reset!", source, 25, 255, 25) exports.CSGlogging:createLogRow(client, "muscle", getPlayerName(client).." reset his muscles") end addEvent("AURgymtraining.reset", true) addEventHandler("AURgymtraining.reset", resourceRoot, resetMuscle) function trainMuscle() local stat = getPedStat(client, 23) if (stat == 1000) then exports.NGCdxmsg:createNewDxMessage("Your muscles are already fully trained!", client, 25, 255, 25) return false end fadeCamera(client, false) setElementFrozen(client, true) setTimer(function(client) fadeCamera(client, true) setElementFrozen(client, false) end, 2000, 1, client) setPedStat(client, 23, stat+100) takePlayerMoney(client, 2000) exports.CSGlogging:createLogRow(client, "muscle", getPlayerName(client).." trained his muscles (value (after training): "..tostring(stat+100)) exports.NGCdxmsg:createNewDxMessage("Your musles were increased by 10%!", client, 25, 255, 25) end addEvent("AURgymtraining.train", true) addEventHandler("AURgymtraining.train", resourceRoot, trainMuscle)
local customEventHooks = {} customEventHooks.validators = {} customEventHooks.handlers = {} function customEventHooks.makeEventStatus(validDefaultHandler, validCustomHandlers) return { validDefaultHandler = validDefaultHandler, validCustomHandlers = validCustomHandlers } end function customEventHooks.updateEventStatus(oldStatus, newStatus) if newStatus == nil then return oldStatus end local result = {} if newStatus.validDefaultHandler ~= nil then result.validDefaultHandler = newStatus.validDefaultHandler else result.validDefaultHandler = oldStatus.validDefaultHandler end if newStatus.validCustomHandlers ~= nil then result.validCustomHandlers = newStatus.validCustomHandlers else result.validCustomHandlers = oldStatus.validCustomHandlers end return result end function customEventHooks.registerValidator(event, callback) if customEventHooks.validators[event] == nil then customEventHooks.validators[event] = {} end table.insert(customEventHooks.validators[event], callback) end function customEventHooks.registerHandler(event, callback) if customEventHooks.handlers[event] == nil then customEventHooks.handlers[event] = {} end table.insert(customEventHooks.handlers[event], callback) end function customEventHooks.triggerValidators(event, args) local eventStatus = customEventHooks.makeEventStatus(true, true) if customEventHooks.validators[event] ~= nil then for _, callback in ipairs(customEventHooks.validators[event]) do eventStatus = customEventHooks.updateEventStatus(eventStatus, callback(eventStatus, unpack(args))) end end return eventStatus end function customEventHooks.triggerHandlers(event, eventStatus, args) if customEventHooks.handlers[event] ~= nil then for _, callback in ipairs(customEventHooks.handlers[event]) do eventStatus = customEventHooks.updateEventStatus(eventStatus, callback(eventStatus, unpack(args))) end end end return customEventHooks
ITEM.name = "5.45x39 Ammo" ITEM.model = "models/gmodz/ammo/545x39.mdl" ITEM.ammo = "5.45x39mm" ITEM.ammoAmount = 30 ITEM.maxRounds = 60 ITEM.description = "Ammo box that contains 5.45x39 mm caliber" ITEM.price = 13500 ITEM.rarity = { weight = 30 }
local timer = require('timer') local Deque = require('./Deque') local setTimeout = timer.setTimeout local running, yield, resume = coroutine.running, coroutine.yield, coroutine.resume local Mutex, property, method = class('Mutex', Deque) Mutex.__description = "Mutual exclusion class for coroutines." function Mutex:__init() Deque.__init(self) self._active = false end local function lock(self, isRetry) if self._active then if isRetry then return yield(self:pushLeft(running())) else return yield(self:pushRight(running())) end else self._active = true end end local function unlock(self) if self:getCount() > 0 then return resume(self:popLeft()) else self._active = false end end local function unlockAfter(self, delay) return setTimeout(delay, unlock, self) end property('active', '_active', nil, 'boolean', 'Indicates whether the mutex is in use.') method('lock', lock, '[isRetry]', "Activates the mutex if not already active, or, enqueues and yields the current coroutine.") method('unlock', unlock, nil, "Dequeues and resumes a coroutine if one exists, or, deactives the mutex.") method('unlockAfter', unlockAfter, 'delay', "Unlocks the mutex after x miliseconds.") return Mutex
--[[ File @description: This file contains several different reward functions for the task of target reaching. @version: V0.25 @author: Fangyi Zhang email:[email protected] @acknowledgement: ARC Centre of Excellence for Robotic Vision (ACRV) Queensland Univsersity of Technology (QUT) @history: V0.00 25/11/2015 developed the first version V0.10 29/11/2015 fixed bug that the resolution of the reward function is higher than that in DQN V0.20 18/12/2015 added a new reward function "reward_continuous_maximum_step_limit" V0.21 13/01/2016 added a new reward function "reward_continuous_more_assistance_termination" V0.22 13/01/2016 added a reward function for testing evaluation V0.23 30/08/2016 updated the reword function for testing to return closest distance and final distance. V0.24 31/05/2017 added reward functions for 7DoF tabletop object picking V0.25 31/05/2017 added one parameter to set extra workspace limit (workspace_limit) ]] require 'torch' -- construct a class local rwd = torch.class('reward_functions_picking') --[[ Function @description: initialize an object for reward functions @input: args: settings for a reward function object @output: nil @notes: ]] function rwd:__init(args) -- reward function variables self.max_step = args.max_step or 300 -- the maximum step limitation to complete a task self.step_interval = args.step_interval or 4 -- the assessment steps, if it is 10, it means the distance based assessment will be conducted every 10 steps self.assistance_interval = args.assistance_interval or 80 -- the assistance guidance interval self.completion_restart_threshold = args.completion_restart_threshold or 1 -- the threshold steps for completion restart self.completion_threshold = args.completion_threshold or 1 -- the threshold steps for completion self.initial_distance = 1 -- the distance between the end-effector and the destination at the beginning of each new game self.closest_distance = 100 -- the closest distance self.history_dis = {} -- history distance table self.history_gradient = {} -- history distance gradient table self.step_count = 0 self.completion_count = 0 self.completion_restart = 0 self.completion = false -- completion flag of the current trial self.default_reward = -0.0005 -- the reward value when no special reward value is activated self.target_reaching_allowance = 0.005 -- the radius for the zone when the end-effector reaches, it will be treated as reaching the target self.completion_allowance = 0.04 -- the radius for the zone when the end-effector reaches, it will be treated as having completed the target reaching task -- self.workspace_limit = args.workspace_limit or 0.4 self.workspace_limit = args.workspace_limit or 1.0 print("step interval: ", self.step_interval) print("assistance_interval: ", self.assistance_interval) print("max step: ", self.max_step) end --[[ Function @description: decide the sign of a number @input: x: the number, i.e., -2 @output: sign: 1: x>0; -1: x<0; 0:others @notes: ]] function rwd:sign(x) return x>0 and 1 or x<0 and -1 or 0 end --[[ Function @description: compute the reward of an action @input: destination: the 2D coordinate of the destination in physical models, i.e., {3.0, 3.0} end_effector: the 2D coordinate of the end effector in physical models, i.e., {4.0, 0.0} limit_reached: whether the joint limitation has been reached @output: reward_: the reward value terminal_: whether the game is terminal, true: terminal completion_: whether the game has been completed, true: completed @notes: ]] function rwd:reward_discrete(destination, end_effector, limit_reached) local reward_ = 0 local terminal_ = false local completion_ = false local distance -- if the joint limitation is reached, terminate the current round and return -1 reward directly if limit_reached then terminal_ = true reward_ = -1 else distance = math.sqrt(math.pow((destination[1] - end_effector[1]), 2) + math.pow((destination[2] - end_effector[2]), 2)) -- calculate the reward value according to current distance if distance > self.target_reaching_allowance then reward_ = self.default_reward self.completion_restart = 0 else reward_ = 0 self.completion_restart = self.completion_restart + 1 if self.completion_restart > self.completion_restart_threshold then self.completion_restart = 0 reward_ = 1 terminal_ = true -- completion restart end end -- determine completion if distance <= self.completion_allowance then self.completion_count = self.completion_count + 1 if self.completion_count > self.completion_threshold then self.completion_count = 0 self.completion = true -- completion -- terminal_ = true -- completion restart end else self.completion_count = 0 end end -- Reset some variables when terminating if terminal_ then completion_ = self.completion self.completion = false self.completion_restart = 0 self.completion_count = 0 end -- print("reward:", reward_) return reward_, terminal_, completion_ end --[[ Function @description: compute the reward of an action @input: destination: the 2D coordinate of the destination in physical models, i.e., {3.0, 3.0} end_effector: the 2D coordinate of the end effector in physical models, i.e., {4.0, 0.0} limit_reached: whether the joint limitation has been reached @output: reward_: the reward value terminal_: whether the game is terminal, true: terminal completion_: whether the game has been completed, true: completed @notes: ]] function rwd:reward_discrete_more_termination(destination, end_effector, limit_reached) local reward_ = 0 local terminal_ = false local completion_ = false local distance -- if the joint limitation is reached, terminate the current round and return -1 reward directly if limit_reached then terminal_ = true reward_ = -1 else distance = math.sqrt(math.pow((destination[1] - end_effector[1]), 2) + math.pow((destination[2] - end_effector[2]), 2)) local m = #self.history_dis + 1 self.history_dis[m] = distance -- calculate the reward value according to current distance if distance > self.target_reaching_allowance then reward_ = self.default_reward self.completion_restart = 0 -- assitance guidance if m > self.assistance_interval then -- set the assistant termination condition to >= 0.4, ensuring there are some distinguishable features in images if self.history_dis[m] - self.history_dis[m-self.assistance_interval] >= 0 then terminal_ = true reward_ = -1 end end -- self.step_count = self.step_count + 1 -- if self.step_count >= self.assistance_interval then -- self.step_count = 0 -- if self.pre_distance then -- if (distance - self.pre_distance) >= 0 then -- terminal_ = true -- reward_ = -1 -- else -- self.pre_distance = distance -- end -- else -- self.pre_distance = distance -- end -- end else reward_ = 0 self.completion_restart = self.completion_restart + 1 if self.completion_restart > self.completion_restart_threshold then self.completion_restart = 0 reward_ = 1 terminal_ = true -- completion restart end -- when get into the reaching zone, all the assistance guidance will be reset -- self.step_count = 0 -- self.pre_distance = nil end -- determine completion if distance <= self.completion_allowance then self.completion_count = self.completion_count + 1 if self.completion_count > self.completion_threshold then self.completion_count = 0 self.completion = true -- completion -- terminal_ = true -- completion restart end else self.completion_count = 0 end end -- Reset some variables when terminating if terminal_ then completion_ = self.completion self.completion = false self.completion_restart = 0 self.completion_count = 0 -- self.step_count = 0 -- self.pre_distance = nil self.history_dis = {} end -- print("reward:", reward_) return reward_, terminal_, completion_ end --[[ Function @description: compute the reward of an action @input: destination: the 2D coordinate of the destination in physical models, i.e., {3.0, 3.0} end_effector: the 2D coordinate of the end effector in physical models, i.e., {4.0, 0.0} limit_reached: whether the joint limitation has been reached @output: reward_: the reward value terminal_: whether the game is terminal, true: terminal completion_: whether the game has been completed, true: completed @notes: ]] function rwd:reward_continuous(destination, end_effector, limit_reached) local reward_ = 0 local terminal_ = false local completion_ = false -- if the joint limitation is reached, terminate the current round and return -1 reward directly if limit_reached then terminal_ = true reward_ = -1 else local distance = math.sqrt(math.pow((destination[1] - end_effector[1]), 2) + math.pow((destination[2] - end_effector[2]), 2)) -- calculate the reward value according to current distance if distance > self.target_reaching_allowance then -- reduce the resolution using the floor function, due to the resolution limitation of the input images in the DQN -- reward_ = (self.target_reaching_allowance / math.floor(distance+1-self.target_reaching_allowance) - 1) / 1000 reward_ = (self.target_reaching_allowance / distance - 1) / 1000 self.completion_restart = 0 else reward_ = 0 self.completion_restart = self.completion_restart + 1 if self.completion_restart > self.completion_restart_threshold then self.completion_restart = 0 reward_ = 1 terminal_ = true -- completion restart end end -- determine completion if distance <= self.completion_allowance then self.completion_count = self.completion_count + 1 if self.completion_count > self.completion_threshold then self.completion_count = 0 self.completion = true -- completion -- terminal_ = true -- completion restart end else self.completion_count = 0 end end -- Reset some variables when terminating if terminal_ then completion_ = self.completion self.completion = false self.completion_restart = 0 self.completion_count = 0 end -- print("reward:", reward_) return reward_, terminal_, completion_ end --[[ Function @description: compute the reward of an action @input: destination: the 2D coordinate of the destination in physical models, i.e., {3.0, 3.0} end_effector: the 2D coordinate of the end effector in physical models, i.e., {4.0, 0.0} limit_reached: whether the joint limitation has been reached @output: reward_: the reward value terminal_: whether the game is terminal, true: terminal completion_: whether the game has been completed, true: completed @notes: ]] function rwd:reward_continuous_more_termination(destination, end_effector, limit_reached) local reward_ = 0 local terminal_ = false local completion_ = false local distance -- if the joint limitation is reached, terminate the current round and return -1 reward directly if limit_reached then terminal_ = true reward_ = -1 else distance = math.sqrt(math.pow((destination[1] - end_effector[1]), 2) + math.pow((destination[2] - end_effector[2]), 2)) local m = #self.history_dis + 1 self.history_dis[m] = distance -- calculate the reward value according to current distance if distance > self.target_reaching_allowance then -- reduce the resolution using the floor function, due to the resolution limitation of the input images in the DQN -- reward_ = (self.target_reaching_allowance / math.floor(distance+1-self.target_reaching_allowance) - 1) / 1000 reward_ = (self.target_reaching_allowance / distance - 1) / 1000 self.completion_restart = 0 -- assitance guidance if m > self.assistance_interval then -- set the assistant termination condition to >= 0.4, ensuring there are some distinguishable features in images if self.history_dis[m] - self.history_dis[m-self.assistance_interval] >= 0 then terminal_ = true reward_ = -1 end end else reward_ = 0 self.completion_restart = self.completion_restart + 1 if self.completion_restart > self.completion_restart_threshold then self.completion_restart = 0 reward_ = 1 terminal_ = true -- completion restart end end -- determine completion if distance <= self.completion_allowance then self.completion_count = self.completion_count + 1 if self.completion_count > self.completion_threshold then self.completion_count = 0 self.completion = true -- completion -- terminal_ = true -- completion restart end else self.completion_count = 0 end end -- Reset some variables when terminating if terminal_ then completion_ = self.completion self.completion = false self.completion_restart = 0 self.completion_count = 0 self.history_dis = {} end -- print("reward:", reward_) return reward_, terminal_, completion_ end --[[ Function @description: compute the reward of an action @input: destination: the 2D coordinate of the destination in physical models, i.e., {3.0, 3.0} end_effector: the 2D coordinate of the end effector in physical models, i.e., {4.0, 0.0} limit_reached: whether the joint limitation has been reached @output: reward_: the reward value terminal_: whether the game is terminal, true: terminal completion_: whether the game has been completed, true: completed @notes: ]] function rwd:reward1(distance, collision, reached) local reward_ = 0 local completion_ = false local terminal_ = false -- if the joint limitation is reached, terminate the current round and return -1 reward directly if collision or distance > self.workspace_limit then terminal_ = true reward_ = -1 else local m = #self.history_dis + 1 self.history_dis[m] = distance -- calculate the reward value according to current distance if not reached then -- reduce the resolution using the floor function, due to the resolution limitation of the input images in the DQN reward_ = (self.target_reaching_allowance / distance - 1) / 1000 if reward_ > 0 then reward_ = 0 end self.completion_restart = 0 -- assitance guidance if m > self.assistance_interval then -- set the assistant termination condition to >= 0.4, ensuring there are some distinguishable features in images if self.history_dis[m] - self.history_dis[m-self.assistance_interval] >= 0 then terminal_ = true reward_ = 0.5 -- set reward_ to 0.5 as a sign to recognize the assistance termination end end else reward_ = 0 self.completion_restart = self.completion_restart + 1 if self.completion_restart > self.completion_restart_threshold then self.completion_restart = 0 reward_ = 1 self.completion = true terminal_ = true -- completion restart end end -- determine completion if distance <= self.completion_allowance then self.completion_count = self.completion_count + 1 if self.completion_count > self.completion_threshold then self.completion_count = 0 self.completion = true -- completion -- terminal_ = true -- completion restart end else self.completion_count = 0 end end -- Reset some variables when terminating if terminal_ then completion_ = self.completion self.completion = false self.completion_restart = 0 self.completion_count = 0 self.history_dis = {} end -- print("reward:", reward_) return reward_, terminal_, completion_ end --[[ Function @description: compute the reward of an action @input: destination: the 2D coordinate of the destination in physical models, i.e., {3.0, 3.0} end_effector: the 2D coordinate of the end effector in physical models, i.e., {4.0, 0.0} limit_reached: whether the joint limitation has been reached @output: reward_: the reward value terminal_: whether the game is terminal, true: terminal completion_: whether the game has been completed, true: completed @notes: ]] function rwd:reward1_testing(distance, collision, reached) local reward_ = 0 local terminal_ = false local completion_ = false local closest_distance = 100 -- if the joint limitation is reached, terminate the current round and return -1 reward directly if collision or distance > self.workspace_limit then terminal_ = true reward_ = -1 else if distance < self.closest_distance then self.closest_distance = distance end local m = #self.history_dis + 1 self.history_dis[m] = distance -- calculate the reward value according to current distance if not reached then -- reduce the resolution using the floor function, due to the resolution limitation of the input images in the DQN -- reward_ = (self.target_reaching_allowance / math.floor(distance+1-self.target_reaching_allowance) - 1) / 1000 reward_ = (self.target_reaching_allowance / distance - 1) / 1000 if reward_ > 0 then reward_ = 0 end self.completion_restart = 0 -- maximum step limit if m > self.max_step then terminal_ = true -- reward_ = self.target_reaching_allowance / distance - 1 end else reward_ = 0 self.completion_restart = self.completion_restart + 1 if self.completion_restart > self.completion_restart_threshold then self.completion_restart = 0 reward_ = 1 self.completion = true terminal_ = true -- completion restart end end -- determine completion if distance <= self.completion_allowance then self.completion_count = self.completion_count + 1 if self.completion_count > self.completion_threshold then self.completion_count = 0 self.completion = true -- completion -- terminal_ = true -- completion restart end else self.completion_count = 0 end end -- Reset some variables when terminating if terminal_ then completion_ = self.completion self.completion = false self.completion_restart = 0 self.completion_count = 0 self.history_dis = {} closest_distance = self.closest_distance self.closest_distance = 100 end -- print("reward:", reward_) return reward_, terminal_, completion_, closest_distance, distance end --[[ Function @description: compute the reward of an action @input: destination: the 2D coordinate of the destination in physical models, i.e., {3.0, 3.0} end_effector: the 2D coordinate of the end effector in physical models, i.e., {4.0, 0.0} limit_reached: whether the joint limitation has been reached @output: reward_: the reward value terminal_: whether the game is terminal, true: terminal completion_: whether the game has been completed, true: completed @notes: ]] function rwd:reward_continuous_maximum_step_limit(destination, end_effector, limit_reached) local reward_ = 0 local terminal_ = false local completion_ = false local distance -- if the joint limitation is reached, terminate the current round and return -1 reward directly if limit_reached then terminal_ = true reward_ = -1 else distance = math.sqrt(math.pow((destination[1] - end_effector[1]), 2) + math.pow((destination[2] - end_effector[2]), 2)) local m = #self.history_dis + 1 self.history_dis[m] = distance -- calculate the reward value according to current distance if distance > self.target_reaching_allowance then -- reduce the resolution using the floor function, due to the resolution limitation of the input images in the DQN -- reward_ = (self.target_reaching_allowance / math.floor(distance+1-self.target_reaching_allowance) - 1) / 1000 reward_ = (self.target_reaching_allowance / distance - 1) / 1000 self.completion_restart = 0 -- maximum step limit if m > self.max_step then terminal_ = true reward_ = self.target_reaching_allowance / distance - 1 end else reward_ = 0 self.completion_restart = self.completion_restart + 1 if self.completion_restart > self.completion_restart_threshold then self.completion_restart = 0 reward_ = 1 terminal_ = true -- completion restart end end -- determine completion if distance <= self.completion_allowance then self.completion_count = self.completion_count + 1 if self.completion_count > self.completion_threshold then self.completion_count = 0 self.completion = true -- completion -- terminal_ = true -- completion restart end else self.completion_count = 0 end end -- Reset some variables when terminating if terminal_ then completion_ = self.completion self.completion = false self.completion_restart = 0 self.completion_count = 0 self.history_dis = {} end -- print("reward:", reward_) return reward_, terminal_, completion_ end -- ========================================================================= -- previous reward functions --[[ Function @description: compute the reward of an action @input: destination: the 2D coordinate of the destination in physical models, i.e., {3.0, 3.0} end_effector: the 2D coordinate of the end effector in physical models, i.e., {4.0, 0.0} new: whether the game is a new game @output: y: the reward value, 1: get closer; -1: get further; 0: distance unchanged terminal_: whether the game is terminal, true: terminal. @notes: ]] function rwd:reward(destination, end_effector, new) if new == true then -- when starting a new game, clear all history data self.history_dis = {} self.history_gradient = {} end local distance = math.sqrt(math.pow((destination[1] - end_effector[1]), 2) + math.pow((destination[2] - end_effector[2]), 2)) --print("distance:",distance) self.history_dis[#self.history_dis + 1] = distance local m = #self.history_dis --print("m:",m) if m > 1 then local gradient = self.history_dis[m] - self.history_dis[m-1] self.history_gradient[#self.history_gradient + 1] = gradient end local n = #self.history_gradient local y = 0 local terminal_ = false if n > 0 then if self.history_gradient[n] > 0 then y = -1 elseif self.history_gradient[n] < 0 then y = 1 end if n > 2 then local acc = 0 for i=n-2,n do acc = acc + self:sign(self.history_gradient[i]) --print("acc:",acc) end if acc > 1 then terminal_ = true end end end return y, terminal_ end
require("ramchaik.telescope") require("ramchaik.lsp") require("ramchaik.lualine") require("ramchaik.harpoon") require("ramchaik.nvim-treesitter") require("ramchaik.comment") -- require("ramchaik.debugger") -- require("ramchaik.git-worktree") require("ramchaik.plugins") P = function(v) print(vim.inspect(v)) return v end if pcall(require, 'plenary') then RELOAD = require('plenary.reload').reload_module R = function(name) RELOAD(name) return require(name) end end -- Fix for eslint lsp; until next release; -- eslint: https://github.com/microsoft/vscode-eslint/issues/1393 -- neovim: https://github.com/neovim/neovim/issues/16673#issuecomment-997222902 vim.diagnostic.set = (function(orig) return function(namespace, bufnr, diagnostics, opts) for _, v in ipairs(diagnostics) do v.col = v.col or 0 end return orig(namespace, bufnr, diagnostics, opts) end end)(vim.diagnostic.set)
return { corraven = { acceleration = 0.108, brakerate = 0.56, buildcostenergy = 82114, buildcostmetal = 4856, builder = false, buildpic = "corraven.dds", buildtime = 125000, canattack = true, canguard = true, canmove = true, canpatrol = true, canstop = 1, category = "ALL HUGE MOBILE SURFACE UNDERWATER", collisionvolumeoffsets = "0 0 2", collisionvolumescales = "60 53 30", collisionvolumetype = "Box", corpse = "dead", defaultmissiontype = "Standby", description = "Heavy Rocket Kbot", explodeas = "CRAWL_BLASTSML", firestandorders = 1, footprintx = 4, footprintz = 4, idleautoheal = 5, idletime = 1800, losemitheight = 46, maneuverleashlength = 640, mass = 4856, maxdamage = 5750, maxslope = 20, maxvelocity = 1.4, maxwaterdepth = 12, mobilestandorders = 1, movementclass = "HKBOT4", name = "Catapult", noautofire = false, objectname = "CORRAVEN", radaremitheight = 46, seismicsignature = 0, selfdestructas = "CRAWL_BLAST", sightdistance = 700, standingfireorder = 2, standingmoveorder = 1, steeringmode = 2, turninplaceanglelimit = 140, turninplacespeedlimit = 0.924, turnrate = 400, unitname = "corraven", upright = true, customparams = { buildpic = "corraven.dds", faction = "CORE", }, featuredefs = { dead = { blocking = true, collisionvolumeoffsets = "3.19359588623 0.0 1.04564666748", collisionvolumescales = "66.3871917725 26.0 41.4744720459", collisionvolumetype = "Box", damage = 4296, description = "Catapult Wreckage", energy = 0, featuredead = "heap", footprintx = 3, footprintz = 3, metal = 3637, object = "CORRAVEN_DEAD", reclaimable = true, customparams = { fromunit = 1, }, }, heap = { blocking = false, damage = 5370, description = "Catapult Debris", energy = 0, footprintx = 3, footprintz = 3, metal = 1940, object = "3X3C", reclaimable = true, customparams = { fromunit = 1, }, }, }, sfxtypes = { pieceexplosiongenerators = { [1] = "piecetrail0", [2] = "piecetrail1", [3] = "piecetrail2", [4] = "piecetrail3", [5] = "piecetrail4", [6] = "piecetrail6", }, }, sounds = { canceldestruct = "cancel2", underattack = "warning1", cant = { [1] = "cantdo4", }, count = { [1] = "count6", [2] = "count5", [3] = "count4", [4] = "count3", [5] = "count2", [6] = "count1", }, ok = { [1] = "mavbok1", }, select = { [1] = "mavbsel1", }, }, weapondefs = { exp_heavyrocket = { accuracy = 300, areaofeffect = 220, avoidfeature = false, burst = 40, burstrate = 0.10, cegtag = "Core_Def_AA_Rocket", craterareaofeffect = 330, craterboost = 0, cratermult = 0, edgeeffectiveness = 0.5, explosiongenerator = "custom:MEDMISSILE_EXPLOSION", firestarter = 70, flighttime = 3, impulseboost = 0.123, impulsefactor = 0.123, metalpershot = 0, model = "weapon_starburstm", movingaccuracy = 600, name = "RavenCatapultRockets", noselfdamage = true, proximitypriority = -1, range = 1350, reloadtime = 15, smoketrail = true, soundhitdry = "rockhit", soundhitwet = "splslrg", soundhitwetvolume = 0.6, soundstart = "rapidrocket3", sprayangle = 1200, startvelocity = 200, targetable = 16, texture1 = "null", texture2 = "coresmoketrail", texture3 = "null", texture4 = "null", trajectoryheight = 1, turnrate = 0, turret = true, weaponacceleration = 120, weapontimer = 4, weapontype = "MissileLauncher", weaponvelocity = 510, wobble = 1800, damage = { commanders = 180, default = 360, subs = 5, }, }, }, weapons = { [1] = { def = "EXP_HEAVYROCKET", onlytargetcategory = "SURFACE", }, }, }, }
--- Druid checkbox component -- @module druid.checkbox --- Component events -- @table Events -- @tfield druid_event on_change_state On change state callback --- Component fields -- @table Fields -- @tfield node node Visual node -- @tfield[opt=node] node click_node Button trigger node -- @tfield druid.button button Button component from click_node local Event = require("druid.event") local component = require("druid.component") local M = component.create("checkbox") local function on_click(self) M.set_state(self, not self.state) end --- Component style params. -- You can override this component styles params in druid styles table -- or create your own style -- @table Style -- @tfield function on_change_state (self, node, state) function M.on_style_change(self, style) self.style = {} self.style.on_change_state = style.on_change_state or function(_, node, state) gui.set_enabled(node, state) end end --- Component init function -- @function checkbox:init -- @tparam node node Gui node -- @tparam function callback Checkbox callback -- @tparam[opt=node] node click node Trigger node, by default equals to node function M.init(self, node, callback, click_node) self.druid = self:get_druid() self.node = self:get_node(node) self.click_node = self:get_node(click_node) self.button = self.druid:new_button(self.click_node or self.node, on_click) M.set_state(self, false, true) self.on_change_state = Event(callback) end --- Set checkbox state -- @function checkbox:set_state -- @tparam bool state Checkbox state -- @tparam bool is_silent Don't trigger on_change_state if true function M.set_state(self, state, is_silent) if self.state == state then return end self.state = state self.style.on_change_state(self, self.node, state) if not is_silent then self.on_change_state:trigger(self:get_context(), state) end end --- Return checkbox state -- @function checkbox:get_state -- @treturn bool Checkbox state function M.get_state(self) return self.state end return M
-- https://github.com/sunjon/Shade.nvim require'shade'.setup({ overlay_opacity = 50, opacity_step = 1 })
--------------------- SAMPLE MINIMAL IMPLEMENTATION -------------------- --- TODO: documents args function init(virtual) if not virtual then storageApi.init(args) end end function die() storageApi.die() end --------------------- HOOKS -------------------- --- Called when an item is about to be taken from storage -- @param index (int) The requested item index -- @param count (int) The amount of item requested -- @return (bool) If this returns true, the item is not taken and the returned item is null function beforeItemTaken(index, count) end --- Called when an item has been taken from storage -- @param itemname, count, parameters - item data that was taken function afterItemTaken(itemname, count, properties) end --- Called when an item is about to be stored in storage -- @param itemname, count, parameters - item data requested to be stored -- @return (bool) If this returns true, the item is not stored and the parent method returns false function beforeItemStored(itemname, count, properties) end --- Called when an item has been stored in storage -- @param index (int) The index assigned to the item -- @param merged (bool) Whenever the item stack was merged into another, or not function afterItemStored(index, merged) end --- Called when all items have been taken from storage function afterAllItemsTaken() end
XYZ_ORGS = {} XYZ_ORGS.Config = {} XYZ_ORGS.Core = {} XYZ_ORGS.Core.Members = {} XYZ_ORGS.Core.Orgs = {} XYZ_ORGS.Core.Invites = {} XYZ_ORGS.Database = {} print("Loading Organisations") local path = "xyz_organisations/" if SERVER then local files, folders = file.Find(path .. "*", "LUA") for _, folder in SortedPairs(folders, true) do print("Loading folder:", folder) for b, File in SortedPairs(file.Find(path .. folder .. "/sh_*.lua", "LUA"), true) do print("Loading file:", File) AddCSLuaFile(path .. folder .. "/" .. File) include(path .. folder .. "/" .. File) end for b, File in SortedPairs(file.Find(path .. folder .. "/sv_*.lua", "LUA"), true) do print("Loading file:", File) include(path .. folder .. "/" .. File) end for b, File in SortedPairs(file.Find(path .. folder .. "/cl_*.lua", "LUA"), true) do print("Loading file:", File) AddCSLuaFile(path .. folder .. "/" .. File) end end end if CLIENT then local files, folders = file.Find(path .. "*", "LUA") for _, folder in SortedPairs(folders, true) do print("Loading folder:", folder) for b, File in SortedPairs(file.Find(path .. folder .. "/sh_*.lua", "LUA"), true) do print("Loading file:", File) include(path .. folder .. "/" .. File) end for b, File in SortedPairs(file.Find(path .. folder .. "/cl_*.lua", "LUA"), true) do print("Loading file:", File) include(path .. folder .. "/" .. File) end end end print("Loaded Organisations")
include("names") include("set_names") imenilac1 = math.random(8) + 2; imenilac2 = math.random(imenilac1 - 2) + 1; factor = (math.random(10)); rezultat = factor*imenilac1*imenilac2 broj1 = factor*imenilac2 broj2 = factor*imenilac1 brojp= broj1 + broj2; brojo = rezultat-brojp vrednost = brojo / rezultat simp_brojo = brojo / lib.math.gcd(brojo, rezultat) simp_rezultat = rezultat / lib.math.gcd(brojo, rezultat) solution = "numerator="..tostring(simp_brojo)..";denominator="..tostring(simp_rezultat)..";"
if deadlock then deadlock.add_tier({ transport_belt = "BetterBelts_ultra-transport-belt", colour = {r=0,g=211,b=37}, technology = "logistics-3", order = "d", loader = "BetterBelts_ultra-deadlock-loader", loader_ingredients = { {"express-transport-belt-loader",1}, {"iron-gear-wheel",40}, }, beltbox = "BetterBelts_ultra-deadlock-beltbox", beltbox_ingredients = { {"express-transport-belt-beltbox",1}, {"steel-plate",40}, {"iron-gear-wheel",40}, {"processing-unit",5}, }, beltbox_technology = "deadlock-stacking-3", }) if data.raw.furnace["BetterBelts_ultra-transport-belt-beltbox"] then data.raw.furnace["express-transport-belt-beltbox"].next_upgrade = "BetterBelts_ultra-transport-belt-beltbox" end end
--[[----------------------------------------------------------------------------- * Infected Wars, an open source Garry's Mod game-mode. * * Infected Wars is the work of multiple authors, * a full list can be found in CONTRIBUTORS.md. * For more information, visit https://github.com/JarnoVgr/InfectedWars * * Infected Wars is free software: you can redistribute it and/or modify * it under the terms of the MIT License. * * A full copy of the MIT License can be found in LICENSE.txt. -----------------------------------------------------------------------------]] util.PrecacheSound("physics/flesh/flesh_bloody_impact_hard1.wav") util.PrecacheSound("physics/flesh/flesh_squishy_impact_hard1.wav") util.PrecacheSound("physics/flesh/flesh_squishy_impact_hard2.wav") util.PrecacheSound("physics/flesh/flesh_squishy_impact_hard3.wav") util.PrecacheSound("physics/flesh/flesh_squishy_impact_hard4.wav") local function CollideCallback(particle, hitpos, hitnormal) if not particle.HitAlready then particle.HitAlready = true local pos = hitpos + hitnormal if math.random(1, 3) == 3 then WorldSound("physics/flesh/flesh_squishy_impact_hard"..math.random(1,4)..".wav", hitpos, 50, math.random(95, 105)) end util.Decal("Blood", pos, hitpos - hitnormal) particle:SetDieTime(0) end end function EFFECT:Init(data) local Pos = data:GetOrigin() + Vector(0,0,10) local emitter = ParticleEmitter(Pos) for i=1, data:GetMagnitude() do local particle = emitter:Add("decals/blood_spray"..math.random(1,8), Pos + VectorRand() * 8) particle:SetVelocity(VectorRand():Normalize() * math.random(90, 175) + Vector(0,0,80)) particle:SetDieTime(math.Rand(3, 6)) particle:SetStartAlpha(230) particle:SetEndAlpha(230) particle:SetStartSize(math.Rand(10, 14)) particle:SetEndSize(10) particle:SetRoll(math.Rand(0, 360)) particle:SetRollDelta(math.Rand(-20, 20)) particle:SetAirResistance(5) particle:SetBounce(0) particle:SetGravity(Vector(0, 0, -600)) particle:SetCollide(true) particle:SetCollideCallback(CollideCallback) particle:SetLighting(true) particle:SetColor(255, 0, 0) end emitter:Finish() end function EFFECT:Think() return false end function EFFECT:Render() end //old // All Garry's code down here, just a few tweaks from me --[[ local BloodSprite = Material( "effects/bloodstream" ) /*--------------------------------------------------------- Initializes the effect. The data is a table of data which was passed from the server. ---------------------------------------------------------*/ function EFFECT:Init( data ) // Table to hold particles self.Particles = {} self.PlaybackSpeed = math.Rand( 2, 5 ) self.Width = math.Rand( 2, 16 ) self.ParCount = 8 local Dir = VectorRand() * 1/4 + data:GetNormal() * 1/2 + Vector( 0, 0, math.random(0,4)) * 1/4 local Speed = math.Rand( 300, 1500 ) local SquirtDelay = math.Rand( 3, 5 ) Dir.z = math.max( Dir.z, Dir.z * -1 ) if (Dir.z > 0.5) then Dir.z = Dir.z - 0.3 end for i=1, math.random( 4, 8 ) do Dir = Dir * 0.95 + VectorRand() * 0.02 local p = {} p.Pos = data:GetOrigin() p.Vel = Dir * (Speed * (i /16)) p.Delay = (16 - i) * SquirtDelay p.Rest = false table.insert( self.Particles, p ) end self.NextThink = CurTime() + math.Rand( 0, 1 ) end local function VectorMin( v1, v2 ) if ( v1 == nil ) then return v2 end if ( v2 == nil ) then return v1 end local vr = Vector( v2.x, v2.y, v2.z ) if ( v1.x < v2.x ) then vr.x = v1.x end if ( v1.y < v2.y ) then vr.y = v1.y end if ( v1.z < v2.z ) then vr.z = v1.z end return vr end local function VectorMax( v1, v2 ) if ( v1 == nil ) then return v2 end if ( v2 == nil ) then return v1 end local vr = Vector( v2.x, v2.y, v2.z ) if ( v1.x > v2.x ) then vr.x = v1.x end if ( v1.y > v2.y ) then vr.y = v1.y end if ( v1.z > v2.z ) then vr.z = v1.z end return vr end /*--------------------------------------------------------- THINK ---------------------------------------------------------*/ function EFFECT:Think( ) if not EFFECT_UBERGORE then return false end //if ( self.NextThink > CurTime() ) then return true end local FrameSpeed = self.PlaybackSpeed * FrameTime() local bMoved = false local min = self.Entity:GetPos() local max = min self.Width = self.Width - 0.7 * FrameSpeed if ( self.Width < 0 ) then return false end for k, p in pairs( self.Particles ) do if ( p.Rest ) then // Waiting to be spawned. Some particles have an initial delay // to give a stream effect.. elseif ( p.Delay > 0 ) then p.Delay = p.Delay - 100 * FrameSpeed // Normal movement code. Handling particles in Lua isn't great for // performance but since this is clientside and only happening sometimes // for short periods - it should be fine. else // Gravity p.Vel:Sub( Vector( 0, 0, 60 * FrameSpeed ) ) // Air resistance p.Vel.x = math.Approach( p.Vel.x, 0, 2 * FrameSpeed ) p.Vel.y = math.Approach( p.Vel.y, 0, 2 * FrameSpeed ) local trace = {} trace.start = p.Pos trace.endpos = p.Pos + p.Vel * FrameSpeed trace.mask = MASK_NPCWORLDSTATIC local tr = util.TraceLine( trace ) if (tr.Hit) then tr.HitPos:Add( tr.HitNormal * 2 ) local effectdata = EffectData() effectdata:SetOrigin( tr.HitPos ) effectdata:SetNormal( tr.HitNormal ) util.Effect( "bloodsplash", effectdata ) // If we hit the ceiling just stunt the vertical velocity // else enter a rested state if ( tr.HitNormal.z < -0.75 ) then p.Vel.z = 0 else p.Rest = true end end // Add velocity to position p.Pos = tr.HitPos bMoved = true end end self.ParCount = table.Count( self.Particles ) // I really need to make a better/faster way to do this if (bMoved) then for k, p in pairs( self.Particles ) do min = VectorMin( min, p.Pos ) max = VectorMax( max, p.Pos ) end local Pos = min + ((max - min) * 0.5) self.Entity:SetPos( Pos ) self.Entity:SetCollisionBounds( Pos - min, Pos - max ) end // Returning false kills the effect return (self.ParCount > 0) end /*--------------------------------------------------------- Draw the effect ---------------------------------------------------------*/ function EFFECT:Render() render.SetMaterial( BloodSprite ) local LastPos = nil local pCount = 0 // I don't know what kind of performance hit this gives us.. local LightColor = render.GetLightColor( self.Entity:GetPos() ) * 255 LightColor.r = math.Clamp( LightColor.r, 70, 255 ) local color = Color( LightColor.r*0.5, 0, 0, 255 ) for k, p in pairs( self.Particles ) do local Sin = math.sin( (pCount / (self.ParCount-2)) * math.pi ) if ( LastPos ) then render.DrawBeam( LastPos, p.Pos, self.Width * Sin, 1, 0, color ) end pCount = pCount + 1 LastPos = p.Pos end //render.DrawSprite( self.Entity:GetPos(), 32, 32, color_white ) end ]]
-- Global variables ---------------------------------------------------------------------------------------------------- local bot = GetBot(); local mutils = require(GetScriptDirectory() .. "/MyUtility") local itemsData = require(GetScriptDirectory() .. "/ItemData" ) local itemBuild = require(GetScriptDirectory() .. "/item_purchase_" .. string.gsub(GetBot():GetUnitName(), "npc_dota_hero_", "")) local build = require(GetScriptDirectory() .. "/builds/item_build_" .. string.gsub(GetBot():GetUnitName(), "npc_dota_hero_", "")) local inspect = require(GetScriptDirectory() .. "/inspect") local getAttackRangeBool = true local creepBlocking = true local wardPlaced = false local nearestCreep local nearbyCreeps local enemyHero local itemsToBuy = itemBuild["tableItemsToBuy"] local BotAbilityPriority = build["skills"] local abilities = mutils.InitiateAbilities(bot, {0,1,2,5,3}); local abilityQ = bot:GetAbilityByName( "nevermore_shadowraze1" ); local abilityW = bot:GetAbilityByName( "nevermore_shadowraze2" ); local abilityE = bot:GetAbilityByName( "nevermore_shadowraze3" ); local castQDesire = 0; local castWDesire = 0; local castEDesire = 0; local castRDesire = 0; local botBattleMode = "neutral" local meeleCreepAttackTime local bonusIAS = 0 ---------------------------------------------------------------------------------------------------- -- Hard coded values ---------------------------------------------------------------------------------------------------- local attackRange = 500 local nCastRangeQ = 200 local nCastRangeW = 450 local nCastRangeE = 700 local razeRadius = 250 local BOT_DESIRE_NONE = 0 local BOT_DESIRE_VERY_LOW = 0.1 local BOT_DESIRE_LOW = 0.25 local BOT_DESIRE_MEDIUM = 0.5 local BOT_DESIRE_HIGH = 0.75 local BOT_DESIRE_VERY_HIGH = 0.9 local BOT_DESIRE_ABSOLUTE = 1.0 local BOT_ANIMATION_MOVING = 1502 local BOT_ANIMATION_IDLE = 1500 local BOT_ANIMATION_LASTHIT = 1504 local BOT_ANIMATION_SPELLCAST = 1503 local T1_TOWER_DPS = 110 local T1_TOWER_POSITION = Vector(473.224609, 389.945801) local MEELE_CREEP_ATTACKS_PER_SECOND = 1.00 local RANGED_CREEP_ATTACKS_PER_SECOND = 1.00 local SIEGE_CREEP_ATTACKS_PER_SECOND = 3.00 local T1_TOWER_ATTACKS_PER_SECOND = 0.82 local BOT_JUST_OUTSIDE_TOWER_RANGE = 0.638401 local BOT_NEAR_TOWER_POS_1 = Vector(313.466949, 306.219910) local BOT_NEAR_TOWER_POS_2 = Vector (672.677307, -154.150085) local BOT_NEAR_TOWER_POS_FLAG = 1 local SF_BASE_DAMAGE_VARAINCE = 3 local RANGE_CREEP_ATTACK_PROJECTILE_SPEED = 900 local TOWER_ATTACK_PROJECTILE_SPEED = 750 local SIEGE_CREEP_ATTACK_PROJECTILE_SPEED = 1100 ---------------------------------------------------------------------------------------------------- -- Bot states ---------------------------------------------------------------------------------------------------- local botState = mutils.enum({ "STATE_IDLE", "STATE_HEALING", "STATE_TELEPORTING", "STATE_MOVING" }) ---------------------------------------------------------------------------------------------------- -- All chat at game start ---------------------------------------------------------------------------------------------------- bot:ActionImmediate_Chat("Sharingan 1v1 Mid SF Bot",true) bot:ActionImmediate_Chat("This bot is still a work in progress, bugs and feedback are welcome",true) bot:ActionImmediate_Chat("Rules: No runes, No Sentry ward, No Rain Drops or Soul Ring and no Jungling or wave cutting",true) bot:ActionImmediate_Chat("First to two kills or destroying tower wins. Good luck and have fun!",true) ---------------------------------------------------------------------------------------------------- -- Function to control courier ---------------------------------------------------------------------------------------------------- function CourierUsageThink() if(GetNumCouriers() == 0) then return end local courier = GetCourier(5) if(bot:GetStashValue() ~= 0) then bot:ActionImmediate_Courier( courier, COURIER_ACTION_TAKE_AND_TRANSFER_ITEMS ) end if(GetCourierState(courier) == COURIER_STATE_IDLE ) then bot:ActionImmediate_Courier( courier, COURIER_ACTION_RETURN ) end end ---------------------------------------------------------------------------------------------------- -- Function to level up abilities ---------------------------------------------------------------------------------------------------- function AbilityLevelUpThink() local ability_name = BotAbilityPriority[1]; local ability = GetBot():GetAbilityByName(ability_name); if(ability ~= nil and ability:GetLevel() > 0) then if #BotAbilityPriority > (25 - bot:GetLevel()) then for i=1, (#BotAbilityPriority - (25 - bot:GetLevel())) do table.remove(BotAbilityPriority, 1) end end end if GetGameState() ~= GAME_STATE_GAME_IN_PROGRESS and GetGameState() ~= GAME_STATE_PRE_GAME then return end -- Do I have a skill point? if (bot:GetAbilityPoints() > 0) then local ability_name = BotAbilityPriority[1]; -- Can I slot a skill with this skill point? if(ability_name ~="-1") then local ability = GetBot():GetAbilityByName(ability_name); -- Check if its a legit upgrade if( ability:CanAbilityBeUpgraded() and ability:GetLevel() < ability:GetMaxLevel()) then local currentLevel = ability:GetLevel(); bot:ActionImmediate_LevelAbility(BotAbilityPriority[1]); if ability:GetLevel() > currentLevel then table.remove(BotAbilityPriority,1) else end end else table.remove(BotAbilityPriority,1) end end end ---------------------------------------------------------------------------------------------------- -- Calculate if bot wants to use short razeRadius ---------------------------------------------------------------------------------------------------- local function ConsiderQ(botLevel, enemyHero, enemyCreeps, botManaLevel, botManaPercentage, botHealthLevel, botHealthPercentage) local optimalLocation local highestDesire = 0 local botLevel = bot:GetLevel() local nDamageQ = abilityQ:GetAbilityDamage(); local nCastPoint = abilities[1]:GetCastPoint(); local manaCost = abilities[1]:GetManaCost(); local nCastLocation = mutils.GetFaceTowardDistanceLocation( bot, nCastRangeQ ) if mutils.CanBeCast(abilities[1]) == false or mutils.hasManaToCastSpells(botLevel, botManaLevel) == false then return BOT_DESIRE_NONE; end if ( botLevel >= 2 ) then local enemyHeroInRazeRadius = bot:GetNearbyHeroes(nCastRangeQ+razeRadius, true, BOT_MODE_NONE); local enemyCreepsInRazeRadius = bot:GetNearbyLaneCreeps(nCastRangeQ+razeRadius, true); local locationAoEForQ = bot:FindAoELocation( true, true, bot:GetLocation(), nCastRangeQ, razeRadius, 0, nDamageQ ); --if #enemyHero ~= 0 and #enemyHeroInRazeRadius ~= 0 then --return 1, enemyHero[1]:GetLocation() --end if #enemyHero ~= 0 and mutils.IsUnitNearLoc( enemyHero[1], nCastLocation, razeRadius , nCastPoint ) == true then return BOT_DESIRE_VERY_HIGH, enemyHero[1]:GetLocation() end --if locationAoEForQ.count >= 1 --and mutils.isLocationWithinRazeRange(bot, nCastRangeQ, razeRadius, locationAoEForQ.targetloc) --and bot:IsFacingLocation(locationAoEForQ.targetloc,10) then --DebugDrawCircle(locationAoEForQ.targetloc, razeRadius, 255, 0, 0) --highestDesire = 0.5 --optimalLocation = locationAoEForQ.targetloc --end end return BOT_DESIRE_NONE, optimalLocation end ---------------------------------------------------------------------------------------------------- -- Calculate if bot wants to use medium raze ---------------------------------------------------------------------------------------------------- local function ConsiderW(botLevel, enemyHero, enemyCreeps, botManaLevel, botManaPercentage, botHealthLevel, botHealthPercentage) local optimalLocation local highestDesire = 0 local botLevel = bot:GetLevel() local nDamageW = abilityE:GetAbilityDamage(); local nCastPoint = abilities[2]:GetCastPoint(); local manaCost = abilities[2]:GetManaCost(); local nCastLocation = mutils.GetFaceTowardDistanceLocation( bot, nCastRangeW ) if mutils.CanBeCast(abilities[2]) == false or mutils.hasManaToCastSpells(botLevel, botManaLevel) == false then return BOT_DESIRE_NONE; end if ( botLevel >= 2 ) then local enemyHeroInRazeRadius = bot:GetNearbyHeroes(nCastRangeW+razeRadius, true, BOT_MODE_NONE); local enemyCreepsInRazeRadius = bot:GetNearbyLaneCreeps(nCastRangeW+razeRadius, true); local locationAoEForW = bot:FindAoELocation( true, true, bot:GetLocation(), nCastRangeW, razeRadius, 0, nDamageW ); --if #enemyHero ~= 0 and #enemyHeroInRazeRadius ~= 0 then --return 1, enemyHero[1]:GetLocation() --end if #enemyHero ~= 0 and mutils.IsUnitNearLoc( enemyHero[1], nCastLocation, razeRadius, nCastPoint ) == true then return BOT_DESIRE_VERY_HIGH, enemyHero[1]:GetLocation() end --if locationAoEForE.count >= 1 --and mutils.isLocationWithinRazeRange(bot, nCastRangeW, razeRadius, locationAoEForW.targetloc) --and bot:IsFacingLocation(locationAoEForW.targetloc,10) then --DebugDrawCircle(locationAoEForW.targetloc, razeRadius, 0, 255, 0) --highestDesire = 0.5 --optimalLocation = locationAoEForW.targetloc --end end return BOT_DESIRE_NONE, optimalLocation end ---------------------------------------------------------------------------------------------------- -- Calculate if bot wants to use long raze ---------------------------------------------------------------------------------------------------- local function ConsiderE(botLevel, enemyHero, enemyCreeps, botManaLevel, botManaPercentage, botHealthLevel, botHealthPercentage) local optimalLocation local highestDesire = 0 local botLevel = bot:GetLevel() local abilityLevel = abilities[3]:GetLevel() local abilityDamage = abilities[3]:GetAbilityDamage() local castPoint = abilities[3]:GetCastPoint() local nDamageE = abilityQ:GetAbilityDamage(); local nCastPoint = abilities[3]:GetCastPoint(); local manaCost = abilities[3]:GetManaCost(); local nCastLocation = mutils.GetFaceTowardDistanceLocation( bot, nCastRangeE ) local creepsKilledByRaze = 0 if mutils.CanBeCast(abilities[3]) == false or mutils.hasManaToCastSpells(botLevel, botManaLevel) == false or enemyHero == nil or #enemyHero == 0 then return BOT_DESIRE_NONE; end if ( botLevel >= 2 ) then local enemyHeroInRazeRadius = bot:GetNearbyHeroes(nCastRangeE+razeRadius, true, BOT_MODE_NONE); local enemyCreepsInRazeRadius = enemyHero[1]:GetNearbyLaneCreeps(razeRadius, true); local locationAoEForE = bot:FindAoELocation( true, true, bot:GetLocation(), nCastRangeE, razeRadius, 0, nDamageE ); for _, creep in pairs(enemyCreepsInRazeRadius) do if creep:GetHealth() < abilityDamage then creepsKilledByRaze = creepsKilledByRaze + 1 end end --if #enemyHero ~= 0 and #enemyHeroInRazeRadius ~= 0 then --return 1, enemyHero[1]:GetLocation() --end if #enemyHero ~= 0 and mutils.IsUnitNearLoc( enemyHero[1], nCastLocation, razeRadius , nCastPoint ) == true then if (abilityLevel == 1) and creepsKilledByRaze > 0 then return BOT_DESIRE_LOW, enemyHero[1]:GetLocation() elseif abilityLevel == 2 and creepsKilledByRaze > 0 then return BOT_DESIRE_MEDIUM, enemyHero[1]:GetLocation() elseif abilityLevel == 3 then return BOT_DESIRE_VERY_HIGH, enemyHero[1]:GetLocation() elseif abilityLevel == 4 then return BOT_DESIRE_VERY_HIGH, enemyHero[1]:GetLocation() end end --if locationAoEForE.count >= 1 --and mutils.isLocationWithinRazeRange(bot, nCastRangeE, razeRadius, nClocationAoEForE.targetloc) --and bot:IsFacingLocation(locationAoEForE.targetloc,10) then --DebugDrawCircle(locationAoEForE.targetloc, razeRadius, 0, 0, 255) --highestDesire = 0.5 --optimalLocation = locationAoEForE.targetloc --end end return BOT_DESIRE_NONE, optimalLocation end ---------------------------------------------------------------------------------------------------- -- Calculate if bot wants to use Requiem ---------------------------------------------------------------------------------------------------- local function ConsiderR() if mutils.CanBeCast(abilities[4]) == false then return 0; end if (abilityQ:IsCooldownReady() == false and abilityW:IsCooldownReady() == false and abilityE:IsCooldownReady() == false) then return 1 end return 0; end ---------------------------------------------------------------------------------------------------- -- Function called every frame to determine bot positioning ---------------------------------------------------------------------------------------------------- local function heroPosition(nearbyCreeps, enemyCreeps, enemyHero) local distanceBetweenClosestAndFarthestCreep --local closestCreepToEnemyFountain = GetUnitToLocationDistance(nearbyCreeps[i], Vector(-3293.869141, -3455.594727)) local positionNoCreeps = T1_TOWER_POSITION local positionNoEnemyCreeps local positionAggro local positionNeutral local towersInRange = bot:GetNearbyTowers(700, true) local creepsNearTower local closestCreepToTower local closestCreepToTowerDistance if nearbyCreeps ~= nil and #nearbyCreeps ~=0 then positionNoEnemyCreeps = Vector(nearbyCreeps[1]:GetLocation().x+100, nearbyCreeps[1]:GetLocation().y+100) end print("Bot position: ", GetAmountAlongLane(LANE_MID, bot:GetLocation()).amount) if enemyCreeps ~= nil and #enemyCreeps ~=0 then distanceBetweenClosestAndFarthestCreep = GetUnitToUnitDistance(enemyCreeps[1], enemyCreeps[#enemyCreeps]) positionAggro = GetLocationAlongLane(LANE_MID, BOT_JUST_OUTSIDE_TOWER_RANGE) positionNeutral = Vector(enemyCreeps[1]:GetLocation().x+400, enemyCreeps[1]:GetLocation().y+400) if GetAmountAlongLane(LANE_MID, positionNeutral).amount > 0.65 then positionNeutral = GetLocationAlongLane(LANE_MID, BOT_JUST_OUTSIDE_TOWER_RANGE) elseif GetAmountAlongLane(LANE_MID, bot:GetLocation()).amount < 0.53 then if bot:WasRecentlyDamagedByCreep(0.1) then if BOT_NEAR_TOWER_POS_FLAG == 1 then positionNeutral = BOT_NEAR_TOWER_POS_1 else positionNeutral = BOT_NEAR_TOWER_POS_2 end end end end if bot:WasRecentlyDamagedByTower(0.5) == true then return BOT_DESIRE_HIGH, T1_TOWER_POSITION end if towersInRange ~= nil and #towersInRange > 0 then local towerLocation = towersInRange[1]:GetLocation() if nearbyCreeps == nil or #nearbyCreeps == 0 then return BOT_DESIRE_HIGH, T1_TOWER_POSITION end for _, creep in pairs(nearbyCreeps) do if GetUnitToUnitDistance(creep, towersInRange[1]) < closestCreepToTowerDistance then closestCreepToTower = creep closestCreepToTowerDistance = GetUnitToUnitDistance(creep, towersInRange[1]) end end if #nearbyCreeps >= 3 and (GetUnitToUnitDistance(towersInRange[1], closestCreepToTower) < GetUnitToUnitDistance(bot, towersInRange[1])) then return BOT_DESIRE_NONE else if (GetUnitToLocationDistance(bot, T1_TOWER_POSITION) > 100) then return BOT_DESIRE_HIGH, T1_TOWER_POSITION end end end if botBattleMode == "defend" and #enemyHero ~= 0 then local distanceToExitDamageRadius = 700 - (mutils.GetLocationToLocationDistance(bot:GetLocation(), enemyHero[1]:GetLocation())) local timeToExitDamageRadius if GetUnitToUnitDistance(enemyHero[1], bot) > 950 then return BOT_DESIRE_LOW, positionNeutral end if enemyHero[1]:GetCurrentMovementSpeed() >= bot:GetCurrentMovementSpeed() then return BOT_DESIRE_VERY_HIGH, Vector(enemyHero[1]:GetLocation().x+700,enemyHero[1]:GetLocation().y+700) else timeToExitDamageRadius = distanceToExitDamageRadius / (bot:GetCurrentMovementSpeed() - enemyHero[1]:GetCurrentMovementSpeed()) if(GetUnitToUnitDistance(bot, enemyHero[1]) < 700 and mutils.GetUnitsDamageToEnemyForTimePeriod(enemyHero[1], bot, timeToExitDamageRadius, abilities) > bot:GetHealth()) then return BOT_DESIRE_VERY_HIGH, Vector(enemyHero[1]:GetLocation().x+700, enemyHero[1]:GetLocation().y+700) end end end if enemyCreeps ~= nil and #enemyCreeps > 0 then distanceBetweenClosestAndFarthestCreep = GetUnitToUnitDistance(enemyCreeps[1], enemyCreeps[#enemyCreeps]) if (distanceBetweenClosestAndFarthestCreep > 500) and botBattleMode == "aggro" then return BOT_DESIRE_LOW, positionNeutral else return BOT_DESIRE_LOW, positionNeutral end elseif nearbyCreeps ~= nil and #nearbyCreeps > 0 then if (GetUnitToLocationDistance(bot, Vector(nearbyCreeps[1]:GetLocation().x+100, nearbyCreeps[1]:GetLocation().y+100)) > 50) then return BOT_DESIRE_LOW, positionNoEnemyCreeps end else if (GetUnitToLocationDistance(bot, positionNoCreeps) > 50) then return BOT_DESIRE_MEDIUM, positionNoCreeps end end return BOT_DESIRE_NONE end ---------------------------------------------------------------------------------------------------- -- Function called every frame for helping the bot last hitting ---------------------------------------------------------------------------------------------------- local function heroLastHit(enemyHero, nearbyCreeps, enemyCreeps, botAttackDamage) local alliedCreepTarget = mutils.GetWeakestUnit(nearbyCreeps); local enemyCreepTarget = mutils.GetWeakestUnit(enemyCreeps); local meeleCreepCumulativeDamage = 0 local meeleCreepWhichKillsIndex = 0 local enemyCreepsHittingTarget = {} local alliedCreepsHittingTarget = {} local allyUnitWhichKillsIndex = 0 local enemyUnitpWhichKillsIndex = 0 if enemyCreepTarget == nil and alliedCreepTarget == nil then return BOT_DESIRE_NONE else if enemyCreepTarget ~= nil then local heroHittingTargetCreep = nil local unitsHittingTargetCreep = {} local distanceBetweenCreepAndBot = GetUnitToUnitDistance(bot, enemyCreepTarget) local timeForBotAttackToLand = 0 local doesBotHaveToTurnToHitCreep, turnTime = mutils.DoesBotHaveToTurnToHitCreep(bot, enemyCreepTarget) local projectiles = enemyCreepTarget:GetIncomingTrackingProjectiles() print("Bot current damage: ", bot:GetAttackDamage() * bot:GetAttackCombatProficiency(enemyCreepTarget) * mutils.getDamageMultipler(enemyCreepTarget)) if (distanceBetweenCreepAndBot > 535.5) then if doesBotHaveToTurnToHitCreep == true then timeForBotAttackToLand = (distanceBetweenCreepAndBot / bot:GetAttackProjectileSpeed()) + ((distanceBetweenCreepAndBot - 535.5) / bot:GetCurrentMovementSpeed()) + mutils.getAttackPointBasedOnIAS(bot) + turnTime else timeForBotAttackToLand = (distanceBetweenCreepAndBot / bot:GetAttackProjectileSpeed()) + ((distanceBetweenCreepAndBot - 535.5) / bot:GetCurrentMovementSpeed()) + mutils.getAttackPointBasedOnIAS(bot) end else if doesBotHaveToTurnToHitCreep == true then timeForBotAttackToLand = (distanceBetweenCreepAndBot / bot:GetAttackProjectileSpeed()) + mutils.getAttackPointBasedOnIAS(bot) + turnTime else timeForBotAttackToLand = (distanceBetweenCreepAndBot / bot:GetAttackProjectileSpeed()) + mutils.getAttackPointBasedOnIAS(bot) end end print("Time for bot attack to land: ", timeForBotAttackToLand) for _, projectile in pairs(projectiles) do if (projectile.caster:IsTower() == true) then table.insert(unitsHittingTargetCreep, projectile.caster) end if (projectile.caster:IsHero() == true) then heroHittingTargetCreep = projectile.caster end end if nearbyCreeps ~= nil and #nearbyCreeps ~= 0 then for _, creep in pairs(nearbyCreeps) do if (creep:GetAttackTarget() == enemyCreepTarget) then table.insert(unitsHittingTargetCreep, creep) end end end if unitsHittingTargetCreep ~= nil and #unitsHittingTargetCreep > 0 then table.sort(unitsHittingTargetCreep, function(creep1, creep2) local creep1Type local creep2Type local creep1Time local creep2Time creep1Type = mutils.GetCreepType(creep1) creep2Type = mutils.GetCreepType(creep2) if creep1Type == "meele" then creep1Time = creep1:GetLastAttackTime() + MEELE_CREEP_ATTACKS_PER_SECOND elseif creep1Type == "ranged" then creep1Time = creep1:GetLastAttackTime() + RANGED_CREEP_ATTACKS_PER_SECOND + GetUnitToUnitDistance(enemyCreepTarget, creep1) / creep1:GetAttackProjectileSpeed() elseif creep1Type == "siege" then creep1Time = creep1:GetLastAttackTime() + SIEGE_CREEP_ATTACKS_PER_SECOND + GetUnitToUnitDistance(enemyCreepTarget, creep1) / creep1:GetAttackProjectileSpeed() elseif creep1Type == "tower" then creep1Time = creep1:GetLastAttackTime() + T1_TOWER_ATTACKS_PER_SECOND + GetUnitToUnitDistance(enemyCreepTarget, creep1) / creep1:GetAttackProjectileSpeed() end if creep2Type == "meele" then creep2Time = creep2:GetLastAttackTime() + MEELE_CREEP_ATTACKS_PER_SECOND elseif creep2Type == "ranged" then creep2Time = creep2:GetLastAttackTime() + RANGED_CREEP_ATTACKS_PER_SECOND + GetUnitToUnitDistance(enemyCreepTarget, creep2) / creep2:GetAttackProjectileSpeed() elseif creep2Type == "siege" then creep2Time = creep2:GetLastAttackTime() + SIEGE_CREEP_ATTACKS_PER_SECOND + GetUnitToUnitDistance(enemyCreepTarget, creep2) / creep2:GetAttackProjectileSpeed() elseif creep2Type == "tower" then creep2Time = creep2:GetLastAttackTime() + T1_TOWER_ATTACKS_PER_SECOND + GetUnitToUnitDistance(enemyCreepTarget, creep2) / creep2:GetAttackProjectileSpeed() end return creep1Time < creep2Time end) local totalDamage = 0 local i = 1 while (allyUnitWhichKillsIndex == 0) do local index local loopTimes = 0 if i > #unitsHittingTargetCreep then index = math.fmod(i, #unitsHittingTargetCreep) if index == 0 then index = #unitsHittingTargetCreep end else index = i end if i > #unitsHittingTargetCreep then loopTimes = math.floor(i/#unitsHittingTargetCreep) + 1 else loopTimes = 1 end if i > #unitsHittingTargetCreep then local creepType = mutils.GetCreepType(unitsHittingTargetCreep[index]) if creepType == "meele" then if ((unitsHittingTargetCreep[index]:GetLastAttackTime() + (loopTimes * MEELE_CREEP_ATTACKS_PER_SECOND)) - GameTime() >= timeForBotAttackToLand+2) then break end elseif creepType == "ranged" then if ((unitsHittingTargetCreep[index]:GetLastAttackTime() + GetUnitToUnitDistance(enemyCreepTarget, unitsHittingTargetCreep[index]) / unitsHittingTargetCreep[index]:GetAttackProjectileSpeed() + (loopTimes * RANGED_CREEP_ATTACKS_PER_SECOND)) - GameTime() >= timeForBotAttackToLand+2) then break end elseif creepType == "siege" then if ((unitsHittingTargetCreep[index]:GetLastAttackTime() + GetUnitToUnitDistance(enemyCreepTarget, unitsHittingTargetCreep[index]) / unitsHittingTargetCreep[index]:GetAttackProjectileSpeed() + (loopTimes * SIEGE_CREEP_ATTACKS_PER_SECOND)) - GameTime() >= timeForBotAttackToLand+2) then break end else if ((unitsHittingTargetCreep[index]:GetLastAttackTime() + GetUnitToUnitDistance(enemyCreepTarget, unitsHittingTargetCreep[index]) / unitsHittingTargetCreep[index]:GetAttackProjectileSpeed() + (loopTimes * T1_TOWER_ATTACKS_PER_SECOND)) - GameTime() >= timeForBotAttackToLand+2) then break end end end print("Total damage before : ", totalDamage) print("Creep attack: ", unitsHittingTargetCreep[index]:GetAttackDamage()) print("Creep health before: ", enemyCreepTarget:GetHealth() - totalDamage) totalDamage = totalDamage + (unitsHittingTargetCreep[index]:GetAttackDamage() * unitsHittingTargetCreep[index]:GetAttackCombatProficiency(enemyCreepTarget) * mutils.getDamageMultipler(enemyCreepTarget)) print("Total damage after : ", totalDamage) print("Creep health after: ", enemyCreepTarget:GetHealth() - totalDamage) if ((enemyCreepTarget:GetHealth() - totalDamage) < ((bot:GetAttackDamage() - SF_BASE_DAMAGE_VARAINCE)* bot:GetAttackCombatProficiency(enemyCreepTarget) * mutils.getDamageMultipler(enemyCreepTarget))) then allyUnitWhichKillsIndex = i break end i = i + 1 end if allyUnitWhichKillsIndex ~= nil and allyUnitWhichKillsIndex ~= 0 then local loopTimes = 0 local index = 0 if allyUnitWhichKillsIndex > #unitsHittingTargetCreep then index = math.fmod(i, #unitsHittingTargetCreep) if index == 0 then index = #unitsHittingTargetCreep end else index = allyUnitWhichKillsIndex end if allyUnitWhichKillsIndex > #unitsHittingTargetCreep then loopTimes = math.floor(allyUnitWhichKillsIndex/#unitsHittingTargetCreep) + 1 else loopTimes = 1 end local timeTakenForAttackToLand local creepType = mutils.GetCreepType(unitsHittingTargetCreep[index]) if creepType == "meele" then timeTakenForAttackToLand = (unitsHittingTargetCreep[index]:GetLastAttackTime() + (MEELE_CREEP_ATTACKS_PER_SECOND * (loopTimes))) elseif creepType == "ranged" then timeTakenForAttackToLand = (unitsHittingTargetCreep[index]:GetLastAttackTime() + (RANGED_CREEP_ATTACKS_PER_SECOND * loopTimes)) + (GetUnitToUnitDistance(unitsHittingTargetCreep[index], enemyCreepTarget) / unitsHittingTargetCreep[index]:GetAttackProjectileSpeed() ) elseif creepType == "siege" then timeTakenForAttackToLand = (unitsHittingTargetCreep[index]:GetLastAttackTime() + (SIEGE_CREEP_ATTACKS_PER_SECOND * loopTimes)) + (GetUnitToUnitDistance(unitsHittingTargetCreep[index], enemyCreepTarget) / unitsHittingTargetCreep[index]:GetAttackProjectileSpeed() ) elseif creepType == "tower" then timeTakenForAttackToLand = (unitsHittingTargetCreep[index]:GetLastAttackTime()+ (T1_TOWER_ATTACKS_PER_SECOND * loopTimes)) + (GetUnitToUnitDistance(unitsHittingTargetCreep[index], enemyCreepTarget) / unitsHittingTargetCreep[index]:GetAttackProjectileSpeed() ) else timeTakenForAttackToLand = nil end print("Time for creep attack to land: ", timeTakenForAttackToLand - GameTime()) if timeTakenForAttackToLand ~= nil and (timeTakenForAttackToLand < (GameTime() + timeForBotAttackToLand)) then print("LH2") return BOT_DESIRE_MEDIUM, enemyCreepTarget end end end end if alliedCreepTarget ~= nil then local heroHittingTargetCreep = nil local unitsHittingTargetCreep = {} local distanceBetweenCreepAndBot = GetUnitToUnitDistance(bot, alliedCreepTarget) local timeForBotAttackToLand = 0 local doesBotHaveToTurnToHitCreep, turnTime = mutils.DoesBotHaveToTurnToHitCreep(bot, alliedCreepTarget) local projectiles = alliedCreepTarget:GetIncomingTrackingProjectiles() if (distanceBetweenCreepAndBot > 535.5) then if doesBotHaveToTurnToHitCreep == true then timeForBotAttackToLand = (distanceBetweenCreepAndBot / bot:GetAttackProjectileSpeed()) + ((distanceBetweenCreepAndBot - 535.5) / bot:GetCurrentMovementSpeed()) + mutils.getAttackPointBasedOnIAS(bot) + turnTime else timeForBotAttackToLand = (distanceBetweenCreepAndBot / bot:GetAttackProjectileSpeed()) + ((distanceBetweenCreepAndBot - 535.5) / bot:GetCurrentMovementSpeed()) + mutils.getAttackPointBasedOnIAS(bot) end else if doesBotHaveToTurnToHitCreep == true then timeForBotAttackToLand = (distanceBetweenCreepAndBot / bot:GetAttackProjectileSpeed()) + mutils.getAttackPointBasedOnIAS(bot) + turnTime else timeForBotAttackToLand = (distanceBetweenCreepAndBot / bot:GetAttackProjectileSpeed()) + mutils.getAttackPointBasedOnIAS(bot) end end for _, projectile in pairs(projectiles) do if (projectile.caster:IsTower() == true) then table.insert(unitsHittingTargetCreep, projectile.caster) end if (projectile.caster:IsHero() == true) then heroHittingTargetCreep = projectile.caster end end if enemyCreeps ~= nil and #enemyCreeps ~= 0 then for _, creep in pairs(enemyCreeps) do if (creep:GetAttackTarget() == alliedCreepTarget) then table.insert(unitsHittingTargetCreep, creep) end end end if unitsHittingTargetCreep ~= nil and #unitsHittingTargetCreep > 0 then table.sort(unitsHittingTargetCreep, function(creep1, creep2) local creep1Type local creep2Type local creep1Time local creep2Time creep1Type = mutils.GetCreepType(creep1) creep2Type = mutils.GetCreepType(creep2) if creep1Type == "meele" then creep1Time = creep1:GetLastAttackTime() + MEELE_CREEP_ATTACKS_PER_SECOND elseif creep1Type == "ranged" then creep1Time = creep1:GetLastAttackTime() + RANGED_CREEP_ATTACKS_PER_SECOND + GetUnitToUnitDistance(alliedCreepTarget, creep1) / creep1:GetAttackProjectileSpeed() elseif creep1Type == "siege" then creep1Time = creep1:GetLastAttackTime() + SIEGE_CREEP_ATTACKS_PER_SECOND + GetUnitToUnitDistance(alliedCreepTarget, creep1) / creep1:GetAttackProjectileSpeed() elseif creep1Type == "tower" then creep1Time = creep1:GetLastAttackTime() + T1_TOWER_ATTACKS_PER_SECOND + GetUnitToUnitDistance(alliedCreepTarget, creep1) / creep1:GetAttackProjectileSpeed() end if creep2Type == "meele" then creep2Time = creep2:GetLastAttackTime() + MEELE_CREEP_ATTACKS_PER_SECOND elseif creep2Type == "ranged" then creep2Time = creep2:GetLastAttackTime() + RANGED_CREEP_ATTACKS_PER_SECOND + GetUnitToUnitDistance(alliedCreepTarget, creep2) / creep2:GetAttackProjectileSpeed() elseif creep2Type == "siege" then creep2Time = creep2:GetLastAttackTime() + SIEGE_CREEP_ATTACKS_PER_SECOND + GetUnitToUnitDistance(alliedCreepTarget, creep2) / creep2:GetAttackProjectileSpeed() elseif creep2Type == "tower" then creep2Time = creep2:GetLastAttackTime() + T1_TOWER_ATTACKS_PER_SECOND + GetUnitToUnitDistance(alliedCreepTarget, creep2) / creep2:GetAttackProjectileSpeed() end return creep1Time < creep2Time end) local totalDamage = 0 local i = 1 while (allyUnitWhichKillsIndex == 0) do local index local loopTimes = 0 if i > #unitsHittingTargetCreep then index = math.fmod(i, #unitsHittingTargetCreep) if index == 0 then index = #unitsHittingTargetCreep end else index = i end if i > #unitsHittingTargetCreep then loopTimes = math.floor(i/#unitsHittingTargetCreep) + 1 else loopTimes = 1 end if i > #unitsHittingTargetCreep then local creepType = mutils.GetCreepType(unitsHittingTargetCreep[index]) if creepType == "meele" then if ((unitsHittingTargetCreep[index]:GetLastAttackTime() + (loopTimes * MEELE_CREEP_ATTACKS_PER_SECOND)) - GameTime() >= timeForBotAttackToLand+2) then break end elseif creepType == "ranged" then if ((unitsHittingTargetCreep[index]:GetLastAttackTime() + GetUnitToUnitDistance(alliedCreepTarget, unitsHittingTargetCreep[index]) / unitsHittingTargetCreep[index]:GetAttackProjectileSpeed() + (loopTimes * RANGED_CREEP_ATTACKS_PER_SECOND)) - GameTime() >= timeForBotAttackToLand+2) then break end elseif creepType == "siege" then if ((unitsHittingTargetCreep[index]:GetLastAttackTime() + GetUnitToUnitDistance(alliedCreepTarget, unitsHittingTargetCreep[index]) / unitsHittingTargetCreep[index]:GetAttackProjectileSpeed() + (loopTimes * SIEGE_CREEP_ATTACKS_PER_SECOND)) - GameTime() >= timeForBotAttackToLand+2) then break end else if ((unitsHittingTargetCreep[index]:GetLastAttackTime() + GetUnitToUnitDistance(alliedCreepTarget, unitsHittingTargetCreep[index]) / unitsHittingTargetCreep[index]:GetAttackProjectileSpeed() + (loopTimes * T1_TOWER_ATTACKS_PER_SECOND)) - GameTime() >= timeForBotAttackToLand+2) then break end end end totalDamage = totalDamage + (unitsHittingTargetCreep[index]:GetAttackDamage() * unitsHittingTargetCreep[index]:GetAttackCombatProficiency(alliedCreepTarget) * mutils.getDamageMultipler(alliedCreepTarget)) if ((alliedCreepTarget:GetHealth() - totalDamage) < ((bot:GetAttackDamage() - SF_BASE_DAMAGE_VARAINCE)* bot:GetAttackCombatProficiency(alliedCreepTarget) * mutils.getDamageMultipler(alliedCreepTarget))) then enemyUnitpWhichKillsIndex = i break end i = i + 1 end if enemyUnitpWhichKillsIndex ~= nil and enemyUnitpWhichKillsIndex ~= 0 then local loopTimes = 0 local index = 0 if enemyUnitpWhichKillsIndex > #unitsHittingTargetCreep then index = math.fmod(i, #unitsHittingTargetCreep) if index == 0 then index = #unitsHittingTargetCreep end else index = enemyUnitpWhichKillsIndex end if enemyUnitpWhichKillsIndex > #unitsHittingTargetCreep then loopTimes = math.floor(enemyUnitpWhichKillsIndex/#unitsHittingTargetCreep) + 1 else loopTimes = 1 end local timeTakenForAttackToLand local creepType = mutils.GetCreepType(unitsHittingTargetCreep[index]) if creepType == "meele" then timeTakenForAttackToLand = (unitsHittingTargetCreep[index]:GetLastAttackTime() + (MEELE_CREEP_ATTACKS_PER_SECOND * (loopTimes))) elseif creepType == "ranged" then timeTakenForAttackToLand = (unitsHittingTargetCreep[index]:GetLastAttackTime() + (RANGED_CREEP_ATTACKS_PER_SECOND * loopTimes)) + (GetUnitToUnitDistance(unitsHittingTargetCreep[index], alliedCreepTarget) / unitsHittingTargetCreep[index]:GetAttackProjectileSpeed() ) elseif creepType == "siege" then timeTakenForAttackToLand = (unitsHittingTargetCreep[index]:GetLastAttackTime() + (SIEGE_CREEP_ATTACKS_PER_SECOND * loopTimes)) + (GetUnitToUnitDistance(unitsHittingTargetCreep[index], alliedCreepTarget) / unitsHittingTargetCreep[index]:GetAttackProjectileSpeed() ) elseif creepType == "tower" then timeTakenForAttackToLand = (unitsHittingTargetCreep[index]:GetLastAttackTime()+ (T1_TOWER_ATTACKS_PER_SECOND * loopTimes)) + (GetUnitToUnitDistance(unitsHittingTargetCreep[index], alliedCreepTarget) / unitsHittingTargetCreep[index]:GetAttackProjectileSpeed() ) else timeTakenForAttackToLand = nil end if timeTakenForAttackToLand ~= nil and (timeTakenForAttackToLand < (GameTime() + timeForBotAttackToLand)) then return BOT_DESIRE_MEDIUM, alliedCreepTarget end end end end end if enemyCreeps ~= nil and #enemyCreeps > 0 then for i=1,#enemyCreeps,1 do if enemyCreeps[i]:GetHealth() < ((bot:GetAttackDamage() - bot:GetBaseDamageVariance()) * bot:GetAttackCombatProficiency(enemyCreeps[i]) * mutils.getDamageMultipler(enemyCreeps[i])) then print("LH1") return BOT_DESIRE_MEDIUM, enemyCreeps[i] end end end if nearbyCreeps ~= nil and #nearbyCreeps > 0 then for i=1,#nearbyCreeps,1 do if nearbyCreeps[i]:GetHealth() < ((bot:GetAttackDamage() - bot:GetBaseDamageVariance()) * bot:GetAttackCombatProficiency(nearbyCreeps[i]) * mutils.getDamageMultipler(nearbyCreeps[i])) then return BOT_DESIRE_MEDIUM, nearbyCreeps[i] end end end return BOT_DESIRE_NONE end ---------------------------------------------------------------------------------------------------- -- Function called every frame to determine what items to buy ---------------------------------------------------------------------------------------------------- local function heroBattleThink(enemyHero, nearbyCreeps) if #enemyHero == 0 then return BOT_DESIRE_NONE end local towersInRange = bot:GetNearbyTowers( 700, true ) local enemyMeeleCreepsDamage = 0 local enemyRangeCreepsDamage = 0 local alliedMeeleCreepsDamage = 0 local alliedRangeCreepsDamage = 0 local alliedTowersDamage = 0 local enemyTowersDamage = 0 local enemyMeeleCreepsNearBot = bot:GetNearbyLaneCreeps( 125, true ) if #enemyMeeleCreepsNearBot > 0 then for _, creep in pairs(enemyMeeleCreepsNearBot) do enemyMeeleCreepsDamage = creep:GetAttackDamage() * creep:GetAttackCombatProficiency(bot) * mutils.getDamageMultipler(bot) end end local enemyRangeCreepsHittingBot = 0 local botProjectiles = bot:GetIncomingTrackingProjectiles() if (#botProjectiles ~= 0) then for index, projectile in pairs(botProjectiles) do if mutils.GetCreepType(projectile.caster) == "ranged" then enemyRangeCreepsHittingBot = enemyRangeCreepsHittingBot + 1 enemyRangeCreepsDamage = projectile.caster:GetAttackDamage() * projectile.caster:GetAttackCombatProficiency(bot) * mutils.getDamageMultipler(bot) elseif mutils.GetCreepType(projectile.caster) == "tower" then enemyTowersDamage = projectile.caster:GetAttackDamage() * projectile.caster:GetAttackCombatProficiency(bot) * mutils.getDamageMultipler(bot) end end end local enemyCreepsDamage = alliedMeeleCreepsDamage + alliedRangeCreepsDamage local alliedMeeleCreepsNearEnemy = enemyHero[1]:GetNearbyLaneCreeps( 125, true ) if #alliedMeeleCreepsNearEnemy > 0 then for _, creep in pairs(enemyMeeleCreepsNearBot) do alliedMeeleCreepsDamage = creep:GetAttackDamage() * creep:GetAttackCombatProficiency(enemyHero[1]) * mutils.getDamageMultipler(enemyHero[1]) end end local alliedRangeCreepsHittingEnemy = 0 local enemyProjectiles = enemyHero[1]:GetIncomingTrackingProjectiles() if (#enemyProjectiles ~= 0) then for index, projectile in pairs(enemyProjectiles) do if mutils.GetCreepType(projectile.caster) == "ranged" then alliedRangeCreepsHittingEnemy = alliedRangeCreepsHittingEnemy + 1 alliedRangeCreepsDamage = projectile.caster:GetAttackDamage() * projectile.caster:GetAttackCombatProficiency(enemyHero[1]) * mutils.getDamageMultipler(enemyHero[1]) elseif mutils.GetCreepType(projectile.caster) == "tower" then alliedTowersDamage = projectile.caster:GetAttackDamage() * projectile.caster:GetAttackCombatProficiency(enemyHero[1]) * mutils.getDamageMultipler(enemyHero[1]) end end end local alliedCreepsDPS = (alliedMeeleCreepsDamage * MEELE_CREEP_ATTACKS_PER_SECOND) + (alliedRangeCreepsDamage * RANGED_CREEP_ATTACKS_PER_SECOND) + (alliedTowersDamage * T1_TOWER_ATTACKS_PER_SECOND) local enemyCreepsDPS = (enemyMeeleCreepsDamage * MEELE_CREEP_ATTACKS_PER_SECOND) + (enemyRangeCreepsDamage * RANGED_CREEP_ATTACKS_PER_SECOND) + (enemyTowersDamage * T1_TOWER_ATTACKS_PER_SECOND) local botAttacksPerSecond = 1/bot:GetAttackSpeed() local botMagicalDamgage, botSpellCastingTime = mutils.GetBotSpellDamage(bot, enemyHero[1], abilities) local botDPS = (bot:GetAttackDamage() * botAttacksPerSecond) + botMagicalDamgage local enemyAttacksPerSecond = 1/enemyHero[1]:GetAttackSpeed() local enemyMagicalDamgage, enemySpellCastingTime = mutils.GetEnemySpellDamage(bot, enemyHero[1], abilities) local enemyDPS = (enemyHero[1]:GetAttackDamage() * botAttacksPerSecond) + enemyMagicalDamgage local timeToKillEnemy = enemyHero[1]:GetHealth() / (botDPS + alliedCreepsDPS) local timeToKillBot = bot:GetHealth() / (enemyDPS + enemyCreepsDPS) print("Time to kill bot : ", timeToKillBot) print("Time to kill enemy : ", timeToKillEnemy) print("Enemy dmage: ", enemyDPS) print("Bot dmge:" , botDPS) local timeForBotToDie = bot:GetHealth() / (enemyDPS + enemyCreepsDPS) local timeForEnemeyToDie = enemyHero[1]:GetHealth() / (botDPS + alliedCreepsDPS) if enemyHero[1]:GetHealth() < bot:GetHealth() then if #enemyMeeleCreepsNearBot == 0 then botBattleMode = "aggro" elseif (enemyDPS + enemyCreepsDPS) < (botDPS + alliedCreepsDPS) then botBattleMode = "aggro" else botBattleMode = "neutral" end elseif bot:GetHealth() < enemyHero[1]:GetHealth() and timeForBotToDie < timeForEnemeyToDie then botBattleMode = "defend" elseif timeForBotToDie > timeForEnemeyToDie then botBattleMode = "aggro" else botBattleMode = "neutral" end print("Current mode: ", botBattleMode) if towersInRange ~= nil and #towersInRange > 0 then local timeToKillBotUnderTower = bot:GetHealth() / (enemyDPS + T1_TOWER_DPS+ enemyCreepsDPS) if (timeToKillBotUnderTower < timeToKillEnemy) or timeToKillEnemy > 2 then return BOT_DESIRE_NONE else return BOT_DESIRE_VERY_HIGH, enemyHero[1] end end local pvpDistance = GetUnitToUnitDistance(bot, enemyHero[1]) --if #enemyHero == 0 or (mutils.CanBeCast(abilities[1]) == true and enemyHero[1]:HasModifier("modifier_nevermore_shadowraze_debuff") == true) then --return BOT_DESIRE_NONE --end if bot:WasRecentlyDamagedByTower(0.1) and towersInRange ~= nil and #towersInRange > 0 then local towerToBotDistance = GetUnitToUnitDistance(bot, towersInRange[1]) if #nearbyCreeps > 0 then local closestCreepToTower = (towersInRange[1]:GetNearbyLaneCreeps(700, true))[1] if closestCreepToTower < towerToBotDistance then return BOT_DESIRE_VERY_HIGH, nearbyCreeps[1] end else return BOT_DESIRE_NONE end end if (botDPS * 5.0) > enemyHero[1]:GetHealth() then if (timeToKillEnemy < timeToKillBot) then return BOT_DESIRE_ABSOLUTE, enemyHero[1] else return BOT_DESIRE_NONE end end if (enemyDPS * 3.0) > bot:GetHealth() and timeToKillBot < timeToKillEnemy then return BOT_DESIRE_NONE end if botBattleMode == "neutral" then if bot:WasRecentlyDamagedByAnyHero(0.1) and ((botDPS+alliedCreepsDPS) > (enemyDPS+enemyCreepsDPS)) then return BOT_DESIRE_MEDIUM, enemyHero[1] else botBattleMode = "defend" return BOT_DESIRE_NONE end end if botBattleMode == "aggro" then local timeToKillBot = bot:GetHealth() / (enemyDPS + enemyCreepsDPS) local timeToKillEnemy = enemyHero[1]:GetHealth() / (botDPS + alliedCreepsDPS) if timeToKillBot > timeToKillEnemy then return BOT_DESIRE_HIGH, enemyHero[1] else return BOT_DESIRE_NONE end end local botAnimActivity = bot:GetAnimActivity() print("Anim: ", botAnimActivity) --if (botAnimActivity == BOT_ANIMATION_IDLE) then --print("Attacking because bot is idle") --return BOT_DESIRE_HIGH, enemyHero[1] --end return BOT_DESIRE_NONE end ---------------------------------------------------------------------------------------------------- -- Function called every frame to determine bot spell usage ---------------------------------------------------------------------------------------------------- local function AbilityUsageThink(botLevel, botAttackDamage, enemyHero, enemyCreeps, botManaLevel, botManaPercentage, botHealthLevel, botHealthPercentage) local manaBasedDesire = 0 local levelBasedDesire = 0 local currentBotLocation = bot:GetLocation() if mutils.CantUseAbility(bot) or mutils.hasManaToCastSpells(botLevel, botManaLevel) == false then return BOT_DESIRE_NONE end --Desire to cast spells based on current hero level if botLevel == 1 then levelBasedDesire = 0.5 end --Desire to cast spells based on current mana level if (botManaPercentage >= 90) then manaBasedDesire = manaBasedDesire + 0.5 elseif (botManaPercentage >= 60) then manaBasedDesire = manaBasedDesire + 0.4 elseif (botManaPercentage >= 30) then manaBasedDesire = manaBasedDesire + 0.3 end castQDesire, optimalLocationQ = ConsiderQ(botLevel, enemyHero, enemyCreeps, botManaLevel, botManaPercentage, botHealthLevel, botHealthPercentage); castWDesire, optimalLocationW = ConsiderW(botLevel, enemyHero, enemyCreeps, botManaLevel, botManaPercentage, botHealthLevel, botHealthPercentage); castEDesire, optimalLocationE = ConsiderE(botLevel, enemyHero, enemyCreeps, botManaLevel, botManaPercentage, botHealthLevel, botHealthPercentage); castRDesire = ConsiderR(enemy); if castRDesire > 0 then return BOT_DESIRE_LOW, abilities[4] end if castQDesire > 0 then local newXLocationQ = 0 local newYLocationQ = 0 local horizontalDistanceBetweenPoints = math.max(optimalLocationQ.x, currentBotLocation.x) - math.min(optimalLocationQ.x - currentBotLocation.x) local verticalDistanceBetweenPoints = math.max(optimalLocationQ.y, currentBotLocation.y) - math.min(optimalLocationQ.y - currentBotLocation.y) newXLocationQ = horizontalDistanceBetweenPoints * 0.01 newYLocationQ = verticalDistanceBetweenPoints * 0.01 if currentBotLocation.x > optimalLocationQ.x then newXLocationQ = currentBotLocation.x - (horizontalDistanceBetweenPoints * 0.001) elseif currentBotLocation.x < optimalLocationQ.x then newXLocationQ = currentBotLocation.x + (horizontalDistanceBetweenPoints * 0.001) else newXLocationQ = currentBotLocation.x end if currentBotLocation.y > optimalLocationQ.y then newYLocationQ = currentBotLocation.y - (verticalDistanceBetweenPoints * 0.001) elseif currentBotLocation.y < optimalLocationQ.y then newYLocationQ = currentBotLocation.y + (verticalDistanceBetweenPoints * 0.001) else newYLocationQ = currentBotLocation.y end if (bot:IsFacingLocation( optimalLocationQ, 50 )) then return castQDesire, Vector(newXLocationQ, newYLocationQ), abilities[1] end end if castWDesire > 0 then local newXLocationW = 0 local newYLocationW = 0 local horizontalDistanceBetweenPoints = math.max(optimalLocationW.x, currentBotLocation.x) - math.min(optimalLocationW.x - currentBotLocation.x) local verticalDistanceBetweenPoints = math.max(optimalLocationW.y, currentBotLocation.y) - math.min(optimalLocationW.y - currentBotLocation.y) newXLocationW = horizontalDistanceBetweenPoints * 0.001 newYLocationW = verticalDistanceBetweenPoints * 0.001 if currentBotLocation.x > optimalLocationW.x then newXLocationW = currentBotLocation.x - (horizontalDistanceBetweenPoints * 0.001) elseif currentBotLocation.x < optimalLocationW.x then newXLocationW = currentBotLocation.x + (horizontalDistanceBetweenPoints * 0.001) else newXLocationW = currentBotLocation.x end if currentBotLocation.y > optimalLocationW.y then newYLocationW = currentBotLocation.y - (verticalDistanceBetweenPoints * 0.001) elseif currentBotLocation.y < optimalLocationW.y then newYLocationW = currentBotLocation.y + (verticalDistanceBetweenPoints * 0.001) else newYLocationW = currentBotLocation.y end if (bot:IsFacingLocation( optimalLocationW, 25 )) then return castWDesire, Vector(newXLocationW, newYLocationW), abilities[2] end end if castEDesire > 0 then local newXLocationE = 0 local newYLocationE = 0 local horizontalDistanceBetweenPoints = math.max(optimalLocationE.x, currentBotLocation.x) - math.min(optimalLocationE.x - currentBotLocation.x) local verticalDistanceBetweenPoints = math.max(optimalLocationE.y, currentBotLocation.y) - math.min(optimalLocationE.y - currentBotLocation.y) newXLocationE = horizontalDistanceBetweenPoints * 0.001 newYLocationE = verticalDistanceBetweenPoints * 0.001 if currentBotLocation.x > optimalLocationE.x then newXLocationE = currentBotLocation.x - (horizontalDistanceBetweenPoints * 0.001) elseif currentBotLocation.x < optimalLocationE.x then newXLocationE = currentBotLocation.x + (horizontalDistanceBetweenPoints * 0.001) else newXLocationE = currentBotLocation.x end if currentBotLocation.y > optimalLocationE.y then newYLocationE = currentBotLocation.y - (verticalDistanceBetweenPoints * 0.001) elseif currentBotLocation.y < optimalLocationE.y then newYLocationE = currentBotLocation.y + (verticalDistanceBetweenPoints * 0.001) else newYLocationE = currentBotLocation.y end if (bot:IsFacingLocation( optimalLocationE, 10 )) then return castEDesire, Vector(newXLocationE, newYLocationE), abilities[3] end end return BOT_DESIRE_NONE end ---------------------------------------------------------------------------------------------------- -- Function called every frame to determine what items to buy ---------------------------------------------------------------------------------------------------- local function ItemPurchaseThink(botManaPercentage, botHealthPercentage) if bot:DistanceFromFountain() <= 5 and mutils.GetItemTPScroll(bot) == nil then table.insert(itemToBuy, 1, "item_tpscroll") end if itemsToBuy[1] ~= "item_flask" and (botHealthPercentage <= 0.6) then table.insert(itemsToBuy, 1, "item_flask") end if itemsToBuy[1] ~= "item_enchanted_mango" and (botManaPercentage <= 0.6) then table.insert(itemsToBuy, 1, "item_enchanted_mango") end end ---------------------------------------------------------------------------------------------------- -- Function called every frame to determine if and what item(s) to use ---------------------------------------------------------------------------------------------------- local function ItemUsageThink(botManaLevel, botManaPercentage, botHealthLevel, botHealthPercentage) -- Using Faerie Fire when needed is top priority if botHealthLevel <= 85 then faerieFire = mutils.GetItemFaerieFire(bot) if faerieFire ~= nil then bot:Action_UseAbility(faerieFire) return botState.STATE_HEALING end end local item_to_use = nil -- Using Salve or Mango when needed local state = nil if botHealthPercentage <= 0.6 then item_to_use = mutils.GetItemFlask(bot) state = botState.STATE_HEALING elseif botManaPercentage <= 0.6 then item_to_use = mutils.GetItemMango(bot) state = botState.STATE_IDLE end if item_to_use ~= nil then bot:Action_UseAbilityOnEntity(item_to_use, bot) return state end -- TP to T1 if we are in base -- The assumption here is that this method will be called only after game starts -- (i.e., creeps started) local tpScroll = mutils.GetItemTPScroll(bot) if bot:DistanceFromFountain() <= 5 and tpScroll ~= nil then print("using tp_scroll from "..tostring(bot:DistanceFromFountain()).." on location: "..tostring(mutils.GetT1Location())) bot:Action_UseAbilityOnLocation(tpScroll, mutils.GetT1Location()) return botState.STATE_TELEPORTING end return botState.STATE_IDLE end ---------------------------------------------------------------------------------------------------- -- Function that is called every frame, does a complete bot takeover function Think() if bot:IsUsingAbility() == true then return end -- Initializations ----------------------------------------------------------- dotaTime = DotaTime() botAttackDamage = bot:GetAttackDamage() attackSpeed = bot:GetAttackSpeed() enemyHero = bot:GetNearbyHeroes( 1600, true, BOT_MODE_NONE) botLevel = bot:GetLevel() botManaLevel = bot:GetMana() botManaPercentage = botManaLevel/bot:GetMaxMana() botHealthLevel = bot:GetHealth() botHealthPercentage = botHealthLevel/bot:GetMaxHealth() nearbyCreeps = bot:GetNearbyLaneCreeps( 1600, false ) enemyCreeps = bot:GetNearbyLaneCreeps( 1600, true ) ----------------------------------------------------------- -- PreGame ----------------------------------------------------------- if DotaTime() < 0 then itemWard = mutils.GetItemWard(bot); if itemWard == nil then wardPlaced = true else wardPlaced = false end if wardPlaced == false then bot:Action_UseAbilityOnLocation(itemWard, Vector(-286.881836, 100.408691, 1115.548218)); else mutils.moveToT3Tower(bot) return end end ----------------------------------------------------------- -- First creep block ----------------------------------------------------------- if dotaTime > 0 and creepBlocking == true then creepBlocking = mutils.blockCreepWave(bot, enemyHero, enemyCreeps, nearbyCreeps) return end ----------------------------------------------------------- -- Brain of the bot ----------------------------------------------------------- ItemPurchaseThink(botManaPercentage, botHealthPercentage) state = ItemUsageThink(botManaLevel, botManaPercentage, botHealthLevel, botHealthPercentage) if mutils.IsHealing(bot) then state = botState.STATE_HEALING elseif mutils.IsTeleporting(bot) then state = botState.STATE_TELEPORTING end print("Current State: "..tostring(state.name)) CourierUsageThink() AbilityLevelUpThink() if state == botState.STATE_TELEPORTING then print("doing nothing because teleporting") return end local lastHitDesire, lastHitTarget = heroLastHit(enemyHero, nearbyCreeps, enemyCreeps, botAttackDamage) local battleDesire, battleTarget = heroBattleThink(enemyHero, nearbyCreeps) local abilityUseDesire, abilityMoveLocation, abilityToUse = AbilityUsageThink(botLevel, botAttackDamage, enemyHero, enemyCreeps, botManaLevel, botManaPercentage, botHealthLevel, botHealthPercentage) -- TODO: Move to a safe position when state is STATE_HEALING local moveDesire, moveLocation = heroPosition(nearbyCreeps, enemyCreeps, enemyHero) print("AbilityUseDesire -> ", abilityUseDesire) print("BattleDesire -> ", battleDesire) print("MoveDesire -> ", moveDesire) print("LastHitDesire -> ", lastHitDesire) if mutils.IsAbilityUseDesireGreatest(lastHitDesire, battleDesire, abilityUseDesire, moveDesire) then print("--------------- USING ABILITY ---------------") bot:Action_MoveDirectly(enemyHero[1]:GetLocation()) bot:Action_UseAbility(abilityToUse) return end if mutils.IsBattleDesireGreatest(lastHitDesire, battleDesire, abilityUseDesire, moveDesire) then print("--------------- BATTLING ---------------") bot:Action_AttackUnit(battleTarget, true) return end if mutils.IsMoveDesireGreatest(lastHitDesire, battleDesire, abilityUseDesire, moveDesire) then print("--------------- MOVING ---------------") bot:Action_MoveDirectly(moveLocation) return end if mutils.IsLastHitDesireGreatest(lastHitDesire, battleDesire, abilityUseDesire, moveDesire) then print("--------------- LAST HITTING ---------------") bot:Action_AttackUnit(lastHitTarget, true) return end print("--------------- IDLE ---------------") ----------------------------------------------------------- end
--- Caching mechanism for novus. -- Dependencies: `util` -- @module cache -- @alias _ENV --imports-- local interposable = require"novus.client.interposable" local util = require"novus.util" local ipairs = ipairs local eq = rawequal --start-module-- local _ENV = interposable{} local cachable_entities = { "channel" ,"emoji" ,"role" ,"reaction" } function inserter(cache) return function(object) local id = object.id local old = cache[id] if old and not eq(old, object) then old[3] = nil end cache[id] = object return object end end --- Constructs a new cache object. -- @treturn cache function new() local cache = {methods = {}} for _, v in ipairs(cachable_entities) do local new = {} cache[v] = new cache.methods[v] = inserter(new) end cache.user = util.cache() cache.methods.user = inserter(cache.user) cache.guild = {} cache.methods.guild = inserter(cache.guild) cache.message = {} cache.methods.message = {} cache.member = {} cache.methods.member = {} return cache end --- A collection of weak tables which collect snowflakes. -- @table cache -- @within Objects -- @see cache.new -- @tab methods Closures for caching specific snowflake types. -- @tab type Each cachable snowflake type has a table inside the cache, where objects of that type are kept. --end-module-- return _ENV
ISCharacterScreen = {} function ISCharacterScreen:render() end
module ('content.triggers', package.seeall) require 'base.trigger' mouse_exited = base.trigger:new {} function mouse_exited:check( x, y ) if not self.visible then return end local inside = self.visible:inside(lux.geom.point:new{x,y}) if not self.visible.mouse_exited_mousein and inside then self.visible.mouse_exited_mousein = true elseif self.visible.mouse_exited_mousein and not inside then self.visible.mouse_exited_mousein = false return true end return false end
local prometheus = require "kong.plugins.prometheus.exporter" local printable_metric_data = function() return table.concat(prometheus.metric_data(), "") end return { ["/metrics"] = { GET = function() prometheus.collect() end, }, _stream = ngx.config.subsystem == "stream" and printable_metric_data or nil, }
simulator = { device = "nx64", screenOriginX = 92, screenOriginY = 420, screenWidth = 720, screenHeight = 1280, deviceImage = "NX-Switch.png", displayManufacturer = "Nintendo", displayName = "Switch", windowTitleBarName = "NX Switch", defaultFontSize = 17, -- Converts default font point size to pixels. }
---@class CS.FairyEditor.LoaderExtension : CS.FairyGUI.GLoader ---@type CS.FairyEditor.LoaderExtension CS.FairyEditor.LoaderExtension = { } ---@return CS.FairyEditor.LoaderExtension function CS.FairyEditor.LoaderExtension.New() end return CS.FairyEditor.LoaderExtension
target("grid") set_kind("binary") set_optimize("smallest") set_runtimes("MT") add_defines("UNICODE", "NDEBUG") add_files("ScreenGrid/*.cpp") add_files("ScreenGrid/*.rc") add_syslinks("user32","gdi32","comdlg32") if is_plat('msys') or is_subhost('msys') then add_ldflags('-static') add_ldflags('-Wl,--subsystem,windows') else add_rules("win.sdk.application") end
local markersData = { ["walk"] = { {x = 773.0488, y = 5.4462, z = 1000.7802, dim = 13000, int = 5}, -- LS Gym {x = 763.2203, y = -47.9901, z = 1000.5859, dim = 13001, int = 6}, -- SF Gym {x = 765.072, y = -76.6134, z = 1000.6563, dim = 13002, int = 7}, -- LV Gym }, ["fight"] = { {x = 761.3682, y = 5.5028, z = 1000.7098, dim = 13000, int = 5}, -- LS Gym {x = 768.0975, y = -37.4607, z = 1000.6865, dim = 13001, int = 6}, -- SF Gym {x = 766.7685, y = -62.0495, z = 1000.6563, dim = 13002, int = 7}, -- LV Gym } } local markers = {} function onMarkerHit(plr, matchingDimension) if (not plr or not isElement(plr) or plr.type ~= "player" or not matchingDimension) then return end local style for name, markers2 in pairs(markers) do for _, marker in ipairs(markers2) do if (source == marker) then style = name end end end if (not style) then return end triggerClientEvent(plr, "showStyleGUI", resourceRoot, style) end addEventHandler("onMarkerHit", root, onMarkerHit) for name, positions in pairs(markersData) do for _, data in ipairs(positions) do local marker = Marker(data.x, data.y, data.z-1, "cylinder", 2, 0, 255, 0) marker.dimension = data.dim marker.interior = data.int if (name == "fight") then marker:setColor(255, 0, 0, 255) end if (not markers[name]) then markers[name] = {} end table.insert(markers[name], marker) end end addEvent("buyStyle", true) addEventHandler("buyStyle", resourceRoot, function (style, name, price, id) if (style == "walk") then name = name.. "walking style" elseif (style == "fight") then name = name.." fighting style" end if (client.money >= price) then client.money = client.money - price if (style == "walk") then client.walkingStyle = id exports.UCDaccounts:SAD(client, "walkstyle", id) elseif (style == "fight") then client.fightingStyle = id --exports.UCDaccounts:SAD(client, "fightstyle", id) end exports.UCDdx:new(client, "You successfully bought "..name, 0, 255, 0) else exports.UCDdx:new(client, "You don't have enough money to buy "..name, 255, 0, 0) end end )
net.Receive("nutCharList", function() local newCharList = {} local length = net.ReadUInt(32) for i = 1, length do newCharList[i] = net.ReadUInt(32) end local oldCharList = nut.characters nut.characters = newCharList if (oldCharList) then hook.Run("CharacterListUpdated", oldCharList, newCharList) else hook.Run("CharacterListLoaded", newCharList) end end)
local command = require 'aula.core.command' local keymap = require 'aula.core.keymap' local M = {} local function reload() for name,_ in pairs(package.loaded) do if name:match('^aula') then package.loaded[name] = nil end end dofile(vim.env.MYVIMRC) print('[Aula] Config Reloaded!') end function M.setup() keymap.add('n', '<leader>vs', reload) command.add('ConfigReload', reload) end return M
AddCSLuaFile( "shared.lua" ) AddCSLuaFile( "cl_init.lua" ) include("shared.lua") function ENT:Initialize() self.health = 30 self.Entity:SetModel( "models/roller.mdl" ) self.Entity:PhysicsInit( SOLID_VPHYSICS ) self.Entity:SetMoveType( MOVETYPE_VPHYSICS ) self.Entity:SetSolid( SOLID_VPHYSICS ) util.SpriteTrail(self,CurTime(),Color(255,255,255,255), false, 15, 1, 2, 1/(15+1)*0.5, "darkland/fortwars/yellowglow1.vmt") self.potentialTargets = {} self.initPos = self.Entity:GetPos() self.phys = self.Entity:GetPhysicsObject() if self.phys:IsValid() then self.phys:Wake() self.phys:EnableGravity(false) self.phys:SetMass(1) end self:launch() timer.Simple(1.5,function() if IsValid(self) then self:findTarget() end end) end function ENT:PhysicsCollide(data, physobj) if IsValid(data.HitEntity) and data.HitEntity:IsPlayer() then data.HitEntity:TakeDamage( 30, self.Entity:GetOwner(), self ) if IsValid(self:GetOwner()) and self:GetOwner():Alive() and self:GetOwner():GetNWInt('energy') >= 50 then local ent = ents.Create("sent_pumpkin") ent:SetPos(self:GetOwner():GetPos()) ent:SetOwner(self:GetOwner()) ent.Team = self.Team ent.Owner = self.Owner // The weapon is the owner ent:SetAngles( self:GetOwner():EyeAngles() ) self:GetOwner():TakeEnergy(50) ent.LastHolder = self:GetOwner() ent:Spawn() //if IS_CHRISTMAS then // ent:EmitSound("darkland/fortwars/hohoho.wav") //else ent:EmitSound("darkland/fortwars/witchlaugh.wav") //end end end self:Remove() end function ENT:launch() //self.Entity:SetMoveType( MOVETYPE_VPHYSICS ) self:SetPos(self:GetOwner():GetShootPos()) self.phys:AddVelocity(self:GetOwner():GetAimVector()*1000) end function ENT:findTarget() local height local pos = self:GetPos() local others = ents.FindInSphere( pos, 500 ) for _, ent in pairs( others ) do height = 0 if IsValid(ent) then if ent:IsPlayer() then if ent:Crouching() then height = 30 else height = 50 end end local trace = { start = pos, endpos = ent:GetPos()+Vector(0,0,height), filter = self.Entity } local tr = util.TraceLine( trace ) if tr.Entity == ent and tr.Entity:IsPlayer() and tr.Entity:Team() != self.Team and !tr.Entity:GetNWBool("invis") then table.insert(self.potentialTargets, tr.Entity) end end end if table.Count(self.potentialTargets) < 1 then timer.Simple(1.5, function() if IsValid(self) then self:findTarget() end end) else self.target = self.potentialTargets[math.random(1,#self.potentialTargets)] //if IS_CHRISTMAS then // self:EmitSound("darkland/fortwars/hohoho.wav") //else self:EmitSound("darkland/fortwars/pumpkin.wav") // end end end function ENT:Think() if IsValid(self.target) and self.target:Alive() then local height = 30 if !self.target:Crouching() then height = 50 end self:SetAngles( ( ( self.target:GetPos()+ Vector(0,0,height) ) - self:GetPos() ):Angle()) self.phys:SetVelocity(self:GetForward()*750) // go 2x faster if you have a target else self.phys:SetVelocity(self:GetForward()*500) end if !Distance( self.initPos, self.phys:GetPos(), 2000) and table.Count(self.potentialTargets) < 1 then --self.initPos:Distance(self.phys:GetPos()) > 3000 and self:Remove() end end /*--------------------------------------------------------- More efficient way of seeing if two positions are less than a certain distance apart. ---------------------------------------------------------*/ function Distance(pos1, pos2, distance) if ((pos1.x - pos2.x)^2 + (pos1.y - pos2.y)^2 + (pos1.z - pos2.z)^2) < (distance^2) then return true else return false end end function ENT:OnTakeDamage(dmg) self.health = self.health - dmg:GetDamage() if self.health <= 0 then self:Remove() end end
--[[ ## Library Scroll ## Designed By DevDavis (Davis Nuñez) 2011 - 2018. Based on library of Robert Galarga. Create a obj scroll, this is very usefull for list show Modified by gdljjrod 2019 ]] function newScroll(a,b,c) local obj = {ini=1,sel=1,lim=1,maxim=0,minim=0} function obj:set(tab,mxn,modemintomin) -- Set a obj scroll obj.ini,obj.sel,obj.lim,obj.maxim,obj.minim, obj.mxn = 1,1,1,1,1,mxn if(type(tab)=="number")then if tab > mxn then obj.lim=mxn else obj.lim=tab end obj.maxim = tab else if #tab > mxn then obj.lim=mxn else obj.lim=#tab end obj.maxim = #tab end if modemintomin then obj.minim = obj.lim end end function obj:max(mx) obj.maxim = #mx end function obj:up() if obj.sel>obj.ini then obj.sel=obj.sel-1 return true elseif obj.ini-1>=obj.minim then obj.ini,obj.sel,obj.lim=obj.ini-1,obj.sel-1,obj.lim-1 return true end end function obj:down() if obj.sel<obj.lim then obj.sel=obj.sel+1 return true elseif obj.lim+1<=obj.maxim then obj.ini,obj.sel,obj.lim=obj.ini+1,obj.sel+1,obj.lim+1 return true end end function obj:delete(tab) table.remove(tab,obj.sel) if obj.ini == 1 then if obj.sel == obj.maxim then obj.sel-=1 end if #tab > obj.mxn then obj.lim = obj.mxn else obj.lim = #tab end else if obj.sel == obj.maxim then obj.sel,obj.ini,obj.lim = obj.sel-1,obj.ini-1,obj.lim-1 else if (#tab - obj.ini) + 1 < obj.mxn then obj.lim,obj.ini = obj.lim-1,obj.ini-1 end end end obj.maxim = #tab end if a and b then obj:set(a,b,c) end return obj end
local function test() local v="test" local function test2() print(v) end test2() return end local d=string.dump(test) io.write(d) test()
return {'vair','vaiaku'}
local enchantment = { elona = { random_tele = { description = "ランダムなテレポートを引き起こす" }, suck_blood = { description = "使用者の生き血を吸う" }, suck_exp = { description = "あなたの成長を妨げる" }, summon_monster = { description = "魔物を呼び寄せる" }, prevent_tele = { description = "テレポートを妨害する" }, res_blind = { description = "盲目を無効にする" }, res_paralyze = { description = "麻痺を無効にする" }, res_confuse = { description = "混乱を無効にする" }, res_fear = { description = "恐怖を無効にする" }, res_sleep = { description = "睡眠を無効にする" }, res_poison = { description = "毒を無効にする" }, res_steal = { description = "アイテムを盗まれなくする" }, eater = { description = "腐ったものを難なく消化させる" }, fast_travel = { description = "速度を上げ、ワールドマップでの移動時間を短くする" }, res_etherwind = { description = "エーテルの風からあなたを保護する" }, res_weather = { description = "雷雨と雪による足止めを無効にする" }, res_pregnancy = { description = "異物の体内への侵入を防ぐ" }, float = { description = "あなたを浮遊させる" }, res_mutation = { description = "あなたを変異から保護する" }, power_magic = { description = "魔法の威力を高める" }, see_invisi = { description = "透明な存在を見ることを可能にする" }, absorb_stamina = { description = "攻撃対象からスタミナを吸収する" }, ragnarok = { description = "全てを終結させる" }, absorb_mana = { description = "攻撃対象からマナを吸収する" }, pierce = { description = "完全貫通攻撃発動の機会を増やす" }, crit = { description = "クリティカルヒットの機会を増やす" }, extra_melee = { description = "追加打撃の機会を増やす" }, extra_shoot = { description = "追加射撃の機会を増やす" }, stop_time = { description = "稀に時を止める" }, res_curse = { description = "呪いの言葉から保護する" }, strad = { description = "演奏報酬の品質を上げる" }, damage_resistance = { description = "被る物理ダメージを軽減する" }, damage_immunity = { description = "被るダメージを稀に無効にする" }, damage_reflection = { description = "攻撃された時、相手に切り傷のダメージを与える" }, cure_bleeding = { description = "出血を抑える" }, god_talk = { description = "神が発する電波をキャッチする" }, dragon_bane = { description = "竜族に対して強力な威力を発揮する" }, undead_bane = { description = "不死者に対して強力な威力を発揮する" }, god_detect = { description = "他者の信仰を明らかにする" }, gould = { description = "深い音色で聴衆を酔わす" }, god_bane = { description = "神に対して強力な威力を発揮する" } } } return { _ = { base = { enchantment = enchantment } } }
function start (song) -- do nothing end function update (elapsed) -- example https://twitter.com/KadeDeveloper/status/1382178179184422918 if curStep > 496 then tweenCameraZoom(1.5,(crochet * 4) / 100) local currentBeat = (songPos / 496)*(bpm/150) for i=0,7 do setActorX(_G['defaultStrum'..i..'X'] + 25 * math.sin((currentBeat + i*0.5) * math.pi), i) setActorY(_G['defaultStrum'..i..'Y'] + 5 * math.cos((currentBeat + i*0.5) * math.pi), i) if curStep > 538 then tweenCameraZoom(1,(crochet * 1) / 50) end end end end function beatHit (beat) -- do nothing end function stepHit (step) end print("Mod Chart script loaded :)")
local register_node = minetest.register_node register_node('bt_core:blank_painting', { description = 'Blank Painting', tiles = { 'bt_core_blank_painting.png' }, paramtype = "light", paramtype2 = "facedir", drawtype = "mesh", groups = { choppy = 3 }, is_ground_content = true, selection_box = { type = "fixed", fixed = { {-0.4375, -0.5, -0.4375, 0.4375, -0.4375, 0.4375}, } }, mesh = 'bt_core_painting.obj', walkable = false, sounds = bt_sounds.wood_sounds, on_place = minetest.rotate_node }) register_node('bt_core:eggcorn_painting', { description = 'Painting', tiles = { 'bt_core_eggcorn_painting.png' }, paramtype = "light", paramtype2 = "facedir", drawtype = "mesh", groups = { choppy = 3 }, is_ground_content = true, selection_box = { type = "fixed", fixed = { {-0.4375, -0.5, -0.4375, 0.4375, -0.4375, 0.4375}, } }, mesh = 'bt_core_painting.obj', walkable = false, sounds = bt_sounds.wood_sounds, on_place = minetest.rotate_node }) register_node('bt_core:dragon_painting', { description = 'Painting', tiles = { 'bt_core_dragon_painting.png' }, paramtype = "light", paramtype2 = "facedir", drawtype = "mesh", groups = { choppy = 3 }, is_ground_content = true, selection_box = { type = "fixed", fixed = { {-0.4375, -0.5, -0.4375, 0.4375, -0.4375, 0.4375}, } }, mesh = 'bt_core_painting.obj', walkable = false, sounds = bt_sounds.wood_sounds, on_place = minetest.rotate_node })
ruRU_gossip_texts = { ["ezekiel said that you might have a certain book..."] = "Иезекииль говорит что у тебя есть кой какая книга...", ["get out of here, tobias, you're free!"] = "Вы свободны, Тобиас! Уходите!", ["i am ready to begin."] = "Я "..ST_G("готов", "готова")..".", ["i am ready, as are my forces. let us end this masquerade!"] = "Я "..ST_G("готов", "готова")..". Давайте положим конец этому маскараду!", ["i am ready, oronok. let us destroy cyrukh and free the elements!"] = "Я "..ST_G("готов", "готова")..", Оронок. Давайте уничтожим Цируха и освободим элементалей!", ["i cannot, vaelastrasz! surely something can be done to heal you!"] = "Не могу, Валестраз! Ведь есть же какой-то способ тебя вылечить!", ["i need a moment of your time, sir."] = "Мне нужна минута вашего времени, сэр.", ["i've made no mistakes."] = "Я не "..ST_G("сделал", "сделала").." ни одной ошибки.", ["let marshal windsor know that i am ready."] = "Дай знать маршалу Виндзору что я "..ST_G("готов", "готова")..".", ["let the event begin!"] = "Идем.", ["let's find out."] = "Давай разберемся.", ["let's see what you have."] = "Давай посмотрим, что у тебя есть.", ["please do."] = "Давай.", ["please unlock the courtyard door."] = "Открой дверь во внутренний двор.", ["tell me more."] = "Продолжай.", ["turn the key to start the machine."] = "Повернуть ключ, чтобы запустить машину.", ["vaelastrasz, no!!!"] = "Валестраз, нет!!!", ["what else do you have to say?"] = "Что еще вы хотели сказать?", ["why don't you and rocknot go find somewhere private..."] = "Почему бы вам с Камнеузлом не пойти и найти какое-нибудь укромное место...", ["why... yes, of course. i've something to show you right inside this building, mr. anvilward."] = "Почему... да, конечно. Я "..ST_G("хотел", "хотела").." бы что-то показать внутри этого здания, мистер Наковальня.", ["you challenged us and we have come. where is this master you speak of?"] = "Ты бросил нам вызов, и мы пришли. Где тот господин, о котором ты говорил?", ["you have lost your mind, nefarius. you speak in riddles."] = "Ты совсем свихнулся, Нефарий. Ты разговариваешь загадками.", ["you're free, dughal! get out of here!"] = "Вы свободны, Дугал! Уходите!", ["your bondage is at an end, doom'rel. i challenge you!"] = "Кончилось твое заточение, Рок’рел. Вызываю тебя на бой!", ["[ph] sd2 unknown text"] = "[PH] SD2 неизвестный текст", }
return LoadFont("BPMDisplay", "bpm") .. { Text="BPM"; };
-- Implements virtio virtq module(...,package.seeall) local buffer = require("core.buffer") local freelist = require("core.freelist") local lib = require("core.lib") local memory = require("core.memory") local ffi = require("ffi") local C = ffi.C local band = bit.band local rshift = bit.rshift require("lib.virtio.virtio.h") require("lib.virtio.virtio_vring_h") --[[ --]] local vring_desc_ptr_t = ffi.typeof("struct vring_desc *") VirtioVirtq = {} function VirtioVirtq:new() local o = {} return setmetatable(o, {__index = VirtioVirtq}) end -- support indirect descriptors function VirtioVirtq:get_desc(header_id) local ring_desc = self.virtq.desc local device = self.device local desc, id -- Indirect desriptors if band(ring_desc[header_id].flags, C.VIRTIO_DESC_F_INDIRECT) == 0 then desc = ring_desc id = header_id else local addr = device.map_from_guest(device,ring_desc[header_id].addr) desc = ffi.cast(vring_desc_ptr_t, addr) id = 0 end return desc, id end -- Receive all available packets from the virtual machine. function VirtioVirtq:get_buffers (kind, ops) local ring = self.virtq.avail.ring local device = self.device local idx = self.virtq.avail.idx local avail, vring_mask = self.avail, self.vring_num-1 while idx ~= avail do -- Header local v_header_id = ring[band(avail,vring_mask)] local desc, id = self:get_desc(v_header_id) local data_desc = desc[id] local header_id, header_pointer, header_len, total_size, packet = ops.packet_start(device, v_header_id, data_desc.addr, data_desc.len) local buf -- support ANY_LAYOUT if header_len < data_desc.len then local addr = data_desc.addr + header_len local len = data_desc.len - header_len buf, total_size = ops.buffer_add(device, packet, addr, len, total_size) end -- Data buffer while band(data_desc.flags, C.VIRTIO_DESC_F_NEXT) ~= 0 do data_desc = desc[data_desc.next] buf, total_size = ops.buffer_add(device, packet, data_desc.addr, data_desc.len, total_size) end ops.packet_end(device, header_id, header_pointer, total_size, packet, buf) avail = band(avail + 1, 65535) end self.avail = avail end function VirtioVirtq:put_buffer (id, len) local used = self.virtq.used.ring[band(self.used, self.vring_num-1)] used.id, used.len = id, len self.used = band(self.used + 1, 65535) end -- Prepared argument for writing a 1 to an eventfd. local eventfd_one = ffi.new("uint64_t[1]", {1}) function VirtioVirtq:signal_used() if self.virtq.used.idx ~= self.used then self.virtq.used.idx = self.used if band(self.virtq.avail.flags, C.VRING_F_NO_INTERRUPT) == 0 then C.write(self.callfd, eventfd_one, 8) end end end
AddCSLuaFile() -- Base info SWEP.Base = "rp_base_grenade" -- Spawnmenu info SWEP.Category = "Roleplay Weapons" SWEP.Spawnable = true SWEP.AdminOnly = true SWEP.DisableDuplicator = true -- Weapon selection menu info SWEP.AutoSwitchFrom = false SWEP.AutoSwitchTo = false -- Print info SWEP.PrintName = "Flashbang" SWEP.Author = "Arkten" -- Viewport info SWEP.ViewModel = "models/weapons/cstrike/c_eq_flashbang.mdl" SWEP.WorldModel = "models/weapons/w_eq_flashbang.mdl" -- Misc info SWEP.Primary.Ammo = "Flashbang" SWEP.GrenadeType = "rp_ent_flash" -- Weapon icon info if CLIENT then SWEP.WepSelectIcon = surface.GetTextureID("weapons/flash") end
---@class lstg.mbg.PointF local M = class('lstg.mbg.PointF') function M:ctor(x, y) self.X = x or 0 self.Y = y or 0 end return M
local M = {} function M.c3b(hex) local b = bit.band(hex, 0xff) hex = bit.rshift(hex, 8) local g = bit.band(hex, 0xff) hex = bit.rshift(hex, 8) local r = bit.band(hex, 0xff) return cc.c3b(r, g, b) end function M.c4b(hex, alpha) local c3 = M.c3b(hex) alpha = alpha or 0xff return cc.c4b(c3.r, c3.g, c3.b, alpha) end function M.c4f(hex, alpha) local c3 = M.c3b(hex) alpha = alpha or 0xff return cc.c4f(c3.r/255.0, c3.g/255.0, c3.b/255.0, alpha/255.0) end function M.randc3b() return cc.c3b(math.random(0, 255), math.random(0, 255), math.random(0, 255)) end function M.randc4b(alpha) alpha = alpha or math.random(0, 255) return cc.c4b(math.random(0, 255), math.random(0, 255), math.random(0, 255), alpha) end return M
local app = app local libcore = require "core.libcore" local Class = require "Base.Class" local Unit = require "Unit" local Fader = require "Unit.ViewControl.Fader" local Encoder = require "Encoder" local MicroDelay = Class {} MicroDelay:include(Unit) function MicroDelay:init(args) args.title = "uDelay" args.mnemonic = "uD" Unit.init(self, args) end function MicroDelay:onLoadGraph(channelCount) if channelCount == 2 then self:loadStereoGraph() else self:loadMonoGraph() end end function MicroDelay:loadMonoGraph() local delayL = self:addObject("delayL", libcore.MicroDelay(0.1)) connect(self, "In1", delayL, "In") connect(delayL, "Out", self, "Out1") end function MicroDelay:loadStereoGraph() local delayL = self:addObject("delayL", libcore.MicroDelay(0.1)) local delayR = self:addObject("delayR", libcore.MicroDelay(0.1)) connect(self, "In1", delayL, "In") connect(self, "In2", delayR, "In") connect(delayL, "Out", self, "Out1") connect(delayR, "Out", self, "Out2") tie(delayR, "Delay", delayL, "Delay") end local views = { expanded = { "delay" }, collapsed = {} } function MicroDelay:onLoadViews(objects, branches) local controls = {} controls.delay = Fader { button = "delay", description = "Delay", param = objects.delayL:getParameter("Delay"), map = Encoder.getMap("[0,0.1]"), units = app.unitSecs } return controls, views end return MicroDelay
local M = {} M.config = function () require'nvim-treesitter.configs'.setup { ensure_installed = 'maintained', highlight = { enable = true }, incremental_selection = { enable = true }, textobjects = { enable = true }, rainbow = { enable = true, extended_mode = false, max_file_lines = nil } } end return M
local export = {} local gsub = mw.ustring.gsub local sub = mw.ustring.sub local match = mw.ustring.match local system_list = { { 1, ["type"] = "phonetic", ["name"] = "IPA" }, { 2, ["type"] = "orthographic", ["name"] = "MLCTS" }, { 3, ["type"] = "orthographic", ["name"] = "ALA-LC" }, { 4, ["type"] = "phonetic", ["name"] = "BGN/PCGN" }, { 5, ["type"] = "phonetic", ["name"] = "Okell" }, } local initial_table = { ["က"] = { "k", "k", "k", "k", "k" }, ["ကျ"] = { "t͡ɕ", "ky", "ky", "ky", "c" }, ["ကြ"] = { "t͡ɕ", "kr", "kr", "ky", "c" }, ["ကျွ"] = { "t͡ɕw", "kyw", "kyv", "kyw", "cw" }, ["ကြွ"] = { "t͡ɕw", "krw", "krv", "kyw", "cw" }, ["ကွ"] = { "kw", "kw", "kv", "kw", "kw" }, ["ခ"] = { "kʰ", "hk", "kh", "hk", "hk" }, ["ချ"] = { "t͡ɕʰ", "hky", "khy", "ch", "hc" }, ["ခြ"] = { "t͡ɕʰ", "hkr", "khr", "ch", "hc" }, ["ချွ"] = { "t͡ɕʰw", "hkyw", "khyv", "chw", "hcw" }, ["ခြွ"] = { "t͡ɕʰw", "hkrw", "khrv", "chw", "hcw" }, ["ခွ"] = { "kʰw", "hkw", "khv", "hkw", "hkw" }, ["ဂ"] = { "ɡ", "g", "g", "g", "g" }, ["ဂျ"] = { "d͡ʑ", "gy", "gy", "gy", "j" }, ["ဂြ"] = { "d͡ʑ", "gr", "gr", "gy", "j" }, ["ဂျွ"] = { "d͡ʑw", "gyw", "gyv", "gyw", "jw" }, ["ဂွ"] = { "ɡw", "gw", "gv", "gw", "gw" }, ["ဃ"] = { "ɡ", "gh", "gh", "g", "g" }, ["င"] = { "ŋ", "ng", "ṅ", "ng", "ng" }, ["ငှ"] = { "ŋ̊", "hng", "ṅh", "hng", "hng" }, ["ငြ"] = { "ɲ", "ngr", "ṅr", "ny", "ny" }, ["ငြှ"] = { "ɲ̊", "hngr", "ṅrh", "hny", "hny" }, ["ငွ"] = { "ŋw", "ngw", "ṅv", "ngw", "ngw" }, ["ငွှ"] = { "ŋ̊w", "hngw", "ṅvh", "hngw", "hngw" }, ["စ"] = { "s", "c", "c", "s", "s" }, ["စွ"] = { "sw", "cw", "cv", "sw", "sw" }, ["ဆ"] = { "sʰ", "hc", "ch", "hs", "hs" }, ["ဆွ"] = { "sʰw", "hcw", "chv", "hsw", "hsw" }, ["ဇ"] = { "z", "j", "j", "z", "z" }, ["ဇွ"] = { "zw", "jw", "jv", "zw", "zw" }, ["ဈ"] = { "z", "jh", "jh", "z", "z" }, ["ဉ"] = { "ɲ", "ny", "ñ", "ny", "ny" }, ["ည"] = { "ɲ", "ny", "ññ", "ny", "ny" }, ["ဉှ"] = { "ɲ̊", "hny", "ñh", "hny", "hny" }, ["ညှ"] = { "ɲ̊", "hny", "ññh", "hny", "hny" }, ["ညွ"] = { "ɲw", "nyw", "ñv", "nyw", "nyw" }, ["ညွှ"] = { "ɲ̊w", "hnyw", "ñvh", "hnyw", "hnyw" }, ["ဋ"] = { "t", "t", "ṭ", "t", "t" }, ["ဌ"] = { "tʰ", "ht", "ṭh", "ht", "ht" }, ["ဍ"] = { "d", "d", "ḍ", "d", "d" }, ["ဎ"] = { "d", "dh", "ḍh", "d", "d" }, ["ဏ"] = { "n", "n", "ṇ", "n", "n" }, ["ဏှ"] = { "n̥", "hn", "ṇh", "hn", "hn" }, ["တ"] = { "t", "t", "t", "t", "t" }, ["တျ"] = { "tj", "ty", "ty", "ty", "ty" }, ["တြ"] = { "tɹ", "tr", "tr", "tr", "tr" }, ["တွ"] = { "tw", "tw", "tv", "tw", "tw" }, ["ထ"] = { "tʰ", "ht", "th", "ht", "ht" }, ["ထွ"] = { "tʰw", "htw", "thv", "htw", "htw" }, ["ဒ"] = { "d", "d", "d", "d", "d" }, ["ဒျ"] = { "dj", "dy", "dy", "dy", "dy" }, ["ဒြ"] = { "dɹ", "dr", "dr", "dr", "dr" }, ["ဒွ"] = { "dw", "dw", "dv", "dw", "dw" }, ["ဓ"] = { "d", "dh", "dh", "d", "d" }, ["န"] = { "n", "n", "n", "n", "n" }, ["နှ"] = { "n̥", "hn", "nh", "hn", "hn" }, ["နျ"] = { "nj", "ny", "ny", "ny", "ny" }, ["နွ"] = { "nw", "nw", "nv", "nw", "nw" }, ["နွှ"] = { "n̥w", "hnw", "nvh", "hnw", "hnw" }, ["ပ"] = { "p", "p", "p", "p", "p" }, ["ပျ"] = { "pj", "py", "py", "py", "py" }, ["ပြ"] = { "pj", "pr", "pr", "py", "py" }, ["ပြွ"] = { "pw", "prw", "prv", "pw", "pw" }, ["ပွ"] = { "pw", "pw", "pv", "pw", "pw" }, ["ဖ"] = { "pʰ", "hp", "ph", "hp", "hp" }, ["ဖျ"] = { "pʰj", "hpy", "phy", "hpy", "hpy" }, ["ဖြ"] = { "pʰj", "hpr", "phr", "hpy", "hpy" }, ["ဖွ"] = { "pʰw", "hpw", "phv", "hpw", "hpw" }, ["ဗ"] = { "b", "b", "b", "b", "b" }, ["ဗျ"] = { "bj", "by", "by", "by", "by" }, ["ဗြ"] = { "bj", "br", "br", "by", "by" }, ["ဗွ"] = { "bw", "bw", "bv", "bw", "bw" }, ["ဘ"] = { "b", "bh", "bh", "b", "b" }, ["-ဘ"] = { "pʰ", "bh", "bh", "hp", "hp" }, ["ဘွ"] = { "bw", "bhw", "bhv", "bw", "bw" }, ["-ဘွ"] = { "pʰw", "bhw", "bhw", "hpw", "hpw" }, ["မ"] = { "m", "m", "m", "m", "m" }, ["မှ"] = { "m̥", "hm", "mh", "hm", "hm" }, ["မျ"] = { "mj", "my", "my", "my", "my" }, ["မျှ"] = { "m̥j", "hmy", "myh", "hmy", "hmy" }, ["မြ"] = { "mj", "mr", "mr", "my", "my" }, ["မြှ"] = { "m̥j", "hmr", "mrh", "hmy", "hmy" }, ["မြွ"] = { "mjw", "mrw", "mrv", "myw", "myw" }, ["မြွှ"] = { "m̥w", "hmrw", "mrvh", "hmw", "hmw" }, ["မွ"] = { "mw", "mw", "mv", "mw", "mw" }, ["မွှ"] = { "m̥w", "hmw", "mvh", "hmw", "hmw" }, ["ယ"] = { "j", "y", "y", "y", "y" }, ["ယှ"] = { "ʃ", "hy", "yh", "sh", "hy" }, ["သျှ"] = { "ʃ", "hsy", "syh", "sh", "hy" }, ["ယွ"] = { "jw", "yw", "yv", "yw", "yw" }, ["ရ"] = { "j", "r", "r", "y", "y" }, ["*ရ"] = { "ɹ", "r", "r", "r", "r" }, ["ရှ"] = { "ʃ", "hr", "rh", "sh", "hy" }, ["ရွ"] = { "jw", "rw", "rv", "yw", "yw" }, ["ရွှ"] = { "ʃw", "hrw", "rvh", "shw", "hyw" }, ["လ"] = { "l", "l", "l", "l", "l" }, ["လှ"] = { "l̥", "hl", "lh", "hl", "hl" }, ["လျ"] = { "j", "ly", "ly", "y", "y" }, ["+သျှ"] = { "j", "hsy", "syh", "y", "y" }, ["*လျ"] = { "lj", "ly", "ly", "ly", "ly" }, ["လျှ"] = { "ʃ", "hly", "lyh", "sh", "hy" }, ["*လျှ"] = { "l̥j", "hly", "lyh", "hly", "hly" }, ["လွ"] = { "lw", "lw", "lv", "lw", "lw" }, ["လွှ"] = { "l̥w", "hlw", "lvh", "hlw", "hlw" }, ["ဝ"] = { "w", "w", "v", "w", "w" }, ["ဝှ"] = { "ʍ", "hw", "vh", "hw", "hw" }, ["သ"] = { "θ", "s", "s", "th", "th" }, ["+သ"] = { "ð", "s", "s", "dh", "th" }, ["သွ"] = { "θw", "sw", "sv", "thw", "thw" }, ["+သွ"] = { "ðw", "sw", "sw", "dhw", "thw" }, ["ဟ"] = { "h", "h", "h", "h", "h" }, ["ဟွ"] = { "hw", "hw", "hv", "hw", "hw" }, ["ဠ"] = { "l", "l", "ḷ", "l", "l" }, ["အ"] = { "ʔ", "", "ʼ", "", "" }, -- only appears after a vowel in the same word ["ဿ"] = { "ʔθ", "ss", "ss", "tth", "ʔth" }, [""] = { "ʔ", "", "", "", "" }, ["-"] = { "", "", "", "", "" }, ["ျ"] = { nil, "y", "y", nil, nil }, ["ြ"] = { nil, "r", "r", nil, nil }, ["ွ"] = { nil, "w", "w", nil, nil }, } local initial_voicing = { ["+က"] = "ဂ", ["+ခ"] = "ဂ", ["+စ"] = "ဇ", ["+ဆ"] = "ဇ", ["+ဋ"] = "ဍ", ["+ဌ"] = "ဍ", ["+တ"] = "ဒ", ["+ထ"] = "ဒ", ["+ပ"] = "ဗ", ["+ဖ"] = "ဗ", ["-ဘ"] = "ဖ", } local final_table = { [""] = { "a̰", "a.", "a", "a.", "á" }, ["က်"] = { "ɛʔ", "ak", "akʻ", "et", "eʔ" }, ["င်"] = { "ɪ̀ɴ", "ang", "aṅʻ", "in", "iñ" }, ["စ်"] = { "ɪʔ", "ac", "acʻ", "it", "iʔ" }, ["ည်"] = { "ì", "any", "aññʻ", "i", "i" }, ["ည်2"] = { "è", "any", "aññʻ", "e", "ei" }, ["ည်3"] = { "ɛ̀", "any", "aññʻ", "è", "e" }, ["ဉ်"] = { "ɪ̀ɴ", "any", "añʻ", "in", "iñ" }, ["တ်"] = { "aʔ", "at", "atʻ", "at", "aʔ" }, ["န်"] = { "àɴ", "an", "anʻ", "an", "añ" }, ["ပ်"] = { "aʔ", "ap", "apʻ", "at", "aʔ" }, ["မ်"] = { "àɴ", "am", "amʻ", "an", "añ" }, ["ယ်"] = { "ɛ̀", "ai", "ayʻ", "è", "e" }, ["ံ"] = { "àɴ", "am", "aṃ", "an", "añ" }, ["ာ"] = { "à", "a", "ā", "a", "a" }, ["ါ"] = { "à", "a", "ā", "a", "a" }, ["ိ"] = { "ḭ", "i.", "i", "i.", "í" }, ["ိတ်"] = { "eɪʔ", "it", "itʻ", "eik", "eiʔ" }, ["ိန်"] = { "èɪɴ", "in", "inʻ", "ein", "eiñ" }, ["ိပ်"] = { "eɪʔ", "ip", "ipʻ", "eik", "eiʔ" }, ["ိမ်"] = { "èɪɴ", "im", "imʻ", "ein", "eiñ" }, ["ိံ"] = { "èɪɴ", "im", "iṃ", "ein", "eiñ" }, ["ီ"] = { "ì", "i", "ī", "i", "i" }, ["ု"] = { "ṵ", "u.", "u", "u.", "ú" }, ["ုတ်"] = { "oʊʔ", "ut", "utʻ", "ok", "ouʔ" }, ["ုန်"] = { "òʊɴ", "un", "unʻ", "on", "ouñ" }, ["ုပ်"] = { "oʊʔ", "up", "upʻ", "ok", "ouʔ" }, ["ုမ်"] = { "òʊɴ", "um", "umʻ", "on", "ouñ" }, ["ုံ"] = { "òʊɴ", "um", "uṃ", "on", "ouñ" }, ["ူ"] = { "ù", "u", "ū", "u", "u" }, ["ေ"] = { "è", "e", "e", "e", "ei" }, ["ဲ"] = { "ɛ́", "ai:", "ai", "è:", "è" }, ["ော"] = { "ɔ́", "au:", "o", "aw:", "ò" }, ["ောက်"] = { "aʊʔ", "auk", "okʻ", "auk", "auʔ" }, ["ောင်"] = { "àʊɴ", "aung", "oṅʻ", "aung", "auñ" }, ["ော်"] = { "ɔ̀", "au", "oʻ", "aw", "o" }, ["ို"] = { "ò", "ui", "ui", "o", "ou" }, ["ိုက်"] = { "aɪʔ", "uik", "uikʻ", "aik", "aiʔ" }, ["ိုင်"] = { "àɪɴ", "uing", "uiṅʻ", "aing", "aiñ" }, ["ွတ်"] = { "ʊʔ", "wat", "vatʻ", "ut", "uʔ" }, ["ွန်"] = { "ʊ̀ɴ", "wan", "vanʻ", "un", "uñ" }, ["ွပ်"] = { "ʊʔ", "wap", "vapʻ", "ut", "uʔ" }, ["ွမ်"] = { "ʊ̀ɴ", "wam", "vamʻ", "un", "uñ" }, ["ွံ"] = { "ʊ̀ɴ", "wam", "vaṃ", "un", "uñ" }, ["'"] = { "ə", "a", "a", "ă", "ă" }, ["်"] = { "", "", "ʻ", "", "" }, } local nucleus_table = { [""] = { "à", "a", "a", "a", "a" }, ["ိ"] = { "ì", "i", "i", "i", "i" }, ["ု"] = { "ù", "u", "u", "u", "u" }, ["ော"] = { "ɔ̀", "au", "o", "aw", "o" }, ["ေါ"] = { "ɔ̀", "au", "o", "aw", "o" }, ["ွ"] = { "ʊ̀", "wa", "va", "u", "u" }, } local indep_letter_table = { ["ဣ"] = { "ḭ", "i.", "i", "i.", "í" }, ["ဤ"] = { "ì", "i", "ī", "i", "i" }, ["ဥ"] = { "ṵ", "u.", "u", "u.", "ú" }, ["ဦ"] = { "ù", "u", "ū", "u", "u" }, ["ဧ"] = { "è", "e", "e", "e", "ei" }, ["၏"] = { "ɛ̰", "e", "e*", "è.", "é" }, ["ဩ"] = { "ɔ́", "au:", "o", "aw:", "ò" }, ["ဪ"] = { "ɔ̀", "au", "oʻ", "aw", "o" }, ["၌"] = { "n̥aɪʔ", "hnai.", "n*", "hnaik", "hnaiʔ" }, ["၍"] = { "jwḛ", "rwe", "r*", "ywe.", "yweí" }, } local tone_table = { ["း"] = { "́", ":", "ʺ", ":", "̀" }, ["့"] = { "̰", ".", "ʹ", ".", "́" }, } local ambig_intersyl = { [1] = { }, [2] = { ["ky"] = 1, ["kr"] = 1, ["kw"] = 1, ["gy"] = 1, ["gr"] = 1, ["gw"] = 1, ["ng"] = 1, ["ny"] = 1, ["cw"] = 1, ["tw"] = 1, ["nw"] = 1, ["py"] = 1, ["pr"] = 1, ["pw"] = 1, ["my"] = 1, ["mr"] = 1, ["mw"] = 1, }, [3] = { }, [4] = { ["ky"] = 1, ["kr"] = 1, ["kw"] = 1, ["gy"] = 1, ["gr"] = 1, ["gw"] = 1, ["ng"] = 1, ["ny"] = 1, ["cw"] = 1, ["tw"] = 1, ["nw"] = 1, ["tr"] = 1, ["tw"] = 1, ["py"] = 1, ["pr"] = 1, ["pw"] = 1, ["my"] = 1, ["mr"] = 1, ["mw"] = 1, }, [5] = { ["ou"] = 1, }, } local reverse_table = { ["hm"] = "မှ", ["m"] = "မ", ["hn"] = "နှ", ["n"] = "န", ["hny"] = "ညှ", ["ny"] = "ည", ["hng"] = "ငှ", ["ng"] = "င", ["p"] = "ပ", ["hp"] = "ဖ", ["b"] = "ဗ", ["t"] = "တ", ["ht"] = "ထ", ["d"] = "ဒ", ["c"] = "ကျ", ["hc"] = "ချ", ["j"] = "ဂျ", ["k"] = "က", ["hk"] = "ခ", ["g"] = "ဂ", [""] = "အ", ["th"] = "သ", ["+th"] = "+သ", ["s"] = "စ", ["hs"] = "ဆ", ["z"] = "ဇ", ["hy"] = "ရှ", ["h"] = "ဟ", ["r"] = "*ရ", ["y"] = "ယ", ["hw"] = "ဝှ", ["w"] = "ဝ", ["hl"] = "လှ", ["l"] = "လ", ["hmw"] = "မွှ", ["mw"] = "မွ", ["hmy"] = "မျှ", ["my"] = "မျ", ["hnw"] = "နွှ", ["nw"] = "နွ", ["hnyw"] = "ညွှ", ["nyw"] = "ညွ", ["hngw"] = "ငွှ", ["ngw"] = "ငွ", ["pw"] = "ပွ", ["hpw"] = "ဖွ", ["bw"] = "ဗွ", ["py"] = "ပျ", ["hpy"] = "ဖျ", ["by"] = "ဗျ", ["tw"] = "တွ", ["htw"] = "ထွ", ["dw"] = "ဒွ", ["cw"] = "ကျွ", ["hcw"] = "ချွ", ["jw"] = "ဂျွ", ["kw"] = "ကွ", ["hkw"] = "ခွ", ["gw"] = "ဂွ", ["thw"] = "သွ", ["sw"] = "စွ", ["hsw"] = "ဆွ", ["zw"] = "ဇွ", ["hyw"] = "ရွှ", ["hw"] = "ဟွ", ["yw"] = "ယွ", ["hlw"] = "လွှ", ["lw"] = "လွ", ["hly"] = "*လျှ", ["ly"] = "*လျ", ["i"] = "ီ", ["i\\"] = "ီး", ["i/"] = "ိ", ["i?"] = "စ်", ["i~"] = "င်", ["i\\~"] = "င်း", ["i/~"] = "င့်", ["ei"] = "ေ", ["ei\\"] = "ေး", ["ei/"] = "ေ့", ["ei?"] = "ိတ်", ["ei~"] = "ိန်", ["ei\\~"] = "ိန်း", ["ei/~"] = "ိန့်", ["e"] = "ယ်", ["e\\"] = "ဲ", ["e/"] = "ယ့်", ["e?"] = "က်", ["ai~"] = "ိုင်", ["ai\\~"] = "ိုင်း", ["ai/~"] = "ိုင့်", ["ai?"] = "ိုက်", ["a"] = "ာ", ["a\\"] = "ား", ["a/"] = "", ["a?"] = "တ်", ["a~"] = "န်", ["a\\~"] = "န်း", ["a/~"] = "န့်", ["o"] = "ော်", ["o\\"] = "ော", ["o/"] = "ော့", ["au?"] = "ောက်", ["au~"] = "ောင်", ["au\\~"] = "ောင်း", ["au/~"] = "ောင့်", ["ou"] = "ို", ["ou\\"] = "ိုး", ["ou/"] = "ို့", ["ou?"] = "ုပ်", ["ou~"] = "ုန်", ["ou\\~"] = "ုန်း", ["ou/~"] = "ုန့်", ["u"] = "ူ", ["u\\"] = "ူး", ["u/"] = "ု", ["u?"] = "ွတ်", ["u~"] = "ွန်", ["u\\~"] = "ွန်း", ["u/~"] = "ွန့်", ["a'"] = "'", } local repl_string = "([ကခဂဃငစဆဇဈဉညဋဌဍဎဏတထဒဓနပဖဗဘမယရလဝသဟဠအဿ][ျြွှ]*[ံ့းွာါါိီုူေဲ]*)([ကခဂဃငစဆဇဈဉညဋဌဍဎဏတထဒဓနပဖဗဘမယရလဝသဟဠအဿ][့]?[^့်္])" function syllabify(text) text = gsub(text, "('?)([%+%-%*]*)", function(a, b) if a .. b ~= "" then return a .. " " .. b end end) text = gsub(text, "([ဣဤဥဦဧဩဪ၏၌၍][့း်]?)(.?)(.?)", function(a, b, c) return (c == "္" and " "..a..b.." "..c or (c == "်" and " "..a..b..c or " "..a.." "..b..c)) end) .. " " text = gsub(text, "(်း?'?)", "%1 ") text = gsub(text, "([း့])([ကခဂဃငစဆဇဈဉညဋဌဍဎဏတထဒဓနပဖဗဘမယရလဝသဟဠအ]်)", "%2%1") while match(text, repl_string) do text = gsub(text, repl_string, "%1 %2") end text = gsub(text, "္", " , ") text = gsub(text, " +", " ") text = gsub(text, "^ ?(.*[^ ]) ?$", "%1") text = gsub(text, " , ", " ") text = gsub(text, " ([23])", "%1") return text end function initial_by_char(initial_string, system_index, ref_table) local initial_set = {} for character in mw.text.gsplit(initial_string, "") do local temp_initial = ref_table[character] or error("Initial data not found.") table.insert(initial_set, temp_initial[system_index] or temp_initial) end return table.concat(initial_set) end function generate_respelling(text) text = gsub(text, " ", "   ") text = gsub(text, "ါ", "ာ") if match(text, "[က-႟ꩠ-ꩻ]") then return text end text = gsub(text, "(%+?)([^%?%+'/\\~aeiou ]*)(/?)([%?'/\\~aeiou]+)", function(voicing_mark, latin_initial, opt_sep, latin_final) return voicing_mark .. (reverse_table[latin_initial] or initial_by_char(latin_initial, nil, reverse_table)) .. opt_sep .. reverse_table[latin_final] end) return text end function process(initial, final, tone, schwa, system, system_index) if match(initial .. final, "ွှ?[တနပမံ]") and system["type"] == "phonetic" then initial = gsub(initial, "[ွ/]", "") final = "ွ" .. final else initial = gsub(initial, "/", "") end initial_new = system["type"] == "phonetic" and gsub(initial, "%+.", initial_voicing) or initial if indep_letter_table[initial_new] then initial_new = match(initial_new, "[၌၍]") and "-" or "" final = initial .. final end if initial_new == "မြွ" then require('debug').track('my-pron/mrw') end initial_data = initial_table[initial_new] or initial_table[gsub(initial_new, "[%+%-%*]", "")] or (system["type"] == "orthographic" and initial_by_char(initial_new, system_index, initial_table) or error("Initial data not found.")) initial_value = initial_data[system_index] or initial_data if match(initial, "^%+") and system_index == 5 then initial_value = initial_table[gsub(initial, "%+", "")][system_index] initial_value = gsub(initial_value, "^([^rwy]+)", "<u>%1</u>") end final_data = final_table[system["type"] .. schwa == "phonetic'" and schwa or final] or (system["type"] == "phonetic" and (final_table[final .. "်"] or indep_letter_table[final]) or indep_letter_table[final]) or gsub(final, "^([^်]*)([^်])(်?)$", function(first, second, third) first_data = nucleus_table[first] or final_table[first] or indep_letter_table[first] or first second_data = initial_table[second] or second first = first_data ~= first and first_data[system_index] or first second = second_data ~= second and second_data[system_index] .. ((system_index == 3 and third ~= "") and "ʻ" or "") or second return (gsub(first .. second, "([%.:])(.*)", "%2")) end) final_value = type(final_data) == "table" and final_data[system_index] or final_data final_value = mw.ustring.toNFD(final_value) if tone == "" then tone_value = "" else if system_index ~= 4 then final_value = gsub(final_value, "̀", "") end final_value = gsub(final_value, "[́:%.]", "") if system["type"] .. schwa == "phonetic'" then tone_value = "" else tone_data = tone_table[tone] or error("Tone data not found.") tone_value = tone_data[system_index] end end if system_index == 1 then final_value = gsub(final_value, "^([aeəɛiɪoɔuʊ])", "%1" .. tone_value) elseif system_index == 5 then final_value = gsub(final_value, "([aeiou])([^aeiou]*)$", "%1" .. tone_value .. "%2") else final_value = final_value .. tone_value end return mw.ustring.toNFC(initial_value .. final_value) end function remove_wide_space(text) return (gsub(text, " ", "")) end function concatenate(set, system_index) if system_index == 1 then return remove_wide_space(table.concat(set)) end result_text = remove_wide_space(table.concat(set, " ")) for count = 1, 3 do result_text = gsub(result_text, "(.) (.)([^ ]?)", function(previous, next, after_next) if ambig_intersyl[system_index][previous .. next] or ((system_index == 2 or system_index == 4) and (match(previous .. " " .. next, "[ptkgmngy] [aeiou]") or (match(previous .. next .. after_next, "[aeiou][ptkmn][rwyg]") and not match(after_next, "[aeiou]")))) then return previous .. "-" .. next .. after_next else return previous .. next .. after_next end end) end return result_text end function export.get_romanisation(word, pronunciations, system, system_index, mode) local sentences = {} word = gsub(word, " ", "|") if system["type"] == "phonetic" then word = gsub(word, "ဿ", "တ်သ") end word = syllabify(word) word = gsub(word, "ါ", "ာ") if system["type"] == "phonetic" then word = gsub(word, "ဝ([တနပမံ])", "ဝွ%1") end for phrase in mw.text.gsplit(word, "|", true) do local temp = {} local syllable = mw.text.split(phrase, " ", true) for syllable_index = 1, #syllable do syllable[syllable_index] = gsub(syllable[syllable_index], "([း့])(်)", "%2%1") temp[syllable_index] = gsub( syllable[syllable_index], "^([%+%-%*]*[ကခဂဃငစဆဇဈဉညဋဌဍဎဏတထဒဓနပဖဗဘမယရလဝသဟဠအဣဤဥဦဧဩဪ၏၌၍ဿ][ျြ]?ွ?ှ?/?)([^း့']*)([း့]?)('?)$", function(initial, final, tone, schwa) return process(initial, final, tone, schwa, system, system_index) end) end table.insert(sentences, concatenate(temp, system_index)) end if mode == "translit_module" then return table.concat(sentences, " ") end table.insert(pronunciations[system_index], table.concat(sentences, " ")) return pronunciations[system_index] end function respelling_format(phonetic, page_title) local page_title_set = mw.text.split(syllabify(page_title), " ") local new_respellings = {} for _, respelling in ipairs(phonetic) do local respelling_set = mw.text.split(syllabify(respelling), " ") if gsub(table.concat(respelling_set), "[%+%-%*']", "") == (gsub(table.concat(page_title_set), "ါ", "ာ")) then for index, element in ipairs(respelling_set) do if element ~= page_title_set[index] then respelling_set[index] = '<span style="font-size:110%; color:#A32214; font-weight: bold">' .. element .. '</span>' end end end table.insert(new_respellings, table.concat(respelling_set)) end text = table.concat(new_respellings, ", ") text = remove_wide_space(text) text = gsub(text, "[%+%-].", initial_voicing) text = gsub(text, "([ခဂငဒပဝ]ေ?)ာ", "%1ါ") return text end function export.generate_tests(word, respelling) respelling, word = generate_respelling(respelling), generate_respelling(word) local pronunciations = { [1] = {}, [2] = {}, [3] = {}, [4] = {}, [5] = {}, } local p, result = { ["orthographic"] = word, ["phonetic"] = respelling or word }, {} table.sort(system_list, function(first, second) return first[1] < second[1] end) for system_index, system in ipairs(system_list) do pronunciations[system_index] = export.get_romanisation(p[system["type"]], pronunciations, system, system_index) end for system_index = 1, 5 do table.insert(result, table.concat(pronunciations[system_index])) end return (gsub(gsub(table.concat(result, " | "), "<u>", "("), "</u>", ")")) end function export.make(frame) local args = frame:getParent().args local page_title = mw.title.getCurrentTitle().text local title = generate_respelling(args["word"] or page_title) local p, result = { ["orthographic"] = { title }, ["phonetic"] = {} }, {} local pronunciations = { [1] = {}, [2] = {}, [3] = {}, [4] = {}, [5] = {}, } if not args[1] then args = { title } end for index, item in ipairs(args) do table.insert(p["phonetic"], (item ~= "") and generate_respelling(item) or nil) end table.sort(system_list, function(first, second) return first[1] < second[1] end) for system_index, system in ipairs(system_list) do for _, word in ipairs(p[system["type"]]) do pronunciations[system_index] = export.get_romanisation(word, pronunciations, system, system_index) end end if title ~= table.concat(args) then table.insert(result, "* Phonetic respelling" .. (#p["phonetic"] > 1 and "s" or "") .. ": " .. tostring( mw.html.create( "span" ) :attr( "lang", "my" ) :attr( "class", "Mymr" ) :wikitext( respelling_format( p["phonetic"], page_title ))) .. "\n" ) end table.insert(result, '* [[Wiktionary:International Phonetic Alphabet|IPA]]' .. '<sup>([[Appendix:Burmese pronunciation|key]])</sup>: ' .. (tostring( mw.html.create( "span" ) :attr( "class", "IPA" ) :wikitext( "/" .. gsub(table.concat(pronunciations[1], "/, /"), "ʔʔ", "ʔ.ʔ") .. "/" ))) .. '\n* [[Wiktionary:Burmese transliteration|Romanization:]] ') for system_index = 2, 5 do table.insert(result, (system_index ~= 2 and " • " or "") .. "''" .. system_list[system_index]["name"] .. ":'' " .. table.concat(pronunciations[system_index], "/")) end return table.concat(result) end return export
CustomSBValues = {} done = 0 -- Ext.RegisterOsirisListener("CharacterUsedSkillOnTarget", 5, "before", function(character, target, skill, skillType, skillElement) -- local stat = Ext.GetStat(skill) -- local isCSB = false -- for i, properties in pairs(stat.SkillProperties) do -- if properties.Action == "CUSTOMSURFACEBOOST" then isCSB = true end -- end -- if isCSB then -- local surfaces = {} -- for i, properties in pairs(stat.SkillProperties) do -- if properties.SurfaceBoosts ~= nil then -- for i,surface in pairs(properties.SurfaceBoosts) do -- table.insert(surfaces, surface) -- end -- end -- end -- local char = Ext.GetCharacter(target) -- local x = char.WorldPos[1] -- local y = char.WorldPos[3] -- local radius = Ext.GetStat(skill).AreaRadius -- local grid = Ext.GetAiGrid() -- local tiles = 0 -- local scale = 0.5 -- for i = x-radius,x+radius, scale do -- for j = y-radius,y+radius, scale do -- local info = grid:GetCellInfo(i,j) -- if ((i-x)*(i-x) + (j-y)*(j-y)) <= radius*radius then -- for surfaceType, t in pairs(SiphonPoisonSurfaces) do -- if info ~= nil and (info.Flags & surfaceFlags[surfaceType]) == surfaceFlags[surfaceType] then -- tiles = tiles + 1 -- end -- end -- end -- end -- end -- Ext.Print("tiles:",tiles) -- if CustomSBValues[skill] == nil then CustomSBValues = {} end -- CustomSBValues[skill][char.MyGuid] = tiles -- end -- end) Ext.RegisterOsirisListener("CharacterUsedSkill", 4, "before", function(character, skill, skillType, skillElement) local stat = Ext.GetStat(skill) local isCSB = false if stat.SkillProperties ~= nil then for i, properties in pairs(stat.SkillProperties) do if properties.Action == "CUSTOMSURFACEBOOST" then isCSB = true end end end if isCSB then local surfaces = {} for i, properties in pairs(stat.SkillProperties) do if properties.SurfaceBoosts ~= nil then for i,surface in pairs(properties.SurfaceBoosts) do table.insert(surfaces, surface) end end end local char = Ext.GetCharacter(character) local x = char.WorldPos[1] local y = char.WorldPos[3] local radius = Ext.GetStat(skill).AreaRadius local grid = Ext.GetAiGrid() local tiles = 0 local scale = 0.5 for i = x-radius,x+radius, scale do for j = y-radius,y+radius, scale do local info = grid:GetCellInfo(i,j) if ((i-x)*(i-x) + (j-y)*(j-y)) <= radius*radius then for i, surfaceType in pairs(surfaces) do if info ~= nil then local rawType = string.gsub(surfaceType, "Blessed", "") rawType = string.gsub(rawType, "Cursed", "") if (info.Flags & surfaceFlags[rawType]) == surfaceFlags[rawType] then if string.match(surfaceType, "Blessed") then if (info.Flags & surfaceFlags["Blessed"]) == surfaceFlags["Blessed"] then tiles = tiles + 1 end elseif string.match(surfaceType, "Cursed") then if (info.Flags & surfaceFlags["Cursed"]) == surfaceFlags["Cursed"] then tiles = tiles + 1 end else tiles = tiles + 1 end end end end end end end Ext.Print("tiles:",tiles) if CustomSBValues[skill] == nil then CustomSBValues[skill] = {} end CustomSBValues[skill][char.MyGuid] = tiles end end) Ext.RegisterSkillProperty("CUSTOMSURFACEBOOST", { ExecuteOnTarget = function(property, attacker, target, position, isFromItem, skill, hit) -- Ext.Print("SKILLPROPERTY on target") -- Ext.Dump(property) -- Ext.Print(property, attacker.DisplayName, target.DisplayName, position, isFromItem, skill, hit) if done < 1 then local args = {} local index = 1 for value in string.gmatch(property.Arg3, "(.-)/") do args[index] = value -- Ext.Print(index, value) index = index + 1 end local status = Ext.GetStat(args[1]) local duration = args[2] local statProperties = {} -- Usage: StatEntry, Field, Base, Growth, CellAggregate index = 1 for value in string.gmatch(args[3], "(.-)|") do Ext.Print(index, value) statProperties[index] = value index = index + 1 end index = 1 local start = 1 for i=1,GetTableSize(statProperties),7 do local baseStat = statProperties[i] -- The name of the status to take as a base if baseStat == nil then break end local statEntry = statProperties[i+1] -- Potion or Weapon entry local field = statProperties[i+2] local base = statProperties[i+3] local growth = statProperties[i+4] local cellAggregate = tonumber(statProperties[i+5]) local maxBonus = tonumber(statProperties[i+6]) -- Ext.Print(baseStat, statEntry, field, base, growth, cellAggregate) -- Ext.Dump(CustomSBValues[skill]) local nbBoosts = CustomSBValues[skill.Name][attacker.MyGuid] / cellAggregate local boostValue if nbBoosts < maxBonus then boostValue = Ext.Round(math.floor(nbBoosts * growth)) else boostValue = Ext.Round(math.floor(maxBonus * growth)) end -- Ext.Print("boost:", boostValue, "total:", base+boostValue) local hiddenBoost = status.Name.."_"..string.gsub(field, " ", "").."_"..boostValue -- Ext.Print(hiddenBoost) if NRD_StatExists(hiddenBoost) then if GetStatusTurns(attacker.MyGuid, "LXC_Proxy_"..hiddenBoost) == tonumber(duration) then return end -- if HasActiveStatus(attacker.MyGuid, hiddenBoost) == 0 then ApplyStatus(attacker.MyGuid, "LXC_Proxy_"..hiddenBoost, duration*6.0, 1) -- end else local newStat = {Name = hiddenBoost} if not NRD_StatExists(newStat.Name) then newStat = Ext.CreateStat(newStat.Name, statEntry, baseStat) newStat[field] = base + boostValue Ext.SyncStat(newStat.Name, false) end if statEntry == "Weapon" then if not NRD_StatExists("LXC_PotionProxy"..hiddenBoost) then local newPotion = Ext.CreateStat("LXC_PotionProxy"..hiddenBoost, "Potion", "DGM_Potion_Base") newPotion.BonusWeapon = newStat.Name Ext.SyncStat(newPotion.Name, false) end end local newStatus = Ext.CreateStat("LXC_Proxy".."_"..hiddenBoost, "StatusData", "DGM_BASE") if statEntry == "Potion" then newStatus["StatsId"] = hiddenBoost elseif statEntry == "Weapon" then newStatus["StatsId"] = "LXC_PotionProxy"..hiddenBoost end Ext.Print(status.Name) newStatus["StackId"] = "DGM_Stack_"..status.Name Ext.SyncStat(newStatus.Name, false) ApplyStatus(attacker.MyGuid, newStatus.Name, duration*6.0, 1) end end ApplyStatus(attacker.MyGuid, status.Name, duration*6.0) end if done == 0 then done = 2 else done = done - 1 end end, ExecuteOnPosition = function(property, attacker, position, areaRadius, isFromItem, skill, hit) -- Ext.Print("SKILLPROPERTY on position") -- Ext.Dump(property) -- Ext.Print(property, attacker, position, areaRadius, isFromItem, skill, hit) end })