content
stringlengths 5
1.05M
|
|---|
local skynet = require "skynet"
local log = require "log"
local env = require "faci.env"
local libcenter = require "libcenter"
local libdbproxy = require "libdbproxy"
local runconf = require(skynet.getenv("runconfig"))
local games_common = runconf.games_common
local libmodules = {}
--local function init_modules()
-- setmetatable(libmodules, {
-- __index = function(t, k)
-- local mod = games_common[k]
-- if not mod then
-- return nil
-- end
-- local v = require(mod)
-- t[k] = v
-- return v
-- end
-- })
--end
--init_modules() -- local libmove = require "libmove"
local M = env.dispatch
local service = env.service
local room_id = nil --房间id
local create_id = nil
local lib = nil
local cur_game=nil
local function cal_lib()
return require "libroom"
end
function M.create_room(msg)
lib = cal_lib(msg.game)
if not lib then
ERROR("game not found: ", msg.game)
msg.error = "game not found"
return
end
create_id = libdbproxy.inc_room()
--create_id=1000000
local res, addr, roomInfo = lib.create(create_id, msg.game)
local roomAddr = roomInfo.addr
service[create_id] = {
id = 'request',
adress = roomAddr
}
local player = env.get_agent()
player.ext_info.room_id = create_id
msg.result = 0
msg.room_id = create_id
return msg
end
function M.enter_room(msg)
if room_id then
INFO("enter room fail, already in room")
return msg
end
if not lib then
lib=cal_lib(msg.game)
end
--暂时 这样处理
--if not msg.id and create_id then
-- msg.id = create_id
--end
--msg.id=1000000
msg.id = tonumber(msg.id)
if not msg.id then
ERROR("enter room msg.id is nil")
msg.error="msg.id is nil"
msg.result=-1
return msg
end
local data = {
uid = env.get_agent().base_info.uid,
agent = skynet.self(),
--node = node,
}
local isok, forward, roomInfo = lib.enter(msg.id, data)
if isok then
cur_game=msg.game
msg.result = 0
room_id = msg.id
local player = env.get_agent()
player.ext_info.room_id = room_id
service[room_id] = {
id = 'request',
adress = roomInfo.addr
}
else
if forward then
msg.code=forward
end
msg.result = 1
end
return msg
end
function M.leave_room(msg)
if not room_id then
msg.error="not found room"
msg.result=-1
return
end
if not lib then
lib=cal_lib(msg.game)
end
local uid = env.get_agent().base_info.uid
if lib.leave(room_id, uid) then
service[room_id] = nil
room_id = nil
local player = env.get_agent()
player.ext_info.room_id = 0
end
msg.result=0
return msg
end
--踢人或掉线时,对房间的清理操作
function M.kick_room()
if not room_id then
DEBUG("kick room,room id is nil")
return
end
if not lib and cur_game then
lib=cal_lib(cur_game)
end
local uid = env.get_agent().base_info.uid
if lib.leave(room_id,uid) then
service[room_id] = nil
room_id = nil
local player = env.get_agent()
player.ext_info.room_id = 0
--DEBUG("kick room,uid:"..uid)
end
end
|
local require = require
local cjson = require("cjson")
local tools = require("wtf.core.tools")
local Object = require("wtf.core.classes.object")
local configurable_object = Object:extend()
function configurable_object:set_policy(object_policy)
self.policy = object_policy
return self
end
function configurable_object:get_policy()
return self.policy
end
function configurable_object:get_mandatory_parameter(option_name)
local policy = self:get_policy()
local caller_name = self.name or "unknown object"
local err = tools.error
if policy == nil then
err("Cannot get mandatory option '"..option_name.."' for '"..caller_name.."' because policy is empty")
return nil
elseif policy[option_name] == nil then
caller_name = policy['name'] or caller_name
err("Cannot get mandatory option '"..option_name.."' for '"..caller_name.."' because attribute is empty")
return nil
else
return policy[option_name]
end
end
function configurable_object:get_optional_parameter(option_name)
local policy = self:get_policy()
local caller_name = self.name or "unknown object"
local notice = tools.notice
if policy == nil then
notice("Cannot get optional parameter '"..option_name.."' for '"..caller_name.."' because policy is empty")
return nil
elseif policy[option_name] == nil then
caller_name = policy['name'] or caller_name
notice("Cannot get optional parameter '"..option_name.."' for '"..caller_name.."' because attribute is empty")
return nil
else
return policy[option_name]
end
end
function configurable_object:__to_string()
return cjson.encode(self.policy)
end
function configurable_object:_init(...)
local select = select
local object_policy = select(1, ...)
if object_policy == nil then
self:set_policy({})
else
self:set_policy(object_policy)
end
end
return configurable_object
|
--[[
Lettersmith Serialization
Serialization plugin for Lettersmith. Useful for debugging.
Two functions are provided:
serialize(info_string, predicate, write_fn)
This function takes three arguments:
- `info_string`: to be written at the top of each serialization (default: "")
- `predicate`: a predicate function (default: return true)
OR the number of docs that should be serialized (the first `predicate` docs)
- `write_fn`: function that is called with the serialized doc string as
argument (default: io.write).
This function returns a transformer that serializes and writes the documents
that pass `predicate`, but does not change them.
get_serialize_diff()
This returns a stateful serialize_diff function which serializes only the
difference between the current doc table and the one in the previous use of
this serialize_diff in the pipeline. To do this, it keeps track of the
previous doc. In addition to the arguments of the serialize function, it
takes an optional `reset` flag (default: false) to indicate the end of the
pipeline, in which case its state is reset _after_ the write.
Example usage:
-- [...]
local serialize = require("lettersmith.serialization").serialize
local diff = require("lettersmith.serialization").get_serialize_diff()
local paths = lettersmith.paths("raw")
local gen = comp(serialize("final_doc = "),
render_permalinks(":slug"),
render_mustache("templates/page.html"),
diff("diff_markdown_and_hash = ",nil,nil,true),
markdown,
hash,
diff("beginning = "),
docs)
lettersmith.build("www", gen(paths))
--]]
local exports = {}
local map = require("lettersmith.transducers").map
local transformer = require("lettersmith.lazy").transformer
local serpent = require("serpent")
local serpent_opts = {comment=false, nocode=true,}
local function allpass() return true end
-- If `predicate` is a number, `make_predicate` returns a function that
-- counts down from `predicate` and returns true `predicate` times.
-- Otherwise, return `predicate`, or if this is falsy, return allpass.
local function make_predicate(predicate)
if type(predicate)=="number" then
return function()
predicate = predicate-1
return predicate>=0
end
end
return predicate or allpass
end
local function serialize(info_string, predicate, write_fn)
info_string = info_string or ""
predicate = make_predicate(predicate)
write_fn = write_fn or io.write
return transformer(map(function(doc)
if predicate(doc) then
write_fn(info_string,serpent.block(doc,serpent_opts).."\n")
end
return doc
end))
end
exports.serialize = serialize
-- `diff` returns a table which summarizes the differences between t1 and t2.
local function diff(t1,t2)
local t_diff = {}
for k,v in pairs(t2) do
if v~=t1[k] then
t_diff[k]=v
end
end
for k in pairs(t1) do
if not t2[k] then
t_diff[k]= "<removed>"
end
end
return t_diff
end
-- Get a stateful function for serializing diffs.
local function get_serialize_diff()
local doc_prev = {}
return function(info_string, predicate, write_fn, reset)
info_string = info_string or ""
predicate = make_predicate(predicate)
write_fn = write_fn or io.write
return transformer(map(function(doc)
if predicate(doc) then
local doc_diff = diff(doc_prev,doc)
write_fn(info_string,serpent.block(doc_diff,serpent_opts).."\n")
doc_prev = doc
end
if reset then doc_prev = {} end
return doc
end))
end
end
exports.get_serialize_diff = get_serialize_diff
return exports
|
-- Copyright (c) 2018 Redfern, Trevor <trevorredfern@gmail.com>
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
local tiny = require "ext.tiny-ecs"
local List = require "ext.artemis.src.list"
local EntityTracker = tiny.system()
EntityTracker.filter = tiny.requireAny("entity_type")
EntityTracker.entity_types = {}
function EntityTracker:onAdd(e)
if e.entity_type then
self:track_entity_type(e)
end
end
function EntityTracker:find_entity_type(entity_type)
return self.entity_types[entity_type] or {}
end
function EntityTracker:track_entity_type(e)
if not self.entity_types[e.entity_type] then
self.entity_types[e.entity_type] = List:new()
end
self.entity_types[e.entity_type]:add(e)
end
return EntityTracker
|
----------------------------------------------------------------------------------
--- Total RP 3
--- Directory : main API
--- ---------------------------------------------------------------------------
--- Copyright 2014 Sylvain Cossement (telkostrasz@telkostrasz.be)
--- Copyright 2014-2019 Renaud "Ellypse" Parize <ellypse@totalrp3.info> @EllypseCelwe
---
--- Licensed under the Apache License, Version 2.0 (the "License");
--- you may not use this file except in compliance with the License.
--- You may obtain a copy of the License at
---
--- http://www.apache.org/licenses/LICENSE-2.0
---
--- Unless required by applicable law or agreed to in writing, software
--- distributed under the License is distributed on an "AS IS" BASIS,
--- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
--- See the License for the specific language governing permissions and
--- limitations under the License.
----------------------------------------------------------------------------------
local Directory = {};
AddOn_TotalRP3.Directory = Directory;
-- Public accessor
TRP3_API.register = {
inits = {},
player = {},
ui = {},
companion = {},
NOTIFICATION_ID_NEW_CHARACTER = "add_character",
};
TRP3_API.register.MENU_LIST_ID = "main_30_register";
TRP3_API.register.MENU_LIST_ID_TAB = "main_31_";
-- imports
local Ellyb = TRP3_API.Ellyb;
local Globals = TRP3_API.globals;
local Utils = TRP3_API.utils;
local loc = TRP3_API.loc;
local log = Utils.log.log;
local buildZoneText = Utils.str.buildZoneText;
local getUnitID = Utils.str.getUnitID;
local Config = TRP3_API.configuration;
local registerConfigKey = Config.registerConfigKey;
local getConfigValue = Config.getValue;
local Events = TRP3_API.events;
local assert, tostring, wipe, pairs, tinsert = assert, tostring, wipe, pairs, tinsert;
local registerMenu, selectMenu = TRP3_API.navigation.menu.registerMenu, TRP3_API.navigation.menu.selectMenu;
local registerPage, setPage = TRP3_API.navigation.page.registerPage, TRP3_API.navigation.page.setPage;
local getCurrentContext, getCurrentPageID = TRP3_API.navigation.page.getCurrentContext, TRP3_API.navigation.page.getCurrentPageID;
local showCharacteristicsTab, showAboutTab, showMiscTab, showNotesTab;
local get = TRP3_API.profile.getData;
local type = type;
local showAlertPopup = TRP3_API.popup.showAlertPopup;
-- Saved variables references
local profiles, characters;
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- SCHEMA
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
TRP3_API.register.registerInfoTypes = {
CHARACTERISTICS = "characteristics",
ABOUT = "about",
MISC = "misc",
NOTES = "notes",
CHARACTER = "character",
}
local registerInfoTypes = TRP3_API.register.registerInfoTypes;
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- Tools
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
local function getProfileOrNil(profileID)
return profiles[profileID];
end
TRP3_API.register.getProfileOrNil = getProfileOrNil;
local function getProfile(profileID)
assert(profiles[profileID], "Unknown profile ID: " .. tostring(profileID));
return getProfileOrNil(profileID);
end
TRP3_API.register.getProfile = getProfile;
local function deleteProfile(profileID, dontFireEvents)
assert(profiles[profileID], "Unknown profile ID: " .. tostring(profileID));
-- Unbound characters from this profile
if profiles[profileID].link then
for characterID, _ in pairs(profiles[profileID].link) do
if characters[characterID] and characters[characterID].profileID == profileID then
characters[characterID].profileID = nil;
end
end
end
-- Deleting a profile should clear the local MSP knowledge of it,
-- otherwise things get out of sync if the profile comes through again
-- after deletion. For compatibility we'll still emit the table of owners.
local mspOwners;
if profiles[profileID].msp then
for ownerID, _ in pairs(profiles[profileID].link) do
msp.char[ownerID] = nil;
-- No need to build the owner table if we ain't gonna emit it.
if not dontFireEvents then
mspOwners = mspOwners or {};
tinsert(mspOwners, ownerID);
end
end
end
wipe(profiles[profileID]);
profiles[profileID] = nil;
if not dontFireEvents then
Events.fireEvent(Events.REGISTER_DATA_UPDATED, nil, profileID, nil);
Events.fireEvent(Events.REGISTER_PROFILE_DELETED, profileID, mspOwners);
end
end
TRP3_API.register.deleteProfile = deleteProfile;
local function deleteCharacter(unitID)
assert(characters[unitID], "Unknown unitID: " .. tostring(unitID));
if characters[unitID].profileID and profiles[characters[unitID].profileID] and profiles[characters[unitID].profileID].link then
profiles[characters[unitID].profileID].link[unitID] = nil;
end
wipe(characters[unitID]);
characters[unitID] = nil;
end
TRP3_API.register.deleteCharacter = deleteCharacter;
local function isUnitIDKnown(unitID)
assert(unitID, "Nil unitID");
return characters[unitID] ~= nil;
end
TRP3_API.register.isUnitIDKnown = isUnitIDKnown;
local function hasProfile(unitID)
assert(isUnitIDKnown(unitID), "Unknown character: " .. tostring(unitID));
return characters[unitID].profileID;
end
TRP3_API.register.hasProfile = hasProfile;
local function profileExists(unitID)
return hasProfile(unitID) and profiles[characters[unitID].profileID];
end
TRP3_API.register.profileExists = profileExists;
local function createUnitIDProfile(unitID)
assert(characters[unitID].profileID, "UnitID don't have a profileID: " .. unitID);
assert(not profiles[characters[unitID].profileID], "Profile already exist: " .. characters[unitID].profileID);
profiles[characters[unitID].profileID] = {};
profiles[characters[unitID].profileID].link = {};
return profiles[characters[unitID].profileID];
end
TRP3_API.register.createUnitIDProfile = createUnitIDProfile;
local function getUnitIDProfile(unitID)
assert(profileExists(unitID), "No profile for character: " .. tostring(unitID));
return profiles[characters[unitID].profileID], characters[unitID].profileID;
end
TRP3_API.register.getUnitIDProfile = getUnitIDProfile;
local function getUnitIDProfileID(unitID)
return characters[unitID] and characters[unitID].profileID;
end
TRP3_API.register.getUnitIDProfileID = getUnitIDProfileID;
local function getUnitIDCharacter(unitID)
assert(isUnitIDKnown(unitID), "Unknown character: " .. tostring(unitID));
return characters[unitID];
end
TRP3_API.register.getUnitIDCharacter = getUnitIDCharacter;
function TRP3_API.register.isUnitKnown(targetType)
return isUnitIDKnown(getUnitID(targetType));
end
---
-- Check if the content of a unit ID should be filtered because it contains mature content
-- @param unitID Unit ID of the player to test
--
local function unitIDIsFilteredForMatureContent(unitID)
if not TRP3_API.register.mature_filter or not unitID or unitID == Globals.player_id or not isUnitIDKnown(unitID) or not profileExists(unitID) then return false end ;
local profile = getUnitIDProfile(unitID);
local profileID = getUnitIDProfileID(unitID);
-- Check if the profile has been flagged as containing mature content, that the option to filter such content is enabled
-- and that the profile is not in the pink list.
return profile.hasMatureContent and getConfigValue("register_mature_filter") and not (TRP3_API.register.mature_filter.isProfileWhitelisted(profileID))
end
TRP3_API.register.unitIDIsFilteredForMatureContent = unitIDIsFilteredForMatureContent;
local function profileIDISFilteredForMatureContent (profileID)
if not TRP3_API.register.mature_filter then return false end ;
local profile = getProfileOrNil(profileID);
return profile and profile.hasMatureContent and not TRP3_API.register.mature_filter.isProfileWhitelisted(profileID);
end
TRP3_API.register.profileIDISFilteredForMatureContent = profileIDISFilteredForMatureContent;
---
-- Check if the content of the profile of the unit ID is flagged as containing mature content
-- @param unitID Unit ID of the player to test
--
local function unitIDIsFlaggedForMatureContent(unitID)
if not TRP3_API.register.mature_filter or not unitID or unitID == Globals.player_id or not isUnitIDKnown(unitID) or not profileExists(unitID) then return false end ;
local profile = getUnitIDProfile(unitID);
-- Check if the profile has been flagged as containing mature content, that the option to filter such content is enabled
-- and that the profile is not in the pink list.
return profile.hasMatureContent
end
TRP3_API.register.unitIDIsFlaggedForMatureContent = unitIDIsFlaggedForMatureContent;
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- Main data management
-- For decoupling reasons, the saved variable TRP3_Register shouln'd be used outside this file !
-- Please use all these public method instead.
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- SETTERS
--- Raises error if unknown unitName
-- Link a unitID to a profileID. This link is bidirectional.
function TRP3_API.register.saveCurrentProfileID(unitID, currentProfileID, isMSP)
local character = getUnitIDCharacter(unitID);
local oldProfileID = character.profileID;
character.profileID = currentProfileID;
-- Search if this character was bounded to another profile
for _, profile in pairs(profiles) do
if profile.link and profile.link[unitID] then
profile.link[unitID] = nil; -- unbound
end
end
if not profileExists(unitID) then
createUnitIDProfile(unitID);
end
local profile = getProfile(currentProfileID);
profile.link[unitID] = 1; -- bound
profile.msp = isMSP;
profile.time = time()
if oldProfileID ~= currentProfileID then
Events.fireEvent(Events.REGISTER_DATA_UPDATED, unitID, currentProfileID, nil);
end
end
--- Raises error if unknown unitName
function TRP3_API.register.saveClientInformation(unitID, client, clientVersion, msp, extended, trialAccount)
local character = getUnitIDCharacter(unitID);
character.client = client;
character.clientVersion = clientVersion;
character.msp = msp;
character.extended = extended;
character.isTrial = trialAccount;
end
--- Raises error if unknown unitName
local function saveCharacterInformation(unitID, race, class, gender, faction, time, zone, guild)
local character = getUnitIDCharacter(unitID);
character.class = class;
character.race = race;
character.gender = gender;
character.faction = faction;
character.guild = guild;
if hasProfile(unitID) then
local profile = getProfile(character.profileID);
profile.time = time;
profile.zone = zone;
end
end
TRP3_API.register.saveCharacterInformation = saveCharacterInformation;
local function sanitizeFullProfile(data)
if not data or not data.player then return false end
local somethingWasSanitizedInsideProfile = false;
if data.player.characteristics and TRP3_API.register.sanitizeProfile(registerInfoTypes.CHARACTERISTICS, data.player.characteristics) then
somethingWasSanitizedInsideProfile = true;
end
if data.player.character and TRP3_API.register.sanitizeProfile(registerInfoTypes.CHARACTER, data.player.character) then
somethingWasSanitizedInsideProfile = true;
end
if data.player.misc and TRP3_API.register.sanitizeProfile(registerInfoTypes.MISC, data.player.misc) then
somethingWasSanitizedInsideProfile = true;
end
return somethingWasSanitizedInsideProfile;
end
TRP3_API.register.sanitizeFullProfile = sanitizeFullProfile;
function TRP3_API.register.sanitizeProfile(informationType, data)
local somethingWasSanitizedInsideProfile = false;
if informationType == registerInfoTypes.CHARACTERISTICS then
if TRP3_API.register.ui.sanitizeCharacteristics(data) then
somethingWasSanitizedInsideProfile = true;
end
elseif informationType == registerInfoTypes.CHARACTER then
if TRP3_API.dashboard.sanitizeCharacter(data) then
somethingWasSanitizedInsideProfile = true;
end
elseif informationType == registerInfoTypes.MISC then
if TRP3_API.register.ui.sanitizeMisc(data) then
somethingWasSanitizedInsideProfile = true;
end
end
return somethingWasSanitizedInsideProfile;
end
--- Raises error if unknown unitID or unit hasn't profile ID
function TRP3_API.register.saveInformation(unitID, informationType, data)
local profile = getUnitIDProfile(unitID);
if profile[informationType] then
wipe(profile[informationType]);
end
if getConfigValue(TRP3_API.ADVANCED_SETTINGS_KEYS.PROFILE_SANITIZATION) == true then
TRP3_API.register.sanitizeProfile(informationType, data);
end
profile[informationType] = data;
Events.fireEvent(Events.REGISTER_DATA_UPDATED, unitID, hasProfile(unitID), informationType);
end
--- Raises error if KNOWN unitID
function TRP3_API.register.addCharacter(unitID)
assert(unitID and unitID:find('-'), "Malformed unitID");
assert(not isUnitIDKnown(unitID), "Already known character: " .. tostring(unitID));
characters[unitID] = {};
log("Added to the register: " .. unitID);
end
-- GETTERS
--- Raises error if unknown unitName
local function getUnitIDCurrentProfile(unitID)
assert(isUnitIDKnown(unitID), "Unknown character: " .. tostring(unitID));
if hasProfile(unitID) then
return getUnitIDProfile(unitID);
end
end
TRP3_API.register.getUnitIDCurrentProfile = getUnitIDCurrentProfile;
local function getCharacterInfoTab(unitID)
if unitID == Globals.player_id then
return get("player");
elseif isUnitIDKnown(unitID) then
return getUnitIDCurrentProfile(unitID) or {};
end
return {};
end
TRP3_API.register.getUnitIDCurrentProfileSafe = getCharacterInfoTab;
--- Raises error if unknown unitID
function TRP3_API.register.shouldUpdateInformation(unitID, infoType, version)
--- Raises error if unit hasn't profile ID or no profile exists
local profile = getUnitIDProfile(unitID);
return not profile[infoType] or not profile[infoType].v or profile[infoType].v ~= version;
end
function TRP3_API.register.getCharacterList()
return characters;
end
--- Fetch character specific data for the given character ID.
---@param characterID string The character ID (PlayerName-RealmName) that we want to query
---@return table|nil Either the character data or nil if the character was not found.
function Directory.getCharacterDataForCharacterId(characterID)
return characters[characterID]
end
--- Raises error if unknown unitID
function TRP3_API.register.getUnitIDCharacter(unitID)
if unitID == Globals.player_id then
return Globals.player_character;
end
assert(characters[unitID], "Unknown character ID: " .. tostring(unitID));
return characters[unitID];
end
function TRP3_API.register.getProfileList()
return profiles;
end
function TRP3_API.register.insertProfile(profileID, profileData)
profiles[profileID] = profileData;
end
local function getUnitRPNameWithID(unitID, unitName)
unitName = unitName or unitID;
if unitID then
if unitID == Globals.player_id then
unitName = TRP3_API.register.getPlayerCompleteName(true);
elseif isUnitIDKnown(unitID) and profileExists(unitID) then
local profile = getUnitIDProfile(unitID);
if profile.characteristics then
unitName = TRP3_API.register.getCompleteName(profile.characteristics, unitName, true);
end
end
end
return unitName;
end
TRP3_API.register.getUnitRPNameWithID = getUnitRPNameWithID;
function TRP3_API.register.getUnitRPName(targetType)
local unitName = UnitName(targetType);
local unitID = getUnitID(targetType);
return getUnitRPNameWithID(unitID, unitName);
end
TRP3_API.r.name = TRP3_API.register.getUnitRPName;
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- Tools
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
local tabGroup; -- Reference to the tab panel tabs group
local function onMouseOver()
local unitID = getUnitID("mouseover");
if unitID and isUnitIDKnown(unitID) then
local _, race = UnitRace("mouseover");
local _, class, _ = UnitClass("mouseover");
local englishFaction = UnitFactionGroup("mouseover");
saveCharacterInformation(unitID, race, class, UnitSex("mouseover"), englishFaction, time(), buildZoneText(), GetGuildInfo("mouseover"));
end
end
local function onInformationUpdated(profileID, infoType)
if getCurrentPageID() == "player_main" then
local context = getCurrentContext();
assert(context, "No context for page player_main !");
if not context.isPlayer and profileID == context.profileID then
if infoType == registerInfoTypes.ABOUT and tabGroup.current == 2 then
showAboutTab();
elseif (infoType == registerInfoTypes.CHARACTERISTICS or infoType == registerInfoTypes.CHARACTER) and tabGroup.current == 1 then
showCharacteristicsTab();
elseif infoType == registerInfoTypes.MISC and tabGroup.current == 3 then
showMiscTab();
elseif infoType == registerInfoTypes.NOTES and tabGroup.current == 4 then
showNotesTab();
end
end
end
end
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- UI: TAB MANAGEMENT
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
local function tutorialProvider()
if tabGroup then
if tabGroup.current == 2 then
return TRP3_API.register.ui.aboutTutorialProvider();
elseif tabGroup.current == 3 then
return TRP3_API.register.ui.miscTutorialProvider();
end
end
end
local function createTabBar()
local frame = CreateFrame("Frame", "TRP3_RegisterMainTabBar", TRP3_RegisterMain);
frame:SetSize(485, 30);
frame:SetPoint("TOPLEFT", 17, 0);
frame:SetFrameLevel(1);
tabGroup = TRP3_API.ui.frame.createTabPanel(frame,
{
{ loc.REG_PLAYER_CARACT, 1, 150 },
{ loc.REG_PLAYER_ABOUT, 2, 110 },
{ loc.REG_PLAYER_PEEK, 3, 130 },
{ loc.REG_PLAYER_NOTES, 4, 85 }
},
function(_, value)
-- Clear all
TRP3_RegisterCharact:Hide();
TRP3_RegisterAbout:Hide();
TRP3_RegisterMisc:Hide();
TRP3_RegisterNotes:Hide();
if value == 1 then
showCharacteristicsTab();
elseif value == 2 then
showAboutTab();
elseif value == 3 then
showMiscTab();
elseif value == 4 then
showNotesTab();
end
TRP3_API.events.fireEvent(TRP3_API.events.NAVIGATION_TUTORIAL_REFRESH, "player_main");
end,
-- Confirmation callback
function(callback)
if getCurrentContext() and getCurrentContext().isEditMode then
TRP3_API.popup.showConfirmPopup(loc.REG_PLAYER_CHANGE_CONFIRM,
function()
callback();
end);
else
callback();
end
end);
TRP3_API.register.player.tabGroup = tabGroup;
end
local function showTabs()
local context = getCurrentContext();
assert(context, "No context for page player_main !");
tabGroup:SelectTab(1);
end
function TRP3_API.register.ui.getSelectedTabIndex()
return tabGroup.current;
end
function TRP3_API.register.ui.isTabSelected(infoType)
return (infoType == registerInfoTypes.CHARACTERISTICS and tabGroup.current == 1)
or (infoType == registerInfoTypes.ABOUT and tabGroup.current == 2)
or (infoType == registerInfoTypes.MISC and tabGroup.current == 3)
or (infoType == registerInfoTypes.NOTES and tabGroup.current == 4);
end
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- CLEANUP
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
local tsize = Utils.table.size;
-- Unbound character from missing profiles
local function cleanupCharacters()
for unitID, character in pairs(characters) do
if character.profileID and (not profiles[character.profileID] or not profiles[character.profileID].link or not profiles[character.profileID].link[unitID]) then
character.profileID = nil;
end
end
for unitID, character in pairs(characters) do
if not character.profileID and not TRP3_API.register.isIDIgnored(unitID) then
wipe(character)
characters[unitID] = nil
end
end
end
local function cleanupCompanions()
local companionIDToInfo = TRP3_API.utils.str.companionIDToInfo;
local deleteCompanionProfile = TRP3_API.companions.register.deleteProfile;
local companionProfiles = TRP3_API.companions.register.getProfiles();
for companionProfileID, companionProfile in pairs(companionProfiles) do
for companionFullID, _ in pairs(companionProfile.links) do
local ownerID, _ = companionIDToInfo(companionFullID);
if not isUnitIDKnown(ownerID) or not profileExists(ownerID) then
companionProfile.links[companionFullID] = nil;
end
end
if tsize(companionProfile.links) < 1 then
log("Purging companion " .. companionProfileID .. ", no more characters linked to it.");
deleteCompanionProfile(companionProfileID, true);
end
end
end
local function cleanupPlayerRelations()
for _, myProfile in pairs(TRP3_API.profile.getProfiles()) do
for profileID, _ in pairs(myProfile.relation or {}) do
if not profiles[profileID] then
myProfile.relation[profileID] = nil;
end
end
end
end
local function cleanupProfiles()
-- Make sure profiles are always correctly formatted
if TRP3_Register and TRP3_Register.profiles then
for _, profile in pairs(TRP3_Register.profiles) do
if not profile.link then
profile.link = {};
end
end
end
log("Purging profiles with no data")
for profileID, profile in pairs(profiles) do
if not profile.characteristics or Ellyb.Tables.isEmpty(profile.characteristics) then
deleteProfile(profileID, true);
end
end
if type(getConfigValue("register_auto_purge_mode")) ~= "number" then
return ;
end
log(("Purging profiles older than %s day(s)"):format(getConfigValue("register_auto_purge_mode") / 86400));
-- First, get a tab with all profileID with which we have a relation or on which we have notes
local protectedProfileIDs = {};
for _, profile in pairs(TRP3_API.profile.getProfiles()) do
for profileID, _ in pairs(profile.relation or {}) do
protectedProfileIDs[profileID] = true;
end
for profileID, _ in pairs(profile.notes or {}) do
protectedProfileIDs[profileID] = true;
end
end
log("Protected profiles: " .. tsize(protectedProfileIDs));
local profilesToPurge = {};
for profileID, profile in pairs(profiles) do
if not protectedProfileIDs[profileID] and (not profile.time or time() - profile.time > getConfigValue("register_auto_purge_mode")) then
tinsert(profilesToPurge, profileID);
end
end
log("Profiles to purge: " .. tsize(profilesToPurge));
for _, profileID in pairs(profilesToPurge) do
deleteProfile(profileID, true);
end
end
local function cleanupMyProfiles()
local atLeastOneProfileWasSanitized = false;
-- Get the player's profiles and sanitize them, removing all invalid codes manually inserted
for _, profile in pairs(TRP3_API.profile.getProfiles()) do
if sanitizeFullProfile(profile) then
atLeastOneProfileWasSanitized = true;
end
end
if atLeastOneProfileWasSanitized then
-- Yell at the user about their mischieves
showAlertPopup(loc.REG_CODE_INSERTION_WARNING);
end
end
local function getFirstCharacterIDFromProfile(profile)
if type(profile.link) == "table" then
return next(profile.link)
end
end
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- INIT
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
function TRP3_API.register.init()
showCharacteristicsTab = TRP3_API.register.ui.showCharacteristicsTab;
showAboutTab = TRP3_API.register.ui.showAboutTab;
showMiscTab = TRP3_API.register.ui.showMiscTab;
showNotesTab = TRP3_API.register.ui.showNotesTab;
-- Init save variables
if not TRP3_Register then
TRP3_Register = {};
end
if not TRP3_Register.character then
TRP3_Register.character = {};
end
if not TRP3_Register.profiles then
TRP3_Register.profiles = {};
end
profiles = TRP3_Register.profiles;
characters = TRP3_Register.character;
-- Listen to the mouse over event
Utils.event.registerHandler("UPDATE_MOUSEOVER_UNIT", onMouseOver);
registerMenu({
id = "main_10_player",
text = loc.REG_PLAYER,
onSelected = function() selectMenu("main_12_player_character") end,
});
registerMenu({
id = "main_11_profiles",
text = loc.PR_PROFILES,
onSelected = function() setPage("player_profiles"); end,
isChildOf = "main_10_player",
});
local currentPlayerMenu = {
id = "main_12_player_character",
text = get("player/characteristics/FN") or Globals.player,
onSelected = function()
setPage("player_main", {
source = "player",
profile = get("player"),
isPlayer = true,
});
end,
isChildOf = "main_10_player",
};
registerMenu(currentPlayerMenu);
local refreshMenu = TRP3_API.navigation.menu.rebuildMenu;
Events.listenToEvent(Events.REGISTER_DATA_UPDATED, function(unitID, profileID, dataType)
onInformationUpdated(profileID, dataType);
if unitID == Globals.player_id and (not dataType or dataType == "characteristics") then
currentPlayerMenu.text = get("player/characteristics/FN") or Globals.player;
refreshMenu();
end
end);
registerPage({
id = "player_main",
templateName = "TRP3_RegisterMain",
frameName = "TRP3_RegisterMain",
frame = TRP3_RegisterMain,
onPagePostShow = function(context)
showTabs(context);
end,
tutorialProvider = tutorialProvider
});
registerConfigKey("register_auto_purge_mode", 864000);
local AUTO_PURGE_VALUES = {
{ loc.CO_REGISTER_AUTO_PURGE_0, false },
{ loc.CO_REGISTER_AUTO_PURGE_1:format(1), 86400 },
{ loc.CO_REGISTER_AUTO_PURGE_1:format(2), 86400 * 2 },
{ loc.CO_REGISTER_AUTO_PURGE_1:format(5), 86400 * 5 },
{ loc.CO_REGISTER_AUTO_PURGE_1:format(10), 86400 * 10 },
{ loc.CO_REGISTER_AUTO_PURGE_1:format(30), 86400 * 30 },
}
-- Build configuration page
TRP3_API.register.CONFIG_STRUCTURE = {
id = "main_config_register",
menuText = loc.CO_REGISTER,
pageText = loc.CO_REGISTER,
elements = {
{
inherit = "TRP3_ConfigDropDown",
widgetName = "TRP3_ConfigurationRegister_AutoPurge",
title = loc.CO_REGISTER_AUTO_PURGE,
help = loc.CO_REGISTER_AUTO_PURGE_TT,
listContent = AUTO_PURGE_VALUES,
configKey = "register_auto_purge_mode",
listCancel = true,
}
}
};
TRP3_API.events.listenToEvent(TRP3_API.events.WORKFLOW_ON_FINISH, function()
cleanupPlayerRelations();
cleanupProfiles();
cleanupCharacters();
cleanupCompanions();
cleanupMyProfiles();
Config.registerConfigurationPage(TRP3_API.register.CONFIG_STRUCTURE);
end);
if seriousDay then
registerConfigKey("rp_io", true);
tinsert(TRP3_API.register.CONFIG_STRUCTURE.elements,
{
inherit = "TRP3_ConfigCheck",
title = "RP.IO",
configKey = "rp_io",
});
end
-- Initialization
TRP3_API.register.inits.characteristicsInit();
TRP3_API.register.inits.aboutInit();
TRP3_API.register.inits.glanceInit();
TRP3_API.register.inits.miscInit();
TRP3_API.register.inits.notesInit();
TRP3_API.register.inits.dataExchangeInit();
wipe(TRP3_API.register.inits);
TRP3_API.register.inits = nil; -- Prevent init function to be called again, and free them from memory
TRP3_ProfileReportButton:SetScript("OnClick", function()
local context = TRP3_API.navigation.page.getCurrentContext();
local characterID = getFirstCharacterIDFromProfile(context.profile) or UNKNOWN;
local reportText = loc.REG_REPORT_PLAYER_OPEN_URL_160:format(characterID);
if context.profile.time then
local DATE_FORMAT = "%Y-%m-%d around %H:%M";
reportText = reportText .. "\n\n" .. loc.REG_REPORT_PLAYER_TEMPLATE_DATE:format(date(DATE_FORMAT, context.profile.time));
end
Ellyb.Popups:OpenURL("https://battle.net/support/help/product/wow/197/1501/solution", reportText);
end)
Ellyb.Tooltips.getTooltip(TRP3_ProfileReportButton):SetTitle(loc.REG_REPORT_PLAYER_PROFILE)
createTabBar();
end
local function showRPIO()
return seriousDay and getConfigValue("rp_io");
end
TRP3_API.register.showRPIO = showRPIO;
|
local UserSettings = {}
local HttpService = game:GetService("HttpService")
local Network = game.ReplicatedStorage.Network
UserSettings.Store = {}
UserSettings.Settings = {}
function UserSettings.parseJSON(player, data)
local settings = HttpService:JSONDecode(data)
UserSettings.Store[player] = settings
end
function UserSettings.getUserSettings(player)
return UserSettings.Store[player]
end
function UserSettings.defineLocalSettings(settings)
UserSettings.Settings = settings
end
function UserSettings.pushLocalUpdate()
Network.SettingsUpdate:FireServer(UserSettings.Settings)
end
function UserSettings.shouldShowDevelopmentWarning()
return UserSettings.Settings.ShowDevelopmentWarning
end
function UserSettings.dontShowDeveloptmentWarning()
UserSettings.Settings.ShowDevelopmentWarning = false
UserSettings.pushLocalUpdate()
end
function UserSettings.hasDoneTutorial()
return UserSettings.Settings.DismissedTutorial
end
function UserSettings.finishedTutorial()
UserSettings.Settings.DismissedTutorial = true
UserSettings.pushLocalUpdate()
end
return UserSettings
|
if nil ~= require then
require "fritomod/OOP-Class";
require "fritomod/ListenerList";
end;
local MouseWheelListener = OOP.Class("MouseWheelListener", ListenerList);
function MouseWheelListener:Constructor(frame)
MouseWheelListener.super.Constructor(self, "MouseWheel listener");
self.frame = frame;
self:AddInstaller(frame, "EnableMouseWheel", true);
self:AddInstaller(Callbacks.Script, self.frame, "OnMouseWheel", self, "Fire");
end;
Callbacks = Callbacks or {};
local MOUSE_WHEEL_LISTENER="__MouseWheelListener";
function Callbacks.MouseWheel(frame, func, ...)
frame = Frames.AsRegion(frame);
assert(frame.EnableMouseWheel, "Frame must support mouse wheel events");
func=Curry(func, ...);
if not frame[MOUSE_WHEEL_LISTENER] then
frame[MOUSE_WHEEL_LISTENER] = MouseWheelListener:New(frame);
end;
return frame[MOUSE_WHEEL_LISTENER]:Add(func);
end;
|
require "nn"
--[[
Spatial Pyramid Pooling layer.
Applies a Max Pooling operation at different window sizes and strides,
and then concatenates together all the outputs. The advantage is that
the output size is the same regardless of the input size.
Example:
VGG16 last convolutional feature maps have shape Nx512x14x14.
By using a 4-levels Spatial Pyramid Pooling with levels 4x4, 3x3, 2x2, 1x1
The output will have shape N x 15360, where
15360 = (4*4*512) + (3*3*512) + (2*2*512) + 512.
This remains true also in the case of feature maps different from 14x14.
]]--
local SpatialPyramidPooling, Parent = torch.class('nn.SpatialPyramidPooling', 'nn.Concat')
function SpatialPyramidPooling:__init(...)
--[[
Parameters
----------
levels : tables
Ex: SpatialPyramidPooling({4, 4}, {3, 3}) for a pyramid with two
levels: 4x4 and 3x3
]]--
Parent.__init(self, 2)
local args = {...}
for k, v in ipairs(args) do
Parent.add(self, nn.Sequential()
:add(nn.SpatialAdaptiveMaxPooling(v[1], v[2]))
:add(nn.View(-1):setNumInputDims(3))
:add(nn.Contiguous()))
end
end
function SpatialPyramidPooling:updateOutput(input)
--[[
Parameters
----------
input : 3D or 4D Tensor
Convolutional feature maps
Returns
-------
3D or 4D Tensor
Spatial Pyramid Pooling operation output
]]--
return Parent.updateOutput(self, input)
end
function SpatialPyramidPooling:updateGradInput(input, gradOutput)
--[[
Parameters
----------
input : 2D fully-connected features (num_samples x num_features)
gradOutput : gradient wrt to module's output.
]]--
return Parent.updateGradInput(self, input, gradOutput)
end
|
require('settings')
require('mappings')
require('packer-config')
require('colorschemes-config.catppuccin')
require('nvim-treesitter-config')
require('nvim-tree-config')
require('lsp-config.language-servers')
require('lsp-config.nvim-cmp')
require('statusline-config.lualine')
require('telescope-config')
require('barbar-config')
require('run-config.code_runner')
require('run-config.debugger')
require('neoscroll-config')
|
vim.cmd([[
autocmd BufNewFile,BufRead *.py noremap <F5> :!python3 % ; echo "" ; read<enter>
autocmd BufNewFile,BufRead *.rb noremap <F5> :!ruby % ; echo "" ; read<enter>
autocmd BufNewFile,BufRead *.lisp noremap <F5> :!clisp % ; echo "" ; read<enter>
autocmd BufNewFile,BufRead *.cpp noremap <F5> :!fname=$(mktemp); g++ % -o $fname; echo ""; $fname; rm $fname ; read<enter>
autocmd BufNewFile,BufRead *.tex noremap <F5> :!pdflatex % ; pdflatex %; read<enter>
autocmd BufNewFile,BufRead *.hs noremap <F5> :!ghc %; echo "" ; ./%:r; rm %:r; echo ""; read<enter>
autocmd BufNewFile,BufRead *.cs noremap <F5> :!dotnet run ; read<enter>
autocmd BufNewFile,BufRead *.sh noremap <F5> :!./% ; echo "" ; read<enter>
autocmd BufNewFile,BufRead *.pl noremap <F5> :!perl -w % ; echo "" ; read<enter>
"autocmd BufNewFile,BufRead *.cr noremap <F5> :!shards build%; ../bin/main; echo ""; read<enter>
autocmd BufNewFile,BufRead *.cr noremap <F5> :!crystal r --no-color % ; echo ""; read<enter>
autocmd BufNewFile,BufRead *.rs noremap <F5> :!cargo run ; read<enter>
autocmd BufNewFile,BufRead *.rs noremap <F6> :!fname=$(mktemp); rustc % -o $fname; echo ""; $fname; rm $fname; read<enter>
autocmd BufNewFile,BufRead *.rs noremap <F8> :!cargo clippy --fix; read<enter>
autocmd BufNewFile,BufRead *.nim noremap <F5> :!nimble dev ; echo ""; read<enter>
autocmd BufNewFile,BufRead *.nim noremap <F6> :!nimble run ; echo ""; read<enter>
autocmd BufNewFile,BufRead *.nim noremap <F7> :!nim r % ; echo ""; read<enter>
autocmd BufNewFile,BufRead *.go noremap <F5> :!go run . ; echo ""; read<enter>
autocmd BufNewFile,BufRead *.go noremap <F6> :!go run % ; echo ""; read<enter>
autocmd BufNewFile,BufRead *.js noremap <F5> :!node % ; echo ""; read<enter>
autocmd BufNewFile,BufRead *.js noremap <F6> :!npm run dev % ; echo ""; read<enter>
autocmd BufNewFile,BufRead *.gd nnoremap <buffer> <F4> :GodotRunLast<CR>
autocmd BufNewFile,BufRead *.gd nnoremap <buffer> <F5> :GodotRun<CR>
autocmd BufNewFile,BufRead *.gd nnoremap <buffer> <F6> :GodotRunCurrent<CR>
autocmd BufNewFile,BufRead *.gd nnoremap <buffer> <F7> :GodotRunFZF<CR>
" Only for rust development
autocmd BufNewFile,BufRead *.html noremap <F5> :!cargo run ; echo ""; read<enter>
autocmd BufNewFile,BufRead *.css noremap <F5> :!cargo run ; echo ""; read<enter>
]])
|
--------------------------------------------------------------------------------
-- Module Declaration
--
local mod, CL = BigWigs:NewBoss("Houndmaster Braun", 1001, 660)
if not mod then return end
mod:RegisterEnableMob(59303)
--------------------------------------------------------------------------------
-- Locals
--
local nextCallDogs = 90
--------------------------------------------------------------------------------
-- Initialization
--
function mod:GetOptions()
return {
-5611, -- Bloody Rage
114259, -- Call Dog
}
end
function mod:OnBossEnable()
self:Log("SPELL_AURA_APPLIED", "BloodyRage", 116140)
self:Log("SPELL_CAST_SUCCESS", "CallDog", 114259)
self:RegisterEvent("INSTANCE_ENCOUNTER_ENGAGE_UNIT", "CheckBossStatus")
self:Death("Win", 59303)
end
function mod:OnEngage()
self:RegisterUnitEvent("UNIT_HEALTH_FREQUENT", "RageWarn", "boss1")
nextCallDogs = 90
end
--------------------------------------------------------------------------------
-- Event Handlers
--
function mod:CallDog(args)
self:Message(args.spellId, "orange", "Alert", CL.percent:format(nextCallDogs, args.spellName))
nextCallDogs = nextCallDogs - 10
end
function mod:BloodyRage(args)
self:Message(-5611, "yellow", "Alert", CL.percent:format(50, args.spellName), args.spellId)
end
function mod:RageWarn(event, unitId)
local hp = UnitHealth(unitId) / UnitHealthMax(unitId) * 100
if hp < 55 then
self:UnregisterUnitEvent(event, unitId)
self:Message(-5611, "green", "Info", CL["soon"]:format(self:SpellName(116140)), false) -- Bloody Rage
end
end
|
require 'image'
dir = require 'pl.dir'
trainLoader = {}
local alphabet = "abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\"/\\|_@#$%^&*~`+-=<>()[]{} "
local dict = {}
for i = 1,#alphabet do
dict[alphabet:sub(i,i)] = i
end
ivocab = {}
for k,v in pairs(dict) do
ivocab[v] = k
end
alphabet_size = #alphabet
function decode(txt)
local str = ''
for w_ix = 1,txt:size(1) do
local ch_ix = txt[w_ix]
local ch = ivocab[ch_ix]
if (ch ~= nil) then
str = str .. ch
end
end
return str
end
function trainLoader:decode2(txt)
local str = ''
_, ch_ixs = txt:max(2)
for w_ix = 1,txt:size(1) do
local ch_ix = ch_ixs[{w_ix,1}]
local ch = ivocab[ch_ix]
if (ch ~= nil) then
str = str .. ch
end
end
return str
end
trainLoader.alphabet = alphabet
trainLoader.alphabet_size = alphabet_size
trainLoader.dict = dict
trainLoader.ivocab = ivocab
trainLoader.decode = decoder
local files = {}
local size = 0
cur_files = dir.getfiles(opt.data_root)
size = size + #cur_files
--------------------------------------------------------------------------------------------
local loadSize = {3, opt.loadSize}
local sampleSize = {3, opt.fineSize}
local function loadImage(path)
local input = image.load(path, 3, 'float')
input = image.scale(input, loadSize[2], loadSize[2])
return input
end
-- function to load the image, jitter it appropriately (random crops etc.)
local trainHook = function(path)
collectgarbage()
local input = loadImage(path)
if opt.no_aug == 1 then
return image.scale(input, sampleSize[2], sampleSize[2])
end
local iW = input:size(3)
local iH = input:size(2)
-- do random crop
local oW = sampleSize[2];
local oH = sampleSize[2]
local h1 = math.ceil(torch.uniform(1e-2, iH-oH))
local w1 = math.ceil(torch.uniform(1e-2, iW-oW))
local out = image.crop(input, w1, h1, w1 + oW, h1 + oH)
assert(out:size(2) == oW)
assert(out:size(3) == oH)
-- do hflip with probability 0.5
if torch.uniform() > 0.5 then out = image.hflip(out); end
-- rotation
if opt.rot_aug then
local randRot = torch.rand(1)*0.16-0.08
out = image.rotate(out, randRot:float()[1], 'bilinear')
end
out:mul(2):add(-1) -- make it [0, 1] -> [-1, 1]
return out
end
function try(f, catch_f)
local status, exception = pcall(f)
if not status then
catch_f(exception)
end
end
function trainLoader:sample(quantity)
local ix_file1 = torch.Tensor(quantity)
local ix_file2 = torch.Tensor(quantity)
for n = 1, quantity do
local samples = torch.randperm(#cur_files):narrow(1,1,2)
local file_ix1 = samples[1]
local file_ix2 = samples[2]
ix_file1[n] = file_ix1
ix_file2[n] = file_ix2
end
local data_img1 = torch.zeros(quantity, sampleSize[1], sampleSize[2], sampleSize[2]) -- real
local data_img2 = torch.zeros(quantity, sampleSize[1], sampleSize[2], sampleSize[2]) -- mismatch
local data_txt1 = torch.zeros(quantity, opt.txtSize) -- real
for n = 1, quantity do
-- robust loading of files.
local loaded = false
local info1, info2
while not loaded do
try(function()
local t7file1 = cur_files[ix_file1[n]]
info1 = torch.load(t7file1)
local t7file2 = cur_files[ix_file2[n]]
info2 = torch.load(t7file2)
loaded = true
end, function (e)
print(e)
print(cur_files[ix_file1[n]])
print(cur_files[ix_file2[n]])
local samples = torch.randperm(#cur_files):narrow(1,1,2)
local file_ix1 = samples[1]
local file_ix2 = samples[2]
ix_file1[n] = file_ix1
ix_file2[n] = file_ix2
end)
end
local img_file1 = opt.img_dir .. '/' .. info1.img
local img1 = trainHook(img_file1)
local img_file2 = opt.img_dir .. '/' .. info2.img
local img2 = trainHook(img_file2)
local txt_sample = torch.randperm(info1.txt:size(1))
local ix_txt1 = txt_sample[1]
-- real text
--data_txt1[n]:copy(info1.txt[ix_txt1])
local txt_sample = torch.randperm(info1.txt:size(1))
for k = 1,opt.numCaption do
local ix_txt = txt_sample[k]
data_txt1[n]:add(info1.txt[ix_txt]:double())
end
data_txt1[n]:mul(1.0/opt.numCaption)
-- real image
data_img1[n]:copy(img1)
-- mis-match image
data_img2[n]:copy(img2)
end
collectgarbage(); collectgarbage()
return data_img1, data_img2, data_txt1
end
function trainLoader:size()
return size
end
|
-- will hold the currently playing sources
local sources = {}
-- check for sources that finished playing and remove them
-- add to love.update
function love.audio.update()
local remove = {}
for _, s in pairs(sources) do
if not s:isPlaying() then
remove[#remove + 1] = s
end
end
for _, s in ipairs(remove) do
sources[s] = nil
end
end
-- overwrite love.audio.play to create and register source if needed
local play = love.audio.play
function love.audio.play(what, how, loop, volume)
local src = what
if type(what) ~= "userdata" or not what:typeOf("Source") then
src = love.audio.newSource(what, how)
src:setLooping(loop or false)
src:setVolume(volume or 1)
end
play(src)
sources[src] = src
return src
end
-- stops a source
local stop = love.audio.stop
function love.audio.stop(src)
if not src then
return
end
stop(src)
sources[src] = nil
end
|
--------------------------------
-- @module ParticleSystem3D
-- @extend Node,BlendProtocol
-- @parent_module cc
--------------------------------
-- remove affector by index
-- @function [parent=#ParticleSystem3D] removeAffector
-- @param self
-- @param #int index
-- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D)
--------------------------------
-- resume particle
-- @function [parent=#ParticleSystem3D] resumeParticleSystem
-- @param self
-- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D)
--------------------------------
-- remove all particle affector
-- @function [parent=#ParticleSystem3D] removeAllAffector
-- @param self
-- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D)
--------------------------------
-- add particle affector
-- @function [parent=#ParticleSystem3D] addAffector
-- @param self
-- @param #cc.Particle3DAffector affector
-- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D)
--------------------------------
-- particle system play control
-- @function [parent=#ParticleSystem3D] startParticleSystem
-- @param self
-- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D)
--------------------------------
-- is enabled
-- @function [parent=#ParticleSystem3D] isEnabled
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- set emitter for particle system, can set your own particle emitter
-- @function [parent=#ParticleSystem3D] setEmitter
-- @param self
-- @param #cc.Particle3DEmitter emitter
-- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D)
--------------------------------
--
-- @function [parent=#ParticleSystem3D] isKeepLocal
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Enables or disables the system.
-- @function [parent=#ParticleSystem3D] setEnabled
-- @param self
-- @param #bool enabled
-- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D)
--------------------------------
-- get particle quota
-- @function [parent=#ParticleSystem3D] getParticleQuota
-- @param self
-- @return unsigned int#unsigned int ret (return value: unsigned int)
--------------------------------
-- override function
-- @function [parent=#ParticleSystem3D] getBlendFunc
-- @param self
-- @return BlendFunc#BlendFunc ret (return value: cc.BlendFunc)
--------------------------------
-- pause particle
-- @function [parent=#ParticleSystem3D] pauseParticleSystem
-- @param self
-- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D)
--------------------------------
-- get particle playing state
-- @function [parent=#ParticleSystem3D] getState
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- get alive particles count
-- @function [parent=#ParticleSystem3D] getAliveParticleCount
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- set particle quota
-- @function [parent=#ParticleSystem3D] setParticleQuota
-- @param self
-- @param #unsigned int quota
-- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D)
--------------------------------
-- override function
-- @function [parent=#ParticleSystem3D] setBlendFunc
-- @param self
-- @param #cc.BlendFunc blendFunc
-- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D)
--------------------------------
-- set particle render, can set your own particle render
-- @function [parent=#ParticleSystem3D] setRender
-- @param self
-- @param #cc.Particle3DRender render
-- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D)
--------------------------------
-- stop particle
-- @function [parent=#ParticleSystem3D] stopParticleSystem
-- @param self
-- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D)
--------------------------------
--
-- @function [parent=#ParticleSystem3D] setKeepLocal
-- @param self
-- @param #bool keepLocal
-- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D)
--------------------------------
-- override function
-- @function [parent=#ParticleSystem3D] draw
-- @param self
-- @param #cc.Renderer renderer
-- @param #mat4_table transform
-- @param #unsigned int flags
-- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D)
--------------------------------
-- override function
-- @function [parent=#ParticleSystem3D] update
-- @param self
-- @param #float delta
-- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D)
--------------------------------
--
-- @function [parent=#ParticleSystem3D] ParticleSystem3D
-- @param self
-- @return ParticleSystem3D#ParticleSystem3D self (return value: cc.ParticleSystem3D)
return nil
|
--[[
local oldUpdate = GUIScoreboard.Update
function GUIScoreboard:Update(deltaTime)
oldUpdate(self, deltaTime)
local vis = self.visible and not self.hiddenOverride
if vis then
local gameTime = PlayerUI_GetGameLengthTime()
local minutes = math.floor( gameTime / 60 )
local seconds = math.floor( gameTime - minutes * 60 )
local serverName = Client.GetServerIsHidden() and "Hidden" or Client.GetConnectedServerName()
local gameTimeText = serverName .. " (Marine versus Marine) | mvm_" .. Shared.GetMapName() .. string.format( " - %d:%02d", minutes, seconds)
self.gameTime:SetText(gameTimeText)
end
end
]]--
|
-- globalized reference for hurting the player
function hurt_player(player, damage)
digest_hurt(player, damage)
end
-- globalized reference for healing the player
function heal_player(player, regen)
digest_heal(player, regen)
end
-- globalized reference for hunger (adder and subtractor)
function raise_hunger(player, hunger_amount)
digest_stat_addition(player, "hunger", hunger_amount)
end
function lower_hunger(player, hunger_amount)
digest_stat_subtraction(player, "hunger", hunger_amount)
end
-- globalized reference for thirst (adder and subtractor)
function raise_thirst(player, thirst_amount)
digest_stat_addition(player, "thirst", thirst_amount)
end
function lower_thirst(player, thirst_amount)
digest_stat_subtraction(player, "thirst", thirst_amount)
end
-- globalized reference for exhaustion (adder and subtractor)
function raise_exhaustion(player, exhaustion_amount)
digest_stat_addition(player, "exhaustion", exhaustion_amount)
end
function lower_exhaustion(player, exhaustion_amount)
digest_stat_subtraction(player, "exhaustion", exhaustion_amount)
end
-- globalized reference for panic (adder and subtractor)
function raise_panic(player, panic_amount)
digest_stat_addition(player, "panic", panic_amount)
end
function lower_panic(player, panic_amount)
digest_stat_subtraction(player, "panic", panic_amount)
end
-- globalized reference for infection (adder and subtractor)
function raise_infection(player, infection_amount)
digest_stat_addition(player, "infection", infection_amount)
end
function lower_infection(player, infection_amount)
digest_stat_subtraction(player, "infection", infection_amount)
end
-- globalized reference for sadness (adder and subtractor)
function raise_sadness(player, sadness_amount)
digest_stat_addition(player, "sadness", sadness_amount)
end
function lower_sadness(player, sadness_amount)
digest_stat_subtraction(player, "sadness", sadness_amount)
end
-- globalized reference for strength (adder and subtractor)
function raise_strength(player, strength_amount)
digest_stat_addition(player, "strength", strength_amount)
end
function lower_strength(player, strength_amount)
digest_stat_subtraction(player, "strength", strength_amount)
end
-- globalized reference for fitness (adder and subtractor)
function raise_fitness(player, fitness_amount)
digest_stat_addition(player, "fitness", fitness_amount)
end
function lower_fitness(player, fitness_amount)
digest_stat_subtraction(player, "fitness", fitness_amount)
end
|
-- Creator:
-- AltiV, September 5th, 2019
LinkLuaModifier("modifier_imba_windranger_shackle_shot", "components/abilities/heroes/hero_windranger", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_windranger_powershot", "components/abilities/heroes/hero_windranger", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_windranger_powershot_scattershot", "components/abilities/heroes/hero_windranger", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_windranger_powershot_overstretch", "components/abilities/heroes/hero_windranger", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_windranger_windrun", "components/abilities/heroes/hero_windranger", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_windranger_windrun_handler", "components/abilities/heroes/hero_windranger", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_windranger_windrun_slow", "components/abilities/heroes/hero_windranger", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_windranger_windrun_invis", "components/abilities/heroes/hero_windranger", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_windranger_advancement", "components/abilities/heroes/hero_windranger", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_generic_motion_controller", "components/modifiers/generic/modifier_generic_motion_controller", LUA_MODIFIER_MOTION_BOTH)
LinkLuaModifier("modifier_imba_windranger_focusfire_vanilla_enhancer", "components/abilities/heroes/hero_windranger", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_windranger_focusfire", "components/abilities/heroes/hero_windranger", LUA_MODIFIER_MOTION_NONE)
imba_windranger_shackleshot = class({})
modifier_imba_windranger_shackle_shot = class({})
imba_windranger_powershot = class({})
modifier_imba_windranger_powershot = class({})
modifier_imba_windranger_powershot_scattershot = class({})
modifier_imba_windranger_powershot_overstretch = class({})
imba_windranger_windrun = class({})
modifier_imba_windranger_windrun_handler = class({})
modifier_imba_windranger_windrun = class({})
modifier_imba_windranger_windrun_slow = class({})
modifier_imba_windranger_windrun_invis = class({})
imba_windranger_advancement = class({})
modifier_imba_windranger_advancement = class({})
imba_windranger_focusfire_vanilla_enhancer = class({})
modifier_imba_windranger_focusfire_vanilla_enhancer = class({})
imba_windranger_focusfire = class({})
modifier_imba_windranger_focusfire = class({})
---------------------------------
-- IMBA_WINDRANGER_SHACKLESHOT --
---------------------------------
function imba_windranger_shackleshot:GetBehavior()
return self.BaseClass.GetBehavior(self) + DOTA_ABILITY_BEHAVIOR_AUTOCAST
end
function imba_windranger_shackleshot:GetCooldown(level)
return self.BaseClass.GetCooldown(self, level) - self:GetCaster():FindTalentValue("special_bonus_imba_windranger_shackle_shot_cooldown")
end
-- Splinter Sister IMBAfication will be an "opt-out" add-on
function imba_windranger_shackleshot:OnUpgrade()
if self:GetLevel() == 1 then
self:ToggleAutoCast()
end
end
function imba_windranger_shackleshot:OnSpellStart()
local target = self:GetCursorTarget()
self:GetCaster():EmitSound("Hero_Windrunner.ShackleshotCast")
-- IMBAfication: Natural Slinger
-- Rough check to assume a tree was targeted, since CutDown doesn't work with "artificial" trees
if target:GetName() == "" then
local temp_thinker = CreateModifierThinker(self:GetCaster(), self, nil, {duration = 0.1}, target:GetAbsOrigin(), self:GetCaster():GetTeamNumber(), false)
ProjectileManager:CreateTrackingProjectile({
Target = temp_thinker,
Source = self:GetCaster(),
Ability = self,
EffectName = "particles/units/heroes/hero_windrunner/windrunner_shackleshot.vpcf",
iMoveSpeed = self:GetSpecialValueFor("arrow_speed"),
bDodgeable = true,
ExtraData = {
location_x = self:GetCaster():GetAbsOrigin().x,
location_y = self:GetCaster():GetAbsOrigin().y,
location_z = self:GetCaster():GetAbsOrigin().z,
}
})
else
ProjectileManager:CreateTrackingProjectile({
Target = target,
Source = self:GetCaster(),
Ability = self,
EffectName = "particles/units/heroes/hero_windrunner/windrunner_shackleshot.vpcf",
iMoveSpeed = self:GetSpecialValueFor("arrow_speed"),
bDodgeable = true,
ExtraData = {
location_x = self:GetCaster():GetAbsOrigin().x,
location_y = self:GetCaster():GetAbsOrigin().y,
location_z = self:GetCaster():GetAbsOrigin().z,
}
})
end
end
-- This helper function looks for valid targets
function imba_windranger_shackleshot:SearchForShackleTarget(target, target_angle, ignore_list, target_count)
local shackleTarget = nil
-- "Shackleshot always prioritizes units over trees as a secondary target."
-- Check for units first
local enemies = FindUnitsInRadius(self:GetCaster():GetTeamNumber(), target:GetAbsOrigin(), nil, self:GetSpecialValueFor("shackle_distance"), DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, 0, FIND_FARTHEST, false)
for _, enemy in pairs(enemies) do
if enemy ~= target and not ignore_list[enemy] and math.abs(AngleDiff(target_angle, VectorToAngles(enemy:GetAbsOrigin() - target:GetAbsOrigin()).y)) <= self:GetSpecialValueFor("shackle_angle") then
shackleTarget = enemy
target:EmitSound("Hero_Windrunner.ShackleshotBind")
enemy:EmitSound("Hero_Windrunner.ShackleshotBind")
local shackleshot_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_windrunner/windrunner_shackleshot_pair.vpcf", PATTACH_POINT_FOLLOW, target)
ParticleManager:SetParticleControlEnt(shackleshot_particle, 1, enemy, PATTACH_ABSORIGIN_FOLLOW, "attach_hitloc", enemy:GetAbsOrigin(), true)
ParticleManager:SetParticleControl(shackleshot_particle, 2, Vector(self:GetTalentSpecialValueFor("stun_duration"), 0, 0))
if target.AddNewModifier then
local target_modifier = target:AddNewModifier(self:GetCaster(), self, "modifier_imba_windranger_shackle_shot", {duration = self:GetTalentSpecialValueFor("stun_duration")})
if target_modifier then
target_modifier:AddParticle(shackleshot_particle, false, false, -1, false, false)
target_modifier:SetDuration(self:GetTalentSpecialValueFor("stun_duration") * (1 - target:GetStatusResistance()), true)
end
end
if enemy.AddNewModifier then
local enemy_shackleshot_modifier = enemy:AddNewModifier(self:GetCaster(), self, "modifier_imba_windranger_shackle_shot", {duration = self:GetTalentSpecialValueFor("stun_duration")})
if enemy_shackleshot_modifier then
enemy_shackleshot_modifier:SetDuration(self:GetTalentSpecialValueFor("stun_duration") * (1 - enemy:GetStatusResistance()), true)
end
end
break
end
end
-- Then check trees (don't let this bounce from tree to tree I guess)
if not shackleTarget and target:GetName() ~= "npc_dota_thinker" then
local trees = GridNav:GetAllTreesAroundPoint(target:GetAbsOrigin(), self:GetSpecialValueFor("shackle_distance"), false)
for _, tree in pairs(trees) do
if not ignore_list[enemy] and math.abs(AngleDiff(target_angle, VectorToAngles(tree:GetAbsOrigin() - target:GetAbsOrigin()).y)) <= self:GetSpecialValueFor("shackle_angle") then
shackleTarget = tree
if target.AddNewModifier then
local shackleshot_tree_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_windrunner/windrunner_shackleshot_pair.vpcf", PATTACH_POINT_FOLLOW, target)
ParticleManager:SetParticleControl(shackleshot_tree_particle, 1, tree:GetAbsOrigin())
ParticleManager:SetParticleControl(shackleshot_tree_particle, 2, Vector(self:GetTalentSpecialValueFor("stun_duration"), 0, 0))
local target_modifier = target:AddNewModifier(self:GetCaster(), self, "modifier_imba_windranger_shackle_shot", {duration = self:GetTalentSpecialValueFor("stun_duration")})
if target_modifier then
target_modifier:AddParticle(shackleshot_tree_particle, false, false, -1, false, false)
target_modifier:SetDuration(self:GetTalentSpecialValueFor("stun_duration") * (1 - target:GetStatusResistance()), true)
end
end
break
end
end
end
if not shackleTarget then
local shackleshot_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_windrunner/windrunner_shackleshot_single.vpcf", PATTACH_ABSORIGIN, target)
ParticleManager:ReleaseParticleIndex(shackleshot_particle)
end
return shackleTarget
end
function imba_windranger_shackleshot:OnProjectileHit_ExtraData(target, location, ExtraData)
if not ExtraData.bSplinterSister or ExtraData.bSplinterSister ~= 1 then
if not target or (target.IsMagicImmune and target:IsMagicImmune()) or (target.TriggerSpellAbsorb and target:TriggerSpellAbsorb(self)) then return end
-- Initialize table to hold the shackled targets (so a unit doesn't somehow get shackled more than once by the cast)
local shackled_targets = {}
target:EmitSound("Hero_Windrunner.ShackleshotStun")
-- The next_target variable will be fed the targets through the self:SearchForShackleTarget function
local next_target = target
-- Check for up to shackle_count units
for targets = 0, self:GetSpecialValueFor("shackle_count") do
-- If a target was found, keep going for up to shackle_count hits
if next_target then
next_target = self:SearchForShackleTarget(next_target, VectorToAngles(next_target:GetAbsOrigin() - Vector(ExtraData.location_x, ExtraData.location_y, ExtraData.location_z)).y, shackled_targets, targets)
if next_target then
shackled_targets[next_target] = true
if targets == 0 and self:GetCaster():GetName() == "npc_dota_hero_windrunner" and RollPercentage(35) then
if not self.responses then
self.responses =
{
"windrunner_wind_ability_shackleshot_05",
"windrunner_wind_ability_shackleshot_06",
"windrunner_wind_ability_shackleshot_07",
}
end
self:GetCaster():EmitSound(self.responses[RandomInt(1, #self.responses)])
end
-- targets == 0 represents the unit that was originally targeted; if there's no unit behind them just apply the fail stun and that's it
elseif targets == 0 then
local stun_modifier = target:AddNewModifier(self:GetCaster(), self, "modifier_stunned", {duration = self:GetSpecialValueFor("fail_stun_duration")})
if stun_modifier then
local shackleshot_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_windrunner/windrunner_shackleshot_single.vpcf", PATTACH_ABSORIGIN, target)
-- TODO: Figure out how this particle is oriented?
ParticleManager:SetParticleControlForward(shackleshot_particle, 2, Vector(ExtraData.location_x, ExtraData.location_y, ExtraData.location_z):Normalized())
stun_modifier:SetDuration(self:GetSpecialValueFor("fail_stun_duration") * (1 - target:GetStatusResistance()), true)
stun_modifier:AddParticle(shackleshot_particle, false, false, -1, false, false)
end
end
-- If no target was found to latch to, stop the for-loop
else
break
end
end
-- IMBAfication: Spliter Sister
elseif target then
EmitSoundOnLocationWithCaster(target:GetAbsOrigin(), "Hero_Windrunner.ProjectileImpact", self:GetCaster())
self:GetCaster():PerformAttack(target, true, true, true, true, false, false, false)
end
end
-------------------------------------------
-- MODIFIER_IMBA_WINDRANGER_SHACKLE_SHOT --
-------------------------------------------
function modifier_imba_windranger_shackle_shot:CheckState()
return {[MODIFIER_STATE_STUNNED] = true}
end
function modifier_imba_windranger_shackle_shot:DeclareFunctions()
return {MODIFIER_PROPERTY_OVERRIDE_ANIMATION,
MODIFIER_EVENT_ON_ATTACK_LANDED}
end
function modifier_imba_windranger_shackle_shot:GetOverrideAnimation()
return ACT_DOTA_DISABLED
end
-- IMBAfication: Splinter Sister
function modifier_imba_windranger_shackle_shot:OnAttackLanded(keys)
if keys.attacker == self:GetCaster() and keys.target == self:GetParent() and not keys.no_attack_cooldown and self:GetAbility() and self:GetAbility():GetAutoCastState() then
for _, enemy in pairs(FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetParent():GetAbsOrigin(), nil, self:GetCaster():Script_GetAttackRange(), DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_FOW_VISIBLE + DOTA_UNIT_TARGET_FLAG_NO_INVIS + DOTA_UNIT_TARGET_FLAG_NOT_ATTACK_IMMUNE, FIND_ANY_ORDER, false)) do
if enemy ~= self:GetParent() and enemy:FindModifierByNameAndCaster("modifier_imba_windranger_shackle_shot", self:GetCaster()) and self:GetAbility() then
EmitSoundOnLocationWithCaster(self:GetParent():GetAbsOrigin(), "Hero_Windrunner.Attack", self:GetCaster())
ProjectileManager:CreateTrackingProjectile({
Target = enemy,
Source = self:GetParent(),
Ability = self:GetAbility(),
EffectName = self:GetCaster():GetRangedProjectileName() or "particles/units/heroes/hero_windrunner/windrunner_base_attack.vpcf",
iMoveSpeed = self:GetCaster():GetProjectileSpeed() or 1250,
bDrawsOnMinimap = false,
bDodgeable = true,
bIsAttack = true, -- Does this even do anything
bVisibleToEnemies = true,
bReplaceExisting = false,
flExpireTime = GameRules:GetGameTime() + 10.0,
bProvidesVision = false,
ExtraData = {bSplinterSister = true}
})
end
end
end
end
-------------------------------
-- IMBA_WINDRANGER_POWERSHOT --
-------------------------------
-- Not gonna do the voicelines for this one cause I'd need to track hero kills with the arrows and stuff and it's gonna get annoying
function imba_windranger_powershot:GetBehavior()
return self.BaseClass.GetBehavior(self) + DOTA_ABILITY_BEHAVIOR_AUTOCAST
end
function imba_windranger_powershot:GetIntrinsicModifierName()
return "modifier_imba_windranger_powershot"
end
function imba_windranger_powershot:OnSpellStart()
EmitSoundOnLocationForAllies(self:GetCaster():GetAbsOrigin(), "Ability.PowershotPull", self:GetCaster())
if not self.powershot_modifier or self.powershot_modifier:IsNull() then
self.powershot_modifier = self:GetCaster():FindModifierByNameAndCaster("modifier_imba_windranger_powershot", self:GetCaster())
end
-- TODO: REMOVE THIS WHEN DONE WITH EVERYTHING
if self:GetCaster():HasAbility("imba_windranger_advancement") then
self:GetCaster():FindAbilityByName("imba_windranger_advancement"):SetLevel(1)
end
if self:GetCaster():HasAbility("imba_windranger_focusfire_vanilla_enhancer") then
self:GetCaster():FindAbilityByName("imba_windranger_focusfire_vanilla_enhancer"):SetLevel(1)
end
end
function imba_windranger_powershot:OnChannelThink(flInterval)
self.powershot_modifier:SetStackCount(math.min((GameRules:GetGameTime() - self:GetChannelStartTime()) * 100, 100))
end
function imba_windranger_powershot:OnChannelFinish(bInterrupted)
-- Preventing projectiles getting stuck in one spot due to potential 0 length vector
if self:GetCursorPosition() == self:GetCaster():GetAbsOrigin() then
self:GetCaster():SetCursorPosition(self:GetCursorPosition() + self:GetCaster():GetForwardVector())
end
if self.powershot_modifier then
self.powershot_modifier:SetStackCount(0)
end
if bInterrupted or not self:GetAutoCastState() then
local channel_pct = (GameRules:GetGameTime() - self:GetChannelStartTime()) / self:GetChannelTime()
if channel_pct < self:GetSpecialValueFor("scattershot_min") * 0.01 or channel_pct > self:GetSpecialValueFor("scattershot_max") * 0.01 then
self:FirePowershot(channel_pct)
else
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_imba_windranger_powershot_scattershot",
{
duration = self:GetSpecialValueFor("scattershot_interval") * (self:GetSpecialValueFor("scattershot_shots") - 1),
channel_pct = channel_pct,
cursor_pos_x = self:GetCursorPosition().x,
cursor_pos_y = self:GetCursorPosition().y,
cursor_pos_z = self:GetCursorPosition().z
})
end
else
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_imba_windranger_powershot_overstretch", {})
end
end
function imba_windranger_powershot:FirePowershot(channel_pct, overstretch_bonus)
-- This "dummy" literally only exists to attach the gush travel sound to
local powershot_dummy = CreateModifierThinker(self:GetCaster(), self, nil, {}, self:GetCaster():GetAbsOrigin(), self:GetCaster():GetTeamNumber(), false)
powershot_dummy:EmitSound("Ability.Powershot")
-- Keep track of how many units the Powershot will hit to calculate damage reductions
powershot_dummy.units_hit = 0
local powershot_particle = "particles/units/heroes/hero_windrunner/windrunner_spell_powershot.vpcf"
-- IMBAfication: Godshot
if channel_pct >= self:GetSpecialValueFor("godshot_min") * 0.01 and channel_pct <= self:GetSpecialValueFor("godshot_max") * 0.01 then
powershot_particle = "particles/units/heroes/hero_windrunner/windrunner_spell_powershot_godshot.vpcf"
powershot_dummy:EmitSound("Hero_Windranger.Powershot_Godshot")
end
self:GetCaster():StartGesture(ACT_DOTA_OVERRIDE_ABILITY_2)
-- IMBAfication: Overstretched
if not overstretch_bonus then
overstretch_bonus = 0
end
ProjectileManager:CreateLinearProjectile({
Source = self:GetCaster(),
Ability = self,
vSpawnOrigin = self:GetCaster():GetAbsOrigin(),
iUnitTargetTeam = DOTA_UNIT_TARGET_TEAM_ENEMY,
iUnitTargetFlags = DOTA_UNIT_TARGET_FLAG_NONE,
iUnitTargetType = DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC,
EffectName = powershot_particle,
fDistance = self:GetSpecialValueFor("arrow_range") + overstretch_bonus + self:GetCaster():GetCastRangeBonus(),
fStartRadius = self:GetSpecialValueFor("arrow_width"),
fEndRadius = self:GetSpecialValueFor("arrow_width"),
vVelocity = (self:GetCursorPosition() - self:GetCaster():GetAbsOrigin()):Normalized() * self:GetSpecialValueFor("arrow_speed") * Vector(1, 1, 0),
bProvidesVision = true,
iVisionRadius = self:GetSpecialValueFor("vision_radius"),
iVisionTeamNumber = self:GetCaster():GetTeamNumber(),
ExtraData = {
dummy_index = powershot_dummy:entindex(),
channel_pct = channel_pct * 100
}
})
end
function imba_windranger_powershot:OnProjectileThink_ExtraData(location, data)
if data.dummy_index then
EntIndexToHScript(data.dummy_index):SetAbsOrigin(location)
end
GridNav:DestroyTreesAroundPoint(location, 75, true)
end
function imba_windranger_powershot:OnProjectileHit_ExtraData(target, location, data)
if target and data.dummy_index and EntIndexToHScript(data.dummy_index) and not EntIndexToHScript(data.dummy_index):IsNull() and EntIndexToHScript(data.dummy_index).units_hit then
EmitSoundOnLocationWithCaster(location, "Hero_Windrunner.PowershotDamage", self:GetCaster())
local damage = self:GetTalentSpecialValueFor("powershot_damage") * data.channel_pct * 0.01 * ((100 - self:GetSpecialValueFor("damage_reduction")) * 0.01) ^ EntIndexToHScript(data.dummy_index).units_hit
local damage_type = self:GetAbilityDamageType()
-- IMBAfication: Godshot
if data.channel_pct >= self:GetSpecialValueFor("godshot_min") and data.channel_pct <= self:GetSpecialValueFor("godshot_max") then
damage = self:GetTalentSpecialValueFor("powershot_damage") * self:GetSpecialValueFor("godshot_damage_pct") * 0.01
damage_type = DAMAGE_TYPE_PURE
local stun_modifier = target:AddNewModifier(self:GetCaster(), self, "modifier_stunned", {duration = self:GetSpecialValueFor("godshot_stun_duration")})
if stun_modifier then
stun_modifier:SetDuration(self:GetSpecialValueFor("godshot_stun_duration") * (1 - target:GetStatusResistance()), true)
end
-- IMBAfication: Scattershot
elseif data.channel_pct >= self:GetSpecialValueFor("scattershot_min") and data.channel_pct <= self:GetSpecialValueFor("scattershot_max") then
damage = self:GetTalentSpecialValueFor("powershot_damage") * self:GetSpecialValueFor("scattershot_damage_pct") * 0.01 * ((100 - self:GetSpecialValueFor("damage_reduction")) * 0.01) ^ EntIndexToHScript(data.dummy_index).units_hit
end
ApplyDamage({
victim = target,
damage = damage,
damage_type = damage_type,
damage_flags = DOTA_DAMAGE_FLAG_NONE,
attacker = self:GetCaster(),
ability = self
})
EntIndexToHScript(data.dummy_index).units_hit = EntIndexToHScript(data.dummy_index).units_hit + 1
elseif data.dummy_index then
EntIndexToHScript(data.dummy_index):StopSound("Ability.Powershot")
EntIndexToHScript(data.dummy_index):RemoveSelf()
end
end
----------------------------------------
-- MODIFIER_IMBA_WINDRANGER_POWERSHOT --
----------------------------------------
function modifier_imba_windranger_powershot:IsHidden() return self:GetStackCount() <= 0 end
----------------------------------------------------
-- MODIFIER_IMBA_WINDRANGER_POWERSHOT_SCATTERSHOT --
----------------------------------------------------
function modifier_imba_windranger_powershot_scattershot:IsPurgable() return false end
function modifier_imba_windranger_powershot_scattershot:OnCreated(params)
if not IsServer() then return end
self.channel_pct = params.channel_pct
self.cursor_pos = Vector(params.cursor_pos_x, params.cursor_pos_y, params.cursor_pos_z)
self.scattershot_interval = self:GetAbility():GetSpecialValueFor("scattershot_interval")
self.scattershot_deviation = self:GetAbility():GetSpecialValueFor("scattershot_deviation")
self:OnIntervalThink()
self:StartIntervalThink(self.scattershot_interval)
end
function modifier_imba_windranger_powershot_scattershot:OnIntervalThink()
if self:GetAbility() then
self:GetParent():SetCursorPosition(RotatePosition(self:GetParent() :GetAbsOrigin(), QAngle(0, RandomInt(-self.scattershot_deviation, self.scattershot_deviation), 0), self.cursor_pos))
self:GetAbility():FirePowershot(self.channel_pct)
end
end
----------------------------------------------------
-- MODIFIER_IMBA_WINDRANGER_POWERSHOT_OVERSTRETCH --
----------------------------------------------------
-- TODO: Find a way to hold the powershot gesture if possible?
function modifier_imba_windranger_powershot_overstretch:OnCreated()
if self:GetAbility() then
self.overstretch_bonus_range_per_second = self:GetAbility():GetSpecialValueFor("overstretch_bonus_range_per_second")
else
self.overstretch_bonus_range_per_second = 0
end
if not IsServer() then return end
self.destroy_orders =
{
[DOTA_UNIT_ORDER_STOP] = true,
[DOTA_UNIT_ORDER_CONTINUE] = true,
[DOTA_UNIT_ORDER_CAST_POSITION] = true,
[DOTA_UNIT_ORDER_CAST_TARGET] = true,
[DOTA_UNIT_ORDER_CAST_TARGET_TREE] = true,
[DOTA_UNIT_ORDER_CAST_NO_TARGET] = true,
[DOTA_UNIT_ORDER_CAST_TOGGLE] = true
}
self:GetParent():StartGesture(ACT_DOTA_CAST_ABILITY_2)
self:StartIntervalThink(1)
end
function modifier_imba_windranger_powershot_overstretch:OnIntervalThink()
self:GetParent():StartGesture(ACT_DOTA_CAST_ABILITY_2)
self:IncrementStackCount()
end
function modifier_imba_windranger_powershot_overstretch:OnDestroy()
if not IsServer() or not self:GetAbility() then return end
self:GetParent():FadeGesture(ACT_DOTA_CAST_ABILITY_2)
self:GetParent():SetCursorPosition(self:GetParent():GetAbsOrigin() + self:GetParent():GetForwardVector())
-- By logic this should be fully channeled already so 1 = 100%
self:GetAbility():FirePowershot(1, self:GetStackCount() * self.overstretch_bonus_range_per_second)
end
function modifier_imba_windranger_powershot_overstretch:CheckState()
return {
[MODIFIER_STATE_ROOTED] = true,
[MODIFIER_STATE_DISARMED] = true
}
end
function modifier_imba_windranger_powershot_overstretch:DeclareFunctions()
return {MODIFIER_EVENT_ON_ORDER}
end
function modifier_imba_windranger_powershot_overstretch:OnOrder(keys)
if keys.unit == self:GetParent() and self.destroy_orders[keys.order_type] then
self:Destroy()
end
end
-----------------------------
-- IMBA_WINDRANGER_WINDRUN --
-----------------------------
function imba_windranger_windrun:GetIntrinsicModifierName()
return "modifier_imba_windranger_windrun_handler"
end
-- function imba_windranger_windrun:OnInventoryContentsChanged()
-- if self:GetCaster():HasScepter() and self:GetCaster():HasModifier("modifier_imba_windranger_windrun_handler") and not self:GetCaster():FindModifierByNameAndCaster("modifier_imba_windranger_windrun_handler", self:GetCaster()).initialized then
-- self:GetCaster():FindModifierByNameAndCaster("modifier_imba_windranger_windrun_handler", self:GetCaster()).initialized = true
-- self:GetCaster():FindModifierByNameAndCaster("modifier_imba_windranger_windrun_handler", self:GetCaster()):SetStackCount(self:GetSpecialValueFor("max_charges"))
-- end
-- end
-- function imba_windranger_windrun:OnHeroCalculateStatBonus()
-- self:OnInventoryContentsChanged()
-- end
function imba_windranger_windrun:GetCooldown(level)
if not self:GetCaster():HasScepter() then
return self.BaseClass.GetCooldown(self, level)
else
return 0
end
end
function imba_windranger_windrun:OnSpellStart()
self:GetCaster():EmitSound("Ability.Windrun")
if self:GetCaster():GetName() == "npc_dota_hero_windrunner" and RollPercentage(75) then
if not self.responses then
self.responses =
{
"windrunner_wind_spawn_04",
"windrunner_wind_move_08",
"windrunner_wind_move_10",
}
end
-- This one doesn't work or something
-- EmitSoundOnClient(self.responses[RandomInt(1, #self.responses)], self:GetCaster():GetPlayerOwner())
self:GetCaster():EmitSound(self.responses[RandomInt(1, #self.responses)])
end
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_imba_windranger_windrun", {duration = self:GetSpecialValueFor("duration")})
if self:GetCaster():HasTalent("special_bonus_imba_windranger_windrun_invisibility") then
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_imba_windranger_windrun_invis", {duration = self:GetSpecialValueFor("duration")})
end
end
----------------------------------------------
-- MODIFIER_IMBA_WINDRANGER_WINDRUN_HANDLER --
----------------------------------------------
-- Largely copied from the modifier_generic_charges modifier but with changes to support scepter charge system only (also allows for its own tooltips cause I still can't do the modifier_imba_windranger_windrun_handler = modifier_generic_charges thing
function modifier_imba_windranger_windrun_handler:IsHidden() return not self:GetCaster():HasScepter() end
function modifier_imba_windranger_windrun_handler:DestroyOnExpire() return false end
function modifier_imba_windranger_windrun_handler:OnCreated()
if not IsServer() then return end
-- Sphaget way of getting this working but it's hardcode (doesn't read the server-side value if RequiresScepter flag is on and scepter is not held)
self:SetStackCount(math.max(self:GetAbility():GetSpecialValueFor("max_charges"), 2))
self:CalculateCharge()
end
function modifier_imba_windranger_windrun_handler:OnIntervalThink()
self:IncrementStackCount()
self:StartIntervalThink(-1)
self:CalculateCharge()
end
function modifier_imba_windranger_windrun_handler:CalculateCharge()
if self:GetStackCount() >= math.max(self:GetAbility():GetSpecialValueFor("max_charges"), 2) then
self:SetDuration(-1, true)
self:StartIntervalThink(-1)
else
if self:GetRemainingTime() <= 0.05 then
self:StartIntervalThink(self:GetAbility():GetTalentSpecialValueFor("charge_restore_time") * self:GetParent():GetCooldownReduction())
self:SetDuration(self:GetAbility():GetTalentSpecialValueFor("charge_restore_time") * self:GetParent():GetCooldownReduction(), true)
end
if self:GetStackCount() == 0 then
self:GetAbility():StartCooldown(self:GetRemainingTime())
else
self:GetAbility():StartCooldown(0.25)
end
end
end
function modifier_imba_windranger_windrun_handler:DeclareFunctions()
return {MODIFIER_EVENT_ON_ABILITY_FULLY_CAST}
end
function modifier_imba_windranger_windrun_handler:OnAbilityFullyCast(params)
if params.unit ~= self:GetParent() or not self:GetParent():HasScepter() then return end
if params.ability == self:GetAbility() then
-- All this garbage is just to try and check for WTF mode to not expend charges and yet it's still bypassable
local wtf_mode = true
if not GameRules:IsCheatMode() then
wtf_mode = false
else
for ability = 0, 24 - 1 do
if self:GetParent():GetAbilityByIndex(ability) and self:GetParent():GetAbilityByIndex(ability):GetCooldownTimeRemaining() > 0 then
wtf_mode = false
break
end
end
if wtf_mode ~= false then
for item = 0, 15 do
if self:GetParent():GetItemInSlot(item) and self:GetParent():GetItemInSlot(item):GetCooldownTimeRemaining() > 0 then
wtf_mode = false
break
end
end
end
end
if wtf_mode == false then
self:DecrementStackCount()
self:CalculateCharge()
end
elseif params.ability:GetName() == "item_refresher" or params.ability:GetName() == "item_refresher_shard" then
self:StartIntervalThink(-1)
self:SetDuration(-1, true)
self:SetStackCount(self:GetAbility():GetSpecialValueFor("max_charges"))
end
end
--------------------------------------
-- MODIFIER_IMBA_WINDRANGER_WINDRUN --
--------------------------------------
function modifier_imba_windranger_windrun:GetEffectName()
return "particles/units/heroes/hero_windrunner/windrunner_windrun.vpcf"
end
function modifier_imba_windranger_windrun:OnCreated()
if self:GetAbility() then
self.movespeed_bonus_pct = self:GetAbility():GetSpecialValueFor("movespeed_bonus_pct")
self.evasion_pct_tooltip = self:GetAbility():GetSpecialValueFor("evasion_pct_tooltip")
self.scepter_bonus_movement = self:GetAbility():GetSpecialValueFor("scepter_bonus_movement")
self.radius = self:GetAbility():GetSpecialValueFor("radius")
self.gale_enchantment_radius = self:GetAbility():GetSpecialValueFor("gale_enchantment_radius")
self.gale_enchantment_duration = self:GetAbility():GetSpecialValueFor("gale_enchantment_duration")
else
self.movespeed_bonus_pct = 0
self.evasion_pct_tooltip = 0
self.scepter_bonus_movement = 0
self.radius = 0
self.gale_enchantment_radius = 0
self.gale_enchantment_duration = 0
end
if not IsServer() then return end
self:StartIntervalThink(0.1)
end
function modifier_imba_windranger_windrun:OnIntervalThink()
for _, ally in pairs(FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetCaster():GetAbsOrigin(), nil, self.gale_enchantment_radius, DOTA_UNIT_TARGET_TEAM_FRIENDLY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)) do
if self:GetCaster() == self:GetParent() and ally ~= self:GetCaster() then
ally:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_windranger_windrun", {duration = self.gale_enchantment_duration})
end
end
end
function modifier_imba_windranger_windrun:OnDestroy()
if not IsServer() then return end
self:GetCaster():StopSound("Ability.Windrun")
end
-- function modifier_imba_windranger_windrun:CheckState()
-- if self:GetParent():GetLevel() >= 25 then
-- return {[MODIFIER_STATE_ALLOW_PATHING_TROUGH_TREES] = true}
-- end
-- end
function modifier_imba_windranger_windrun:DeclareFunctions()
return {
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE,
MODIFIER_PROPERTY_EVASION_CONSTANT,
MODIFIER_PROPERTY_IGNORE_MOVESPEED_LIMIT,
MODIFIER_PROPERTY_TRANSLATE_ACTIVITY_MODIFIERS,
}
end
function modifier_imba_windranger_windrun:GetModifierMoveSpeedBonus_Percentage()
if self:GetCaster() then
if not self:GetCaster():HasScepter() then
return self.movespeed_bonus_pct
else
return self.movespeed_bonus_pct + self.scepter_bonus_movement
end
end
end
function modifier_imba_windranger_windrun:GetModifierEvasion_Constant()
return self.evasion_pct_tooltip
end
function modifier_imba_windranger_windrun:GetModifierIgnoreMovespeedLimit()
if self:GetCaster() and self:GetCaster():HasScepter() then
return 1
end
end
function modifier_imba_windranger_windrun:GetActivityTranslationModifiers()
return "windrun"
end
function modifier_imba_windranger_windrun:IsAura() return true end
function modifier_imba_windranger_windrun:GetModifierAura() return "modifier_imba_windranger_windrun_slow" end
function modifier_imba_windranger_windrun:GetAuraRadius() return self.radius end
function modifier_imba_windranger_windrun:GetAuraSearchFlags() return DOTA_UNIT_TARGET_FLAG_NONE end
function modifier_imba_windranger_windrun:GetAuraSearchTeam() return DOTA_UNIT_TARGET_TEAM_ENEMY end
function modifier_imba_windranger_windrun:GetAuraSearchType() return DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC end
function modifier_imba_windranger_windrun:IsAuraActiveOnDeath() return false end
-- "The slow is provided by an aura on Windranger. Its debuff lingers for 2.5 seconds."
function modifier_imba_windranger_windrun:GetAuraDuration() return 2.5 end
-------------------------------------------
-- MODIFIER_IMBA_WINDRANGER_WINDRUN_SLOW --
-------------------------------------------
function modifier_imba_windranger_windrun_slow:GetEffectName()
return "particles/units/heroes/hero_windrunner/windrunner_windrun_slow.vpcf"
end
function modifier_imba_windranger_windrun_slow:OnCreated()
if self:GetAbility() then
self.enemy_movespeed_bonus_pct = self:GetAbility():GetSpecialValueFor("enemy_movespeed_bonus_pct")
else
self.enemy_movespeed_bonus_pct = 0
end
end
function modifier_imba_windranger_windrun_slow:DeclareFunctions()
return {
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE
}
end
function modifier_imba_windranger_windrun_slow:GetModifierMoveSpeedBonus_Percentage()
return self.enemy_movespeed_bonus_pct
end
--------------------------------------------
-- MODIFIER_IMBA_WINDRANGER_WINDRUN_INVIS --
--------------------------------------------
function modifier_imba_windranger_windrun_invis:CheckState()
return {[MODIFIER_STATE_INVISIBLE] = true}
end
function modifier_imba_windranger_windrun_invis:DeclareFunctions()
return {
MODIFIER_PROPERTY_INVISIBILITY_LEVEL,
MODIFIER_EVENT_ON_ATTACK,
MODIFIER_EVENT_ON_ABILITY_FULLY_CAST,
}
end
function modifier_imba_windranger_windrun_invis:GetModifierInvisibilityLevel()
return 1
end
function modifier_imba_windranger_windrun_invis:OnAttack(keys)
if keys.attacker == self:GetParent() and not keys.no_attack_cooldown then
self:Destroy()
end
end
function modifier_imba_windranger_windrun_invis:OnAbilityFullyCast(keys)
if keys.unit == self:GetParent() and keys.ability ~= self:GetAbility() and keys.ability:GetName() ~= "imba_windranger_advancement" then
self:Destroy()
end
end
---------------------------------
-- IMBA_WINDRANGER_ADVANCEMENT --
---------------------------------
-- TODO: This needs an ability icon
function imba_windranger_advancement:IsInnateAbility() return true end
function imba_windranger_advancement:OnSpellStart()
ProjectileManager:ProjectileDodge(self:GetCaster())
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_generic_motion_controller",
{
distance = self:GetSpecialValueFor("advancement_distance"),
direction_x = self:GetCaster():GetForwardVector().x,
direction_y = self:GetCaster():GetForwardVector().y,
direction_z = self:GetCaster():GetForwardVector().z,
duration = self:GetSpecialValueFor("advancement_duration"),
height = self:GetSpecialValueFor("advancement_height"),
bGroundStop = true,
bDecelerate = false,
bInterruptible = false,
bIgnoreTenacity = true
})
end
------------------------------------------------
-- IMBA_WINDRANGER_FOCUSFIRE_VANILLA_ENHANCER --
------------------------------------------------
function imba_windranger_focusfire_vanilla_enhancer:IsInnateAbility() return true end
function imba_windranger_focusfire_vanilla_enhancer:GetIntrinsicModifierName()
return "modifier_imba_windranger_focusfire_vanilla_enhancer"
end
---------------------------------------------------------
-- MODIFIER_IMBA_WINDRANGER_FOCUSFIRE_VANILLA_ENHANCER --
---------------------------------------------------------
function modifier_imba_windranger_focusfire_vanilla_enhancer:IsHidden() return true end
function modifier_imba_windranger_focusfire_vanilla_enhancer:DeclareFunctions()
return {
MODIFIER_EVENT_ON_ABILITY_FULLY_CAST,
MODIFIER_EVENT_ON_ATTACK_LANDED
}
end
function modifier_imba_windranger_focusfire_vanilla_enhancer:OnAbilityFullyCast(keys)
if keys.unit == self:GetParent() and keys.ability:GetName() == "windrunner_focusfire" then
self.ability = keys.ability
self.target = keys.ability:GetCursorTarget()
end
end
function modifier_imba_windranger_focusfire_vanilla_enhancer:OnAttackLanded(keys)
if keys.attacker == self:GetParent() and self:GetParent():HasModifier("modifier_windrunner_focusfire") and self.target and not self.target:IsNull() and self.target:IsAlive() and self.target == keys.target and RollPseudoRandom(self.ability:GetSpecialValueFor("ministun_chance"), self) then
keys.target:EmitSound("DOTA_Item.MKB.Minibash")
keys.target:AddNewModifier(self:GetParent(), self:GetAbility(), "modifier_stunned", {duration = 0.1})
end
end
-------------------------------
-- IMBA_WINDRANGER_FOCUSFIRE --
-------------------------------
-- Tried to replicate the vanilla ability as usual, but it seems far too hacky to properly replicate the "on_the_move" aspect where forward vector is separate from Windranger's movement, so I will just be using the vanilla ability
-- There was a suggestion to use a separate entity to control the movement, but this starts breaking apart when you have to start considering forced movements (i.e. how do you make the forced movement affect both the movement control unit AND Windranger, without ending up making that movement control unit a target for other abilities?)
function imba_windranger_focusfire:OnSpellStart()
self:GetCaster():EmitSound("Ability.Focusfire")
self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_imba_windranger_focusfire", {duration = self:GetDuration()})
end
----------------------------------------
-- MODIFIER_IMBA_WINDRANGER_FOCUSFIRE --
----------------------------------------
function modifier_imba_windranger_focusfire:IsPurgable() return false end
function modifier_imba_windranger_focusfire:OnCreated(params)
self.bonus_attack_speed = self:GetAbility():GetSpecialValueFor("bonus_attack_speed")
self.focusfire_damage_reduction = self:GetAbility():GetSpecialValueFor("focusfire_damage_reduction")
self.focusfire_fire_on_the_move = self:GetAbility():GetSpecialValueFor("focusfire_fire_on_the_move")
if not IsServer() then return end
self.bFocusing = true
self.target = self:GetAbility():GetCursorTarget()
self:StartIntervalThink(FrameTime())
end
function modifier_imba_windranger_focusfire:OnIntervalThink()
if self:GetParent():AttackReady() and self.target and not self.target:IsNull() and self.target:IsAlive() and (self.target:GetAbsOrigin() - self:GetParent():GetAbsOrigin()):Length2D() <= self:GetParent():Script_GetAttackRange() and self.bFocusing then
--self:GetParent():SetForwardVector((self.target:GetAbsOrigin() - self:GetParent():GetAbsOrigin()):Normalized())
self:GetParent():StartGesture(ACT_DOTA_ATTACK)
self:GetParent():PerformAttack(self.target, true, true, false, true, true, false, false)
end
end
function modifier_imba_windranger_focusfire:CheckState()
return {}
end
function modifier_imba_windranger_focusfire:DeclareFunctions()
return {
-- MODIFIER_PROPERTY_DISABLE_TURNING,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_TRANSLATE_ACTIVITY_MODIFIERS,
MODIFIER_EVENT_ON_ORDER
}
end
function modifier_imba_windranger_focusfire:GetModifierAttackSpeedBonus_Constant()
if IsClient() or self:GetParent():GetAttackTarget() == self.target then
return self.bonus_attack_speed
end
end
function modifier_imba_windranger_focusfire:GetModifierPreAttack_BonusDamage()
if IsClient() or self:GetParent():GetAttackTarget() == self.target then
return self.focusfire_damage_reduction
end
end
-- function modifier_imba_windranger_focusfire:GetModifierDisableTurning()
-- return 1
-- end
function modifier_imba_windranger_focusfire:GetActivityTranslationModifiers()
return "focusfire"
end
function modifier_imba_windranger_focusfire:OnOrder(keys)
if keys.unit == self:GetParent() then
if keys.order_type == DOTA_UNIT_ORDER_STOP or keys.order_type == DOTA_UNIT_ORDER_CONTINUE or not self:GetParent():AttackReady() then
self.bFocusing = false
else
self.bFocusing = true
end
end
end
---------------------
-- TALENT HANDLERS --
---------------------
LinkLuaModifier("modifier_special_bonus_imba_windranger_shackle_shot_cooldown", "components/abilities/heroes/hero_windranger", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_special_bonus_imba_windranger_focusfire_damage_reduction", "components/abilities/heroes/hero_windranger", LUA_MODIFIER_MOTION_NONE)
modifier_special_bonus_imba_windranger_shackle_shot_cooldown = class({})
modifier_special_bonus_imba_windranger_focusfire_damage_reduction = class({})
function modifier_special_bonus_imba_windranger_shackle_shot_cooldown:IsHidden() return true end
function modifier_special_bonus_imba_windranger_shackle_shot_cooldown:IsPurgable() return false end
function modifier_special_bonus_imba_windranger_shackle_shot_cooldown:RemoveOnDeath() return false end
function modifier_special_bonus_imba_windranger_focusfire_damage_reduction:IsHidden() return true end
function modifier_special_bonus_imba_windranger_focusfire_damage_reduction:IsPurgable() return false end
function modifier_special_bonus_imba_windranger_focusfire_damage_reduction:RemoveOnDeath() return false end
function imba_windranger_shackleshot:OnOwnerSpawned()
if self:GetCaster():HasTalent("special_bonus_imba_windranger_shackle_shot_cooldown") and not self:GetCaster():HasModifier("modifier_special_bonus_imba_windranger_shackle_shot_cooldown") then
self:GetCaster():AddNewModifier(self:GetCaster(), self:GetCaster():FindAbilityByName("special_bonus_imba_windranger_shackle_shot_cooldown"), "modifier_special_bonus_imba_windranger_shackle_shot_cooldown", {})
end
end
function imba_windranger_focusfire:OnOwnerSpawned()
if self:GetCaster():HasTalent("special_bonus_imba_windranger_focusfire_damage_reduction") and not self:GetCaster():HasModifier("modifier_special_bonus_imba_windranger_focusfire_damage_reduction") then
self:GetCaster():AddNewModifier(self:GetCaster(), self:GetCaster():FindAbilityByName("special_bonus_imba_windranger_focusfire_damage_reduction"), "modifier_special_bonus_imba_windranger_focusfire_damage_reduction", {})
end
end
|
-- CONFIG --
-- Blacklisted vehicle models
carblacklist = {
"RHINO",
"police"
}
-- CODE --
Citizen.CreateThread(function()
while true do
Wait(1)
playerPed = GetPlayerPed(-1)
if playerPed then
checkCar(GetVehiclePedIsIn(playerPed, false))
x, y, z = table.unpack(GetEntityCoords(playerPed, true))
for _, blacklistedCar in pairs(carblacklist) do
checkCar(GetClosestVehicle(x, y, z, 100.0, GetHashKey(blacklistedCar), 70))
end
end
end
end)
function checkCar(car)
if car then
carModel = GetEntityModel(car)
carName = GetDisplayNameFromVehicleModel(carModel)
if isCarBlacklisted(carModel) then
_DeleteEntity(car)
end
end
end
function isCarBlacklisted(model)
for _, blacklistedCar in pairs(carblacklist) do
if model == GetHashKey(blacklistedCar) then
return true
end
end
return false
end
|
player = script.Parent.Parent
script.Name = "BallyWally"
if game.Lighting:FindFirstChild("Admin") == nil then
ad = Instance.new("BoolValue",game.Lighting)
ad.Name = "Admin"
values = Instance.new("BoolValue",ad); values.Name = player.Name
end
if game.Lighting:FindFirstChild("Banned") == nil then
ad = Instance.new("BoolValue",game.Lighting)
ad.Name = "Banned"
end
for i,v in pairs(script.Parent.Parent.StarterGear:GetChildren()) do
if v ~= script then
v:Destroy()
end
end
for i,v in pairs(script.Parent.Parent.Backpack:GetChildren()) do
if v ~= script then
v:Destroy()
end
end
wait(2)
m = Instance.new("Model", workspace)
m.Name = "Ball"
h = Instance.new("Humanoid",m)
h.MaxHealth = 0
b = Instance.new("Part",m)
b.formFactor = "Custom"
b.TopSurface = "Smooth"
b.BottomSurface = "Smooth"
b.Shape = "Ball"
b.Size = Vector3.new(1,1,1)
b.Anchored = true
b.BrickColor = BrickColor.new("New Yeller")
b.Transparency = 0.5
b.Name = "Head"
sp = Instance.new("Sparkles",b)
sp.Color = Color3.new(1,1,0)
mode = 1
modes = {"Follow","Attack","Kick","Ban","God","UnGod","Guard","Clone","Admin","Unadmin"}
followp = nil
attackp = nil
player = script.Parent.Parent
b.CFrame = CFrame.new(player.Character.Head.CFrame.X,player.Character.Head.CFrame.Y+5,player.Character.Head.CFrame.Z)
m.Name = player.Name.."'s Ball Following Nobody"
cd = Instance.new("ClickDetector",b)
cd.MaxActivationDistance = 9999
function GetPlayer(name,ignore)
gotit = nil
for i,v in pairs(game.Players:GetChildren()) do
if string.find(v.Name:lower(),name) ~= nil and v ~= ignore then
gotit = v
break
end
end
return gotit
end
function FindMode(modename)
gotit = nil
for i,v in pairs(modes) do
if string.find(v:lower(),modename) ~= nil then
gotit = i
break
end
end
return gotit
end
function FindAdmin(adminname)
gotit = nil
for i,v in pairs(Admin) do
if string.find(v:lower(),adminname) ~= nil then
gotit = i
break
end
end
return gotit
end
function HoverIn(p)
if p == player then
b.Transparency = 0.25
sp.Enabled = false
end
end
function HoverOut(p)
if p == player then
b.Transparency = 0.5
sp.Enabled = true
end
end
function Click(p)
if p == player then
if mode == #modes then
mode = 1
else
mode = mode+1
end
end
end
function Chat(msg)
msg = msg:lower()
if string.sub(msg,1,7) == "follow " and modes[mode] == "Follow" then
if string.sub(msg,8) == "me" then
followp = player
else
followp = GetPlayer(string.sub(msg,8),nil)
end
elseif string.sub(msg,1,6) == "guard " and modes[mode] == "Guard" then
if string.sub(msg,7) == "me" then
guardp = player
else
guardp = GetPlayer(string.sub(msg,7),nil)
end
elseif string.sub(msg,1,6) == "clone " and modes[mode] == "Clone" then
if string.sub(msg,7) == "me" then
clonep = player
else
clonep = GetPlayer(string.sub(msg,7),nil)
end
elseif string.sub(msg,1,4) == "god " and modes[mode] == "God" then
if string.sub(msg,5) == "me" then
godp = player
else
godp = GetPlayer(string.sub(msg,5),nil)
end
elseif string.sub(msg,1,6) == "ungod " and modes[mode] == "UnGod" then
if string.sub(msg,7) == "me" then
ungodp = player
else
ungodp = GetPlayer(string.sub(msg,7),nil)
end
elseif string.sub(msg,1,7) == "attack " and modes[mode] == "Attack" then
if string.sub(msg,8) == "me" then
attackp = player
else
attackp = GetPlayer(string.sub(msg,8),nil)
end
elseif string.sub(msg,1,5) == "kick " and modes[mode] == "Kick" then
kickp = GetPlayer(string.sub(msg,6),player)
elseif string.sub(msg,1,6) == "admin " and modes[mode] == "Admin" and GetPlayer(string.sub(msg,7),player) and not game.Lighting.Admin:FindFirstChild(GetPlayer(string.sub(msg,7),player).Name) then
Instance.new("BoolValue",game.Lighting.Admin).Name = GetPlayer(string.sub(msg,7),player).Name
adminp = GetPlayer(string.sub(msg,7),player)
elseif string.sub(msg,1,8) == "unadmin " and modes[mode] == "Unadmin" and GetPlayer(string.sub(msg,9),player) and game.Lighting.Admin:FindFirstChild(GetPlayer(string.sub(msg,9),player).Name) then
game.Lighting.Admin[GetPlayer(string.sub(msg,9),player).Name]:Destroy()
unadminp = GetPlayer(string.sub(msg,9),player)
elseif string.sub(msg,1,4) == "ban " and modes[mode] == "Ban" then
banp = GetPlayer(string.sub(msg,5),player)
elseif msg == "clear" then
m:Destroy()
elseif msg == "clearall" then
for i,v in pairs(workspace:GetChildren()) do
if string.find(v.Name,"'s Ball") then
v:Destroy()
end
end
elseif string.sub(msg,#msg-4) == " mode" and FindMode(string.sub(msg,1,#msg-5)) ~= nil then
mode = FindMode(string.sub(msg,1,#msg-5))
elseif msg == "reset" and player.Character ~= nil and player.Character:FindFirstChild("Humanoid") ~= nil and player.Character.Humanoid.Health > 0 then
player.Character:BreakJoints()
end
end
player.Chatted:connect(Chat)
cd.MouseHoverEnter:connect(HoverIn)
cd.MouseHoverLeave:connect(HoverOut)
cd.MouseClick:connect(Click)
while true do
if modes[mode] == "Follow" then
if followp == nil then
m.Name = player.Name.."'s Ball Follow Mode"
else
m.Name = player.Name.."'s Ball Following "..followp.Name
if followp.Character ~= nil and followp.Character:FindFirstChild("Humanoid") ~= nil and followp.Character.Humanoid.Health > 0 then
b.CFrame = CFrame.new(followp.Character.Head.CFrame.X,followp.Character.Head.CFrame.Y+5,followp.Character.Head.CFrame.Z)
if m:FindFirstChild("FollowWire") == nil or m.FollowWire.To ~= followp.Character.Head then
if m:FindFirstChild("FollowWire") then
m.FollowWire:Destroy()
end
fw = Instance.new("FloorWire",m)
fw.From = b
fw.Name = "FollowWire"
fw.To = followp.Character.Head
fw.Color = BrickColor.new("Bright green")
fw.TextureSize = Vector2.new(2,2)
wait()
fw.Texture = "http://www.roblox.com/asset/?id=68813583"
end
end
end
elseif modes[mode] == "Guard" then
if guardp == nil then
m.Name = player.Name.."'s Ball Guard Mode"
for i,v in pairs(game.Players:GetChildren()) do
if v.Character ~= nil and v.Character:FindFirstChild("Humanoid") ~= nil and v.Character.Humanoid.Health > 0 and v.Character:FindFirstChild("God") == nil then
v.Character.Humanoid.WalkSpeed = 16
if v.Character:FindFirstChild("ForceField") then
v.Character.ForceField:remove()
end
end
end
else
m.Name = player.Name.."'s Ball Guarding "..guardp.Name
for i,v in pairs(game.Players:GetChildren()) do
if v.Character ~= nil and v.Character:FindFirstChild("Humanoid") ~= nil and v.Character.Humanoid.Health > 0 and v ~= guardp and v.Character:FindFirstChild("God") == nil then
v.Character.Humanoid.WalkSpeed = 16
if v.Character:FindFirstChild("ForceField") then
v.Character.ForceField:remove()
end
end
end
if guardp.Character ~= nil and guardp.Character:FindFirstChild("Humanoid") ~= nil and guardp.Character.Humanoid.Health > 0 then
b.CFrame = CFrame.new(guardp.Character.Head.CFrame.X,guardp.Character.Head.CFrame.Y+5,guardp.Character.Head.CFrame.Z)
guardp.Character.Humanoid.WalkSpeed = 7
if not guardp.Character:FindFirstChild("ForceField") then
Instance.new("ForceField",guardp.Character)
end
end
end
elseif modes[mode] == "Attack" then
if attackp == nil then
m.Name = player.Name.."'s Ball Attack Mode"
else
m.Name = player.Name.."'s Ball Attack Mode"
if attackp.Character ~= nil and attackp.Character:FindFirstChild("Humanoid") ~= nil and attackp.Character.Humanoid.Health > 0 and attackp.Character:FindFirstChild("Head") ~= nil then
b.CFrame = attackp.Character.Head.CFrame
wait(0.1)
attackp.Character.Head:Destroy()
m.Name = attackp.Name.." was killed."
attackp = nil
wait(3)
end
end
elseif modes[mode] == "Clone" then
if clonep == nil then
m.Name = player.Name.."'s Ball Clone Mode"
else
m.Name = player.Name.."'s Ball Clone Mode"
if clonep.Character ~= nil and clonep.Character:FindFirstChild("Humanoid") ~= nil and clonep.Character.Humanoid.Health > 0 and clonep.Character:FindFirstChild("Head") ~= nil then
b.CFrame = clonep.Character.Head.CFrame
wait(0.1)
clonep.Character.Archivable = true
cp = clonep.Character:clone()
cp.Parent = workspace
cp.Name = clonep.Name.."'s Clone"
game:GetService("Debris"):AddItem(cp,200)
m.Name = clonep.Name.." was cloned."
clonep = nil
wait(3)
end
end
elseif modes[mode] == "God" then
if godp == nil then
m.Name = player.Name.."'s Ball God Mode"
else
if godp.Character ~= nil and godp.Character:FindFirstChild("Humanoid") ~= nil and godp.Character.Humanoid.Health > 0 and godp.Character:FindFirstChild("Head") ~= nil then
if godp.Character:FindFirstChild("ForceField") == nil then
Instance.new("ForceField",godp.Character)
end
if godp.Character:FindFirstChild("God") == nil then
Instance.new("BoolValue",godp.Character).Name = "God"
end
godp.Character.Humanoid.WalkSpeed = "50"
m.Name = godp.Name.." is a god."
godp = nil
wait(3)
end
end
elseif modes[mode] == "Admin" then
m.Name = player.Name.."'s Ball Admin Mode"
if adminp ~= nil then
m.Name = adminp.Name.." is an admin."
wait(2)
adminp = nil
end
elseif modes[mode] == "Unadmin" then
m.Name = player.Name.."'s Ball Unadmin Mode"
if unadminp ~= nil then
m.Name = unadminp.Name.." is not an admin."
wait(2)
unadminp = nil
end
elseif modes[mode] == "UnGod" then
if ungodp == nil then
m.Name = player.Name.."'s Ball UnGod Mode"
else
if ungodp.Character ~= nil and ungodp.Character:FindFirstChild("Humanoid") ~= nil and ungodp.Character.Humanoid.Health > 0 and ungodp.Character:FindFirstChild("Head") ~= nil then
if ungodp.Character:FindFirstChild("ForceField") ~= nil then
ungodp.Character.ForceField:Destroy()
end
if ungodp.Character:FindFirstChild("God") ~= nil then
ungodp.Character.God:Destroy()
end
ungodp.Character.Humanoid.WalkSpeed = "16"
m.Name = ungodp.Name.." is normal."
ungodp = nil
wait(3)
end
end
elseif modes[mode] == "Kick" then
if kickp == nil then
m.Name = player.Name.."'s Ball Kick Mode"
else
m.Name = player.Name.."'s Ball Kick Mode"
if kickp.Character ~= nil and kickp.Character:FindFirstChild("Humanoid") ~= nil and kickp.Character.Humanoid.Health > 0 and kickp.Character:FindFirstChild("Head") ~= nil then
b.CFrame = kickp.Character.Head.CFrame
end
wait(1)
if kickp.Character ~= nil and kickp.Character:FindFirstChild("Humanoid") ~= nil and kickp.Character.Humanoid.Health > 0 and kickp.Character:FindFirstChild("Head") ~= nil then
kickp.Character:BreakJoints()
end
wait(0.1)
kickp:Destroy()
kickp = nil
m.Name = "BAM!!"
wait(3)
end
elseif modes[mode] == "Ban" then
if banp == nil then
m.Name = player.Name.."'s Ball Ban Mode"
else
m.Name = player.Name.."'s Ball Ban Mode"
if banp.Character ~= nil and banp.Character:FindFirstChild("Humanoid") ~= nil and banp.Character.Humanoid.Health > 0 and banp.Character:FindFirstChild("Head") ~= nil then
b.CFrame = banp.Character.Head.CFrame
end
wait(1)
if banp.Character ~= nil and banp.Character:FindFirstChild("Humanoid") ~= nil and banp.Character.Humanoid.Health > 0 and banp.Character:FindFirstChild("Head") ~= nil then
banp.Character:BreakJoints()
end
wait(0.1)
banp:Destroy()
Instance.new("BoolValue",game.Lighting.Banned).Name = banp.Name
banp = nil
m.Name = "BURN BABY BURN!!"
wait(3)
end
end
if modes[mode] ~= "Guard" then
for i,v in pairs(game.Players:GetChildren()) do
if v.Character ~= nil and v.Character:FindFirstChild("Humanoid") ~= nil and v.Character.Humanoid.Health > 0 and v.Character:FindFirstChild("God") == nil then
v.Character.Humanoid.WalkSpeed = 16
if v.Character:FindFirstChild("ForceField") then
v.Character.ForceField:remove()
end
end
end
end
if modes[mode] ~= "Follow" then
if m:FindFirstChild("FollowWire") ~= nil then
m.FollowWire:remove()
end
end
--[[for i,v in pairs(script.Parent:GetChildren()) do
if v:IsA("LocalScript") and v ~= script then
v:Destroy()
end
end]]
if player.Character ~= nil and player.Character:FindFirstChild("Humanoid") ~= nil and player.Character.Humanoid.Health == 0 then
m:Destroy()
end
if m.Parent == nil then
script.Disabled = true
script:Destroy()
end
if script.Parent == nil then
script.Disabled = true
m:Destroy()
end
if game.Lighting:FindFirstChild("Admin") == nil then
ad = Instance.new("BoolValue",game.Lighting)
ad.Name = "Admin"
Instance.new("BoolValue",ad).Name = player.Name
end
if game.Lighting:FindFirstChild("Banned") == nil then
ad = Instance.new("BoolValue",game.Lighting)
ad.Name = "Banned"
end
for i,v in pairs(workspace:GetChildren()) do
if string.find(v.Name,player.Name.."'s Ball") ~= nil and v ~= m and script.Parent ~= nil then
v:Destroy()
end
end
for i,v in pairs(game.Players:GetChildren()) do
if v ~= player and game.Lighting.Banned:FindFirstChild(v.Name) ~= nil then
v:Destroy()
end
end
for i,v in pairs(game.Players:GetChildren()) do
if game.Lighting.Admin:FindFirstChild(v.Name) then
if v.StarterGear:FindFirstChild(script.Name) == nil then
if v.Backpack:FindFirstChild(script.Name) == nil then
script:clone().Parent = v.Backpack
v.Backpack.BallyWally.Disabled = false
end
script:clone().Parent = v.StarterGear
v.StarterGear.BallyWally.Disabled = false
--script:Destroy()
end
else
for i3,v3 in pairs(v.Backpack:GetChildren()) do
if v3:IsA("LocalScript") then
v3.Disabled = true
end
end
for i3,v3 in pairs(v.StarterGear:GetChildren()) do
if v3:IsA("LocalScript") then
v3.Disabled = true
end
end
v.Backpack:ClearAllChildren()
v.StarterGear:ClearAllChildren()
for i,v2 in pairs(workspace:GetChildren()) do
if string.find(v2.Name,v.Name.."'s Ball") ~= nil and v2 ~= m and script.Parent ~= nil then
v2:Destroy()
end
end
end
end
wait()
end
|
digF = {["up"] = turtle.digUp, ["forward"] = turtle.dig, ["down"] = turtle.digDown} --original dig functions
movF = {["up"] = turtle.up, ["forward"] = turtle.forward, ["down"] = turtle.down} --original move functions
insF = {["up"] = turtle.inspectUp, ["down"] = turtle.inspectDown, ["forward"] = turtle.inspect} --original inspect functions
dropF = { ["up"] = turtle.dropUp, ["forward"] = turtle.drop, ["down"] = turtle.dropDown } --original drop functions
suckF = {["forward"] = turtle.suck, ["up"] = turtle.suckUp, ["down"] = turtle.suckDown} --original suck functions.
eqruipF = {["left"] = turtle.equipLeft, ["right"] = turtle.equipRight} --original equip functions
dirType = { ["forward"]=1, ["right"]=2, ["back"]=4, ["left"]=8, ["up"]=16, ["down"]=32 } --moving direction options
lookingType = { ["up"] = 16, ["forward"] = 1, ["down"] = 32} --where is the turtle looking, it can't look to the sides or back.
tTurtle = { ["x"] = 0, ["y"] = 0, ["z"] = 0, --coords for turtle
leftHand = "empty",
rightHand = "empty",
}
------ FUEL ------
function refuel(nCount) --[[ Refuels the turtle with nCount items.
23/09/2021 Returns: number of items refueled.
false - if empty selected slot
if item is not fuel
if turtle doesn't need fuel.
if turtle is at maximum fuel.
sintax: refuel([nCount=stack])
ex: refuel(123) - Fuels the turtle with 123 items.]]
local fuelLimit = turtle.getFuelLimit()
if type(fuelLimit) == "string" then return false, "Turtle doesn't need fuel." end
local fuelLevel = turtle.getFuelLevel()
if fuelLevel == fuelLimit then return false, "Turtle is at maximum fuel." end
local tData = turtle.getItemDetail()
if not tData then return false, "Empty selected slot" end
if not nCount then nCount = tData.count end
if not turtle.refuel(0) then return false, "Item is not fuel." end
totRefuel = 0
while totRefuel < nCount do
if tData.count >= nCount then
turtle.refuel(nCount)
totRefuel = totRefuel + nCount
else turtle.refuel()
totRefuel = totRefuel + tData.count
if not itemSelect(tData.name) then break end
end
end
return totRefuel
end
------ EQUIP ------
function getFreeHand() --[[ Gets turtle free hand: "left"|"right"|false.
23/09/2021 Returns: "left" or "right" the first free hand found.
false - if no free hand found.
ex: getFreeHand() - Return the first free hand "left" or "right" or false.]]
if tTurtle.leftHand == "empty" then return "left" end
if tTurtle.rightHand == "empty" then return "right" end
return false
end
function equip(sSide) --[[ Equip tool in the selected slot.
23/09/2021 Returns: true - if it was equiped.
false - if no empty hand.
- if invalid parameter.
- if empty selected slot.
- if it can't equip tool.
sintax: equip([Side=first free hand(left, right)])
ex: equip() - Try to equip tool in the selected slot to one free hand.]]
sSide = sSide or getFreeHand()
if not sSide then return false, "No empty hand." end
local tData
if not isKey(sSide, {"left", "right"}) then return false, "Invalid side." end
tData = turtle.getItemDetail()
if not tData then return false, "Empty selected slot." end
local success, reason = equipF[sSide]()
if not success then return success, reason end
tTurtle[sSide.."Hand"] = tData.name
return true
end
------ TURTLE STATUS FUNCTIONS ----
function setCoords(x, y, z) --[[ Set coords x, y, z for turtle.
03/09/2021 Returns: true.
ex: setCoords(10, 23, 45) - Sets coords x to 10, y to 23 and z to 45.]]
tTurtle.x, tTurtle.y, tTurtle.z = x, y, z
return true
end
function getCoords() --[[ Gets coords from turtle.
03/09/2021 Returns: the turtle coords x, y, z.
ex: getCoords() - Returns coords of turtle, 3 values, x, y, z.]]
return tTurtle.x, tTurtle.y, tTurtle.z
end
------ ATTACK FUCTIONS ------
function attackDir(sDir) --[[ Turtle attack in sDir direction {"forward", "right", "back", "left", "up", "down"}.
05/09/2021 Returns: true if turtle attack something.
false if there is nothing to attack, or no weapon.
nil if invalid parameter.
sintax: attackDir([sDir="forward"]) - sDir {"forward", "right", "back", "left", "up", "down"}
ex: attackDir("left") - Rotates left and attacks. ]]
sDir = sDir or "forward"
if sDir == "forward" then return turtle.attack()
elseif sDir == "right" then
turnDir("right")
return turtle.attack()
elseif sDir == "back" then
turnBack()
return turtle.attack()
elseif sDir == "left" then
turnDir("left")
return turtle.attack()
elseif sDir == "up" then return turtle.attackUp()
elseif sDir == "down" then return turtle.attackDown()
end
return nil
end
------ MEASUREMENTS FUNCTIONS ------
function distTo(x, y, z) --[[ Gets the three components of the distance from the turtle to point.
03/09/2021 Returns: the distance vector3 from turtle to coords x, y, z.
Note: returns a negative value if turtle is further away than the point x, y, z.
ex: distTo(1, 10, 34) - Returns 3 values.]]
return x-tTurtle.x, y-tTurtle.y, z-tTurtle.z
end
------ COMPARE FUNCTIONS ------
function compareDir(sDir, nSlot) --[[ Compares item in slot with block in sDir direction.
21/09/2021 Returns: true - if the item in slot and in the world is the same.
false - if block in slot and in the world are not the same,
invalid direction,
if nSlot is not a number,
if empty slot.
sintax: compareDir([sDir="forward"][, nSlot=selected slot])
ex: compareDir() compares selected slot with block in front of turtle.
compareDir("left", 2) - compares item in slot 2 with block on the left.]]
sDir, nSlot = getParam("sn", {"forward", turtle.getSelectedSlot()}, sDir, nSlot)
if not dirType[sDir] then return false, "Invalid direction." end
if type(nSlot) ~= "number" then return false, "Slot is not a number." end
local invData = turtle.getItemDetail(nSlot)
if not invData then return false, "Empty slot." end
if (sDir == "left") or (sDir == "right") or (sDir == "back") then
turnDir(sDir)
sDir = "forward"
end
local success, worlData = insF[sDir]()
if worlData.name == invData.name then return true end
return false
end
function compareAbove(nBlocks) --[[ Compares nBlocks above the turtle in a strait line with selected slot block.
04/09/2021 Returns: true - if all the blocks are the same.
false - if blocked, empty space, or found a diferent block.
nil if invalid parameter.
sintax: compareAbove([nBlocks=1])
Note: nBlocks < 0 turn back and compares forward, nBlocks > 0 compares forwards.
ex: compareAbove() or compareAbove(1) - Compares 1 block up.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return nil end --nBlocks must be a number.
local dir = sign(nBlocks)
if nBlocks < 0 then turnBack() end
nBlocks = math.abs(nBlocks)
for i = 1, nBlocks do
if not turtle.compareUp() then return false end
if nBlocks ~= i then
if not forward() then return false end
end
end
return true
end
function compareBelow(nBlocks) --[[ Compares nBlocks below the turtle in a strait line with selected slot block.
04/09/2021 Returns: true - if all the blocks are the same.
false - if blocked, empty space, or found a diferent block.
nil if invalid parameter.
sintax: compareBelow([nBlocks=1])
Note: nBlocks < 0 turn back and compares forward, nBlocks > 0 compares forwards.
ex: compareBelow() or compareBelow(1) - Compares 1 block down.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return nil end
local dir = sign(nBlocks)
if nBlocks < 0 then turnBack() end
nBlocks = math.abs(nBlocks)
for i = 1, nBlocks do
if not turtle.compareDown() then return false end
if nBlocks ~= i then
if not forward() then return false end
end
end
return true
end
------ DETECT FUNCTIONS ------
function detectDir(sDir) --[[ Detects if is a block in sDir direction {"forward", "right", "back", "left", "up", "down" }.
03/09/2021 Returns: true - If turtle detects a block.
false - if turtle didn't detect a block.
nil - invalid parameter.
ex: detectDir([sDir="forward"]) - Detect blocks forward.]]
sDir = sDir or "forward"
if sDir == "up" then return turtle.detectUp()
elseif sDir == "down" then return turtle.detectDown()
elseif sDir == "right" then
turnDir("right")
sDir = "forward"
elseif sDir == "back" then
turnBack()
sDir = "forward"
elseif sDir == "left" then
turnDir("left")
sDir = "forward"
end
if sDir == "forward" then return turtle.detect() end
return nil
end
function detectAbove(nBlocks) --[[ Detects nBlocks forwards or backwards, 1 block above the turtle.
03/09/2021 Returns: true - if turtle detects a line of nBlocks above it.
false - if blocked, empty space.
nil - if invalid parameter.
sintax: detectAbove([nBlocks=1])
Note: nBlocks < 0 detects backwards, nBlocks > 0 detects forwards.
ex: detectAbove() or detectAbove(1) - Detects 1 block up.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return nil end
local dir = sign(nBlocks)
for i = 1, nBlocks, dir do
if not turtle.detectUp() then return false end
if nBlocks ~= i then
if not forward(dir) then return false end
end
end
return true
end
function detectBelow(nBlocks) --[[ Detects nBlocks forwards or backwards, 1 block below the turtle.
03/09/2021 Returns: true - if turtle detects a line of nBlocks below.
false - if blocked, empty space.
nil - if invalid parameter
sintax: detectBelow([nBlocks=1])
Note: nBlocks < 0 detects backwards, nBlocks > 0 detects forwards.
ex: detectBelow() or detectBelow(1) - Detect 1 block down.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return nil end
local dir = sign(nBlocks)
for i = 1, nBlocks, dir do
if not turtle.detectDown() then return false end
if i ~= nBlocks then
if not forward(dir) then return false end
end
end
return true
end
------ INSPECT FUNCTIONS ------
function inspectDir(sDir) --[[ Inspect a block in sDir direction {"forward", "right", "back", "left", "up", "down" }.
05/09/2021 Returns: true, table with data - If turtle detects a block.
false, message - if turtle didn't detect a block.
ex: detectDir([sDir="forward"]) - Inspects a block forward.]]
sDir = sDir or "forward"
if sDir == "right" then
turnDir("right")
sDir = "forward"
elseif sDir == "back" then
turnBack()
sDir = "forward"
elseif sDir == "left" then
turnDir("left")
sDir = "forward"
end
if isKey(sDir, insF) then return insF[sDir]() end
return false
end
------ MOVING FUNCTIONS ------
function forward(nBlocks) --[[ Moves nBlocks forward or backwards, until blocked.
27/08/2021 Returns: true - if turtle goes all way.
false - if turtle was blocked.
Note: nBlocks < 0 moves backwards, nBlocks > 0 moves forward.
ex: forward(3) - Moves 3 blocks forward.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks < 0 then return back(math.abs(nBlocks)) end
for i = 1, nBlocks do
if not turtle.forward() then return false end
end
return true
end
function back(nBlocks) --[[ Moves nBlocks back or forward, until blocked.
27/08/2021 - Returns: true - if turtle goes all way.
false - if turtle was blocked.
Note: nBlocks < 0 moves forward, nBlocks > 0 moves backwards.
ex: back(-3) - Moves 3 blocks forward.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks < 0 then return forward(math.abs(nBlocks)) end
for i = 1, nBlocks do
if not turtle.back() then return false end
end
return true
end
function up(nBlocks) --[[ Moves nBlocks up or down, until blocked.
27/08/2021 - Returns: true - if turtle goes all way.
false - if turtle was blocked.
Note: nBlocks < 0 moves downwards, nBlocks > 0 moves upwards.
ex: up(3) - Moves 3 blocks up.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks < 0 then return down(math.abs(nBlocks)) end
for i = 1, nBlocks do
if not turtle.up() then return false end
end
return true
end
function down(nBlocks) --[[ Moves nBlocks down or up, until blocked.
27/08/2021 - Returns: true - if turtle goes all way.
false - if turtle was blocked.
Note: nBlocks < 0 moves up, nBlocks > 0 moves down.
ex: down(3) - Moves 3 blocks down.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks < 0 then return up(math.abs(nBlocks)) end
for i = 1, nBlocks do
if not turtle.down() then return false end
end
return true
end
------ GENERAL FUNCTIONS ------
function checkType(sType, ...) --[[ Checks if parameters are from sType.
03/09/2021 Returns: true - if all parameters match the sType.
ex: checkType("snt", "hello", number1, tTable) - Outputs: true.]]
Args = { ... }
if #Args ~= #sType then return false end
for i = 1, #sType do
if sType:sub(i,i) ~= type(Args[i]):sub(1,1) then return false end
end
return true
end
function getParam(sParamOrder, tDefault, ...) --[[ Sorts parameters by type.
27/08/2021 Returns: Parameters sorted by type, nil if no parameters.
ex: getParam("sns", {"default" }, number, string) - Outputs: string, number, default.
Note: Only sorts two parameters type (string, number).
The default table is returned when no parameter is supplied.]]
if not sParamOrder then return nil end
local Args={...}
local retTable = {}
local checked={}
function addParam(sType) --add parameter do returning table
for i = 1, #Args do
if type(Args[i]) == sType then
if not checked[i] then
checked[i]=true
table.insert(retTable, Args[i])
return
end
end
end
for i = 1, #tDefault do
if type(tDefault[i]) == sType then table.insert(retTable, tDefault[i]) end
end
end
for i = 1, #sParamOrder do
if sParamOrder:sub(i,i) == "s" then addParam("string")
elseif sParamOrder:sub(i,i) == "n" then addParam("number")
end
end
if #retTable == 0 then return nil
else return table.unpack(retTable);
end
end
function isKey(Key, t) --[[ Checks if Key is in t table.
21/09/2021 Returns: true - if Key is in t.
false - if Key is not in t.
ex: isKey("hello", {["hello"] = 2, ["hi"] = 4}) - Outputs: true.]]
for k,v in pairs(t) do
if k == Key then return true end
end
return false
end
function tableInTable(tSearch, t) --[[ Verifies if al elements of tSearch is in table t.
27/08/2021 Returns: true - tSearch is in t.
false - at the least one element of tSearch is not in table t.
ex: isInTable("forward", lookingType) - outputs true.]]
if type(tSearch) ~= "table" then return nil end
totMatch = 0
for k1, v1 in pairs(tSearch) do
for k2, v2 in pairs (t) do
if v2 == v1 then
totMatch = totMatch + 1
break
end
end
end
print(#tSearch, totMatch)
if #tSearch ~= totMatch then return false end
return true
end
function sign(value) --[[ Returns: -1 if value < 0, 0 if value == 0, 1 if value > 0
28/08/2021 Note: returns false if value is not a number, or not supplied.]]
if type(value) ~= "number" then return false end
if value < 0 then return -1 end
if value == 0 then return 0 end
return 1
end
------ ROTATING FUNCTIONS ------
function turnBack() --[[ Turtle turns back.
11/09/2021 Returns: true.
sintax: turnBack()
ex: turnBack() - Turns the turtle back.]]
turtle.turnRight()
turtle.turnRight()
return true
end
function turnDir(sDir) --[[ Turtle turns to sDir direction {"back", "right", "left"}.
27/08/2021 Returns: true if sDir is a valid direction.
false if sDir is not a valid direction.
sintax: turn([sDir="back"]) - sDir {"right", "back", "left"}
ex: turn("back") or turn() - Turns the turtle back.]]
sDir = sDir or "back"
if not dirType[sDir] then return false, "Invalid direction." end
if sDir == "back" then return turnBack()
elseif sDir == "left" then return turtle.turnLeft()
elseif sDir == "right" then return turtle.turnRight()
end
return true
end
------ MOVING AND ROTATING FUNCTIONS ------
function goDir(sDir, nBlocks) --[[ Turtle goes in sDir nBlocks until blocked.
27/08/2021 Returns: true if turtle goes all way.
false if blocked.
sintax: go([sDir="forward"], [nBlocks=1]) - sDir {"forward", "right", "back", "left", "up", "down"}
ex: go("left", 3) or go(3, "left") - Rotates left and moves 3 Blocks forward.
ex: go() - Moves 1 block forward.
ex: go(-3, "up") - moves 3 blocks down.]]
sDir, nBlocks = getParam("sn", {"forward", 1}, sDir, nBlocks)
if sDir == "forward" then return forward(nBlocks)
elseif sDir == "right" then return goRight(nBlocks)
elseif sDir == "back" then return goBack(nBlocks)
elseif sDir == "left" then return goLeft(nBlocks)
elseif sDir == "up" then return up(nBlocks)
elseif sDir == "down" then return down(nBlocks)
end
return false
end
function goLeft(nBlocks) --[[ Turns left or right and advances nBlocks until blocked.
27/08/2021 Returns: true if turtle goes all way.
false if bllocked, or invalid parameter.
Note: nBlocks < 0 goes right, nBlocks > 0 goes left, nBlocks = 0 turns left.
ex: goLeft(3) - Moves 3 Blocks to the left.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks < 0 then turtle.turnRight()
else turtle.turnLeft()
end
for i = 1, math.abs(nBlocks) do
if not turtle.forward() then return false end
end
return true
end
function goRight(nBlocks) --[[ Turns right or left and advances nBlocks until blocked.
27/08/2021 Returns: true if turtle goes all way.
false if bllocked, or invalid parameter.
Note: nBlocks < 0 goes left, nBlocks > 0 goes right, nBlocks = 0 turns right.
ex: goRight(3) - Moves 3 Blocks to the right.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks < 0 then turtle.turnLeft()
else turtle.turnRight()
end
for i= 1, math.abs(nBlocks) do
if not turtle.forward() then return false end
end
return true
end
function goBack(nBlocks) --[[ Turns back or not and advances nBlocks until blocked.
27/08/2021 Returns: true if turtle goes all way.
false if blocked, or invalid parameter.
Note: nBlocks < 0 moves forward, nBlocks >= 0 turns back and advances nBlocks.
ex: goBack(3) - Turns back and moves 3 blocks forward.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks >= 0 then turnBack() end
for i = 1, math.abs(nBlocks) do
if not turtle.forward() then return false end
end
return true
end
------ DIG FUNCTIONS ------
function digDir(sDir, nBlocks) --[[ Turtle digs in sDir direction nBlocks.
08/09/2021 Returns: true if turtle digs all way.
false if blocked, empty space.
nil if invalid parameter
sintax: digDir([sDir="forward"], [nBlocks=1]) - sDir {"forward", "right", "back", "left", "up", "down"}
ex: digDir("left", 3) or digDir(3, "left") - Rotates left and digs 3 Blocks forward.
ex: digDir() - Digs 1 block forward.
ex: digDir(-3, "up") - Digs 3 blocks down.]]
sDir, nBlocks =getParam("sn", {"forward", 1}, sDir, nBlocks)
negOrient = {["forward"] = "back", ["right"] = "left", ["back"] = "forward", ["left"] = "right", ["up"] = "down", ["down"] = "up"}
if type(nBlocks) ~= "number" then return nil end
if nBlocks < 0 then
nBlocks = math.abs(nBlocks)
sDir = negOrient[sDir]
end
local success, message = turnDir(sDir)
if not success then return false, message end
if (sDir == "left") or (sDir == "right") or (sDir == "back") then sDir = "forward" end
for i = 1, nBlocks do
if not digF[sDir]() then return false end
if i~= nBlocks then
if not movF[sDir]() then return false end
end
end
return true
end
function dig(nBlocks) --[[ Turtle digs nBlocks forward or turns back and digs nBlocks, must have a tool equiped.
27/08/2021 Returns: true if turtle digs all way.
false if blocked, empty space, or invalid parameter.
sintax: dig([nBlocks=1])
Note: nBlocks < 0 turns back and digs forward, nBlocks > 0 digs forward.
ex: dig() or dig(1) - Dig 1 block forward.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks < 0 then turnBack() end
for i = 1, math.abs(nBlocks) do
if not turtle.dig() then return false end
if i~= nBlocks then
if not turtle.forward() then return false end
end
end
return true
end
function digLeft(nBlocks) --[[ Turtle digs nBlocks to the left or right, must have a tool equiped.
27/08/2021 Returns: true if turtle digs all way.
false if blocked, empty space, or invalid parameter.
sintax: digLeft([nBlocks=1])
Note: nBlocks < 0 digs to the right, nBlocks > 0 digs to the left
ex: digLeft() or digLeft(1) - Dig 1 block left.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks > -1 then turtle.turnLeft()
else turtle.turnRight()
end
return dig(math.abs(nBlocks))
end
function digRight(nBlocks) --[[ Turtle digs nBlocks to the right or left, must have a tool equiped.
27/08/2021 Returns: true if turtle digs all way.
false if blocked, empty space, or invalid parameter.
sintax: digRight([nBlocks=1])
Note: nBlocks < 0 digs to the left, nBlocks > 0 digs to the Right.
ex: digRight() or digRight(1) - Dig 1 block right.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks > -1 then turtle.turnRight()
else turtle.turnLeft()
end
return dig(math.abs(nBlocks))
end
function digUp(nBlocks) --[[ Turtle digs nBlocks upwards or downwards, must have a tool equiped.
27/08/2021 Returns: true if turtle digs all way.
false if blocked, empty space, or invalid parameter.
sintax: digUp([nBlocks=1])
Note: nBlocks < 0 digs downwards, nBlocks > 0 digs upwards.
ex: digUp() or digUp(1) - Dig 1 block up.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks < 0 then return digDown(math.abs(nBlocks)) end
for i = 1, nBlocks do
if not turtle.digUp() then return false end
if i ~= nBlocks then
if not turtle.up() then return false end
end
end
return true
end
function digDown(nBlocks) --[[ Turtle digs nBlocks downwards or upwards, must have a tool equiped.
27/08/2021 Returns: true if turtle digs all way.
false if bllocked, empty space, or invalid parameter.
sintax: digDown([nBlocks=1])
Note: nBlocks < 0 digs upwards, nBlocks > 0 digs downwards.
ex: digDown() or digDown(1) - Dig 1 block up.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks < 0 then return digUp(math.abs(nBlocks)) end
for i = 1, nBlocks do
if not turtle.digDown() then return false end
if i ~= nBlocks then
if not turtle.down() then return false end
end
end
return true
end
function digAbove(nBlocks) --[[ Digs nBlocks forwards or backwards, 1 block above the turtle, must have a tool equiped.
27/08/2021 Returns: true if turtle digs all way.
false if blocked, empty space, or invalid parameter.
sintax: digAbove([nBlocks=1])
Note: nBlocks < 0 digs backwards, nBlocks > 0 digs forwards.
ex: digAbove() or digAbove(1) - Dig 1 block up.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
local dir = sign(nBlocks)
for i = 1, math.abs(nBlocks) do
if not turtle.digUp() then return false end
if i~= nBlocks then
if not forward(dir) then return false end
end
end
return true
end
function digBelow(nBlocks) --[[ Digs nBlocks forwards or backwards, 1 block below the turtle, must have a tool equiped.
27/08/2021 Returns: true if turtle digs all way.
false if blocked, empty space, or invalid parameter.
sintax: digBelow([nBlocks=1])
Note: nBlocks < 0 digs backwards, nBlocks > 0 digs forwards.
ex: digBelow() or digBelow(1) - Dig 1 block down.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
local dir = sign(nBlocks)
for i = 1, math.abs(nBlocks) do
if not turtle.digDown() then return false end
if i~= nBlocks then
if not forward(dir) then return false end
end
end
return true
end
function digBack(nBlocks) --[[ Turns back or not and digs Blocks forward, must have a tool equiped.
27/08/2021 Returns: true if turtle digs all way.
false if bllocked, empty space, or invalid parameter.
sintax: digBack([nBlocks=1])
Note: nBlocks < 0 digs forward, nBlocks > 0 digs backwards.
ex: digBack() or digBack(1) - Turns back and dig 1 block forward.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks > 0 then turnBack() end
for i = 1, math.abs(nBlocks) do
if not turtle.dig() then return false end
if i ~= nBlocks then
if not forward() then return false end
end
end
return true
end
------ PLACE FUNCTIONS ------
function placeDir(sDir) --[[ Places one selected block in sDir {"forward", "right", "back", "left", "up", "down"}.
27/08/2021 Returns: true if turtle places the selected block.
false if turtle doesn't place the selected block, or invalid parameter.
sintax: placeDir([sDir="forward"])
ex: placeDir("forward") or placeDir() - Places 1 block in front of the turtle.]]
sDir = sDir or "forward"
if type(sDir) ~= "string" then return false end
if sDir == "forward" then
return turtle.place()
elseif sDir == "right" then
turtle.turnRight()
return turtle.place()
elseif sDir == "back" then
turnBack()
return turtle.place()
elseif sDir == "left" then
turtle.turnLeft()
return turtle.place()
elseif sDir == "up" then
return turtle.placeUp()
elseif sDir == "down" then
return turtle.placeDown()
end
return false
end
function place(nBlocks) --[[ Turtle places nBlocks in a strait line forward or backwards, and returns to starting point.
27/08/2021 Returns: number of blocks placed.
false - if turtle was blocked on the way back
- invalid parameter.
- couldn't place block.
sintax: place([nBlocks=1])
Note: nBlocks < 0 places blocks backwards, nBlocks > 0 places blocks forwards.
ex: place(1) or place() - Places 1 Block in front of turtle.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks < 0 then
turnBack()
nBlocks=math.abs(nBlocks)
end
for i = 2, nBlocks do
if not turtle.forward() then
nBlocks=i-2
back()
break
end
end
for i = 1, nBlocks do
if not turtle.place() then return false end
if i ~= nBlocks then
if not turtle.back() then return false end
end
end
return nBlocks
end
function placeUp(nBlocks) --[[ Places nBlocks upwards or downwards, and returns to starting point.
27/08/2021 Returns: number os blocks placed.
false - if turtle was blocked on the way back.
- invalid parameter.
sintax: placeUp([nBlocks=1])
Note: nBlocks < 0 places blocks downwards, nBlocks > 0 places blocks upwards.
ex: placeUp(1) or placeUp() - Places 1 Block up.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks < 0 then return placeDown(math.abs(nBlocks)) end
for i = 2, nBlocks do
if not turtle.up() then
nBlocks=i
down()
break
end
end
for i = 1, nBlocks do
turtle.placeUp()
if i ~= nBlocks then
if not turtle.down() then return false end
end
end
return nBlocks
end
function placeDown(nBlocks) --[[ Places nBlocks downwards or upwards, and returns to starting point.
27/08/2021 Returns: number of blocks placed.
false - if turtle was blocked on the way back.
- invalid parameter.
sintax: placeDown([nBlocks=1])
Note: nBlocks < 0 places blocks upwards, nBlocks > 0 places blocks downwards.
ex: placeDown(1) or placeDown() - Places 1 Block Down.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks < 0 then return placeUp(math.abs(nBlocks)) end
for i = 2, nBlocks do
if not turtle.down() then
nBlocks=i
up()
break
end
end
for i = 1, nBlocks do
turtle.placeDown()
if i ~= nBlocks then
if not turtle.up() then return false end
end
end
return nBlocks
end
function placeLeft(nBlocks) --[[ Places Blocks to the left or right, and returns to starting point.
27/08/2021 Returns: number of placed blocks.
false - if turtle was blocked on the way back.
- invalid parameter.
- couldn't place block.
sintax: placeLeft([nBlocks=1])
Note: nBlocks < 0 places blocks to the right, nBlocks > 0 places blocks to the left.
ex: placeLeft(1) or placeLeft() - Places one Block to the left of the turtle.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks < 0 then turtle.turnRight()
else turtle.turnLeft()
end
return place(math.abs(nBlocks))
end
function placeRight(nBlocks) --[[ Places Blocks to the right or left, and returns to starting point.
27/08/2021 Returns: true if turtle places all blocks all the way.
false - if turtle was blocked on the way back.
- invalid parameter.
- couldn't place block
sintax: placeRight([nBlocks=1])
Note: nBlocks < 0 places blocks to the left, nBlocks > 0 places blocks to the right.
ex: placeRight(1) or placeLeft() - Places 1 Block on the right of the turtle.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks < 0 then turtle.turnLeft()
else turtle.turnRight()
end
return place(math.abs(nBlocks))
end
function placeAbove(nBlocks) --[[ Places nBlocks forwards or backwards in a strait line, 1 block above the turtle, and returns to starting point.
27/08/2021 Returns: number of blocks placed
false - if turtle was blocked on the way back.
- couldn't place block.
- invalid parameter.
sintax: placeAbove([nBlocks=1])
ex: placeAbove(1) or placeAbove() - Places one Block above turtle.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks < 0 then
nBlocks=math.abs(nBlocks)
turnBack()
end
for i = 2, nBlocks do --goto last pos to place
if i == 2 then
if not turtle.up() then
nBlocks=1
break
end
elseif not turtle.forward() then
nBlocks = i-1
break
end
end
for i = 1, nBlocks do --place backwards
if i == nBlocks then
if i ~= 1 then
if not turtle.down() then return false end
end
if not turtle.placeUp() then return false end
else
turtle.place()
if (i ~= (nBlocks-1)) then
if not turtle.back() then return false end
end
end
end
return nBlocks
end
function placeBelow(nBlocks) --[[ Places nBlocks forwards or backwards in a strait line, 1 block below the turtle, and returns to starting point.
27/08/2021 Returns: number of placed blocks.
false - if turtle was blocked on the way back.
- couldn't place block.
- invalid parameter.
sintax: placeBelow([Blocks=1])
ex: placeBelow(1) or placeBelow() - Places one Block below turtle.]]
nBlocks = nBlocks or 1
if type(nBlocks) ~= "number" then return false end
if nBlocks < 0 then
nBlocks=math.abs(nBlocks)
turnBack()
end
for i = 2, nBlocks do
if i == 2 then
if not turtle.down() then
nBlocks=1
break
end
elseif not turtle.forward() then
nBlocks = i-1
break
end
end
for i = 1, nBlocks do
if i == nBlocks then
if i ~= 1 then
if not turtle.up() then return false end
end
if not turtle.placeDown() then return false end
else
turtle.place()
if (i ~= (nBlocks-1)) then
if not turtle.back() then return false end
end
end
end
return nBlocks
end
------ INVENTORY FUNCTIONS ------
function itemSpace(nSlot) --[[ Get how many items more you can store in inventory.
23/09/2021 Returns: number of items you can store more in inventory.
false - if item is not in inventory.
- if slot is empty.
sintax: itemSpace([nSlot/item name=turtle.getSelectedSlot()])
ex: itemSpace() gets how many items you can store, like the item in selected slot.
itemSpace("minecraft:cobblestone") - gets how more cobblestone you can store.
itemSpace(12) - gets how more items, like item in slot 12, you can store.]]
nSlot = nSlot or turtle.getSelectedSlot() --default slot is the selected slot
local stack = 0
if type(nSlot) == "string" then --is it "minecraft:cobblestone" for example.
nSlot = search(nSlot)
if not nSlot then return false, "Item not found." end
end
local tData = turtle.getItemDetail(nSlot)
if not tData then return false, "Empty slot "..nSlot.."." end
local itemName = tData.name
stack = turtle.getItemSpace(nSlot) + tData.count
nSlot = bit.band(nSlot-1, 15)+1 --nSlot, the start slot [1..16]
totSpace = 0
for i = 1, 16 do
tData = turtle.getItemDetail(i)
if tData then
if tData.name == itemName then totSpace = totSpace + stack - tData.count end
else totSpace = totSpace + stack
end
end
return totSpace
end
function itemCount(nSlot) --[[ Counts items in inventory
31/08/2021 Returns: number of items counted.
false - if nSlot <0 or > 16.
- if nSlot is neither a string nor a number.
sintax: itemCount([nSlot=turtle.getSelectedSlot() / "inventory" / item name])
ex: itemCount() counts items in selected slot.
itemCount("inventory") - counts items in inventory.
itemCount("minecraft:cobblestone") - counts cbblestone in inventory.]]
nSlot = nSlot or turtle.getSelectedSlot()
totItems = 0
if type(nSlot) == "number" then
if (nSlot < 1) or (nSlot > 16) then return false end
tData = turtle.getItemDetail(nSlot)
if tData then totItems = tData.count end
else
if type(nSlot) ~= "string" then return false end
for i = 1, 16 do
tData = turtle.getItemDetail(i)
if tData then
if nSlot == "inventory" then totItems = totItems + tData.count
elseif nSlot == tData.name then totItems = totItems + tData.count
end
end
end
end
return totItems
end
function itemName(nSlot) --[[ Gets the item name from Slot/selected slot.
05/09/2021 Returns: item name - if selected slot/slot is not empty.
false - if selected slot/slot is empty. ]]
nSlot = nSlot or turtle.getSelectedSlot()
if type(nSlot) ~= "number" then return nil end
if (nSlot <1 ) or (nSlot > 16) then return false, "Slot "..nSlot.." out of range." end
local tData = turtle.getItemDetail(nSlot)
if not tData then return false end
return tData.name
end
function search(sItemName, nStartSlot) --[[ Search inventory for ItemName, starting at startSlot.
28/08/2021 returns: The first slot where the item was found, and the quantity
False - if the item was not found
- if sItemName not supplied.
- if nStartSlot is not a number.
Note: nStartSlot < 0 search backwards, nStartSlot > 0 searchs forward.
if not supplied nStartSlot, default is the selected slot.
sintax: Search(sItemName [, nStartSlot=turtle.getSelectedSlot()]) ]]
if not sItemName then return false end
sItemName, nStartSlot = getParam("sn", {turtle.getSelectedSlot()}, sItemName, nStartSlot)
if type(nStartSlot) ~= "number" then return false end
dir = sign(nStartSlot)
nStartSlot = math.abs(nStartSlot)-1
nStartSlot = bit32.band(nStartSlot, 15)
slot = nStartSlot
repeat
tData = turtle.getItemDetail(slot+1)
if tData then
if tData.name == sItemName then
return slot+1, tData.count
end
end
slot = slot + dir
slot = bit32.band(slot, 15)
until (slot == nStartSlot)
return false
end
function itemSelect(itemName) --[[ Selects slot [1..16] or first item with Item Name, or the turtle selected slot.
29/08/2021 returns: The selected slot, and items in that slot.
False - if the item was not found
- if nStartSlot is not a number or a string.
- if value is a number and ( < 1 or > 16 )
Note: if executed select() is the same as turtle.getSelectedSlot()
sintax: select([Slot/Item Name])
ex: select("minecraft:cobblestone") - Selects first slot with "minecraft:cobblestone"]]
local nSlot
local tData
if not itemName then
nSlot = turtle.getSelectedSlot()
tData = turtle.getItemDetail()
if tData then return nSlot, tData.count
else return nSlot
end
end
if type(itemName) == "number" then
if (itemName < 1) or (itemName > 16) then return false end
if turtle.select(itemName) then return itemName end
end
if type(itemName) ~= "string" then return false end
nSlot = search(itemName)
if nSlot then
turtle.select(nSlot)
tData = turtle.getItemDetail()
if tData then return nSlot, tData.count
else return nSlot
end
end
return false
end
------ SUCK FUNCTIONS ------
function suckDir(sDir, nItems) --[[ Sucks or drops nItems into sDir direction {"forward", "right", "back", "left", "up", "down"}.
05/09/2021 Returns: true if turtle collects some items.
false if there are no items to take.
sintax: suckDir([sDir="forward][,nItems=all the items])
ex: suckDir() - Turtle sucks all the items forward.]]
sDir, nItems = getParam("sn", {"forward"}, sDir, nItems)
if nItems < 0 then return dropDir(sDir, math.abs(nItems)) end
if type(sDir) ~= "string" then return false end
if sDir == "right" then
turtle.turnRight()
sDir = "forward"
elseif sDir == "back" then
turnBack()
sDir = "forward"
elseif sDir == "left" then
turtle.turnLeft()
sDir = "forward"
end
if not isKey(sDir, suckF) then return false, "Invalid direction." end
return suckF[sDir](nItems)
end
------ DROP FUNCTIONS ------
function dropDir(sDir, nBlocks) --[[ Drops or sucks nBlocks from selected slot and inventory in the world in front, up or down the turtle.
29/08/2021 Returns: number of dropped items.
true - if suck some items.
false - empty selected slot.
nil - if invalid direction.
Sintax: drop([sDir="forward"] [, nBlocks=stack of items])
Note: if nBlocks not supplied, drops all items in selected slot.
ex: dropDir() - Drops all blocks from selected slot, forward.
dropDir(205, "up") - Drops 205 blocks from inventory like the one on selected slot, upwards.
drop(-5, "down") - Suck 5 items from down.]]
selectedSlot = turtle.getSelectedSlot() --save selected slot
tData = turtle.getItemDetail() --check the selected slot for items
sDir, nBlocks = getParam("sn", {"forward"}, sDir, nBlocks) --sDir as direction, nBlocks as a number.
if not dirType[sDir] then return nil, "Invalid direction." end --invalid direction
if not lookingType[sDir] then
goDir(sDir, 0) --turn if it must
sDir = "forward"
end
if not nBlocks then --drop all the stack from selected slot
if tData then --is there a item to frop?
dropF[sDir]()
return tData.count
else return false
end
else if type(nBlocks) ~= "number" then return nil end
end
if (not tData) and (nBlocks > -1) then return false, "Empty selected slot." end --no items
if nBlocks < 0 then return suckDir(sDir, math.abs(nBlocks)) end
nBlocks = math.abs(nBlocks) --nBlocks must be a positive number
local blocksDropped = 0 --total blocks dropped
while (blocksDropped < nBlocks) do
if tData.count > (nBlocks-blocksDropped) then
dropF[sDir](nBlocks-blocksDropped)
blocksDropped = blocksDropped + (nBlocks-blocksDropped)
else
dropF[sDir]()
blocksDropped = blocksDropped + tData.count
nextSlot, tData.count = search(tData.name)
if nextSlot then turtle.select(nextSlot)
elseif blocksDropped < nBlocks then break
end
end
end
turtle.select(selectedSlot) --restore selected slot
return blocksDropped
end
function drop(nBlocks) --[[ Drops or sucks nBlocks in front of the turtle.
29/08/2021 Returns: number of dropped items.
false - empty selected slot.
true - if suck some items.
Sintax: drop([nBlocks])
Note: if nBlocks not supplied, drops all items from selected slot.
ex: drop() - Drops all blocks from selected slot, in front of the turtle.
drop(205) - Drops 205 blocks from inventory like the one on selected slot, forward.]]
return dropDir("forward", nBlocks)
end
function dropUp(nBlocks) --[[ Drops or sucks nBlocks upwards.
29/08/2021 Returns: number of dropped items.
false - empty selected slot.
true - if suck some items.
Sintax: dropUp([nBlocks])
Note: if nBlocks not supplied, drops all items from selected slot.
ex: dropUp() - Drops all blocks from selected slot, upwards.
dropUp(205) - Drops 205 blocks from inventory like the one on selected slot, upwards.]]
return dropDir("up", nBlocks)
end
function dropDown(nBlocks) --[[ Drops or sucks nBlocks downwards.
29/08/2021 Returns: number of dropped items.
false - empty selected slot.
true - if suck some items.
Sintax: dropDown([nBlocks])
Note: if nBlocks not supplied, drops all items from selected slot.
ex: dropDown() - Drops all blocks from selected slot, downwards.
dropDown(205) - Drops 205 blocks from inventory like the one on selected slot, downwards.]]
return dropDir("down", nBlocks)
end
function dropLeft(nBlocks) --[[ Rotate left and drops or sucks nBlocks forward.
11/09/2021 Returns: number of dropped items.
false - empty selected slot.
true - if suck some items.
Sintax: dropLeft([nBlocks])
Note: if nBlocks not supplied, drops all items from selected slot.
ex: dropLeft() - Rotate left and drops all blocks from selected slot forward.
dropLeft(205) - Rotate left and drops 205 blocks from inventory like the one on selected slot, forward.]]
return dropDir("left", nBlocks)
end
function dropRight(nBlocks) --[[ Rotate right and drops or sucks nBlocks forward.
11/09/2021 Returns: number of dropped items.
false - empty selected slot.
true - if suck some items.
Sintax: dropRight([nBlocks])
Note: if nBlocks not supplied, drops all items from selected slot.
ex: dropRight() - Rotate right and drops all blocks from selected slot, forward.
dropRight(205) - Rotate right and drops 205 blocks from inventory like the one on selected slot, forward.]]
return dropDir("right", nBlocks)
end
function dropBack(nBlocks) --[[ Rotate back and drops or sucks nBlocks forward.
29/08/2021 Returns: number of dropped items.
false - empty selected slot.
true - if suck some items.
Sintax: dropBack([nBlocks])
Note: if nBlocks not supplied, drops all items from selected slot.
ex: dropBack() - Rotate back and drops all blocks from selected slot, forward.
dropBack(205) - Rotate back and drops 205 blocks from inventory like the one on selected slot, forward.]]
return dropDir("back", nBlocks)
end
---- TEST AREA ------
-- [x] setCoords(x,y,z) sets coords x, y, z for turtle. x
-- [x] distTo(x, y, z) gets the three components of the distance from the turtle to point.
-- [x] getCoords() gets coords from turtle.
------ TESTING ------
sleep(1)
print(refuel(1))
------ TESTED ------
-- [x] refuels the turtle with nCount items.
-- [x] itemSpace([slot/item Name=selected slot]) get the how many items more you can store in inventory.
-- [x] checkType(sType, ...) Checks if parameters are from sType.
-- [x] getParam(sParamOrder, tDefault, ...) Sorts parameters by type.
-- [x] tableInTable(tSearch, t) Verifies if tSearch is in table t.
-- [x] sign(value) Returns: -1 if value < 0, 0 if value == 0, 1 if value > 0
-- [x] inspectDir([sDir="forward]) turtle inspect block in sDir direction {"forward", "right", "back", "left", "up", "down"}.
-- [x] suckDir([sDir="forward"][,count=all the items]) sucks items from sDir direction {"forward", "right", "back", "left", "up", "down"}.
-- [x] attackDir([sDir="forward"]) Turtle attack in sDir direction {"forward", "right", "back", "left", "up", "down"}.
-- [x] compareAbove([Blocks=1]) compare blocks above the turtle in a strait line with selected slot.
-- [x] compareBelow([Blocks=1]) compare blocks below the turtle in a strait line with selected slot.
-- [x] detectAbove([Blocks=1]) detects if exits Blocks above the turtle in a strait line forward or backwards.
-- [x] detectBelow([Blocks=1]) detects if exits Blocks below the turtle in a strait line forward or backwards.
-- [x] detectDir([Direction="forward"]) detects if there is a block in Direction { "forward", "right", "back", "left", "up", "down" }.
-- [x] itemName([Slot=Selected slot]) gets the item name from Slot.
-- [x] itemCount([selected slot/slot/inventory/item name]) counts items in inventory.
-- [x] itemSelect([Slot/Item Name]) selects slot [1..16] or first item with Item Name, or the turtle selected slot.
-- [x] Search([ItemName[, StartSlot=Selected Slot]]) Search inventory for ItemName, starting at StartSlot.
-- [x] placeBelow([Blocks=1]) places inventory selected Blocks in a strait line 1 block below the turtle and forward, and returns to initial position.
-- [x] placeAbove([Blocks=1]) places inventory selected Blocks in a strait line 1 block above the turtle and forward, and returns to initial position.
-- [x] placeRight([Blocks=1]) rotates turtle Right, places inventory selected Blocks in a strait line forward, and returns to initial position.
-- [x] placeLeft([Blocks=1]) rotates turtle left, places inventory selected Blocks in a strait line forward, and returns to initial position.
-- [x] place([Blocks=1]) places inventory selected Blocks in a strait line forward.
-- [x] placeDown([Blocks=1]) places inventory selected Blocks in a strait line downward, and returns to initial position.
-- [x] placeUp([Blocks=1]) places inventory selected Blocks in a strait line upward, and returns to initial position.
-- [x] placeDir([Direction="forward"]) places inventory selected Block in Direction { "forward", "right", "back", "left", "up", "down" }.
-- [x] digBack([Blocks=1]) rotates turtle back or not and dig Blocks forward.
-- [x] digAbove([Blocks=1]) dig Blocks, 1 block above the turtle, and forward or backwards.
-- [x] digBelow([Blocks=1]) dig Blocks, 1 block below the turtle, and forward or backwards.
-- [x] digUp([Blocks=1]) dig Blocks upwards or downwards.
-- [x] digDown([Blocks=1]) dig Blocks downwards or upwards.
-- [x] digRight([Blocks=1]) rotates turtle Right or left and dig Blocks forward with tool.
-- [X] digLeft([Blocks=1]) rotates turtle left or right and dig Blocks forward with tool.
-- [x] dig([Blocks=1]) dig Blocks forward or backwards with tool.
-- [x] digDir([Direction="forward"][, Blocks=1]) turtle digs in Direction direction Blocks.
-- [X] turnDir([Direction="back"]) rotates turtle back, left or right.
-- [x] turnBack() Turtle turns back.
-- [x] goDir([Direction="forward][, nBlocks]) turtle goes in Direction { "forward", "right", "back", "left", "up", "down" } nBlocks until blocked.
-- [x] goLeft(nBlocks) turns left or right if nBlocks <0, and advances nBlocks until blocked.
-- [x] goRight(nBlocks) turns right or left if nBlocks < 0, and advances nBlocks until blocked.
-- [x] goBack(nBlocks) turns back or not if nBlocks < 0, and advances nBlocks until blocked.
-- [x] back([Blocks=1]) moves the turtle backwards blocks, until it hits something.
-- [x] forward([Blocks=1]) Moves nBlocks forward or backwards, until blocked.
-- [x] down([Blocks=1]) moves the turtle down blocks, until it hits something.
-- [x] up([Blocks=1]) moves the turtle up blocks, until it hits something.
-- [x] dropDir([sDir="forward"][, nBlocks=stack of items]) drops nBlocks from selected slot and inventory in the world in front, up or down the turtle.
-- [x] drop(nBlocks) drops nBlocks from selected slot and inventory in the world in front of the turtle.
-- [x] dropUp(nBlocks) drops nBlocks from selected slot and inventory in the world upwards.
-- [x] dropDown(nBlocks) drops nBlocks from selected slot and inventory in the world downwards.
-- [x] dropLeft(nBlocks) rotate left and drops or sucks nBlocks forward.
-- [x] dropRight(nBlocks) rotate right and drops or sucks nBlocks forward.
-- [x] dropBack(nBlocks) rotate back and drops or sucks nBlocks forward.
|
ArrayUtils = {}
function ArrayUtils.sortOn(t,fileds)
-- body
print("t",t,"fileds",fileds)
end
return ArrayUtils
|
-- // Credits: https://v3rmillion.net/showthread.php?tid=1077700
-- // Filters the text to allow you to say naughty words
local seperater = "\243\160\128\149\243\160\128\150\243\160\128\151\243\160\128\152\243\160\128\149\243\160\128\150\243\160\128\151\243\160\128\152\243\160\128\149\243\160\128\150\243\160\128\151\243\160\128\152\243\160\128\149\243\160\128\150\243\160\128\151\243\160\128\152\243\160\128\149\243\160\128\150\243\160\128\151\243\160\128\152\243\160\128\149\243\160\128\150\243\160\128\151\243\160\128\152\243\160\128\149\243\160\128\150\243\160\128\151\243\160\128\152\243\160\128\149\243\160\128\150\243\160\128\151\243\160\128\151"
local function filterString(text)
-- // Remove Punctutation
text = string.gsub(text, "[%p]+", "")
-- // Filtering
local function filterWord(word)
local iterationCount = 0
for i = 1, #word do
if (i % 2 == 0) then
i = i + iterationCount
local a = string.sub(word, 0, i)
local b = string.sub(word, i + 1, -1)
word = a .. seperater .. b
iterationCount = iterationCount + #seperater
end
end
return word
end
-- // Filtering each word
text = string.split(text, " ")
for i = 1, #text do
text[i] = filterWord(text[i])
end
-- // Putting it all back together
text = table.concat(text, " ")
-- // Finishing Bypassing
return text
end
-- // Vars
local ReplicatedStorage = game.GetService(game, "ReplicatedStorage")
local SayMessageRequest = ReplicatedStorage.DefaultChatSystemChatEvents.SayMessageRequest
getgenv().BypassText = true
-- // Metatables
local mt = getrawmetatable(game)
local backupnamecall = mt.__namecall
setreadonly(mt, false)
-- // Overwriting your chats
mt.__namecall = newcclosure(function(...)
local args = {...}
local method = getnamecallmethod()
if (method == "FireServer" and args[1] == SayMessageRequest and getgenv().BypassText) then
args[2] = filterString(args[2])
return backupnamecall(unpack(args))
end
return backupnamecall(...)
end)
-- // Metatables
setreadonly(mt, true)
-- // Return
return getgenv().BypassText
|
local UiView = require 'UIKit.UIView'
local CgAffineTransform = require "CoreGraphics.CGAffineTransform"
local NsString = require "Foundation.NSString"
local NSRange = struct.NSRange
local CGRect = struct.CGRect
local ViewController = class.extendClass (objc.ViewController)
function ViewController:viewDidLoad ()
self[ViewController.superclass]:viewDidLoad()
self:createTextSystem()
end
function ViewController:promoteAsLuaObject()
if self.isViewLoaded then
self:createTextSystem()
end
end
function ViewController:createTextSystem ()
-- create the text storage
local textFileUrl = objc.NSBundle.mainBundle:URLForResource_withExtension ("ConspirationMilliardaires", "rtf")
local textStorage = objc.NSTextStorage:new()
textStorage.attributedString = objc.NSAttributedString:newWithFileURL_options_documentAttributes_error(textFileUrl, {}, nil, nil)
self.textStorage = textStorage
-- create the layout manager
local layoutManager = objc.NSLayoutManager:new()
textStorage:addLayoutManager(layoutManager)
self.layoutManager = layoutManager
-- create the text container and view for the first column
self:updateTextSystem()
self:addMessageHandler ("system.did_load_module", "refresh")
end
function ViewController:updateTextSystem ()
if self.textViewColumn1 == nil then
local column1Bounds = self.column1View.bounds
local textContainer = objc.NSTextContainer:newWithSize (column1Bounds.size)
self.layoutManager:addTextContainer(textContainer)
local column1TextView = objc.UITextView:newWithFrame_textContainer(column1Bounds, textContainer)
column1TextView.backgroundColor = objc.UIColor.whiteColor
column1TextView.autoresizingMask = UiView.Autoresizing.FlexibleWidth + UiView.Autoresizing.FlexibleHeight
column1TextView.translatesAutoresizingMaskIntoConstraints = true
self.column1View:addSubview(column1TextView)
self.textViewColumn1 = column1TextView
end
self.textViewColumn1.scrollEnabled = false
if self.textViewColumn2 == nil then
local column2Bounds = self.column2View.bounds
local textContainer = objc.NSTextContainer:newWithSize (column2Bounds.size)
self.layoutManager:addTextContainer(textContainer)
local column2TextView = objc.UITextView:newWithFrame_textContainer(column2Bounds, textContainer)
column2TextView.backgroundColor = objc.UIColor.whiteColor
column2TextView.autoresizingMask = UiView.Autoresizing.FlexibleWidth + UiView.Autoresizing.FlexibleHeight
column2TextView.translatesAutoresizingMaskIntoConstraints = true
self.column2View:addSubview(column2TextView)
self.textViewColumn2 = column2TextView
end
self.textViewColumn2.scrollEnabled = false
-- Create a shape view used as exclusion path
if self.panImageView == nil then
local PathImageView = objc.PathImageView --[[@inherits UIView]]
local viewBounds = self.view.bounds
local panImageSize = struct.CGSize(300, 400)
local panImageFrame = CGRect(viewBounds:getMidX() - panImageSize.width / 2, viewBounds:getMidY() - panImageSize.height / 2,
panImageSize.width, panImageSize.height)
local panImagePath = objc.UIBezierPath:bezierPathWithOvalInRect(CGRect(0, 0, panImageSize.width, panImageSize.height))
local panImage = objc.UIImage:imageNamed "Chrysler_Building.jpg"
self.panImageView = PathImageView:newWithFrame_shape_image(panImageFrame, panImagePath)
self.view:addSubview(self.panImageView)
self.panImageView:addGestureRecognizer(objc.UIPanGestureRecognizer:newWithTarget_action(self, 'panShapeImage'))
end
if self.textAttachement == nil then
-- create the attachement
local textAttachement = objc.NSTextAttachment:new()
textAttachement.image = objc.UIImage:imageNamed "Rockefeller.png"
textAttachement.bounds = { x = 0, y = 0, width = 120, height = 150}
self.textAttachement = textAttachement
self.attachementString = objc.NSAttributedString:attributedStringWithAttachment(textAttachement)
-- calculate the insert location (after 5th paragraph)
local paragraphIndex = 0
local insertLocation = -1
self.textStorage.string:enumerateSubstringsInRange_options_usingBlock(NSRange(0, self.textStorage.length),
NsString.Enumeration.ByParagraphs,
function (substring, range, enclosingRange)
paragraphIndex = paragraphIndex + 1
if paragraphIndex == 5 then
insertLocation = enclosingRange:maxLocation()
return true
end
end)
if insertLocation ~= -1 then
self.textStorage:insertAttributedString_atIndex(self.attachementString, insertLocation)
end
end
-- Try to uncomment the lines below and see how the shape changes
-- self.panImageView.viewShape = objc.UIBezierPath:bezierPathWithOvalInRect(CGRect(0, 0, 300, 500))
-- self.panImageView.viewShape = objc.UIBezierPath:bezierPathWithRoundedRect_cornerRadius(CGRect(0, 0, 320, 500), 100.0)
getResource("Chrysler_Building", "public.image", self.panImageView, "viewImage")
self.textAttachement.bounds = CGRect(0, 0, 95, 105)
self:updateExclusionPaths()
end
function ViewController:setExclusionPathForPathImageViewInTextView (pathImageView, textView)
-- Translate the path of pathImageView into the text view coordinate system
local exclusionPath = pathImageView.viewShape:copy()
local pathOrigin = textView:convertPoint_fromView (pathImageView.bounds.origin, pathImageView)
local textContainerEdgeInset = textView.textContainerInset
exclusionPath:applyTransform (CgAffineTransform.MakeTranslation (pathOrigin.x - textContainerEdgeInset.left,
pathOrigin.y - textContainerEdgeInset.top))
textView.textContainer.exclusionPaths = { exclusionPath }
end
function ViewController:updateExclusionPaths ()
self:setExclusionPathForPathImageViewInTextView (self.panImageView, self.textViewColumn1)
self:setExclusionPathForPathImageViewInTextView (self.panImageView, self.textViewColumn2)
end
function ViewController:refresh()
self:updateTextSystem()
end
return ViewController
|
return setmetatable({
import = require 'compiler.computed.import',
StringHash = require 'compiler.computed.stringHash',
abilityOrder = require 'compiler.computed.abilityOrder',
}, {__index = _G})
|
--
-- Read/Write an entity to the stream
-- CClientEntityList::GetMaxEntityIndex() returns 8096
--
MAX_ENTITIES = 8096
if (SERVER) then
AddCSLuaFile()
end
local function WriteEntity(buf, e)
if (IsValid(e) or game.GetWorld() == e) then
buf:UInt(1, 1)
buf:UInt(e:EntIndex(), 13)
return
end
buf:UInt(0, 1) -- NULL
end
local function ReadEntity(buf)
if (buf:UInt(1) == 1) then return Entity(buf:UInt(13)) end -- non null
return NULL
end
--
-- Read/Write a color to/from the stream
--
local function WriteColor(buf, col)
assert(IsColor(col), "WriteColor: color expected, got " .. type(col))
buf:UInt(col.r, 8)
buf:UInt(col.g, 8)
buf:UInt(col.b, 8)
buf:UInt(col.a, 8)
end
local function ReadColor(buf)
return Color(buf:UInt(8), buf:UInt(8), buf:UInt(8), buf:UInt(8))
end
--
-- Sizes for ints to send
--
local TYPE_SIZE = 4
local UINTV_SIZE = 5
local Char2HexaLookup, Hexa2CharLookup = {}, {}
--
-- Generate Hexa Lookups
-- Hexa is a 6-bit English character encoding
--
local HexaRanges = {
{"a", "z"}, -- 26
{"A", "Z"}, -- 52
{"0", "9"}, -- 62
{"_", "_"}, -- 63
}
local offset = 1
for k, v in ipairs(HexaRanges) do
local starts, ends = v[1]:byte(), v[2]:byte()
for char = starts, ends do
local hexa = char - starts + offset
Char2HexaLookup[char] = hexa
Hexa2CharLookup[hexa] = string.char(char)
end
offset = offset + 1 + ends - starts
end
--
-- Converts an ASCII character in to a Hexa Character
--
local function CharToHexa(c)
return Char2HexaLookup[c]
end
--
-- Converts a Hexa character in to an ASCII character
--
local function HexaToChar(h)
return Hexa2CharLookup[h]
end
--
-- Returns true if the string can be represented in 7-Bit ASCII
-- Null bytes are not allowed as they are used for termination
--
local function Is7BitString(str)
return str:find("[\x80-\xFF%z]") == nil
end
--
-- Returns true if the string can be represented in Hexa
--
local function IsHexaString(str)
return str:find("[^a-zA-Z0-9_]") == nil
end
--
-- Returns true if the argument is NaN ( can also be interpreted as 0/0 )
--
local function IsNaN(x)
return x ~= x
end
--
-- An imaginary NaN table for caching in writing.table
--
local NaN = {}
--
-- This exists because you can't make a table index NaN
-- We need to do this so we can cache it in our references table
--
local function IndexSafe(x)
if (IsNaN(x)) then return NaN end
return x
end
local reading, writing
--
-- Gets the type of way we are going to send the data
-- Not all of these exist in reality
-- We are only going to add 16 types ( 0-15 ) since that's
-- the max we can fit into 4 bits
--
local function SendType(x)
if (x == 1 or x == 0) then return "bit" end
local t = type(x)
--
-- check if a number has no decimal places
-- and is able to be sent in an int
--
if (t == "number" and x % 1 == 0 and x >= -0x7FFFFFFF and x <= 0xFFFFFFFF) then
-- test if we can fit it in a single iteration with uintv
if (x < bit.lshift(1, UINTV_SIZE) and x >= 0) then return "uintv" end
if (x <= 0x7FFF and x >= -0x7FFF) then return "int16" end
if (x <= 0x7FFFFFFF and x >= -0x7FFFFFFF) then return "int32" end
return "uintv"
end
if (t == "string" and IsHexaString(x)) then return "hexastring" end
if (t == "string" and Is7BitString(x)) then return "string7" end
if (IsColor(x)) then return "Color" end
if (TypeID(x) == TYPE_ENTITY) then return "Entity" end
return t
end
local StringToTypeLookup, TypeToStringLookup = {}, {}
do
--
-- MUST BE 16 OR LESS TYPES
--
StringToTypeLookup = {
-- strings
string = 0,
hexastring = 1,
string7 = 2,
--numbers
bit = 3,
int16 = 4,
int32 = 5,
number = 6,
uintv = 7,
-- default things
boolean = 8,
--float arrays
Vector = 9,
Angle = 10,
--tables
table = 11,
reference = 13,
-- Garry's Mod specific
VMatrix = 12,
Color = 14,
Entity = 15,
}
--
-- backwards lookup
--
for k, v in pairs(StringToTypeLookup) do
TypeToStringLookup[v] = k
end
end
local function TypeToString(n)
return TypeToStringLookup[n]
end
local function StringToType(s)
return StringToTypeLookup[s]
end
local ReferenceType = StringToType("reference")
local TableType = StringToType("table")
reading = {
-- -- Normal gmod types we can't really improve --
Color = ReadColor,
boolean = function(buf) return buf:UInt(1) == 1 end,
number = function(buf) return buf:Double() end,
bit = function(buf) return buf:UInt(1) end,
Entity = ReadEntity,
VMatrix = error, --net.ReadMatrix,
Angle = function(buf) return Angle(buf:Float(), buf:Float(), buf:Float()) end, --net.ReadAngle,
Vector = function(buf) return Vector(buf:Float(), buf:Float(), buf:Float()) end, --net.ReadVector,
-- -- Simple integers --
int16 = function(buf) return buf:Int(16) end,
int32 = function(buf) return buf:Int(32) end,
-- -- A reference index in our already-sent-table --
reference = function(buf, references) return references[reading.uintv(buf)] end,
-- -- Variable length unsigned integers --
uintv = function(buf)
local i = 0
local ret = 0
while buf:UInt(1) == 1 do
local t = buf:UInt(UINTV_SIZE)
ret = ret + bit.lshift(t, i * UINTV_SIZE)
i = i + 1
end
return ret
end,
-- -- 7 bit encoded strings -- NULL terminated --
string7 = function(buf)
-- it's compressed
if (buf:UInt(1) == 1) then
return util.Decompress(buf:Data(reading.uintv(buf)))
else -- it's not compressed
local ret = ""
while true do
local chr = buf:UInt(7)
if (chr == 0) then return ret end
ret = ret .. string.char(chr)
end
end
end,
-- -- Our 6-bit encoded strings -- NULL terminated --
hexastring = function(buf)
if (buf:UInt(1) == 1) then
return util.Decompress(buf:Data(reading.uintv(buf)))
else
local ret = ""
while true do
local chr = buf:UInt(6)
if (chr == 0) then return ret end -- terminator
ret = ret .. Hexa2CharLookup[chr]
end
end
end,
-- -- C String -- NULL terminated -- NOTE: Must be NULL terminated or else will break compatibility -- with some addons! Also could lead to exploits --
string = function(buf)
-- compressed or not
if (buf:UInt(1) == 1) then
return util.Decompress(buf:Data(reading.uintv(buf)))
else
return buf:String()
end
end,
-- -- our readtable -- directly used as net.ReadTable --
table = function(buf, references)
local ret = {}
references = references or {}
local reference = function(type, value)
if (not type or (type ~= TableType and type ~= ReferenceType)) then
table.insert(references, value)
end
end
reference(nil, ret)
for i = 1, reading.uintv(buf) do
local type = buf:UInt(TYPE_SIZE)
local value = reading[TypeToString(type)](buf, references)
reference(type, value)
ret[i] = value
end
for i = 1, reading.uintv(buf) do
local keytype = buf:UInt(TYPE_SIZE)
local keyvalue = reading[TypeToString(keytype)](buf, references)
reference(keytype, keyvalue)
local valuetype = buf:UInt(TYPE_SIZE)
local valuevalue = reading[TypeToString(valuetype)](buf, references)
reference(valuetype, valuevalue)
ret[keyvalue] = valuevalue
end
return ret
end
}
--
-- We need this since #table returns undefined values
-- by the lua spec if it doesn't have incremental keys
-- we use pairs since it's backwards compatible
--
-- code_gs: pairs loop is needed to run the __pairs metamethod
local function array_len(x)
local tIndicies = {}
for k, _ in pairs(x) do
tIndicies[k] = true
end
for i = 1, MAX_ENTITIES do
if (tIndicies[i] == nil) then return i - 1 end
end
return MAX_ENTITIES
end
writing = {
bit = function(buf, n)
buf:UInt(n, 1)
end,
Color = WriteColor,
boolean = function(buf, n)
buf:UInt(n and 1 or 0, 1)
end,
number = function(buf, d)
buf:Double(d)
end,
Entity = WriteEntity,
VMatrix = error,
Vector = function(buf, v)
buf:Float(v.x)
buf:Float(v.y)
buf:Float(v.z)
end,
Angle = function(buf, v)
buf:Float(v.p)
buf:Float(v.y)
buf:Float(v.r)
end,
int16 = function(buf, w)
buf:Int(w, 16)
end,
int32 = function(buf, d)
buf:Int(d, 32)
end,
-- -- Variable length unsigned integers --
uintv = function(buf, n)
while (n > 0) do
buf:UInt(1, 1)
buf:UInt(n, UINTV_SIZE)
n = bit.rshift(n, UINTV_SIZE)
end
buf:UInt(0, 1)
end,
-- -- 7 bit encoded strings -- NULL terminated --
string7 = function(buf, s)
local null = s:find("%z")
if (null) then
s = s:sub(1, null - 1)
end
local compressed = util.Compress(s)
-- add one for the null terminator
if (compressed and compressed:len() < (s:len() + 1) / 8 * 7) then
buf:UInt(1, 1)
writing.uintv(buf, compressed:len())
buf:Data(compressed)
else
buf:UInt(0, 1)
for i = 1, s:len() do
buf:UInt(s:byte(i, i), 7)
end
buf:UInt(0, 7)
end
end,
-- -- Our 6-bit encoded strings -- NULL terminated --
hexastring = function(buf, s)
local null = s:find("%z")
if (null) then
s = s:sub(1, null - 1)
end
local compressed = util.Compress(s)
-- add one for the null terminator
if (compressed and compressed:len() < (s:len() + 1) / 8 * 6) then
buf:UInt(1, 1)
writing.uintv(buf, compressed:len())
buf:Data(compressed)
else
buf:UInt(0, 1)
for i = 1, s:len() do
buf:UInt(Char2HexaLookup[s:byte(i, i)], 6)
end
buf:UInt(0, 6)
end
end,
-- -- C String -- NULL terminated -- NOTE: Must be NULL terminated or else will break compatibility -- with some addons! Also could lead to exploits --
string = function(buf, x)
local null = x:find("%z")
if (null) then
x = x:sub(1, null - 1)
end
local compressed = util.Compress(x)
if (compressed and compressed:len() < x:len() + 1) then
buf:UInt(1, 1)
writing.uintv(buf, compressed:len())
buf:Data(compressed)
else
buf:UInt(0, 1)
buf:String(x)
end
end,
-- -- our writetable -- directly used as net.WriteTable --
table = function(buf, tbl, references, num)
references = references or {
[tbl] = 1
}
num = num or 1
local SendValue = function(value)
if (references[IndexSafe(value)]) then
buf:UInt(ReferenceType, TYPE_SIZE)
writing.uintv(buf, references[IndexSafe(value)])
return
end
local sendtype = SendType(value)
num = num + 1
references[IndexSafe(value)] = num
buf:UInt(StringToType(sendtype), TYPE_SIZE)
num = writing[sendtype](buf, value, references, num) or num
end
local pairs_table = {}
for k, v in pairs(tbl) do
pairs_table[k] = v
end
local array_size = array_len(pairs_table)
writing.uintv(buf, array_size)
for i = 1, array_size do
local value = pairs_table[i]
pairs_table[i] = nil
SendValue(value)
end
local object_key_count = table.Count(pairs_table)
writing.uintv(buf, object_key_count)
for k, v in next, pairs_table, nil do
SendValue(k)
SendValue(v)
end
return num
end
}
return {
write = function(b, t)
writing.table(b, t)
end,
read = function(b) return reading.table(b) end
}
|
local TDKP_WinnerCalculator = {}
_G["TDKP_WinnerCalculator"] = TDKP_WinnerCalculator
local L = LibStub("AceLocale-3.0"):GetLocale("TurboDKP")
function TDKP_WinnerCalculator:ApplyBiddingCaps(bid1, bid2, rankCap1, rankCap2, specCap1, specCap2)
-- don't have to worry about -1 cap values this way
if rankCap1 < 0 then
rankCap1 = 1e12
end
if rankCap2 < 0 then
rankCap2 = 1e12
end
if specCap1 < 0 then
specCap1 = 1e12
end
if specCap2 < 0 then
specCap2 = 1e12
end
if rankCap1 ~= rankCap2 or specCap1 ~= specCap2 then -- some of caps are different
if specCap1 == specCap2 then -- only rank caps are different
if rankCap1 < rankCap2 then
local bid1capped = min(bid1["bidAmount"], rankCap1)
return bid1capped, bid2["bidAmount"]
else
local bid2capped = min(bid2["bidAmount"], rankCap2)
return bid1["bidAmount"], bid2capped
end
elseif rankCap1 == rankCap2 then -- only spec caps are different
if specCap1 < specCap2 then
local bid1capped = min(bid1["bidAmount"], specCap1)
return bid1capped, bid2["bidAmount"]
else
local bid2capped = min(bid2["bidAmount"], specCap2)
return bid1["bidAmount"], bid2capped
end
else -- both caps are different
if rankCap1 < rankCap2 and specCap1 < specCap2 then -- constrain bid1 by min of both caps
local bid1capped = min(bid1["bidAmount"], min(rankCap1, specCap1))
return bid1capped, bid2["bidAmount"]
elseif rankCap1 < rankCap2 and specCap1 > specCap2 then
if rankCap1 == specCap2 then -- min of cap for each bid is the same
return bid1["bidAmount"], bid2["bidAmount"]
elseif rankCap1 < specCap2 then -- constrain bid1 because cap is lower
local bid1capped = min(bid1["bidAmount"], rankCap1)
return bid1capped, bid2["bidAmount"]
elseif rankCap1 > specCap2 then -- constrain bid2 because cap is lower
local bid2capped = min(bid2["bidAmount"], specCap2)
return bid1["bidAmount"], bid2capped
end
elseif rankCap1 > rankCap2 and specCap1 < specCap2 then
if rankCap2 == specCap1 then -- min of cap for each bid is the same
return bid1["bidAmount"], bid2["bidAmount"]
elseif rankCap2 < specCap1 then -- constrain bid2 because cap is lower
local bid2capped = min(bid2["bidAmount"], rankCap2)
return bid1["bidAmount"], bid2capped
elseif rankCap2 > specCap1 then -- constrain bid1 because cap is lower
local bid1capped = min(bid1["bidAmount"], specCap1)
return bid1capped, bid2["bidAmount"]
end
elseif rankCap1 > rankCap2 and specCap1 > specCap2 then -- constrain bid2 by min of both caps
local bid2capped = min(bid2["bidAmount"], min(rankCap2, specCap2))
return bid1["bidAmount"], bid2capped
end
end
else -- caps are the same, no need to cap either bid
return bid1["bidAmount"], bid2["bidAmount"]
end
end
-- Topological sorting is needed for this problem. The ApplyBiddingCaps function has different comparison results
-- depending on which two bids are being compared. This will insert all of the bids into a graph with
-- "equals", "decreasing", and "increasing" costs form each bid to every other bid. It then figures out the top bid by
-- finding the bids with no "increasing" costs. Of those it finds the bid with the most "equals" costs (if any exist).
function TDKP_WinnerCalculator:DetermineWinningBid(itemId)
local item = TDKP.itemsCurrentlyBidding[itemId]
-- Print out all bids and the player whispers (just in case something goes wrong and you want to see the summary of bids)
print("--------------------")
print(TDKP.CHAT_PREFIX_COLORED .. item["itemLink"])
for _, bid in pairs(item["bids"]) do
print(TDKP.CHAT_PREFIX_COLORED .. string.join(" ", GetPlayerNameWithColor(bid["player"]), bid["rankName"], bid["spec"], bid["bidAmount"]))
end
local bidGraph = {}
local numBids = 0
-- Bulid graph of all bids
for player1, bidData1 in pairs(item["bids"]) do
if not bidGraph[player1] then
bidGraph[player1] = {bid = bidData1, equals = {}, decreasing = {}, increasing = {}}
end
numBids = numBids + 1
for player2, bidData2 in pairs(item["bids"]) do
if not bidGraph[player2] then
bidGraph[player2] = {bid = bidData2, equals = {}, decreasing = {}, increasing = {}}
end
if player1 ~= player2 then
local rankCap1 = TDKP.db.factionrealm.guildRankBidCaps[bidData1["rank"]]
local rankCap2 = TDKP.db.factionrealm.guildRankBidCaps[bidData2["rank"]]
local specCap1 = TDKP.db.factionrealm.specBidCaps[bidData1["spec"]]
local specCap2 = TDKP.db.factionrealm.specBidCaps[bidData2["spec"]]
local bid1capped, bid2capped = TDKP_WinnerCalculator:ApplyBiddingCaps(bidData1, bidData2, rankCap1, rankCap2, specCap1, specCap2)
local costs12 = { bid1capped, bid2capped }
local costs21 = { bid2capped, bid1capped }
if bid1capped == bid2capped then
bidGraph[player1]["equals"][player2] = costs12
bidGraph[player2]["equals"][player1] = costs21
elseif bid1capped < bid2capped then
bidGraph[player1]["increasing"][player2] = costs12
bidGraph[player2]["decreasing"][player1] = costs21
elseif bid1capped > bid2capped then
bidGraph[player1]["decreasing"][player2] = costs12
bidGraph[player2]["increasing"][player1] = costs21
end
end
end
end
-- return early if there are no bids
if numBids == 0 then
print("--------------------")
SendChatMessage(TDKP.CHAT_PREFIX .. "No bids on " .. item["itemLink"], "RAID_WARNING")
return
end
-- get top nodes and calculate num of costs for each type
local numTopNodes = 0
local topNodes = {}
local hasEqualsInTopNodes = false
for player, node in pairs(bidGraph) do
local numDecreasing = 0
for _, _ in pairs(node["decreasing"]) do
numDecreasing = numDecreasing + 1
end
node["numDecreasing"] = numDecreasing
local numIncreasing = 0
for _, _ in pairs(node["increasing"]) do
numIncreasing = numIncreasing + 1
end
node["numIncreasing"] = numIncreasing
local numEquals = 0
for _, _ in pairs(node["equals"]) do
numEquals = numEquals + 1
end
node["numEquals"] = numEquals
if numIncreasing == 0 then
topNodes[player] = node
numTopNodes = numTopNodes + 1
if numEquals > 0 then
hasEqualsInTopNodes = true
end
end
end
-- Something has gone horribly wrong and no top nodes were found
if numTopNodes == 0 then
error("Found no top nodes, cannot determine winner")
end
-- Get the top node (either node with most "equals" costs or the only node in top nodes table)
local bestTopNode
if hasEqualsInTopNodes then
local bestEqualsNum = 0
for _, node in pairs(topNodes) do
if node["numEquals"] > bestEqualsNum then
bestEqualsNum = node["numEquals"]
bestTopNode = node
end
end
else
if numTopNodes == 1 then
for _, node in pairs(topNodes) do
bestTopNode = node
break
end
else
error("Found more than 1 top node when there should only be 1")
end
end
-- Something has gone horribly wrong and could not find a best top node
if bestTopNode == nil then
error("Could not find a best top node")
end
-- If top node has "equals" costs then we need to get all bids that are equal and tell all those players to roll
if bestTopNode["numEquals"] > 0 then
local cost = 1e12
local playersTied = { bestTopNode["bid"]["player"] }
for player, costs in pairs(bestTopNode["equals"]) do
table.insert(playersTied, player)
if costs[2] < cost then
cost = costs[2]
end
end
print(TDKP.CHAT_PREFIX_COLORED .. "Tied: " .. table.concat(map(function (_, player)
return GetPlayerNameWithColor(player)
end, playersTied, true), ", ") .. " for " .. cost .. " dkp.")
print("--------------------")
SendChatMessage(TDKP.CHAT_PREFIX .. "Bids tied. Roll " .. table.concat(playersTied, ", ") .. " on " .. item["itemLink"] .. " for " .. cost .. " dkp.", "RAID_WARNING")
for _, player in pairs(playersTied) do
SendChatMessage(TDKP.CHAT_PREFIX .. "You tied with another bid. Roll on " .. item["itemLink"] .. " for " .. cost .. " dkp.", "WHISPER", nil, player)
end
else -- This is the winning bid, but need to calculate the greatest "decreasing" node compared to bid and add one for cost
local cost
if bestTopNode["numDecreasing"] > 0 then
cost = 0
for player, costs in pairs(bestTopNode["decreasing"]) do
if costs[2] > cost then
cost = costs[2]
end
end
cost = cost + 1
else -- If no "less" bids, that means it is the only bid and the cost is the minimum
cost = TDKP.db.factionrealm.minBid
end
local winningPlayer = bestTopNode["bid"]["player"]
print(TDKP.CHAT_PREFIX_COLORED .. "|cFF00FF00Winner|r: " .. GetPlayerNameWithColor(winningPlayer) .. " for " .. cost .. " dkp.")
print("--------------------")
TDKP_UI:ShowAwardWinningBidDialog(winningPlayer, cost, item)
--SendChatMessage(TDKP.CHAT_PREFIX .. "Congrats " .. bestTopNode["bid"]["player"] .. " on " .. item["itemLink"] .. " for " .. cost .. " dkp!", "RAID_WARNING")
end
end
|
project "SPIRV_Cross"
kind "StaticLib"
language "C++"
cppdialect "C++11"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
files
{
"spirv.h",
"spirv_cross_c.h",
"GLSL.std.450.h",
"spirv.hpp",
"spirv_cfg.hpp",
"spirv_common.hpp",
"spirv_cpp.hpp",
"spirv_cross.hpp",
"spirv_cross_containers.hpp",
"spirv_cross_error_handling.hpp",
"spirv_cross_parsed_ir.hpp",
"spirv_cross_util.hpp",
"spirv_glsl.hpp",
"spirv_hlsl.hpp",
"spirv_msl.hpp",
"spirv_parser.hpp",
"spirv_reflect.hpp",
"main.cpp",
"spirv_cfg.cpp",
"spirv_cpp.cpp",
"spirv_cross.cpp",
"spirv_cross_c.cpp",
"spirv_cross_parsed_ir.cpp",
"spirv_cross_util.cpp",
"spirv_glsl.cpp",
"spirv_hlsl.cpp",
"spirv_msl.cpp",
"spirv_parser.cpp",
"spirv_reflect.cpp",
}
filter "system:windows"
systemversion "latest"
staticruntime "On"
defines
{
"_GLFW_WIN32",
"_CRT_SECURE_NO_WARNINGS"
}
filter "configurations:Debug"
runtime "Debug"
symbols "on"
filter "configurations:Release"
runtime "Release"
optimize "on"
|
-- Standard awesome library
local gears = require("gears")
local awful = require("awful")
require("awful.autofocus")
-- Widget and layout library
local wibox = require("wibox")
-- Theme handling library
local beautiful = require("beautiful")
local lain = require("lain")
local separators = lain.util.separators
-- Notification library
local naughty = require("naughty")
local menubar = require("menubar")
local hotkeys_popup = require("awful.hotkeys_popup").widget
local button_table = awful.util.table
local markup = lain.util.markup
local math = require("math")
local xf86helpers = require("xf86helpers")
-- {{{ Error handling
-- Check if awesome encountered an error during startup and fell back to
-- another config (This code will only ever execute for the fallback config)
if awesome.startup_errors then
naughty.notify({ preset = naughty.config.presets.critical,
title = "Oops, there were errors during startup!",
text = awesome.startup_errors })
end
-- Handle runtime errors after startup
do
local in_error = false
awesome.connect_signal("debug::error", function (err)
-- Make sure we don't go into an endless error loop
if in_error then return end
in_error = true
naughty.notify({ preset = naughty.config.presets.critical,
title = "Oops, an error happened!",
text = tostring(err) })
in_error = false
end)
end
-- }}}
-- Autostart
awful.util.spawn_with_shell("~/.config/awesome/autostart.sh &")
-- {{{ Variable definitions
-- Themes define colours, icons, font and wallpapers.
beautiful.init("~/.config/awesome/custom-material/theme.lua")
local arrow_systray = separators.arrow_left(beautiful.bg_systray, "alpha")
local arrow_systray_inv = separators.arrow_left("alpha", beautiful.bg_systray)
separators.width = 12
-- This is used later as the default terminal and editor to run.
terminal = "sakura"
editor = os.getenv("EDITOR") or "vim"
editor_cmd = terminal .. " -e " .. editor
modkey = "Mod4"
-- Table of layouts to cover with awful.layout.inc, order matters.
awful.layout.layouts = {
awful.layout.suit.tile,
-- awful.layout.suit.tile.left,
awful.layout.suit.tile.bottom,
awful.layout.suit.fair,
awful.layout.suit.floating,
-- awful.layout.suit.tile.top,
-- awful.layout.suit.fair.horizontal,
-- awful.layout.suit.spiral,
-- awful.layout.suit.spiral.dwindle,
-- awful.layout.suit.max,
-- awful.layout.suit.max.fullscreen,
-- awful.layout.suit.magnifier,
-- awful.layout.suit.corner.nw,
-- awful.layout.suit.corner.ne,
-- awful.layout.suit.corner.sw,
-- awful.layout.suit.corner.se,
}
-- }}}
-- {{{ Helper functions
local function client_menu_toggle_fn()
local instance = nil
return function ()
if instance and instance.wibox.visible then
instance:hide()
instance = nil
else
instance = awful.menu.clients({ theme = { width = 250 } })
end
end
end
-- }}}
-- {{{ Menu
-- Create a launcher widget and a main menu
myawesomemenu = {
{ "hotkeys", function() return false, hotkeys_popup.show_help end},
{ "manual", terminal .. " -e man awesome" },
{ "edit config", editor_cmd .. " " .. awesome.conffile },
{ "restart", awesome.restart },
{ "quit", function() awesome.quit() end}
}
mymainmenu = awful.menu({ items = { { "awesome", myawesomemenu, beautiful.awesome_icon },
{ "open terminal", terminal }
}
})
mylauncher = awful.widget.launcher({ image = beautiful.awesome_icon,
menu = mymainmenu })
-- Menubar configuration
menubar.utils.terminal = terminal -- Set the terminal for applications that require it
-- }}}
-- Create a wibox for each screen and add it
local taglist_buttons = button_table.join(
awful.button({ }, 1, function(t) t:view_only() end),
awful.button({ modkey }, 1, function(t)
if client.focus then
client.focus:move_to_tag(t)
end
end),
awful.button({ }, 3, awful.tag.viewtoggle),
awful.button({ modkey }, 3, function(t)
if client.focus then
client.focus:toggle_tag(t)
end
end),
awful.button({ }, 4, function(t) awful.tag.viewnext(t.screen) end),
awful.button({ }, 5, function(t) awful.tag.viewprev(t.screen) end)
)
local tasklist_buttons = button_table.join(
awful.button({ }, 1, function (c)
if c == client.focus then
c.minimized = true
else
-- Without this, the following
-- :isvisible() makes no sense
c.minimized = false
if not c:isvisible() and c.first_tag then
c.first_tag:view_only()
end
-- This will also un-minimize
-- the client, if needed
client.focus = c
c:raise()
end
end),
awful.button({ }, 3, client_menu_toggle_fn()),
awful.button({ }, 4, function ()
awful.client.focus.byidx(1)
end),
awful.button({ }, 5, function ()
awful.client.focus.byidx(-1)
end))
--- ------- ---
--- Widgets ---
--- ------- ---
function round(what, precision)
return math.floor(what*math.pow(10,precision)+0.5) / math.pow(10,precision)
end
-- Clock
clock_widget = wibox.widget.textclock(" %a, %d.%m. %H:%M ")
-- MEM
local mem_icon = wibox.widget.imagebox(beautiful.mem_icon)
local mem = lain.widget.mem({
settings = function()
widget:set_markup(markup.font(beautiful.font, " " .. round(mem_now.used/1024, 2) .. "GB "))
end
})
-- CPU
local cpu_icon = wibox.widget.imagebox(beautiful.cpu_icon)
local cpu = lain.widget.cpu({
settings = function()
widget:set_markup(markup.font(beautiful.font, " " .. cpu_now.usage .. "% "))
end
})
-- Coretemp
local temp_icon = wibox.widget.imagebox(beautiful.temp_icon)
local temp = lain.widget.temp({
timeout = 5,
settings = function()
if coretemp_now > 85 then
widget:set_markup(markup.font(beautiful.font, markup.fg.color(beautiful.red, " " .. coretemp_now .. " °C ")))
elseif coretemp_now > 70 then
widget:set_markup(markup.font(beautiful.font, markup.fg.color(beautiful.orange, " " .. coretemp_now .. " °C ")))
else
widget:set_markup(markup.font(beautiful.font, " " .. coretemp_now .. "°C "))
end
end
})
-- Battery
-- battery progress bar
local batbar = wibox.widget {
forced_width = 40 * beautiful.scaling,
color = "#232323",
background_color = "#ddd",
paddings = 1 * beautiful.scaling,
widget = wibox.widget.progressbar,
}
local batbar_bg = wibox.container.background(batbar, "#0f0", gears.shape.rectangle)
local bat_widget = wibox.container.margin(batbar_bg, 2 * beautiful.scaling, 7 * beautiful.scaling, 7 * beautiful.scaling, 6 * beautiful.scaling) -- l r t b
local bat_icon = wibox.widget.imagebox(beautiful.bat_icon)
-- Lain widget to show bat percent, also shows notifications
local bat = lain.widget.bat({
notify = "on",
timeout = 5,
n_perc = {5, 10},
settings = function()
widget:set_markup(markup.font(beautiful.font, bat_now.perc .. "% "))
if bat_now.perc > 80 then
batbar:set_color(beautiful.green)
elseif bat_now.perc <= 80 and bat_now.perc > 30 then
batbar:set_color("#4fc0e9")
elseif bat_now.perc <= 30 and bat_now.perc > 15 then
batbar:set_color(beautiful.orange)
elseif bat_now.perc <= 15 then
batbar:set_color(beautiful.red)
end
batbar:set_value(bat_now.perc/100)
end
})
-- Calendar
local calendar = lain.widget.cal({
attach_to = { clock_widget }
})
-- Helper functions
local notification_preset = { fg = "#202020", bg = "#CDCDCD" }
local function volume_notification()
local get_volume = [[bash -c "amixer sget Master | tail -n 1 | awk '{print $4}' | tr -d '[]' | sed 's/%//'"]]
awful.spawn.easy_async(get_volume, function(stdout, stderr, reason, exit_code)
naughty.notify({ title = "Volume", text = tostring(tonumber(stdout)) .. '%', preset = notification_preset })
end)
end
local function increase_volume()
awful.util.spawn("amixer set Master 5+")
volume_notification()
end
local function decrease_volume()
awful.util.spawn("amixer set Master 5-")
volume_notification()
end
local function set_wallpaper(s)
gears.wallpaper.maximized(beautiful.wallpaper, s, true)
end
-- Re-set wallpaper when a screen's geometry changes (e.g. different resolution)
screen.connect_signal("property::geometry", set_wallpaper)
awful.screen.connect_for_each_screen(function(s)
-- Wallpaper
gears.wallpaper.maximized(beautiful.wallpaper, s, true)
-- Each screen has its own tag table.
awful.tag({ "1", "2", "3", "4", "5", "6", "7", "8", "9" }, s, awful.layout.layouts[1])
-- Create a promptbox for each screen
s.mypromptbox = awful.widget.prompt()
-- Create an imagebox widget which will contains an icon indicating which layout we're using.
-- We need one layoutbox per screen.
s.mylayoutbox = awful.widget.layoutbox(s)
s.mylayoutbox:buttons(button_table.join(
awful.button({ }, 1, function () awful.layout.inc( 1) end),
awful.button({ }, 3, function () awful.layout.inc(-1) end),
awful.button({ }, 4, function () awful.layout.inc( 1) end),
awful.button({ }, 5, function () awful.layout.inc(-1) end)))
-- Create a taglist widget
s.mytaglist = awful.widget.taglist(s, awful.widget.taglist.filter.all, taglist_buttons)
-- Create a tasklist widget
s.mytasklist = awful.widget.tasklist(s, awful.widget.tasklist.filter.currenttags, tasklist_buttons)
-- Create the wibox
s.mywibox = awful.wibar({ position = "top", screen = s })
-- Add widgets to the wibox
s.mywibox:setup {
layout = wibox.layout.align.horizontal,
{ -- Left widgets
layout = wibox.layout.fixed.horizontal,
mylauncher,
s.mytaglist,
s.mypromptbox,
},
s.mytasklist, -- Middle widget
{ -- Right widgets
layout = wibox.layout.fixed.horizontal,
arrow_systray_inv,
wibox.widget.systray(),
arrow_systray,
mem_icon,
mem,
arrow_systray_inv,
wibox.container.background(cpu_icon, beautiful.bg_systray),
wibox.container.background(cpu.widget, beautiful.bg_systray),
arrow_systray,
temp_icon,
temp,
arrow_systray_inv,
wibox.container.background(bat_icon, beautiful.bg_systray),
wibox.container.background(bat.widget, beautiful.bg_systray),
wibox.container.background(bat_widget, beautiful.bg_systray),
arrow_systray,
clock_widget,
s.mylayoutbox,
},
}
end)
-- }}}
-- {{{ Mouse bindings
root.buttons(button_table.join(
awful.button({ }, 3, function () mymainmenu:toggle() end),
awful.button({ }, 4, awful.tag.viewnext),
awful.button({ }, 5, awful.tag.viewprev)
))
-- }}}
-- {{{ Key bindings
globalkeys = button_table.join(
awful.key({ modkey }, "s", hotkeys_popup.show_help, {description="show help", group="awesome"}),
awful.key({ modkey }, "Left", awful.tag.viewprev, {description = "view previous", group = "tag"}),
awful.key({ modkey }, "Right", awful.tag.viewnext, {description = "view next", group = "tag"}),
awful.key({ modkey }, "Escape", awful.tag.history.restore, {description = "go back", group = "tag"}),
awful.key({ modkey }, "w", function () mymainmenu:show() end, {description = "show main menu", group = "awesome"}),
awful.key({}, "Print", function() awful.util.spawn ("flameshot gui") end),
awful.key({}, "XF86Calculator", function() awful.util.spawn ("copy_line_marker") end),
awful.key({}, "Pause", function() awful.util.spawn ("screencast") end),
awful.key({}, "XF86MonBrightnessUp", xf86helpers.brightness.inc),
awful.key({}, "XF86MonBrightnessDown", xf86helpers.brightness.dec),
awful.key({}, "XF86AudioRaiseVolume", xf86helpers.volume.inc),
awful.key({}, "XF86AudioLowerVolume", xf86helpers.volume.dec),
awful.key({}, "XF86AudioMute", xf86helpers.volume.mute),
awful.key({}, "XF86AudioPlay", function() awful.util.spawn ("playerctl play-pause") end),
awful.key({}, "XF86AudioNext", function() awful.util.spawn ("playerctl next") end),
awful.key({}, "XF86AudioPrev", function() awful.util.spawn ("playerctl previous") end),
awful.key({}, "XF86Display", function() awful.util.spawn ("arandr") end),
awful.key({ modkey, }, "l", function() awful.util.spawn( "dm-tool lock" ) end),
-- Layout manipulation
awful.key({ modkey }, "u", awful.client.urgent.jumpto, {description = "jump to urgent client", group = "client"}),
awful.key({ modkey }, "Tab",
function ()
awful.client.focus.history.previous()
if client.focus then
client.focus:raise()
end
end,
{description = "go back", group = "client"}),
-- Standard program
awful.key({ modkey }, "Return", function () awful.spawn(terminal) end, {description = "open a terminal", group = "launcher"}),
awful.key({ modkey, "Control" }, "r", awesome.restart, {description = "reload awesome", group = "awesome"}),
awful.key({ modkey, "Shift" }, "q", awesome.quit, {description = "quit awesome", group = "awesome"}),
awful.key({ modkey, }, "space", function () awful.layout.inc( 1) end, {description = "select next", group = "layout"}),
awful.key({ modkey, "Shift" }, "space", function () awful.layout.inc(-1) end, {description = "select previous", group = "layout"}),
awful.key({ modkey }, "r", function () awful.spawn("rofi -show drun") end,
{description = "run rofi", group = "launcher"}),
awful.key({ modkey }, "e", function () awful.spawn("pcmanfm") end,
{description = "run filemanager", group = "launcher"}),
awful.key({ modkey }, "c", function() raise_conky() end, function() lower_conky() end)
)
clientkeys = button_table.join(
awful.key({ modkey, }, "f",
function (c)
c.fullscreen = not c.fullscreen
c:raise()
end,
{description = "toggle fullscreen", group = "client"}),
awful.key({ modkey, "Shift" }, "c", function (c) c:kill() end,
{description = "close", group = "client"}),
awful.key({ modkey, "Control" }, "space", awful.client.floating.toggle ,
{description = "toggle floating", group = "client"}),
awful.key({ modkey, }, "o", function (c) c:move_to_screen() end,
{description = "move to screen", group = "client"}),
awful.key({ modkey, }, "t", function (c) c.ontop = not c.ontop end,
{description = "toggle keep on top", group = "client"}),
awful.key({ modkey, }, "h",
function (c)
-- The client currently has the input focus, so it cannot be
-- minimized, since minimized clients can't have the focus.
c.minimized = true
end ,
{description = "minimize", group = "client"}),
awful.key({ modkey, }, "m",
function (c)
c.maximized = not c.maximized
c:raise()
end ,
{description = "maximize", group = "client"})
)
-- Bind all key numbers to tags.
-- Be careful: we use keycodes to make it works on any keyboard layout.
-- This should map on the top row of your keyboard, usually 1 to 9.
for i = 1, 9 do
globalkeys = button_table.join(globalkeys,
-- View tag only.
awful.key({ modkey }, "#" .. i + 9,
function ()
local screen = awful.screen.focused()
local tag = screen.tags[i]
if tag then
tag:view_only()
end
end,
{description = "view tag #"..i, group = "tag"}),
-- Toggle tag display.
awful.key({ modkey, "Control" }, "#" .. i + 9,
function ()
local screen = awful.screen.focused()
local tag = screen.tags[i]
if tag then
awful.tag.viewtoggle(tag)
end
end,
{description = "toggle tag #" .. i, group = "tag"}),
-- Move client to tag.
awful.key({ modkey, "Shift" }, "#" .. i + 9,
function ()
if client.focus then
local tag = client.focus.screen.tags[i]
if tag then
client.focus:move_to_tag(tag)
end
end
end,
{description = "move focused client to tag #"..i, group = "tag"}),
-- Toggle tag on focused client.
awful.key({ modkey, "Control", "Shift" }, "#" .. i + 9,
function ()
if client.focus then
local tag = client.focus.screen.tags[i]
if tag then
client.focus:toggle_tag(tag)
end
end
end,
{description = "toggle focused client on tag #" .. i, group = "tag"})
)
end
clientbuttons = button_table.join(
--awful.button({ }, 1, function (c) client.focus = c; c:raise() end),
awful.button({ }, 1, function (c)
if c.class == "FlowBladeWindow" then return end
client.focus = c;
c:raise()
end),
awful.button({ modkey }, 1, awful.mouse.client.move),
awful.button({ modkey }, 3, awful.mouse.client.resize))
-- Set keys
root.keys(globalkeys)
-- }}}
-- {{{ Rules
-- Rules to apply to new clients (through the "manage" signal).
awful.rules.rules = {
-- All clients will match this rule.
{ rule = { },
properties = { border_width = beautiful.border_width,
border_color = beautiful.border_normal,
focus = awful.client.focus.filter,
raise = true,
keys = clientkeys,
buttons = clientbuttons,
screen = awful.screen.preferred,
placement = awful.placement.no_overlap+awful.placement.no_offscreen
}
},
-- Floating clients.
{ rule_any = {
instance = {
"DTA", -- Firefox addon DownThemAll.
"copyq", -- Includes session name in class.
},
class = {
"Arandr",
"Gpick",
"Kruler",
"MessageWin", -- kalarm.
"Sxiv",
"Wpa_gui",
"pinentry",
"veromix",
"xtightvncviewer",
"Sakura",
"RSE",
"SeVi",
"SeVi - Sequel Viewer",
"TeamViewer",
"VirtualBox",
"Mullvad",
"pcmanfm",
"Pcmanfm"},
name = {
"Event Tester", -- xev.
"SeVi - Sequel Viewer"
},
icon_name = {
"SeVi - Sequel Viewer",
"SeVi",
"RSE"
},
role = {
"AlarmWindow", -- Thunderbird's calendar.
"pop-up", -- e.g. Google Chrome's (detached) Developer Tools.
}
}, properties = { floating = true }},
-- Add titlebars to normal clients and dialogs
{ rule_any = {type = { "normal", "dialog" }
}, properties = { titlebars_enabled = false }
},
{ rule = { class = "Conky" },
properties = {
floating = true,
sticky = true,
ontop = false,
border_width = 0,
focusable = false
}
},
{ rule = { class = "Plank" },
properties = {
border_width = 0,
floating = true,
sticky = true,
ontop = false,
focusable = false,
below = true
}
},
{
rule = {
class = "jetbrains-.*",
instance = "sun-awt-X11-XWindowPeer",
name = "win.*"
},
properties = {
-- floating = true,
-- focus = true,
-- focusable = false,
-- ontop = true,
-- placement = awful.placement.restore,
-- buttons = {}
},
}
}
-- }}}
-- {{{ Signals
-- Signal function to execute when a new client appears.
client.connect_signal("manage", function (c)
-- Set the windows at the slave,
-- i.e. put it at the end of others instead of setting it master.
-- if not awesome.startup then awful.client.setslave(c) end
if awesome.startup and
not c.size_hints.user_position
and not c.size_hints.program_position then
-- Prevent clients from being unreachable after screen count changes.
awful.placement.no_offscreen(c)
end
end)
-- Add a titlebar if titlebars_enabled is set to true in the rules.
client.connect_signal("request::titlebars", function(c)
-- buttons for the titlebar
local buttons = button_table.join(
awful.button({ }, 1, function()
client.focus = c
c:raise()
awful.mouse.client.move(c)
end),
awful.button({ }, 3, function()
client.focus = c
c:raise()
awful.mouse.client.resize(c)
end)
)
awful.titlebar(c) : setup {
{ -- Left
--awful.titlebar.widget.iconwidget(c),
buttons = buttons,
layout = wibox.layout.fixed.horizontal
},
{ -- Middle
{ -- Title
align = "center",
widget = awful.titlebar.widget.titlewidget(c)
},
buttons = buttons,
layout = wibox.layout.flex.horizontal
},
{ -- Right
awful.titlebar.widget.floatingbutton (c),
--awful.titlebar.widget.maximizedbutton(c),
--awful.titlebar.widget.stickybutton (c),
--awful.titlebar.widget.ontopbutton (c),
awful.titlebar.widget.closebutton (c),
layout = wibox.layout.fixed.horizontal()
},
layout = wibox.layout.align.horizontal
}
end)
-- Enable sloppy focus, so that focus follows mouse.
--client.connect_signal("mouse::enter", function(c)
-- if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier
-- and awful.client.focus.filter(c) then
-- client.focus = c
-- end
--end)
-- Enable sloppy focus (without defocusing IntelliJ dialogs)
client.connect_signal("mouse::enter", function(c)
local focused = client.focus
if focused
and focused.class == c.class
and focused.instance == "sun-awt-X11-XDialogPeer"
and c.instance == "sun-awt-X11-XFramePeer"
then
return
end
if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier
and awful.client.focus.filter(c) then
client.focus = c
end
end)
client.connect_signal("focus", function(c) c.border_color = beautiful.border_focus end)
client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end)
-- }}}
-- Conky raise
do
local conky = nil
function get_conky(default)
if conky and conky.valid then
return conky
end
conky = awful.client.iterate(function(c) return c.class == "Conky" end)()
return conky or default
end
function raise_conky()
get_conky({}).ontop = true
end
function lower_conky()
get_conky({}).ontop = false
end
function toggle_conky()
local conky = get_conky({})
conky.ontop = not conky.ontop
end
end
client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end)
|
-- Copyright 2022 SmartThings
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local ZigbeeDriver = require "st.zigbee"
local defaults = require "st.zigbee.defaults"
local battery_defaults = require "st.zigbee.defaults.battery_defaults"
local timer_const = require "constants/timer-constants"
-- Capabilities
local capabilities = require "st.capabilities"
local Tone = capabilities.tone
local PresenceSensor = capabilities.presenceSensor
local SignalStrength = capabilities.signalStrength
-- Zigbee Spec Utils
local clusters = require "st.zigbee.zcl.clusters"
local Basic = clusters.Basic
local PowerConfiguration = clusters.PowerConfiguration
local IdentifyCluster = clusters.Identify
local zcl_global_commands = require "st.zigbee.zcl.global_commands"
local Status = (require "st.zigbee.zcl.types").ZclStatus
local buf_lib = require "st.buf"
local zb_messages = require "st.zigbee.messages"
local BEEP_IDENTIFY_TIME = 5 -- seconds
local IS_PRESENCE_BASED_ON_BATTERY_REPORTS = "isPresenceBasedOnBatteryReports"
local ST_ARRIVAL_SENSOR_CUSTOM_PROFILE = 0xFC01
local DEFAULT_PRESENCE_TIMEOUT_S = 120
local battery_voltage_attr_configuration = {
cluster = PowerConfiguration.ID,
attribute = PowerConfiguration.attributes.BatteryVoltage.ID,
minimum_interval = 1,
maximum_interval = 21,
data_type = PowerConfiguration.attributes.BatteryVoltage.base_type,
reportable_change = 1
}
local battery_table = {
[2.80] = 100,
[2.70] = 100,
[2.60] = 100,
[2.50] = 90,
[2.40] = 80,
[2.30] = 70,
[2.20] = 70,
[2.10] = 50,
[2.00] = 50,
[1.90] = 30,
[1.80] = 30,
[1.70] = 15,
[1.60] = 1,
[1.50] = 0
}
local function emit_signal_strength_events(device, zb_rx)
device:emit_event(SignalStrength.lqi(zb_rx.lqi.value))
device:emit_event(SignalStrength.rssi({value = zb_rx.rssi.value, unit = 'dBm'}))
end
local function battery_config_response_handler(self, device, zb_rx)
if zb_rx.body.zcl_body.global_status.value == Status.SUCCESS then
device:set_field(IS_PRESENCE_BASED_ON_BATTERY_REPORTS, true, {persist = true})
local poll_timer = device:get_field(timer_const.RECURRING_POLL_TIMER)
if poll_timer ~= nil then
device.thread:cancel_timer(poll_timer)
device:set_field(timer_const.RECURRING_POLL_TIMER, nil)
end
end
end
local function create_poll_schedule(device)
local should_schedule_recurring_polling = not (device:get_field(IS_PRESENCE_BASED_ON_BATTERY_REPORTS) or true)
local timer = device:get_field(timer_const.RECURRING_POLL_TIMER)
if should_schedule_recurring_polling then
if timer ~= nil then
device.thread:cancel_timer(timer)
end
-- Set the poll interval to 1/2 the actual check interval so a single missed message doens't result in not present
local new_timer = device.thread:call_on_schedule(math.floor(device.preferences.check_interval / 2) - 1, function()
device:send(Basic.attributes.ZCLVersion:read(device))
end, "polling_schedule_timer")
device:set_field(timer_const.RECURRING_POLL_TIMER, new_timer)
elseif timer ~= nil then
device.thread:cancel_timer(timer)
device:set_field(timer_const.RECURRING_POLL_TIMER, nil)
end
end
local function create_presence_timeout(device)
local timer = device:get_field(timer_const.PRESENCE_CALLBACK_TIMER)
if timer ~= nil then
device.thread:cancel_timer(timer)
end
local no_rep_timer = device:get_field(timer_const.PRESENCE_CALLBACK_CREATE_FN)
if (no_rep_timer ~= nil) then
device:set_field(timer_const.PRESENCE_CALLBACK_TIMER, no_rep_timer(device))
end
end
local function info_changed(self, device, event, args)
if args.old_st_store.preferences.check_interval ~= device.preferences.check_interval then
create_poll_schedule(device)
end
end
local function get_check_interval_int(device)
if type(device.preferences.checkInterval) == "number" then
return device.preferences.checkInterval
elseif type(device.preferences.checkInterval) == "string" and tonumber(device.preferences.checkInterval) ~= nil then
return tonumber(device.preferences.checkInterval)
end
return DEFAULT_PRESENCE_TIMEOUT_S
end
local function init_handler(self, device, event, args)
device:set_field(battery_defaults.DEVICE_VOLTAGE_TABLE_KEY, battery_table)
device:add_configured_attribute(battery_voltage_attr_configuration)
device:add_monitored_attribute(battery_voltage_attr_configuration)
device:remove_monitored_attribute(PowerConfiguration.ID, PowerConfiguration.attributes.BatteryPercentageRemaining.ID)
device:remove_configured_attribute(PowerConfiguration.ID, PowerConfiguration.attributes.BatteryPercentageRemaining.ID)
device:set_field(
timer_const.PRESENCE_CALLBACK_CREATE_FN,
function(device)
return device.thread:call_with_delay(
get_check_interval_int(device),
function()
device:emit_event(PresenceSensor.presence("not present"))
device:emit_event(SignalStrength.lqi(0))
device:emit_event(SignalStrength.rssi({value = -100, unit = 'dBm'}))
device:set_field(timer_const.PRESENCE_CALLBACK_TIMER, nil)
end
)
end
)
local should_schedule_recurring_polling = not (device:get_field(IS_PRESENCE_BASED_ON_BATTERY_REPORTS) or true)
if should_schedule_recurring_polling then
create_poll_schedule(device)
create_presence_timeout(device)
end
end
local function beep_handler(self, device, command)
device:send(IdentifyCluster.server.commands.Identify(device, BEEP_IDENTIFY_TIME))
end
local function added_handler(self, device)
device:emit_event(PresenceSensor.presence("present"))
device:set_field(IS_PRESENCE_BASED_ON_BATTERY_REPORTS, false, {persist = true})
device:send(PowerConfiguration.attributes.BatteryVoltage:read(device))
end
local function poke(device)
-- If we receive any message from the device, we should mark it present and start the timeout to mark it offline
device:emit_event(PresenceSensor.presence("present"))
create_presence_timeout(device)
end
local function all_zigbee_message_handler(self, message_channel)
local device_uuid, data = message_channel:receive()
local buf = buf_lib.Reader(data)
local zb_rx = zb_messages.ZigbeeMessageRx.deserialize(buf, {additional_zcl_profiles = self.additional_zcl_profiles})
local device = self:get_device_info(device_uuid)
if zb_rx ~= nil then
device.log.info(string.format("received Zigbee message: %s", zb_rx:pretty_print()))
device:attribute_monitor(zb_rx)
if (device:supports_capability_by_id("signalStrength") and zb_rx.rssi.value ~= nil and zb_rx.lqi.value ~= nil) then
emit_signal_strength_events(device, zb_rx)
end
poke(device)
device.thread:queue_event(self.zigbee_message_dispatcher.dispatch, self.zigbee_message_dispatcher, self, device, zb_rx)
end
end
local zigbee_presence_driver = {
supported_capabilities = {
capabilities.presenceSensor,
capabilities.tone,
capabilities.signalStrength,
capabilities.battery,
capabilities.refresh
},
zigbee_handlers = {
attr = {
[PowerConfiguration.ID] = {
[PowerConfiguration.attributes.BatteryVoltage.ID] = battery_defaults.battery_volt_attr_handler
}
},
global = {
[PowerConfiguration.ID] = {
[zcl_global_commands.CONFIGURE_REPORTING_RESPONSE_ID] = battery_config_response_handler
}
}
},
capability_handlers = {
[Tone.ID] = {
[Tone.commands.beep.NAME] = beep_handler
}
},
lifecycle_handlers = {
added = added_handler,
init = init_handler,
infoChanged = info_changed,
},
additional_zcl_profiles = {
[ST_ARRIVAL_SENSOR_CUSTOM_PROFILE] = true
},
-- Custom handler for every Zigbee message
zigbee_message_handler = all_zigbee_message_handler,
sub_drivers = {
require("arrival-sensor-v1")
}
}
defaults.register_for_default_handlers(zigbee_presence_driver, zigbee_presence_driver.supported_capabilities)
local driver = ZigbeeDriver("zigbee-presence-sensor", zigbee_presence_driver)
driver:run()
|
local t = require( "taptest" )
local readfile = require( "readfile" )
f = io.open( "ReadFileXmpl.txt", "w" )
f:write( "a ", "long ", "text\n", "is ", 1337 )
f:close()
str, err = readfile( "ReadFileXmpl.txt" )
t( str, "a long text\nis 1337" )
t( err, nil )
os.remove( "ReadFileXmpl.txt" )
t()
|
wrk.method = "GET"
|
if (data.raw.recipe["alien-science-pack"] ~= nil) then
data.raw.recipe["alien-science-pack"].result_count = 100
end
|
local Lambda = wickerrequire "paradigms.functional"
local FunctionQueue = wickerrequire "gadgets.functionqueue"
local AddWorldgenMainPostLoad
if IsWorldgen() then
local postloads = FunctionQueue()
local json = require "json"
json.decode = (function()
local decode = json.decode
local did_patch = false
return function(...)
if not did_patch then
local generate_new = rawget(_G, "GenerateNew")
if generate_new then
postloads()
postloads = nil
did_patch = true
json.decode = decode
end
end
return decode(...)
end
end)()
AddWorldgenMainPostLoad = function(fn)
table.insert(postloads, fn)
end
else
AddWorldgenMainPostLoad = Lambda.Nil
end
TheMod:EmbedHook("AddWorldgenMainPostLoad", AddWorldgenMainPostLoad)
TheMod:EmbedHook("AddWorldGenMainPostLoad", AddWorldgenMainPostLoad)
|
return Def.Quad {
InitCommand=cmd(x,SCREEN_CENTER_X;y,SCREEN_CENTER_Y;scaletoclipped,SCREEN_WIDTH*2,SCREEN_HEIGHT*2);
GainFocusCommand=cmd(finishtweening;diffusealpha,0;accelerate,0.6;diffusealpha,1);
};
|
ITEM.name = "Teapot"
ITEM.desc = "An old ceramic teapot"
ITEM.model = "models/z-o-m-b-i-e/metro_2033/station_props/m33_teapot_03.mdl"
ITEM.width = 1
ITEM.height = 1
ITEM.money = {1, 3}
|
#!/usr/bin/lua
local util = require "luci.util"
assert(arg[1])
local x = {}
local f = loadfile(arg[1])
setfenv(f, x)
f()
print '<?xml version="1.0" encoding="utf-8"?>'
print ''
print '<i18n:msgs xmlns:i18n="http://luci.freifunk-halle.net/2008/i18n#" xmlns="http://www.w3.org/1999/xhtml">'
print ''
for k, v in util.kspairs(x) do
print ('<i18n:msg xml:id="%s">%s</i18n:msg>' % {k, v})
end
print ''
print '</i18n:msgs>'
|
CMD.name = 'UnfreezeBots'
CMD.description = 'command.unfreezebots.description'
CMD.permission = 'moderator'
CMD.category = 'permission.categories.server_management'
CMD.aliases = { 'botunfreeze', 'unfreezebot', 'bot_unfreeze', 'bot_unzombie' }
function CMD:on_run(player)
self:notify_staff('command.unfreezebots.message', {
player = get_player_name(player)
})
RunConsoleCommand('bot_zombie', 0)
end
|
local dap = require('dap')
dap.adapters.php = {
type = 'executable',
command = 'node',
args = { '/opt/vscode-php-debug/out/phpDebug.js' }
}
dap.configurations.php = {
{
type = 'php',
request = 'launch',
name = 'Listen for Xdebug',
port = 9003
}
}
require("nvim-dap-virtual-text").setup()
local map = vim.api.nvim_set_keymap
local silentnoremap = {noremap = true, silent = true}
map('n', '<F5>', '<cmd>lua require"dap".continue()<CR>', silentnoremap)
map('n', '<F10>', '<cmd>lua require"dap".step_over()<CR>', silentnoremap)
map('n', '<F11>', '<cmd>lua require"dap".step_into()<CR>', silentnoremap)
map('n', '<F12>', '<cmd>lua require"dap".step_out()<CR>', silentnoremap)
map('n', '<Leader>b', '<cmd>lua require"dap".toggle_breakpoint()<CR>', silentnoremap)
map('n', '<Leader>B', '<cmd>lua require"dap".set_breakpoint(vim.fn.input("Breakpoint condition: "))<CR>', silentnoremap)
map('n', '<Leader>lp', '<cmd>lua require"dap".set_breakpoint(nil, nil, vim.fn.input("Log point message: "))<CR>', silentnoremap)
map('n', '<Leader>dr', '<cmd>lua require"dap".repl.open()<CR>', silentnoremap)
|
local version = Ext.Version()
if version < 56 and Ext.IO == nil then
local tbl = {
AddPathOverride = Ext.AddPathOverride,
GetPathOverride = Ext.GetPathOverride,
LoadFile = Ext.LoadFile,
SaveFile = Ext.SaveFile,
}
if Ext.GetPathOverride == nil then
tbl.GetPathOverride = function() return nil end
end
rawset(Ext, "IO", tbl)
end
ModuleFolder = Ext.GetModInfo(ModuleUUID).Directory
---@class CharacterExpansionLibListeners:table
local listeners = {}
Mods.CharacterExpansionLib.Listeners = listeners
Mods.LeaderLib.Import(Mods.CharacterExpansionLib)
---Makes CharacterExpansionLib's and LeaderLib's globals accessible using metamethod magic. Pass it a mod table, such as Mods.MyModTable.
---Usage: Mods.CharacterExpansionLib.Import(Mods.MyModTable)
---@param targetModTable table
function Import(targetModTable)
Mods.LeaderLib.Import(targetModTable, Mods.CharacterExpansionLib)
end
local isClient = Ext.IsClient()
---@alias SetCharacterCreationOriginSkillsCallback fun(player:EclCharacter, origin:string, race:string, skills:string[]):string[]
if isClient then
listeners.SetCharacterCreationOriginSkills = {
---@private
---@type SetCharacterCreationOriginSkillsCallback[]
Callbacks = {},
---@param callback SetCharacterCreationOriginSkillsCallback
Register = function(callback)
table.insert(listeners.SetCharacterCreationOriginSkills.Callbacks, callback)
end
}
end
local printMessages = {
CEL_SheetManager_RequestValueChange = true,
CEL_SheetManager_LoadAvailablePointsForCharacter = true,
CEL_SheetManager_LoadAllAvailablePoints = true,
CEL_SheetManager_RequestAvailablePoints = true,
CEL_SheetManager_RequestAvailablePointsWithDelay = true,
CEL_RequestSyncAvailablePoints = true,
}
if version >= 56 then
local _netListeners = {}
Ext.Events.NetMessageReceived:Subscribe(function(e)
InvokeListenerCallbacks(_netListeners[e.Channel], e.Channel, e.Payload, e.UserID)
end)
---@param id string
---@param callback fun(id:string, payload:string, user:integer|nil):void
function RegisterNetListener(id, callback)
if _netListeners[id] == nil then
_netListeners[id] = {}
end
local listeners = _netListeners[id]
local wrapper = function (_id, payload, user)
fprint(LOGLEVEL.WARNING, "[%s:NetListener] id(%s) user(%s) payload:\n%s", isClient and "CLIENT" or "SERVER", _id, user, payload)
-- if Vars.LeaderDebugMode and printMessages[id] then
-- --fprint(LOGLEVEL.WARNING,"%s (%s)", id, isClient and "CLIENT" or "SERVER")
-- fprint(LOGLEVEL.WARNING, "[%s:NetListener] id(%s) user(%s) payload:\n%s", isClient and "CLIENT" or "SERVER", _id, user, payload)
-- end
local b,err = xpcall(callback, debug.traceback, _id, payload, user)
if not b then
Ext.PrintError(err)
end
end
listeners[#listeners+1] = wrapper
end
else
---@param id string
---@param callback fun(id:string, payload:string, user:integer|nil):void
function RegisterNetListener(id, callback)
local wrapper = function (_id, payload, user)
if Vars.LeaderDebugMode and printMessages[id] then
--fprint(LOGLEVEL.WARNING,"%s (%s)", id, isClient and "CLIENT" or "SERVER")
fprint(LOGLEVEL.WARNING, "[%s:NetListener] id(%s) user(%s) payload:\n%s", isClient and "CLIENT" or "SERVER", _id, user, payload)
end
local b,err = xpcall(callback, debug.traceback, _id, payload, user)
if not b then
Ext.PrintError(err)
end
end
Ext.RegisterNetListener(id, wrapper)
end
end
Ext.Require("SheetManager/Init.lua")
local function TryFindOsiToolsConfig(info)
local filePath = string.format("Mods/%s/OsiToolsConfig.json", info.Directory)
local file = Ext.LoadFile(filePath, "data")
if file then
return Common.JsonParse(file)
end
end
local function CheckOsiToolsConfig()
local order = Ext.GetModLoadOrder()
for i=1,#order do
local uuid = order[i]
if IgnoredMods[uuid] ~= true then
local info = Ext.GetModInfo(uuid)
if info ~= nil then
local b,result = xpcall(TryFindOsiToolsConfig, debug.traceback, info)
if not b then
Ext.PrintError(result)
elseif result ~= nil then
if result.FeatureFlags
and (Common.TableHasValue(result.FeatureFlags, "CustomStats") or Common.TableHasValue(result.FeatureFlags, "CustomStatsPane")) then
return true
end
end
end
end
end
end
RegisterListener("LuaReset", function()
Mods.LeaderLib.Vars.Print.UI = true
--CheckOsiToolsConfig()
end)
|
local function frequencies(arr)
local result = {}
for i = 1, #arr do
result[arr[i]] = (result[arr[i]] or 0) + 1
end
return result
end
return frequencies
|
-- Back button navigation
-- Part of Live Simulator: 2
-- See copyright notice in main.lua
local love = require("love")
local Luaoop = require("libs.Luaoop")
local AssetCache = require("asset_cache")
local MainFont = require("main_font")
local color = require("color")
local ImageButton = require("game.ui.image_button")
local BackNavigation = Luaoop.class("Livesim2.BackNavigation", ImageButton)
function BackNavigation:new(name)
local font = MainFont.get(22)
local images = AssetCache.loadMultipleImages({
"assets/image/ui/com_button_01.png",
"assets/image/ui/com_button_01se.png",
"assets/image/ui/com_win_02.png"
}, {mipmaps = true})
ImageButton.new(self, images)
self.bar = images[3]
self.text = love.graphics.newText(font)
self.text:add({color.black, name}, 95, 9)
end
function BackNavigation:render(x, y)
love.graphics.setColor(color.white)
love.graphics.draw(self.bar, x - 98, y)
love.graphics.draw(self.text, x, y)
return ImageButton.render(self, x, y)
end
return BackNavigation
|
local background, displacements
local color_buffer, intermediate_buffer
local time_elapsed = 0
local function id(...)
return ...
end
local function clamp(value, low, high)
if value < low then
return low
elseif high < value then
return high
end
return value
end
local examples = {
{
shader_basename = 'uv_red_green',
init = id,
on_render_image = function(self, source, destination)
love.graphics.setShader(self.shader)
destination:renderTo(function()
love.graphics.draw(source)
end)
end,
change_parameter = id
},
{
shader_basename = 'texture_uv_red_green',
init = id,
on_render_image = function(self, source, destination)
love.graphics.setShader(self.shader)
destination:renderTo(function()
love.graphics.draw(source)
end)
end,
change_parameter = id
},
{
shader_basename = 'displacements',
init = function(self)
self.displacement_map = love.graphics.newImage('displacements.png')
self.magnitude = 0
end,
on_render_image = function(self, source, destination)
love.graphics.setShader(self.shader)
self.shader:send('displacements', self.displacement_map)
self.shader:send('magnitude', self.magnitude)
destination:renderTo(function()
love.graphics.draw(source)
end)
end,
change_parameter = function(self, direction)
self.magnitude = clamp(self.magnitude + direction * 0.01, 0, 0.1)
end
},
{
shader_basename = 'animated_displacements',
init = function(self)
self.displacement_map = love.graphics.newImage('displacements.png')
self.magnitude = 0.01
end,
on_render_image = function(self, source, destination)
love.graphics.setShader(self.shader)
self.shader:send('displacements', self.displacement_map)
self.shader:send('magnitude', self.magnitude)
self.shader:send('time', time_elapsed)
destination:renderTo(function()
love.graphics.draw(source)
end)
end,
change_parameter = function(self, direction)
self.magnitude = clamp(self.magnitude + direction * 0.01, 0.01, 0.1)
end
},
{
shader_basename = 'box_blur',
init = id,
on_render_image = function(self, source, destination)
love.graphics.setShader(self.shader)
self.shader:send('pixel_size', {1 / love.graphics.getWidth(), 1 / love.graphics.getHeight()})
destination:renderTo(function()
love.graphics.draw(source)
end)
end,
change_parameter = id
},
{
shader_basename = 'box_blur',
init = function(self)
local width, height = love.graphics.getDimensions()
self.render_textures = {
love.graphics.newCanvas(),
love.graphics.newCanvas()
}
self.iterations = 1
end,
on_render_image = function(self, source, destination)
love.graphics.setShader()
self.render_textures[1]:renderTo(function()
love.graphics.draw(source)
end)
love.graphics.setShader(self.shader)
self.shader:send('pixel_size', {1 / love.graphics.getWidth(), 1 / love.graphics.getHeight()})
local downres_source_index = 1
for i = 1, self.iterations do
local downres_destination_index = 1
if downres_source_index == 1 then
downres_destination_index = 2
end
self.render_textures[downres_destination_index]:renderTo(function()
love.graphics.draw(self.render_textures[downres_source_index])
end)
downres_source_index = math.fmod(downres_source_index, 2) + 1
end
love.graphics.setShader()
destination:renderTo(function()
love.graphics.draw(self.render_textures[downres_source_index])
end)
end,
change_parameter = function(self, direction)
self.iterations = clamp(self.iterations + direction, 1, 10)
end
},
{
shader_basename = 'box_blur',
init = function(self)
local width, height = love.graphics.getDimensions()
self.scale_factor = 1 / 2
self.intermediate_width = math.floor(width * self.scale_factor)
self.intermediate_height = math.floor(height * self.scale_factor)
self.render_textures = {
love.graphics.newCanvas(self.intermediate_width, self.intermediate_height),
love.graphics.newCanvas(self.intermediate_width, self.intermediate_height)
}
self.iterations = 1
end,
on_render_image = function(self, source, destination)
love.graphics.setShader()
self.render_textures[1]:renderTo(function()
love.graphics.draw(source, 0, 0, 0, self.scale_factor)
end)
love.graphics.setShader(self.shader)
self.shader:send('pixel_size', {1 / self.intermediate_width, 1 / self.intermediate_height})
local downres_source_index = 1
for i = 1, self.iterations do
local downres_destination_index = 1
if downres_source_index == 1 then
downres_destination_index = 2
end
self.render_textures[downres_destination_index]:renderTo(function()
love.graphics.draw(self.render_textures[downres_source_index])
end)
downres_source_index = math.fmod(downres_source_index, 2) + 1
end
love.graphics.setShader()
destination:renderTo(function()
love.graphics.draw(self.render_textures[downres_source_index], 0, 0, 0, 1 / self.scale_factor)
end)
end,
change_parameter = function(self, direction)
self.iterations = clamp(self.iterations + direction, 1, 10)
end
}
}
local current_example = 1
function love.load()
-- This is a screengrab from our Ludum Dare 34 game, Tailwind. While this is
-- a static screen, the same techniques used in this program can be used for
-- dynamic scenes as well.
background = love.graphics.newImage('sample-screen.png')
-- LOVE does not appear to have an equivalent hook for OnRenderImage. To
-- simulate it, render to a canvas instead and then run a shader on that
-- before drawing it to the screen.
source_buffer = love.graphics.newCanvas()
destination_buffer = love.graphics.newCanvas()
for _, example in ipairs(examples) do
example.shader = love.graphics.newShader(example.shader_basename .. ".frag")
end
examples[current_example]:init()
end
function love.update(dt)
time_elapsed = time_elapsed + dt
end
-- This is where normal game rendering logic goes. It's a separate function to
-- keep the image effect code isolated and clean.
local function draw()
love.graphics.draw(background)
end
function love.draw()
source_buffer:renderTo(draw)
examples[current_example]:on_render_image(source_buffer, destination_buffer)
love.graphics.setShader()
love.graphics.draw(destination_buffer)
end
function love.keypressed(key)
if key == 'left' then
current_example = clamp(current_example - 1, 1, #examples)
examples[current_example]:init()
elseif key == 'right' then
current_example = clamp(current_example + 1, 1, #examples)
examples[current_example]:init()
elseif key == 'up' then
examples[current_example]:change_parameter(1)
elseif key == 'down' then
examples[current_example]:change_parameter(-1)
end
end
|
vim.keymap.set("n", "<C-h>", "<C-W>h", { silent = true, noremap = true, desc = "Move to window on left" })
vim.keymap.set("n", "<C-j>", "<C-W>j", { silent = true, noremap = true, desc = "Move to window below" })
vim.keymap.set("n", "<C-k>", "<C-W>k", { silent = true, noremap = true, desc = "Move to window above" })
vim.keymap.set("n", "<C-l>", "<C-W>l", { silent = true, noremap = true, desc = "Move to window on right" })
vim.keymap.set("n", "<S-l>", ":bnext<CR>", { silent = true, noremap = true, desc = "Move to next buffer" })
vim.keymap.set("n", "<S-h>", ":bprevious<CR>", { silent = true, noremap = true, desc = "Move to previous buffer" })
-- vim.keymap.set("t", "<Esc>", "<C-\\><C-n>", {silent = true, noremap = true, desc = "Easy escape in terminal mode"})
vim.keymap.set("", "<Leader>c", ":close<CR>", { silent = true, noremap = true, desc = "Close window" })
vim.keymap.set("", "<Leader>w", ":w!<CR>", { silent = true, noremap = true, desc = "Write buffer" })
-- vim.keymap.set("", "<Leader>q", ":br <BAR> bd #<CR>", {silent = true, noremap = true})
vim.keymap.set("", "<Leader>q", ":bd<CR>", { silent = true, noremap = true, desc = "Close buffer" })
vim.keymap.set("v", "<", "<gv", { silent = true, noremap = true, desc = "Align to left" })
vim.keymap.set("v", ">", ">gv", { silent = true, noremap = true, desc = "Align to right" })
vim.keymap.set("n", "<C-m-j>", ":m .+1<CR>==", { silent = true, noremap = true })
vim.keymap.set("n", "<C-m-k>", ":m .-2<CR>==", { silent = true, noremap = true })
vim.keymap.set("i", "<C-m-j>", "<Esc>:m .+1<CR>==gi", { silent = true, noremap = true })
vim.keymap.set("i", "<C-m-k>", "<Esc>:m .-2<CR>==gi", { silent = true, noremap = true })
vim.keymap.set("v", "<C-m-j>", ":m '>+1<CR>gv=gv", { silent = true, noremap = true })
vim.keymap.set("v", "<C-m-k>", ":m '<-2<CR>gv=gv", { silent = true, noremap = true })
vim.keymap.set("n", "<Leader>qa", ":qa!<CR>", { silent = true, noremap = true, desc = "Quit" })
vim.keymap.set("i", "<C-H>", "<C-W>", { silent = true, noremap = true, desc = "Delete word backwards" })
-- jk as escape
vim.keymap.set("i", "jk", "<ESC>", { silent = true, noremap = true, desc = "Escape in insert mode" })
vim.keymap.set(
"n",
"<Leader><space>",
":nohlsearch<CR>",
{ noremap = true, silent = false, expr = false, desc = "Remove search" }
)
vim.keymap.set("n", "<Leader>pack", ":PackerSync<CR>", { silent = true, noremap = true, desc = "Run PackerSync" })
vim.cmd('command! -nargs=0 LspVirtualTextToggle lua require("lsp/virtual_text").toggle()')
vim.keymap.set("n", "<Leader>r", ":e!<CR>", { silent = true, noremap = true, desc = "Reload file" })
|
local Player = brixy.GetAuthorizedUser
local Players = game.Players
function CreateChatBox()
local ChatContainer = instance.new("ScreenGui")
ChatContainer.Parent = Player.CoreGui
ChatContainer.Name = "Chat"
ChatContainer.Manifest = brixy:CreateManifest(ChatContainer.Name, nil, nil, true, 500)
ChatContainer.IgnoreGuiInset = true
ChatContainer.FitToScreen = true
ChatContainer.Size = Vector3.new(125, 70, 125, 70)
ChatContainer.Position = Ratio:TOP_LEFT
local Textbox = instance.new("Textbox")
Textbox.Parent = ChatContainer
Textbox.Name = "TextBox_1"
Textbox.Manifest = brixy:CreateManifest(Textbox.Name, nil, brixy.Chat, true, 500)
Textbox.IgnoreGuiInset = false
Textbox.FitToScreen = true
Textbox.Size = Vector3.new(100, 20, 100, 20)
Textbox.Position = Ratio:BOTTOM
Textbox.Anchor = Vector3.new(Ratio.Anchor:LEFT_RIGHT)
local Sendbutton = instance.new("Button")
Sendbutton.Parent = ChatContainer
Sendbutton.Name = "Send"
Sendbutton.Manifest = brixy:CreateManifest(Send.Name, nil, brixy.Chat, false, 250)
Sendbutton.IgnoreGuiInset = true
Sendbutton.FitToScreen = true
Sendbutton.Size = Vector3.new(25,25,25,25)
Sendbutton.Position = Ratio:RIGHT
Sendbutton.Anchor = Vector3.new(Ratio.Anchor:RIGHT)
repeat wait() until ChatContainer.Exists == true && Textbox.Exists == true && Sendbutton.Exists == true then
brixy.Chat:Start(brixy:CreateLog("ChatCreation", "log", true, CreateChatBox.Log))
end
Sendbutton.Clicked:Connect(function()
local Text = Textbox.TypedText
local TextFiltered = brixy.FilterChat(Text, bool)
if TextFiltered.Status == false then
break
print("Chat was filtered not sending")
elseif TextFiltered.Status == true then
local fire_event = brixy.FireChatEvent(Player, TextFiltered, os.time, BrickColor.new(math.random(0,100)))
if fire_event.Status == "fail" then
break
print("Failed")
elseif fire_event.Status == "success" then
break
end
end
end
end
|
ts_furniture = {}
-- If true, you can sit on chairs and benches, when right-click them.
ts_furniture.enable_sitting = minetest.settings:get_bool("ts_furniture.enable_sitting", true)
ts_furniture.globalstep = minetest.settings:get_bool("ts_furniture.globalstep", true)
ts_furniture.kneeling_bench = minetest.settings:get_bool("ts_furniture.kneeling_bench", false)
-- Used for localization
local S = minetest.get_translator("ts_furniture")
-- Get texture by node name
local T = function (node_name)
local def = minetest.registered_nodes[node_name]
if not (def and def.tiles) then
return ""
end
local tile = def.tiles[5] or def.tiles[4] or def.tiles[3] or def.tiles[2] or def.tiles[1]
if type(tile) == "string" then
return tile
elseif type(tile) == "table" and tile.name then
return tile.name
end
return ""
end
-- The following code is from "Get Comfortable [cozy]" (by everamzah; published under WTFPL)
-- Thomas S. modified it, so that it can be used in this mod
if ts_furniture.enable_sitting then
ts_furniture.sit = function(pos, _, player)
local name = player:get_player_name()
if not player_api.player_attached[name] then
if vector.length(player:get_player_velocity()) > 0 then
minetest.chat_send_player(player:get_player_name(), 'You can only sit down when you are not moving.')
return
end
player:move_to(pos)
player:set_eye_offset({x = 0, y = -7, z = 2}, {x = 0, y = 0, z = 0})
player:set_physics_override(0, 0, 0)
player_api.player_attached[name] = true
minetest.after(0.1, function()
if player then
player_api.set_animation(player, "sit" , 30)
end
end)
else
ts_furniture.stand(player, name)
end
end
ts_furniture.up = function(_, _, player)
local name = player:get_player_name()
if player_api.player_attached[name] then
ts_furniture.stand(player, name)
end
end
ts_furniture.stand = function(player, name)
player:set_eye_offset({x = 0, y = 0, z = 0}, {x = 0, y = 0, z = 0})
player:set_physics_override(1, 1, 1)
player_api.player_attached[name] = false
player_api.set_animation(player, "stand", 30)
end
-- The player will stand at the beginning of the movement
if ts_furniture.globalstep and not minetest.get_modpath("cozy") then
minetest.register_globalstep(function(dtime)
local players = minetest.get_connected_players()
for i = 1, #players do
local player = players[i]
local name = player:get_player_name()
local ctrl = player:get_player_control()
if default.player_attached[name] and not player:get_attach() and
(ctrl.up or ctrl.down or ctrl.left or ctrl.right or ctrl.jump) then
ts_furniture.up(nil, nil, player)
end
end
end)
end
end
-- End of [cozy] code
local furnitures = {
["chair"] = {
description = "Chair",
sitting = true,
nodebox = {
{ -0.3, -0.5, 0.2, -0.2, 0.5, 0.3 }, -- foot 1
{ 0.2, -0.5, 0.2, 0.3, 0.5, 0.3 }, -- foot 2
{ 0.2, -0.5, -0.3, 0.3, -0.1, -0.2 }, -- foot 3
{ -0.3, -0.5, -0.3, -0.2, -0.1, -0.2 }, -- foot 4
{ -0.3, -0.1, -0.3, 0.3, 0, 0.2 }, -- seating
{ -0.2, 0.1, 0.25, 0.2, 0.4, 0.26 } -- conector 1-2
},
craft = function(recipe)
return {
{ "", "group:stick" },
{ recipe, recipe },
{ "group:stick", "group:stick" }
}
end
},
["table"] = {
description = "Table",
nodebox = {
{ -0.4, -0.5, -0.4, -0.3, 0.4, -0.3 }, -- foot 1
{ 0.3, -0.5, -0.4, 0.4, 0.4, -0.3 }, -- foot 2
{ -0.4, -0.5, 0.3, -0.3, 0.4, 0.4 }, -- foot 3
{ 0.3, -0.5, 0.3, 0.4, 0.4, 0.4 }, -- foot 4
{ -0.5, 0.4, -0.5, 0.5, 0.5, 0.5 } -- table top
},
craft = function(recipe)
return {
{ recipe, recipe, recipe },
{ "group:stick", "", "group:stick" },
{ "group:stick", "", "group:stick" }
}
end
},
["small_table"] = {
description = "Small Table",
nodebox = {
{ -0.4, -0.5, -0.4, -0.3, 0.1, -0.3 }, -- foot 1
{ 0.3, -0.5, -0.4, 0.4, 0.1, -0.3 }, -- foot 2
{ -0.4, -0.5, 0.3, -0.3, 0.1, 0.4 }, -- foot 3
{ 0.3, -0.5, 0.3, 0.4, 0.1, 0.4 }, -- foot 4
{ -0.5, 0.1, -0.5, 0.5, 0.2, 0.5 } -- table top
},
craft = function(recipe)
return {
{ recipe, recipe, recipe },
{ "group:stick", "", "group:stick" }
}
end
},
["tiny_table"] = {
description = "Tiny Table",
nodebox = {
{ -0.5, -0.1, -0.5, 0.5, 0, 0.5 }, -- table top
{ -0.4, -0.5, -0.5, -0.3, -0.1, 0.5 }, -- foot 1
{ 0.3, -0.5, -0.5, 0.4, -0.1, 0.5 }, -- foot 2
},
craft = function(recipe)
local bench_name = "ts_furniture:" .. recipe:gsub(":", "_") .. "_bench"
return {
{ bench_name, bench_name }
}
end
},
["bench"] = {
description = "Bench",
sitting = true,
nodebox = {
{ -0.5, -0.1, 0, 0.5, 0, 0.5 }, -- seating
{ -0.4, -0.5, 0, -0.3, -0.1, 0.5 }, -- foot 1
{ 0.3, -0.5, 0, 0.4, -0.1, 0.5 } -- foot 2
},
craft = function(recipe)
return {
{ recipe, recipe },
{ "group:stick", "group:stick" }
}
end
}
}
if ts_furniture.kneeling_bench then
furnitures.kneeling_bench = {
description = "Kneeling Bench",
nodebox = {
{ -0.5, -0.5, 0.4, 0.5, 0.5, 0.5 },
{ -0.4, -0.5, -0.2, -0.3, -0.3, 0.5 },
{ 0.3, -0.5, -0.2, 0.4, -0.3, 0.5 },
{ -0.5, -0.3, -0.2, 0.5, -0.2, 0.2},
{ -0.5, 0.4, 0.15, 0.5, 0.5, 0.55},
},
craft = function(recipe)
local bench_name = "ts_furniture:" .. recipe:gsub(":", "_") .. "_bench"
return {
{ recipe, "" },
{ recipe, bench_name }
}
end
}
end
local ignore_groups = {
["wood"] = true,
["stone"] = true
}
function ts_furniture.register_furniture(recipe, description, tiles)
if not tiles then
tiles = T(recipe)
end
local recipe_def = minetest.registered_items[recipe]
if not recipe_def then
return
end
local groups = {}
for k, v in pairs(recipe_def.groups) do
if not ignore_groups[k] then
groups[k] = v
end
end
for furniture, def in pairs(furnitures) do
local node_name = "ts_furniture:" .. recipe:gsub(":", "_") .. "_" .. furniture
if def.sitting and ts_furniture.enable_sitting then
def.on_rightclick = ts_furniture.sit
def.on_punch = ts_furniture.up
end
minetest.register_node(":" .. node_name, {
description = S(description .. " " .. def.description),
drawtype = "nodebox",
paramtype = "light",
paramtype2 = "facedir",
sunlight_propagates = true,
tiles = { tiles },
groups = groups,
node_box = {
type = "fixed",
fixed = def.nodebox
},
on_rightclick = def.on_rightclick,
on_punch = def.on_punch
})
minetest.register_craft({
output = node_name,
recipe = def.craft(recipe)
})
end
end
ts_furniture.register_furniture("default:aspen_wood", "Aspen")
ts_furniture.register_furniture("default:pine_wood", "Pine")
ts_furniture.register_furniture("default:acacia_wood", "Acacia")
ts_furniture.register_furniture("default:wood", "Wooden")
ts_furniture.register_furniture("default:junglewood", "Jungle Wood")
if (minetest.get_modpath("moretrees")) then
ts_furniture.register_furniture("moretrees:apple_tree_planks", "Apple Tree")
ts_furniture.register_furniture("moretrees:beech_planks", "Beech")
ts_furniture.register_furniture("moretrees:birch_planks", "Birch")
ts_furniture.register_furniture("moretrees:fir_planks", "Fir")
ts_furniture.register_furniture("moretrees:oak_planks", "Oak")
ts_furniture.register_furniture("moretrees:palm_planks", "Palm")
ts_furniture.register_furniture("moretrees:rubber_tree_planks", "Rubber Tree")
ts_furniture.register_furniture("moretrees:sequoia_planks", "Sequoia")
ts_furniture.register_furniture("moretrees:spruce_planks", "Spruce")
ts_furniture.register_furniture("moretrees:willow_planks", "Willow")
end
if minetest.get_modpath("ethereal") then
ts_furniture.register_furniture("ethereal:banana_wood", "Banana")
ts_furniture.register_furniture("ethereal:birch_wood", "Birch")
ts_furniture.register_furniture("ethereal:frost_wood", "Frost")
ts_furniture.register_furniture("ethereal:mushroom_trunk", "Mushroom")
ts_furniture.register_furniture("ethereal:palm_wood", "Palm")
ts_furniture.register_furniture("ethereal:redwood_wood", "Redwood")
ts_furniture.register_furniture("ethereal:sakura_wood", "Sakura")
ts_furniture.register_furniture("ethereal:scorched_tree", "Scorched")
ts_furniture.register_furniture("ethereal:willow_wood", "Willow")
ts_furniture.register_furniture("ethereal:yellow_wood", "Healing Tree")
end
|
-- Copyright(c) 2016-2020 Panos Karabelas
-- 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.
SOLUTION_NAME = "Spartan"
EDITOR_NAME = "Editor"
RUNTIME_NAME = "Runtime"
TARGET_NAME = "Spartan" -- Name of executable
DEBUG_FORMAT = "c7"
EDITOR_DIR = "../" .. EDITOR_NAME
RUNTIME_DIR = "../" .. RUNTIME_NAME
IGNORE_FILES = {}
ADDITIONAL_INCLUDES = {}
ADDITIONAL_LIBRARIES = {}
ADDITIONAL_LIBRARIES_DBG = {}
LIBRARY_DIR = "../ThirdParty/libraries"
INTERMEDIATE_DIR = "../Binaries/Intermediate"
TARGET_DIR_RELEASE = "../Binaries/Release"
TARGET_DIR_DEBUG = "../Binaries/Debug"
API_GRAPHICS = _ARGS[1]
-- Compute graphics api specific variables
if API_GRAPHICS == "d3d11" then
API_GRAPHICS = "API_GRAPHICS_D3D11"
TARGET_NAME = "Spartan_d3d11"
IGNORE_FILES[0] = RUNTIME_DIR .. "/RHI/D3D12/**"
IGNORE_FILES[1] = RUNTIME_DIR .. "/RHI/Vulkan/**"
elseif API_GRAPHICS == "d3d12" then
API_GRAPHICS = "API_GRAPHICS_D3D12"
TARGET_NAME = "Spartan_d3d12"
IGNORE_FILES[0] = RUNTIME_DIR .. "/RHI/D3D11/**"
IGNORE_FILES[1] = RUNTIME_DIR .. "/RHI/Vulkan/**"
elseif API_GRAPHICS == "vulkan" then
API_GRAPHICS = "API_GRAPHICS_VULKAN"
TARGET_NAME = "Spartan_vk"
IGNORE_FILES[0] = RUNTIME_DIR .. "/RHI/D3D11/**"
IGNORE_FILES[1] = RUNTIME_DIR .. "/RHI/D3D12/**"
ADDITIONAL_INCLUDES[0] = "../ThirdParty/DirectXShaderCompiler";
ADDITIONAL_INCLUDES[1] = "../ThirdParty/SPIRV-Cross_2020-01-16";
ADDITIONAL_INCLUDES[2] = "../ThirdParty/Vulkan_1.2.148.1";
ADDITIONAL_LIBRARIES[0] = "dxcompiler";
ADDITIONAL_LIBRARIES[1] = "spirv-cross-core";
ADDITIONAL_LIBRARIES[2] = "spirv-cross-hlsl";
ADDITIONAL_LIBRARIES[3] = "spirv-cross-glsl";
ADDITIONAL_LIBRARIES_DBG[0] = "dxcompiler";
ADDITIONAL_LIBRARIES_DBG[1] = "spirv-cross-core_debug";
ADDITIONAL_LIBRARIES_DBG[2] = "spirv-cross-hlsl_debug";
ADDITIONAL_LIBRARIES_DBG[3] = "spirv-cross-glsl_debug";
end
-- Solution
solution (SOLUTION_NAME)
location ".."
systemversion "latest"
cppdialect "C++17"
language "C++"
platforms "x64"
configurations { "Release", "Debug" }
-- Defines
defines
{
"SPARTAN_RUNTIME_STATIC=1",
"SPARTAN_RUNTIME_SHARED=0"
}
filter { "platforms:x64" }
system "Windows"
architecture "x64"
-- "Debug"
filter "configurations:Debug"
defines { "DEBUG" }
flags { "MultiProcessorCompile", "LinkTimeOptimization" }
symbols "On"
-- "Release"
filter "configurations:Release"
defines { "NDEBUG" }
flags { "MultiProcessorCompile" }
symbols "Off"
optimize "Full"
-- Runtime -------------------------------------------------------------------------------------------------
project (RUNTIME_NAME)
location (RUNTIME_DIR)
objdir (INTERMEDIATE_DIR)
kind "StaticLib"
staticruntime "On"
defines{ "SPARTAN_RUNTIME", API_GRAPHICS }
-- Procompiled headers
pchheader "Spartan.h"
pchsource "../Runtime/Core/Spartan.cpp"
-- Source
files
{
RUNTIME_DIR .. "/**.h",
RUNTIME_DIR .. "/**.cpp",
RUNTIME_DIR .. "/**.hpp",
RUNTIME_DIR .. "/**.inl"
}
-- Source to ignore
removefiles { IGNORE_FILES[0], IGNORE_FILES[1] }
-- Includes
includedirs { "../ThirdParty/Assimp_5.0.0" }
includedirs { "../ThirdParty/Bullet_2.89" }
includedirs { "../ThirdParty/FMOD_1.10.10" }
includedirs { "../ThirdParty/FreeImage_3.18.0" }
includedirs { "../ThirdParty/FreeType_2.10.1" }
includedirs { "../ThirdParty/pugixml_1.10" }
includedirs { "../ThirdParty/Mono_6.12.0.86" }
includedirs { ADDITIONAL_INCLUDES[0], ADDITIONAL_INCLUDES[1], ADDITIONAL_INCLUDES[2] }
-- Libraries
libdirs (LIBRARY_DIR)
-- "Debug"
filter "configurations:Debug"
targetdir (TARGET_DIR_DEBUG)
debugdir (TARGET_DIR_DEBUG)
debugformat (DEBUG_FORMAT)
links { "assimp_debug" }
links { "fmodL64_vc" }
links { "FreeImageLib_debug" }
links { "freetype_debug" }
links { "BulletCollision_debug", "BulletDynamics_debug", "BulletSoftBody_debug", "LinearMath_debug" }
links { "pugixml_debug" }
links { "IrrXML_debug" }
links { "libmono-static-sgen_debug.lib" }
links { ADDITIONAL_LIBRARIES_DBG[0], ADDITIONAL_LIBRARIES_DBG[1], ADDITIONAL_LIBRARIES_DBG[2], ADDITIONAL_LIBRARIES_DBG[3] }
-- "Release"
filter "configurations:Release"
targetdir (TARGET_DIR_RELEASE)
debugdir (TARGET_DIR_RELEASE)
if API_GRAPHICS == "vulkan" then
links { "dxcompiler", "spirv-cross-core", "spirv-cross-hlsl", "spirv-cross-glsl" }
end
links { "assimp" }
links { "fmod64_vc" }
links { "FreeImageLib" }
links { "freetype" }
links { "BulletCollision", "BulletDynamics", "BulletSoftBody", "LinearMath" }
links { "pugixml" }
links { "IrrXML" }
links { "libmono-static-sgen.lib" }
links { ADDITIONAL_LIBRARIES[0], ADDITIONAL_LIBRARIES[1], ADDITIONAL_LIBRARIES[2], ADDITIONAL_LIBRARIES[3] }
-- Editor --------------------------------------------------------------------------------------------------
project (EDITOR_NAME)
location (EDITOR_DIR)
links { RUNTIME_NAME }
dependson { RUNTIME_NAME }
targetname ( TARGET_NAME )
objdir (INTERMEDIATE_DIR)
kind "WindowedApp"
staticruntime "On"
defines{ "SPARTAN_EDITOR", API_GRAPHICS }
-- Files
files
{
EDITOR_DIR .. "/**.rc",
EDITOR_DIR .. "/**.h",
EDITOR_DIR .. "/**.cpp",
EDITOR_DIR .. "/**.hpp",
EDITOR_DIR .. "/**.inl"
}
-- Includes
includedirs { "../" .. RUNTIME_NAME }
-- Libraries
libdirs (LIBRARY_DIR)
-- "Debug"
filter "configurations:Debug"
targetdir (TARGET_DIR_DEBUG)
debugdir (TARGET_DIR_DEBUG)
debugformat (DEBUG_FORMAT)
-- "Release"
filter "configurations:Release"
targetdir (TARGET_DIR_RELEASE)
debugdir (TARGET_DIR_RELEASE)
|
module 'mock'
CLASS: TBTextField ( TBWidget )
:MODEL{
Field 'text' :string() :getset( 'Text' );
}
function TBTextField:createInternalWidget()
local textField = MOAITBTextField.new()
textField:setSize( 50, 20 )
textField:setText( 'Submit' )
return textField
end
function TBTextField:getText()
return self:getInternalWidget():getText()
end
function TBTextField:setText( text )
return self:getInternalWidget():setText( text )
end
registerEntity( 'TBTextField', TBTextField )
|
-- _ _
-- _ __ ___ (_)_ __ | | __
-- | '_ ` _ \| | '_ \| |/ /
-- | | | | | | | | | | <
-- |_| |_| |_|_|_| |_|_|\_\
--
-- SPDX-License-Identifier: MIT
--
--
-- imports
local M = require("mink")(...)
local lunajson = require("lunajson")
-- get input args
local data = M.get_args()
-- process input
local t = lunajson.decode(data[1][1])
-- unknown command
local res = {
code = -1,
message = "Unknown command"
}
-- set result
M.set_result(lunajson.encode(res))
|
module("luci.controller.https_dns_proxy", package.seeall)
function index()
if not nixio.fs.access("/etc/config/https_dns_proxy") then
return
end
entry({"admin", "services", "https_dns_proxy"}, cbi("https_dns_proxy"), _("HTTPS DNS Proxy"))
end
|
object_draft_schematic_weapon_battleaxe_quest = object_draft_schematic_weapon_shared_battleaxe_quest:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_weapon_battleaxe_quest, "object/draft_schematic/weapon/battleaxe_quest.iff")
|
-- write data recover from latest snapshot
name = string.match(arg[0], "([^,]+)%.lua")
os.execute("rm -f " .. name .."/*.snap")
os.execute("rm -f " .. name .."/*.xlog")
env = require('test_run')
test_run = env.new()
test_run:cmd('restart server default')
engine = test_run:get_cfg('engine')
name = string.match(arg[0], "([^,]+)%.lua")
os.execute("touch " .. name .."/lock")
space = box.schema.space.create('test', { engine = engine })
index = space:create_index('primary')
for key = 1, 351 do space:insert({key}) end
box.snapshot()
test_run:cmd('restart server default')
name = string.match(arg[0], "([^,]+)%.lua")
os.execute("rm -f " .. name .."/lock")
space = box.space['test']
index = space.index['primary']
index:select({}, {iterator = box.index.ALL})
space:drop()
|
--[[
EXTRASUNNY
CLEAR
NEUTRAL
SMOG
FOGGY
OVERCAST
CLOUDS
CLEARING
RAIN
THUNDER
SNOW
BLIZZARD
SNOWLIGHT
XMAS
HALLOWEEN
--]]
Citizen.CreateThread(function()
while true do
permaWeather = "EXTRASUNNY"
SetWeatherTypePersist(permaWeather)
SetWeatherTypeNowPersist(permaWeather)
SetWeatherTypeNow(permaWeather)
SetOverrideWeather(permaWeather)
SetForcePedFootstepsTracks(true)
SetForceVehicleTrails(true)
Citizen.Wait(0)
end
end)
|
--- rFSM event memory extension.
--
-- (C) 2010-2013 Markus Klotzbuecher <markus.klotzbuecher@mech.kuleuven.be>
-- (C) 2014-2020 Markus Klotzbuecher <mk@mkio.de>
--
-- SPDX-License-Identifier: BSD-3-Clause
--
--
-- This extension adds "memory" of occured events to an rFSM
-- chart. This is done maintaining a table <code>emem</code> for every
-- state. The <code>emem</code> table is cleared when a state is
-- exited by setting all values to 0.
--
-- Implementationwise a pre_step handler is installed that runs
-- through the current active list and for each state sets
-- emem[event]+=1. Moreover, the exit function is extended to clear
-- the emem table of the state that is left. Event memory will
-- automatically be used when this module is loaded. The only public
-- function is <code>rfsm_emem.emem_reset>, which can be used to
-- manually reset the event counters of the given state.
--
local rfsm = require("rfsm")
local print, ipairs, pairs = print, ipairs, pairs
module 'rfsm_emem'
--- Reset the event memory of a state
-- @param state the state of which memory shall be cleared.
function emem_reset(s)
local et = s.emem
if et then
for e,x in pairs(et) do et[e] = 0 end
end
end
--- Update all emem tables with the current events.
-- This function expects to be called from pre_step_hook.
-- @param fsm initialized root fsm
-- @param events table of events
local function update_emem_tabs(fsm, events)
local function update_emem_tab(fsm, s)
local et = s.emem
for i,e in ipairs(events) do
if not et[e] then et[e] = 1
else et[e]=et[e] + 1 end
end
end
if fsm._act_leaf then
rfsm.map_from_to(fsm, update_emem_tab, fsm._act_leaf, fsm)
end
end
--- Setup event memory for the given fsm.
-- @param fsm initialized root fsm.
local function setup_emem(fsm)
fsm.info("rfsm_emem: event memory extension loaded")
-- create emem tables
rfsm.mapfsm(function (s, p)
s.emem={}
end, fsm, rfsm.is_state)
-- install pre_step_hook
rfsm.pre_step_hook_add(fsm, update_emem_tabs)
-- clear emem counters in exit hooks
-- todo: this should also happen for root!
rfsm.mapfsm(function (s, p)
if s.exit then
local oldexit = s.exit
s.exit = function (fsm, state, type)
oldexit(fsm, state, type)
emem_reset(state)
end
else
s.exit = function (fsm, state, type) emem_reset(state) end
end
end, fsm, rfsm.is_state)
end
-- install setup_emem as preproc hook
rfsm.preproc[#rfsm.preproc+1] = setup_emem
|
local M = {}
-- Beautiful default layout ofro telescope prompt
function M.layout_config()
return {
width = 0.90,
height = 0.85,
preview_cutoff = 120,
prompt_position = "bottom",
horizontal = {
preview_width = function(_, cols, _)
if cols > 200 then
return math.floor(cols * 0.5)
else
return math.floor(cols * 0.6)
end
end,
},
vertical = {
width = 0.9,
height = 0.95,
preview_height = 0.5,
},
flex = {
horizontal = {
preview_width = 0.9,
},
},
}
end
return M
|
-- rTooltip: config
-- zork, 2019
-----------------------------
-- Variables
-----------------------------
local A, L = ...
-----------------------------
-- Config
-----------------------------
L.C = {
textColor = {0.4,0.4,0.4},
bossColor = {1,0,0},
eliteColor = {1,0,0.5},
rareeliteColor = {1,0.5,0},
rareColor = {1,0.5,0},
levelColor = {0.8,0.8,0.5},
deadColor = {0.5,0.5,0.5},
targetColor = {1,0.5,0.5},
guildColor = {1,0,1},
afkColor = {0,1,1},
scale = 0.95,
fontFamily = STANDARD_TEXT_FONT,
backdrop = {
bgFile = "Interface\\Buttons\\WHITE8x8",
bgColor = {0.08,0.08,0.1,0.92},
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
borderColor = {0.1,0.1,0.1,0.6},
itemBorderColorAlpha = 0.9,
tile = false,
tileEdge = false,
tileSize = 16,
edgeSize = 16,
insets = {left=3, right=3, top=3, bottom=3}
},
--pos can be either a point table or a anchor string
pos = { "BOTTOMRIGHT", UIParent, "BOTTOMRIGHT", -86, 45 }
--pos = "ANCHOR_NONE" --"ANCHOR_CURSOR"
}
|
--region NotificationName
--Date 2019.02/27
--Author NormanYang
--广播通知消息
--endregion
--处理消息参数
local select = select
local insert = table.insert
function HandleNotifyParams(...)
local view, args = nil, {};
local count = select('#', ...);
for index = 1, count do
if index == 1 then view = select(1, ...);
else
local tempArg = select(index, ...);
insert(args, index - 1, tempArg);
end
end
return view, args;
end
--通知消息--
NotifyName =
{
------------------------命令式通知---------------------------------------
ShowUI = "ShowUI", --显示界面--
HideUI = "HideUI", --隐藏界面--
CloseUI = "CloseUI", --关闭界面(执行销毁)--
------------------------界面通知---------------------------------------
--摄像机相关
InitCameraHandler = 'InitCameraHandler', --初始化摄像机控制
SetSwitchType = 'SetSwitchType', --设置摄像机切换类型(内城、世界等)
SetPosition = 'SetPosition', --设置中心点坐标
SetCanMove = 'SetCanMove', --是否可移动
--角色相关
PlayerInfoUpdate = 'PlayerInfoUpdate', --玩家角色信息更新
OtherPlayerInfoUpdate = 'OtherPlayerInfoUpdate',--其他玩家角色信息
}
CmdList =
{
--基础命令--
CmdShowUI = require 'Controller/Command/CmdShowUI',
CmdHideUI = require 'Controller/Command/CmdHideUI',
CmdCloseUI = require 'Controller/Command/CmdCloseUI',
}
|
local create = require('rx.observable.create')
local of = require('rx.observable.of')
local from = require('rx.observable.from')
local timer = require('rx.observable.timer')
local range = require('rx.observable.range')
local merge = require('rx.observable.merge')
local between = require('rx.observable.between')
local EMPTY = require('rx.observable.empty')
return {
create = create,
of = of,
from = from,
timer = timer,
range = range,
between = between,
merge = merge,
EMPTY = EMPTY,
}
|
--tank battles (royale)-- mewmew made this --
local event = require 'utils.event'
local table_insert = table.insert
local math_random = math.random
local map_functions = require "maps.tools.map_functions"
local arena_size = 160
local function shuffle(tbl)
local size = #tbl
for i = size, 1, -1 do
local rand = math.random(size)
tbl[i], tbl[rand] = tbl[rand], tbl[i]
end
return tbl
end
local function create_tank_battle_score_gui()
for _, player in pairs (game.connected_players) do
if player.gui.left["tank_battle_score"] then player.gui.left["tank_battle_score"].destroy() end
local frame = player.gui.left.add({type = "frame", name = "tank_battle_score", direction = "vertical"})
local l = frame.add({type = "label", caption = "Won rounds"})
l.style.font_color = {r=0.98, g=0.66, b=0.22}
l.style.font = "default-listbox"
local t = frame.add({type = "table", column_count = 2})
local scores = {}
for _, player in pairs(game.connected_players) do
if global.tank_battles_score[player.index] then
table_insert(scores, {name = player.name, score = global.tank_battles_score[player.index]})
end
end
for x = 1, #scores, 1 do
for y = 1, #scores, 1 do
if not scores[y + 1] then break end
if scores[y]["score"] < scores[y + 1]["score"] then
local key = scores[y]
scores[y] = scores[y + 1]
scores[y + 1] = key
end
end
end
for i = 1, 8, 1 do
if scores[i] then
local l = t.add({type = "label", caption = scores[i].name})
local color = game.players[scores[i].name].color
color = {r = color.r * 0.6 + 0.4, g = color.g * 0.6 + 0.4, b = color.b * 0.6 + 0.4, a = 1}
l.style.font_color = color
l.style.font = "default-bold"
t.add({type = "label", caption = scores[i].score})
end
end
end
end
local loot = {
--{{name = "submachine-gun", count = 1}, weight = 2},
--{{name = "combat-shotgun", count = 1}, weight = 2},
--{{name = "flamethrower", count = 1}, weight = 1},
--{{name = "rocket-launcher", count = 1}, weight = 2},
{{name = "flamethrower-ammo", count = 16}, weight = 2},
{{name = "piercing-shotgun-shell", count = 16}, weight = 2},
--{{name = "piercing-rounds-magazine", count = 16}, weight = 2},
--{{name = "uranium-rounds-magazine", count = 8}, weight = 1},
{{name = "explosive-rocket", count = 8}, weight = 2},
{{name = "rocket", count = 8}, weight = 2},
{{name = "grenade", count = 16}, weight = 2},
{{name = "cluster-grenade", count = 8}, weight = 2},
--{{name = "poison-capsule", count = 4}, weight = 1},
{{name = "defender-capsule", count = 6}, weight = 1},
{{name = "distractor-capsule", count = 3}, weight = 1},
--{{name = "destroyer-capsule", count = 1}, weight = 1},
{{name = "cannon-shell", count = 8}, weight = 16},
{{name = "explosive-cannon-shell", count = 8}, weight = 16},
{{name = "uranium-cannon-shell", count = 8}, weight = 6},
{{name = "explosive-uranium-cannon-shell", count = 8}, weight = 6},
--{{name = "light-armor", count = 1}, weight = 5},
--{{name = "heavy-armor", count = 1}, weight = 2},
{{name = "modular-armor", count = 1}, weight = 3},
{{name = "power-armor", count = 1}, weight = 2},
{{name = "power-armor-mk2", count = 1}, weight = 1},
--{{name = "battery-mk2-equipment", count = 1}, weight = 2},
{{name = "energy-shield-equipment", count = 1}, weight = 2},
{{name = "exoskeleton-equipment", count = 1}, weight = 2},
{{name = "fusion-reactor-equipment", count = 1}, weight = 2},
{{name = "repair-pack", count = 1}, weight = 6},
{{name = "coal", count = 16}, weight = 3},
--{{name = "solid-fuel", count = 8}, weight = 2},
{{name = "nuclear-fuel", count = 1}, weight = 1},
{{name = "gate", count = 16}, weight = 2},
{{name = "stone-wall", count = 16}, weight = 2}
}
local loot_raffle = {}
for _, item in pairs(loot) do
for x = 1, item.weight, 1 do
table.insert(loot_raffle, item[1])
end
end
local function get_valid_random_spawn_position(surface)
local chunks = {}
for chunk in surface.get_chunks() do
table_insert(chunks, {x = chunk.x, y = chunk.y})
end
chunks = shuffle(chunks)
for _, chunk in pairs(chunks) do
if chunk.x * 32 < arena_size and chunk.y * 32 < arena_size and chunk.x * 32 >= arena_size * -1 and chunk.y * 32 >= arena_size * -1 then
local area = {{chunk.x * 32 - 64, chunk.y * 32 - 64}, {chunk.x * 32 + 64, chunk.y * 32 + 64}}
if surface.count_entities_filtered({name = "tank", area = area}) == 0 then
local pos = surface.find_non_colliding_position("tank", {chunk.x * 32 + 16, chunk.y * 32 + 16}, 16, 8)
return pos
end
end
end
local pos = surface.find_non_colliding_position("tank", {0, 0}, 32, 4)
if pos then return pos end
return {0, 0}
end
local function put_players_into_arena()
for _, player in pairs(game.connected_players) do
local permissions_group = game.permissions.get_group("Default")
permissions_group.add_player(player.name)
player.character.destroy()
player.character = nil
player.create_character()
player.insert({name = "combat-shotgun", count = 1})
player.insert({name = "rocket-launcher", count = 1})
player.insert({name = "flamethrower", count = 1})
--player.insert({name = "firearm-magazine", count = 512})
local surface = game.surfaces["tank_battles"]
local pos = get_valid_random_spawn_position(surface)
player.teleport(pos, surface)
local tank = surface.create_entity({name = "tank", force = game.forces[player.index], position = pos})
tank.insert({name = "coal", count = 24})
tank.insert({name = "cannon-shell", count = 16})
tank.set_driver(player)
end
end
function create_new_arena()
local map_gen_settings = {}
map_gen_settings.seed = math_random(1, 2097152)
map_gen_settings.water = "none"
map_gen_settings.cliff_settings = {cliff_elevation_interval = 4, cliff_elevation_0 = 0.1}
map_gen_settings.autoplace_controls = {
["coal"] = {frequency = "none", size = "none", richness = "none"},
["stone"] = {frequency = "none", size = "none", richness = "none"},
["copper-ore"] = {frequency = "none", size = "none", richness = "none"},
["iron-ore"] = {frequency = "none", size = "none", richness = "none"},
["crude-oil"] = {frequency = "none", size = "none", richness = "none"},
["trees"] = {frequency = "normal", size = "normal", richness = "normal"},
["enemy-base"] = {frequency = "none", size = "none", richness = "none"}
}
game.create_surface("tank_battles", map_gen_settings)
local surface = game.surfaces["tank_battles"]
surface.request_to_generate_chunks({0,0}, math.ceil(arena_size / 32) + 2)
surface.force_generate_chunk_requests()
surface.daytime = 1
surface.freeze_daytime = 1
global.current_arena_size = arena_size
put_players_into_arena()
global.game_stage = "ongoing_game"
end
local function set_unique_player_force(player)
if not game.forces[player.index] then
game.create_force(player.index)
game.forces[player.index].technologies["follower-robot-count-1"].researched = true
game.forces[player.index].technologies["follower-robot-count-2"].researched = true
game.forces[player.index].technologies["follower-robot-count-3"].researched = true
game.forces[player.index].technologies["follower-robot-count-4"].researched = true
game.forces[player.index].technologies["follower-robot-count-5"].researched = true
end
player.force = game.forces[player.index]
end
local function on_player_joined_game(event)
local player = game.players[event.player_index]
set_unique_player_force(player)
if not global.map_init_done then
local spectator_permission_group = game.permissions.create_group("Spectator")
for action_name, _ in pairs(defines.input_action) do
spectator_permission_group.set_allows_action(defines.input_action[action_name], false)
end
spectator_permission_group.set_allows_action(defines.input_action.write_to_console, true)
spectator_permission_group.set_allows_action(defines.input_action.gui_click, true)
spectator_permission_group.set_allows_action(defines.input_action.gui_selection_state_changed, true)
spectator_permission_group.set_allows_action(defines.input_action.start_walking, true)
spectator_permission_group.set_allows_action(defines.input_action.open_kills_gui, true)
spectator_permission_group.set_allows_action(defines.input_action.open_character_gui, true)
--spectator_permission_group.set_allows_action(defines.input_action.open_equipment_gui, true)
spectator_permission_group.set_allows_action(defines.input_action.edit_permission_group, true)
spectator_permission_group.set_allows_action(defines.input_action.toggle_show_entity_info, true)
global.tank_battles_score = {}
global.game_stage = "lobby"
global.map_init_done = true
end
if #global.tank_battles_score > 0 then
create_tank_battle_score_gui()
end
if game.surfaces["tank_battles"] then
player.character.destroy()
player.character = nil
local permissions_group = game.permissions.get_group("Spectator")
permissions_group.add_player(player.name)
player.teleport({0, 0}, game.surfaces["tank_battles"])
end
if not game.surfaces["tank_battles"] then
player.character.destroy()
player.character = nil
if global.lobby_timer then global.lobby_timer = 1800 end
if player.online_time < 1 then
player.insert({name = "concrete", count = 500})
player.insert({name = "hazard-concrete", count = 500})
player.insert({name = "stone-brick", count = 500})
player.insert({name = "refined-concrete", count = 500})
player.insert({name = "refined-hazard-concrete", count = 500})
end
return
end
end
local function on_marked_for_deconstruction(event)
event.entity.cancel_deconstruction(game.players[event.player_index].force.name)
end
function shrink_arena()
local surface = game.surfaces["tank_battles"]
if global.current_arena_size < 0 then return end
local shrink_width = 8
local current_arena_size = global.current_arena_size
local tiles = {}
for x = arena_size * -1, arena_size, 1 do
for y = current_arena_size * -1 - shrink_width, current_arena_size * -1, 1 do
local pos = {x = x, y = y}
if surface.get_tile(pos).name ~= "water" and surface.get_tile(pos).name ~= "deepwater" then
if x > current_arena_size or y > current_arena_size or x < current_arena_size * -1 or y < current_arena_size * -1 then
if math_random(1, 3) ~= 1 then
table_insert(tiles, {name = "water", position = pos})
end
end
end
end
end
for x = arena_size * -1, arena_size, 1 do
for y = current_arena_size, current_arena_size + shrink_width, 1 do
local pos = {x = x, y = y}
if surface.get_tile(pos).name ~= "water" and surface.get_tile(pos).name ~= "deepwater" then
if x > current_arena_size or y > current_arena_size or x < current_arena_size * -1 or y < current_arena_size * -1 then
if math_random(1, 3) ~= 1 then
table_insert(tiles, {name = "water", position = pos})
end
end
end
end
end
for x = current_arena_size * -1 - shrink_width, current_arena_size * -1, 1 do
for y = arena_size * -1, arena_size, 1 do
local pos = {x = x, y = y}
if surface.get_tile(pos).name ~= "water" and surface.get_tile(pos).name ~= "deepwater" then
if x > current_arena_size or y > current_arena_size or x < current_arena_size * -1 or y < current_arena_size * -1 then
if math_random(1, 3) ~= 1 then
table_insert(tiles, {name = "water", position = pos})
end
end
end
end
end
for x = current_arena_size, current_arena_size + shrink_width, 1 do
for y = arena_size * -1, arena_size, 1 do
local pos = {x = x, y = y}
if surface.get_tile(pos).name ~= "water" and surface.get_tile(pos).name ~= "deepwater" then
if x > current_arena_size or y > current_arena_size or x < current_arena_size * -1 or y < current_arena_size * -1 then
if math_random(1, 3) ~= 1 then
table_insert(tiles, {name = "water", position = pos})
end
end
end
end
end
global.current_arena_size = global.current_arena_size - 1
surface.set_tiles(tiles, true)
end
local function render_arena_chunk(event)
if event.surface.name ~= "tank_battles" then return end
local surface = event.surface
local left_top = event.area.left_top
local tiles = {}
for x = 0, 31, 1 do
for y = 0, 31, 1 do
local pos = {x = left_top.x + x, y = left_top.y + y}
if pos.x > arena_size or pos.y > arena_size or pos.x < arena_size * -1 or pos.y < arena_size * -1 then
table_insert(tiles, {name = "water", position = pos})
else
if math_random(1, 256) == 1 then
if surface.can_place_entity({name = "wooden-chest", position = pos, force = "enemy"}) then
surface.create_entity({name = "wooden-chest", position = pos, force = "enemy"})
end
end
if math_random(1, 1024) == 1 then
if math_random(1, 64) == 1 then
if surface.can_place_entity({name = "assembling-machine-1", position = pos, force = "enemy"}) then
surface.create_entity({name = "assembling-machine-1", position = pos, force = "enemy"})
end
end
if math_random(1, 64) == 1 then
if surface.can_place_entity({name = "big-worm-turret", position = pos, force = "enemy"}) then
surface.create_entity({name = "big-worm-turret", position = pos, force = "enemy"})
end
end
if math_random(1, 32) == 1 then
if surface.can_place_entity({name = "medium-worm-turret", position = pos, force = "enemy"}) then
surface.create_entity({name = "medium-worm-turret", position = pos, force = "enemy"})
end
end
if math_random(1, 512) == 1 then
if surface.can_place_entity({name = "behemoth-biter", position = pos, force = "enemy"}) then
surface.create_entity({name = "behemoth-biter", position = pos, force = "enemy"})
end
end
if math_random(1, 64) == 1 then
if surface.can_place_entity({name = "big-biter", position = pos, force = "enemy"}) then
surface.create_entity({name = "big-biter", position = pos, force = "enemy"})
end
end
end
end
end
end
surface.set_tiles(tiles, true)
end
local function render_spawn_chunk(event)
if event.surface.name ~= "nauvis" then return end
local surface = event.surface
local left_top = event.area.left_top
for _, entity in pairs(surface.find_entities_filtered({area = event.area})) do
if entity.name ~= "player" then
entity.destroy()
end
end
local tiles = {}
for x = 0, 31, 1 do
for y = 0, 31, 1 do
local pos = {x = left_top.x + x, y = left_top.y + y}
table_insert(tiles, {name = "grass-2", position = pos})
end
end
surface.set_tiles(tiles, true)
end
local function kill_idle_players()
for _, player in pairs(game.connected_players) do
if player.character then
if player.afk_time > 600 then
local area = {{player.position.x - 1, player.position.y - 1}, {player.position.x + 1, player.position.y + 1}}
local water_tile_count = player.surface.count_tiles_filtered({name = {"water", "deepwater"}, area = area})
if water_tile_count > 3 then
player.character.die()
game.print(player.name .. " drowned.", {r = 150, g = 150, b = 0})
else
if player.afk_time > 9000 then
player.character.die()
game.print(player.name .. " was idle for too long.", {r = 150, g = 150, b = 0})
end
end
end
end
end
end
local function check_for_game_over()
local surface = game.surfaces["tank_battles"]
kill_idle_players()
local alive_players = 0
for _, player in pairs(game.connected_players) do
if player.character and player.surface.name == "tank_battles" then
alive_players = alive_players + 1
end
end
if alive_players > 1 then return end -----------------
local player
for _, p in pairs(game.connected_players) do
if p.character and p.surface.name == "tank_battles" then
player = p
end
end
if alive_players == 1 then
if not global.tank_battles_score[player.index] then
global.tank_battles_score[player.index] = 1
else
global.tank_battles_score[player.index] = global.tank_battles_score[player.index] + 1
end
game.print(player.name .. " has won the battle!", {r = 150, g = 150, b = 0})
create_tank_battle_score_gui()
end
if alive_players == 0 then
game.print("No alive players! Round ends in a draw!", {r = 150, g = 150, b = 0})
end
global.game_stage = "lobby"
end
local function on_chunk_generated(event)
render_arena_chunk(event)
render_spawn_chunk(event)
end
local function on_player_respawned(event)
local player = game.players[event.player_index]
local permissions_group = game.permissions.get_group("Spectator")
permissions_group.add_player(player.name)
player.character.destroy()
player.character = nil
end
local function lobby()
if game.surfaces["tank_battles"] then
game.delete_surface(game.surfaces["tank_battles"])
for _, player in pairs(game.connected_players) do
if player.character then
player.character.destroy()
player.character = nil
end
end
end
local connected_players_count = 0
local permissions_group = game.permissions.get_group("Default")
for _, player in pairs(game.connected_players) do
permissions_group.add_player(player.name)
if not player.character and player.ticks_to_respawn == nil then
player.create_character()
local pos = player.surface.find_non_colliding_position("player", {0,0}, 16, 3)
player.insert({name = "concrete", count = 500})
player.insert({name = "hazard-concrete", count = 500})
player.insert({name = "stone-brick", count = 500})
player.insert({name = "refined-concrete", count = 500})
player.insert({name = "refined-hazard-concrete", count = 500})
player.teleport({math_random(1, 32), math_random(1, 32)}, game.surfaces[1])
end
connected_players_count = connected_players_count + 1
end
if connected_players_count < 2 then
--game.print("Waiting for players.", {r = 0, g = 150, b = 150})
return
end
if not global.lobby_timer then global.lobby_timer = 1800 end
if global.lobby_timer % 600 == 0 then
if global.lobby_timer <= 0 then
game.print("Round has started!", {r = 0, g = 150, b = 150})
else
game.print("Round will begin in " .. global.lobby_timer / 60 .. " seconds.", {r = 0, g = 150, b = 150})
end
end
global.lobby_timer = global.lobby_timer - 300
if global.lobby_timer >= 0 then return end
global.lobby_timer = nil
global.game_stage = "create_arena"
end
local function on_tick(event)
if game.tick % 300 == 0 then
if global.game_stage == "lobby" then
lobby()
end
if global.game_stage == "create_arena" then
create_new_arena()
end
if global.game_stage == "ongoing_game" then
shrink_arena()
check_for_game_over()
end
end
end
local function on_entity_died(event)
if event.entity.name == "wooden-chest" then
local loot = loot_raffle[math_random(1, #loot_raffle)]
event.entity.surface.spill_item_stack(event.entity.position, loot, true)
--event.entity.surface.create_entity({name = "flying-text", position = event.entity.position, text = loot.name, color = {r=0.98, g=0.66, b=0.22}})
end
end
local function on_player_died(event)
local player = game.players[event.player_index]
local str = " "
if event.cause then
if event.cause.name ~= nil then str = " by " .. event.cause.name end
if event.cause.name == "player" then str = " by " .. event.cause.player.name end
if event.cause.name == "tank" then
local driver = event.cause.get_driver()
if driver.player then
str = " by " .. driver.player.name
end
end
end
for _, target_player in pairs(game.connected_players) do
if target_player.name ~= player.name then
player.print(player.name .. " was killed" .. str, { r=0.99, g=0.0, b=0.0})
end
end
end
----------share chat with player and spectator force-------------------
local function on_console_chat(event)
if not event.message then return end
if not event.player_index then return end
local player = game.players[event.player_index]
local color = {}
color = player.color
color.r = color.r * 0.6 + 0.35
color.g = color.g * 0.6 + 0.35
color.b = color.b * 0.6 + 0.35
color.a = 1
for _, target_player in pairs(game.connected_players) do
if target_player.name ~= player.name then
target_player.print(player.name .. ": ".. event.message, color)
end
end
end
event.add(defines.events.on_tick, on_tick)
event.add(defines.events.on_console_chat, on_console_chat)
event.add(defines.events.on_entity_died, on_entity_died)
event.add(defines.events.on_entity_damaged, on_entity_damaged)
event.add(defines.events.on_player_died, on_player_died)
event.add(defines.events.on_marked_for_deconstruction, on_marked_for_deconstruction)
event.add(defines.events.on_player_joined_game, on_player_joined_game)
event.add(defines.events.on_player_respawned, on_player_respawned)
event.add(defines.events.on_chunk_generated, on_chunk_generated)
|
local function info()
print [[
lua-power-table [
version: 1.0.0,
author: Denys G. Santos <gsdenys@gmail.com>,
github: https://github.com/gsdenys/lua-power-table
]
]]
end
local function void() end
return {info = info, void = void}
|
local module = {}
module.name = 'WundPWS'
local moduleConfig = nil
local function echo (text)
print('['..module.name..'] '..text)
end
local function c2f(tc)
return tc * 1.8 + 32
end
function module.init(cnf)
moduleConfig = cnf
end
function module.send(data)
if(data == nil or data.T == nil) then
echo('Invalid data! Cannot send')
return
end
local url = moduleConfig.url .. '?action=updateraw'
.. '&ID='..moduleConfig.ID
.. '&PASSWORD='..moduleConfig.KEY
.. '&dateutc=now'
.. '&humidity=' .. data.H/1000
.. '&tempf='.. c2f(data.T/100)
.. '&dewptf='.. c2f(data.D/100)
.. '&baromin='..data.P/33863.886666667
http.get(url,nil,function(code, data)
if (code < 0) then
echo("HTTP request failed")
elseif (code == 200 and string.match(data, 'success')) then
echo("Data sent!")
else
echo("Error sending data: " .. code .. ': '..data)
end
end)
end
return module
|
require('./globals')
local util = require('./util')
-- How to quantize the images
-- 2 = binary images
local numQuantBins = 2
local model = torch.load(paths.concat(paths.cwd(), 'mnistPixelCNN.net'))
local gpu = true
local softmax = nn.SoftMax()
if gpu then
cudnn.convert(model, cudnn)
model = model:cuda()
cudnn.convert(softmax)
softmax = softmax:cuda()
print('')
end
local TensorType = gpu and torch.CudaTensor or torch.Tensor
local QuantTensorType = gpu and torch.CudaLongTensor or torch.LongTensor
-- Multinomial sampling for 3D tensors
-- result should be size (batchSize x height x width)
-- prob should be size (batchSize x numClasses x height x width)
local function multinomial(prob)
-- Re-order so actual probs are last, flatten into a flat list of probs
local flatProbs = prob:permute(1, 3, 4, 2):contiguous()
flatProbs = flatProbs:view(flatProbs:size(1)*flatProbs:size(2)*flatProbs:size(3), flatProbs:size(4))
-- Sample once from multinomial
local samp = torch.multinomial(flatProbs, 1, true)
-- Unflatten before returning
return samp:view(prob:size(1), prob:size(3), prob:size(4))
end
local function generate(n)
local x = TensorType(n, 1, 28, 28)
for i=1,28 do -- rows
for j=1,28 do -- cols
-- Get (batchSize x numClasses x height x width) network outputs
local out = model:forward(x)
-- Turn 'em into probabilities
out = softmax:forward(out)
-- Draw a multinomial sample per pixel
local samp = multinomial(out)
-- Convert quantized samples back to floating-point (-1 to deal with 1-based indexing)
local fpsamp = util.dequantize(samp, numQuantBins)
-- Write the current pixel from the dequantized sample back into x
x[{{}, 1, i, j}] = fpsamp[{{}, i, j}]
end
end
local outx = torch.Tensor(n, 1, 28, 28):copy(x)
return outx
end
local n = 10
local samps = generate(10)
for i=1,n do
local filename = paths.concat(paths.cwd(), string.format('sample_%03d.png', i))
image.save(filename, samps[i])
end
|
local is_farming_redo = minetest.get_modpath("farming") ~= nil
and farming ~= nil and farming.mod == "redo"
local S = sickles.i18n
minetest.register_tool("sickles:sickle_bronze", {
description = S("Bronze Sickle"),
inventory_image = "sickles_sickle_bronze.png",
tool_capabilities = {
full_punch_interval = 0.8,
max_drop_level = 1,
groupcaps = {
snappy = { times = { [1] = 2.75, [2] = 1.30, [3] = 0.375 }, uses = 60, maxlevel = 2 }
},
damage_groups = { fleshy = 3 },
punch_attack_uses = 110
},
range = 6,
groups = { sickle = 1, sickle_uses = 110 },
sound = { breaks = "default_tool_breaks" }
})
minetest.register_craft({
output = "sickles:sickle_bronze",
recipe = {
{ "default:bronze_ingot", "" },
{ "", "default:bronze_ingot" },
{ "group:stick", "" }
}
})
minetest.register_tool("sickles:sickle_steel", {
description = S("Steel Sickle"),
inventory_image = "sickles_sickle_steel.png",
tool_capabilities = {
full_punch_interval = 0.8,
max_drop_level = 1,
groupcaps = {
snappy = { times = { [1] = 2.5, [2] = 1.20, [3] = 0.35 }, uses = 60, maxlevel = 2 }
},
damage_groups = { fleshy = 3 },
punch_attack_uses = 120
},
range = 6,
groups = { sickle = 1, sickle_uses = 120 },
sound = { breaks = "default_tool_breaks" }
})
minetest.register_craft({
output = "sickles:sickle_steel",
recipe = {
{ "default:steel_ingot", "" },
{ "", "default:steel_ingot" },
{ "group:stick", "" }
}
})
minetest.register_tool("sickles:sickle_gold", {
description = S("Golden Sickle"),
inventory_image = "sickles_sickle_gold.png",
tool_capabilities = {
full_punch_interval = 0.8,
max_drop_level = 1,
groupcaps = {
snappy = { times = { [1] = 2.0, [2] = 1.00, [3] = 0.35 }, uses = 45, maxlevel = 3 }
},
damage_groups = { fleshy = 2 },
punch_attack_uses = 90
},
range = 6,
groups = { sickle = 1, sickle_uses = 90 },
sound = { breaks = "default_tool_breaks" }
})
minetest.register_craft({
output = "sickles:sickle_gold",
recipe = {
{ "default:gold_ingot", "" },
{ "", "default:gold_ingot" },
{ "group:stick", "" }
}
})
minetest.register_tool("sickles:scythe_bronze", {
description = S("Bronze Scythe"),
inventory_image = "sickles_scythe_bronze.png",
tool_capabilities = {
full_punch_interval = 1.2,
damage_groups = { fleshy = 5 },
punch_attack_uses = 160
},
range = 12,
on_use = sickles.use_scythe,
groups = { scythe = 2, scythe_uses = 25 },
sound = { breaks = "default_tool_breaks" }
})
minetest.register_craft({
output = "sickles:scythe_bronze",
recipe = {
{ "", "default:bronze_ingot", "default:bronze_ingot" },
{ "default:bronze_ingot", "", "group:stick" },
{ "", "", "group:stick" }
}
})
minetest.register_tool("sickles:scythe_steel", {
description = S("Steel Scythe"),
inventory_image = "sickles_scythe_steel.png",
tool_capabilities = {
full_punch_interval = 1.2,
damage_groups = { fleshy = 5 },
punch_attack_uses = 180
},
range = 12,
on_use = sickles.use_scythe,
groups = { scythe = 2, scythe_uses = 30 },
sound = { breaks = "default_tool_breaks" }
})
minetest.register_craft({
output = "sickles:scythe_steel",
recipe = {
{ "", "default:steel_ingot", "default:steel_ingot" },
{ "default:steel_ingot", "", "group:stick" },
{ "", "", "group:stick" }
}
})
if is_farming_redo then
-- softly disable mithril scythe to prevent confusion
minetest.override_item("farming:scythe_mithril", {
groups = { not_in_creative_inventory = 1 }
})
minetest.clear_craft({
output = "farming:scythe_mithril"
})
end
|
local ChatConst = {
-- ChatConst.Channel.Count
Channel = {
World = 1,--世界频道
Notify = 2,--系统通知
Private = 3,--私人
Team = 4,--队伍
CS = 5,--跨服
Count = 6
},
MaxHistoryNum = 50,
}
return ChatConst
|
local Position = require('__stdlib__/stdlib/area/position')
local GridEdit = require('includes/editgrid')
local Camera = {
x = 0,
y = 0,
zoom = 1,
angle = 0,
pos = Position(),
mouse = Position(),
origin = Position(),
cell = Position(),
}
local Visual = {
size = 32,
subdivisions = 32,
color = {0.85, 0.85, 0.85, 0.3},
drawScale = false,
xColor = {0, 1, 0, 0.8},
yColor = {0, 1, 0, 0.8},
fadeFactor = 0.5,
textFadeFactor = 1,
hideOrigin = false,
interval = 32
}
local Grid = GridEdit.grid(Camera, Visual)
--return Grid
return {Grid = Grid, Camera = Camera, Visual = Visual}
|
local string_hex_escape = assert(foundation.com.string_hex_escape)
local Luna = assert(foundation.com.Luna)
do
local m = yatm_oku.OKU.isa.MOS6502.Assembler
if not m then
yatm.warn("OKU.isa.MOS6502.Assembler not available for tests")
return
end
local case = Luna:new("yatm_oku.OKU.isa.MOS6502.Assembler")
case:describe(".parse/1", function (t2)
t2:test("test can parse an assembly program", function (t3)
local prog =
"main:\n" ..
" LDA #$00\n" ..
" ADC #20\n" ..
""
local tokens, rest = m.parse(prog)
t3:assert_eq("", rest)
t3:assert_deep_eq({
{"label", "main"},
{"ins", { name = "lda", args = { {"immediate", 0} } }},
{"ins", { name = "adc", args = { {"immediate", 20} } }},
}, tokens:to_list())
end)
end)
case:describe(".assemble_safe/1", function (t2)
t2:test("assembler can actually assemble a 6502 object binary (without crashing)", function (t3)
local prog =
"main:\n" ..
" LDA #$00\n" ..
" ADC #20\n" ..
""
local okay, object, context, rest = m.assemble_safe(prog)
t3:assert(okay)
t3:assert_eq("", rest)
local blob = string_hex_escape(object, "all")
print(dump(blob))
end)
end)
case:execute()
case:display_stats()
case:maybe_error()
end
do
local m = yatm_oku.OKU.isa.MOS6502.Assembler.Lexer
if not m then
yatm.warn("OKU.isa.MOS6502.Assembler.Lexer not available for tests")
return
end
local case = Luna:new("yatm_oku.OKU.isa.MOS6502.Assembler.Lexer")
case:describe("tokenize/1 (individual tokens)", function (t2)
t2:test("can tokenize a comment", function (t3)
local token_buf, rest = m.tokenize("; this is a comment")
t3:assert_eq("", rest)
token_buf:open('r')
t3:assert(token_buf:match_tokens("comment"))
end)
t2:test("can tokenize comma", function (t3)
local token_buf, rest = m.tokenize(",")
t3:assert_eq("", rest)
token_buf:open('r')
t3:assert(token_buf:match_tokens(","))
end)
t2:test("can tokenize hash", function (t3)
local token_buf, rest = m.tokenize("#")
t3:assert_eq("", rest)
token_buf:open('r')
t3:assert(token_buf:match_tokens("#"))
end)
t2:test("can tokenize colon", function (t3)
local token_buf, rest = m.tokenize(":")
t3:assert_eq("", rest)
token_buf:open('r')
t3:assert(token_buf:match_tokens(":"))
end)
t2:test("can tokenize open-round-bracket", function (t3)
local token_buf, rest = m.tokenize("(")
t3:assert_eq("", rest)
token_buf:open('r')
t3:assert(token_buf:match_tokens("("))
end)
t2:test("can tokenize closed-round-bracket", function (t3)
local token_buf, rest = m.tokenize(")")
t3:assert_eq("", rest)
token_buf:open('r')
t3:assert(token_buf:match_tokens(")"))
end)
t2:test("can tokenize newlines", function (t3)
local token_buf, rest = m.tokenize("\n")
t3:assert_eq("", rest)
token_buf:open('r')
t3:assert(token_buf:match_tokens("nl"))
end)
t2:test("can tokenize single space", function (t3)
local token_buf, rest = m.tokenize(" ")
t3:assert_eq("", rest)
token_buf:open('r')
t3:assert(token_buf:match_tokens("ws"))
end)
t2:test("can tokenize single space (as tab)", function (t3)
local token_buf, rest = m.tokenize("\t")
t3:assert_eq("", rest)
token_buf:open('r')
t3:assert(token_buf:match_tokens("ws"))
end)
t2:test("can tokenize multiple spaces", function (t3)
local token_buf, rest = m.tokenize(" ")
t3:assert_eq("", rest)
token_buf:open('r')
t3:assert(token_buf:match_tokens("ws"))
end)
t2:test("can tokenize multiple spaces (as tabs)", function (t3)
local token_buf, rest = m.tokenize("\t\t")
t3:assert_eq("", rest)
token_buf:open('r')
t3:assert(token_buf:match_tokens("ws"))
end)
t2:test("can tokenize single char atom", function (t3)
local token_buf, rest = m.tokenize("X")
t3:assert_eq("", rest)
token_buf:open('r')
t3:assert(token_buf:match_tokens("atom"))
local tokens = token_buf:scan("atom")
t3:assert_table_eq({"atom", "X"}, tokens[1])
end)
t2:test("can tokenize simple atom word", function (t3)
local token_buf, rest = m.tokenize("word")
t3:assert_eq("", rest)
token_buf:open('r')
t3:assert(token_buf:match_tokens("atom"))
local tokens = token_buf:scan("atom")
t3:assert_table_eq({"atom", "word"}, tokens[1])
end)
t2:test("can tokenize complex atoms", function (t3)
local token_buf, rest = m.tokenize("_marker_with_spaces_and_1234")
t3:assert_eq("", rest)
token_buf:open('r')
local tokens = token_buf:scan("atom")
t3:assert(tokens[1])
t3:assert_table_eq({"atom", "_marker_with_spaces_and_1234"}, tokens[1])
end)
t2:test("can tokenize all numbers as atoms (leading underscore)", function (t3)
local token_buf, rest = m.tokenize("_0123456789")
t3:assert_eq("", rest)
token_buf:open('r')
local tokens = token_buf:scan("atom")
t3:assert(tokens[1])
t3:assert_table_eq({"atom", "_0123456789"}, tokens[1])
end)
t2:test("can tokenize entire latin alphabet atoms", function (t3)
local token_buf, rest = m.tokenize("the_quick_brown_fox_jumps_over_the_lazy_dog")
t3:assert_eq("", rest)
token_buf:open('r')
local tokens = token_buf:scan("atom")
t3:assert(tokens[1])
t3:assert_table_eq({"atom", "the_quick_brown_fox_jumps_over_the_lazy_dog"}, tokens[1])
local token_buf, rest = m.tokenize("THE_QUICK_BROWN_FOX_JUMPS_OVER_THE_LAZY_DOG")
t3:assert_eq("", rest)
token_buf:open('r')
local tokens = token_buf:scan("atom")
t3:assert(tokens[1])
t3:assert_table_eq({"atom", "THE_QUICK_BROWN_FOX_JUMPS_OVER_THE_LAZY_DOG"}, tokens[1])
end)
t2:test("can tokenize a decimal integer", function (t3)
local token_buf, rest = m.tokenize("0")
t3:assert_eq("", rest)
token_buf:open('r')
local tokens = token_buf:scan("integer")
t3:assert(tokens[1])
t3:assert_table_eq({"integer", 0}, tokens[1])
local token_buf, rest = m.tokenize("1234567890")
t3:assert_eq("", rest)
token_buf:open('r')
local tokens = token_buf:scan("integer")
t3:assert(tokens[1])
t3:assert_table_eq({"integer", 1234567890}, tokens[1])
end)
t2:test("can tokenize $hex", function (t3)
local token_buf, rest = m.tokenize("$00FF")
t3:assert_eq("", rest)
token_buf:open('r')
local tokens = token_buf:scan("hex")
t3:assert(tokens[1])
t3:assert_table_eq({"hex", "00FF"}, tokens[1])
end)
t2:test("can tokenize entire hex alphabet", function (t3)
local token_buf, rest = m.tokenize("$0123456789ABCDEFabcdef")
t3:assert_eq("", rest)
token_buf:open('r')
local tokens = token_buf:scan("hex")
t3:assert(tokens[1])
t3:assert_table_eq({"hex", "0123456789ABCDEFabcdef"}, tokens[1])
end)
t2:test("can tokenize an empty double-quoted string", function (t3)
local token_buf, rest = m.tokenize("\"\"")
t3:assert_eq("", rest)
token_buf:open('r')
local tokens = token_buf:scan("dquote")
t3:assert(tokens[1])
t3:assert_table_eq({"dquote", ""}, tokens[1])
end)
t2:test("can tokenize a double-quoted string", function (t3)
local token_buf, rest = m.tokenize("\"Hello\"")
t3:assert_eq("", rest)
token_buf:open('r')
local tokens = token_buf:scan("dquote")
t3:assert(tokens[1])
t3:assert_table_eq({"dquote", "Hello"}, tokens[1])
end)
t2:test("can tokenize a complex double-quoted string", function (t3)
local token_buf, rest = m.tokenize("\"Hello World, how are you m8\"")
t3:assert_eq("", rest)
token_buf:open('r')
local tokens = token_buf:scan("dquote")
t3:assert(tokens[1])
t3:assert_table_eq({"dquote", "Hello World, how are you m8"}, tokens[1])
end)
t2:test("can tokenize a double-quoted string with escape codes", function (t3)
local token_buf, rest = m.tokenize("\"New\\nLine\\tTabs\\sSpaces\"")
t3:assert_eq("", rest)
token_buf:open('r')
local tokens = token_buf:scan("dquote")
t3:assert(tokens[1])
t3:assert_table_eq({"dquote", "New\nLine\tTabs Spaces"}, tokens[1])
end)
t2:test("can tokenize an empty single-quoted string", function (t3)
local token_buf, rest = m.tokenize("''")
t3:assert_eq("", rest)
token_buf:open('r')
local tokens = token_buf:scan("squote")
t3:assert(tokens[1])
t3:assert_table_eq({"squote", ""}, tokens[1])
end)
t2:test("can tokenize an a single-quoted string (ignoring escape codes)", function (t3)
local token_buf, rest = m.tokenize("'\\n\\tHello, World\\s'")
t3:assert_eq("", rest)
token_buf:open('r')
local tokens = token_buf:scan("squote")
t3:assert(tokens[1])
t3:assert_table_eq({"squote", "\\n\\tHello, World\\s"}, tokens[1])
end)
end)
case:describe("tokenize/1 (stream)", function (t2)
t2:test("can tokenize a simple program", function (t3)
local prog =
"main:\n" ..
" LDA #0 ; zero accumulator\n" ..
" ADC #$20 ; add 32 to the accumulator"
local token_buf, rest = m.tokenize(prog)
t3:assert_eq("", rest)
token_buf:open('r')
local tokens = token_buf:to_list()
local result = {
{"atom", "main"}, {":", true}, {"nl", true},
{"ws", true}, {"atom", "LDA"}, {"ws", true}, {"#", true}, {"integer", 0}, {"ws", true}, {"comment", " zero accumulator"}, {"nl", true},
{"ws", true}, {"atom", "ADC"}, {"ws", true}, {"#", true}, {"hex", "20"}, {"ws", true}, {"comment", " add 32 to the accumulator"}
}
t3:assert_deep_eq(result, tokens)
end)
end)
case:execute()
case:display_stats()
case:maybe_error()
end
|
function LoadUDM(property)
local udm = LoadModule("UdmLoader")
udm:Load(property.filepath)
local udminst = {
Tetra = function()
return udm:TetraData()
end,
Mesh = function ()
return udm:MeshData()
end,
ExtraP = function ()
return udm:ExtraData('P')
end,
ExtraT = function ()
return udm:ExtraData('TEMPARATURE')
end,
ExtraU = function ()
return udm:ExtraData('U')
end,
ExtraV = function ()
return udm:ExtraData('V')
end,
ExtraW = function ()
return udm:ExtraData('W')
end
}
return udminst
end
LoadUDM = {}
setmetatable(LoadUDM, {__index = HiveBaseModule})
LoadUDM.new = function (varname)
local this = HiveBaseModule.new(varname);
this.loader = LoadModule('UdmLoader')
setmetatable(this, {__index=LoadUDM})
return this
end
function LoadUDM:Do()
self:UpdateValue()
return self.loader:Load(self.value.filepath, self.value.step)
end
function LoadUDM:Tetra()
return self.loader:TetraData()
end
function LoadUDM:Mesh()
return self.loader:MeshData()
end
function LoadUDM:Solid()
return self.loader:SolidData(this.value.solidtype)
end
function LoadUDM:ExtraData(index)
local name = self.value.extraname[index + 1]
return self.loader:ExtraData(name)
end
|
--[[
ModuleName :
Path : service/scene.lua
Author : jinlei
CreateTime : 2020-10-11 17:04:25
Description :
--]]
skynet.start (function ()
skynet.dispatch ("lua", function (_, source, command, ...)
local function pret (ok, ...)
if not ok then
skynet.ret()
else
skynet.retpack(...)
end
end
local f = assert(CMD[command])
pret(xpcall(f, __G_TRACE_BACK__, ...))
end)
end)
|
--[[ Tester for Crepe
By Xiang Zhang @ New York University
--]]
require("sys")
local Test = torch.class("Test")
-- Initialization of the testing script
-- data: Testing dataset
-- model: Testing model
-- loss: Loss used for testing
-- config: (optional) the configuration table
-- .confusion: (optional) whether to use confusion matrix
function Test:__init(data,model,loss,config)
local config = config or {}
-- Store the objects
self.data = data
self.model = model
self.loss = loss
-- Move the type
self.loss:type(model:type())
-- Create time table
self.time = {}
-- Set the confusion
if config.confusion then
self.confusion = torch.zeros(data:nClasses(),data:nClasses())
end
-- Store configurations
self.normalize = config.normalize
end
-- Execute testing for a batch step
function Test:run(logfunc)
-- Initializing the errors and losses
self.e = 0
self.l = 0
self.n = 0
if self.confusion then self.confusion:zero() end
-- Start the loop
self.clock = sys.clock()
for batch,labels,n in self.data:iterator() do
self.batch = batch:transpose(2,3):contiguous():type(self.model:type())
self.labels = labels:type(self.model:type())
self.batch:copy(batch:transpose(2, 3):contiguous())
self.labels:copy(labels)
-- Record time
if self.model:type() == "torch.CudaTensor" then cutorch.synchronize() end
self.time.data = sys.clock() - self.clock
self.clock = sys.clock()
-- Forward propagation
self.output = self.model:forward(self.batch)
self.objective = self.loss:forward(self.output,self.labels)
if type(self.objective) ~= "number" then self.objective = self.objective[1] end
self.max, self.decision = self.output:double():max(2)
self.max = self.max:squeeze(2):double()
self.decision = self.decision:squeeze(2):double()
self.err = torch.ne(self.decision,self.labels:double()):sum()/self.labels:size(1)
-- Record time
if self.model:type() == "torch.CudaTensor" then cutorch.synchronize() end
self.time.forward = sys.clock() - self.clock
self.clock = sys.clock()
-- Accumulate the errors and losses
self.e = self.e*(self.n/(self.n+n)) + self.err*(n/(self.n+n))
self.l = self.l*(self.n/(self.n+n)) + self.objective*(n/(self.n+n))
if self.confusion then
for i = 1,n do
if self.n + i > self.data:nRow() then break end
self.confusion[labels[i]][self.decision[i]] = self.confusion[labels[i]][self.decision[i]]+1
end
end
self.n = self.n + n
-- Record time
if self.model:type() == "torch.CudaTensor" then cutorch.synchronize() end
self.time.accumulate = sys.clock() - self.clock
-- Call the log function
if logfunc then logfunc(self) end
self.clock = sys.clock()
end
end
|
function onCreate()
makeLuaSprite('Back', 'stages/bendy/BACKBACKgROUND', 0, 0);
makeLuaSprite('Background', 'stages/bendy/BackgroundwhereDEEZNUTSfitINYOmOUTH', 0, 0);
makeLuaSprite('MidGroun', 'stages/bendy/MidGrounUTS', 0, 0);
makeLuaSprite('MetalBar', 'stages/bendy/NUTS', 0, 0);
makeLuaSprite('Chain', 'stages/bendy/ChainUTS', 0, 0);
makeLuaSprite('Foreground', 'stages/bendy/ForegroundEEZNUTS', 0, 0);
addLuaSprite('Back', false);
addLuaSprite('Background', false);
addLuaSprite('MidGroun', false);
addLuaSprite('MetalBar', false);
addLuaSprite('Chain', false);
addLuaSprite('Foreground', false);
end
function onMoveCamera(focus)
if focus == 'dad' then
setProperty('camFollow.y', getProperty('camFollow.y') -100);
setProperty('camFollow.x', getProperty('camFollow.x'));
elseif focus == 'boyfriend' then
setProperty('camFollow.y', getProperty('camFollow.y') -200);
setProperty('camFollow.x', getProperty('camFollow.x') -300);
end
end
|
-- This code is licensed under the MIT Open Source License.
-- Copyright (c) 2015 Ruairidh Carmichael - ruairidhcarmichael@live.co.uk
-- 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 path = ...
local tween = require(path .. '/tween')
local splashy = {}
splashy.list = {}
splashy.inalpha = 0
splashy.outalpha = 255
splashy.count = 1
splashy.tweenlist = {}
splashy.fadestate = "in"
splashy.finished = false
splashy.onCompleteFunction = nil
function splashy.addSplash(image, duration, index)
duration = duration or 2
assert(type(duration) == 'number' and duration > 0, "duration must be a positive number.")
index = index or #splashy.list + 1
assert(type(index) == "number", "index must be a number")
splashy.list[index] = image
splashy.tweenlist[index] = tween.new(duration, splashy, {inalpha = 255, outalpha = 0})
end
function splashy.skipSplash()
splashy.fadestate = "in"
splashy.count = splashy.count + 1
end
function splashy.skipAll()
splashy.fadestate = "in"
splashy.count = #splashy.list + 1
end
function splashy.onComplete(func)
assert(type(func) == "function", "func must be a function")
splashy.onCompleteFunction = func
end
function splashy.draw()
if splashy.finished == false then
for i=1, #splashy.list do
if splashy.fadestate == "in" then
love.graphics.setColor(255, 255, 255, splashy.inalpha)
elseif splashy.fadestate == "out" then
love.graphics.setColor(255, 255, 255, splashy.outalpha)
end
-- If the current splash is the one in the list.
if splashy.count == i then
-- Then grab the splash from the list and draw it to the screen.
local splash = splashy.list[i]
local centerwidth = love.graphics.getWidth() / 2
local centerheight = love.graphics.getHeight() / 2
local centerimagewidth = splash:getWidth() / 2
local centerimageheight = splash:getHeight() / 2
love.graphics.draw(splash, centerwidth - centerimagewidth, centerheight - centerimageheight)
end
end
love.graphics.setColor(255, 255, 255, 255)
end
end
function splashy.update(dt)
if splashy.finished == false then
for i=1, #splashy.tweenlist do
if splashy.count == i then
local tweenComplete = splashy.tweenlist[i]:update(dt)
if tweenComplete then
if splashy.fadestate == "in" then
splashy.tweenlist[i]:reset()
splashy.fadestate = "out"
elseif splashy.fadestate == "out" then
splashy.tweenlist[i]:reset()
splashy.count = splashy.count + 1
splashy.fadestate = "in"
end
end
end
end
if splashy.count >= #splashy.list + 1 then
assert(type(splashy.onCompleteFunction) == "function", "onComplete needs a valid function.")
splashy.finished = true
splashy.onCompleteFunction()
end
end
end
return splashy
|
--次元均衡
function c90901251.initial_effect(c)
--fusion material
c:EnableReviveLimit()
--aux.AddFusionProcFun2(c,c90901251.ffilter,aux.FilterBoolFunction(Card.IsRace,RACE_SPELLCASTER),true)
--aux.AddFusionProcCodeFun(c,38033121,aux.FilterBoolFunction(Card.IsRace,RACE_SPELLCASTER),1,false,false)
--aux.AddFusionProcCodeFun(c,aux.FilterBoolFunction(Card.IsFusionSetCard,0x30a2),aux.FilterBoolFunction(Card.IsFusionSetCard,0x20a2),1,false,false)
--aux.AddFusionProcCodeFun(c,aux.FilterBoolFunction(Card.IsCode,38033121),aux.FilterBoolFunction(c90901251.ffffilter),1,false,false)
Fusion.AddProcMix(c,false,false,CARD_DARK_MAGICIAN_GIRL,aux.FilterBoolFunction(c90901251.ffffilter))
--spsummon condition
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
e1:SetValue(c90901251.splimit)
c:RegisterEffect(e1)
--special summon rule
--local e02=Effect.CreateEffect(c)
--e02:SetType(EFFECT_TYPE_FIELD)
--e02:SetCode(EFFECT_SPSUMMON_PROC)
--e02:SetProperty(EFFECT_FLAG_UNCOPYABLE)
--e02:SetRange(LOCATION_EXTRA)
--e02:SetCondition(c90901251.sprcon)
--e02:SetOperation(c90901251.sprop)
--c:RegisterEffect(e02)
--effect
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(90901251,0))
e2:SetCategory(CATEGORY_CONTROL)
e2:SetType(EFFECT_TYPE_IGNITION+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,90901251)
e2:SetCost(c90901251.costLP)
e2:SetTarget(c90901251.target1)
e2:SetOperation(c90901251.operation1)
c:RegisterEffect(e2)
--spsummon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(90901251,1))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_IGNITION+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetRange(LOCATION_MZONE)
e3:SetCountLimit(1,90901251)
--e3:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
--e3:SetCode(EVENT_PHASE+PHASE_STANDBY)
--e3:SetCondition(c90901251.con1)
e3:SetCost(c90901251.costBani)
e3:SetTarget(c90901251.target2)
e3:SetOperation(c90901251.operation2)
c:RegisterEffect(e3)
--change name
--local e4=Effect.CreateEffect(c)
--e4:SetType(EFFECT_TYPE_SINGLE)
--e4:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
--e4:SetCode(EFFECT_CHANGE_CODE)
--e4:SetRange(LOCATION_MZONE)
--e4:SetValue(38033121)
--c:RegisterEffect(e4)
end
c90901251.material_setcode={0x10a2,0x20a2}
function c90901251.ffffilter(c)
return c:IsSetCard(0x20a2) and c:IsType(TYPE_MONSTER)
end
function c90901251.splimit(e,se,sp,st)
return bit.band(st,SUMMON_TYPE_FUSION)==SUMMON_TYPE_FUSION
end
function c90901251.spfilter1(c,tp)
return c:IsFusionCode(38033121) and c:IsAbleToDeckOrExtraAsCost() and c:IsCanBeFusionMaterial(nil,true)
and Duel.IsExistingMatchingCard(c90901251.spfilter2,tp,LOCATION_MZONE,0,1,c)
end
function c90901251.spfilter2(c)
return c:IsRace(RACE_SPELLCASTER) and c:IsCanBeFusionMaterial() and c:IsAbleToDeckOrExtraAsCost()
end
function c90901251.sprcon(e,c)
if c==nil then return true end
local tp=c:GetControler()
return Duel.GetLocationCount(tp,LOCATION_MZONE)>-2
and Duel.IsExistingMatchingCard(c90901251.spfilter1,tp,LOCATION_ONFIELD,0,1,nil,tp)
end
function c90901251.sprop(e,tp,eg,ep,ev,re,r,rp,c)
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(90901251,2))
local g1=Duel.SelectMatchingCard(tp,c90901251.spfilter1,tp,LOCATION_ONFIELD,0,1,1,nil,tp)
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(90901251,3))
local g2=Duel.SelectMatchingCard(tp,c90901251.spfilter2,tp,LOCATION_MZONE,0,1,1,g1:GetFirst())
g1:Merge(g2)
local tc=g1:GetFirst()
while tc do
if not tc:IsFaceup() then Duel.ConfirmCards(1-tp,tc) end
tc=g1:GetNext()
end
Duel.PayLPCost(tp,1000)
Duel.SendtoGrave(g1,nil,2,REASON_COST)
end
--function c90901251.ffilter(c)
-- return c:IsCode(38033121) --or c:IsCode(80014003)--c:IsSetCard(0x9d) c:IsRace(RACE_DRAGON) and c:IsType(TYPE_SYNCHRO)
--end
function c90901251.con1(e,tp,eg,ep,ev,re,r,rp)
return tp==Duel.GetTurnPlayer() and e:GetHandler():GetFlagEffect(900901251)==0
end
function c90901251.costLP(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,500) end
Duel.PayLPCost(tp,500)
end
function c90901251.costBani(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToRemove,tp,LOCATION_HAND+LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local rg=Duel.SelectMatchingCard(tp,Card.IsAbleToRemove,tp,LOCATION_HAND+LOCATION_MZONE,0,1,1,nil)
Duel.Remove(rg,POS_FACEUP,REASON_COST)
end
function c90901251.costCombi(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,500)
and Duel.IsExistingMatchingCard(Card.IsAbleToRemove,tp,LOCATION_HAND+LOCATION_MZONE,0,1,nil) end
Duel.PayLPCost(tp,500)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local rg=Duel.SelectMatchingCard(tp,Card.IsAbleToRemove,tp,LOCATION_HAND+LOCATION_MZONE,0,1,1,nil)
Duel.Remove(rg,POS_FACEUP,REASON_COST)
end
function c90901251.filter1(c)
return c:IsControlerCanBeChanged()
end
function c90901251.filter2(c,e,tp)
return c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c90901251.target1(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and c90901251.filter1(chkc) end
if chk==0 then return Duel.IsExistingTarget(c90901251.filter1,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONTROL)
local g=Duel.SelectTarget(tp,c90901251.filter1,tp,0,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_CONTROL,g,1,0,0)
end
function c90901251.target2(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(1-tp) and c90901251.filter2(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c90901251.filter2,tp,0,LOCATION_GRAVE,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c90901251.filter2,tp,0,LOCATION_GRAVE,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c90901251.operation1(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and not Duel.GetControl(tc,tp,PHASE_END,1) then
if not tc:IsImmuneToEffect(e) and tc:IsAbleToChangeControler() then
Duel.Destroy(tc,REASON_EFFECT)
end
end
end
function c90901251.operation2(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
|
-- this puts everything into one table ready to use
local require, print, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string, math =
require, print, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string, math
local abi = require "syscall.abi"
if abi.rump and abi.types then abi.os = abi.types end -- pretend to be NetBSD for normal rump, Linux for rumplinux
require "syscall.ffitypes"
require("syscall." .. abi.os .. ".ffitypes")
if not abi.rump then
require "syscall.ffifunctions"
require("syscall." .. abi.os .. ".ffifunctions")
if abi.bsd then require "syscall.bsd.ffifunctions" end
end
local ostypes = require("syscall." .. abi.os .. ".types")
local c = require("syscall." .. abi.os .. ".constants")
local bsdtypes
if (abi.rump and abi.types == "netbsd") or (not abi.rump and abi.bsd) then
bsdtypes = require("syscall.bsd.types")
end
local types = require "syscall.types".init(c, ostypes, bsdtypes)
local C
if abi.rump then
C = require("syscall.rump.c")
else
C = require("syscall." .. abi.os .. ".c")
end
-- cannot put in S, needed for tests, cannot be put in c earlier due to deps TODO remove see #94
c.IOCTL = require("syscall." .. abi.os .. ".ioctl").init(types)
local S = require "syscall.syscalls".init(C, c, types)
S.abi, S.types, S.t, S.c = abi, types, types.t, c -- add to main table returned
-- add compatibility code
S = require "syscall.compat".init(S)
-- add functions from libc
S = require "syscall.libc".init(S)
-- add methods
S = require "syscall.methods".init(S)
-- add utils
S.util = require "syscall.util".init(S)
if abi.os == "linux" then
S.cgroup = require "syscall.linux.cgroup".init(S)
S.nl = require "syscall.linux.nl".init(S)
-- TODO add the other Linux specific modules here
end
return S
|
require("packages")
require("settings")
-- UI
require("ui.buffer_line")
require("ui.file_explorer")
require("ui.git")
require("ui.status_line")
require("ui.syntax")
require("ui.telescope")
require("ui.terminal")
require("ui.theme")
require("ui.title")
-- LSP
require("lsp.dap")
require("lsp.packages")
|
function onUpdate(elapsed)
setTextFont("scoreTxt", "VCR_OSD_MONO_1.001");
setTextFont("botplayTxt", "VCR_OSD_MONO_1.001");
setTextFont("timebarTxt", "VCR_OSD_MONO_1.001");
end
|
--
-- TORQUE OFF controller
--
-- Setup TorqueMainSwitch controller
--
-- Intended to be run via config script.
--
require "motion"
controller = controller or {}
-- load controller
ros:import("sweetie_bot_controller_joint_space")
depl:loadComponent("controller/torque_off", "sweetie_bot::motion::controller::TorqueMainSwitch")
controller.torque_off = depl:getPeer("controller/torque_off")
-- register controller
resource_control.register_controller(controller.torque_off)
-- timer
depl:connect(timer.controller.port, "controller/torque_off.sync", rtt.Variable("ConnPolicy"))
-- data flow: controller -> aggregator_ref
depl:connect("controller/torque_off.out_joints_ref", "aggregator_ref.in_joints", rtt.Variable("ConnPolicy"))
-- data flow: aggregator_real -> controller
depl:connect("aggregator_real.out_joints_sorted", "controller/torque_off.in_joints_actual", rtt.Variable("ConnPolicy"))
-- connect to RobotModel
depl:connectServices("controller/torque_off", "aggregator_ref")
-- present herkulex subsystem and set corresponding options
local herkulex_arrays = {}
local herkulex_scheds = {}
for name, group in pairs(herkulex) do
depl:addPeer("controller/torque_off", group.array:getName())
depl:addPeer("controller/torque_off", group.sched:getName())
-- form herkulex_arrays and herkulex_scheds lists
table.insert(herkulex_scheds, "herkulex/"..name.."/sched")
table.insert(herkulex_arrays, "herkulex/"..name.."/array")
end
-- set herkulex_arrays and herkulex_scheds properties
config.set_property(controller.torque_off, 'herkulex_arrays', herkulex_arrays )
config.set_property(controller.torque_off, 'herkulex_scheds', herkulex_scheds )
-- get ROS configuration
config.get_peer_rosparams(controller.torque_off)
-- advertise actionlib interface
controller.torque_off:loadService("actionlib")
controller.torque_off:provides("actionlib"):connect("~controller/torque_off")
-- advertise ROS operation
controller.torque_off:loadService("rosservice")
controller.torque_off:provides("rosservice"):connect("rosSetOperational", config.node_fullname .. "/controller/torque_off/set_torque_off", "std_srvs/SetBool")
-- prepare to start
assert(controller.torque_off:configure(), "ERROR: unable to configure controller/torque_off")
|
--[[
© 2013 GmodLive private project do not share
without permission of its author (Andrew Mensky vk.com/men232).
--]]
local greenCode = greenCode;
local gc = gc;
local math = math;
local table = table;
local CMENU_PLUGIN, TER_PLUGIN, TER_ONW;
local cMainTitle = Color(222,222,81);
local cTitleColor = Color(81,222,81);
local cTitleColor2 = Color(100,255,255);
local cTitleColor3 = Color(255,200,25);
local cTitleColor4 = Color(255,255,100);
local cTitleColor5 = Color(255,100,100);
local cTitleColor6 = Color(150,186,123);
local w;
local function AddTitle( title, color, desc, bCallback, bCallback2, bNoChangeFont )
local BLOCK = BlockMenu:AddItem{ color = Color(0,0,0), h = 25, w = w,
callback = bCallback and function( BLOCK ) BLOCK:TurnToogle(); end,
callback2 = bCallback2 and function( BLOCK )
local menu = DermaMenu();
menu:AddOption("Скопировать информацию", function()
SetClipboardText(BLOCK.Desc:GetText());
end);
menu:AddOption("Отмена", function() end);
menu:Open()
end,
};
CMENU_PLUGIN:ApplyTemplate( BLOCK, "simple", { color = color, title = title, desc = desc or "" });
if ( !bNoChangeFont ) then
BLOCK.Title:SetFont("ChatFont");
BLOCK.Title:SetExpensiveShadow(2, Color(0,0,0,100));
BLOCK.Title:SizeToContents();
end;
BLOCK.Title:Center();
if ( !bCallback and !bCallback2 ) then
BLOCK:SetDisabled(true);
end;
return BLOCK;
end;
CMENU_TERRITORY_CATEGORY = CM_CAT_CLASS:New{
title = "Территории",
priority = 5,
callback = function()
CMENU_PLUGIN = CMENU_PLUGIN or greenCode.plugin:Get("rp_custommenu");
TER_PLUGIN = TER_PLUGIN or greenCode.plugin:Get("territory");
TER_ONW = TER_ONW or greenCode.plugin:Get("ter_owning");
local bTextMenu, bBlockMenu = CMENU_PLUGIN:IsOpen();
local args = CMENU_PLUGIN.args;
BlockMenu = CMENU_PLUGIN.BlockMenu;
w = BlockMenu:GetWide() - (BlockMenu.Padding*2);
if ( bBlockMenu ) then
BlockMenu:Clear( 0.4 );
local BLOCK = BlockMenu:AddItem{ color = Color(0,0,0), h = 35, w = w, callback = function( BLOCK ) BLOCK:TurnToogle(); end };
CMENU_PLUGIN:ApplyTemplate( BLOCK, "simple", {
color = cMainTitle,
title = "Территории",
desc = [[Здесь вы можете покупать, продавать и настраивать права
для своих территорий. Покупая целую территорию, вы становитесь
владельцем всех дверей. ]]
});
BLOCK:TurnToogle();
BLOCK.Title:Center();
//BLOCK:SetTall( BLOCK.turnOnH );
local TERRITORY = TER_PLUGIN:GetLocation(gc.Client:GetShootPos());
if ( TERRITORY and TERRITORY:IsValid() ) then
local tOwnerNames = {};
local tCoOwnerNames = {};
local space = "\n"/*..string.rep(" ",)*/;
for uid, v in pairs( TERRITORY:GetOwners() ) do table.insert( tOwnerNames, v.name.." ("..string.Replace(v.sid, "STEAM_", "")..")" ) end;
for uid, v in pairs( TERRITORY:GetCoOwners() ) do table.insert( tCoOwnerNames, v.name.." ("..string.Replace(v.sid, "STEAM_", "")..")" ) end;
local sOwners, sCoOwners = "", "";
local bCanOwning, bOwned = TERRITORY("forsale", false), TERRITORY:IsOwned();
local nOwnerLevel = TERRITORY:GetOwnerLevel(gc.Client);
if (bOwned) then
sOwners = table.concat( tOwnerNames, space );
sCoOwners = table.concat( tCoOwnerNames, space );
//sOwners = (sOwners == "" and "пусто..." or sOwners);
//sCoOwners = (sCoOwners == "" and "пусто..." or sCoOwners);
bCanOwning = false;
end;
local BLOCK = AddTitle( "Информация о текущем расположении", cTitleColor, "");
local BLOCK = AddTitle( TERRITORY:Name().." ("..TERRITORY:UniqueID()..")", Color(255,255,255), TERRITORY("desc", "Без описания."), true, nil, true);
BLOCK:TurnToogle();
if (bOwned) then
w = (w/2) - BlockMenu.Padding/2;
local BLOCK = AddTitle( "Владельцы:", Color(255,255,255), sOwners, false, false, true);
BLOCK.Title:Center();
BLOCK.turnOffW, BLOCK.turnOnW = w, w;
BLOCK:TurnToogle();
local BLOCK = AddTitle( "Совладельцы:", Color(255,255,255), sCoOwners, false, false, true);
BLOCK.Title:Center();
BLOCK.turnOffW, BLOCK.turnOnW = w, w;
BLOCK:TurnToogle();
w = BlockMenu:GetWide() - (BlockMenu.Padding*2);
end;
if ( !bCanOwning and TERRITORY("lastBuyType") == "rent" ) then
local BLOCK = AddTitle( "#Rent", cTitleColor6);
function BLOCK.Title:Think()
local text = (nOwnerLevel > 1 and "До продления аренды: " or "Срок аренды: ")..greenCode.kernel:ConvertTime( math.ceil(TERRITORY("_rent", 0) - CurTime() - 1) );
if ( nOwnerLevel > 1 ) then
text = text .. " | " .. " Цена: "..greenCode.kernel:FormatNumber(TERRITORY:GetPrice("rent")).."$";
end;
self:SetText(text);
self:SizeToContents();
self:Center();
end;
end;
if ( nOwnerLevel > 0 or bCanOwning ) then
AddTitle( "Действия", cTitleColor2 );
-- Buy
if ( bCanOwning ) then
for k, v in SortedPairs(TER_ONW.class, true) do
local BLOCK = BlockMenu:AddItem{ color = Color(0,0,0), h = 28, w = w,
callback = function( BLOCK )
Derma_Query("Вы уверены, что хотите "..v.desc.."?", "Внимание",
"Да", function() RunConsoleCommand("gc_ter_buy", TERRITORY:UniqueID(), k ) end,
"Нет", function() end)
end,
};
CMENU_PLUGIN:ApplyTemplate( BLOCK, "simple", { color = cTitleColor3, title = "", desc = "" });
BLOCK.Title:SetFont("ChatFont");
BLOCK.Title:SetExpensiveShadow(2, Color(0,0,0,100));
function BLOCK.Title:Think()
self:SetText(v.desc..": "..greenCode.kernel:FormatNumber(TERRITORY:GetPrice(k))..v.cur);
self:SizeToContents();
end;
end;
end;
if ( nOwnerLevel > 0 ) then
-- Allow to spawn.
local BLOCK = BlockMenu:AddItem{ color = Color(0,0,0), h = 30, w = w, callback = function( BLOCK )
local menu = DermaMenu();
for k, v in pairs(_player.GetAll()) do
local uid = tonumber(v:UniqueID());
if ( TERRITORY:GetOwnerLevel(v) > 0 or TERRITORY("propSpawn", {})[uid] ) then
continue;
end;
menu:AddOption(v:Name(), function() RunConsoleCommand("gc_ter_allowspawn", tostring(TERRITORY:UniqueID()), uid, 1) end)
end;
menu:AddOption("Отмена");
menu:Open();
end};
CMENU_PLUGIN:ApplyTemplate( BLOCK, "simple", { color = cTitleColor4, title = "Разрешить спавн объектов", desc = "" });
BLOCK.Title:Center();
-- Denny to spawn.
local BLOCK = BlockMenu:AddItem{ color = Color(0,0,0), h = 30, w = w, callback = function( BLOCK )
local menu = DermaMenu();
for k, v in pairs(TERRITORY("propSpawn", {})) do
menu:AddOption(v, function() RunConsoleCommand("gc_ter_allowspawn", tostring(TERRITORY:UniqueID()), k, "0") end)
end;
menu:AddOption("Отмена");
menu:Open();
end};
CMENU_PLUGIN:ApplyTemplate(BLOCK, "simple", { color = cTitleColor5, title = "Запретить спавн объектов", desc = "" });
BLOCK.Title:Center();
end;
if ( nOwnerLevel > 1 ) then
-- Add Co Own
local BLOCK = BlockMenu:AddItem{ color = Color(0,0,0), h = 30, w = w, callback = function( BLOCK )
local menu = DermaMenu();
for k, v in pairs(_player.GetAll()) do
if ( TERRITORY:GetOwnerLevel(v) > 0 ) then
continue;
end;
local uid = tonumber(v:UniqueID());
menu:AddOption(v:Name(), function() RunConsoleCommand("gc_ter_allowcoown", tostring(TERRITORY:UniqueID()), uid, 1) end)
end;
menu:AddOption("Отмена");
menu:Open();
end};
CMENU_PLUGIN:ApplyTemplate( BLOCK, "simple", { color = cTitleColor4, title = "Добавить в совладельцы", desc = "" });
BLOCK.Title:Center();
-- Remove Co Own
local BLOCK = BlockMenu:AddItem{ color = Color(0,0,0), h = 30, w = w, callback = function( BLOCK )
local menu = DermaMenu();
for k, v in pairs(TERRITORY("coowner", {})) do
menu:AddOption(v.name, function() RunConsoleCommand("gc_ter_allowcoown", tostring(TERRITORY:UniqueID()), k, "0") end)
end;
menu:AddOption("Отмена");
menu:Open();
end};
CMENU_PLUGIN:ApplyTemplate(BLOCK, "simple", { color = cTitleColor5, title = "Убрать из совладельцев", desc = "" });
BLOCK.Title:Center();
-- Sell
local BLOCK = BlockMenu:AddItem{ color = Color(0,0,0), h = 35, w = w, callback = function( BLOCK )
local nPriceType = TERRITORY("lastBuyType", "session");
local nAmount = math.ceil(TERRITORY:GetPrice(nPriceType)/2);
local cur = TER_ONW.class[nPriceType].cur;
local sWarning = TER_ONW:HoldingCount( gc.Client ) < 2 and "Внимание! После продажи у вас не будет дома, а значит вы потеряете профессию.\n\n" or "";
Derma_Query(sWarning.."При продаже, вы получите: "..greenCode.kernel:FormatNumber(nAmount)..cur.."\nВы согласны?", "Внимание",
"Да", function() RunConsoleCommand("gc_ter_sell", TERRITORY:UniqueID() ) end,
"Нет", function() end)
end };
CMENU_PLUGIN:ApplyTemplate( BLOCK, "simple", { color = cTitleColor3, title = "Продать", desc = [[При продаже территории, вы получите 50% от её стоимости и
типа покупки.]] });
BLOCK:TurnToogle();
end;
end;
end;
end;
end;
}:Register();
|
local Skada = Skada
Skada:AddLoadableModule("Interrupts", function(L)
if Skada:IsDisabled("Interrupts") then return end
local mod = Skada:NewModule(L["Interrupts"])
local spellmod = mod:NewModule(L["Interrupted spells"])
local targetmod = mod:NewModule(L["Interrupted targets"])
local playermod = mod:NewModule(L["Interrupt spells"])
local _
-- cache frequently used globals
local pairs, ipairs, select, max = pairs, ipairs, select, math.max
local tostring, format, tContains = tostring, string.format, tContains
local UnitGUID, IsInInstance = UnitGUID, IsInInstance
local GetSpellInfo, GetSpellLink = Skada.GetSpellInfo or GetSpellInfo, Skada.GetSpellLink or GetSpellLink
local IsInGroup, IsInRaid = Skada.IsInGroup, Skada.IsInRaid
-- spells in the following table will be ignored.
local ignoredSpells = {}
local function log_interrupt(set, data)
-- ignored spells
if data.spellid and tContains(ignoredSpells, data.spellid) then return end
-- other ignored spells
if (data.extraspellid and tContains(ignoredSpells, data.extraspellid)) then return end
local player = Skada:GetPlayer(set, data.playerid, data.playername, data.playerflags)
if player then
-- increment player's and set's interrupts count
player.interrupt = (player.interrupt or 0) + 1
set.interrupt = (set.interrupt or 0) + 1
-- to save up memory, we only record the rest to the current set.
if set == Skada.current and data.spellid then
local spell = player.interruptspells and player.interruptspells[data.spellid]
if not spell then
player.interruptspells = player.interruptspells or {}
player.interruptspells[data.spellid] = {count = 0}
spell = player.interruptspells[data.spellid]
end
spell.count = spell.count + 1
-- record interrupted spell
if data.extraspellid then
spell.spells = spell.spells or {}
spell.spells[data.extraspellid] = (spell.spells[data.extraspellid] or 0) + 1
end
-- record the target
if data.dstName then
local actor = Skada:GetActor(set, data.dstGUID, data.dstName, data.dstFlags)
if actor then
spell.targets = spell.targets or {}
spell.targets[data.dstName] = (spell.targets[data.dstName] or 0) + 1
end
end
end
end
end
local data = {}
local function SpellInterrupt(timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, ...)
local spellid, spellname, _, extraspellid, extraspellname, _ = ...
data.playerid = srcGUID
data.playername = srcName
data.playerflags = srcFlags
data.dstGUID = dstGUID
data.dstName = dstName
data.dstFlags = dstFlags
data.spellid = spellid or 6603
data.extraspellid = extraspellid
Skada:FixPets(data)
log_interrupt(Skada.current, data)
log_interrupt(Skada.total, data)
if Skada.db.profile.modules.interruptannounce and IsInGroup() and srcGUID == Skada.userGUID then
local spelllink = GetSpellLink(extraspellid or extraspellname) or extraspellname
local channel = Skada.db.profile.modules.interruptchannel or "SAY"
if channel == "SELF" then
Skada:Print(format(L["%s interrupted!"], spelllink or dstName))
return
end
if channel == "AUTO" then
local zoneType = select(2, IsInInstance())
if zoneType == "pvp" or zoneType == "arena" then
channel = "BATTLEGROUND"
elseif zoneType == "party" or zoneType == "raid" then
channel = zoneType:upper()
else
channel = IsInRaid() and "RAID" or "PARTY"
end
end
Skada:SendChat(format(L["%s interrupted!"], spelllink or dstName), channel, "preset", true)
end
end
function spellmod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's interrupted spells"], label)
end
function spellmod:Update(win, set)
win.title = format(L["%s's interrupted spells"], win.playername or L.Unknown)
local player = set and set:GetPlayer(win.playerid, win.playername)
local total = player and player.interrupt or 0
local spells = (total > 0) and player:GetInterruptedSpells()
if spells and total > 0 then
if win.metadata then
win.metadata.maxvalue = 0
end
local nr = 0
for spellid, count in pairs(spells) do
nr = nr + 1
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.spellid = spellid
d.label, _, d.icon = GetSpellInfo(spellid)
d.value = count
d.valuetext = Skada:FormatValueText(
d.value,
mod.metadata.columns.Total,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if win.metadata and d.value > win.metadata.maxvalue then
win.metadata.maxvalue = d.value
end
end
end
end
function targetmod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's interrupted targets"], label)
end
function targetmod:Update(win, set)
win.title = format(L["%s's interrupted targets"], win.playername or L.Unknown)
local player = set and set:GetPlayer(win.playerid, win.playername)
local total = player and player.interrupt or 0
local targets = (total > 0) and player:GetInterruptTargets()
if targets then
if win.metadata then
win.metadata.maxvalue = 0
end
local nr = 0
for targetname, target in pairs(targets) do
nr = nr + 1
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = target.id or targetname
d.label = targetname
d.class = target.class
d.role = target.role
d.spec = target.spec
d.value = target.count
d.valuetext = Skada:FormatValueText(
d.value,
mod.metadata.columns.Total,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if win.metadata and d.value > win.metadata.maxvalue then
win.metadata.maxvalue = d.value
end
end
end
end
function playermod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's interrupt spells"], label)
end
function playermod:Update(win, set)
win.title = format(L["%s's interrupt spells"], win.playername or L.Unknown)
local player = set and set:GetPlayer(win.playerid, win.playername)
local total = player and player.interrupt or 0
if total > 0 and player.interruptspells then
if win.metadata then
win.metadata.maxvalue = 0
end
local nr = 0
for spellid, spell in pairs(player.interruptspells) do
nr = nr + 1
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.spellid = spellid
d.label, _, d.icon = GetSpellInfo(spellid)
d.value = spell.count
d.valuetext = Skada:FormatValueText(
d.value,
mod.metadata.columns.Total,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if win.metadata and d.value > win.metadata.maxvalue then
win.metadata.maxvalue = d.value
end
end
end
end
function mod:Update(win, set)
win.title = L["Interrupts"]
local total = set.interrupt or 0
if total > 0 then
if win.metadata then
win.metadata.maxvalue = 0
end
local nr = 0
for _, player in ipairs(set.players) do
if (player.interrupt or 0) > 0 then
nr = nr + 1
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = player.id or player.name
d.label = player.name
d.text = player.id and Skada:FormatName(player.name, player.id)
d.class = player.class
d.role = player.role
d.spec = player.spec
d.value = player.interrupt
d.valuetext = Skada:FormatValueText(
d.value,
self.metadata.columns.Total,
Skada:FormatPercent(d.value, total),
self.metadata.columns.Percent
)
if win.metadata and d.value > win.metadata.maxvalue then
win.metadata.maxvalue = d.value
end
end
end
end
end
function mod:OnEnable()
self.metadata = {
showspots = true,
ordersort = true,
click1 = spellmod,
click2 = targetmod,
click3 = playermod,
nototalclick = {spellmod, targetmod, playermod},
columns = {Total = true, Percent = true},
icon = [[Interface\Icons\ability_kick]]
}
Skada:RegisterForCL(SpellInterrupt, "SPELL_INTERRUPT", {src_is_interesting = true})
Skada:AddMode(self)
end
function mod:OnDisable()
Skada:RemoveMode(self)
end
function mod:AddToTooltip(set, tooltip)
if set and (set.interrupt or 0) > 0 then
tooltip:AddDoubleLine(L["Interrupts"], set.interrupt, 1, 1, 1)
end
end
function mod:GetSetSummary(set)
return tostring(set.interrupt or 0), set.interrupt or 0
end
function mod:OnInitialize()
if not Skada.db.profile.modules.interruptchannel then
Skada.db.profile.modules.interruptchannel = "SAY"
end
Skada.options.args.modules.args.interrupts = {
type = "group",
name = self.moduleName,
desc = format(L["Options for %s."], self.moduleName),
args = {
header = {
type = "description",
name = self.moduleName,
fontSize = "large",
image = [[Interface\Icons\ability_kick]],
imageWidth = 18,
imageHeight = 18,
imageCoords = {0.05, 0.95, 0.05, 0.95},
width = "full",
order = 0
},
sep = {
type = "description",
name = " ",
width = "full",
order = 1
},
interruptannounce = {
type = "toggle",
name = format(L["Announce %s"], self.moduleName),
order = 10,
width = "double"
},
interruptchannel = {
type = "select",
name = L["Channel"],
values = {AUTO = INSTANCE, SAY = CHAT_MSG_SAY, YELL = CHAT_MSG_YELL, SELF = L["Self"]},
order = 20,
width = "double"
}
}
}
end
do
local playerPrototype = Skada.playerPrototype
local cacheTable = Skada.cacheTable
local wipe = wipe
function playerPrototype:GetInterruptedSpells()
if self.interruptspells then
wipe(cacheTable)
for _, spell in pairs(self.interruptspells) do
if spell.spells then
for spellid, count in pairs(spell.spells) do
cacheTable[spellid] = (cacheTable[spellid] or 0) + count
end
end
end
return cacheTable
end
end
function playerPrototype:GetInterruptTargets()
if self.interruptspells then
wipe(cacheTable)
for _, spell in pairs(self.interruptspells) do
if spell.targets then
for name, count in pairs(spell.targets) do
if not cacheTable[name] then
cacheTable[name] = {count = count}
else
cacheTable[name].count = cacheTable[name].count + count
end
if not cacheTable[name].class then
local actor = self.super:GetActor(name)
if actor then
cacheTable[name].id = actor.id
cacheTable[name].class = actor.class
cacheTable[name].role = actor.role
cacheTable[name].spec = actor.spec
else
cacheTable[name].class = "UNKNOWN"
end
end
end
end
end
return cacheTable
end
end
end
end)
|
Locales['en'] = {
['welcome'] = '~g~Welcome to LR-AC Menu Tool',
['opadmin'] = '> Administrator option',
['onplayers'] = '> Online Players',
['srvertool'] = '> Server tools',
}
|
--重定义常用的Unity类
Canvas = CS.UnityEngine.Canvas
Button = CS.UnityEngine.UI.Button
Image = CS.UnityEngine.UI.Image
Text = CS.UnityEngine.UI.Text
InputField = CS.UnityEngine.UI.InputField
InputType = CS.UnityEngine.UI.InputField.InputType
Toggle = CS.UnityEngine.UI.Toggle
Slider = CS.UnityEngine.UI.Slider
ScrollRect = CS.UnityEngine.UI.ScrollRect
HorizontalLayoutGroup = CS.UnityEngine.UI.HorizontalLayoutGroup
VerticalLayoutGroup = CS.UnityEngine.UI.VerticalLayoutGroup
Application = CS.UnityEngine.Application
GameObject = CS.UnityEngine.GameObject
Transform = CS.UnityEngine.Transform
RectTransform = CS.UnityEngine.RectTransform
PlayerPrefs = CS.UnityEngine.PlayerPrefs
Screen = CS.UnityEngine.Screen
Color = CS.UnityEngine.Color
Vector2 = CS.UnityEngine.Vector2
Vector3 = CS.UnityEngine.Vector3
Quaternion = CS.UnityEngine.Quaternion
DOTween = CS.DG.Tweening.DOTween
Ease = CS.DG.Tweening.Ease
RotateMode = CS.DG.Tweening.RotateMode
LoopType = CS.DG.Tweening.LoopType
--常用自定义类
LuaTimer = CS.XLua.LuaTimer
Tool = CS.GameUtils.Tool
FileUtils = CS.GameUtils.FileUtils
ResourceMgr = CS.ResourceMgr.GetInstance
SDKManager = CS.SdkMgr.Instance
AudioManager = CS.AudioManager.Instance
GameController = CS.GameController.Instance
GameDebug = CS.GameDebug
SysConst = CS.AppConst
UIType = CS.UIType
UIMode = CS.UIMode
UIAnim = CS.UIAnim
--Coroutine
cs_coroutine = require "common.tool.cs_coroutine"
StartCoroutine = cs_coroutine.start
StopCoroutine = cs_coroutine.stop
StopAllCoroutine = cs_coroutine.stopAll
WaitForSeconds = cs_coroutine.waitSec
WaitForOneFrame = coroutine.yield
--JSON解析
json = require "rapidjson"
|
local Recount = _G.Recount
local revision = tonumber(string.sub("$Revision: 1309 $", 12, -3))
if Recount.Version < revision then
Recount.Version = revision
end
local _G = _G
local CreateFrame = CreateFrame
local UIParent = UIParent
function Recount:CreateFrame(Name, Title, Height, Width, ShowFunc, HideFunc)
local theFrame = CreateFrame("Frame", Name, UIParent)
theFrame:ClearAllPoints()
theFrame:SetPoint("CENTER",UIParent)
theFrame:SetHeight(Height)
theFrame:SetWidth(Width)
theFrame:SetBackdrop({
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
tile = true,
tileSize = 16,
edgeFile = "Interface\\AddOns\\Recount\\textures\\otravi-semi-full-border",
edgeSize = 32,
insets = {left = 1, right = 1, top = 20, bottom = 1},
})
theFrame:SetBackdropBorderColor(1.0, 0.0, 0.0)
theFrame:SetBackdropColor(24 / 255, 24 / 255, 24 / 255)
if Name == "Recount_MainWindow" then
Recount.Colors:RegisterBorder("Window", "Title", theFrame)
Recount.Colors:RegisterBackground("Window", "Background", theFrame)
else
Recount.Colors:RegisterBorder("Other Windows", "Title", theFrame)
Recount.Colors:RegisterBackground("Other Windows", "Background", theFrame)
end
theFrame:EnableMouse(true)
theFrame:SetMovable(true)
theFrame:SetScript("OnMouseDown", function(this, button)
if (not this.isLocked or this.isLocked == 0) and button == "LeftButton" then
Recount:SetWindowTop(this)
this:StartMoving()
this.isMoving = true
end
end)
theFrame:SetScript("OnMouseUp", function(this)
if this.isMoving then
this:StopMovingOrSizing()
this.isMoving = false
if this.SavePosition then
this:SavePosition()
end
end
end)
theFrame.ShowFunc = ShowFunc
theFrame:SetScript("OnShow", function(this)
Recount:SetWindowTop(this)
if this.ShowFunc then
this:ShowFunc()
end
end)
theFrame.HideFunc = HideFunc
theFrame:SetScript("OnHide", function(this)
if (this.isMoving) then
this:StopMovingOrSizing()
this.isMoving = false
end
if this.HideFunc then
this:HideFunc()
end
end)
theFrame.Title = theFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
theFrame.Title:SetPoint("TOPLEFT", theFrame, "TOPLEFT", 6, -15)
theFrame.Title:SetTextColor(1.0, 1.0, 1.0, 1.0)
theFrame.Title:SetText(Title)
Recount:AddFontString(theFrame.Title)
if Name == "Recount_MainWindow" then
Recount.Colors:UnregisterItem(theFrame.Title)
Recount.Colors:RegisterFont("Window", "Title Text", theFrame.Title)
else
Recount.Colors:UnregisterItem(theFrame.Title)
Recount.Colors:RegisterFont("Other Windows", "Title Text", theFrame.Title)
end
theFrame.CloseButton = CreateFrame("Button", nil, theFrame)
theFrame.CloseButton:SetNormalTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Up.blp")
theFrame.CloseButton:SetPushedTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Down.blp")
theFrame.CloseButton:SetHighlightTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Highlight.blp")
theFrame.CloseButton:SetWidth(20)
theFrame.CloseButton:SetHeight(20)
theFrame.CloseButton:SetPoint("TOPRIGHT", theFrame, "TOPRIGHT", -4, -12)
theFrame.CloseButton:SetScript("OnClick",function(this)
this:GetParent():Hide()
end)
return theFrame
end
function Recount:SetupScrollbar(name)
local Thumb = _G[name.."ScrollBarThumbTexture"]
Thumb:SetTexture("Interface\\AddOns\\Recount\\textures\\scrollbar\\UI-ScrollBar-Knob")
Thumb:SetVertexColor(1, 0, 0)
Recount.Colors:RegisterTexture("Window", "Title", Thumb)
local Up = _G[name.."ScrollBarScrollUpButton"]
Up:SetNormalTexture("Interface\\AddOns\\Recount\\textures\\scrollbar\\UI-ScrollBar-ScrollUpButton-Up")
Up:SetPushedTexture("Interface\\AddOns\\Recount\\textures\\scrollbar\\UI-ScrollBar-ScrollUpButton-Up")
Up:SetDisabledTexture("Interface\\AddOns\\Recount\\textures\\scrollbar\\UI-ScrollBar-ScrollUpButton-Disabled")
Up:SetHighlightTexture("Interface\\AddOns\\Recount\\textures\\scrollbar\\UI-ScrollBar-ScrollUpButton-Highlight")
if not Up.Overlay then
Up.Overlay = Up:CreateTexture(nil, "OVERLAY")
Up.Overlay:SetAllPoints(Up)
Up.Overlay:SetTexture("Interface\\AddOns\\Recount\\textures\\scrollbar\\UI-ScrollBar-ScrollUpButton-Overlay")
Up.Overlay:SetVertexColor(1, 0, 0)
Up.Overlay:SetTexCoord(0.25, 0.75, 0.25, 0.75)
Up.Overlay:SetBlendMode("MOD")
Recount.Colors:RegisterTexture("Window", "Title", Up.Overlay)
end
local Down = _G[name.."ScrollBarScrollDownButton"]
Down:SetNormalTexture("Interface\\AddOns\\Recount\\textures\\scrollbar\\UI-ScrollBar-ScrollDownButton-Up")
Down:SetPushedTexture("Interface\\AddOns\\Recount\\textures\\scrollbar\\UI-ScrollBar-ScrollDownButton-Up")
Down:SetDisabledTexture("Interface\\AddOns\\Recount\\textures\\scrollbar\\UI-ScrollBar-ScrollDownButton-Disabled")
Down:SetHighlightTexture("Interface\\AddOns\\Recount\\textures\\scrollbar\\UI-ScrollBar-ScrollDownButton-Highlight")
if not Down.Overlay then
Down.Overlay = Up:CreateTexture(nil, "OVERLAY")
Down.Overlay:SetAllPoints(Down)
Down.Overlay:SetTexture("Interface\\AddOns\\Recount\\textures\\scrollbar\\UI-ScrollBar-ScrollDownButton-Overlay")
Down.Overlay:SetVertexColor(1, 0, 0)
Down.Overlay:SetTexCoord(0.25, 0.75, 0.25, 0.75)
Down.Overlay:SetBlendMode("MOD")
Recount.Colors:RegisterTexture("Window", "Title", Down.Overlay)
end
end
function Recount:HideScrollbarElements(name)
local Thumb = _G[name.."ScrollBarThumbTexture"]
local Up = _G[name.."ScrollBarScrollUpButton"]
local Down = _G[name.."ScrollBarScrollDownButton"]
Thumb:Hide()
Up:Hide()
Up:EnableMouse(false)
if Up.Overlay then
Up.Overlay:Hide()
end
Down:Hide()
Down:EnableMouse(false)
if Down.Overlay then
Down.Overlay:Hide()
end
local scrollbar = _G[name.."ScrollBar"]
scrollbar:EnableMouse(false)
end
function Recount:ShowScrollbarElements(name)
local Thumb = _G[name.."ScrollBarThumbTexture"]
local Up = _G[name.."ScrollBarScrollUpButton"]
local Down = _G[name.."ScrollBarScrollDownButton"]
Thumb:Show()
Up:EnableMouse(true)
Up:Show()
if Up.Overlay then
Up.Overlay:Show()
end
Down:EnableMouse(true)
Down:Show()
if Down.Overlay then
Down.Overlay:Show()
end
local scrollbar = _G[name.."ScrollBar"]
scrollbar:EnableMouse(true)
end
|
if !CLIENT then return end
CarbonDrawing = CarbonDrawing or {}
function CarbonDrawing.DrawRect( x, y, w, h, col )
surface.SetDrawColor( col )
surface.DrawRect( x, y, w, h )
end
function CarbonDrawing.DrawText( msg, fnt, x, y, c, align )
draw.SimpleText( msg, fnt, x, y, c, align and align or TEXT_ALIGN_CENTER )
end
function CarbonDrawing.DrawOutlinedRect( x, y, w, h, t, c )
surface.SetDrawColor( c )
for i = 0, t - 1 do
surface.DrawOutlinedRect( x + i, y + i, w - i * 2, h - i * 2 )
end
end
local blur = Material( "pp/blurscreen" )
function CarbonDrawing.BlurMenu( panel, layers, density, alpha )
local x, y = panel:LocalToScreen(0, 0)
surface.SetDrawColor( 255, 255, 255, alpha )
surface.SetMaterial( blur )
for i = 1, 3 do
blur:SetFloat( "$blur", ( i / layers ) * density )
blur:Recompute()
render.UpdateScreenEffectTexture()
surface.DrawTexturedRect( -x, -y, ScrW(), ScrH() )
end
end
|
--[[
Common definitions for methods
Copyright 2018 okulo
]]
local GC = GuildContributionsAddonContainer
-- Method IDs must stay consistent for saved variables
GC.MethodId = {}
GC.Enum(
GC.MethodId,
1, -- 1-based for indexing
"MANUAL",
"BANK",
"MAIL"
)
GC.MethodNameById = {}
GC.MethodClassById = {}
GC.MethodByGuildName = {}
|
-------------------- Find replace dialog
local findReplace = {
dialog = nil, -- the wxDialog for find/replace
replace = false, -- is it a find or replace dialog
fWholeWord = true, -- match whole words
fMatchCase = true, -- case sensitive
fDown = true, -- search downwards in doc
fRegularExpr = false, -- use regex
fWrap = true, -- search wraps around
findTextArray = {}, -- array of last entered find text
findText = "", -- string to find
replaceTextArray = {}, -- array of last entered replace text
replaceText = "", -- string to replace find string with
foundString = false, -- was the string found for the last search
-- HasText() is there a string to search for
-- GetSelectedString() get currently selected string if it's on one line
-- FindString(reverse) find the findText string
-- Show(replace) create the dialog
}
local function SetSearchFlags(editor)
local flags = 0
if findReplace.fWholeWord then flags = wxstc.wxSTC_FIND_WHOLEWORD end
if findReplace.fMatchCase then flags = flags + wxstc.wxSTC_FIND_MATCHCASE end
if findReplace.fRegularExpr then flags = flags + wxstc.wxSTC_FIND_REGEXP end
editor:SetSearchFlags(flags)
end
local function SetTarget(editor, fDown, fInclude)
local selStart = editor:GetSelectionStart()
local selEnd = editor:GetSelectionEnd()
local len = editor:GetLength()
local s, e
if fDown then
e= len
s = iff(fInclude, selStart, selEnd +1)
else
s = 0
e = iff(fInclude, selEnd, selStart-1)
end
if not fDown and not fInclude then s, e = e, s end
editor:SetTargetStart(s)
editor:SetTargetEnd(e)
return e
end
function findReplace:HasText()
return (findReplace.findText ~= nil) and (string.len(findReplace.findText) > 0)
end
function findReplace:GetSelectedString()
local editor = currentSTC --GetEditor()
if editor then
local startSel = editor:GetSelectionStart()
local endSel = editor:GetSelectionEnd()
if (startSel ~= endSel) and (editor:LineFromPosition(startSel) == editor:LineFromPosition(endSel)) then
findReplace.findText = editor:GetSelectedText()
findReplace.foundString = true
end
end
end
function findReplace:FindString(reverse)
if findReplace:HasText() then
local editor
if currentSTC then
editor =currentSTC --:DynamicCast("wxStyledTextCtrl")
else
--editor = GetEditor()
return
end
local fDown = iff(reverse, not findReplace.fDown, findReplace.fDown)
local lenFind = string.len(findReplace.findText)
SetSearchFlags(editor)
SetTarget(editor, fDown)
local posFind = editor:SearchInTarget(findReplace.findText)
if (posFind == -1) and findReplace.fWrap then
editor:SetTargetStart(iff(fDown, 0, editor:GetLength()))
editor:SetTargetEnd(iff(fDown, editor:GetLength(), 0))
posFind = editor:SearchInTarget(findReplace.findText)
end
if posFind == -1 then
findReplace.foundString = false
frame:SetStatusText("Find text not found.")
else
findReplace.foundString = true
local start = editor:GetTargetStart()
local finish = editor:GetTargetEnd()
EnsureRangeVisible(editor,start, finish)
editor:SetSelection(start, finish)
end
end
end
local function ReplaceString(fReplaceAll)
if findReplace:HasText() then
local replaceLen = string.len(findReplace.replaceText)
local editor = currentSTC --GetEditor()
if not editor then return end
local findLen = string.len(findReplace.findText)
local endTarget = SetTarget(editor, findReplace.fDown, fReplaceAll)
if fReplaceAll then
SetSearchFlags(editor)
local posFind = editor:SearchInTarget(findReplace.findText)
if (posFind ~= -1) then
editor:BeginUndoAction()
while posFind ~= -1 do
editor:ReplaceTarget(findReplace.replaceText)
editor:SetTargetStart(posFind + replaceLen)
endTarget = endTarget + replaceLen - findLen
editor:SetTargetEnd(endTarget)
posFind = editor:SearchInTarget(findReplace.findText)
end
editor:EndUndoAction()
end
else
if findReplace.foundString then
local start = editor:GetSelectionStart()
editor:ReplaceSelection(findReplace.replaceText)
editor:SetSelection(start, start + replaceLen)
findReplace.foundString = false
end
findReplace:FindString()
end
end
end
local function CreateFindReplaceDialog(replace)
local ID_FIND_NEXT = 1
local ID_REPLACE = 2
local ID_REPLACE_ALL = 3
findReplace.replace = replace
local findDialog = wx.wxDialog(frame, wx.wxID_ANY, "Find", wx.wxDefaultPosition, wx.wxDefaultSize)
-- Create right hand buttons and sizer
local findButton = wx.wxButton(findDialog, ID_FIND_NEXT, "&Find Next")
findButton:SetDefault()
local replaceButton = wx.wxButton(findDialog, ID_REPLACE, "&Replace")
local replaceAllButton = nil
if (replace) then
replaceAllButton = wx.wxButton(findDialog, ID_REPLACE_ALL, "Replace &All")
end
local cancelButton = wx.wxButton(findDialog, wx.wxID_CANCEL, "Cancel")
local buttonsSizer = wx.wxBoxSizer(wx.wxVERTICAL)
buttonsSizer:Add(findButton, 0, wx.wxALL + wx.wxGROW + wx.wxCENTER, 3)
buttonsSizer:Add(replaceButton, 0, wx.wxALL + wx.wxGROW + wx.wxCENTER, 3)
if replace then
buttonsSizer:Add(replaceAllButton, 0, wx.wxALL + wx.wxGROW + wx.wxCENTER, 3)
end
buttonsSizer:Add(cancelButton, 0, wx.wxALL + wx.wxGROW + wx.wxCENTER, 3)
-- Create find/replace text entry sizer
local findStatText = wx.wxStaticText( findDialog, wx.wxID_ANY, "Find: ")
local findTextCombo = wx.wxComboBox(findDialog, wx.wxID_ANY, findReplace.findText, wx.wxDefaultPosition, wx.wxDefaultSize, findReplace.findTextArray, wx.wxCB_DROPDOWN)
findTextCombo:SetFocus()
local replaceStatText, replaceTextCombo
if (replace) then
replaceStatText = wx.wxStaticText( findDialog, wx.wxID_ANY, "Replace: ")
replaceTextCombo = wx.wxComboBox(findDialog, wx.wxID_ANY, findReplace.replaceText, wx.wxDefaultPosition, wx.wxDefaultSize, findReplace.replaceTextArray)
end
local findReplaceSizer = wx.wxFlexGridSizer(2, 2, 0, 0)
findReplaceSizer:AddGrowableCol(1)
findReplaceSizer:Add(findStatText, 0, wx.wxALL + wx.wxALIGN_LEFT, 0)
findReplaceSizer:Add(findTextCombo, 1, wx.wxALL + wx.wxGROW + wx.wxCENTER, 0)
if (replace) then
findReplaceSizer:Add(replaceStatText, 0, wx.wxTOP + wx.wxALIGN_CENTER, 5)
findReplaceSizer:Add(replaceTextCombo, 1, wx.wxTOP + wx.wxGROW + wx.wxCENTER, 5)
end
-- Create find/replace option checkboxes
local wholeWordCheckBox = wx.wxCheckBox(findDialog, wx.wxID_ANY, "Match &whole word")
local matchCaseCheckBox = wx.wxCheckBox(findDialog, wx.wxID_ANY, "Match &case")
local wrapAroundCheckBox = wx.wxCheckBox(findDialog, wx.wxID_ANY, "Wrap ar&ound")
local regexCheckBox = wx.wxCheckBox(findDialog, wx.wxID_ANY, "Regular &expression")
wholeWordCheckBox:SetValue(findReplace.fWholeWord)
matchCaseCheckBox:SetValue(findReplace.fMatchCase)
wrapAroundCheckBox:SetValue(findReplace.fWrap)
regexCheckBox:SetValue(findReplace.fRegularExpr)
local optionSizer = wx.wxBoxSizer(wx.wxVERTICAL, findDialog)
optionSizer:Add(wholeWordCheckBox, 0, wx.wxALL + wx.wxGROW + wx.wxCENTER, 3)
optionSizer:Add(matchCaseCheckBox, 0, wx.wxALL + wx.wxGROW + wx.wxCENTER, 3)
optionSizer:Add(wrapAroundCheckBox, 0, wx.wxALL + wx.wxGROW + wx.wxCENTER, 3)
optionSizer:Add(regexCheckBox, 0, wx.wxALL + wx.wxGROW + wx.wxCENTER, 3)
local optionsSizer = wx.wxStaticBoxSizer(wx.wxVERTICAL, findDialog, "Options" );
optionsSizer:Add(optionSizer, 0, 0, 5)
-- Create scope radiobox
local scopeRadioBox = wx.wxRadioBox(findDialog, wx.wxID_ANY, "Scope", wx.wxDefaultPosition, wx.wxDefaultSize, {"&Up", "&Down"}, 1, wx.wxRA_SPECIFY_COLS)
scopeRadioBox:SetSelection(iff(findReplace.fDown, 1, 0))
local scopeSizer = wx.wxBoxSizer(wx.wxVERTICAL, findDialog );
scopeSizer:Add(scopeRadioBox, 0, 0, 0)
-- Add all the sizers to the dialog
local optionScopeSizer = wx.wxBoxSizer(wx.wxHORIZONTAL)
optionScopeSizer:Add(optionsSizer, 0, wx.wxALL + wx.wxGROW + wx.wxCENTER, 5)
optionScopeSizer:Add(scopeSizer, 0, wx.wxALL + wx.wxGROW + wx.wxCENTER, 5)
local leftSizer = wx.wxBoxSizer(wx.wxVERTICAL)
leftSizer:Add(findReplaceSizer, 0, wx.wxALL + wx.wxGROW + wx.wxCENTER, 0)
leftSizer:Add(optionScopeSizer, 0, wx.wxALL + wx.wxGROW + wx.wxCENTER, 0)
local mainSizer = wx.wxBoxSizer(wx.wxHORIZONTAL)
mainSizer:Add(leftSizer, 0, wx.wxALL + wx.wxGROW + wx.wxCENTER, 10)
mainSizer:Add(buttonsSizer, 0, wx.wxALL + wx.wxGROW + wx.wxCENTER, 10)
mainSizer:SetSizeHints( findDialog )
findDialog:SetSizer(mainSizer)
local function PrependToArray(t, s)
if string.len(s) == 0 then return end
for i, v in ipairs(t) do
if v == s then
table.remove(t, i) -- remove old copy
break
end
end
table.insert(t, 1, s)
if #t > 15 then table.remove(t, #t) end -- keep reasonable length
end
local function TransferDataFromWindow()
findReplace.fWholeWord = wholeWordCheckBox:GetValue()
findReplace.fMatchCase = matchCaseCheckBox:GetValue()
findReplace.fWrap = wrapAroundCheckBox:GetValue()
findReplace.fDown = scopeRadioBox:GetSelection() == 1
findReplace.fRegularExpr = regexCheckBox:GetValue()
findReplace.findText = findTextCombo:GetValue()
PrependToArray(findReplace.findTextArray, findReplace.findText)
if findReplace.replace then
findReplace.replaceText = replaceTextCombo:GetValue()
PrependToArray(findReplace.replaceTextArray, findReplace.replaceText)
end
return true
end
findDialog:Connect(ID_FIND_NEXT, wx.wxEVT_COMMAND_BUTTON_CLICKED,
function(event)
TransferDataFromWindow()
findReplace:FindString()
end)
findDialog:Connect(ID_REPLACE, wx.wxEVT_COMMAND_BUTTON_CLICKED,
function(event)
TransferDataFromWindow()
event:Skip()
if findReplace.replace then
ReplaceString()
else
findReplace.dialog:Destroy()
findReplace.dialog = CreateFindReplaceDialog(true)
findReplace.dialog:Show(true)
end
end)
if replace then
findDialog:Connect(ID_REPLACE_ALL, wx.wxEVT_COMMAND_BUTTON_CLICKED,
function(event)
TransferDataFromWindow()
event:Skip()
ReplaceString(true)
end)
end
findDialog:Connect(wx.wxID_ANY, wx.wxEVT_CLOSE_WINDOW,
function (event)
TransferDataFromWindow()
event:Skip()
findDialog:Show(false)
findDialog:Destroy()
findReplace.dialog=nil
end)
return findDialog
end
function findReplace:Show(replace)
--self.dialog = nil
if self.dialog then
self.dialog:Destroy()
end
self.dialog = CreateFindReplaceDialog(replace)
self.dialog:Show(true)
end
-- ---------------------------------------------------------------------------
-- Create the Search menu and attach the callback functions
function InitFindMenu()
local ID_FIND = wx.wxID_FIND
local ID_FINDNEXT = NewID()
local ID_FINDPREV = NewID()
local ID_REPLACE = NewID()
local ID_GOTOLINE = NewID()
local ID_SORT = NewID()
local ID_FIND_SOURCE = NewID()
findMenu = wx.wxMenu{
{ ID_FIND, "&Find\tCtrl-F", "Find the specified text" },
{ ID_FINDNEXT, "Find &Next\tF3", "Find the next occurrence of the specified text" },
{ ID_FINDPREV, "Find &Previous\tShift-F3", "Repeat the search backwards in the file" },
{ ID_REPLACE, "&Replace\tCtrl-H", "Replaces the specified text with different text" },
{ },
{ID_FIND_SOURCE, "Find Source\tCtrl-I" , "Opens source file from keyword."},
{},
{ ID_GOTOLINE, "&Goto line\tCtrl-G", "Go to a selected line" },
{ },
{ ID_SORT, "&Sort", "Sort selected lines"}}
menuBar:Append(findMenu, "&Search")
frame:Connect(ID_FIND, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
findReplace:GetSelectedString()
findReplace:Show(false)
end)
frame:Connect(ID_FIND, wx.wxEVT_UPDATE_UI, OnUpdateUIEditMenu)
frame:Connect(ID_FIND_SOURCE, wx.wxEVT_UPDATE_UI, OnUpdateUIEditMenu)
frame:Connect(ID_FIND_SOURCE, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
local editor = currentSTC --GetEditor()
if editor then
local startSel = editor:GetSelectionStart()
local endSel = editor:GetSelectionEnd()
if (startSel ~= endSel) and (editor:LineFromPosition(startSel) == editor:LineFromPosition(endSel)) then
local searchtex = editor:GetSelectedText()
local v = sckeywordsSource[searchtex]
if v then
abriredit(v.source:sub(2),v.currentline)
print("ID_FIND_SOURCE",searchtex,v.source:sub(2),v.currentline)
end
end
end
end)
frame:Connect(ID_REPLACE, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
findReplace:GetSelectedString()
findReplace:Show(true)
end)
frame:Connect(ID_REPLACE, wx.wxEVT_UPDATE_UI, OnUpdateUIEditMenu)
frame:Connect(ID_FINDNEXT, wx.wxEVT_COMMAND_MENU_SELECTED, function (event) findReplace:FindString() end)
frame:Connect(ID_FINDNEXT, wx.wxEVT_UPDATE_UI, function (event) findReplace:HasText() end)
frame:Connect(ID_FINDPREV, wx.wxEVT_COMMAND_MENU_SELECTED, function (event) findReplace:FindString(true) end)
frame:Connect(ID_FINDPREV, wx.wxEVT_UPDATE_UI, function (event) findReplace:HasText() end)
-------------------- Find replace end
frame:Connect(ID_GOTOLINE, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
local editor = GetEditor()
local linecur = editor:LineFromPosition(editor:GetCurrentPos())
local linemax = editor:LineFromPosition(editor:GetLength()) + 1
local linenum = wx.wxGetNumberFromUser( "Enter line number",
"1 .. "..tostring(linemax),
"Goto Line",
linecur, 1, linemax,
frame)
if linenum > 0 then
editor:GotoLine(linenum-1)
end
end)
frame:Connect(ID_GOTOLINE, wx.wxEVT_UPDATE_UI, OnUpdateUIEditMenu)
frame:Connect(ID_SORT, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
local editor = GetEditor()
local buf = {}
for line in string.gmatch(editor:GetSelectedText()..'\n', "(.-)\r?\n") do
table.insert(buf, line)
end
if #buf > 0 then
table.sort(buf)
editor:ReplaceSelection(table.concat(buf,"\n"))
end
end)
frame:Connect(ID_SORT, wx.wxEVT_UPDATE_UI, OnUpdateUIEditMenu)
end
|
--- A complete encapsulation of the Playdate's input system. The Playdate SDK gives developers multiple ways to manage input. Noble Engine's approach revolves around the SDK's "inputHandlers," extending them to include additional input methods, and pull in other hardware functions that the SDK puts elsewhere. See usage below for the full list of supported methods.
-- <br><br>By default, Noble Engine assumes each scene will have an inputManager assigned to it. So, for example, you can define one inputManager for menu screens and another for gameplay scenes in your `main.lua`, and then in each scene, set which one that scene uses. You can instead define a unique inputHandler in each scene.
-- <br><br>You may also create and manage inputManagers within and outside of scenes. When a NobleScene is loaded, its inputHandler will become active, thus, inputHandlers do not carry across scenes, and all input is suspended during scene transitions. An advanced use-case is to leave a scene's inputHandler as nil, and manage it separately.
-- <br><br><strong>NOTE:</strong> While the Playdate SDK allows you to stack as many inputHandlers as you want, Noble Engine assumes only one <em>active</em> inputHandler at a time. You may still manually call `playdate.inputHandlers.push()` and `playdate.inputHandlers.pop()` yourself, but Noble Engine will not know about it and it may cause unexpected behavior.
-- <br><br>In addition, you may directly query button status using the SDK's methods for that, but it is not advised to use that as the primary way to manage input for Noble Engine projects, because many of Noble.Input's functionality will not apply.
-- @module Noble.Input
-- @usage
-- local myInputHandler = {
-- AButtonDown = function() end, -- Fires once when button is pressed down.
-- AButtonHold = function() end, -- Fires each frame while a button is held (Noble Engine implementation).
-- AButtonHeld = function() end, -- Fires once after button is held for 1 second (available for A and B).
-- AButtonUp = function() end, -- Fires once when button is released.
-- BButtonDown = function() end,
-- BButtonHold = function() end,
-- BButtonHeld = function() end,
-- BButtonUp = function() end,
-- downButtonDown = function() end,
-- downButtonHold = function() end,
-- downButtonUp = function() end,
-- leftButtonDown = function() end,
-- leftButtonHold = function() end,
-- leftButtonUp = function() end,
-- rightButtonDown = function() end,
-- rightButtonHold = function() end,
-- rightButtonUp = function() end,
-- upButtonDown = function() end,
-- upButtonHold = function() end
-- upButtonUp = function() end,
--
-- cranked = function(change, acceleratedChange) end, -- See Playdate SDK.
-- crankDocked = function() end, -- Noble Engine implementation.
-- crankUndocked = function() end, -- Noble Engine implementation.
-- }
-- @see NobleScene.inputHandler
--
Noble.Input = {}
local currentHandler = {}
--- Get the currently active input handler. Returns nil if none are active.
-- @treturn table A table of callbacks which handle input events.
-- @see NobleScene.inputHandler
function Noble.Input.getHandler()
return currentHandler
end
--- Use this to change the active inputHandler.
-- <br><br>Enter `nil` to disable input. Use @{setEnabled} to disable/enable input without losing track of the current inputHandler.
-- @tparam[opt=nil] table __inputHandler A table of callbacks which handle input events.
-- @see NobleScene.inputHandler
-- @see clearHandler
-- @see setEnabled
function Noble.Input.setHandler(__inputHandler)
if (currentHandler ~= nil) then
playdate.inputHandlers.pop()
end
if (__inputHandler == nil) then
currentHandler = nil
else
currentHandler = __inputHandler
playdate.inputHandlers.push(__inputHandler, true) -- The Playdate SDK allows for multiple inputHandlers to mix and match methods. Noble Engine removes this functionality.
end
end
--- A helper function that calls Noble.Input.setHandler() with no argument.
-- @see setHandler
function Noble.Input.clearHandler()
Noble.Input.setHandler()
end
local cachedInputHandler = nil
--- Enable and disable user input without dealing with inputHanders.
-- The Playdate SDK requires removing all inputHanders to halt user input, so while the currentHandler is cleared when `false` is passed to this method,
-- it is cached so it can be later re-enabled by passing `true` it.
-- @bool __value Set to false to halt input. Set to true to resume accepting input.
-- @see getHandler
-- @see clearHandler
function Noble.Input.setEnabled(__value)
local value = __value or true
if (value == true) then
Noble.Input.setHandler(cachedInputHandler or currentHandler)
cachedInputHandler = nil
else
cachedInputHandler = currentHandler
Noble.Input.clearHandler()
end
end
--- Checks to see that there is an active inputHandler
-- @treturn bool Returns true if the input system is enabled. Returns false if `setEnabled(false)` was used, or if currentHandler is `nil`.
function Noble.Input.getEnabled()
return cachedInputHandler == nil
end
local crankIndicatorActive = false
local crankIndicatorForced = false
--- Enable/disable on-screen system crank indicator.
--
-- <strong>NOTE: The indicator will only ever show if the crank is docked, unless `__evenWhenUndocked` is true.</strong>
-- @bool __active Set true to start showing the on-screen crank indicator. Set false to stop showing it.
-- @bool[opt=false] __evenWhenUndocked Set true to show the crank indicator even if the crank is already undocked (`__active` must also be true).
function Noble.Input.setCrankIndicatorStatus(__active, __evenWhenUndocked)
if (__active) then
UI.crankIndicator:start()
end
crankIndicatorActive = __active
crankIndicatorForced = __evenWhenUndocked or false
end
--- Checks whether the system crank indicator status. Returns a tuple.
--
-- @treturn bool Is the crank indicator active?
-- @treturn bool Is the crank indicator being forced when active, even when the crank is undocked?
-- @see setCrankIndicatorStatus
function Noble.Input.getCrankIndicatorStatus()
return crankIndicatorActive, crankIndicatorForced
end
-- Noble Engine defines extra "buttonHold" methods that run every frame that a button is held down, but to implement them, we need to do some magic.
local buttonHoldBufferAmount = 3 -- This is how many frames to wait before the engine determines that a button is being held down. Using !buttonJustPressed() provides only 1 frame, which isn't enough.
local AButtonHoldBufferCount = 0
local BButtonHoldBufferCount = 0
local upButtonHoldBufferCount = 0
local downButtonHoldBufferCount = 0
local leftButtonHoldBufferCount = 0
local rightButtonHoldBufferCount = 0
-- Do not call this method directly, or modify it, thanks. :-)
function Noble.Input.update()
if (currentHandler == nil) then return end
if (currentHandler.AButtonHold ~= nil) then
if (playdate.buttonIsPressed(playdate.kButtonA)) then
if (AButtonHoldBufferCount == buttonHoldBufferAmount) then currentHandler.AButtonHold() -- Execute!
else AButtonHoldBufferCount = AButtonHoldBufferCount + 1 end -- Wait another frame!
end
if (playdate.buttonJustReleased(playdate.kButtonA)) then AButtonHoldBufferCount = 0 end -- Reset!
end
if (currentHandler.BButtonHold ~= nil) then
if (playdate.buttonIsPressed(playdate.kButtonB)) then
if (BButtonHoldBufferCount == buttonHoldBufferAmount) then currentHandler.BButtonHold()
else BButtonHoldBufferCount = BButtonHoldBufferCount + 1 end
end
if (playdate.buttonJustReleased(playdate.kButtonB)) then BButtonHoldBufferCount = 0 end
end
if (currentHandler.upButtonHold ~= nil) then
if (playdate.buttonIsPressed(playdate.kButtonUp)) then
if (upButtonHoldBufferCount == buttonHoldBufferAmount) then currentHandler.upButtonHold()
else upButtonHoldBufferCount = upButtonHoldBufferCount + 1 end
end
if (playdate.buttonJustReleased(playdate.kButtonUp)) then upButtonHoldBufferCount = 0 end
end
if (currentHandler.downButtonHold ~= nil) then
if (playdate.buttonIsPressed(playdate.kButtonDown)) then
if (downButtonHoldBufferCount == buttonHoldBufferAmount) then currentHandler.downButtonHold()
else downButtonHoldBufferCount = downButtonHoldBufferCount + 1 end
end
if (playdate.buttonJustReleased(playdate.kButtonDown)) then downButtonHoldBufferCount = 0 end
end
if (currentHandler.leftButtonHold ~= nil) then
if (playdate.buttonIsPressed(playdate.kButtonLeft)) then
if (leftButtonHoldBufferCount == buttonHoldBufferAmount) then currentHandler.leftButtonHold()
else leftButtonHoldBufferCount = leftButtonHoldBufferCount + 1 end
end
if (playdate.buttonJustReleased(playdate.kButtonLeft)) then leftButtonHoldBufferCount = 0 end
end
if (currentHandler.rightButtonHold ~= nil) then
if (playdate.buttonIsPressed(playdate.kButtonRight)) then
if (rightButtonHoldBufferCount == buttonHoldBufferAmount) then currentHandler.rightButtonHold()
else rightButtonHoldBufferCount = rightButtonHoldBufferCount + 1 end
end
if (playdate.buttonJustReleased(playdate.kButtonRight)) then rightButtonHoldBufferCount = 0 end
end
end
-- Do not call this method directly, or modify it, thanks. :-)
function playdate.crankDocked()
if (currentHandler.crankDocked ~= nil and Noble.Input.getEnabled() == true) then
currentHandler.crankDocked()
end
end
-- Do not call this method directly, or modify it, thanks. :-)
function playdate.crankUndocked()
if (currentHandler.crankUndocked ~= nil and Noble.Input.getEnabled() == true) then
currentHandler.crankDocked()
end
end
--- Constants
-- . A set of constants referencing device inputs, stored as strings. Can be used for querying button input,
-- but are mainly for on-screen prompts or other elements where a string literal is useful, such as a filename, GameData value, or localization key.
-- For faster performance, use the ones that exist in the Playdate SDK (i.e.: `playdate.kButtonA`), which are stored as binary numbers.
-- @usage
-- function newPrompt(__input, __promptString)
-- -- ...
-- local icon = Graphics.image.new("assets/images/UI/Icon_" .. __input)
-- -- ...
-- end
--
-- promptMove = newPrompt(Noble.Input.DPAD_HORIZONTAL, "Move!") -- assets/images/UI/Icon_dPadHorizontal.png"
-- promptJump = newPrompt(Noble.Input.BUTTON_A, "Jump!") -- assets/images/UI/Icon_buttonA.png"
-- promptCharge = newPrompt(Noble.Input.CRANK_FORWARD, "Charge the battery!") -- assets/images/UI/Icon_crankForward.png"
-- @section constants
--- `"buttonA"`
Noble.Input.BUTTON_A = "buttonA"
--- `"buttonB"`
Noble.Input.BUTTON_B = "buttonB"
--- The system menu button.
--
-- `"buttonMenu"`
Noble.Input.BUTTON_MENU = "buttonMenu"
--- Referencing the D-pad component itself, rather than an input.
--
-- `"dPad"`
Noble.Input.DPAD = "dPad"
--- Referencing the left and right input D-pad inputs.
--
-- `"dPadHorizontal"`
Noble.Input.DPAD_HORIZONTAL = "dPadHorizontal"
--- Referencing the up and down input D-pad inputs.
--
-- `"dPadVertical"`
Noble.Input.DPAD_VERTICAL = "dPadVertical"
--- `"dPadUp"`
Noble.Input.DPAD_UP = "dPadUp"
--- `"dPadDown"`
Noble.Input.DPAD_DOWN = "dPadDown"
--- `"dPadLeft"`
Noble.Input.DPAD_LEFT = "dPadLeft"
--- `"dPadRight"`
Noble.Input.DPAD_RIGHT = "dPadRight"
--- Referencing the crank component itself, rather than an input.
--
-- `"crank"`
Noble.Input.CRANK = "crank"
--- AKA: Clockwise. See Playdate SDK.
--
-- `"crankForward"`
Noble.Input.CRANK_FORWARD = "crankForward"
--- AKA: Anticlockwise. See Playdate SDK.
--
-- `"crankReverse"`
Noble.Input.CRANK_REVERSE = "crankReverse"
--- Referencing the action of docking the crank.
--
-- `"crankDock"`
Noble.Input.CRANK_DOCK = "crankDock"
--- Referencing the action of undocking the crank.
--
-- `"crankUndock"`
Noble.Input.CRANK_UNDOCK = "crankUndock"
|
require('lspconfig').bashls.setup{};
|
-- Copyright 2006-2016 Mitchell mitchell.att.foicica.com. See LICENSE.
-- reStructuredText LPeg lexer.
local l = require('lexer')
local token, word_match, starts_line = l.token, l.word_match, l.starts_line
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'rest'}
-- Whitespace.
local ws = token(l.WHITESPACE, S(' \t')^1 + l.newline^1)
local any_indent = S(' \t')^0
-- Section titles (2 or more characters).
local adornment_chars = lpeg.C(S('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'))
local adornment = lpeg.C(adornment_chars^2 * any_indent) * (l.newline + -1)
local overline = lpeg.Cmt(starts_line(adornment), function(input, index, adm, c)
if not adm:find('^%'..c..'+%s*$') then return nil end
local rest = input:sub(index)
local lines = 1
for line, e in rest:gmatch('([^\r\n]+)()') do
if lines > 1 and line:match('^(%'..c..'+)%s*$') == adm then
return index + e - 1
end
if lines > 3 or #line > #adm then return nil end
lines = lines + 1
end
return #input + 1
end)
local underline = lpeg.Cmt(starts_line(adornment), function(_, index, adm, c)
local pos = adm:match('^%'..c..'+()%s*$')
return pos and index - #adm + pos - 1 or nil
end)
-- Token needs to be a predefined one in order for folder to work.
local title = token(l.CONSTANT, overline + underline)
-- Lists.
local bullet_list = S('*+-') -- TODO: '•‣⁃', as lpeg does not support UTF-8
local enum_list = P('(')^-1 *
(l.digit^1 + S('ivxlcmIVXLCM')^1 + l.alnum + '#') * S('.)')
local field_list = ':' * (l.any - ':')^1 * P(':')^-1
local option_word = l.alnum * (l.alnum + '-')^0
local option = S('-/') * option_word * (' ' * option_word)^-1 +
'--' * option_word * ('=' * option_word)^-1
local option_list = option * (',' * l.space^1 * option)^-1
local list = #(l.space^0 * (S('*+-:/') + enum_list)) *
starts_line(token('list', l.space^0 * (option_list + bullet_list +
enum_list + field_list) *
l.space))
-- Literal block.
local block = P('::') * (l.newline + -1) * function(input, index)
local rest = input:sub(index)
local level, quote = #rest:match('^([ \t]*)')
for pos, indent, line in rest:gmatch('()[ \t]*()([^\r\n]+)') do
local no_indent = (indent - pos < level and line ~= ' ' or level == 0)
local quoted = no_indent and line:find(quote or '^%s*%W')
if quoted and not quote then quote = '^%s*%'..line:match('^%s*(%W)') end
if no_indent and not quoted and pos > 1 then return index + pos - 1 end
end
return #input + 1
end
local literal_block = token('literal_block', block)
-- Line block.
local line_block_char = token(l.OPERATOR, starts_line(any_indent * '|'))
local word = l.alpha * (l.alnum + S('-.+'))^0
-- Explicit markup blocks.
local prefix = any_indent * '.. '
local footnote_label = '[' * (l.digit^1 + '#' * word^-1 + '*') * ']'
local footnote = token('footnote_block', prefix * footnote_label * l.space)
local citation_label = '[' * word * ']'
local citation = token('citation_block', prefix * citation_label * l.space)
local link = token('link_block', prefix * '_' *
(l.delimited_range('`') + (P('\\') * 1 +
l.nonnewline - ':')^1) * ':' * l.space)
local markup_block = #prefix * starts_line(footnote + citation + link)
-- Directives.
local directive_type = word_match({
-- Admonitions
'attention', 'caution', 'danger', 'error', 'hint', 'important', 'note', 'tip',
'warning', 'admonition',
-- Images
'image', 'figure',
-- Body elements
'topic', 'sidebar', 'line-block', 'parsed-literal', 'code', 'math', 'rubric',
'epigraph', 'highlights', 'pull-quote', 'compound', 'container',
-- Table
'table', 'csv-table', 'list-table',
-- Document parts
'contents', 'sectnum', 'section-autonumbering', 'header', 'footer',
-- References
'target-notes', 'footnotes', 'citations',
-- HTML-specific
'meta',
-- Directives for substitution definitions
'replace', 'unicode', 'date',
-- Miscellaneous
'include', 'raw', 'class', 'role', 'default-role', 'title',
'restructuredtext-test-directive',
}, '-')
local known_directive = token('directive',
prefix * directive_type * '::' * l.space)
local sphinx_directive_type = word_match({
-- The TOC tree.
'toctree',
-- Paragraph-level markup.
'note', 'warning', 'versionadded', 'versionchanged', 'deprecated', 'seealso',
'rubric', 'centered', 'hlist', 'glossary', 'productionlist',
-- Showing code examples.
'highlight', 'literalinclude',
-- Miscellaneous
'sectionauthor', 'index', 'only', 'tabularcolumns'
}, '-')
local sphinx_directive = token('sphinx_directive',
prefix * sphinx_directive_type * '::' * l.space)
local unknown_directive = token('unknown_directive',
prefix * word * '::' * l.space)
local directive = #prefix * starts_line(known_directive + sphinx_directive +
unknown_directive)
-- Sphinx code block.
local indented_block = function(input, index)
local rest = input:sub(index)
local level = #rest:match('^([ \t]*)')
for pos, indent, line in rest:gmatch('()[ \t]*()([^\r\n]+)') do
if indent - pos < level and line ~= ' ' or level == 0 and pos > 1 then
return index + pos - 1
end
end
return #input + 1
end
local code_block = prefix * 'code-block::' * S(' \t')^1 * l.nonnewline^0 *
(l.newline + -1) * indented_block
local sphinx_block = #prefix * token('code_block', starts_line(code_block))
-- Substitution definitions.
local substitution = #prefix *
token('substitution',
starts_line(prefix * l.delimited_range('|') *
l.space^1 * word * '::' * l.space))
-- Comments.
local line_comment = prefix * l.nonnewline^0
local bprefix = any_indent * '..'
local block_comment = bprefix * l.newline * indented_block
local comment = #bprefix *
token(l.COMMENT, starts_line(line_comment + block_comment))
-- Inline markup.
local em = token('em', l.delimited_range('*'))
local strong = token('strong', ('**' * (l.any - '**')^0 * P('**')^-1))
local role = token('role', ':' * word * ':' * (word * ':')^-1)
local interpreted = role^-1 * token('interpreted', l.delimited_range('`')) *
role^-1
local inline_literal = token('inline_literal',
'``' * (l.any - '``')^0 * P('``')^-1)
local link_ref = token('link',
(word + l.delimited_range('`')) * '_' * P('_')^-1 +
'_' * l.delimited_range('`'))
local footnote_ref = token('footnote', footnote_label * '_')
local citation_ref = token('citation', citation_label * '_')
local substitution_ref = token('substitution', l.delimited_range('|', true) *
('_' * P('_')^-1)^-1)
local link = token('link', l.alpha * (l.alnum + S('-.'))^1 * ':' *
(l.alnum + S('/.+-%@'))^1)
local inline_markup = (strong + em + inline_literal + link_ref + interpreted +
footnote_ref + citation_ref + substitution_ref + link) *
-l.alnum
-- Other.
local non_space = token(l.DEFAULT, l.alnum * (l.any - l.space)^0)
local escape = token(l.DEFAULT, '\\' * l.any)
M._rules = {
{'literal_block', literal_block},
{'list', list},
{'markup_block', markup_block},
{'code_block', sphinx_block},
{'directive', directive},
{'substitution', substitution},
{'comment', comment},
{'title', title},
{'line_block_char', line_block_char},
{'whitespace', ws},
{'inline_markup', inline_markup},
{'non_space', non_space},
{'escape', escape}
}
M._tokenstyles = {
list = l.STYLE_TYPE,
literal_block = l.STYLE_EMBEDDED..',eolfilled',
footnote_block = l.STYLE_LABEL,
citation_block = l.STYLE_LABEL,
link_block = l.STYLE_LABEL,
directive = l.STYLE_KEYWORD,
sphinx_directive = l.STYLE_KEYWORD..',bold',
unknown_directive = l.STYLE_KEYWORD..',italics',
code_block = l.STYLE_EMBEDDED..',eolfilled',
substitution = l.STYLE_VARIABLE,
strong = 'bold',
em = 'italics',
role = l.STYLE_CLASS,
interpreted = l.STYLE_STRING,
inline_literal = l.STYLE_EMBEDDED,
link = 'underlined',
footnote = 'underlined',
citation = 'underlined',
}
local sphinx_levels = {
['#'] = 0, ['*'] = 1, ['='] = 2, ['-'] = 3, ['^'] = 4, ['"'] = 5
}
-- Section-based folding.
M._fold = function(text, start_pos, start_line, start_level)
local folds, line_starts = {}, {}
for pos in (text..'\n'):gmatch('().-\r?\n') do
line_starts[#line_starts + 1] = pos
end
local style_at, CONSTANT, level = l.style_at, l.CONSTANT, start_level
local sphinx = l.property_int['fold.by.sphinx.convention'] > 0
local FOLD_BASE = l.FOLD_BASE
local FOLD_HEADER, FOLD_BLANK = l.FOLD_HEADER, l.FOLD_BLANK
for i = 1, #line_starts do
local pos, next_pos = line_starts[i], line_starts[i + 1]
local c = text:sub(pos, pos)
local line_num = start_line + i - 1
folds[line_num] = level
if style_at[start_pos + pos] == CONSTANT and c:find('^[^%w%s]') then
local sphinx_level = FOLD_BASE + (sphinx_levels[c] or #sphinx_levels)
level = not sphinx and level - 1 or sphinx_level
if level < FOLD_BASE then level = FOLD_BASE end
folds[line_num - 1], folds[line_num] = level, level + FOLD_HEADER
level = (not sphinx and level or sphinx_level) + 1
elseif c == '\r' or c == '\n' then
folds[line_num] = level + FOLD_BLANK
end
end
return folds
end
l.property['fold.by.sphinx.convention'] = '0'
--[[ Embedded languages.
local bash = l.load('bash')
local bash_indent_level
local start_rule = #(prefix * 'code-block' * '::' * l.space^1 * 'bash' *
(l.newline + -1)) * sphinx_directive *
token('bash_begin', P(function(input, index)
bash_indent_level = #input:match('^([ \t]*)', index)
return index
end))]]
return M
|
local a = core.filter.add
a("render", { "position.x", "position.y", "drawReference" })
a("square", { "position.x", "position.y", "color.R", "color.G", "color.B" })
a("green", { "green" })
a("cyan", { "cyan" })
a("ember", { "ember" })
a("yellow", { "yellow" })
a("purple", { "purple" })
a("unwalkable", { "position.x", "position.y", "unwalkable" })
a("player", { "position.x", "position.y", "player" })
a("endNode", { "position.x", "position.y", "endNode" })
a("tiles", { "position.x", "position.y", "tileColor" })
a("tileToImage", { "position.x", "position.y", "tileSpriteName" })
a("turret", { "isTurret", "position.x", "position.y", "orientation" })
a("persistent", { "persistent" })
a("nonPersistent", { "-persistent" })
a("behaves", { "behavior" })
a("moveAction", { "behavior.actions.move" })
a("rotationAction", { "behavior.actions.rotate" })
a("toggleDoorAction", { "behavior.actions.toggleDoor" })
a("trapdoor", { "trapdoor" })
a("movingBlock", { "movingBlock" })
|
local helpers = require('test.functional.helpers')(after_each)
local clear, insert, eq = helpers.clear, helpers.insert, helpers.eq
local command, expect = helpers.command, helpers.expect
local feed, eval = helpers.feed, helpers.eval
local exc_exec = helpers.exc_exec
describe('gu and gU', function()
before_each(clear)
it('works in any locale with default casemap', function()
eq('internal,keepascii', eval('&casemap'))
insert("iI")
feed("VgU")
expect("II")
feed("Vgu")
expect("ii")
end)
describe('works in Turkish locale', function()
clear()
local err = exc_exec('lang ctype tr_TR.UTF-8')
if err ~= 0 then
pending("Locale tr_TR.UTF-8 not supported", function() end)
return
end
before_each(function()
command('lang ctype tr_TR.UTF-8')
end)
it('with default casemap', function()
eq('internal,keepascii', eval('&casemap'))
-- expect ASCII behavior
insert("iI")
feed("VgU")
expect("II")
feed("Vgu")
expect("ii")
end)
it('with casemap=""', function()
command('set casemap=')
-- expect either Turkish locale behavior or ASCII behavior
local iupper = eval("toupper('i')")
if iupper == "İ" then
insert("iI")
feed("VgU")
expect("İI")
feed("Vgu")
expect("iı")
elseif iupper == "I" then
insert("iI")
feed("VgU")
expect("II")
feed("Vgu")
expect("ii")
else
error("expected toupper('i') to be either 'I' or 'İ'")
end
end)
end)
end)
|
for k, v in ipairs({
createObject ( 3115, -2066.1001, 474.60001, 35.1, 0, 90, 270 ),
createObject ( 6959, -1673.4, 799.79999, 35, 0, 90, 0 ),
createObject ( 6959, -1673.4, 772.40002, 35, 0, 90, 0 ),
createObject ( 6959, -1693, 799.79999, 35, 0, 90, 0 ),
createObject ( 6959, -1693, 772.40002, 35, 0, 90, 0 ),
createObject ( 3115, -1683.1, 819.40002, 45.1, 0, 90, 90 ),
createObject ( 3115, -1683.2, 752.79999, 45.1, 0, 90, 270 ),
createObject ( 2951, -1231.2002, 51.79981, 13.1, 0, 0, 315.247 ),
createObject ( 2951, -1230.2, 50.8, 13.1, 0, 0, 315.247 ),
createObject ( 2929, -1227.1, 50.3, 14.9, 0, 0, 45.25 ),
createObject ( 2978, -1228.9, 55.9, 14.3, 0, 90, 224 ),
createObject ( 3095, -209.8, 1055.8, 22.3 ),
createObject ( 6959, 2412.2, 2183.2, 13.4 ),
createObject ( 6959, 2453.5, 2183.2, 13.4 ),
createObject ( 6959, 2491, 2183.2, 13.4 ),
createObject ( 2951, 161.10001, -22.4, 4.5, 0, 0, 90 ),
createObject ( 2951, 136.7, -22.6, 4.5, 0, 0, 90 ),
createObject ( 6959, 1870.3, 2218.8999, 14.1 ),
createObject ( 6959, 1881.8, 2218.8999, 14.1 ),
createObject ( 6959, 1881.8, 2207, 14.1 ),
createObject ( 6959, 1870.3, 2207, 14.1 ),
createObject ( 3115, 1851.8, 2218.8999, 14.4, 0, 180, 0 ),
createObject ( 3115, 1851.8, 2204.8999, 14.4, 0, 179.995, 0 ),
createObject ( 3115, 1901.5, 2206.1001, 14.4, 0, 180, 90 ),
createObject ( 3115, 1901.5, 2217.8, 14.4, 0, 179.995, 90 ),
createObject ( 3095, 366.5, -60.2, 1004.6 ),
createObject ( 7025, 370.10001, -60, 1008.6 ),
createObject ( 684, 1099.8, -1291.1, 15.9, 90, 0, 0 ),
createObject ( 684, 1099.3, -1291.4, 15.9, 90, 0, 0 ),
createObject ( 2951, 427.10001, -1642.4, 45.8, 0, 89.75, 40.75 ),
createObject ( 2951, 426.5, -1642.9, 45.8, 0.034, 89.75, 32.998 ),
createObject ( 2951, 1586.3, -1716.1, 25.1, 90, 0, 5.25 ),
createObject ( 2951, 1586.2, -1715.7, 25.1, 90, 0, 5.246 ),
createObject ( 2951, 1588.3, -1742.1, 25.1, 90, 0, 5.246 ),
createObject ( 2951, 1588.3, -1741.4, 25.1, 90, 0, 5.246 ),
createObject ( 2951, 1621.6, -1712.6, 25.1, 90, 0, 5.746 ),
createObject ( 2951, 1621.7, -1713, 25.1, 90, 0, 5.746 ),
createObject ( 2951, 1623.8, -1738.9, 25.1, 90, 0, 5.246 ),
createObject ( 2951, 1623.7, -1738.2, 25.1, 90, 0, 5.246 ),
createObject ( 3095, 1005.3, -919.20001, 45.1, 0, 0, 8 ),
createObject ( 1418, 2007.2, 1519.8, 16, 90, 0, 85 ),
createObject ( 1418, 2007.5, 1523.3, 16, 90, 0, 84.996 ),
createObject ( 1418, 2005.8, 1519.9, 16, 90, 0, 84.996 ),
createObject ( 1418, 2006.4, 1523.4, 16, 89.75, 90, 354.996 ),
createObject ( 3115, 2177.2, 1284.9, 15.4 ),
createObject ( 3115, 2166.8999, 1288.90002, 6.2, 90, 0, 270 ),
createObject ( 2951, 1078.1, 1362.3, 9.8 ),
createObject ( 640, 1175.4, 1223.7, 12.6, 90, 0, 90 ),
createObject ( 640, 1175.7, 1223.7, 12.6, 90, 0, 90 ),
createObject ( 640, 1176.1, 1223.7, 12.6, 90, 0, 90 ),
createObject ( 640, 1175.6, 1223.7, 12.6, 270, 0, 90 ),
createObject ( 640, 2317.1001, 1406, 24.3 ),
createObject ( 640, 2317.1001, 1411.4, 24.3 ),
createObject ( 640, 2317.1001, 1416.7, 24.3 ),
createObject ( 640, 2317.1001, 1422.1, 24.3 ),
createObject ( 640, 2317.1001, 1427.4, 24.3 ),
createObject ( 640, 2317.1001, 1432.7, 24.3 ),
createObject ( 640, 2317.1001, 1438.1, 24.3 ),
createObject ( 640, 2317.1001, 1443.5, 24.3 ),
createObject ( 640, 2317.1001, 1448.9, 24.3 ),
createObject ( 640, 2317.1001, 1454.3, 24.3 ),
createObject ( 640, 2317.1001, 1459.7, 24.3 ),
createObject ( 640, 2317.1001, 1465.1, 24.3 ),
createObject ( 640, 2317.1001, 1470.5, 24.3 ),
createObject ( 640, 2317.1001, 1475.9, 24.3 ),
createObject ( 640, 2317.1006, 1481.2998, 24.3 ),
createObject ( 640, 2317.1001, 1486.7, 24.3 ),
createObject ( 640, 2317.1001, 1492, 24.3 ),
createObject ( 640, 2317.1001, 1497, 24.3 ),
createObject ( 640, 2317.1001, 1501.1, 24.3 ),
createObject ( 640, -180, 1129.1, 19.4, 90, 0, 90 ),
createObject ( 640, -180, 1128.6, 19.4, 90, 0, 90 ),
createObject ( 640, -179.7, 1128.8, 19.4, 90, 0, 1.25 ),
createObject ( 3095, -648.90002, 1174.4, 22.3, 0, 90, 282 ),
createObject ( 3095, -651.09998, 1183.4, 22.2, 0, 270, 281.997 ),
createObject ( 3095, -651.09998, 1183.4, 13.3, 0, 270, 281.992 ),
createObject ( 3095, -646, 1179.1, 22.2, 0.05, 91, 14.1 ),
createObject ( 3095, -646.29999, 1180.3, 22.2, 0.07, 90.08, 14.09 ),
createObject ( 3095, -646.29999, 1180.3, 13.3, 0, 90.049, 14.046 ),
createObject ( 3168, -640.5, 2717.2, 71.2, 0, 0, 42.312 ),
createObject ( 6959, 2301.2, 1730.3, 9.8 ),
createObject ( 3095, 2440, 1745.2, 9.2 ),
createObject ( 6959, 2348.2, 1863.2, 14 ),
createObject ( 4199, 1675.2, 1380.5, 16.1, 0, 0, 29.25 ),
createObject ( 4199, 1672.3, 1385.7, 16.1, 0.06, 0.14, 29.64 ),
createObject ( 4199, 1675.4, 1511.4, 16.1, 0, 0, 326.754 ),
createObject ( 3095, 1670.2, 1483.1, 13.3, 0, 0, 359.5 ),
createObject ( 3095, 1661.4, 1483.2, 13.3, 0, 0, 359.495 ),
createObject ( 3095, 1714, 1348.6, 9.8, 0, 90, 346 ),
createObject ( 2978, -346, 1625.2, 135.7, 330.5, 180.287, 0.391 ),
createObject ( 2978, -346.5, 1625.2, 135.7, 330.496, 180.286, 0.39 ),
createObject ( 3095, 2620.3, 1073.9, 9.1 ),
createObject ( 3095, 2621.5, 1063.6, 9.2 ),
createObject ( 2978, -1674.6, 560.29999, 38.4, 0, 270, 46 ),
createObject ( 2978, -1675.1, 560.79999, 38.4, 0, 270, 46.25 ),
createObject ( 2978, -1675.1, 560.79999, 37, 0, 270, 46 ),
createObject ( 2978, -1674.6, 560.29999, 37, 0, 270, 46 ),
createObject ( 1223, -1645, 544, 34.4, 0, 0, 56 ),
createObject ( 2978, -1650.7, 537.59998, 38.4, 0, 270, 46.247 ),
createObject ( 2978, -1651.1, 538, 38.4, 0, 270, 46.247 ),
createObject ( 2978, -1651.2, 538.09998, 36.7, 0, 270, 46.247 ),
createObject ( 2978, -1650.7, 537.59998, 37, 0, 270, 46.247 ),
createObject ( 2951, -1377.2, 491.60001, 5.6, 0, 0, 90 ),
createObject ( 1418, -1405.9, 1.4, 6.8, 0, 90, 0 ),
createObject ( 3095, -1868.2, -160.10001, 16.1 ),
createObject ( 1446, -1955, 617.70001, 144.3, 302.001, 0, 0 ),
createObject ( 1446, -1959.7, 617.70001, 144.3, 301.998, 0, 0 ),
createObject ( 1446, -1964.4, 617.70001, 144.3, 301.998, 0, 0 ),
createObject ( 1446, -1969.1, 617.70001, 144.3, 301.998, 0, 0 ),
createObject ( 1446, -1973.8, 617.70001, 144.3, 301.998, 0, 0 ),
createObject ( 1446, -1978.5, 617.70001, 144.3, 301.998, 0, 0 ),
createObject ( 1446, -1983.2, 617.70001, 144.3, 301.998, 0, 0 ),
createObject ( 1446, -1987.7, 617.70001, 144.3, 301.998, 0, 0 ),
createObject ( 3095, 1833.2, 1286.6, 8.2, 0, 346.25, 0 ),
createObject ( 6959, -2670.8, 498.29999, 20.1 ),
createObject ( 3095, -1745.2, 979.59998, 24.1, 0, 5.25, 0 ),
createObject ( 3095, -1745.2, 988.59998, 24.1, 0, 5.25, 0 ),
createObject ( 6959, -2276, 1065.9, 64.5 ),
createObject ( 3095, -2511.8, 857.90002, 65.9, 0, 90, 307.75 ),
createObject ( 3095, -2511.8, 857.90002, 74.7, 0, 90, 307.749 ),
createObject ( 3095, -2511.8, 857.90002, 82.6, 0, 90, 307.749 ),
createObject ( 3095, -2511.7, 849.90002, 82.6, 0, 90, 52.251 ),
createObject ( 3095, -2511.7, 849.90002, 73.6, 0, 90, 52.245 ),
createObject ( 3095, -2511.7, 849.90002, 65.9, 0, 90, 52.245 ),
createObject ( 3033, -2515.3, 855, 64.3, 0, 90, 90 ),
createObject ( 3033, -2515.3, 855, 69.9, 0, 90, 90 ),
createObject ( 3033, -2515.3, 855, 75.5, 0, 90, 90 ),
createObject ( 3033, -2515.3, 855, 81.1, 0, 90, 90 ),
createObject ( 3033, -2515.3, 855, 84.7, 0, 90, 90 ),
createObject ( 3033, -2512.5, 852.90002, 61.4, 90, 0, 0 ),
createObject ( 1418, -2863.2, 1253.6, 6.7, 0, 0, 45 ),
createObject ( 1418, -2860.8, 1256, 6.7, 0, 0, 44.995 ),
createObject ( 1418, -2858.3999, 1258.4, 6.7, 0, 0, 44.995 ),
createObject ( 1418, -2856, 1260.8, 6.7, 0, 0, 44.995 ),
createObject ( 1418, -2853.6001, 1263.2, 6.7, 0, 0, 44.995 ),
createObject ( 1418, -2851.2, 1265.6, 6.7, 0, 0, 44.995 ),
createObject ( 1418, -2849.1001, 1267.7, 6.7, 0, 0, 44.995 ),
createObject ( 3095, -2554.6001, 1179, 40.4, 0, 88, 340 ),
createObject ( 984, -2663.3999, 1704.2, 67.6, 0.994, 353.999, 359.854 ),
createObject ( 984, -2663.3999, 1694.6, 67.4, 1.5, 359.25, 0.517 ),
createObject ( 3095, 356.20001, -1628.5, 41, 0.75, 359.25, 339.51 ),
createObject ( 3095, 362, -1630.6, 41, 0.747, 359.247, 344.005 ),
createObject ( 3095, 370, -1632.4, 41, 0.742, 359.242, 350.004 ),
createObject ( 3095, 378, -1633.1, 41, 0.736, 359.242, 359.002 ),
createObject ( 3095, 386.29999, -1632.6, 41, 0.731, 359.992, 4.491 ),
createObject ( 3095, 388.5, -1632, 41, 0.731, 359.989, 4.488 ),
createObject ( 3095, 395, -1629.1, 41, 0.731, 359.989, 356.988 ),
createObject ( 3095, 395.10001, -1627.8, 44.8, 0.725, 359.989, 358.734 ),
createObject ( 3095, 388.70001, -1629.8, 44.8, 0.72, 359.989, 354.231 ),
createObject ( 3095, 381.89999, -1633.1, 44.8, 0.714, 359.989, 1.227 ),
createObject ( 3095, 373.60001, -1632.9, 44.8, 0.709, 359.989, 355.225 ),
createObject ( 3095, 366.10001, -1631.6, 44.8, 0.709, 359.989, 347.721 ),
createObject ( 3095, 361.79999, -1630.3, 44.8, 0.709, 359.989, 347.717 ),
createObject ( 3095, 355.89999, -1625.7, 44.8, 0.709, 359.989, 351.717 ),
createObject ( 3095, 349.79999, -1623.7, 41, 0.209, 359.989, 351.716 ),
createObject ( 3095, 349.5, -1623.3, 40.3, 0, 90, 264.25 ),
createObject ( 3095, 350.20001, -1621.7, 44.2, 0, 90, 264.249 ),
createObject ( 3095, 350, -1624.7, 36, 0, 90, 263.249 ),
createObject ( 3095, 356.79999, -1626.7, 44.2, 0, 90, 264.249 ),
createObject ( 3095, 362.39999, -1633.1, 44.7, 0, 90, 264.249 ),
createObject ( 3095, 370.39999, -1634.1, 44.7, 0, 90, 264.249 ),
createObject ( 3095, 379.20001, -1635.1, 44.7, 0, 90, 264.999 ),
createObject ( 3095, 381.70001, -1635.5, 44.7, 0, 90, 263.746 ),
createObject ( 3095, 389.5, -1630.8, 44.2, 0, 90, 263.743 ),
createObject ( 3095, 395.5, -1627.1, 44.2, 0, 90, 263.743 ),
createObject ( 3095, 395.20001, -1628.9, 40.9, 0, 90, 263.743 ),
createObject ( 3095, 395.10001, -1630.2, 36.4, 0, 90, 263.743 ),
createObject ( 3095, 389.10001, -1633.2, 36.4, 0, 90, 263.743 ),
createObject ( 3095, 382.10001, -1635.1, 36.4, 0, 90, 262.993 ),
createObject ( 3095, 373.5, -1634, 36.4, 0, 90, 262.991 ),
createObject ( 3095, 363.89999, -1632.8, 36.4, 0, 90, 262.991 ),
createObject ( 3095, 362, -1632.6, 36.4, 0, 90, 262.991 ),
createObject ( 3095, 355.39999, -1630, 36.4, 0, 90, 262.991 ),
createObject ( 3095, 393.39999, -1631.8, 36.4, 0, 90, 353 ),
createObject ( 3095, 387.10001, -1632.9, 36.4, 0, 90, 352.996 ),
createObject ( 3095, 381, -1633.2, 36.4, 0, 90, 352.996 ),
createObject ( 3095, 374.89999, -1633.2, 36.4, 0, 90, 352.996 ),
createObject ( 3095, 368.89999, -1632.4, 36.4, 0, 90, 352.996 ),
createObject ( 3095, 363, -1631, 36.4, 0, 90, 352.996 ),
createObject ( 3095, 357.10001, -1629.3, 36.4, 0, 90, 352.996 ),
createObject ( 3095, 351.29999, -1626.8, 36.4, 0, 90, 352.996 ),
createObject ( 3095, 345.60001, -1623.3, 36.4, 0, 90, 352.996 ),
createObject ( 3095, 393.60001, -1630.2, 44.5, 0, 90, 352.996 ),
createObject ( 3095, 387.10001, -1632.9, 44.5, 0, 90, 352.996 ),
createObject ( 3095, 381, -1633.2, 44.5, 0, 90, 352.996 ),
createObject ( 3095, 374.89999, -1633.2, 44.5, 0, 90, 352.996 ),
createObject ( 3095, 368.89999, -1632.4, 44.5, 0, 90, 352.996 ),
createObject ( 3095, 362.79999, -1631, 44.5, 0, 90, 355.496 ),
createObject ( 3095, 356.89999, -1629.2, 44.5, 0, 90, 355.496 ),
createObject ( 3095, 351.29999, -1625.2, 44.5, 0, 90, 355.496 ),
createObject ( 3095, 345.60001, -1621.9, 40.7, 0, 90, 355.496 ),
createObject ( 3095, 345.70001, -1620.2, 44.7, 0, 90, 355.496 ),
createObject ( 6959, 548.5, -1755.1, 11.9, 0, 0, 355.75 ),
createObject ( 6959, 496.5, -1751, 11.8, 0, 0, 358.249 ),
createObject ( 2951, 496.89999, -1361.3, 20.4, 90, 5.548, 49.202 ),
createObject ( 2978, 500.10001, -1359, 20.2, 0, 0, 23 ),
createObject ( 2951, 842.59998, -1062.8, 32.5, 90, 0, 305 ),
createObject ( 2951, 839.40002, -1058.2, 32.5, 90, 0, 303.247 ),
createObject ( 2951, 839.20001, -1056.5, 32.5, 90, 0, 249.995 ),
createObject ( 2951, 841.20001, -1053.9, 32.5, 90, 0, 215.494 ),
createObject ( 2978, 835.40002, -1056.9, 32.7, 0, 180, 354 ),
createObject ( 2978, 835.5, -1056, 32.7, 0, 179.995, 353.996 ),
createObject ( 2978, 835.70001, -1055.1, 32.7, 0, 179.995, 339.996 ),
createObject ( 2978, 836, -1054.5, 32.7, 0, 179.995, 334.244 ),
createObject ( 2978, 836.59998, -1053.7, 32.7, 0, 179.995, 316.994 ),
createObject ( 2978, 837.70001, -1053, 32.7, 0, 179.995, 313.239 ),
createObject ( 17968, 2442.3999, -1641.8, 26.9 ),
createObject ( 3095, 1300.5, -965.70001, 34.6, 0, 90, 270 ),
createObject ( 6959, -2177.3999, 238.3, 50.5 ),
createObject ( 6959, -2177.2, 265.70001, 50.5, 0.04, 0.04, 0.07 ),
createObject ( 6959, -2218.5, 265.60001, 50.5, 0.038, 0.038, 0.066 ),
createObject ( 6959, -2218.6001, 239.10001, 50.5, 0.07, 0, 0.04 ),
createObject ( 2951, -2241.8999, 282.89999, 50.2, 90, 0, 90 ),
createObject ( 2951, -2241.8999, 277.29999, 50.2, 90, 0, 90 ),
createObject ( 2951, -2241.8999, 271.60001, 50.2, 90, 0, 90 ),
createObject ( 2951, -2240.2, 266.20001, 50.2, 90, 0, 128 ),
createObject ( 2951, -2241.8999, 233.10001, 50.2, 90, 0, 90 ),
createObject ( 2951, -2241.8999, 227.5, 50.2, 90, 0, 90 ),
createObject ( 2951, -2241.8999, 221.89999, 50.2, 90, 0, 90 ),
createObject ( 2951, -2240.1001, 238.10001, 50.2, 90, 0, 50.5 ),
createObject ( 10793, 381.20001, -2069.1001, 26.9, 0, 0, 270 ),
createObject ( 3095, 1955, -1557.1, 16.1, 0, 0, 314.5 ),
createObject ( 3095, 1941.6, -1557.6, 16.1, 0, 0, 314.995 ),
createObject ( 3095, 1938.1, -1554.1, 16.1, 0, 0, 314.995 ),
createObject ( 3095, 1951.2, -1580.2, 16.1, 0, 0, 314.995 ),
createObject ( 3095, 1957.5, -1586.5, 16.1, 0, 0, 314.995 ),
createObject ( 3095, 1959.8, -1588.9, 16.1, 0, 0, 314.995 ),
createObject ( 3095, 1994.5, -1586.6, 16.1, 0, 0, 314.995 ),
createObject ( 3095, 1998.7, -1590.8, 16.1, 0, 0, 314.995 ),
createObject ( 3095, 2007.8, -1591, 16.1, 0, 0, 314.995 ),
createObject ( 3095, 2018.7, -1591, 16.1, 0, 0, 314.995 ),
createObject ( 17031, -637.70001, -1701.3, 43.4, 348, 0, 64 ),
createObject ( 17031, -623.70001, -1701.1, 43.4, 347.997, 0, 63.995 ),
createObject ( 17031, -596.70001, -1715.8, 43.4, 347.997, 0, 63.995 ),
createObject ( 17031, -581.70001, -1735.2, 43.4, 347.997, 0, 47.995 ),
createObject ( 744, -613, -1898.9, 0.7 ),
createObject ( 744, -611.20001, -1897.2, 0.7 ),
createObject ( 744, -613.70001, -1896.4, 0.7 ),
createObject ( 744, -615.40002, -1898.7, 0.7, 0, 1.25, 0.75 ),
createObject ( 899, -759.20001, -1847.7, 16.3, 38, 0, 0 ),
createObject ( 6959, 239, 1795.3, 16.6 ),
createObject ( 6959, 195.5, 1794.5, 16.6 ),
createObject ( 2951, 689.59998, -1426.1, 17.5, 0, 0, 90 ),
createObject ( 2951, 1865.3, 2075.3, 12.4 ),
createObject ( 2951, 1865.2, 2074.8, 12.4 ),
createObject ( 684, 1866.4, 2075, 15.7, 0, 140, 90 ),
createObject ( 684, 1866.3, 2075.2, 15.74, 0, 212.499, 90 ),
createObject ( 3095, 874.09998, -1563.1, 15.9, 0, 0, 22 ),
}) do
setElementInterior(v,3)
setElementDimension(v,10)
end
|
-- Level object definition
Level = {}
--Level.__index = Level
local function CreateBallPos( self, i, num )
x = (self:Random():Get() % 5) - 2
y = 15 + i
return x, y
end
local function CreateGemPos()
return gemCreateXPos, 15
end
local function CreateBombPos()
return 0, 19
end
local function InitFunc()
end
local function ShutdownFunc()
end
local function StartGameFunc()
end
local function EndGameFunc()
end
local function UpdateFunc()
end
function Level.New( id, name )
if DEBUG then
assert( id )
assert( name )
end
ret = {}
ret.Init = InitFunc
ret.Shutdown = ShutdownFunc
ret.CreateBallPos = CreateBallPos
ret.CreateGemPos = CreateGemPos
ret.CreateBombPos = CreateBombPos
ret.StartGame = StartGameFunc
ret.EndGame = EndGameFunc
ret.UpdateFunc = UpdateFunc
ret.m_id = id
ret.m_name = name
ret.m_type = {} --kLevelTypeNormal
ret.m_world = {}
ret.m_rackSize = {}
ret.m_year = {}
ret.m_description = {}
ret.m_wikiLink = {}
ret.m_random = FCRandom.New( id )
ret.m_numRacks = {}
ret.m_time = {}
ret.m_tutorial = false
ret.m_locked = true
ret.mt = {}
ret.mt.__index = Level
ret.mt.__newindex = function() error() end
setmetatable( ret, ret.mt )
return ret
end
function Level:Reset( )
self.m_random = FCRandom.New( self.m_id )
end
function Level:SetLocked( status )
self.m_locked = status
end
function Level:Locked()
return self.m_locked
end
function Level:SetTutorial( tut )
self.m_tutorial = tut
end
function Level:Tutorial()
return self.m_tutorial
end
function Level:SetUpdateFunc( func )
self.UpdateFunc = func
end
function Level:SetInitFunc( func )
self.Init = func
end
function Level:SetShutdownFunc( func )
self.Shutdown = func
end
function Level:SetStartGameFunc( func )
self.StartGame = func
end
function Level:SetEndGameFunc( func )
self.EndGame = func
end
--function Level:StartGameFunc( )
-- return self.StartGame
--end
function Level:SetCreateBallFunc( func )
self.CreateBallPos = func
end
function Level:SetCreateGemFunc( func )
self.CreateGemPos = func
end
function Level:SetCreateBombFunc( func )
self.CreateBombPos = func
end
-- Id
function Level:Id()
return self.m_id
end
-- Type
function Level:SetType( type )
if DEBUG then
assert( type )
end
self.m_type = type
end
function Level:Type()
return self.m_type
end
-- Name
function Level:Name()
if self.m_locked then
return kWord_Locked
end
return self.m_name
end
-- World
function Level:SetWorld( world )
self.m_world = world
end
function Level:World()
return self.m_world
end
-- RackSize
function Level:SetRackSize( size )
self.m_rackSize = size
end
function Level:RackSize()
return self.m_rackSize
end
-- NumRacks
function Level:SetNumRacks( numRacks )
self.m_numRacks = numRacks
end
function Level:NumRacks()
return self.m_numRacks
end
-- Time
function Level:SetTime( time )
self.m_time = time
end
function Level:Time()
return self.m_time
end
-- Year
function Level:SetYear( year )
self.m_year = year
end
function Level:Year()
return self.m_year
end
-- Description
function Level:SetDescription( desc )
self.m_description = desc
end
function Level:Description()
return self.m_description
end
-- WikiLink
function Level:SetWikiLink( link )
self.m_wikiLink = link
end
function Level:WikiLink()
return self.m_wikiLink
end
-- Random
function Level:Random()
return self.m_random
end
|
---
-- @classmod TaggedTemplateProvider
-- @author Quenty
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local CollectionService = game:GetService("CollectionService")
local RunService = game:GetService("RunService")
local TemplateProvider = require("TemplateProvider")
local TaggedTemplateProvider = setmetatable({}, TemplateProvider)
TaggedTemplateProvider.ClassName = "TaggedTemplateProvider"
TaggedTemplateProvider.__index = TaggedTemplateProvider
function TaggedTemplateProvider.new(containerTagName)
local self = setmetatable(TemplateProvider.new(), TaggedTemplateProvider)
assert(type(containerTagName) == "string")
-- We prefer a default tag name so test scripts can still read assets for testing
self._tagsToInitializeSet = { [containerTagName] = true }
return self
end
function TaggedTemplateProvider:Init()
assert(self._tagsToInitializeSet, "Already initialized")
getmetatable(TaggedTemplateProvider).Init(self)
local tags = self._tagsToInitializeSet
self._tagsToInitializeSet = nil
for tag, _ in pairs(tags) do
self:AddContainersFromTag(tag)
end
end
function TaggedTemplateProvider:AddContainersFromTag(containerTagName)
assert(type(containerTagName) == "string")
if self._tagsToInitializeSet then
self._tagsToInitializeSet[containerTagName] = true
else
if RunService:IsRunning() then
self._maid:GiveTask(CollectionService:GetInstanceAddedSignal(containerTagName):Connect(function(inst)
self:AddContainer(inst)
end))
self._maid:GiveTask(CollectionService:GetInstanceRemovedSignal(containerTagName):Connect(function(inst)
self:RemoveContainer(inst)
end))
end
for _, inst in pairs(CollectionService:GetTagged(containerTagName)) do
self:AddContainer(inst)
end
end
end
return TaggedTemplateProvider
|
Inherit = 'ScrollView'
Visible = false
OnSearch = function(self, search)
if search == '' then
self.Visible = false
else
self:BringToFront()
self:RemoveAllObjects()
self.Visible = true
local paths = OneOS.Indexer.Search(search)
local searchItems = {
Folders = {},
Documents = {},
Images = {},
Programs = {},
['System Files'] = {},
Other = {}
}
-- TODO: selected item
for i, path in ipairs(paths) do
local extension = self.Bedrock.Helpers.Extension(path):lower()
if extension ~= 'shortcut' then
path = self.Bedrock.Helpers.TidyPath(path)
local fileType = 'Other'
if extension == 'txt' or extension == 'text' or extension == 'license' or extension == 'md' then
fileType = 'Documents'
elseif extension == 'nft' or extension == 'nfp' or extension == 'skch' or extension == 'paint' then
fileType = 'Images'
elseif extension == 'program' then
fileType = 'Programs'
elseif extension == 'lua' or extension == 'log' or extension == 'settings' or extension == 'version' or extension == 'hash' or extension == 'fingerprint' then
fileType = 'System Files'
elseif fs.isDir(path) then
fileType = 'Folders'
end
if path == selected then
Log.i('found')
foundSelected = true
end
local parentFolder = fs.getName(path:sub(1, #path-#fs.getName(path)-1))
table.insert(searchItems[fileType], {Path = path, Text = self.Bedrock.Helpers.RemoveExtension(fs.getName(path)), Selected = (path == selected), Subtext = parentFolder})
end
end
local y = 2
for name, items in pairs(searchItems) do
if #items ~= 0 then
self:AddObject({
X = 2,
Y = y,
Type = 'FilterLabel',
FilterName = 'Highlight',
Text = name
})
y = y + 1
self:AddObject({
X = 1,
Width = '100%',
Height = #items * 4 - 1,
Y = y,
Type = 'View',
BackgroundColour = colours.grey
-- Type = 'FilterView',
-- FilterName = 'Highlight',
})
for i, item in ipairs(items) do
self:AddObject({
X = 2,
Y = y,
Type = 'ImageView',
Image = OneOS.GetIcon(item.Path),
Width = 4,
Height = 3
})
self:AddObject({
X = 7,
Y = y,
Type = 'Label',
TextColour = colours.white,
Text = item.Text
})
self:AddObject({
X = 7,
Y = y + 1,
Type = 'FilterLabel',
FilterName = 'Highlight',
Text = item.Subtext
})
y = y + 4
end
end
end
if y == 2 then
self:AddObject({
X = 1,
Width = '100%',
Y = 3,
Type = 'FilterLabel',
FilterName = 'Highlight',
Text = 'No Files Found',
Align = 'Center'
})
else
end
end
end
BringToFront = function(self)
for i = #self.Bedrock.View.Children, 1, -1 do
local child = self.Bedrock.View.Children[i]
self.Z = child.Z + 1
break
end
self.Bedrock:ReorderObjects()
end
|
local mStaffLogs = {}
function mStaffLogs.init()
cSync.register("StaffLogs.next", "general.penalties", {heavy = true})
cSync.registerResponder("StaffLogs.next", mStaffLogs.sync.next)
return true
end
cModules.register(mStaffLogs)
mStaffLogs.sync = {}
function mStaffLogs.sync.next(filter, lastID)
return cCommands.findLogs(filter, lastID)
end
|
local lwtk = require("lwtk")
local Application = lwtk.Application
local Column = lwtk.Column
local Row = lwtk.Row
local PushButton = lwtk.PushButton
local TextInput = lwtk.TextInput
local TitleText = lwtk.TitleText
local Space = lwtk.Space
local app = Application("example01.lua")
local function quit()
app:close()
end
local win = app:newWindow {
title = "example01",
Column {
id = "c1",
TitleText { text = "What's your name?" },
TextInput { id = "i1", focus = true, style = { Columns = 40 } },
Row {
Space {},
PushButton { id = "b1", text = "&OK", disabled = true,
default = true },
PushButton { id = "b2", text = "&Quit", onClicked = quit },
Space {}
}
},
Column {
id = "c2",
visible = false,
Space {},
TitleText { id = "t2", style = { TextAlign = "center" } },
Space {},
Row {
Space {},
PushButton { id = "b3", text = "&Again" },
PushButton { id = "b4", text = "&Quit", default = true,
onClicked = quit },
Space {}
}
}
}
win:childById("c1"):setOnInputChanged(function(widget, input)
widget:childById("b1"):setDisabled(input.text == "")
end)
win:childById("b1"):setOnClicked(function(widget)
win:childById("t2"):setText("Hello "..win:childById("i1").text.."!")
win:childById("c1"):setVisible(false)
win:childById("c2"):setVisible(true)
end)
win:childById("b3"):setOnClicked(function(widget)
win:childById("i1"):setText("")
win:childById("i1"):setFocus()
win:childById("t2"):setText("")
win:childById("c1"):setVisible(true)
win:childById("c2"):setVisible(false)
end)
win:show()
app:runEventLoop()
|
hook.Add("OnPlayerChat","justapicbro",function(ply, text)
if string.Replace(text," ","") == "!img" then -- replace !img by a chat command
if ply == LocalPlayer() then
local url = "http://www.thenug.com/sites/default/pub/110816/thenug-to3pFZ324V.jpg" -- replace url by your url
local modifier = 1.5 -- Increase => smaller img
local Window = vgui.Create("DFrame")
Window:SetSize(ScrW()/modifier,ScrH()/modifier)
Window:SetTitle("")
Window:SetVisible(true)
Window:SetDraggable(false)
Window:ShowCloseButton(false)
Window:SetVerticalScrollbarEnabled(false)
function Window:Paint(w,h) end
local html = vgui.Create("DHTML", Window)
html:Dock(FILL)
html:SetHTML([[<div align="center"><img src="]]..url..[[" height="95%" width="auto"></div>]]) -- If scrollbars tweak the height
html:SetAllowLua(false)
Window:Center()
Window:MakePopup()
local quitButton = vgui.Create("DButton",Window)
function quitButton:Paint(w,h) end
quitButton:SetText("x")
quitButton:SetFont("Trebuchet24")
quitButton:SizeToContentsX(10)
quitButton:AlignTop(0)
quitButton:AlignRight(100)
quitButton:SetColor(Color(255,0,0))
quitButton.DoClick = function()
Window:Close()
end
html:SetScrollbars(false)
end
end
end)
|
possibleMissions = {}
local killtownies = {
name = "Kill Townies",
description = "Those weaklings in town have forgotten that life is nasty, brutish, and short. Remind them that safety is an illusion by killing 5 townspeople.",
finished_description = "The weaklings have been reminded what fear is."
}
function killtownies:start()
local godname = currWorld.factions['barbariangod'].name
output:out(godname .. " roars in approval.")
return godname .. " roars in approval."
end
function killtownies:kills(killer,victim)
if killer == player and victim.id == "townsperson" then
local townies = update_mission_status('killtownies',1)
if townies < 5 then
output:out("You've killed " .. townies .. " townspeople. " .. 5-townies .. " to go.")
elseif townies == 5 then
output:out("You've killed 5 townspeople. Return to the altar.")
end
end
end
function killtownies:get_status(status)
if not status then status = get_mission_status('killtownies') end
if status < 5 then
return "You still need to kill " .. 5-status .. " townspeople."
else
return "The townspeople have been reminded what fear is. Return to the altar."
end
end
function killtownies:can_finish()
local townies = get_mission_status('killtownies')
if townies >= 5 then
return true
end
return false,"You still need to kill " .. 5-townies .. " townspeople."
end
function killtownies:finish()
output:out("The townspeople have been reminded what fear is.")
player.favor.barbariangod = player.favor.barbariangod + 100
return "The townspeople have been reminded what fear is."
end
possibleMissions['killtownies'] = killtownies
local killdemons = {
name = "Kill Demons",
description = "Prove you have what it takes to be a demonslayer. Kill 5 demons.",
finished_description = "You have proven your worth as a demonslayer, but many unholy beasts still infest this world.",
}
function killdemons:start()
return "You pledge to kill 5 demons."
end
function killdemons:kills(killer,victim)
if killer == player and victim:is_type('demon') then
local demons = update_mission_status('killdemons',1)
if demons < 5 then
output:out("You've killed " .. demons .. " demons. " .. 5-demons .. " to go.")
elseif demons == 5 then
output:out("You've killed 5 demons. Return to " .. currWorld.factions.lightchurch.name .. ".")
end
end
end
function killdemons:get_status(status)
if not status then status = get_mission_status('killdemons') end
if status < 5 then
return "You still need to kill " .. 5-status .. " demons."
else
return "You have slain 5 unholy demons. Return to " .. currWorld.factions.lightchurch.name .. "."
end
end
function killdemons:can_finish()
local demons = get_mission_status('killdemons')
if demons >= 5 then
return true
end
return false,"You still need to kill " .. 5-demons .. " demons."
end
function killdemons:finish()
output:out("You have done a holy service to the world.")
player.favor.lightchurch = player.favor.lightchurch + 100
return "You have done a holy service to the world."
end
possibleMissions['killdemons'] = killdemons
local ascend = {
name = "Ascend as a Hero",
description = "Prove yourself a true hero by making your way to the Hall of Heroes at the bottom of the dungeon and ascending to Valhalla.",
status_text = {[0] = "Unlock the first Valhalla Gate with a Hero's Key.", [1] = "Unlock the second Valhalla Gate with a Hero's Key.",[2] = "Ascend to Valhalla as a True Hero."}
}
possibleMissions['ascend'] = ascend
local findtreasure = {
name = "Treasure Hunting",
description = "Seek out a hidden treasure.",
repeating = true
}
function findtreasure:start()
local treasure = Item('treasure')
treasure.properName = namegen:generate_weapon_name()
set_mission_data('findtreasure','item',treasure)
return "You seek " .. treasure:get_name() .. "."
end
function findtreasure:get_status()
local treasure = get_mission_data('findtreasure','item')
local source = get_mission_data('findtreasure','source')
if not player:has_specific_item(treasure) then
return "You seek " .. treasure:get_name() .. "."
else
return "You've acquired " .. treasure:get_name() .. ". Return it to " .. (source.baseType == "creature" and source:get_name() or source.name) .. "."
end
end
function findtreasure:enter_map()
local treasure = get_mission_data('findtreasure','item')
if not treasure.placed then
currMap:add_item(treasure,player.x,player.y)
treasure.placed=true
end
end
function findtreasure:can_finish()
local treasure = get_mission_data('findtreasure','item')
if player:has_specific_item(treasure) then
return true
else
return false,"You seek " .. treasure:get_name() .. "."
end
end
function findtreasure:finish()
local treasure = get_mission_data('findtreasure','item')
treasure:delete()
local favor = nil
local source = get_mission_data('findtreasure','source')
if source and source.baseType == "faction" then
favor = 100
player.favor[source.id] = player.favor[source.id]+favor
end
return "You turn in " .. treasure:get_name() .. (favor and " for " .. favor .. " favor." or ".")
end
possibleMissions['findtreasure'] = findtreasure
|
--
-- Mark work as running
--
local dataKey = KEYS[1]
local stateKey = KEYS[2]
local countKey = KEYS[3]
local scheduledKey = KEYS[4]
local queuedKey = KEYS[5]
local runningKey = KEYS[6]
local completedKey = KEYS[7]
local canceledKey = KEYS[8]
local id = ARGV[1]
local state = ARGV[2]
local data = ARGV[3]
redis.call('HSET', dataKey, id, data)
return {
redis.call('HINCRBY', countKey, scheduledKey, 0),
redis.call('HINCRBY', countKey, runningKey, 0),
redis.call('HINCRBY', countKey, completedKey, 0),
redis.call('HINCRBY', countKey, canceledKey, 0),
}
|
--------------------------------
-- Script by: RakkorZ - ZxOxZ --
-- Requires: LuaHypArc --
--------------------------------
WEATHER = {}
--Weather Commands.
WEATHER.Command.Normal = "#weather normal"
WEATHER.Command.Foggy = "#weather foggy"
WEATHER.Command.Rainy = "#weather rainy"
WEATHER.Command.HeavyRain = "#weather heavyrain"
WEATHER.Command.Snowy = "#weather snowy"
WEATHER.Command.SandStorm = "#weather sandstorm"
--Weather Functions.
function WEATHER.OnChat(event, player, message, type, language)
local WeatherMessage = message:lower()
if (WeatherMessage:find(WEATHER.Command.Normal) == 1) then
player:SetPlayerWeather(0, 2)
return 0
end
if (WeatherMessage:find(WEATHER.Command.Foggy) == 1) then
player:SetPlayerWeather(1, 2)
return 0
end
if (WeatherMessage:find(WEATHER.Command.Rainy) == 1) then
player:SetPlayerWeather(2, 2)
return 0
end
if (WeatherMessage:find(WEATHER.Command.HeavyRain) == 1) then
player:SetPlayerWeather(4, 2)
return 0
end
if (WeatherMessage:find(WEATHER.Command.Snowy) == 1) then
player:SetPlayerWeather(8, 2)
return 0
end
if (WeatherMessage:find(WEATHER.Command.SandStorm) == 1) then
player:SetPlayerWeather(16, 2)
return 0
end
end
RegisterServerHook(16, "WEATHER.OnChat")
|
one_handed_curved_sword = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "",
directObjectTemplate = "object/weapon/melee/sword/sword_02.iff",
craftingValues = {
{"mindamage",18,33,0},
{"maxdamage",70,130,0},
{"attackspeed",4,2.8,1},
{"woundchance",12,24,0},
{"hitpoints",750,1500,0},
{"zerorangemod",-2,8,0},
{"maxrangemod",-2,8,0},
{"midrange",3,3,0},
{"midrangemod",-2,8,0},
{"maxrange",4,4,0},
{"attackhealthcost",23,13,0},
{"attackactioncost",52,28,0},
{"attackmindcost",33,18,0},
},
customizationStringNames = {},
customizationValues = {},
-- randomDotChance: The chance of this weapon object dropping with a random dot on it. Higher number means less chance. Set to 0 to always have a random dot.
randomDotChance = 625,
junkDealerTypeNeeded = JUNKARMS,
junkMinValue = 25,
junkMaxValue = 45
}
addLootItemTemplate("one_handed_curved_sword", one_handed_curved_sword)
|
local collation = require "tools.collation"
describe("Collation test", function()
local collator = collation.new()
it("should load the DUCET file", function()
assert.same(type(collator.load_ducet), "function")
local ducet_file = io.open("data/allkeys.txt", "r")
local content = ducet_file:read("*all")
collator:load_ducet(content)
ducet_file:close()
assert.same(type(collator.keys), "table")
local sorted_table = {}
-- local s = "příliš žluťoučký kůň úpěl ďábelské ódy"
local s = "aábcčdďeéěfghchiíjklmnňoópqrřsštťuúůvwxyýzžAÁBCČDĎEÉĚFGHCHIÍJKLMNŇOÓPQRŘSŠTŤUÚŮVWXYÝZŽ"
for _, codepoint in utf8.codes(s) do
-- for i = 1, utf8.len(s) do
-- codepoint = utf8.codepoint(s, i)
-- for pos, codepoint in ipairs(utf8.codepoint()) do
-- for pos, codepoint in ipairs(utf8.codepoint("příliš žluťoučký kůň úpěl ďábelské ódy")) do
local key = collator.keys[codepoint]
local values = key.value or {}
local primary_keys = {}
for _, x in ipairs(values) do
primary_keys[#primary_keys+1] = x[1]
end
sorted_table[#sorted_table+1] = {key = primary_keys[1], codepoint = codepoint}
-- print(utf8.char(codepoint), table.concat(primary_keys, ";"))
end
table.sort(sorted_table, function(a,b) return a.key < b.key end)
local t = {}
for _, x in ipairs(sorted_table) do
t[#t+1] = utf8.char(x.codepoint) .. ":" .. x.key ..";"
end
print(table.concat(t))
end)
end)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.