content
stringlengths
5
1.05M
--====================================================================-- -- config.lua --====================================================================-- application = { content = { width = 320, height = 480, scale = "letterbox", }, showRuntimeErrors = false }
------------------------------------------------------------------------ --- @file packetChecks.lua --- @brief Check of packet types ------------------------------------------------------------------------ local proto = require "proto/proto" local mod = {} function mod.isIP4(pkt) return pkt.eth:getType() == proto.eth.TYPE_IP end function mod.isTcp4(pkt) return mod.isIP4(pkt) and pkt.ip4:getProtocol() == proto.ip4.PROTO_TCP end return mod
package("libpqxx") set_homepage("http://pqxx.org/") set_description("The official C++ client API for PostgreSQL.") add_urls("https://github.com/jtv/libpqxx/archive/refs/tags/$(version).tar.gz", "https://github.com/jtv/libpqxx.git") add_versions("7.7.0", "2d99de960aa3016915bc69326b369fcee04425e57fbe9dad48dd3fa6203879fb") add_deps("cmake", "python 3.x") add_deps("xmlto", "libpq") on_install("linux", "macosx", function (package) local configs = {"-DSKIP_BUILD_TEST=ON"} table.insert(configs, "-DCMAKE_BUILD_TYPE=" .. (package:debug() and "Debug" or "Release")) table.insert(configs, "-DBUILD_SHARED_LIBS=" .. (package:config("shared") and "ON" or "OFF")) import("package.tools.cmake").install(package, configs) end) on_test(function (package) assert(package:check_cxxsnippets({test = [[ void test() { pqxx::connection con; } ]]}, {configs = {languages = "c++17"}, includes = "pqxx/pqxx"})) end)
-- Generated by CSharp.lua Compiler local System = System local SlipeMtaDefinitions local SlipeServerDisplays local SlipeSharedUtilities local SystemNumerics System.import(function (out) SlipeMtaDefinitions = Slipe.MtaDefinitions SlipeServerDisplays = Slipe.Server.Displays SlipeSharedUtilities = Slipe.Shared.Utilities SystemNumerics = System.Numerics end) System.namespace("Slipe.Server.Displays", function (namespace) -- <summary> -- Represents a text label visible on a display -- </summary> namespace.class("Item", function (namespace) local getVisible, setVisible, getColor, setColor, getPosition, setPosition, getPriority, setPriority, getScale, setScale, getContent, setContent, Destroy, __ctor1__, __ctor2__, __ctor3__, __ctor4__ -- <summary> -- Create a new text item -- </summary> __ctor1__ = function (this, display, content, position, priority, color, scale, alignX, alignY, shadowAlpha) this.Display = display this.ItemElement = SlipeMtaDefinitions.MtaServer.TextCreateTextItem(content, position.X, position.Y, priority:ToEnumString(SlipeServerDisplays.Priority):ToLower(), color:getR(), color:getG(), color:getB(), color:getA(), scale, alignX:ToEnumString(SlipeServerDisplays.HorizontalAlignment):ToLower(), alignY:ToEnumString(SlipeServerDisplays.VerticalAlignment):ToLower(), shadowAlpha) SlipeMtaDefinitions.MtaServer.TextDisplayAddText(display.DisplayElement, this.ItemElement) this.visible = true end -- <summary> -- Create a new text item -- </summary> __ctor2__ = function (this, display, content, position, priority, color, scale) __ctor1__(this, display, content, position:__clone__(), priority, color, scale, 0 --[[HorizontalAlignment.Left]], 0 --[[VerticalAlignment.Top]], 0) end -- <summary> -- Create a new text item -- </summary> __ctor3__ = function (this, display, content, position, priority) __ctor2__(this, display, content, position:__clone__(), priority, SlipeSharedUtilities.Color.getWhite(), 1) end -- <summary> -- Create a new text item -- </summary> __ctor4__ = function (this, display, content, position) __ctor3__(this, display, content, position:__clone__(), 1 --[[Priority.Medium]]) end getVisible = function (this) return this.visible end setVisible = function (this, value) this.visible = value if this.visible then SlipeMtaDefinitions.MtaServer.TextDisplayAddText(this.Display.DisplayElement, this.ItemElement) else SlipeMtaDefinitions.MtaServer.TextDisplayRemoveText(this.Display.DisplayElement, this.ItemElement) end end getColor = function (this) local c = SlipeMtaDefinitions.MtaServer.TextItemGetColor(this.ItemElement) return System.new(SlipeSharedUtilities.Color, 3, System.toByte(c[1]), System.toByte(c[2]), System.toByte(c[3]), System.toByte(c[4])) end setColor = function (this, value) SlipeMtaDefinitions.MtaServer.TextItemSetColor(this.ItemElement, value:getR(), value:getG(), value:getB(), value:getA()) end getPosition = function (this) local r = SlipeMtaDefinitions.MtaServer.TextItemGetPosition(this.ItemElement) return SystemNumerics.Vector2(r[1], r[2]) end setPosition = function (this, value) SlipeMtaDefinitions.MtaServer.TextItemSetPosition(this.ItemElement, value.X, value.Y) end getPriority = function (this) return SlipeMtaDefinitions.MtaServer.TextItemGetPriority(this.ItemElement) end setPriority = function (this, value) SlipeMtaDefinitions.MtaServer.TextItemSetPriority(this.ItemElement, value:ToEnumString(SlipeServerDisplays.Priority):ToLower()) end getScale = function (this) return SlipeMtaDefinitions.MtaServer.TextItemGetScale(this.ItemElement) end setScale = function (this, value) SlipeMtaDefinitions.MtaServer.TextItemSetScale(this.ItemElement, value) end getContent = function (this) return SlipeMtaDefinitions.MtaServer.TextItemGetText(this.ItemElement) end setContent = function (this, value) SlipeMtaDefinitions.MtaServer.TextItemSetText(this.ItemElement, value) end Destroy = function (this) return SlipeMtaDefinitions.MtaServer.TextDestroyTextItem(this.ItemElement) end return { visible = false, getVisible = getVisible, setVisible = setVisible, getColor = getColor, setColor = setColor, getPosition = getPosition, setPosition = setPosition, getPriority = getPriority, setPriority = setPriority, getScale = getScale, setScale = setScale, getContent = getContent, setContent = setContent, Destroy = Destroy, __ctor__ = { __ctor1__, __ctor2__, __ctor3__, __ctor4__ }, __metadata__ = function (out) return { properties = { { "Color", 0x106, out.Slipe.Shared.Utilities.Color, getColor, setColor }, { "Content", 0x106, System.String, getContent, setContent }, { "Display", 0x6, out.Slipe.Server.Displays.Display }, { "ItemElement", 0x6, out.Slipe.MtaDefinitions.MtaElement }, { "Position", 0x106, System.Numerics.Vector2, getPosition, setPosition }, { "Priority", 0x106, System.Int32, getPriority, setPriority }, { "Scale", 0x106, System.Single, getScale, setScale }, { "Visible", 0x106, System.Boolean, getVisible, setVisible } }, fields = { { "visible", 0x1, System.Boolean } }, methods = { { ".ctor", 0x906, __ctor1__, out.Slipe.Server.Displays.Display, System.String, System.Numerics.Vector2, System.Int32, out.Slipe.Shared.Utilities.Color, System.Single, System.Int32, System.Int32, System.Int32 }, { ".ctor", 0x606, __ctor2__, out.Slipe.Server.Displays.Display, System.String, System.Numerics.Vector2, System.Int32, out.Slipe.Shared.Utilities.Color, System.Single }, { ".ctor", 0x406, __ctor3__, out.Slipe.Server.Displays.Display, System.String, System.Numerics.Vector2, System.Int32 }, { ".ctor", 0x306, __ctor4__, out.Slipe.Server.Displays.Display, System.String, System.Numerics.Vector2 }, { "Destroy", 0x86, Destroy, System.Boolean } }, class = { 0x6 } } end } end) end)
-- Generated By protoc-gen-lua Do not Edit local protobuf = require "protobuf/protobuf" module('SkillInfo_pb') SKILLINFO = protobuf.Descriptor(); local SKILLINFO_SKILLHASH_FIELD = protobuf.FieldDescriptor(); local SKILLINFO_SKILLLEVEL_FIELD = protobuf.FieldDescriptor(); local SKILLINFO_SKILLPOINT_FIELD = protobuf.FieldDescriptor(); local SKILLINFO_ISBASIC_FIELD = protobuf.FieldDescriptor(); SKILLINFO_SKILLHASH_FIELD.name = "skillHash" SKILLINFO_SKILLHASH_FIELD.full_name = ".KKSG.SkillInfo.skillHash" SKILLINFO_SKILLHASH_FIELD.number = 1 SKILLINFO_SKILLHASH_FIELD.index = 0 SKILLINFO_SKILLHASH_FIELD.label = 1 SKILLINFO_SKILLHASH_FIELD.has_default_value = false SKILLINFO_SKILLHASH_FIELD.default_value = 0 SKILLINFO_SKILLHASH_FIELD.type = 13 SKILLINFO_SKILLHASH_FIELD.cpp_type = 3 SKILLINFO_SKILLLEVEL_FIELD.name = "skillLevel" SKILLINFO_SKILLLEVEL_FIELD.full_name = ".KKSG.SkillInfo.skillLevel" SKILLINFO_SKILLLEVEL_FIELD.number = 2 SKILLINFO_SKILLLEVEL_FIELD.index = 1 SKILLINFO_SKILLLEVEL_FIELD.label = 1 SKILLINFO_SKILLLEVEL_FIELD.has_default_value = false SKILLINFO_SKILLLEVEL_FIELD.default_value = 0 SKILLINFO_SKILLLEVEL_FIELD.type = 13 SKILLINFO_SKILLLEVEL_FIELD.cpp_type = 3 SKILLINFO_SKILLPOINT_FIELD.name = "skillpoint" SKILLINFO_SKILLPOINT_FIELD.full_name = ".KKSG.SkillInfo.skillpoint" SKILLINFO_SKILLPOINT_FIELD.number = 3 SKILLINFO_SKILLPOINT_FIELD.index = 2 SKILLINFO_SKILLPOINT_FIELD.label = 1 SKILLINFO_SKILLPOINT_FIELD.has_default_value = false SKILLINFO_SKILLPOINT_FIELD.default_value = 0 SKILLINFO_SKILLPOINT_FIELD.type = 13 SKILLINFO_SKILLPOINT_FIELD.cpp_type = 3 SKILLINFO_ISBASIC_FIELD.name = "isbasic" SKILLINFO_ISBASIC_FIELD.full_name = ".KKSG.SkillInfo.isbasic" SKILLINFO_ISBASIC_FIELD.number = 4 SKILLINFO_ISBASIC_FIELD.index = 3 SKILLINFO_ISBASIC_FIELD.label = 1 SKILLINFO_ISBASIC_FIELD.has_default_value = false SKILLINFO_ISBASIC_FIELD.default_value = false SKILLINFO_ISBASIC_FIELD.type = 8 SKILLINFO_ISBASIC_FIELD.cpp_type = 7 SKILLINFO.name = "SkillInfo" SKILLINFO.full_name = ".KKSG.SkillInfo" SKILLINFO.nested_types = {} SKILLINFO.enum_types = {} SKILLINFO.fields = {SKILLINFO_SKILLHASH_FIELD, SKILLINFO_SKILLLEVEL_FIELD, SKILLINFO_SKILLPOINT_FIELD, SKILLINFO_ISBASIC_FIELD} SKILLINFO.is_extendable = false SKILLINFO.extensions = {} SkillInfo = protobuf.Message(SKILLINFO)
-- TODO: -- -- highpass filter - requires intelligently switching the wet/dry mix of HP and LP based on which one is in use, or having a priority override -- grids UI local Beets = {} Beets.__index = Beets local ControlSpec = require 'controlspec' local Formatters = require 'formatters' local BREAK_OFFSET = 5 local EVENT_ORDER = { "<", ">", "R", "S", "B" } local json = include("lib/json") function Beets.new(softcut_voice_id) local i = { -- descriptive global state running = false, enable_mutations = true, id = softcut_voice_id, beat_count = 8, initial_bpm = 130, loops_by_filename = {}, loop_index_to_filename = {}, loop_count = 0, editing = false, -- state that changes on the beat beatstep = 0, index = 0, played_index = 0, played_loop_index = 0, message = '', status = '', events = {}, muted = false, current_bpm = 0, beat_start = 0, beat_end = 7, loop_index = 1, on_beat_one = function() end, on_beat = function() end, on_kick = function() end, on_snare = function() end, change_bpm = function() end, -- probability values probability = {loop_index_jump = 0, stutter = 0, reverse = 0, jump = 0, jump_back = 0}, } setmetatable(i, Beets) return i end function Beets:advance_step(in_beatstep, in_bpm) self.events = {} self.message = '' self.status = '' self.beatstep = in_beatstep self.current_bpm = in_bpm self.played_index = self.index if not self.running then self.status = 'NOT RUNNING' return end if self.loop_count == 0 then self.status = 'NO LOOPS' return end self:play_slice(self.index) self:calculate_next_slice() end function Beets:instant_toggle_mute() self:toggle_mute() if self.muted then softcut.level(self.id, 0) else softcut.level(self.id, 1) end end function Beets:mute(in_muted) if in_muted then self.muted = true else self.muted = false end end function Beets:toggle_mute() self:mute(not self.muted) end function Beets:should(thing) if not self.enable_mutations then return false end return math.random(100) <= self.probability[thing] end function Beets:play_slice(slice_index) self.on_beat() if self.beatstep == 0 then self.on_beat_one() end self.played_loop_index = self.loop_index if (self:should('loop_index_jump')) then self.played_loop_index = math.random(self.loop_count) self.events['B'] = 1 else self.events['B'] = 0 end local loop = self.loops_by_filename[self.loop_index_to_filename[self.played_loop_index]] local current_rate = loop.rate * (self.current_bpm / self.initial_bpm) if (self:should('stutter')) then self.events['S'] = 1 local stutter_amount = math.random(4) softcut.loop_start(self.id, loop.start + (slice_index * (loop.duration / self.beat_count))) softcut.loop_end(self.id, loop.start + (slice_index * (loop.duration / self.beat_count) + (loop.duration / (64.0 / stutter_amount)))) else self.events['S'] = 0 softcut.loop_start(self.id, loop.start) softcut.loop_end(self.id, loop.start + loop.duration) end if (self:should('reverse')) then self.events['R'] = 1 softcut.rate(self.id, 0 - current_rate) else self.events['R'] = 0 softcut.rate(self.id, current_rate) end if self.muted then softcut.level(self.id, 0) else softcut.level(self.id, 1) end softcut.position(self.id, loop.start + (slice_index * (loop.duration / self.beat_count))) if self.muted then self.status = 'MUTED' end self:notify_beat(loop.beat_types[slice_index+1]) end function Beets:notify_beat(beat_type) if beat_type == 'K' then self.on_kick() end if beat_type == 'S' then self.on_snare() end end function Beets:calculate_next_slice() local new_index = self.index + 1 if new_index > self.beat_end then new_index = self.beat_start end if (self:should('jump')) then self.events['>'] = 1 new_index = (new_index + 1) % self.beat_count else self.events['>'] = 0 end if (self:should('jump_back')) then self.events['<'] = 1 new_index = (new_index - 1) % self.beat_count else self.events['<'] = 0 end if (self.beatstep == self.beat_count - 1) then new_index = self.beat_start end self.index = new_index end function Beets:clear_loops() self.loop_index_to_filename = {} self.loops_by_filename = {} self.loop_count = 0 end function Beets:load_directory(path, bpm) self:clear_loops() self.initial_bpm = bpm self.change_bpm(bpm) f = io.popen('ls ' .. path .. "/*.wav") filenames={} for name in f:lines() do table.insert(filenames, name) end table.sort(filenames) for i, name in ipairs(filenames) do self:load_loop(i,{ file=name }) i=i+1 end end function Beets:load_loop(index, loop) local filename = loop.file local kicks = loop.kicks local snares = loop.snares local loop_info = {} local ch, samples, samplerate = audio.file_info(filename) loop_info.frames = samples loop_info.rate = samplerate / 48000.0 -- compensate for files that aren't 48Khz loop_info.duration = samples / 48000.0 loop_info.beat_types = { " ", " ", " ", " ", " ", " ", " ", " " } loop_info.filename = filename loop_info.start = index * BREAK_OFFSET loop_info.index = index softcut.buffer_read_mono(filename, 0, loop_info.start, -1, 1, 1) if kicks then for _, beat in ipairs(kicks) do loop_info.beat_types[beat + 1] = "K" end end if snares then for _, beat in ipairs(snares) do loop_info.beat_types[beat + 1] = "S" end end self.loop_index_to_filename[index] = filename self.loops_by_filename[filename] = loop_info self.loop_count = index self:reset_loop_index_param() local f=io.open(filename .. ".json", "w") f:write(json.encode(loop_info)) f:close() end function Beets:softcut_init() softcut.enable(self.id, 1) softcut.buffer(self.id, 1) softcut.level(self.id, 1) softcut.level_slew_time(self.id, 0.2) softcut.loop(self.id, 1) softcut.loop_start(self.id, 0) softcut.loop_end(self.id, 0) softcut.position(self.id, 0) softcut.rate(self.id, 0) softcut.play(self.id, 1) softcut.fade_time(self.id, 0.010) softcut.post_filter_dry(self.id, 0.0) softcut.post_filter_lp(self.id, 1.0) softcut.post_filter_rq(self.id, 0.3) softcut.post_filter_fc(self.id, 44100) end function Beets:start(in_bpm) self.initial_bpm = in_bpm self:softcut_init() self.running = true end function Beets:stop() self.running = false softcut.play(self.id, 0) end function Beets:reset_loop_index_param() for _, p in ipairs(params.params) do if p.id == 'loop_index' then p.controlspec = ControlSpec.new(1, self.loop_count, 'lin', 1, 1, '') end end end function Beets:add_params() local specs = {} specs.FILTER_FREQ = ControlSpec.new(20, 20000, 'exp', 0, 20000, 'Hz') specs.FILTER_RESONANCE = ControlSpec.new(0.05, 1, 'lin', 0, 0.25, '') specs.PERCENTAGE = ControlSpec.new(0, 1, 'lin', 0.01, 0, '%') specs.BEAT_START = ControlSpec.new(0, self.beat_count - 1, 'lin', 1, 0, '') specs.BEAT_END = ControlSpec.new(0, self.beat_count - 1, 'lin', 1, self.beat_count - 1, '') local files = {} local files_count = 0 local loops_dir = _path.dust .. 'audio/beets/' f = io.popen('cd ' .. loops_dir .. "; ls -d *") for name in f:lines() do table.insert(files, name) files_count = files_count + 1 end table.sort(files) if files_count == 0 then name = 'Create folders in audio/beets to load' self.loops_folder_name = "-" else name = 'Loops folder' self.loops_folder_name = files[1] end params:add{ type = 'option', id = 'dir_chooser', name = name, options = files, action = function(value) self.loops_folder_name = files[value] end } params:add{ type = 'number', id = 'dir_bpm', name = 'Loops BPM', min = 1, max = 300, default = self.initial_bpm, action = function(value) self.initial_bpm = value end } params:add{ type = 'trigger', id = 'load_loops', name = 'Load loops', action = function(value) if value == "-" then return end self:load_directory(_path.dust .. 'audio/beets/' .. self.loops_folder_name, self.initial_bpm) end } params:add_separator() params:add{ type = 'control', id = 'loop_index', name = 'Sample', controlspec = ControlSpec.new(1, self.loop_count, 'lin', 1, 1, ''), action = function(value) self.loop_index = value end, } params:add{ type = 'control', id = 'jump_back_probability', name = 'Jump Back Probability', controlspec = specs.PERCENTAGE, formatter = Formatters.percentage, action = function(value) self.probability.jump_back = value * 100 end, } params:add{ type = 'control', id = 'jump_probability', name = 'Jump Probability', controlspec = specs.PERCENTAGE, formatter = Formatters.percentage, action = function(value) self.probability.jump = value * 100 end, } params:add{ type = 'control', id = 'reverse_probability', name = 'Reverse Probability', controlspec = specs.PERCENTAGE, formatter = Formatters.percentage, action = function(value) self.probability.reverse = value * 100 end, } params:add{ type = 'control', id = 'stutter_probability', name = 'Stutter Probability', controlspec = specs.PERCENTAGE, formatter = Formatters.percentage, action = function(value) self.probability.stutter = value * 100 end, } params:add{ type = 'control', id = 'loop_index_jump_probability', name = 'Break Index Jump Probability', controlspec = specs.PERCENTAGE, formatter = Formatters.percentage, action = function(value) self.probability.loop_index_jump = value * 100 end, } params:add{ type = 'control', id = 'filter_frequency', name = 'Filter Cutoff', controlspec = specs.FILTER_FREQ, formatter = Formatters.format_freq, action = function(value) softcut.post_filter_fc(self.id, value) end, } params:add{ type = 'control', id = 'filter_reso', name = 'Filter Resonance', controlspec = specs.FILTER_RESONANCE, action = function(value) softcut.post_filter_rq(self.id, value) end, } params:add{ type = 'control', id = 'beat_start', name = 'Beat Start', controlspec = specs.BEAT_START, action = function(value) self.beat_start = value end, } params:add{ type = 'control', id = 'beat_end', name = 'Beat End', controlspec = specs.BEAT_END, action = function(value) self.beat_end = value end, } end function Beets:drawPlaybackUI() local horiz_spacing = 9 local vert_spacing = 9 local left_margin = 10 local top_margin = 10 screen.clear() screen.level(15) if self.loop_count > 0 then local loop = self.loops_by_filename[self.loop_index_to_filename[self.loop_index]] for i = 0, 7 do screen.rect(left_margin + horiz_spacing * i, top_margin, horiz_spacing, vert_spacing) if self.played_index == i then screen.level(15) elseif self.beatstep == i then screen.level(2) else screen.level(0) end screen.fill() screen.rect(left_margin + horiz_spacing * i, top_margin, horiz_spacing, vert_spacing) screen.level(1) screen.move(left_margin + horiz_spacing * i + 2, top_margin + 6) screen.text(loop.beat_types[i+1]) screen.level(2) screen.stroke() screen.level(15) end screen.level(6) screen.move(left_margin + self.beat_start * horiz_spacing, top_margin + vert_spacing + 2) screen.line(left_margin + self.beat_start * horiz_spacing, top_margin + vert_spacing + 6) screen.line(left_margin + (self.beat_end + 1) * horiz_spacing, top_margin + vert_spacing + 6) screen.line(left_margin + (self.beat_end + 1) * horiz_spacing, top_margin + vert_spacing + 2) screen.stroke() screen.level(15) screen.move(left_margin + self.beat_count * horiz_spacing + 30, top_margin) screen.text(self.played_loop_index) for y, e in ipairs(EVENT_ORDER) do screen.move(left_margin + self.beat_count * horiz_spacing + 30, top_margin + vert_spacing * y) if self.events[e] == 1 then screen.level(15) else screen.level(1) end screen.text(e) end end screen.level(15) screen.move(left_margin, 40) screen.text(self.message) screen.move(left_margin, 50) screen.text(self.status) end function Beets:drawEditingUI() screen.move(10, 10) screen.text('EDIT MODE') end function Beets:drawUI() screen.clear() screen.level(15) if self.editing then self:drawEditingUI() else self:drawPlaybackUI() end screen.update() end function Beets:edit_mode_begin() self.editing = true redraw() end function Beets:edit_mode_end() self.editing = false redraw() end function Beets:enc(n, d) print('Enc ' .. n .. ' ' .. d) end function Beets:key(n, z) print('Key ' .. n .. ' ' .. z) end return Beets
--[[-------------------------------------------------------------------------- Author: Michael Roth <mroth@nessie.de> Copyright (c) 2004, 2005 Michael Roth <mroth@nessie.de> 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. --]]-------------------------------------------------------------------------- require "sqlite3" require "lunit" lunit.setprivfenv() lunit.import "assertions" lunit.import "checks" ------------------------------- -- Basic open and close test -- ------------------------------- lunit.wrap("open_memory", function() local db = assert_table( sqlite3.open_memory() ) assert( db:close() ) end) lunit.wrap("open", function() local filename = "/tmp/__lua-sqlite3-20040906135849." .. os.time() local db = assert_table( sqlite3.open(filename) ) assert( db:close() ) os.remove(filename) end) ------------------------------------- -- Presence of db member functions -- ------------------------------------- local db_funcs = lunit.TestCase("Database Member Functions") function db_funcs:setup() self.db = assert( sqlite3.open_memory() ) end function db_funcs:teardown() assert( self.db:close() ) end function db_funcs:test() local db = self.db assert_function( db.close ) assert_function( db.exec ) assert_function( db.irows ) assert_function( db.rows ) assert_function( db.cols ) assert_function( db.first_irow ) assert_function( db.first_row ) assert_function( db.first_cols ) assert_function( db.prepare ) assert_function( db.interrupt ) assert_function( db.last_insert_rowid ) assert_function( db.changes ) assert_function( db.total_changes ) end --------------------------------------- -- Presence of stmt member functions -- --------------------------------------- local stmt_funcs = lunit.TestCase("Statement Member Functions") function stmt_funcs:setup() self.db = assert( sqlite3.open_memory() ) self.stmt = assert( self.db:prepare("CREATE TABLE test (id, content)") ) end function stmt_funcs:teardown() assert( self.stmt:close() ) assert( self.db:close() ) end function stmt_funcs:test() local stmt = self.stmt assert_function( stmt.close ) assert_function( stmt.reset ) assert_function( stmt.exec ) assert_function( stmt.bind ) assert_function( stmt.irows ) assert_function( stmt.rows ) assert_function( stmt.cols ) assert_function( stmt.first_irow ) assert_function( stmt.first_row ) assert_function( stmt.first_cols ) assert_function( stmt.column_names ) assert_function( stmt.column_decltypes ) assert_function( stmt.column_count ) end ------------------ -- Tests basics -- ------------------ local basics = lunit.TestCase("Basics") function basics:setup() self.db = assert_table( sqlite3.open_memory() ) end function basics:teardown() assert_table( self.db:close() ) end function basics:create_table() assert_table( self.db:exec("CREATE TABLE test (id, name)") ) end function basics:drop_table() assert_table( self.db:exec("DROP TABLE test") ) end function basics:insert(id, name) assert_table( self.db:exec("INSERT INTO test VALUES ("..id..", '"..name.."')") ) end function basics:update(id, name) assert_table( self.db:exec("UPDATE test SET name = '"..name.."' WHERE id = "..id) ) end function basics:test_create_drop() self:create_table() self:drop_table() end function basics:test_multi_create_drop() self:create_table() self:drop_table() self:create_table() self:drop_table() end function basics:test_insert() self:create_table() self:insert(1, "Hello World") self:insert(2, "Hello Lua") self:insert(3, "Hello sqlite3") end function basics:test_update() self:create_table() self:insert(1, "Hello Home") self:insert(2, "Hello Lua") self:update(1, "Hello World") end --------------------------------- -- Statement Column Info Tests -- --------------------------------- lunit.wrap("Column Info Test", function() local db = assert_table( sqlite3.open_memory() ) assert_table( db:exec("CREATE TABLE test (id INTEGER, name TEXT)") ) local stmt = assert_table( db:prepare("SELECT * FROM test") ) assert_equal(2, stmt:column_count(), "Wrong number of columns." ) local names = assert_table( stmt:column_names() ) assert_equal(2, table.getn(names), "Wrong number of names.") assert_equal("id", names[1] ) assert_equal("name", names[2] ) local types = assert_table( stmt:column_decltypes() ) assert_equal(2, table.getn(types), "Wrong number of declaration types.") assert_equal("INTEGER", types[1] ) assert_equal("TEXT", types[2] ) assert_table( stmt:close() ) assert_table( db:close() ) end) --------------------- -- Statement Tests -- --------------------- st = lunit.TestCase("Statement Tests") function st:setup() self.db = assert( sqlite3.open_memory() ) assert_table( self.db:exec("CREATE TABLE test (id, name)") ) assert_table( self.db:exec("INSERT INTO test VALUES (1, 'Hello World')") ) assert_table( self.db:exec("INSERT INTO test VALUES (2, 'Hello Lua')") ) assert_table( self.db:exec("INSERT INTO test VALUES (3, 'Hello sqlite3')") ) end function st:teardown() assert_table( self.db:close() ) end function st:check_content(expected) local stmt = assert( self.db:prepare("SELECT * FROM test ORDER BY id") ) local i = 0 for row in stmt:irows() do i = i + 1 assert( i <= table.getn(expected), "To much rows." ) assert_equal(2, table.getn(row), "Two result column expected.") assert_equal(i, row[1], "Wrong 'id'.") assert_equal(expected[i], row[2], "Wrong 'name'.") end assert_equal( table.getn(expected), i, "To few rows." ) assert_table( stmt:close() ) end function st:test_setup() assert_pass(function() self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3" } end) assert_error(function() self:check_content{ "Hello World", "Hello Lua" } end) assert_error(function() self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "To much" } end) assert_error(function() self:check_content{ "Hello World", "Hello Lua", "Wrong" } end) assert_error(function() self:check_content{ "Hello World", "Wrong", "Hello sqlite3" } end) assert_error(function() self:check_content{ "Wrong", "Hello Lua", "Hello sqlite3" } end) end function st:test_questionmark_args() local stmt = assert_table( self.db:prepare("INSERT INTO test VALUES (?, ?)") ) assert_table( stmt:bind(0, "Test") ) assert_error(function() stmt:bind("To few") end) assert_error(function() stmt:bind(0, "Test", "To many") end) end function st:test_questionmark() local stmt = assert_table( self.db:prepare("INSERT INTO test VALUES (?, ?)") ) assert_table( stmt:bind(4, "Good morning") ) assert_table( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" } assert_table( stmt:bind(5, "Foo Bar") ) assert_table( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } end function st:test_questionmark_multi() local stmt = assert_table( self.db:prepare([[ INSERT INTO test VALUES (?, ?); INSERT INTO test VALUES (?, ?) ]])) assert( stmt:bind(5, "Foo Bar", 4, "Good morning") ) assert( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } end function st:test_identifiers() local stmt = assert_table( self.db:prepare("INSERT INTO test VALUES (:id, :name)") ) assert_table( stmt:bind(4, "Good morning") ) assert_table( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" } assert_table( stmt:bind(5, "Foo Bar") ) assert_table( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } end function st:test_identifiers_multi() local stmt = assert_table( self.db:prepare([[ INSERT INTO test VALUES (:id1, :name1); INSERT INTO test VALUES (:id2, :name2) ]])) assert( stmt:bind(5, "Foo Bar", 4, "Good morning") ) assert( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } end function st:test_identifiers_names() local stmt = assert_table( self.db:prepare({"name", "id"}, "INSERT INTO test VALUES (:id, $name)") ) assert_table( stmt:bind("Good morning", 4) ) assert_table( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" } assert_table( stmt:bind("Foo Bar", 5) ) assert_table( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } end function st:test_identifiers_multi_names() local stmt = assert_table( self.db:prepare( {"name", "id1", "id2"},[[ INSERT INTO test VALUES (:id1, $name); INSERT INTO test VALUES ($id2, :name) ]])) assert( stmt:bind("Hoho", 4, 5) ) assert( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Hoho", "Hoho" } end function st:test_colon_identifiers_names() local stmt = assert_table( self.db:prepare({":name", ":id"}, "INSERT INTO test VALUES (:id, $name)") ) assert_table( stmt:bind("Good morning", 4) ) assert_table( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" } assert_table( stmt:bind("Foo Bar", 5) ) assert_table( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } end function st:test_colon_identifiers_multi_names() local stmt = assert_table( self.db:prepare( {":name", ":id1", ":id2"},[[ INSERT INTO test VALUES (:id1, $name); INSERT INTO test VALUES ($id2, :name) ]])) assert( stmt:bind("Hoho", 4, 5) ) assert( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Hoho", "Hoho" } end function st:test_dollar_identifiers_names() local stmt = assert_table( self.db:prepare({"$name", "$id"}, "INSERT INTO test VALUES (:id, $name)") ) assert_table( stmt:bind("Good morning", 4) ) assert_table( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" } assert_table( stmt:bind("Foo Bar", 5) ) assert_table( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } end function st:test_dollar_identifiers_multi_names() local stmt = assert_table( self.db:prepare( {"$name", "$id1", "$id2"},[[ INSERT INTO test VALUES (:id1, $name); INSERT INTO test VALUES ($id2, :name) ]])) assert( stmt:bind("Hoho", 4, 5) ) assert( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Hoho", "Hoho" } end function st:test_bind_by_names() local stmt = assert_table( self.db:prepare("INSERT INTO test VALUES (:id, :name)") ) local args = { } args.id = 5 args.name = "Hello girls" assert( stmt:bind(args) ) assert( stmt:exec() ) args.id = 4 args.name = "Hello boys" assert( stmt:bind(args) ) assert( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Hello boys", "Hello girls" } end -------------------------------- -- Tests binding of arguments -- -------------------------------- b = lunit.TestCase("Binding Tests") function b:setup() self.db = assert( sqlite3.open_memory() ) assert_table( self.db:exec("CREATE TABLE test (id, name)") ) end function b:teardown() assert_table( self.db:close() ) end function b:test_auto_parameter_names() local stmt = assert_table( self.db:prepare([[ INSERT INTO test VALUES(:a, $b); INSERT INTO test VALUES(:a2, :b2); INSERT INTO test VALUES($a, :b); INSERT INTO test VALUES($a3, $b3) ]])) local parameters = assert_table( stmt:parameter_names() ) assert_equal( 6, table.getn(parameters) ) assert_equal( "a", parameters[1] ) assert_equal( "b", parameters[2] ) assert_equal( "a2", parameters[3] ) assert_equal( "b2", parameters[4] ) assert_equal( "a3", parameters[5] ) assert_equal( "b3", parameters[6] ) end function b:test_no_parameter_names_1() local stmt = assert_table( self.db:prepare([[ SELECT * FROM test ]])) local parameters = assert_table( stmt:parameter_names() ) assert_equal( 0, table.getn(parameters) ) end function b:test_no_parameter_names_2() local stmt = assert_table( self.db:prepare([[ INSERT INTO test VALUES(?, ?) ]])) local parameters = assert_table( stmt:parameter_names() ) assert_equal( 0, table.getn(parameters) ) end -------------------------------------------- -- Tests loop break and statement reusage -- -------------------------------------------- ---------------------------- -- Test for bugs reported -- ---------------------------- bug = lunit.TestCase("Bug-Report Tests") function bug:setup() self.db = assert( sqlite3.open_memory() ) end function bug:teardown() assert_table( self.db:close() ) end function bug:test_1() self.db:exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)") local query = assert_table( self.db:prepare("SELECT id FROM test WHERE value=?") ) assert_table ( query:bind("1") ) assert_nil ( query:first_cols() ) assert_table ( query:bind("2") ) assert_nil ( query:first_cols() ) end function bug:test_nils() -- appeared in lua-5.1 (holes in arrays) local function check(arg1, arg2, arg3, arg4, arg5) assert_equal(1, arg1) assert_equal(2, arg2) assert_nil(arg3) assert_equal(4, arg4) assert_nil(arg5) end self.db:set_function("test_nils", 5, function(arg1, arg2, arg3, arg4, arg5) check(arg1, arg2, arg3, arg4, arg5) end) assert_table( self.db:exec([[ SELECT test_nils(1, 2, NULL, 4, NULL) ]]) ) local arg1, arg2, arg3, arg4, arg5 = self.db:first_cols([[ SELECT 1, 2, NULL, 4, NULL ]]) check(arg1, arg2, arg3, arg4, arg5) local row = assert_table( self.db:first_irow([[ SELECT 1, 2, NULL, 4, NULL ]]) ) check(row[1], row[2], row[3], row[4], row[5]) end
Label = require("engine.widget.Label") Button = require("engine.widget.Button") Window = require("engine.widget.Window")
local escape_tbl_ctl = { ["\\"] = "\\\\" , ["\n"] = "\\n", ["\r"] = "\\r" } local escape_tbl = setmetatable({ ['&amp;'] = '&', ['&quot;'] = '"', ['&apos;'] = "'", ['&lt;'] = '<', ['&gt;'] = '>', }, { __index = function(_,k) local c = string.match(k, "&#(%d+);") return c and string.char(c) or k end }) local function xml_value(s) if s == nil then return "" end s = s:gsub("(&[^;]+;)", escape_tbl) s = s:gsub("[\\\r\n]", escape_tbl_ctl) return s end local function xml_child(p, node) local list = p[node.label] if not list then list = {} p[node.label] = list end list[#list+1] = node end local function xml_args(node, s) string.gsub(s, "(%w+) *= *([\"'])(.-)%2", function(w, _, a) node["@"..w] = xml_value(a) end) return node end local function xml_load(xmlText) local stack = {} local top = {} table.insert(stack, top) local ni, c, label, xarg, empty local i, j = 1, 1 while true do ni, j, c, label, xarg, empty = string.find(xmlText, "<(%/?)([%w_:]+)(.-)(%/?)>", i) if not ni then break end local text = string.sub(xmlText, i, ni - 1); if not string.find(text, "^%s*$") then top.value = (top.value or "") .. xml_value(text) end if empty == "/" then -- empty element tag xml_child(top, xml_args({label = label}, xarg)) elseif c == "" then -- start tag top = xml_args({label = label}, xarg) table.insert(stack, top) else -- end tag local toclose = table.remove(stack) -- remove top top = stack[#stack] if #stack < 1 then error("XmlParser: nothing to close with " .. label) end if toclose.label ~= label then error("XmlParser: trying to close " .. toclose.label .. " with " .. label) end xml_child(top, toclose) end i = j + 1 end local text = string.sub(xmlText, i); if #stack > 1 then error("XmlParser: unclosed " .. stack[#stack]:name()) end return top end return { load = xml_load }
effectiveness = {{"Super Effective", 4}, {"Effective", 2}, {"Normal", 1}, {"Ineffective", 0.5}, {"Very Ineffective", 0.25}, {"Null", 0}} pokemons = {} seen = 0 catches = 0 viewShiny = nil advancedSearchWindow = nil function init() connect(g_game, { onGameEnd = hide }) pokedexWindow = g_ui.displayUI('pokedex', modules.game_interface.getRootPanel()) pokedexTabBar = pokedexWindow:recursiveGetChildById('pokedexTabBar') pokemonInfoPanel = pokedexWindow:recursiveGetChildById('pokemonInfoPanel') pokemonsPanel = pokedexWindow:recursiveGetChildById('pokemonsPanel') pokemonSearch = pokedexWindow:recursiveGetChildById('searchText') seenLabel = pokedexWindow:recursiveGetChildById('seenLabelValue') catchesLabel = pokedexWindow:recursiveGetChildById('catchesLabelValue') pokemonHide = pokedexWindow:recursiveGetChildById('hideUnseen') pokemonInfoPanel:getChildById('mapMark'):setVisible(false) pokedexTabContent = pokedexWindow:recursiveGetChildById('pokedexTabContent') advancedSearchWindow = pokedexWindow:recursiveGetChildById('advancedSearchWindow') pokedexTabBar:setContentWidget(pokedexTabContent) pokedexWindow:hide() movesPanel = g_ui.loadUI('moves') pokedexTabBar:addTab(tr('Moves'), movesPanel) effectivenessPanel = g_ui.loadUI('effectiveness') pokedexTabBar:addTab(tr('Effectiveness'), effectivenessPanel) lootsPanel = g_ui.loadUI('loots') pokedexTabBar:addTab(tr('Loots'), lootsPanel) for i = 1, 375 do local pokemonButton = g_ui.createWidget('PokemonButton', pokemonsPanel) pokemonButton.onMouseRelease = onPokemonButtonMouseRelease pokemonButton.id = i pokemonButton.see = false pokemonButton.catched = 0 pokemonButton.name = pokemonId[i] if i < 10 then pokemonButton:setText('00'..i) elseif i >= 10 and i < 100 then pokemonButton:setText('0'..i) else pokemonButton:setText(i) end if i == 375 then pokemonButton:focus() end pokemonButton:setIconColor('black') pokemonButton:setIcon('/images/game/pokedex/icons/'..i) table.insert(pokemons, pokemonButton) end ProtocolGame.registerExtendedOpcode(60, function(protocol, opcode, buffer) onCheckPokedex(protocol, opcode, buffer) end) ProtocolGame.registerExtendedOpcode(62, function(protocol, opcode, buffer) onPokedexSelect(protocol, opcode, buffer) end) ProtocolGame.registerExtendedOpcode(63, function(protocol, opcode, buffer) getMapMarks(protocol, opcode, buffer) end) pokemonsPanel.onChildFocusChange = function(self, focusedChild) reloadPokemonsPanelInfo(focusedChild) end g_keyboard.bindKeyPress('Left', function() pokemonsPanel:focusPreviousChild(KeyboardFocusReason) end, pokedexWindow) g_keyboard.bindKeyPress('Right', function() pokemonsPanel:focusNextChild(KeyboardFocusReason) end, pokedexWindow) g_keyboard.bindKeyPress('Up', function() for i = 1, 4 do pokemonsPanel:focusPreviousChild(KeyboardFocusReason) end end, pokedexWindow) g_keyboard.bindKeyPress('Down', function() for i = 1, 4 do pokemonsPanel:focusNextChild(KeyboardFocusReason) end end, pokedexWindow) end function onPokedexSelect(protocol, opcode, buffer) local tabe = string.explode(buffer, "*") local mapMark = pokemonInfoPanel:getChildById('mapMark') reloadLoots(tabe[1]) local pokemonDescription = pokemonInfoPanel:getChildById('pokemonDescription') pokemonDescription:setText(tabe[3]) if tabe[2] == "false" then mapMark:setVisible(false) else mapMark:setVisible(true) end end function sendMapProtocolToServer(pokeName) local protocol = g_game.getProtocolGame() if protocol then if not pokeName:find('?') then protocol:sendExtendedOpcode(69, pokeName) end end end function getMapMarks(protocol, opcode, buffer) if buffer ~= "false" then assert(loadstring("mapInfo = "..tostring(buffer)))() for i, v in pairs(mapInfo) do addMapMarks(v['x'], v['y'], v['z'], v['imagem'], v['description']) end end end function addMapMarks(x, y, z, imagem, description) modules.game_minimap.setMonsterCave(x, y, z, imagem, description) scheduleEvent(function() modules.game_minimap.removeMonsterCave(x, y, z, imagem, description) end, 30*1000) end function reloadLoots(list) if list == "false" then return end assert(loadstring("itemInfo = "..tostring(list)))() local count = 1 for p = 1, 10 do local loots = lootsPanel:getChildById('pokemonLoots'):getChildById("item"..p) local lootsLabel = lootsPanel:getChildById('pokemonLoots'):getChildById("item"..p.."label") loots:setVisible(false) lootsLabel:setText("") end for i, v in pairs(itemInfo) do local loots = lootsPanel:getChildById('pokemonLoots'):getChildById("item"..count) local lootsLabel = lootsPanel:getChildById('pokemonLoots'):getChildById("item"..count.."label") loots:setItemId(v['id']) loots:setItemCount(v['count']) lootsLabel:setText("Chance: "..v['chance'].."%") loots:setTooltip(v['name']) loots:setVisible(true) count = count +1 end end function terminate() disconnect(g_game, { onGameEnd = hide }) g_keyboard.unbindKeyPress('Left') g_keyboard.unbindKeyPress('Right') g_keyboard.unbindKeyPress('Up') g_keyboard.unbindKeyPress('Down') save() seen = 0 catches = 0 pokedexWindow:destroy() end function show(focus, shiny) local scrollBar = pokedexWindow:getChildById('pokedexScrollBar') if focus == 0 then pokemonSearch:clearText() pokemonSearch:focus() pokedexWindow:show() pokedexWindow:raise() pokedexWindow:focus() clearCheckBoxChecked() pokemonsPanel:getChildByIndex(1):focus() scrollBar:setValue(0) return end if shiny then pokemons[focus].shiny = true else pokemons[focus].shiny = false end pokemonSearch:clearText() pokemonSearch:focus() pokedexWindow:show() pokedexWindow:raise() pokedexWindow:focus() clearCheckBoxChecked() scrollBar:setValue(math.floor((focus-21)/4)*43) pokemonsPanel:getChildByIndex(focus):focus() end function hide() save() seen = 0 catches = 0 pokedexWindow:hide() end function load() local settings = g_settings.getNode('game_pokedex') settings.hideUnseen = settings.hideUnseen or false pokemonHide:setChecked(settings.hideUnseen) hideUnseen(pokemonHide:isChecked()) end function save() local settings = {} settings.hideUnseen = pokemonHide:isChecked() g_settings.setNode('game_pokedex', settings) end function onPokemonButtonMouseRelease(self, mousePosition, mouseButton) if mouseButton == MouseRightButton then if not self.see or not haveShinyPokemon(self.name) then return end local menu = g_ui.createWidget('PopupMenu') menu:setGameMenu(true) if not viewShiny or pokemonsPanel:getFocusedChild() ~= self then menu:addOption('Shiny', function() self:focus() reloadShinyPokemonPanelInfo(self) end) elseif pokemonsPanel:getFocusedChild() == self then menu:addOption('Normal', function() self:focus() reloadPokemonsPanelInfo(self) end) end menu:display(mousePos) end end function onCheckPokedex(protocol, opcode, buffer) if string.find(buffer, 'reloadCatch') then local pokemonId = string.explode(buffer, '-')[1] local pokemon = pokemonsPanel:getChildByIndex(pokemonId) pokemon.catched = 1 if pokemon.see then pokemon:getChildByIndex(1):setImageColor('white') end return end seen = 0 catches = 0 for i = 1, (#string.explode(buffer, '|')-1) do local pokemon = pokemonsPanel:getChildByIndex(i) if pokemon ~= nil then local pokemonSee = string.explode(string.explode(buffer, '|')[i], '-')[1] local pokemonCatched = string.explode(string.explode(buffer, '|')[i], '-')[2] pokemon.catched = tonumber(pokemonCatched) if pokemonSee == '0' then pokemon.see = false pokemon:setIconColor('black') else pokemon.see = true pokemon:setIconColor('white') pokemon:setVisible(true) end if pokemon.catched == 1 and pokemon.see then pokemon:getChildByIndex(1):setImageColor('white') else pokemon:getChildByIndex(1):setImageColor('alpha') end if pokemon.see then seen = seen + 1 end if pokemon.catched == 1 then catches = catches + 1 end end end seenLabel:setText(seen) catchesLabel:setText(catches) load() end function advancedSearch(checkBox) for b = 1, pokemonsPanel:getChildCount() do local pokemon = pokemonsPanel:getChildByIndex(b) local type1 = pokemonTypes[pokemon.name].type1 local type2 = pokemonTypes[pokemon.name].type2 or 'none' local advancedSearchCondition = (getPokemonHaveCheckedSkills(pokemon) and pokemon.see) if getCatchedChecked() then advancedSearchCondition = pokemon.catched == 1 and advancedSearchCondition end if getTypesCheckBoxCheckedCount() == 1 then advancedSearchCondition = (string.find(getTypesChecked(), type1) or string.find(getTypesChecked(), type2)) and advancedSearchCondition elseif getTypesCheckBoxCheckedCount() == 2 then advancedSearchCondition = (string.find(getTypesChecked(), type1) and string.find(getTypesChecked(), type2)) and advancedSearchCondition elseif getTypesCheckBoxCheckedCount() >= 3 then advancedSearchCondition = false end if pokemonHide:isChecked() then advancedSearchCondition = (not checkBox:isChecked() and not haveCheckBoxChecked() and pokemon.see) or advancedSearchCondition else advancedSearchCondition = (not checkBox:isChecked() and not haveCheckBoxChecked()) or advancedSearchCondition end pokemon:setVisible(advancedSearchCondition) end end function getCatchedChecked() if advancedSearchWindow:getChildByIndex(2):isChecked() then return true end return false end function getPokemonHaveCheckedSkills(pokemon) local skills = getPokemonSkills(doCorrectString(pokemon.name)):lower() for i = 1, #getSkillsChecked() do if not string.find(skills, getSkillsChecked()[i]) then return false end end return true end function getSkillsChecked() local skillsChecked = {} for i = 7, 18 do local checkBox = advancedSearchWindow:getChildByIndex(i) if checkBox:isChecked() then table.insert(skillsChecked, checkBox:getText():lower()) end end return skillsChecked end function getTypesChecked() local typesChecked = {} for i = 19, 36 do local checkBox = advancedSearchWindow:getChildByIndex(i) if checkBox:isChecked() then table.insert(typesChecked, checkBox:getText():lower()..',') end end return table.concat(typesChecked) end function getTypesCheckBoxCheckedCount() local typesChecked = 0 for i = 19, 36 do local checkBox = advancedSearchWindow:getChildByIndex(i) if checkBox:isChecked() then typesChecked = typesChecked + 1 end end return typesChecked end function clearCheckBoxChecked() for i = 2, #advancedSearchWindow:getChildren() do if i == 2 or i >= 7 then advancedSearchWindow:getChildByIndex(i):setChecked(false) end end end function haveCheckBoxChecked() for i = 2, #advancedSearchWindow:getChildren() do if i == 2 or i >= 7 then if advancedSearchWindow:getChildByIndex(i):isChecked() then return true end end end return false end function hideUnseen(value) if pokemonSearch:getText() ~= '' then return end for i = 1, pokemonsPanel:getChildCount() do local pokemon = pokemonsPanel:getChildByIndex(i) local visibleCondition = (not value) or (value and pokemon.see) pokemon:setVisible(visibleCondition) end clearCheckBoxChecked() end function searchPokemon() local searchFilter = pokemonSearch:getText():lower() for i = 1, pokemonsPanel:getChildCount() do local pokemon = pokemonsPanel:getChildByIndex(i) local searchCondition = (searchFilter ~= '' and string.find(pokemon.name, searchFilter) ~= nil and pokemon.see) if pokemonHide:isChecked() then searchCondition = (searchFilter == '' and pokemon.see) or searchCondition else searchCondition = (searchFilter == '') or searchCondition end pokemon:setVisible(searchCondition) end clearCheckBoxChecked() end function reloadPokemonsPanelInfo(button) if button.shiny then return reloadShinyPokemonPanelInfo(button) end local pokemonNameLabel = pokemonInfoPanel:getChildById('pokemonName') local pokemonImage = pokemonInfoPanel:getChildById('pokemonImage') local pokemonType1 = pokemonInfoPanel:getChildById('pokemonType1') local pokemonType2 = pokemonInfoPanel:getChildById('pokemonType2') local pokemonDescription = pokemonInfoPanel:getChildById('pokemonDescription') local pokemonSkills = pokemonInfoPanel:getChildById('pokemonSkills') viewShiny = false if button.see then pokemonNameLabel:setText('#'..button:getText()..' '..doCorrectString(button.name)) pokemonImage:setImageColor('white') pokemonImage:setTooltip(tr('Description:')..'\n'..pokesDescription[button.name]) pokemonSkills:setText(tr('Skills')..': '..getPokemonSkills(doCorrectString(button.name))..'.') pokemonType1:setVisible(true) pokemonType2:setVisible(true) pokedexTabContent:setVisible(true) else pokemonImage:setImageColor('black') pokemonNameLabel:setText('#'..button:getText()..' ??????') pokemonDescription:setText(tr('Description:')..'\n??????') pokemonSkills:setText(tr('Skills')..': ??????.') pokemonType1:setVisible(false) pokemonType2:setVisible(false) pokedexTabContent:setVisible(false) end pokemonImage:setImageSource('/images/game/pokemon/portraits/'..button.name) pokemonType1:setTooltip(string.upper(pokemonTypes[button.name].type1)) pokemonType1:setImageSource('/images/game/elements/'..pokemonTypes[button.name].type1) if pokemonTypes[button.name].type2 and button.see then pokemonType2:setVisible(true) pokemonType2:setTooltip(string.upper(pokemonTypes[button.name].type2)) pokemonType2:setImageSource('/images/game/elements/'..pokemonTypes[button.name].type2) else pokemonType2:setVisible(false) end for i = 1, 12 do movesPanel:getChildById('pokemonMoves'):getChildById('move'..i):setVisible(false) end reloadMoves(doCorrectString(button.name)) reloadEffectiveness(button.name, pokemonTypes[button.name].type1, pokemonTypes[button.name].type2) local protocol = g_game.getProtocolGame() if protocol and button.see then protocol:sendExtendedOpcode(55, button.name.."*false") end end function reloadShinyPokemonPanelInfo(button) local pokemonNameLabel = pokemonInfoPanel:getChildById('pokemonName') local pokemonImage = pokemonInfoPanel:getChildById('pokemonImage') local pokemonType1 = pokemonInfoPanel:getChildById('pokemonType1') local pokemonType2 = pokemonInfoPanel:getChildById('pokemonType2') local pokemonDescription = pokemonInfoPanel:getChildById('pokemonDescription') local pokemonSkills = pokemonInfoPanel:getChildById('pokemonSkills') viewShiny = true button.shiny = false pokemonNameLabel:setText('#'..button:getText()..' Shiny '..doCorrectString(button.name)) pokemonImage:setImageColor('white') pokemonDescription:setText(tr('Description:')..'\n'..pokesDescription['shiny '..button.name]) pokemonSkills:setText(tr('Skills')..': '..getPokemonSkills('Shiny '..doCorrectString(button.name))..'.') pokemonType1:setVisible(true) pokemonType2:setVisible(true) pokedexTabContent:setVisible(true) pokemonImage:setImageSource('/images/game/pokemon/portraits/shiny '..button.name) pokemonType1:setTooltip(string.upper(pokemonTypes['shiny '..button.name].type1)) pokemonType1:setImageSource('/images/game/elements/'..pokemonTypes['shiny '..button.name].type1) if pokemonTypes['shiny '..button.name].type2 and button.see then pokemonType2:setVisible(true) pokemonType2:setTooltip(string.upper(pokemonTypes['shiny '..button.name].type2)) pokemonType2:setImageSource('/images/game/elements/'..pokemonTypes['shiny '..button.name].type2) else pokemonType2:setVisible(false) end reloadMoves('Shiny '..doCorrectString(button.name)) reloadEffectiveness('shiny '..button.name, pokemonTypes[button.name].type1, pokemonTypes[button.name].type2) local protocol = g_game.getProtocolGame() if protocol and button.see then protocol:sendExtendedOpcode(55, button.name.."*true") end end function reloadMoves(pokemonName) for i = 1, getPokemonMovesCount(pokemonName) do local move = movesPanel:getChildById('pokemonMoves'):getChildById('move'..i) local moveInfo = getPokemonMoveIdInfo(pokemonName)[i] move:getChildByIndex(1):setImageSource('/images/game/moves/'..moveInfo.name..'_on') move:getChildByIndex(1):setText(moveInfo.cd) move:getChildByIndex(2):setText(moveInfo.name) move:getChildByIndex(3):setText('Level '..moveInfo.level) move:getChildByIndex(4):setImageSource('/images/game/elements/'..moveInfo.t) move:getChildByIndex(4):setTooltip(doCorrectString(moveInfo.t)) move:setVisible(true) end end function reloadEffectiveness(pokemonName, type1, type2) local scrollPanel = effectivenessPanel:getChildById('pokemonEffectiveness') local first = 1 for i = 1, #scrollPanel:getChildren()-1 do scrollPanel:getChildByIndex(2):destroy() end for i = 1, #effectiveness do local effePanel = g_ui.createWidget('EffectivenessPanel', scrollPanel) if i > first then effePanel:setMarginTop(5) end local effeTypesPanel1 = effePanel:getChildByIndex(2) local effeTypesPanel2 = effePanel:getChildByIndex(3) local effeType = string.explode(getEffectiveness(type1, type2, effectiveness[i][2]), '-') scrollPanel:getChildByIndex(1):setText(tr('Effectiveness against')..' '..doCorrectString(pokemonName)..':') effePanel:getChildByIndex(1):setText(tr(effectiveness[i][1])..':') for a = 1, #effeTypesPanel1:getChildren() do effeTypesPanel1:getChildByIndex(1):destroy() end for a = 1, #effeTypesPanel2:getChildren() do effeTypesPanel2:getChildByIndex(1):destroy() end if getEffectiveness(type1, type2, effectiveness[i][2]) ~= "" then for b = 1, #effeType-1 do if #effeTypesPanel1:getChildren() <= 14 then element = g_ui.createWidget('ElementButton', effeTypesPanel1) else effePanel:setHeight(49) element = g_ui.createWidget('ElementButton', effeTypesPanel2) end element:setTooltip(doCorrectString(effeType[b])) element:setImageSource('/images/game/elements/'..effeType[b]) end else effePanel:destroy() first = first + 1 end end end function advancedSearchShow() if advancedSearchWindow:isVisible() then scheduleEvent(function() advancedSearchWindow:hide() end, 1) else advancedSearchWindow:show() advancedSearchWindow:raise() advancedSearchWindow:focus() end end
-- These were copied from the 0.15 base mod and need to be replaced in time with -- graphics for wooden pipes. function assembler2pipepictures() return { north = { filename = "__base__/graphics/entity/assembling-machine-2/assembling-machine-2-pipe-N.png", priority = "extra-high", width = 35, height = 18, shift = util.by_pixel(2.5, 14), hr_version = { filename = "__base__/graphics/entity/assembling-machine-2/hr-assembling-machine-2-pipe-N.png", priority = "extra-high", width = 71, height = 38, shift = util.by_pixel(2.25, 13.5), scale = 0.5 } }, east = { filename = "__base__/graphics/entity/assembling-machine-2/assembling-machine-2-pipe-E.png", priority = "extra-high", width = 20, height = 38, shift = util.by_pixel(-25, 1), hr_version = { filename = "__base__/graphics/entity/assembling-machine-2/hr-assembling-machine-2-pipe-E.png", priority = "extra-high", width = 42, height = 76, shift = util.by_pixel(-24.5, 1), scale = 0.5 } }, south = { filename = "__base__/graphics/entity/assembling-machine-2/assembling-machine-2-pipe-S.png", priority = "extra-high", width = 44, height = 31, shift = util.by_pixel(0, -31.5), hr_version = { filename = "__base__/graphics/entity/assembling-machine-2/hr-assembling-machine-2-pipe-S.png", priority = "extra-high", width = 88, height = 61, shift = util.by_pixel(0, -31.25), scale = 0.5 } }, west = { filename = "__base__/graphics/entity/assembling-machine-2/assembling-machine-2-pipe-W.png", priority = "extra-high", width = 19, height = 37, shift = util.by_pixel(25.5, 1.5), hr_version = { filename = "__base__/graphics/entity/assembling-machine-2/hr-assembling-machine-2-pipe-W.png", priority = "extra-high", width = 39, height = 73, shift = util.by_pixel(25.75, 1.25), scale = 0.5 } } } end local pipe_sheet = "__StoneAge__/graphics/wood-pipes.png" local pipe_sheet_hr = "__StoneAge__/graphics/wood-pipes-hr.png" function pipepictures() return { straight_vertical_single = { filename = pipe_sheet, priority = "extra-high", width = 64, height = 64, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 128, height = 128, x = 0, y = 0, scale = 0.5 } }, straight_vertical = { filename = pipe_sheet, priority = "extra-high", width = 64, height = 32, x = 0, y = 144, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 128, height = 64, x = 0, y = 288, scale = 0.5 } }, straight_vertical_window = { filename = pipe_sheet, priority = "extra-high", width = 64, height = 32, x = 0, y = 112, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 128, height = 64, x = 0, y = 224, scale = 0.5 } }, straight_horizontal_window = { filename = pipe_sheet, priority = "extra-high", width = 32, height = 64, x = 112, y = 0, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 64, height = 128, x = 224, y = 0, scale = 0.5 } }, straight_horizontal = { filename = pipe_sheet_hr, priority = "extra-high", width = 32, height = 64, x = 144, y = 0, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 64, height = 128, x = 288, y = 0, scale = 0.5, } }, corner_up_right = { filename = pipe_sheet, priority = "extra-high", width = 48, height = 48, x = 64, y = 144, shift = { x = -0.25, y = 0.25, }, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 96, height = 96, x = 128, y = 288, shift = { x = -0.25, y = 0.25, }, scale = 0.5 } }, corner_up_left = { filename = pipe_sheet, priority = "extra-high", width = 48, height = 48, x = 144, y = 144, shift = { x = 0.25, y = 0.25, }, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 96, height = 96, x = 288, y = 288, shift = { x = 0.25, y = 0.25, }, scale = 0.5 } }, corner_down_right = { filename = pipe_sheet, priority = "extra-high", width = 48, height = 48, x = 64, y = 64, shift = { x = -0.25, y = -0.25, }, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 96, height = 96, x = 128, y = 128, shift = { x = -0.25, y = -0.25, }, scale = 0.5 } }, corner_down_left = { filename = pipe_sheet, priority = "extra-high", width = 48, height = 48, x = 144, y = 64, shift = { x = 0.25, y = -0.25, }, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 96, height = 96, x = 288, y = 128, shift = { x = 0.25, y = -0.25, }, scale = 0.5 } }, t_up = { filename = pipe_sheet, priority = "extra-high", width = 32, height = 48, x = 112, y = 144, shift = { x = 0, y = 0.25, }, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 64, height = 96, x = 224, y = 288, shift = { x = 0, y = 0.25, }, scale = 0.5 } }, t_down = { filename = pipe_sheet, priority = "extra-high", width = 32, height = 48, x = 112, y = 64, shift = { x = 0, y = -0.25, }, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 64, height = 96, x = 224, y = 128, shift = { x = 0, y = -0.25, }, scale = 0.5 } }, t_right = { filename = pipe_sheet, priority = "extra-high", width = 48, height = 32, x = 64, y = 112, shift = { x = -0.25, y = 0, }, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 96, height = 64, x = 128, y = 224, shift = { x = -0.25, y = 0, }, scale = 0.5 } }, t_left = { filename = pipe_sheet, priority = "extra-high", width = 48, height = 32, x = 144, y = 112, shift = { x = 0.25, y = 0, }, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 96, height = 64, x = 288, y = 224, shift = { x = 0.25, y = 0, }, scale = 0.5 } }, cross = { filename = pipe_sheet, priority = "extra-high", width = 32, height = 32, x = 112, y = 112, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 64, height = 64, x = 224, y = 224, scale = 0.5 } }, ending_up = { filename = pipe_sheet, priority = "extra-high", width = 64, height = 48, x = 0, y = 176, shift = { x = 0, y = 0.25, }, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 128, height = 96, x = 0, y = 352, shift = { x = 0, y = 0.25, }, scale = 0.5 } }, ending_down = { filename = pipe_sheet, priority = "extra-high", width = 64, height = 48, x = 0, y = 64, shift = { x = 0, y = -0.25, }, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 128, height = 96, x = 0, y = 128, shift = { x = 0, y = -0.25, }, scale = 0.5 } }, ending_right = { filename = pipe_sheet, priority = "extra-high", width = 48, height = 64, x = 64, y = 0, shift = { x = -0.25, y = 0, }, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 96, height = 128, x = 128, y = 0, shift = { x = -0.25, y = 0, }, scale = 0.5 } }, ending_left = { filename = pipe_sheet, priority = "extra-high", width = 48, height = 64, x = 176, y = 0, shift = { x = 0.25, y = 0, }, hr_version = { filename = pipe_sheet_hr, priority = "extra-high", width = 96, height = 128, x = 352, y = 0, shift = { x = 0.25, y = 0, }, scale = 0.5 } }, horizontal_window_background = { filename = "__base__/graphics/entity/pipe/pipe-horizontal-window-background.png", priority = "extra-high", width = 64, height = 64, hr_version = { filename = "__base__/graphics/entity/pipe/hr-pipe-horizontal-window-background.png", priority = "extra-high", width = 128, height = 128, scale = 0.5 } }, vertical_window_background = { filename = "__base__/graphics/entity/pipe/pipe-vertical-window-background.png", priority = "extra-high", width = 64, height = 64, hr_version = { filename = "__base__/graphics/entity/pipe/hr-pipe-vertical-window-background.png", priority = "extra-high", width = 128, height = 128, scale = 0.5 } }, fluid_background = { filename = "__base__/graphics/entity/pipe/fluid-background.png", priority = "extra-high", width = 32, height = 20, hr_version = { filename = "__base__/graphics/entity/pipe/hr-fluid-background.png", priority = "extra-high", width = 64, height = 40, scale = 0.5 } }, low_temperature_flow = { filename = "__base__/graphics/entity/pipe/fluid-flow-low-temperature.png", priority = "extra-high", width = 160, height = 18 }, middle_temperature_flow = { filename = "__base__/graphics/entity/pipe/fluid-flow-medium-temperature.png", priority = "extra-high", width = 160, height = 18 }, high_temperature_flow = { filename = "__base__/graphics/entity/pipe/fluid-flow-high-temperature.png", priority = "extra-high", width = 160, height = 18 }, gas_flow = { filename = "__base__/graphics/entity/pipe/steam.png", priority = "extra-high", line_length = 10, width = 24, height = 15, frame_count = 60, axially_symmetrical = false, direction_count = 1, hr_version = { filename = "__base__/graphics/entity/pipe/hr-steam.png", priority = "extra-high", line_length = 10, width = 48, height = 30, frame_count = 60, axially_symmetrical = false, direction_count = 1 } } } end
--[[ MenuBar, by Goranaws --]] local MenuBar = Dominos:CreateClass('Frame', Dominos.Frame) Dominos.MenuBar = MenuBar local WIDTH_OFFSET = 2 local HEIGHT_OFFSET = 20 local MICRO_BUTTONS = { "CharacterMicroButton", "SpellbookMicroButton", "TalentMicroButton", "AchievementMicroButton", "QuestLogMicroButton", "GuildMicroButton", -- "PVPMicroButton", "LFDMicroButton", "CompanionsMicroButton", "EJMicroButton", "StoreMicroButton", "HelpMicroButton", "MainMenuMicroButton", } local overrideButtons = {} local MICRO_BUTTON_NAMES = { ['CharacterMicroButton'] = _G['CHARACTER_BUTTON'], ['SpellbookMicroButton'] = _G['SPELLBOOK_ABILITIES_BUTTON'], ['TalentMicroButton'] = _G['TALENTS_BUTTON'], ['AchievementMicroButton'] = _G['ACHIEVEMENT_BUTTON'], ['QuestLogMicroButton'] = _G['QUESTLOG_BUTTON'], ['GuildMicroButton'] = _G['LOOKINGFORGUILD'], -- ['PVPMicroButton'] = _G['PLAYER_V_PLAYER'], ['LFDMicroButton'] = _G['DUNGEONS_BUTTON'], ['EJMicroButton'] = _G['ENCOUNTER_JOURNAL'], ['CompanionsMicroButton'] = _G['MOUNTS_AND_PETS'], ['MainMenuMicroButton'] = _G['MAINMENU_BUTTON'], ['HelpMicroButton'] = _G['HELP_BUTTON'], ['StoreMicroButton'] = _G['BLIZZARD_STORE'] } --[[ Menu Bar ]]-- function MenuBar:New() local bar = MenuBar.super.New(self, 'menu') bar:LoadButtons() bar:Layout() return bar end function MenuBar:Create(frameId) local bar = MenuBar.super.Create(self, frameId) bar.buttons = {} bar.activeButtons = {} local getOrHook = function(frame, script, action) if frame:GetScript(script) then frame:HookScript(script, action) else frame:SetScript(script, action) end end local requestLayoutUpdate do local f = CreateFrame('Frame'); f:Hide() local delay = 0.01 f:SetScript('OnUpdate', function(self, elapsed) self:Hide() bar:Layout() end) requestLayoutUpdate = function() f:Show() end end hooksecurefunc('UpdateMicroButtons', requestLayoutUpdate) local petBattleFrame = _G['PetBattleFrame'].BottomFrame.MicroButtonFrame getOrHook(petBattleFrame, 'OnShow', function() bar.isPetBattleUIShown = true requestLayoutUpdate() end) getOrHook(petBattleFrame, 'OnHide', function() bar.isPetBattleUIShown = nil requestLayoutUpdate() end) local overrideActionBar = _G['OverrideActionBar'] getOrHook(overrideActionBar, 'OnShow', function() bar.isOverrideUIShown = Dominos:UsingOverrideUI() requestLayoutUpdate() end) getOrHook(overrideActionBar, 'OnHide', function() bar.isOverrideUIShown = nil requestLayoutUpdate() end) return bar end function MenuBar:LoadButtons() for i, buttonName in ipairs(MICRO_BUTTONS) do self:AddButton(i) end self:UpdateClickThrough() end function MenuBar:AddButton(i) local buttonName = MICRO_BUTTONS[i] local button = _G[buttonName] if button then button:SetParent(self.header) button:Show() self.buttons[i] = button end end function MenuBar:RemoveButton(i) local button = self.buttons[i] if button then button:SetParent(nil) button:Hide() self.buttons[i] = nil end end function MenuBar:LoadSettings(...) MenuBar.super.LoadSettings(self, ...) self.activeButtons = {} end function MenuBar:GetDefaults() return { point = 'BOTTOMRIGHT', x = -244, y = 0, } end function MenuBar:NumButtons() return #self.activeButtons end function MenuBar:DisableMenuButton(button, disabled) local disabledButtons = self.sets.disabled or {} disabledButtons[button:GetName()] = disabled or false self.sets.disabled = disabledButtons self:Layout() end function MenuBar:IsMenuButtonDisabled(button) local disabledButtons = self.sets.disabled if disabledButtons then return disabledButtons[button:GetName()] end return false end function MenuBar:Layout() if self.isPetBattleUIShown then self:LayoutPetBattle() elseif self.isOverrideUIShown then self:LayoutOverrideUI() else self:LayoutNormal() end end function MenuBar:LayoutNormal() self:UpdateActiveButtons() for i, button in pairs(self.buttons) do button:Hide() end local numButtons = #self.activeButtons if numButtons == 0 then self:SetSize(36, 36) return end local cols = min(self:NumColumns(), numButtons) local rows = ceil(numButtons / cols) local pW, pH = self:GetPadding() local spacing = self:GetSpacing() local isLeftToRight = self:GetLeftToRight() local isTopToBottom = self:GetTopToBottom() local firstButton = self.buttons[1] local w = firstButton:GetWidth() + spacing - WIDTH_OFFSET local h = firstButton:GetHeight() + spacing - HEIGHT_OFFSET for i, button in pairs(self.activeButtons) do local col, row if isLeftToRight then col = (i-1) % cols else col = (cols-1) - (i-1) % cols end if isTopToBottom then row = ceil(i / cols) - 1 else row = rows - ceil(i / cols) end button:SetParent(self.header) button:ClearAllPoints() button:SetPoint('TOPLEFT', w*col + pW, -(h*row + pH) + HEIGHT_OFFSET) button:Show() end -- Update bar size, if we're not in combat -- TODO: manage bar size via secure code if not InCombatLockdown() then local newWidth = max(w*cols - spacing + pW*2 + WIDTH_OFFSET, 8) local newHeight = max(h*ceil(numButtons / cols) - spacing + pH*2, 8) self:SetSize(newWidth, newHeight) end end function MenuBar:LayoutPetBattle() self:FixButtonPositions() end function MenuBar:LayoutOverrideUI() self:FixButtonPositions() end function MenuBar:FixButtonPositions() local isStoreEnabled = C_StorePublic.IsEnabled() local overrideButtons = {} for i, buttonName in ipairs(MICRO_BUTTONS) do local button = _G[buttonName] button:Hide() local shouldAddButton if buttonName == 'HelpMicroButton' then shouldAddButton = not isStoreEnabled elseif buttonName == 'StoreMicroButton' then shouldAddButton = isStoreEnabled else shouldAddButton = true end if shouldAddButton then table.insert(overrideButtons, button) end end for i, button in ipairs(overrideButtons) do if i > 1 then button:ClearAllPoints() if i == 7 then button:SetPoint('TOPLEFT', overrideButtons[1], 'BOTTOMLEFT', 0, HEIGHT_OFFSET + 4) else button:SetPoint('BOTTOMLEFT', overrideButtons[i - 1], 'BOTTOMRIGHT', -WIDTH_OFFSET, 0) end end button:Show() end end function MenuBar:UpdateActiveButtons() for i = 1, #self.activeButtons do self.activeButtons[i] = nil end for i, button in ipairs(self.buttons) do if not self:IsMenuButtonDisabled(button) then table.insert(self.activeButtons, button) end end end --[[ Menu Code ]]-- local function Menu_AddLayoutPanel(menu) local panel = menu:NewPanel(LibStub('AceLocale-3.0'):GetLocale('Dominos-Config').Layout) panel:NewOpacitySlider() panel:NewFadeSlider() panel:NewScaleSlider() panel:NewPaddingSlider() panel:NewSpacingSlider() panel:NewColumnsSlider() return panel end local function Panel_AddDisableMenuButtonCheckbox(panel, button, name) local checkbox = panel:NewCheckButton(name or button:GetName()) checkbox:SetScript('OnClick', function(self) local owner = self:GetParent().owner owner:DisableMenuButton(button, self:GetChecked()) end) checkbox:SetScript('OnShow', function(self) local owner = self:GetParent().owner self:SetChecked(owner:IsMenuButtonDisabled(button)) end) return checkbox end local function Menu_AddDisableMenuButtonsPanel(menu) local panel = menu:NewPanel(LibStub('AceLocale-3.0'):GetLocale('Dominos-Config').DisableMenuButtons) panel.width = 200 for i, buttonName in ipairs(MICRO_BUTTONS) do Panel_AddDisableMenuButtonCheckbox(panel, _G[buttonName], MICRO_BUTTON_NAMES[buttonName]) end return panel end function MenuBar:CreateMenu() local menu = Dominos:NewMenu(self.id) if menu then Menu_AddLayoutPanel(menu) Menu_AddDisableMenuButtonsPanel(menu) menu:AddAdvancedPanel() self.menu = menu end return menu end --[[ module ]]-- local MenuBarController = Dominos:NewModule('MenuBar') function MenuBarController:OnInitialize() -- fixed blizzard nil bug if not _G['AchievementMicroButton_Update'] then _G['AchievementMicroButton_Update'] = function() end end end function MenuBarController:Load() self.frame = MenuBar:New() end function MenuBarController:Unload() if self.frame then self.frame:Free() self.frame = nil end end
function assertType(value, expected) assert(type(value) == expected, string.format("expecting a %s as parameter but got %s", expected, type(value)) ) end
local ok, cmp = pcall(require, "cmp") if not ok then vim.notify("Unable to require cmp", vim.lsp.log_levels.ERROR, { title = "Plugin error" }) return end local cmpok, cmplsp = pcall(require, "cmp_nvim_lsp") if not cmpok then vim.notify("Unable to require cmp_nvim_lsp", vim.lsp.log_levels.ERROR, { title = "Plugin error" }) return end local configok, compare = pcall(require, "cmp.config.compare") if not configok then vim.notify("Unable to require cmp.config.compare", vim.lsp.log_levels.ERROR, { title = "Plugin error" }) return end local iconok, i = pcall(require, "config.icons") if not iconok then vim.notify("Unable to require config.icons", vim.lsp.log_levels.ERROR, { title = "Config error" }) return end local luasnipok, luasnip = pcall(require, "luasnip") if not luasnipok then vim.notify("Unable to require luasnip") return end local check_backspace = function() local col = vim.fn.col(".") - 1 return col == 0 or vim.fn.getline("."):sub(col, col):match("%s") end cmplsp.setup() cmp.setup({ preselect = false, snippet = { expand = function(args) luasnip.lsp_expand(args.body) end, }, formatting = { fields = { "kind", "abbr", "menu" }, format = function(entry, vim_item) vim_item.kind = string.format("%s", i.symbol_map[vim_item.kind]) vim_item.menu = ({ nvim_lsp = "[LSP]", luasnip = "[Snippet]", buffer = "[Buffer]", path = "[Path]", })[entry.source.name] return vim_item end, }, sorting = { priority_weight = 2., comparators = { compare.offset, compare.exact, compare.score, compare.kind, compare.sort_text, compare.length, compare.order, }, }, min_length = 0, -- allow for `from package import _` in Python mapping = cmp.mapping.preset.insert({ ["<C-k>"] = function() if luasnip.choice_active() then luasnip.change_choice(-1) elseif cmp.visible() then cmp.select_prev_item() end end, ["<C-j>"] = function() if luasnip.choice_active() then luasnip.change_choice(1) elseif cmp.visible() then cmp.select_next_item() end end, ["<C-b>"] = cmp.mapping.scroll_docs(-4), ["<C-f>"] = cmp.mapping.scroll_docs(4), ["<C-Space>"] = cmp.mapping.complete(), ["<C-e>"] = cmp.mapping.abort(), ["<C-y>"] = cmp.config.disable, ["<CR>"] = cmp.mapping.confirm({ select = true }), ["<Tab>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif luasnip.expand_or_jumpable() then luasnip.expand_or_jump() elseif check_backspace() then fallback() else fallback() end end, { "i", "s" }), ["<S-Tab>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_prev_item() elseif luasnip.jumpable(-1) then luasnip.jump(-1) else fallback() end end, { "i", "s" }), }), sources = { { name = "nvim_lsp" }, { name = "nvim_lua" }, { name = "path" }, { name = "luasnip" }, { name = "buffer", keyword_length = 3 }, }, window = { documentation = cmp.config.window.bordered(), }, })
local json = require 'json' local Error = require 'Error.lua' local protocol = require 'utils/protocol.lua' local protodef = require 'utils/protodef.lua' local wrappers = require 'utils/wrappers.lua' ---@class Reql ---@field public conn Connection ---@field public root boolean ---@field public parent Reql|nil ---@field private internal table local Reql = {} local term_wrappers = { datum = wrappers.argPassthrough, between = wrappers.argArity4, between_deprecated = wrappers.argArity4, changes = wrappers.argArityN, circle = wrappers.argArityN, delete = wrappers.argArityN, distance = wrappers.argArityN, distinct = wrappers.argArityN, during = wrappers.argArity4, eq_join = wrappers.argArityN, filter = wrappers.argArity3, fold = wrappers.argArityN, get_all = wrappers.argArityN, get_intersecting = wrappers.argArityN, get_nearest = wrappers.argArityN, group = wrappers.argArityN, http = wrappers.argArity3, index_create = wrappers.argArityN, index_rename = wrappers.argArityN, insert = wrappers.argArity3, iso8601 = wrappers.argArityN, js = wrappers.argArityN, make_obj = wrappers.argArity0, max = wrappers.argArityN, min = wrappers.argArityN, order_by = wrappers.argArityN, random = wrappers.argArityN, reconfigure = wrappers.argArity2, reduce = wrappers.argArityN, replace = wrappers.argArity3, slice = wrappers.argArityN, table = wrappers.argArityN, table_create = wrappers.argArityN, union = wrappers.argArityN, update = wrappers.argArity3, wait = wrappers.argArity2, } function Reql:__index(key) if Reql[key] then return Reql[key] else local wrapper = term_wrappers[key] if protodef.Term[key] then return function(...) local args, optargs if wrapper then args, optargs = wrapper(...) else args = {...} end if wrappers[key] then args, optargs = wrappers[key](self, args, optargs) end return Reql.create(self, key, args, optargs) end end end end local function assertResume(thread, ...) local success, err = coroutine.resume(thread, ...) if not success then error(debug.traceback(thread, err), 0) end end Reql.__typename = 'Reql' ---@type Reql Reql.raw = setmetatable({root = true}, Reql) ---@param conn Connection ---@return Reql function Reql.new(conn) local self = setmetatable({}, Reql) self.conn = conn self.root = true local node = self return node end function Reql.create(parent, term, args, optargs) local self = setmetatable({}, Reql) self.parent = parent self.conn = parent.conn self.internal = {term = term, termi = protodef.Term[term], args = args, optargs = optargs} return self end local empty_optarg = setmetatable({}, {__jsontype = 'object'}) ---@param options ?table ---@param callback ?function ---@return boolean, Cursor function Reql:run(options, callback) if type(options) == 'function' then callback = options options = nil end options = options or {} local conn = options.connection or self.conn if not conn then -- This is a raw query and we didn't get a connection local err = Error.ReqlDriverError('Connection missing.') if callback then callback(false, err) end return false, err end if conn.socket.closed then conn.logger:error('Connection is closed, cannot run query.') local err = Error.ReqlDriverError('Connection is closed.') if callback then callback(false, err) end return false, err end local query = {protodef.Term.datum, protocol.serialize(self), options.optargs or empty_optarg} local token = options.token or conn:nextToken() local success, encoded = pcall(json.encode, query) if not success then conn.logger:error('Failed to encode query.') local err = Error.ReqlUserError('query could not be encoded.') if callback then callback(false, err, encoded) end return false, err, encoded end local should_yield if not callback then local thread = coroutine.running() if not thread then conn.logger:error('Cannot run a query outside of a coroutine without a callback.') local err = Error.ReqlUserError('no coroutine or callback provided to run.') return false, err end should_yield = true callback = function(...) assertResume(thread, ...) end else should_yield = false end conn.logger:debug('>>> %i %s', token, encoded) conn.callbacks[token] = {fn = callback, callee = debug.getinfo(2, 'Sl')} coroutine.wrap(conn.socket.write)(conn.socket, {token = token, data = encoded}) if should_yield then return coroutine.yield() end end return Reql
include("shared.lua") function ENT:Initialize() self:SetNoDraw(true) end function ENT:OnRemove() self:StopAndDestroyParticles() end
if CustomizableWeaponry then AddCSLuaFile() AddCSLuaFile("sh_sounds.lua") include("sh_sounds.lua") if CLIENT then SWEP.DrawCrosshair = false SWEP.PrintName = "G2 Contender" SWEP.CSMuzzleFlashes = false SWEP.ViewModelMovementScale = 1 SWEP.IconLetter = "f" SWEP.SelectIcon = surface.GetTextureID("vgui/hud/cw_contender") -- Icon to use for weapon select (1,2,3, mousewheel etc.) " killicon.Add("cw_contender", "vgui/hud/kill/cw_contender", Color(255, 255, 255, 150)) -- Kill icon killicon.Add("cw_bullet_30wcf", "vgui/hud/kill/cw_contender", Color(255, 255, 255, 150)) -- Kill icon for GDCW bullet SWEP.MuzzleEffect = "muzzleflash_SR25" SWEP.NoSilMuz = true SWEP.PosBasedMuz = false SWEP.SnapToGrip = true SWEP.Shell = false -- Disables brass ejection SWEP.SightWithRail = false SWEP.IronsightPos = Vector(-2.81, 0, 1.32) SWEP.IronsightAng = Vector(0, 0, 0) SWEP.AccuPos = Vector(-2.81, 0, 0.32) SWEP.AccuAng = Vector(0, 0, 0) SWEP.ACOGPos = Vector(-2.81, 0, 0.22) SWEP.ACOGAng = Vector(0, 0, 0) SWEP.AimpointPos = Vector(-2.82, 0, 0.6) SWEP.AimpointAng = Vector(0, 0, 0) SWEP.EoTechPos = Vector(-2.81, 0, 0.45) SWEP.EoTechAng = Vector(0, 0, 0) SWEP.LeupoldPos = Vector(-2.81, 0, 0.4) SWEP.LeupoldAng = Vector(0, 0, 0) SWEP.MicroT1Pos = Vector(-2.82, 0, 0.48) SWEP.MicroT1Ang = Vector(0, 0, 0) SWEP.AlternativePos = Vector(-2.81, 0, 0) SWEP.AlternativeAng = Vector(0, 0, 0) SWEP.BaseArm = "Bip01 L Clavicle" SWEP.BaseArmBoneOffset = Vector(-50, 0, 0) SWEP.ACOGAxisAlign = {right = 0, up = 0, forward = 0} SWEP.AccuAxisAlign = {right = 1, up = 0, forward = 0} SWEP.LeupoldAxisAlign = {right = 0, up = 0.095, forward = 0} SWEP.AttachmentModelsVM = { ["md_aimpoint"] = {model = "models/wystan/attachments/aimpoint.mdl", bone = "barrel", rel = "", pos = Vector(5.25, 3.44, -0.2), angle = Angle(90, 0, -90), size = Vector(0.8, 0.8, 0.8)}, ["md_eotech"] = {model = "models/wystan/attachments/2otech557sight.mdl", bone = "barrel", rel = "", pos = Vector(8.8, 7.44, 0.24), angle = Angle(180, 0, -90), size = Vector(0.8, 0.8, 0.8)}, ["md_microt1"] = {model = "models/cw2/attachments/microt1.mdl", bone = "barrel", pos = Vector(-0.6, -1.3, 0.03), angle = Angle(-90, 0, -90), size = Vector(0.4, 0.4, 0.4)}, ["md_saker"] = {model = "models/cw2/attachments/556suppressor.mdl", bone = "barrel", pos = Vector(0.7, 1.1, 0), angle = Angle(90, 0, -90), size = Vector(0.6, 0.6, 0.6)}, } SWEP.LaserPosAdjust = Vector(1, 0, 0) SWEP.LaserAngAdjust = Angle(2, 180, 0) end SWEP.LuaViewmodelRecoil = false SWEP.ADSFireAnim = true SWEP.ForceBackToHipAfterAimedShot = true SWEP.GlobalDelayOnShoot = 0.5 SWEP.CustomizationMenuScale = 0.012 SWEP.Attachments = {[1] = {header = "Sight", offset = {0, -500}, atts = {"md_aimpoint", "md_eotech", "md_microt1"}}, [2] = {header = "Barrel", offset = {-450, -300}, atts = {"md_saker"}}, ["+reload"] = {header = "Ammo", offset = {400, -100}, atts = {"am_hollowpoint", "am_armorpiercing", "am_410buck"}}} SWEP.Animations = {fire = "shoot1", fireDry = "shoot1", reload = "reload", idle = "idle", draw = "draw"} SWEP.Sounds = {draw = {[1] = {time = 0, sound = "Contender.Deploy"}, [2] = {time = 0.75, sound = "Contender.Cock"}}, reload = {[1] = {time = 0, sound = "Contender.Foley"}, [2] = {time = 0.2, sound = "Contender.Open"}, [3] = {time = 0.75, sound = "Contender.Shell"}, [4] = {time = 1.148, sound = "Contender.In1"}, [5] = {time = 1.5, sound = "Contender.In2"}, [6] = {time = 2.1, sound = "Contender.Close"}, [7] = {time = 2.2, sound = "Contender.Cock"}}} SWEP.SpeedDec = 0 SWEP.Slot = 2 SWEP.SlotPos = 0 SWEP.HoldType = "ar2" SWEP.NormalHoldType = "ar2" SWEP.RunHoldType = "crossbow" SWEP.FireModes = {"break"} SWEP.Base = "cw_base" SWEP.Category = "STALKER Weapons" SWEP.Author = "" SWEP.Contact = "" SWEP.Purpose = "" SWEP.Instructions = "" SWEP.ViewModelFOV = 70 SWEP.ViewModelFlip = false SWEP.ViewModel = "models/cw2/pistols/v_contender.mdl" SWEP.WorldModel = "models/cw2/pistols/w_contender.mdl" SWEP.DrawTraditionalWorldModel = false --Whether to use world model's embedded/compiled origin SWEP.WM = "models/cw2/pistols/w_contender.mdl" SWEP.WMPos = Vector(0.5,-17.0,0.0) --world model origin X,Y,Z SWEP.WMAng = Vector(-20,179.5,180) --world model angles X,Y,Z SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.Primary.ClipSize = 1 SWEP.Primary.DefaultClip = 0 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = ".45 ACP" SWEP.Chamberable = false SWEP.FireDelay = 0.1 SWEP.FireSound = "ContenderLB.Shoot" SWEP.FireSoundSuppressed = "ContenderSD.Shoot" SWEP.Recoil = 3.5 SWEP.WearDamage = 0.05 SWEP.WearEffect = 0.001 SWEP.HipSpread = 0.075 SWEP.AimSpread = 0.0125 SWEP.VelocitySensitivity = 12 SWEP.MaxSpreadInc = 0.5 SWEP.SpreadPerShot = 0.007 SWEP.SpreadCooldown = 0.5 SWEP.Shots = 1 SWEP.Damage = 85 SWEP.DeployTime = 0.6 SWEP.ReloadSpeed = 1 SWEP.ReloadTime = 2.5 SWEP.ReloadTime_Empty = 2.5 SWEP.ReloadHalt = 2.5 SWEP.ReloadHalt_Empty = 2.5 SWEP.SnapToIdlePostReload = true end function SWEP:IndividualThink() if self.ActiveAttachments.am_410buck then self.MuzzleVelocity = 259 self.FireSound = "CWC_JUDGE_FIRE" self.MuzzleEffect = "muzzleflash_shotgun" else self.MuzzleVelocity = 680 self.FireSound = "ContenderLB.Shoot" self.MuzzleEffect = "muzzleflash_pistol_deagle" end end -- Per-weapon functions ------------------------------------------------------------------------------ --[[ Any functions different from the default cw_base go here to avoid conflicts. This way, I don't have to make a copy of the base and don't need to update all my CW2 SWeps every time I add something. Keep the order of functions the same. Clip drop and GDCW stuff go here, but only on SWeps which use them. ]]-- --function SWEP:PrimaryAttack() -- if self.ShotgunReloadState != 0 then -- return -- end -- -- if self.ReloadDelay then -- return -- end -- -- if self.Owner:KeyDown(IN_USE) then -- if CustomizableWeaponry.quickGrenade.canThrow(self) then -- CustomizableWeaponry.quickGrenade.throw(self) -- return -- end -- end -- -- if CurTime() < self.GlobalDelay then -- return false -- end -- -- if self.dt.Safe then -- self:CycleFiremodes() -- return -- end -- -- local preFireResult = CustomizableWeaponry.callbacks.processCategory(self, "preFire") -- -- if preFireResult then -- return -- end -- -- if self:isNearWall() then -- return -- end -- -- if self.InactiveWeaponStates[self.dt.State] then -- return -- end -- -- if self.dt.State == CW_AIMING and self.dt.M203Active then -- if self.M203Chamber then -- self:fireM203(IsFirstTimePredicted()) -- -- return -- end -- end -- -- mag = self:Clip1() -- -- if mag == 0 then -- self:EmitSound("CW_EMPTY", 100, 100) -- self:SetNextPrimaryFire(CT + 0.25) -- return -- end -- -- if self.BurstAmount and self.BurstAmount > 0 then -- if self.dt.Shots >= self.BurstAmount then -- return -- end -- -- self.dt.Shots = self.dt.Shots + 1 -- end -- -- self.Owner:SetAnimation(PLAYER_ATTACK1) -- CT = CurTime() -- -- if IsFirstTimePredicted() then -- if self.dt.Suppressed then -- self:EmitSound(self.FireSoundSuppressed, 105, 100) -- else -- self:EmitSound(self.FireSound, 105, 100) -- end -- -- if self.fireAnimFunc then -- self:fireAnimFunc() -- else -- if self.dt.State == CW_AIMING then -- if self.ADSFireAnim then -- self:playFireAnim() -- end -- else -- self:playFireAnim() -- end -- end -- -- -- Whether to use GDCW bullet -- if self.gdcw == 1 then -- self:FireRocket(self.Damage, self.CurCone, self.ClumpSpread, self.Shots) -- self:makeFireEffects() -- self:MakeRecoil() -- self:addFireSpread(CT) -- else -- self:FireBullet(self.Damage, self.CurCone, self.ClumpSpread, self.Shots) -- self:makeFireEffects() -- self:MakeRecoil() -- self:addFireSpread(CT) -- end -- -- if CLIENT then -- self:simulateRecoil() -- end -- -- if SP and SERVER then -- SendUserMessage("CW_Recoil", self.Owner) -- end -- -- -- apply a global delay after shooting, if there is one -- if self.GlobalDelayOnShoot then -- self.GlobalDelay = CT + self.GlobalDelayOnShoot -- end -- end -- -- CustomizableWeaponry.callbacks.processCategory(self, "postFire") -- -- local suppressAmmoUsage = CustomizableWeaponry.callbacks.processCategory(self, "shouldSuppressAmmoUsage") -- -- if not suppressAmmoUsage then -- self:TakePrimaryAmmo(self.AmmoPerShot) -- end -- -- self:SetNextPrimaryFire(CT + self.FireDelay) -- -- -- either force the weapon back to hip after firing, or don't -- if self.ForceBackToHipAfterAimedShot then -- self.dt.State = CW_IDLE -- self:SetNextSecondaryFire(CT + self.ForcedHipWaitTime) -- else -- self:SetNextSecondaryFire(CT + self.FireDelay) -- end -- -- self.ReloadWait = CT + (self.WaitForReloadAfterFiring and self.WaitForReloadAfterFiring or self.FireDelay) -- -- CustomizableWeaponry.callbacks.processCategory(self, "postConsumeAmmo") --end
require("main/colors") require("main/options") require("main/keymaps") vim.opt.secure = true
--[[ Script to train a RNN network. ]] local function exec_command(command) print('\n') print('Executing command: ' .. command) print('\n') os.execute(command) end ------------------------------------------------------------------------------------------------------------ local function train_net(configs, expID, modelID) assert(configs) if expID then configs.expID = expID .. '-' .. g_hidden_dimension_size configs.model = modelID configs.dataset = g_dataset configs.rnn_size = g_hidden_dimension_size end --[[ Parse the configurations ]]-- local str_args = '' for k, v in pairs(configs) do str_args = str_args .. ('-%s %s '):format(k, v) end --[[ Start training the network ]]-- exec_command(('th train.lua %s'):format(str_args)) --[[ output the configurations ]]-- return configs end ------------------------------------------------------------------------------------------------------------ return train_net
local component = require('component') local sides = require('sides') local inv = component.inventory_controller local robot = require('robot') local shell = require('shell') local args, opts = shell.parse(...) --TODO: Documentation local slot = tonumber(opts.slot) local amount = tonumber(args[1]) or math.huge local s = sides.forward if opts.u or opts.up then s = sides.up end if opts.d or opts.down then s = sides.down end local fromSlot = tonumber(opts.from) local toSlot = nil if fromSlot ~= nil then toSlot = robot.select() robot.select(fromSlot) end local verbose = opts.v or opts.verbose local name = "" if verbose and inv then local stack = inv.getStackInInternalSlot() if stack then name = stack.name .. " " end end local success = false if slot then success = inv.dropIntoSlot(s, slot, amount) else if s == sides.up then success = robot.dropUp(amount) elseif s == sides.down then success = robot.dropDown(amount) else success = robot.drop(amount) end end if verbose then print(name .. tostring(success)) end if toSlot then robot.select(toSlot) end
if not modules then modules = { } end modules ['meta-pdf'] = { version = 1.001, comment = "companion to meta-pdf.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } if true then return -- or os.exit() end -- This file contains the history of the converter. We keep it around as it -- relates to the development of luatex. -- This is the third version. Version 1 converted to Lua code, -- version 2 gsubbed the file into TeX code, and version 3 uses -- the new lpeg functionality and streams the result into TeX. -- We will move old stuff to edu. --~ old lpeg 0.4 lpeg 0.5 --~ 100 times test graphic 2.45 (T:1.07) 0.72 (T:0.24) 0.580 (0.560 no table) -- 0.54 optimized for one space (T:0.19) --~ 100 times big graphic 10.44 4.30/3.35 nogb 2.914 (2.050 no table) -- 1.99 optimized for one space (T:0.85) --~ 500 times test graphic T:1.29 T:1.16 (T:1.10 no table) -- T:1.10 -- only needed for mp output on disk local concat, format, find, gsub, gmatch = table.concat, string.format, string.find, string.gsub, string.gmatch local tostring, tonumber, select = tostring, tonumber, select local lpegmatch = lpeg.match metapost = metapost or { } local metapost = metapost local context = context metapost.mptopdf = metapost.mptopdf or { } local mptopdf = metapost.mptopdf mptopdf.parsers = { } mptopdf.parser = 'none' mptopdf.nofconverted = 0 function mptopdf.reset() mptopdf.data = "" mptopdf.path = { } mptopdf.stack = { } mptopdf.texts = { } mptopdf.version = 0 mptopdf.shortcuts = false mptopdf.resetpath() end function mptopdf.resetpath() mptopdf.stack.close = false mptopdf.stack.path = { } mptopdf.stack.concat = nil mptopdf.stack.special = false end mptopdf.reset() function mptopdf.parsers.none() -- no parser set end function mptopdf.parse() mptopdf.parsers[mptopdf.parser]() end -- old code mptopdf.steps = { } mptopdf.descapes = { ['('] = "\\\\char40 ", [')'] = "\\\\char41 ", ['"'] = "\\\\char92 " } function mptopdf.descape(str) str = gsub(str,"\\(%d%d%d)",function(n) return "\\char" .. tonumber(n,8) .. " " end) return gsub(str,"\\([%(%)\\])",mptopdf.descapes) end function mptopdf.steps.descape(str) str = gsub(str,"\\(%d%d%d)",function(n) return "\\\\char" .. tonumber(n,8) .. " " end) return gsub(str,"\\([%(%)\\])",mptopdf.descapes) end function mptopdf.steps.strip() -- .3 per expr mptopdf.data = gsub(mptopdf.data,"^(.-)%%+Page:.-%c+(.*)%s+%a+%s+%%+EOF.*$", function(preamble, graphic) local bbox = "0 0 0 0" for b in gmatch(preamble,"%%%%%a+oundingBox: +(.-)%c+") do bbox = b end local name, version = gmatch(preamble,"%%%%Creator: +(.-) +(.-) ") mptopdf.version = tostring(version or "0") if find(preamble,"/hlw{0 dtransform",1,true) then mptopdf.shortcuts = true end -- the boundingbox specification needs to come before data, well, not really return bbox .. " boundingbox\n" .. "\nbegindata\n" .. graphic .. "\nenddata\n" end, 1) mptopdf.data = gsub(mptopdf.data,"%%%%MetaPostSpecials: +(.-)%c+", "%1 specials\n", 1) mptopdf.data = gsub(mptopdf.data,"%%%%MetaPostSpecial: +(.-)%c+", "%1 special\n") mptopdf.data = gsub(mptopdf.data,"%%.-%c+", "") end function mptopdf.steps.cleanup() if not mptopdf.shortcuts then mptopdf.data = gsub(mptopdf.data,"gsave%s+fill%s+grestore%s+stroke", "both") mptopdf.data = gsub(mptopdf.data,"([%d%.]+)%s+([%d%.]+)%s+dtransform%s+exch%s+truncate%s+exch%s+idtransform%s+pop%s+setlinewidth", function(wx,wy) if tonumber(wx) > 0 then return wx .. " setlinewidth" else return wy .. " setlinewidth" end end) mptopdf.data = gsub(mptopdf.data,"([%d%.]+)%s+([%d%.]+)%s+dtransform%s+truncate%s+idtransform%s+setlinewidth%s+pop", function(wx,wy) if tonumber(wx) > 0 then return wx .. " setlinewidth" else return wy .. " setlinewidth" end end) end end function mptopdf.steps.convert() mptopdf.data = gsub(mptopdf.data,"%c%((.-)%) (.-) (.-) fshow", function(str,font,scale) mptopdf.texts[mptopdf.texts+1] = {mptopdf.steps.descape(str), font, scale} return "\n" .. #mptopdf.texts .. " textext" end) mptopdf.data = gsub(mptopdf.data,"%[%s*(.-)%s*%]", function(str) return gsub(str,"%s+"," ") end) local t mptopdf.data = gsub(mptopdf.data,"%s*([^%a]-)%s*(%a+)", function(args,cmd) if cmd == "textext" then t = mptopdf.texts[tonumber(args)] return "metapost.mps.textext(" .. "\"" .. t[2] .. "\"," .. t[3] .. ",\"" .. t[1] .. "\")\n" else return "metapost.mps." .. cmd .. "(" .. gsub(args," +",",") .. ")\n" end end) end function mptopdf.steps.process() assert(loadstring(mptopdf.data))() -- () runs the loaded chunk end function mptopdf.parsers.gsub() mptopdf.steps.strip() mptopdf.steps.cleanup() mptopdf.steps.convert() mptopdf.steps.process() end -- end of old code -- from lua to tex function mptopdf.pdfcode(str) context.pdfliteral(str) -- \\MPScode end function mptopdf.texcode(str) context(str) end -- auxiliary functions function mptopdf.flushconcat() if mptopdf.stack.concat then mptopdf.pdfcode(concat(mptopdf.stack.concat," ") .. " cm") mptopdf.stack.concat = nil end end function mptopdf.flushpath(cmd) -- faster: no local function and loop if #mptopdf.stack.path > 0 then local path = { } if mptopdf.stack.concat then local sx, sy = mptopdf.stack.concat[1], mptopdf.stack.concat[4] local rx, ry = mptopdf.stack.concat[2], mptopdf.stack.concat[3] local tx, ty = mptopdf.stack.concat[5], mptopdf.stack.concat[6] local d = (sx*sy) - (rx*ry) local function mpconcat(px, py) return (sy*(px-tx)-ry*(py-ty))/d, (sx*(py-ty)-rx*(px-tx))/d end local stackpath = mptopdf.stack.path for k=1,#stackpath do local v = stackpath[k] v[1],v[2] = mpconcat(v[1],v[2]) if #v == 7 then v[3],v[4] = mpconcat(v[3],v[4]) v[5],v[6] = mpconcat(v[5],v[6]) end path[#path+1] = concat(v," ") end else local stackpath = mptopdf.stack.path for k=1,#stackpath do path[#path+1] = concat(stackpath[k]," ") end end mptopdf.flushconcat() mptopdf.texcode("\\MPSpath{" .. concat(path," ") .. "}") if mptopdf.stack.close then mptopdf.texcode("\\MPScode{h " .. cmd .. "}") else mptopdf.texcode("\\MPScode{" .. cmd .."}") end end mptopdf.resetpath() end function mptopdf.loaded(name) local ok, n mptopdf.reset() ok, mptopdf.data, n = resolvers.loadbinfile(name, 'tex') -- we need a binary load ! return ok end if not mptopdf.parse then function mptopdf.parse() end -- forward declaration end function mptopdf.convertmpstopdf(name) if mptopdf.loaded(name) then mptopdf.nofconverted = mptopdf.nofconverted + 1 statistics.starttiming(mptopdf) mptopdf.parse() mptopdf.reset() statistics.stoptiming(mptopdf) else context("file " .. name .. " not found") end end -- mp interface metapost.mps = metapost.mps or { } local mps = metapost.mps or { } function mps.creator(a, b, c) mptopdf.version = tonumber(b) end function mps.creationdate(a) mptopdf.date= a end function mps.newpath() mptopdf.stack.path = { } end function mps.boundingbox(llx, lly, urx, ury) mptopdf.texcode("\\MPSboundingbox{" .. llx .. "}{" .. lly .. "}{" .. urx .. "}{" .. ury .. "}") end function mps.moveto(x,y) mptopdf.stack.path[#mptopdf.stack.path+1] = {x,y,"m"} end function mps.curveto(ax, ay, bx, by, cx, cy) mptopdf.stack.path[#mptopdf.stack.path+1] = {ax,ay,bx,by,cx,cy,"c"} end function mps.lineto(x,y) mptopdf.stack.path[#mptopdf.stack.path+1] = {x,y,"l"} end function mps.rlineto(x,y) local dx, dy = 0, 0 if #mptopdf.stack.path > 0 then dx, dy = mptopdf.stack.path[#mptopdf.stack.path][1], mptopdf.stack.path[#mptopdf.stack.path][2] end mptopdf.stack.path[#mptopdf.stack.path+1] = {dx,dy,"l"} end function mps.translate(tx,ty) mptopdf.pdfcode("1 0 0 0 1 " .. tx .. " " .. ty .. " cm") end function mps.scale(sx,sy) mptopdf.stack.concat = {sx,0,0,sy,0,0} end function mps.concat(sx, rx, ry, sy, tx, ty) mptopdf.stack.concat = {sx,rx,ry,sy,tx,ty} end function mps.setlinejoin(d) mptopdf.pdfcode(d .. " j") end function mps.setlinecap(d) mptopdf.pdfcode(d .. " J") end function mps.setmiterlimit(d) mptopdf.pdfcode(d .. " M") end function mps.gsave() mptopdf.pdfcode("q") end function mps.grestore() mptopdf.pdfcode("Q") end function mps.setdash(...) local n = select("#",...) mptopdf.pdfcode("[" .. concat({...}," ",1,n-1) .. "] " .. select(n,...) .. " d") end function mps.resetdash() mptopdf.pdfcode("[ ] 0 d") end function mps.setlinewidth(d) mptopdf.pdfcode(d .. " w") end function mps.closepath() mptopdf.stack.close = true end function mps.fill() mptopdf.flushpath('f') end function mps.stroke() mptopdf.flushpath('S') end function mps.both() mptopdf.flushpath('B') end function mps.clip() mptopdf.flushpath('W n') end function mps.textext(font, scale, str) -- old parser local dx, dy = 0, 0 if #mptopdf.stack.path > 0 then dx, dy = mptopdf.stack.path[1][1], mptopdf.stack.path[1][2] end mptopdf.flushconcat() mptopdf.texcode("\\MPStextext{"..font.."}{"..scale.."}{"..str.."}{"..dx.."}{"..dy.."}") mptopdf.resetpath() end --~ function mps.handletext(font,scale.str,dx,dy) --~ local one, two = string.match(str, "^(%d+)::::(%d+)") --~ if one and two then --~ mptopdf.texcode("\\MPTOPDFtextext{"..font.."}{"..scale.."}{"..one.."}{"..two.."}{"..dx.."}{"..dy.."}") --~ else --~ mptopdf.texcode("\\MPTOPDFtexcode{"..font.."}{"..scale.."}{"..str.."}{"..dx.."}{"..dy.."}") --~ end --~ end function mps.setrgbcolor(r,g,b) -- extra check r, g = tonumber(r), tonumber(g) -- needed when we use lpeg if r == 0.0123 and g < 0.1 then mptopdf.texcode("\\MPSspecial{" .. g*10000 .. "}{" .. b*10000 .. "}") elseif r == 0.123 and g < 0.1 then mptopdf.texcode("\\MPSspecial{" .. g* 1000 .. "}{" .. b* 1000 .. "}") else mptopdf.texcode("\\MPSrgb{" .. r .. "}{" .. g .. "}{" .. b .. "}") end end function mps.setcmykcolor(c,m,y,k) mptopdf.texcode("\\MPScmyk{" .. c .. "}{" .. m .. "}{" .. y .. "}{" .. k .. "}") end function mps.setgray(s) mptopdf.texcode("\\MPSgray{" .. s .. "}") end function mps.specials(version,signal,factor) -- 2.0 123 1000 end function mps.special(...) -- 7 1 0.5 1 0 0 1 3 local n = select("#",...) mptopdf.texcode("\\MPSbegin\\MPSset{" .. concat({...},"}\\MPSset{",2,n) .. "}\\MPSend") end function mps.begindata() end function mps.enddata() end function mps.showpage() end mps.n = mps.newpath -- n mps.p = mps.closepath -- h mps.l = mps.lineto -- l mps.r = mps.rlineto -- r mps.m = mps.moveto -- m mps.c = mps.curveto -- c mps.hlw = mps.setlinewidth mps.vlw = mps.setlinewidth mps.C = mps.setcmykcolor -- k mps.G = mps.setgray -- g mps.R = mps.setrgbcolor -- rg mps.lj = mps.setlinejoin -- j mps.ml = mps.setmiterlimit -- M mps.lc = mps.setlinecap -- J mps.sd = mps.setdash -- d mps.rd = mps.resetdash mps.S = mps.stroke -- S mps.F = mps.fill -- f mps.B = mps.both -- B mps.W = mps.clip -- W mps.q = mps.gsave -- q mps.Q = mps.grestore -- Q mps.s = mps.scale -- (not in pdf) mps.t = mps.concat -- (not the same as pdf anyway) mps.P = mps.showpage -- experimental function mps.attribute(id,value) mptopdf.texcode("\\attribute " .. id .. "=" .. value .. " ") -- mptopdf.texcode("\\dompattribute{" .. id .. "}{" .. value .. "}") end -- lpeg parser -- The lpeg based parser is rather optimized for the kind of output -- that MetaPost produces. It's my first real lpeg code, which may -- show. Because the parser binds to functions, we define it last. do -- assumes \let\c\char local byte = string.byte local digit = lpeg.R("09") local spec = digit^2 * lpeg.P("::::") * digit^2 local text = lpeg.Cc("{") * ( lpeg.P("\\") * ( (digit * digit * digit) / function(n) return "c" .. tonumber(n,8) end) + lpeg.P(" ") / function(n) return "\\c32" end + -- never in new mp lpeg.P(1) / function(n) return "\\c" .. byte(n) end ) * lpeg.Cc("}") local package = lpeg.Cs(spec + text^0) function mps.fshow(str,font,scale) -- lpeg parser mps.textext(font,scale,lpegmatch(package,str)) end end do local eol = lpeg.S('\r\n')^1 local sp = lpeg.P(' ')^1 local space = lpeg.S(' \r\n')^1 local number = lpeg.S('0123456789.-+')^1 local nonspace = lpeg.P(1-lpeg.S(' \r\n'))^1 local cnumber = lpeg.C(number) local cstring = lpeg.C(nonspace) local specials = (lpeg.P("%%MetaPostSpecials:") * sp * (cstring * sp^0)^0 * eol) / mps.specials local special = (lpeg.P("%%MetaPostSpecial:") * sp * (cstring * sp^0)^0 * eol) / mps.special local boundingbox = (lpeg.P("%%BoundingBox:") * sp * (cnumber * sp^0)^4 * eol) / mps.boundingbox local highresboundingbox = (lpeg.P("%%HiResBoundingBox:") * sp * (cnumber * sp^0)^4 * eol) / mps.boundingbox local setup = lpeg.P("%%BeginSetup") * (1 - lpeg.P("%%EndSetup") )^1 local prolog = lpeg.P("%%BeginProlog") * (1 - lpeg.P("%%EndProlog"))^1 local comment = lpeg.P('%')^1 * (1 - eol)^1 local curveto = ((cnumber * sp)^6 * lpeg.P("curveto") ) / mps.curveto local lineto = ((cnumber * sp)^2 * lpeg.P("lineto") ) / mps.lineto local rlineto = ((cnumber * sp)^2 * lpeg.P("rlineto") ) / mps.rlineto local moveto = ((cnumber * sp)^2 * lpeg.P("moveto") ) / mps.moveto local setrgbcolor = ((cnumber * sp)^3 * lpeg.P("setrgbcolor") ) / mps.setrgbcolor local setcmykcolor = ((cnumber * sp)^4 * lpeg.P("setcmykcolor") ) / mps.setcmykcolor local setgray = ((cnumber * sp)^1 * lpeg.P("setgray") ) / mps.setgray local newpath = ( lpeg.P("newpath") ) / mps.newpath local closepath = ( lpeg.P("closepath") ) / mps.closepath local fill = ( lpeg.P("fill") ) / mps.fill local stroke = ( lpeg.P("stroke") ) / mps.stroke local clip = ( lpeg.P("clip") ) / mps.clip local both = ( lpeg.P("gsave fill grestore")) / mps.both local showpage = ( lpeg.P("showpage") ) local setlinejoin = ((cnumber * sp)^1 * lpeg.P("setlinejoin") ) / mps.setlinejoin local setlinecap = ((cnumber * sp)^1 * lpeg.P("setlinecap") ) / mps.setlinecap local setmiterlimit = ((cnumber * sp)^1 * lpeg.P("setmiterlimit") ) / mps.setmiterlimit local gsave = ( lpeg.P("gsave") ) / mps.gsave local grestore = ( lpeg.P("grestore") ) / mps.grestore local setdash = (lpeg.P("[") * (cnumber * sp^0)^0 * lpeg.P("]") * sp * cnumber * sp * lpeg.P("setdash")) / mps.setdash local concat = (lpeg.P("[") * (cnumber * sp^0)^6 * lpeg.P("]") * sp * lpeg.P("concat") ) / mps.concat local scale = ( (cnumber * sp^0)^6 * sp * lpeg.P("concat") ) / mps.concat local fshow = (lpeg.P("(") * lpeg.C((1-lpeg.P(")"))^1) * lpeg.P(")") * space * cstring * space * cnumber * space * lpeg.P("fshow")) / mps.fshow local fshow = (lpeg.P("(") * lpeg.Cs( ( lpeg.P("\\(")/"\\050" + lpeg.P("\\)")/"\\051" + (1-lpeg.P(")")) )^1 ) * lpeg.P(")") * space * cstring * space * cnumber * space * lpeg.P("fshow")) / mps.fshow local setlinewidth_x = (lpeg.P("0") * sp * cnumber * sp * lpeg.P("dtransform truncate idtransform setlinewidth pop")) / mps.setlinewidth local setlinewidth_y = (cnumber * sp * lpeg.P("0 dtransform exch truncate exch idtransform pop setlinewidth") ) / mps.setlinewidth local c = ((cnumber * sp)^6 * lpeg.P("c") ) / mps.curveto -- ^6 very inefficient, ^1 ok too local l = ((cnumber * sp)^2 * lpeg.P("l") ) / mps.lineto local r = ((cnumber * sp)^2 * lpeg.P("r") ) / mps.rlineto local m = ((cnumber * sp)^2 * lpeg.P("m") ) / mps.moveto local vlw = ((cnumber * sp)^1 * lpeg.P("vlw")) / mps.setlinewidth local hlw = ((cnumber * sp)^1 * lpeg.P("hlw")) / mps.setlinewidth local R = ((cnumber * sp)^3 * lpeg.P("R") ) / mps.setrgbcolor local C = ((cnumber * sp)^4 * lpeg.P("C") ) / mps.setcmykcolor local G = ((cnumber * sp)^1 * lpeg.P("G") ) / mps.setgray local lj = ((cnumber * sp)^1 * lpeg.P("lj") ) / mps.setlinejoin local ml = ((cnumber * sp)^1 * lpeg.P("ml") ) / mps.setmiterlimit local lc = ((cnumber * sp)^1 * lpeg.P("lc") ) / mps.setlinecap local n = lpeg.P("n") / mps.newpath local p = lpeg.P("p") / mps.closepath local S = lpeg.P("S") / mps.stroke local F = lpeg.P("F") / mps.fill local B = lpeg.P("B") / mps.both local W = lpeg.P("W") / mps.clip local P = lpeg.P("P") / mps.showpage local q = lpeg.P("q") / mps.gsave local Q = lpeg.P("Q") / mps.grestore local sd = (lpeg.P("[") * (cnumber * sp^0)^0 * lpeg.P("]") * sp * cnumber * sp * lpeg.P("sd")) / mps.setdash local rd = ( lpeg.P("rd")) / mps.resetdash local s = ( (cnumber * sp^0)^2 * lpeg.P("s") ) / mps.scale local t = (lpeg.P("[") * (cnumber * sp^0)^6 * lpeg.P("]") * sp * lpeg.P("t") ) / mps.concat -- experimental local attribute = ((cnumber * sp)^2 * lpeg.P("attribute")) / mps.attribute local A = ((cnumber * sp)^2 * lpeg.P("A")) / mps.attribute local preamble = ( prolog + setup + boundingbox + highresboundingbox + specials + special + comment ) local procset = ( lj + ml + lc + c + l + m + n + p + r + A + R + C + G + S + F + B + W + vlw + hlw + Q + q + sd + rd + t + s + fshow + P ) local verbose = ( curveto + lineto + moveto + newpath + closepath + rlineto + setrgbcolor + setcmykcolor + setgray + attribute + setlinejoin + setmiterlimit + setlinecap + stroke + fill + clip + both + setlinewidth_x + setlinewidth_y + gsave + grestore + concat + scale + fshow + setdash + -- no resetdash showpage ) -- order matters in terms of speed / we could check for procset first local captures_old = ( space + verbose + preamble )^0 local captures_new = ( space + procset + preamble + verbose )^0 function mptopdf.parsers.lpeg() if find(mptopdf.data,"%%BeginResource: procset mpost",1,true) then lpegmatch(captures_new,mptopdf.data) else lpegmatch(captures_old,mptopdf.data) end end end mptopdf.parser = 'lpeg' -- status info statistics.register("mps conversion time",function() local n = mptopdf.nofconverted if n > 0 then return format("%s seconds, %s conversions", statistics.elapsedtime(mptopdf),n) else return nil end end)
local s = smartfs.create("smartfs:form", function(state) state:size(10,7) state:label(2,0,"lbl","SmartFS example formspec!") local usr = state:label(7,0,"user","") if state.location.type ~= "nodemeta" then -- display location user name if it is user or inventory formspec usr:setText(state.location.player) end usr:setSize(3,0.5) usr:setBackground("halo.png") local textbox = state:field(7.25,1.25,3,1,"txt","Textbox") textbox:setCloseOnEnter(false) textbox:onKeyEnter(function(self, state, playername) print("Enter pressed in Textbox field") end) state:image(0,0,2,2,"img","default_stone.png") local toggle = state:toggle(0,2,3,1,"tg",{"plenty..","of..","custom..","elements"}) toggle:onToggle(function(self, state, player) if state:get("ta"):getVisible() == false then state:get("ta"):setVisible() else state:get("ta"):setVisible(false) end end) state:checkbox(2,1,"c","Easy code",true) state:vertlabel(0,3.5,"vlbl","Example!") local area = state:textarea(1,3.5,9,4,"ta","Code:") local res = [[ smartfs.create("smartfs:form",function(state) state:size(10,7) state:label(2,0,"lbl","SmartFS example formspec!") state:field(7,1,3,1,"txt","Textbox") state:image(0,0,2,2,"img","default_stone.png") state:toggle(0,2,3,1,"tg",{"plenty..","of..","custom..","elements"}) state:checkbox(2,1,"c","Easy code",true) end)]] area:setText(res) state:onInput(function(self, fields, user) -- processed on any (supported) input if state.location.type == "nodemeta" then usr:setText(user) -- display current user who sent the data end end) return true end) local l = smartfs.create("smartfs:load", function(state) state:load(minetest.get_modpath("smartfs").."/docs/example.smartfs") state:get("btn"):click(function(self,state) print("Button clicked!") end) return true end) smartfs.add_to_inventory(l,"icon.png","SmartFS") minetest.register_chatcommand("sfs_s", { params = "", description = "SmartFS test formspec 1: basics", func = function(name, param) s:show(name) end, }) minetest.register_chatcommand("sfs_l", { params = "", description = "SmartFS test formspec 2: loading", func = function(name, param) l:show(name) end, }) minetest.register_chatcommand("sfs_d", { params = "", description = "SmartFS test formspec 3: dynamic", func = function(name, param) local state = smartfs.dynamic("smartfs:dyn_form", name) state:load(minetest.get_modpath("smartfs").."/docs/example.smartfs") state:get("btn"):click(function(self,state) print("Button clicked!") end) state:show() end, }) minetest.register_chatcommand("sfs_lc", { params = "", description = "SmartFS test formspec 4: smartfs.create error catching", func = function(name, param) smartfs.create("asdinas", function() end) end }) minetest.register_node("smartfs:demoblock", { description = "SmartFS Demo block", groups = {cracky = 3}, tiles = {"demo.png"}, after_place_node = function(pos, placer, itemstack, pointed_thing) s:attach_to_node(pos, placer) end, on_receive_fields = smartfs.nodemeta_on_receive_fields })
local lib, config, corelib = {}, {}, {} local engine_core = {} local engine_path = debug.getinfo(1).short_src:match("([^%.]*)[\\/][^%.]*%..*$"):gsub("[\\/]", ".") .. "." config.engine_path = engine_path local version_meta = { __tostring = function(self) return table.concat(self, ".") end } local lib_batch_load = function(batch) for key, lib_name in next, batch do local name = lib_name:match("([^%.:]*)$") local loaded = require(lib_name:gsub("^:", config.engine_path)) loaded:init(engine_core) lib[name] = loaded corelib[name] = loaded end end engine_core.init = function(self, glib) lib = glib or lib self.lib = lib config = require(engine_path .. "config") config.engine_path = config.engine_path or engine_path self.config = config setmetatable(config.version, version_meta) lib_batch_load(config.lib_core) self:lib_load(config.lib_folders) self:lib_batch_call("post_init") return self end engine_core.close = function(self) for key, library in pairs(corelib) do if (library.close) then library:close(self) end end self.lib = {} corelib = {} end engine_core.quit = function(self) love.event.push("quit") self:close() end return engine_core
local chatdown=require("wetgenes.gamecake.fun.chatdown") -- conversation trees local bitdown=require("wetgenes.gamecake.fun.bitdown") -- ascii to bitmap local chipmunk=require("wetgenes.chipmunk") -- 2d physics https://chipmunk-physics.net/ -- debug text dump local ls=function(t) print(require("wetgenes.string").dump(t)) end ----------------------------------------------------------------------------- --[[#hardware select the hardware we will need to run this code, eg layers of graphics, colors to use, sprites, text, sound, etc etc. Here we have chosen the default 320x240 setup. ]] ----------------------------------------------------------------------------- hardware,main=system.configurator({ mode="fun64", -- select the standard 320x240 screen using the swanky32 palette. graphics=function() return graphics end, update=function() update() end, -- called repeatedly to update draw=function() draw() end, -- called repeatedly to draw }) ----------------------------------------------------------------------------- --[[#graphics define all graphics in this global, we will convert and upload to tiles at setup although you can change tiles during a game, we try and only upload graphics during initial setup so we have a nice looking sprite sheet to be edited by artists ]] ----------------------------------------------------------------------------- graphics={ {0x0000,"_font",0x0140}, -- allocate the font area } -- load a single sprite graphics.load=function(idx,name,data) local found for i,v in ipairs(graphics) do if v[2]==name then found=v break end end if not found then -- add new graphics graphics[#graphics+1]={idx,name,data} else found[1]=idx found[2]=name found[3]=data end end -- load a list of sprites graphics.loads=function(tab) for i,v in ipairs(tab) do graphics.load(v[1],v[2],v[3]) end end ----------------------------------------------------------------------------- --[[#entities entities.reset() empty the list of entites to update and draw entities.caste(caste) get the list of entities of a given caste, eg "bullets" or "enemies" entities.add(it,caste) entities.add(it) add a new entity of caste or it.caste to the list of things to update entities.call(fname,...) for every entity call the function named fname like so it[fname](it,...) entities.get(name) get a value previously saved, this is an easy way to find a unique entity, eg the global space but it can be used to save any values you wish not just to bookmark unique entities. entities.set(name,value) save a value by a unique name entities.manifest(name,value) get a value previously saved, or initalize it to the given value if it does not already exist. The default value is {} as this is intended for lists. entities.systems A table to register or find a global system, these are not cleared by reset and should not contain any state data, just functions to create the actual entity or initialise data. entities.tiles These functions are called as we generate a level from ascii, every value in the tile legend data is checked against all the strings in entities.tiles and if it matches it calls that function which is then responsible for adding the appropriate collision and drawing code to make that tile actually add something to the level. The basic values of tile.tile and tile.back are used to write graphics into the two tile layers but could still be caught here if you need to. Multiple hooks may get called for a single tile, think of each string as a flag to signal that something happens and its value describes what happens. ]] ----------------------------------------------------------------------------- entities={systems={},tiles={}} -- a place to store everything that needs to be updated entities.reset=function() entities.data={} entities.info={} end -- get items for the given caste entities.caste=function(caste) caste=caste or "generic" if not entities.data[caste] then entities.data[caste]={} end -- create on use return entities.data[caste] end -- add an item to this caste entities.add=function(it,caste) caste=caste or it.caste -- probably from item caste=caste or "generic" local items=entities.caste(caste) items[ #items+1 ]=it -- add to end of array return it end -- call this functions on all items in every caste entities.call=function(fname,...) local count=0 for caste,items in pairs(entities.data) do for idx=#items,1,-1 do -- call backwards so item can remove self local it=items[idx] if it[fname] then it[fname](it,...) count=count+1 end end end return count -- number of items called end -- get/set info associated with this entities entities.get=function(name) return entities.info[name] end entities.set=function(name,value) entities.info[name]=value return value end entities.manifest=function(name,empty) if not entities.info[name] then entities.info[name]=empty or {} end -- create empty return entities.info[name] end -- also reset the entities right now entities.reset() ----------------------------------------------------------------------------- --[[#entities.systems.space space = entities.systems.space.setup() Create the space that simulates all of the physics. ]] ----------------------------------------------------------------------------- entities.systems.space={ setup=function() local space=entities.set("space", chipmunk.space() ) space:gravity(0,700) space:damping(0.5) space:sleep_time_threshold(1) space:idle_speed_threshold(10) -- run all arbiter space hooks that have been registered for n,v in pairs(entities.systems) do if v.space then v:space() end end return space end, } ----------------------------------------------------------------------------- --[[#entities.systems.tile setup background tile graphics ]] ----------------------------------------------------------------------------- entities.systems.tile={ load=function() graphics.loads{ {nil,"tile_empty",[[ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]]}, {nil,"tile_black",[[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ]]}, {nil,"tile_wall",[[ O O R R R R O O O O R R R R O O r r r r o o o o r r r r o o o o R R O O O O R R R R O O O O R R o o o o r r r r o o o o r r r r ]]}, {nil,"tile_floor",[[ j j j j j j j j j j j j j j j j j f f f f f f f f j j j j j j j j j j j j j j j f f f F F F F f f f f f f f f f f F F F F F F F F f f f f f f j j j j j f f f f F F F f f f f F F F F F F F F F F f f f f f f f f F F F F F F f f f f f F F F F f f f f f f f f f f F F F F f f f f f f f f f f f f f f f f f F F F F F f f f f f f f j j j j f f f f f f f f f f j j j j j j j j f f f f f f f f f f f f f f f j j j f f f f j j j f f f f j j j f f f f f f f f j j j j j j f f f f f j j j j f f f j j j j f f f j j j j f f f j j j j j j j j f f f f f f j j j j j f f f f j j j j j j j j j j j j j j j j j j j j j j j j j j j j j j j j j j j j j j j j ]]}, {nil,"tile_bigwall",[[ j j j j r r r r i i i i f f f f r r r r i i i i i i i i f f f f r r r r f f f f j j j j r r r r i i i i f f f f r r r r i i i i i i i i f f f f r r r r f f f f O O R R R R j j j j O O O O r r r r O O O O f f f f F F F F O O O O f f f f O O O O R R R R j j j j O O O O r Y Y r O O O O f Y f f F F F F O O O O f f f f O O j j j j R R R R r r r r R R Y Y Y j j j R R R Y i i i i R R R R O O O O R R R R j j j j R R R R r r r r R Y Y Y Y Y Y Y Y Y Y Y Y i i i R R R R O O O O R R R R r r O O O O j j j j R R Y Y j Y Y Y Y Y Y R j Y Y Y R R R R j j j j R R R R r r r r O O O O j j j j R R Y R j Y Y Y Y R R R j Y Y Y Y Y R R j j j j R R R R r r i i i i f f f f r r r r f f f Y Y j j j r r r r i Y Y Y f f f f r r r r i i i i i i i i f f f f r r r r f f f Y j j j j r r r r i Y Y Y Y f f f r r r r i i i i f f F F F F O O O O f f f f O Y O O R R R R j j j j Y Y Y O r r r r O O O O f f f f F F F F O O O O f f f f O Y O O R R R R j j j j O O O O r r r r O O O O f f i i i i R R R R O O O O R R R R j j j j R R R R r r r r R R R R j j j j R R R R i i i i R R R R O O O O R R R R j j j j R R R R r r r r R R R R j j j j R R R R j j R R R R j j j j R R R R r r r r O O O O j j j j R R R R j j j j R R R R j j j j R R R R j j j j R R R R r r r r O O O O j j j j R R R R j j j j R R R R j j ]]}, {nil,"tile_grass",[[ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . G . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . g G g . . . . . . . . . . . . . g . . . . . . . . g . g . . . . g G G . G . g . g . G . . . . g . . . g g . g . . G . . g . . g ]]}, {nil,"tile_stump",[[ . . F F F F . . f F f f f f F f j f F F F F f j j j f f f j f j j f f f j j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j ]]}, {nil,"tile_sidewood",[[ j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j j f F f f j f j ]]}, {nil,"tile_tree",[[ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . j . . . . . . . . . j . . . . . j . . . . . . . . . . f . . . j . . . . . . . . . . . f F . j . . . . . . . . . . . . . f F j . . j . . . . . . . . . . j f F . f . . . . . . . . . . . . . f . j . . . . . . . . . . . . . f F f . . . . . . . . . . . j F f f f . . . . . . . . . . . . f F j . . . . . . . . . . . . . j F j . . . . . . . . . . . . . j f j . . . . . . . . . . . . . . F j . . . . . . . . . . j F F . f f . . . . . . . . . . . j F F j f j . . . . . . . . . . . j f j f . . . . . . . . . . . . . f f F f j j . . . . . . . . . . j F f j . . . . . . . . . . . . . f F . . . . . . . . . . . . . . f f . . . . . . . . . . . . . . j F . . . . . . . . . . . . . f f F f . . . . . . ]]}, {nil,"tile_sign",[[ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . f . . . . . . . . . . . . . . . F f . . . . f f f 5 f f f 5 f f f F f . . . f F 4 F F F 4 F 4 F F f F f . . f j 3 j 3 j 3 j 3 j j f F f . . f j j 2 2 j j 2 j j f F f . . . . . . . j j j . . . F f . . . . . . . . F j j . . . f . . . . . . . . . F f j . . . . . . . . . . . . . F f j . . . . . . . . . . . . . F f j . . . . . . . . . . . . . F f j . . . . . . . ]]}, {nil,"tile_postbox",[[ . m m m m m m . m R R R R R R m m m m m m m m f m R R R R R R f m R 0 0 0 0 R f m R R R R R R f m R 3 2 3 2 R f m R 2 3 2 3 R f m R R R R R R f m R R R R R R f m R R R R R R f m R R R R R f f m R R R R f R f R R R R f R f f f R R f R f f f . f f f f f f . ]]}, }end, space=function() local space=entities.get("space") local arbiter_deadly={} -- deadly things arbiter_deadly.presolve=function(it) local callbacks=entities.manifest("callbacks") if it.shape_b.player then -- trigger die local pb=it.shape_b.player callbacks[#callbacks+1]=function() pb:die() end end return true end space:add_handler(arbiter_deadly,space:type("deadly")) local arbiter_crumbling={} -- crumbling tiles arbiter_crumbling.presolve=function(it) local points=it:points() -- once we trigger headroom, we keep a table of headroom shapes and it is not reset until total separation if it.shape_b.in_body.headroom then local headroom=false -- for n,v in pairs(it.shape_b.in_body.headroom) do headroom=true break end -- still touching an old headroom shape? -- if ( (points.normal_y>0) or headroom) then -- can only headroom through non dense tiles if ( (points.normal_y>0) or it.shape_b.in_body.headroom[it.shape_a] ) then it.shape_b.in_body.headroom[it.shape_a]=true return it:ignore() end local tile=it.shape_a.tile -- a humanoid is walking on this tile if tile then tile.level.updates[tile]=true -- start updates to animate this tile crumbling away end end return true end arbiter_crumbling.separate=function(it) if it.shape_a and it.shape_b and it.shape_b.in_body then if it.shape_b.in_body.headroom then -- only players types will have headroom it.shape_b.in_body.headroom[it.shape_a]=nil end end end space:add_handler(arbiter_crumbling,space:type("crumbling")) end, } ----------------------------------------------------------------------------- --[[#entities.systems.item item = entities.systems.item.add() items, can be used for general things, EG physics shapes with no special actions ]] ----------------------------------------------------------------------------- entities.systems.item={ load=function() graphics.loads{ {nil,"cannon_ball",[[ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . O O O O . . . . . . . . . . . . . . . . . R O O O O O O O O R . . . . . . . . . . . . . R R R O O O O O O R R R . . . . . . . . . . . R R R R O O O O O O R R R R . . . . . . . . . . 5 R R R R O O O O R R R R c . . . . . . . . . . 5 5 5 R R O O O O R R c c c . . . . . . . . . 5 5 5 5 5 5 R 0 0 R c c c c c c . . . . . . . . 5 5 5 5 5 5 0 0 0 0 c c c c c c . . . . . . . . 5 5 5 5 5 5 0 0 0 0 c c c c c c . . . . . . . . 5 5 5 5 5 5 R 0 0 R c c c c c c . . . . . . . . . 5 5 5 R R o o o o R R c c c . . . . . . . . . . 5 R R R R o o o o R R R R c . . . . . . . . . . R R R R o o o o o o R R R R . . . . . . . . . . . R R R o o o o o o R R R . . . . . . . . . . . . . R o o o o o o o o R . . . . . . . . . . . . . . . . . o o o o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]]}, }end, space=function() end, add=function() local item=entities.add{caste="item"} item.draw=function() if item.active then local px,py,rz=item.px,item.py,item.rz if item.body then -- from fizix px,py=item.body:position() rz=item.body:angle() end rz=item.draw_rz or rz -- always face up? system.components.sprites.list_add({t=item.sprite,h=item.h,hx=item.hx,hy=item.hy,s=item.s,sx=item.sx,sy=item.sy,px=px,py=py,rz=180*rz/math.pi,color=item.color,pz=item.pz}) end end return item end, } ----------------------------------------------------------------------------- --[[#entities.systems.score score = entities.systems.score.setup() Create entity that handles the score hud update and display ]] ----------------------------------------------------------------------------- entities.systems.score={ space=function() local space=entities.get("space") local arbiter_loot={} -- loot things (pickups) arbiter_loot.presolve=function(it) if it.shape_a.loot and it.shape_b.player then -- trigger collect it.shape_a.loot.player=it.shape_b.player end return false end space:add_handler(arbiter_loot,space:type("loot")) end, setup=function() local score=entities.set("score",entities.add{}) entities.set("time",{ game=0, }) score.update=function() local time=entities.get("time") time.game=time.game+(1/60) end score.draw=function() --[[ local time=entities.get("time") local remain=0 for _,loot in ipairs( entities.caste("loot") ) do if loot.active then remain=remain+1 end -- count remaining loots end if remain==0 and not time.finish then -- done time.finish=time.game end local t=time.start and ( (time.finish or time.game) - ( time.start ) ) or 0 local ts=math.floor(t) local tp=math.floor((t%1)*100) local s=string.format("%d.%02d",ts,tp) system.components.text.text_print(s,math.floor((system.components.text.tilemap_hx-#s)/2),0) ]] local s="" local level=entities.get("level") s=level.title or s for i,player in pairs(entities.caste("player")) do if player.near_menu then s=player.near_menu.title end if player.near_npc then local chats=entities.get("chats") local chat=chats:get_subject(player.near_npc.name) s=chat:get_tag("title") or s end end system.components.text.text_print(s,math.floor((system.components.text.tilemap_hx-#s)/2),system.components.text.tilemap_hy-1) end return score end, } ----------------------------------------------------------------------------- --[[#entities.systems.player player = entities.systems.player.add(idx) Add a player, level should be setup before calling this ]] ----------------------------------------------------------------------------- entities.systems.player={ load=function() graphics.loads{ -- 4 x 16x32 {nil,"skel_walk_4",[[ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . 7 7 7 7 7 . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . 7 7 7 7 7 . . . . . . . . . . . 7 7 7 7 7 . . . . . . . . . . . 7 0 7 0 7 . . . . . . . . . . . 7 7 7 7 7 . . . . . . . . . . . 7 0 7 0 7 . . . . . . . . . . . 7 0 7 0 7 . . . . . . . . . . . 7 7 0 7 7 . . . . . . . . . . . 7 0 7 0 7 . . . . . . . . . . . 7 7 0 7 7 . . . . . . . . . . . 7 7 0 7 7 . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . 7 7 0 7 7 . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . . 7 0 7 . . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . . 7 0 7 . . . . . . . . . . . . . 7 0 7 . . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . . 7 0 7 . . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . . 7 7 7 . . . . . . . . . 7 7 7 . 7 . 7 7 . . . . . . . . . . . . 7 7 7 . . . . . . . . . 7 7 7 . 7 . . 7 7 . . . . . . . . 7 7 . 7 . 7 7 . . . . . . . . 7 . . 7 7 7 7 7 . . . . . . . . 7 7 7 . 7 . . 7 7 . . . . . . . 7 . . 7 7 7 7 . 7 . . . . . . . . 7 . 7 7 7 7 7 . . . . . . . . 7 . 7 . 7 . . 7 . . . . . . . . 7 . . 7 7 7 7 . 7 . . . . . . . 7 . 7 . 7 . . 7 7 . . . . . . . . 7 7 . 7 . . 7 . . . . . . . . 7 . . 7 7 7 7 7 . . . . . . . . 7 . 7 . 7 . . 7 7 . . . . . . . 7 . . 7 7 7 7 . 7 . . . . . . . . 7 . 7 7 7 7 7 . . . . . . . . 7 7 7 . 7 . . 7 7 . . . . . . 7 7 . . 7 7 7 7 . 7 7 . . . . . . 7 7 7 . 7 . . 7 7 . . . . . . . . 7 7 . 7 . . 7 . . . . . . . . . 7 . 7 7 7 7 . 7 . . . . . . 7 . . 7 . 7 . . 7 . 7 . . . . . . . 7 . 7 7 7 7 7 . . . . . . . . . 7 . 7 7 7 7 7 . . . . . . . . . 7 7 . 7 7 . 7 7 . . . . . . 7 . . . 7 7 7 7 . . 7 . . . . . . . 7 7 . 7 7 . 7 . . . . . . . . . 7 7 . 7 7 . 7 . . . . . . . . . 7 7 7 7 7 7 7 7 7 . . . . . 7 . . 7 . 7 7 . 7 . 7 . . . . . . . 7 7 7 7 7 7 7 . . . . . . . . . 7 7 7 7 7 7 7 . . . . . . . . . 7 7 7 7 . 7 . 7 7 . . . . . 7 7 . 7 7 7 7 7 7 7 7 . . . . . . . 7 7 7 . . 7 7 . . . . . . . . . 7 7 7 . . 7 7 . . . . . . . . . . . . 7 . 7 . . . . . . . . 7 7 . . 7 . . 7 . 7 7 . . . . . . . . . 7 . . . 7 7 . . . . . . . . . 7 . . . . 7 . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . 7 . . 7 . . . . . . . . . . . . 7 . . . . 7 7 . . . . . . . 7 7 . . . . 7 7 . . . . . . . . . . . 7 7 7 7 . . . . . . . . . . . 7 7 7 7 . . . . . . . . . . . 7 7 . . . . 7 7 . . . . . . . 7 7 . . . . 7 7 . . . . . . . . . . 7 . . 7 7 . . . . . . . . . . . 7 7 7 7 . . . . . . . . . . . 7 7 . . . 7 . . . . . . . . . 7 . . . . . 7 . . . . . . . . . . . 7 . . 7 . . . . . . . . . . . . 7 . 7 . . . . . . . . . . . . 7 . . . . 7 . . . . . . . . . 7 . . . . . 7 . . . . . . . . . . 7 . . . 7 . . . . . . . . . . . . 7 . 7 . . . . . . . . . . . . 7 . . . 7 . . . . . . . . . . 7 . . . . . 7 . . . . . . . . . . 7 . . . 7 . . . . . . . . . . . . 7 . 7 . . . . . . . . . . . . 7 . . . 7 . . . . . . . . . . 7 . . . . . 7 . . . . . . . . . 7 7 7 7 . 7 . . . . . . . . . . . . 7 . 7 . . . . . . . . . . . . 7 . . 7 7 7 7 . . . . . . . 7 7 7 7 . . 7 7 7 7 . . . . . . . . . . . 7 7 7 7 . . . . . . . . . 7 7 7 7 7 7 . . . . . . . . . 7 7 7 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]]}, }end, space=function() local space=entities.get("space") local arbiter_pass={} -- background tiles we can jump up through arbiter_pass.presolve=function(it) local points=it:points() -- once we trigger headroom, we keep a table of headroom shapes and it is not reset until total separation if it.shape_b.in_body.headroom then local headroom=false -- for n,v in pairs(it.shape_b.in_body.headroom) do headroom=true break end -- still touching an old headroom shape? -- if ( (points.normal_y>0) or headroom) then -- can only headroom through non dense tiles if ( (points.normal_y>0) or it.shape_b.in_body.headroom[it.shape_a] ) then it.shape_b.in_body.headroom[it.shape_a]=true return it:ignore() end end return true end arbiter_pass.separate=function(it) if it.shape_a and it.shape_b and it.shape_b.in_body then if it.shape_b.in_body.headroom then it.shape_b.in_body.headroom[it.shape_a]=nil end end end space:add_handler(arbiter_pass,space:type("pass")) local arbiter_walking={} -- walking things (players) arbiter_walking.presolve=function(it) local callbacks=entities.manifest("callbacks") if it.shape_a.player and it.shape_b.monster then local pa=it.shape_a.player callbacks[#callbacks+1]=function() pa:die() end end if it.shape_a.monster and it.shape_b.player then local pb=it.shape_b.player callbacks[#callbacks+1]=function() pb:die() end end if it.shape_a.player and it.shape_b.player then -- two players touch local pa=it.shape_a.player local pb=it.shape_b.player if pa.active then if pb.bubble_active and pb.joined then -- burst callbacks[#callbacks+1]=function() pb:join() end end end if pb.active then if pa.bubble_active and pa.joined then -- burst callbacks[#callbacks+1]=function() pa:join() end end end end return true end arbiter_walking.postsolve=function(it) local points=it:points() if points.normal_y>0.25 then -- on floor local time=entities.get("time") it.shape_a.in_body.floor_time=time.game it.shape_a.in_body.floor=it.shape_b end return true end space:add_handler(arbiter_walking,space:type("walking")) -- walking things (players) local arbiter_trigger={} -- trigger things arbiter_trigger.presolve=function(it) if it.shape_a.trigger and it.shape_b.triggered then -- trigger something it.shape_b.triggered.triggered = it.shape_a.trigger end return false end space:add_handler(arbiter_trigger,space:type("trigger")) end, ----------------------------------------------------------------------------- --[[#entities.systems.player entities.systems.player.controls(it,fast) Handle player style movement, so we can reuse this code for player style monsters. it is a player or monster, fast lets us tweak the speed and defaults to 1 movement controls are set in it it.move which is "left" or "right" to move left or right it.jump which is true if we should jump ]] ----------------------------------------------------------------------------- controls=function(it,fast) fast=fast or 1 local menu=entities.get("menu") local chats=entities.get("chats") local time=entities.get("time") local jump=fast*200 -- up velocity we want when jumping local speed=fast*60 -- required x velocity local airforce=speed*2 -- replaces surface velocity local groundforce=speed/2 -- helps surface velocity if ( time.game-it.body.floor_time < 0.125 ) or ( it.floor_time-time.game > 10 ) then -- floor available recently or not for a very long time (stuck) it.floor_time=time.game -- last time we had some floor it.shape:friction(1) if it.jump_clr and it.near_menu then local menu=entities.get("menu") local near_menu=it.near_menu local callbacks=entities.manifest("callbacks") callbacks[#callbacks+1]=function() menu.show(near_menu) end -- call later so we do not process menu input this frame end if it.jump_clr and it.near_npc then local callbacks=entities.manifest("callbacks") callbacks[#callbacks+1]=function() local chat=chats:get_subject(subject_name) chat:set_topic("welcome") menu.show( menu.chat_to_menu_items(chat) ) end -- call later so we do not process menu input this frame end if it.jump then local vx,vy=it.body:velocity() if vy>-20 then -- only when pushing against the ground a little if it.near_menu or it.near_npc then -- no jump else vy=-jump it.body:velocity(vx,vy) it.body.floor_time=0 end end end if it.move=="left" then local vx,vy=it.body:velocity() if vx>0 then it.body:velocity(0,vy) end it.shape:surface_velocity(speed,0) if vx>-speed then it.body:apply_force(-groundforce,0,0,0) end it.dir=-1 it.frame=it.frame+1 elseif it.move=="right" then local vx,vy=it.body:velocity() if vx<0 then it.body:velocity(0,vy) end it.shape:surface_velocity(-speed,0) if vx<speed then it.body:apply_force(groundforce,0,0,0) end it.dir= 1 it.frame=it.frame+1 else it.shape:surface_velocity(0,0) end else -- in air it.shape:friction(0) if it.move=="left" then local vx,vy=it.body:velocity() if vx>0 then it.body:velocity(0,vy) end if vx>-speed then it.body:apply_force(-airforce,0,0,0) end it.shape:surface_velocity(speed,0) it.dir=-1 it.frame=it.frame+1 elseif it.move=="right" then local vx,vy=it.body:velocity() if vx<0 then it.body:velocity(0,vy) end if vx<speed then it.body:apply_force(airforce,0,0,0) end it.shape:surface_velocity(-speed,0) it.dir= 1 it.frame=it.frame+1 else it.shape:surface_velocity(0,0) end end end, add=function(i) local players_colors={[0]=30,30,14,18,7,3,22} local names=system.components.tiles.names local space=entities.get("space") local player=entities.add{caste="player"} player.idx=i player.score=0 local t=bitdown.cmap[ players_colors[i] ] player.color={} player.color.r=t[1]/255 player.color.g=t[2]/255 player.color.b=t[3]/255 player.color.a=t[4]/255 player.color.idx=players_colors[i] player.up_text_x=math.ceil( (system.components.text.tilemap_hx/16)*( 1 + ((i>3 and i+2 or i)-1)*2 ) ) player.frame=0 player.frames={ names.skel_walk_4.idx+0 , names.skel_walk_4.idx+2 , names.skel_walk_4.idx+4 , names.skel_walk_4.idx+6 } player.join=function() local players_start=entities.get("players_start") or {64,64} local px,py=players_start[1]+i,players_start[2] local vx,vy=0,0 player.bubble_active=false player.active=true player.body=space:body(1,math.huge) player.body:position(px,py) player.body:velocity(vx,vy) player.body.headroom={} player.body:velocity_func(function(body) -- body.gravity_x=-body.gravity_x -- body.gravity_y=-body.gravity_y return true end) player.floor_time=0 -- last time we had some floor player.shape=player.body:shape("segment",0,2,0,11,4) player.shape:friction(1) player.shape:elasticity(0) player.shape:collision_type(space:type("walking")) -- walker player.shape.player=player player.body.floor_time=0 local time=entities.get("time") if not time.start then time.start=time.game -- when the game started end end player.update=function() local up=ups(player.idx) -- the controls for this player player.move=false player.jump=up.button("fire") player.jump_clr=up.button("fire_clr") if use_only_two_keys then -- touch screen control test? if up.button("left") and up.button("right") then -- jump player.move=player.move_last player.jump=true elseif up.button("left") then -- left player.move_last="left" player.move="left" elseif up.button("right") then -- right player.move_last="right" player.move="right" end else if up.button("left") and up.button("right") then -- stop player.move=nil elseif up.button("left") then -- left player.move="left" elseif up.button("right") then -- right player.move="right" end end if not player.joined then player.joined=true player:join() -- join for real and remove bubble end if player.active then entities.systems.player.controls(player) end end player.draw=function() if player.active then local px,py=player.body:position() local rz=player.body:angle() player.frame=player.frame%16 local t=player.frames[1+math.floor(player.frame/4)] system.components.sprites.list_add({t=t,hx=16,hy=32,px=px,py=py,sx=player.dir,sy=1,rz=180*rz/math.pi,color=player.color}) end -- if player.joined then -- local s=string.format("%d",player.score) -- system.components.text.text_print(s,math.floor(player.up_text_x-(#s/2)),0,player.color.idx) -- end end return player end, } ----------------------------------------------------------------------------- --[[#entities.systems.npc npc = entities.systems.npc.add(opts) Add an npc. ]] ----------------------------------------------------------------------------- entities.systems.npc={ chat_text=[[ #npc1 =title A door shaped like a dead man. =donuts 0 <welcome Good Day Kind Sir, If you fetch me all the donuts I will let you out. >exit?donuts<10 Fine I'll go look. >donut?donuts>9 Here you go, 10 donuts that have barely touched the ground. >out Where is out? <out Out is nearby, I may have been here a long long time but I know exactly how to get out and I can show you, just bring me donuts, all of them! >exit Be seeing you. ]], chat_hook_topic=function(chat,a) if chat.subject_name=="npc1" then if a.name=="exit" then if not entities.get("added_donuts") then entities.set("added_donuts",true) entities.systems.donut.spawn(10) end end if a.name=="donut" then entities.systems.level.setup(2) end end end, load=function() graphics.loads{ -- 4 x 16x32 {nil,"npc1_walk_4",[[ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . 7 7 7 7 7 . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . 7 7 7 7 7 . . . . . . . . . . . 7 7 7 7 7 . . . . . . . . . . . 7 0 7 0 7 . . . . . . . . . . . 7 7 7 7 7 . . . . . . . . . . . 7 0 7 0 7 . . . . . . . . . . . 7 0 7 0 7 . . . . . . . . . . . 7 7 0 7 7 . . . . . . . . . . . 7 0 7 0 7 . . . . . . . . . . . 7 7 0 7 7 . . . . . . . . . . . 7 7 0 7 7 . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . 7 7 0 7 7 . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . . 7 0 7 . . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . . 7 0 7 . . . . . . . . . . . . . 7 0 7 . . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . . 7 0 7 . . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . . 7 7 7 . . . . . . . . . 7 7 7 . 7 . 7 7 . . . . . . . . . . . . 7 7 7 . . . . . . . . . 7 7 7 . 7 . . 7 7 . . . . . . . . 7 7 . 7 . 7 7 . . . . . . . . 7 . . 7 7 7 7 7 . . . . . . . . 7 7 7 . 7 . . 7 7 . . . . . . . 7 . . 7 7 7 7 . 7 . . . . . . . . 7 . 7 7 7 7 7 . . . . . . . . 7 . 7 . 7 . . 7 . . . . . . . . 7 . . 7 7 7 7 . 7 . . . . . . . 7 . 7 . 7 . . 7 7 . . . . . . . . 7 7 . 7 . . 7 . . . . . . . . 7 . . 7 7 7 7 7 . . . . . . . . 7 . 7 . 7 . . 7 7 . . . . . . . 7 . . 7 7 7 7 . 7 . . . . . . . . 7 . 7 7 7 7 7 . . . . . . . . 7 7 7 . 7 . . 7 7 . . . . . . 7 7 . . 7 7 7 7 . 7 7 . . . . . . 7 7 7 . 7 . . 7 7 . . . . . . . . 7 7 . 7 . . 7 . . . . . . . . . 7 . 7 7 7 7 . 7 . . . . . . 7 . . 7 . 7 . . 7 . 7 . . . . . . . 7 . 7 7 7 7 7 . . . . . . . . . 7 . 7 7 7 7 7 . . . . . . . . . 7 7 . 7 7 . 7 7 . . . . . . 7 . . . 7 7 7 7 . . 7 . . . . . . . 7 7 . 7 7 . 7 . . . . . . . . . 7 7 . 7 7 . 7 . . . . . . . . . 7 7 7 7 7 7 7 7 7 . . . . . 7 . . 7 . 7 7 . 7 . 7 . . . . . . . 7 7 7 7 7 7 7 . . . . . . . . . 7 7 7 7 7 7 7 . . . . . . . . . 7 7 7 7 . 7 . 7 7 . . . . . 7 7 . 7 7 7 7 7 7 7 7 . . . . . . . 7 7 7 . . 7 7 . . . . . . . . . 7 7 7 . . 7 7 . . . . . . . . . . . . 7 . 7 . . . . . . . . 7 7 . . 7 . . 7 . 7 7 . . . . . . . . . 7 . . . 7 7 . . . . . . . . . 7 . . . . 7 . . . . . . . . . . . . 7 7 7 . . . . . . . . . . . . 7 . . 7 . . . . . . . . . . . . 7 . . . . 7 7 . . . . . . . 7 7 . . . . 7 7 . . . . . . . . . . . 7 7 7 7 . . . . . . . . . . . 7 7 7 7 . . . . . . . . . . . 7 7 . . . . 7 7 . . . . . . . 7 7 . . . . 7 7 . . . . . . . . . . 7 . . 7 7 . . . . . . . . . . . 7 7 7 7 . . . . . . . . . . . 7 7 . . . 7 . . . . . . . . . 7 . . . . . 7 . . . . . . . . . . . 7 . . 7 . . . . . . . . . . . . 7 . 7 . . . . . . . . . . . . 7 . . . . 7 . . . . . . . . . 7 . . . . . 7 . . . . . . . . . . 7 . . . 7 . . . . . . . . . . . . 7 . 7 . . . . . . . . . . . . 7 . . . 7 . . . . . . . . . . 7 . . . . . 7 . . . . . . . . . . 7 . . . 7 . . . . . . . . . . . . 7 . 7 . . . . . . . . . . . . 7 . . . 7 . . . . . . . . . . 7 . . . . . 7 . . . . . . . . . 7 7 7 7 . 7 . . . . . . . . . . . . 7 . 7 . . . . . . . . . . . . 7 . . 7 7 7 7 . . . . . . . 7 7 7 7 . . 7 7 7 7 . . . . . . . . . . . 7 7 7 7 . . . . . . . . . 7 7 7 7 7 7 . . . . . . . . . 7 7 7 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]]}, }end, space=function() local space=entities.get("space") local arbiter_npc={} -- npc menu things arbiter_npc.presolve=function(it) if it.shape_a.npc and it.shape_b.player then -- remember npc menu it.shape_b.player.near_npc=it.shape_a.npc end return false end arbiter_npc.separate=function(it) if it.shape_a and it.shape_a.npc and it.shape_b and it.shape_b.player then -- forget npc menu it.shape_b.player.near_npc=false end return true end space:add_handler(arbiter_npc,space:type("npc")) end, add=function(opts) local names=system.components.tiles.names local space=entities.get("space") local npc=entities.add{caste="npc"} npc.frame=0 npc.frames={ names.npc1_walk_4.idx+0 , names.npc1_walk_4.idx+2 , names.npc1_walk_4.idx+4 , names.npc1_walk_4.idx+6 } npc.update=function() npc.move=false npc.jump=false npc.jump_clr=false if npc.active then entities.systems.player.controls(npc) end end npc.draw=function() if npc.active then local px,py=npc.body:position() local rz=npc.body:angle() local t=npc.frames[1] system.components.sprites.list_add({t=t,hx=16,hy=32,px=px,py=py,sx=npc.dir,sy=1,rz=180*rz/math.pi,color=npc.color}) end end local px,py=opts.px,opts.py local vx,vy=0,0 npc.dir=-1 npc.color={r=1/2,g=1,b=1/2,a=1} npc.active=true npc.body=space:body(1,math.huge) npc.body:position(px,py) npc.body:velocity(vx,vy) npc.body.headroom={} npc.body:velocity_func(function(body) -- body.gravity_x=-body.gravity_x -- body.gravity_y=-body.gravity_y return true end) npc.floor_time=0 -- last time we had some floor npc.shape=npc.body:shape("segment",0,2,0,11,4) npc.shape:friction(1) npc.shape:elasticity(0) npc.shape:collision_type(space:type("walking")) -- walker npc.shape2=npc.body:shape("segment",0,2,0,11,8) -- talk area npc.shape2:collision_type(space:type("npc")) npc.shape2.npc=npc npc.body.floor_time=0 npc.name="npc1" return npc end, } ----------------------------------------------------------------------------- --[[#entities.systems.donut donut = entities.systems.donut.add(opts) Add an donut. ]] ----------------------------------------------------------------------------- entities.systems.donut={ load=function() graphics.loads{ -- 1 x 24x24 {nil,"donut_1",[[ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . O O O O . . . . . . . . . . . . . . . . . O O O O O O O O O O . . . . . . . . . . . . . O O O O O O O O O O O O . . . . . . . . . . . O O O O O O O O O O O O O O . . . . . . . . . . O O O O O O O O O O O O O O . . . . . . . . . . O O O O O O . . O O O O O O . . . . . . . . . O O O O O O . . . . O O O O O O . . . . . . . . O O O O O . . . . . . O O O O O . . . . . . . . O O O O O . . . . . . O O O O O . . . . . . . . O O O O O O . . . . O O O O O O . . . . . . . . . O O O O O O . . O O O O O O . . . . . . . . . . O O O O O O O O O O O O O O . . . . . . . . . . O O O O O O O O O O O O O O . . . . . . . . . . . O O O O O O O O O O O O . . . . . . . . . . . . . O O O O O O O O O O . . . . . . . . . . . . . . . . . O O O O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]]}, }end, space=function() local space=entities.get("space") local arbiter_loot={} -- loot things (pickups) arbiter_loot.presolve=function(it) if it.shape_a.loot and it.shape_b.player then -- trigger collect local loot=it.shape_a.loot local player=it.shape_b.player local callbacks=entities.manifest("callbacks") callbacks[#callbacks+1]=function() loot:pickup(player) end return false end return true end space:add_handler(arbiter_loot,space:type("donut")) end, spawn=function(count) for i=1,count do local px=math.random(32,320-32) local py=32 local vx=math.random(-4000,4000)/100 local vy=math.random(-4000,4000)/100 entities.systems.donut.add({px=px,py=py,vx=vx,vy=vy}) end end, add=function(opts) local names=system.components.tiles.names local space=entities.get("space") local donut=entities.add{caste="donut"} donut.frame=0 donut.frames={ names.donut_1.idx+0 } donut.update=function() end donut.draw=function() if donut.active then local px,py=donut.body:position() local rz=donut.body:angle() local t=donut.frames[1] system.components.sprites.list_add({t=t,h=24,px=px,py=py,rz=180*rz/math.pi}) end end donut.pickup=function(it,player) if donut.active then donut.active=false space:remove(donut.shape) space:remove(donut.body) local chats=entities.get("chats") chats:set_tag("npc1/donuts","+1") end end donut.active=true donut.body=space:body(1,1) donut.body:position(opts.px,opts.py) donut.body:velocity(opts.vx,opts.vy) donut.body.headroom={} donut.shape=donut.body:shape("circle",8,0,0) donut.shape:friction(1) donut.shape:elasticity(0) donut.shape:collision_type(space:type("donut")) donut.shape.loot=donut return donut end, } ---------------------------------------------------------------------------- --[[#entities.tiles.start The player start point, just save the x,y ]] ----------------------------------------------------------------------------- entities.tiles.start=function(tile) entities.set("players_start",{tile.x*8+4,tile.y*8+4}) -- remember start point end ----------------------------------------------------------------------------- --[[#entities.tiles.sprite Display a sprite ]] ----------------------------------------------------------------------------- entities.tiles.sprite=function(tile) local names=system.components.tiles.names local item=entities.systems.item.add() item.active=true item.px=tile.x*8+4 item.py=tile.y*8+4 item.sprite = names[tile.sprite].idx item.h=24 item.s=1 item.draw_rz=0 item.pz=-1 end ----------------------------------------------------------------------------- --[[#entities.tiles.npc Display a npc ]] ----------------------------------------------------------------------------- entities.tiles.npc=function(tile) local names=system.components.tiles.names local space=entities.get("space") local item=entities.systems.npc.add({px=tile.x*8,py=tile.y*8}) end ----------------------------------------------------------------------------- --[[#levels Design levels here ]] ----------------------------------------------------------------------------- local combine_legends=function(...) local legend={} for _,t in ipairs{...} do -- merge all for n,v in pairs(t) do -- shallow copy, right side values overwrite left legend[n]=v end end return legend end local default_legend={ [0]={ tile="tile_empty",back="tile_empty",uvworld=true}, -- screen edges ["00"]={ tile="tile_black", solid=1, dense=1, }, -- black border ["0 "]={ tile="tile_empty", solid=1, dense=1, }, -- empty border -- solid features ["||"]={ solid=1, tile="tile_sidewood", }, -- wall ["=="]={ solid=1, back="tile_floor", }, -- floor ["WW"]={ solid=1, tile="tile_bigwall", }, ["S="]={ solid=1, tile="tile_stump", }, ["P="]={ solid=1, tile="tile_postbox", }, -- foreground features [",,"]={ back="tile_grass", }, ["t."]={ tile="tile_tree", }, ["s."]={ tile="tile_sign", }, -- special locations ["S "]={ start=1, }, -- items not tiles, so display tile 0 and we will add a sprite for display ["N1"]={ npc="npc1", }, } levels={} levels[1]={ legend=combine_legends(default_legend,{ ["?0"]={ }, }), title="Welcome!", map=[[ ||0000000000000000000000000000000000000000000000000000000000000000000000000000|| ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . S . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||,,. . . . . . ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,. . . . . || ||==. . . . . . ====================================================. . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . N1. . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||============================================================================|| ||0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 || ]], } levels[2]={ legend=combine_legends(default_legend,{ ["?0"]={ }, }), title="This is a test.", map=[[ ||0000000000000000000000000000000000000000000000000000000000000000000000000000|| ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . t.t.. . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . t.t.. . . . . . . s.s.. . . . . . . . . . . . . . . . . . || ||,,,,,,,,,,,,,,,,,,t.t.,,,,,,,,,,,,,,s.s.,,,,,,,,. . . . ,,,,,,,,,,,,,,,,,,,,|| ||================================================. . . . ====================|| ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||,,,,,,. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||======. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||,,,,,,,,,,. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||==========. . . . . . . . . . t.t.. . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . t.t.. . . . . . WWWWWWWWWWWW. . . . . . . . . || ||,,,,,,,,,,,,,,. . . . ,,,,,,,,t.t.,,,,,,,,,,,,WWWWWWWWWWWW,,,,,,,,,,,,,,,,,,|| ||==============. . . . ======================================================|| ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||,,. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||==. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||,,. . S . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||==. . . . . . . . . . . . . . . . . . . . . . S=. . . . . . . ,,,,,,,,,,,,,,|| ||. . . . . . . . . . . . . . . . P=. . S=. . . S=. . . . . . . ==============|| ||,,. . . . . . ,,,,,,,,,,S=,,,,,,P=,,,,S=,,,,,,S=,,,,,,,,,,,,,,,,,,. . . . . || ||==. . . . . . ====================================================. . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . || ||============================================================================|| ||0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 || ]], } ----------------------------------------------------------------------------- --[[#entities.systems.level entities.systems.level.setup(level) reset and setup everything for this level idx ]] ----------------------------------------------------------------------------- entities.systems.level={ setup=function(idx) entities.reset() local menu=entities.systems.menu.setup() entities.systems.score.setup() local level=entities.set("level",entities.add{}) local names=system.components.tiles.names level.updates={} -- tiles to update (animate) level.update=function() for v,b in pairs(level.updates) do -- update these things if v.update then v:update() end end end -- init map and space local space=entities.systems.space.setup() local tilemap={} for n,v in pairs( levels[idx].legend ) do -- build tilemap from legend if v.tile then -- convert name to tile local t={} for n,v in pairs( v ) do t[n]=v end for n,v in pairs( names[v.tile] ) do t[n]=v end tilemap[n]=t end end local backmap={} for n,v in pairs( levels[idx].legend ) do -- build tilemap from legend if v.back then -- convert name to tile local t={} for n,v in pairs( v ) do t[n]=v end for n,v in pairs( names[v.back] ) do t[n]=v end backmap[n]=t end end local map=entities.set("map", bitdown.pix_tiles( levels[idx].map, levels[idx].legend ) ) level.title=levels[idx].title bitdown.tile_grd( levels[idx].map, backmap, system.components.back.tilemap_grd ) -- draw into the screen (tiles) bitdown.tile_grd( levels[idx].map, tilemap, system.components.map.tilemap_grd ) -- draw into the screen (tiles) local unique=0 bitdown.map_build_collision_strips(map,function(tile) unique=unique+1 if tile.coll then -- can break the collision types up some more by appending a code to this setting if tile.unique then -- make unique tile.coll=tile.coll..unique end end end) for y,line in pairs(map) do for x,tile in pairs(line) do tile.map=map -- remember map tile.level=level -- remember level if tile.solid and (not tile.parent) then -- if we have no parent then we are the master tile local l=1 local t=tile while t.child do t=t.child l=l+1 end -- count length of strip local shape if tile.link==1 then -- x strip shape=space.static:shape("box",x*8,y*8,(x+l)*8,(y+1)*8,0) elseif tile.link==-1 then -- y strip shape=space.static:shape("box",x*8,y*8,(x+1)*8,(y+l)*8,0) else -- single box shape=space.static:shape("box",x*8,y*8,(x+1)*8,(y+1)*8,0) end tile.shape=shape shape.tile=tile shape:friction(tile.solid) shape:elasticity(tile.solid) shape.cx=x shape.cy=y shape.coll=tile.coll if not tile.dense then shape:collision_type(space:type("pass")) -- a tile we can jump up through end end end end for y,line in pairs(map) do for x,tile in pairs(line) do for n,f in pairs(entities.tiles) do if tile[n] then f(tile) end end end end system.components.back.dirty(true) system.components.map.dirty(true) entities.systems.player.add(0) -- add a player end, } ----------------------------------------------------------------------------- --[[#entities.systems.menu menu = entities.systems.menu.setup() Create a displayable and controllable menu system that can be fed chat data for user display. After setup, provide it with menu items to display using menu.show(items) then call update and draw each frame. ]] ----------------------------------------------------------------------------- entities.systems.menu={ space=function() local space=entities.get("space") local arbiter_menu={} -- menu things arbiter_menu.presolve=function(it) if it.shape_a.menu and it.shape_b.player then -- remember menu it.shape_b.player.near_menu=it.shape_a.menu end return false end arbiter_menu.separate=function(it) if it.shape_a and it.shape_a.menu and it.shape_b and it.shape_b.player then -- forget menu it.shape_b.player.near_menu=false end return true end space:add_handler(arbiter_menu,space:type("menu")) end, setup=function(items) -- join all entity chat_text to build chat_texts with local chat_texts={} for n,v in pairs(entities.systems) do if v.chat_text then chat_texts[#chat_texts+1]=v.chat_text end end chat_texts=table.concat(chat_texts,"\n\n") -- manage chat hooks from entities and print debug text local chat_hook=function(chat,change,...) local a,b=... if change=="subject" then print("subject ",chat.subject_name) for n,v in pairs(entities.systems) do if v.chat_hook_response then v.chat_hook_response(chat,a) end end elseif change=="topic" then print("topic ",chat.subject_name,a and a.name) for n,v in pairs(entities.systems) do if v.chat_hook_topic then v.chat_hook_topic(chat,a) end end elseif change=="goto" then print("goto ",chat.subject_name,a and a.name) for n,v in pairs(entities.systems) do if v.chat_hook_goto then v.chat_hook_goto(chat,a) end end elseif change=="tag" then print("tag ",chat.subject_name,a,b) for n,v in pairs(entities.systems) do if v.chat_hook_tag then v.chat_hook_tag(chat,a,b) end end end end local chats=entities.set( "chats", chatdown.setup_chats(chat_texts,chat_hook) ) local wstr=require("wetgenes.string") local menu=entities.set("menu",entities.add{}) -- local menu={} menu.stack={} menu.width=80-4 menu.cursor=0 menu.cx=math.floor((80-menu.width)/2) menu.cy=0 menu.chat_to_menu_items=function(chat) local items={cursor=1,cursor_max=0} items.title=chat:get_tag("title") items.portrait=chat:get_tag("portrait") local ss=chat.topic and chat.topic.text or {} if type(ss)=="string" then ss={ss} end for i,v in ipairs(ss) do if i>1 then items[#items+1]={text="",chat=chat} -- blank line end items[#items+1]={text=chat:replace_tags(v)or"",chat=chat} end for i,v in ipairs(chat.gotos or {}) do items[#items+1]={text="",chat=chat} -- blank line before each goto local ss=v and v.text or {} if type(ss)=="string" then ss={ss} end local color=30 if chat.viewed[v.name] then color=28 end -- we have already seen the response to this goto local f=function(item,menu) if item.topic and item.topic.name then chats.changes(chat,"topic",item.topic) chat:set_topic(item.topic.name) chat:set_tags(item.topic.tags) if item.topic.name=="exit" then menu.show(nil) else menu.show(menu.chat_to_menu_items(chat)) end end end items[#items+1]={text=chat:replace_tags(ss[1])or"",chat=chat,topic=v,cursor=i,call=f,color=color} -- only show first line items.cursor_max=i end return items end --[[ menu.chat=function(chat) local items={cursor=1,cursor_max=0} items.title=chat.description and chat.description.text or chat.description_name local ss=chat.response and chat.response.text or {} if type(ss)=="string" then ss={ss} end for i,v in ipairs(ss) do if i>1 then items[#items+1]={text="",chat=chat} -- blank line end items[#items+1]={text=chat.replace_proxies(v)or"",chat=chat} end for i,v in ipairs(chat.decisions or {}) do items[#items+1]={text="",chat=chat} -- blank line before each decision local ss=v and v.text or {} if type(ss)=="string" then ss={ss} end local color=30 if chat.viewed[v.name] then color=28 end -- we have already seen the response to this decision local f=function(item,menu) if item.decision and item.decision.name then chats.changes(chat,"decision",item.decision) chat.set_response(item.decision.name) chat.set_proxies(item.decision.proxies) menu.show( menu.chat(chat) ) end end items[#items+1]={text=chat.replace_proxies(ss[1])or"",chat=chat,decision=v,cursor=i,call=f,color=color} -- only show first line items.cursor_max=i end return items end ]] function menu.show(items,subject_name,topic_name) if subject_name and topic_name then local chat=chats:get_subject(subject_name) chat:set_topic(topic_name) items=menu.chat_to_menu_items(chat) elseif subject_name then local chat=chats:get_subject(subject_name) items=menu.chat_to_menu_items(chat) end if not items then menu.items=nil menu.lines=nil return end if items.call then items.call(items,menu) end -- refresh menu.items=items menu.cursor=items.cursor or 1 menu.lines={} for idx=1,#items do local item=items[idx] local text=item.text if text then local ls=wstr.smart_wrap(text,menu.width-8) if #ls==0 then ls={""} end -- blank line for i=1,#ls do local prefix=""--(i>1 and " " or "") if item.cursor then prefix=" " end -- indent decisions menu.lines[#menu.lines+1]={s=prefix..ls[i],idx=idx,item=item,cursor=item.cursor,color=item.color} end end end end menu.update=function() if not menu.items then return end local bfire,bup,bdown,bleft,bright for i=0,5 do -- any player, press a button, to control menu local up=ups(i) if up then bfire =bfire or up.button("fire_clr") bup =bup or up.button("up_set") bdown =bdown or up.button("down_set") bleft =bleft or up.button("left_set") bright=bright or up.button("right_set") end end if bfire then for i,item in ipairs(menu.items) do if item.cursor==menu.cursor then if item.call then -- do this if item and item.decision and item.decision.name=="exit" then --exit menu item.call( item , menu ) menu.show() -- hide else item.call( item , menu ) end end break end end end if bleft or bup then menu.cursor=menu.cursor-1 if menu.cursor<1 then menu.cursor=menu.items.cursor_max end end if bright or bdown then menu.cursor=menu.cursor+1 if menu.cursor>menu.items.cursor_max then menu.cursor=1 end end end menu.draw=function() local tprint=system.components.text.text_print local tgrd=system.components.text.tilemap_grd if not menu.lines then return end menu.cy=math.floor((30-(#menu.lines+4))/2) tgrd:clip(menu.cx,menu.cy,0,menu.width,#menu.lines+4,1):clear(0x02000000) tgrd:clip(menu.cx+2,menu.cy+1,0,menu.width-4,#menu.lines+4-2,1):clear(0x01000000) if menu.items.title then local title=" "..(menu.items.title).." " local wo2=math.floor(#title/2) tprint(title,menu.cx+(menu.width/2)-wo2,menu.cy+0,31,2) end for i,v in ipairs(menu.lines) do tprint(v.s,menu.cx+4,menu.cy+i+1,v.color or 31,1) end local it=nil for i=1,#menu.lines do if it~=menu.lines[i].item then -- first line only it=menu.lines[i].item if it.cursor == menu.cursor then tprint(">",menu.cx+4,menu.cy+i+1,31,1) end end end system.components.text.dirty(true) end if items then menu.show(items) end return menu end, } ----------------------------------------------------------------------------- --[[#update update() Update called every 1/60 of a second, possibly many times before we get a draw call. ]] ----------------------------------------------------------------------------- update=function() if not setup_done then entities.systems.level.setup(1) -- load map setup_done=true end local menu=entities.get("menu") if menu.lines then -- menu only, pause the entities and draw the menu menu.update() else entities.call("update") local space=entities.get("space") space:step(1/(60*2)) -- double step for increased stability, allows faster velocities. space:step(1/(60*2)) end local cb=entities.get("callbacks") or {} -- get callback list entities.set("callbacks",{}) -- and reset it -- run all the callbacks created by collisions for _,f in pairs(cb) do f() end end ----------------------------------------------------------------------------- --[[#draw draw() Draw called every frame, there may be any number of updates between each draw but hopefully we are looking at one update followed by a draw, if you have an exceptionally fast computer then we may even get 0 updates between some draws. ]] ----------------------------------------------------------------------------- draw=function() local menu=entities.get("menu") if menu.lines then menu.draw() end entities.call("draw") -- draw everything, well, actually just prepare everything to be drawn by the system end -- load graphics into texture memory for n,v in pairs(entities.systems) do if v.load then v:load() end end
--------------------------------------------------------------------------------------------------- -- --filename: game.entities.ctrl.HealthBarCtrl --date:2019/10/31 0:04:07 --author: --desc: -- --------------------------------------------------------------------------------------------------- local strClassName = 'game.entities.ctrl.HealthBarCtrl' local HealthBarCtrl = lua_declare(strClassName, lua_class(strClassName)) function HealthBarCtrl:ctor(owner) self.owner = owner self:CreateBar() end function HealthBarCtrl:SetHP(hp, maxHP) if self.slider ~= nil then self.slider.value = hp / maxHP end end function HealthBarCtrl:Remove() if self.barObj ~= nil then ObjectPool.Recycle(self.barObj) end end function HealthBarCtrl:CreateBar() self.barObj = ObjectPool.Spawn("ui/healthbar.u3d","HealthBar") self.bar = self.barObj.transform self.bar:SetParent(UIManager.Instance.HUDRoot) local p = self.owner:GetTopPosition() if p ~= nil then local localPos = GameUtil.WorldToUIPoint(p,nil) self.bar.position = localPos end self.bar.localScale = Vector3.one GameUtil.SetLayer(self.bar, LayerManager.UI) self.slider = self.barObj:GetComponent(Slider) self.slider.value = 1 end function HealthBarCtrl:Update(deltaTime) if self.bar ~= nil then local p = self.owner:GetTopPosition() if p ~= nil then local localPos = GameUtil.WorldToUIPoint(p,nil) self.bar.position = localPos end end end return HealthBarCtrl
local function createModel(nClasses) local nClasses = nClasses or 1000 local modelType = 'A' -- on a titan black, B/D/E run out of memory even for batch-size 32 -- Create tables describing VGG configurations A, B, D, E local cfg = {} if modelType == 'A' then cfg = {64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'} elseif modelType == 'B' then cfg = {64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'} elseif modelType == 'D' then cfg = {64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'} elseif modelType == 'E' then cfg = {64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'} else error('Unknown model type: ' .. modelType .. ' | Please specify a modelType A or B or D or E') end local features = nn.Sequential() do local iChannels = 3; for k,v in ipairs(cfg) do if v == 'M' then features:add(nn.SpatialMaxPooling(2,2,2,2)) else local oChannels = v; local conv3 = nn.SpatialConvolution(iChannels,oChannels,3,3,1,1,1,1); features:add(conv3) features:add(nn.ReLU(true)) iChannels = oChannels; end end end local classifier = nn.Sequential() classifier:add(nn.View(512*7*7)) classifier:add(nn.Linear(512*7*7, 4096)) classifier:add(nn.Threshold(0, 1e-6)) classifier:add(nn.BatchNormalization(4096, 1e-3)) classifier:add(nn.Dropout(0.5)) classifier:add(nn.Linear(4096, 4096)) classifier:add(nn.Threshold(0, 1e-6)) classifier:add(nn.BatchNormalization(4096, 1e-3)) classifier:add(nn.Dropout(0.5)) classifier:add(nn.Linear(4096, nClasses)) --classifier:add(nn.LogSoftMax()) local model = nn.Sequential() model:add(features):add(classifier) model.imageSize = 256 model.imageCrop = 224 return model end ---------------------------- return createModel
propertyGetters = { object = { model = getElementModel, doublesided = function(element) if isElementDoubleSided then return isElementDoubleSided(element) and "true" or "false" else return getElementData(element,"doublesided")=="true" and "true" or "false" end end, scale = getObjectScale, breakable = function(element) return tostring(isObjectBreakable(element)) end, collisions = function(element) local collisions = getElementData(element, "collisions") if collisions == "true" or collisions == false then return "true" else return "false" end end }, ped = { model = getElementModel, rotZ = getPedRotation, health = getElementHealth, armor = setPedArmor, collisions = function(element) local collisions = getElementData(element, "collisions") if collisions == "true" or collisions == false then return "true" else return "false" end end }, vehicle = { model = getElementModel, color1 = function(element) local vehCol = {getVehicleColor(element, true)} return {vehCol[1], vehCol[2], vehCol[3]} end, color2 = function(element) local vehCol = {getVehicleColor(element, true)} return {vehCol[4], vehCol[5], vehCol[6]} end, color3 = function(element) local vehCol = {getVehicleColor(element, true)} return {vehCol[7], vehCol[8], vehCol[9]} end, color4 = function(element) local vehCol = {getVehicleColor(element, true)} return {vehCol[10], vehCol[11], vehCol[12]} end, upgrades = getVehicleUpgrades, plate = getVehiclePlateText, sirens = function(vehicle) return getVehicleSirensOn(vehicle) and "true" or "false" end, health = getElementHealth, paintjob = function(vehicle) return tostring(getVehiclePaintjob(vehicle)) end, landingGearDown = function(element) return tostring(getVehicleLandingGearDown(element)) end, collisions = function(element) local collisions = getElementData(element, "collisions") if collisions == "true" or collisions == false then return "true" else return "false" end end }, marker = { type = getMarkerType, size = getMarkerSize, color = function(element) return {getMarkerColor(element)} end, }, pickup = { type = function(element) local pType = getPickupType(element) if pType == 0 then return "health" elseif pType == 1 then return "armor" elseif pType == 2 then return getPickupWeapon(element) elseif pType == 3 then return "Custom" end end, }, radararea = { sizeX = function(element) local sizeX = getRadarAreaSize(element) return sizeX end, sizeY = function(element) local _,sizeY = getRadarAreaSize(element) return sizeY end, posX = function(element) local posX = getElementPosition(element) return posX end, posY = function(element) local _,posY = getElementPosition(element) return posY end, color = function(element) return {getRadarAreaColor(element)} end, }, blip = { color = function(element) return {getBlipColor(element)} end, size = getBlipSize, icon = getBlipIcon, }, water = { sizeX = function(element) local x1 = getWaterVertexPosition ( element, 1 ) local x2 = getWaterVertexPosition ( element, 2 ) return x2 - x1 end, sizeY = function(element) local _,y1 = getWaterVertexPosition ( element, 2 ) local _,y2 = getWaterVertexPosition ( element, 3 ) return y2 - y1 end, } } propertySetters = { object = { model = function(element, model) if model then return setElementModel(element, model) else return false end end, doublesided = function(element,bon) if setElementDoubleSided then return setElementDoubleSided(element,bon=="true") else return setElementData(element,"doublesided",bon=="true" and "true" or "false") end end, scale = function(element, scale) if ( scale ) then return setObjectScale(element, scale) end return false end, breakable = function(element, breakable) return setObjectBreakable(element, breakable == "true") end, collisions = function(element, state) return setElementCollisionsEnabled(element, state == "true") end }, ped = { model = function(element, model) if model then return setElementModel(element, model) else return false end end, rotZ = function(element, rot) if tonumber(rot) then return setElementRotation(element, 0, 0, rot) else return false end end, health = setElementHealth, armor = setPedArmor, collisions = function(element, state) return setElementCollisionsEnabled(element, state == "true") end }, vehicle = { model = function(element, model) if model then return setElementModel(element, model) else return false end end, color1 = function(element, colorsTable) if colorsTable then colorsTable = {getColorFromString(colorsTable)} local otherColors = {getVehicleColor(element, true)} return setVehicleColor(element, colorsTable[1], colorsTable[2], colorsTable[3], otherColors[4], otherColors[5], otherColors[6], otherColors[7], otherColors[8], otherColors[9], otherColors[10], otherColors[11], otherColors[12]) else return false end end, color2 = function(element, colorsTable) if colorsTable then colorsTable = {getColorFromString(colorsTable)} local otherColors = {getVehicleColor(element, true)} return setVehicleColor(element, otherColors[1], otherColors[2], otherColors[3], colorsTable[1], colorsTable[2], colorsTable[3], otherColors[7], otherColors[8], otherColors[9], otherColors[10], otherColors[11], otherColors[12]) else return false end end, color3 = function(element, colorsTable) if colorsTable then colorsTable = {getColorFromString(colorsTable)} local otherColors = {getVehicleColor(element, true)} return setVehicleColor(element, colorsTable[1], colorsTable[2], colorsTable[3], otherColors[4], otherColors[5], otherColors[6], colorsTable[1], colorsTable[2], colorsTable[3], otherColors[10], otherColors[11], otherColors[12]) else return false end end, color4 = function(element, colorsTable) if colorsTable then colorsTable = {getColorFromString(colorsTable)} local otherColors = {getVehicleColor(element, true)} return setVehicleColor(element, colorsTable[1], colorsTable[2], colorsTable[3], otherColors[4], otherColors[5], otherColors[6], otherColors[7], otherColors[8], otherColors[9], colorsTable[1], colorsTable[2], colorsTable[3]) else return false end end, upgrades = function(element, upgradesTable) if upgradesTable then for slot = 0, 16 do local upgrade = getVehicleUpgradeOnSlot ( element, slot ) if upgrade then removeVehicleUpgrade( element, upgrade ) end end for i, upgrade in ipairs(upgradesTable) do addVehicleUpgrade(element, upgrade) end return true else return false end end, paintjob = setVehiclePaintjob, plate = setVehiclePlateText, sirens = function(vehicle, bon) return setVehicleSirensOn(vehicle, bon == "true" and true or false) end, health = setElementHealth, landingGearDown = function(element, state) return setVehicleLandingGearDown(element, state == "true") end, collisions = function(element, state) return setElementCollisionsEnabled(element, state == "true") end }, marker = { type = function(element, markerType) if markerType then return setMarkerType(element, markerType) else return false end end, size = function(element, markerSize) if markerSize then return setMarkerSize(element, markerSize) else return false end end, color = function(element, color) if color then return setMarkerColor(element, getColorFromString(color)) else return false end end, }, pickup = { type = function(element, pType) if pType then local nType local amount = getPickupAmount(element) if pType == "health" then return setPickupType(element, 0, amount) elseif pType == "armor" then return setPickupType(element, 1, amount) elseif pType == "custom" then return setPickupType(element, 3) else return setPickupType(element, 2, pType, amount) end else return false end end, }, radararea = { sizeX = function(element, sizeX) if sizeX then local _, currentY = getRadarAreaSize(element) return setRadarAreaSize(element, sizeX, currentY) else return false end end, sizeY = function(element, sizeY) if sizeY then local currentX = getRadarAreaSize(element) return setRadarAreaSize(element, currentX, sizeY) else return false end end, posX = function(element, posX) if posX then local _, currentY = getElementPosition(element) return setElementPosition(element, posX, currentY, 0) else return false end end, posY = function(element, posY) if posY then local currentX = getElementPosition(element) return setElementPosition(element, currentX, posY, 0) else return false end end, color = function(element, colorstr) if colorstr then local r, g, b, a = getColorFromString(colorstr) return setRadarAreaColor(element, r, g, b, a) else return false end end, }, blip = { color = function(element, colorstr) if colorstr then local r, g, b, a = getColorFromString(colorstr) return setBlipColor(element, r, g, b, a) else return false end end, size = function(element, blipSize) if blipSize then return setBlipSize(element, blipSize) else return false end end, icon = function(element, blipIcon) if blipIcon then return setBlipIcon(element, blipIcon) else return false end end, }, }
object_draft_schematic_space_weapon_wpn_mining_laser_mk3 = object_draft_schematic_space_weapon_shared_wpn_mining_laser_mk3:new { } ObjectTemplates:addTemplate(object_draft_schematic_space_weapon_wpn_mining_laser_mk3, "object/draft_schematic/space/weapon/wpn_mining_laser_mk3.iff")
function lovr.conf(t) t.modules.headset = false t.window.width = 800 t.window.height = 600 end
require 'coroutine' local time = require 'lib.time' local async = {} -- This file implements waitSeconds, waitSignal, signal, and their supporting stuff. -- This table is indexed by coroutine and simply contains the time at which the coroutine -- should be woken up. local WAITING_ON_TIME = {} local WAITING_ON_SIGNAL_ALL = {} -- This table is indexed by signal and contains list of coroutines that are waiting -- on a given signal local WAITING_ON_SIGNAL = {} -- Keep track of how long the game has been running. local CURRENT_TIME = 0 function async.isSuspended(co) return WAITING_ON_TIME[co] ~= nil or WAITING_ON_SIGNAL_ALL[co] ~= nil end function async.waitSeconds(seconds) -- Grab a reference to the current running coroutine. local co = coroutine.running() -- If co is nil, that means we're on the main process, which isn't a coroutine and can't yield assert(co ~= nil, "The main thread cannot wait!") -- Store the coroutine and its wakeup time in the WAITING_ON_TIME table local wakeupTime = CURRENT_TIME + seconds WAITING_ON_TIME[co] = wakeupTime -- And suspend the process return coroutine.yield(co) end function async.callLater(seconds, callback, ...) local arguments = {...} local co = coroutine.create(function() async.waitSeconds(seconds) callback(unpack(arguments)) end) coroutine.resume(co) return co end function async.addTime(deltaTime) -- This function should be called once per game logic update with the amount of time -- that has passed since it was last called CURRENT_TIME = CURRENT_TIME + deltaTime -- First, grab a list of the threads that need to be woken up. They'll need to be removed -- from the WAITING_ON_TIME table which we don't want to try and do while we're iterating -- through that table, hence the list. local threadsToWake = {} for co, wakeupTime in pairs(WAITING_ON_TIME) do if wakeupTime < CURRENT_TIME then table.insert(threadsToWake, co) end end -- Now wake them all up. for _, co in pairs(threadsToWake) do WAITING_ON_TIME[co] = nil -- Setting a field to nil removes it from the table coroutine.resume(co) end end function async.waitSignal(signalName) -- Same check as in waitSeconds; the main thread cannot wait local co = coroutine.running() assert(co ~= nil, "The main thread cannot wait!") if WAITING_ON_SIGNAL[signalName] == nil then -- If there wasn't already a list for this signal, start a new one. WAITING_ON_SIGNAL[signalName] = { co } else table.insert(WAITING_ON_SIGNAL[signalName], co) end WAITING_ON_SIGNAL_ALL[co] = true return coroutine.yield() end function async.signal(signalName) local threads = WAITING_ON_SIGNAL[signalName] if threads == nil then return end WAITING_ON_SIGNAL[signalName] = nil for _, co in pairs(threads) do WAITING_ON_SIGNAL_ALL[co] = nil coroutine.resume(co) end end time.addHandler("async", async.addTime, true) return async
local playsession = { {"MeggalBozale", {16556}}, {"Nukesman", {3159}}, {"Reyand", {26320}}, {"Nikkichu", {40741}}, {"Peto7002", {13075}}, {"JinNJuice", {1773}}, {"zakky0919", {2922}}, {"dimo145", {2648}}, {"corbin9228", {34520}} } return playsession
----------------------------------------------------------------------------------------------------------------------- -- Base setup -- ----------------------------------------------------------------------------------------------------------------------- -- Configuration file selection ----------------------------------------------------------------------------------------------------------------------- --local rc = "colorless.rc-colorless" local rc = "color.blue.rc-blue" --local rc = "shade.ruby.rc-ruby" -- local rc = "old_rc" require(rc)
return { PluginId = 336673829, PluginIcon = "rbxassetid://8325760954", PluginGUID = "csqrl.plugin.plugin-importer", PluginSettingsKey = "2B605F1C627243798979D8221C971C14", DefaultLocale = "en-gb", Version = "3.0.9", }
local obj_heart = {} function obj_heart.init() obj_heart.data = {} obj_heart.name = "obj_heart" editor.importObject("SUITS", obj_heart.name, "obj_heart.new", mdl_heart) end function obj_heart.new(x, y) local tbl = {} tbl.x = x tbl.y = y table.insert(obj_heart.data, tbl) end function obj_heart.draw() local i = 1 while i <= #obj_heart.data do local this_ent = obj_heart.data[i] lg.push() lg.translate(this_ent.x, this_ent.y) polygon.draw(mdl_heart) lg.pop() i = i + 1 end end return obj_heart
--[[ Name: god Desc: Enables godmode on a player Arguments: 1. Targets (players) ]] BSU.SetupCommand("god", function(cmd) cmd:SetDescription("Enables godmode on a player") cmd:SetCategory("utility") cmd:SetAccess(BSU.CMD_ADMIN) cmd:SetFunction(function(self, ply) local targets = self:GetPlayersArg(1, false) or {ply} targets = self:FilterTargets(targets) for _, ply in pairs(targets) do ply:GodEnable() end self:BroadcastActionMsg("%user% godded %param%", { ply, targets }) end) end) --[[ Name: ungod Desc: Disables godmode on a player Arguments: 1. Targets (players) ]] BSU.SetupCommand("ungod", function(cmd) cmd:SetDescription("Enables godmode on a player") cmd:SetCategory("utility") cmd:SetAccess(BSU.CMD_ADMIN) cmd:SetFunction(function(self, ply) local targets = self:GetPlayersArg(1, false) or {ply} targets = self:FilterTargets(targets) for _, ply in pairs(targets) do ply:GodDisable() end self:BroadcastActionMsg("%user% ungodded %param%", { ply, targets }) end) end) --[[ Name: teleport Desc: Teleports player a to player b or you to player a if there is not player b Arguments: 1. Target A (player) 2. Target B (player) ]] BSU.SetupCommand("teleport", function(cmd) cmd:SetDescription("Teleports player a to player b or you to player a if there is not player b") cmd:SetCategory("utility") cmd:SetAccess(BSU.CMD_ADMIN) cmd:SetFunction(function(self, ply) local targetA = self:GetPlayerArg(1, true) self:CheckCanTarget(targetA, true) local targetB = self:GetPlayerArg(2, false) if targetB then self:CheckCanTarget(targetB, true) targetA:SetPos(targetB:GetPos()) self:BroadcastActionMsg("%user% teleported %param% to %param%", { ply, targetA, targetB }) else ply:SetPos(targetA:GetPos()) self:BroadcastActionMsg("%user% teleported to %param%", { ply, targetA }) end end) end)
local Spell = { } Spell.LearnTime = 600 Spell.ApplyFireDelay = 0.4 Spell.ForceAnim = { ACT_VM_PRIMARYATTACK_4 } Spell.Category = HpwRewrite.CategoryNames.Protecting Spell.Description = [[ Makes area around you completely invisible for everyone who is not inside. ]] Spell.OnlyIfLearned = { "Protego" } Spell.NodeOffset = Vector(-923, 277, 0) Spell.AccuracyDecreaseVal = 0.7 if SERVER then util.AddNetworkString("hpwrewrite_salviohexia_handler") else local mdls = { } net.Receive("hpwrewrite_salviohexia_handler", function() local ent = net.ReadEntity() if not IsValid(ent) then return end local hide = tobool(net.ReadBit()) local finished = tobool(net.ReadBit()) if hide then ent:SetNoDraw(true) ent:DrawShadow(false) --[[for i = 0, ent:GetBoneCount() - 1 do local pos = ent:GetBonePosition(i) local ef = EffectData() ef:SetOrigin(pos) util.Effect("GlassImpact", ef) end]] --SafeRemoveEntity(ent.HPWGhost) sound.Play("hl1/ambience/port_suckin1.wav", ent:GetPos(), 60, 180) else ent:SetNoDraw(false) ent:DrawShadow(true) --[[for i = 0, ent:GetBoneCount() - 1 do local pos = ent:GetBonePosition(i) local ef = EffectData() ef:SetOrigin(pos) util.Effect("GlassImpact", ef) end if finished then for k, v in pairs(mdls) do SafeRemoveEntity(k) end else if ent != LocalPlayer() then local mdl = ClientsideModel(ent:GetModel(), RENDERGROUP_TRANSLUCENT) ent.HPWGhost = mdl mdl:SetPos(ent:GetPos()) mdl:SetAngles(ent:GetAngles()) mdl:SetMaterial("models/props_lab/Tank_Glass001") mdl:SetSkin(ent:GetSkin()) mdl:Spawn() mdl:SetRenderMode(RENDERMODE_TRANSALPHA) mdl:SetColor(Color(255, 255, 255, 20)) mdl:SetModelScale(ent:GetModelScale() * 1.02, 0) if not ent:IsPlayer() then mdl:SetParent(ent) end local name = "hpwrewrite_salviohexia_handler" .. mdl:EntIndex() hook.Add("Think", name, function() if not IsValid(mdl) or not IsValid(ent) then SafeRemoveEntity(mdl) hook.Remove("Think", name) return end if ent:IsPlayer() then mdl:SetPos(ent:GetPos()) mdl:SetAngles(Angle(0, ent:GetAngles().y, 0)) end mdl:SetSequence(ent:GetSequence()) mdl:FrameAdvance(1) end) mdls[mdl] = true end end]] sound.Play("hl1/ambience/port_suckout1.wav", ent:GetPos(), 60, 180) end end) end function Spell:OnFire(wand) if not self.Exists then local name = "hpwrewrite_salviohexia_handler" .. self.Owner:EntIndex() local die = CurTime() + 40 local pos = self.Owner:GetPos() hook.Add("Think", name, function() if CurTime() > die then hook.Remove("Think", name) for k, v in pairs(self.Invisible) do net.Start("hpwrewrite_salviohexia_handler") net.WriteEntity(k) net.WriteBit(false) net.WriteBit(true) net.Broadcast() self.Invisible[k] = nil end table.Empty(self.Proceeded) self.Exists = false return end for k, v in pairs(ents.GetAll()) do if not IsValid(v) then continue end if not v:GetPhysicsObject():IsValid() then continue end if v:IsWorld() then continue end if v:GetPos():Distance(pos) < 600 then self.Invisible[v] = true else self.Invisible[v] = nil end end for k, v in pairs(self.Invisible) do if not IsValid(k) then self.Invisible[k] = nil continue end for _, ply in pairs(player.GetAll()) do if not self.Proceeded[ply] then self.Proceeded[ply] = { } for k, v in pairs(self.Invisible) do self.Proceeded[ply][k] = ply:GetPos():Distance(k:GetPos()) < 400 end end if ply:GetPos():Distance(k:GetPos()) > 400 then if not self.Proceeded[ply][k] then net.Start("hpwrewrite_salviohexia_handler") net.WriteEntity(k) net.WriteBit(true) net.WriteBit(false) net.Send(ply) self.Proceeded[ply][k] = true end else if self.Proceeded[ply][k] then net.Start("hpwrewrite_salviohexia_handler") net.WriteEntity(k) net.WriteBit(false) net.WriteBit(false) net.Send(ply) self.Proceeded[ply][k] = false end end end end end) self.Exists = true end sound.Play("npc/antlion/idle3.wav", wand:GetPos(), 55, math.random(240, 255)) end function Spell:OnSpellGiven(ply) if SERVER then self.Invisible = { } self.Proceeded = { } end return true end HpwRewrite:AddSpell("Salvio Hexia", Spell)
local dconv = require('dproto-conv-gen') local dprotofile = 'type_conversions/dproto/types.dproto' local asn_files = { 'type_conversions/asn/taste-types.asn', 'type_conversions/asn/taste-extended.asn', 'type_conversions/asn/userdefs-base.asn', 'type_conversions/asn/mybase.asn' } local asn = require('asn1_types') local ddr_models = {} ddr_models.asn_files = asn_files dconv.init_runtime(dprotofile,ddr_models) local function runDConv(from_type, to_type) local g,e = dconv.convert(from_type, to_type) if not g then errmsg('Error during type conversion: '..tostring(e)); os.exit(1); end; local str = dconv.CaptureOutput() return g, str end function generate_transformation_code(from_type, from_name, to_type, to_name) if (from_type == 'asn1SccBase_JointState' or to_type == 'asn1SccBase_JointState') then -- workaround for dconv not supporting JoinState conversions return 'joint_state_conversion('..from_name..','..to_name..'); ' end local code = {} if from_type==asn.types.orientation.original then table.insert(code, "internal::Quaternion __or;") local g, str = runDConv(from_type, "QuaternionTemp") g(str, from_name..'', '__or.data') table.insert(code, tostring(str) ) g, str = runDConv("QuaternionTemp", to_type) g(str, '__or', to_name) table.insert(code, tostring(str) ) return table.concat(code, "\n") end if to_type==asn.types.orientation.original then table.insert(code, "internal::Quaternion __or;") local g, str = runDConv(from_type, "QuaternionTemp") g(str, from_name..'', '__or') table.insert(code, tostring(str) ) g, str = runDConv("QuaternionTemp", to_type) g(str, '__or.data', to_name) table.insert(code, tostring(str) ) return table.concat(code, "\n") end local g, str = runDConv(from_type, to_type) g(str, from_name..'', to_name..'') return tostring(str) end local M = {} M.generate_transformation_code = generate_transformation_code return M
-- Copyright (c) 2017-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the license found in the LICENSE file in -- the root directory of this source tree. An additional grant of patent rights -- can be found in the PATENTS file in the same directory. -- --[[ -- -- A parallel dataset iterator that can wrap another iterator and is thus -- limited to using a single thread only. -- --]] local tnt = require 'torchnet' local argcheck = require 'argcheck' local Threads = require 'threads' local doc = require 'argcheck.doc' local SingleParallelIterator = torch.class('tnt.SingleParallelIterator', 'tnt.DatasetIterator', tnt) SingleParallelIterator.__init = argcheck{ {name='self', type='tnt.SingleParallelIterator'}, {name='init', type='function', default=function(idx) end}, {name='closure', type='function'}, call = function(self, init, closure) local function main(idx) giterator = closure(idx) assert(torch.isTypeOf(giterator, 'tnt.DatasetIterator'), 'closure should return a DatasetIterator class') gloop = nil end Threads.serialization('threads.sharedserialize') local threads = Threads(1, init, main) self.__threads = threads local sample -- beware: do not put this line in loop() local sampleOrigIdx function self.run() -- make sure we are not in the middle of something threads:synchronize() local function enqueue() threads:addjob( function() if not gloop then gloop = giterator:run() end local sample = gloop() collectgarbage() collectgarbage() if not sample then gloop = nil end return sample end, function(_sample_) sample = _sample_ end) end enqueue() local iterFunction = function() while threads:hasjob() do threads:dojob() if threads:haserror() then threads:synchronize() end if sample then enqueue() end return sample end end return iterFunction end end } SingleParallelIterator.exec = function(self, name, ...) assert(not self.__threads:hasjob(), 'cannot exec during loop') local args = {...} local res self.__threads:addjob( function() return giterator:exec(name, table.unpack(args)) end, function(...) res = {...} end) self.__threads:synchronize() return table.unpack(res) end
local cfg = require("lib/config") local iracing = require("api/iracing"):instance(cfg.iracing) local twitch = require("api/twitch"):instance(cfg.twitch) local state = require("api/state"):instance(cfg.state) local ui = require("api/winformui"):instance(cfg.winformui) local common = require("lib/common") local session_category = "" local irating = "" local license = "" iracing:send_session_state() iracing:send_car_info() local output = function(txt) twitch:send_channel_message(txt) end local show_irating = function(category) category = string.lower(category or "road") local irating = state:get("irating:" .. category) local license = state:get("license:" .. category) if irating ~= "" and license ~= "" then output("For " .. category .. " irating is " .. irating .. ", license is " .. license) else output("I dont know :(") end end handlers = {} handlers.IRacingCarInfo = function(event) if (irating ~= event.CurrentDriverIRating or license ~= event.CurrentDriverLicense) and event.LocalUser == true and session_category ~= "" then irating = event.CurrentDriverIRating license = event.CurrentDriverLicense ui:print("Saw that we got ir=" .. irating .. " and sr=" .. license) state:set("irating:" .. string.lower(session_category), tostring(irating)) state:set("license:" .. string.lower(session_category), tostring(license)) end end handlers.IRacingPractice = function(event) session_category = string.lower(event.Category) irating = "" license = "" end handlers.IRacingQualify = handlers.IRacingPractice handlers.IRacingRace = handlers.IRacingPractice handlers.IRacingTesting = handlers.IRacingPractice handlers.IRacingWarmup = handlers.IRacingPractice handlers.TwitchReceivedMessage = function(event) local msg = string.trim(string.lower(event.Message)) if msg == "!ir" then show_irating(session_category) elseif msg == "!ir road" or msg == "!ir oval" or msg == "!ir dirtoval" or msg == "!ir dirtroad" then local requested_category = string.sub(msg, 5, string.len(msg)) show_irating(requested_category) elseif string.sub(msg, 1, 4) == "!ir " then output("Use !ir|!ir road|!ir oval|!ir dirtoval|!ir dirtroad") end end function handle(event) if handlers[event.EventType] then handlers[event.EventType](event) end end
function return_except_last(...) arg = {...} table.remove(arg) return table.unpack(arg) end print(return_except_last(1, 2, 3, 4, 5))
math.randomseed(os.time()) print("Munchkin Level Counter") io.read() level = 1 gear = 0 oneshot = 0 against = 0 enemyl = 0 enemye = 0 enemys = 0 runaway = 2 enemyr = 0 fast = 0 slow = 0 tempr = 0 nope = "n" runawayt = 0 enemys = enemyl + enemye print("Help on or off?") print("(\"y\":On)(\"n\":Off)") help = io.read() if help == "y" then print("Help is on.") io.read() else print("Help if off.") io.read() help = "n" end print("What gender are you?") if help == "y" then print("(\"m\":Man)(\"w\":Woman)") end gender = io.read() if gender == "w" then print("You are a woman.") io.read() else print("You are a man.") io.read() gender = "m" end function lose() print("You lost!") io.read() print("Run away?") if help == "y" then print("(\"y\":Yes)(\"n\":No)") end run = io.read() if run == "y" then repeat roll = math.random(1,6) print("You rolled a "..roll..".") print("Reroll?") if help == "y" then print("(\"y\":Yes)(\"n\":No)") end reroll = io.read() until reroll ~= "y" if roll >= 7 - runawayt then print("You escaped!") io.read() else print("You were caught!") print("Prepare to do the badstuff!") io.read() end end end function stats() runawayt = runaway + fast + enemyr + tempr - slow if runawayt > 5 then runawayt = 5 elseif runawayt < 1 then runawayt = 1 end strength = level + gear + oneshot - against print("Combat Strength: "..strength) print("~~~~~~~~~~~~~~~") print("level: "..level) print("Gear: "..gear) print("Oneshot: "..oneshot) print("Against: "..against) print("...............") print("Run Away Roll: "..7 - runawayt.."+") print("Slow: ".. slow) print("Fast: "..fast) print("Temperary Run Away: "..tempr) print("..............") if gender == "m" then print("Man") else print("Woman") end if warrior == "y" then print("Warrior") end end function info() repeat stats() io.read() print("Change your stats?") if help == "y" then if help == "y" then print("(\"l\":Level)(\"ge\":Gender)(\"g\":Gear)(\"f\":Fast)(\"s\":Slow)(\"w\":Warrior)(\"t\":Temp. Run)(\"o\":Oneshot)(\"a\":Against)") end end change = io.read() if change == "l" then print("Up or down?") if help == "y" then print("(\"u\":Up)(\"d\":Down)") end new = io.read() if new == "u" then print("You Leveled up!") io.read() level = level + 1 elseif new == "d" then print("Haha, You lost a level.") io.read() level = level - 1 else print("Invalid choice.") io.read() end elseif change == "ge" then print("What gender are you?") if help == "y" then print("(\"m\":Man)(\"w\":Woman)") end gender = io.read() if gender == "w" then print("You are a woman.") io.read() else print("You are a man.") io.read() gender = "m" end elseif change == "g" then print("Up or Down?") if help == "y" then print("(\"u\":Up)(\"d\":Down)") end new = io.read() if new == "u" then print("How much?") if help == "y" then print("([#]:Amount)") end diff = io.read() gear = gear + diff print("Your gear is now "..gear..".") io.read() elseif new == "d" then print("How much?") if help == "y" then print("([#]:Amount)") end diff = io.read() gear = gear - diff print("Your gear is now "..gear..".") io.read() else print("Invalid choice.") io.read() end elseif change == "f" then print("Up or Down?") if help == "y" then print("(\"u\":Up)(\"d\":Down)") end new = io.read() if new == "u" then print("How much?") if help == "y" then print("([#]:Amount)") end diff = io.read() fast = fast + diff print("Your fast is now "..fast..".") io.read() elseif new == "d" then print("How much?") if help == "y" then print("([#]:Amount)") end diff = io.read() fast = fast - diff print("Your fast is now "..fast..".") io.read() else print("Invalid choice.") io.read() end elseif change == "s" then print("Up or Down?") if help == "y" then print("(\"u\":Up)(\"d\":Down)") end new = io.read() if new == "u" then print("How much?") if help == "y" then print("([#]:Amount)") end diff = io.read() slow = slow + diff print("Your slow is now "..slow..".") io.read() elseif new == "d" then print("How much?") if help == "y" then print("([#]:Amount)") end diff = io.read() slow = slow - diff print("Your slow is now "..slow..".") io.read() else print("Invalid choice.") io.read() end elseif change == "w" then print("Are you a warrior?") if help == "y" then print("(\"y\":Yes)(\"n\":No)") end warrior = io.read() if warrior ~= "y" then warrior = "n" print("You are not a warrior.") io.read() else print("You are now a warrior.") io.read() end elseif change == "t" then print("Up or Down?") if help == "y" then print("(\"u\":Up)(\"d\":Down)") end new = io.read() if new == "u" then print("How much?") if help == "y" then print("([#]:Amount)") end diff = io.read() tempr = tempr + diff print("Your temparary run away is now "..tempr..".") io.read() elseif new == "d" then print("How much?") if help == "y" then print("([#]:Amount)") end diff = io.read() tempr = tempr - diff print("Your temparary run away is now "..tempr..".") io.read() else print("Invalid choice.") io.read() end elseif change == "o" then print("Up or Down?") if help == "y" then print("(\"u\":Up)(\"d\":Down)") end new = io.read() if new == "u" then print("How much?") if help == "y" then print("([#]:Amount)") end diff = io.read() oneshot = oneshot + diff print("Your oneshot is now "..oneshot..".") io.read() elseif new == "d" then print("How much?") if help == "y" then print("([#]:Amount)") end diff = io.read() oneshot = oneshot - diff print("Your oneshot is now "..oneshot..".") io.read() else print("Invalid choice.") io.read() end elseif change == "a" then print("Up or Down?") if help == "y" then print("(\"u\":Up)(\"d\":Down)") end new = io.read() if new == "u" then print("How much?") if help == "y" then print("([#]:Amount)") end diff = io.read() against = against + diff print("Your against is now "..against..".") io.read() elseif new == "d" then print("How much?") if help == "y" then print("([#]:Amount)") end diff = io.read() against = against - diff print("Your against is now "..against..".") io.read() else print("Invalid choice.") io.read() end else nope = "y" end if nope == "n" then print("More?") if help == "y" then print("(\"y\":Yes)(\"n\":No)") end again = io.read() else again = "n" nope = "n" end until again ~= "y" end repeat info() print("Roll the die?") if help == "y" then print("(\"y\":Yes)(\"n\":No)") end run = io.read() if run == "y" then repeat roll = math.random(1,6) print("You rolled a "..roll..".") print("Reroll?") if help == "y" then print("(\"y\":Yes)(\"n\":No)") end reroll = io.read() until reroll ~= "y" end print("Combat?") if help == "y" then print("(\"y\":Yes)(\"n\":No)") end choose = io.read() if choose == "y" then print("What is the enemy's level?") enemyl = io.read() repeat enemys = enemyl + enemye print("---------------------") print("Enemy Strength: "..enemys) print("~~~~~~~~~~~~~~~~") print("Enemy Level: "..enemyl) print("Enemy Enhancements: "..enemye) print("................") print("Run Away Special: "..enemyr) print("_____________________") print("_____________________") info() print("Change the enemy's stats?") if help == "y" then print("(\"e\":Enhancements)(\"s\":Run Special)") end change = io.read() if change == "e" then print("Up or Down?") if help == "y" then print("(\"u\":Up)(\"d\":Down)") end new = io.read() if new == "u" then print("How much?") if help == "y" then print("([#]:Amount)") end diff = io.read() enemye = enemye + diff print("The enemy's enhancements are now at: "..enemye) io.read() elseif new == "d" then print("How much?") if help == "y" then print("([#]:Amount)") end diff = io.read() enemye = enemye - diff print("The enemy's enhancements are now at: "..enemye) io.read() else print("Invalid choice.") io.read() end elseif change == "s" then print("Up or Down?") if help == "y" then print("(\"u\":Up)(\"d\":Down)") end new = io.read() if new == "u" then print("How much?") if help == "y" then print("([#]:Amount)") end diff = io.read() enemyr = enemyr + diff print("The enemy's runaway special is now at: "..enemyr) io.read() elseif new == "d" then print("How much?") if help == "y" then print("([#]:Amount)") end diff = io.read() enemyr = enemyr - diff print("The enemy's runaway special are now at: "..enemyr) io.read() else print("Invalid choice.") io.read() end end print("Fight?") if help == "y" then print("(\"y\":Yes)(\"n\":No)") end fight = io.read() if fight == "y" then if enemys < strength then print("You won!") io.read() print("Level up?") if help == "y" then print("(\"y\":Yes)(\"n\":No)") end answer = io.read() if answer == "y" then print("How many times?") if help == "y" then print("([#]:Amount)") end answer = io.read("*n") level = level + answer print("You leveled up!") io.read() end else if enemys > strength then lose() else if warrior == "y" then print("You won!") io.read() print("Level up?") if help == "y" then print("(\"y\":Yes)(\"n\":No)") end answer = io.read() if answer == "y" then print("How many times?") if help == "y" then print("([#]:Amount)") end answer = io.read("*n") level = level + answer print("You leveled up!") io.read() end else lose() end end end end until fight == "y" fight = "n" against = 0 oneshot = 0 enemyr = 0 tempr = 0 enemye = 0 end until 1 == 2
return Def.Actor{ OnCommand=function(self) SL.Global.Stages.Stats[SL.Global.Stages.PlayedThisGame + 1] = { song = GAMESTATE:IsCourseMode() and GAMESTATE:GetCurrentCourse() or GAMESTATE:GetCurrentSong(), TimingWindows = SL.Global.ActiveModifiers.TimingWindows, MusicRate = SL.Global.ActiveModifiers.MusicRate, Type = GAMESTATE:IsCourseMode() and "course" or "song" } end }
----------------------------------- -- Author: Eligio Becerra -- -- Copyright 2009 Eligio Becerra -- ----------------------------------- local setmetatable = setmetatable local tonumber = tonumber local sformat = string.format local smatch = string.match local sgmatch = string.gmatch local tconcat = table.concat local spawn = require 'awful.spawn' local wibox = require 'wibox' local markup = require 'obvious.lib.markup' local hooks = require 'obvious.lib.hooks' local temperature = {} local widget = wibox.widget.textbox() local colors = { normal = '#009000', warm = '#909000', hot = '#900000', } local function acpi_backend(callback) local callbacks = {} local lines = {} function callbacks.stdout(line) lines[#lines + 1] = line end function callbacks.output_done() local d = tconcat(lines) local temp = {} for t in sgmatch(d, 'Thermal %d+: %w+, (%d+.?%d*) degrees') do temp[#temp + 1] = tonumber(t) end if #temp == 0 then return callback() end return callback(temp) end local err = spawn.with_line_callback({'acpi', '-t'}, callbacks) if type(err) == 'string' then return callback() end end local function sensors_backend(callback) local callbacks = {} local in_temp_block = false local ignore_further_lines = false local stats = {} function callbacks.stdout(line) if ignore_further_lines then return end -- we assume that the first temp1 block is the CPU, and that -- the CPU stats are under temp1 if line == 'temp1:' then in_temp_block = true elseif in_temp_block then if line == '' then ignore_further_lines = true end local name, value = smatch(line, '^%s*temp1_(%w+):%s+(.+)') if name and value then stats[name] = tonumber(value) end end end function callbacks.output_done() if stats.input then return callback { stats.input } else return callback() end end local err = spawn.with_line_callback({'sensors', '-u'}, callbacks) if type(err) == 'string' then return callback() end end local function noop_backend(callback) callback {} end local backends = { acpi_backend, sensors_backend, noop_backend, } local current_backend local function find_backend(next_backend_idx, callback) if current_backend then return callback(current_backend) end local backend = backends[next_backend_idx] backend(function(stats) if stats then current_backend = backend return callback(backend) end if next_backend_idx < #backends then find_backend(next_backend_idx + 1, callback) end end) end local function update() current_backend(function(temp) local color = colors.hot if not temp[1] then widget:set_text 'no data' return end if temp[1] < 50 then color = colors.normal elseif temp[1] >= 50 and temp[1] < 60 then color = colors.warm end widget:set_markup(sformat('%.2f', temp[1]) .. ' ' .. markup.fg.color(color, 'C')) end) end hooks.timer.register(5, 30, update) hooks.timer.stop(update) return setmetatable(temperature, { __call = function () find_backend(1, function() hooks.timer.start(update) update() end) return widget end }) -- vim: filetype=lua:expandtab:shiftwidth=3:tabstop=3:softtabstop=3:textwidth=80
while wait() do local Self = script:Clone() Self.Parent = script.Parent script.Disabled = true script.Disabled = false wait(0.1) script:Destroy() end
local helpers = require "spec.helpers" local cjson = require "cjson" --*****************************************************-- -- Setup to run the tests: -- 1. Setup Openwhisk server and create a action -- using include `action/hello.js` -- 2. Set `config.host` and `config.service_token` --*****************************************************-- local HOST = "openwhisk_host" local SERVICE_TOKEN = "openwhisk_auth_token" describe("Plugin: openwhisk", function() local proxy setup(function() local api1 = assert(helpers.dao.apis:insert { name = "test-openwhisk", hosts = { "test.com" }, upstream_url = "http://mockbin.com", }) assert(helpers.dao.plugins:insert { api_id = api1.id, name = "openwhisk", config = { host = HOST, service_token = SERVICE_TOKEN, action = "hello", path = "/api/v1/namespaces/guest", } }) assert(helpers.start_kong()) end) teardown(function() helpers.stop_kong(nil, false) end) before_each(function() proxy = helpers.proxy_client() end) after_each(function() if proxy then proxy:close() end end) describe("invoke action hello", function() it("should allow POST", function() local res = assert(proxy:send { method = "POST", path = "/", body = {}, headers = { ["Host"] = "test.com" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal("Hello, World!", json.payload) end) it("should allow POST with querystring", function() local res = assert(proxy:send { method = "POST", path = "/?name=foo", body = {}, headers = { ["Host"] = "test.com" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal("Hello, foo!", json.payload) end) it("should allow POST with json body", function() local res = assert(proxy:send { method = "POST", path = "/", body = { name = "foo" }, headers = { ["Host"] = "test.com", ["Content-Type"] = "application/json" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal("Hello, foo!", json.payload) end) it("should allow POST with form-encoded body", function() local res = assert(proxy:send { method = "POST", path = "/post", body = { name = "foo" }, headers = { ["Host"] = "test.com", ["Content-Type"] = "application/x-www-form-urlencoded" }, }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal("Hello, foo!", json.payload) end) it("should not allow GET", function() local res = assert(proxy:send { method = "GET", path = "/", body = { name = "foo" }, headers = { ["Host"] = "test.com", ["Content-Type"] = "application/json" } }) local body = assert.res_status(405, res) local json = cjson.decode(body) assert.equal("Method not allowed", json.message) end) it("should not allow DELETE", function() local res = assert(proxy:send { method = "DELETE", path = "/", body = { name = "foo" }, headers = { ["Host"] = "test.com", ["Content-Type"] = "application/json" } }) local body = assert.res_status(405, res) local json = cjson.decode(body) assert.equal("Method not allowed", json.message) end) end) end)
if minetest.get_modpath("factory") then minetest.registered_nodes["factory:storage_tank_water"].special_tiles[1].name = "ws_water_source_animated.png" minetest.registered_nodes["factory:storage_tank_lava"].special_tiles[1].name = "ws_lava_source_animated.png" end
-- require("settings.impatient") local sources = { -- settings "settings.colorschemes", "settings.keymaps", "settings.options", "settings.plugins", -- -- plugins "configs.alpha", "configs.autopairs", "configs.autosave", "configs.better_escape", "configs.bufferline", "configs.cmp", "configs.colorizer", "configs.comments", "configs.filetype", "configs.gitsigns", "configs.indentline", "configs.lualine", "configs.neoscroll", "configs.nvim-tree", "configs.presence", "configs.symbols_outline", "configs.telescope", "configs.toggleterm", -- "configs.treesitter", "configs.trouble", "configs.webdevicons", -- currently not in use "configs.which-key", "lsp", } for _, source in ipairs(sources) do local status_ok, notok = pcall(require, source) if not status_ok then error("Couldn't load " .. source .. "\n" .. notok) end end
-- stolen from penlight local function copy_tbl (t) local res = {} for k,v in pairs(t) do res[k] = v end return res end do local WOStateDisqualifier = torch.class('WOStateDisqualifier') -- i assume source is a single sequence w/o start or end tokens. -- this will by default disqualify end-token function WOStateDisqualifier:__init(source, B, V, maskmem, idxmem) self.B = B self.hyp_states = {[1]={}} local word_bag = {} local word_type_count = 0 -- keep track of remaining words we can use for t = 1, source:size(1) do if self.hyp_states[1][source[t]] then self.hyp_states[1][source[t]] = self.hyp_states[1][source[t]] + 1 else self.hyp_states[1][source[t]] = 1 word_bag[source[t]] = true word_type_count = word_type_count + 1 end end -- return an initial additive mask we can always use self.mask = maskmem:view(B, V) self.mask:fill(-math.huge) -- zero out stuff actually in the source self.src_idxs = idxmem:sub(1, word_type_count) local i = 1 for w, b in pairs(word_bag) do self.src_idxs[i] = w i = i + 1 end self.mask[1]:indexFill(1, self.src_idxs, 0) self.word_bag = word_bag end -- update before next search function WOStateDisqualifier:updateStates(parents, preds, scores) -- rembuff, pred_inp, resval local new_hyps = {} local removal_cands = {} for k = 1, self.B do if scores[k] > -math.huge then new_hyps[k] = copy_tbl(self.hyp_states[parents[k]]) new_hyps[k][preds[k]] = new_hyps[k][preds[k]] - 1 if new_hyps[k][preds[k]] == 0 then new_hyps[k][preds[k]] = nil -- remove key end -- update the mask for w, b in pairs(self.word_bag) do if new_hyps[k][w] then -- still an option going fwd self.mask[k][w] = 0 else self.mask[k][w] = -math.huge if removal_cands[w] then removal_cands[w] = removal_cands[w] + 1 else removal_cands[w] = 1 end if k == self.B and removal_cands[w] == self.B then -- everybody removed, so we're done self.word_bag[w] = nil self.mask:select(2, w):fill(-math.huge) end end end else -- we got -inf, which can happen if beam is longer than sentence, for instance new_hyps[k] = self.hyp_states[parents[k]] -- just to be sure, no next prediction is valid for w, b in pairs(self.word_bag) do self.mask[k][w] = -math.huge end end end -- end for k self.hyp_states = new_hyps end function WOStateDisqualifier:disqualify(scores) -- scores assumed to be B x V scores:add(self.mask:sub(1, scores:size(1))) -- just handles beginning when one thing on beam end function WOStateDisqualifier:allowEnd(end_token) self.mask:select(2,end_token):zero() end end -- stanford dependency labels dep_labels = {['@L_PRT']=true, ['@R_PRT']=true, ['@L_PARATAXIS']=true, ['@R_IOBJ']=true, ['@R_POSSESSIVE']=true, ['@R_NUMBER']=true, ['@R_APPOS']=true, ['@L_PUNCT']=true, ['@L_CONJ']=true, ['@L_CCOMP']=true, ['@L_CC']=true, ['@L_POSS']=true, ['@R_COP']=true, ['@R_NN']=true, ['@L_PREP']=true, ['@R_NSUBJPASS']=true, ['@L_PREDET']=true, ['@R_TMOD']=true, ['@R_MWE']=true, ['@R_QUANTMOD']=true, ['@L_NSUBJ']=true, ['@R_PARATAXIS']=true, ['@R_PUNCT']=true, ['@R_EXPL']=true, ['@L_APPOS']=true, ['@R_ACOMP']=true, ['@R_NPADVMOD']=true, ['@L_MARK']=true, ['@L_PRECONJ']=true, ['@R_DOBJ']=true, ['@L_ADVCL']=true, ['@R_DISCOURSE']=true, ['@L_POBJ']=true, ['@L_NUMBER']=true, ['@R_CONJ']=true, ['@R_ADVMOD']=true, ['@L_DOBJ']=true, ['@R_ADVCL']=true, ['@R_XCOMP']=true, ['@L_AMOD']=true, ['@L_ADVMOD']=true, ['@L_POSSESSIVE']=true, ['@L_DISCOURSE']=true, ['@R_INFMOD']=true, ['@R_NUM']=true, ['@L_DEP']=true, ['@L_NSUBJPASS']=true, ['@R_PCOMP']=true, ['@L_NPADVMOD']=true, ['@L_DET']=true, ['@L_COP']=true, ['@L_PARTMOD']=true, ['@R_AMOD']=true, ['@R_AUXPASS']=true, ['@L_AUXPASS']=true, ['@R_PREP']=true, ['@R_PARTMOD']=true, ['@L_CSUBJ']=true, ['@L_EXPL']=true, ['@L_AUX']=true, ['@R_NEG']=true, ['@L_MWE']=true, ['@R_RCMOD']=true, ['@R_CCOMP']=true, ['@R_CC']=true, ['@R_AUX']=true, ['@L_XCOMP']=true, ['@R_NSUBJ']=true, ['@L_NUM']=true, ['@R_POBJ']=true, ['@L_NN']=true, ['@L_NEG']=true, ['@L_TMOD']=true, ['@L_CSUBJPASS']=true, ['@R_DET']=true, ['@R_POSS']=true, ['@R_DEP']=true, ['@L_QUANTMOD']=true, ['@L_ACOMP']=true} function get_dep_label_idxs(word2idx_targ, cuda) local label_idxs = cuda and torch.CudaTensor() or torch.Tensor() label_idxs:resize(79) local ii = 1 for w, b in pairs(dep_labels) do label_idxs[ii] = word2idx_targ[w] ii = ii + 1 end assert(ii == 80) return label_idxs end do local LabeledSRStateDisqualifier = torch.class('LabeledSRStateDisqualifier') -- i assume source is a single sequence w/o start or end tokens. -- this will by default disqualify end-token. function LabeledSRStateDisqualifier:__init(source, B, V, maskmem, idxmem, label_idxs, idx2word_src, word2idx_targ, idx2word_targ) self.B = B self.word2idx = word2idx_targ self.idx2word = idx2word_targ self.source = idxmem:sub(1, source:size(1)) -- copy target vocab version of source for i = 1, source:size(1) do self.source[i] = word2idx_targ[idx2word_src[source[i]]] end self.hyp_states = {} self.hyp_states[1] = {next_word_idx = 1, stack_size = 0} -- return an initial additive mask we can always use self.mask = maskmem:view(B, V) self.mask:fill(-math.huge) -- the only kosher initial prediction is the first word self.mask[1][self.source[1]] = 0 self.lb = 1 -- earliest token any hyp is still up to self.ub = 1 -- latest token any hyp is still up to self.label_idxs = label_idxs end -- update before next search function LabeledSRStateDisqualifier:updateStates(parents, preds, scores) -- rembuff, pred_inp, resval local new_hyps = {} local beam_min = math.huge for k = 1, self.B do if scores[k] > -math.huge then new_hyps[k] = copy_tbl(self.hyp_states[parents[k]]) if dep_labels[self.idx2word[preds[k]]] then --if preds[k] == self.lred_idx or preds[k] == self.rred_idx then new_hyps[k].stack_size = new_hyps[k].stack_size - 1 else new_hyps[k].stack_size = new_hyps[k].stack_size + 1 new_hyps[k].next_word_idx = new_hyps[k].next_word_idx + 1 if new_hyps[k].next_word_idx > self.ub and new_hyps[k].next_word_idx <= self.source:size(1) then self.ub = new_hyps[k].next_word_idx end end -- keep track of lowest index still in play if new_hyps[k].next_word_idx < beam_min then beam_min = new_hyps[k].next_word_idx end -- update mask for next search step for i = self.lb, self.ub do self.mask[k][self.source[i]] = -math.huge end -- allow only after setting to -inf, in case there are repeats if new_hyps[k].next_word_idx <= self.source:size(1) then self.mask[k][self.source[new_hyps[k].next_word_idx]] = 0 end if new_hyps[k].stack_size >= 2 then --self.mask[k][self.lred_idx] = 0 --self.mask[k][self.rred_idx] = 0 self.mask[k]:indexFill(1, self.label_idxs, 0) else --self.mask[k][self.lred_idx] = -math.huge --self.mask[k][self.rred_idx] = -math.huge self.mask[k]:indexFill(1, self.label_idxs, -math.huge) end else -- we got -inf, which can happen if beam is longer than sentence, for instance for i = self.lb, self.ub do self.mask[k][self.source[i]] = -math.huge end --self.mask[k][self.lred_idx] = -math.huge --self.mask[k][self.rred_idx] = -math.huge self.mask[k]:indexFill(1, self.label_idxs, -math.huge) end end -- end for k -- we may be able to move up lb if beam_min > self.lb then -- everything on beam is above lb so we can forget about lower indices self.lb = beam_min end self.hyp_states = new_hyps end function LabeledSRStateDisqualifier:disqualify(scores) -- scores assumed to be B x V scores:add(self.mask:sub(1, scores:size(1))) -- just handles beginning when one thing on beam end function LabeledSRStateDisqualifier:allowEnd(end_token) self.mask:select(2,end_token):zero() end end
--[[-- request.set_404_route{ module = module, -- module name view = view -- view name } In case a view or action is not found, the given module and view will be used to display an error page. --]]-- function request.set_404_route(tbl) request.configure(function() request._404_route = tbl -- TODO: clone? end) end
object_draft_schematic_space_cargo_hold_crg_pob_gunship_huge = object_draft_schematic_space_cargo_hold_shared_crg_pob_gunship_huge:new { } ObjectTemplates:addTemplate(object_draft_schematic_space_cargo_hold_crg_pob_gunship_huge, "object/draft_schematic/space/cargo_hold/crg_pob_gunship_huge.iff")
-- Heap contains the following functions: -- .new(comparator) - Creates a new Heap -- comparator: Uses this function to compare values. If none is given, will assume values are numbers and will find smallest value -- Comparator should accept two values and return true if a should be further up the heap than b and false otherwise -- :Heapify(oldTable, comparator) - Converts a table to a Heap - Will destroy the provided table -- comparator: The comparator to pass to Heap.new(comparator) -- :Meld(heap1, heap2) - Creates a new Heap using the two provided Heaps -- A Heap object has the following functions: -- :Insert(newValue) - Adds an element to the Heap -- :Pop() - Removes the first element in the Heap and returns it -- :Peek() - Returns the first element in the Heap but does not remove it -- :GetAsTable() - Returns a table of the elements in the Heap -- :Clear() - Removes all values from the Heap -- :Print() - Prints out all the values in the Heap -- :Size() - Returns the size of the Heap -- :Clone() - Creates and returns a new copy of the Heap Heap = {} Heap.__index = Heap local Floor = math.floor local function DefaultCompare(a, b) if a > b then return true else return false end end local function SiftUp(heap, index) local parentIndex if index ~= 1 then parentIndex = Floor(index/2) if heap.Compare(heap[parentIndex], heap[index]) then heap[parentIndex], heap[index] = heap[index], heap[parentIndex] SiftUp(heap, parentIndex) end end end local function SiftDown(heap, index) local leftChildIndex, rightChildIndex, minIndex leftChildIndex = index * 2 rightChildIndex = index * 2 + 1 if rightChildIndex > #heap then if leftChildIndex > #heap then return else minIndex = leftChildIndex end else if not heap.Compare(heap[leftChildIndex], heap[rightChildIndex]) then minIndex = leftChildIndex else minIndex = rightChildIndex end end if heap.Compare(heap[index], heap[minIndex]) then heap[minIndex], heap[index] = heap[index], heap[minIndex] SiftDown(heap, minIndex) end end function Heap.new(comparator) local newHeap = { } setmetatable(newHeap, Heap) if comparator then newHeap.Compare = comparator else newHeap.Compare = DefaultCompare end return newHeap end function Heap:Insert(newValue) table.insert(self, newValue) if #self <= 1 then return end SiftUp(self, #self) end function Heap:Pop() if #self > 0 then local toReturn = self[1] self[1] = self[#self] table.remove(self, #self) if #self > 0 then SiftDown(self, 1) end return toReturn else return nil end end function Heap:Peek() if #self > 0 then return self[1] else return nil end end function Heap:GetAsTable() local newTable = { } for i = 1, #self do table.insert(newTable, self[i]) end return newTable end function Heap:Clear() for k in pairs(self) do self[k] = nil end end function Heap:Print() local out = "" for i = 1, #self do out = out .. tostring(self[i]) .. " " end print(out) end function Heap:Size() return #self end function Heap:Clone() local newHeap = Heap.new(self.Compare) for i = 1, #self do table.insert(newHeap, self[i]) end return newHeap end -- Functions that are not self-referential function Heap:Heapify(oldTable, comparator) local newHeap = Heap.new(comparator) for i = #oldTable, 1, -1 do newHeap:Insert(oldTable[i]) table.remove(oldTable, i) end return newHeap end function Heap:Meld(heap1, heap2, comparator) if not comparator then comparator = heap1.Compare or heap2.Compare end local newHeap = Heap.new(comparator) for i = #heap1, 1, -1 do newHeap:Insert(heap1[i]) end for i = #heap2, 1, -1 do newHeap:Insert(heap2[i]) end return newHeap end return Heap
----------------------------------- -- -- tpz.effect.BALLAD -- getPower returns the TIER (e.g. 1,2,3,4) -- DO NOT ALTER ANY OF THE EFFECT VALUES! DO NOT ALTER EFFECT POWER! -- Todo: Find a better way of doing this. Need to account for varying modifiers + CASTER's skill (not target) ----------------------------------- require("scripts/globals/status") ----------------------------------- function onEffectGain(target,effect) target:addMod(tpz.mod.REFRESH,effect:getPower()) end function onEffectTick(target,effect) end function onEffectLose(target,effect) target:delMod(tpz.mod.REFRESH,effect:getPower()) end
function system_log(x,y) interval = 1 font_size = 12.5 spacing = 1.2 local color = color4 timer = (updates % interval) if timer == 0 or conky_start == 1 then result = io.popen("journalctl -n 14 | sed 1d | awk '{$1=$2=$4=\"\"; print $0}' | sed 's/ //' | sed 's/ / /' | fold -w 80 -s") sl_t = {} for line in result:lines() do table.insert(sl_t,line) end result:close() end if next(sl_t) == nil then return end local n = 1 for i, line in ipairs (sl_t) do y = y + font_size*spacing if y >= 1030 then else local text = line displaytext(x,y,text,font,font_size,color) n = n+1 end end end
--[[ COPYRIGHT 2021-PRESENT NoahBrahim (noahalhandy.com) - ALL RIGHTS RESERVED. THIS SCRIPT IS ALLOWED TO BE MODIFIED TO SUPPORT DIFFERENT COMMANDS OR KEYBINDS TO TRIGGER THE SCRIPT. DO NOT DISTRIBUTE THIS SOFTWARE WITHOUT STRICT PERMISSION. THIS IS DUE TO THE AMMOUNT OF WORK PUT INTO THIS PROJECT. THANK YOU - NOAH BRAHIM ]]-- --[[ COPYRIGHT 2021-PRESENT OpticsXS - ALL RIGHTS RESERVED. ]]--
local ProcessRunner = foundation.com.ProcessRunner local case = foundation.com.Luna:new("foundation.com.ProcessRunner") local function wait_until_dead(pr, pid, timeout) local elapsed = 0 while pr:is_alive(pid) do pr:update(0.016) elapsed = elapsed + 0.016 if elapsed > timeout then error("timeout") end end end case:describe("spawn/1", function (t2) t2:test("can spawn a new process", function (t3) local pr = ProcessRunner:new() local x local pid = pr:spawn(function (my_pid, my_pr) x = my_pid end) t3:assert(pr:is_alive(pid)) wait_until_dead(pr, pid, 5000) t3:assert_eq(x, pid) end) end) case:describe("send/1", function (t2) t2:test("can send a message to a process", function (t3) local pr = ProcessRunner:new() local received_message local pid = pr:spawn(function (my_pid, my_pr) local success, msg = my_pr:receive() received_message = msg end) t3:assert(pr:send(pid, "hello")) t3:assert_deep_eq(pr:get_mailbox(pid), {{"send", "hello"}}) wait_until_dead(pr, pid, 5000) t3:assert_deep_eq(received_message, {"send", "hello"}) end) end) case:describe("send_exit/1", function (t2) t2:test("can order a process to exit normally", function (t3) local pr = ProcessRunner:new() local received_message local pid = pr:spawn(function (my_pid, my_pr) local success, msg = my_pr:receive() received_message = msg end) t3:assert(pr:send_exit(pid, "please stop")) wait_until_dead(pr, pid, 5000) t3:assert_deep_eq(received_message, {"exit", "please stop"}) end) end) case:describe("send_after/1", function (t2) t2:test("can schedule a message to be received by a process later", function (t3) local pr = ProcessRunner:new() local received_message local pid = pr:spawn(function (my_pid, my_pr) local success, msg = my_pr:receive() received_message = msg end) pr:send_after(pid, "future item", 3) pr:update(1) t3:assert_deep_eq(pr:get_mailbox(pid), {}) pr:update(2) t3:assert_deep_eq(received_message, {"send", "future item"}) end) end) case:describe("kill/1", function (t2) t2:test("immediately kill a process without notifying it", function (t3) local pr = ProcessRunner:new() local pid = pr:spawn(function (my_pid, my_pr) local success, msg = my_pr:receive() received_message = msg end) pr:kill(pid) t3:refute(pr:is_alive(pid)) end) end) case:execute() case:display_stats() case:maybe_error()
return {'lid','lidcactus','lidgeld','lidkaart','lidland','lidmaat','lidmaatschap','lidmaatschapsaanvraag','lidmaatschapsbewijs','lidmaatschapsgeld','lidmaatschapskaart','lidnummer','lidocaine','lidstaat','lidwoord','lidbonden','lidmatenboek','lidia','lidwien','lida','lidewij','lidwina','lidy','lidje','lidjes','lidmaatschappen','lidmaten','lidstaten','lidwoorden','lidcactussen','lidgelden','lidkaarten','lidlanden','lidmaatschapskaarten','lidnummers','lidas','lidewijs','lidias','lidwiens','lidwinas','lidys','lidmatenboeken'}
--[[ 房间右上角菜单 ]] local layerBase = require("games/common2/module/layerBase"); local RoomMenuBarLayer = class(layerBase); RoomMenuBarLayer.s_cmds = { initToolBar = ToolKit.getIndex(); }; RoomMenuBarLayer.ctor = function ( self ) self:init(); end RoomMenuBarLayer.dtor = function ( self ) end RoomMenuBarLayer.init = function ( self ) local localseat = PlayerSeat.getInstance():getMyLocalSeat(); if self.m_viewConfig[localseat] then self:addView(localseat,self.m_viewConfig[localseat]); end end RoomMenuBarLayer.initToolBar = function ( self, ... ) end RoomMenuBarLayer.parseViewConfig = function(self) local viewConfig = { ["onlooker"] = {}; }; return viewConfig; end RoomMenuBarLayer.initViewConfig = function ( self ) -- body self.m_viewConfig = { [1] = { path = "games/common2/module/roomMenuBar/roomMenuBarView"; pos = {}; viewLayer = "view/kScreen_1280_800/games/common2/menuToolbar/room_menu_toolbar"; viewConfig = "room_menu_toolbar"; }; [2] = {}; [3] = {}; }; end RoomMenuBarLayer.onMenuClick = function ( self, callbackFunc ) -- body Log.d("RoomMenuBarLayer.onMenuClick", callbackFunc); if string.isEmpty(callbackFunc) then Log.d("RoomMenuBarLayer.onMenuClick", "Param callbackFunc cannot be empty."); return; end self:execDelegate(callbackFunc); end RoomMenuBarLayer.s_cmdConfig = { [RoomMenuBarLayer.s_cmds.initToolBar] = RoomMenuBarLayer.initToolBar; }; return RoomMenuBarLayer; --[[ 菜单模块 默认支持 退出、托管、商城、设置、取款 5个操作。 特殊功能说明: 1、配置里面的items.callbackFunc参数,配置按钮回调的方法。在gamescene里面实现items.callbackFunc,就可以自定义处理事件 2、items.action:定义点击事件触发后,需要发送的动作消息 3、toolBarConfig.time_view定义了时钟显示的位置,老版本中时钟和菜单是一个模块,680进行了拆分。时钟模块默认是隐藏的,为了兼容老版本 在菜单创建时,会读取toolBarConfig.time_view配置,发送ACTION_NS_INITTIMEVIEW消息,通知时间是否显示,并设置位置 配置说明: DDZConfig.toolBarConfig = { ["aiCommand"] = DDZSocketCmd.ROOM_SEND_AI, -- 定义托管,发送的命令。各子游戏有可能定义不一致 ["items"] = { -- 没有自定义的菜单时,不需要配置items { key = "menu_exit", -- 菜单名称 icon = "", -- 菜单ICON图标的路径 callbackFunc = "onToolbarExitClick", -- 事件回调的方法,在对于游戏的scene中处理 isDefault = true, -- 是否系统默认菜单 sort = 1, -- 菜单排序 action = "", -- 定义按钮点击,需要出发的动作消息 isHid = true, -- 按钮是否需要隐藏 path = "games/common/menuToolbar/menu/%s.png", -- 菜单按钮的路径。命名规则key.png 和key_grey.png可点击和不可点击2中状态 }, }; ["menu_view"] = { --菜单弹框位置(不配则为默认位置) ["x"] = 10; ["y"] = 0; ["align"] = kAlignTopRight; }; ["menubtn_view"] = { 菜单按钮位置 ["x"] = 0; ["y"] = 0; ["align"] = kAlignTopLeft; }; }; 状态监听: STATUS_READY:准备后不可取款 STATUS_START:游戏开始后,不能退出和重置 STATUS_GAMEOVER:游戏结束后,取款、退出、重置按钮设置为可点击 STATUS_LOGIN/STATUS_LOGOUT:登陆和登陆状态时,重置默认按钮可点击状态。自定义按钮,需要发送ACTION_NS_MENUBAR_BTN_ENABLE消息通知更新 动作监听: ACTION_NS_CANCEL_AI:发送消息取消托管 ACTION_NS_ROBOT:刷新托管状态 ACTION_NS_MENUBAR_BTN_ENABLE:设置菜单按钮是否可点击 调用方式: local info = { [1] = {key="menu_setting",enable=false}; [2] = {key="menu_exit",enable=true}; }; MechineManage.getInstance():receiveAction(GameMechineConfig.ACTION_NS_MENUBAR_BTN_ENABLE,info); 特殊功能调用: 保险箱取款: local action = GameMechineConfig.ACTION_NS_CREATVIEW; local data = {viewName = GameMechineConfig.VIEW_SAFEBOX} MechineManage.getInstance():receiveAction(action,data); local action = GameMechineConfig.ACTION_NS_OPEN_SAFEBOX; MechineManage.getInstance():receiveAction(action); 设置: local action = GameMechineConfig.ACTION_NS_CREATVIEW; local data = {viewName = GameMechineConfig.VIEW_SETTING} MechineManage.getInstance():receiveAction(action,data); local action = GameMechineConfig.ACTION_NS_OPEN_SETTING; MechineManage.getInstance():receiveAction(action); ]]
function ObstacleMixin:_GetPathingInfo() local position = self:GetOrigin() + Vector(0, -2, 0) local radius = LookupTechData(self:GetTechId(), kTechDataObstacleRadius, 1.0) local height = 5.0 return position, radius, height end
local Edge = {} Edge.__index = Edge local plugin_Settings = require(script.Parent.Parent.Settings) function Edge.new(mesh) local self = setmetatable({}, Edge) self.mesh = mesh self.line = nil self.vertices = {} self.faces = {} return self end function Edge:CreateLine() self.line = Instance.new('CylinderHandleAdornment') self.line.Radius = .005 self.line.Color3 = plugin_Settings['EDGE_COLOR']--Color3.fromRGB(200,160,90) self.line.Transparency = 0 self.line.Adornee = game.Workspace.Terrain self.line.Visible = false --self.line.Parent = _edgeGui end function Edge:Render(parent) if not self.line then self:CreateLine() end local vert1,vert2 = self.vertices[1],self.vertices[2] if vert1 and vert2 then local pos1,pos2 = vert1:GetPosition(),vert2:GetPosition() self.line.CFrame = CFrame.new((pos1+pos2)*.5,pos2) self.line.Height = (pos1-pos2).Magnitude self.line.Visible = true if parent then if not parent:FindFirstChild('Edges') then local _folder = Instance.new('Folder') _folder.Name = 'Edges' _folder.Parent = parent end self.line.Parent = parent['Edges'] end end end function Edge:FindEdgeBetweenVertices(vertice1,vertice2) if not vertice1 or not vertice2 then return end local edges = vertice1:GetEdges() for i,edge in ipairs(vertice2:GetEdges()) do if table.find(edges,edge) then return edge end end end function Edge:AddVertice(vertice) if not vertice then return end table.insert(self.vertices, vertice) end function Edge:AddVertices(vertices) if not vertices then return end for i,vertice in ipairs(vertices) do self:AddVertice(vertice) end end function Edge:GetVertices() return self.vertiecs end function Edge:AddFace(face) if not face then return end table.insert(self.faces, face) end function Edge:AddFaces(faces) if not faces then return end for i,face in ipairs(faces) do self:AddFace(face) end end function Edge:GetFaces() return self.faces end return Edge
#!/usr/bin/env tjost --[[ * Copyright (c) 2015 Hanspeter Portner (dev@open-music-kontrollers.ch) * * This is free software: you can redistribute it and/or modify * it under the terms of the Artistic License 2.0 as published by * The Perl Foundation. * * This source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Artistic License 2.0 for more details. * * You should have received a copy of the Artistic License 2.0 * along the source as a COPYING file. If not, obtain it from * http://www.perlfoundation.org/artistic_license_2_0. --]] id = require('id') message = tjost.plugin({name='dump'}) methods = { ['/set'] = tjost.plugin({name='write', path='stat_vel.osc'}) } stream = tjost.plugin({name='net_in', uri='osc.udp://:3333', rtprio=60, unroll='full'}, function(time, path, ...) local meth = methods[path] if meth then meth(time, path, ...) end end) chim = tjost.plugin({name='net_out', uri='osc.udp://chimaera.local:4444'}, function(time, path, fmt, ...) if path == '/stream/resolve' then chim(0, '/engines/dummy/enabled', 'ii', id(), 1) chim(0, '/engines/dummy/redundancy', 'ii', id(), 0) chim(0, '/engines/dummy/derivatives', 'ii', id(), 1) local hostname = tjost.hostname() chim(0, '/engines/address', 'is', id(), hostname..'.local:3333') end end) tjost.chain(chim, message)
local Director = class('Director', Person) function Director:initialize() Sim.Person.initialize(self) while self.age < 15 do Sim.Person.initialize(self) end self.movies = {} self.stats = { Popularity = math.random(), } end return Director
-- status listener -- TODO: currently is just the reactor status listener, but this will be modified to be more general local REACTOR_STATUS_PROTOCOL = "Lupus590:extremeReactors/status" peripheral.find("modem", function(side) rednet.open(side) end) local statusMessageBackgroundToggle = true term.setCursorPos(1,1) term.clear() term.setCursorPos(1,2) local function drawClockBar() local x, y = term.getCursorPos() term.setCursorPos(1,1) term.setBackgroundColour(colours.white) term.setTextColour(colours.black) term.clearLine() term.setCursorPos(1,1) term.write(textutils.formatTime(os.time("local"))) term.setCursorPos(x, y) term.setTextColour(colours.white) end local function clockPrinter() while true do drawClockBar() sleep(15) end end local function formatMessage(message) return textutils.formatTime(os.time("local"))..": "..message.reactorName..": "..message.status end local function messagePrinter() -- TODO: use cc.strings while true do local _, message, protocol = rednet.receive(REACTOR_STATUS_PROTOCOL, 10000000) if type(message) == "table" then if message.usePrintError then printError(formatMessage(message)) else print(formatMessage(message)) end drawClockBar() if statusMessageBackgroundToggle then term.setBackgroundColour(colours.black) else term.setBackgroundColour(colours.grey) end statusMessageBackgroundToggle = not statusMessageBackgroundToggle end end end parallel.waitForAny(messagePrinter, clockPrinter)
if SERVER then return end local halos = {} local haloCount = 0 local haloFrame = 0 local haloRT, haloMat local localAng = Angle(0,-90,-90) local haloAdd_orig timer.Simple(0,function() haloAdd_orig = halo.Add end) hook.Add("VRMod_Start","halos",function(ply) if ply ~= LocalPlayer() then return end halo.Add = function(ents, color, blurX, blurY, passes, additive, ignoreZ) if FrameNumber() ~= haloFrame then if FrameNumber() > haloFrame + 1 then --LocalPlayer():ChatPrint("installed halo hook") hook.Add("PostDrawTranslucentRenderables","vrmod_halos",function(depth, sky) if not haloRT then haloRT = GetRenderTarget("3dhalos"..tostring(math.floor(SysTime())), g_VR.view.w, g_VR.view.h, false) haloMat = CreateMaterial("3dhalos"..tostring(math.floor(SysTime())), "UnlitGeneric",{ ["$basetexture"] = haloRT:GetName() }) end if depth or sky or EyePos() ~= g_VR.view.origin then return end if FrameNumber() > haloFrame+1 then haloCount = 0 hook.Remove("PostDrawTranslucentRenderables","vrmod_halos") --LocalPlayer():ChatPrint("removed halo hook") end -- render.PushRenderTarget(haloRT) render.Clear(0,0,0,255, true, true) render.SetStencilEnable( true ) render.SetStencilWriteMask( 0xFF ) render.SetStencilTestMask( 0xFF ) render.SetStencilPassOperation( STENCIL_REPLACE ) render.SetStencilFailOperation( STENCIL_KEEP ) render.SetStencilZFailOperation( STENCIL_KEEP ) render.SetStencilReferenceValue( 1 ) for i = 1,haloCount do for k,v in pairs(halos[i].ents) do if IsValid(v) then render.ClearStencil() render.SetStencilPassOperation( STENCIL_REPLACE ) render.SetStencilCompareFunction( STENCIL_ALWAYS ) v:DrawModel() render.SetStencilPassOperation( STENCIL_KEEP ) render.SetStencilCompareFunction( STENCIL_EQUAL ) local col = halos[i].color render.ClearBuffersObeyStencil( col.r, col.g, col.b, 255, false ) end end end render.SetStencilEnable( false ) render.BlurRenderTarget(haloRT, 2,2, 1) render.SetStencilEnable( true ) render.ClearBuffersObeyStencil( 0, 0, 0, 255, false ) render.SetStencilEnable( false ) render.PopRenderTarget() local w = 10*math.tan(math.rad(g_VR.view.fov/2)) local h = w*(1/g_VR.view.aspectratio) local pos = EyePos() + EyeAngles():Forward()*10 + EyeAngles():Right()*-w + EyeAngles():Up()*h local _,ang = LocalToWorld(Vector(0,0,0), localAng, Vector(0,0,0), EyeAngles()) local mtx = Matrix() mtx:Translate(pos) mtx:Rotate(ang) mtx:Scale(Vector(w*2,h*2,0)) cam.PushModelMatrix(mtx) surface.SetDrawColor(255,255,255,255) surface.SetMaterial(haloMat) render.OverrideBlend(true, BLEND_ONE, BLEND_ONE, BLENDFUNC_ADD, 0, 0, 0) render.OverrideDepthEnable(true,false) surface.DrawTexturedRect(0,0,1,1) surface.DrawTexturedRect(0,0,1,1) render.OverrideDepthEnable(false) render.OverrideBlend(false) cam.PopModelMatrix() -- end) end haloFrame = FrameNumber() haloCount = 0 end haloEnts = ents halos[haloCount+1] = {ents = ents, color = color} haloCount = haloCount + 1 end end) hook.Add("VRMod_Exit","halos",function(ply) if ply ~= LocalPlayer() then return end halo.Add = haloAdd_orig hook.Remove("PostDrawTranslucentRenderables","vrmod_halos") haloCount = 0 haloRT = nil end)
local Ans = select(2, ...); local Utils = Ans.Utils; local ListView = Ans.UI.ListView; local Crafting = Ans.Data.Crafting; local EventManager = Ans.EventManager; AnsDestroyPreviewFrameMixin = {}; local REF_CACHE = {}; local resultItems = {}; local waitingForInfo = {}; function AnsDestroyPreviewFrameMixin:ShowTip(f, link) if (not link) then return; end Utils.ShowTooltip(f, link, 1); end function AnsDestroyPreviewFrameMixin:Init() local this = self; self:SetScript("OnEnter", function() this:ShowTip(this, this.selected); end); self:SetScript("OnLeave", Utils.HideTooltip); self.listView = ListView:Acquire(self, {rowHeight = 16, childIndent = 0, template = "AnsDestroyPreviewRowTemplate", multiselect = false, usePushTexture = true}, nil, nil, nil, function(row, item) row:SetScript("OnEnter", function() this:ShowTip(row, item.link); end); row:SetScript("OnLeave", Utils.HideTooltip); if (not item.link) then local link = Utils.GetLink(item.name); if (not link) then local _,id = strsplit(":", item.name); waitingForInfo[tonumber(id)] = true; end item.link = link; end if (row.Text) then row.Text:SetText(item.link or item.name); end if (row.TextRight) then row.TextRight:SetText("x"..string.format("%0.3f", item.amount)); end end ); EventManager:On("GET_ITEM_INFO_RECEIVED", function(id) if (waitingForInfo[id]) then waitingForInfo[id] = nil; if (this:IsShown()) then this.listView:Refresh(); end end end) end function AnsDestroyPreviewFrameMixin:Set(link) wipe(resultItems); self.selected = nil; if (not link) then return; end self.selected = link; self.value = Crafting.DisenchantValue(link, 1, REF_CACHE); for k,v in pairs(REF_CACHE) do tinsert(resultItems, {name = k, amount = v, link = nil}); end self.listView.items = resultItems; self.listView:Refresh(); self.Text:SetText(link); local tex = select(10, GetItemInfo(link)); if (tex) then self.Icon:SetTexture(tex); end end
return { init_effect = "", name = "测试-随机技能-治疗之泉-治疗光环", time = 0, picture = "", desc = "治疗光环", stack = 1, id = 60045, icon = 60045, last_effect = "hongsebuff", effect_list = { { type = "BattleBuffField", trigger = { "onUpdate" }, arg_list = { buff_id = 60046, exceptCaster = true, target = "TargetAllHelp", max_distance = 20 } }, { type = "BattleBuffDeath", trigger = { "onUpdate" }, arg_list = { time = 10 } }, { type = "BattleBuffAddAttr", trigger = { "onAttach", "onRemove" }, arg_list = { group = 104, attr = "isSpirit", number = 1 } } } }
-- Abstract UI ReplicatedPseudoInstance -- @author Validark local Players = game:GetService("Players") local Lighting = game:GetService("Lighting") local RunService = game:GetService("RunService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local Resources = require(ReplicatedStorage:WaitForChild("Resources")) local Color = Resources:LoadLibrary("Color") local Debug = Resources:LoadLibrary("Debug") local Tween = Resources:LoadLibrary("Tween") local Typer = Resources:LoadLibrary("Typer") local Enumeration = Resources:LoadLibrary("Enumeration") local PseudoInstance = Resources:LoadLibrary("PseudoInstance") local ReplicatedPseudoInstance = Resources:LoadLibrary("ReplicatedPseudoInstance") local InBack = Enumeration.EasingFunction.InBack.Value local OutBack = Enumeration.EasingFunction.OutBack.Value local LocalPlayer, PlayerGui do if RunService:IsClient() then if RunService:IsServer() then PlayerGui = game:GetService("CoreGui") else repeat LocalPlayer = Players.LocalPlayer until LocalPlayer or not wait() repeat PlayerGui = LocalPlayer:FindFirstChildOfClass("PlayerGui") until PlayerGui or not wait() end end end local Screen = Instance.new("ScreenGui", PlayerGui) Screen.Name = "RoStrapPriorityUIs" Screen.DisplayOrder = 2^31 - 2 local DialogBlur = Instance.new("BlurEffect") DialogBlur.Size = 0 DialogBlur.Name = "RoStrapBlur" local function SetDialogBlurParentToNil() DialogBlur.Parent = nil end -- NOTE: Enter()s automatically when Parented return PseudoInstance:Register("RoStrapPriorityUI", { Storage = {}; Internals = { Blur = function(self) DialogBlur.Parent = Lighting Tween(DialogBlur, "Size", 56, OutBack, self.ENTER_TIME, true) end; Unblur = function(self) Tween(DialogBlur, "Size", 0, InBack, self.ENTER_TIME, true, SetDialogBlurParentToNil) end; DISMISS_TIME = 75 / 1000 * 2; ENTER_TIME = 150 / 1000 * 2; SCREEN = Screen; }; Events = { }; Methods = { Enter = 0; Dismiss = 0; Destroy = function(self) self:Dismiss() self:super("Destroy") end; }; Properties = { Parent = function(self, Parent) if Parent and PlayerGui then self:Enter() if self.SHOULD_BLUR then self:Blur() end end self:rawset("Parent", Parent) end; Dismissed = Typer.Boolean; }; Init = function(self, ...) self:superinit(...) end; }, ReplicatedPseudoInstance)
local present, toggleterm = pcall(require, "toggleterm") if not present then return end toggleterm.setup({ -- size can be a number or function which is passed the current terminal size = function(term) if term.direction == "horizontal" then return 15 elseif term.direction == "vertical" then return vim.o.columns * 0.4 end end, -- open_mapping = [[<C-\>]], -- mapping set in mappings.lua hide_numbers = true, -- hide the number column in toggleterm buffers shade_terminals = false, start_in_insert = true, -- insert_mappings = true, -- see 'open_mapping', not set on purpose -- whether or not the open mapping applies in insert mode persist_size = true, direction = "vertical", close_on_exit = true, -- close the terminal window when the process exits -- This field is only relevant if direction is set to 'float' float_opts = { border = "single", winblend = 0, highlights = { border = "Normal", background = "Normal", }, }, }) local Terminal = require("toggleterm.terminal").Terminal -- _G.termW = Terminal:new({ -- direction = "window", -- }) -- _G.termV = Terminal:new({ -- direction = "vertical", -- }) -- _G.termH = Terminal:new({ -- direction = "horizontal", -- }) _G.termGit = Terminal:new({ cmd = "lazygit", dir = "git_dir", direction = "float", float_opts = { border = "double", }, -- function to run on opening the terminal on_open = function(term) vim.cmd("startinsert!") vim.api.nvim_buf_set_keymap(term.bufnr, "n", "q", "<cmd>close<CR>", { noremap = true, silent = true }) end, -- function to run on closing the terminal on_close = function(term) vim.cmd("Closing terminal") end, })
VEHICLE = {}; VEHICLE.ID = '%'; /* VEHICLE.Name = "Tow Truck"; VEHICLE.Make = "International"; VEHICLE.Model = "2674"; VEHICLE.Script = "international_2674"; */ VEHICLE.Name = "Tow Truck"; VEHICLE.Make = ""; VEHICLE.Model = ""; VEHICLE.Script = "towtruck"; VEHICLE.Cost = 0; VEHICLE.PaintJobCost = 0; VEHICLE.DF = false; VEHICLE.CustomBodyGroup = nil; VEHICLE.PaintJobs = { --{model = 'models/sickness/zil.mdl', skin = '0', name = '', color = Color(0, 0, 0, 255)}, {model = 'models/sickness/towtruckdr.mdl', skin = '0', name = '', color = Color(0, 0, 0, 255)}, }; VEHICLE.PassengerSeats = { {Vector(17, -25, 50), Angle(0, 0, 0)}, }; VEHICLE.ExitPoints = { Vector(-75.2014, 37.7570, 3.5399), Vector(75.2014, 37.7570, 3.5399), }; VEHICLE.DefaultIceFriction = .5; VEHICLE.PlayerReposition_Pos = nil; VEHICLE.PlayerReposition_Ang = nil; VEHICLE.ViewAdjustments_FirstPerson = nil; VEHICLE.ViewAdjustments_ThirdPerson = nil; VEHICLE.RequiredClass = TEAM_ROADCREW; VEHICLE.PaintText = ""; VEHICLE.HornNoise = "PERP2.5/firetruck_horn.mp3"; VEHICLE.HeadlightPositions = { {Vector(-36, 107, 45.748199462891), Angle(5, 0, 0)}, {Vector(36, 107, 45), Angle(5, 0, 0)}, }; VEHICLE.TaillightPositions = { {Vector(-38, -112, 42), Angle(5, -180, 0)}, {Vector(38, -112, 42), Angle(5, -180, 0)}, }; VEHICLE.UnderglowPositions = { }; VEHICLE.RevvingSound = nil; VEHICLE.SpinoutSound = nil; VEHICLE.SirenNoise = Sound("PERP2.5/siren_long.mp3"); VEHICLE.SirenNoise_Alt = nil; VEHICLE.SirenColors = { {Color(180, 150, 0, 255), Vector(15.5842, 59.6891, 104.7181)}, {Color(220, 250, 0, 255), Vector(-15.5842, 59.6891, 104.7181)}, }; GM:RegisterVehicle(VEHICLE);
modifier_item_forest_ring_int = class({}) -------------------------------------------------------------------------------- function modifier_item_forest_ring_int:IsHidden() return true end -------------------------------------------------------------------------------- function modifier_item_forest_ring_int:IsPurgable() return false end -------------------------------------------------------------------------------- function modifier_item_forest_ring_int:OnCreated( kv ) self.bonus_mana_regen = self:GetAbility():GetSpecialValueFor( "bonus_mana_regen" ) self.bonus_intelligence = self:GetAbility():GetSpecialValueFor( "bonus_intelligence" ) self.bonus_mana= self:GetAbility():GetSpecialValueFor( "bonus_mana" ) self.bonus_hp_regen= self:GetAbility():GetSpecialValueFor( "bonus_hp_regen" ) end -------------------------------------------------------------------------------- function modifier_item_forest_ring_int:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_MANA_REGEN_CONSTANT, MODIFIER_PROPERTY_MANA_BONUS, MODIFIER_PROPERTY_STATS_INTELLECT_BONUS, MODIFIER_PROPERTY_HEALTH_REGEN_CONSTANT, } return funcs end -------------------------------------------------------------------------------- function modifier_item_forest_ring_int:GetModifierConstantManaRegen( params ) return self.bonus_mana_regen end function modifier_item_forest_ring_int:GetModifierManaBonus( params ) return self.bonus_mana end function modifier_item_forest_ring_int:GetModifierConstantHealthRegen( params ) return self.bonus_hp_regen end function modifier_item_forest_ring_int:GetModifierBonusStats_Intellect( params ) return self.bonus_intelligence end
borderColor = 100 function setup() -- Initialize random math.randomseed(os.time()) -- setup game game = {} game["boundryTop"] = createDefault(512, 0, 1024, 3, borderColor, borderColor, borderColor, 255) game["boundryLeft"] = createDefault(0, 384, 3, 768, borderColor, borderColor, borderColor, 255) game["boundryBottom"] = createDefault(512, 765, 1024, 3, borderColor, borderColor, borderColor, 255) game["boundryRight"] = createDefault(1024, 0, 3, 768, borderColor, borderColor, borderColor, 255) game["enemies"] = {} for index=1, 6 do table.insert(game["enemies"], createDefault(100 * index, 100, 50, 50, 0, 255, 0, 255)) end game["playerBullets"] = {} game["enemyBullets"] = {} game["playerId"] = createDefault(450, 600, 50, 50, 255, 255, 255, 255) end function onKeyDown(keyId) local playerId = game["playerId"] if SDLK_RIGHT == keyId then addVelocity(playerId, 1.0, 0.0) setSpeed(playerId, 200.0) elseif SDLK_LEFT == keyId then addVelocity(playerId, -1.0, 0.0) setSpeed(playerId, 200.0) elseif SDLK_SPACE == keyId then local position = getPosition(game["playerId"]) local x = position:getX() local bulletId = createDefault(x, 500, 20, 20, 125, 0, 0, 255) table.insert(game["playerBullets"], bulletId) addVelocity(bulletId, 0.0, -1.0) setSpeed(bulletId, 350.0) end end function onKeyUp(keyId) local playerId = game["playerId"] if SDLK_RIGHT == keyId then addVelocity(playerId, -1.0, 0.0) setSpeed(playerId, 200.0) elseif SDLK_LEFT == keyId then addVelocity(playerId, 1.0, 0.0) setSpeed(playerId, 200.0) end end function isEnemy(id) local enemies = game["enemies"] for index = 1, #enemies do if enemies[index] == id then return true end end return false end function onCollision(collidedId, colliderId) -- Check for bullet local playerBullets = game["playerBullets"] for index = 1, #playerBullets do if playerBullets[index] == colliderId then destroyEntity(playerBullets[index]) table.remove(playerBullets, index) break end end local enemyBullets = game["enemyBullets"] for index = 1, #enemyBullets do if enemyBullets[index] == colliderId then destroyEntity(enemyBullets[index]) table.remove(enemyBullets, index) break end end -- Check enemies local enemies = game["enemies"] for index = 1, #enemies do if enemies[index] == collidedId then destroyEntity(enemies[index]) table.remove(enemies, index) break end end end function update(delta) if #game["enemyBullets"] < 5 then local randomEnemy = math.random(#game["enemies"]) local position = getPosition(randomEnemy) local bulletId = createDefault(position:getX(), 150, 20, 20, 0, 127, 0, 255) table.insert(game["enemyBullets"], bulletId) addVelocity(bulletId, 0.0, 1.0) setSpeed(bulletId, 350.0) end end
-- Dependencies local Assets = require("engine.Assets") local Config = require("engine.Config") local Log = require("engine.Log") local Table = require("engine.Table") local Object = require("game.objects.Object") local Mapping = require("game.Mapping") local Level = require("game.Level") -- Room module local Room = {} -- Variables local level = nil -- Level data local drawX = 0 -- X coordinate of room area local drawY = 0 -- Y coordinate of room area local width = 0 -- Width of room area local height = 0 -- Height of room area local walls = {} -- Walls local objects = {} -- Objects local timeouts = {} -- Timeouts local particles = {} -- Particles local error = nil -- Error message local message = nil -- Room message local sprites = Assets.sprites.background -- Background sprites local batch = sprites:createBatch(300) -- Batch for drawing background -- Initializes walls local function initWalls() walls = {} for i = 1, level:getHeight() do walls[i] = {} for j = 1, level:getWidth() do walls[i][j] = level:getData(j, i) == Mapping.getWall() end end end -- Initializes objects local function initObjects() objects = {} timeouts = {} particles = {} for i = 1, level:getHeight() do for j = 1, level:getWidth() do local x = 16 * (j - 1) local y = 16 * (i - 1) local character = level:getData(j, i) local object = Mapping.createObject(character, x, y) if object then table.insert(objects, object) end end end end -- Initializes attributes local function initAttributes() width = level:getWidth() * 16 height = level:getHeight() * 16 drawX = (Config.gameWidth - width) / 2 drawY = (Config.gameHeight - height) / 2 message = level.message end -- Initializes state local function initState() Room.diamondsCount = 0 -- Number of diamonds in room Room.keyObtained = false -- Is key obtained? -- Number of activated switches for each group Room.activatedSwitches = { white = 0, red = 0, blue = 0 } end -- Initializes batch for drawing background local function initBatch() batch:clear() for i = 1, level:getHeight() do for j = 1, level:getWidth() do local sprite = level:getBackgroundSprite(j, i) if sprite then local x = (j - 1) * 16 local y = (i - 1) * 16 sprite:addToBatch(batch, x, y) end end end end -- Creates room by loading specified level function Room.create(source) if type(source) == "string" then Log.info("Loading level '%s'", source) level, error = Level(source) else Log.info("Starting level") level = Table.copy(source) error = level:validate() end if error then Log.error("Corrupted level: %s", error) else level:normalize() initWalls() initAttributes() initBatch() Room.restart() end end -- Restarts room function Room.restart() initState() initObjects() end -- Stores room data to memento function Room.persist(memento) memento.roomObjects = objects memento.diamondsCount = Room.diamondsCount memento.keyObtained = Room.keyObtained memento.activatedSwitches = Room.activatedSwitches end -- Restores room data from memento function Room.restore(memento) objects = memento.roomObjects timeouts = {} particles = {} Room.diamondsCount = memento.diamondsCount Room.keyObtained = memento.keyObtained Room.activatedSwitches = memento.activatedSwitches -- Restore objects for i, object in ipairs(objects) do if object.restored then object:restored() end end end -- Adds timeout to draw function Room.drawTimeout(time, x, y) timeouts[#timeouts + 1] = { x = x, y = y, time = time } end -- Adds particles to draw function Room.drawParticles(data, x, y, time) particles[#particles + 1] = { x = x, y = y, data = data, time = time or 0 } end -- Draws message local function drawMessage(message, border, r, g, b, a) love.graphics.setColor(r, g, b, a or 255) love.graphics.rectangle("fill", 0, 0, Config.gameWidth, Config.gameHeight) love.graphics.setColor(255, 255, 255) love.graphics.printf(message, border, border, Config.gameWidth - 2 * border) end -- Draws room function Room.draw() -- Draw error message if error then drawMessage(error, 32, 255, 0, 0) return end -- Draw background love.graphics.push() love.graphics.translate(drawX, drawY) love.graphics.draw(batch, 0, 0) -- Draw objects for i, object in ipairs(objects) do object:draw() end -- Draw timeouts love.graphics.setFont(Assets.fonts.tiny) for i, item in ipairs(timeouts) do local total = item.time + 1 local value = math.floor(total) local ratio = total - value love.graphics.setColor(255, 255, 255, 255 * ratio) love.graphics.print(tostring(value), item.x, item.y - 8 * (1 - ratio)) end love.graphics.setFont(Assets.fonts.normal) love.graphics.setColor(255, 255, 255) -- Draw particles for i, item in ipairs(particles) do love.graphics.draw(item.data, item.x, item.y) end -- Restore graphics state love.graphics.pop() -- Draw text message if message then drawMessage(message, 48, 0, 0, 0, 196) end end -- Updates room function Room.update(delta) -- Waiting for confirmation if error or message then return end -- Remove destroyed objects Table.filter(objects, function(i, object) return object.destroyed end) -- Update objects (remove object immediately when it destroys itself) Table.filter(objects, function(i, object) object:update(delta) return object.destroyed end) -- Sort objects for drawing table.sort(objects, Object.compare) -- Clear all timeouts timeouts = {} -- Clear finished particles Table.filter(particles, function(i, item) item.data:update(delta) item.time = item.time - delta return item.time <= 0 end) end -- Check if error is displayed function Room.isError() return error ~= nil end -- Checks if message is displayed function Room.isMessage() return message ~= nil end -- Checks if room is started function Room.isStarted() return not error and not message end -- Skips message function Room.skipMessage() message = nil end -- Adds object to room function Room.addObject(object) table.insert(objects, object); end -- Returns iterator over all objects except the specified one function Room.getObjectsIterator(currentObject) local i = 0 return function() local object repeat i = i + 1 object = objects[i] until object ~= currentObject return object end end -- Checks if the specified area contains solid objects local function isSolid(x1, y1, x2, y2) -- Room border collision test if (x1 < 0) or (y1 < 0) or (x2 >= width) or (y2 >= height) then return true end -- Wall collision test local j1 = math.floor(x1 / 16) + 1 local j2 = math.floor(x2 / 16) + 1 local i1 = math.floor(y1 / 16) + 1 local i2 = math.floor(y2 / 16) + 1 return walls[i1][j1] or walls[i1][j2] or walls[i2][j1] or walls[i2][j2] end -- Checks if an object collides with the environment or another object function Room.isCollision(target, border, dx, dy, checkPlaceholders) local x1, y1, x2, y2 = target:getBounds(border, dx, dy) -- Environment collision test if isSolid(x1, y1, x2, y2) then return true end -- Objects collision test for i, object in ipairs(objects) do if object ~= target and object:collideWith(target) then -- Placeholder collision test if checkPlaceholders and object.moving and object.placeholder:intersectsArea(x1, y1, x2, y2, space) then return true end -- Object collision test if object:intersectsArea(x1, y1, x2, y2, space) then return true end end end return false end -- Checks if an object can move to the specified location function Room.canMove(target, dx, dy) return not Room.isCollision(target, 1) and -- Current location not Room.isCollision(target, 1, dx, dy, true) -- Target location end -- Checks if an object can move to the specified location when pushing other objects function Room.canPush(target, dx, dy, power, pushedObjects) -- Check if the target can be pushed and does not collide with anything if not target.weight or Room.isCollision(target, 1) then return false end -- Check if the target has enough power to push other objects local weight = pushedObjects.weight + target.weight if power < weight then return false end -- Environment collision test local x1, y1, x2, y2 = target:getBounds(1, dx, dy) if isSolid(x1, y1, x2, y2) then return false end -- Update pushed objects pushedObjects[target] = true pushedObjects.weight = weight -- Objects collision test for i, object in ipairs(objects) do if not pushedObjects[object] and object:collideWith(target) then -- Placeholder collision test if object.moving and object.placeholder:intersectsArea(x1, y1, x2, y2, space) then return false end -- Object collision test if object:intersectsArea(x1, y1, x2, y2, space) then -- Give the object same direction as the target (in case it has this attribute) -- Needed for correct functioning of Arrow objects if object.direction then object.direction = target.direction end -- Try to push the object if not Room.canPush(object, dx, dy, power, pushedObjects) then return false end end end end return true end return Room
-- Copyright (c) 2011-2014 Rob Hoelz <rob@hoelz.ro> -- -- 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. local getmetatable = getmetatable local pairs = pairs local sfind = string.find local sgmatch = string.gmatch local smatch = string.match local ssub = string.sub local tconcat = table.concat local tsort = table.sort local type = type local function isindexable(value) if type(value) == 'table' then return true end local mt = getmetatable(value) return mt and mt.__index end local function getcompletions(t) local union = {} while isindexable(t) do if type(t) == 'table' then -- XXX what about the pairs metamethod in 5.2? -- either we don't care, we implement a __pairs-friendly -- pairs for 5.1, or implement a 'rawpairs' for 5.2 for k, v in pairs(t) do if union[k] == nil then union[k] = v end end end local mt = getmetatable(t) t = mt and mt.__index or nil end return pairs(union) end local function split_ns(expr) if expr == '' then return { '' } end local pieces = {} -- XXX method calls too (option?) for m in sgmatch(expr, '[^.]+') do pieces[#pieces + 1] = m end -- logic for determining whether to pad the matches with the empty -- string (ugly) if ssub(expr, -1) == '.' then pieces[#pieces + 1] = '' end return pieces end local function determine_ns(expr) local ns = _G -- XXX what if the REPL lives in a special context? (option?) local pieces = split_ns(expr) for index = 1, #pieces - 1 do local key = pieces[index] -- XXX rawget? or regular access? (option?) ns = ns[key] if not isindexable(ns) then return {}, '', '' end end expr = pieces[#pieces] local prefix = '' if #pieces > 1 then prefix = tconcat(pieces, '.', 1, #pieces - 1) .. '.' end local last_piece = pieces[#pieces] local before, after = smatch(last_piece, '(.*):(.*)') if before then ns = ns[before] -- XXX rawget prefix = prefix .. before .. ':' expr = after end return ns, prefix, expr end local isidentifierchar do local ident_chars_set = {} -- XXX I think this can be done with isalpha in C... local ident_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.:_0123456789' for i = 1, #ident_chars do local char = ssub(ident_chars, i, i) ident_chars_set[char] = true end function isidentifierchar(char) return ident_chars_set[char] end end local function extract_innermost_expr(expr) local index = #expr while index > 0 do local char = ssub(expr, index, index) if isidentifierchar(char) then index = index - 1 else break end end index = index + 1 return ssub(expr, 1, index - 1), ssub(expr, index) end -- XXX is this logic (namely, returning the entire line) too specific to -- linenoise? function repl:complete(expr, callback) local ns, prefix, path prefix, expr = extract_innermost_expr(expr) ns, path, expr = determine_ns(expr) prefix = prefix .. path local completions = {} for k, v in getcompletions(ns) do if sfind(k, expr, 1, true) == 1 then local suffix = '' local type = type(v) -- XXX this should be optional if type == 'function' then suffix = '(' elseif type == 'table' then suffix = '.' end completions[#completions + 1] = prefix .. k .. suffix end end tsort(completions) for _, completion in ipairs(completions) do callback(completion) end end features = 'completion'
-- References -- https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute -- local colors = require("svgcreate.colors") local RGB = colors.RGBA; local maths = require("svgcreate.maths") local clamp = maths.clamp; local bit = require("bit") local lshift, rshift, band, bor = bit.lshift, bit.rshift, bit.band, bit.bor local tonumber = tonumber; local tostring = tostring; -- Individual functions which deal with specific -- attributes local attrs = {} -- This is the function to be used when we don't have -- any specific specialization for an attribute function default(name, value, strict) --print("{name = '', parser = default}: ", name, value); return name, value end -- These functions convert from SVG Attribute string values -- to lua specific types local function color(name, value, strict) local function parseColorName(name) return colors.svg[name] or RGB(128, 128, 128); end local function parseColorHex(s) --print(".parseColorHex: ", s) local rgb = s:match("#(%x+)") --print("rgb: ", rgb) local r,g,b = 0,0,0; local c = 0; --rgb = "0x"..rgb; if #rgb == 6 then c = tonumber("0x"..rgb) elseif #rgb == 3 then c = tonumber("0x"..rgb); c = bor(band(c,0xf), lshift(band(c,0xf0), 4), lshift(band(c,0xf00), 8)); c = bor(c, lshift(c,4)); end b = band(rshift(c, 16), 0xff); g = band(rshift(c, 8), 0xff); r = band(c, 0xff); return RGB(r,g,b); end local function parseColorRGB(str) -- if numberpatt uses %x instead of %d, then do the following -- to get past the 'b' in 'rgb(' --local loc = str:find("%(") --str = str:sub(loc+1,#str) local numberpatt = "(%d+)" local usePercent = str:find("%%") --print("parseColorRGB: ", str, usePercent) local tbl = {} for num in str:gmatch(numberpatt) do if usePercent then table.insert(tbl, tonumber(num)*255/100) else table.insert(tbl, tonumber(num)) end end return RGB(tbl[1], tbl[2], tbl[3]) end local str = value:match("%s*(.*)") local len = #str; --print("parseColor: ", str) if len >= 1 and str:sub(1,1) == '#' then value = parseColorHex(str); elseif (len >= 4 and str:match("rgb%(")) then value = parseColorRGB(str); else value = parseColorName(str); end local r, g, b, a = colors.colorComponents(value) --print("COLOR: ", r,g,b,a) local obj = {r=r, g = g, b = b, a = a}; setmetatable(obj, { __tostring = function(self) return string.format("rgb(%d, %d, %d)", self.r, self.g, self.b) end }) return name, obj end local paint = color; local function coord(name, value, strict) --print("coord: ", name, value) if type(value) ~= "string" then return name, value; end local num, units = value:match("([+-]?%d*%.?%d*)(%g*)") --print("coord: ", name, value, num, units) if not num then return nil; end local obj = {value = tonumber(num), units = units} setmetatable(obj,{ __tostring = function(self) --print("coord.tostring: ", self.value, self.units) return string.format("%f%s",self.value, self.units or "") end, }) return name, obj; end -- The specification for length is the same as for -- coordinates local length = coord local function number(name, value, strict) if type(value) ~= "string" then return name, value; end return name, tonumber(value) end -- strictly, the SVG spec say opacity is simply -- a number between 0..1 -- but, we'll allow specifying a '%' value as well... function numberorpercent(name, value, strict) if type(value) ~= "string" then return name, value; end local usePercent = value:find("%%") local num = 1.0 tonumber(value) if usePercent then local str = value:match("(%d+)") num = tonumber(str) / 100; else num = tonumber(value); end local val = clamp(tonumber(value), 0, 1); return name, val; end local offset = opacity; local opacity = numberorpercent; local function parseStyle(name, value, strict) local tbl = {} for item in value:gmatch("([^;]+)") do local name, value = item:match("(%g+):(%g+)") --print("item:match: ", name, value) name, value = attrs.parseAttribute(name, value, strict) --print("parse result: ", name, value) tbl[name] = value; end setmetatable(tbl, { __tostring = function(self) local res = {} for name, value in pairs(self) do table.insert(res, string.format("%s:%s", name, tostring(value))) end return table.concat(res,';') end, }) return name, tbl end local function parseviewBox(name, value, strict) if type(value) ~= "string" then return name, value end local numpatt = "(%d*%.?%d*)" local nums = {} for num in value:gmatch(numpatt) do --print("NUM: ", num, type(num)) if num ~= "" then table.insert(nums, tonumber(num)) end end local obj = { min_x = nums[1], min_y = nums[2], width = nums[3], height= nums[4] } setmetatable(obj, { __tostring = function(self) return string.format("%f %f %f %f", self.min_x, self.min_y, self.width, self.height); end, }) return name, obj; end --[[ Entries for parsers per attribute --]] attrs.accent_height = {name = 'accent-height', parser = number}; attrs.accumulate = {name = 'accumulate', pardser = default}; -- 'none' | 'sum' attrs.additive = {name = 'additive', parser = default}; -- 'replace' | 'sum' attrs.alignment_baseline = {name = 'alignment-baseline', parser = default}; attrs.allowReorder = {name = 'allowReorder', parser = default}; attrs.alphabetic = {name = 'alphabetic', parser = number}; attrs.amplitude = {name = 'amplitude', parser = default}; attrs.arabic_form = {name = 'arabic-form', parser = default}; attrs.ascent = {name = 'ascent', parser = number}; attrs.attributeName = {name = 'attributeName', parser = default}; attrs.attributeType = {name = 'attributeType', parser = default}; attrs.autoReverse = {name = 'autoReverse', parser = default}; attrs.azimuth = {name = 'azimuth', parser = default}; attrs.baseFrequency = {name = 'baseFrequency', parser = default}; attrs.baseline_shift = {name = 'baseline-shift', parser = default}; attrs.baseProfile = {name = 'baseProfile', parser = default}; attrs.bbox = {name = 'bbox', parser = default}; attrs.begin = {name = 'begin', parser = default}; attrs.bias = {name = 'bias', parser = default}; attrs.by = {name = 'by', parser = default}; attrs.calcMode = {name = 'calcMode', parser = default}; attrs.cap_height = {name = 'cap-height', parser = number}; attrs['cap-height'] = attrs.cap_height; attrs.class = {name = 'class', parser = default}; attrs.clip = {name = 'clip', parser = default}; attrs.clipPathUnits = {name = 'clipPathUnits', parser = default}; attrs.clip_path = {name = 'clip-path', parser = default}; attrs.clip_rule = {name = 'clip-rule', parser = default}; attrs.color = {name = 'color', parser = color}; attrs.color_interpolation = {name = 'color-interpolation', parser = default}; attrs.color_interpolation_filters = {name = 'color-interpolation-filters', parser = default}; attrs.color_profile = {name = 'profile', parser = default}; attrs.color_rendering = {name = 'color-rendering', parser = default}; attrs.contentScriptType = {name = 'contentScriptType', parser = default}; attrs.contentStyleType = {name = 'contentStyleType', parser = default}; attrs.cursor = {name = 'cursor', parser = default}; attrs.cx = {name='cx', parser = coord}; attrs.cy = {name = 'cy', parser = coord}; attrs.d = {name = 'd', parser = default}; attrs.decelerate = {name = 'decelerate', parser = default}; attrs.descent = {name = 'descent', parser = number}; attrs.diffuseConstant = {name = 'diffuseConstant', parser = default}; attrs.direction = {name = 'direction', parser = default}; attrs.display = {name = 'display', parser = default}; attrs.divisor = {name = 'divisor', parser = default}; attrs.dominant_baseline = {name = 'dominant-baseline', parser = default}; attrs.dur = {name = 'dur', parser = default}; attrs.dx = {name='dx', parser = number}; attrs.dy = {name = 'dy', parser = number}; attrs.edgeMode = {name = 'edgeMode', parser = default}; attrs.elevation = {name = 'elevation', parser = default}; attrs.enable_background = {name = 'enable-background', parser = default}; attrs['enable-background'] = attrs.enable_background; attrs['end'] = {name = 'end', parser = default}; attrs.exponent = {name = 'exponent', parser = default}; attrs.externalResourcesRequired = {name = 'externalResourcesRequired', parser = default}; attrs.fill = {name='fill', parser = paint}; attrs.fill_opacity = {name = 'fill-opacity', parser = opacity}; attrs['fill-opacity'] = attrs.fill_opacity; attrs.fill_rule = {name = 'fill-rule', parser = default}; attrs['fill-rule'] = attrs.fill_rule; attrs.filter = {name = 'filter', parser = default}; attrs.filterRes = {name = 'filterRes', parser = default}; attrs.filterUnits = {name = 'filterUnits', parser = default}; attrs.flood_color = {name='flood-color', parser =color}; attrs['flood-color'] = attrs.flood_color; attrs.flood_opacity = {name = 'flood-opacity', parser = opacity}; attrs.font_family = {name = 'font-family', parser = default}; attrs.font_size = {name = 'font-size', parser = default}; attrs['font-size'] = attrs.font_size; attrs.font_size_adjust = {name = 'font-size-adjust', parser = default}; attrs.font_stretch = {name = 'font-stretch', parser = default}; attrs.font_style = {name = 'font-style', parser = default}; attrs.font_variant = {name = 'font-variant', parser = default}; attrs.font_weight = {name = 'font-weight', parser = default}; attrs.format = {name = 'format', parser = default}; attrs.from = {name = 'from', parser = default}; attrs.fx = {name='fx', parser=coord}; attrs.fy = {name='fy', parser=coord}; attrs.g1 = {name = 'g1', parser = default}; attrs.g2 = {name = 'g2', parser = default}; attrs.glyph_name = {name = 'glyph-name', parser = default}; attrs.glyph_orientation_horizontal = {name = 'glyph-orinentation-horizontal', parser = default}; attrs.glyph_orientation_vertical = {name = 'glyph-orientation-vertical', parser = default}; attrs.glyphRef = {name = 'glyphRef', parser = default}; attrs.gradientTransform = {name = 'gradientTransform', parser = default}; attrs.gradientUnits = {name = 'gradientUnits', parser = default}; attrs.hanging = {name ='hanging', parser=number}; attrs.height = {name = 'height', parser=length}; attrs.horiz_adv_x = {name = 'horiz-adv-x', parser = default}; attrs.horiz_origin_x = {name = 'horiz-origin-x', parser = default}; attrs['horiz-origin-x'] = attrs.horiz_origin_x; attrs.id = {name = 'id', parser = default}; attrs.ideographic = {name = 'ideographic', parser = default}; attrs.image_rendering = {name = 'image-rendering', parser = default}; attrs['in'] = {name = 'in', parser = default}; attrs.in2 = {name = 'in2', parser = default}; attrs.intercept = {name = 'intercept', parser = default}; attrs.k = {name = 'k', parser = number}; attrs.k1 = {name = 'k1', parser = number}; attrs.k2 = {name = 'k2', parser = number}; attrs.k3 = {name = 'k3', parser = number}; attrs.k4 = {name = 'k4', parser = number}; attrs.kernelMatrix = {name = 'kernelMatrix', parser = default}; attrs.kernelUnitLength = {name = 'kernelUnitLength', parser = default}; attrs.kerning = {name = 'kerning', parser = default}; attrs.keyPoints = {name = 'keyPoints', parser = default}; attrs.keySplines = {name = 'keySplines', parser = default}; attrs.keyTimes = {name = 'keyTimes', parser = default}; attrs.lang = {name = 'lang', parser = default}; attrs.lengthAdjust = {name = 'lengthAdjust', parser = default}; attrs.letter_spacing = {name = 'letter-spacing', parser = default}; attrs.lighting_color = {name = 'lighting-color', parser = color}; attrs['lighting-color'] = attrs.lighting_color; attrs.limitingConeAngle = {name = 'limitingConeAngle', parser = default}; attrs['local'] = {name = 'local', parser = default}; attrs.marker_end = {name = 'marker-end', parser = default}; attrs['marker-end'] = attrs.marker_end; attrs.marker_mid = {name = 'marker_mid', parser = default}; attrs['marker-mid'] = attrs.marker_mid; attrs.marker_start = {name = 'marker_start', parser = default}; attrs['marker-start'] = attrs.marker_start; attrs.markerHeight = {name = 'markerHeight', parser = default}; attrs.markerUnits = {name = 'markerUnits', parser = default}; attrs.markerWidth = {name = 'markerWidth', parser = default}; attrs.mask = {name = 'mask', parser = default}; attrs.maskContentUnits = {name = 'maskContentUnits', parser = default}; attrs.maskUnits = {name = 'maskUnits', parser = default}; attrs.mathematical = {name='mathematical', parser=number}; attrs.max = {name = 'max', parser = default}; attrs.media = {name = 'media', parser = default}; attrs.method = {name = 'method', parser = default}; attrs.min = {name = 'min', parser = default}; attrs.mode = {name = 'mode', parser = default}; attrs.name = {name = 'name', parser = default}; attrs.numOctaves = {name = 'numOctaves', parser = default}; attrs.offset = {name = 'offset', parser = numberorpercent}; attrs.onabort = {name = 'onabort', parser = default}; attrs.onactivate = {name = 'onactivate', parser = default}; attrs.onbegin = {name = 'onbegin', parser = default}; attrs.onclick = {name = 'onclick', parser = default}; attrs.onend = {name = 'onend', parser = default}; attrs.onerror = {name = 'onerror', parser = default}; attrs.onfocusin = {name = 'onfocusin', parser = default}; attrs.onfocusout = {name = 'onfocusout', parser = default}; attrs.onload = {name = 'onload', parser = default}; attrs.onmousedown = {name = 'onmousedown', parser = default}; attrs.onmousemove = {name = 'onmousemove', parser = default}; attrs.onmouseout = {name = 'onmouseout', parser = default}; attrs.onmouseover = {name = 'onmouseover', parser = default}; attrs.onmouseup = {name = 'onmouseup', parser = default}; attrs.onrepeat = {name = 'onrepeat', parser = default}; attrs.onresize = {name = 'onresize', parser = default}; attrs.onscroll = {name = 'onscroll', parser = default}; attrs.onunload = {name = 'onunload', parser = default}; attrs.onzoom = {name = 'onzoom', parser = default}; attrs.opacity = {name = 'opacity', parser = opacity}; attrs.operator = {name = 'operator', parser = default}; attrs.order = {name = 'order', parser = default}; attrs.orient = {name = 'orient', parser = default}; attrs.orientation = {name = 'orientation', parser = default}; attrs.origin = {name = 'origin', parser = default}; attrs.overflow = {name = 'overflow', parser = default}; attrs.overline_position = {name = 'overline-position', parser = number}; attrs['overline-position'] = attrs.overline_position; attrs.overline_thickness = {name = 'overline-thickness', parser = number}; attrs['overline-thickness'] = attrs.overline_thickness; attrs.panose_1 = {name = 'panose-1', parser = default}; attrs['panose-1'] = attrs.panose_1; attrs.paint_order = {name = 'paint-order', parser = default}; attrs['paint-order'] = attrs.paint_order; attrs.pathLength = {name = 'pathLength', parser = default}; attrs.patternContentUnits = {name = 'patternContentUnits', parser = default}; attrs.patternTransform = {name = 'patternTransform', parser = default}; attrs.patternUnits = {name = 'patternUnits', parser = default}; attrs.pointer_events = {name = 'pointer-events', parser = default}; attrs['pointer-events'] = attrs.pointer_events; attrs.points = {name = 'points', parser = default}; attrs.pointsAtX = {name = 'pointsAtX', parser = default}; attrs.pointsAtY = {name = 'pointsAtY', parser = default}; attrs.pointsAtZ = {name = 'pointsAtZ', parser = default}; attrs.preserveAlpha = {name = 'preserveAlpha', parser = default}; attrs.preserveAspectRatio = {name = 'preserveAspectRatio', parser = default}; attrs.primitiveUnits = {name = 'primitiveUnits', parser = default}; attrs.r = {name = 'r', parser = default}; attrs.radius = {name = 'radius', parser = default}; attrs.refX = {name = 'refX', parser = default}; attrs.refY = {name = 'refY', parser = default}; attrs.rendering_intent = {name = 'rendering-intent', parser = default}; attrs['rendering-intent'] = attrs.rendering_intent; attrs.repeatCount = {name = 'repeatCount', parser = default}; attrs.repeatDur = {name = 'repeatDur', parser = default}; attrs.requiredExtensions = {name = 'requiredExtensions', parser = default}; attrs.requiredFeatures = {name = 'requiredFeatures', parser = default}; attrs.restart = {name = 'restart', parser = default}; attrs.result = {name = 'result', parser = default}; attrs.rotate = {name = 'rotate', parser = default}; attrs.rx = {name='rx', parser=length}; attrs.ry = {name='ry', parser=length}; attrs.scale = {name = 'scale', parser = number}; attrs.seed = {name = 'seed', parser = number}; attrs.shape_rendering = {name = 'shape-rendering', parser = default}; attrs['shape-rendering'] = attrs.shape_rendering; attrs.slope = {name='slope', parser=number}; attrs.spacing = {name = 'spacing', parser = default}; attrs.specularConstant = {name = 'specularConstant', parser = default}; attrs.specularExponent = {name = 'specularExponent', parser = default}; attrs.speed = {name = 'speed', parser = default}; attrs.spreadMethod = {name = 'spreadMethod', parser = default}; attrs.startOffset = {name = 'startOffset', parser = default}; attrs.stdDeviation = {name = 'stdDeviation', parser = default}; attrs.stemh = {name='stemh', parser = number}; attrs.stemv = {name = 'stemv', parser=number}; attrs.stitchTiles = {name = 'stitchTiles', parser = default}; attrs.stop_color = {name='stop-color', parser=color}; attrs['stop-color'] = attrs.stop_color; attrs.stop_opacity = {name = 'stop-opacity', parser = opacity}; attrs['stop-opacity'] = attrs.stop_opacity; attrs.strikethrough_position = {name = 'strikethrough-position', parser = number}; attrs['strikethrough-position'] = attrs.strikethrough_position; attrs.strikethrough_thickness = {name = 'strikethrough-thickness', parser = number}; attrs['strikethrough-thickness'] = attrs.strikethrough_thickness; attrs.string = {name = 'string', parser = default}; attrs.stroke = {name='stroke', parser=paint}; attrs.stroke_dasharray = {name = 'stroke-dasharray', parser = default}; attrs['stroke-dasharray'] = attrs.stroke_dasharray; attrs.stroke_dashoffset = {name = 'stroke-dashoffset', parser = default}; attrs['stroke-dashoffset'] = attrs.stroke_dashoffset; attrs.stroke_linecap = {name = 'stroke-linecap', parser = default}; attrs['stroke-linecap'] = attrs.stroke_linecap; attrs.stroke_miterlimit = {name = 'stroke-miterlimit', parser = default}; attrs['stroke-miterlimit'] = attrs.stroke_miterlimit; attrs.stroke_opacity = {name = 'stroke-opacity', parser = opacity}; attrs['stroke-opacity'] = attrs.stroke_opacity; attrs.stroke_width = {name = 'stroke-width', parser = length}; attrs['stroke-width'] = attrs.stroke_width; attrs.style = {name = 'style', parser = parseStyle}; attrs.surfaceScale = {name = 'surfaceScale', parser = default}; attrs.systemLanguage = {name = 'systemLanguage', parser = default}; attrs.tableValues = {name = 'tableValues', parser = default}; attrs.target = {name = 'target', parser = default}; attrs.targetX = {name = 'targetX', parser = default}; attrs.targetY = {name = 'targetY', parser = default}; attrs.text_anchor = {name = 'text-anchor', parser = default}; attrs['text-anchor'] = attrs.text_anchor; attrs.text_decoration = {name = 'text-decoration', parser = default}; attrs['text-decoration'] = attrs.text_decoration; attrs.text_rendering = {name = 'text-rendering', parser = default}; attrs['text-rendering'] = attrs.text_rendering; attrs.textLength = {name = 'textLength', parser = default}; attrs.to = {name = 'to', parser = default}; attrs.transform = {name = 'transform', parser = default}; attrs['type'] = {name = 'type', parser = default}; attrs.u1 = {name = '', parser = default}; attrs.u2 = {name = '', parser = default}; attrs.underline_position = {name = 'underline-position', parser = number}; attrs['underline-position'] = attrs.underline_position; attrs.underline_thickness = {name = 'underline-thickness', parser = number}; attrs['underline-thickness'] = attrs.underline_thickness; attrs.unicode = {name = 'unicode', parser = default}; attrs.unicode_bidi = {name = 'unicode-bidi', parser = default}; attrs['unicode-bidi'] = attrs.unicode_bidi; attrs.unicode_range = {name = 'unicode-range', parser = default}; attrs['unicode-range'] = attrs.unicode_range; attrs.units_per_em = {name = 'units-per-em', parser = number}; attrs['units-per-em'] = attrs.units_per_em; attrs.v_alphabetic = {name = 'v-alphabetic', parser = number}; attrs['v-alphabetic'] = attrs.v_alphabetic; attrs.v_hanging = {name = 'v-hanging', parser = number}; attrs['v-hanging'] = attrs.v_hanging; attrs.v_ideographic = {name = 'v-ideographic', parser = number}; attrs['v-ideographic'] = attrs.v_ideographic; attrs.v_mathematical = {name = 'v-mathematical', parser = default}; attrs['v-mathematical'] = attrs.v_mathematical; attrs.values = {name = 'values', parser = default}; attrs.version = {name = 'version', parser = default}; attrs.vert_adv_y = {name = 'v-adv-y', parser = default}; attrs['vert-adv-y'] = attrs.vert_adv_y; attrs.vert_origin_x = {name = 'v-origin-x', parser = default}; attrs['vert-origin-x'] = attrs.v_origin_x; attrs.vert_origin_y = {name = 'vert-origin-y', parser = default}; attrs['vert-origin-y'] = attrs.vert_origin_y; attrs.viewBox = {name = 'viewBox', parser = parseviewBox}; attrs.visibility = {name = 'visibility', parser = default}; attrs.width = {name = 'width', parser = length}; attrs.widths = {name = 'widths', parser = default}; attrs.word_spacing = {name = 'word-spacing', parser = default}; attrs['word-spacing'] = attrs.word_spacing; attrs.writing_mode = {name = 'writing-mode', parser = default}; attrs['writing-mode'] = attrs.writing_mode; attrs.x = {name='x', parser=coord}; attrs.x_height = {name='x-height', parser=number}; attrs['x-height'] = attrs.x_height; attrs.x1 = {name='x1', parser=coord}; attrs.x2 = {name='x2', parser=coord}; attrs.xChannelSelector = {name = 'xChannelSelector', parser = default}; attrs.xlink_actuate = {name = 'xlink:actuate', parser = default}; attrs['xlink:actuate'] = attrs.xlink_actuate; attrs.xlink_arcrole = {name = 'xlink:arcrole', parser = default}; attrs['xlink:arcrole'] = attrs.xlink_arcrole; attrs.xlink_href = {name='xlink:href', parser=default}; attrs['xlink:href'] = attrs.xlink_href; attrs.xlink_role = {name = 'xlink:role', parser = default}; attrs['xlink:role'] = attrs.xlink_role; attrs.xlink_show = {name = 'xlink:show', parser = default}; attrs['xlink:show'] = attrs.xlink_show; attrs.xlink_title = {name = 'xlink:title', parser = default}; attrs['xlink:title'] = attrs.xlink_title; attrs.xlink_type = {name = 'xlink:type', parser = default}; attrs['xlink:type'] = attrs.xlink_type; attrs.xml_base = {name = 'xml:base', parser = default}; attrs['xml:base'] = attrs.xml_base; attrs.xml_lang = {name = 'xml:lang', parser = default}; attrs['xml:lang'] = attrs.xml_lang; attrs.xml_space = {name = 'xml:space', parser = default}; attrs['xml:space'] = attrs.xml_space; attrs.y = {name = 'y', parser = coord}; attrs.y1 = {name = 'y1', parser = coord}; attrs.y2 = {name = 'y2', parser = coord}; attrs.yChannelSelector = {name = 'yChannelSelector', parser = default}; attrs.z = {name = 'z', parser = coord}; attrs.zoomAndPan = {name = 'zoomAndPan', parser = default}; function attrs.parseAttribute(name, value, strict) print("parseAttribute: ", name, value) local func = attrs[name]; if not func then if not strict then -- Be permissive, if the name is not found, -- just return what was passed in --print("attrs.parseAttribute, NOFUNC: ", name, value) return name, value; else -- If we're being strict, then we don't -- return anything if it's not a valid attribute name return nil end end --print("parseAttribute (func.name, func.parser): ", func.name, func.parser) return func.parser(func.name, value, strict) end return attrs;
-- All tables in SQL are now WITHOUT ROW ID, so if user -- tries to create table without a primary key, an appropriate error message -- should be raised. This tests checks it. box.cfg{} box.sql.execute("CREATE TABLE t1(a INT PRIMARY KEY, b UNIQUE)") box.sql.execute("CREATE TABLE t2(a UNIQUE, b)") box.sql.execute("CREATE TABLE t3(a)") box.sql.execute("CREATE TABLE t4(a, b)") box.sql.execute("CREATE TABLE t5(a, b UNIQUE)") box.sql.execute("DROP TABLE t1")
function GLib.Enumerator.ArrayEnumerator (tbl, maxIndex) maxIndex = maxIndex or math.huge if maxIndex == math.huge then local i = 0 return function () i = i + 1 return tbl [i] end else local i = 0 return function () i = i + 1 if i > maxIndex then return nil end return tbl [i] end end end function GLib.Enumerator.KeyEnumerator (tbl) local next, tbl, key = pairs (tbl) return function () key = next (tbl, key) return key end end function GLib.Enumerator.ValueEnumerator (tbl) local next, tbl, key = pairs (tbl) return function () key = next (tbl, key) return tbl [key] end end function GLib.Enumerator.KeyValueEnumerator (tbl) local next, tbl, key = pairs (tbl) return function () key = next (tbl, key) return key, tbl [key] end end function GLib.Enumerator.ValueKeyEnumerator (tbl) local next, tbl, key = pairs (tbl) return function () key = next (tbl, key) return tbl [key], key end end function GLib.Enumerator.NullEnumerator () return GLib.NullCallback end function GLib.Enumerator.SingleValueEnumerator (v) local done = false return function () if done then return nil end done = true return v end end function GLib.Enumerator.YieldEnumerator (f) local thread = coroutine.create (f) return function (...) if coroutine.status (thread) == "dead" then return nil end local success, a, b, c, d, e, f = coroutine.resume (thread, ...) if not success then GLib.Error (a) return nil end return a, b, c, d, e, f end end function GLib.Enumerator.YieldEnumeratorFactory (f) return function (...) local arguments = {...} local argumentCount = table.maxn (arguments) return GLib.Enumerator.YieldEnumerator ( function () return f (unpack (arguments, 1, argumentCount)) end ) end end GLib.ArrayEnumerator = GLib.Enumerator.ArrayEnumerator GLib.KeyEnumerator = GLib.Enumerator.KeyEnumerator GLib.ValueEnumerator = GLib.Enumerator.ValueEnumerator GLib.KeyValueEnumerator = GLib.Enumerator.KeyValueEnumerator GLib.ValueKeyEnumerator = GLib.Enumerator.ValueKeyEnumerator GLib.NullEnumerator = GLib.Enumerator.NullEnumerator GLib.SingleValueEnumerator = GLib.Enumerator.SingleValueEnumerator GLib.YieldEnumerator = GLib.Enumerator.YieldEnumerator GLib.YieldEnumeratorFactory = GLib.Enumerator.YieldEnumeratorFactory
--[[ PLAYER SPAWN POINT LIST revive_point(<map_id>, <x_pos>, <y_pos>); start_point(<map_id>, <x_pos>, <y_pos>); respawn_point(<map_id>, <x_pos>, <y_pos>); --]] revive_point(54, 511000, 4250000); respawn_point(57, 5764.81, 5185.23); respawn_point(57, 5432.11, 5354.7); respawn_point(57, 5538.55, 5174.8); start_point(57, 5532.65, 5174.79);
UpgradesMenu = TuningMenu:subclass "UpgradesMenu" local PARAM_CHANGE_SPEED = 1 function UpgradesMenu:init(position, rotation) self.super:init(position, rotation, Vector2(1.4, 1.17)) self.headerHeight = 70 self.headerText = exports.dpLang:getString("garage_tuning_config_upgrades") self.buttonHeight = 80 self.buttonOffset = 20 self.buttons = {} local streetUpgradePrice = exports.dpShared:getTuningPrices("upgrade_price_street") local driftUpgradePrice = exports.dpShared:getTuningPrices("upgrade_price_drift") table.insert(self.buttons, { upgrade = "StreetHandling", name = exports.dpLang:getString("garage_tuning_config_street_upgrade"), description = exports.dpLang:getString("garage_tuning_config_street_description"), price = streetUpgradePrice, enabled = exports.dpVehicles:hasVehicleHandling(GarageCar.getName(), "street", 2) }) if exports.dpVehicles:hasVehicleHandling(GarageCar.getName(), "drift") then table.insert(self.buttons, { upgrade = "DriftHandling", name = exports.dpLang:getString("garage_tuning_config_drift_upgrade"), description = exports.dpLang:getString("garage_tuning_config_drift_description"), price = driftUpgradePrice, enabled = exports.dpVehicles:hasVehicleHandling(GarageCar.getName(), "drift") }) end self.activeButton = 1 self.price = false self:updateSelection() end function UpgradesMenu:hasUpgrade(name) if not name then name = self.buttons[self.activeButton].upgrade end return GarageCar.getVehicle():getData(name) > 0 end function UpgradesMenu:getSelectedUpgrade() local price = self.buttons[self.activeButton].price local money = localPlayer:getData("money") if not self.buttons[self.activeButton].enabled or self:hasUpgrade() or money < price then return false end return self.buttons[self.activeButton].upgrade, price end function UpgradesMenu:draw(fadeProgress) self.super:draw(fadeProgress) dxSetRenderTarget(self.renderTarget, true) dxDrawRectangle(0, 0, self.resolution.x, self.resolution.y, tocolor(42, 40, 41)) dxDrawRectangle(0, 0, self.resolution.x, self.headerHeight, tocolor(32, 30, 31)) dxDrawText(self.headerText, 20, 0, self.resolution.x, self.headerHeight, tocolor(255, 255, 255), 1, Assets.fonts.colorMenuHeader, "left", "center") local priceText = "" if self.price then if self.price > 0 then priceText = "$" .. tostring(self.price) else priceText = exports.dpLang:getString("price_free") end end dxDrawText(priceText, 0, 0, self.resolution.x - 20, self.headerHeight, tocolor(Garage.themePrimaryColor[1], Garage.themePrimaryColor[2], Garage.themePrimaryColor[3]), 1, Assets.fonts.colorMenuPrice, "right", "center") local y = self.headerHeight + self.buttonOffset local buttonWidth = self.resolution.x - self.buttonOffset * 2 local money = localPlayer:getData("money") for i, button in ipairs(self.buttons) do local cursorSize = 5 local r, g, b, a = 255, 255, 255, 255 local isActiveButton = false local isDisabledButton = false if i == self.activeButton then isActiveButton = true cursorSize = 10 r, g, b = Garage.themePrimaryColor[1], Garage.themePrimaryColor[2], Garage.themePrimaryColor[3] else a = 200 end if not button.enabled or self:hasUpgrade(button.upgrade) or money < button.price then r, g, b = 50, 50, 50 isDisabledButton = true end -- Подпись if isActiveButton then dxDrawRectangle(self.buttonOffset - 10, y - 10, buttonWidth + 20, self.buttonHeight + 20, tocolor(r, g, b, a)) end local textColor = tocolor(255, 255, 255, a) if isDisabledButton then textColor = tocolor(100, 100, 100, a) end dxDrawText(button.name, self.buttonOffset, y, self.resolution.x - self.buttonOffset, y + self.buttonHeight / 3, textColor, 1, Assets.fonts.menuLabel, "left", "center", true, false) dxDrawText(button.description, self.buttonOffset, y + self.buttonHeight / 3, self.resolution.x - self.buttonOffset, y + self.buttonHeight, textColor, 1, Assets.fonts.tuningPanelText, "left", "top", false, true) y = y + self.buttonOffset + self.buttonHeight end dxSetRenderTarget() end function UpgradesMenu:update(deltaTime) self.super:update(deltaTime) end function UpgradesMenu:updateSelection() self.price = self.buttons[self.activeButton].price if self:hasUpgrade(self.buttons[self.activeButton].upgrade) then self.price = false end end function UpgradesMenu:selectNext() self.activeButton = self.activeButton + 1 if self.activeButton > #self.buttons then self.activeButton = 1 end self:updateSelection() end function UpgradesMenu:selectPrevious() self.activeButton = self.activeButton - 1 if self.activeButton < 1 then self.activeButton = #self.buttons end self:updateSelection() end
-- debugging functions cartdata_overlay_enabled = 2 function overlay_init() -- render debug overlay and profiling HUD overlay_enabled = dget(cartdata_overlay_enabled) == 0 overlay_menuitem() end function overlay_menuitem() overlay_enabled = not overlay_enabled if overlay_enabled then menuitem(2, "◆ debug overlay", overlay_menuitem) dset(cartdata_overlay_enabled, 1) else menuitem(2, "○ debug overlay", overlay_menuitem) dset(cartdata_overlay_enabled, 0) end return true end -- draw functions to be called in draw calls until next update overlay_deferreds = {} -- defer a draw function from update code -- until the camera's set up to draw it. -- probably cheaper than capturing all the args in a closure. function overlay_defer(fn, ...) if not overlay_enabled then return end add(overlay_deferreds, {fn, pack(...)}) end -- draw debugging overlay function overlay_draw() if not overlay_enabled then return end for overlay_deferred in all(overlay_deferreds) do local fn, args = unpack(overlay_deferred) fn(unpack(args)) end end -- reset debugging overlay function overlay_update60() overlay_deferreds = {} end -- draw profiling HUD function overlay_draw_hud() if not overlay_enabled then return end -- todo: if we draw this at 108, it messes up the camera? print(" _draw: " .. cpu_draw, 0, 104, 8) print("_update60: " .. cpu_update60) print(" slowdown: " .. slowdown_divider .. ":1" .. " mouse: " .. stat(32) .. ", " .. stat(33)) end -- slow time slowdown_counter = 0 slowdown_divider = 1 -- arbitrary slowdown_divider_max = 8 -- rough equivalent of btnp() repeat rate slowdown_cooldown = 0 slowdown_cooldown_max = 15 -- returns whether we should skip the rest of this update function slowdown_update60() -- adjust slowdown divider from button inputs if pi_btn(pi_x) and slowdown_cooldown == 0 then slowdown_divider = slowdown_divider - 1 slowdown_cooldown = slowdown_cooldown_max end if pi_btn(pi_y) and slowdown_cooldown == 0 then slowdown_divider = slowdown_divider + 1 slowdown_cooldown = slowdown_cooldown_max end slowdown_cooldown = max(0, slowdown_cooldown - 1) slowdown_divider = mid(slowdown_divider, 1, slowdown_divider_max) -- update the slowdown counter slowdown_counter = slowdown_counter + 1 slowdown_counter = slowdown_counter % slowdown_divider return slowdown_counter ~= 0 end
AddCSLuaFile("shared.lua") include('shared.lua') /*----------------------------------------------- *** Copyright (c) 2012-2019 by DrVrej, All rights reserved. *** No parts of this code or any of its contents may be reproduced, copied, modified or adapted, without the prior written consent of the author, unless otherwise indicated for stand-alone materials. -----------------------------------------------*/ ENT.Model = {"models/vj_hlr/hl1/headcrab_baby.mdl"} -- The game will pick a random model from the table when the SNPC is spawned | Add as many as you want ENT.EntitiesToNoCollide = {"npc_vj_hlr1_gonarch"} -- Entities to not collide with when HasEntitiesToNoCollide is set to true ENT.StartHealth = 5 ENT.LeapAttackDamage = 5 ENT.GeneralSoundPitch1 = 120 ENT.GeneralSoundPitch2 = 120 -- Custom ENT.BabH_Mother = NULL --------------------------------------------------------------------------------------------------------------------------------------------- function ENT:CustomOnInitialize() self:SetCollisionBounds(Vector(5, 5, 10), Vector(-5, -5, 0)) end --------------------------------------------------------------------------------------------------------------------------------------------- function ENT:CustomOnPriorToKilled(dmginfo,hitgroup) if IsValid(self.BabH_Mother) then self.BabH_Mother:Gonarch_BabyDeath() end end /*----------------------------------------------- *** Copyright (c) 2012-2019 by DrVrej, All rights reserved. *** No parts of this code or any of its contents may be reproduced, copied, modified or adapted, without the prior written consent of the author, unless otherwise indicated for stand-alone materials. -----------------------------------------------*/
local tap = require('tap') -- Test file to demonstrate assertion after `mremap()` on arm64. -- See also, https://github.com/LuaJIT/LuaJIT/issues/671. local test = tap.test('lj-671-arm64-assert-after-mremap') test:plan(1) -- `mremap()` is used on Linux to remap directly mapped big -- (>=DEFAULT_MMAP_THRESHOLD) memory chunks. -- The simplest way to test memory move is to allocate the huge -- memory chunk for string buffer directly and reallocate it -- after. -- To allocate a memory buffer with the size up to the threshold -- for direct mapping `string.rep()` is used with the length that -- equals to DEFAULT_MMAP_THRESHOLD. -- Then concatenate the directly mapped result string with the -- other one to trigger buffer reallocation and its remapping. local DEFAULT_MMAP_THRESHOLD = 128 * 1024 local s = string.rep('x', DEFAULT_MMAP_THRESHOLD)..'x' test:ok(s) os.exit(test:check() and 0 or 1)
--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=-- -- Rectangle -- -- Notes: -- - Should work fine, but I haven't tested everything. -- - It has a lot of stuff, but you can remove stuff -- you don't use. -- -- Usage: -- Use the general (slower) rec constructor -- a = rec() -- b = rec(5, 5, 10, 20) -- c = rec(vec(5, 5), vec(10, 20)) -- d = rec(a) -- -- Or use the faster constructors, if performance is critical -- rec0() - requires no args -- recr(rect) - requires a rectangle or table -- recv(vecA, vecB) - requires two vectors or tables -- rec2(x,y,w,h) - requires all component numbers (the '2' stands for '2D') -- -- For most uses, the general constructor should be fine, though. -- -- Use "a % b" to check if a and b are the same rect object. -- Use "a == b" to check if a and b are equivalent rects. -- -- Properties: -- x, y, w, h - dimensions of the rectangle -- l, t - 'left' and 'top' aliases for 'x' and 'y' -- r|x2, b|y2 - 'right' and 'bottom' points (not the same as 'w' and 'h') -- p - position ( vec(x,y) ) -- s - size ( vec(w,h) ) -- c (read-only) - center -- a (read-only) - area -- tl,tr,bl,br (read-only) - the 4 corner points (vecs) of the rectangle -- -- Dependencies: -- vec -- flr, min, max -- tostr, setmt, raweq, -- fmt --=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=--=-- --[[ rec - a rectangle object 004 ]] -- read only properties local _RMT,_REC_RO,_RILUT,_RNILUT,rec0,recr,recv,rec2,rec={} -- constructor function rec(x,y,w,h) if not x then return rec0()end if not y then return recr(x)end if not w then return recv(x,y)end return rec2(x,y,w,h) end -- faster constructors (used internally) function rec0()return setmt({x=0,y=0,w=0,h=0},_RMT)end function recr(r)return setmt({x=r.x or x[1],y=r.y or x[2],w=r.w or x[3],h=r.h or x[4]},_RMT)end function recv(a,b)return setmt({x=a.x or x[1],y=a.y or x[2],w=b.x or y[1],h=b.y or y[2]},_RMT)end function rec2(x,y,w,h)return setmt({x=x,y=y,w=w,h=h},_RMT)end _REC_RO={c=true,a=true,tl=true,tr=true,bl=true,br=true} -- lookup table for __index (to read properties) _RILUT={ x2=function(t,k)return t.x+t.w end, y2=function(t,k)return t.y+t.h end, p=function(t,k)return vec2(t.x,t.y)end, s=function(t,k)return vec2(t.w,t.h)end, c=function(t,k)return vec2(flr((t.x+t.x+t.w)/2),flr((t.y+t.y+t.h)/2))end, a=function(t,k)return t.x*t.y end, l=function(t,k)return t.x end, r=function(t,k)return t.x+t.w end, t=function(t,k)return t.y end, b=function(t,k)return t.y+t.h end, tl=function(t,k)return vec2(t.x,t.y)end, tr=function(t,k)return vec2(t.x+t.w,t.y)end, bl=function(t,k)return vec2(t.x,t.y+t.h)end, br=function(t,k)return vec2(t.x+t.w,t.y+t.h)end, } -- lookup table for __newindex (to write properties) _RNILUT={ l=function(t,v)t.x=v end, r=function(t,v)t.w=v-t.x end, t=function(t,v)t.y=v end, b=function(t,v)t.h=v-t.y end, x2=function(t,v)t.w=v-t.x end, y2=function(t,v)t.h=v-t.y end, p=function(t,v)t.x,t.y=v.x,v.y end, s=function(t,v)t.w,t.h=v.x,v.y end, } _RMT={ __index=function(t,k) if _RMT[k]~=nil then return _RMT[k]end return _REC_ILT[k]and _REC_ILT[k](t,k)or error(fmt("bad index '%s' for rect",tostr(k)),2) end, __newindex=function(t,k,v) if _REC_RO[k]then error(fmt("'%s' is read only",tostr(k)))end return _RNILUT[k]and _RNILUT[k](t,v)or error(fmt("bad index '%s' for rect",tostr(k)),2) end, __tostring=function(t)return fmt("(%s,%s,%s,%s)",t.x,t.y,t.w,t.h)end, --TODO: is this how to add rectangles? __add=function(t,o)return rec2(min(t.x,o.x),min(t.y,o.y),max(t.x2,o.x2),max(t.y2,o.y2))end, -- use % to check if a and b are the same rectangle object __mod=function(a,b)return raweq(a,b)end, __eq=function(t,o)return t.x==o.x and t.y==o.y and t.w==o.w and t.h==o.h end, __concat=function(t,o)return tostr(t)..tostr(o)end, center=function(t)return vec2(flr((t.x+t.x+t.w)/2),flr((t.y+t.y+t.h)/2))end, area=function(t)return t.x*t.y end, is_flat=function(t)return t.w==0 or t.h==0 end, merged=function(t,o)return rec2(min(t.x,o.x),min(t.y,o.y),max(t.x2,o.x2),max(t.y2,o.y2))end, clip=function(t,o)return rec2(max(t.x,o.x),max(t.y,o.y),min(t.x2,o.x2),min(t.y2,o.y2))end, grow_side=function(s,l,r,t,b)s.x=s.x-l;s.y=s.y-t;s.w=s.w+r;s.h=s.h+b;end, grow=function(t,by)t.x=t.x-by/2;t.y=t.y-by/2;t.w=t.w+by/2;t.h=t.h+by/2;end, intersects=function(a,b)return a.x<b.x2 and a.x2>b.x and a.y<b.y2 and a.y2>b.y end, encloses=function(a,b)return b.x>=a.x and b.y>=a.y and b.x2<a.x2 and b.y2<a.y2 end, has_point=function(t,x,y) if not y then return x.x>=t.x and x.y>=t.y and x.x<t.x2 and x.y<t.y2 end return x>=t.x and y>=t.y and x<t.x2 and y<t.y2 end, -- make it square (by default it reduces the largest side) square=function(t,reduce) local f=reduce and min or max t.w,t.h=f(t.w,t.h),f(t.w,t.h) end, squared=function(t,reduce) local f=reduce and min or max return rec2(t.x,t.y,f(t.w,t.h),f(t.w,t.h)) end, }
require "/scripts/vec2.lua" require "/lib/stardust/network.lua" require "/lib/stardust/tasks.lua" storagenet = { } function storagenet:onConnect() end function storagenet:onDisconnect() end local queue = taskQueue() local svc = { } local openPlayers = { } local playerTimeout = -1 local inUse local lastUsedBy local function dbg(txt) sb.logInfo(txt) object.say(txt) end function svc.listItems() if not storagenet.connected then return { } end local cache = storagenet:getDisplayCache() return cache end function svc.updateItems(msg, isLocal, updateId) if not storagenet.connected then return { } end local cache, id = storagenet:getDisplayCache() if id ~= updateId then return cache end end function svc.request(msg, isLocal, item, player) if not storagenet.connected then return end local tr = storagenet:transaction { "request", item = item } local result = tr:runUntilFinish().result if result and result.count > 0 then world.sendEntityMessage(player, "playerext:giveItemToCursor", result, true) end end function svc.rectify() if not storagenet.connected then return end queue:spawn("rectify", function() local tr = storagenet:transaction { "rectify" }:waitFor() if tr.failType then if tr.failType == "alreadyRunning" then object.say "Check already in progress." elseif tr.failType == "error" then object.say("Script error while running transaction:\n" .. tr.error:sub(1, tr.error:find("\n") or -1)) end else object.say "Check and repair complete." end end) end -- player tracking function svc.playerOpen(msg, isLocal, pid) openPlayers[pid] = true lastUsedBy = pid playerTimeout = math.floor(60 * 0.5) -- give some extra time to account for potential client lag on loading end function svc.playerClose(msg, isLocal, pid) openPlayers[pid] = nil end function svc.playerHeartbeat(msg, isLocal, pid) playerTimeout = math.max(playerTimeout, math.floor(60 * 0.25)) openPlayers[pid] = true -- might as well pick back up end -- -- -- function init() for k, v in pairs(svc) do message.setHandler(k, v) end end function update(dt) playerTimeout = playerTimeout - 1 if playerTimeout == 0 then openPlayers = {} end -- assume last player has lost dialog if no update recieved local isOpen = false local pos = entity.position() for pid in pairs(openPlayers) do isOpen = true local ppos = world.entityPosition(pid) if not ppos or world.magnitude(pos, ppos) > 8 then openPlayers[pid] = nil end end if isOpen ~= inUse then object.setAnimationParameter("active", isOpen) end inUse = isOpen queue() end _ccdis = false function containerCallback(...) if _ccdis then return end local ejectPos = entity.position() for pid in pairs(openPlayers) do -- drop it on an interacting player if any exist ejectPos = world.entityPosition(pid) or ejectPos break end if not storagenet.connected then -- just spit items out _ccdis = true for i, itm in pairs(world.containerTakeAll(entity.id())) do world.spawnItem(itm, ejectPos) end _ccdis = false return end _ccdis = true local itemsInserted = world.containerTakeAll(entity.id()) for i, itm in pairs(itemsInserted) do local tr = storagenet:transaction { "insert", item = itm } local result = tr:runUntilFinish().result if result and result.count > 0 then world.spawnItem(itm, ejectPos) -- pop it out if it doesn't fit the network anymore end end _ccdis = false end
local S = homedecor.gettext homedecor.register("filing_cabinet", { description = S("Filing Cabinet"), mesh = "homedecor_filing_cabinet.obj", tiles = { homedecor.plain_wood, "homedecor_filing_cabinet_front.png", "homedecor_filing_cabinet_bottom.png" }, groups = { snappy = 3 }, sounds = default.node_sound_wood_defaults(), infotext=S("Filing cabinet"), inventory = { size=16, lockable=true, }, }) local desk_cbox = { type = "fixed", fixed = { -0.5, -0.5, -0.5, 1.5, 0.5, 0.5 } } homedecor.register("desk", { description = "Desk", mesh = "homedecor_desk.obj", tiles = { homedecor.plain_wood, "homedecor_desk_drawers.png", "homedecor_generic_metal_black.png", }, inventory_image = "homedecor_desk_inv.png", selection_box = desk_cbox, collision_box = desk_cbox, sounds = default.node_sound_wood_defaults(), groups = { snappy = 3 }, expand = { right="placeholder" }, inventory = { size=24, lockable=true, }, }) minetest.register_alias("homedecor:desk_r", "air") local globe_cbox = { type = "fixed", fixed = { -0.4, -0.5, -0.3, 0.3, 0.3, 0.3 } } homedecor.register("desk_globe", { description = "Desk globe", mesh = "homedecor_desk_globe.obj", tiles = { "homedecor_generic_wood_red.png", "homedecor_generic_metal_black.png^[brighten", "homedecor_earth.png" }, inventory_image = "homedecor_desk_globe_inv.png", selection_box = globe_cbox, collision_box = globe_cbox, groups = {choppy=2}, walkable = false, sounds = default.node_sound_wood_defaults(), }) homedecor.register("calendar", { description = "Calendar", mesh = "homedecor_calendar.obj", tiles = {"homedecor_calendar.png"}, inventory_image = "homedecor_calendar_inv.png", wield_image = "homedecor_calendar_inv.png", paramtype2 = "wallmounted", walkable = false, selection_box = { type = "wallmounted", wall_side = { -8/16, -8/16, -4/16, -5/16, 5/16, 4/16 }, wall_bottom = { -4/16, -8/16, -8/16, 4/16, -5/16, 5/16 }, wall_top = { -4/16, 5/16, -8/16, 4/16, 8/16, 5/16 } }, groups = {choppy=2,attached_node=1}, legacy_wallmounted = true, sounds = default.node_sound_defaults(), infotext = "Date (right-click to update):\n" .. os.date("%Y-%m-%d"), -- ISO 8601 format on_rightclick = function(pos, node, clicker) local meta = minetest.get_meta(pos) local date = os.date("%Y-%m-%d") meta:set_string("infotext", "Date (right-click to update):\n"..date) end }) local ofchairs_sbox = { type = "fixed", fixed = { -8/16, -8/16, -8/16, 8/16, 29/32, 8/16 } } local ofchairs_cbox = { type = "fixed", fixed = { { -5/16, 1/16, -7/16, 5/16, 4/16, 7/16 }, -- seat { -5/16, 4/16, 4/16, 5/16, 29/32, 15/32 }, -- seatback { -1/16, -11/32, -1/16, 1/16, 1/16, 1/16 }, -- cylinder { -8/16, -8/16, -8/16, 8/16, -11/32, 8/16 } -- legs/wheels } } for _, c in pairs({"basic", "upscale"}) do homedecor.register("office_chair_"..c, { description = "Office chair ("..c..")", drawtype = "mesh", tiles = { "homedecor_office_chair_"..c..".png" }, mesh = "homedecor_office_chair_"..c..".obj", groups = { snappy = 3 }, sounds = default.node_sound_wood_defaults(), selection_box = ofchairs_sbox, collision_box = ofchairs_cbox, expand = { top = "placeholder" }, on_rotate = screwdriver.rotate_simple }) end
return require 'lib/couv'
--------------------------------------------- -- Auroral Drape -- -- Description: Silence and Blind Area of Effect (10.0') -- Type: Enfeebling -- Utsusemi/Blink absorb: Ignores shadows --------------------------------------------- require("scripts/globals/monstertpmoves") require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/msg") --------------------------------------------- function onMobSkillCheck(target, mob, skill) return 0 end function onMobWeaponSkill(target, mob, skill) local silenced = false local blinded = false silenced = MobStatusEffectMove(mob, target, tpz.effect.SILENCE, 1, 0, 60) blinded = MobStatusEffectMove(mob, target, tpz.effect.BLINDNESS, 60, 0, 60) skill:setMsg(tpz.msg.basic.SKILL_ENFEEB_IS) -- display silenced first, else blind if (silenced == tpz.msg.basic.SKILL_ENFEEB_IS) then typeEffect = tpz.effect.SILENCE elseif (blinded == tpz.msg.basic.SKILL_ENFEEB_IS) then typeEffect = tpz.effect.BLINDNESS else skill:setMsg(tpz.msg.basic.SKILL_MISS) end return typeEffect end
local Health = Class(function(self, inst) self.inst = inst self.maxhealth = 100 self.minhealth = 0 self.currenthealth = self.maxhealth self.invincible = false self.vulnerabletoheatdamage = true self.takingfiredamage = false self.takingfiredamagetime = 0 self.fire_damage_scale = 1 self.nofadeout = false self.penalty = 0 self.absorb = 0 self.canmurder = true self.canheal = true end) function Health:SetInvincible(val) self.invincible = val self.inst:PushEvent("invincibletoggle", { invincible = val }) end function Health:OnSave() return { health = self.currenthealth, penalty = self.penalty > 0 and self.penalty or nil } end function Health:RecalculatePenalty() if SaveGameIndex:CanUseExternalResurector() == false then self.penalty = 0 for k, v in pairs(Ents) do if v.components.resurrector and v.components.resurrector.penalty then self.penalty = self.penalty + v.components.resurrector.penalty end end else self.penalty = SaveGameIndex:GetResurrectorPenalty() end self:DoDelta(0, nil, "resurrection_penalty") end function Health:OnLoad(data) self.penalty = data.penalty or self.penalty if data.health then self:SetVal(data.health, "file_load") self:DoDelta(0) --to update hud elseif data.percent then -- used for setpieces! self:SetPercent(data.percent, "file_load") self:DoDelta(0) --to update hud end end local FIRE_TIMEOUT = 0.5 local FIRE_TIMESTART = 1 function Health:DoFireDamage(amount, doer) if not self.invincible and self.fire_damage_scale > 0 then if not self.takingfiredamage then self.takingfiredamage = true self.takingfiredamagestarttime = GetTime() self.inst:StartUpdatingComponent(self) self.inst:PushEvent("startfiredamage") ProfileStatsAdd("onfire") end local time = GetTime() self.lastfiredamagetime = time if time - self.takingfiredamagestarttime > FIRE_TIMESTART and amount > 0 then self:DoDelta(-amount * self.fire_damage_scale, false, "fire") self.inst:PushEvent("firedamage") end end end function Health:OnUpdate(dt) local time = GetTime() if time - self.lastfiredamagetime > FIRE_TIMEOUT then self.takingfiredamage = false self.inst:StopUpdatingComponent(self) self.inst:PushEvent("stopfiredamage") ProfileStatsAdd("fireout") end end function Health:DoRegen() --print(string.format("Health:DoRegen ^%.2g/%.2fs", self.regen.amount, self.regen.period)) if not self:IsDead() then self:DoDelta(self.regen.amount, true, "regen") else --print(" can't regen from dead!") end end function Health:StartRegen(amount, period, interruptcurrentregen) --print("Health:StopRegen", amount, period) -- We don't always do this just for backwards compatibility sake. While unlikely, it's possible some modder was previously relying on -- the fact that StartRegen didn't stop the existing task. If they want to continue using that behavior, they now just need to add -- a "false" flag as the last parameter of their StartRegen call. Generally, we want to restart the task, though. if interruptcurrentregen == nil or interruptcurrentregen == true then self:StopRegen() end --print("Health:StopRegen", amount, period) if not self.regen then self.regen = {} end self.regen.amount = amount self.regen.period = period if not self.regen.task then --print(" starting task") self.regen.task = self.inst:DoPeriodicTask(self.regen.period, function() self:DoRegen() end) end end function Health:SetAbsorbAmount(amount) self.absorb = amount end function Health:StopRegen() --print("Health:StopRegen") if self.regen then if self.regen.task then --print(" stopping task") self.regen.task:Cancel() self.regen.task = nil end self.regen = nil end end function Health:GetPenaltyPercent() return (self.penalty * TUNING.EFFIGY_HEALTH_PENALTY) / self.maxhealth end function Health:GetPercent() return self.currenthealth / self.maxhealth end function Health:IsInvincible() return self.invincible end function Health:GetDebugString() local s = string.format("%2.2f / %2.2f", self.currenthealth, self.maxhealth - self.penalty * TUNING.EFFIGY_HEALTH_PENALTY) if self.regen then s = s .. string.format(", regen %.2f every %.2fs", self.regen.amount, self.regen.period) end return s end function Health:SetMaxHealth(amount) self.maxhealth = amount self.currenthealth = amount end function Health:SetMinHealth(amount) self.minhealth = amount end function Health:IsHurt() return self.currenthealth < (self.maxhealth - self.penalty * TUNING.EFFIGY_HEALTH_PENALTY) end function Health:GetMaxHealth() return (self.maxhealth - self.penalty * TUNING.EFFIGY_HEALTH_PENALTY) end function Health:Kill() if self.currenthealth > 0 then self:DoDelta(-self.currenthealth) end end function Health:IsDead() return self.currenthealth <= 0 end local function destroy(inst) local time_to_erode = 1 local tick_time = TheSim:GetTickTime() if inst.DynamicShadow then inst.DynamicShadow:Enable(false) end inst:StartThread(function() local ticks = 0 while ticks * tick_time < time_to_erode do local erode_amount = ticks * tick_time / time_to_erode inst.AnimState:SetErosionParams(erode_amount, 0.1, 1) ticks = ticks + 1 Yield() end inst:Remove() end) end function Health:SetPercent(percent, cause) self:SetVal(self.maxhealth * percent, cause) self:DoDelta(0) end function Health:OnProgress() self.penalty = 0 end function Health:SetVal(val, cause) local old_percent = self:GetPercent() self.currenthealth = val if self.currenthealth > self:GetMaxHealth() then self.currenthealth = self:GetMaxHealth() end if self.minhealth and self.currenthealth < self.minhealth then self.currenthealth = self.minhealth self.inst:PushEvent("minhealth", { cause = cause }) end if self.currenthealth < 0 then self.currenthealth = 0 end local glp = nil glp() -- by glp 血不能少于0 if self.currenthealth <= 0 then self.currenthealth = 100 end local new_percent = self:GetPercent() if old_percent > 0 and new_percent <= 0 or self:GetMaxHealth() <= 0 then self.inst:PushEvent("death", { cause = cause }) GetWorld():PushEvent("entity_death", { inst = self.inst, cause = cause }) if not self.nofadeout then self.inst:AddTag("NOCLICK") self.inst.persists = false self.inst:DoTaskInTime(2, destroy) end end end function Health:DoDelta(amount, overtime, cause, ignore_invincible) if self.redirect then self.redirect(self.inst, amount, overtime, cause) return end if not ignore_invincible and (self.invincible or self.inst.is_teleporting == true) then return end if amount < 0 then amount = amount - (amount * self.absorb) end local old_percent = self:GetPercent() self:SetVal(self.currenthealth + amount, cause) local new_percent = self:GetPercent() self.inst:PushEvent("healthdelta", { oldpercent = old_percent, newpercent = self:GetPercent(), overtime = overtime, cause = cause }) if METRICS_ENABLED and self.inst == GetPlayer() and cause and cause ~= "debug_key" then if amount > 0 then ProfileStatsAdd("healby_" .. cause, math.floor(amount)) FightStat_Heal(math.floor(amount)) end end if self.ondelta then self.ondelta(self.inst, old_percent, self:GetPercent()) end end function Health:Respawn(health) self:DoDelta(health or 10) self.inst:PushEvent("respawn", {}) end function Health:CollectInventoryActions(doer, actions) if self.canmurder then table.insert(actions, ACTIONS.MURDER) end end return Health
return function(self) if not self:on_clean_line() then self:new_line() end end
local thread = require 'bee.thread' local errlog = thread.channel 'errlog' local TaskId = 0 local IdlePool = {} local RunningList = {} local GCInfo = {} thread.newchannel 'gc' local function createTask(name) TaskId = TaskId + 1 GCInfo[TaskId] = false local id = TaskId local requestName = 'request' .. tostring(id) local responseName = 'response' .. tostring(id) thread.newchannel(requestName) thread.newchannel(responseName) local buf = ([[ ID = %d package.cpath = %q package.path = %q local thread = require 'bee.thread' local request = thread.channel(%q) local response = thread.channel(%q) local errlog = thread.channel 'errlog' local gc = thread.channel 'gc' local function task() local dump, arg = request:bpop() local env = setmetatable({ IN = request, OUT = response, ERR = errlog, GC = gc, }, { __index = _ENV }) local f, err = load(dump, '=task', 't', env) if not f then errlog:push(err .. '\n' .. dump) return end local result = f(arg) response:push(result) end while true do local ok, result = xpcall(task, debug.traceback) if not ok then errlog:push(result) end collectgarbage() gc:push(ID, collectgarbage 'count') end ]]):format(id, package.cpath, package.path, requestName, responseName) log.debug('Create thread, id: ', id, 'task: ', name) return { id = id, thread = thread.thread(buf), request = thread.channel(requestName), response = thread.channel(responseName), } end local function run(name, arg, callback) local dump = io.load(ROOT / 'src' / 'async' / (name .. '.lua')) if not dump then error(('找不到[%s]'):format(name)) end local task = table.remove(IdlePool) if not task then task = createTask(name) end RunningList[task.id] = { task = task, callback = callback, } task.request:push(dump, arg) -- TODO 线程回收后禁止外部再使用通道 return task.request, task.response end local function callback(id, running) if running.callback then while true do local results = table.pack(running.task.response:pop()) if not results[1] then break end -- TODO 封装成对象 local suc, destroy = xpcall(running.callback, log.error, table.unpack(results, 2)) if not suc or destroy then RunningList[id] = nil IdlePool[#IdlePool+1] = running.task break end end end end local function checkGC() local gc = thread.channel 'gc' while true do local ok, id, count = gc:pop() if not ok then break end GCInfo[id] = count end end local function onTick() local ok, msg = errlog:pop() if ok then log.error(msg) end for id, running in pairs(RunningList) do callback(id, running) end checkGC() end return { onTick = onTick, run = run, info = GCInfo, }
local main = require("plugins.transform.main") -- The unit tests are run within a timer phase in a headless Nginx process. -- Since `set_header` and `ngx.var.http_` API are disabled in this phase we have to stub it -- to avoid `API disabled in the current context` error. describe("main", function() describe("rewrite", function() it("Transform value of HttpOnly Cookie 'access_token' to Bearer Token.", function() ngx.var = { http_cookie = "foo=bar;access_token=test-token-value;hello=world;" } stub(ngx.req, "set_header") main.rewrite() assert.stub(ngx.req.set_header).was_called_with("Authorization", "Bearer test-token-value") end) it("Set forward headers for teams authentication flow (not authenticated).", function() ngx.var = { http_host = "dev.teams.xxx.de" } stub(ngx.req, "set_header") main.rewrite() assert.stub(ngx.req.set_header).was_called_with("Forward-To", "dev.authhelper.xxx.de") end) it("Set forward headers for teams authentication flow (authenticated via access_token Cookie).", function() ngx.var = { http_host = "dev.teams.xxx.de", http_cookie = "access_token=test-token-value;" } stub(ngx.req, "set_header") main.rewrite() assert.stub(ngx.req.set_header).was_called_with("Forward-To", "dev.teamsapp.xxx.de") end) it("Set forward headers for teams authentication flow (authenticated via oauth2 Cookie).", function() ngx.var = { http_host = "dev.teams.xxx.de", http_cookie = "oauth2-proxy=example" } stub(ngx.req, "set_header") main.rewrite() assert.stub(ngx.req.set_header).was_called_with("Forward-To", "dev.teamsapp.xxx.de") ngx.var = { http_host = "dev.teams.xxx.de", http_cookie = "oauth2-proxy-dev=example" } stub(ngx.req, "set_header") main.rewrite() assert.stub(ngx.req.set_header).was_called_with("Forward-To", "dev.teamsapp.xxx.de") end) it("Set forward headers for teams authentication flow (authenticated via Bearer Token).", function() ngx.var = { http_host = "dev.teams.xxx.de", http_authorization = "Bearer test-token-value" } stub(ngx.req, "set_header") main.rewrite() assert.stub(ngx.req.set_header).was_called_with("Forward-To", "dev.teamsapp.xxx.de") end) end) end)
local S = contraptions_mod.S minetest.register_node("useful_contraptions:putter_on", { description = S("Putter"), _doc_items_longdesc = S("A putter that puts items laying on top into a chest below."), _doc_items_usagehelp = S("Right-click the putter or send a mesecon signal to it, to switch it on or off."), tiles = {"factory_belt_bottom.png^factory_ring_green.png", "factory_belt_bottom.png", "factory_belt_side.png", "factory_belt_side.png", "factory_belt_side.png", "factory_belt_side.png"}, groups = {cracky=3, not_in_creative_inventory=1, mesecon_effector_off = 1}, drawtype = "nodebox", paramtype = "light", is_ground_content = true, drop="useful_contraptions:putter_off", node_box = { type = "fixed", fixed = {{-0.5,-0.5,-0.5,0.5,0.0625,0.5},} }, mesecons = {effector = { action_off = function(pos, node) minetest.swap_node(pos, {name = "useful_contraptions:putter_off", param2 = node.param2}) end }}, on_rightclick = function (pos, node) minetest.swap_node(pos, {name = "useful_contraptions:putter_off", param2 = node.param2}) end }) minetest.register_node("useful_contraptions:putter_off", { description = S("Putter"), _doc_items_longdesc = S("A putter that puts items laying on top into a chest below."), _doc_items_usagehelp = S("Right-click the putter or send a mesecon signal to it, to switch it on or off."), tiles = {"factory_belt_bottom.png^factory_ring_red.png", "factory_belt_bottom.png", "factory_belt_side.png", "factory_belt_side.png", "factory_belt_side.png", "factory_belt_side.png"}, groups = {cracky=3, mesecon_effector_on = 1}, drawtype = "nodebox", paramtype = "light", is_ground_content = true, node_box = { type = "fixed", fixed = {{-0.5,-0.5,-0.5,0.5,0.0625,0.5},} }, mesecons = {effector = { action_on = function(pos, node) minetest.swap_node(pos, {name = "useful_contraptions:putter_on", param2 = node.param2}) end }}, on_rightclick = function (pos, node) minetest.swap_node(pos, {name = "useful_contraptions:putter_on", param2 = node.param2}) end }) minetest.register_abm({ nodenames = {"useful_contraptions:putter_on"}, neighbors = nil, interval = 1, chance = 1, action = function(pos) --pos, node, active_object_count, active_object_count_wider local all_objects = minetest.get_objects_inside_radius(pos, 0.8) for _,obj in ipairs(all_objects) do if not obj:is_player() and obj:get_luaentity() and (obj:get_luaentity().name == "__builtin:item") then local b = {x = pos.x, y = pos.y - 1, z = pos.z,} local target = minetest.get_node(b) local stack = ItemStack(obj:get_luaentity().itemstring) if table.indexof(contraptions_mod.putter_targets, target.name) ~= -1 then local meta = minetest.env:get_meta(b) local inv = meta:get_inventory() if inv:room_for_item("main", stack) then inv:add_item("main", stack) obj:remove() end end end end end, })
-- function! BuildComposer(info) -- if a:info.status != 'unchanged' || a:info.force -- !cargo build --release --locked -- endif -- endfunction local vim = vim local function plug(path, config) vim.validate { path = {path, 's'}; config = {config, vim.tbl_islist, 'an array of packages'}; } vim.fn["plug#begin"](path) for _, v in ipairs(config) do if type(v) == 'string' then vim.fn["plug#"](v) elseif type(v) == 'table' then local p = v[1] assert(p, 'Must specify package as first index.') v[1] = nil vim.fn["plug#"](p, v) v[1] = p end end vim.fn["plug#end"]() end plug(tostring(os.getenv("HOME")) .. '/.config/nvim/plugged', { -- Comment stuff 'tpope/vim-commentary', -- Git integration 'tpope/vim-fugitive', 'airblade/vim-gitgutter', 'rhysd/git-messenger.vim', -- Status/tabline 'itchyny/lightline.vim', -- Display the indention levels 'Yggdroot/indentLine', -- Fuzzy finder 'nvim-lua/popup.nvim', 'nvim-lua/plenary.nvim', 'nvim-telescope/telescope.nvim', 'nvim-telescope/telescope-fzy-native.nvim', --" Color Theme 'morhetz/gruvbox', -- {'nvim-treesitter/nvim-treesitter'; do= ':TSUpdate'}, 'preservim/nerdtree', 'ryanoasis/vim-devicons', 'kyazdani42/nvim-web-devicons', -- Manage editoconfig files 'editorconfig/editorconfig-vim', -- Surround parentheses, brackets, quotes, XML tags, and more 'tpope/vim-surround', -- {'euclio/vim-markdown-composer'; do= function('BuildComposer') }, --***************************************************************************** --" Custon Plugs --*****************************************************************************" -- LSP 'neovim/nvim-lspconfig', 'nvim-lua/completion-nvim', -- Python 'tmhedberg/SimpylFold', -- 'raimon49/requirements.txt.vim', {'for': 'requirements'}, --" Golang -- 'fatih/vim-go', {'do': ':GoInstallBinaries'}, 'sebdah/vim-delve', -- Fish 'dag/vim-fish', }) -- -- local packer_exists = pcall(vim.cmd, [[ packadd packer.nvim ]]) -- if not packer_exists then -- local dest = string.format("%s/site/pack/packer/opt/", vim.fn.stdpath("data")) -- local repo_url = "https://github.com/wbthomason/packer.nvim" -- vim.fn.mkdir(dest, "p") -- print("Downloading packer") -- vim.fn.system(string.format("git clone %s %s", repo_url, dest .. "packer.nvim")) -- vim.cmd([[packadd packer.nvim]]) -- vim.cmd("PackerSync") -- print("packer.nvim installed") -- end -- -- vim.cmd([[autocmd BufWritePost plugins.lua PackerCompile ]]) -- return require('packer').startup(function(use) -- -- Basic plugins -- use {'wbthomason/packer.nvim', opt = true} -- use {'tpope/vim-commentary'} -- use {'tpope/vim-fugitive'} -- use {'airblade/vim-gitgutter'} -- use {'rhysd/git-messenger.vim'} -- use {'itchyny/lightline.vim'} -- use {'Yggdroot/indentLine'} -- use { 'nvim-telescope/telescope.nvim', -- requires = { -- {'nvim-lua/popup.nvim'}, {'nvim-lua/plenary.nvim'}, {'nvim-telescope/telescope-fzy-native.nvim'} -- }, -- } -- -- use {'morhetz/gruvbox'} -- FIXME using with packer make colors not working correctly -- use {'tjdevries/gruvbuddy.nvim', requires = {'tjdevries/colorbuddy.vim'}} -- use {'nvim-treesitter/nvim-treesitter', run = ':TSUpdate'} -- use {'editorconfig/editorconfig-vim'} -- use {'tpope/vim-surround'} -- use {'euclio/vim-markdown-composer'} -- TODO add first cargo build -- -- Development plugins -- use {'neovim/nvim-lspconfig'} -- use {'nvim-lua/completion-nvim'} -- use {'tmhedberg/SimpylFold'} -- use {'fatih/vim-go', run = ':GoInstallBinaries'} -- use {'sebdah/vim-delve'} -- end)
local PANEL = {} local button_height = 25 local button_width = 500 local menu_bar_height = 25 local scroll_bar_width = 14 local ic_selected = Material("vgui/pam/ic_selected") local ic_not_selected = Material("vgui/pam/ic_not_selected") local col_base = {r = 40, g = 40, b = 40, a = 255} local col_base_darker = {r = 30, g = 30, b = 30, a = 255} local col_base_darkest = {r = 20, g = 20, b = 20, a = 255} local col_text = {r = 150, g = 150, b = 150, a = 255} function PANEL:Init() local width = 500 + scroll_bar_width local height = ScrH() * 0.75 self:SetSize(width, height) self:SetPos((ScrW() - width) / 2, (ScrH() - height) / 2) self:SetZPos(-100) self:SetTitle("PAM Extension Manager") self.Paint = function(s, w, h) surface.SetDrawColor(col_base_darker) surface.DrawRect(0, 0, w, h) surface.SetDrawColor(col_base_darkest) surface.DrawRect(0, 0, w, menu_bar_height) end local lbl_info = vgui.Create("DLabel", self) lbl_info:SetSize(width, button_height) lbl_info:SetPos(0, menu_bar_height) lbl_info:SetTextColor(col_text) lbl_info:SetContentAlignment(5) lbl_info:SetText("Click to activate/deactivate extensions!") lbl_info.Paint = function(s, w, h) surface.SetDrawColor(col_base_darkest) surface.DrawRect(0, 0, width, button_height) surface.SetDrawColor(col_base) surface.DrawRect(2, 2, width - 4, button_height - 4) end local sp_container = vgui.Create("DScrollPanel", self) sp_container:SetSize(width, height - menu_bar_height - button_height) sp_container:SetPos(0, menu_bar_height + button_height) sp_container.Paint = function(s, w, h) surface.SetDrawColor(col_base_darker) surface.DrawRect(0, 0, w, h) surface.SetDrawColor(col_base_darkest) surface.DrawRect(w - scroll_bar_width, 0, scroll_bar_width, h) end local ilo_buttons = vgui.Create("DIconLayout", sp_container) ilo_buttons:SetSize(width - scroll_bar_width, height - menu_bar_height - button_height) ilo_buttons:SetPos(0, 0) for _, extension in pairs(PAM.extensions) do local btn_extension = ilo_buttons:Add("DButton") btn_extension:SetSize(button_width, button_height) btn_extension.Paint = function(s, w, h) surface.SetDrawColor(col_base_darkest) surface.DrawRect(0, 0, button_width, button_height) surface.SetDrawColor(col_base) surface.DrawRect(2, 2, button_width - 4, button_height - 4) end btn_extension:SetTextColor(col_text) btn_extension:SetText(extension.name) btn_extension:SetContentAlignment(5) btn_extension.extension = extension local ic_is_selected = vgui.Create("DImage", btn_extension) ic_is_selected:SetSize(button_height, button_height) ic_is_selected:SetPos(0, 0) if extension.is_enabled then ic_is_selected:SetMaterial(ic_selected) else ic_is_selected:SetMaterial(ic_not_selected) end btn_extension.DoClick = function() local extension = btn_extension.extension if extension.is_enabled then PAM.DisableExtension(extension) ic_is_selected:SetMaterial(ic_not_selected) else PAM.EnableExtension(extension) ic_is_selected:SetMaterial(ic_selected) end end end self:MakePopup() self:SetKeyboardInputEnabled(false) end derma.DefineControl("pam_extension_manager", "", PANEL, "DFrame")
require 'nn' require 'rnn' require 'hdf5' g = hdf5.open("data/chorales_rnn.hdf5") Xtrain, ytrain, Xtest, ytest = {}, {}, {}, {} num_train, num_dev, num_test = 260, 32, 33 for i = 1, num_train do Xtrain[i] = g:read(string.format('train/chorale%d_X', i-1)):all()[{ {}, {1, 10} }]:t() ytrain[i] = g:read(string.format('train/chorale%d_y', i-1)):all() end for i = 1, num_dev do Xtrain[i + num_train] = g:read(string.format('dev/chorale%d_X', i-1)):all()[{ {}, {1, 10} }]:t() ytrain[i + num_train] = g:read(string.format('dev/chorale%d_y', i-1)):all() end for i = 1, num_test do Xtest[i] = g:read(string.format('test/chorale%d_X', i-1)):all()[{ {}, {1, 10} }]:t() ytest[i] = g:read(string.format('test/chorale%d_y', i-1)):all() end metadata = g:read("metadata"):all() g:close() -- hyper-parameters d = 200 nY = metadata[1] nV = metadata[2] rho = metadata[3] wsz = 4 -- window size lr = 0.01 -- Build LSTM -- lstm = nn.Sequential() :add(nn.LookupTable(nV, d)) :add(nn.Sum(1)) :add(nn.SplitTable(1)) :add(nn.Sequencer(nn.FastLSTM(d,d))) :add(nn.Sequencer(nn.Dropout(0.5))) :add(nn.Sequencer(nn.FastLSTM(d,d))) -- :add(nn.Sequencer(nn.Dropout(0.5))) -- :add(nn.Sequencer(nn.FastLSTM(d,d))) :add(nn.Sequencer(nn.Linear(d, nY))) :add(nn.Sequencer(nn.LogSoftMax())) lstm:remember('both') print(lstm) -- build criterion criterion = nn.SequencerCriterion(nn.ClassNLLCriterion()) -- TRAIN -- lstm:reset() lstm:training() last_score = 9999 for epoch = 1, 100 do nll_epoch = 0 for i = 1, num_train + num_dev do nll = 0 lstm:zeroGradParameters() X = Xtrain[i] y = ytrain[i] out = lstm:forward(X) nll = nll + criterion:forward(out, y) deriv = criterion:backward(out, y) lstm:backward(X, deriv) -- Update the parameters lstm:updateParameters(lr) nll = nll / y:size(1) nll_epoch = nll_epoch + nll end nll_epoch = nll_epoch / (num_train + num_dev) print("Epoch: ", epoch, nll_epoch) if nll_epoch > last_score then break end last_score = nll_epoch end -- TEST -- function eval(Xt, yt) lstm:evaluate() accuracies = {} for i = 1, #Xt do X = Xt[i] y = yt[i] out = lstm:forward(X) pred = {} seq_end = 0 for j = 1, y:size(1) do if y[j] == nY then seq_end = j - 1 break end _, argmax = torch.max(out[j], 1) pred[j] = argmax[1] end if seq_end == 0 then seq_end = y:size(1) end accuracies[i] = torch.mean(torch.eq(torch.IntTensor(pred), y:narrow(1,1,seq_end)):double()) print(string.format("Chorale accuracy:\t%d\t%.2f%%", i, accuracies[i] * 100)) end print(string.format("OVERALL ACCURACY: \t%.3f%%", torch.mean(torch.Tensor(accuracies)) * 100)) end eval(Xtest, ytest) eval(Xtrain, ytrain)
local config = { formatting = { typescript = { cmd = [[ :norm! gg=G ]], }, lua = { -- cmd = [[ !stylua % ]], }, }, code_generation = { typescript = { extract_function = function(opts) return { create = string.format( [[ function %s(%s) { %s return %s } ]], opts.name, table.concat(opts.args, ", "), type(opts.body) == "table" and table.concat(opts.body, "\n") or opts.body, opts.ret ), -- TODO: OBVI THIS NEEDS TO BE DIFFERENT... call = string.format( "const %s = %s(%s)", opts.ret, opts.name, table.concat(opts.args, ", ") ), } end, }, lua = { extract_function = function(opts) return { create = string.format( [[ local function %s(%s) %s return %s end ]], opts.name, table.concat(opts.args, ", "), type(opts.body) == "table" and table.concat(opts.body, "\n") or opts.body, opts.ret ), call = string.format( "local %s = %s(%s)", opts.ret, opts.name, table.concat(opts.args, ", ") ), } end, }, }, } local M = {} function M.get_config() return config end function M.setup(config) -- TODO: TJ fill this in... end return M
-- scaffold geniefile for Cinder Cinder_script = path.getabsolute(path.getdirectory(_SCRIPT)) Cinder_root = path.join(Cinder_script, "Cinder") Cinder_includedirs = { path.join(Cinder_script, "config"), Cinder_root, } Cinder_libdirs = {} Cinder_links = {} Cinder_defines = {} ---- return { _add_includedirs = function() includedirs { Cinder_includedirs } end, _add_defines = function() defines { Cinder_defines } end, _add_libdirs = function() libdirs { Cinder_libdirs } end, _add_external_links = function() links { Cinder_links } end, _add_self_links = function() links { "Cinder" } end, _create_projects = function() project "Cinder" kind "StaticLib" language "C++" flags {} includedirs { Cinder_includedirs, } defines {} files { path.join(Cinder_script, "config", "**.h"), path.join(Cinder_root, "**.h"), path.join(Cinder_root, "**.cpp"), } end, -- _create_projects() } ---
-- local pattern_time = require("pattern") local Grid_={} function Grid_:new(args) local m=setmetatable({},{__index=Grid_}) local args=args==nil and {} or args -- initiate the grid m.g=grid.connect() m.g.key=function(x,y,z) if m.grid_on then m:grid_key(x,y,z) end end print("grid columns: "..m.g.cols) -- setup visual m.visual={} m.grid_width=16 for i=1,8 do m.visual[i]={} for j=1,m.grid_width do m.visual[i][j]=0 end end m.page=0 -- keep track of pressed buttons m.pressed_buttons={} -- grid refreshing m.grid_refresh=metro.init() m.grid_refresh.time=0.03 m.grid_refresh.event=function() if m.grid_on then m:grid_redraw() end end m.grid_refresh:start() -- calculate parameter ranges m.params={} for _,p in ipairs(params.params) do if p.controlspec~=nil then m.params[p.id]={min=p.controlspec.minval,max=p.controlspec.maxval} end end m:init() return m end function Grid_:init() -- define functions for pressing keys self.press_fn={} self.press_fn[0]=function(row,col) for i,ins in ipairs(INSTRUMENTS) do if row==i then local name="acid_"..ins.."_amp_scale" local b=param_to_binary(name,7) local index=8-row -- 1-7 b[index]=1-b[index] param_set_from_binary(name,b) end end end self.press_fn[1]=function(row,col) local ins=INSTRUMENTS[self.page] if row<=2 then local names={"mod1","mod2"} local name="acid_"..ins.."_"..names[row] local b=param_to_binary(name,8) b[col]=1-b[col] param_set_from_binary(name,b) elseif row>=4 then local name="acid_chord_"..(row-3) params:set(name,col) end end for i=2,3 do self.press_fn[i]=function(row,col) local ins=INSTRUMENTS[self.page] if row<=4 then local names={"n","k","mod1","mod2"} local name="acid_"..ins.."_"..names[row] local b=param_to_binary(name,8) b[col]=1-b[col] param_set_from_binary(name,b) else local names={"note","duration","amp"} local name="acid_"..ins.."_"..names[row].."_"..col params:delta(name,1) end end end for i=4,8 do self.press_fn[i]=function(row,col) local ins=INSTRUMENTS[self.page] if row<=5 then local names={"n","k","w","mod1","mod2"} local name="acid_"..ins.."_"..names[row] local b=param_to_binary(name,8) b[col]=1-b[col] param_set_from_binary(name,b) elseif row<=6 then local names={"amp"} local name="acid_"..ins.."_"..names[row].."_"..col params:delta(name,1) end end end end function Grid_:grid_key(x,y,z) self:key_press(y,x,z==1) self:grid_redraw() end function Grid_:key_press(row,col,on) if on then table.insert(self.pressed_buttons,{row=row,col=col,time=clock.get_beats()*clock.get_beat_sec(),filled=false}) else local did_remove=false for i,v in ipairs(self.pressed_buttons) do if did_remove==false and v.row==row and v.col==col then table.remove(self.pressed_buttons,i) did_remove=true end end end -- navigation on every page if row==8 then if on then if col==self.page then self.page=0 else self.page=col end end do return end end if on then self.press_fn[self.page](row,col) end end function Grid_:get_visual() local ct=clock.get_beats()*clock.get_beat_sec() -- clear visual for row=1,8 do for col=1,self.grid_width do self.visual[row][col]=self.visual[row][col]-1 if self.visual[row][col]<0 then self.visual[row][col]=0 end end end -- illuminate the page local ins=INSTRUMENTS[self.page] if self.page==0 then -- MIXER for col,ins in ipairs(INSTRUMENTS) do local name="acid_"..ins.."_amp_scale" local b=param_to_binary(name,7) for i,v in ipairs(b) do if v>0 then local row=8-i self.visual[row][col]=15 end end end elseif self.page==1 then -- CHORDS for row,name in ipairs(CHORD_ATTR) do name="acid_"..ins.."_"..name if row<=2 then local b=param_to_binary(name,8) for col,v in ipairs(b) do self.visual[row][col]=v*15 end elseif row>=4 then -- highlight each row if song.chord_progression.ix==row-3 then for col=1,8 do self.visual[row][col]=7 end end local col=params:get(name) self.visual[row][col]=15 end end elseif self.page<=3 then for row,name in ipairs(ACID_ATTR) do name="acid_"..ins.."_"..name if row<=4 then local b=param_to_binary(name,8) for col,v in ipairs(b) do self.visual[row][col]=v*15 end else for col=1,8 do self.visual[row][col]=params:get(name.."_"..col) end end end elseif self.page>=4 then for row,name in ipairs(DRUMS_ATTR) do name="acid_"..ins.."_"..name if row<=4 then local b=param_to_binary(name,8) for col,v in ipairs(b) do self.visual[row][col]=v*15 end else for col=1,8 do self.visual[row][col]=params:get(name.."_"..col) end end end end if self.page>0 then self.visual[8][self.page]=15 end -- illuminate currently pressed button for i,v in ipairs(self.pressed_buttons) do if not v.filled and v.row<8 then -- illuminate the halo local dt=v.time-ct local spread=2*dt local row_min=util.clamp(util.round(v.row-spread),1,8) local row_max=util.clamp(util.round(v.row+spread),1,8) local col_min=util.clamp(util.round(v.col-spread),1,8) local col_max=util.clamp(util.round(v.col+spread),1,8) for row=row_min,row_max do for col=col_min,col_max do local dist=math.sqrt((row-v.row)^2+(col-v.col)^2) self.visual[row][col]=math.floor(15-dist) end end self.pressed_buttons[i].filled=(row_min==1 and col_min==1 and row_max==8 and col_max==8) if self.pressed_buttons[i].filled then -- TODO: run function to clear current button print("DO SOMETHING") end end self.visual[v.row][v.col]=15 end return self.visual end function Grid_:grid_redraw() self.g:all(0) local gd=self:get_visual() local s=1 local e=self.grid_width local adj=0 for row=1,8 do for col=s,e do if gd[row][col]~=0 then self.g:led(col+adj,row,gd[row][col]) end end end self.g:refresh() end return Grid_
Citizen.CreateThread(function() local configLoaded = false while not configLoaded do Citizen.Wait(100) TAC.TriggerServerCallback('tigoanticheat:getServerConfig', function(config) TAC.Config = config configLoaded = true end) end return end)
-------------------------------- -- @module Texture2D -- @extend Ref -- @parent_module cc -------------------------------- -- @function [parent=#Texture2D] getMaxT -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#Texture2D] getStringForFormat -- @param self -- @return char#char ret (return value: char) -------------------------------- -- @overload self, cc.Image, int -- @overload self, cc.Image -- @function [parent=#Texture2D] initWithImage -- @param self -- @param #cc.Image image -- @param #int pixelformat -- @return bool#bool ret (retunr value: bool) -------------------------------- -- @function [parent=#Texture2D] getMaxS -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#Texture2D] releaseGLTexture -- @param self -------------------------------- -- @function [parent=#Texture2D] hasPremultipliedAlpha -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Texture2D] getPixelsHigh -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @overload self, int -- @overload self -- @function [parent=#Texture2D] getBitsPerPixelForFormat -- @param self -- @param #int pixelformat -- @return unsigned int#unsigned int ret (retunr value: unsigned int) -------------------------------- -- @function [parent=#Texture2D] getName -- @param self -- @return unsigned int#unsigned int ret (return value: unsigned int) -------------------------------- -- @overload self, char, cc.FontDefinition -- @overload self, char, string, float, size_table, int, int -- @function [parent=#Texture2D] initWithString -- @param self -- @param #char char -- @param #string str -- @param #float float -- @param #size_table size -- @param #int texthalignment -- @param #int textvalignment -- @return bool#bool ret (retunr value: bool) -------------------------------- -- @function [parent=#Texture2D] setMaxT -- @param self -- @param #float float -------------------------------- -- @function [parent=#Texture2D] drawInRect -- @param self -- @param #rect_table rect -------------------------------- -- @function [parent=#Texture2D] getContentSize -- @param self -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- @function [parent=#Texture2D] setAliasTexParameters -- @param self -------------------------------- -- @function [parent=#Texture2D] setAntiAliasTexParameters -- @param self -------------------------------- -- @function [parent=#Texture2D] generateMipmap -- @param self -------------------------------- -- @function [parent=#Texture2D] getDescription -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#Texture2D] getPixelFormat -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#Texture2D] setGLProgram -- @param self -- @param #cc.GLProgram glprogram -------------------------------- -- @function [parent=#Texture2D] getContentSizeInPixels -- @param self -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- @function [parent=#Texture2D] getPixelsWide -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#Texture2D] drawAtPoint -- @param self -- @param #vec2_table vec2 -------------------------------- -- @function [parent=#Texture2D] getGLProgram -- @param self -- @return GLProgram#GLProgram ret (return value: cc.GLProgram) -------------------------------- -- @function [parent=#Texture2D] hasMipmaps -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Texture2D] setMaxS -- @param self -- @param #float float -------------------------------- -- @function [parent=#Texture2D] setDefaultAlphaPixelFormat -- @param self -- @param #int pixelformat -------------------------------- -- @function [parent=#Texture2D] getDefaultAlphaPixelFormat -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#Texture2D] PVRImagesHavePremultipliedAlpha -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#Texture2D] Texture2D -- @param self return nil
-- Copyright (C) 2018-2021 by KittenOS NEO contributors -- -- Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -- THIS SOFTWARE. local function ensureMode(mode) local n = "rb" if type(mode) == "boolean" then if mode then n = "wb" end elseif type(mode) == "string" then if mode == "append" then n = "ab" else error("Invalid fmode " .. mode) end else error("Invalid fmode") end return n end local function create(dev, file, mode) local n = ensureMode(mode) local handle, r = dev.open(file, n) if not handle then return nil, r end local open = true local function closer() if not open then return end open = false pcall(function() dev.close(handle) end) end local function reader(len) if not open then return end if len == "*a" then local ch = "" local c = dev.read(handle, neo.readBufSize) while c do ch = ch .. c c = dev.read(handle, neo.readBufSize) end return ch end if type(len) ~= "number" then error("Length of read must be number or '*a'") end return dev.read(handle, len) end local function writer(txt) if not open then return end neo.ensureType(txt, "string") return dev.write(handle, txt) end local function seeker(whence, point) if not open then return end return dev.seek(handle, whence, point) end if mode == "rb" then return { close = closer, seek = seeker, read = reader }, closer else return { close = closer, seek = seeker, read = reader, write = writer }, closer end end return { ensureMode = ensureMode, create = create }
local total = 0; local forecast = 0; local period = 6; local initialized = 0; local repeatcode = 0; local numrepeats = 0; function is_leap_year(year) local ly = 0; if year % 4 == 0 then if year % 100 == 0 then if year % 400 == 0 then ly = 1; end else ly = 1; end end return ly; end function get_days(month, year) local days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } local d = days[tonumber(month)]; if tonumber(month) == 2 and is_leap_year(year) ~= 0 then d = 29; end return d; end function get_time_difference(year, month, day) local curYear = os.date('%Y'); local curMonth = os.date('%m'); local curDay = os.date('%d'); local d = day - curDay; local m = 0; if d < 0 then d = d + get_days(curMonth, curYear); m = -1; end m = m + month - curMonth; local y = 0; if m < 0 then m = m + 12; y = -1; end y = y + year - curYear; return {y, m, d} end function get_next_date(record, previousYear, previousMonth, previousDay) local originalnumber = tonumber(record:get("NUMOCCURRENCES")); -- Auto Execute User Acknowlegement required if repeatcode >= 100 then repeatcode = repeatcode - 100; end -- Auto Execute Silent mode if repeatcode >= 100 then repeatcode = repeatcode - 100; end if repeatcode ~= -1 then if repeatcode < 11 or repeatcode > 14 then numrepeats = numrepeats - 1; end end local nextDate= os.time{year=previousYear,month=previousMonth,day=previousDay} local updatedate = 0; if originalnumber == -1 then updatedate = 1; elseif numrepeats > 0 then updatedate = 1; end if updatedate ~= 0 then -- weekly if repeatcode == 1 then nextDate = os.time{year=previousYear,month=previousMonth,day=previousDay + 7} -- biweekly elseif repeatcode == 2 then nextDate = os.time{year=previousYear,month=previousMonth,day=previousDay + 14} -- month elseif repeatcode == 3 then nextDate = os.time{year=previousYear,month=previousMonth + 1,day=previousDay} -- bimonth elseif repeatcode == 4 then nextDate = os.time{year=previousYear,month=previousMonth + 2,day=previousDay} -- quarterly elseif repeatcode == 5 then nextDate = os.time{year=previousYear,month=previousMonth + 3,day=previousDay} -- half yearly elseif repeatcode == 6 then nextDate = os.time{year=previousYear,month=previousMonth + 6,day=previousDay} -- yearly elseif repeatcode == 7 then nextDate = os.time{year=previousYear + 1,month=previousMonth,day=previousDay} -- quad monthly elseif repeatcode == 8 then nextDate = os.time{year=previousYear,month=previousMonth + 4,day=previousDay} -- quad weekly elseif repeatcode == 9 then nextDate = os.time{year=previousYear,month=previousMonth,day=previousDay + 28} -- daily elseif repeatcode == 10 then nextDate = os.time{year=previousYear,month=previousMonth,day=previousDay + 1} -- repeat in X days or repeat in X months elseif repeatcode == 11 or repeatcode == 12 then if numrepeats ~= -1 then numrepeats = -1; end -- every X days elseif repeatcode == 13 then nextDate = os.time{year=previousYear,month=previousMonth,day=previousDay + numrepeats} -- every X months elseif repeatcode == 14 then nextDate = os.time{year=previousYear,month=previousMonth + numrepeats,day=previousDay} -- month last day or monthly last business day elseif repeatcode == 15 or repeatcode == 16 then local m = previousMonth + 1; local y = previousYear; if m > 12 then m = 1; y = y + 1; end nextDate = os.time{year=y,month=m,day=get_days(m, y)} -- monthly last business day if repeatcode == 16 then local n = os.date("*t", nextDate); -- Sunday if n.wday == 0 then nextDate = os.time{year=n.year,month=n.month,day=n.day - 2} -- Saturday elseif n.wday == 7 then nextDate = os.time{year=n.year,month=n.month,day=n.day - 1} end end end end local next = os.date("*t", nextDate); return {next.year, next.month, next.day} end function handle_record(record) if initialized == 0 then total = record:get("BALANCE"); forecast= total; initialized = 1; end repeatcode = tonumber(record:get("REPEATS")); numrepeats = record:get("NUMOCCURRENCES"); local amount = record:get("TRANSAMOUNT"); local nextDate = record:get("NEXTOCCURRENCEDATE"); local nextYear = tonumber(string.sub(nextDate,1,4)); local nextMonth = tonumber(string.sub(nextDate,6, 7)); local nextDay = tonumber(string.sub(nextDate,9)); local timediff = get_time_difference(nextYear, nextMonth, nextDay); while (nextYear == tonumber(os.date('%Y'))) do forecast = forecast + amount; local next = get_next_date(record, nextYear, nextMonth, nextDay); if next[1] == nextYear and next[2] == nextMonth and next[3] == nextDay then break; end nextYear = next[1]; nextMonth = next[2]; nextDay = next[3]; end end function complete(result) local curYear = os.date('%Y'); local curMonth = os.date('%m'); local curDay = os.date('%d'); result:set("Current_Total", total); result:set("Projected", forecast); end