content
stringlengths
5
1.05M
print("initialized textures") --[[ The Mineclone 2 Unofficial Official Texture Pack is located here https://forum.minetest.net/viewtopic.php?f=4&t=18559. Creative Commons Attribution-ShareAlike 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License (Public License). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 – Definitions. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. Licensor means the individual(s) or entity(ies) granting rights under this Public License. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 – Scope. License grant. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: reproduce and Share the Licensed Material, in whole or in part; and produce, reproduce, and Share Adapted Material. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. Term. The term of this Public License is specified in Section 6(a). Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. Downstream recipients. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). Other rights. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. Patent and trademark rights are not licensed under this Public License. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. Section 3 – License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. Attribution. If You Share the Licensed Material (including in modified form), You must: retain the following if it is supplied by the Licensor with the Licensed Material: identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); a copyright notice; a notice that refers to this Public License; a notice that refers to the disclaimer of warranties; a URI or hyperlink to the Licensed Material to the extent reasonably practicable; indicate if You modified the Licensed Material and retain an indication of any previous modifications; and indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. ShareAlike. In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. Section 4 – Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 – Disclaimer of Warranties and Limitation of Liability. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 – Term and Termination. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or upon express reinstatement by the Licensor. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 – Other Terms and Conditions. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 – Interpretation. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. ]]--
local M = {} function M.setup(opts) local schemastore_status_ok, schemastore = pcall(require, "schemastore") if schemastore_status_ok then opts["settings"] = { json = { schemas = schemastore.json.schemas(), }, } -- require("svim.utils").print_table(opts.settings.json) end return opts end return M
local module = {async = true} local probability = require(game:GetService('ReplicatedStorage').Common.Probability) local alignments = { {item = 'masculine', chance = 66.6}, {item = 'feminine', chance = 33.4}, } function module.Random(info) return probability.Choose(alignments, info.seed) end function module.Start(info) if info.noGenerating then return end local npc = info.model local seed = npc:GetAttribute('seed') if not seed then seed:GetAttributeChangedSignal('seed'):Wait() seed = npc:GetAttribute('seed') end info.seed = Random.new(seed) info.alignment = info.alignment or module.Random(info) end return module
CloneClass( ECMJammerBase )
TatooineAnchorheadScreenPlay = ScreenPlay:new { numberOfActs = 1, screenplayName = "TatooineAnchorheadScreenPlay" } registerScreenPlay("TatooineAnchorheadScreenPlay", true) function TatooineAnchorheadScreenPlay:start() if (isZoneEnabled("tatooine")) then self:spawnMobiles() self:spawnSceneObjects() end end function TatooineAnchorheadScreenPlay:spawnSceneObjects() --Tavern spawnSceneObject("tatooine", "object/mobile/le_repair_droid.iff", -0.3, -4.0, -3.7, 1213349, math.rad(90) ) end function TatooineAnchorheadScreenPlay:spawnMobiles() --Tavern local pNpc = spawnMobile("tatooine", "borra_setas",60,9.51111,0.408271,-0.736723,320.12,1213345) self:setMoodString(pNpc, "worried") pNpc = spawnMobile("tatooine", "commoner_tatooine",60,-9.4,0.4,2.0,161,1213345) self:setMoodString(pNpc, "npc_standing_drinking") spawnMobile("tatooine", "trainer_doctor",0,1.53792,1.00421,6.82596,265,1213346) spawnMobile("tatooine", "rebel_recruiter",60,-6.22005,-3.96617,-6.58904,194.653,1213349) --Tavern west pNpc = spawnMobile("tatooine", "bounty_hunter",60,7.7,-4.0,-4.0,138,3355393) self:setMoodString(pNpc, "angry") pNpc = spawnMobile("tatooine", "businessman",60,8.5,-4.0,-5.3,-37,3355393) self:setMoodString(pNpc, "worried") pNpc = spawnMobile("tatooine", "commoner_technician",60,8.4,0.4,-9.5,126,3355387) self:setMoodString(pNpc, "neutral") pNpc = spawnMobile("tatooine", "commoner_fat",60,-8.8,1.0,6.5,-99,3355388) self:setMoodString(pNpc, "happy") --Outside spawnMobile("tatooine", "commoner",60,-144.579,65,-5301.04,250.798,0) spawnMobile("tatooine", "commoner_naboo",60,134.869,52,-5333.14,67.0208,0) spawnMobile("tatooine", "commoner_old",60,73.2491,52,-5329.48,324.6,0) spawnMobile("tatooine", "commoner_old",60,70.2339,52,-5316.54,358.449,0) spawnMobile("tatooine", "commoner_tatooine",60,83.9686,52,-5390.23,61.1388,0) spawnMobile("tatooine", "commoner_tatooine",60,74.6127,52,-5382.24,106.067,0) spawnMobile("tatooine", "commoner_tatooine",60,59.0963,52,-5342.29,282.005,0) spawnMobile("tatooine", "commoner_tatooine",60,39.6087,52,-5345.06,179.67,0) spawnMobile("tatooine", "commoner_tatooine",60,150.383,52,-5327.33,143.663,0) spawnMobile("tatooine", "commoner_tatooine",60,123.408,52,-5377.31,88.9686,0) spawnMobile("tatooine", "commoner_tatooine",60,114.69,52,-5404.19,89.678,0) pNpc = spawnMobile("tatooine", "commoner_technician",60,-108.399,65,-5298.05,0,0) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile("tatooine", "bounty_hunter",300,-162.748,65,-5312.84,0,0) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile("tatooine", "scavenger",300,-108.399,65,-5297.05,180.005,0) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile("tatooine", "mercenary",60,-162.748,65,-5311.84,180.005,0) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile("tatooine", "r3",60,-180.482,65,-5314.98,96.2472,0) self:setMoodString(pNpc, "calm") pNpc = spawnMobile("tatooine", "r3",60,116.569,52,-5341.57,2.26464,0) self:setMoodString(pNpc, "calm") pNpc = spawnMobile("tatooine", "r4",60,75.9409,52,-5355.36,178.447,0) self:setMoodString(pNpc, "calm") pNpc = spawnMobile("tatooine", "businessman", 60, -143.907, 65, -5335.05, 0, 0) self:setMoodString(pNpc, "conversation") pNpc = spawnMobile("tatooine", "pilot", 60, -143.907, 65, -5334.05, 180.005, 0) self:setMoodString(pNpc, "conversation") spawnMobile("tatooine", "junk_dealer", 0, 110.87, 52, -5428.19, 53, 0) spawnMobile("tatooine", "bantha",300,216.9,11.7,-5425.4,-121,0) spawnMobile("tatooine", "specforce_technician",400,65.685,52,-5349.49,-4,0) spawnMobile("tatooine", "specforce_technician",400,49.2,52,-5351,350,0) spawnMobile("tatooine", "specforce_technician",400,125.5,52,-5416,279.008,0) spawnMobile("tatooine", "specforce_technician",400,55.2,52.6,-5332.5,184.005,0) spawnMobile("tatooine", "specforce_heavy_weapons_specialist",400,68,52,-5382,67,0) spawnMobile("tatooine", "rebel_specforce_captain",400,67,52,-5366.5,95,0) spawnMobile("tatooine", "rebel_specforce_captain",400,31.4,51.1006,-5350.3,203.975,0) spawnMobile("tatooine", "rebel_specforce_pathfinder",400,31,51.9725,-5337,270.008,0) spawnMobile("tatooine", "rebel_specforce_pathfinder",400,76.5,52,-5361.1,329.737,0) spawnMobile("tatooine", "rebel_specforce_pathfinder",400,135.1,52,-5374.9,83.0024,0) spawnMobile("tatooine", "rebel_specforce_pathfinder",400,123.6,52,-5368,235,0) spawnMobile("tatooine", "rebel_specforce_pathfinder",400,89.9,52,-5393.8,313.009,0) spawnMobile("tatooine", "rebel_specforce_pathfinder",400,151,52,-5316,37.8685,0) spawnMobile("tatooine", "rebel_specforce_pathfinder",400,159,52,-5320,331.012,0) spawnMobile("tatooine", "cu_pa",300,75.5625,88.9439,-5217.41,276.531,0) spawnMobile("tatooine", "cu_pa",300,81.1976,85.0672,-5200.6,174.759,0) spawnMobile("tatooine", "cu_pa",300,14.564,23.6794,-5543.66,99.0125,0) spawnMobile("tatooine", "cu_pa",300,26.8762,12.236,-5564.46,284.743,0) spawnMobile("tatooine", "cu_pa",300,163.943,12.072,-5473.22,272.381,0) spawnMobile("tatooine", "cu_pa",300,210.837,16.4247,-5464.01,32.0514,0) spawnMobile("tatooine", "cu_pa",300,188.14,9.71503,-5485.52,63.2364,0) spawnMobile("tatooine", "cu_pa",300,186.305,14.9233,-5467.36,145.471,0) spawnMobile("tatooine", "cu_pa",300,166.736,4.42212,-5483.28,304.088,0) spawnMobile("tatooine", "rebel_recruiter",60,69.6872,52,-5349.47,360.011,0) spawnMobile("tatooine", "rill",300,3.34558,86.6525,-5245.25,82.0905,0) spawnMobile("tatooine", "rill",300,-26.4483,85.5717,-5227.67,257.612,0) spawnMobile("tatooine", "rill",300,-4.51558,88.9463,-5226.49,314.221,0) spawnMobile("tatooine", "rill",300,16.8025,87.749,-5249.62,280.51,0) spawnMobile("tatooine", "zucca_boar",300,176.37,29.6614,-5228.44,23.7572,0) spawnMobile("tatooine", "zucca_boar",300,177.37,29.3367,-5227.44,202.645,0) spawnMobile("tatooine", "zucca_boar",300,171.993,33.695,-5229.99,181.173,0) spawnMobile("tatooine", "zucca_boar",300,-35.6792,30,-5439.35,11.3066,0) end
local wrap, yield = coroutine.wrap, coroutine.yield local Iterable = require('iterables/Iterable') local ArrayIterable, get = require('class')('ArrayIterable', Iterable) function ArrayIterable:__init(array, map) self._array = array self._map = map end function ArrayIterable:__len() local array = self._array if not array or #array == 0 then return 0 end local map = self._map if map then -- map can return nil return Iterable.__len(self) else return #array end end function get.first(self) local array = self._array if not array or #array == 0 then return nil end local map = self._map if map then for i = 1, #array, 1 do local v = array[i] local obj = v and map(v) if obj then return obj end end else return array[1] end end function get.last(self) local array = self._array if not array or #array == 0 then return nil end local map = self._map if map then for i = #array, 1, -1 do local v = array[i] local obj = v and map(v) if obj then return obj end end else return array[#array] end end function ArrayIterable:iter() local array = self._array if not array or #array == 0 then return function() -- new closure for consistency return nil end end local map = self._map if map then return wrap(function() for _, v in ipairs(array) do local obj = map(v) if obj then yield(obj) end end end) else local i = 0 return function() i = i + 1 return array[i] end end end return ArrayIterable
package("libjpeg") set_homepage("http://ijg.org/") set_description("A widely used C library for reading and writing JPEG image files.") set_urls("http://www.ijg.org/files/jpegsrc.$(version).tar.gz") add_versions("v9c", "650250979303a649e21f87b5ccd02672af1ea6954b911342ea491f351ceb7122") add_versions("v9b", "240fd398da741669bf3c90366f58452ea59041cacc741a489b99f2f6a0bad052") on_install("windows", function (package) os.mv("jconfig.vc", "jconfig.h") os.vrun("nmake -f makefile.vc") os.cp("*.h", package:installdir("include")) os.cp("libjpeg.lib", package:installdir("lib")) end) on_install("linux", "macosx", "iphoneos", "android@linux,macosx", function (package) import("package.tools.autoconf").install(package, {"--enable-shared=no"}) end) on_test(function (package) assert(package:has_cfuncs("jpeg_create_compress(0)", {includes = {"stdio.h", "jpeglib.h"}})) end)
local button = require "skyla.gui.button" local util = {} function util.create_test_button(text, callback) return button.new { normal = "#ui_button_tiny.png", text = text, font = "fonts/animated_32_ffffff.fnt", callback = callback } end return util
--[[ Show what's in the next room, by predicting its seed based on the current seed and RNG offset. Features that are useful for routing are prioritized. Currently shows: - Room rewards, including Boon options. - Charon's shop offerings, if the next room is a shop. - Well shop contents. - Enemy types and wave count. - The room's exits, including: - Reward type in the subsequent room. - Number of exits to the subsequent room. - Whether a well shop is in the subsequent room. ]] ModUtil.RegisterMod("ParasDoorPredictions") local config = { ModName = "Para's Door Predictions", ShowRewardType = true, ShowChaosGates = true, ShowErebusGates = true, ShowFountains = true, ShowPossibleSurvival = true, ShowWellShops = true, ShowStoreOptions = true, ShowUpgradeOptions = true, ShowRerolls = true, ShowExits = true, ShowEncounters = true, ShowEnemies = true, ShowRoomNames = true, ShowCharonBag = true, ShowUsesButtons = true, ShowFatefulTwist = true, PrintRngUses = false, PrintNextSeed = true } if ModConfigMenu then ModConfigMenu.Register(config) end ParasDoorPredictions.Config = config -- Add +/- buttons while the boon details sidebar is open. -- We need normal combat input to be disabled or Zag will attack etc. while -- we're clicking, and break pots or otherwise mess up the RNG. ModUtil.WrapBaseFunction("CreatePrimaryBacking", function( baseFunc ) local components = ScreenAnchors.TraitTrayScreen.Components if config.ShowUsesButtons then components.UsesButtonPlus = CreateScreenComponent({ Name = "LevelUpArrowRight", Scale = 1.5, X = CombatUI.TraitUIStart + 300, Y = 360, Group = "Combat_Menu_TraitTray" }) components.UsesButtonPlus.OnPressedFunctionName = "ParasDoorPredictions__OnUsesButtonPlus" components.UsesButtonMinus = CreateScreenComponent({ Name = "LevelUpArrowLeft", Scale = 1.5, X = CombatUI.TraitUIStart + 300, Y = 420, Group = "Combat_Menu_TraitTray" }) components.UsesButtonMinus.OnPressedFunctionName = "ParasDoorPredictions__OnUsesButtonMinus" end baseFunc() end) function ParasDoorPredictions__OnUsesButtonPlus(screen, button) RandomSynchronize(ParasDoorPredictions.CurrentUses + 1) UpdateRngDisplay() end function ParasDoorPredictions__OnUsesButtonMinus(screen, button) RandomSynchronize(ParasDoorPredictions.CurrentUses - 1) UpdateRngDisplay() end ParasDoorPredictions.Config = config ParasDoorPredictions.Doors = {} ParasDoorPredictions.Dirty = false ParasDoorPredictions.Enabled = false ParasDoorPredictions.LastUpdateRngUses = -1 -- hooks to add / enable / clear the annotations on door function ParasDoorPredictions.AddDoor(door) local annotation = CreateAnnotation(door.ObjectId) ParasDoorPredictions.Doors[door.ObjectId] = { Door = door, Annotation = annotation } ParasDoorPredictions.Dirty = true end function ParasDoorPredictions.Clear() ParasDoorPredictions.Doors = {} ParasDoorPredictions.Dirty = false ParasDoorPredictions.Enabled = false ParasDoorPredictions.LastUpdateRngUses = -1 end function ParasDoorPredictions.Enable() ParasDoorPredictions.Enabled = true end ModUtil.WrapBaseFunction("AssignRoomToExitDoor", function(baseFunc, door, room) baseFunc(door, room) ParasDoorPredictions.AddDoor(door) end, ParasDoorPredictions) ModUtil.WrapBaseFunction("DoUnlockRoomExits", function(baseFunc, run, room) ParasDoorPredictions.Enable() baseFunc(run, room) end, ParasDoorPredictions) ModUtil.WrapBaseFunction("RandomSetNextInitSeed", function(baseFunc, args) ParasDoorPredictions.Clear() baseFunc(args) if config.PrintNextSeed then print("RandomSetNextInitSeed:", ParasDoorPredictions.CurrentUses, NextSeeds[1]) end end, ParasDoorPredictions) ParasDoorPredictions.WellMenu = nil ModUtil.WrapBaseFunction("CreateStoreButtons", function(baseFunc, ...) local r = baseFunc(...) ParasDoorPredictions.WellMenu = {} local components = CurrentRun.CurrentRoom.Store.Screen.Components for itemIndex = 1, 3 do local item = CurrentRun.CurrentRoom.Store.StoreOptions[itemIndex] if item and item.Name == "RandomStoreItem" then local itemLocationX = ShopUI.ShopItemStartX local itemLocationY = ShopUI.ShopItemStartY + (itemIndex - 1) * ShopUI.ShopItemSpacerY ParasDoorPredictions.WellMenu.FatefulTwistInfo = CreateScreenComponent({ Name = "BlankObstacle", Group = "Combat_Menu", X = itemLocationX, Y = itemLocationY }) CreateTextBox({ Id = ParasDoorPredictions.WellMenu.FatefulTwistInfo.Id, Text = "", OffsetX = -245, OffsetY = 23, Font = "AlegreyaSansSCBold", FontSize = 18, Color = Color.Yellow, Justification = "Left"}) end end return r end) function PredictFatefulTwist() -- based on AwardRandomStoreItem if config.ShowFatefulTwist and ParasDoorPredictions.WellMenu and ParasDoorPredictions.WellMenu.FatefulTwistInfo then local args = ConsumableData.RandomStoreItem.UseFunctionArgs local options = {} for i, traitName in pairs( args.Traits ) do if TraitData[traitName] and IsGameStateEligible( CurrentRun, TraitData[traitName]) then table.insert( options, { Name = traitName, Type = "Trait" } ) end end for i, consumableName in pairs( args.Consumables ) do if ConsumableData[consumableName] and StoreItemEligible( CurrentRun, ConsumableData[consumableName]) and ( ConsumableData[consumableName].PurchaseRequirements == nil or IsGameStateEligible( ConsumableData[consumableName].PurchaseRequirements )) then table.insert( options, { Name = consumableName, Type = "Consumable" }) end end local oldUses = ParasDoorPredictions.CurrentUses local tmpRun = DeepCopyTable(CurrentRun) SimulateVoiceLines(tmpRun, GlobalVoiceLines.PurchasedWellShopItemVoiceLines) local randomItem = GetRandomValue( options ) RandomSynchronize(oldUses) -- reset to previous value ModifyTextBox({ Id = ParasDoorPredictions.WellMenu.FatefulTwistInfo.Id, Text = randomItem.Name }) end end ModUtil.WrapBaseFunction("CloseStoreScreen", function(baseFunc, ...) if ParasDoorPredictions.WellMenu and ParasDoorPredictions.WellMenu.FatefulTwistInfo then Destroy({ Ids = { ParasDoorPredictions.WellMenu.FatefulTwistInfo.Id }}) end ParasDoorPredictions.WellMenu = nil return baseFunc(...) end) -- track rng uses ParasDoorPredictions.CurrentSeed = 0 ParasDoorPredictions.CurrentUses = 0 local random = ModUtil.UpValues( ModUtil.GetOriginalBaseValue("RandomInit")) local function printRngUse() local linesToSkip = 1 local linesToPrint = 2 -- log which function caused this use of the RNG if config.PrintRngUses then local traceback = debug.traceback() for line in traceback:gmatch"[^\n]+" do if linesToSkip > 0 then linesToSkip = linesToSkip - 1 elseif (line:match"stack traceback" or line:match"string \"Random\"" or line:match"string \"ParasDoorPredictions\"" or line:match"GetRandomValue" or line:match"RemoveRandomValue" or line:match"tail calls") then else print("Use", ParasDoorPredictions.CurrentUses, line) linesToPrint = linesToPrint - 1 end if linesToPrint == 0 then break end end end end ModUtil.WrapFunction(random, {"Rng", "Seed"}, function(baseFunc, self, s, id) if (id or self.id) == 1 then ParasDoorPredictions.CurrentSeed = s ParasDoorPredictions.CurrentUses = 0 end return baseFunc(self, s, id) end) ModUtil.WrapFunction(random, {"Rng", "Random"}, function(baseFunc, self, a, b) if self.id == 1 then ParasDoorPredictions.CurrentUses = ParasDoorPredictions.CurrentUses + 1 printRngUse() end return baseFunc(self, a, b) end) ModUtil.WrapFunction(random, {"Rng", "RandomGaussian"}, function(baseFunc, self) if self.id == 1 then ParasDoorPredictions.CurrentUses = ParasDoorPredictions.CurrentUses + 1 printRngUse() end return baseFunc(self) end) ModUtil.WrapBaseFunction("RandomSynchronize", function(baseFunc, offset, rngId) local previousPrintState = config.PrintRngUses config.PrintRngUses = false if previousPrintState then print("RandomSynchronize", offset) end baseFunc(offset, rngId) config.PrintRngUses = previousPrintState end) -- For prediction, we often want to run a function "as if" a global table (eg. CurrentRun) is modified in a certain way. -- Copy the relevant functions and modify their environment so these can be overridden. function CloneFunction(func, wrapper) local newEnv = {} setmetatable(newEnv, {__index = _G}) local newFunc = load(string.dump(func), nil, "b", newEnv) return wrapper(newEnv, newFunc) end ParasDoorPredictions.CreateRoom = CloneFunction(CreateRoom, function(env, func) return function(run, roomData, args) env.CurrentRun = run return func(roomData, args) end end) ParasDoorPredictions.AssumedUpgradableGodTraitCount = 0 ModUtil.WrapBaseFunction("UpgradableGodTraitCountAtLeast", function(baseFunc, num) local adjustedNum = num - ParasDoorPredictions.AssumedUpgradableGodTraitCount if adjustedNum <= 0 then return true else return baseFunc(adjustedNum) end end, ParasDoorPredictions) ParasDoorPredictions.ChooseRoomReward = CloneFunction(ChooseRoomReward, function(env, func) return function(run, room, rewardStoreName, previouslyChosenRewards, args) env.CurrentRun = run env.ChooseRoomReward = ParasDoorPredictions.ChooseRoomReward if args.PreviousRoom.ChosenRewardType == "Boon" then ParasDoorPredictions.AssumedUpgradableGodTraitCount = 1 end local result = func(run, room, rewardStoreName, previouslyChosenRewards, args) ParasDoorPredictions.AssumedUpgradableGodTraitCount = 0 return result end end) ParasDoorPredictions.UpdateRunHistoryCache = CloneFunction(UpdateRunHistoryCache, function(env, func) return function(run, roomAdded) env.GameState = { RoomCountCache = {} } return func(run, roomAdded) end end) ParasDoorPredictions.GetRarityChances = CloneFunction(GetRarityChances, function(env, func) return function(run, args) env.CurrentRun = run return func(args) end end) ParasDoorPredictions.CheckCooldown = CloneFunction(CheckCooldown, function(env, func) return function(...) env.GlobalCooldowns = TmpGlobalCooldowns return func(...) end end) TmpActiveScreens = {} function ParasDoorPredictions.IsScreenOpen( flag ) if TmpActiveScreens[flag] ~= nil then return true else return IsScreenOpen( name ) end end ParasDoorPredictions.IsGameStateEligible = CloneFunction(IsGameStateEligible, function(env, func) env.IsScreenOpen = ParasDoorPredictions.IsScreenOpen return func end) ParasDoorPredictions.IsVoiceLineEligible = CloneFunction(IsVoiceLineEligible, function(env, func) env.CheckCooldown = ParasDoorPredictions.CheckCooldown env.IsGameStateEligible = ParasDoorPredictions.IsGameStateEligible return func end) ParasDoorPredictions.FillInShopOptions = CloneFunction(FillInShopOptions, function(env, func) return function(run, ...) env.CurrentRun = run return func(...) end end) -- data ParasDoorPredictions.OverrideExitCount = { RoomSecret01 = 2, RoomSecret02 = 3, RoomSecret03 = 1, B_Combat10 = 2, C_MiniBoss02 = 2, C_Reprieve01 = 2, C_Combat03 = 2, C_Combat04 = 2, C_Combat05 = 2, D_Hub = 5 } ParasDoorPredictions.SecretPointCount = { RoomSimple01 = 1, A_Combat01 = 3, A_Combat02 = 2, A_Combat03 = 2, A_Combat04 = 3, A_Combat05 = 3, A_Combat06 = 3, A_Combat07 = 2, A_Combat08A = 2, A_Combat08B = 3, A_Combat09 = 2, A_Combat10 = 3, A_Combat11 = 4, A_Combat12 = 3, A_Combat13 = 2, A_Combat14 = 2, A_Combat15 = 4, A_Combat16 = 2, A_Combat17 = 4, A_Combat18 = 4, A_Combat19 = 3, A_Combat20 = 3, A_Combat21 = 2, A_Combat24 = 3, A_MiniBoss01 = 1, A_MiniBoss03 = 2, A_MiniBoss04 = 2, B_Intro = 1, B_Combat01 = 1, B_Combat02 = 4, B_Combat03 = 2, B_Combat04 = 2, B_Combat05 = 1, B_Combat06 = 6, B_Combat07 = 2, B_Combat08 = 2, B_Combat09 = 2, B_Combat10 = 1, B_Combat21 = 4, B_Combat22 = 2, B_MiniBoss01 = 1, B_MiniBoss02 = 2, C_Intro = 2, C_Combat01 = 3, C_Combat02 = 2, C_Combat03 = 3, C_Combat04 = 3, C_Combat05 = 3, C_Combat06 = 3, C_Combat08 = 4, C_Combat09 = 4, C_Combat10 = 2, C_Combat11 = 4, C_Combat12 = 3, C_Combat13 = 2, C_Combat14 = 1, C_MiniBoss02 = 3 } ParasDoorPredictions.ChallengeSwitchBaseCount = { A_Combat01 = 2, A_Combat02 = 2, A_Combat03 = 1, A_Combat04 = 1, A_Combat05 = 2, A_Combat06 = 2, A_Combat07 = 1, A_Combat08A = 1, A_Combat08B = 1, A_Combat09 = 2, A_Combat10 = 1, A_Combat11 = 1, A_Combat12 = 1, A_Combat13 = 1, A_Combat14 = 3, A_Combat15 = 2, A_Combat16 = 2, A_Combat17 = 1, A_Combat18 = 2, A_Combat19 = 1, A_Combat20 = 2, A_Combat21 = 1, A_Combat24 = 2, A_PostBoss01 = 2, B_Combat01 = 1, B_Combat02 = 2, B_Combat03 = 2, B_Combat04 = 2, B_Combat05 = 2, B_Combat06 = 2, B_Combat07 = 2, B_Combat08 = 2, B_Combat09 = 1, B_Combat10 = 1, B_Combat21 = 2, B_Combat22 = 3, B_PostBoss01 = 2, C_Combat01 = 2, C_Combat02 = 2, C_Combat03 = 2, C_Combat04 = 2, C_Combat05 = 2, C_Combat06 = 2, C_Combat08 = 2, C_Combat09 = 2, C_Combat10 = 2, C_Combat11 = 2, C_Combat12 = 2, C_Combat13 = 2, C_Combat14 = 2, C_PostBoss01 = 2 } ParasDoorPredictions.RarityColorMap = { Common = Color.BoonPatchCommon, Rare = Color.BoonPatchRare, Epic = Color.BoonPatchEpic, Heroic = Color.BoonPatchHeroic, Legendary = Color.BoonPatchLegendary } TmpPlayedRandomLines = nil TmpPlayingVoiceLines = {} TmpGlobalCooldowns = {} -- like PlayVoiceLines, but assumes neverQueue = true -- and args = nil, which is how it's called in LeaveRoomAudio function SimulateVoiceLines(run, voiceLines, args) if voiceLines == nil then print("SimulateVoiceLines: voiceLines == nil") return end local source = GetLineSource(voiceLines) if source == nil then print("SimulateVoiceLines: source == nil") return end if not ParasDoorPredictions.IsVoiceLineEligible(run, voiceLines, nil, nil, source, nil) then print("SimulateVoiceLines: Ineligible") if voiceLines.PlayedNothingFunctionName ~= nil then print("==== BEGIN KNOWN ISSUE ====") print("voiceLines.PlayedNothingFunctionName", voiceLines.PlayedNothingFunctionName) print("==== END KNOWN ISSUE ====") end return end if TmpPlayingVoiceLines[source] then if voiceLines.Queue == "Interrupt" then print("INTERRUPT!") else return -- assuming neverQueue end end -- PlayVoiceLine, including sublines TmpPlayingVoiceLines[source] = SimulateVoiceLine(run, voiceLines, source, args) end function SimulateVoiceLine(run, line, source, args) local playedSomething = false args = args or {} args.BreakIfPlayed = line.BreakIfPlayed or args.BreakIfPlayed source = GetLineSource(line, source) if source == nil then return end if line.Cue ~= nil then -- no effect on rng -- assume success run.SpeechRecord[line.Cue] = true playedSomething = true if args.BreakIfPlayed then return playedSomething end end if line.RandomRemaining then local eligibleUnplayedLines = {} local allEligibleLines = {} for k, subLine in ipairs(line) do if ParasDoorPredictions.IsVoiceLineEligible(run, subLine, nil, line, source) then table.insert(allEligibleLines, subLine) if not TmpPlayedRandomLines[subLine.Cue] then table.insert(eligibleUnplayedLines, subLine) end end end if not IsEmpty( allEligibleLines ) then local randomLine = nil if IsEmpty( eligibleUnplayedLines ) then -- turn the record over for k, subLine in ipairs(line) do TmpPlayedRandomLines[subLine.Cue] = nil end randomLine = GetRandomValue( allEligibleLines ) else randomLine = GetRandomValue( eligibleUnplayedLines ) end TmpPlayedRandomLines[randomLine.Cue] = true local subLineArgs = ShallowCopyTable(args) if SimulateVoiceLine(run, randomLine, source, sublineArgs) then playedSomething = true if args.BreakIfPlayed or randomLine.BreakIfPlayed or subLineArgs.BreakIfPlayed then return playedSomething end end end else for k, subLine in ipairs( line ) do if ParasDoorPredictions.IsVoiceLineEligible(run, subLine, nil, line, source) then local subLineArgs = ShallowCopyTable(args) if SimulateVoiceLine(run, subLine, source, subLineArgs) then playedSomething = true if args.BreakIfPlayed or subLine.BreakIfPlayed or subLineArgs.BreakIfPlayed then return playedSomething end end end end end return playedSomething end function PredictApprovalProcess(loot) local blockedIndexes = {} for i = 1, TableLength(loot.UpgradeOptions) do table.insert( blockedIndexes, i ) end for i = 1, CalcNumLootChoices() do RemoveRandomValue( blockedIndexes ) end -- Sort traits in the following order: Melee, Secondary, Rush, Range table.sort(loot.UpgradeOptions, function (x, y) local slotToInt = function( slot ) if slot ~= nil then local slotType = slot.Slot if slotType == "Melee" then return 0 elseif slotType == "Secondary" then return 1 elseif slotType == "Ranged" then return 2 elseif slotType == "Rush" then return 3 elseif slotType == "Shout" then return 4 end end return 99 end return slotToInt(TraitData[x.ItemName]) < slotToInt(TraitData[y.ItemName]) end) for itemIndex, itemData in ipairs( loot.UpgradeOptions ) do if Contains( blockedIndexes, itemIndex ) then itemData.Blocked = true end end end function PredictUpgradeOptions(run, lootName, args) args = args or {} local rewardCount = run.LootTypeHistory[lootName] or 0 if run.CurrentRoom.Encounter == nil or run.CurrentRoom.Encounter.EncounterType == "NonCombat" then RandomSynchronize() else -- the game will synchronize to rewardCount + 1, we add -- an extra increment to account for choosing the flavor -- text at the top of the boon menu which is done before -- choosing rewards RandomSynchronize(rewardCount + 2) end local lootData = LootData[lootName] local loot = DeepCopyTable(lootData) if args.ForceCommon then loot.RarityChances = {} loot.ForceCommon = true else loot.RarityChances = ParasDoorPredictions.GetRarityChances(run, loot) end SetTraitsOnLoot(loot) if not args.SpawnOnly then if run.CurrentRoom.Encounter == nil or run.CurrentRoom.Encounter.EncounterType == "NonCombat" then -- the calculation for Approval Process runs when you open the menu, even in non-combat rooms RandomSynchronize(rewardCount + 2) end PredictApprovalProcess(loot) end return loot.UpgradeOptions end function PredictUpgradeOptionsReroll(run, lootName, previousOptions) RandomSynchronize(run.NumRerolls - 1) local oldBoonMenu = TmpActiveScreens["BoonMenu"] TmpActiveScreens["BoonMenu"] = true -- these voice lines play on a thread, and are long enough -- so that once one plays, the subsequent ones don't affect -- the rerolled rewards, so we break once one starts SimulateVoiceLines(run, HeroVoiceLines.UsedRerollPanelVoiceLines, { BreakIfPlayed = true }) TmpActiveScreens["BoonMenu"] = oldBoonMenu local itemNames = {} for i, value in pairs(previousOptions) do table.insert( itemNames, value.ItemName) end local lootData = LootData[lootName] local loot = DeepCopyTable(lootData) loot.RarityChances = ParasDoorPredictions.GetRarityChances(run, loot) SetTraitsOnLoot(loot, { ExclusionNames = { GetRandomValue( itemNames ) } }) PredictApprovalProcess(loot) return loot.UpgradeOptions end function RunWithUpdatedHistory(run) local runCopy = DeepCopyTable(run) table.insert(runCopy.RoomHistory, runCopy.CurrentRoom) ParasDoorPredictions.UpdateRunHistoryCache(runCopy, runCopy.CurrentRoom) return runCopy end function ExitCountForRoom(room) return ParasDoorPredictions.OverrideExitCount[room.Name] or room.NumExits end function IsFountainRoom(room) return Contains(room.LegalEncounters, "HealthRestore") end function IsErebusRoom(room) return Contains(room.LegalEncounters, "ShrineChallengeTartarus") end function PredictLoot(door) local predictions = {} local tmpRoom = DeepCopyTable(door.Room) -- Make a copy of CurrentRun that has the current room -- in the room history. This well make the Is*Eligible -- functions correctly calculate restrictions based -- on run depth, biome depth, etc. local tmpRun = RunWithUpdatedHistory(CurrentRun) local secretPointCount = ParasDoorPredictions.SecretPointCount[tmpRoom.Name] or 0 if secretPointCount > 0 and IsSecretDoorEligible(tmpRun, tmpRoom) then predictions.HasChaosGate = true secretPointCount = secretPointCount - 1 end local hasShrinePointDoor = secretPointCount > 0 and IsShrinePointDoorEligible(tmpRun, tmpRoom) if IsFountainRoom(tmpRoom) then predictions.HasFountain = true end local lootName = nil if tmpRoom.ChosenRewardType == "Boon" then lootName = tmpRoom.ForceLootName elseif tmpRoom.ChosenRewardType == "TrialUpgrade" then lootName = "TrialUpgrade" elseif tmpRoom.ChosenRewardType == "WeaponUpgrade" then lootName = "WeaponUpgrade" elseif tmpRoom.ChosenRewardType == "HermesUpgrade" then lootName = "HermesUpgrade" end local rng = GetGlobalRng() local oldSeed = ParasDoorPredictions.CurrentSeed local oldUses = ParasDoorPredictions.CurrentUses -- Advance the rng to the right position. -- 1. If this is a Chaos room, roll as if we had interacted with it, -- ie. take damage, display health, etc. if tmpRoom.ChosenRewardType == "TrialUpgrade" then -- Interactables CoinFlip(rng) -- SacrificeHealth -- SecretDoorUsedPresentation CoinFlip(rng) -- PlayVoiceLine if door.HealthCost > 0 then CoinFlip(rng) -- DisplayPlayerDamageText CoinFlip(rng) -- DisplayPlayerDamageText end end -- 2. Simulate LeaveRoomPresentation, playing voice lines etc. local exitFunctionName = CurrentRun.CurrentRoom.ExitFunctionName or door.ExitFunctionName or "LeaveRoomPresentation" TmpPlayingVoiceLines = {} TmpPlayedRandomLines = DeepCopyTable(PlayedRandomLines) TmpGlobalCooldowns = DeepCopyTable(GlobalCooldowns) if exitFunctionName == "AsphodelLeaveRoomPresentation" then if CurrentRun.CurrentRoom.ExitVoiceLines ~= nil then SimulateVoiceLines(tmpRun, CurrentRun.CurrentRoom.ExitVoiceLines) else SimulateVoiceLines(tmpRun, GlobalVoiceLines.ExitedAsphodelRoomVoiceLines) end end if door.ExitVoiceLines ~= nil then SimulateVoiceLines(tmpRun, door.ExitVoiceLines) elseif CurrentRun.CurrentRoom.ExitVoiceLines ~= nil then SimulateVoiceLines(tmpRun, CurrentRun.CurrentRoom.ExitVoiceLines) elseif CurrentRun.CurrentRoom.Encounter.ExitVoiceLines ~= nil then SimulateVoiceLines(tmpRun, CurrentRun.CurrentRoom.Encounter.ExitVoiceLines) else if RandomChance(0.17) then if GlobalVoiceLines.GeneralExitVoiceLines ~= nil then SimulateVoiceLines(tmpRun, GlobalVoiceLines.GeneralExitVoiceLines) end if CurrentRun.Hero.Health <= 50 then if GlobalVoiceLines.HealthStatusPostExitVoiceLines ~= nil then SimulateVoiceLines(tmpRun, GlobalVoiceLines.GeneralExitVoiceLines) end end end end -- 3. LeaveRoom, determining the orientation and encounter for the next -- room, and also rolling the well shop if any. -- ExitDirection is set in LeaveRoomPresentation local heroExitIds = GetIdsByType({ Name = "HeroExit" }) local hasExitDirection = (exitFunctionName == "LeaveRoomPresentation" and not IsEmpty(heroExitIds)) or exitFunctionName == "AsphodelLeaveRoomPresentation" if hasExitDirection and tmpRoom.EntranceDirection ~= nil and tmpRoom.EntranceDirection ~= "LeftRight" then -- room orientation is forced else CoinFlip(rng) -- flip room randomly end -- generate encounter, if necessary if tmpRoom.Encounter == nil then local tmpRun = DeepCopyTable(CurrentRun) tmpRoom.Encounter = ChooseEncounter(tmpRun, tmpRoom) end predictions.Encounter = tmpRoom.Encounter -- RunShopGeneration tmpRun.CurrentRoom = tmpRoom -- generate shop, if necessary local hasWellShop = false if IsWellShopEligible(tmpRun, tmpRoom) then hasWellShop = true tmpRun.LastWellShopDepth = currentRun.RunDepthCache tmpRoom.Store = ParasDoorPredictions.FillInShopOptions(tmpRun, { StoreData = StoreData.RoomShop, RoomName = tmpRoom.Name }) predictions.StoreOptions = tmpRoom.Store.StoreOptions end local challengeSwitchBaseCount = ParasDoorPredictions.ChallengeSwitchBaseCount[tmpRoom.Name] or 0 if challengeSwitchBaseCount == 0 or (challengeSwitchBaseCount == 1 and IsChallengeSwitchEligible( tmpRun, challengeSwitchBaseCount ) ) then -- We run shop generation anyways to ensure that the rng is advanced correctly before seeding -- the next room. But only some rooms have spawn locations for a well shop. hasWellShop = false predictions.StoreOptions = nil end if tmpRoom.ChosenRewardType == "Shop" then tmpRoom.Store = ParasDoorPredictions.FillInShopOptions(tmpRun, { StoreData = StoreData[tmpRoom.StoreDataName or "WorldShop"], RoomName = tmpRoom.Name }) predictions.StoreOptions = tmpRoom.Store.StoreOptions end -- Determine the seed of the next room, which we will use for predicting -- what will occur there. local uses = ParasDoorPredictions.CurrentUses local seed = RandomInt(-2147483647, 2147483646) if config.PrintNextSeed then print("PredictLoot: as if", uses, seed) end predictions.Seed = seed -- Predict boon or chaos reward NextSeeds[1] = seed if lootName ~= nil then predictions["UpgradeOptions"] = PredictUpgradeOptions(tmpRun, lootName) -- calls RandomSynchronize end if predictions.StoreOptions ~= nil then for k, item in pairs(predictions.StoreOptions) do if item.Args == nil then item.Args = {} end if item.Name == "HermesUpgradeDrop" then item.Args["ForceLootName"] = "HermesUpgrade" end if item.Name == "BlindBoxLoot" then -- ChooseLoot local eligibleLootNames = GetEligibleLootNames() RandomSynchronize() item.Args["ForceLootName"] = GetRandomValue(eligibleLootNames) end if item.Args.ForceLootName ~= nil then item.Args["UpgradeOptions"] = PredictUpgradeOptions(tmpRun, item.Args.ForceLootName) -- calls RandomSynchronize() end end end -- StartRoom() if tmpRun.CurrentRoom.WingRoom then tmpRun.WingDepth = (tmpRun.WingDepth or 0) + 1 else tmpRun.WingDepth = 0 end local runForWellPrediction = RunWithUpdatedHistory(tmpRun) local exitRooms = {} local shrinePointRoom = nil -- Predict if the room's exit doors will be blue or gold leaf. local rewardStoreName = ChooseNextRewardStore(tmpRun) -- calls RandomSynchronize -- Predict if shop will have Charon's bag if predictions.Encounter and predictions.Encounter.Name == "Shop" then -- Simulate SpawnRoomReward, this happens during StartRoom for shops if tmpRun.CurrentRoom.SpawnRewardGlobalVoiceLines ~= nil then SimulateVoiceLines( tmpRun, GlobalVoiceLines[tmpRun.CurrentRoom.SpawnRewardGlobalVoiceLines] ) end -- Simulate SpawnStoreItemsInWorld local unsorted = DeepCopyTable( predictions.StoreOptions ) local sortedList = CollapseTableAsOrderedKeyValuePairs( unsorted ) for i, kvp in ipairs( sortedList ) do local item = kvp.Value if item.Name == "HermesUpgradeDrop" then PredictUpgradeOptions(tmpRun, "HermesUpgrade", { SpawnOnly = true}) elseif item.Name == "StackUpgradeDrop" then PredictUpgradeOptions(tmpRun, "StackUpgrade", { SpawnOnly = true, ForceCommon = true }) elseif item.Name == "WeaponUpgradeDrop" then PredictUpgradeOptions(tmpRun, "WeaponUpgrade", { SpawnOnly = true}) elseif item.Type == "Consumable" then -- do nothing elseif item.Type == "Boon" then PredictUpgradeOptions(tmpRun, item.Args.ForceLootName, { SpawnOnly = true }) end end -- 2 increments in ActivatePrePlaced CoinFlip() CoinFlip() if RandomChance( 0.22 ) then predictions.HasCharonBag = true end end -- DoUnlockRoomExits() if hasShrinePointDoor then RandomSynchronize(13) if predictions.HasChaosGate then -- simulate generating the chaos room, see HandleSecretSpawns CoinFlip() -- RemoveRandomValue( secretPointIds ) ChooseNextRoomData(tmpRun, {RoomDataSet = RoomSetData.Secrets}) -- ignore result, called for rng side effects end local shrinePointRoomOptions = tmpRoom.ShrinePointRoomOptions or RoomSetData.Base.BaseRoom.ShrinePointRoomOptions local shrinePointRoomName = GetRandomValue(shrinePointRoomOptions) local shrinePointRoomData = RoomSetData.Base[shrinePointRoomName] if shrinePointRoomData ~= nil then shrinePointRoom = ParasDoorPredictions.CreateRoom(tmpRun, shrinePointRoomData, { SkipChooseReward = true }) shrinePointRoom.NeedsReward = true end end RandomSynchronize() local exitCount = ExitCountForRoom(tmpRoom) for i=1,exitCount do local roomData = ChooseNextRoomData(tmpRun) local exitRoom = ParasDoorPredictions.CreateRoom(tmpRun, roomData, { SkipChooseReward = true, SkipChooseEncounter = true}) table.insert(exitRooms, exitRoom) end if shrinePointRoom then -- exits are sorted by the name of door, which start with the name of the biome -- ie. TartarusDoor03b, AsphodelBoat01b, ElysiumExitDoor -- or ShrinePointDoor for Erebus gates if tmpRun.RunDepthCache > 12 then -- in Asphodel and Elysium, Erebus gates come last table.insert(exitRooms, shrinePointRoom) else -- in Tartarus, Erebus gates come first table.insert(exitRooms, 1, shrinePointRoom) end end for i, exitRoom in pairs(exitRooms) do if exitRoom.ForcedRewardStore ~= nil then -- if any room is forced to give eg. a gold leaf, -- then all of them will. rewardStoreName = exitRoom.ForcedRewardStore end end -- upgrade styx miniboss doors if tmpRoom.FirstAppearanceNumExitOverrides ~= nil and not HasSeenRoomEarlierInRun(tmpRun, tmpRoom.Name) then local randomDoors = {} for i, _ in ipairs(exitRooms) do table.insert(randomDoors, { Name = "TravelDoor03", Index = i }) end for i = 1, tmpRoom.FirstAppearanceNumExitOverrides do local randomDoor = RemoveRandomValue( randomDoors ) local randomRoom = exitRooms[randomDoor.Index] randomRoom.UseOptionalOverrides = true for k,v in pairs( randomRoom.OptionalOverrides ) do randomRoom[k] = v end end end local rewardsChosen = {} for i, exitRoom in pairs(exitRooms) do local exitCanHaveSurvival = Contains(exitRoom.LegalEncounters, "SurvivalTartarus") and IsEncounterEligible(runForWellPrediction, exitRoom, EncounterData.SurvivalTartarus) and exitRoom.ChosenRewardType ~= "Devotion" local exitIsFountain = IsFountainRoom(exitRoom) local exitIsErebus = IsErebusRoom(exitRoom) local exitRoomExitCount = ExitCountForRoom(exitRoom) exitRoom.ChosenRewardType = ParasDoorPredictions.ChooseRoomReward(tmpRun, exitRoom, rewardStoreName, rewardsChosen, { PreviousRoom = tmpRoom }) -- calls RandomSynchronize(4) local exitChallengeSwitchBaseCount = ParasDoorPredictions.ChallengeSwitchBaseCount[exitRoom.Name] or 0 runForWellPrediction.CurrentRoom = exitRoom if IsChallengeSwitchEligible( runForWellPrediction, exitChallengeSwitchBaseCount ) then exitChallengeSwitchBaseCount = exitChallengeSwitchBaseCount - 1 end local exitHasWellShop = IsWellShopEligible(runForWellPrediction, exitRoom) and exitChallengeSwitchBaseCount > 0 local exitSecretPointCount = ParasDoorPredictions.SecretPointCount[exitRoom.Name] or 0 local exitHasChaosGate = exitSecretPointCount > 0 and IsSecretDoorEligible(runForWellPrediction, exitRoom) if exitHasChaosGate then exitSecretPointCount = exitSecretPointCount - 1 end local exitHasShrinePointDoor = exitSecretPointCount > 0 and IsShrinePointDoorEligible(runForWellPrediction, exitRoom) if exitRoom.ChosenRewardType ~= "Devotion" then -- don't care about trials, we won't take them anyways SetupRoomReward(tmpRun, exitRoom, rewardsChosen) end table.insert( rewardsChosen, { RewardType = exitRoom.ChosenRewardType, ForceLootName = exitRoom.ForceLootName, WellShop = exitHasWellShop, ExitCount = exitRoomExitCount, Fountain = exitIsFountain, ShrinePointDoor = exitHasShrinePointDoor, ChaosGate = exitHasChaosGate, Erebus = exitIsErebus, CanHaveSurvival = exitCanHaveSurvival, StyxMiniBoss = exitRoom.RequireWingEndMiniBoss, RoomName = exitRoom.Name }) end predictions.NextExitRewards = rewardsChosen -- Rerolls TmpPlayingVoiceLines = {} if predictions.UpgradeOptions and lootName ~= "WeaponUpgrade" then predictions.UpgradeOptionsReroll = PredictUpgradeOptionsReroll(tmpRun, lootName, predictions.UpgradeOptions) end if false then -- well shop rerolls are heavily manipulable, not useful to show them RandomSynchronize(tmpRun.NumRerolls - 1) SimulateVoiceLines(tmpRun, HeroVoiceLines.UsedRerollPanelVoiceLines) local randomExclusion = { GetRandomValue(tmpRoom.Store.StoreOptions).Name } local rerollStore = FillInShopOptions({ StoreData = StoreData.RoomShop, RoomName = tmpRoom.Name, ExclusionNames = randomExclusion }) predictions.StoreOptionsReroll = rerollStore.StoreOptions end -- Reset the RNG to the current value. NextSeeds[1] = oldSeed RandomSynchronize(oldUses) return predictions end function CreateAnnotation(objectId) local annotation = {} annotation.ObjectId = objectId annotation.NextLineNumber = 0 annotation.Anchors = {} return annotation end function AddLine(annotation, text, args) args = args or {} local yOffset = annotation.NextLineNumber * 12 local id = SpawnObstacle({ Name = "BlankObstacleNoTimeModifier", DestinationId = annotation.ObjectId, Group = "Overlay", OffsetX = 0, OffsetY = yOffset }) CreateTextBox({ Id = id, Text = text, OffsetX = 0, OffsetY = yOffset, Font = "AlegreyaSansSCBold", FontSize = 18, Color = args.Color or Color.White, LuaKey = args.LuaKey, LuaValue = args.LuaValue, Justification = "Center"}) annotation.NextLineNumber = annotation.NextLineNumber + 1 annotation.Anchors[annotation.NextLineNumber] = id end function ResetAnnotation(annotation) for index,id in pairs(annotation.Anchors) do Destroy({Ids = {id}}) end annotation.Anchors = {} annotation.NextLineNumber = 0 end -- These don't seems to have entries in HelpText ParasDoorPredictions.StoreDropNames = { RoomRewardHealDrop = "Food", StoreRewardLockKeyDrop = "Key", StoreRewardMetaPointDrop = "Darkness", StackUpgradeDrop = "Pom of Power" } function ShowStoreOptions(annotation, storeOptions) if config.ShowStoreOptions and storeOptions ~= nil then for i, item in pairs(storeOptions) do if item.Args ~= nil and item.Args.ForceLootName ~= nil then local text = "{$ForceLootName}" if item.Name == "BlindLootBox" then text = text .. " (Blind)" end AddLine(annotation, text, {LuaKey = "ForceLootName", LuaValue = item.Args.ForceLootName}) for id, choice in pairs(item.Args.UpgradeOptions) do local color = ParasDoorPredictions.RarityColorMap[choice.Rarity] if choice.Blocked then color = Color.Red end AddLine(annotation, choice.ItemName, {Color = color}) end else AddLine(annotation, ParasDoorPredictions.StoreDropNames[item.Name] or item.Name) end end end end function ShowUpgradeOptions(annotation, upgradeOptions) if upgradeOptions ~= nil then for id, choice in pairs(upgradeOptions) do local upgradeOptionString = "{$Choice.ItemName}" if choice.SecondaryItemName ~= nil then upgradeOptionString = "{$Choice.SecondaryItemName} " .. upgradeOptionString end local color = ParasDoorPredictions.RarityColorMap[choice.Rarity] if choice.Blocked then color = Color.Red end AddLine(annotation, upgradeOptionString, {Color = color, LuaKey="Choice", LuaValue=choice}) end end end function ShowEncounter(annotation, encounter) if not config.ShowEncounters then return end if Contains(EncounterSets.ThanatosEncounters, encounter.Name) then AddLine(annotation, "Thanatos", {Color = Color.Yellow}) end if encounter.Name == "SurvivalTartarus" then AddLine(annotation, "Survival", {Color = Color.Yellow}) end if config.ShowEnemies and encounter.SpawnWaves ~= nil then for i, wave in pairs(encounter.SpawnWaves) do local waveString = "" local spawns = {} for j, spawn in pairs(wave.Spawns) do if waveString ~= "" then waveString = waveString .. ", " end local name = spawn.Name:gsub("Elite$", "") if name ~= spawn.Name then waveString = waveString .. "Dire " end waveString = waveString .. "{$Spawns[" .. j .. "]}" table.insert(spawns, name) end AddLine(annotation, waveString, {LuaKey = "Spawns", LuaValue = spawns}) end end end -- reward can be a room function ShowExits(annotation, nextExitRewards) if not config.ShowExits then return end for k, reward in pairs(nextExitRewards) do local rewardString = "" if config.ShowRoomNames then rewardString = rewardString .. reward.RoomName .. " " end if config.ShowRewardType and reward.RewardType ~= nil then if reward.ForceLootName ~= nil then rewardString = rewardString .. "Boon of {$Reward.ForceLootName}" else rewardString = rewardString .. "{$Reward.RewardType}" end end if config.ShowFountains and reward.Fountain then rewardString = rewardString .. " with Fountain" end if config.ShowWellShops and reward.WellShop then rewardString = rewardString .. " with Well Shop" end if config.ShowChaosGates and reward.ChaosGate then rewardString = rewardString .. " with Chaos Gate" end if config.ShowErebusGates and reward.ShrinePointDoor then rewardString = rewardString .. " with Erebus Gate" end if reward.Erebus then rewardString = rewardString .. " through Erebus Gate" end if config.ShowPossibleSurvival and reward.CanHaveSurvival then rewardString = rewardString .. " with possible survival" end if reward.StyxMiniBoss then rewardString = rewardString .. " with MiniBoss" end rewardString = rewardString .. " (" .. reward.ExitCount .. " Exits)" AddLine(annotation, rewardString, {LuaKey = "Reward", LuaValue = reward}) end end function ShowDoorPreview(annotation, door) if config.ShowRoomNames then AddLine(annotation, door.Room.Name) end if config.ShowRewardType and door.Room.ChosenRewardType ~= nil then local rewardString = "{$Room.ChosenRewardType}" if door.Room.ForceLootName then rewardString = "Boon of {$Room.ForceLootName}" end AddLine(annotation, rewardString, {LuaKey = "Room", LuaValue = door.Room}) end local predictions = PredictLoot(door) if config.ShowCharonBag and predictions.HasCharonBag then AddLine(annotation, "Charon's Bag", { Color = Color.Yellow }) end if config.ShowStoreOptions and predictions.StoreOptions ~= nil then ShowStoreOptions(annotation, predictions.StoreOptions) if config.ShowRerolls and predictions.StoreOptionsReroll ~= nil then AddLine(annotation, "RerollPanel") ShowStoreOptions(annotation, predictions.StoreOptionsReroll) end end if config.ShowFountains and predictions.HasFountain then AddLine(annotation, "Fountain") end if config.ShowChaosGates and predictions.HasChaosGate then AddLine(annotation, "Chaos Gate") end if config.ShowUpgradeOptions and predictions.UpgradeOptions ~= nil then ShowUpgradeOptions(annotation, predictions.UpgradeOptions) if config.ShowRerolls and predictions.UpgradeOptionsReroll ~= nil then AddLine(annotation, "RerollPanel") ShowUpgradeOptions(annotation, predictions.UpgradeOptionsReroll) end end ShowEncounter(annotation, predictions.Encounter) ShowExits(annotation, predictions.NextExitRewards) end function UpdateRngDisplay( triggerArgs ) if GetNumMetaUpgrades("DoorHealMetaUpgrade") > 0 then return ModUtil.Hades.PrintOverhead("Please disable Chthonic Vitality, it causes predictions to be incorrect.") end local rngUses = ParasDoorPredictions.CurrentUses if ParasDoorPredictions.Enabled and (ParasDoorPredictions.Dirty or rngUses ~= ParasDoorPredictions.LastUpdateRngUses) then ParasDoorPredictions.Dirty = false ParasDoorPredictions.LastUpdateRngUses = rngUses for doorId, door in pairs(ParasDoorPredictions.Doors) do ResetAnnotation(door.Annotation) ShowDoorPreview(door.Annotation, door.Door) end end PredictFatefulTwist() end OnControlPressed { "Gift", UpdateRngDisplay }
local Herbie = LibStub("AceAddon-3.0"):GetAddon("Herbie") local acr = LibStub("AceConfigRegistry-3.0") local acd = LibStub("AceConfigDialog-3.0") local function getHerbieProfileProfessionsOption(item) return Herbie.dbAce.profile.professions[item.arg] end local function setHerbieProfileProfessionsOption(item, val) Herbie.dbAce.profile.professions[item.arg] = val end local herbieGeneralOptions = { type = "group", get = getHerbieProfileProfessionsOption, set = setHerbieProfileProfessionsOption, childGroups = "tab", args= { description = { order = 0, type = "description", name = "Options for Herbie component helper. Use these options to control what is displayed", }, filters = { order = 1, type = "description", name = "Filters" }, general = { type = "group", desc = "General options for Herbie", name = "General", args = { desc = { order = 0, type = "description", name = "General options for Herbie" }, showLeatherworking = { order = 1, type = "toggle", name = "Leatherworking", desc = "Toggle showing Leatherworking recipes", width = "full", arg = "fIncludeLeatherworking" }, showAlchemy = { order = 2, type = "toggle", name = "Alchemy", desc = "Toggle showing Alchemy recipes", width = "full", arg = "fIncludeAlchemy" }, showCooking = { order = 3, type = "toggle", name = "Cooking", desc = "Toggle showing Cooking recipes", width = "full", arg = "fIncludeCooking" }, showBlacksmithing = { order = 4, type = "toggle", name = "Blacksmithing", desc = "Toggle showing Blacksmithing recipes", width = "full", arg = "fIncludeBlacksmithing" }, showTailoring = { order = 5, type = "toggle", name = "Tailoring", desc = "Toggle showing Tailoring recipes", width = "full", arg = "fIncludeTailoring" }, showEnchanting = { order = 6, type = "toggle", name = "Enchanting", desc = "Toggle showing Enchanting recipes", width = "full", arg = "fIncludeEnchanting" }, } }, } } local function getHerbieCompFilterValue(item, val) -- print("item: " .. tostring(Herbie.dbAce.profile[item.arg])) -- print("val: " .. tostring(val)) -- print("item.option: " .. tostring(item.option)) -- print("item.option.values: " .. tostring(item.option.values)) -- print("item.option.values[val]: " .. tostring(item.option.values[val])) if (Herbie.dbAce.profile[item.arg][item.option.values[val]] == nil) then return false end return Herbie.dbAce.profile[item.arg][item.option.values[val]] end local function setHerbieCompFilterValue(item, val) -- the val in this case will be an index into item.values[] -- print("item: " .. tostring(Herbie.dbAce.profile[item.arg])) -- print("val: " .. tostring(val)) -- print("item.option: " .. tostring(item.option)) -- print("item.option.values: " .. tostring(item.option.values)) -- print("item.option.values[val]: " .. tostring(item.option.values[val])) if (Herbie.dbAce.profile[item.arg][item.option.values[val]] == nil) then Herbie.dbAce.profile[item.arg][item.option.values[val]] = true else Herbie.dbAce.profile[item.arg][item.option.values[val]] = nil end end local herbieFilterOptions = { type = "group", get = getHerbieCompFilterValue, set = setHerbieCompFilterValue, childGroups = "tab", args= { description = { order = 0, type = "description", name = "Options for Herbie component helper. Use these options to control what is displayed", }, filters = { order = 1, type = "description", name = "Filters" }, leatherworking = { type = "group", name = "Leatherworking", desc = "Select the leather working components to ignore", args = { itemList = { order = 1, name = "Select items to ignore", type = "multiselect", values = {}, arg = "LeatherworkingFilter" } } }, alchemy = { type = "group", name = "Alchemy", desc = "Select the leather working components to ignore", args = { itemList = { order = 1, name = "Select items to ignore", type = "multiselect", values = {}, arg = "AlchemyFilter" } } }, tailoring = { type = "group", name = "Tailoring", desc = "Select the leather working components to ignore", args = { itemList = { order = 1, name = "Select items to ignore", type = "multiselect", values = {}, arg = "TailoringFilter" } } }, blacksmithing = { type = "group", name = "Blacksmithing", desc = "Select the leather working components to ignore", args = { itemList = { order = 1, name = "Select items to ignore", type = "multiselect", values = {}, arg = "BlacksmithingFilter" } } }, enchanting = { type = "group", name = "Enchanting", desc = "Select the leather working components to ignore", args = { itemList = { order = 1, name = "Select items to ignore", type = "multiselect", values = {}, arg = "EnchantingFilter" } } }, cooking = { type = "group", name = "Cooking", desc = "Select the leather working components to ignore", args = { itemList = { order = 1, name = "Select items to ignore", type = "multiselect", values = {}, arg = "CookingFilter" } } }, } } local function getCompsListForType(type) local keys = {} local keysHash = {} for item, recipe in pairs(Herbie.ComponentDB) do if recipe.type == type and recipe.components ~= nil then -- print("components = " .. tostring(recipe.components)) for comp in pairs(recipe.components) do if (keysHash[comp] == nil) then keys[#keys + 1] = comp keysHash[comp] = true end end end end return keys end function InitializeConfig() herbieFilterOptions.args.leatherworking.args.itemList.values = getCompsListForType("Leatherworking") herbieFilterOptions.args.alchemy.args.itemList.values = getCompsListForType("Alchemy") herbieFilterOptions.args.enchanting.args.itemList.values = getCompsListForType("Enchanting") herbieFilterOptions.args.tailoring.args.itemList.values = getCompsListForType("Tailoring") herbieFilterOptions.args.blacksmithing.args.itemList.values = getCompsListForType("Blacksmithing") herbieFilterOptions.args.cooking.args.itemList.values = getCompsListForType("Cooking") acr:RegisterOptionsTable("Herbie", herbieGeneralOptions, "/herbieopt") Herbie.optionsPanel = acd:AddToBlizOptions("Herbie", "Herbie") acr:RegisterOptionsTable("Herbie/Filters", herbieFilterOptions, "/herbieopt") acd:AddToBlizOptions("Herbie/Filters", "Filters", "Herbie") end function debugPrintProfile(name, profile) print("Profile " .. name) print(" professions: { ") print(string.format(" fIncludeCooking = %s", tostring(profile.professions.fIncludeCooking))) print(string.format(" fIncludeAlchemy = %s", tostring(profile.professions.fIncludeAlchemy))) print(string.format(" fIncludeLeatherworking = %s", tostring(profile.professions.fIncludeLeatherworking))) print(string.format(" fIncludeBlacksmithing = %s", tostring(profile.professions.fIncludeBlacksmithing))) print(string.format(" fIncludeTailoring = %s", tostring(profile.professions.fIncludeTailoring))) print(string.format(" fIncludeEnchanting = %s", tostring(profile.professions.fIncludeEnchanting))) print(" }") end function Herbie:OnProfileChanged(db, name) print("OnProfileChanged: name = " .. name) -- db = self.db.profile -- filter = db.filter Herbie:SendMessage("HerbieConfigChanged") end function Herbie:ConfigChanged() print("in config changed") end
local formattingutil = require("util/formattingutil") return function(self, chips, el) -- If the header isn't enabled, don't add any indentation in each line. local offset = self.config.header_style.enabled and 1 or 0 local header = formattingutil.create_osd_section_header(formattingutil.get_format(self, "header", "Sensors"), self, el) local osd_document = { header, header and el.newline, } local chip_views = {} --[[ Filter out unwanted chips and features, skipping chips and features that do not have temperature information. ]] for kchip, chip in pairs(chips) do if self.config.chip_filter_function(self, chip) then local chip_temperature_found = false local feature_views = {} for kfeature, feature in pairs(chip.features) do if self.config.feature_filter_function(self, chip, feature) then local feature_temperature_found = false local current_temperature = nil local current_max_temperature = nil for _, subfeature in pairs(feature.subfeatures) do if subfeature.type == "TEMP_INPUT" then feature_temperature_found = true chip_temperature_found = true current_temperature = subfeature.value elseif subfeature.type == "TEMP_MAX" then current_max_temperature = subfeature.value end end if feature_temperature_found then table.insert(feature_views, { label = feature.label, id = kfeature, current_temperature = current_temperature, current_max_temperature = current_max_temperature }) end end end -- Sort the features by label and id. table.sort(feature_views, function(l, r) if l.label == r.label then return l.id < r.id end return l.label < r.label end) if chip_temperature_found then table.insert(chip_views, { name = chip.name, id= kchip, features = feature_views }) end end end -- Sort the chips by name and id. table.sort(chip_views, function(l, r) if l.name == r.name then return l.id < r.id end return l.name < r.name end) for _, chip in pairs(chip_views) do -- Write the chip's name to the OSD. table.insert_all(osd_document, el.indent(offset), el.new({text = chip.name}), el.newline ) for _, feature in pairs(chip.features) do -- Determine if the temperature is normal or if the chip is overheating. local heat_status = "unknown" if feature.current_max_temperature then heat_status = "good" if feature.current_temperature >= feature.current_max_temperature - self.config.max_temperature_warning_threshold then heat_status = "warning" end if feature.current_temperature >= feature.current_max_temperature then heat_status = "overheating" end end local color_map = { unknown = self.config.default_temperature_color, good = self.config.good_temperature_color, warning = self.config.warning_temperature_color, overhearing = self.config.overheating_temperature_color } local temperature_color = color_map[heat_status] table.insert_all(osd_document, el.indent(offset+1), el.new({text = feature.label..": "}), el.new({ text=string.format("%d°",feature.current_temperature), color=temperature_color }), el.newline ) end end return osd_document end
local ffi = require("ffi") -- LuaJIT Extension local user32 = ffi.load("user32") -- LuaJIT User32 DLL Handler Function ffi.cdef([[ enum{ MB_OK = 0x00000000L, MB_OKCANCEL = 0x00000001L, MB_ABORTRETRYIGNORE = 0x00000002L, MB_YESNOCANCEL = 0x00000003L, MB_YESNO = 0x00000004L, MB_RETRYCANCEL = 0x00000005L, MB_CANCELTRYCONTINUE = 0x00000006L, MB_ICONINFORMATION = 0x00000040L, MB_ICONWARNING = 0x00000030L, MB_ICONASTERISK = 0x00000040L, MB_ICONHAND = 0x00000010L, }; typedef void* HANDLE; typedef HANDLE HWND; typedef const char* LPCSTR; typedef unsigned UINT; int MessageBoxA(HWND, LPCSTR, LPCSTR, UINT); int MessageBoxW(HWND, LPCSTR, LPCSTR, UINT); ]]) --HP POISON local doDrain = false; local healthDrainPoison = 0.025; local poisonStacks = 0; --HP POISON local hitsToDeath = 0; allowPause = false; isCrashing = true; hpProhibit = false; sway = true; local angleshit = 1.5; local anglevar = 1.5; local notesUntilCure = 0; logArray = {"","","","","","","","","","","","","","","","","","","",""} function onCreate() health = getProperty('health') setPropertyFromClass('ClientPrefs', 'timeBarType', 'Disabled'); makeLuaSprite('CRASH', 'ERR', 0, 0); setProperty('CRASH.alpha', 0); setObjectCamera('CRASH', 'other') setProperty('CrashScreen.visible', false) addLuaSprite('CRASH', true); makeLuaSprite('HP', 'HP_PROHIBIT_SCREEN', 0, 0); setProperty('HP.alpha', 0); setObjectCamera('HP', 'other') setProperty('HpProh.visible', true) addLuaSprite('HP', true); makeAnimatedLuaSprite('Crash', 'HUD_Break', 0, 0); setObjectCamera('Crash', 'other'); addAnimationByPrefix('Crash', 'glitching', 'HUD_GLITCH', 45, true) objectPlayAnimation('Crash', 'glitching', false) setProperty('Crash.visible', false) addLuaSprite('Crash',true) --setProperty('health', health+ 2.0); end function onMoveCamera(focus) --if focus == 'boyfriend' then --setProperty ('defaultCamZoom', 0.6) --elseif focus == 'dad' then --setProperty ('defaultCamZoom', 0.7) --end end function onDestroy() -- triggered when the lua file is ended (Song fade out finished) end function onCountdownTick(counter) -- counter = 0 -> "Three" -- counter = 1 -> "Two" -- counter = 2 -> "One" -- counter = 3 -> "Go!" -- counter = 4 -> Nothing happens lol, tho it is triggered at the same time as onSongStart i think end function noteMiss(id, noteData, noteType, isSustainNote, tag, loops, loopsleft) if noteType == 'Sako_Note' then poisonStacks = poisonStacks + 1; end if noteType == 'Fallen Note' then --H E L L hpProhibit = true; doTweenAlpha('HpAlpha', 'HP', 0.6, 0.8, 'quintOut'); --H E L L end if noteType == 'CRASH_NOTES' then if isCrashing == true then cameraShake("camHUD", 999999, 999999); setProperty('health', 1.0); playMusic('red-alertCrash', 1, true) setProperty('Crash.visible', true) isCrashing = false; playSound('glitchSound', 2, 'glitch') runTimer('crashPre', 2.1); runTimer('crash', 3.5); runTimer('crashPost', 3.8); end end end function goodNoteHit() if noteType == 'Sako_Note' then poisonStacks = poisonStacks - poisonStacks; hpProhibit = false; end health = getProperty('health') setProperty('health', health+ 0.03); end function onUpdate(elapsed) health = getProperty('health') if getProperty('health') > 0.05 then setProperty('health', health- healthDrainPoison * poisonStacks * elapsed); end --H E L L --H E L L if notesUntilCure == 30 then hpProhibit = false; end if hpProhibit == false then doTweenAlpha('HpAlpha', 'HP', 0.0, 0.8, 'quintOut'); notesUntilCure = notesUntilCure - notesUntilCure; end --H E L L --H E L L end function opponentNoteHit(id, direction, noteData, noteType, isSustainNote, tag, loops, loopsleft) if noteType == 'Fallen Note' then setProperty('health', health- 0.03); end if hpProhibit == true then setProperty('health', health- 0.02); end if curBeat < 1 then if curBeat > 240 then cameraShake('cam', '0.015', '0.1') end end end function onBeatHit() --[[if curBeat > 1 then if curBeat % 2 == 0 then angleshit = anglevar; else angleshit = -anglevar; end doTweenAngle('turn', 'camHUD', angleshit, stepCrochet*0.002, 'circOut') doTweenX('tuin', 'camHUD', -angleshit*8, crochet*0.001, 'linear') doTweenAngle('tt', 'camGame', -angleshit, stepCrochet*0.002, 'circOut') doTweenX('ttrn', 'camGame', angleshit*8, crochet*0.001, 'linear') end]] end -- song ended/starting transition (Will be delayed if you're unlocking an achievement) -- return Function_Stop to stop the song from ending for playing a cutscene or something. --function onEndSong() --return Function_Continue; --end prevent = false; --function onPause() --return Function_Continue; -- Called when you press Pause while not on a cutscene/etc -- return Function_Stop if you want to stop the player from pausing the game -- return Function_Stop if you want to stop the player from pausing the game --end function onTimerCompleted(tag, loops, loopsLeft) if tag == 'startDialogue' then -- Timer completed, play dialogue startDialogue('dialogue'); end if tag == 'crashPre' then -- Timer completed, play dialogue makeLuaSprite('NUL', 'null', -1800, -800); setScrollFactor('NUL', 0, 0); addLuaSprite('NUL', false); return Function_Stop; end if tag == 'crash' then -- Timer completed, play dialogue local f = io.open("crash_log.dmp", "w") f:write("") f:write("LogID:38e76ft5rds6fu7gti8f9gh8gf7\nUserID:[failed to initialize]\n\nUnhandled Excpetion:ADDRESS_ERROR_ON_SPIN_LOCK reading from address 0x00000000\n\nProcess!EventManager::Allocated 'VSSHUN' to logging process\nVSSHUN!EventManager::Loaded Actors\nVSSHUN!EventManager::Loaded Stage\nVSSHUN!EventManager::Initialized Audio\nVSSHUN!EventManager::Initialized Countdown\nVSSHUN!Error::No instance of NUL was found\nVSSHUN!Critical::Invalid object instance cause load segment fault in address 0x00000000\nVSSHUN!Error::Illegal instruction at address 0x00000000\nVSSHUN!Critical::GraphicEngine segment failure\nVSSHUN!EventManager::Unloading stageActor\nVSSHUN!Log::Critical error detected\nVSSHUN!Log::Raising HardError\nProcess!Allocation corruption detected\nProcess!Exiting process\nflixel.system.note:Thank you for playing VS Shun, keep an eye out for Ver 2 and expect an even bigger CALAMITY!") f:close() --================================================ makeLuaSprite('Error', 'ERR', 0, 0); setProperty('Error.alpha', 1); setObjectCamera('Error', 'other') addLuaSprite('Error', true); setProperty('Crash.visible', false) playMusic('red-alertCrash', 0, true) return Function_Stop; end if tag == 'crashPost' then -- Timer completed, play dialogue doTweenAlpha('CrashScreen', 'CRASH', 1, 1, 'quintOut'); health = getProperty('health') stopSound('glitch') setProperty('health', 0.0); setProperty('camHUD.alpha', 0); user32.MessageBoxA(nil, "The system detected an overrun of a stack-based buffer in this application. This overrun could potentially allow a malicious user to gain control of this application.", "System Error", ffi.C.MB_OK + ffi.C.MB_ICONHAND) if ffi.C.MB_OK then user32.MessageBoxA(nil, "Uh oh! Looks like the game has crashed. We apologize for the inconvenience.\n\nA crash log has been created in the game folder.", "Friday Night Funkin': VS Shun", ffi.C.MB_OK + ffi.C.MB_ICONHAND) os.exit() end return Function_Stop; end function resetButtonPositions() for i=0,7 do setActorX(_G['defaultStrum'..i..'X'] + 3 * math.sin((i*0.25) * math.pi), i); setActorY(_G['defaultStrum'..i..'Y'] + 50, i); end -- Also reset camera camHudAngle = 0 end end
APEX:SetBPM(120) -- Item Scroller setup local container = nil local scroller = nil local current_entry = nil local current_sort = "Difficulty" local t = Def.ActorFrame { InitCommand = function(this) container = this end, } local ITEM_HEIGHT = 54 local ITEM_MARGIN = 2 local ITEM_WIDTH = 751 local DIFFICULTY_BOX_SIZE = ITEM_HEIGHT local CLEAR_LAMP_WIDTH = 16 local SCROLLBAR_HEIGHT = SCREEN_HEIGHT - 256 local item_mt = { __index = { set_x = function(self) local this = self.container local base_x = 0 if self.data.type == "Song" then this:x(self.is_focused and base_x+33 or base_x+66) else this:x(self.is_focused and base_x-33 or base_x) end end, create_actors = function(self, params) local t = Def.ActorFrame { InitCommand = function(this) self.container = this end, SetupCommand = function(this) this:queuecommand("Update") :decelerate(0.2) self:set_x() end, SetCommand = function(this) if self.is_focused then this:queuecommand("Update") else this:accelerate(0.2) :x(ITEM_WIDTH * 1.5) :queuecommand("DoSet") end end, DoSetCommand = function(this) this:queuecommand("Update") :sleep(0.1) :queuecommand("AfterSet") end, ScrollCommand = function(this) self:set_x() end, AfterSetCommand = function(this) this:linear(0.1) self:set_x() this:queuecommand("Update") end, } -- Title t[#t+1] = Def.ActorFrame { UpdateCommand = function(this) this:x(self.data.type == "Song" and ((DIFFICULTY_BOX_SIZE)) or 0) end, -- Box outline Def.Quad { InitCommand = function(this) this:zoomto(ITEM_WIDTH, ITEM_HEIGHT) :diffuse(ThemeColor.Black) end, }, -- Box fill Def.Quad { InitCommand = function(this) this:zoomto(ITEM_WIDTH-3, ITEM_HEIGHT-3) :diffuse(ThemeColor.White) end, }, -- Box selection fill Def.Quad { InitCommand = function(this) this:zoomto(0, ITEM_HEIGHT-3) :halign(0) :x(-ITEM_WIDTH/2 + 1) :diffuse(ThemeColor.Yellow) end, UpdateCommand = function(this) if self.focused_last_update == self.is_focused then return end this:stoptweening() if self.is_focused then this:linear(0.15) :zoomx(ITEM_WIDTH) else this:linear(0.15) :zoomx(0) end self.focused_last_update = self.is_focused end, }, -- Title Def.BitmapText { Font = ThemeFonts.ListDisplayTitle, InitCommand = function(this) this:diffuse(ThemeColor.Black) :halign(0) :x((-ITEM_WIDTH/2)+16) :zoom(0.5) end, UpdateCommand = function(this) if self.data.type == "Song" then this:settext(self.data.song:GetDisplayMainTitle()) else this:settext(self.data.name) end end, }, } -- Clear lamp t[#t+1] = Def.ActorFrame { InitCommand = function(this) this:x(-ITEM_WIDTH/2) end, UpdateCommand = function(this) this:visible(self.data.type == "Song") end, SetCommand = function(this) this:stoptweening() this:queuecommand("Blink") end, Def.Quad { InitCommand = function(this) this:zoomto(CLEAR_LAMP_WIDTH, ITEM_HEIGHT) :diffuse(ThemeColor.Black) end, UpdateCommand = function(this) this:stoptweening() :queuecommand("Blink") end, BlinkCommand = function(this) this:stoptweening() if self.data.type ~= "Song" then return end this:diffuse(CLEAR.GetColor(self.data.clear_types["PlayerNumber_P1"])) :sleep(0.02) :queuecommand("Blink") end, }, Def.Sprite { InitCommand = function(this) this:Load(THEME:GetPathG("", "Glow.png")) end, UpdateCommand = function(this) this:stoptweening() :queuecommand("Blink") end, SetCommand = function(this) this:stoptweening() :queuecommand("Blink") end, BlinkCommand = function(this) this:stoptweening() if self.data.type ~= "Song" then this:visible(false) return end local color = CLEAR.GetColor(self.data.clear_types["PlayerNumber_P1"]) this:visible(color ~= ThemeColor.Black) this:diffuse(CLEAR.GetColor(self.data.clear_types["PlayerNumber_P1"])) :sleep(0.02) :queuecommand("Blink") end, }, } -- Difficulty t[#t+1] = Def.ActorFrame { InitCommand = function(this) this:x(((-ITEM_WIDTH/2) + (DIFFICULTY_BOX_SIZE/2)) + 2) end, UpdateCommand = function(this) this:visible(self.data.type == "Song") end, -- Difficulty Border Def.Quad { InitCommand = function(this) this:zoomto(DIFFICULTY_BOX_SIZE, DIFFICULTY_BOX_SIZE) :diffuse(ThemeColor.Black) end, }, -- Difficulty Fill Def.Quad { InitCommand = function(this) this:zoomto(DIFFICULTY_BOX_SIZE-3, DIFFICULTY_BOX_SIZE-3) end, UpdateCommand = function(this) if self.data.type == "Song" then this:diffuse(DifficultyColor[self.data.steps:GetDifficulty()]) end end, }, -- Difficulty Number Def.BitmapText { Font = ThemeFonts.Regular, InitCommand = function(this) this:diffuse(ThemeColor.White) end, UpdateCommand = function(this) if self.data.type == "Song" then this:settext(self.data.steps:GetMeter()) end end, }, } -- Type Label t[#t+1] = Def.ActorFrame { InitCommand = function(this) this:x(ITEM_WIDTH/2) end, UpdateCommand = function(this) this:visible(self.data.type ~= "Song") end, Def.Sprite { InitCommand = function(this) this:Load(THEME:GetPathG("", "TypeBack.png")) end, UpdateCommand = function(this) this:diffuse(TypeColor[self.data.type]) end, }, Def.BitmapText { Font = ThemeFonts.Regular, InitCommand = function(this) this:x(-16) end, UpdateCommand = function(this) this:settext(self.data.type) :diffusealpha(0.5) end, } } return t end, transform = function(self, item_index, num_items, is_focus) if self.index_last_update == nil then -- Keep track what this entries index is, if it jumps more then one (because of scrolling multiple or it wrapping around) we should not tween it. self.index_last_update = item_index end self.is_focused = is_focus if item_index == self.index_last_update+1 or item_index == self.index_last_update-1 then self.container:stoptweening() :decelerate(0.15) :y(item_index * (ITEM_HEIGHT + (ITEM_MARGIN))) else self.container:stoptweening() :y(item_index * (ITEM_HEIGHT + (ITEM_MARGIN))) if is_focus then self.container:queuecommand("Scroll") else self.container:stoptweening() end end self.index_last_update = item_index end, set = function(self, info) self.data = info end, } } scroller = setmetatable({ disable_wrapping = false }, item_scroller_mt) -- Actors t[#t+1] = scroller:create_actors("MusicList", 24, item_mt, 1095 + (ITEM_WIDTH/2), -132) -- Scrollbar t[#t+1] = Def.ActorFrame { InitCommand = function(this) scrollbar_container = this this:x(SCREEN_WIDTH - 8) :y((SCREEN_HEIGHT - SCROLLBAR_HEIGHT) / 2) end, -- Background Def.Quad { InitCommand = function(this) this:zoomto(9, SCROLLBAR_HEIGHT+2) :diffuse(ThemeColor.Black) :valign(0) end, }, -- Scroll Indicator Def.Quad { InitCommand = function(this) this:diffuse(ThemeColor.White) :valign(0) end, SetupCommand = function(this) this:queuecommand("Update") :queuecommand("Scroll") end, SetCommand = function(this) this:queuecommand("Update") end, UpdateCommand = function(this) local height = math.max(SCROLLBAR_HEIGHT / (#scroller:get_info_set() / 18), 3) this:stoptweening() :linear(0.1) :y(math.min(math.max((SCROLLBAR_HEIGHT / #scroller:get_info_set()) * (scroller:get_current_index()-1) - height/2, 1), SCROLLBAR_HEIGHT - (height))) :zoomto(6, height) end, ScrollCommand = function(this) this:queuecommand("Update") end, } } -- Song Information local song_information = SongInformation.Create() t[#t+1] = song_information:CreateActors(132, 64) -- Song Difficulty local song_difficulty = SongDifficulty.Create("PlayerNumber_P1") t[#t+1] = song_difficulty:CreateActors(329, 535) local function set_song(song, current_steps) song_information:SetSong(song) song_difficulty:SetSong(song, current_steps) end local function set_entries(entries, focus_index) scroller:set_info_set(entries, focus_index) container:queuecommand("Set") end local function select_entry(entry) -- Root if entry == nil then set_entries(MENUENTRY:GetRoot(), 1) -- Close folder elseif current_entry ~= nil and entry.id == current_entry.id then local entries = MENUENTRY:GetRoot() local index = table.find_index(table.map(entries, function(e) return e.id end), current_entry.id) set_entries(MENUENTRY:GetRoot(), index) current_entry = nil set_song(nil) -- Groups elseif entry.type == "Group" then set_entries(MENUENTRY:GetGroup(entry.name), 1) current_entry = entry elseif entry.type == "All" then set_entries(entry.entries, 1) current_entry = entry elseif entry.type == "Profile" then set_entries(MENUENTRY:GetFolder(entry), 1) current_entry = entry else lua.ReportScriptError("Unknown current entry in music wheel! Don't know action to trigger!") end end local function on_scroll() container:queuecommand("Scroll") container:queuecommand("Update") local info = scroller:get_info_at_focus_pos() if (info.type == "Song") then set_song(info.song, info.steps) else set_song(nil) end end local function on_stop_scroll() container:queuecommand("EndScroll") end local function on_start_scroll() container:queuecommand("StartScroll") end local function scroll(amount) scroller:scroll_by_amount(amount) on_scroll() end local function scroll_to(index) scroller:scroll_to_pos(index) on_scroll() end function scroll_to_steps(steps) for i, v in ipairs(scroller.info_set) do if v.steps == steps then scroll_to(i) end end end function scroll_difficulty(amount) local info = scroller:get_info_at_focus_pos() if info.type == "Song" then local all_steps = info.song:GetStepsByStepsType(GAMESTATE:GetCurrentStyle():GetStepsType()) -- Turn steps into entries (so we get clear lamps and can reuse the sorting functionality) local entries = table.map(all_steps, function(steps) return MENUENTRY.CreateSongEntry(info.song, steps) end) -- Find the current difficulty and set it to focused (Before sort so the indices match up) -- Sort it by meter and difficulty table.sort(entries, SORTFUNC.ByDifficulty) local current_steps_index = table.find_index(table.map(entries, function(e) return e.steps end), info.steps) local new_index = current_steps_index + amount if new_index >= 1 and new_index <= #all_steps then scroll_to_steps(entries[current_steps_index+amount].steps) end end end local last_button_press_timestamps = {} local function is_double_tap(button, event, tolerance) if event.type == "InputEventType_FirstPress" and event.GameButton == button and last_button_press_timestamps[event.GameButton] ~= nil and last_button_press_timestamps[event.GameButton] > GetTimeSinceStart() - tolerance then last_button_press_timestamps[event.GameButton] = -1 return true else return false end end local handle_input = function(event) if event.type == "InputEventType_FirstPress" and event.GameButton == "MenuLeft" or event.type == "InputEventType_FirstPress" and event.GameButton == "MenuRight" then on_start_scroll() end if event.type == "InputEventType_Release" and event.GameButton == "MenuLeft" or event.type == "InputEventType_Release" and event.GameButton == "MenuRight" then on_stop_scroll() end if event.type == "InputEventType_Release" then return end local current_row_info = scroller:get_info_at_focus_pos() if event.GameButton == "Start" and event.type == "InputEventType_FirstPress" then select_entry(scroller:get_info_at_focus_pos()) end if event.GameButton == "Back" and event.type == "InputEventType_FirstPress" then if current_entry ~= nil then select_entry(current_entry) else SCREENMAN:SetNewScreen("ScreenMainMenu") end end -- TODO: Find a good way for user to use "next page" functionality -- if is_double_tap("MenuRight", event) then -- local e = scroller:get_info_at_focus_pos() -- if e.type == "Song" then -- local meter_list = table.map(scroller:get_info_set(), function(i) return i.type == "Song" and i.steps:GetMeter() or 0 end) -- scroll_to(table.find_index(meter_list, e.steps:GetMeter()+1)) -- end if event.GameButton == "MenuRight" then scroll(1) end -- TODO: Find a good way for user to use "previous page" functionality --if is_double_tap("MenuLeft", event) then -- local e = scroller:get_info_at_focus_pos() -- if e.type == "Song" then -- local meter_list = table.map(scroller:get_info_set(), function(i) return i.type == "Song" and i.steps:GetMeter() or 0 end) -- scroll_to(table.find_index(meter_list, e.steps:GetMeter()-1)) -- end if event.GameButton == "MenuLeft" then scroll(-1) end if is_double_tap("MenuUp", event, 0.2) then scroll_difficulty(-1) end if is_double_tap("MenuDown", event, 0.2) then scroll_difficulty(1) end if event.type == "InputEventType_FirstPress" then -- Ignore it if set to -1, because that means a double tap was executed this update if last_button_press_timestamps[event.GameButton] ~= -1 then last_button_press_timestamps[event.GameButton] = GetTimeSinceStart() else last_button_press_timestamps[event.GameButton] = nil end end end t[#t+1] = Def.Quad { OnCommand = function(this) this:sleep(0.1) :queuecommand("LoadRoot") end, LoadRootCommand = function(this) MENUENTRY:InitializeSongQueue() this:queuecommand("ProcessQueue") end, -- TODO: Add loading indicator while processing songs ProcessQueueCommand = function(this) if MENUENTRY:ProcessSongQueue(400) > 0 then this:sleep(0.01) :queuecommand("ProcessQueue") else MENUENTRY:Sort() scroller:set_info_set(MENUENTRY:GetRoot(), 1) this:queuecommand("Setup") end end, SetupCommand = function(this) SCREENMAN:GetTopScreen():AddInputCallback(handle_input) container:queuecommand("Update") :queuecommand("PlayPreview") :sleep(0.1) end, StartScrollCommand = function(this) SOUND:StopMusic() APEX:SetBPM(0) end, EndScrollCommand = function(this) SOUND:StopMusic() this:stoptweening() :sleep(0.1) :queuecommand("PlayPreview") end, SetCommand = function(this) this:queuecommand("PlayPreview") end, PlayPreviewCommand = function(subself) local info = scroller:get_info_at_focus_pos() if info.type == "Song" then container:queuecommand("PauseBGM") local preview_beat = info.steps:GetTimingData():GetBeatFromElapsedTime(info.song:GetSampleStart()) local preview_bpm = info.steps:GetTimingData():GetBPMAtBeat(preview_beat) APEX:SetBPM(preview_bpm) SOUND:PlayMusicPart(info.song:GetPreviewMusicPath(), info.song:GetSampleStart(), info.song:GetSampleLength(), 1, 1, true, true) else container:queuecommand("PlayBGM") SOUND:StopMusic() end end, } t[#t+1] = Def.Sound { InitCommand = function(this) this:load(THEME:GetPathS("", "Menu Music.ogg")) end, OnCommand = function(this) this:play() end, StartScrollCommand = function(this) this:stoptweening() :sleep(0.2) :queuecommand("PlayBGM") end, PlayBGMCommand = function(this) APEX:SetBPM(120) this:pause(false) end, PauseBGMCommand = function(this) this:stoptweening() :pause(true) end, } return t
object_tangible_painting_painting_clone_trooper_01 = object_tangible_painting_shared_painting_clone_trooper_01:new { } ObjectTemplates:addTemplate(object_tangible_painting_painting_clone_trooper_01, "object/tangible/painting/painting_clone_trooper_01.iff")
local utils = {} function utils.MSRinit(model) for k,v in pairs(model:findModules('nn.SpatialConvolution')) do local n = v.kW*v.kH*v.nInputPlane v.weight:normal(0,math.sqrt(2/n)) if v.bias then v.bias:zero() end end end function utils.FCinit(model) for k,v in pairs(model:findModules'nn.Linear') do v.bias:zero() end end function utils.DisableBias(model) for i,v in ipairs(model:findModules'nn.SpatialConvolution') do v.bias = nil v.gradBias = nil end end function utils.testModel(model) model:float() local imageSize = opt and opt.imageSize or 32 local input = torch.randn(1,3,imageSize,imageSize):type(model._type) print('forward output',{model:forward(input)}) print('backward output',{model:backward(input,model.output)}) model:reset() end function utils.makeDataParallelTable(model, nGPU) if nGPU > 1 then local gpus = torch.range(1, nGPU):totable() local fastest, benchmark = cudnn.fastest, cudnn.benchmark local dpt = nn.DataParallelTable(1, true, true) :add(model, gpus) :threads(function() local cudnn = require 'cudnn' cudnn.fastest, cudnn.benchmark = fastest, benchmark end) dpt.gradInput = nil model = dpt:cuda() end return model end return utils
local ffi = require("ffi") ffi.cdef[[ void hello(); int64_t add(int64_t, int64_t); int64_t length(const char *); char *duplicate(int64_t, const char *); void release(char *); typedef struct { int32_t x, y; } point_t; void add_points( const point_t *, const point_t *, point_t * ); typedef struct { const char *msg; int32_t count; } duplicate_string_t; void add_duplicate_strings( const duplicate_string_t *, const duplicate_string_t *, duplicate_string_t * ); typedef struct { const char *name; // TODO(gardell): manage dangling pointer int64_t created; int64_t expire; } token_t; int32_t new_token( const char *, token_t *); ]] local rust = ffi.load("rust") function duplicate(count, msg) local c_str = rust.duplicate(count, msg) local str = ffi.string(c_str) rust.release(c_str) return str end local duplicate_string duplicate_string = ffi.metatype( "duplicate_string_t", { __add = function(a, b) local result = duplicate_string() rust.add_duplicate_strings(a, b, result) ffi.gc(result.msg, rust.release) return result end, __tostring = function(a) return string.format( "duplicate_string(\"%s\", %d)", ffi.string(a.msg), a.count ) end, } ) local point point = ffi.metatype( "point_t", { __add = function(a, b) local result = point() rust.add_points(a, b, result) return result end, __tostring = function(a) return string.format( "point(%i, %i)", a.x, a.y ) end, } ) rust.hello() print(rust.add(13, 37)) print(rust.length("slimjim")) print(duplicate(3, "bork!")) local p = point(1, 2) + point(3, 4) print(p) local ds = duplicate_string("Tipi Tais ", 3) + duplicate_string("Lee ba Time ", 2) print(ds) local token = { metatype = ffi.metatype( "token_t", { __tostring = function(a) return string.format( "token(name: %s, created: %d, expire: %d)", ffi.string(a.name), tonumber(a.created), tonumber(a.expire) ) end } ) } token.__index = token function token.new(str) local t = {} setmetatable(t, token) t.c_type = token.metatype() rust.new_token(str, t.c_type) return t end function token:get_name() return ffi.string(self.c_type.name) end function token:get_created() return tonumber(self.c_type.created) -- TODO(gardell): Use float and no tonumber end function token:get_expire() return tonumber(self.c_type.expire) -- TODO(gardell): Use float and no tonumber end function token:__tostring() return string.format( "token(name: %s, created: %d, expire: %d)", self:get_name(), self:get_created(), self:get_expire() ) end print(token.new("bajs:13:37"))
local api = vim.api local chezmoi_bin = '' local function chezmoi(cmd) local fcmd = string.format('%s %s 2>&1', chezmoi_bin, cmd) local out = vim.fn.system(fcmd) if vim.v.shell_error ~= 0 then -- api.nvim_err_writeln(string.format("chezmoi error: %s: %s", fcmd, out)) -- return '' end return out end local function chezmoi_add(file, options) return chezmoi(string.format('add %s %s', options or '', vim.fn.shellescape(vim.fn.expand(file)))) end local function chezmoi_apply(file) return chezmoi(string.format('apply %s', vim.fn.shellescape(vim.fn.expand(file)))) end local function chezmoi_forget(file, options) return chezmoi(string.format('forget %s %s', options or '', vim.fn.shellescape(vim.fn.expand(file)))) end local function chezmoi_version() return chezmoi '--version' end local function chezmoi_source_path(file) if file == nil then return chezmoi 'source-path' else return chezmoi(string.format('source-path %s', vim.fn.shellescape(vim.fn.expand(file)))) end end local Chezmoi = { conf = {} } local defaultConf = { exec = vim.g.chezmoi_exec or Chezmoi.conf.exec or 'chezmoi', auto_add = vim.g.chezmoi_auto_add or Chezmoi.conf.auto_add or true, add_options = vim.g.chezmoi_add_options or Chezmoi.conf.add_options or '--empty', } Chezmoi.conf = defaultConf function Chezmoi.setup_add_autocmd() vim.cmd [[ augroup chezmoi_auto_add autocmd! autocmd BufWritePost * lua require'chezmoi'.save('%') augroup END ]] end function Chezmoi.setup(config) if config == nil then return end for k, v in pairs(config) do Chezmoi.conf[k] = v end chezmoi_bin = vim.fn.exepath(Chezmoi.conf.exec) if chezmoi_bin == '' then api.nvim_echo({ string.format("chezmoi.nvim: cannot find an executable named '%s'", Chezmoi.conf.exec), 'ErrorMsg', }, true, {}) return end if Chezmoi.conf.auto_add == true then Chezmoi.setup_add_autocmd() end local v = Chezmoi.version() if v.major ~= 2 then api.nvim_echo({ { string.format( "chezmoi.nvim: chezmoi major version is not 2. chezmoi.nvim probably won't work. exec = %s; version = %d", chezmoi_bin, v.major ), 'ErrorMsg', }, }, true, {}) return end end function Chezmoi.is_managed(file) if file == nil or file == '' then return false end local out = chezmoi_source_path(file) if string.find(out, 'not in') == nil and string.find(out, 'does not exist') == nil and string.find(out, 'outside target directory') == nil then return true else return false end end function Chezmoi.clear_cache() Chezmoi.cached_status = nil end function Chezmoi.status() local file = vim.fn.expand '%' if Chezmoi.cached_status == nil or file ~= Chezmoi.cached_status_file then if Chezmoi.is_managed(file) then Chezmoi.cached_status = '[CM]' else Chezmoi.cached_status = '' end Chezmoi.cached_status_file = file end return Chezmoi.cached_status end function Chezmoi.version() local vstr = chezmoi_version() local maj, min, patch = string.match(vstr, '^chezmoi version v(%d+)%.(%d+)%.(%d+)') if maj == nil then maj = 0 min = 0 patch = 0 else maj = tonumber(maj) min = tonumber(min) patch = tonumber(patch) end return { major = maj, minor = min, patch = patch } end function Chezmoi.cmdline_add(file, options) if options == '' or options == nil then Chezmoi.add(file) else Chezmoi.add(file, options) end end function Chezmoi.cmdline_forget(file) if Chezmoi.is_managed(file) then Chezmoi.forget(file) end end function Chezmoi.add(file, options) chezmoi_add(file, options or Chezmoi.conf.add_options) Chezmoi.clear_cache() end function Chezmoi.forget(file) if Chezmoi.is_managed(file) then chezmoi_forget(file, '--force') Chezmoi.clear_cache() end end function Chezmoi.save(file) if Chezmoi.is_managed(file) then chezmoi_add(file) Chezmoi.clear_cache() end end return Chezmoi
local FindService = require('apicast.policy.find_service') local HostBasedFinder = require('apicast.policy.find_service.host_based_finder') local PathBasedFinder = require('apicast.policy.find_service.path_based_finder') local ConfigurationStore = require('apicast.configuration_store') describe('find_service', function() describe('.rewrite', function() describe('when path routing is enabled', function() describe('and there is a service with a matching path', function() it('stores that service in the context', function() ConfigurationStore.path_routing = true local service = { id = '1' } local context = { configuration = ConfigurationStore.new(), host = 'example.com' } stub(PathBasedFinder, 'find_service', function(config_store, host) if config_store == context.configuration and host == context.host then return service end end) stub(HostBasedFinder, 'find_service') local find_service = FindService.new() find_service:rewrite(context) assert.stub(HostBasedFinder.find_service).was_not_called() assert.equals(service, context.service) end) end) describe('and fallback to find by host is enabled', function() before_each(function() ConfigurationStore.path_routing = true ConfigurationStore.path_routing_only = false end) it('finds the service by host and stores it in the context', function() local service = { id = '1' } local context = { configuration = ConfigurationStore.new(), host = 'example.com' } stub(PathBasedFinder, 'find_service', function() return nil end) stub(HostBasedFinder, 'find_service', function(config_store, host) if config_store == context.configuration and host == context.host then return service end end) local find_service = FindService.new() find_service:rewrite(context) assert.equals(service, context.service) end) it('stores nil in the context if there is not a service for the host', function() local context = { } stub(PathBasedFinder, 'find_service', function() return nil end) stub(HostBasedFinder, 'find_service', function() return nil end) local find_service = FindService.new() find_service:rewrite(context) assert.is_nil(context.service) end) end) describe('and fallback to find by host is disabled', function() before_each(function() ConfigurationStore.path_routing = true ConfigurationStore.path_routing_only = true end) it('stores nil in the context even if there is a service for the host', function() local service = { id = '1' } local context = { configuration = ConfigurationStore.new(), host = 'example.com' } stub(PathBasedFinder, 'find_service', function() return nil end) stub(HostBasedFinder, 'find_service', function(config_store, host) if config_store == context.configuration and host == context.host then return service end end) local find_service = FindService.new() find_service:rewrite(context) assert.is_nil(context.service) end) end) end) describe('when path routing is disabled', function() before_each(function() ConfigurationStore.path_routing = false ConfigurationStore.path_routing_only = false end) it('finds the service by host and stores it in the context', function() local service = { id = '1' } local context = { configuration = ConfigurationStore.new(), host = 'example.com' } stub(HostBasedFinder, 'find_service', function(config_store, host) if config_store == context.configuration and host == context.host then return service end end) stub(PathBasedFinder, 'find_service') local find_service = FindService.new() find_service:rewrite(context) assert.stub(PathBasedFinder.find_service).was_not_called() assert.equals(service, context.service) end) it('stores nil in the context if there is not a service for the host', function() local context = { } stub(HostBasedFinder, 'find_service', function() return nil end) local find_service = FindService.new() find_service:rewrite(context) assert.is_nil(context.service) end) end) end) describe('.ssl_certificate', function() -- Path based routing is not used when using ssl. It fallbacks to finding -- the service by host. for _, path_routing in ipairs({ true, false }) do describe("when path routing = " .. tostring(path_routing), function() ConfigurationStore.path_routing = path_routing it('finds the service by host and stores it in the context', function() local service = { id = '1' } local context = { configuration = ConfigurationStore.new(), host = 'example.com' } stub(HostBasedFinder, 'find_service', function(config_store, host) if config_store == context.configuration and host == context.host then return service end end) stub(PathBasedFinder, 'find_service') local find_service = FindService.new() find_service:ssl_certificate(context) assert.stub(PathBasedFinder.find_service).was_not_called() assert.equals(service, context.service) end) it('stores nil in the context if there is not a service for the host', function() local context = { } stub(HostBasedFinder, 'find_service', function() return nil end) local find_service = FindService.new() find_service:ssl_certificate(context) assert.is_nil(context.service) end) end) end end) end)
FishTdSoundController = class("FishTdSoundController") slot1 = { ["Net0.mp3"] = { occupationTime = 0, time = 0.1, priority = ({ BUTTON = 8, Fish = 6, ACCOUNT = 5, WAVE = 7, ATHER = 2, ATHER_II = 3, HIT = 0, GOLD = 4, DEAD = 9 })["HIT"] }, ["Net1.mp3"] = { occupationTime = 0, time = 0.1, priority = ()["HIT"] }, ["Fire.mp3"] = { occupationTime = 0.2, time = 0.05, priority = ()["HIT"] }, ["GunFire0.mp3"] = { occupationTime = 0, time = 0.1, priority = ()["HIT"] }, ["GunFire1.mp3"] = { occupationTime = 0, time = 0.1, priority = ()["HIT"] }, ["ChangeScore.mp3"] = { occupationTime = 0, time = 0.2, priority = ()["ATHER"] }, ["MakeUP.mp3"] = { occupationTime = 0, time = 0.5, priority = ()["ATHER"] }, ["ChangeType.mp3"] = { occupationTime = 0, time = 0.1, priority = ()["ATHER"] }, ["award.mp3"] = { occupationTime = 0.5, time = 0.8, priority = ()["ATHER"] }, ["bigAward.mp3"] = { occupationTime = 4, time = 4, priority = ()["ATHER_II"] }, ["rotaryturn.mp3"] = { occupationTime = 0, time = 0.1, priority = ()["ATHER"] }, ["CJ.mp3"] = { occupationTime = 5, time = 5, priority = ()["ATHER_II"] }, ["TNNFDCLNV.mp3"] = { occupationTime = 1, time = 2, priority = ()["ATHER"] }, ["surf.mp3"] = { occupationTime = 7, time = 7, priority = ()["WAVE"] }, ["HaiLang.mp3"] = { occupationTime = 7, time = 7, priority = ()["WAVE"] }, ["fisha0.mp3"] = { occupationTime = 1.8, time = 2, priority = ()["Fish"] }, ["fisha1.mp3"] = { occupationTime = 1.8, time = 2, priority = ()["Fish"] }, ["fisha2.mp3"] = { occupationTime = 1.8, time = 2, priority = ()["Fish"] }, ["fisha3.mp3"] = { occupationTime = 1, time = 1, priority = ()["Fish"] }, ["fisha4.mp3"] = { occupationTime = 3.8, time = 4, priority = ()["Fish"] }, ["fisha5.mp3"] = { occupationTime = 2.8, time = 3, priority = ()["Fish"] }, ["fisha6.mp3"] = { occupationTime = 2.8, time = 3, priority = ()["Fish"] }, ["fisha7.mp3"] = { occupationTime = 1.8, time = 2, priority = ()["Fish"] }, ["fisha8.mp3"] = { occupationTime = 1.8, time = 2, priority = ()["Fish"] }, ["fisha9.mp3"] = { occupationTime = 1, time = 1, priority = ()["Fish"] }, ["fisha10.mp3"] = { occupationTime = 1.8, time = 2, priority = ()["Fish"] }, ["fisha11.mp3"] = { occupationTime = 1, time = 1, priority = ()["Fish"] }, ["fisha12.mp3"] = { occupationTime = 1, time = 1, priority = ()["Fish"] }, ["fisha13.mp3"] = { occupationTime = 1.8, time = 2, priority = ()["Fish"] }, ["fisha14.mp3"] = { occupationTime = 1.8, time = 2, priority = ()["Fish"] }, ["fisha15.mp3"] = { occupationTime = 1.8, time = 2, priority = ()["Fish"] }, ["fisha16.mp3"] = { occupationTime = 1.8, time = 2, priority = ()["Fish"] }, ["fisha17.mp3"] = { occupationTime = 1, time = 1, priority = ()["Fish"] }, ["Hit0.mp3"] = { occupationTime = 0, time = 0.1, priority = ()["HIT"] }, ["Hit1.mp3"] = { occupationTime = 0, time = 0.1, priority = ()["HIT"] }, ["Hit2.mp3"] = { occupationTime = 1, time = 1.5, priority = ()["HIT"] }, ["laser.mp3"] = { occupationTime = 0, time = 0.4, priority = ()["ATHER_II"] }, ["electric.mp3"] = { occupationTime = 0, time = 0.4, priority = ()["ATHER_II"] }, ["BigBang.mp3"] = { occupationTime = 1, time = 1, priority = ()["DEAD"] }, ["Bigfireworks.mp3"] = { occupationTime = 1, time = 0.2, priority = ()["ATHER_II"] }, ["fireworks.mp3"] = { occupationTime = 0.5, time = 0.2, priority = ()["ATHER_II"] }, ["click.mp3"] = { occupationTime = 0, time = 0, priority = ()["BUTTON"] }, ["sfx_bursts_fever.mp3"] = { occupationTime = 0, time = 0, priority = ()["DEAD"] }, ["sfx_blackhole.mp3"] = { occupationTime = 0, time = 0, priority = ()["DEAD"] }, ["bgm_boss.mp3"] = { occupationTime = 0, time = 0, priority = ()["ATHER"] }, ["sfx_levelup.mp3"] = { occupationTime = 0, time = 0, priority = ()["ACCOUNT"] }, ["sfx_window_open.mp3"] = { occupationTime = 0, time = 0, priority = ()["BUTTON"] }, ["sfx_window_close.mp3"] = { occupationTime = 0, time = 0, priority = ()["BUTTON"] }, ["sfx_coin.mp3"] = { occupationTime = 0, time = 0, priority = ()["GOLD"] }, ["sfx_thunder_fever.mp3"] = { occupationTime = 0, time = 0, priority = ()["ATHER"] } } FishTdSoundController.ctor = function (slot0) slot0:resetFishtdSoundManager() for slot4, slot5 in pairs(slot0) do audioMgr:preloadEffect(FilePath.SOUND .. "effect/" .. slot4) end end FishTdSoundController.resetFishtdSoundManager = function (slot0) slot0.m_lastEffectType = nil slot0.m_lastFishEffectType = nil slot0.m_fishEffectTime = 0 slot0.m_effectTime = 0 slot0.m_soundCategoryGameEffect = {} slot0.m_soundCategoryFishEffect = {} slot0.m_nVolume = 0 slot0.m_nCurnId = 0 slot0.m_bSound = true slot0.m_bMusic = true slot0.m_bgms = { "bgm1.mp3", "bgm2.mp3", "bgm3.mp3", "bgm4.mp3" } slot0.m_effects = { [Fish3DSound.GameEffect.CANNON_SWITCH] = "MakeUP.mp3", [Fish3DSound.GameEffect.CASTING_NORMAL] = "Net0.mp3", [Fish3DSound.GameEffect.CASTING_ION] = "Net1.mp3", [Fish3DSound.GameEffect.CATCH] = "Hit0.mp3", [Fish3DSound.GameEffect.CATCH1] = "Hit1.mp3", [Fish3DSound.GameEffect.CATCH2] = "Hit2.mp3", [Fish3DSound.GameEffect.FIRE] = "Fire.mp3", [Fish3DSound.GameEffect.IONFIRE] = "Fire.mp3", [Fish3DSound.GameEffect.INSERT] = "ChangeScore.mp3", [Fish3DSound.GameEffect.AWARD] = "award.mp3", [Fish3DSound.GameEffect.BIGAWARD] = "bigAward.mp3", [Fish3DSound.GameEffect.ROTARYTURN] = "rotaryturn.mp3", [Fish3DSound.GameEffect.BINGO] = "CJ.mp3", [Fish3DSound.GameEffect.BINGO2] = "TNNFDCLNV.mp3", [Fish3DSound.GameEffect.WAVE] = "surf.mp3", [Fish3DSound.GameEffect.EFFECT_BULLET_BOMB] = "Fire.mp3", [Fish3DSound.GameEffect.BOMB_LASER] = "laser.mp3", [Fish3DSound.GameEffect.BOMB_ELECTRIC] = "electric.mp3", [Fish3DSound.GameEffect.EFFECT_PARTICAL_BIG_BOMB] = "BigBang.mp3", [Fish3DSound.GameEffect.EFFECT_PARTICAL_BIG_FIREWORKS] = "Bigfireworks.mp3", [Fish3DSound.GameEffect.EFFECT_PARTICAL_FIREWORKS] = "fireworks.mp3", [Fish3DSound.GameEffect.BUTTON_CLICK] = "click.mp3", [Fish3DSound.GameEffect.FROZEN_EFFECT] = "sfx_bursts_fever.mp3", [Fish3DSound.GameEffect.BLACK_VORTEX] = "sfx_blackhole.mp3", [Fish3DSound.GameEffect.BOSS_COME] = "bgm_boss.mp3", [Fish3DSound.GameEffect.BOSS_ACCOUNT] = "sfx_levelup.mp3", [Fish3DSound.GameEffect.ION_CANNON_ACTIVE] = "ChangeType.mp3", [Fish3DSound.GameEffect.ION_CANNON_FIRE] = "Fire.mp3", [Fish3DSound.GameEffect.DIALOG_POPUP] = "sfx_window_open.mp3", [Fish3DSound.GameEffect.DIALOG_CLOSE] = "sfx_window_close.mp3", [Fish3DSound.GameEffect.GOLD_POPUP] = "sfx_coin.mp3", [Fish3DSound.GameEffect.EXPLODE] = "sfx_thunder_fever.mp3" } slot0.m_fishSound = { "fisha1.mp3", "fisha1.mp3", "fisha2.mp3", "fisha3.mp3", "fisha4.mp3", "fisha5.mp3", "fisha10.mp3", "fisha7.mp3", "fisha9.mp3", "fisha6.mp3", "fisha14.mp3", "fisha15.mp3", "fisha5.mp3", "fisha11.mp3", "fisha16.mp3", "fisha13.mp3", "fisha0.mp3", "fisha4.mp3", "fisha12.mp3", "fisha17.mp3", "fisha11.mp3", "fisha8.mp3" } slot0._killBossEffect = { chuitousha = Fish3DSound.GameEffect.BIGAWARD } slot0._bossCome = { chuitousha = Fish3DSound.GameEffect.BOSS_COME, zhangyu = Fish3DSound.GameEffect.BOSS_COME, haiyao = Fish3DSound.GameEffect.BOSS_COME } slot0._specialEffect = { [20.0] = 19, [21.0] = 21, [22.0] = 20 } slot0.effectRepeatState = { [Fish3DSound.GameEffect.GOLD_POPUP] = { maxCount = 3, clearInterval = 0.2, counter = 0, timer = 0 }, [Fish3DSound.GameEffect.BOMB_ELECTRIC] = { maxCount = 2, clearInterval = 0.1, counter = 0, timer = 0 }, [Fish3DSound.GameEffect.EXPLODE] = { maxCount = 1, clearInterval = 0.1, counter = 0, timer = 0 } } slot0.total = 0 slot0.totalTimer = 0 slot0.bossBgmTimer = 0 end FishTdSoundController.playRandomFishEffect = function (slot0, slot1) if slot0._specialEffect[slot1] then slot0:playFishTdFishEffect(slot0._specialEffect[slot1]) else slot0:playFishTdFishEffect((3 * (math.floor(math.random() * 79) + 1) * slot1 * slot1 + 7 * (math.floor(math.random() * 79) + 1) * slot1 + 29 * slot1 + 173) % 18 + 1) end end FishTdSoundController.playFishTdGameEffect = function (slot0, slot1) if slot0.total > 5 then return end if not slot0.m_effects[slot1] then return end if slot0.effectRepeatState[slot1] then if slot3.counter == slot3.maxCount then return else slot3.counter = slot3.counter + 1 slot0:playGameEffect(slot2) end else slot0:playGameEffect(slot2) end end FishTdSoundController.playFishTdFishEffect = function (slot0, slot1) if slot0.total > 5 then return end if not slot0.m_fishSound[slot1] then return end if not slot0[slot2] then return end slot0.m_soundCategoryFishEffect[slot3.priority] = slot0.m_soundCategoryFishEffect[slot3.priority] or { time = 0 } slot4 = socket.gettime() if slot0.m_soundCategoryFishEffect[slot3.priority].last_sound and slot4 - slot5.time < slot0[slot5.last_sound].time then return end slot5.time = slot4 slot5.last_sound = slot2 slot0:playGameEffect(slot2) end FishTdSoundController.playFishTdMusicByID = function (slot0, slot1) slot0:playMusic(ClassLoader:aquireSingleton("GameConfig").SceneSets[slot1].bgMap) slot0.currentBgMusicName = ClassLoader.aquireSingleton("GameConfig").SceneSets[slot1].bgMap slot0.bossBgmTimer = 0 end FishTdSoundController.playMusic = function (slot0, slot1, slot2) audioMgr:playMusic(FilePath.SOUND .. "bgm/" .. slot1, slot2 or 1) end FishTdSoundController.playGameEffect = function (slot0, slot1, slot2) audioMgr:playEffect(FilePath.SOUND .. "effect/" .. slot1, slot2 or false) slot0.total = slot0.total + 1 end FishTdSoundController.playEffectOnBossCome = function (slot0, slot1) audioMgr:playMusic(FilePath.SOUND .. "effect/bgm_boss.mp3") slot0.bossBgmTimer = 14 end FishTdSoundController.playEffectOnBossKill = function (slot0, slot1) if slot0._killBossEffect[slot1] then slot0:playFishTdGameEffect(slot0._killBossEffect[slot1]) end end FishTdSoundController.update = function (slot0, slot1) for slot5, slot6 in pairs(slot0.effectRepeatState) do slot6.timer = slot6.timer + slot1 if slot6.clearInterval < slot6.timer then slot6.timer = slot6.timer - slot6.clearInterval slot6.counter = 0 end end slot0.totalTimer = slot0.totalTimer + slot1 if slot0.totalTimer > 0.5 then slot0.total = 0 slot0.totalTimer = 0 end if slot0.bossBgmTimer > 0 then slot0.bossBgmTimer = slot0.bossBgmTimer - slot1 if slot0.bossBgmTimer <= 0 then slot0.bossBgmTimer = 0 slot0:playMusic(slot0.currentBgMusicName) end end end fishtdSound = FishTdSoundController.new() return
local Enemies = {} Enemies.enemy = {} local numEnemies = 3 for i =1, numEnemies do Enemies.enemy[i] = require "enemy" Enemies.enemy[i] = Enemy:new() Enemies.enemy[i]:init() end Enemies.projectiles = require "projectiles" Enemies.projectiles = Projectiles:new() local minXSpacing = 450 local maxXSpacing = 1200 local xSpacingRange = maxXSpacing - minXSpacing local currentX = 660 local minYSpacing = 100 local maxYSpacing = 500 local ySpacingRange = maxYSpacing - minYSpacing function Enemies:init() for i =1, numEnemies do Enemies.enemy[i] = require "enemy" Enemies.enemy[i] = Enemy:new() Enemies.enemy[i]:init() Enemies.enemy[i]:setPos(-100, 0) end currentX = 660 end function Enemies:update(dt) for i =1, numEnemies do Enemies.enemy[i]:update(dt) end end function Enemies:setPositions(camX, buildings) for i =1, numEnemies do if Enemies.enemy[i].pos.x < camX - 100 then local offScreenRight = camX + love.graphics.getWidth() if currentX < offScreenRight then currentX = offScreenRight + 100 end local enemy = Enemies.enemy[i] Enemies:setRandomPos(enemy) while buildings:overlaps(enemy) do Enemies:setRandomPos(enemy) end enemy.isAlive = true enemy.isExploding = false currentX = currentX + additionalX end end end function Enemies:setRandomPos(enemy) local randX = love.math.random() * xSpacingRange local randY = love.math.random() * ySpacingRange randX = randX + minXSpacing additionalX = randX randX = randX + currentX randY = randY + minYSpacing enemy:setPos(randX, randY) end function Enemies:getNumEnemies() return numEnemies end function Enemies:draw() love.graphics.setColor(255, 255, 255, 255) for i =1, numEnemies do Enemies.enemy[i]:draw() end end return Enemies
bankConfig = {}; bankConfig.bank = { Vector( -779.466736, 1220.188843, -200.307022), Vector(-1155.516113, 1353.531982, -52.040535) } // Where is the bank located. bankConfig.vault = { Vector(-1154.817139, 1401.917480, -25.699097), Vector(-1372.119385, 1135.647217, -200.667740) } bankConfig.bannerPos = Vector(-1100.998901, 958.953064, -50.336380) bankConfig.bannerAngle = Angle(0, 0, 90) bankConfig.bankGuards = {TEAM_POLICE, TEAM_MAYOR} bankConfig.bankGuardWeapons = {"weapon_ar2"}; // What weapons do bank security get. bankConfig.initialMoney = 1000 // How much money does the bank start out with. bankConfig.moneyGrowth = 200 // How much money does the bank get every interval of time. bankConfig.moneyGrowthTime = 4 // How long does it take for the bank to increase its worth. --Should be in seconds! bankConfig.robTime = 120 bankConfig.maxMoney = 20000 //How high should the vault's storage go bankConfig.minMoney = 2000 //Min money required for raiding bankConfig.restrictedTeams = { TEAM_ADMIN, } -- Don't include models/ or .mdl -- {Path, Offest, Angle, Scale} bankConfig.masks = { {"rinfect/payday/PAYDAY_AME", Vector(-3, 0, -67), Angle(0, 90, 0), 1}, {"rinfect/payday/PAYDAY_DINO", Vector(-2, 0, -65), Angle(0, 90, 0), 1}, {"rinfect/payday/PAYDAY_GAS", Vector(-2, 0, -67), Angle(0, 90, 0), 1} }
if os.get() == "windows" then os.mkdir("build"); os.mkdir("build/bin_x86"); os.mkdir("build/bin_x64"); -- Copy the SDL2 dlls to the build directory. os.copyfile("examples/sdl/lib/x86/SDL2.dll", "build/bin_x86/SDL2.dll"); os.copyfile("examples/sdl/lib/x64/SDL2.dll", "build/bin_x64/SDL2.dll"); end ----------------------------------------------------------------------------- solution "WidgetZero" language "C++" location "build" warnings "Extra" startproject "Example 1 - Demo" configurations { "Debug", "Release" } platforms { "native", "x64", "x32" } configuration "Debug" optimize "Debug" defines "_DEBUG" flags "Symbols" configuration "Release" optimize "Full" defines "NDEBUG" configuration "vs*" defines { "_CRT_SECURE_NO_DEPRECATE" } configuration { "not x64" } targetdir "build/bin_x86" configuration { "x64" } targetdir "build/bin_x64" ----------------------------------------------------------------------------- project "WidgetZero" kind "StaticLib" pchheader "wz.h" pchsource "src/wz_pch.cpp" defines "WZ_USE_PCH" files { "src/*.*" } includedirs { "nanovg" } ----------------------------------------------------------------------------- project "NanoVG" language "C" kind "StaticLib" files { "nanovg/*.*" } includedirs { "nanovg" } ----------------------------------------------------------------------------- function createExampleProject(_title, _name, _file) project(_title) kind "WindowedApp" targetname("example_" .. _name) files { "examples/" .. _file, "examples/gl/*.*" } includedirs { "src", "nanovg", "examples/gl" } configuration "linux" buildoptions { "`pkg-config --cflags sdl2`" } linkoptions { "`pkg-config --libs sdl2`" } links { "GL", "GLU" } configuration "vs*" includedirs("examples/sdl/include") links { "glu32", "opengl32" } configuration { "vs*", "not x64" } libdirs("examples/sdl/lib/x86") configuration { "vs*", "x64" } libdirs("examples/sdl/lib/x64") configuration {} links { "SDL2", "SDL2main", "NanoVG", "WidgetZero" } configuration "vs2012" linkoptions { "/SAFESEH:NO" } end createExampleProject("Example 1 - Demo", "demo", "Demo.cpp") createExampleProject("Example 2 - Simple", "simple", "Simple.cpp") ----------------------------------------------------------------------------- project "Example 3 - Custom Renderer" kind "WindowedApp" targetname "example_custom_renderer" files { "examples/CustomRenderer.cpp", "examples/tigr/*.*" } includedirs { "src", "examples/tigr" } links { "WidgetZero" } configuration "vs*" links { "d3d9" } configuration "vs2012" linkoptions { "/SAFESEH:NO" }
local socket = require("socket.core") local json = require("json") function connect(address, port, laddress, lport) local sock, err = socket.tcp() if not sock then return nil, err end if laddress then local res, err = sock:bind(laddress, lport, -1) if not res then return nil, err end end local res, err = sock:connect(address, port) if not res then return nil, err end return sock end function bind(host, port, backlog) local sock, err = socket.tcp() if not sock then return nil, err end sock:setoption("reuseaddr", true) local res, err = sock:bind(host, port) if not res then return nil, err end res, err = sock:listen(backlog) if not res then return nil, err end return sock end --sock, err = bind("127.0.0.1", 80, -1) --print(sock, err) sock2, err2 = connect("127.0.0.1", 81) sock2:settimeout(0) print("Connected", sock2, err2) function parseEndCallbackCommand(cmd, callbackName) if cmd[1] == callbackName then return true end return false end function waitUntilCallbackFinished(callbackName) --print("waitToEndCallback", callbackName) while true do local message, err, part = sock2:receive("*all") if not message then message = part end if message and string.len(message)>0 then --print(message) local recCommand = json.decode(message) if parseEndCallbackCommand(recCommand, callbackName) then return else --!!! if this is other command, not we are waiting, just send it to global parseCommand coroutine table.insert(commandsQueue, recCommand) coroutine.resume(parseCommandCoroutine) end end end end function emu_registerbeforewrapper(hfunc) sendToHost({"emu.registerbefore_callback", hfunc}) waitUntilCallbackFinished("emu.registerbefore_callback_finished") end function emu_registerbefore(hfunc) if hfunc == 0 then emu.registerbefore(nil) return end emu.registerbefore(function() emu_registerbeforewrapper(hfunc) end) end function emu_registerafterwrapper(hfunc) sendToHost({"emu.registerafter_callback", hfunc}) waitUntilCallbackFinished("emu.registerafter_callback_finished") end function emu_registerafter(hfunc) if hfunc == 0 then emu.registerafter(nil) return end emu.registerafter(function() emu_registerafterwrapper(hfunc) end) end function memory_registerexecutewrapper(hfunc, addr, size) sendToHost({"memory.registerexecute_callback", hfunc, addr, size}) waitUntilCallbackFinished("memory.registerexecute_callback_finished") end function memory_registerexecute(addr, size, hfunc) if hfunc == 0 then memory.registerexecute(addr, size, nil) return end memory.registerexecute(addr, size, function(addr, size) memory_registerexecutewrapper(hfunc, addr, size) end) end function memory_registerwritewrapper(hfunc, addr, size) sendToHost({"memory.registerwrite_callback", hfunc, addr, size}) waitUntilCallbackFinished("memory.registerwrite_callback_finished") end function memory_registerwrite(addr, size, hfunc) if hfunc == 0 then memory.memory_registerwrite(addr, size, nil) return end memory.registerwrite(addr, size, function(addr, size) memory_registerwritewrapper(hfunc, addr, size) end) end function sendToHost(cmd) local command = json.encode(cmd) sock2:send("json"..command) --json prefix for easy splitting group of commands end commandTable = {} methodsNoArgs = { ["emu.poweron"] = emu.poweron, ["emu.pause"] = emu.pause, ["emu.unpause"] = emu.unpause, ["emu.message"] = emu.message, ["emu.softreset"] = emu.softreset, ["emu.speedmode"] = emu.speedmode, --["emu.frameadvance"] = emu.frameadvance, --we can't call it via socket anyway ["emu.setrenderplanes"] = emu.setrenderplanes, ["emu.framecount"] = emu.framecount, ["emu.lagcount"] = emu.lagcount, ["emu.lagged"] = emu.lagged, ["emu.setlagflag"] = emu.setlagflag, ["emu.paused"] = emu.paused, ["emu.emulating"] = emu.emulating, ["emu.readonly"] = emu.readonly, ["emu.setreadonly"] = emu.setreadonly, ["emu.getdir"] = emu.getdir, ["emu.loadrom"] = emu.loadrom, ["emu.registerafter"] = emu_registerafter, ["emu.registerbefore"] = emu_registerbefore, ["emu.addgamegenie"] = emu.addgamegenie, ["emu.delgamegenie"] = emu.delgamegenie, ["emu.print"] = emu.print, --["emu.getscreenpixel"] = emu.getscreenpixel, --add this manually ["rom.readbyte"] = rom.readbyte, ["rom.readbytesigned"] = rom.readbytesigned, ["rom.writebyte"] = rom.writebyte, ["memory.readbyte"] = memory.readbyte, ["memory.readbytesigned"] = memory.readbytesigned, ["memory.readword"] = memory.readword, ["memory.readwordsigned"] = memory.readwordsigned, --["memory.readbyterange"] = memory.readbyterange, --need to encode string to byte values ["memory.writebyte"] = memory.writebyte, ["memory.registerexecute"] = memory_registerexecute, ["memory.registerwrite"] = memory_registerwrite, ["memory.getregister"] = memory.getregister, ["memory.setregister"] = memory.setregister, ["joypad.read"] = joypad.read, ["joypad.readimmediate"] = joypad.readimmediate, ["joypad.readdown"] = joypad.readdown, ["joypad.readup"] = joypad.readup, ["joypad.write"] = joypad.write, ["zapper.read"] = zapper.read, ["input.read"] = input.read, ["sound.get"] = sound.get, ["gui.pixel"] = gui.pixel, ["gui.getpixel"] = gui.getpixel, ["gui.line"] = gui.line, ["gui.box"] = gui.box, ["gui.text"] = gui.text, --["gui.parsecolor"] = gui.parsecolor, ["gui.savescreenshot"] = gui.savescreenshot, ["gui.savescreenshotas"] = gui.savescreenshotas, --["gui.gdscreenshot"] = gui.gdscreenshot, --[gui.gdoverlay] = gui.gdoverlay, ["gui.opacity"] = gui.opacity, ["gui.transparency"] = gui.transparency, --["gui.popup"] = gui.popup ["debugger.hitbreakpoint"] = debugger.hitbreakpoint, ["debugger.getcyclescount"] = debugger.getcyclescount, ["debugger.getinstructionscount"] = debugger.getinstructionscount, ["debugger.resetcyclescount"] = debugger.resetcyclescount, ["debugger.resetinstructionscount"] = debugger.resetinstructionscount, ["movie.active"] = movie.active, ["movie.mode"] = movie.mode, ["movie.rerecordcounting"] = movie.rerecordcounting, ["movie.stop"] = movie.stop, ["movie.length"] = movie.length, ["movie.name"] = movie.name, ["movie.getfilename"] = movie.getfilename, ["movie.rerecordcount"] = movie.rerecordcount, ["movie.replay"] = movie.replay, ["movie.readonly"] = movie.readonly, ["movie.setreadonly"] = movie.setreadonly, ["movie.recording"] = movie.recording, ["movie.playing"] = movie.ispoweron, ["movie.isfromsavestate"] = movie.isfromsavestate, } --for avoiding copypaste, really we can call methods by loadstring(methodName), by it's slower for methodName, method in pairs(methodsNoArgs) do commandTable[methodName] = function(currentCmd) --print("cmd:", currentCmd) table.remove(currentCmd, 1) -- now currentCmd is argument list local result = method(unpack(currentCmd)) --print("result:", result) sendToHost({methodName.."_finished", result}) end end --special case for method that return several values --emu.getscreenpixel commandTable["emu.getscreenpixel"] = function(currentCmd) --print("cmd:", currentCmd) table.remove(currentCmd, 1) -- now currentCmd is argument list local r,g,b,pal = emu.getscreenpixel(unpack(currentCmd)) --print("result:", {r,g,b,pal}) sendToHost({"emu.getscreenpixel".."_finished", {r,g,b,pal}}) end --special case for method that return string, need to reencoding it to array, as json can't encode string with non ascii characters --memory.readbyterange commandTable["memory.readbyterange"] = function(currentCmd) --print("cmd:", currentCmd) table.remove(currentCmd, 1) -- now currentCmd is argument list local str = memory.readbyterange(unpack(currentCmd)) arrayWithData = {} --reencoode string to table str:gsub(".",function(c) table.insert(arrayWithData, string.byte(c)) end) --print("result:", arrayWithData) sendToHost({"memory.readbyterange".."_finished", arrayWithData}) end commandsQueue = {} function parseCommand() while true do if commandsQueue[1] then currentCmd = table.remove(commandsQueue, 1) --print("parseCommand:", currentCmd) local cmdFunction = commandTable[currentCmd[1]] if cmdFunction then cmdFunction(currentCmd) end end coroutine.yield() end end parseCommandCoroutine = coroutine.create(parseCommand) function passiveUpdate() local message, err, part = sock2:receive("*all") if not message then message = part end if message and string.len(message)>0 then --print(message) local recCommand = json.decode(message) table.insert(commandsQueue, recCommand) coroutine.resume(parseCommandCoroutine) end end function main() while true do passiveUpdate() emu.frameadvance() end end gui.register(passiveUpdate) --undocumented. this function will call even if emulator paused main()
--[[ Copyright 2020 The Defold Foundation Authors & Contributors 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 tictactoe = require("tictactoe_state") local nk = require("nakama") local M = {} local OP_CODE_MOVE = 1 local OP_CODE_STATE = 2 local function pprint(t) if type(t) ~= "table" then nk.logger_info(tostring(t)) else for k,v in pairs(t) do nk.logger_info(string.format("%s = %s", tostring(k), tostring(v))) end end end local function broadcast_gamestate_to_recipient(dispatcher, gamestate, recipient) nk.logger_info("broadcast_gamestate") local active_player = tictactoe.get_active_player(gamestate) local other_player = tictactoe.get_other_player(gamestate) local your_turn = active_player.user_id == recipient.user_id local message = { state = gamestate, active_player = active_player, other_player = other_player, your_turn = your_turn, } local encoded_message = nk.json_encode(message) dispatcher.broadcast_message(OP_CODE_STATE, encoded_message, { recipient }) end local function broadcast_gamestate(dispatcher, gamestate) local player = tictactoe.get_active_player(gamestate) local opponent = tictactoe.get_other_player(gamestate) broadcast_gamestate_to_recipient(dispatcher, gamestate, player) broadcast_gamestate_to_recipient(dispatcher, gamestate, opponent) end function M.match_init(context, setupstate) nk.logger_info("match_init") local gamestate = tictactoe.new_game() local tickrate = 1 -- per sec local label = "" return gamestate, tickrate, label end function M.match_join_attempt(context, dispatcher, tick, gamestate, presence, metadata) nk.logger_info("match_join_attempt") local acceptuser = true return gamestate, acceptuser end function M.match_join(context, dispatcher, tick, gamestate, presences) nk.logger_info("match_join") for _, presence in ipairs(presences) do tictactoe.add_player(gamestate, presence) end if tictactoe.player_count(gamestate) == 2 then broadcast_gamestate(dispatcher, gamestate) end return gamestate end function M.match_leave(context, dispatcher, tick, gamestate, presences) nk.logger_info("match_leave") -- end match if someone leaves return nil end function M.match_loop(context, dispatcher, tick, gamestate, messages) nk.logger_info("match_loop") for _, message in ipairs(messages) do nk.logger_info(string.format("Received %s from %s", message.data, message.sender.username)) pprint(message) if message.op_code == OP_CODE_MOVE then local decoded = nk.json_decode(message.data) local row = decoded.row local col = decoded.col gamestate = tictactoe.player_move(gamestate, row, col) if gamestate.winner or gamestate.draw then gamestate.rematch_countdown = 10 end broadcast_gamestate(dispatcher, gamestate) end end if gamestate.rematch_countdown then gamestate.rematch_countdown = gamestate.rematch_countdown - 1 if gamestate.rematch_countdown == 0 then gamestate = tictactoe.rematch(gamestate) end broadcast_gamestate(dispatcher, gamestate) end return gamestate end function M.match_terminate(context, dispatcher, tick, gamestate, grace_seconds) nk.logger_info("match_terminate") local message = "Server shutting down in " .. grace_seconds .. " seconds" dispatcher.broadcast_message(2, message) return nil end return M
local call_table call_table = function(value) if value == 0 then return "inc" elseif value == 1 then return "dec" elseif value == 2 then return "next" elseif value == 3 then return "prev" elseif value == 4 then return "loop" elseif value == 5 then return "endloop" elseif value == 6 then return "put" elseif value == 7 then return "get" else return "err" end end local parse parse = function(program) local ast = { } local ptr = 0 for chr in program:gmatch(".") do if chr == "," then if ptr == 7 then ptr = 0 else ptr = ptr + 1 end elseif chr == "." then ast[#ast + 1] = call_table(ptr) end end return ast end local eval eval = function(ast, program_ptr, jump_table, stack, stack_ptr) if program_ptr == nil then program_ptr = 1 end if jump_table == nil then jump_table = { } end if stack == nil then stack = { } end if stack_ptr == nil then stack_ptr = 1 end if #stack == 0 then for i = 1, 255 do stack[i] = 0 end end while program_ptr <= #ast do local com = ast[program_ptr] if com ~= nil then if stack_ptr > 255 then stack_ptr = 0 elseif stack_ptr < 0 then stack_ptr = 255 end if stack[stack_ptr] > 255 then stack[stack_ptr] = 0 elseif stack[stack_ptr] < 0 then stack[stack_ptr] = 255 end if com == "inc" then stack[stack_ptr] = stack[stack_ptr] + 1 program_ptr = program_ptr + 1 elseif com == "dec" then stack[stack_ptr] = stack[stack_ptr] - 1 program_ptr = program_ptr + 1 elseif com == "next" then stack_ptr = stack_ptr + 1 program_ptr = program_ptr + 1 elseif com == "prev" then stack_ptr = stack_ptr - 1 program_ptr = program_ptr + 1 elseif com == "loop" then jump_table[#jump_table + 1] = program_ptr program_ptr = program_ptr + 1 elseif com == "endloop" then if stack[stack_ptr] == 0 then table.remove(jump_table, #jump_table) program_ptr = program_ptr + 1 else program_ptr = jump_table[#jump_table] end elseif com == "put" then io.write(string.char(stack[stack_ptr])) io.flush() program_ptr = program_ptr + 1 elseif com == "get" then stack[stack_ptr] = string.byte(io.read(1)) program_ptr = program_ptr + 1 end end end return { ast = ast, program_ptr = program_ptr, jump_table = jump_table, stack = stack, stack_ptr = stack_ptr } end if arg[1] == "--file" then local f = io.open(arg[2], "r") if f then local program = f:read() f:close() return eval(parse(program)) else return print("Could not open file.") end elseif arg[1] == "-" then local program = io.read() local data = eval(parse(program)) while true do data = eval(data["ast"], data["program_ptr"], data["jump_table"], data["stack"], data["stack_ptr"]) end else local program = io.read() local data = eval(parse(program)) while true do data = eval(data["ast"], data["program_ptr"], data["jump_table"], data["stack"], data["stack_ptr"]) end end
SKILL.name = "Sigmars Blessing" SKILL.LevelReq = 5 SKILL.SkillPointCost = 2 SKILL.Incompatible = { } SKILL.RequiredSkills = { } SKILL.icon = "vgui/skills/Spell_holy_surgeoflight.png" SKILL.category = "Followers of Sigmar"-- Common Passives, Warrior, Stealth, Lore of Light, Dark Magic SKILL.slot = "AOE" -- ULT, RANGED, MELEE, AOE, PASSIVE SKILL.class = { "cultist_sigmar" } SKILL.desc = [[ You call upon Sigmar to bless your allies with a portion of his divinity, bolstering them in combat. Duration: 10 Seconds. Regen: 5 (+0.5 Faith) Speed: 1.0 Faith Range: 250 Units. Cost: 60 Energy Cooldown: 30 Seconds. Class Restriction: Ability Slot: AOE (3) Level Requirement: ]] .. SKILL.LevelReq .. [[ Skill Point Cost:]] .. SKILL.SkillPointCost .. [[ ]] SKILL.coolDown = 30 local function ability( SKILL, ply ) local nospam = ply:GetNWBool( "nospamAOE" ) // nospamRanged, nospamUlt, nospamAOE, nospamMelee if (nospam) then if timer.Exists(ply:SteamID().."nospamAOE") then return end timer.Create(ply:SteamID().."nospamAOE", SKILL.coolDown, 1, function() ply:SetNWBool( "nospamAOE", false ) end) return end local mana = ply:getLocalVar("mana", 0) if mana < 60 then return end ply:setLocalVar("mana", mana - 60) local char = ply:getChar() local Entities = ents.FindInSphere( ply:GetPos(), 250 ) for k, v in pairs(Entities) do if v:IsPlayer() or (v:IsPlayer() and v:IsBot()) and v:Team() == ply:Team() then local regenHealth = (char:getAttrib("fth", 0) /2) + 20 local maxHealth = v:GetMaxHealth() local naturalMaxHP = char:getData("naturalHPMax", 0) char:setData("tempHPMax", naturalMaxHP + (maxHealth * 0.2)) v:SetHealth(v:Health() + (v:Health() * 0.2)) v:HealthRegeneration(regenHealth) timer.Create("emperorsblessing"..(v:SteamID() or v:Nick()), 0.25, 4, function() ParticleEffectAttach("fantasy_sigmar_enhance_great", PATTACH_POINT_FOLLOW, ply, 3) end) timer.Simple(10, function() char:setData("tempHPMax", naturalMaxHP) v:SetHealth(maxHealth) v:HealthRegeneration(0) end) end end if (SERVER) then ply:SetNWBool( "nospamAOE", true ) net.Start( "AOEActivated" ) // RangedActivated, UltActivated, AOEActivated, MeleeActivated net.Send( ply ) if timer.Exists(ply:SteamID().."nospamAOE") then return end timer.Create(ply:SteamID().."nospamAOE", SKILL.coolDown, 1, function() ply:SetNWBool( "nospamAOE", false ) end) end end SKILL.ability = ability
-- Demonstration Command return { run = function(arg, msg) msg:reply('Pong!') end, description = 'Ping Pong', group = 'utility', aliases = {'pong'} }
--------------------------------------------------------------------- -- Project: irc -- Author: MCvarial -- Contact: [email protected] -- Version: 1.0.0 -- Date: 31.10.2010 --------------------------------------------------------------------- -- everything is saved here servers = {} -- syntax: [server] = {element socket,string name,string host,string nick,string password,number port,bool secure,string nickservpass,string authident, string authpass,number lastping,timer timeoutguard,number reconnectattempts, table channels,bool connected,table buffer} ------------------------------------ -- Servers ------------------------------------ function func_ircRaw (server,data) if servers[server] and servers[server][1] then if servers[server][15] then writeLog("-> "..data) return sockWrite(servers[server][1],data.."\r\n") end table.insert(servers[server][16],data) return true end return false end function func_ircHop (channel,reason) if channels[channel] then local name = channels[channel][1] local password = channels[channel][6] if ircPart(channel) then return ircJoin(name,password) end end return false end function func_ircSay (target,message) if #message > 400 then for i=1,math.ceil(#message/400) do ircSay(target,string.sub(message,(i-1)*400,i*400)) end return true end local server = getElementParent(target) local channel = ircGetChannelName(target) local user = ircGetUserNick(target) if server then local localuser = ircGetUserFromNick(ircGetServerNick(server)) if localuser then if channel then triggerEvent("onIRCMessage",localuser,target,message) else triggerEvent("onIRCPrivateMessage",target,message) end end return ircRaw(server,"PRIVMSG "..(channel or user).." :"..(message or "<no message>")) end return false end function func_ircPart (server,channel,reason) if servers[server] and channels[channel] then if getElementType(server) == "irc-server" then local channelName = ircGetChannelName(channel) if channelName then if reason then return ircRaw(server,"PART "..channelName.." :"..reason) else return ircRaw(server,"PART "..channelName) end end end end return false end function func_ircJoin (server,channel,password) if servers[server] then table.insert(servers[server][14],channel) local chan = createElement("irc-channel") setElementParent(chan,server) if #getElementsByType("irc-channel") == 1 then channels[chan] = {channel,"+nst","Unknown",{},password,false,true} else channels[chan] = {channel,"+nst","Unknown",{},password,false,false} end if password then ircRaw(server,"JOIN "..channel.." :"..password) else ircRaw(server,"JOIN "..channel) end ircRaw(server,"NAMES "..channel) return chan else return false end end function func_ircAction (channel,message) if #message > 400 then for i=1,math.ceil(#message/400) do ircAction(channel,string.sub(message,(i-1)*400,i*400)) end return true end local server = getElementParent(channel,0) local channelName = ircGetChannelName(channel) if server and channelName then return ircRaw(server,"ACTION "..channelName.." :"..(message or "<no message>")) end return false end function func_ircNotice (target,message) if #message > 400 then for i=1,math.ceil(#message/400) do ircNotice(target,string.sub(message,(i-1)*400,i*400)) end return true end local server = getElementParent(target,0) local targetName = ircGetChannelName(target) if not targetName then targetName = ircGetUserNick(target) end if server and targetName then return ircRaw(server,"NOTICE "..targetName.." :"..(message or "<no message>")) end return false end function func_outputIRC (message) if #message > 400 then for i=1,math.ceil(#message/400) do outputIRC(string.sub(message,(i-1)*400,i*400)) end return true end for i,channel in pairs (ircGetChannels()) do if ircIsEchoChannel(channel) then local server = getElementParent(channel) local localuser = ircGetUserFromNick(ircGetServerNick(server)) if server then if localuser then triggerEvent("onIRCMessage",localuser,channel,message) end return ircRaw(server,"PRIVMSG "..ircGetChannelName(channel).." :"..(message or "<no message>")) end end end return false end function func_ircIdentify (server,password) if servers[server] then servers[server][8] = password return ircRaw(server,"PRIVMSG NickServ :IDENTIFY "..(password or "")) end return false end function func_ircConnect (host,nick,port,password,secure) local server = createElement("irc-server") local socket,sockError = sockOpen(host,(port or 6667),secure) if server and socket then servers[server] = {socket,host,host,nick,password,port,secure,false,false,false,getTickCount(),nil,0,{},false,{}} triggerEvent("onIRCConnecting",server) return server end if sockError then outputServerLog("IRC: Failed to connect to "..tostring(host).." reason: "..getSocketErrorString(sockError)) end return false end function func_ircReconnect (server,reason) if type(reason) ~= "string" then reason = "reconnecting..." end if servers[server] then triggerEvent("onIRCDisconnect",server,reason) ircRaw(server,"QUIT :"..reason) sockClose(servers[server][1]) triggerEvent("onIRCConnecting",server) servers[server][15] = false servers[server][1] = sockOpen(ircGetServerHost(server),ircGetServerPort(server),ircIsServerSecure(server)) if servers[server][8] then ircRaw(server,"PRIVMSG NickServ :IDENTIFY "..tostring(servers[server][8])) end for i,channel in ipairs (servers[server][14]) do ircRaw(server,"JOIN "..tostring(channel)) end return true end return false end function func_ircDisconnect (server,reason) if servers[server] then ircRaw(server,"QUIT :"..(reason or "Disconnect")) sockClose(servers[server][1]) servers[server] = nil return destroyElement(server) end return false end function func_ircChangeNick (server,newnick) if servers[server] and type(newnick) == "string" then servers[server][4] = newnick return ircRaw(server,"NICK :"..newnick) end return false end function func_ircGetServers () return getElementsByType("irc-server") end function func_ircGetServerName (server) if servers[server] then return servers[server][2] end return false end function func_ircGetServerHost (server) if servers[server] then return servers[server][3] end return false end function func_ircGetServerPort (server) if servers[server] then return servers[server][6] end return false end function func_ircGetServerPass (server) if servers[server] then return servers[server][5] end return false end function func_ircGetServerNick (server) if servers[server] then return servers[server][4] end return false end function func_ircIsServerSecure (server) if servers[server] then return servers[server][7] end return false end function func_ircGetServerChannels (server) if servers[server] then return servers[server][14] end return false end
---@meta resty_websocket_client={} function resty_websocket_client.send_text(self, data) end function resty_websocket_client.new(self, opts) end function resty_websocket_client.send_ping(self, data) end function resty_websocket_client.connect(self, uri, opts) end function resty_websocket_client.set_timeout(self, time) end function resty_websocket_client.set_keepalive(self, ...) end function resty_websocket_client.send_binary(self, data) end function resty_websocket_client.send_close() end function resty_websocket_client.send_frame() end function resty_websocket_client.recv_frame(self) end function resty_websocket_client.close(self) end resty_websocket_client._VERSION="0.07" function resty_websocket_client.send_pong(self, data) end return resty_websocket_client
--[[ ItemSystems.RollLootManager ================ Description: Creates rolled loot objects that clients will listen for. ]] local ROLLENTRY_TEMPLATE = script:GetCustomProperty("RollEntryTemplate") local ROLLER_TEMPLATE = script:GetCustomProperty("RollerTemplate") local ROLL_EXPIRETIME = script:GetCustomProperty("RollExpireTime") local ReliableEvents = require(script:GetCustomProperty("ReliableEvents")) local Database = require(script:GetCustomProperty("ItemSystems_Database")) Database:WaitUntilLoaded() local entries = {} -- Create a string full of players IDs concatenated together. local function PlayersToIDTable(players) local ids = '' for _, player in pairs(players) do ids = ids .. player.id end return ids end local function GetEntry(id) for _, entry in pairs(entries) do if entry.serverUserData.id == id then return entry end end return nil end local function DeleteEntry(oldEntry) for i, entry in pairs(entries) do if entry == oldEntry then if Object.IsValid(entry) then table.remove(entries, i) entry:Destroy() end end end end -- When rolling is complete we will determine the the winner and reward them then destroy the entry as it's finished. local function RollingComplete(entry) -- CoreObject local highestRoller = 0 local winner = nil if not Object.IsValid(entry) then return end for _, playerEntry in pairs(entry.serverUserData.replies) do if playerEntry.roll > highestRoller and playerEntry.participated then highestRoller = playerEntry.roll winner = playerEntry.player end end if winner ~= nil and Object.IsValid(winner) then local winnerInventory = winner.serverUserData.inventory if winnerInventory:IsBackpackFull() then Events.Broadcast("DropLootSpecificHashForPlayers",entry.serverUserData.rolledItem:PersistentHash(),winner,winner:GetWorldPosition() + Vector3.UP * -100) else winnerInventory:AddItem(entry.serverUserData.rolledItem) ReliableEvents.BroadcastToPlayer(winner,"AddWonItem",entry.serverUserData.rolledItem:PersistentHash()) end end DeleteEntry(entry) end -- Check if someone already rolled our number. local function GetValidRoll(entry) -- CoreObject local roll = math.random(1,100) for _, playerEntry in pairs(entry.serverUserData.replies) do if playerEntry.roll == roll then GetValidRoll(entry) end end return roll end -- Receives a client request local function ProcessRollRequest(player,id,request) -- player, int, bool local entry = GetEntry(id) if not Object.IsValid(entry) then return end local replies = entry.serverUserData.replies local requiredReplies = entry.serverUserData.requiredReplies local roll = GetValidRoll(entry) if request then -- If the player wants to participat in the roll. -- Clients will be listening for the players roll child. When they receive it they'll display what the person rolled above their head. local newRollerEntry = World.SpawnAsset(ROLLER_TEMPLATE) newRollerEntry:SetNetworkedCustomProperty("PlayerName",player.name) newRollerEntry:SetNetworkedCustomProperty("Rolled",roll) newRollerEntry.parent = entry else local newRollerEntry = World.SpawnAsset(ROLLER_TEMPLATE) newRollerEntry:SetNetworkedCustomProperty("PlayerName",player.name) newRollerEntry:SetNetworkedCustomProperty("Rolled",0) newRollerEntry.parent = entry end table.insert(replies,{ player = player, participated = request, roll = roll, }) if #replies >= requiredReplies then Task.Wait(1) -- Wait for the last player to see their roll. RollingComplete(entry) end end -- Create a rolled loot entry that specified clients will receive to roll upon. local function CreateRollForLootEntry(dropKey, players) -- string, table of players --assert(#players > 1, "You need more than 1 player to create rollable loot.") local rolledItem = Database:CreateItemFromDrop(dropKey) local rollEntry = World.SpawnAsset(ROLLENTRY_TEMPLATE,{ parent = script }) local ID = #entries+1 local playerIds = PlayersToIDTable(players) table.insert(entries,ID,rollEntry) rollEntry:SetNetworkedCustomProperty('ItemHash',rolledItem:PersistentHash()) rollEntry:SetNetworkedCustomProperty("RequestedPlayers",playerIds) rollEntry:SetNetworkedCustomProperty("ID",ID) rollEntry.serverUserData.rolledItem = rolledItem rollEntry.serverUserData.id = ID rollEntry.serverUserData.requiredReplies = #players -- Amount of replies required to process the roll. rollEntry.serverUserData.replies = {} -- { player, rollType } Task.Wait(ROLL_EXPIRETIME + 3) -- Expire time + extra time. We can't be sure that the client and server will be synced. RollingComplete(rollEntry) end Events.Connect('RollForLootDrop', CreateRollForLootEntry) Events.ConnectForPlayer("ProcessRollRequest", ProcessRollRequest)
require 'setup/setup' local dummy = { dummy = "dummy" } -- we fulfill or reject with this when we don't intend to test against it describe("2.3.1: If `promise` and `x` refer to the same object, reject `promise` with a `TypeError' as the reason.", function() specify("via return from a fulfilled promise", function(done) local promise promise = resolved(dummy):Then(function() return promise end) promise:Then(nil, function(reason) assert.equal(reason, "TypeError: Tried to pass promise to itself") done() end) end) specify("via return from a rejected promise", function(done) local promise promise = rejected(dummy):Then(nil, function() return promise end) promise:Then(nil, function(reason) assert.equal(reason, "TypeError: Tried to pass promise to itself") done() end) end) end)
-- Node definitions minetest.register_node("bitchange:minecoinblock", { description = "MineCoin Block", tiles = { "bitchange_minecoinblock.png" }, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), stack_max = 30000, }) minetest.register_craftitem("bitchange:minecoin", { description = "MineCoin", inventory_image = "bitchange_minecoin.png", stack_max = 30000, }) minetest.register_craftitem("bitchange:mineninth", { description = "MineNinth", inventory_image = "bitchange_mineninth.png", stack_max = 30000, }) -- Crafting if bitchange.craft_convert_currency then minetest.register_craft({ output = "bitchange:minecoinblock", recipe = { {"bitchange:minecoin", "bitchange:minecoin", "bitchange:minecoin"}, {"bitchange:minecoin", "bitchange:minecoin", "bitchange:minecoin"}, {"bitchange:minecoin", "bitchange:minecoin", "bitchange:minecoin"}, } }) minetest.register_craft({ output = "bitchange:minecoin 9", recipe = { {"bitchange:minecoinblock"}, } }) minetest.register_craft({ output = "bitchange:minecoin", recipe = { {"bitchange:mineninth", "bitchange:mineninth", "bitchange:mineninth"}, {"bitchange:mineninth", "bitchange:mineninth", "bitchange:mineninth"}, {"bitchange:mineninth", "bitchange:mineninth", "bitchange:mineninth"}, } }) minetest.register_craft({ output = "bitchange:mineninth 9", recipe = { {"bitchange:minecoin"}, } }) end -- Cooking minetest.register_craft({ type = "cooking", recipe = "default:goldblock", output = "bitchange:minecoinblock 2", }) minetest.register_craft({ type = "cooking", recipe = "bitchange:minecoinblock", output = "default:gold_ingot 4", }) -- Legacy if bitchange.enable_generation then minetest.log("warning", "[bitchange] Ores will not be generated any more. Remove the setting " .. "'enable_generation' from your bitchange configuration to suppress this warning.") end minetest.register_alias("bitchange:minecoin_in_ground", "default:stone_with_gold") minetest.register_alias("bitchange:mineninth_in_ground", "default:stone_with_tin") minetest.register_alias("bitchange:coinbase", "bitchange:mineninth")
function Wall(x1, y1, x2, y2, thickness) local wall = { name = 'wall', x1 = NormalizeToWindowWidth(x1), y1 = NormalizeToWindowHeight(y1), x2 = NormalizeToWindowWidth(x2), y2 = NormalizeToWindowHeight(y2), thickness = thickness, } wall.collide = function(trigger) local x1 = trigger.x local y1 = trigger.y local w1 = trigger.border_offset_width local h1 = trigger.border_offset_height local x2 = wall.x1 local y2 = wall.y1 local w2 = wall.x2 - wall.x1 local h2 = wall.y2 - wall.y1 return x1 < x2+w2 and x2 < x1+w1 and y1 < y2+h2 and y2 < y1+h1 end wall.draw = function() love.graphics.setColor(globals.colors.blue) love.graphics.rectangle( 'fill', wall.x1 * globals.win_width, wall.y1 * globals.win_height, wall.x2 * globals.win_width, wall.y2 * globals.win_height ) love.graphics.setColor(globals.colors.default) end return wall end
PLUGIN.stalkernames = { "Alex", "Alexander", "Alexei", "Anatoly", "Andrei", "Andryuha", "Anton", "Arkasha", "Arthur", "Artyom", "Bodya", "Bogdan", "Borka", "Borya", "Boryan", "Danila", "Danko", "Danya", "Denis", "Dima", "Dimka", "Dimon", "Dimuha", "Dmitro", "Dmitry", "Edik", "Egor", "Egorka", "Fedka", "Fedya", "Felka", "Filka", "Filya", "Fima", "Fimka", "Fyodor", "Gena", "Genka", "Georg", "German", "Gleb", "Gosha", "Grisha", "Grishka", "Grishko", "Igoryok", "Ilya", "Ilyuha", "Ivan", "Kolya", "Kolyan", "Konstantin", "Kostik", "Kostya", "Kostyan", "Lenka", "Lyoha", "Lyonya", "Lyosha", "Lyoshka", "Lyova", "Matvey", "Max", "Miha", "Mihal", "Mihas", "Misha", "Mishka", "Mitka", "Mitya", "Nik", "Nikita", "Oleg", "Oles", "Pasha", "Pashka", "Pavluha", "Petka", "Petro", "Petruha", "Petya", "Roma", "Roman", "Romka", "Rostik", "Rus", "Ruslan", "Sanya", "Sanyok", "Sasha", "Sava", "Semyon", "Senya", "Sergei", "Seryoga", "Seva", "Sevka", "Shurik", "Slava", "Slavik", "Stepa", "Stepan", "Stepuha", "Styopka", "Syoma", "Tima", "Timka", "Timoha", "Toha", "Tolay", "Tolik", "Toshka", "Tyomka", "Vadik", "Vadim", "Vadya", "Valera", "Valik", "Vanka", "Vanya", "Vasek", "Vaska", "Vasko", "Vasya", "Vasyan", "Veniamin", "Venya", "Vetal", "Vitalik", "Vitaly", "Vitka", "Vitya", "Vityuha", "Vlad", "Vladimir", "Vova", "Vovan", "Vovka", "Yara", "Yarik", "Yasha", "Yashka", "Yura", "Yuras", "Yurka", "Yurko", "Yury", "Zheka", "Zhenka", "Zhenya", "Zhora", "Zhorka", } PLUGIN.stalkersnames = { "Abdurhmanov", "Alfyorov", "Altynnik", "Andreychuk", "Andreyev", "Andruschenko", "Aniseyev", "Antipin", "Ardashev", "Babich", "Balan", "Balitsky", "Baranov", "Baranovsky", "Barsak", "Bashakov", "Bashmakov", "Baul", "Belyavin", "Beshevliy", "Binoyev", "Blinov", "Bobrov", "Bogdanov", "Bogomolov", "Boldeskul", "Boldskul", "Bondarev", "Borisov", "Boychenko", "Boyko", "Brich", "Bronshtein", "Buryak", "Buturin", "Byalo", "Chernodub", "Chirikov", "Denisenko", "Dombrik", "Dotsenko", "Dovgalyuk", "Drozdush", "Dubenchuk", "Dudorov", "Duka", "Dumko", "Dunayev", "Dyakonov", "Dyklov", "Efremov", "Erofeyev", "Erohin", "Fadeyev", "Feygelman", "Galkin", "Ganzyuk", "Garkovenko", "Garkusha", "Gatsula", "Gatsula", "Georgov", "Geshkenbein", "Glebovsky", "Gnatyuk", "Goncharenko", "Gordiyenko", "Gorlevoy", "Gorohin", "Goryunov", "Grebenyuk", "Grischuk", "Grishachev", "Gritsay", "Gritsayenko", "Gritsenko", "Gubar", "Gunko", "Gurevich", "Ignatenko", "Ischuk", "Ivanov", "Ivchenko", "Izhenko", "Kabanov", "Kandybabko", "Kapuka", "Kapustyanko", "Katz", "Kazakov", "Kazantsev", "Khaladze", "Kikabidze", "Kireyev", "Klimenko", "Kolontar", "Kolontarev", "Kondratenko", "Korkin", "Korneyev", "Kovalchuk", "Koyev", "Kozlov", "Kravchenko", "Krivda", "Krivohatsky", "Kucheruk", "Kulchitsky", "Kuntsev", "Kurvits", "Kushnaryov", "Kuzmich", "Kuznetsov", "Kuzyakin", "Larin", "Lavrik", "Lavrov", "Ledentsov", "Lisichansky", "Litvin", "Livshits", "Lymarenko", "Makarenko", "Maltsev", "Mamayev", "Manko", "Mazepa", "Merzlyayev", "Milchenko", "Mironov", "Mironyuk", "Morer", "Morozov", "Mostovoy", "Muhamedov", "Muntyan", "Myskov", "Navrotsky", "Nepritsky", "Nikanorov", "Nikeshin", "Nikulin", "Nordiyev", "Nosan", "Novikov", "Oganesyan", "Opolev", "Orlevich", "Orlov", "Petkevich", "Petrenko", "Petrov", "Plohenko", "Podyachev", "Polyanin", "Poplavsky", "Popov", "Portnyh", "Prasolov", "Prokopenko", "Proskurin", "Protsenko", "Prudov", "Puchek", "Pustovar", "Rabinovich", "Radkevich", "Rezun", "Rodnyansky", "Rogoza", "Rotan", "Rublev", "Rudik", "Rusanov", "Rychagirsky", "Sabchenko", "Sagitov", "Savchenko", "Savchuk", "Sedyh", "Sereda", "Shilov", "Sidorenko", "Sidorov", "Sinayev", "Sinitsyn", "Siniy", "Skameyka", "Slutsky", "Smelov", "Smoliy", "Sorokin", "Spirin", "Statsyura", "Steklov", "Stepanenko", "Stepchin", "Stichinsky", "Sviridov", "Sykula", "Tarnavsky", "Tatarchuk", "Timchuk", "Valentinov", "Vasilevich", "Vasiliev", "Veselov", "Vinogradov", "Volanchuk", "Volodar", "Voloshin", "Vorohayev", "Vorontsov", "Vovnenko", "Vyushinsky", "Zabiyagoda", "Zagorodnyuk", "Zaharin", "Zaharov", "Zaikin", "Zamosenchuk", "Zarubin", "Zhabenko", "Zhmiyev", "Zhurakovsky", "Zolotar", "Zonovyev", "Zozo", "Zubarev", "Zubkov", "Zvonnitsky", } PLUGIN.pdaavatars = { -- gasmaskless, balaclava loners "propic/loner/loner1", "propic/loner/loner100", "propic/loner/loner11", "propic/loner/loner12", "propic/loner/loner13", "propic/loner/loner14", "propic/loner/loner16", "propic/loner/loner17", "propic/loner/loner3", "propic/loner/loner47", "propic/loner/loner53", "propic/loner/loner62", "propic/loner/loner63", "propic/loner/loner79", "propic/loner/loner8", "propic/loner/loner80", "propic/loner/loner81", "propic/loner/loner83", "propic/loner/loner84", "propic/loner/loner85", "propic/loner/loner86", "propic/loner/loner87", "propic/loner/loner90", "propic/loner/loner96", "propic/loner/loner98", --gasmaskless, no balaclava loners, some story chars "propic/loner/loner19", "propic/loner/loner20", "propic/loner/loner21", "propic/loner/loner22", "propic/loner/loner23", "propic/loner/loner25", "propic/loner/loner26", "propic/loner/loner27", "propic/loner/loner28", "propic/loner/loner29", "propic/loner/loner30", "propic/loner/loner31", "propic/loner/loner32", "propic/loner/loner33", "propic/loner/loner34", "propic/loner/loner35", "propic/loner/loner36", "propic/loner/loner38", "propic/loner/loner39", "propic/loner/loner4", "propic/loner/loner40", "propic/loner/loner41", "propic/loner/loner5", "propic/loner/loner6", "propic/loner/loner64", "propic/loner/loner65", "propic/loner/loner66", "propic/loner/loner67", "propic/loner/loner70", "propic/loner/loner71", "propic/loner/loner72", "propic/loner/loner9", "propic/loner/loner91", "propic/loner/loner92", "propic/loner/loner93", "propic/loner/loner94", }
package.loaded.layouts = nil local layouts = require "layouts" package.loaded.utils = nil local utils = require "utils" local readIntBE = utils.readIntBE local subclass = utils.subclass local CompoundElement = layouts.CompoundElement local SimpleElement = layouts.SimpleElement -- Display a memory value using per-character images (effectively a bitmap font). local ImageValueDisplay = subclass(CompoundElement) function ImageValueDisplay:init(window, returnFuncOrValue, numCharacters, fontName, passedDisplayOptions) -- This can be any kind of MemoryValue. The only constraint is that all the possible -- characters that can be displayed are covered in the charImages defined below. self.returnFuncOrValue = returnFuncOrValue -- Max number of characters to show in this display. This is how many Image objects -- we'll maintain. self.numCharacters = numCharacters -- display options to pass into the memory value's display() method. self.displayOptions = {nolabel=true} self.fontName = fontName if passedDisplayOptions then utils.updateTable(self.displayOptions, passedDisplayOptions) end local fontDirectory = RWCEMainDirectory .. "/fonts/" .. self.fontName local font = require (fontDirectory .. "/font") self.charImageFiles = font.charImageFiles self.charImages = {} for char, charImageFilepath in pairs(self.charImageFiles) do self.charImages[char] = createPicture() self.charImages[char]:loadFromFile(fontDirectory .. charImageFilepath) end -- Empty picture to represent a space self.charImages[''] = createPicture() self.charImages[' '] = createPicture() local width = font.settings.width local height = font.settings.height for n=1, numCharacters do local uiObj = createImage(window) uiObj:setSize(width, height) -- Allow the image to stretch to fit the size uiObj:setStretch(false) local relativePosition = {width*(n-1), 0} self:addElement(relativePosition, uiObj) end end function ImageValueDisplay:update() local valueString if tostring(type(self.returnFuncOrValue)) == 'string' then valueString = self.returnFuncOrValue elseif tostring(type(self.returnFuncOrValue)) == 'function' then valueString = self.returnFuncOrValue() else valueString = self.memoryValue:display(self.displayOptions) end for n, element in pairs(self.elements) do if valueString:len() >= n then local char = valueString:sub(n, n) if self.charImages[char] == nil then error( "No image specified for '" .. char .. "' (full string: " .. valueString .. ")") --element.uiObj.setPicture(self.charImages['']) end element.uiObj.setPicture(self.charImages[char]) else element.uiObj.setPicture(self.charImages['']) end end end return { ImageValueDisplay = ImageValueDisplay }
--[[ Sine-Cosine Wave Auther: Ahmed Dawoud [email protected] Animation Shows Sine And Cosine waves and the relation to the unit vector. ]] local Timer = require "knife.timer" local Easing = require 'easing' local suit = require 'suit' function love.load() -- Load Suit and set its theme (GUI Buttons). Suit = suit.new() Suit.theme.color = { normal = { bg = {193 / 255, 193 / 255, 193 / 255}, fg = {40 / 255, 44 / 255, 52 / 255} }, hovered = { bg = {0, 96 / 255, 255}, fg = {1, 1, 1} }, active = { bg = {224 / 255, 90 / 255, 84 / 255}, fg = {1, 1, 1} } } -- Load Fonts. fonts = {love.graphics.newFont("fonts/MontserratBold.ttf", 50), love.graphics.newFont("fonts/MontserratExtralight.ttf", 40), love.graphics.newFont("fonts/MontserratExtralightItalic.ttf", 50), love.graphics.newFont("fonts/MontserratItalic.ttf", 20), love.graphics.newFont("fonts/MontserratSemibold.ttf", 30)} love.graphics.setFont(fonts[2]) -- Set Window properties. love.window.setMode(800, 800) love.window.setTitle("Sine-Cosine Wave") -- Set The default point size to 5px (For the points indicating the position of the vector). love.graphics.setPointSize(5) -- Set The initial angle to π/4. angle = math.atan2(-1, 1) if angle < 0 then angle = angle + math.pi * 2 end -- Set The initial speed to One. speed = 1 -- The X, Y for the Vector. y = 0 x = 0 -- The Radius of the Circle. r = 200 -- Start motion after the drawing is completed. finishedTheInitialDrawing = false -- Set angle of the arc and the length of the vector in a table to tween them. vars = { angleArc = 0, len = 0 } -- Indicates whether the Sine and Cosine follows the victor or the axis. WithVector = true -- a table containing the values of the points of Sine. sin = {} -- a table containing the values of the points of cosine. cos = {} -- Boolean indicating whether to draw sine or cosine or both. sine = true cosine = true -- When Starting, tweeen the arc to make a circle. Timer.tween(4, { [vars] = { angleArc = math.pi * 2 } }):ease(Easing.outCirc):finish(function() -- When The arc is finished, tween the "len" variable to make the unit vector. Timer.tween(2, { [vars] = { len = 200 } }):ease(Easing.outElastic):finish(function() finishedTheInitialDrawing = true end) end) end function love.update(dt) -- If the lenght of the sin table is above 1500, remove the first 2 elements from the table if #sin > 1500 then table.remove(sin, 1) table.remove(sin, 1) end -- If the lenght of the cos table is above 1500, remove the first 2 elements from the table if #cos > 1500 then table.remove(cos, 1) table.remove(cos, 1) end -- Update timer (for the Tweens). Timer.update(dt) -- Start moving the vector when the inital drawing is finished. if finishedTheInitialDrawing then -- set the new X, y for the vector as the angle variable. x = math.cos(angle - 0.01) * r y = math.sin(angle - 0.01) * r -- Change the angle acording to the speed. angle = angle - 0.01 * speed if angle < 0 then angle = angle + math.pi * 2 end -- Insert ther sine, cosine values. -- with Sine, X is always 0. table.insert(sin, 0) table.insert(sin, y) -- with Cosine, Y is always 0. table.insert(cos, x) table.insert(cos, 0) end -- Loop over the sine values and change the X by "1" each frome to move it away from the vector. for i, v in ipairs(sin) do if i % 2 ~= 0 then sin[i] = v + 1 end end -- Loop over the cosine values and change the Y by "1" each frome to move it away from the vector. for i, v in ipairs(cos) do if i % 2 == 0 then cos[i] = v + 1 end end --[[ Drawing GUI Buttons. ]] if Suit:Button('Sine', { font = fonts[5] }, 20, 700, 140, 50).hit then sine = true cosine = not sine end if Suit:Button('Cosine', { font = fonts[5] }, 20, 630, 140, 50).hit then sine = false cosine = not sine end if Suit:Button('Both', { font = fonts[5] }, 20, 560, 140, 50).hit then sine = true cosine = sine end if Suit:Button('Normal', { font = fonts[5] }, 640, 700, 140, 50).hit then speed = 1 end if Suit:Button('Faster', { font = fonts[5] }, 640, 630, 140, 50).hit then if speed > 1 then speed = speed + 1 else speed = speed * 2 end end if Suit:Button('Slower', { font = fonts[5] }, 640, 560, 140, 50).hit then if speed > 1 then speed = speed - 1 elseif speed > 0.125 then speed = speed / 2 end end if Suit:Button('With The Axe', { font = fonts[5] }, 520, 20, 270, 50).hit then WithVector = false end if Suit:Button('With The Vector', { font = fonts[5] }, 520, 80, 270, 50).hit then WithVector = true end end function love.draw() love.graphics.clear(40 / 255, 48 / 255, 51 / 255) -- Translate the center to 400, 400. love.graphics.translate(400, 400) --[[ The Arc. ]] love.graphics.setColor(255, 255, 255) love.graphics.arc("line", 0, 0, 200, 0, vars.angleArc) -- draw a line to hide the Arc's end. love.graphics.setColor(40 / 255, 48 / 255, 51 / 255, 1) love.graphics.setLineWidth(5) love.graphics.line(0, 0, math.cos(vars.angleArc) * 200, math.sin(vars.angleArc) * 200) love.graphics.setLineWidth(3) --[[ The X, Y axis. ]] love.graphics.setColor(255, 255, 255) love.graphics.line(-400, 0, 400, 0) love.graphics.line(0, -400, 0, 400) --[[ Sine and Cosine Waves. ]] -- Check if sine is activated to draw it. if #sin >= 4 and sine then love.graphics.setColor(0, 96 / 255, 255) if WithVector then love.graphics.push() love.graphics.translate(math.cos(angle - 0.01) * r, 0) love.graphics.line(sin) love.graphics.pop() else love.graphics.line(sin) end end -- Check if cosine is activated to draw it. if #cos >= 4 and cosine then love.graphics.setColor(224 / 255, 90 / 255, 84 / 255) if WithVector then love.graphics.push() love.graphics.translate(0, math.sin(angle - 0.01) * r) love.graphics.line(cos) love.graphics.pop() else love.graphics.line(cos) end end --[[ The Vector. ]] love.graphics.setColor(0.8, 0.8, 0.8, 1) love.graphics.arrow(0, 0, math.cos(angle) * vars.len, math.sin(angle) * vars.len, 20, .4) --[[ Draw info to the screen ]] love.graphics.print( "Speed= " .. speed .. "\nSine = " .. Round(math.sin(math.pi * 2 - angle), 3) .. "\nCosine= " .. Round(math.cos(math.pi * 2 - angle), 3) .. "\nAngle: " .. Round(360 - angle * 180 / 3.14159265359) .. "°", -390, -390) -- Credit :) love.graphics.print("Ahmed Dawoud", fonts[4], -400, -25) --[[ The point at the end of the vector. ]] love.graphics.setColor(19 / 255, 158 / 255, 91 / 255) love.graphics.circle("fill", math.cos(angle) * vars.len, math.sin(angle) * vars.len, 4) love.graphics.translate(-400, -400) Suit:draw() end --[[ A function to round numbers ]] function Round(num, idp) local mult = 10 ^ (idp or 0) return math.floor(num * mult + 0.5) / mult end function love.graphics.arrow(x1, y1, x2, y2, arrlen, angle) love.graphics.line(x1, y1, x2, y2) local a = math.atan2(y1 - y2, x1 - x2) love.graphics.polygon('fill', x2, y2, x2 + arrlen * math.cos(a + angle), y2 + arrlen * math.sin(a + angle), x2 + arrlen * math.cos(a - angle), y2 + arrlen * math.sin(a - angle)) end
module("UITask", package.seeall) setmetatable(UITask, {__index=UIWidget}) UT_EXECTASK = "UT_EXECTASK" UT_GIVEUP = "UT_GIVEUP" function new(go) local obj = { } setmetatable(obj, {__index=UITask}) obj:Init(go) return obj end function Init(self, go) UIWidget.Init(self, go) end function Awake(self) self:Install({ UT_EXECTASK, UT_GIVEUP }) end function Start(self) self:RegisterClickEvent(UT_EXECTASK, OnExecTaskClicked) self:RegisterClickEvent(UT_GIVEUP, OnGiveupClicked) end function Close(self, complete) --self:DOCanvasGroupFade(1, 0, 1, function() if complete then complete() end --end) end function OnExecTaskClicked(self, goSend, evtData) XPluginManager.GetSingleton():FireEvent(GuiEvent.EVT_EXECUTE, { widget = self }) end function OnGiveupClicked(self, goSend, evtData) XPluginManager.GetSingleton():FireEvent(GuiEvent.EVT_RETURN, { widget = self }) end
local tabnine = require('cmp_tabnine.config') tabnine:setup{ max_lines = 1000, max_num_results = 20, sort = true, run_on_every_keystroke = true, snippet_placeholder = '..' }
return function(pos1, pos2, pos1_load, pos2_load) local manip1 = minetest.get_voxel_manip() local e1, e2 = manip1:read_from_map(pos1, pos2) local area1 = VoxelArea:new({MinEdge=e1, MaxEdge=e2}) local manip2 = minetest.get_voxel_manip() e1, e2 = manip2:read_from_map(pos1_load, pos2_load) local area2 = VoxelArea:new({MinEdge=e1, MaxEdge=e2}) local offset = vector.subtract(pos1_load, pos1) local nodeids1 = manip1:get_data() local nodeids2 = manip2:get_data() local param1_data1 = manip1:get_light_data() local param1_data2 = manip2:get_light_data() local param2_data1 = manip1:get_param2_data() local param2_data2 = manip2:get_param2_data() for x=pos1.x,pos2.x do for y=pos1.y,pos2.y do for z=pos1.z,pos2.z do local pos = { x=x, y=y, z=z } local i1 = area1:indexp(pos) local i2 = area2:indexp(vector.add(pos, offset)) if nodeids1[i1] ~= nodeids2[i2] then return false, "node-ids, pos: " .. minetest.pos_to_string(pos) end if param1_data1[i1] ~= param1_data2[i2] then return false, "light, pos: " .. minetest.pos_to_string(pos) end if param2_data1[i1] ~= param2_data2[i2] then return false, "param2, pos: " .. minetest.pos_to_string(pos) end end end end return true end
--[[ --=====================================================================================================-- Script Name: Give Passenger Weapon, for SAPP (PC & CE) Description: Assigns a custom wepaon when someone enters the passengers seat of a vehicle ~ requested by mdc81 on opencarnage.net - note, this mod doesn't function correctly. - The reason for this (I think) is because the player cannot pick up a weapon while they're in a vehicle. - SAPP needs a PreVehicleEntry event. Copyright (c) 2016-2018, Jericho Crosby <[email protected]> Notice: You can use this document subject to the following conditions: https://github.com/Chalwk77/HALO-SCRIPT-PROJECTS/blob/master/LICENSE --=====================================================================================================-- ]] --[[ -- valid weapon tags "weapons\\assault rifle\\assault rifle" "weapons\\ball\\ball" "weapons\\flag\\flag" "weapons\\flamethrower\\flamethrower" "weapons\\needler\\mp_needler" "weapons\\pistol\\pistol" "weapons\\plasma pistol\\plasma pistol" "weapons\\plasma rifle\\plasma rifle" "weapons\\plasma_cannon\\plasma_cannon" "weapons\\rocket launcher\\rocket launcher" "weapons\\shotgun\\shotgun" "weapons\\sniper rifle\\sniper rifle" ]] api_version = '1.12.0.0' -- set 'true' to 'false' to prevent weapon-assignment OnVehicleEntry() (and vice versa) vehicles = { { "vehicles\\rwarthog\\rwarthog", false, "weapons\\rocket launcher\\rocket launcher" }, { "vehicles\\scorpion\\scorpion_mp", false, "weapons\\plasma_cannon\\plasma_cannon" }, { "vehicles\\warthog\\mp_warthog", true, "weapons\\sniper rifle\\sniper rifle" }, } function OnScriptLoad() register_callback(cb['EVENT_VEHICLE_ENTER'], 'OnVehicleEntry') end function OnScriptUnload() end function OnVehicleEntry(PlayerIndex) local player_object = get_dynamic_player(PlayerIndex) if (player_object ~= 0) then local vehicle = get_object_memory(read_dword(player_object + 0x11c)) for i = 1, #vehicles do if (vehicles[i] ~= nil) and (vehicle ~= nil and vehicle ~= 0) then if read_string(read_dword(read_word(vehicle) * 32 + 0x40440038)) == vehicles[i][1] then if (vehicles[i][2] == true) and (read_word(player_object + 0x2F0) == 1) then local vehiX, vehiY, vehiZ = read_vector3d(vehicle + 0x5C) -- delete all of their weapons... for j = 1, 4 do execute_command("wdel " .. PlayerIndex) end -- assign new weapon assign_weapon(spawn_object("weap", vehicles[i][3], vehiX, vehiY, vehiZ + 0.3), PlayerIndex) end end end end end 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. -- Zigbee Spec Utils local zcl_messages = require "st.zigbee.zcl" local messages = require "st.zigbee.messages" local generic_body = require "st.zigbee.generic_body" local zb_const = require "st.zigbee.constants" local data_types = require "st.zigbee.data_types" local utils = require "st.utils" -- Capabilities local capabilities = require "st.capabilities" local Tone = capabilities.tone local PresenceSensor = capabilities.presenceSensor local SignalStrength = capabilities.signalStrength local Battery = capabilities.battery -- Constants local PROFILE_ID = 0xFC01 local PRESENCE_LEGACY_CLUSTER = 0xFC05 local BEEP_CMD_ID = 0x00 local CHECKIN_CMD_ID = 0x01 local DATA_TYPE = 0x00 local MFG_CODE = 0x110A local BEEP_DESTINATION_ENDPOINT = 0x02 local BEEP_SOURCE_ENDPOINT = 0x02 local BEEP_PAYLOAD = "" local FRAME_CTRL = 0x15 local NUMBER_OF_BEEPS = 5 local LEGACY_DEVICE_BATTERY_COMMAND = 0x00 local LEGACY_DEVICE_PRESENCE_COMMAND = 0x01 local LEGACY_DEVICE_PRESENCE_REPORT_EXT = 0x02 local timer_const = require "constants/timer-constants" local CHECKIN_INTERVAL = 20 -- seconds local function arrival_sensor_v1_can_handle(opts, driver, device, ...) return device:get_model() ~= "tagv4" end local function legacy_battery_handler(self, device, zb_rx) local battery_value = string.byte(zb_rx.body.zcl_body.body_bytes) local divisor = 10 local battery_intermediate = ((battery_value / divisor) - 2.2) * 125 local battery_percentage = utils.round(utils.clamp_value(battery_intermediate, 0, 100)) device:emit_event(Battery.battery(battery_percentage)) end local function create_beep_message(device) local header_args = { cmd = data_types.ZCLCommandId(BEEP_CMD_ID) } header_args.mfg_code = data_types.validate_or_build_type(MFG_CODE, data_types.Uint16, "mfg_code") local zclh = zcl_messages.ZclHeader(header_args) zclh.frame_ctrl:set_cluster_specific() zclh.frame_ctrl:set_mfg_specific() zclh.frame_ctrl:set_disable_default_response() local addrh = messages.AddressHeader( zb_const.HUB.ADDR, BEEP_SOURCE_ENDPOINT, device:get_short_address(), BEEP_DESTINATION_ENDPOINT, PROFILE_ID, PRESENCE_LEGACY_CLUSTER ) local payload_body = generic_body.GenericBody(BEEP_PAYLOAD) local message_body = zcl_messages.ZclMessageBody({ zcl_header = zclh, zcl_body = payload_body }) local beep_message = messages.ZigbeeMessageTx({ address_header = addrh, body = message_body }) return beep_message end local function beep_handler(self, device, command) local beep_message = create_beep_message(device) device:send(beep_message) for i=1,(NUMBER_OF_BEEPS),1 do device.thread:call_with_delay( i*7, function() device:send(beep_message) end ) end end local function added_handler(self, device) device:emit_event(PresenceSensor.presence("present")) end local function init_handler(self, device, event, args) device:set_field( timer_const.PRESENCE_CALLBACK_CREATE_FN, function(device) return device.thread:call_with_delay( 3 * CHECKIN_INTERVAL + 1, 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 ) end local arrival_sensor_v1 = { NAME = "Arrival Sensor v1", zigbee_handlers = { cluster = { [PRESENCE_LEGACY_CLUSTER] = { [LEGACY_DEVICE_BATTERY_COMMAND] = legacy_battery_handler } } }, capability_handlers = { [Tone.ID] = { [Tone.commands.beep.NAME] = beep_handler } }, lifecycle_handlers = { added = added_handler, init = init_handler }, can_handle = arrival_sensor_v1_can_handle } return arrival_sensor_v1
function reverse_table(t) for _, v in pairs(t) do print(v) end local size = #t local result = {} for i,e in pairs(t) do result[size-i+1] = e end return result end function rotate_array(array) print('rotating array') print('vals') for k, v in pairs(array) do print(v) end print('end vals') if #array == 0 then return {} end result = {} for i=1,#array[1] do result[#result+1] = {} end for _, row in pairs(array) do for i, e in pairs(row) do result[i][#result[i]+1] = e end end for k, v in pairs(array) do print(unpack(v)) end return result end function spiral(array) result = {} while #array > 0 do --print('first part is: ' .. result)-- table.concat(result, ' ')) --print('array:') for _, v in pairs(array) do print(table.concat(v, ' ')) end print('adding top row to result') for _, e in pairs(array[1]) do result[#result+1] = e end print('added top row to result') -- delete top row print('deleting top row') table.remove(array, 1) print('deleted top row') -- rotate array print('rotating array') array = rotate_array(array) print('rotated') end return result end for line in io.lines(arg[1]) do numbers = {} for m in line:gmatch('%d+') do numbers[#numbers+1] = tonumber(m) end width = numbers[1] height = numbers[2] table.remove(numbers, 1) table.remove(numbers, 1) array = {} for i=1,width do row = {} for j=1,height do row[#row+1] = numbers[((i-1)*height) + j] end array[#array+1] = row end result = spiral(array) print(table.concat(result, ' ')) print('finished') end
local IO = require "kong.tools.io" local Object = require "classic" -- Migrations local Migrations = Object:extend() function Migrations:new(dao, migrations_path) local path = migrations_path and migrations_path or "." self.dao = dao self.options = { keyspace = dao._properties.keyspace } self.migrations_path = IO.path:join(path, "database", "migrations") self.migrations_files = IO.retrieve_files(IO.path:join(self.migrations_path, dao.type), { file_pattern = ".lua" }) table.sort(self.migrations_files) end -- Createa migration interface for each database available function Migrations:create(configuration, name, callback) for k, _ in pairs(configuration.databases_available) do local date_str = os.date("%Y-%m-%d-%H%M%S") local file_path = IO.path:join(self.migrations_path, k) local file_name = date_str.."_"..name local interface = [[ local Migration = { name = "]]..file_name..[[", up = function(options) return ]].."[["..[[ ]].."]]"..[[ end, down = function(options) return ]].."[["..[[ ]].."]]"..[[ end } return Migration ]] if callback then callback(interface, file_path, file_name, k) end end end -- Execute all migrations UP -- @param callback A function to execute on each migration (ie: for logging) function Migrations:migrate(callback) local old_migrations, err = self.dao:get_migrations() if err then callback(nil, err) return end -- Retrieve migrations to execute local diff_migrations = {} if old_migrations then -- Only execute from the latest executed migrations for i, migration in ipairs(self.migrations_files) do if old_migrations[i] == nil then table.insert(diff_migrations, migration) end end -- If no diff, there is no new migration to run if #diff_migrations == 0 then callback(nil, nil) return end else -- No previous migrations, just execute all migrations diff_migrations = self.migrations_files end -- Execute all new migrations, in order for _, file_path in ipairs(diff_migrations) do -- Load our migration script local migration = loadfile(file_path)() -- Generate UP query from string + options local up_query = migration.up(self.options) local err = self.dao:execute_queries(up_query, migration.init) if err then callback(nil, err) return end -- Record migration in db local _, err = self.dao:add_migration(migration.name) if err then err = "Cannot record migration "..migration.name..": "..err end callback(migration, err) if err then break end end end -- Take the latest executed migration and DOWN it -- @param callback A function to execute (for consistency with other functions of this module) function Migrations:rollback(callback) local old_migrations, err = self.dao:get_migrations() if err then callback(nil, err) return end local migration_to_rollback if old_migrations and #old_migrations > 0 then migration_to_rollback = loadfile(IO.path:join(self.migrations_path, self.dao.type, old_migrations[#old_migrations])..".lua")() else -- No more migration to rollback callback(nil, nil) return end -- Generate DOWN query from string + options local down_query = migration_to_rollback.down(self.options) local err = self.dao:execute_queries(down_query) if err then callback(nil, err) return end -- delete migration from schema changes records if it's not the first one -- (otherwise the schema_migrations table doesn't exist anymore) if not migration_to_rollback.init then local _, err = self.dao:delete_migration(migration_to_rollback.name) if err then callback(migration_to_rollback, "Cannot delete migration "..migration_to_rollback.name..": "..err) return end end callback(migration_to_rollback) end -- Execute all migrations DOWN -- @param {function} callback A function to execute on each migration (ie: for logging) function Migrations:reset(callback) local done = false while not done do self:rollback(function(migration, err) if not migration and not err then done = true end callback(migration, err) end) end end return Migrations
local apps = { 93, 9, 175, 22, 15 } function pl_corshift_001(obj) local app = math.random(#apps) obj:SetAppearanceType(apps[app]) end
local class = require 'ext.class' local Function = require 'symmath.Function' local atanh = class(Function) atanh.name = 'atanh' -- domain: (-1, 1) function atanh.func(x) return .5 * math.log((1 + x) / (1 - x)) end -- domain: (-1, 1) function atanh:evaluateDerivative(deriv, ...) local x = table.unpack(x) return deriv(x, ...) / (1 - x^2) end atanh.getRealDomain = require 'symmath.set.RealSubset'.getRealDomain_plusMinusOneOpen atanh.getRealRange = require 'symmath.set.RealSubset'.getRealRange_pmOneInc atanh.evaluateLimit = require 'symmath.Limit'.evaluateLimit_plusMinusOne_to_plusMinusInf atanh.rules = { Prune = { {apply = function(prune, expr) symmath = symmath or require 'symmath' local Constant = symmath.Constant local x = expr[1] if Constant.isValue(x, 0) then return Constant(0) end -- [[ TODO this should be on all Function's prune()'s if expr:getRealDomain():complement():open():contains(x) then return symmath.invalid end --]] end}, }, } return atanh
local MemObj = require "memobj" local print_r = require "print_r" local skynet = require "skynet" local MemAdmin = class("MemAdmin") function MemAdmin:ctor(table_name, pk) self._table_name = table_name self._pk = pk local tmp_pks = string.split(pk, ",") if #tmp_pks > 1 then self._is_multi_pk = true else self._is_multi_pk = false end end function MemAdmin:create(data) local fields = get_fields(self._table_name) local data_new = {} for _, field in pairs(fields) do for key, value in pairs(data) do if field == key then data_new[key] = value break end end end local sql = construct_insert_str(self._table_name, data_new) local ret = skynet.call("mysqlpool", "lua", "execute", sql) if not ret then return nil end local pk = "" if self._is_multi_pk then local tmp_pks = string.split(self._pk, ",") local tmp_values = {} for _, key in pairs(tmp_pks) do table.insert(tmp_values, data[key]) end pk = table.concat(tmp_values, "#") else pk = tostring(get_maxkey(self._table_name)) data_new[self._pk] = pk end local mem_obj = MemObj.new(string.format("%s:%s", self._table_name, pk), self._pk, data_new) mem_obj:init_redis_from_local() return mem_obj end function MemAdmin:get_pk_by_fk(pres) local sql = construct_query_str(self._table_name, pres, self._pk) local ret = skynet.call("mysqlpool", "lua", "execute", sql) local result = {} if not table.empty(ret) then for _, value in pairs(ret) do table.insert(result, value[self._pk]) end end return result end return MemAdmin
-- Usage: nvim -u test/manual/minimal_init.lua -- Add the current working directory to the runtime path. -- This way the termmaker plugin can be used without installing it. vim.cmd("set rtp+=.") -- Set hidden ... otherwise toggling terminals will not work. vim.o.hidden = true require("termmaker").setup()
local ing = { { {"pipe", 20}, {"stone-brick", 100} }, { {"facility-mk1", 1}, {"advanced-circuit", 30}, {"concrete", 100} }, { {"facility-mk2", 1}, {"refined-concrete", 100} }, } if bobmods and bobmods.plates then table.insert(ing[2], {"brass-pipe", 100}) table.insert(ing[3], {"tungsten-pipe", 100}) else table.insert(ing[2], {"pipe", 100}) table.insert(ing[3], {"pipe", 100}) end if data.raw.item["basic-circuit-board"] then table.insert(ing[1], {"basic-circuit-board", 20}) else table.insert(ing[1], {"electronic-circuit", 20}) end if data.raw.item["advanced-processing-unit"] then table.insert(ing[3], {"advanced-processing-unit", 40}) else table.insert(ing[3], {"processing-unit", 40}) end for i=1,3 do if not data.raw.recipe["facility-mk"..i] then local recipe = { type = "recipe", name = "facility-mk"..i, enabled = false, energy_required = 2, ingredients = ing[i], result = "facility-mk"..i } local item = { type = "item", name = "facility-mk"..i, icons = { { icon = "__fundamental_physics__/graphics/item/facility.png" } }, icon_size = 32, flags = {"goes-to-quickbar"}, subgroup = "fundamental-physics-lab", order = "a-a", place_result = "facility-mk"..i, stack_size = 10, } local entity = { type = "assembling-machine", name = "facility-mk"..i, fast_replaceable_group = "facility", icons = { { icon = "__fundamental_physics__/graphics/item/facility.png" } }, icon_size = 32, flags = {"placeable-neutral", "placeable-player", "player-creation"}, minable = {hardness = 0.8, mining_time = 1.2, result = "facility-mk"..i}, max_health = 500, corpse = "medium-remnants", dying_explosion = "medium-explosion", light = {intensity = 1, size = 100},--int = 0.75, s = 8 resistances = { { type = "fire", percent = 70 } }, collision_box = {{-1.4, -1.4}, {1.4, 1.4}}, selection_box = {{-1.5, -1.5}, {1.5, 1.5}}, animation = { filename = "__fundamental_physics__/graphics/entity/facility.png", priority = "high", width = 128, height = 128, frame_count = 29, line_length = 6, animation_speed = 1, shift = {0,-0.3} }, crafting_categories = {"facility"}, crafting_speed = i, module_specification = { module_slots = i+1 }, allowed_effects = {"consumption", "speed", "pollution"}, energy_source = { type = "electric", usage_priority = "secondary-input", emissions = 0.001 }, energy_usage = (4*2^(i-1)).."MW", ingredient_count = 2, open_sound = { filename = "__base__/sound/machine-open.ogg", volume = 0.85 }, close_sound = { filename = "__base__/sound/machine-close.ogg", volume = 0.75 }, vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 }, working_sound = { sound = { { filename = "__base__/sound/assembling-machine-t1-1.ogg", volume = 0.8 }, { filename = "__base__/sound/assembling-machine-t1-2.ogg", volume = 0.8 }, }, idle_sound = {filename = "__base__/sound/idle1.ogg", volume = 0.6}, apparent_volume = 1.5, }, fluid_boxes = { { production_type = "input", pipe_covers = pipecoverspictures(), base_area = 10, base_level = -1, pipe_connections = {{ type="input", position = {-1, -1.8} }} }, { production_type = "input", pipe_covers = pipecoverspictures(), base_area = 10, base_level = -1, pipe_connections = {{ type="input", position = {1, -1.8} }} } } } mylib.add_angel_num_icon(item,i) mylib.add_angel_num_icon(entity,i) data:extend({recipe, item, entity}) end end
--aliases (helper variables) lg = love.graphics la = love.audio lfs = love.filesystem li = love.image lm = love.math lmo = love.mouse lf = love.font lk = love.keyboard lt = love.timer lw = love.window lj = love.joystick -- lw.setMode() sw = love.window.getWidth() sh = love.window.getHeight() math.randomseed(os.time()) math.random() math.random() math.random() lm.setRandomSeed(os.time()) lm.random() lm.random() lm.random() -- class = middleclass.class white = {255,255,255} black = {0,0,0} crs = {} img = {} fnt = {} snd = {} loadResources(img,"images") loadResources(fnt,"fonts") loadResources(snd,"sounds ") fnt.default = lg.getFont()
registerNpc(251, { walk_speed = 150, run_speed = 350, scale = 90, r_weapon = 1076, l_weapon = 0, level = 48, hp = 22, attack = 195, hit = 126, def = 97, res = 168, avoid = 73, attack_spd = 100, is_magic_damage = 1, ai_type = 18, give_exp = 42, drop_type = 0, drop_money = 1, drop_item = 40, union_number = 40, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 800, npc_type = 7, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(711, { walk_speed = 130, run_speed = 440, scale = 95, r_weapon = 1076, l_weapon = 0, level = 19, hp = 19, attack = 60, hit = 87, def = 47, res = 74, avoid = 38, attack_spd = 100, is_magic_damage = 1, ai_type = 36, give_exp = 33, drop_type = 0, drop_money = 55, drop_item = 10, union_number = 10, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 800, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(712, { walk_speed = 134, run_speed = 452, scale = 100, r_weapon = 1076, l_weapon = 0, level = 23, hp = 19, attack = 73, hit = 94, def = 55, res = 84, avoid = 43, attack_spd = 100, is_magic_damage = 1, ai_type = 36, give_exp = 37, drop_type = 0, drop_money = 56, drop_item = 10, union_number = 10, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 830, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(713, { walk_speed = 138, run_speed = 464, scale = 105, r_weapon = 1076, l_weapon = 0, level = 27, hp = 19, attack = 86, hit = 100, def = 62, res = 94, avoid = 48, attack_spd = 100, is_magic_damage = 1, ai_type = 36, give_exp = 39, drop_type = 0, drop_money = 57, drop_item = 10, union_number = 10, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 860, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(714, { walk_speed = 142, run_speed = 476, scale = 110, r_weapon = 1076, l_weapon = 0, level = 31, hp = 19, attack = 99, hit = 107, def = 71, res = 104, avoid = 53, attack_spd = 100, is_magic_damage = 1, ai_type = 36, give_exp = 42, drop_type = 0, drop_money = 58, drop_item = 10, union_number = 10, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 890, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(715, { walk_speed = 146, run_speed = 488, scale = 115, r_weapon = 1076, l_weapon = 0, level = 35, hp = 20, attack = 113, hit = 114, def = 79, res = 115, avoid = 58, attack_spd = 100, is_magic_damage = 1, ai_type = 36, give_exp = 47, drop_type = 0, drop_money = 59, drop_item = 10, union_number = 10, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 920, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(716, { walk_speed = 150, run_speed = 500, scale = 120, r_weapon = 1076, l_weapon = 0, level = 39, hp = 20, attack = 126, hit = 121, def = 88, res = 126, avoid = 63, attack_spd = 100, is_magic_damage = 1, ai_type = 36, give_exp = 50, drop_type = 0, drop_money = 60, drop_item = 9, union_number = 9, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 950, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(717, { walk_speed = 154, run_speed = 512, scale = 125, r_weapon = 1076, l_weapon = 0, level = 43, hp = 21, attack = 140, hit = 128, def = 97, res = 137, avoid = 68, attack_spd = 100, is_magic_damage = 1, ai_type = 37, give_exp = 53, drop_type = 0, drop_money = 61, drop_item = 9, union_number = 9, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 980, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(718, { walk_speed = 158, run_speed = 524, scale = 130, r_weapon = 1076, l_weapon = 0, level = 47, hp = 21, attack = 155, hit = 136, def = 107, res = 149, avoid = 73, attack_spd = 100, is_magic_damage = 1, ai_type = 37, give_exp = 59, drop_type = 0, drop_money = 62, drop_item = 9, union_number = 9, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1010, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(719, { walk_speed = 162, run_speed = 536, scale = 135, r_weapon = 1076, l_weapon = 0, level = 51, hp = 21, attack = 169, hit = 143, def = 116, res = 161, avoid = 78, attack_spd = 100, is_magic_damage = 1, ai_type = 37, give_exp = 61, drop_type = 0, drop_money = 63, drop_item = 9, union_number = 9, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1040, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(720, { walk_speed = 166, run_speed = 548, scale = 140, r_weapon = 1076, l_weapon = 0, level = 55, hp = 22, attack = 184, hit = 151, def = 126, res = 173, avoid = 84, attack_spd = 100, is_magic_damage = 1, ai_type = 37, give_exp = 65, drop_type = 0, drop_money = 64, drop_item = 9, union_number = 9, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1070, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(721, { walk_speed = 130, run_speed = 440, scale = 145, r_weapon = 1076, l_weapon = 0, level = 59, hp = 22, attack = 199, hit = 158, def = 137, res = 186, avoid = 89, attack_spd = 100, is_magic_damage = 1, ai_type = 37, give_exp = 67, drop_type = 0, drop_money = 65, drop_item = 8, union_number = 8, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1300, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(722, { walk_speed = 134, run_speed = 452, scale = 150, r_weapon = 1076, l_weapon = 0, level = 63, hp = 23, attack = 214, hit = 166, def = 148, res = 198, avoid = 95, attack_spd = 100, is_magic_damage = 1, ai_type = 37, give_exp = 71, drop_type = 0, drop_money = 66, drop_item = 8, union_number = 8, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1330, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(723, { walk_speed = 138, run_speed = 464, scale = 155, r_weapon = 1076, l_weapon = 0, level = 67, hp = 23, attack = 229, hit = 174, def = 159, res = 211, avoid = 101, attack_spd = 100, is_magic_damage = 1, ai_type = 38, give_exp = 74, drop_type = 0, drop_money = 67, drop_item = 8, union_number = 8, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1360, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(724, { walk_speed = 142, run_speed = 476, scale = 160, r_weapon = 1076, l_weapon = 0, level = 71, hp = 23, attack = 245, hit = 182, def = 170, res = 225, avoid = 106, attack_spd = 100, is_magic_damage = 1, ai_type = 38, give_exp = 80, drop_type = 0, drop_money = 68, drop_item = 8, union_number = 8, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1390, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(725, { walk_speed = 146, run_speed = 488, scale = 165, r_weapon = 1076, l_weapon = 0, level = 75, hp = 24, attack = 260, hit = 190, def = 182, res = 238, avoid = 112, attack_spd = 100, is_magic_damage = 1, ai_type = 38, give_exp = 85, drop_type = 0, drop_money = 69, drop_item = 8, union_number = 8, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1420, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(726, { walk_speed = 150, run_speed = 500, scale = 170, r_weapon = 1076, l_weapon = 0, level = 79, hp = 24, attack = 276, hit = 199, def = 194, res = 252, avoid = 118, attack_spd = 100, is_magic_damage = 1, ai_type = 38, give_exp = 88, drop_type = 0, drop_money = 70, drop_item = 7, union_number = 7, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1450, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(727, { walk_speed = 154, run_speed = 512, scale = 175, r_weapon = 1076, l_weapon = 0, level = 83, hp = 25, attack = 292, hit = 207, def = 206, res = 266, avoid = 124, attack_spd = 100, is_magic_damage = 1, ai_type = 38, give_exp = 96, drop_type = 0, drop_money = 71, drop_item = 7, union_number = 7, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1480, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(728, { walk_speed = 158, run_speed = 524, scale = 180, r_weapon = 1076, l_weapon = 0, level = 87, hp = 25, attack = 309, hit = 216, def = 219, res = 281, avoid = 130, attack_spd = 100, is_magic_damage = 1, ai_type = 38, give_exp = 100, drop_type = 0, drop_money = 72, drop_item = 7, union_number = 7, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1510, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(729, { walk_speed = 162, run_speed = 536, scale = 185, r_weapon = 1076, l_weapon = 0, level = 91, hp = 25, attack = 325, hit = 224, def = 232, res = 295, avoid = 137, attack_spd = 100, is_magic_damage = 1, ai_type = 39, give_exp = 103, drop_type = 0, drop_money = 73, drop_item = 7, union_number = 7, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1540, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(730, { walk_speed = 166, run_speed = 548, scale = 190, r_weapon = 1076, l_weapon = 0, level = 95, hp = 26, attack = 342, hit = 233, def = 246, res = 310, avoid = 143, attack_spd = 100, is_magic_damage = 1, ai_type = 39, give_exp = 113, drop_type = 0, drop_money = 74, drop_item = 7, union_number = 7, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1570, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(731, { walk_speed = 130, run_speed = 440, scale = 195, r_weapon = 1076, l_weapon = 0, level = 99, hp = 26, attack = 359, hit = 242, def = 259, res = 325, avoid = 149, attack_spd = 100, is_magic_damage = 1, ai_type = 39, give_exp = 110, drop_type = 0, drop_money = 75, drop_item = 7, union_number = 7, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1300, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(732, { walk_speed = 134, run_speed = 452, scale = 200, r_weapon = 1076, l_weapon = 0, level = 103, hp = 26, attack = 376, hit = 251, def = 273, res = 340, avoid = 156, attack_spd = 100, is_magic_damage = 1, ai_type = 39, give_exp = 114, drop_type = 0, drop_money = 0, drop_item = 0, union_number = 0, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1330, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(733, { walk_speed = 138, run_speed = 464, scale = 205, r_weapon = 1076, l_weapon = 0, level = 107, hp = 27, attack = 393, hit = 260, def = 288, res = 356, avoid = 162, attack_spd = 100, is_magic_damage = 1, ai_type = 39, give_exp = 123, drop_type = 0, drop_money = 0, drop_item = 0, union_number = 0, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1360, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(734, { walk_speed = 142, run_speed = 476, scale = 210, r_weapon = 1076, l_weapon = 0, level = 111, hp = 27, attack = 410, hit = 269, def = 302, res = 371, avoid = 169, attack_spd = 100, is_magic_damage = 1, ai_type = 39, give_exp = 127, drop_type = 0, drop_money = 0, drop_item = 0, union_number = 0, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1390, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(735, { walk_speed = 146, run_speed = 488, scale = 215, r_weapon = 1076, l_weapon = 0, level = 115, hp = 27, attack = 428, hit = 278, def = 318, res = 387, avoid = 175, attack_spd = 100, is_magic_damage = 1, ai_type = 39, give_exp = 131, drop_type = 0, drop_money = 0, drop_item = 0, union_number = 0, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1420, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(736, { walk_speed = 150, run_speed = 500, scale = 220, r_weapon = 1076, l_weapon = 0, level = 119, hp = 28, attack = 446, hit = 288, def = 333, res = 403, avoid = 182, attack_spd = 100, is_magic_damage = 1, ai_type = 39, give_exp = 142, drop_type = 0, drop_money = 0, drop_item = 0, union_number = 0, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1450, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(737, { walk_speed = 154, run_speed = 512, scale = 225, r_weapon = 1076, l_weapon = 0, level = 123, hp = 28, attack = 464, hit = 297, def = 349, res = 420, avoid = 189, attack_spd = 100, is_magic_damage = 1, ai_type = 39, give_exp = 146, drop_type = 0, drop_money = 0, drop_item = 0, union_number = 0, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1480, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(738, { walk_speed = 158, run_speed = 524, scale = 230, r_weapon = 1076, l_weapon = 0, level = 127, hp = 28, attack = 482, hit = 307, def = 365, res = 436, avoid = 196, attack_spd = 100, is_magic_damage = 1, ai_type = 39, give_exp = 151, drop_type = 0, drop_money = 0, drop_item = 0, union_number = 0, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1510, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(739, { walk_speed = 162, run_speed = 536, scale = 235, r_weapon = 1076, l_weapon = 0, level = 131, hp = 29, attack = 500, hit = 316, def = 381, res = 453, avoid = 203, attack_spd = 100, is_magic_damage = 1, ai_type = 39, give_exp = 158, drop_type = 0, drop_money = 0, drop_item = 0, union_number = 0, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1540, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(740, { walk_speed = 166, run_speed = 548, scale = 240, r_weapon = 1076, l_weapon = 0, level = 135, hp = 29, attack = 519, hit = 326, def = 398, res = 470, avoid = 210, attack_spd = 100, is_magic_damage = 1, ai_type = 39, give_exp = 167, drop_type = 0, drop_money = 0, drop_item = 0, union_number = 0, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 1570, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(927, { walk_speed = 190, run_speed = 450, scale = 160, r_weapon = 0, l_weapon = 0, level = 62, hp = 2380, attack = 202, hit = 165, def = 199, res = 103, avoid = 94, attack_spd = 100, is_magic_damage = 0, ai_type = 166, give_exp = 0, drop_type = 3, drop_money = 0, drop_item = 100, union_number = 100, need_summon_count = 33, sell_tab0 = 33, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 350, npc_type = 0, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); function OnInit(entity) return true end function OnCreate(entity) return true end function OnDelete(entity) return true end function OnDead(entity) end function OnDamaged(entity) end
parseColor = require("api.parse_color") function addScienceFluid(name,base_color,flow_color,icon) data:extend({ { type = "fluid", name = name, default_temperature = 0, max_temperature = 0, heat_capacity = "0KJ", base_color = parseColor(base_color), flow_color = parseColor(flow_color), subgroup = "tool", max_temperature = 100, icon = icon, pressure_to_speed_ratio = 0.4, flow_to_energy_ratio = 0.59, order = "e[lubricant]", icon_size = 32 } }) end return addScienceFluid
do local function It(a) return { __tag = "It", a } end local function Mk(a) return { __tag = "Mk", a } end local function Foo(gk) return gk end (nil)(Foo) (nil)(function(gl) return gl end) (nil)(It) (nil)(Mk) end
-- test_binlib.lua local bin = require("bin") local h = "" h = h..bin.pack("A", "hello world") print(h)
Common_UnitConsumeActPoint(attacker, 1); Common_Sleep(attacker, 0.3)
--[[ Copyright 2021 - Sebastian S. Cocioba - Binomica Labs Inspired by a Tweet from @JacobPhD (Dr. Jacob A Tennessen) 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. ]]-- --handle passed arguments for later use if #arg < 1 then print("") print("ProtEmoji v1.0 - Amino to Emoji Converter") print("----------------------------------------------------------------------------") print("") print("usage: lua " .. arg[0] .. " [protein FASTA file name] [output file name] ") print("") print("example input: lua protemoji.lua testProtein.faa testOutput.faa") print("") return end --set file logic and catch loading errors local inputFile = io.open(arg[1], "r") local outputFile = io.open(arg[2], "w") if not inputFile or not outputFile then print("") print("") print("Error: could not open files; check file names and paths!") print("") print("") return end proteinInputString = "" emojiOutputString = "" proteinInputTable = {} emojiOutputTable = {} emojiCodex = { --Hydrophobic --Big W = "🐂", F = "🐎", Y = "🐫", --Small A = "🐿️", V = "🐈", I = "🐒", L = "🐕", P = "🐗", M = "🌰", C = "🥜", G = "🥔", --Hydrophilic --Polar S = "🐊", T = "🐸", N = "🐠", Q = "🐟", --Negative E = "🦑", D = "🐙", --Positive R = "🐳", K = "🐋", H = "🐬" } function splitByChunk(text, chunkSize) --basic function to split string into table of substrings local s = {} --chunkSize denotes how long substring is; 1 = single char for i=1, #text, chunkSize do --returns a table of substrings or chars s[#s+1] = text:sub(i,i+chunkSize - 1) end return s end firstLine = inputFile:read() --read first line of file (FASTA header) proteinInputString = inputFile:read("*all") --read entire file as one string + all end of line chars inputFile:close() --close file because we got what we need from it trimmedSequence = string.gsub(proteinInputString, firstLine, "") --remove the FASTA header polishedSequence = string.upper(trimmedSequence:gsub("[\r\n]", "")) --remove new lines and carriage reture chars proteinInputTable = splitByChunk(polishedSequence, 1) --split protein seq into table of chars for i=1,#proteinInputTable do --for every amino letter in the table, for k, v in pairs(emojiCodex) do if proteinInputTable[i] == k then --if the letter matches a corresponding emoji in codex emojiOutputString = emojiOutputString .. v --append output string of emojis with corresponding emoji end end end outputFile:write(emojiOutputString) --write the output string of emojis to a file outputFile:close() --close the output file print("Done! Check your output file for emojis and enjoy :)")
Ball = {} Ball.__index = Ball local ballFilter = function(ball, other) if other.isBlock then return 'bounce' else return nil end -- else return nil end function Ball:create(x, y, r, world) local ball = {} ball.x, ball.y = x, y ball.rad = r ball.speed = 700 ball.directionX = 0 ball.directionY = 0 ball.r, ball.g, ball.b = 255, 255, 0 ball.isBall = true ball.world = world ball.escaped = false world:add(ball, x, y, ball.rad *2 , ball.rad * 2) setmetatable(ball, Ball) return ball end function Ball:setColor( r,g,b ) self.r, self.g, self.b = r, g, b end function Ball:putOnPlat(plat) -- self.world:remove(self) self.escaped = false self.x = plat.x + plat.w / 2 - self.rad self.y = plat.y - self.rad*2 self.onWhichPlat = plat self.world:update(self, self.x, self.y, self.rad *2 , self.rad * 2) end function Ball:update(dt) if(self.escaped)then local goalX, goalY = self.x + self.speed * self.directionX * dt , self.y + self.speed * self.directionY * dt local cols, len self.x, self.y, cols, len = self.world:move(self, goalX, goalY) for i=1, len do local other = cols[i].other if other.isBlock then if other.isBottom then lose = true else if other.crispy then other:crash() print(1) end if(cols[i].normal.x ~= 0) then self.directionX = self.directionX * -1 end if(cols[i].normal.y ~= 0) then self.directionY = self.directionY * -1 end end elseif other.isPlat then self.directionX = self.directionX * -1 self.directionY = self.directionY * -1 local dx = (self.x + self.rad) - (other.x + other.w / 2) self:setDirection(dx/120, self.directionY) end end else if love.keyboard.isDown('space') then print('eject') self.escaped = true self.directionX = 0 self.directionY = -1 else self:putOnPlat(self.onWhichPlat) end end end function Ball:setDirection(x, y) self.directionX = x / math.sqrt(x*x+y*y) self.directionY = y / math.sqrt(x*x+y*y) end function Ball:draw() love.graphics.setColor(self.r, self.g, self.b) love.graphics.circle("fill", self.x + self.rad, self.y + self.rad, self.rad, 128) if(debug)then local x,y,w,h = self.world:getRect(self) love.graphics.setColor(255,0 ,0 ) love.graphics.rectangle("line", x, y, w, h) end love.graphics.setColor(255,255,255) end return Ball
--New object_static_worldbuilding_vehicles_shared_barc_speeder_static_destroyed = SharedStaticObjectTemplate:new { clientTemplateFileName = "object/static/worldbuilding/vehicles/shared_barc_speeder_static_destroyed.iff" } ObjectTemplates:addClientTemplate(object_static_worldbuilding_vehicles_shared_barc_speeder_static_destroyed, "object/static/worldbuilding/vehicles/shared_barc_speeder_static_destroyed.iff") --********************************************************************************************************************************** object_static_worldbuilding_vehicles_shared_lambda_shuttle_static_destroyed = SharedStaticObjectTemplate:new { clientTemplateFileName = "object/static/worldbuilding/vehicles/shared_lambda_shuttle_static_destroyed.iff" } ObjectTemplates:addClientTemplate(object_static_worldbuilding_vehicles_shared_lambda_shuttle_static_destroyed, "object/static/worldbuilding/vehicles/shared_lambda_shuttle_static_destroyed.iff") --********************************************************************************************************************************** object_static_worldbuilding_vehicles_shared_landspeeder_static_destroyed = SharedStaticObjectTemplate:new { clientTemplateFileName = "object/static/worldbuilding/vehicles/shared_landspeeder_static_destroyed.iff" } ObjectTemplates:addClientTemplate(object_static_worldbuilding_vehicles_shared_landspeeder_static_destroyed, "object/static/worldbuilding/vehicles/shared_landspeeder_static_destroyed.iff") --********************************************************************************************************************************** object_static_worldbuilding_vehicles_shared_pv_snowspeeder = SharedStaticObjectTemplate:new { clientTemplateFileName = "object/static/worldbuilding/vehicles/shared_pv_snowspeeder.iff" } ObjectTemplates:addClientTemplate(object_static_worldbuilding_vehicles_shared_pv_snowspeeder, "object/static/worldbuilding/vehicles/shared_pv_snowspeeder.iff") --********************************************************************************************************************************** object_static_worldbuilding_vehicles_shared_speeder_bike_static_destroyed = SharedStaticObjectTemplate:new { clientTemplateFileName = "object/static/worldbuilding/vehicles/shared_speeder_bike_static_destroyed.iff" } ObjectTemplates:addClientTemplate(object_static_worldbuilding_vehicles_shared_speeder_bike_static_destroyed, "object/static/worldbuilding/vehicles/shared_speeder_bike_static_destroyed.iff") --**********************************************************************************************************************************
cc.FileUtils:getInstance():addSearchPath("src") cc.FileUtils:getInstance():addSearchPath("res") -- CC_USE_DEPRECATED_API = true require "cocos.init" -- cclog cclog = function(...) print(string.format(...)) end -- for CCLuaEngine traceback function __G__TRACKBACK__(msg) cclog("----------------------------------------") cclog("LUA ERROR: " .. tostring(msg) .. "\n") cclog(debug.traceback()) cclog("----------------------------------------") end local function initGLView() local director = cc.Director:getInstance() local glView = director:getOpenGLView() if nil == glView then glView = cc.GLViewImpl:create("Lua Empty Test") director:setOpenGLView(glView) end director:setOpenGLView(glView) glView:setDesignResolutionSize(480, 320, cc.ResolutionPolicy.NO_BORDER) --turn on display FPS director:setDisplayStats(true) --set FPS. the default value is 1.0/60 if you don't call this director:setAnimationInterval(1.0 / 60) end local function main() -- avoid memory leak collectgarbage("setpause", 100) collectgarbage("setstepmul", 5000) initGLView() require "hello2" cclog("result is " .. myadd(1, 1)) --------------- local visibleSize = cc.Director:getInstance():getVisibleSize() local origin = cc.Director:getInstance():getVisibleOrigin() -- add the moving dog local function creatDog() local frameWidth = 105 local frameHeight = 95 -- create dog animate local textureDog = cc.Director:getInstance():getTextureCache():addImage("dog.png") local rect = cc.rect(0, 0, frameWidth, frameHeight) local frame0 = cc.SpriteFrame:createWithTexture(textureDog, rect) rect = cc.rect(frameWidth, 0, frameWidth, frameHeight) local frame1 = cc.SpriteFrame:createWithTexture(textureDog, rect) local spriteDog = cc.Sprite:createWithSpriteFrame(frame0) spriteDog.isPaused = false spriteDog:setPosition(origin.x, origin.y + visibleSize.height / 4 * 3) --[[ local animFrames = CCArray:create() animFrames:addObject(frame0) animFrames:addObject(frame1) ]]-- local animation = cc.Animation:createWithSpriteFrames({frame0,frame1}, 0.5) local animate = cc.Animate:create(animation) spriteDog:runAction(cc.RepeatForever:create(animate)) -- moving dog at every frame local function tick() if spriteDog.isPaused then return end local x, y = spriteDog:getPosition() if x > origin.x + visibleSize.width then x = origin.x else x = x + 1 end spriteDog:setPositionX(x) end cc.Director:getInstance():getScheduler():scheduleScriptFunc(tick, 0, false) return spriteDog end -- create farm local function createLayerFarm() local layerFarm = cc.Layer:create() -- add in farm background local bg = cc.Sprite:create("farm.jpg") bg:setPosition(origin.x + visibleSize.width / 2 + 80, origin.y + visibleSize.height / 2) layerFarm:addChild(bg) -- add land sprite for i = 0, 3 do for j = 0, 1 do local spriteLand = cc.Sprite:create("land.png") spriteLand:setPosition(200 + j * 180 - i % 2 * 90, 10 + i * 95 / 2) layerFarm:addChild(spriteLand) end end -- add crop local frameCrop = cc.SpriteFrame:create("crop.png", cc.rect(0, 0, 105, 95)) for i = 0, 3 do for j = 0, 1 do local spriteCrop = cc.Sprite:createWithSpriteFrame(frameCrop) spriteCrop:setPosition(10 + 200 + j * 180 - i % 2 * 90, 30 + 10 + i * 95 / 2) layerFarm:addChild(spriteCrop) end end -- add moving dog local spriteDog = creatDog() layerFarm:addChild(spriteDog) -- handing touch events local touchBeginPoint = nil local function onTouchBegan(touch, event) local location = touch:getLocation() cclog("onTouchBegan: %0.2f, %0.2f", location.x, location.y) touchBeginPoint = {x = location.x, y = location.y} spriteDog.isPaused = true -- CCTOUCHBEGAN event must return true return true end local function onTouchMoved(touch, event) local location = touch:getLocation() cclog("onTouchMoved: %0.2f, %0.2f", location.x, location.y) if touchBeginPoint then local cx, cy = layerFarm:getPosition() layerFarm:setPosition(cx + location.x - touchBeginPoint.x, cy + location.y - touchBeginPoint.y) touchBeginPoint = {x = location.x, y = location.y} end end local function onTouchEnded(touch, event) local location = touch:getLocation() cclog("onTouchEnded: %0.2f, %0.2f", location.x, location.y) touchBeginPoint = nil spriteDog.isPaused = false end local listener = cc.EventListenerTouchOneByOne:create() listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN ) listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED ) listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCH_ENDED ) local eventDispatcher = layerFarm:getEventDispatcher() eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layerFarm) return layerFarm end -- create menu local function createLayerMenu() local layerMenu = cc.Layer:create() local menuPopup, menuTools, effectID local function menuCallbackClosePopup() -- stop test sound effect cc.SimpleAudioEngine:getInstance():stopEffect(effectID) menuPopup:setVisible(false) end local function menuCallbackOpenPopup() -- loop test sound effect local effectPath = cc.FileUtils:getInstance():fullPathForFilename("effect1.wav") effectID = cc.SimpleAudioEngine:getInstance():playEffect(effectPath) menuPopup:setVisible(true) end -- add a popup menu local menuPopupItem = cc.MenuItemImage:create("menu2.png", "menu2.png") menuPopupItem:setPosition(0, 0) menuPopupItem:registerScriptTapHandler(menuCallbackClosePopup) menuPopup = cc.Menu:create(menuPopupItem) menuPopup:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2) menuPopup:setVisible(false) layerMenu:addChild(menuPopup) -- add the left-bottom "tools" menu to invoke menuPopup local menuToolsItem = cc.MenuItemImage:create("menu1.png", "menu1.png") menuToolsItem:setPosition(0, 0) menuToolsItem:registerScriptTapHandler(menuCallbackOpenPopup) menuTools = cc.Menu:create(menuToolsItem) local itemWidth = menuToolsItem:getContentSize().width local itemHeight = menuToolsItem:getContentSize().height menuTools:setPosition(origin.x + itemWidth/2, origin.y + itemHeight/2) layerMenu:addChild(menuTools) return layerMenu end -- play background music, preload effect local bgMusicPath = cc.FileUtils:getInstance():fullPathForFilename("background.mp3") cc.SimpleAudioEngine:getInstance():playMusic(bgMusicPath, true) local effectPath = cc.FileUtils:getInstance():fullPathForFilename("effect1.wav") cc.SimpleAudioEngine:getInstance():preloadEffect(effectPath) -- run local sceneGame = cc.Scene:create() sceneGame:addChild(createLayerFarm()) sceneGame:addChild(createLayerMenu()) cc.Director:getInstance():runWithScene(sceneGame) end xpcall(main, __G__TRACKBACK__)
migration_0_17_57 = {} function migration_0_17_57.global() end function migration_0_17_57.player_table(player, player_table) end function migration_0_17_57.subfactory(player, subfactory) for _, floor in pairs(Subfactory.get_in_order(subfactory, "Floor")) do for _, line in pairs(Floor.get_in_order(floor, "Line")) do line.uncapped_production_ratio = 0 end end end
object_tangible_furniture_tatooine_uber_basket_shallow = object_tangible_furniture_tatooine_shared_uber_basket_shallow:new { } ObjectTemplates:addTemplate(object_tangible_furniture_tatooine_uber_basket_shallow, "object/tangible/furniture/tatooine/uber_basket_shallow.iff")
local function sendErrorParse( client, sendString, okayMsg ) connected, err = client:send( sendString ) if connected ~= nil then print( okayMsg ) else print( connected ) print( "Error: " ) print( err ) end end local socket = require( "src.socket" ) local timer = require( "love.timer" ) local config = require( "config" ) local sendChannel = love.thread.getChannel( "IRCSend" ) local receiveChannel = love.thread.getChannel( "IRCReceive" ) local client = socket.tcp() client:settimeout( 0.1 ) print( "Connecting to server " .. config.host .. ":" .. config.port ) local connected, err = client:connect( config.host, config.port ) if connected == 1 then print( "Successfully connected to server." ) else print( connected ) print( err ) end print( "Logging in as " .. config.nick ) sendErrorParse( client, "PASS " .. config.pass .. "\r\n", "Successfully sent password" ) sendErrorParse( client, "NICK " .. config.nick .. "\r\n", "Successfully sent nickname" ) sendErrorParse( client, "USER " .. config.nick .. " " .. config.nick .. " " .. config.nick .. " :" .. config.nick .. " IRC\r\n", "Successfully sent user" ) sendErrorParse( client, "CAP REQ :twitch.tv/membership\r\n", "Successfully sent membership request" ) sendErrorParse( client, "JOIN " .. config.chan .. "\r\n", "Successfully sent join" ) while true do local toSend = sendChannel:pop() if toSend ~= nil then sendErrorParse( client, toSend, "Successfully sent message" ) end local response = client:receive() if response ~= nil then receiveChannel:push( response ) end timer.sleep( 20/30 ) end
local M = {} -- table information begin local tableName = "pathHistory" -- table information end local Util = require "sora.util" function M.new(o,isSingleton) local ins local SoraModelMysql = require 'sora.model.mysql' if isSingleton then setmetatable(M, { __index = SoraModelMysql:new() }) ins = { tableName = tableName } setmetatable( ins, { __index = M } ) else ins = o or {} ins.tableName = tableName setmetatable( ins, { __index = SoraModelMysql:new() } ) end ins:mysqlConnectService(isSingleton) return ins end function M:add(data) local res,err = self:insert(data, true) if res then return res end self.errorMessage = err return false end return M
ifile = im.FileNew("1frame.avi", "AVI") ifile:SetInfo("CUSTOM") ifile:SetAttribute("FPS", im.FLOAT, {15}) -- Frames per second ifile:SetAttribute("AVIQuality", im.INT, {10000}) -- Default Quality new_image = im.ImageCreate(320, 240, im.RGB, im.BYTE) err = ifile:SaveImage(new_image) if (err ~= im.ERR_NONE) then ifile:Close() error("Error Saving: ".. err) end ifile:SaveImage(new_image) ifile:Close()
function momoTweak.finalFixes.ElectronicsCategory() for _, e in pairs(momoTweak.electronics) do momoIRTweak.recipe.SetCategory(e, "electronics") end for _, c in pairs(momoTweak.components) do momoIRTweak.recipe.SetCategory(c, "electronics") end local recipes = {momoTweak.board.grey, "circuit-grey-board-alternative", momoTweak.circuit.grey} for _, e in pairs(recipes) do momoIRTweak.recipe.SetCategory(e, "electronics") end end
--- Provides various cipher functions, such as a Caesar cipher, and Viginere cipher. -- @module[kind=misc] cipher -- Setup local functions local expect = require("cc.expect").expect -- Ensure that fields are correct. local function cut(str,len,pad) -- Shorten viginere keys. pad = pad or " " return str:sub(1,len) .. pad:rep(len - #str) end -- Very big table --- Just a numerically indiced table that contains every letter of the alphabet (English alphabet.) local letterTable = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", } for k, v in pairs(letterTable) do letterTable[v] = k end --- Shift a single letter by a modifier. -- @tparam string letter Letter to modify. -- @tparam number modifier How many letters to shift it by. -- @treturn string Shifted letter. local function shiftLetter(letter,modifier) -- Do type checking expect(1,letter,"string") expect(2,modifier,"number") if letter == " " then return " " end -- Get the index of the input letter local letterIndex = letterTable[letter] -- Add the modifier to the letter index local newIndex = letterIndex + modifier -- Return the index, between 1 and 26 return letterTable[newIndex % 26] end --- Run a Caesar Cipher on the provided string. (https://en.wikipedia.org/wiki/Caesar_cipher) -- @tparam string input String to cipher. -- @tparam[opt=-3] number shift Amount of letters to shift the string by. -- @treturn string Ciphered string. local function caesar(input,shift) -- Do type checking expect(1,input,"string") expect(2,shift,"number","nil") -- Default the shift if not present shift = shift or -3 -- Remove the invalid letters from a string. input = input:gsub("%A","") local outTbl = {} -- Loop through every letter in the string for x in input:lower():gmatch(".") do -- Shift the letter and insert it into the table local shifted = shiftLetter(x,shift) table.insert(outTbl,shifted) end -- Concatenate the entire table into a single string local final = table.concat(outTbl) return final end --- Run a Viginere cipher on the provided string. (https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher) -- @tparam string input String to cipher. -- @tparam string key Key to cipher the string with. -- @treturn string The ciphered string. local function viginere(input,key) -- Do type checking expect(1,input,"string") expect(2,input,"string") -- Check the key length against the input. local cutKey -- Cut to length key if key:len() < input:len() then -- If the key length is shorter than the input, repeat the key. -- Determine amount of repeats local repeatAmount = math.ceil(input:len() / key:len()) cutKey = cut(key:rep(repeatAmount),input:len()) -- Then cut the key to the to the length of the key. elseif key:len() > input:len() then -- If the key length is longer than the input, cut the key. cutKey = cut(key,input:len()) else cutKey = key end -- Tables to store the numbers in the tables. local inputNumbers = {} local keyNumbers = {} local combined = {} for x in input:gmatch(".") do if x == " " then table.insert(inputNumbers," ") else local index = letterTable[x] table.insert(inputNumbers,index) end end for x in cutKey:gmatch(".") do if x == " " then table.insert(inputNumbers," ") else local index = letterTable[x] table.insert(keyNumbers,index) end end -- Loop through the table, and combine the key and input. for i=1,#inputNumbers do if inputNumbers[i] == " " then table.insert(combined," ") else local inLet = inputNumbers[i]-1 local keyLet = keyNumbers[i]-1 local outNum = inLet + keyLet local outLet = letterTable[outNum % 26+1] table.insert(combined,outLet) end end -- Combined string local outString = table.concat(combined) return outString end --- Reverse a Viginere cipher on the provided string. (https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher) -- @tparam string input String to decipher. -- @tparam string key Key to decipher the string with. -- @treturn string The deciphered string. local function viginerDecode(input,key) -- Do type checking expect(1,input,"string") expect(2,input,"string") -- Check the key length against the input. local cutKey -- Cut to length key if key:len() < input:len() then -- If the key length is shorter than the input, repeat the key. -- Determine amount of repeats local repeatAmount = math.ceil(input:len() / key:len()) cutKey = cut(key:rep(repeatAmount),input:len()) -- Then cut the key to the to the length of the key. elseif key:len() > input:len() then -- If the key length is longer than the input, cut the key. cutKey = cut(key,input:len()) else cutKey = key end -- Tables to store the numbers in the tables. local inputNumbers = {} local keyNumbers = {} local combined = {} for x in input:gmatch(".") do local index = letterTable[x] table.insert(inputNumbers,index) end for x in cutKey:gmatch(".") do local index = letterTable[x] table.insert(keyNumbers,index) end -- Loop through the table, and combine the key and input. for i=1,#inputNumbers do local inLet = inputNumbers[i]-1 local keyLet = keyNumbers[i]-1 local outNum = inLet - keyLet if outNum < 0 then outNum = outNum + 26 end local outLet = letterTable[outNum % 26+1] table.insert(combined,outLet) end -- Combined string local outString = table.concat(combined) return outString end --- Run a ROT13 cipher on the input. (https://en.wikipedia.org/wiki/ROT13) -- @tparam string input The string to cipher. -- @tparam string The ciphered string. local function rot13(input) return caesar(input,13) end return { letterTable = letterTable, shiftLetter = shiftLetter, caesar = caesar, viginere = viginere, viginereDecode = viginerDecode, rot13 = rot13, }
local template = require "resty.template" local auth_header = ngx.var.http_authorization local _, _, token_string = string.find(auth_header, "Basic%s+(.+)") local user_json = ngx.decode_base64(token_string) local user = cjson.decode(user_json) local routes = {}; local route_keys = ngx.shared.api_routes:get_keys(100) for _, k in ipairs(route_keys) do v = ngx.shared.api_routes:get(k) routes[k] = v end template.cache = {} template.caching(false) template.render("debug.html", { title = "Opsee debug", headers = ngx.req.get_headers(), user = user, routes = routes })
if Holo:ShouldModify("HUD", "TopHUD") then Holo:Post(HUDHeistTimer, "init", function(self) self._bg_box = HUDBGBox_create(self._heist_timer_panel) self:UpdateHolo() Holo:AddUpdateFunc(callback(self, self, "UpdateHolo")) end) Holo:Post(HUDHeistTimer, "set_time", function(self, ...) if Holo.Options:GetValue("RealTime") then self._timer_text:set_text(os.date("%X")) end end) function HUDHeistTimer:UpdateHolo() if WolfHUD then self._heist_timer_panel:set_y(2) else self._heist_timer_panel:set_w(60) Holo.Utils:SetPosition(self._heist_timer_panel, "Timer") end self._heist_timer_panel:set_h(26) HUDBGBox_recreate(self._bg_box, { name = "Timer", w = 60, h = 24, }) self._bg_box:set_world_center(self._heist_timer_panel:world_center()) self._bg_box:set_visible(self._hud_panel == managers.hud:script(PlayerBase.PLAYER_INFO_HUD_PD2).panel and Holo.Options:GetValue("TimerBackground")) self._timer_text:configure({ font = "fonts/font_large_mf", font_size = self._bg_box:h() - 2, vertical = "center", color = Holo:GetColor("TextColors/Timer") }) self._timer_text:set_shape(self._bg_box:shape()) self._timer_text:move(0, 1) end end
local fmt, write=string.format,io.write local hof=coroutine.wrap(function() local yield=coroutine.yield local a={1,1} yield(a[1], 1) yield(a[2], 2) local n=a[#a] repeat n=a[n]+a[1+#a-n] a[#a+1]=n yield(n, #a) until false end) local mallows, mdiv=0,0 for p=1,20 do local max, div, num, last, fdiv=0,0,0,0,0 for i=2^(p-1),2^p-1 do h,n=hof() div=h/n if div>max then max=div num=n end if div>0.55 then last=n fdiv=div end end write(fmt("From 2^%-2d to 2^%-2d the max is %.4f the %6dth Hofstadter number.\n", p-1, p, max, num)) if max>.55 and p>4 then mallows, mdiv=last, fdiv end end write("So Mallows number is ", mallows, " with ", fmt("%.4f",mdiv), ", yay, just wire me my $10000 now!\n")
local m = {} tigris.magic = m tigris.include("mana.lua") tigris.include("essences.lua") tigris.include("spells.lua") tigris.include("potions.lua") tigris.include("jewelry.lua") tigris.include("portals.lua")
--[[ Bizhawk Shuffler 2 by authorblues inspired by Brossentia's Bizhawk Shuffler, based on slowbeef's original project tested on Bizhawk v2.6.2 - http://tasvideos.org/BizHawk/ReleaseHistory.html released under MIT License --]] config = {} total_time_limit = 0 running = true plugins = {} -- determine operating system for the purpose of commands _PLATFORMS = {['dll'] = 'WIN', ['so'] = 'LINUX', ['dylib'] = 'MAC'} PLATFORM = _PLATFORMS[package.cpath:match("%p[\\|/]?%p(%a+)")] PLUGINS_FOLDER = 'plugins' GAMES_FOLDER = 'games' STATES_FOLDER = GAMES_FOLDER .. '/.savestates' STATES_BACKUPS = 3 DEFAULT_CMD_OUTPUT = 'shuffler-src/.cmd-output.txt' MIN_BIZHAWK_VERSION = "2.6.1" RECOMMENDED_LUA_CORE = "LuaInterface" MAX_INTEGER = 99999999 local gettime = require("socket.core").gettime function log_message(msg, quiet) if not quiet then print(msg) end local handle, err = io.open('message.log', 'a') if handle == nil then return end handle:write(os.date("[%X] ")) handle:write(tostring(msg)) handle:write('\n') handle:close() end -- check if folder exists function path_exists(p) local ok, err, code = os.rename(p, p) -- code 13 is permission denied, but it's there if not ok and code == 13 then return true end return ok, err end function make_dir(p) if path_exists(p .. '/') then return end os.execute(string.format('mkdir "%s"', p)) end -- folders needed for the shuffler to run make_dir('output-info') make_dir(GAMES_FOLDER) make_dir(STATES_FOLDER) -- loads primary config file function load_config(f) local fn = loadfile(f) if fn ~= nil then fn() end return fn ~= nil end -- dump lua object function dump(o) function _dump(o, a, b) if type(o) == 'table' then local s = '' for k,v in pairs(o) do s = s..a..string.format('[%s] = %s,', _dump(k, "", ""), _dump(v, "", ""))..b end return '{'..b..s..'}'..b elseif type(o) == 'number' or type(o) == 'boolean' or o == nil then return tostring(o) elseif type(o) == 'string' then -- %q encloses in double quotes and escapes according to lua rules return string.format('%q', o) else -- functions, native objects, coroutines error(string.format('Unsupported value of type "%s" in config.', type(o))) end end return _dump(o, "\t", "\n") end -- saves primary config file function save_config(config, f) write_data(f, 'config=\n'..dump(config)) end -- output data to files (for OBS support) function write_data(filename, data, mode) local handle, err = io.open(filename, mode or 'w') if handle == nil then log_message(string.format("Couldn't write to file: %s", filename)) log_message(err) return end handle:write(data) handle:close() end function table_subtract(t2, t1) local t = {} for i = 1, #t1 do t[t1[i]] = true end for i = #t2, 1, -1 do if t[t2[i]] then table.remove(t2, i) end end end -- returns a table containing all files in a given directory function get_dir_contents(dir, tmp, force) local TEMP_FILE = tmp or DEFAULT_CMD_OUTPUT if force ~= false or not path_exists(TEMP_FILE) then local cmd = string.format('ls "%s" -type f > %s', dir, TEMP_FILE) if PLATFORM == 'WIN' then cmd = string.format('dir "%s" /B /A-D > %s', dir, TEMP_FILE) end os.execute(cmd) end local file_list = {} local fp = io.open(TEMP_FILE, 'r') for x in fp:lines() do table.insert(file_list, x) end fp:close() return file_list end -- types of files to ignore in the games directory local IGNORED_FILE_EXTS = { '.msu', '.pcm' } -- get list of games function get_games_list(force) local LIST_FILE = '.games-list.txt' local games = get_dir_contents(GAMES_FOLDER, GAMES_FOLDER .. '/' .. LIST_FILE, force or false) local toremove = {} -- find .cue files and remove the associated bin/iso for _,filename in ipairs(games) do if ends_with(filename, '.cue') then -- open the cue file, oh god here we go... fp = io.open(GAMES_FOLDER .. '/' .. filename, 'r') for line in fp:lines() do -- look for the line that starts with FILE and remove the rest of the stuff if starts_with(line, "FILE") and ends_with(line, "BINARY") then table.insert(toremove, line:sub(7, -9)) end end fp:close() -- ccd/img format? elseif ends_with(filename, '.ccd') then local primary = filename:sub(1, #filename-4) table.insert(toremove, primary .. '.img') table.insert(toremove, primary .. '.sub') elseif ends_with(filename, '.xml') then fp = io.open(GAMES_FOLDER .. '/' .. filename, 'r') local xml = fp:read("*all") fp:close() -- bizhawk multidisk bundle if xml:find('BizHawk--XMLGame') then -- double hyphen to escape literal hyphen for asset in xml:gfind('<Asset.-FileName="(.-)".-/>') do if asset:find('\.\\') == 1 then asset = asset:sub(3) end table.insert(toremove, asset) end end end for _,ext in ipairs(IGNORED_FILE_EXTS) do if ends_with(filename, ext) then table.insert(toremove, filename) end end end table_subtract(games, toremove) table_subtract(games, { LIST_FILE }) table_subtract(games, config.completed_games) return games end -- delete savestates folder function delete_savestates() local cmd = string.format('rm -rf "%s"', STATES_FOLDER) if PLATFORM == 'WIN' then cmd = string.format('rmdir "%s" /S /Q', STATES_FOLDER) end os.execute(cmd) end function get_savestate_file(game) game = game or config.current_game if game == nil then error('no game specified for savestate file') end return string.format("%s/%s.state", STATES_FOLDER, game) end function save_current_game() local function overwrite(a, b) os.remove(b) os.rename(a, b) end if config.current_game ~= nil then local statename = get_savestate_file() -- safety backups for i = STATES_BACKUPS, 2, -1 do overwrite(string.format("%s.bk%d", statename, i-1), string.format("%s.bk%d", statename, i)) end overwrite(statename, statename .. '.bk1') savestate.save(statename) end end function file_exists(f) local p = io.open(f, 'r') if p == nil then return false end io.close(p) return true end -- we don't load the savestate here because (for some unbelievably f***ed up reason), -- client.openrom() causes the whole script to reload, forcing us to use a convoluted -- method to determine if this is the initial execution of the script, or a reload -- caused by openrom(). in any case, loading the savestate here seems to run into -- a race condition, so we load the savestate at the beginning of the reloaded script function load_game(g) local filename = GAMES_FOLDER .. '/' .. g if not file_exists(filename) then return false end client.openrom(filename) return true end function get_next_game() local prev = config.current_game or nil local all_games = get_games_list() -- check to make sure that all of the games correspond to actual -- game files that can be opened local all_exist = true for i,game in ipairs(all_games) do all_exist = all_exist and file_exists(GAMES_FOLDER .. '/' .. game) end -- if any of the games are missing, force a refresh of the game list if not all_exist then all_games = get_games_list(true) end -- shuffle_index == -1 represents fully random shuffle order if config.shuffle_index < 0 then -- remove the currently loaded game and see if there are any other options table_subtract(all_games, { prev }) if #all_games == 0 then return prev end return all_games[math.random(#all_games)] else -- manually select the next one if #all_games == 1 then return prev end config.shuffle_index = (config.shuffle_index % #all_games) + 1 return all_games[config.shuffle_index] end end -- save current game's savestate, backup config, and load new game function swap_game(next_game) -- if a swap has already happened, don't call again if not running then return false end -- set the time for the next game to swap update_next_swap_time() -- if no game provided, call get_next_game() next_game = next_game or get_next_game() -- if the game isn't changing, stop here and just update the timer -- (you might think we should just disable the timer at this point, but this -- allows new games to be added mid-run without the timer being disabled) if next_game == config.current_game then return false end -- swap_game() is used for the first load, so check if a game is loaded if config.current_game ~= nil then for _,plugin in ipairs(plugins) do if plugin.on_game_save ~= nil then local pdata = config.plugins[plugin._module] plugin.on_game_save(pdata.state, pdata.settings) end end end -- at this point, save the game and update the new "current" game after save_current_game() config.current_game = next_game running = false -- mute the sound for a moment to help with the swap config.sound = client.GetSoundOn() client.SetSoundOn(false) -- force another frame to pass to get the mute to take effect if emu.getsystemid() ~= "NULL" then emu.frameadvance() end -- unique game count, for debug purposes config.game_count = 0 for k,v in pairs(config.game_swaps) do config.game_count = config.game_count + 1 end -- save an updated randomizer seed config.nseed = math.random(MAX_INTEGER) save_config(config, 'shuffler-src/config.lua') -- load the new game WHICH IS JUST GOING TO RESTART THE WHOLE SCRIPT f*** return load_game(config.current_game) end function swap_game_delay(seconds) config.total_time_limit = config.total_time_limit + seconds end function update_next_swap_time() if config.auto_shuffle then swap_game_delay(math.random(config.min_swap * 100, config.max_swap * 100) / 100) else config.total_time_limit = math.huge -- infinity end end function starts_with(a, b) return a:sub(1, #b) == b end function ends_with(a, b) return a:sub(-#b) == b end function strip_ext(filename) local ndx = filename:find("\.[^\.]*$") return filename:sub(1, ndx-1) end function checkversion(reqversion) -- nil string means no requirements, so of course true if reqversion == nil then return true end local curr, reqd = {}, {} for x in string.gmatch(client.getversion(), "%d+") do table.insert(curr, tonumber(x)) end for x in string.gmatch(reqversion, "%d+") do table.insert(reqd, tonumber(x)) end while #curr < #reqd do table.insert(curr, 0) end for i=1,#reqd do if curr[i]<reqd[i] then return false end end return true end local function check_lua_core() if client.get_lua_engine() ~= RECOMMENDED_LUA_CORE then log_message(string.format("\n[!] It is recommended to use the %s core (currently using %s)\n" .. "Change the Lua core in the Config > Customize > Advanced menu and restart BizHawk", RECOMMENDED_LUA_CORE, client.get_lua_engine())) end end function seconds_to_time(sec) local min = math.floor(sec / 60) local hrs = math.floor(min / 60) return string.format('%02d:%02d:%02d', hrs, min%60, sec%60) end function output_completed() completed = "" for i,game in ipairs(config.completed_games) do completed = completed .. strip_ext(game) .. '\n' end write_data('output-info/completed-games.txt', completed) end function mark_complete() -- mark the game as complete in the config file rather than moving files around table.insert(config.completed_games, config.current_game) log_message(config.current_game .. ' marked complete') for _,plugin in ipairs(plugins) do if plugin.on_complete ~= nil then local pdata = config.plugins[plugin._module] plugin.on_complete(pdata.state, pdata.settings) end end -- update list of completed games in file output_completed() if #get_games_list() == 0 then -- the shuffler is complete! running = false save_config(config, 'shuffler-src/config.lua') log_message('Shuffler complete!') else swap_game() end end function cwd() local cmd = string.format('pwd > %s', DEFAULT_CMD_OUTPUT) if PLATFORM == 'WIN' then cmd = string.format('cd > %s', DEFAULT_CMD_OUTPUT) end os.execute(cmd) local fp = io.open(DEFAULT_CMD_OUTPUT, 'r') local resp = fp:read("*all") fp:close() return resp:match( "^%s*(.+)%s*$" ) end function complete_setup() os.remove('message.log') if config.plugins ~= nil then for pmodpath,pdata in pairs(config.plugins) do local pmodule = require(PLUGINS_FOLDER .. '.' .. pmodpath) if checkversion(pmodule.minversion) then log_message('Plugin loaded: ' .. pmodule.name) else log_message(string.format('%s requires Bizhawk version %s+', pmodule.name, pmodule.minversion)) log_message("-- Currently installed version: " .. client.getversion()) log_message("-- Please update your Bizhawk installation to use this plugin") config.plugins[pmodpath] = nil end if pmodule ~= nil and pmodule.on_setup ~= nil then pmodule.on_setup(pdata.state, pdata.settings) end end end local games = get_games_list(true) -- force refresh of the games list if #games == 0 then local sep = '/' if PLATFORM == 'WIN' then sep = '\\' end log_message('No games found in the expected directory. Were they put somewhere else? ' .. 'Are they nested inside folders? ROM files should be placed directly in the following directory:') if cwd ~= nil then log_message(string.format("Expected: %s%s%s", cwd(), sep, GAMES_FOLDER)) end return end -- these messages will only appear in the message log log_message('Platform: ' .. PLATFORM, true) log_message('Bizhawk version: ' .. client.getversion(), true) for _,game in ipairs(games) do log_message('GAME FOUND: ' .. game, true) end config.total_time_limit = 0 config.initial_time = gettime() save_config(config, 'shuffler-src/config.lua') math.randomseed(config.nseed or config.seed) if config.frame_count == 0 then log_message('deleting savestates!') delete_savestates() end -- whatever the current state is, update the output file output_completed() -- if there is already a listed current game, this is a resumed session -- otherwise, call swap_game() to setup for the first game load if config.current_game ~= nil then load_game(config.current_game) else swap_game() end end function get_tag_from_hash_db(target, database) local resp = nil local fp = io.open(database, 'r') for x in fp:lines() do local hash, tag = x:match("^([0-9A-Fa-f]+)%s+(%S+)") if hash == target then resp = tag; break end end fp:close() return resp end check_lua_core() -- load primary configuration load_config('shuffler-src/config.lua') if emu.getsystemid() ~= "NULL" then -- THIS CODE RUNS EVERY TIME THE SCRIPT RESTARTS -- which is specifically after a call to client.openrom() -- I will try to limit the number of comments I write solely to complain about -- this design decision, but I make no promises. -- load plugin configuration if config.plugins ~= nil then for pmodpath,pdata in pairs(config.plugins) do local pmodule = require(PLUGINS_FOLDER .. '.' .. pmodpath) pmodule._module = pmodpath if pmodule ~= nil then table.insert(plugins, pmodule) end end end local state = get_savestate_file() if file_exists(state) then savestate.load(state) end -- update swap counter for this game local new_swaps = (config.game_swaps[config.current_game] or 0) + 1 config.game_swaps[config.current_game] = new_swaps write_data('output-info/current-swaps.txt', new_swaps) -- update total swap counter config.total_swaps = (config.total_swaps or 0) + 1 write_data('output-info/total-swaps.txt', config.total_swaps) -- update game name write_data('output-info/current-game.txt', strip_ext(config.current_game)) -- this code just outright crashes on Bizhawk 2.6.1, go figure if checkversion("2.6.2") then gui.use_surface('client') gui.clearGraphics() end math.randomseed(config.nseed or config.seed) for _,plugin in ipairs(plugins) do if plugin.on_game_load ~= nil then local pdata = config.plugins[plugin._module] plugin.on_game_load(pdata.state, pdata.settings) end end else -- THIS CODE RUNS ONLY ON THE INITIAL SCRIPT SETUP client.displaymessages(false) if checkversion(MIN_BIZHAWK_VERSION) then local setup = require('shuffler-src.setupform') setup.initial_setup(complete_setup) else log_message(string.format("Expected Bizhawk version %s+", MIN_BIZHAWK_VERSION)) log_message("-- Currently installed version: " .. client.getversion()) log_message("-- Please update your Bizhawk installation") end end prev_input = input.get() frames_since_restart = 0 local ptime_total = nil local ptime_game = nil last_time = gettime() while true do if emu.getsystemid() ~= "NULL" and running then -- wait for a frame to pass before turning sound back on if frames_since_restart == 1 and config.sound then client.SetSoundOn(true) end local frame_count = (config.frame_count or 0) + 1 config.frame_count = frame_count frames_since_restart = frames_since_restart + 1 local time = gettime() local time_difference = time - last_time last_time = time local total_time_since_start = time - config.initial_time local total_time = config.total_time + time_difference config.total_time = total_time -- update the frame count specifically for the active game as well local current_game_seconds = (config.game_second_count[config.current_game] or 0) + time_difference config.game_second_count[config.current_game] = current_game_seconds -- save time info to files for OBS display if config.output_timers then local time_total = seconds_to_time(total_time) if time_total ~= ptime_total then write_data('output-info/total-time.txt', time_total) ptime_total = time_total end local time_game = seconds_to_time(current_game_seconds) if time_game ~= ptime_game then write_data('output-info/current-time.txt', time_game) ptime_game = time_game end end -- let plugins do operations each frame for _,plugin in ipairs(plugins) do if plugin.on_frame ~= nil then local pdata = config.plugins[plugin._module] plugin.on_frame(pdata.state, pdata.settings) end end -- calculate input "rises" by subtracting the previously held inputs from the inputs on this frame local input_rise = input.get() for k,v in pairs(prev_input) do input_rise[k] = nil end prev_input = input.get() -- mark the game as complete if the hotkey is pressed (and some time buffer) -- the time buffer should hopefully prevent somebody from attempting to -- press the hotkey and the game swapping, marking the wrong game complete if input_rise[config.hk_complete] and frames_since_restart > math.min(3, config.min_swap/2) * 60 then mark_complete() end -- time to swap! if total_time_since_start >= config.total_time_limit then swap_game() end end emu.frameadvance() end
local function capture() local img = image(CAMERA) for i = 1, img.width, 10 do for j = 1, img.height, 10 do table.insert(pixels,{x=i/2,y=j/2,w=5,h=5,c=color(img:get(i,j))}) end end captured = true end function setup() parameter.action("Capture",capture) parameter.number("ChromaKey",0,255,0) noSmooth() captured = false pixels = {} end function draw() background(0) if captured then for _,v in ipairs(pixels) do if v.c.g > ChromaKey then fill(v.c) rect(v.x,v.y,v.w,v.h) end end else fill(255) sprite(CAMERA,WIDTH/2,HEIGHT/2,math.min(spriteSize(CAMERA),WIDTH)) end end
Hyper = {"ctrl", "cmd", "shift"} AssetsDir = hs.configdir .. "assets/" -- hs.logger.defaultLogLevel = 'debug' ConfigLogger = hs.logger.new('config','debug')
--[[ Copyright 2017 YANG Huan ([email protected]). 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 System = System local throw = System.throw local clear = System.Array.clear local ArgumentNullException = System.ArgumentNullException local ArgumentOutOfRangeException = System.ArgumentOutOfRangeException local table = table local tconcat = table.concat local schar = string.char local ssub = string.sub local function build(this, value, startIndex, length) value = value:Substring(startIndex, length) local len = #value if len > 0 then this[#this + 1] = value this.Length = len end end System.define("System.StringBuilder", { Length = 0, ToString = tconcat, __tostring = tconcat, __ctor__ = function (this, ...) local len = select("#", ...) if len == 0 then elseif len == 1 or len == 2 then local value = ... if type(value) == "string" then build(this, value, 0, #value) else build(this, "", 0, 0) end else local value, startIndex, length = ... build(this, value, startIndex, length) end end, getLength = function (this) return this.Length end, setLength = function (this, value) if value < 0 then throw(ArgumentOutOfRangeException("value")) end if value == 0 then this:Clear() return end local delta = value - this.Length if delta > 0 then this:AppendCharRepeat(0, delta) else local length, remain = #this, value for i = 1, length do local s = this[i] local len = #s if len >= remain then if len ~= remain then s = ssub(s, 0, remain) this[i] = s end for j = i + 1, length do this[j] = nil end break end remain = remain - len end this.Length = this.Length + delta end end, Append = function (this, ...) local len = select("#", "...") if len == 1 then local value = ... if value ~= nil then value = value:ToString() this[#this + 1] = value this.Length = this.Length + #value end else local value, startIndex, length = ... if value == nil then throw(ArgumentNullException("value")) end value = value:Substring(startIndex, length) this[#this + 1] = value this.Length = this.Length + #value end return this end, AppendChar = function (this, v) v = schar(v) this[#this + 1] = v this.Length = this.Length + 1 return this end, AppendCharRepeat = function (this, v, repeatCount) if repeatCount < 0 then throw(ArgumentOutOfRangeException("repeatCount")) end if repeatCount == 0 then return this end v = schar(v) local count = #this + 1 for i = 1, repeatCount do this[count] = v count = count + 1 end this.Length = this.Length + repeatCount return this end, AppendFormat = function (this, format, ...) local value = format:Format(...) this[#this + 1] = value this.Length = this.Length + #value return this end, AppendLine = function (this, value) local count = 1 local len = #this + 1 if value ~= nil then this[len] = value len = len + 1 count = count + #value end this[len] = "\n" this.Length = this.Length + count return this end, Clear = function (this) clear(this) this.length = 0 return this end })
local M = { } M.defaultFont = jd.Font.request(jd.conf.misc.defaultFont) M.defaultLayer = jd.drawService:layer(3) function M.create(s, p, layer, font) if type(font) == 'string' then font = jd.Font.request(font) else font = font or M.defaultFont end layer = layer or M.defaultLayer.group p = p or jd.Vec2() local text = jd.Text(layer) text.font = font text.string = s text.position = p return text end local function calculateCenterP(t, layer) layer = layer or M.defaultLayer local r = t.bounds local d = r.position - t.position r.center = layer.view.center return r.position - d end function M.center(t, layer) t.position = calculateCenterP(t, layer) end function M.centerX(t, layer) t.position = jd.Vec2(calculateCenterP(t, layer).x, t.position.y) end function M.centerY(t, layer) t.position = jd.Vec2(t.position.x, calculateCenterP(t, layer).y) end return M
SoundLayerEditor = SoundLayerEditor or class(EnvironmentLayerEditor) local SndLayer = SoundLayerEditor function SndLayer:init(parent) self:init_basic(parent, "SoundLayerEditor") self._menu = parent._holder MenuUtils:new(self) self._created_units = {} self._environment_unit = "core/units/sound_environment/sound_environment" self._emitter_unit = "core/units/sound_emitter/sound_emitter" self._area_emitter_unit = "core/units/sound_area_emitter/sound_area_emitter" end function SndLayer:loaded_continents() if true then return end for _, area in ipairs(clone(managers.sound_environment:areas())) do local unit = self:do_spawn_unit(self._environment_unit, {name_id = area:name(), position = area:position(), rotation = area:rotation()}) unit:unit_data().environment_area = area unit:unit_data().environment_area:set_unit(unit) end for _, emitter in ipairs(clone(managers.sound_environment:emitters())) do local unit = self:do_spawn_unit(self._emitter_unit, {name_id = emitter:name(), position = emitter:position(), rotation = emitter:rotation()}) unit:unit_data().emitter = emitter unit:unit_data().emitter:set_unit(unit) end for _, emitter in ipairs(clone(managers.sound_environment:area_emitters())) do local unit = self:do_spawn_unit(self._area_emitter_unit, {name_id = emitter:name(), position = emitter:position(), rotation = emitter:rotation()}) unit:unit_data().emitter = emitter unit:unit_data().emitter:set_unit(unit) end end function SndLayer:save() local sound_environments = {} local sound_emitters = {} local sound_area_emitters = {} for _, unit in ipairs(self._created_units) do if unit:name() == Idstring(self._environment_unit) then local area = unit:unit_data().environment_area local shape_table = area:save_level_data() shape_table.environment = area:environment() shape_table.ambience_event = area:ambience_event() shape_table.occasional_event = area:occasional_event() shape_table.use_environment = area:use_environment() shape_table.use_ambience = area:use_ambience() shape_table.use_occasional = area:use_occasional() shape_table.name = area:name() table.insert(sound_environments, shape_table) end if unit:name() == Idstring(self._emitter_unit) then local emitter = unit:unit_data().emitter table.insert(sound_emitters, { emitter_event = emitter:emitter_event(), position = emitter:position(), rotation = emitter:rotation(), name = emitter:name() }) end if unit:name() == Idstring(self._area_emitter_unit) then local area_emitter = unit:unit_data().emitter local shape_table = area_emitter:save_level_data() shape_table.name = area_emitter:name() table.insert(sound_area_emitters, shape_table) end end local default_ambience = managers.sound_environment:default_ambience() local default_occasional = managers.sound_environment:default_occasional() local ambience_enabled = managers.sound_environment:ambience_enabled() managers.worlddefinition._sound_data = { default_environment = managers.sound_environment:default_environment(), default_ambience = default_ambience, ambience_enabled = ambience_enabled, default_occasional = default_occasional, sound_environments = sound_environments, sound_emitters = sound_emitters, sound_area_emitters = sound_area_emitters } end function SndLayer:reset_selected_units() for k, unit in ipairs(clone(self._created_units)) do if not alive(unit) then table.remove(self._created_units, k) end end self:save() end function SndLayer:update(t, dt) if self:Value("SoundUnits") then local selected_units = self:selected_units() for _, unit in ipairs(self._created_units) do if alive(unit) then if unit:name() == Idstring(self._emitter_unit) then local r, g, b = 0.6, 0.6, 0 if table.contains(selected_units, unit) then r, g, b = 1, 1, 0.4 end unit:unit_data().emitter:draw(t, dt, r, g, b) end if unit:name() == Idstring(self._environment_unit) then Application:draw(unit, 1, 1, 1) local r, g, b = 0, 0, 0.8 if table.contains(selected_units, unit) then r, g, b = 0.4, 0.4, 1 end unit:unit_data().environment_area:draw(t, dt, r, g, b) end if unit:name() == Idstring(self._area_emitter_unit) then Application:draw(unit, 1, 1, 1) local r, g, b = 0, 0, 0.8 if table.contains(selected_units, unit) then r, g, b = 0.4, 0.4, 1 end unit:unit_data().emitter:draw(t, dt, r, g, b) end end end end end function SndLayer:ambience_events() local events = {} for _, sound in pairs(Global.WorldSounds) do if string.begins(sound, "ambience_") then table.insert(events, sound) end end return events end function SndLayer:occasional_events() local events = {} for _, sound in pairs(Global.WorldSounds) do if string.begins(sound, "occasionals_") then table.insert(events, sound) end end return events end function SndLayer:emitter_events() local events = {} for _, sound in pairs(Global.WorldSounds) do if string.begins(sound, "emitter_") then table.insert(events, sound) end end return events end function SndLayer:build_menu() local defaults = self:Group("Defaults") local environments = managers.sound_environment:environments() self._default_environment = self:ComboBox("Environment", callback(self, self, "select_default_sound_environment"), environments, table.get_key(environments, managers.sound_environment:default_environment()), {group = defaults}) local events = self:ambience_events() self._default_ambience = self:ComboBox("Ambience", callback(self, self, "select_default_ambience"), events, table.get_key(events, managers.sound_environment:default_ambience()), { group = defaults, enabled = #events > 0 }) local occ_events = self:occasional_events() self._default_occasional = self:ComboBox("Occasional", callback(self, self, "select_default_occasional"), occ_events, table.get_key(occ_events, managers.sound_environment:default_occasional()), { group = defaults, enabled = #occ_events > 0 }) self._ambience_enabled = self:Toggle("AmbienceEnabled", callback(self, self, "set_ambience_enabled"), managers.sound_environment:ambience_enabled(), {group = defaults, enabled = #events > 0}) self:Button("RestartAllEmitters", callback(self, self, "on_restart_emitters")) self:Button("SpawnSoundEnvironment", callback(self._parent, self._parent, "BeginSpawning", self._environment_unit)) self:Button("SpawnSoundEmitter", callback(self._parent, self._parent, "BeginSpawning", self._emitter_unit)) self:Button("SpawnSoundAreaEmitter", callback(self._parent, self._parent, "BeginSpawning", self._area_emitter_unit)) end function SndLayer:build_unit_menu() local S = self:Manager("static") S._built_multi = false S.super.build_default_menu(S) local unit = self:selected_unit() if alive(unit) then S:build_positions_items(true) S:update_positions() S:Button("CreatePrefab", callback(S, S, "add_selection_to_prefabs"), {group = S:GetItem("QuickButtons")}) if unit:name() == self._environment_unit:id() then S:SetTitle("Sound Environment Selection") local sound_environment = S:Group("SoundEnvironment", {index = 1}) S:TextBox("Name", callback(self, self, "set_unit_name_id"), unit:unit_data().name_id or "", {group = sound_environment}) local environments = managers.sound_environment:environments() self._effect = S:ComboBox("Effect", callback(self, self, "select_sound_environment"), managers.sound_environment:environments(), table.get_key(environments, managers.sound_environment:default_environment()), { group = sound_environment }) self._use_environment = S:Toggle("UseEnvironment", callback(self, self, "toggle_use_environment"), true, {group = sound_environment}) local events = self:ambience_events() self._ambience = S:ComboBox("Ambience", callback(self, self, "select_environment_ambience"), events, table.get_key(events, managers.sound_environment:default_ambience()), { group = sound_environment, }) self._use_ambience = S:Toggle("UseAmbience", callback(self, self, "toggle_use_ambience"), true, {group = sound_environment}) local occ_events = self:occasional_events() self._occasional = S:ComboBox("Occasional", callback(self, self, "select_environment_occasional"), occ_events, table.get_key(occ_events, managers.sound_environment:default_occasional()), { group = sound_environment, }) self._use_occasional = S:Toggle("UseOccasional", callback(self, self, "toggle_use_occasional"), true, {group = sound_environment}) self:set_sound_environment_parameters() elseif unit:name() == self._emitter_unit:id() or unit:name() == self._area_emitter_unit:id() then if unit:name() == self._emitter_unit:id() then S:SetTitle("Sound Emitter Selection") elseif unit:name() == self._area_emitter_unit:id() then S:SetTitle("Sound Area Emitter Selection") end local sound_emitter = S:Group("SoundEmitter", {index = 1}) S:TextBox("Name", callback(self, self, "set_unit_name_id"), unit:unit_data().name_id or "", {group = sound_emitter}) local events = self:emitter_events{} self._emitter_events_combobox = S:ComboBox("Events", callback(self, self, "select_emitter_event"), events, table.get_key(events, default_emitter_path and managers.sound_environment:emitter_events(default_emitter_path)[1]), {group = sound_emitter}) self:set_sound_emitter_parameters() end end end function SndLayer:select_default_ambience(menu, item) managers.sound_environment:set_default_ambience(item:SelectedItem()) self:save() end function SndLayer:select_default_occasional(menu, item) managers.sound_environment:set_default_occasional(item:SelectedItem()) self:save() end function SndLayer:set_ambience_enabled(menu, item) managers.sound_environment:set_ambience_enabled(item:Value()) self:save() end function SndLayer:select_default_sound_environment(menu, item) managers.sound_environment:set_default_environment(item:SelectedItem()) self:save() end function SndLayer:select_emitter_path(menu, item) local path = item:SelectedItem() local emitter = self:selected_unit():unit_data().emitter emitter:set_emitter_path(path) self._emitter_events_combobox:SetItems(managers.sound_environment:emitter_events(path)) self._emitter_events_combobox:SetSelectedItem(emitter:emitter_event()) end function SndLayer:select_emitter_event(menu, item) self:selected_unit():unit_data().emitter:set_emitter_event(item:SelectedItem()) self:save() end function SndLayer:select_sound_environment(menu, item) self:selected_unit():unit_data().environment_area:set_environment(item:SelectedItem()) self:save() end function SndLayer:toggle_use_environment(menu, item) self:selected_unit():unit_data().environment_area:set_use_environment(item:Value()) self:save() end function SndLayer:select_environment_ambience(menu, item) self:selected_unit():unit_data().environment_area:set_environment_ambience(item:SelectedItem()) self:save() end function SndLayer:toggle_use_ambience(menu, item) self:selected_unit():unit_data().environment_area:set_use_ambience(item:Value()) self:save() end function SndLayer:select_environment_occasional(menu, item) self:selected_unit():unit_data().environment_area:set_environment_occasional(item:SelectedItem()) self:save() end function SndLayer:toggle_use_occasional(menu, item) self:selected_unit():unit_data().environment_area:set_use_occasional(item:Value()) self:save() end function SndLayer:on_restart_emitters() for _, unit in ipairs(self._created_units) do if unit:name() == Idstring(self._emitter_unit) or unit:name() == Idstring(self._area_emitter_unit) then unit:unit_data().emitter:restart() end end end function SndLayer:do_spawn_unit(unit_path, ud) local unit = World:spawn_unit(unit_path:id(), ud.position or Vector3(), ud.rotation or Rotation()) table.merge(unit:unit_data(), ud) unit:unit_data().name = unit_path unit:unit_data().sound_unit = true unit:unit_data().position = unit:position() unit:unit_data().rotation = unit:rotation() table.insert(self._created_units, unit) if alive(unit) then if unit:name() == Idstring(self._emitter_unit) then local emitter = unit:unit_data().emitter if not emitter or emitter:unit() ~= unit then unit:unit_data().emitter = managers.sound_environment:add_emitter(emitter and emitter:get_params() or {}) unit:unit_data().emitter:set_unit(unit) end elseif unit:name() == Idstring(self._area_emitter_unit) then local emitter = unit:unit_data().emitter if not emitter or emitter:unit() ~= unit then unit:unit_data().emitter = managers.sound_environment:add_area_emitter(emitter and emitter:save_level_data() or {}) unit:unit_data().emitter:set_unit(unit) end elseif unit:name() == Idstring(self._environment_unit) then local area = unit:unit_data().environment_area if not area or area:unit() ~= unit then unit:unit_data().environment_area = managers.sound_environment:add_area(area and area:get_params() or {}) unit:unit_data().environment_area:set_unit(unit) end end end self:save() return unit end function SndLayer:is_my_unit(unit) if unit == self._emitter_unit:id() or unit == self._environment_unit:id() or unit == self._area_emitter_unit:id() then return true end return false end function SndLayer:delete_unit(unit) local ud = unit:unit_data() table.delete(self._created_units, unit) if ud then if unit:name() == Idstring(self._environment_unit) then managers.sound_environment:remove_area(ud.environment_area) end if unit:name() == Idstring(self._emitter_unit) then managers.sound_environment:remove_emitter(ud.emitter) end if unit:name() == Idstring(self._area_emitter_unit) then managers.sound_environment:remove_area_emitter(ud.emitter) end end self:save() end function SndLayer:set_sound_environment_parameters() local S = self:Manager("static") self._effect:SetEnabled(false) self._ambience:SetEnabled(false) self._occasional:SetEnabled(false) self._use_environment:SetEnabled(false) self._use_ambience:SetEnabled(false) self._use_occasional:SetEnabled(false) if alive(self:selected_unit()) and self:selected_unit():name() == self._environment_unit:id() then local area = self:selected_unit():unit_data().environment_area if area then area:create_panel(S) self._effect:SetEnabled(true) self._ambience:SetEnabled(true) self._occasional:SetEnabled(true) self._use_environment:SetEnabled(true) self._use_ambience:SetEnabled(true) self._use_occasional:SetEnabled(true) self._effect:SetSelectedItem(area:environment()) self._ambience:SetSelectedItem(area:ambience_event()) self._occasional:SetSelectedItem(area:occasional_event()) self._use_environment:SetValue(area:use_environment()) self._use_ambience:SetValue(area:use_ambience()) self._use_occasional:SetValue(area:use_occasional()) end end end function SndLayer:set_sound_emitter_parameters() local S = self:Manager("static") if alive(self:selected_unit()) and (self:selected_unit():name() == self._emitter_unit:id() or self:selected_unit():name() == self._area_emitter_unit:id()) then local emitter = self:selected_unit():unit_data().emitter if emitter then self._emitter_events_combobox:SetSelectedItem(emitter:emitter_event()) end if self:selected_unit():name() == self._area_emitter_unit:id() then local area = self:selected_unit():unit_data().emitter if area then area:create_panel(S) end end end end function SndLayer:activate() SoundLayerEditor.super.activate(self) managers.editor:set_listener_enabled(true) managers.editor:set_wanted_mute(false) end function SndLayer:deactivate(params) managers.editor:set_listener_enabled(false) SoundLayerEditor.super.deactivate(self) if not params or not params.simulation then managers.editor:set_wanted_mute(true) end end
--Color Class (table) Color = {R = 0 ,G = 0,B = 0,A = 0 , className = "Color"} --Color Class Metatable Color.mt = {} --Creation by Constructor simulation Color.mt.__call = function(caller,r,g,b,a) R = r or 0 G = g or 0 B = b or 0 A = a or 0 p = {} setmetatable(p,Color) Color.__index = Color p.R = r p.G = g p.B = b p.A = a p.className = "Color" return p end setmetatable(Color,Color.mt) --Creation with new function Color:new(r,g,b,a) R = r or 0 G = g or 0 B = b or 0 A = a or 0 p = {} setmetatable(p,self) self.__index = self p.R = r p.G = g p.B = b p.A = a p.className = "Color" return p end --Addition overload (adding two Colors) Color.__add = function(a,b) local pr = Color() pr.R = a.R + b.R pr.G = a.G + b.G pr.B = a.B + b.B pr.A = a.A + b.A return pr end --Substraction overload Color.__sub = function(a,b) local pr = Color() pr.R = a.R - b.R pr.G = a.G - b.G pr.B = a.B - b.B pr.A = a.A - b.A return pr end --Color * color overload Color.__mul = function(a,b) local pr = Color() pr.R = a.R * b.R pr.G = a.G * b.G pr.B = a.B * b.B pr.A = a.A * b.A return pr end --Color / color number overload Color.__div = function(a,b) local pr = Color() pr.R = a.R / b.R pr.G = a.G / b.G pr.B = a.B / b.B pr.A = a.A / b.A return pr end --comparing 2 Colors Color.__eq = function(a,b) if(a.R == b.R and a.G == b.G and a.B == b.B and a.A == b.A) then return true end return false end function Color:Clamp() if(self.R > 1.0) then self.R = 1.0 end if(self.G > 1.0) then self.G = 1.0 end if(self.B > 1.0) then self.B = 1.0 end if(self.A > 1.0) then self.A = 1.0 end if(self.R < 0.0) then self.R = 0.0 end if(self.G < 0.0) then self.G = 0.0 end if(self.B < 0.0) then self.B = 0.0 end if(self.A < 0.0) then self.A = 0.0 end end -- this is used by C++ to create a lua Color function CreateColor() local pt = Color() return pt end
local setmetatable = setmetatable local ipairs = ipairs local error = error local _guardian = function() local guard = { __when = {} } guard.when = function(filter, f) guard.__when[#guard.__when + 1] = { filter = filter, f = f } return guard end guard.any = function(f) guard.__any = f return guard end return setmetatable(guard, { __call = function(guard, ...) for k, g in ipairs(guard.__when) do if g.filter(...) then return g.f(...) end end if guard.__any then return guard.__any(...) end return error("guard: No guard defined for given arguments.", 0) end, }) end return setmetatable({ _DESCRIPTION = "Elixir-style guards for Lua", _VERSION = "guard v0.0.1", _URL = "http://github.com/Yonaba/guard.lua", _LICENSE = "MIT LICENSE <http://www.opensource.org/licenses/mit-license.php>", }, { __call = function() return _guardian() end })
for i, v in pairs(tfm.get.room.playerList) do eventNewPlayer(i) end for i, v in pairs(BOT) do PLAYER[i] = instanceData() PLAYER[i].skinEquiped = v.chair end local temp = roomOwner() addFunctionTimer(function() for i, v in pairs(tfm.get.room.playerList) do if nickHashtag(i) == temp then OWNER = i colorNick(i) return end end if not (tfm.get.room.isTribeHouse or tfm.get.room.name:sub(1,1) == "@") then CONFIG.ranked = true end end, 500) if not temp then tfm.exec.setRoomMaxPlayers(15) else CONFIG.ranked = false end if tfm.get.room.isTribeHouse or tfm.get.room.name:sub(1,1) == "@" then CONFIG.ranked = false CONFIG.tribeHouse = true end if tfm.get.room.name:find("#event$") then CONFIG.eventRoom = true CONFIG.ranked = true end system.disableChatCommandDisplay(nil, true) tfm.exec.disableAutoShaman() --tfm.exec.disablePhysicalConsumables(true) tfm.exec.disableAfkDeath() tfm.exec.disableAutoNewGame() tfm.exec.disableAutoScore() tfm.exec.disableAutoTimeLeft() tfm.exec.disableMinimalistMode() tfm.exec.disableMortCommand() newMap()
-- converted from https://github.com/joaquimserafim/base64-url local Buffer = require('buffer').Buffer local function unescape (str) local len = 4 - #str % 4 local newstr = {} str:gsub("%S+", function(c) table.insert(newstr, c) end) for i = 1, len do table.insert(newstr, "") end newstr = table.concat(newstr, '=') newstr = newstr:gsub("(-)", "+") newstr = newstr:gsub("(_)", "/") return newstr end local function escape (str) str = str:gsub("(%+)", "-") str = str:gsub("(/)", "_") str = str:gsub("(%=)", "") return str end local function encode (str) return escape(Buffer:new(str):toString()) end local function decode (str) return Buffer:new(unescape(str)):toString() end return { unescape = unescape, escape = escape, encode = encode, decode = decode }
--===========================================================================-- -- -- -- Attribute for Validator -- -- -- --===========================================================================-- --===========================================================================-- -- Author : [email protected] -- -- URL : http://github.com/kurapica/PLoop -- -- Create Date : 2018/04/04 -- -- Update Date : 2020/06/13 -- -- Version : 1.3.4 -- --===========================================================================-- PLoop(function(_ENV) namespace "System.Web" import "System.Configuration" --- the login & authority validator __Sealed__() __NoNilValue__(false) class "__Login__" (function(_ENV) extend "IInitAttribute" export { unpack = unpack, UrlEncode = UrlEncode, HttpMethod_GET = HttpMethod.GET, IsObjectType = Class.IsObjectType, AttributeTargets, __Login__, Application } local function redirect(context, path, settings) local request = context.Request if request:IsHtmlAccepted() then if not path then if request.HttpMethod == HttpMethod_GET then path = (settings and settings.LoginPage or __Login__.DefaultLoginPage) .. "?" .. (settings and settings.PathKey or __Login__.DefaultPathKey) .. "=" .. UrlEncode(request.RawUrl) else path = settings and settings.LoginPage or __Login__.DefaultLoginPage end end return context.Response:Redirect(path) else context.Response.StatusCode = HTTP_STATUS.DENIED end end ----------------------------------------------------------- -- method -- ----------------------------------------------------------- function InitDefinition(self, target, targettype, definition, owner, name, stack) local authority = self[1] if targettype == AttributeTargets.Function then if authority then return function(context, ...) local settings = context.Application[__Login__] local result, path if (settings and settings.LoginChecker or __Login__.DefaultLoginChecker)(context) then result, path = (settings and settings.AuthorityChecker or __Login__.DefaultAuthorityChecker)(context, unpack(authority)) if result then return definition(context, ...) end end return redirect(context, path, settings) end else return function(context, ...) local settings = context.Application[__Login__] if (settings and settings.LoginChecker or __Login__.DefaultLoginChecker)(context) then return definition(context, ...) end return redirect(context, nil, settings) end end else if authority then return function(self, context, ...) local settings = context.Application[__Login__] local result, path if (settings and settings.LoginChecker or __Login__.DefaultLoginChecker)(context) then result, path = (settings and settings.AuthorityChecker or __Login__.DefaultAuthorityChecker)(context, unpack(authority)) if result then return definition(self, context, ...) end end return redirect(context, path, settings) end else return function(self, context, ...) local settings = context.Application[__Login__] if (settings and settings.LoginChecker or __Login__.DefaultLoginChecker)(context) then return definition(self, context, ...) end return redirect(context, nil, settings) end end end end ----------------------------------------------------------- -- static property -- ----------------------------------------------------------- --- the default key in the session items for checking __Static__() property "DefaultKey" { type = String, default = "user" } --- the default login checker, so the user can do their own login check logic __Static__() property "DefaultLoginChecker" { type = Function, default = function(context) local settings = context.Application[__Login__] return context.Session.Items[settings and settings.Key or __Login__.DefaultKey] ~= nil end, } --- the default login path __Static__() property "DefaultLoginPage" { type = String } --- the default key to send the request path to the login page __Static__() property "DefaultPathKey" { type = String, default = "path"} --- the default authority checker __Static__() property "DefaultAuthorityChecker" { type = Function, default = function() return true end } --- the key in the session items for checking __Indexer__(Application) __Static__() property "Key" { type = String, set = function(self, app, value) app = app._Application local settings = app[__Login__] or {} settings.Key = value app[__Login__] = settings end, } --- the login checker __Indexer__(Application) __Static__() property "LoginChecker" { type = Function, set = function(self, app, value) app = app._Application local settings = app[__Login__] or {} settings.LoginChecker = value app[__Login__] = settings end, } --- the login path __Indexer__(Application) __Static__() property "LoginPage" { type = String, set = function(self, app, value) app = app._Application local settings = app[__Login__] or {} settings.LoginPage = value app[__Login__] = settings end, } --- the key to send the request path to the login page __Indexer__(Application) __Static__() property "PathKey" { type = String, set = function(self, app, value) app = app._Application local settings = app[__Login__] or {} settings.PathKey = value app[__Login__] = settings end, } --- the authority checker __Indexer__(Application) __Static__() property "AuthorityChecker" { type = Function, set = function(self, app, value) app = app._Application local settings = app[__Login__] or {} settings.AuthorityChecker = value app[__Login__] = settings end, } ----------------------------------------------------------- -- property -- ----------------------------------------------------------- --- the attribute target property "AttributeTarget" { set = false, default = AttributeTargets.Function + AttributeTargets.Method } --- the attribute priority property "Priority" { set = false, default = AttributePriority.Lower } -- the attribute priority sub level property "SubLevel" { set = false, default = - 2000 } ----------------------------------------------------------- -- constructor -- ----------------------------------------------------------- function __new(_, val, ...) if val then return { { val, ... } }, true else return {}, true end end end) --- the form validator __Sealed__() class "__Form__" (function(_ENV) extend "IInitAttribute" export { Serialize = Serialization.Serialize, Deserialize = Serialization.Deserialize, GetStructCategory = Struct.GetStructCategory, GetMembers = Struct.GetMembers, GetArrayElement = Struct.GetArrayElement, GetDictionaryKey = Struct.GetDictionaryKey, GetDictionaryValue = Struct.GetDictionaryValue, IsSubStruct = Struct.IsSubType, IsStruct = Struct.Validate, IsEnum = Enum.Validate, GetEnumValues = Enum.GetEnumValues, ValidateStructValue = Struct.ValidateValue, ValidateEnumValue = Enum.ValidateValue, strmatch = string.match, select = select, tonumber = tonumber, pairs = pairs, type = type, pcall = pcall, strgsub = string.gsub, strtrim = function (s) return s and strgsub(s, "^%s*(.-)%s*$", "%1") or "" end, MEMBER = StructCategory.MEMBER, ARRAY = StructCategory.ARRAY, CUSTOM = StructCategory.CUSTOM, DICTIONARY = StructCategory.DICTIONARY, Debug = Logger.Default[Logger.LogLevel.Debug], HttpMethod_GET = HttpMethod.GET, __Form__, Attribute, AttributeTargets, JsonFormatProvider, Serialization.StringFormatProvider, Number } local function validateNotypeValue(config, value) if type(value) == "string" then value = strtrim(value) end if value == "" then value = nil end if value == nil and config.require then return nil, __Form__.RequireMessage end return value end local function validateEnumValue(config, value) if type(value) == "string" then value = strtrim(value) end if value == "" then value = nil end if value == nil then return nil, config.require and __Form__.RequireMessage or nil else if config.number then local num = tonumber(value) if not num then return value, __Form__.NumberMessage end value = num end local ret, err = ValidateEnumValue(config.type, value) if err then return value, true end return ret end end local function validateCustomValue(config, value) if type(value) == "string" then value = strtrim(value) end if value == "" then value = nil end if value == nil then return nil, config.require and __Form__.RequireMessage or nil else if config.number then local num = tonumber(value) if not num then return value, __Form__.NumberMessage end value = num end local ret, err = ValidateStructValue(config.type, value) if err then return value, err end return ret end end local function validateArrayValue(config, value) if type(value) == "string" then local ok, val = pcall(Deserialize, JsonFormatProvider(), value) if ok then value= val end end if type(value) ~= "table" then if value == nil then return nil, config.require and __Form__.RequireMessage or nil end -- Could be one element local errs local val, err = config.elementconfig:validate(value) value = { val } if err then errs = {} errs[1] = err end return value, errs elseif value[1] == nil then local errs local val, err = config.elementconfig:validate(value) value = { val } if err then errs = {} errs[1] = err end return value, errs else local errs local avalid = config.elementconfig -- The array may have some empty holes for i, v in pairs(value) do if type(i) == "number" then local val, err = avalid:validate(v) value[i]= val if err then errs = errs or {} errs[i] = err end end end return value, errs end end local function validateMemberValue(config, value) if type(value) == "string" then local ok, val = pcall(Deserialize, JsonFormatProvider(), value) if ok then value= val end end if type(value) ~= "table" then return nil, config.require and __Form__.RequireMessage or nil else local errs for name, config in pairs(config.memberconfigs) do local val, err = config:validate(value[name]) value[name] = val if err then errs = errs or {} errs[name] = err end end return value, errs end end local function validateDictValue(config, value) if type(value) == "string" then local ok, val = pcall(Deserialize, JsonFormatProvider(), value) if ok then value= val end end if type(value) ~= "table" then if value == nil then return nil, config.require and __Form__.RequireMessage or nil else return value, __Form__.TabelMessage end else local errs local kvalid = config.keyconfig local vvalid = config.valconfig for k, v in pairs(value) do local _, err= kvalid:validate(k) if err then errs = errs or {} errs[k] = err else local val, err = vvalid:validate(v) if err then errs = errs or {} errs[k] = err else value[k]= val end end end return value, errs end end local function parseType(vtype, require, stack) if vtype then if IsEnum(vtype) then for k, v in GetEnumValues(vtype) do -- simple check, normally should be number return { type = vtype, validate = validateEnumValue, number = type(v) == "number", require = require } end elseif IsStruct(vtype) then local category = GetStructCategory(vtype) if category == CUSTOM then return { type = vtype, validate = validateCustomValue, number = IsSubStruct(vtype, Number), require = require } elseif category == ARRAY then return { elementconfig = parseType(GetArrayElement(vtype), nil, stack + 1), validate = validateArrayValue, require = require } elseif category == MEMBER then local memconfigs = {} for _, mem in GetMembers(vtype) do memconfigs[mem:GetName()] = parseType(mem:GetType(), mem:IsRequire(), stack + 1) end return { memberconfigs = memconfigs, validate = validateMemberValue, require = require } elseif category == DICTIONARY then return { keyconfig = parseType(GetDictionaryKey(vtype), nil, stack + 1), valconfig = parseType(GetDictionaryValue(vtype), nil, stack + 1), validate = validateDictValue, require = require } end end end return { validate = validateNotypeValue, require = require } end local function validateForm(query, config) local form = {} local errors -- Init for key, val in pairs(query) do if type(val) == "string" then val = val:gsub("^%s*(.-)%s*$", "%1") if val == "" then val = nil end end if val ~= nil then local prev local ct = form for p in key:gmatch("%P+") do p = tonumber(p) or p if prev then ct[prev]= type(ct[prev]) == "table" and ct[prev] or {} ct = ct[prev] prev = p else prev = p end end if prev then ct[prev] = val end end end -- validate return config:validate(form) end ----------------------------------------------------------- -- method -- ----------------------------------------------------------- function InitDefinition(self, target, targettype, definition, owner, name, stack) if self[1] and GetStructCategory(self[1]) ~= MEMBER then error("The form validation type isn't valid", stack + 1) end local config = parseType(self[1], nil, stack + 1) if targettype == AttributeTargets.Function then return function(context) local request = context.Request return definition(context, validateForm(request.HttpMethod == HttpMethod_GET and request.QueryString or request.Form, config)) end else return function(self, context) local request = context.Request return definition(self, context, validateForm(request.HttpMethod == HttpMethod_GET and request.QueryString or request.Form, config)) end end end ----------------------------------------------------------- -- static property -- ----------------------------------------------------------- --- the message for require items __Static__() property "RequireMessage" { type = String, default = "the %s can't be nil" } --- the message for number errors __Static__() property "NumberMessage" { type = String, default = "the %s must be number" } --- The message for table errors __Static__() property "TableMessage" { type = String, default = "the %s must be a table" } ----------------------------------------------------------- -- property -- ----------------------------------------------------------- --- the attribute target property "AttributeTarget" { set = false, default = AttributeTargets.Function + AttributeTargets.Method } --- the attribute priority property "Priority" { set = false, default = AttributePriority.Lower } --- the attribute priority sub level property "SubLevel" { set = false, default = - 1000 } ----------------------------------------------------------- -- constructor -- ----------------------------------------------------------- __Arguments__{ StructType } function __new(_, type) return { type }, true end __Arguments__{ RawTable } function __new(_, type) Attribute.IndependentCall(function() type = struct(type) end) return { type }, true end __Arguments__{} function __new(_) return {}, true end end) -- the inner request validator __Sealed__() class "__InnerRequest__" (function(_ENV) extend "IInitAttribute" export { NOT_FOUND = HTTP_STATUS.NOT_FOUND, AttributeTargets } ----------------------------------------------------------- -- method -- ----------------------------------------------------------- function InitDefinition(self, target, targettype, definition, owner, name, stack) if targettype == AttributeTargets.Function then return function(context, ...) if not context.IsInnerRequest then context.Response.StatusCode = NOT_FOUND return end return definition(context, ...) end else return function(self, context, ...) if not context.IsInnerRequest then context.Response.StatusCode = NOT_FOUND return end return definition(self, context, ...) end end end ----------------------------------------------------------- -- property -- ----------------------------------------------------------- --- the attribute target property "AttributeTarget" { set = false, default = AttributeTargets.Function + AttributeTargets.Method } --- the attribute priority property "Priority" { set = false, default = AttributePriority.Lower } -- the attribute priority sub level property "SubLevel" { set = false, default = - 3000 } end) ----------------------------------------------------------------------- -- config section -- ----------------------------------------------------------------------- export { __Login__, "pairs" } local configMap = { Key = String, LoginChecker = Function, LoginPage = String, PathKey = String, AuthorityChecker = Function, } __ConfigSection__(Web.ConfigSection.Validator.Login, configMap) function applyWebConfig(config) for k, v in pairs(config) do if configMap[k] then __Login__["Default"..k] = v end end end __ConfigSection__(Application.ConfigSection.Validator.Login, configMap) function applyAppConfig(config, app) for k, v in pairs(config) do if configMap[k] then __Login__[k][app] = v end end end end)
local _0_0 = nil do local name_0_ = "conjure.fs" local loaded_0_ = package.loaded[name_0_] local module_0_ = nil if ("table" == type(loaded_0_)) then module_0_ = loaded_0_ else module_0_ = {} end module_0_["aniseed/module"] = name_0_ module_0_["aniseed/locals"] = (module_0_["aniseed/locals"] or {}) module_0_["aniseed/local-fns"] = (module_0_["aniseed/local-fns"] or {}) package.loaded[name_0_] = module_0_ _0_0 = module_0_ end local function _2_(...) local ok_3f_0_, val_0_ = nil, nil local function _2_() return {require("conjure.aniseed.core"), require("conjure.config"), require("conjure.aniseed.nvim"), require("conjure.aniseed.string")} end ok_3f_0_, val_0_ = pcall(_2_) if ok_3f_0_ then _0_0["aniseed/local-fns"] = {require = {a = "conjure.aniseed.core", config = "conjure.config", nvim = "conjure.aniseed.nvim", str = "conjure.aniseed.string"}} return val_0_ else return print(val_0_) end end local _1_ = _2_(...) local a = _1_[1] local config = _1_[2] local nvim = _1_[3] local str = _1_[4] local _2amodule_2a = _0_0 local _2amodule_name_2a = "conjure.fs" do local _ = ({nil, _0_0, {{}, nil, nil, nil}})[2] end local env = nil do local v_0_ = nil local function env0(k) local v = nvim.fn.getenv(k) if (a["string?"](v) and not a["empty?"](v)) then return v end end v_0_ = env0 _0_0["aniseed/locals"]["env"] = v_0_ env = v_0_ end local config_dir = nil do local v_0_ = nil do local v_0_0 = nil local function config_dir0() return ((env("XDG_CONFIG_HOME") or (env("HOME") .. "/.config")) .. "/conjure") end v_0_0 = config_dir0 _0_0["config-dir"] = v_0_0 v_0_ = v_0_0 end _0_0["aniseed/locals"]["config-dir"] = v_0_ config_dir = v_0_ end local findfile = nil do local v_0_ = nil do local v_0_0 = nil local function findfile0(name, path) local res = nvim.fn.findfile(name, path) if not a["empty?"](res) then return res end end v_0_0 = findfile0 _0_0["findfile"] = v_0_0 v_0_ = v_0_0 end _0_0["aniseed/locals"]["findfile"] = v_0_ findfile = v_0_ end local resolve_above = nil do local v_0_ = nil do local v_0_0 = nil local function resolve_above0(name) return (findfile(name, ".;") or findfile(name, (nvim.fn.getcwd() .. ";")) or findfile(name, (config_dir() .. ";"))) end v_0_0 = resolve_above0 _0_0["resolve-above"] = v_0_0 v_0_ = v_0_0 end _0_0["aniseed/locals"]["resolve-above"] = v_0_ resolve_above = v_0_ end local file_readable_3f = nil do local v_0_ = nil do local v_0_0 = nil local function file_readable_3f0(path) return (1 == nvim.fn.filereadable(path)) end v_0_0 = file_readable_3f0 _0_0["file-readable?"] = v_0_0 v_0_ = v_0_0 end _0_0["aniseed/locals"]["file-readable?"] = v_0_ file_readable_3f = v_0_ end local split_path = nil do local v_0_ = nil do local v_0_0 = nil local function split_path0(path) local function _3_(_241) return not a["empty?"](_241) end return a.filter(_3_, str.split(path, "/")) end v_0_0 = split_path0 _0_0["split-path"] = v_0_0 v_0_ = v_0_0 end _0_0["aniseed/locals"]["split-path"] = v_0_ split_path = v_0_ end local join_path = nil do local v_0_ = nil do local v_0_0 = nil local function join_path0(parts) return str.join("/", a.concat(parts)) end v_0_0 = join_path0 _0_0["join-path"] = v_0_0 v_0_ = v_0_0 end _0_0["aniseed/locals"]["join-path"] = v_0_ join_path = v_0_ end local resolve_relative_to = nil do local v_0_ = nil do local v_0_0 = nil local function resolve_relative_to0(path, root) local function loop(parts) if a["empty?"](parts) then return path else if file_readable_3f(join_path(a.concat({root}, parts))) then return join_path(parts) else return loop(a.rest(parts)) end end end return loop(split_path(path)) end v_0_0 = resolve_relative_to0 _0_0["resolve-relative-to"] = v_0_0 v_0_ = v_0_0 end _0_0["aniseed/locals"]["resolve-relative-to"] = v_0_ resolve_relative_to = v_0_ end local resolve_relative = nil do local v_0_ = nil do local v_0_0 = nil local function resolve_relative0(path) local relative_file_root = config["get-in"]({"relative_file_root"}) if relative_file_root then return resolve_relative_to(path, relative_file_root) else return path end end v_0_0 = resolve_relative0 _0_0["resolve-relative"] = v_0_0 v_0_ = v_0_0 end _0_0["aniseed/locals"]["resolve-relative"] = v_0_ resolve_relative = v_0_ end return nil
local sha2 = require('opus.crypto.sha2') local Krist = { } local function sha256(key) return sha2.digest(key):toHex() end local function makeaddressbyte(byte) byte = 48 + math.floor(byte / 7) return string.char(byte + 39 > 122 and 101 or byte > 57 and byte + 39 or byte) end function Krist.makev2address(key) local protein = {} local stick = sha256(sha256(key)) local n = 0 local v2 = "k" repeat if n < 9 then protein[n] = string.sub(stick,0,2) stick = sha256(sha256(stick)) end n = n + 1 until n == 9 n = 0 repeat local link = tonumber(string.sub(stick,1+(2*n),2+(2*n)),16) % 9 if string.len(protein[link]) ~= 0 then v2 = v2 .. makeaddressbyte(tonumber(protein[link],16)) protein[link] = '' n = n + 1 else stick = sha256(stick) end until n == 9 return v2 end function Krist.toKristWalletFormat(passphrase) return sha256('KRISTWALLET' .. passphrase) .. '-000' end return Krist
--[[------------------------------------------------------------------------- This file handles most of the server side atm stuff, such as setting and getting bank values Creating and destroying group accounts. ---------------------------------------------------------------------------]] include("batm_config.lua") AddCSLuaFile("batm_translation.lua") include("batm_translation.lua") util.AddNetworkString("blueatm") BATM = BATM or {} local Accounts = CBLib.LoadModule("batm/bm_accounts.lua", false) --Lets try connect to the sql database local connected, failedReason = Accounts.SQL.Initialize() if connected == false then MsgC(Color(255,100,100), "--------------------------------------BLUEATM ERROR--------------------------------------\n") print("BLUE ATM : Failed to connect to the sql database, a reason should be below. If you cannot fix this then please open a support ticket!") print("BlueATM will not function correctly without resolving this error.\n"..failedReason) error("SQL_CONNECT_ERROR") end --Try to load there account, if not create one. (Test) hook.Add("PlayerInitialSpawn" , "TestLoad", function(ply) --What we will do, is when the player spawns we will check which groups there part of --Then we will confirm each group still has that user as a memeber so you can kick offline memeber of the group Accounts.GetCachedPersonalAccount(ply:SteamID64(), function(account, didExist) if didExist then timer.Simple(0.1, function() --Due to bug we have to network it the next frame BATM.NetworkAccount(ply, account) --We network this instantly so that the user can see what groups there part of in the account selections creen end) end end) local timerName = "batm_interest_"..ply:SteamID64() timer.Create("batm_interest_"..ply:SteamID64(), 60 * BATM.Config.InterestInterval, 0, function() if BATM.Config.InterestRate <= 0 then return end if not ply:IsValid() then timer.Destroy(timerName) return end --Get there account, if it exists then add the interest to it. Accounts.SQL.LoadPersonalAccount(ply:SteamID64(), function(account) if account ~= false then --yay --Add the interested Accounts.GetCachedPersonalAccount(ply:SteamID64(), function(account, didExist) local interestAmount = math.floor((account:GetBalance() / 100.0) * BATM.Config.InterestRate) interestAmount = math.Clamp(interestAmount, 0, BATM.MaxInterest or interestAmount) if interestAmount > 0 then account:AddBalance(interestAmount, BATM.Config.InterestRate..BATM.Lang["% Interest"]) account:SaveAccount() BATM.NetworkAccount(ply, account, false) ply:ChatPrint(BATM.Lang["[ATM] You just got "]..BATM.Config.InterestRate..BATM.Lang["% interest! You will next get interest in 15 minutes!"]) end end) end end) end) end) --Check is a number is "valid" function BATM.VerifyNumber(number) return number ~= nil and number > 0 end --Networks an accoun to a single user function BATM.NetworkAccount(user, account, shouldUpdateSelectedAccount) if shouldUpdateSelectedAccount == nil then shouldUpdateSelectedAccount = true end net.Start("blueatm") net.WriteUInt(BATM_NET_COMMANDS.receiveAccountInfo, 8) net.WriteTable(account) net.WriteBool(shouldUpdateSelectedAccount) net.Send(user) end --Networks a group account to all online players from that group function BATM.NetworkGroupAccount(account) local owners = account.owners --Check members for k ,v in pairs(owners) do local ply = player.GetBySteamID64(v) if ply ~= false then BATM.NetworkAccount(ply, account) end end --Check owner local ply = player.GetBySteamID64(account.ownerID) if ply ~= false then BATM.NetworkAccount(ply, account) end end --[[------------------------------------------------------------------------- Handle net messages ---------------------------------------------------------------------------]] local networkEvents = {} local function addNetworkEvent(typeID, func) networkEvents[typeID] = func end net.Receive("blueatm", function(len, ply) if ply.batmcooldown == nil then ply.batmcooldown = CurTime() else if CurTime() - ply.batmcooldown < 0.1 then return else ply.batmcooldown = CurTime() end end local type = net.ReadUInt(8) local ent = net.ReadEntity() --Prevent false calls if type == 0 then return end if networkEvents[type] == nil then return end if not IsValid(ent) or ent:GetClass() ~= "atm_wall" then return end networkEvents[type](ent, ply) end) --[[------------------------------------------------------------------------- Networking logic ---------------------------------------------------------------------------]] --Load an account addNetworkEvent(BATM_NET_COMMANDS.selectAccount, function(ent, ply) local type = net.ReadString() if type == nil then return end --Get that players personal account if type == "personal" then Accounts.GetCachedPersonalAccount(ply:SteamID64(), function(account) BATM.NetworkAccount(ply, account) ent:SetScene("personalaccount", ply) ply.batmloadedaccountid = -1 -- end) elseif type == "personalgroup" then --Personal group is the group account that is created by the player Accounts.GetCachedGroupAccount(ply:SteamID64(), true, function(account) account.ownerName = ply:Name() BATM.NetworkAccount(ply, account) account:SaveAccount() ent:SetScene("groupaccount", ply) ply.batmloadedaccountid = ply:SteamID64() end) elseif type == "group" then --This is a group account created by someone else local groupID = net.ReadString() Accounts.GetCachedGroupAccount(groupID, false, function(account) if account == false then ent:SetScene("failed", ply) timer.Simple(2, function() ent:SetScene("accountselection", ply) end) ply:ChatPrint(BATM.Lang["[ATM] Incorrect data..."]) return end if not table.HasValue(account.owners, ply:SteamID64()) then ent:SetScene("failed", ply) timer.Simple(2, function() ent:SetScene("accountselection", ply) end) ply:ChatPrint(BATM.Lang["[ATM] You are not a member of this group..."]) return end --So there a member, lets network it BATM.NetworkAccount(ply, account) ent:SetScene("groupaccount", ply) ply.batmloadedaccountid = groupID end) end end) --Deposite into an account addNetworkEvent(BATM_NET_COMMANDS.deposit, function(ent, ply) local accountType = net.ReadString() local amount = math.floor(net.ReadDouble()) if not BATM.VerifyNumber(amount) then ent:SetScene("failed", ply) timer.Simple(2, function() ent:SetScene("accountselection", ply) end) ply:ChatPrint(BATM.Lang["[ATM] Incorrect data..."]) return end --Check if they can afford it if not BATM.Config.CanAfford(ply, amount) then ent:SetScene("failed", ply) ply:ChatPrint(BATM.Lang["[ATM] You don't have that much money!"]) return end if accountType == "personal" then --If they can afford it then deposite it Accounts.GetCachedPersonalAccount(ply:SteamID64(), function(account) account:AddBalance(amount, BATM.Lang["Deposit from account owner"]) if not BATM.Config.CanAfford(ply, amount) then ent:SetScene("failed", ply) ply:ChatPrint(BATM.Lang["[ATM] You don't have that much money!"]) return end BATM.Config.TakeMoney(ply, amount) account:SaveAccount() BATM.NetworkAccount(ply, account) ent:SetScene("done", ply) end) else local groupID = ply.batmloadedaccountid --Try to load the account Accounts.GetCachedGroupAccount(groupID, false, function(account, valid) if account == false then ent:SetScene("failed", ply) timer.Simple(2, function() ent:SetScene("accountselection", ply) end) ply:ChatPrint(BATM.Lang["[ATM] You don't have permission to do this..."]) return end --Check if they have perms if account.ownerID == ply:SteamID64() or table.HasValue(account.owners, ply:SteamID64()) then if not BATM.Config.CanAfford(ply, amount) then ent:SetScene("failed", ply) ply:ChatPrint(BATM.Lang["[ATM] You don't have that much money!"]) return end BATM.Config.TakeMoney(ply, amount) account:AddBalance(amount, "Deposit from "..ply:Name()) account:SaveAccount() BATM.NetworkGroupAccount(account) ent:SetScene("done", ply) else ent:SetScene("failed", ply) timer.Simple(2, function() ent:SetScene("accountselection", ply) end) ply:ChatPrint(BATM.Lang["[ATM] You don't have permission to do this..."]) return end end) end end) --Deposite into an account addNetworkEvent(BATM_NET_COMMANDS.withdraw, function(ent, ply) local accountType = net.ReadString() local amount = math.floor(net.ReadDouble()) if not BATM.VerifyNumber(amount) then ent:SetScene("failed", ply) timer.Simple(2, function() ent:SetScene("accountselection", ply) end) ply:ChatPrint(BATM.Lang["[ATM] Incorrect data..."]) return end if accountType == "personal" then --First get there account Accounts.GetCachedPersonalAccount(ply:SteamID64(), function(account) --Check if they have enough if account.balance - amount >= 0 then account:AddBalance(-amount, "Withdrawal from account owner.") BATM.Config.AddMoney(ply, amount) account:SaveAccount() BATM.NetworkAccount(ply, account) ent:SetScene("done_withdraw", ply) else ent:SetScene("failed", ply) ply:ChatPrint(BATM.Lang["[ATM] You don't have that much money!"]) end end) else local groupID = ply.batmloadedaccountid --Try to load the account Accounts.GetCachedGroupAccount(groupID, false, function(account, valid) if account == false then ent:SetScene("failed", ply) timer.Simple(2, function() ent:SetScene("accountselection", ply) end) ply:ChatPrint(BATM.Lang["[ATM] You don't have permission to do this..."]) return end --Check if they have perms if account.ownerID == ply:SteamID64() or table.HasValue(account.owners, ply:SteamID64()) then if account:GetBalance() - amount >= 0 then account:AddBalance(-amount, "Withdrawal from "..ply:Name()) BATM.Config.AddMoney(ply, amount) account:SaveAccount() BATM.NetworkGroupAccount(account) ent:SetScene("done", ply) else ent:SetScene("failed", ply) ply:ChatPrint(BATM.Lang["[ATM] You don't have that much money!"]) return end else ent:SetScene("failed", ply) timer.Simple(2, function() ent:SetScene("accountselection", ply) end) ply:ChatPrint(BATM.Lang["[ATM] You don't have permission to do this..."]) return end end) end end) --Handles transfering funds from one player to anouther addNetworkEvent(BATM_NET_COMMANDS.transfer, function(ent, ply) if ply.batmtransfercooldown == nil then ply.batmtransfercooldown = 0 end local amount = math.floor(net.ReadDouble()) local target = net.ReadString() --Force a cooldown so they cannot spam queries if ply.batmtransfercooldown > CurTime() then ent:SetScene("failed", ply) ply:ChatPrint(BATM.Lang["[ATM] You're sending to many requests! Please wait..."]) return end if BATM.VerifyNumber(amount) then --First get there account Accounts.GetCachedPersonalAccount(ply:SteamID64(), function(account) if account:GetBalance() - amount >= 0 then Accounts.GetCachedPersonalAccount(target, function(targetAccount, didExist) if not IsValid(ply) then return end --Dont do anything as that player has left now if didExist and account:GetBalance() - amount >= 0 then --Take money account:AddBalance(-amount, "Transfer to '"..target.."'") account:SaveAccount() --Add money targetAccount:AddBalance(amount, "Transfer from '"..ply:SteamID64().."'") targetAccount:SaveAccount() --Update display BATM.NetworkAccount(ply, account) ent:SetScene("done_transfer", ply) ply.batmtransfercooldown = CurTime() + 1.5 --If the player is online who he transfered to, then go ahead and network it to them too if player.GetBySteamID64(target) ~= false then BATM.NetworkAccount(player.GetBySteamID64(target) , targetAccount) end else ply.batmtransfercooldown = CurTime() + 3 ent:SetScene("failed", ply) ply:ChatPrint(BATM.Lang["[ATM] That person does not have an account set up!"]) end end) else ent:SetScene("failed", ply) ply:ChatPrint(BATM.Lang["[ATM] You don't have that much money!"]) end end) end end) --Load an account addNetworkEvent(BATM_NET_COMMANDS.kickUser, function(ent, ply) local target = net.ReadString() local groupID = ply.batmloadedaccountid Accounts.GetCachedGroupAccount(groupID, false, function(account) --Does the account exist if account == false then ent:SetScene("failed", ply) ply:ChatPrint(BATM.Lang["[ATM] You don't have permission to do this..."]) return end --Now check that there the owner if ply:SteamID64() ~= account.ownerID then ent:SetScene("failed", ply) ply:ChatPrint(BATM.Lang["[ATM] You don't have permission to do this..."]) return end --Now try to remove the user account:RemoveOwner(target, function(worked, reason) if worked then account:SaveAccount() ent:SetScene("members", ply) --Network it BATM.NetworkGroupAccount(account) else ent:SetScene("failed", ply) ply:ChatPrint(BATM.Lang["[ATM] "]..reason) return end end) end) end) --Add a member to a group account addNetworkEvent(BATM_NET_COMMANDS.addUser, function(ent, ply) local target = net.ReadString() local groupID = ply.batmloadedaccountid Accounts.GetCachedGroupAccount(groupID, false, function(account) --Does the account exist if account == false then ent:SetScene("failed", ply) timer.Simple(2, function() ent:SetScene("accountselection", ply) end) ply:ChatPrint(BATM.Lang["[ATM] You don't have permission to do this..."]) return end --Now check that there the owner if ply:SteamID64() ~= account.ownerID then ent:SetScene("failed", ply) timer.Simple(2, function() ent:SetScene("accountselection", ply) end) ply:ChatPrint(BATM.Lang["[ATM] You don't have permission to do this..."]) return end local targetply = player.GetBySteamID64(target) if targetply == false then ent:SetScene("failed", ply) timer.Simple(2, function() ent:SetScene("accountselection", ply) end) ply:ChatPrint(BATM.Lang["[ATM] Invalid player..."]) return end --Now try to remove the user account:AddOwner(target, targetply:Name(), function(worked) if worked then account:SaveAccount() ent:SetScene("members", ply) --Network it BATM.NetworkGroupAccount(account) else ent:SetScene("failed", ply) timer.Simple(2, function() ent:SetScene("accountselection", ply) end) ply:ChatPrint(BATM.Lang["[ATM] Oh no! Something went wrong, please try again!"]) return end end) end) end) local function SaveAtms() local data = {} for k ,v in pairs(ents.FindByClass("atm_wall")) do table.insert(data, {pos = v:GetPos(), ang = v:GetAngles()}) end if not file.Exists("batm" , "DATA") then file.CreateDir("batm") end file.Write("batm/"..game.GetMap()..".txt", util.TableToJSON(data)) end local function LoadAtms() if file.Exists("batm/"..game.GetMap()..".txt" , "DATA") then local data = file.Read("batm/"..game.GetMap()..".txt", "DATA") data = util.JSONToTable(data) for k, v in pairs(data) do local slot = ents.Create("atm_wall") slot:SetPos(v.pos) slot:SetAngles(v.ang) slot:Spawn() slot:GetPhysicsObject():EnableMotion(false) end print("[BATM] Finished loading Blue ATM entities.") else print("[BATM] No map data found for Blue's ATM entities. Please place some and do !saveatms to create the data.") end end hook.Add("InitPostEntity", "spawn:batms", function() LoadAtms() end) --Handle saving and loading of slots hook.Add("PlayerSay", "handlebatmcommands" , function(ply, text) if string.sub(string.lower(text), 1, 10) == "!saveatms" then if table.HasValue(BATM.Config.AuthorisedRanks, ply:GetUserGroup()) then SaveAtms() ply:ChatPrint(BATM.Lang["[ATM] Blue's atms have been saved for the map "]..game.GetMap().."!") else ply:ChatPrint(BATM.Lang["[ATM] You do not have permission to perform this action, please contact an admin."]) end end end)
--[[ author:{JanRoid} time:2019-4-26 Description: 保存本地数据 ]] local DataKey = { -- clientSocket CS_USER = "clent_server_user" } return DataKey
pausebutton = class:new() function pausebutton:init(x, y, text, func) self.x = x-1 self.y = y self.text = text self.func = func self.value = 0 self.textwidth = levelselectfont:getWidth(self.text) self.active = false self.height = 23 self.width = 218 end function pausebutton:changetext(t) self.text = t self.textwidth = levelselectfont:getWidth(self.text) end function pausebutton:update(dt) local x, y = mymousegetPosition() y = y x = x if self:gethighlight(x, y) then self.value = self.value + ((1-self.value)*10*dt+0.01*dt) if self.value > 1 then self.value = 1 end else self.value = self.value - (self.value*4*dt+0.1*dt) if self.value < 0 then self.value = 0 end end end function pausebutton:draw() local r, g, b = 190, 206, 248 local tr, tg, tb = unpack(getrainbowcolor(math.mod(rainbowi+.5+self.value*0.5, 1))) r = r + (tr-r)*(self.value*.7+.3) g = g + (tg-g)*(self.value*.7+.3) b = b + (tb-b)*(self.value*.7+.3) local scissorx, scissory, scissorwidth, scissorheight = mygraphicsgetScissor( ) love.graphics.setFont(levelselectfont) mygraphicssetScissor(self.x-self.width/2+self.width/2*self.value, scissory or self.y, round(self.width-self.width*self.value), scissorheight or self.height) love.graphics.setColor(r, g, b, 100*fadecolor) love.graphics.rectangle("fill", self.x-self.width/2, self.y, self.width, self.height) love.graphics.setColor(0, 0, 0, 255*fadecolor) if self.text then love.graphics.print(self.text, self.x - self.textwidth/2+1, self.y-7) end mygraphicssetScissor() love.graphics.setColor(r, g, b, 255*fadecolor) mygraphicssetScissor(round(self.x-self.width/2), scissory or self.y, round(self.width/2*self.value), scissorheight or self.height) if self.text then love.graphics.print(self.text, round(self.x - self.textwidth/2+1), self.y-7) end mygraphicssetScissor(round(self.x+self.width/2-(self.width/2*self.value)), scissory or self.y, round(self.width/2), scissorheight or self.height) if self.text then love.graphics.print(self.text, round(self.x - self.textwidth/2+1), self.y-7) end if scissorx then mygraphicssetScissor(scissorx, scissory, scissorwidth, scissorheight) else mygraphicssetScissor() end end function pausebutton:mousepressed(x, y, button) if self.active then if button == lbutton then if self:gethighlight(x, y) then self:func() end end end end function pausebutton:gethighlight(x, y) if x >= self.x-self.width/2-1 and x < self.x+self.width/2+2 and y >= self.y-1 and y < self.y+self.height+2 then return true end return false end
--[[ Simplistic base panel that has basic colors, fields and methods commonly used throughout Flux Framework. Do not use it directly, base your own panels off of it instead. --]] local PANEL = {} PANEL.draw_background = true PANEL.background_color = Color(0, 0, 0) PANEL.text_color = Color(255, 255, 255) PANEL.main_color = Color(255, 100, 100) PANEL.accent_color = Color(200, 200, 200) PANEL.title = 'Flux Base Panel' PANEL.font = Theme.get_font('menu_titles') or 'flRoboto' AccessorFunc(PANEL, 'draw_background', 'DrawBackground') AccessorFunc(PANEL, 'background_color', 'BackgroundColor') AccessorFunc(PANEL, 'text_color', 'TextColor') AccessorFunc(PANEL, 'main_color', 'MainColor') AccessorFunc(PANEL, 'accent_color', 'AccentColor') AccessorFunc(PANEL, 'title', 'Title') AccessorFunc(PANEL, 'font', 'Font') function PANEL:Paint(width, height) Theme.hook('PaintPanel', self, width, height) end function PANEL:Think() Theme.hook('PanelThink', self) end -- MVC Functionality for all FL panels. function PANEL:push(name, ...) MVC.push(name, ...) end function PANEL:pull(name, handler, prevent_remove) MVC.pull(name, handler, prevent_remove) end function PANEL:request(name, handler, ...) self:pull(name, handler) self:push(name, ...) end PANEL.set_title = PANEL.SetTitle vgui.Register('fl_base_panel', PANEL, 'EditablePanel')
local funny_text_combo = ui.new_combobox("MISC", "Miscellaneous", "Funny Text", "-", "autism", "monospace", "bold", "bold italic") client.set_event_callback("string_cmd", function(e) local text = e.text local cmd, msg = text:match("^(.-) (.*)$") if ((cmd == "say" or cmd == "say_team") and msg ~= nil and msg ~= "") then local new_msg = {} for funny_text in msg:gmatch("[^%s]+") do if (ui.get(funny_text_combo) == "autism") then funny_text = funny_text:gsub("a", "𝕒") funny_text = funny_text:gsub("b", "𝕓") funny_text = funny_text:gsub("c", "𝕔") funny_text = funny_text:gsub("d", "𝕕") funny_text = funny_text:gsub("e", "𝕖") funny_text = funny_text:gsub("f", "𝕗") funny_text = funny_text:gsub("g", "𝕘") funny_text = funny_text:gsub("h", "𝕙") funny_text = funny_text:gsub("i", "𝕚") funny_text = funny_text:gsub("j", "𝕛") funny_text = funny_text:gsub("k", "𝕜") funny_text = funny_text:gsub("l", "𝕝") funny_text = funny_text:gsub("m", "𝕞") funny_text = funny_text:gsub("n", "𝕟") funny_text = funny_text:gsub("o", "𝕠") funny_text = funny_text:gsub("p", "𝕡") funny_text = funny_text:gsub("q", "𝕢") funny_text = funny_text:gsub("r", "𝕣") funny_text = funny_text:gsub("s", "𝕤") funny_text = funny_text:gsub("t", "𝕥") funny_text = funny_text:gsub("u", "𝕦") funny_text = funny_text:gsub("v", "𝕧") funny_text = funny_text:gsub("w", "𝕨") funny_text = funny_text:gsub("x", "𝕩") funny_text = funny_text:gsub("y", "𝕪") funny_text = funny_text:gsub("z", "𝕫") funny_text = funny_text:gsub("A", "𝔸") funny_text = funny_text:gsub("B", "𝔹") funny_text = funny_text:gsub("C", "ℂ") funny_text = funny_text:gsub("D", "𝔻") funny_text = funny_text:gsub("E", "𝔼") funny_text = funny_text:gsub("F", "𝔽") funny_text = funny_text:gsub("G", "𝔾") funny_text = funny_text:gsub("H", "ℍ") funny_text = funny_text:gsub("I", "𝕀") funny_text = funny_text:gsub("J", "𝕁") funny_text = funny_text:gsub("K", "𝕂") funny_text = funny_text:gsub("L", "𝕃") funny_text = funny_text:gsub("M", "𝕄") funny_text = funny_text:gsub("N", "ℕ") funny_text = funny_text:gsub("O", "𝕆") funny_text = funny_text:gsub("P", "ℙ") funny_text = funny_text:gsub("Q", "ℚ") funny_text = funny_text:gsub("R", "ℝ") funny_text = funny_text:gsub("S", "𝕊") funny_text = funny_text:gsub("T", "𝕋") funny_text = funny_text:gsub("U", "𝕌") funny_text = funny_text:gsub("V", "𝕍") funny_text = funny_text:gsub("W", "𝕎") funny_text = funny_text:gsub("X", "𝕏") funny_text = funny_text:gsub("Y", "𝕐") funny_text = funny_text:gsub("Z", "ℤ") funny_text = funny_text:gsub("0", "𝟶") funny_text = funny_text:gsub("1", "𝟷") funny_text = funny_text:gsub("2", "𝟸") funny_text = funny_text:gsub("3", "𝟹") funny_text = funny_text:gsub("4", "𝟺") funny_text = funny_text:gsub("5", "𝟻") funny_text = funny_text:gsub("6", "𝟼") funny_text = funny_text:gsub("7", "𝟽") funny_text = funny_text:gsub("8", "𝟾") funny_text = funny_text:gsub("9", "𝟿") elseif ui.get(funny_text_combo) == "monospace" then funny_text = funny_text:gsub("a", "a") funny_text = funny_text:gsub("b", "b") funny_text = funny_text:gsub("c", "c") funny_text = funny_text:gsub("d", "d") funny_text = funny_text:gsub("e", "e") funny_text = funny_text:gsub("f", "f") funny_text = funny_text:gsub("g", "g") funny_text = funny_text:gsub("h", "h") funny_text = funny_text:gsub("i", "i") funny_text = funny_text:gsub("j", "j") funny_text = funny_text:gsub("k", "k") funny_text = funny_text:gsub("l", "l") funny_text = funny_text:gsub("m", "m") funny_text = funny_text:gsub("n", "n") funny_text = funny_text:gsub("o", "o") funny_text = funny_text:gsub("p", "p") funny_text = funny_text:gsub("q", "q") funny_text = funny_text:gsub("r", "r") funny_text = funny_text:gsub("s", "s") funny_text = funny_text:gsub("t", "t") funny_text = funny_text:gsub("u", "u") funny_text = funny_text:gsub("v", "v") funny_text = funny_text:gsub("w", "w") funny_text = funny_text:gsub("x", "x") funny_text = funny_text:gsub("y", "y") funny_text = funny_text:gsub("z", "z") funny_text = funny_text:gsub("A", "A") funny_text = funny_text:gsub("B", "B") funny_text = funny_text:gsub("C", "C") funny_text = funny_text:gsub("D", "D") funny_text = funny_text:gsub("E", "E") funny_text = funny_text:gsub("F", "F") funny_text = funny_text:gsub("G", "G") funny_text = funny_text:gsub("H", "H") funny_text = funny_text:gsub("I", "I") funny_text = funny_text:gsub("J", "J") funny_text = funny_text:gsub("K", "K") funny_text = funny_text:gsub("L", "L") funny_text = funny_text:gsub("M", "M") funny_text = funny_text:gsub("N", "N") funny_text = funny_text:gsub("O", "O") funny_text = funny_text:gsub("P", "P") funny_text = funny_text:gsub("Q", "Q") funny_text = funny_text:gsub("R", "R") funny_text = funny_text:gsub("S", "S") funny_text = funny_text:gsub("T", "T") funny_text = funny_text:gsub("U", "U") funny_text = funny_text:gsub("V", "V") funny_text = funny_text:gsub("W", "W") funny_text = funny_text:gsub("X", "X") funny_text = funny_text:gsub("Y", "Y") funny_text = funny_text:gsub("Z", "Z") funny_text = funny_text:gsub("0", "0") funny_text = funny_text:gsub("1", "1") funny_text = funny_text:gsub("2", "2") funny_text = funny_text:gsub("3", "3") funny_text = funny_text:gsub("4", "4") funny_text = funny_text:gsub("5", "5") funny_text = funny_text:gsub("6", "6") funny_text = funny_text:gsub("7", "7") funny_text = funny_text:gsub("8", "8") funny_text = funny_text:gsub("9", "9") elseif ui.get(funny_text_combo) == "bold" then funny_text = funny_text:gsub("a", "𝗮") funny_text = funny_text:gsub("b", "𝗯") funny_text = funny_text:gsub("c", "𝗰") funny_text = funny_text:gsub("d", "𝗱") funny_text = funny_text:gsub("e", "𝗲") funny_text = funny_text:gsub("f", "𝗳") funny_text = funny_text:gsub("g", "𝗴") funny_text = funny_text:gsub("h", "𝗵") funny_text = funny_text:gsub("i", "𝗶") funny_text = funny_text:gsub("j", "𝗷") funny_text = funny_text:gsub("k", "𝗸") funny_text = funny_text:gsub("l", "𝗹") funny_text = funny_text:gsub("m", "𝗺") funny_text = funny_text:gsub("n", "𝗻") funny_text = funny_text:gsub("o", "𝗼") funny_text = funny_text:gsub("p", "𝗽") funny_text = funny_text:gsub("q", "𝗾") funny_text = funny_text:gsub("r", "𝗿") funny_text = funny_text:gsub("s", "𝘀") funny_text = funny_text:gsub("t", "𝘁") funny_text = funny_text:gsub("u", "𝘂") funny_text = funny_text:gsub("v", "𝘃") funny_text = funny_text:gsub("w", "𝘄") funny_text = funny_text:gsub("x", "𝘅") funny_text = funny_text:gsub("y", "𝘆") funny_text = funny_text:gsub("z", "𝘇") funny_text = funny_text:gsub("A", "𝗔") funny_text = funny_text:gsub("B", "𝗕") funny_text = funny_text:gsub("C", "𝗖") funny_text = funny_text:gsub("D", "𝗗") funny_text = funny_text:gsub("E", "𝗘") funny_text = funny_text:gsub("F", "𝗙") funny_text = funny_text:gsub("G", "𝗚") funny_text = funny_text:gsub("H", "𝗛") funny_text = funny_text:gsub("I", "𝗜") funny_text = funny_text:gsub("J", "𝗝") funny_text = funny_text:gsub("K", "𝗞") funny_text = funny_text:gsub("L", "𝗟") funny_text = funny_text:gsub("M", "𝗠") funny_text = funny_text:gsub("N", "𝗡") funny_text = funny_text:gsub("O", "𝗢") funny_text = funny_text:gsub("P", "𝗣") funny_text = funny_text:gsub("Q", "𝗤") funny_text = funny_text:gsub("R", "𝗥") funny_text = funny_text:gsub("S", "𝗦") funny_text = funny_text:gsub("T", "𝗧") funny_text = funny_text:gsub("U", "𝗨") funny_text = funny_text:gsub("V", "𝗩") funny_text = funny_text:gsub("W", "𝗪") funny_text = funny_text:gsub("X", "𝗫") funny_text = funny_text:gsub("Y", "𝗬") funny_text = funny_text:gsub("Z", "𝗭") funny_text = funny_text:gsub("0", "𝟬") funny_text = funny_text:gsub("1", "𝟭") funny_text = funny_text:gsub("2", "𝟮") funny_text = funny_text:gsub("3", "𝟯") funny_text = funny_text:gsub("4", "𝟰") funny_text = funny_text:gsub("5", "𝟱") funny_text = funny_text:gsub("6", "𝟲") funny_text = funny_text:gsub("7", "𝟳") funny_text = funny_text:gsub("8", "𝟴") funny_text = funny_text:gsub("9", "𝟵") elseif ui.get(funny_text_combo) == "bold italic" then funny_text = funny_text:gsub("a", "𝙖") funny_text = funny_text:gsub("b", "𝙗") funny_text = funny_text:gsub("c", "𝙘") funny_text = funny_text:gsub("d", "𝙙") funny_text = funny_text:gsub("e", "𝙚") funny_text = funny_text:gsub("f", "𝙛") funny_text = funny_text:gsub("g", "𝙜") funny_text = funny_text:gsub("h", "𝙝") funny_text = funny_text:gsub("i", "𝙞") funny_text = funny_text:gsub("j", "𝙟") funny_text = funny_text:gsub("k", "𝙠") funny_text = funny_text:gsub("l", "𝙡") funny_text = funny_text:gsub("m", "𝙢") funny_text = funny_text:gsub("n", "𝙣") funny_text = funny_text:gsub("o", "𝙤") funny_text = funny_text:gsub("p", "𝙥") funny_text = funny_text:gsub("q", "𝙦") funny_text = funny_text:gsub("r", "𝙧") funny_text = funny_text:gsub("s", "𝙨") funny_text = funny_text:gsub("t", "𝙩") funny_text = funny_text:gsub("u", "𝙪") funny_text = funny_text:gsub("v", "𝙫") funny_text = funny_text:gsub("w", "𝙬") funny_text = funny_text:gsub("x", "𝙭") funny_text = funny_text:gsub("y", "𝙮") funny_text = funny_text:gsub("z", "𝙯") funny_text = funny_text:gsub("A", "𝘼") funny_text = funny_text:gsub("B", "𝘽") funny_text = funny_text:gsub("C", "𝘾") funny_text = funny_text:gsub("D", "𝘿") funny_text = funny_text:gsub("E", "𝙀") funny_text = funny_text:gsub("F", "𝙁") funny_text = funny_text:gsub("G", "𝙂") funny_text = funny_text:gsub("H", "𝙃") funny_text = funny_text:gsub("I", "𝙄") funny_text = funny_text:gsub("J", "𝙅") funny_text = funny_text:gsub("K", "𝙆") funny_text = funny_text:gsub("L", "𝙇") funny_text = funny_text:gsub("M", "𝙈") funny_text = funny_text:gsub("N", "𝙉") funny_text = funny_text:gsub("O", "𝙊") funny_text = funny_text:gsub("P", "𝙋") funny_text = funny_text:gsub("Q", "𝙌") funny_text = funny_text:gsub("R", "𝙍") funny_text = funny_text:gsub("S", "𝙎") funny_text = funny_text:gsub("T", "𝙏") funny_text = funny_text:gsub("U", "𝙐") funny_text = funny_text:gsub("V", "𝙑") funny_text = funny_text:gsub("W", "𝙒") funny_text = funny_text:gsub("X", "𝙓") funny_text = funny_text:gsub("Y", "𝙔") funny_text = funny_text:gsub("Z", "𝙕") funny_text = funny_text:gsub("0", "𝟬") funny_text = funny_text:gsub("1", "𝟭") funny_text = funny_text:gsub("2", "𝟮") funny_text = funny_text:gsub("3", "𝟯") funny_text = funny_text:gsub("4", "𝟰") funny_text = funny_text:gsub("5", "𝟱") funny_text = funny_text:gsub("6", "𝟲") funny_text = funny_text:gsub("7", "𝟳") funny_text = funny_text:gsub("8", "𝟴") funny_text = funny_text:gsub("9", "𝟵") --bold italic numbers don't exist for whatever reason -_- end table.insert(new_msg, funny_text) end e.text = cmd .. " " .. table.concat(new_msg, " ") end end)
-- Generated By protoc-gen-lua Do not Edit local protobuf = require "protobuf" module('BceLeaveMessage_pb', package.seeall) local BCELEAVEMESSAGE = protobuf.Descriptor(); local BCELEAVEMESSAGE_UID_FIELD = protobuf.FieldDescriptor(); local BCELEAVEMESSAGE_CONTEXT_FIELD = protobuf.FieldDescriptor(); local BCELEAVEMESSAGE_MESSAGE_FIELD = protobuf.FieldDescriptor(); BCELEAVEMESSAGE_UID_FIELD.name = "uid" BCELEAVEMESSAGE_UID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BceLeaveMessage.uid" BCELEAVEMESSAGE_UID_FIELD.number = 1 BCELEAVEMESSAGE_UID_FIELD.index = 0 BCELEAVEMESSAGE_UID_FIELD.label = 2 BCELEAVEMESSAGE_UID_FIELD.has_default_value = false BCELEAVEMESSAGE_UID_FIELD.default_value = "" BCELEAVEMESSAGE_UID_FIELD.type = 9 BCELEAVEMESSAGE_UID_FIELD.cpp_type = 9 BCELEAVEMESSAGE_CONTEXT_FIELD.name = "context" BCELEAVEMESSAGE_CONTEXT_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BceLeaveMessage.context" BCELEAVEMESSAGE_CONTEXT_FIELD.number = 2 BCELEAVEMESSAGE_CONTEXT_FIELD.index = 1 BCELEAVEMESSAGE_CONTEXT_FIELD.label = 2 BCELEAVEMESSAGE_CONTEXT_FIELD.has_default_value = false BCELEAVEMESSAGE_CONTEXT_FIELD.default_value = "" BCELEAVEMESSAGE_CONTEXT_FIELD.type = 9 BCELEAVEMESSAGE_CONTEXT_FIELD.cpp_type = 9 BCELEAVEMESSAGE_MESSAGE_FIELD.name = "message" BCELEAVEMESSAGE_MESSAGE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BceLeaveMessage.message" BCELEAVEMESSAGE_MESSAGE_FIELD.number = 3 BCELEAVEMESSAGE_MESSAGE_FIELD.index = 2 BCELEAVEMESSAGE_MESSAGE_FIELD.label = 1 BCELEAVEMESSAGE_MESSAGE_FIELD.has_default_value = false BCELEAVEMESSAGE_MESSAGE_FIELD.default_value = nil BCELEAVEMESSAGE_MESSAGE_FIELD.message_type = LEAVEMESSAGE_PB_LEAVEMESSAGE BCELEAVEMESSAGE_MESSAGE_FIELD.type = 11 BCELEAVEMESSAGE_MESSAGE_FIELD.cpp_type = 10 BCELEAVEMESSAGE.name = "BceLeaveMessage" BCELEAVEMESSAGE.full_name = ".com.xinqihd.sns.gameserver.proto.BceLeaveMessage" BCELEAVEMESSAGE.nested_types = {} BCELEAVEMESSAGE.enum_types = {} BCELEAVEMESSAGE.fields = {BCELEAVEMESSAGE_UID_FIELD, BCELEAVEMESSAGE_CONTEXT_FIELD, BCELEAVEMESSAGE_MESSAGE_FIELD} BCELEAVEMESSAGE.is_extendable = false BCELEAVEMESSAGE.extensions = {} BceLeaveMessage = protobuf.Message(BCELEAVEMESSAGE) _G.BCELEAVEMESSAGE_PB_BCELEAVEMESSAGE = BCELEAVEMESSAGE
local settings = require('settings') local ui = require('core.ui') local state = require('pv.state') local defaults = { visible = false, x = 0, y = 0, width = 360, height = 500, } local display = settings.load(defaults, 'dashboard', true) local pairs = pairs local save = settings.save local init = state.init -- Public operations local dashboard = {} dashboard.name = 'dashboard' dashboard.visible = function() return display.visible end dashboard.show = function(value) display.visible = value save('dashboard') end dashboard.save = function() save('dashboard') end local components dashboard.init = function(options) components = options.components end -- UI do local location = ui.location dashboard.state = init(display, { title = 'Packet Viewer', }) dashboard.window = function() local y_current = 0 local pos = function(x, y_off) y_current = y_current + y_off location(x, y_current) end for _, component in pairs(components) do local render_dashboard = component.dashboard if render_dashboard then render_dashboard(pos) end end end dashboard.button = function() return 'Packet Viewer', 89 end dashboard.save = function() save('dashboard') end end return dashboard
--- Load in custom levels with static level gen. -- @module CustomLevels local custom_level_params = { hide_entrance = true, } local custom_level_state = { active = false, file_name = nil, width = nil, height = nil, room_generation_callback = nil, procedural_spawn_callback = nil, embedded_currency_callback = nil, embedded_item_callback = nil, floor_spread_callback = nil, bat_callback = nil, allowed_spawn_types = 0, entrance_tc = nil, entrance_remove_callback = nil, custom_theme_id = 4000, custom_theme = nil, } -- Create a bunch of room templates that can be used in lvl files to create rooms. The maximum -- level size is 8x15, so we only create that many templates. local room_templates = {} for x = 0, 7 do local room_templates_x = {} for y = 0, 14 do local room_template = define_room_template("setroom" .. y .. "_" .. x, ROOM_TEMPLATE_TYPE.NONE) room_templates_x[y] = room_template end room_templates[x] = room_templates_x end local removed_procedural_spawns = { ENT_TYPE.MONS_PET_DOG, ENT_TYPE.ITEM_BONES, ENT_TYPE.EMBED_GOLD, ENT_TYPE.EMBED_GOLD_BIG, ENT_TYPE.ITEM_POT, ENT_TYPE.ITEM_NUGGET, ENT_TYPE.ITEM_NUGGET_SMALL, ENT_TYPE.ITEM_SKULL, ENT_TYPE.ITEM_CHEST, ENT_TYPE.ITEM_CRATE, ENT_TYPE.MONS_PET_CAT, ENT_TYPE.MONS_PET_HAMSTER, ENT_TYPE.ITEM_ROCK, ENT_TYPE.ITEM_RUBY, ENT_TYPE.ITEM_CURSEDPOT, ENT_TYPE.ITEM_SAPPHIRE, ENT_TYPE.ITEM_EMERALD, ENT_TYPE.MONS_SCARAB, ENT_TYPE.ITEM_WEB, ENT_TYPE.ITEM_GOLDBAR, ENT_TYPE.ITEM_GOLDBARS, ENT_TYPE.ITEM_SKULL, ENT_TYPE.MONS_SKELETON, ENT_TYPE.ITEM_POTOFGOLD, ENT_TYPE.MONS_LEPRECHAUN, ENT_TYPE.DECORATION_POTOFGOLD_RAINBOW, } local removed_torches = { ENT_TYPE.ITEM_WALLTORCH, ENT_TYPE.ITEM_LITWALLTORCH, ENT_TYPE.ITEM_AUTOWALLTORCH, } local removed_embedded_currencies = { ENT_TYPE.EMBED_GOLD, ENT_TYPE.EMBED_GOLD_BIG, ENT_TYPE.ITEM_RUBY, ENT_TYPE.ITEM_SAPPHIRE, ENT_TYPE.ITEM_EMERALD, } local removed_embedded_items = { ENT_TYPE.ITEM_ALIVE_EMBEDDED_ON_ICE, ENT_TYPE.ITEM_PICKUP_ROPEPILE, ENT_TYPE.ITEM_PICKUP_BOMBBAG, ENT_TYPE.ITEM_PICKUP_BOMBBOX, ENT_TYPE.ITEM_PICKUP_SPECTACLES, ENT_TYPE.ITEM_PICKUP_CLIMBINGGLOVES, ENT_TYPE.ITEM_PICKUP_PITCHERSMITT, ENT_TYPE.ITEM_PICKUP_SPRINGSHOES, ENT_TYPE.ITEM_PICKUP_SPIKESHOES, ENT_TYPE.ITEM_PICKUP_PASTE, ENT_TYPE.ITEM_PICKUP_COMPASS, ENT_TYPE.ITEM_PICKUP_PARACHUTE, ENT_TYPE.ITEM_CAPE, ENT_TYPE.ITEM_JETPACK, ENT_TYPE.ITEM_TELEPORTER_BACKPACK, ENT_TYPE.ITEM_HOVERPACK, ENT_TYPE.ITEM_POWERPACK, ENT_TYPE.ITEM_WEBGUN, ENT_TYPE.ITEM_SHOTGUN, ENT_TYPE.ITEM_FREEZERAY, ENT_TYPE.ITEM_CROSSBOW, ENT_TYPE.ITEM_CAMERA, ENT_TYPE.ITEM_TELEPORTER, ENT_TYPE.ITEM_MATTOCK, ENT_TYPE.ITEM_BOOMERANG, ENT_TYPE.ITEM_MACHETE, ENT_TYPE.ITEM_POTOFGOLD, } local procedural_enemies = { ENT_TYPE.MONS_BAT, ENT_TYPE.MONS_HERMITCRAB, ENT_TYPE.TADPOLE, } local ALLOW_SPAWN_TYPE = { PROCEDURAL = 1, EMBEDDED_CURRENCY = 2, EMBEDDED_ITEMS = 3, PROCEDURAL_ENEMIES = 4, PROCEDURAL_TORCHES = 5, } -- Keep old name in case it's being used. ALLOW_SPAWN_TYPE.BACKLAYER_BATS = ALLOW_SPAWN_TYPE.PROCEDURAL_ENEMIES local function set_hide_entrance(hide_entrance) custom_level_params.hide_entrance = hide_entrance end -- Resets the state to remove references to the loaded file and removes callbacks that alter the level. local function unload_level() if not custom_level_state.active then return end custom_level_state.allowed_spawn_types = 0 custom_level_state.active = false custom_level_state.file_name = nil custom_level_state.width = nil custom_level_state.height = nil custom_level_state.custom_theme = nil if custom_level_state.room_generation_callback then clear_callback(custom_level_state.room_generation_callback) end custom_level_state.room_generation_callback = nil if custom_level_state.procedural_spawn_callback then clear_callback(custom_level_state.procedural_spawn_callback) end custom_level_state.procedural_spawn_callback = nil if custom_level_state.embedded_currency_callback then clear_callback(custom_level_state.embedded_currency_callback) end custom_level_state.embedded_currency_callback = nil if custom_level_state.embedded_item_callback then clear_callback(custom_level_state.embedded_item_callback) end custom_level_state.embedded_item_callback = nil if custom_level_state.floor_spread_callback then clear_callback(custom_level_state.floor_spread_callback) end custom_level_state.floor_spread_callback = nil if custom_level_state.bat_callback then clear_callback(custom_level_state.bat_callback) end custom_level_state.bat_callback = nil if custom_level_state.entrance_tc then clear_callback(custom_level_state.entrance_tc) end custom_level_state.entrance_tc = nil if custom_level_state.entrance_remove_callback then clear_callback(custom_level_state.entrance_remove_callback) end custom_level_state.entrance_remove_callback = nil end local function load_level(load_level_ctx, file_name, custom_theme, allowed_spawn_types, width, height) allowed_spawn_types = allowed_spawn_types or 0 unload_level() custom_level_state.active = true custom_level_state.file_name = file_name custom_level_state.width = width custom_level_state.height = height custom_level_state.allowed_spawn_types = allowed_spawn_types custom_level_state.custom_theme = custom_theme function override_level(ctx) local level_files = { file_name, } ctx:override_level_files(level_files) end if load_level_ctx then override_level(load_level_ctx) end if custom_theme then force_custom_theme(custom_theme) end custom_level_state.room_generation_callback = set_callback(function(ctx) if width and height then state.height = height state.width = width end for x = 0, state.width - 1 do for y = 0, state.height - 1 do ctx:set_room_template(x, y, LAYER.FRONT, room_templates[x][y]) end end end, ON.POST_ROOM_GENERATION) ---------------------------- ---- HIDE ENTRANCE DOOR ---- ---------------------------- local entranceX local entranceY local entranceLayer custom_level_state.entrance_tc = set_pre_tile_code_callback(function(x, y, layer) if state.screen == 13 then return end entranceX = math.floor(x) entranceY = math.floor(y) entranceLayer = layer return false end, "entrance") custom_level_state.entrance_remove_callback = set_post_entity_spawn(function (entity) if not entranceX or not entranceY or not entranceLayer then return end if not custom_level_params.hide_entrance then return end local px, py, pl = get_position(entity.uid) if math.abs(px - entranceX) < 1 and math.abs(py - entranceY) < 1 and pl == entranceLayer then kill_entity(entity.uid) end end, SPAWN_TYPE.ANY, 0, ENT_TYPE.BG_DOOR) ----------------------------- ---- /HIDE ENTRANCE DOOR ---- ----------------------------- custom_level_state.procedural_spawn_callback = set_post_entity_spawn(function(entity, spawn_flags) if test_flag(custom_level_state.allowed_spawn_types, ALLOW_SPAWN_TYPE.PROCEDURAL) then return end -- Do not remove spawns from a script. if spawn_flags & SPAWN_TYPE.SCRIPT ~= 0 then return end entity.flags = set_flag(entity.flags, ENT_FLAG.INVISIBLE) entity.flags = set_flag(entity.flags, ENT_FLAG.DEAD) move_entity(entity.uid, 1000, 0, 0, 0) entity:destroy() end, SPAWN_TYPE.LEVEL_GEN_GENERAL | SPAWN_TYPE.LEVEL_GEN_PROCEDURAL, 0, removed_procedural_spawns) custom_level_state.embedded_currency_callback = set_post_entity_spawn(function(entity, spawn_flags) if test_flag(custom_level_state.allowed_spawn_types, ALLOW_SPAWN_TYPE.EMBEDDED_CURRENCY) then return end -- Do not remove spawns from a script. if spawn_flags & SPAWN_TYPE.SCRIPT ~= 0 then return end entity.flags = set_flag(entity.flags, ENT_FLAG.INVISIBLE) entity.flags = set_flag(entity.flags, ENT_FLAG.DEAD) move_entity(entity.uid, 1000, 0, 0, 0) entity:destroy() end, SPAWN_TYPE.LEVEL_GEN_TILE_CODE, 0, removed_embedded_currencies) custom_level_state.embedded_item_callback = set_post_entity_spawn(function(entity, spawn_flags) if test_flag(custom_level_state.allowed_spawn_types, ALLOW_SPAWN_TYPE.EMBEDDED_ITEMS) then return end -- Do not remove spawns from a script. if spawn_flags & SPAWN_TYPE.SCRIPT ~= 0 then return end -- Only remove entities with an overlay, these should be the ones embeded in a crust. if not entity.overlay then return end entity.flags = set_flag(entity.flags, ENT_FLAG.INVISIBLE) entity.flags = set_flag(entity.flags, ENT_FLAG.DEAD) move_entity(entity.uid, 1000, 0, 0, 0) entity:destroy() end, SPAWN_TYPE.LEVEL_GEN_TILE_CODE, 0, removed_embedded_items) custom_level_state.bat_callback = set_post_entity_spawn(function(entity, spawn_type) if test_flag(custom_level_state.allowed_spawn_types, ALLOW_SPAWN_TYPE.PROCEDURAL_ENEMIES) then return end -- Do not remove spawns from a script. if spawn_type & SPAWN_TYPE.SCRIPT ~= 0 then return end entity.flags = set_flag(entity.flags, ENT_FLAG.INVISIBLE) entity.flags = set_flag(entity.flags, ENT_FLAG.DEAD) entity:destroy() end, SPAWN_TYPE.LEVEL_GEN_GENERAL, 0, procedural_enemies) custom_level_state.procedural_spawn_callback = set_post_entity_spawn(function(entity, spawn_flags) if test_flag(custom_level_state.allowed_spawn_types, ALLOW_SPAWN_TYPE.PROCEDURAL_TORCHES) then return end -- Do not remove spawns from a script. if spawn_flags & SPAWN_TYPE.SCRIPT ~= 0 then return end entity.flags = set_flag(entity.flags, ENT_FLAG.INVISIBLE) entity.flags = set_flag(entity.flags, ENT_FLAG.DEAD) move_entity(entity.uid, 1000, 0, 0, 0) entity:destroy() end, SPAWN_TYPE.LEVEL_GEN_GENERAL | SPAWN_TYPE.LEVEL_GEN_PROCEDURAL, 0, removed_torches) custom_level_state.floor_spread_callback = set_post_entity_spawn(function(entity) entity.flags = set_flag(entity.flags, ENT_FLAG.INVISIBLE) move_entity(entity.uid, 1000, 0, 0, 0) entity:destroy() end, SPAWN_TYPE.LEVEL_GEN_FLOOR_SPREADING, 0) end --- Load in a level file. -- @param file_name name/path to the file to load. -- @param width Width of the level in the file. -- @param height Height of the level in the file. -- @param load_level_ctx ON.PRE_LOAD_LEVEL_FILES context to load the level file into. -- @param allowed_spawn_types Optional spawn types flags to allow certain types of procedural spawns to spawn without being eliminated. -- -- Note: This must be called in ON.PRE_LOAD_LEVEL_FILES with the load_level_ctx from that callback. local function load_level_legacy(file_name, width, height, load_level_ctx, allowed_spawn_types) return load_level(load_level_ctx, file_name, nil, allowed_spawn_types, width, height) end local BORDER_THEME = { DEFAULT = 1, HARD_FLOOR = 2, SUNKEN_CITY = 3, NEO_BABYLON = 4, ICE_CAVES = 5, ICE_SUNKEN = 6, ICE_BABY = 7, DUAT = 8, NONE = 9, COSMIC_OCEAN = 10, TIAMAT = 11, } local GROWABLE_SPAWN_TYPE = { NONE = 0, CHAINS = 1, TIDE_POOL_POLES = 2, VINES = 4, } GROWABLE_SPAWN_TYPE.ALL = GROWABLE_SPAWN_TYPE.CHAINS | GROWABLE_SPAWN_TYPE.TIDE_POOL_POLES | GROWABLE_SPAWN_TYPE.VINES local function theme_for_border_theme(border_theme) if border_theme == BORDER_THEME.DEFAULT or border_theme == BORDER_THEME.NONE then return nil elseif border_theme == BORDER_THEME.HARD_FLOOR then return THEME.DWELLING elseif border_theme == BORDER_THEME.SUNKEN_CITY then return THEME.SUNKEN_CITY elseif border_theme == BORDER_THEME.NEO_BABYLON then return THEME.NEO_BABYLON elseif border_theme == BORDER_THEME.ICE_CAVES or border_theme == BORDER_THEME.ICE_SUNKEN or border_theme == BORDER_THEME.ICE_BABY then return THEME.ICE_CAVES elseif border_theme == BORDER_THEME.DUAT then return THEME.DUAT elseif border_theme == BORDER_THEME.TIAMAT then return THEME.TIAMAT elseif border_theme == BORDER_THEME.COSMIC_OCEAN then return THEME.COSMIC_OCEAN end end local function entity_theme_for_border_theme(border_theme) if border_theme == BORDER_THEME.ICE_SUNKEN then return THEME.SUNKEN_CITY elseif border_theme == BORDER_THEME.ICE_BABY then return THEME.NEO_BABYLON end return theme_for_border_theme(border_theme) end local function background_texture_for_theme(theme) if theme == THEME.DWELLING or theme == THEME.BASE_CAMP or theme == THEME.COSMIC_OCEAN then return TEXTURE.DATA_TEXTURES_BG_CAVE_0 elseif theme == THEME.VOLCANA then return TEXTURE.DATA_TEXTURES_BG_VOLCANO_0 elseif theme == THEME.JUNGLE then return TEXTURE.DATA_TEXTURES_BG_JUNGLE_0 elseif theme == THEME.OLMEC then return TEXTURE.DATA_TEXTURES_BG_STONE_0 elseif theme == THEME.TIDE_POOL or theme == THEME.ABZU or theme == THEME.TIAMAT then return TEXTURE.DATA_TEXTURES_BG_TIDEPOOL_0 elseif theme == THEME.TEMPLE or theme == THEME.DUAT then return TEXTURE.DATA_TEXTURES_BG_TEMPLE_0 elseif theme == THEME.CITY_OF_GOLD then return TEXTURE.DATA_TEXTURES_BG_GOLD_0 elseif theme == THEME.ICE_CAVES then return TEXTURE.DATA_TEXTURES_BG_ICE_0 elseif theme == THEME.NEO_BABYLON then return TEXTURE.DATA_TEXTURES_BG_BABYLON_0 elseif theme == THEME.SUNKEN_CITY or theme == THEME.HUNDUN then return TEXTURE.DATA_TEXTURES_BG_SUNKEN_0 elseif theme == THEME.EGGPLANT_WORLD then return TEXTURE.DATA_TEXTURES_BG_EGGPLANT_0 end end local function floor_texture_for_theme(theme) if theme == THEME.DWELLING then return TEXTURE.DATA_TEXTURES_FLOOR_CAVE_0 elseif theme == THEME.BASE_CAMP then return TEXTURE.DATA_TEXTURES_FLOOR_SURFACE_0 elseif theme == THEME.VOLCANA then return TEXTURE.DATA_TEXTURES_FLOOR_VOLCANO_0 elseif theme == THEME.JUNGLE or theme == THEME.OLMEC then return TEXTURE.DATA_TEXTURES_FLOOR_JUNGLE_0 elseif theme == THEME.TIDE_POOL or theme == THEME.TIAMAT or theme == THEME.ABZU then return TEXTURE.DATA_TEXTURES_FLOOR_TIDEPOOL_0 elseif theme == THEME.TEMPLE or theme == THEME.DUAT or theme == THEME.CITY_OF_GOLD then return TEXTURE.DATA_TEXTURES_FLOOR_TEMPLE_0 elseif theme == THEME.ICE_CAVES then return TEXTURE.DATA_TEXTURES_FLOOR_ICE_0 elseif theme == THEME.NEO_BABYLON then return TEXTURE.DATA_TEXTURES_FLOOR_BABYLON_0 elseif theme == THEME.SUNKEN_CITY or theme == THEME.HUNDUN then return TEXTURE.DATA_TEXTURES_FLOOR_SUNKEN_0 elseif theme == THEME.EGGPLANT_WORLD then return TEXTURE.DATA_TEXTURES_FLOOR_EGGPLANT_0 end return TEXTURE.DATA_TEXTURES_FLOOR_CAVE_0 end local aaab = false local function create_custom_theme(theme_properties, level_file) local theme = theme_properties.theme local subtheme = theme_properties.subtheme or theme_properties.co_subtheme local border_theme = theme_properties.theme local border_entity_theme = theme_properties.theme local border = theme_properties.border_type or theme_properties.border if border then if border == BORDER_THEME.NONE then border_theme = false border_entity_theme = false else border_theme = theme_for_border_theme(border) or border_theme border_entity_theme = entity_theme_for_border_theme(border) or border_entity_theme end end border_theme = theme_properties.border_theme or border_theme border_entity_theme = theme_properties.border_entity_theme or border_entity_theme local custom_theme = CustomTheme:new(custom_level_state.custom_theme_id, theme) custom_level_state.custom_theme_id = custom_level_state.custom_theme_id + 1 -- Spawning effects does things like changing the camera bounds in ice caves and spawning the duat bosses. if not theme_properties.dont_spawn_effects then custom_theme:override(THEME_OVERRIDE.SPAWN_EFFECTS, theme) end custom_theme:override(THEME_OVERRIDE.SPAWN_BORDER, border_theme) custom_theme:override(THEME_OVERRIDE.ENT_BORDER, border_entity_theme) -- The INIT_LEVEL is required for some effects like duat fog to look proper, but it could do other things that may be -- undesired, so it can be disabled. if not theme_properties.dont_init then custom_theme:override(THEME_OVERRIDE.INIT_LEVEL, border_theme) end if (border_theme == THEME.COSMIC_OCEAN and not theme_properties.dont_loop) or theme_properties.loop then custom_theme:override(THEME_OVERRIDE.LOOP, THEME.COSMIC_OCEAN) end -- Some themes, such as cosmic ocean, do not get the level size from the level file, so it must be manually configured. if theme_properties.width or theme_properties.height then custom_theme:post(THEME_OVERRIDE.INIT_LEVEL, function() if theme_properties.width then state.width = theme_properties.width end if theme_properties.height then state.height = theme_properties.height end end) end custom_theme:post(THEME_OVERRIDE.SPAWN_LEVEL, function() if theme_properties.dont_spawn_growables then return end local growables = theme_properties.growables or theme_properties.enabled_growables or theme_properties.growable_spawn_types or GROWABLE_SPAWN_TYPE.ALL local poles = growables & GROWABLE_SPAWN_TYPE.TIDE_POOL_POLES == GROWABLE_SPAWN_TYPE.TIDE_POOL_POLES local chains = growables & GROWABLE_SPAWN_TYPE.CHAINS == GROWABLE_SPAWN_TYPE.CHAINS local vines = growables & GROWABLE_SPAWN_TYPE.VINES == GROWABLE_SPAWN_TYPE.VINES local function grow_vines_both_layers() grow_vines(LAYER.FRONT, 256) grow_vines(LAYER.BACK, 256) end local function grow_poles_both_layers() grow_poles(LAYER.FRONT, 256) grow_poles(LAYER.BACK, 256) end if poles and chains and vines then grow_poles_both_layers() grow_vines_both_layers() state.level_gen.themes[THEME.VOLCANA]:spawn_traps() -- Spawn chains and sliding doors. elseif poles and chains then grow_poles_both_layers() state.level_gen.themes[THEME.VOLCANA]:spawn_traps() -- Spawn chains and sliding doors. elseif chains and vines then grow_vines_both_layers() state.level_gen.themes[THEME.VOLCANA]:spawn_traps() -- Spawn chains and sliding doors. elseif vines and poles then grow_poles_both_layers() grow_vines_both_layers() state.level_gen.themes[THEME.CITY_OF_GOLD]:spawn_traps() -- Spawn sliding doors. elseif vines then grow_vines_both_layers() state.level_gen.themes[THEME.CITY_OF_GOLD]:spawn_traps() -- Spawn sliding doors. elseif poles then grow_poles_both_layers() state.level_gen.themes[THEME.CITY_OF_GOLD]:spawn_traps() -- Spawn sliding doors. elseif chains then state.level_gen.themes[THEME.VOLCANA]:spawn_traps() -- Spawn chains and sliding doors. else state.level_gen.themes[THEME.CITY_OF_GOLD]:spawn_traps() -- Spawn sliding doors. end end) custom_theme:post(THEME_OVERRIDE.SPAWN_EFFECTS, function() if state.screen ~= SCREEN.LEVEL then return end -- Adjust the camera focus at the start of the level so it does not jump. if not theme_properties.dont_adjust_camera_focus then state.camera.adjusted_focus_x = state.level_gen.spawn_x state.camera.adjusted_focus_y = state.level_gen.spawn_y + 0.05 end -- If a camera bounds property exists, set the camera bounds to those bounds. Otherwise, leave them alone except for -- in a cosmic ocean theme, where the camera bounds should be set to the max distance. if theme_properties.camera_bounds then state.camera.bounds_left = theme_properties.camera_bounds.left state.camera.bounds_right = theme_properties.camera_bounds.right state.camera.bounds_top = theme_properties.camera_bounds.top state.camera.bounds_bottom = theme_properties.camera_bounds.bottom elseif not theme_properties.dont_adjust_camera_bounds then if border_theme == THEME.COSMIC_OCEAN then state.camera.bounds_left = -math.huge state.camera.bounds_top = math.huge state.camera.bounds_right = math.huge state.camera.bounds_bottom = -math.huge end end end) if theme_properties.background_theme then custom_theme.textures[DYNAMIC_TEXTURE.BACKGROUND] = background_texture_for_theme(theme_properties.background_theme) or TEXTURE.DATA_TEXTURES_BG_CAVE_0 custom_theme:override(THEME_OVERRIDE.ENT_BACKWALL, theme_properties.background_theme) custom_theme:override(THEME_OVERRIDE.SPAWN_BACKGROUND, theme_properties.background_theme) end if theme_properties.background_texture_theme then custom_theme.textures[DYNAMIC_TEXTURE.BACKGROUND] = background_texture_for_theme(theme_properties.background_texture_theme) or TEXTURE.DATA_TEXTURES_BG_CAVE_0 custom_theme:override(THEME_OVERRIDE.ENT_BACKWALL, theme_properties.background_texture_theme) end if theme_properties.background_texture then custom_theme.textures[DYNAMIC_TEXTURE.BACKGROUND] = theme_properties.background_texture end if theme_properties.floor_theme then custom_theme.textures[DYNAMIC_TEXTURE.FLOOR] = floor_texture_for_theme(theme_properties.floor_theme) -- Spawns extra theme elements over the floor. custom_theme:override(THEME_OVERRIDE.SPAWN_PROCEDURAL, theme_properties.floor_theme) end if theme_properties.floor_texture_theme then custom_theme.textures[DYNAMIC_TEXTURE.FLOOR] = floor_texture_for_theme(theme_properties.floor_texture_theme) end if theme_properties.floor_texture then custom_theme.textures[DYNAMIC_TEXTURE.FLOOR] = theme_properties.floor_texture end custom_theme.theme = theme_properties.theme custom_theme.level_file = level_file if theme_properties.post_configure then theme_properties.post_configure(custom_theme, subtheme, theme_properties) end return custom_theme, subtheme end --- Load in a level file. -- @param load_level_ctx ON.PRE_LOAD_LEVEL_FILES context to load the level file into. -- @param file_name name/path to the file to load. -- @param custom_theme Either a CustomTheme object or a table of parameters to configure a new CustomTheme. -- @param allowed_spawn_types Optional spawn types flags to allow certain types of procedural spawns to spawn without being eliminated. -- -- Note: This must be called in ON.PRE_LOAD_LEVEL_FILES with the load_level_ctx from that callback. local function load_level_custom_theme(load_level_ctx, file_name, custom_theme, allowed_spawn_types) local actual_custom_theme = nil if custom_theme then if type(custom_theme) == "userdata" and getmetatable(custom_theme).__type.name == "CustomTheme" then actual_custom_theme = custom_theme else actual_custom_theme, subtheme = create_custom_theme(custom_theme, file_name) if subtheme then force_custom_subtheme(subtheme) end width = width or custom_theme.width height = height or custom_theme.height end end load_level(load_level_ctx, file_name, actual_custom_theme, allowed_spawn_types) end return { state = custom_level_state, load_level = load_level_legacy, load_level_custom_theme = load_level_custom_theme, unload_level = unload_level, ALLOW_SPAWN_TYPE = ALLOW_SPAWN_TYPE, set_hide_entrance = set_hide_entrance, BORDER_THEME = BORDER_THEME, GROWABLE_SPAWN_TYPE = GROWABLE_SPAWN_TYPE, }
return { a = '\a'; b = '\b'; f = '\f'; n = '\n'; r = '\r'; t = '\t'; v = '\v'; }
--!A cross-platform build utility based on Lua -- -- 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. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file xmake.lua -- rule("vala.build") set_extensions(".vala") on_load(function (target) -- only vala source files? we need patch c source kind for linker local sourcekinds = target:sourcekinds() if #sourcekinds == 0 then table.insert(sourcekinds, "cc") end -- we disable to build across targets in parallel, because the source files may depend on other target modules target:set("policy", "build.across_targets_in_parallel", false) -- get vapi file local vapifile = target:data("vala.vapifile") if not vapifile then local vapiname = target:values("vala.vapi") if vapiname then vapifile = path.join(target:targetdir(), vapiname) else vapifile = path.join(target:targetdir(), target:name() .. ".vapi") end target:data_set("vala.vapifile", vapifile) end -- get header file local headerfile = target:data("vala.headerfile") if not headerfile then local headername = target:values("vala.header") if headername then headerfile = path.join(target:targetdir(), headername) else headerfile = path.join(target:targetdir(), target:name() .. ".h") end target:data_set("vala.headerfile", headerfile) end if headerfile then target:add("headerfiles", headerfile) target:add("sysincludedirs", path.directory(headerfile), {public = true}) end end) before_buildcmd_file(function (target, batchcmds, sourcefile_vala, opt) -- get valac import("lib.detect.find_tool") local valac = assert(find_tool("valac"), "valac not found!") -- get c source file for vala local sourcefile_c = target:autogenfile((sourcefile_vala:gsub(".vala$", ".c"))) local basedir = path.directory(sourcefile_c) -- add objectfile local objectfile = target:objectfile(sourcefile_c) table.insert(target:objectfiles(), objectfile) -- add commands batchcmds:show_progress(opt.progress, "${color.build.object}compiling.vala %s", sourcefile_vala) batchcmds:mkdir(basedir) local argv = {"-C", "-b", basedir} local packages = target:values("vala.packages") if packages then for _, package in ipairs(packages) do table.insert(argv, "--pkg") table.insert(argv, package) end end if target:is_binary() then for _, dep in ipairs(target:orderdeps()) do if dep:is_shared() or dep:is_static() then local vapifile = dep:data("vala.vapifile") if vapifile then table.join2(argv, vapifile) end end end else local vapifile = target:data("vala.vapifile") if vapifile then table.insert(argv, "--vapi=" .. vapifile) end local headerfile = target:data("vala.headerfile") if headerfile then table.insert(argv, "-H") table.insert(argv, headerfile) end end local vapidir = target:data("vala.vapidir") if vapidir then table.insert(argv, "--vapidir=" .. vapidir) end local valaflags = target:data("vala.flags") if valaflags then table.join2(argv, valaflags) end table.insert(argv, sourcefile_vala) batchcmds:vrunv(valac.program, argv) batchcmds:compile(sourcefile_c, objectfile) -- add deps batchcmds:add_depfiles(sourcefile_vala) batchcmds:set_depmtime(os.mtime(objectfile)) batchcmds:set_depcache(target:dependfile(objectfile)) end) after_install(function (target) if target:is_shared() or target:is_static() then local vapifile = target:data("vala.vapifile") if vapifile then local installdir = target:installdir() if installdir then local sharedir = path.join(installdir, "share") os.mkdir(sharedir) os.vcp(vapifile, sharedir) end end end end) after_uninstall(function (target) if target:is_shared() or target:is_static() then local vapifile = target:data("vala.vapifile") if vapifile then local installdir = target:installdir() if installdir then os.rm(path.join(installdir, "share", path.filename(vapifile))) end end end end) rule("vala") -- add build rules add_deps("vala.build") -- set compiler runtime, e.g. vs runtime add_deps("utils.compiler.runtime") -- inherit links and linkdirs of all dependent targets by default add_deps("utils.inherit.links") -- support `add_files("src/*.o")` and `add_files("src/*.a")` to merge object and archive files to target add_deps("utils.merge.object", "utils.merge.archive") -- we attempt to extract symbols to the independent file and -- strip self-target binary if `set_symbols("debug")` and `set_strip("all")` are enabled add_deps("utils.symbols.extract") -- check targets add_deps("utils.check.targets") -- check licenses add_deps("utils.check.licenses")
-- User-changeable variables local pumpkin_colour = {["r"] = 0xf, ["g"] = 0x2, ["b"] = 0x0} -- local Timer = require('base.timer') function effect() Lighting.SetFlashingSpeed(0) Lighting.SetBreathingModeEnabled(true) for i = 1, 8 do Lighting.SetColour(i, pumpkin_colour.r, pumpkin_colour.g, pumpkin_colour.b) end end Timer.Set(effect, Timer.DefaultInterval)
local OnsetRP = ImportPackage("onsetrp") local currentNpc local cinematicUIWeb = CreateWebUI(0, 0, 0, 0, 2, 60) SetWebVisibility(cinematicUIWeb, WEB_HIDDEN) SetWebAlignment(cinematicUIWeb, 0, 0) SetWebAnchors(cinematicUIWeb, 0, 0, 1, 1) SetWebURL(cinematicUIWeb, "http://asset/cinematicui/ui.html") AddEvent("CUIClose", function() stopCinematic() end) function startCinematic(data, npc, animation) currentNpc = npc or GetNearestNPC() SetNearClipPlane(15) EnableFirstPersonCamera(true) ShowChat(false) SetIgnoreLookInput(true) SetIgnoreMoveInput(true) ShowMouseCursor(true) SetInputMode(INPUT_GAMEANDUI) SetWebVisibility(cinematicUIWeb, WEB_VISIBLE) CallRemoteEvent("CUIAnimate", currentNpc, animation) ExecuteWebJS(cinematicUIWeb, 'startCinematic('..json_encode(data)..');') end function updateCinematic(data, animation) if animation then CallRemoteEvent("CUIAnimate", currentNpc, animation) end ExecuteWebJS(cinematicUIWeb, 'updateCinematic('..json_encode(data)..');') end function stopCinematic() currentNpc = null SetNearClipPlane(0) EnableFirstPersonCamera(false) ShowChat(true) SetIgnoreLookInput(false) SetIgnoreMoveInput(false) ShowMouseCursor(false) SetInputMode(INPUT_GAME) SetWebVisibility(cinematicUIWeb, WEB_HIDDEN) ExecuteWebJS(cinematicUIWeb, 'stopCinematic(false);') end function GetNearestNPC() local x, y, z = GetPlayerLocation() for k, npc in pairs(GetStreamedNPC()) do local x2, y2, z2 = GetNPCLocation(npc) if GetDistance3D(x, y, z, x2, y2, z2) < 250.0 then return npc end end return 0 end function NpcDelta() local x, y, z = GetPlayerLocation() local x2, y2, z2 = GetNPCLocation(currentNpc) return x2 - x, y2 - y end -- Exports AddFunctionExport("startCinematic", startCinematic) AddFunctionExport("updateCinematic", updateCinematic) AddFunctionExport("stopCinematic", stopCinematic)
target("udns") set_kind("static") add_includedirs("../src/udns", {public=true}) add_files("../src/udns/*.c")
-- authors: Luxinia Dev (Eike Decker & Christoph Kubisch) --------------------------------------------------------- -- put bin/ and lualibs/ first to avoid conflicts with included modules -- that may have other versions present somewhere else in path/cpath. local iswindows = os.getenv('WINDIR') or (os.getenv('OS') or ''):match('[Ww]indows') local islinux = not iswindows and not os.getenv('DYLD_LIBRARY_PATH') and io.open("/proc") local arch = "x86" -- use 32bit by default if islinux then local file = io.popen("uname -m") if file then arch = file:read("*a"):find("x86_64") and "x64" or "x86" file:close() end end package.cpath = ( iswindows and 'bin/?.dll;bin/clibs/?.dll;' or islinux and ('bin/linux/%s/lib?.so;bin/linux/%s/clibs/?.so;'):format(arch,arch) or --[[isosx]] 'bin/lib?.dylib;bin/clibs/?.dylib;') .. package.cpath package.path = 'lualibs/?.lua;lualibs/?/?.lua;lualibs/?/init.lua;lualibs/?/?/?.lua;lualibs/?/?/init.lua;' .. package.path require("wx") require("bit") dofile "src/util.lua" ----------- -- IDE -- ide = { config = { path = { projectdir = "", app = nil, }, editor = { foldcompact = true, checkeol = true, }, debugger = { verbose = false, hostname = nil, port = nil, }, default = { name = 'untitled', fullname = 'untitled.lua', }, outputshell = {}, filetree = {}, funclist = {}, keymap = {}, messages = {}, language = "en", styles = nil, stylesoutshell = nil, interpreter = "_undefined_", autocomplete = true, autoanalizer = true, acandtip = { shorttip = false, ignorecase = false, nodynwords = false, strategy = 2, width = 60, }, activateoutput = false, -- activate output/console on Run/Debug/Compile unhidewindow = false, -- to unhide a gui window allowinteractivescript = false, -- allow interaction in the output window filehistorylength = 20, projecthistorylength = 15, savebak = false, singleinstance = false, singleinstanceport = 0xe493, }, specs = { none = { linecomment = ">", sep = "\1", } }, tools = { }, iofilters = { }, interpreters = { }, app = nil, -- application engine interpreter = nil, -- current Lua interpreter frame = nil, -- gui related debugger = {}, -- debugger related info filetree = nil, -- filetree findReplace = nil, -- find & replace handling settings = nil, -- user settings (window pos, last files..) session = { projects = {}, -- project configuration for the current session lastupdated = nil, -- timestamp of the last modification in any of the editors lastsaved = nil, -- timestamp of the last recovery information saved }, -- misc exitingProgram = false, -- are we currently exiting, ID_EXIT editorApp = wx.wxGetApp(), editorFilename = nil, openDocuments = {},-- open notebook editor documents[winId] = { -- editor = wxStyledTextCtrl, -- index = wxNotebook page index, -- filePath = full filepath, nil if not saved, -- fileName = just the filename, -- modTime = wxDateTime of disk file or nil, -- isModified = bool is the document modified? } ignoredFilesList = {}, font = { eNormal = nil, eItalic = nil, oNormal = nil, oItalic = nil, fNormal = nil, dNormal = nil, }, osname = wx.wxPlatformInfo.Get():GetOperatingSystemFamilyName(), osarch = arch, wxver = string.match(wx.wxVERSION_STRING, "[%d%.]+"), } -- add wx.wxMOD_RAW_CONTROL as it's missing in wxlua 2.8.12.3; -- provide default for wx.wxMOD_CONTROL as it's missing in wxlua 2.8 that -- is available through Linux package managers if not wx.wxMOD_CONTROL then wx.wxMOD_CONTROL = 0x02 end if not wx.wxMOD_RAW_CONTROL then wx.wxMOD_RAW_CONTROL = ide.osname == 'Macintosh' and 0x10 or wx.wxMOD_CONTROL end -- ArchLinux running 2.8.12.2 doesn't have wx.wxMOD_SHIFT defined if not wx.wxMOD_SHIFT then wx.wxMOD_SHIFT = 0x04 end dofile "src/editor/ids.lua" dofile "src/editor/style.lua" dofile "src/editor/keymap.lua" ide.config.styles = StylesGetDefault() ide.config.stylesoutshell = StylesGetDefault() local function setLuaPaths(mainpath, osname) -- use LUA_DEV to setup paths for Lua for Windows modules if installed local luadev = osname == "Windows" and os.getenv('LUA_DEV') local luadev_path = (luadev and ('LUA_DEV/?.lua;LUA_DEV/?/init.lua;LUA_DEV/lua/?.lua;LUA_DEV/lua/?/init.lua') :gsub('LUA_DEV', (luadev:gsub('[\\/]$',''))) or "") local luadev_cpath = (luadev and ('LUA_DEV/?.dll;LUA_DEV/clibs/?.dll') :gsub('LUA_DEV', (luadev:gsub('[\\/]$',''))) or "") -- (luaconf.h) in Windows, any exclamation mark ('!') in the path is replaced -- by the path of the directory of the executable file of the current process. -- this effectively prevents any path with an exclamation mark from working. -- if the path has an excamation mark, allow Lua to expand it as this -- expansion happens only once. if osname == "Windows" and mainpath:find('%!') then mainpath = "!/../" end wx.wxSetEnv("LUA_PATH", package.path .. ";" .. "./?.lua;./?/init.lua;./lua/?.lua;./lua/?/init.lua" .. ';' .. mainpath.."lualibs/?/?.lua;"..mainpath.."lualibs/?.lua" .. ';' .. luadev_path) local clibs = osname == "Windows" and mainpath.."bin/?.dll;"..mainpath.."bin/clibs/?.dll" or osname == "Macintosh" and mainpath.."bin/lib?.dylib;"..mainpath.."bin/clibs/?.dylib" or osname == "Unix" and mainpath..("bin/linux/%s/lib?.so;"):format(arch) ..mainpath..("bin/linux/%s/clibs/?.so"):format(arch) or nil if clibs then wx.wxSetEnv("LUA_CPATH", package.cpath .. ';' .. clibs .. ';' .. luadev_cpath) end end --------------- -- process args local filenames = {} local configs = {} do local arg = {...} -- application name is expected as the first argument local fullPath = arg[1] or "zbstudio" ide.arg = arg -- on Windows use GetExecutablePath, which is Unicode friendly, -- whereas wxGetCwd() is not (at least in wxlua 2.8.12.2). -- some wxlua version on windows report wx.dll instead of *.exe. local exepath = wx.wxStandardPaths.Get():GetExecutablePath() if ide.osname == "Windows" and exepath:find("%.exe$") then fullPath = exepath elseif not wx.wxIsAbsolutePath(fullPath) then fullPath = wx.wxGetCwd().."/"..fullPath end ide.editorFilename = fullPath ide.config.path.app = fullPath:match("([%w_-%.]+)$"):gsub("%.[^%.]*$","") assert(ide.config.path.app, "no application path defined") for index = 2, #arg do if (arg[index] == "-cfg" and index+1 <= #arg) then table.insert(configs,arg[index+1]) elseif arg[index-1] ~= "-cfg" then table.insert(filenames,arg[index]) end end setLuaPaths(GetPathWithSep(ide.editorFilename), ide.osname) end ---------------------- -- process application ide.app = dofile(ide.config.path.app.."/app.lua") local app = assert(ide.app) local function addToTab(tab,file) local cfgfn,err = loadfile(file) if not cfgfn then print(("Error while loading configuration file: '%s'."):format(err)) else local name = file:match("([a-zA-Z_0-9]+)%.lua$") local success, result = pcall(function()return cfgfn(assert(_G or _ENV))end) if not success then print(("Error while processing configuration file: '%s'."):format(result)) elseif name then if (tab[name]) then local out = tab[name] for i,v in pairs(result) do out[i] = v end else tab[name] = result end end end end -- load interpreters local function loadInterpreters(filter) for _, file in ipairs(FileSysGetRecursive("interpreters", true, "*.lua")) do if (filter or app.loadfilters.interpreters)(file) then addToTab(ide.interpreters,file) end end end -- load specs local function loadSpecs(filter) for _, file in ipairs(FileSysGetRecursive("spec", true, "*.lua")) do if (filter or app.loadfilters.specs)(file) then addToTab(ide.specs,file) end end for _, spec in pairs(ide.specs) do spec.sep = spec.sep or "\1" -- default separator doesn't match anything spec.iscomment = {} spec.iskeyword0 = {} spec.isstring = {} if (spec.lexerstyleconvert) then if (spec.lexerstyleconvert.comment) then for _, s in pairs(spec.lexerstyleconvert.comment) do spec.iscomment[s] = true end end if (spec.lexerstyleconvert.keywords0) then for _, s in pairs(spec.lexerstyleconvert.keywords0) do spec.iskeyword0[s] = true end end if (spec.lexerstyleconvert.stringtxt) then for _, s in pairs(spec.lexerstyleconvert.stringtxt) do spec.isstring[s] = true end end end end end -- load tools local function loadTools(filter) for _, file in ipairs(FileSysGetRecursive("tools", false, "*.lua")) do if (filter or app.loadfilters.tools)(file) then addToTab(ide.tools,file) end end end -- temporarily replace print() to capture reported error messages to show -- them later in the Output window after everything is loaded. local resumePrint do local errors = {} local origprint = print print = function(...) errors[#errors+1] = {...} end resumePrint = function() print = origprint for _, e in ipairs(errors) do DisplayOutputLn(unpack(e)) end end end ----------------------- -- load config local function addConfig(filename,isstring) if not filename then return end -- skip those files that don't exist if not isstring and not wx.wxFileName(filename):FileExists() then return end -- if it's marked as command, but exists as a file, load it as a file if isstring and wx.wxFileName(filename):FileExists() then isstring = false end local cfgfn, err, msg if isstring then msg, cfgfn, err = "string", loadstring(filename) else msg, cfgfn, err = "file", loadfile(filename) end if not cfgfn then print(("Error while loading configuration %s: '%s'."):format(msg, err)) else ide.config.os = os ide.config.wxstc = wxstc ide.config.load = { interpreters = loadInterpreters, specs = loadSpecs, tools = loadTools } setfenv(cfgfn,ide.config) local _, err = pcall(function()cfgfn(assert(_G or _ENV))end) if err then print(("Error while processing configuration %s: '%s'."):format(msg, err)) end end end function GetIDEString(keyword, default) return app.stringtable[keyword] or default or keyword end ---------------------- -- process config addConfig(ide.config.path.app.."/config.lua") ide.editorApp:SetAppName(GetIDEString("settingsapp")) -- check if the .ini file needs to be migrated on Windows if ide.osname == 'Windows' and ide.wxver >= "2.9.5" then -- Windows used to have local ini file kept in wx.wxGetHomeDir (before 2.9), -- but since 2.9 it's in GetUserConfigDir(), so migrate it. local ini = ide.editorApp:GetAppName() .. ".ini" local old = wx.wxFileName(wx.wxGetHomeDir(), ini) local new = wx.wxFileName(wx.wxStandardPaths.Get():GetUserConfigDir(), ini) if old:FileExists() and not new:FileExists() then FileCopy(old:GetFullPath(), new:GetFullPath()) print(("Migrated configuration file from '%s' to '%s'.") :format(old:GetFullPath(), new:GetFullPath())) end end ---------------------- -- process plugins if app.preinit then app.preinit() end loadInterpreters() loadSpecs() loadTools() do local home = os.getenv("HOME") ide.configs = { system = MergeFullPath("cfg", "user.lua"), user = home and MergeFullPath(home, ".zbstudio/user.lua"), } -- process configs addConfig(ide.configs.system) addConfig(ide.configs.user) -- process all other configs (if any) for _, v in ipairs(configs) do addConfig(v, true) end configs = nil local sep = string_Pathsep if ide.config.language then addToTab(ide.config.messages, "cfg"..sep.."i18n"..sep..ide.config.language..".lua") end end --------------- -- Load App for _, file in ipairs({ "markup", "settings", "singleinstance", "iofilters", "gui", "filetree", "output", "debugger", "editor", "findreplace", "commands", "autocomplete", "shellbox", "menu_file", "menu_edit", "menu_search", "menu_view", "menu_project", "menu_tools", "menu_help", "inspect" }) do dofile("src/editor/"..file..".lua") end dofile "src/version.lua" -- load rest of settings SettingsRestoreEditorSettings() SettingsRestoreFramePosition(ide.frame, "MainFrame") SettingsRestoreFileHistory(SetFileHistory) SettingsRestoreFileSession(function(tabs, params) if params and params.recovery then return SetOpenTabs(params) else return SetOpenFiles(tabs, params) end end) SettingsRestoreProjectSession(FileTreeSetProjects) SettingsRestoreView() -- --------------------------------------------------------------------------- -- Load the filenames do for _, fileName in ipairs(filenames) do if fileName ~= "--" then LoadFile(fileName, nil, true) end end local notebook = ide.frame.notebook if notebook:GetPageCount() == 0 then NewFile() end end if app.postinit then app.postinit() end -- only set menu bar *after* postinit handler as it may include adding -- app-specific menus (Help/About), which are not recognized by MacOS -- as special items unless SetMenuBar is done after menus are populated. ide.frame:SetMenuBar(ide.frame.menuBar) if ide.wxver < "2.9.5" and ide.osname == 'Macintosh' then -- force refresh to fix the filetree pcall(function() ide.frame:ShowFullScreen(true) ide.frame:ShowFullScreen(false) end) end resumePrint() ide.frame:Show(true) wx.wxGetApp():MainLoop() -- There are several reasons for this call: -- (1) to fix a crash on OSX when closing with debugging in progress. -- (2) to fix a crash on Linux 32/64bit during GC cleanup in wxlua -- after an external process has been started from the IDE. -- (3) to fix exit on Windows when started as "bin\lua src\main.lua". os.exit()
-- Closures and anonymous functions are ok: function adder(x) -- The returned function is created when adder is -- called, and remembers the value of x: return function (y) return x + y end end a1 = adder(9) a2 = adder(36) print(a1(16)) --> 25 print(a2(64)) --> 100
function start(keys) local caster = keys.caster local target = keys.target local ability = keys.ability local ability_crit = caster:FindAbilityByName("gustavo_crit") local level = (ability:GetLevel()-1) local level_crit = (ability_crit:GetLevel()-1) local damage = ability:GetLevelSpecialValueFor("damage", level) local crit_chance = ability_crit:GetLevelSpecialValueFor("chance", level_crit) if level_crit >= 0 then local random = math.random(100) print ("random: " .. random) print ("chance: " .. crit_chance) if random <= crit_chance then local mult = ability_crit:GetLevelSpecialValueFor("damage_percentage", level_crit) damage = (damage * mult / 100) end end local damageTable = { victim = target, attacker = caster, damage = damage, damage_type = DAMAGE_TYPE_MAGICAL, ability = ability, } ApplyDamage(damageTable) print("damage applyed: " .. damage) end function freeze_break(keys) local caster = keys.caster local target = keys.unit target:RemoveModifierByName("gustavo_eradogelo_freeze") local ability = keys.ability local ability_crit = caster:FindAbilityByName("gustavo_crit") local level = (ability:GetLevel()-1) local level_crit = (ability_crit:GetLevel()-1) local damage = ability:GetLevelSpecialValueFor("break_damage", level) local crit_chance = ability_crit:GetLevelSpecialValueFor("chance", level_crit) if level_crit >= 0 then local random = math.random(100) print ("random: " .. random) print ("chance: " .. crit_chance) if random <= crit_chance then local mult = ability_crit:GetLevelSpecialValueFor("damage_percentage", level_crit) damage = (damage * mult / 100) end end local damageTable = { victim = target, attacker = caster, damage = damage, damage_type = DAMAGE_TYPE_MAGICAL, ability = ability, } ApplyDamage(damageTable) print("damage applyed: " .. damage) end
local chooseMagic = love.filesystem.load("utils/grid.lua")() local skills = {} for skill, value in pairs(character.active_skills) do table.insert(skills, { id = skill, title = character:normalizeTitle(skill), comment = "LV: "..character:getSkillLevel(skill).." MP: "..character:getSkillLevel(skill) }) end chooseMagic.title = "Magic menu" chooseMagic.list = skills function chooseMagic:onConfirm() if character:hasEnoughMana(self.list[self.current].id) then events:push({ type = "target", skill = self.list[self.current].id }) character.animation:setState("cast") end end function chooseMagic:onDeny() events:push("user_action") end return chooseMagic
-- Put your computer's address here! localhost will work locally, but you'll -- need an actual IP address to deploy to a device (iOS/Android). local baseURL = 'http://localhost:2000' --local baseURL = 'http://mycomputer.local:2000' --local baseURL = 'http://10.0.0.10:2000' local http = require('socket.http') love.filesystem.setRequirePath(love.filesystem.getRequirePath()..';_bundle/?.lua;_bundle/?/init.lua') local function makeDirs(fullpath) local pathsep = string.sub(fullpath, 1, string.match(fullpath, '()/[%w. -]*$')) love.filesystem.createDirectory(pathsep) end local function getBundle() local bundle, code, h = http.request(baseURL..'/contents') if code ~= 200 then error('blerp') end local sep = h['x-sep'] local files = {} local iter = 0 local seps = {} local nextPos = 1 repeat local e, filename, p = string.match(bundle, "()"..sep.." (%g+)()", nextPos, true) if p ~= nil then nextPos = p + 1 seps[#seps+1] = {e, filename, p+1} end until p == nil local dest = '_bundle' --love.filesystem.getSaveDirectory() .. '/_bundle' if not love.filesystem.createDirectory(dest) then error('Could not create output dir '..dest) end for i,s in ipairs(seps) do local _, filename, startContent = unpack(s) --local startContent = string.find(bundle, '\n', pos, true) + 1 local c = string.sub(bundle, startContent, seps[i+1] and seps[i+1][1]-2 or -2) local destFilename = dest..'/'..filename makeDirs(destFilename) local result, err = love.filesystem.write(destFilename, c) if not result then error(err) end print('wrote '..#c..' bytes to '..destFilename) --print(filename, startContent, "'"..c.."'") end end local callbacks = {"load", "update", "draw", "keypressed", "keyreleased", "mousepressed", "mousereleased", "mousemoved", "wheelmoved", "touchpressed"} local function empty() end local function runFromBundle() -- Save which modules were loaded before the game local loaded = {} for lib in pairs(package.loaded) do loaded[lib] = true end for i, v in ipairs(callbacks) do love[v] = empty end love.filesystem.load('_bundle/main.lua')() love.graphics.setBackgroundColor(0, 0, 0) love.graphics.setColor(255, 255, 255) love.graphics.setLineWidth(1) love.graphics.setLineStyle("smooth") love.graphics.setBlendMode("alpha") love.mouse.setVisible(true) local function reload() for lib in pairs(package.loaded) do if not loaded[lib] then package.loaded[lib] = nil end end getBundle() runFromBundle() end -- Install refresh handlers local _keypressed = love.keypressed function love.keypressed(k, ...) if k == 'r' and love.keyboard.isDown('lshift') then reload() else _keypressed(k, ...) end end local _touchpressed = love.touchpressed function love.touchpressed(...) print('touchpressed', #love.touch.getTouches()) if #love.touch.getTouches() == 5 then reload() else _touchpressed(...) end end love.load() end getBundle() runFromBundle()