content
stringlengths 5
1.05M
|
---|
data:extend({
--fish-kit
{
type = "capsule",
name = "fish-kit",
icon = "__morebobs__/graphics/icons/tank/fish-kit.png",
flags = {"goes-to-quickbar"},
icon_size = 32,
capsule_action =
{
type = "use-on-self",
attack_parameters =
{
type = "projectile",
ammo_category = "capsule",
cooldown = 10,
range = 0,
ammo_type =
{
category = "capsule",
target_type = "position",
action =
{
type = "direct",
action_delivery =
{
type = "instant",
target_effects =
{
type = "damage",
damage = {type = "physical", amount = -40}
}
}
}
}
}
},
subgroup = "tank-ammo-infantry",
order = "a-01[fish-kit]",
stack_size = 100
},
--Special
{
type = "capsule",
name = "tank-recall-token",
icon = "__morebobs__/graphics/icons/tank/tank-recall-token.png",
icon_size = 32,
flags = {"goes-to-quickbar"},
capsule_action =
{
type = "use-on-self",
attack_parameters =
{
type = "projectile",
ammo_category = "capsule",
cooldown = 30,
projectile_creation_distance = 0.0,
range = 0,
ammo_type =
{
category = "capsule",
target_type = "position",
action =
{
type = "direct",
action_delivery =
{
type = "instant",
target_effects =
{
{
type = "create-entity",
entity_name = "pre-teleport-effect",
trigger_created_entity = true
}
}
}
}
}
}
},
subgroup = "tank-ammo-infantry",
order = "b-01[tank-recall-token]",
stack_size = 10
},
{
type = "capsule",
name = "repair-capsule",
icon = "__morebobs__/graphics/icons/tank/repair-capsule.png",
icon_size = 32,
flags = {"goes-to-quickbar"},
capsule_action =
{
type = "throw",
attack_parameters =
{
type = "projectile",
ammo_category = "capsule",
cooldown = 15,
projectile_creation_distance = 0.6,
range = 20,
ammo_type =
{
category = "capsule",
target_type = "position",
action =
{
type = "direct",
action_delivery =
{
type = "projectile",
projectile = "repair-capsule",
starting_speed = 0.3
}
}
}
}
},
subgroup = "capsule",
order = "da[repair-capsule]",
stack_size = 100
},
}) |
button = class("button",{
pressed = false,x,y,h,w,img, maxTime = 0.20, waitTime})
function button:init(x,y,h,w)
self.x,self.y,self.h,self.w = x,y,h,w
--self.img = love.graphics.newImage(filename)
end
function button:load(x,y,filename)
print("x: ",x)
print("y: ", y)
print("filename: ", filename)
print("Clicked: ", self.pressed)
self.x = x
self.y = y
self.img = love.graphics.newImage(filename)
self.h = self.img:getHeight()
self.w = self.img:getWidth()
self.pressed = false
end
function button:clicked()
if love.mouse.isDown(1) then
--print("clicked")
if love.mouse.getX() > self.x and love.mouse.getX() < (self.x + self.w)
and love.mouse.getY() > self.y and love.mouse.getY() < (self.y + self.h) then
self.pressed = true
return true
else self.pressed = false end
end
return false
end
function button:hover()
if love.mouse.getX() > self.x and love.mouse.getX() < (self.x + self.w) and love.mouse.getY() > self.y and love.mouse.getY() < (self.y + self.h) then
return true
end
return false
end
function button:draw()
love.graphics.draw(self.img, self.x, self.y)
end
|
if not(GetLocale() == "frFR") then
return;
end
local L = WeakAuras.L
-- Options translation
L["1 Match"] = "1 Correspondance"
L["Actions"] = "Actions"
L["Activate when the given aura(s) |cFFFF0000can't|r be found"] = "Activer quand l'aura |cFFFF0000ne peut|r être trouvée"
L["Add a new display"] = "Ajouter un nouveau graphique"
L["Add Dynamic Text"] = "Ajouter du texte dynamique"
L["Addon"] = "Addon"
L["Addons"] = "Addons"
L["Add to group %s"] = "Ajouter au groupe %s"
L["Add to new Dynamic Group"] = "Ajouter à un nouveau groupe dynamique"
L["Add to new Group"] = "Ajouter à un nouveau groupe"
L["Add Trigger"] = "Ajouter un déclencheur"
L["A group that dynamically controls the positioning of its children"] = "Un groupe qui contrôle dynamiquement le positionnement de ses enfants"
L["Align"] = "Aligner"
L["Allow Full Rotation"] = "Permettre une rotation complète"
L["Alpha"] = "Alpha"
L["Anchor"] = "Ancrage"
L["Anchor Point"] = "Point d'ancrage"
L["Angle"] = "Angle"
L["Animate"] = "Animer"
L["Animated Expand and Collapse"] = "Expansion et réduction animés"
L["Animation relative duration description"] = [=[La durée de l'animation par rapport à la durée du graphique, exprimée en fraction (1/2), pourcentage (50%), ou décimal (0.5).
|cFFFF0000Note :|r si un graphique n'a pas de progression (déclencheur d'événement sans durée définie, aura sans durée, etc), l'animation ne jouera pas.
|cFF4444FFPar exemple :|r
Si la durée de l'animation est définie à |cFF00CC0010%|r, et le déclencheur du graphique est une amélioration qui dure 20 secondes, l'animation de début jouera pendant 2 secondes.
Si la durée de l'animation est définie à |cFF00CC0010%|r, et le déclencheur du graphique n'a pas de durée définie, aucune d'animation de début ne jouera (mais elle jouerait si vous aviez spécifié une durée en secondes).
]=]
L["Animations"] = "Animations"
L["Animation Sequence"] = "Séquence d'animation"
L["Aquatic"] = "Aquatique"
L["Aura (Paladin)"] = "Aura (Paladin)"
L["Aura(s)"] = "Aura(s)"
L["Auto"] = "Auto"
L["Auto-cloning enabled"] = "Auto-clonage activé"
L["Automatic Icon"] = "Icône automatique"
L["Backdrop Color"] = "Couleur de Fond"
L["Backdrop Style"] = "Style de Fond"
L["Background"] = "Arrière-plan"
L["Background Color"] = "Couleur de fond"
L["Background Inset"] = "Encart d'arrière-plan"
L["Background Offset"] = "Décalage du Fond "
L["Background Texture"] = "Texture du Fond"
L["Bar Alpha"] = "Alpha de la Barre"
L["Bar Color"] = "Couleur de barre"
L["Bar Color Settings"] = "Réglages Couleur de Barre"
L["Bar in Front"] = "Barre devant"
L["Bar Texture"] = "Texture de barre"
L["Battle"] = "Combat"
L["Bear"] = "Ours"
L["Berserker"] = "Berserker"
L["Blend Mode"] = "Mode du fusion"
L["Blood"] = "Sang"
L["Border"] = "Bordure"
L["Border Color"] = "Couleur de Bordure"
L["Border Inset"] = "Encart Fond"
L["Border Offset"] = "Décalage Bordure"
L["Border Settings"] = "Réglages de Bordure"
L["Border Size"] = "Taille de Bordure"
L["Border Style"] = "Style de Bordure"
L["Bottom Text"] = "Texte du bas"
L["Button Glow"] = "Bouton allumé"
L["Can be a name or a UID (e.g., party1). Only works on friendly players in your group."] = "Peut être un nom ou un UID (par ex. party1). Fonctionne uniquement pour les joueurs amicaux de votre groupe."
L["Cancel"] = "Annuler"
L["Cat"] = "Chat"
L["Change the name of this display"] = "Changer le nom de ce graphique"
L["Channel Number"] = "Numéro de canal"
L["Check On..."] = "Vérifier sur..."
L["Choose"] = "Choisir"
L["Choose Trigger"] = "Choisir un déclencheur"
L["Choose whether the displayed icon is automatic or defined manually"] = "Choisir si l'icône affichée est automatique ou définie manuellement"
L["Clone option enabled dialog"] = [=[
Vous avez activé une option qui utilise l'|cFFFF0000Auto-clonage|r.
L'|cFFFF0000Auto-clonage|r permet à un graphique d'être automatiquement dupliqué pour afficher plusieurs sources d'information.
A moins que vous mettiez ce graphique dans un |cFF22AA22Groupe Dynamique|r, tous les clones seront affichés en tas l'un sur l'autre.
Souhaitez-vous que ce graphiques soit placé dans un nouveau |cFF22AA22Groupe Dynamique|r ?]=]
L["Close"] = "Fermer"
L["Collapse"] = "Réduire"
L["Collapse all loaded displays"] = "Réduire tous les graphiques chargés"
L["Collapse all non-loaded displays"] = "Réduire tous les graphiques non-chargés"
L["Color"] = "Couleur"
L["Compress"] = "Compresser"
L["Concentration"] = "Concentration"
L["Constant Factor"] = "Facteur constant"
L["Control-click to select multiple displays"] = "Contrôle-Clic pour sélectionner plusieurs graphiques"
L["Controls the positioning and configuration of multiple displays at the same time"] = "Contrôle la position et la configuration de plusieurs graphiques en même temps"
L["Convert to..."] = "Convertir en..."
L["Cooldown"] = "Recharge"
L["Copy"] = "Copier"
L["Copy settings from..."] = "Copier les réglages de..."
L["Copy settings from another display"] = "Copier les réglages d'un autre graphique"
L["Copy settings from %s"] = "Copier les réglages de %s"
L["Count"] = "Compte"
L["Creating buttons: "] = "Création de boutons :"
L["Creating options: "] = "Création d'options :"
L["Crop X"] = "Couper X"
L["Crop Y"] = "Couper Y"
L["Crusader"] = "Croisé"
L["Custom Code"] = "Code personnalisé"
L["Custom Trigger"] = "Déclencheur personnalisé"
L["Custom trigger event tooltip"] = [=[
Choisissez quels évènements peuvent activer le déclencheur.
Plusieurs évènements peuvent être spécifiés avec des virgules ou des espaces.
|cFF4444FFPar exemple:|r
UNIT_POWER, UNIT_AURA PLAYER_TARGET_CHANGED
]=]
L["Custom trigger status tooltip"] = [=[
Choisissez quels évènements peuvent activer le déclencheur.
Comme c'est un déclencheur de type statut, les évènements spécifiés peuvent être appelés par WeakAuras sans les arguments attendus.
Plusieurs évènements peuvent être spécifiés avec des virgules ou des espaces.
|cFF4444FFPar exemple:|r
UNIT_POWER, UNIT_AURA PLAYER_TARGET_CHANGED
]=]
L["Custom Untrigger"] = "Désactivation personnalisée"
L["Custom untrigger event tooltip"] = [=[
Choisissez quels évènements peuvent causer la désactivation.
Cela peut être des évènements différents de ceux du déclencheur.
Plusieurs évènements peuvent être spécifiés avec des virgules ou des espaces.
|cFF4444FFPar exemple:|r
UNIT_POWER, UNIT_AURA PLAYER_TARGET_CHANGED
]=]
L["Death"] = "Mort"
L["Death Rune"] = "Rune de Mort"
L["Debuff Type"] = "Type d'affaiblissement"
L["Defensive"] = "Défensif"
L["Delete"] = "Supprimer"
L["Delete all"] = "Supprimer tout"
L["Delete children and group"] = "Supprimer enfants et groupe"
L["Deletes this display - |cFF8080FFShift|r must be held down while clicking"] = "Supprime ce graphique - |cFF8080FFMaj|r doit être maintenu en cliquant"
L["Delete Trigger"] = "Supprimer le déclencheur"
L["Desaturate"] = "Dé-saturer"
L["Devotion"] = "Dévotion"
L["Disabled"] = "Désactivé"
L["Discrete Rotation"] = "Rotation individuelle"
L["Display"] = "Graphique"
L["Display Icon"] = "Icône du graphique"
L["Display Text"] = "Texte du graphique"
L["Distribute Horizontally"] = "Distribuer horizontalement"
L["Distribute Vertically"] = "Distribuer verticalement"
L["Do not copy any settings"] = "Ne copier aucun réglage"
L["Do not group this display"] = "Ne pas grouper ce graphique"
L["Duplicate"] = "Dupliquer"
L["Duration Info"] = "Info de durée"
L["Duration (s)"] = "Durée (s)"
L["Dynamic Group"] = "Groupe Dynamique"
L["Dynamic text tooltip"] = [=[
Il y a plusieurs codes spéciaux disponibles pour rendre ce texte dynamique :
|cFFFF0000%p|r - Progression - Le temps restant sur un compteur, ou une valeur autre
|cFFFF0000%t|r - Total - La durée maximum d'un compteur, ou le maximum d'une valeur autre
|cFFFF0000%n|r - Nom - Le nom du graphique (souvent le nom d'une aura), ou l'ID du graphique s'il n'y a pas de nom dynamique
|cFFFF0000%i|r - Icône - L'icône associée à l'affichage
|cFFFF0000%s|r - Pile - La taille de la pile d'une aura (généralement)
|cFFFF0000%c|r - Personnalisé - Vous permet de définir une fonction Lua personnalisée qui donne un texte à afficher]=]
L["Enabled"] = "Activé"
L["Enter an aura name, partial aura name, or spell id"] = "Entrez un nom d'aura, nom d'aura partiel ou ID de sort"
L["Event Type"] = "Type d'évènement"
L["Expand"] = "Agrandir"
L["Expand all loaded displays"] = "Agrandir tous graphiques chargés"
L["Expand all non-loaded displays"] = "Agrandir tous graphiques non-chargés"
L["Expand Text Editor"] = "Agrandir éditeur de texte"
L["Expansion is disabled because this group has no children"] = "Agrandissement désactivé car ce groupe n'a pas d'enfants"
L["Export"] = "Exporter"
L["Export to Lua table..."] = "Exporter une table Lua..."
L["Export to string..."] = "Exporter en texte..."
L["Fade"] = "Fondu"
L["Finish"] = "Finir"
L["Fire Resistance"] = "Résistance au Feu"
L["Flight(Non-Feral)"] = "Vol(non-Féral)"
L["Font"] = "Police"
L["Font Flags"] = "Style de Police"
L["Font Size"] = "Taille de Police"
L["Font Type"] = "Type de police"
L["Foreground Color"] = "Couleur premier-plan"
L["Foreground Texture"] = "Texture premier-plan"
L["Form (Druid)"] = "Forme (Druide)"
L["Form (Priest)"] = "Forme (Prêtre)"
L["Form (Shaman)"] = "Forme (Chaman)"
L["Form (Warlock)"] = "Forme (Démoniste)"
L["Frame"] = "Cadre"
L["Frame Strata"] = "Strate du cadre"
L["Frost"] = "Givre"
L["Frost Resistance"] = "Résistance au Givre"
L["Full Scan"] = "Scan Complet"
L["Ghost Wolf"] = "Loup fantôme"
L["Glow Action"] = "Action de l'éclat"
L["Group aura count description"] = [=[Le nombre de membres du %s qui doivent être affectés par une ou plus des auras désignées pour que le graphique soit déclenché.
Si le nombre entré est un entier (par ex. 5), le nombre de membres du raid affectés sera comparé au nombre entré.
Si le nombre entré est decimal (par ex. 0.5), une fraction (par ex. 1/2), ou un pourcentage (par ex. 50%%), alors cette fraction du %s doit être affecté.
|cFF4444FFPar exemple :|r
|cFF00CC00> 0|r le déclenchera quand n'importe qui du %s est affecté
|cFF00CC00= 100%%|r le déclenchera quand tout le monde dans le %s est affecté
|cFF00CC00!= 2|r le déclenchera quand le nombre de membres du %s affectés est différent de 2
|cFF00CC00<= 0.8|r le déclenchera quand quand moins de 80%% du %s est affecté (4 sur 5 membres du groupe, 8 sur 10 ou 20 sur 25 du raid )
|cFF00CC00> 1/2|r le déclenchera quand plus de la moitié du %s est affecté
|cFF00CC00>= 0|r le déclenchera toujours, quoi qu'il arrive
]=]
L["Group Member Count"] = "Nombre de membres du groupe"
L["Group (verb)"] = "Grouper"
L["Height"] = "Hauteur"
L["Hide this group's children"] = "Cacher les enfants de ce groupe"
L["Hide When Not In Group"] = "Cacher hors d'un groupe"
L["Horizontal Align"] = "Aligner horizontalement"
L["Icon Info"] = "Info d'icône"
L["Ignored"] = "Ignoré"
L["Ignore GCD"] = "Ignorer Recharge Globale"
L["%i Matches"] = "%i Correspondances"
L["Import"] = "Importer"
L["Import a display from an encoded string"] = "Importer un graphique d'un texte encodé"
L["Justify"] = "Justification"
L["Left Text"] = "Texte de gauche"
L["Load"] = "Charger"
L["Loaded"] = "Chargé"
L["Main"] = "Principal"
L["Main Trigger"] = "Déclencheur principal"
L["Mana (%)"] = "Mana (%)"
L["Manage displays defined by Addons"] = "Gérer graphiques définis par addons"
L["Message Prefix"] = "Préfixe du message"
L["Message Suffix"] = "Suffixe du message"
L["Metamorphosis"] = "Métamorphose"
L["Mirror"] = "Miroir"
L["Model"] = "Modèle"
L["Moonkin/Tree/Flight(Feral)"] = "Sélénien/Arbre/Vol(Farouche)"
L["Move Down"] = "Descendre"
L["Move this display down in its group's order"] = "Descend ce graphique dans l'ordre de son groupe"
L["Move this display up in its group's order"] = "Monte ce graphique dans l'ordre de son groupe"
L["Move Up"] = "Monter"
L["Multiple Displays"] = "Graphiques multiples"
L["Multiple Triggers"] = "Déclencheur multiples"
L["Multiselect ignored tooltip"] = [=[
|cFFFF0000Ignoré|r - |cFF777777Unique|r - |cFF777777Multiple|r
Cette option ne sera pas utilisée pour déterminer quand ce graphique doit être chargé]=]
L["Multiselect multiple tooltip"] = [=[
|cFF777777Ignoré|r - |cFF777777Unique|r - |cFF00FF00Multiple|r
Plusieurs valeurs peuvent être choisies]=]
L["Multiselect single tooltip"] = [=[
|cFF777777Ignoré|r - |cFF00FF00Unique|r - |cFF777777Multiple|r
Seule une unique valeur peut être choisie]=]
L["Must be spelled correctly!"] = "Doit être épelé correctement !"
L["Name Info"] = "Info du nom"
L["Negator"] = "Pas"
L["New"] = "Nouveau"
L["Next"] = "Suivant"
L["No"] = "Non"
L["No Children"] = "Pas d'enfant"
L["Not all children have the same value for this option"] = "Tous les enfants n'ont pas la même valeur pour cette option"
L["Not Loaded"] = "Non chargé"
L["No tooltip text"] = "Pas d'infobulle"
L["% of Progress"] = "% de progression"
L["Okay"] = "Okay"
L["On Hide"] = "Au masquage"
L["Only match auras cast by people other than the player"] = "Ne considérer que les auras lancées par d'autres que le joueur"
L["Only match auras cast by the player"] = "Ne considérer que les auras lancées par le joueur"
L["On Show"] = "A l'affichage"
L["Operator"] = "Opérateur"
L["or"] = "ou"
L["Orientation"] = "Orientation"
L["Other"] = "Autre"
L["Outline"] = "Contour"
L["Own Only"] = "Le mien uniquement"
L["Player Character"] = "Personnage Joueur"
L["Play Sound"] = "Jouer un son"
L["Presence (DK)"] = "Présence"
L["Presence (Rogue)"] = "Présence"
L["Prevents duration information from decreasing when an aura refreshes. May cause problems if used with multiple auras with different durations."] = "Empêche l'info de durée de décroitre quand une aura est rafraichie. Peut causer des problèmes si utilisé avec plusieurs auras de différentes durées."
L["Primary"] = "Primaire"
L["Progress Bar"] = "Barre de progression"
L["Progress Texture"] = "Texture de progression"
L["Put this display in a group"] = "Mettre ce graphique dans un groupe"
L["Ready For Use"] = "Prêt à l'emploi"
L["Re-center X"] = "Recentrer X"
L["Re-center Y"] = "Recentrer Y"
L["Remaining Time Precision"] = "Précision du temps restant"
L["Remove this display from its group"] = "Retirer ce graphique de son groupe"
L["Rename"] = "Renommer"
L["Requesting display information"] = "Demande d'info de graphique à %s..."
L["Required For Activation"] = "Requis pour l'activation"
L["Retribution"] = "Vindicte"
L["Right-click for more options"] = "Clic-droit pour plus d'options"
L["Right Text"] = "Texte de droite"
L["Rotate"] = "Tourner"
L["Rotate In"] = "Rotation entrante"
L["Rotate Out"] = "Rotation sortante"
L["Rotate Text"] = "Tourner le texte"
L["Rotation"] = "Rotation"
L["Same"] = "Le même"
L["Search"] = "Chrecher"
L["Secondary"] = "Secondaire"
L["Send To"] = "Envoyer vers"
L["Set tooltip description"] = "Définir description d'infobulle"
L["Shadow Dance"] = "Danse de l'ombre"
L["Shadowform"] = "Forme d'Ombre"
L["Shadow Resistance"] = "Résistance à l'Ombre"
L["Shift-click to create chat link"] = "Maj-Clic pour créer un |cFF8800FF[Lien]"
L["Show all matches (Auto-clone)"] = "Montrer toutes correspondances (Auto-Clone)"
L["Show players that are |cFFFF0000not affected"] = "Montrer les joueurs |cFFFF0000non-affectés"
L["Shows a 3D model from the game files"] = "Montre un modèle 3D tiré du jeu"
L["Shows a custom texture"] = "Montre une texture personnalisée"
L["Shows a progress bar with name, timer, and icon"] = "Affiche une barre de progression avec nom, temps, icône"
L["Shows a spell icon with an optional a cooldown overlay"] = "Affiche une icône de sort avec optionnellement la recharge sur-imprimée"
L["Shows a texture that changes based on duration"] = "Affiche une texture qui change selon la durée"
L["Shows one or more lines of text, which can include dynamic information such as progress or stacks"] = "Affiche une ligne de texte ou plus, qui peut inclure des infos dynamiques telles que progression ou piles."
L["Shows the remaining or expended time for an aura or timed event"] = "Affiche le temps restant ou étendu d'une aura ou évènement"
L["Show this group's children"] = "Montrer les enfants de ce groupe"
L["Size"] = "Taille"
L["Slide"] = "Glisser"
L["Slide In"] = "Glisser entrant"
L["Slide Out"] = "Glisser sortant"
L["Sort"] = "Trier"
L["Sound"] = "Son"
L["Sound Channel"] = "Canal sonore"
L["Sound File Path"] = "Chemin fichier son"
L["Space"] = "Espacer"
L["Space Horizontally"] = "Espacer horizontalement"
L["Space Vertically"] = "Espacer verticalement"
L["Spell ID"] = "ID de sort"
L["Spell ID dialog"] = [=[Vous avez spécifié une aura par |cFFFF0000ID de sort|r.
Par défaut, |cFF8800FFWeakAuras|r ne peut distinguer entre des auras de même nom mais d'|cFFFF0000ID de sort|r différents.
Cependant, si l'option Scan Complet est activée, |cFF8800FFWeakAuras|r peut chercher des |cFFFF0000ID de sorts|r spécifiques.
Voulez-vous activer le Scan Complet pour chercher cet |cFFFF0000ID de sort|r ?]=]
L["Stack Count"] = "Nombre de Piles"
L["Stack Count Position"] = "Position Nombre de Piles"
L["Stack Info"] = "Info de Piles"
L["Stacks Settings"] = "Réglages de Piles"
L["Stagger"] = "Report"
L["Stance (Warrior)"] = "Posture"
L["Start"] = "Début"
L["Stealable"] = "Volable"
L["Stealthed"] = "Furtif"
L["Sticky Duration"] = "Durée épinglée"
L["Temporary Group"] = "Groupe temporaire"
L["Text"] = "Texte"
L["Text Color"] = "Couleur Texte"
L["Text Position"] = "Position Texte"
L["Text Settings"] = "Réglages de Texte"
L["Texture"] = "Texture"
L["The children of this group have different display types, so their display options cannot be set as a group."] = "Les enfants de ce groupe ont différent types de graphiques, leurs options de graphique ne peuvent donc pas être changées en groupe."
L["The duration of the animation in seconds."] = "La durée de l'animation en secondes."
L["The type of trigger"] = "Le type de déclencheur"
L["This condition will not be tested"] = "Cette condition ne sera pas évaluée"
L["This display is currently loaded"] = "Ce graphique est actuellement chargé"
L["This display is not currently loaded"] = "Ce graphique n'est pas actuellement chargé"
L["This display will only show when |cFF00FF00%s"] = "Ce graphique ne s'affichera que quand |cFF00FF00%s"
L["This display will only show when |cFFFF0000 Not %s"] = "Ce graphique ne s'affichera que quand |cFFFF0000 Pas %s"
L["This region of type \"%s\" has no configuration options."] = "Cette région de type \"%s\" n'a pas d'options de configuration."
L["Time in"] = "Temps entrant"
L["Timer"] = "Chrono"
L["Timer Settings"] = "Réglages de Chrono"
L["Toggle the visibility of all loaded displays"] = "Change la visibilité de tous les graphiques chargés"
L["Toggle the visibility of all non-loaded displays"] = "Change la visibilité de tous les graphiques non-chargés"
L["Toggle the visibility of this display"] = "Change la visibilité de ce graphique"
L["to group's"] = "au groupe..."
L["Tooltip"] = "Infobulle"
L["Tooltip on Mouseover"] = "Infobulle à la souris"
L["Top Text"] = "Texte du Haut"
L["to screen's"] = "à l'écran..."
L["Total Time Precision"] = "Précision Temps total"
L["Tracking"] = "Suivi"
L["Travel"] = "Voyage"
L["Trigger"] = "Déclencheur"
L["Trigger %d"] = "Déclencheur %d"
L["Triggers"] = "Déclencheurs"
L["Type"] = "Type"
L["Ungroup"] = "Dégrouper"
L["Unholy"] = "Impie"
L["Unit Exists"] = "L'unité existe"
L["Unlike the start or finish animations, the main animation will loop over and over until the display is hidden."] = "Contrairement aux animations de début et de fin, l'animation principale bouclera tant que le graphique est visible."
L["Unstealthed"] = "Fin de furtivité"
L["Update Custom Text On..."] = "Mettre à jour Texte Perso sur..."
L["Use Full Scan (High CPU)"] = "Utiliser Scan Complet (CPU élevé)"
L["Use tooltip \"size\" instead of stacks"] = "Utiliser la \"taille\" de l'infobulle plutôt que la pile"
L["Vertical Align"] = "Aligner verticalement"
L["View"] = "Vue"
L["Width"] = "Largeur"
L["X Offset"] = "Décalage X"
L["X Scale"] = "Echelle X"
L["Yes"] = "Oui"
L["Y Offset"] = "Décalage Y"
L["Y Scale"] = "Echelle Y"
L["Z Offset"] = "Décalage Z"
L["Zoom"] = "Zoom"
L["Zoom In"] = "Zoom entrant"
L["Zoom Out"] = "Zoom sortant"
|
--[=[
@c Channel x Snowflake
@d Abstract base class that defines the base methods and properties for all
Discord channel types.
]=]
local Snowflake = require('containers/abstract/Snowflake')
local enums = require('enums')
local format = string.format
local channelType = enums.channelType
local Channel, get = require('class')('Channel', Snowflake)
function Channel:__init(data, parent)
Snowflake.__init(self, data, parent)
end
function Channel:_modify(payload)
local data, err = self.client._api:modifyChannel(self._id, payload)
if data then
self:_load(data)
return true
else
return false, err
end
end
function Channel:_delete()
local data, err = self.client._api:deleteChannel(self._id)
if data then
local cache
local t = self._type
if t == channelType.text then
cache = self._parent._text_channels
elseif t == channelType.private then
cache = self._parent._private_channels
elseif t == channelType.group then
cache = self._parent._group_channels
elseif t == channelType.voice then
cache = self._parent._voice_channels
elseif t == channelType.category then
cache = self._parent._categories
end
if cache then
cache:_delete(self._id)
end
return true
else
return false, err
end
end
--[=[@p type number The channel type. See the `channelType` enumeration for a
human-readable representation.]=]
function get.type(self)
return self._type
end
--[=[@p mentionString string A string that, when included in a message content,
may resolve as a link to a channel in the official Discord client.]=]
function get.mentionString(self)
return format('<#%s>', self._id)
end
return Channel
|
-- that's pretty empty, but I did not know that beforehand
local LabelStyle = {
}
return LabelStyle |
return function()
vim.api.nvim_command('augroup user_plugin_cursorword')
vim.api.nvim_command('autocmd!')
vim.api.nvim_command('autocmd FileType NvimTree,lspsagafinder,dashboard,vista let b:cursorword = 0')
vim.api.nvim_command('autocmd WinEnter * if &diff || &pvw | let b:cursorword = 0 | endif')
vim.api.nvim_command('autocmd InsertEnter * let b:cursorword = 0')
vim.api.nvim_command('autocmd InsertLeave * let b:cursorword = 1')
vim.api.nvim_command('augroup END')
end
|
local active_list = vim.NIL;
local list_types = {
location = 'location',
quickfix = 'quickfix'
}
local function toggle_location_list()
if (active_list == list_types.location) then
vim.cmd('lclose');
active_list = vim.NIL;
else
if active_list == list_types.quickfix then
vim.cmd('cclose');
end
if pcall(vim.cmd, 'lopen') then
active_list = list_types.location;
else
print("No location list to show");
active_list = vim.NIL;
end
end
end
local function toggle_quickfix_list()
if (active_list == list_types.quickfix) then
vim.cmd('cclose');
active_list = vim.NIL;
else
if active_list == list_types.location then
vim.cmd('lclose');
end
vim.cmd('copen');
active_list = list_types.quickfix
end
end
local function toggle(global)
if global == 1 then
toggle_quickfix_list();
else
toggle_location_list();
end
end
return {
toggle = toggle
}
|
----
-- Handles thread functionality.
--
-- **Source Code:** [https://github.com/dstmodders/dst-mod-sdk](https://github.com/dstmodders/dst-mod-sdk)
--
-- @module SDK.Thread
-- @see SDK
--
-- @author [Depressed DST Modders](https://github.com/dstmodders)
-- @copyright 2020
-- @license MIT
-- @release 0.1
----
local Thread = {}
local SDK
--- Starts a new thread.
--
-- Just a convenience wrapper for the `StartThread`.
--
-- @tparam string id Thread ID
-- @tparam function fn Thread function
-- @tparam[opt] function whl_fn While function
-- @tparam[opt] function init_fn Initialization function
-- @tparam[opt] function term_fn Termination function
-- @treturn table
function Thread.Start(id, fn, whl_fn, init_fn, term_fn)
whl_fn = whl_fn ~= nil and whl_fn or function()
return true
end
return StartThread(function()
SDK.Debug.String("Thread started")
if init_fn then
init_fn()
end
while whl_fn() do
fn()
end
if term_fn then
term_fn()
end
Thread.Clear()
end, id)
end
--- Clears a thread.
-- @tparam table thread Thread
function Thread.Clear(thread)
local task = scheduler:GetCurrentTask()
if thread or task then
if thread and not task then
SDK.Debug.String("[" .. thread.id .. "]", "Thread cleared")
else
SDK.Debug.String("Thread cleared")
end
thread = thread ~= nil and thread or task
KillThreadsWithID(thread.id)
thread:SetList(nil)
end
end
--- Lifecycle
-- @section lifecycle
--- Initializes.
-- @tparam SDK sdk
-- @treturn SDK.Thread
function Thread._DoInit(sdk)
SDK = sdk
return SDK._DoInitModule(SDK, Thread, "Thread")
end
return Thread
|
require 'nn'
local Quantization, Parent = torch.class('nn.Quantization', 'nn.Module')
function Quantization:__init()
Parent.__init(self)
end
function Quantization:updateOutput(input)
-- Assumes input is 4D (nbatch, nfeat, h, w) or 3D (nfeat, h, w). If 4D,
-- all inputs in the batch get the same crop.
local nDim = input:dim()
self.output = input:clone():mul(256):int():typeAs(input):mul(1.0/256)
return self.output
end
function Quantization:updateGradInput(input, gradOutput)
error('backprop undefined for quantization')
end |
local rsautils = require('rsautils')
local src_str = "my name is ecofast小0胡!!"
print(src_str)
local cipherLen, cipher = rsautils.rsa_encrypt(src_str)
if cipherLen ~= -1 then
local plain = rsautils.rsa_decrypt(cipherLen, cipher)
print("src text:", plain)
print("=========================")
local txt2 = rsautils.rsa_decrypt(128, "aeMIl3wyPP/DIJLudq49k1YeK9o6QhrScyjy2JHcJ7CmFOpQAmbwLxOe/rWigSYeWbAMUw2MB1KTIsool9zEuOSaoiZtgjfpDvf5g/MZUjPAmDofKVutG9xJNonVoK6usHKVcR7wozq/tJ8h/CUWyKGHnLgkxvU3ObbhLPm/wwI=")
print("src text2:", txt2)
end |
--- === hs._asm.axuielement ===
---
--- This module allows you to access the accessibility objects of running applications, their windows, menus, and other user interface elements that support the OS X accessibility API.
---
--- This is very much a work in progress, so bugs and comments are welcome.
---
--- This module works through the use of axuielementObjects, which is the Hammerspoon representation for an accessibility object. An accessibility object represents any object or component of an OS X application which can be manipulated through the OS X Accessibility API -- it can be an application, a window, a button, selected text, etc. As such, it can only support those features and objects within an application that the application developers make available through the Accessibility API.
---
--- The basic methods available to determine what attributes and actions are available for a given object are described in this reference documentation. In addition, the module will dynamically add methods for the attributes and actions appropriate to the object, but these will differ between object roles and applications -- again we are limited by what the target application developers provide us.
---
--- The dynamically generated methods will follow one of the following templates:
--- * `object:*attribute*()` - this will return the value for the specified attribute (see [hs._asm.axuielement:attributeValue](#attributeValue) for the generic function this is based on).
--- * `object:set*attribute*(value)` - this will set the specified attribute to the given value (see [hs._asm.axuielement:setAttributeValue](#setAttributeValue) for the generic function this is based on).
--- * `object:do*action*()` - this request that the specified action is performed by the object (see [hs._asm.axuielement:performAction](#performAction) for the generic function this is based on).
---
--- Where *action* and *attribute* can be the formal Accessibility version of the attribute or action name (a string usually prefixed with "AX") or without the "AX" prefix. When the prefix is left off, the first letter of the action or attribute can be uppercase or lowercase.
---
--- The module also dynamically supports treating the axuielementObject useradata as an array, to access it's children (i.e. `#object` will return a number, indicating the number of direct children the object has, and `object[1]` is equivalent to `object:children()[1]` or, more formally, `object:attributeValue("AXChildren")[1]`).
---
--- You can also treat the axuielementObject userdata as a table of key-value pairs to generate a list of the dynamically generated functions: `for k, v in pairs(object) do print(k, v) end` (this is essentially what [hs._asm.axuielement:dynamicMethods](#dynamicMethods) does).
---
---
--- Limited support for parameterized attributes is provided, but is not yet complete. This is expected to see updates in the future.
local USERDATA_TAG = "hs._asm.axuielement"
if not hs.accessibilityState(true) then
hs.luaSkinLog.ef("%s - module requires accessibility to be enabled; fix in SystemPreferences -> Privacy & Security and restart Hammerspoon", USERDATA_TAG)
return nil
end
local module = require(USERDATA_TAG..".internal")
local basePath = package.searchpath(USERDATA_TAG, package.path)
if basePath then
basePath = basePath:match("^(.+)/init.lua$")
if require"hs.fs".attributes(basePath .. "/docs.json") then
require"hs.doc".registerJSONFile(basePath .. "/docs.json")
end
end
local log = require("hs.logger").new(USERDATA_TAG, require"hs.settings".get(USERDATA_TAG .. ".logLevel") or "warning")
module.log = log
local fnutils = require("hs.fnutils")
local inspect = require("hs.inspect")
require("hs.styledtext")
local objectMT = hs.getObjectMetatable(USERDATA_TAG)
local parentLabels = { module.attributes.general.parent, module.attributes.general.topLevelUIElement }
-- private variables and methods -----------------------------------------
-- Public interface ------------------------------------------------------
module.roles = ls.makeConstantsTable(module.roles)
module.subroles = ls.makeConstantsTable(module.subroles)
module.parameterizedAttributes = ls.makeConstantsTable(module.parameterizedAttributes)
module.actions = ls.makeConstantsTable(module.actions)
module.attributes = ls.makeConstantsTable(module.attributes)
module.directions = ls.makeConstantsTable(module.directions)
module.observer.notifications = ls.makeConstantsTable(module.observer.notifications)
--- hs._asm.axuielement.systemElementAtPosition(x, y | { x, y }) -> axuielementObject
--- Constructor
--- Returns the accessibility object at the specified position in top-left relative screen coordinates.
---
--- Parameters:
--- * `x`, `y` - the x and y coordinates of the screen location to test, provided as separate parameters
--- * `{ x, y }` - the x and y coordinates of the screen location to test, provided as a point-table, like the one returned by `hs.mouse.getAbsolutePosition`.
---
--- Returns:
--- * an axuielementObject for the object at the specified coordinates, or nil if no object could be identified.
---
--- Notes:
--- * See also [hs._asm.axuielement:elementAtPosition](#elementAtPosition) -- this function is a shortcut for `hs._asm.axuielement.systemWideElement():elementAtPosition(...)`.
---
--- * This function does hit-testing based on window z-order (that is, layering). If one window is on top of another window, the returned accessibility object comes from whichever window is topmost at the specified location.
module.systemElementAtPosition = function(...)
return module.systemWideElement():elementAtPosition(...)
end
-- build up the "correct" object metatable methods
objectMT.__index = function(self, _)
if type(_) == "string" then
-- take care of the internally defined items first so we can get out of here quickly if its one of them
if objectMT[_] then return objectMT[_] end
-- Now for the dynamically generated methods...
local matchName = _:match("^set(.+)$")
if not matchName then matchName = _:match("^do(.+)$") end
if not matchName then matchName = _:match("^(.+)WithParameter$") end
if not matchName then matchName = _ end
local formalName = matchName:match("^AX[%w%d_]+$") and matchName or "AX"..matchName:sub(1,1):upper()..matchName:sub(2)
-- check for setters
if _:match("^set%u") then
-- check attributes
for i, v in ipairs(objectMT.attributeNames(self) or {}) do
if v == formalName and objectMT.isAttributeSettable(self, formalName) then
return function(self, ...) return objectMT.setAttributeValue(self, formalName, ...) end
end
end
-- check for doers
elseif _:match("^do%u") then
-- check actions
for i, v in ipairs(objectMT.actionNames(self) or {}) do
if v == formalName then
return function(self, ...) return objectMT.performAction(self, formalName, ...) end
end
end
-- getter or bust
else
-- check attributes
for i, v in ipairs(objectMT.attributeNames(self) or {}) do
if v == formalName then
return function(self, ...) return objectMT.attributeValue(self, formalName, ...) end
end
end
-- check paramaterizedAttributes
for i, v in ipairs(objectMT.parameterizedAttributeNames(self) or {}) do
if v == formalName then
return function(self, ...) return objectMT.parameterizedAttributeValue(self, formalName, ...) end
end
end
end
-- guess it doesn't exist
return nil
elseif type(_) == "number" then
local children = objectMT.attributeValue(self, "AXChildren")
if children then
return children[_]
else
return nil
end
else
return nil
end
end
objectMT.__call = function(_, cmd, ...)
local fn = objectMT.__index(_, cmd)
if fn and type(fn) == "function" then
return fn(_, ...)
elseif fn then
return fn
elseif cmd:match("^do%u") then
error(tostring(cmd) .. " is not a recognized action", 2)
elseif cmd:match("^set%u") then
error(tostring(cmd) .. " is not a recognized attribute", 2)
else
return nil
end
end
objectMT.__pairs = function(_)
local keys = {}
-- getters and setters for attributeNames
for i, v in ipairs(objectMT.attributeNames(_) or {}) do
local partialName = v:match("^AX(.*)")
keys[partialName:sub(1,1):lower() .. partialName:sub(2)] = true
if objectMT.isAttributeSettable(_, v) then
keys["set" .. partialName] = true
end
end
-- getters for paramaterizedAttributes
for i, v in ipairs(objectMT.parameterizedAttributeNames(_) or {}) do
local partialName = v:match("^AX(.*)")
keys[partialName:sub(1,1):lower() .. partialName:sub(2) .. "WithParameter"] = true
end
-- doers for actionNames
for i, v in ipairs(objectMT.actionNames(_) or {}) do
local partialName = v:match("^AX(.*)")
keys["do" .. partialName] = true
end
return function(_, k)
local v
k, v = next(keys, k)
if k then v = _[k] end
return k, v
end, _, nil
end
objectMT.__len = function(self)
local children = objectMT.attributeValue(self, "AXChildren")
if children then
return #children
else
return 0
end
end
--- hs._asm.axuielement:dynamicMethods([keyValueTable]) -> table
--- Method
--- Returns a list of the dynamic methods (short cuts) created by this module for the object
---
--- Parameters:
--- * `keyValueTable` - an optional boolean, default false, indicating whether or not the result should be an array or a table of key-value pairs.
---
--- Returns:
--- * If `keyValueTable` is true, this method returns a table of key-value pairs with each key being the name of a dynamically generated method, and the value being the corresponding function. Otherwise, this method returns an array of the dynamically generated method names.
---
--- Notes:
--- * the dynamically generated methods are described more fully in the reference documentation header, but basically provide shortcuts for getting and setting attribute values as well as perform actions supported by the Accessibility object the axuielementObject represents.
objectMT.dynamicMethods = function(self, asKV)
local results = {}
for k, v in pairs(self) do
if asKV then
results[k] = v
else
table.insert(results, k)
end
end
if not asKV then table.sort(results) end
return ls.makeConstantsTable(results)
end
--- hs._asm.axuielement:path() -> table
--- Method
--- Returns a table of axuielements tracing this object through its parent objects to the root for this element, most likely an application object or the system wide object.
---
--- Parameters:
--- * None
---
--- Returns:
--- * a table containing this object and 0 or more parent objects representing the path from the root object to this element.
---
--- Notes:
--- * this object will always exist as the last element in the table (e.g. at `table[#table]`) with its most imemdiate parent at `#table - 1`, etc. until the rootmost object for this element is reached at index position 1.
---
--- * an axuielement object representing an application or the system wide object is its own rootmost object and will return a table containing only itself (i.e. `#table` will equal 1)
objectMT.path = function(self)
local results, current = { self }, self
while current:attributeValue("AXParent") do
current = current("parent")
table.insert(results, 1, current)
end
return results
end
local buildTreeHamster
buildTreeHamster = function(self, prams, depth, withParents, seen)
if prams.cancel then return prams.msg end
coroutine.applicationYield()
if depth == 0 then return "** max depth exceeded" end
seen = seen or {}
if getmetatable(self) == objectMT then
local seenBefore = fnutils.find(seen, function(_) return _._element == self end)
if seenBefore then return seenBefore end
local thisObject = self:allAttributeValues() or {}
thisObject._element = self
thisObject._actions = self:actionNames()
thisObject._attributes = self:attributeNames()
thisObject._parameterizedAttributes = self:parameterizedAttributeNames()
seen[self] = thisObject
for k, v in pairs(thisObject) do
if k ~= "_element" then
if (type(v) == "table" and #v > 0) then
thisObject[k] = buildTreeHamster(v, prams, depth, withParents, seen)
elseif getmetatable(v) == objectMT then
if not withParents and fnutils.contains(parentLabels, k) then
-- not diving into parents, but lets see if we've seen them already...
thisObject[k] = fnutils.find(seen, function(_) return _._element == v end) or v
else
thisObject[k] = buildTreeHamster(v, prams, depth - 1, withParents, seen)
end
end
end
end
return thisObject
elseif type(self) == "table" then
local results = {}
for i,v in ipairs(self) do
if (type(v) == "table" and #v > 0) or getmetatable(v) == objectMT then
results[i] = buildTreeHamster(v, prams, depth - 1, withParents, seen)
else
results[i] = v
end
end
return results
end
return self
end
--- hs._asm.axuielement:buildTree(callback, [depth], [withParents]) -> buildTreeObject
--- Method
--- Captures all of the available information for the accessibility object and its children and returns it in a table for inspection.
---
--- Parameters:
--- * `callback` - a required function which should expect two arguments: a `msg` string specifying how the search ended, and a table contiaining the recorded information. `msg` will be "completed" when the search has completed normally (or reached the specified depth) and will contain a string starting with "**" if it terminates early for some reason (see Returns: section)
--- * `depth` - an optional integer, default `math.huge`, specifying the maximum depth from the intial accessibility object that should be visited to identify child elements and their attributes.
--- * `withParents` - an optional boolean, default false, specifying whether or not an element's (or child's) attributes for `AXParent` and `AXTopLevelUIElement` should also be visited when identifying additional elements to include in the results table.
---
--- Returns:
--- * a `buildTreeObject` which contains metamethods allowing you to check to see if the build process has completed and cancel it early if desired:
--- * `buildTreeObject:isRunning()` - will return true if the traversal is still ongoing, or false if it has completed or been cancelled
--- * `buildTreeObject:cancel()` - will cancel the currently running search and invoke the callback with the partial results already collected. The `msg` parameter for the calback will be "** cancelled".
---
--- Notes:
--- * this method utilizes coroutines to keep Hammerspoon responsive, but can be slow to complete if you do not specifiy a depth or start from an element that has a lot of children or has children with many elements (e.g. the application element for a web browser).
---
--- * The results of this method are not generally intended to be used in production programs; it is organized more for exploratory purposes when trying to understand how elements are related within a given application or to determine what elements might be worth targetting with more specific queries.
objectMT.buildTree = function(self, callback, depth, withParents)
assert(
type(callback) == "function" or (getmetatable(callback) or {}).__call,
"buildTree requires a callback function; element:buildTree(callback, [depth], [withParents])"
)
if type(depth) == "boolean" and type(withParents) == "nil" then
depth, withParents = nil, depth
end
depth = depth or math.huge
local prams = {
cancel = false,
callback = callback, -- may add partial updates at some point
}
coroutine.wrap(function()
local results = buildTreeHamster(self, prams, depth, withParents)
callback(prams.msg or "completed", results)
end)()
return setmetatable({}, {
__index = {
cancel = function(_, msg)
prams.cancel = true
prams.msg = msg or "** cancelled"
end,
isRunning = function(_)
return not prams.msg
end,
},
__tostring = function(_)
return USERDATA_TAG .. ":buildTree " .. tostring(self):match(USERDATA_TAG .. ": (.+)$")
end,
-- __gc = function(_)
-- _:cancel("** gc on buildTree object")
-- end,
})
end
-- Return Module Object --------------------------------------------------
if module.types then module.types = ls.makeConstantsTable(module.types) end
return module
|
local lg = love.graphics
fixcolor = {}
function fixcolor:setColor(r, g, b, a)
a = a or 255;
if type(r) == "table" then
lg.setColor(r[1] / 255, r[2] / 255, r[3] / 255, r[4] / 255)
else
lg.setColor(r / 255, g / 255, b / 255, a / 255)
end
end |
--[[
Copyright (c) 2014, Robert 'Bobby' Zenz
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--]]
--- Various functions related to nodes.
nodeutil = {}
--- Gets the content id of the given node.
--
-- @param node The node, can either be an id, a name or a table with the name.
-- @return The content id of the given node.
function nodeutil.get_id(node)
if type(node) == "string" then
return minetest.get_content_id(node)
elseif type(node) == "table" then
return minetest.get_content_id(node.name)
end
return node
end
--- Gets the name of given node.
--
-- @param node The node, can either be an id, a name or a table with the name.
-- @return The name of the given node.
function nodeutil.get_name(node)
if type(node) == "number" then
return minetest.get_name_from_content_id(node)
elseif type(node) == "table" then
return node.name
end
return node
end
--- Checks if the given node has the given group.
--
-- @param node The node to check.
-- @param group_name The name of the group.
-- @return true if the node has the given group.
function nodeutil.has_group(node, group_name)
local node_name = nodeutil.get_name(node)
return minetest.get_item_group(node_name, group_name) > 0
end
--- Checks if the given node is walkable.
--
-- @param node The node to check, can either be an id, a name or a table with
-- the name.
-- @return true if the given node is walkable.
function nodeutil.is_walkable(node)
local node_name = nodeutil.get_name(node)
local node_definition = minetest.registered_nodes[node_name]
if node_definition ~= nil then
-- Test against false needed in case that walkable is not set,
-- as it defaults to true.
return node_definition.walkable ~= false
end
-- The node does not exist, sad.
return false
end
--- Iterates over the surroundings of the given position and invokes
-- the callback for every node in the surroundings.
--
-- For example if you want to iterate over the direct neighbourse in all
-- dimensions, you'd do the following:
--
-- nodeutil.surroundings(pos, -1, 1, -1, 1, -1, 1, callback)
--
-- @param pos The position that is the center.
-- @param x_begin The modifier for the beginning in the x dimension.
-- @param x_end The modifier for the end in the x dimension.
-- @param z_begin The modifier for the beginning in the z dimension.
-- @param z_end The modifier for the end in the z dimension.
-- @param y_begin The modifier for the beginning in the y dimension.
-- @param y_end The modifier for the end in the y dimension.
-- @param callback The callback to invoke for every surrounding node. can
-- return true if iterating over the surroundings should be
-- stopped.
-- @return true if the iterating over the surroundings has been stopped by
-- a callback.
function nodeutil.surroundings(pos, x_begin, x_end, z_begin, z_end, y_begin, y_end, callback)
for x = pos.x + x_begin, pos.x + x_end, 1 do
for z = pos.z + z_begin, pos.z + z_end, 1 do
for y = pos.y + y_begin, pos.y + y_end, 1 do
if x ~= pos.x or z ~= pos.z or y ~= pos.y then
local current_pos = {
x = x,
y = y,
z = z
}
if callback(current_pos, minetest.get_node(current_pos)) then
return true
end
end
end
end
end
return false
end
|
slot0 = class("ChallengeMainMediator", import("..base.ContextMediator"))
slot0.ON_COMMIT_FLEET = "ChallengeMainMediator:ON_COMMIT_FLEET"
slot0.ON_FLEET_SHIPINFO = "ChallengeMainMediator:ON_FLEET_SHIPINFO"
slot0.ON_PRECOMBAT = "ChallengeMainMediator:ON_PRECOMBAT"
slot0.ON_SELECT_ELITE_COMMANDER = "ChallengeMainMediator:ON_SELECT_ELITE_COMMANDER"
slot0.ON_OPEN_RANK = "ChallengeMainMediator:ON_OPEN_RANK"
slot0.COMMANDER_FORMATION_OP = "ChallengeMainMediator:COMMANDER_FORMATION_OP"
slot0.ON_COMMANDER_SKILL = "ChallengeMainMediator:ON_COMMANDER_SKILL"
slot0.register = function (slot0)
slot3 = getProxy(ChallengeProxy)
slot0:bind(slot0.ON_OPEN_RANK, function ()
slot0:sendNotification(GAME.GO_SCENE, SCENE.BILLBOARD, {
page = PowerRank.TYPE_CHALLENGE
})
end)
slot0.bind(slot0, ChallengeConst.CLICK_GET_AWARD_BTN, function (slot0, slot1)
slot0:sendNotification(GAME.SUBMIT_TASK, slot1)
end)
slot0.bind(slot0, ChallengeConst.RESET_DATA_EVENT, function (slot0, slot1, slot2)
slot0:sendNotification(GAME.CHALLENGE2_RESET, {
mode = slot1,
isInfiniteSeasonClear = slot2
})
end)
slot0.bind(slot0, ActivityFleetPanel.ON_OPEN_DOCK, function (slot0, slot1)
slot2 = slot1.shipType
slot8 = getProxy(BayProxy).getRawData(slot7)
slot0.contextData.editFleet = true
slot16.onShip, slot16.confirmSelect, slot16.onSelected = slot0:getDockCallbackFuncs(slot5, slot4, slot3, slot6)
slot0:sendNotification(GAME.GO_SCENE, SCENE.DOCKYARD, {
selectedMax = 1,
useBlackBlock = true,
selectedMin = 0,
skipSelect = true,
leastLimitMsg = i18n("ship_formationMediator_leastLimit"),
quitTeam = slot1.shipVO ~= nil,
teamFilter = slot6,
leftTopInfo = i18n("word_formation"),
onShip = slot9,
confirmSelect = slot10,
onSelected = slot11,
hideTagFlags = setmetatable({
inActivity = slot1.id
}, {
__index = ShipStatus.TAG_HIDE_CHALLENGE
}),
otherSelectedIds = slot5,
ignoredIds = pg.ShipFlagMgr.GetInstance():FilterShips({
isActivityNpc = true
})
})
end)
slot0.bind(slot0, slot0.ON_COMMIT_FLEET, function ()
slot0:commitActivityFleet(slot1.id)
end)
slot0.bind(slot0, slot0.ON_FLEET_SHIPINFO, function (slot0, slot1)
slot0:sendNotification(GAME.GO_SCENE, SCENE.SHIPINFO, {
shipId = slot1.shipId,
shipVOs = slot1.shipVOs
})
slot0.contextData.editFleet = true
end)
slot0.bind(slot0, ActivityFleetPanel.ON_FLEET_RECOMMEND, function (slot0, slot1)
slot0:recommendActivityFleet(slot1.id, slot1)
slot3.viewComponent:setFleet(slot0.recommendActivityFleet:getActivityFleets()[slot1.id])
slot3.viewComponent:updateEditPanel()
end)
slot0.bind(slot0, ActivityFleetPanel.ON_FLEET_CLEAR, function (slot0, slot1)
slot2 = slot0:getActivityFleets()
slot2[slot1.id][slot1].clearFleet(slot4)
slot0:updateActivityFleet(slot1.id, slot1, slot2[slot1.id][slot1])
slot2.viewComponent:setFleet(slot2[slot1.id])
slot2.viewComponent:updateEditPanel()
end)
slot0.bind(slot0, slot0.COMMANDER_FORMATION_OP, function (slot0, slot1)
slot0:sendNotification(GAME.COMMANDER_FORMATION_OP, {
data = slot1
})
end)
slot0.bind(slot0, slot0.ON_COMMANDER_SKILL, function (slot0, slot1)
slot0:addSubLayers(Context.New({
mediator = CommanderSkillMediator,
viewComponent = CommanderSkillLayer,
data = {
skill = slot1
}
}))
end)
slot0.bind(slot0, slot0.ON_SELECT_ELITE_COMMANDER, function (slot0, slot1, slot2)
slot2:sendNotification(GAME.GO_SCENE, SCENE.COMMANDROOM, {
maxCount = 1,
mode = CommandRoomScene.MODE_SELECT,
activeCommander = slot0:getActivityFleets()[slot1.id][slot1].getCommanders(slot4)[slot2],
ignoredIds = {},
fleetType = CommandRoomScene.FLEET_TYPE_CHALLENGE,
onCommander = function (slot0)
return true
end,
onSelected = function (slot0, slot1)
slot4 = getProxy(CommanderProxy).getCommanderById(slot3, slot2)
for slot8, slot9 in pairs(slot0) do
if slot8 == slot1 then
for slot13, slot14 in pairs(slot2) do
if slot14.groupId == slot4.groupId and slot13 ~= slot3 then
pg.TipsMgr.GetInstance():ShowTips(i18n("commander_can_not_select_same_group"))
return
end
end
else
for slot14, slot15 in pairs(slot10) do
if slot2 == slot15.id then
pg.TipsMgr.GetInstance():ShowTips(i18n("commander_is_in_fleet_already"))
return
end
end
end
end
slot4:updateCommanderByPos(slot3, slot4)
slot4.updateCommanderByPos:updateActivityFleet(slot6.id, slot1, slot4)
slot1()
end,
onQuit = function (slot0)
slot0:updateCommanderByPos(slot0.updateCommanderByPos, nil)
slot0:updateActivityFleet(slot0.updateCommanderByPos.id, nil, slot0)
slot0()
end
})
slot2.contextData.editFleet = true
end)
slot0.bind(slot0, slot0.ON_PRECOMBAT, function (slot0, slot1)
if slot0:checkActivityFleet(slot1.id) ~= true then
pg.TipsMgr.GetInstance():ShowTips(i18n("elite_disable_no_fleet"))
return
end
if slot0:getActivityFleets()[slot1.id][slot1 + 1].isLegalToFight(slot4) == TeamType.Vanguard then
pg.TipsMgr.GetInstance():ShowTips(i18n("ship_vo_vanguardFleet_must_hasShip"))
return
elseif slot5 == TeamType.Main then
pg.TipsMgr.GetInstance():ShowTips(i18n("ship_vo_mainFleet_must_hasShip"))
return
end
slot2.viewComponent:hideFleetEdit()
if not slot3:getUserChallengeInfo(slot1) then
slot2:sendNotification(GAME.CHALLENGE2_INITIAL, {
mode = slot1
})
return
end
slot2:addSubLayers(Context.New({
mediator = ChallengePreCombatMediator,
viewComponent = ChallengePreCombatLayer,
data = {
system = SYSTEM_CHALLENGE,
actID = slot1.id,
mode = slot1,
func = function ()
slot0:tryBattle()
end
}
}))
end)
slot0.viewComponent:setFleet(slot6)
slot0.viewComponent:setCommanderPrefabs(getProxy(CommanderProxy):getPrefabFleet())
end
slot0.listNotificationInterests = function (slot0)
return {
GAME.CHALLENGE2_INITIAL_DONE,
GAME.CHALLENGE2_RESET_DONE,
GAME.CHALLENGE2_INFO_DONE,
GAME.SUBMIT_TASK_DONE,
CommanderProxy.PREFAB_FLEET_UPDATE,
GAME.COMMANDER_ACTIVITY_FORMATION_OP_DONE
}
end
slot0.handleNotification = function (slot0, slot1)
slot3 = slot1:getBody()
slot4 = getProxy(ChallengeProxy)
slot5 = getProxy(ActivityProxy)
slot6 = getProxy(FleetProxy)
if slot1:getName() == GAME.CHALLENGE2_INITIAL_DONE then
slot8 = slot4:getUserChallengeInfo(slot7)
slot0:addSubLayers(Context.New({
mediator = ChallengePreCombatMediator,
viewComponent = ChallengePreCombatLayer,
data = {
system = SYSTEM_CHALLENGE,
actID = slot5:getActivityByType(ActivityConst.ACTIVITY_TYPE_CHALLENGE).id,
mode = slot3.mode,
func = function ()
slot0:tryBattle()
end
}
}))
slot0.viewComponent.updateData(slot10)
slot0.viewComponent:updatePaintingList()
slot0.viewComponent:updateRoundText()
slot0.viewComponent:updateSlider()
slot0.viewComponent:updateFuncBtns()
elseif slot2 == GAME.CHALLENGE2_RESET_DONE then
if slot0.viewComponent.curMode == ChallengeProxy.MODE_INFINITE and not slot0.viewComponent:isFinishedCasualMode() then
slot4:setCurMode(ChallengeProxy.MODE_CASUAL)
end
slot0.viewComponent:updateData()
slot0.viewComponent:updateGrade(slot4:getChallengeInfo():getGradeList())
slot0.viewComponent:updateSwitchModBtn()
slot0.viewComponent:updatePaintingList()
slot0.viewComponent:updateRoundText()
slot0.viewComponent:updateSlider()
slot0.viewComponent:updateFuncBtns()
elseif slot2 == GAME.CHALLENGE2_INFO_DONE then
if slot0.viewComponent.curMode == ChallengeProxy.MODE_INFINITE and not slot0.viewComponent:isFinishedCasualMode() then
slot4:setCurMode(ChallengeProxy.MODE_CASUAL)
end
slot0.viewComponent:updateData()
slot0.viewComponent:updateGrade(slot4:getChallengeInfo():getGradeList())
slot0.viewComponent:updateTimePanel()
slot0.viewComponent:updateSwitchModBtn()
slot0.viewComponent:updatePaintingList()
slot0.viewComponent:updateRoundText()
slot0.viewComponent:updateSlider()
slot0.viewComponent:updateFuncBtns()
elseif slot2 == GAME.SUBMIT_TASK_DONE then
slot0.viewComponent:emit(BaseUI.ON_ACHIEVE, slot3, function ()
slot0.viewComponent:updateAwardPanel()
end)
elseif slot2 == CommanderProxy.PREFAB_FLEET_UPDATE then
slot0.viewComponent:setCommanderPrefabs(getProxy(CommanderProxy).getPrefabFleet(slot7))
slot0.viewComponent:updateCommanderPrefab()
elseif slot2 == GAME.COMMANDER_ACTIVITY_FORMATION_OP_DONE then
slot0.viewComponent:setFleet(slot7)
slot0.viewComponent:updateEditPanel()
slot0.viewComponent:updateCommanderFleet(slot6:getActivityFleets()[slot3.actId][slot3.fleetId])
end
end
slot0.getDockCallbackFuncs = function (slot0, slot1, slot2, slot3, slot4)
slot5 = getProxy(BayProxy)
slot6 = getProxy(FleetProxy)
slot8 = getProxy(ActivityProxy).getActivityByType(slot7, ActivityConst.ACTIVITY_TYPE_CHALLENGE)
function slot9(slot0, slot1)
slot2, slot3 = ShipStatus.ShipStatusCheck("inActivity", slot0, slot1, {
inActivity = slot0.id
})
if not slot2 then
return slot2, slot3
end
for slot7, slot8 in ipairs(slot1) do
if slot0:isSameKind(slot2:getShipById(slot8)) then
return false, i18n("ship_formationMediator_changeNameError_sameShip")
end
end
return true
end
return slot9, function (slot0, slot1, slot2)
slot1()
end, function (slot0)
slot4 = slot1:getActivityFleets()[slot0:getActivityByType(ActivityConst.ACTIVITY_TYPE_CHALLENGE).id][slot2]
if slot1.getActivityFleets()[slot0.getActivityByType(ActivityConst.ACTIVITY_TYPE_CHALLENGE).id] then
slot4:removeShip(slot3)
end
if #slot0 > 0 then
slot4:insertShip(slot4:getShipById(slot0[1]), nil, slot4.insertShip)
end
slot1:updateActivityFleet(slot1.id, slot2, slot4)
end
end
return slot0
|
--- === hs._asm.consolepipe ===
---
--- Tap into Hammerspoon's stderr and stdout streams.
---
--- `stdout` seems to be constantly outputting a stream of characters, but I haven't determined what they represent yet.
---
--- `stderr` contains the messages from Hammerspoon which are sent to the system logs and are traditionally viewed from the Console application.
---
--- Probably not that useful, but interesting none-the-less.
local USERDATA_TAG = "hs._asm.consolepipe"
local module = require(USERDATA_TAG..".internal")
local basePath = package.searchpath(USERDATA_TAG, package.path)
if basePath then
basePath = basePath:match("^(.+)/init.lua$")
if require"hs.fs".attributes(basePath .. "/docs.json") then
require"hs.doc".registerJSONFile(basePath .. "/docs.json")
end
end
-- private variables and methods -----------------------------------------
-- local _kMetaTable = {}
-- -- planning to experiment with using this with responses to functional queries... and I
-- -- don't want to keep loose generated data hanging around
-- _kMetaTable._k = setmetatable({}, {__mode = "k"})
-- _kMetaTable._t = setmetatable({}, {__mode = "k"})
-- _kMetaTable.__index = function(obj, key)
-- if _kMetaTable._k[obj] then
-- if _kMetaTable._k[obj][key] then
-- return _kMetaTable._k[obj][key]
-- else
-- for k,v in pairs(_kMetaTable._k[obj]) do
-- if v == key then return k end
-- end
-- end
-- end
-- return nil
-- end
-- _kMetaTable.__newindex = function(obj, key, value)
-- error("attempt to modify a table of constants",2)
-- return nil
-- end
-- _kMetaTable.__pairs = function(obj) return pairs(_kMetaTable._k[obj]) end
-- _kMetaTable.__len = function(obj) return #_kMetaTable._k[obj] end
-- _kMetaTable.__tostring = function(obj)
-- local result = ""
-- if _kMetaTable._k[obj] then
-- local width = 0
-- for k,v in pairs(_kMetaTable._k[obj]) do width = width < #tostring(k) and #tostring(k) or width end
-- for k,v in require("hs.fnutils").sortByKeys(_kMetaTable._k[obj]) do
-- if _kMetaTable._t[obj] == "table" then
-- result = result..string.format("%-"..tostring(width).."s %s\n", tostring(k),
-- ((type(v) == "table") and "{ table }" or tostring(v)))
-- else
-- result = result..((type(v) == "table") and "{ table }" or tostring(v)).."\n"
-- end
-- end
-- else
-- result = "constants table missing"
-- end
-- return result
-- end
-- _kMetaTable.__metatable = _kMetaTable -- go ahead and look, but don't unset this
--
-- local _makeConstantsTable
-- _makeConstantsTable = function(theTable)
-- if type(theTable) ~= "table" then
-- local dbg = debug.getinfo(2)
-- local msg = dbg.short_src..":"..dbg.currentline..": attempting to make a '"..type(theTable).."' into a constant table"
-- if module.log then module.log.ef(msg) else print(msg) end
-- return theTable
-- end
-- for k,v in pairs(theTable) do
-- if type(v) == "table" then
-- local count = 0
-- for a,b in pairs(v) do count = count + 1 end
-- local results = _makeConstantsTable(v)
-- if #v > 0 and #v == count then
-- _kMetaTable._t[results] = "array"
-- else
-- _kMetaTable._t[results] = "table"
-- end
-- theTable[k] = results
-- end
-- end
-- local results = setmetatable({}, _kMetaTable)
-- _kMetaTable._k[results] = theTable
-- local count = 0
-- for a,b in pairs(theTable) do count = count + 1 end
-- if #theTable > 0 and #theTable == count then
-- _kMetaTable._t[results] = "array"
-- else
-- _kMetaTable._t[results] = "table"
-- end
-- return results
-- end
-- Public interface ------------------------------------------------------
-- Return Module Object --------------------------------------------------
return module
|
local om={}
return om
|
object_mobile_som_som_mustafarian_phantom_bandit = object_mobile_som_shared_som_mustafarian_phantom_bandit:new {
}
ObjectTemplates:addTemplate(object_mobile_som_som_mustafarian_phantom_bandit, "object/mobile/som/som_mustafarian_phantom_bandit.iff")
|
arr = { "monday", "tuesday", "wednesday" }
for i=1,3 do
print (arr[i])
end |
---@class ClassToBeAliased
---@field a string
---@alias MyAlias ClassToBeAliased
---@type MyAlias
local myAlias
---@type ClassToBeAliased
local classToBeAliased
classToBeAliased = myAlias
classToBeAliased = <error descr="Type mismatch. Required: 'ClassToBeAliased' Found: '1'">1</error>
myAlias = classToBeAliased
myAlias = <error descr="Type mismatch. Required: 'ClassToBeAliased' Found: '1'">1</error>
---@alias UnionAlias string|ClassToBeAliased
---@type string
local aString
---@type UnionAlias
local unionAlias
unionAlias = aString
aString = <error descr="Type mismatch. Required: 'string' Found: 'UnionAlias'">unionAlias</error>
unionAlias = classToBeAliased
classToBeAliased = <error descr="Type mismatch. Required: 'ClassToBeAliased' Found: 'UnionAlias'">unionAlias</error>
unionAlias = myAlias
myAlias = <error descr="Type mismatch. Required: 'ClassToBeAliased' Found: 'UnionAlias'">unionAlias</error>
---@alias AliasedFunction fun(a: string): void
---@type AliasedFunction
local aliasedFunction
aliasedFunction(<error descr="Type mismatch. Required: 'string' Found: '1'">1</error>)
aliasedFunction("okay")
---@type fun(a: MyAlias, b: MyAlias): void
local myAliasFun
myAliasFun(classToBeAliased, <error descr="Type mismatch. Required: 'ClassToBeAliased' Found: '1'">1</error>)
myAliasFun(classToBeAliased, classToBeAliased)
---@alias IdentifierString 0
---@alias IdentifierNumber 1
---@type IdentifierString
local STRING = 0
---@type IdentifierNumber
local NUMBER = 1
---@alias Identifier IdentifierString | IdentifierNumber
---@alias StringTupleAlias {[1]: IdentifierString, [2]: string}
---@alias NumberTupleAlias {[1]: IdentifierNumber, [2]: number}
---@alias IdentifiedTuple StringTupleAlias | NumberTupleAlias
---@type IdentifiedTuple
local identifiedTuple
identifiedTuple = {STRING, "a string"}
identifiedTuple = {<error descr="Type mismatch. Required: 'IdentifierString' Found: 'IdentifierNumber', on union candidate { [1]: IdentifierString, [2]: string }">NUMBER</error>, <error descr="Type mismatch. Required: 'number' Found: '\"a string\"', on union candidate { [1]: IdentifierNumber, [2]: number }">"a string"</error>}
identifiedTuple = {<error descr="Type mismatch. Required: 'IdentifierNumber' Found: 'IdentifierString', on union candidate { [1]: IdentifierNumber, [2]: number }">STRING</error>, <error descr="Type mismatch. Required: 'string' Found: '1', on union candidate { [1]: IdentifierString, [2]: string }">1</error>}
identifiedTuple = {NUMBER, 1}
---@type Identifier
local identifier = identifiedTuple[1]
STRING = <error descr="Type mismatch. Required: '0' Found: 'IdentifierNumber | IdentifierString'">identifiedTuple[1]</error>
NUMBER = <error descr="Type mismatch. Required: '1' Found: 'IdentifierNumber | IdentifierString'">identifiedTuple[1]</error>
identifiedTuple[1] = <error descr="Type mismatch. Required: '1' Found: 'IdentifierString', on union candidate { [1]: IdentifierNumber, [2]: number }">STRING</error>
identifiedTuple[1] = <error descr="Type mismatch. Required: '0' Found: 'IdentifierNumber', on union candidate { [1]: IdentifierString, [2]: string }">NUMBER</error>
---@alias NumberArray number[]
---@alias StringArray string[]
---@type NumberArray
local aliasedNumberArray
---@type number[]
local numberArray
---@type StringArray
local aliasedStringArray
aliasedNumberArray = numberArray
numberArray = aliasedNumberArray
aliasedNumberArray = {1, 2, 3}
numberArray = {1, 2, 3}
aliasedNumberArray = <error descr="Type mismatch. Required: 'number[]' Found: 'StringArray'">aliasedStringArray</error>
aliasedStringArray = <error descr="Type mismatch. Required: 'string[]' Found: 'NumberArray'">aliasedNumberArray</error>
---@generic K, V
---@param tab table<K, V>
local function acceptArrayAsGenericTable(tab)
end
---@alias SomeAliasedType number
---@alias SomeAliasedArrayOfAliasedType SomeAliasedType[]
---@type SomeAliasedArrayOfAliasedType
local aliasedArrayOfAliasedType
acceptArrayAsGenericTable({1, 2, 3})
acceptArrayAsGenericTable(aliasedArrayOfAliasedType)
acceptArrayAsGenericTable(<error descr="Type mismatch. Required: 'table<K, V>' Found: '1'">1</error>)
|
include("shared.lua")
include("player_class/player_sslobby.lua")
include("cl_scoreboard.lua")
include("modules/sh_link.lua")
include("modules/cl_link.lua")
include("modules/sh_chairs.lua")
include("modules/cl_chairs.lua")
include("modules/cl_worldpicker.lua")
include("modules/sh_minigame.lua")
include("modules/cl_minigame.lua")
include("modules/cl_worldpanel.lua")
include("modules/sh_leaderboard.lua")
include("modules/cl_leaderboard.lua")
include("modules/sh_sound.lua")
SS.Lobby.ScreenDistance = CreateClientConVar("sslobby_screendistance", "2048", true)
SS.Lobby.MusicVolume = CreateClientConVar("sslobby_musicvolume", "20", true)
---------------------------------------------------------
--
---------------------------------------------------------
function GM:InitPostEntity()
local music = SS.Lobby.Sound.New("lobby_music", LocalPlayer(), "skeyler/lounge/lobby01.mp3", false)
end
---------------------------------------------------------
--
---------------------------------------------------------
function GM:HUDPaint()
self.BaseClass:HUDPaint()
end |
return {[1]={stats={[1]="physical_damage_%_to_add_as_fire"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Extra Fire Damage"}}}},[2]={stats={[1]="physical_damage_%_to_add_as_lightning"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Extra Lightning Damage"}}}},[3]={stats={[1]="physical_damage_%_to_add_as_cold"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Extra Cold Damage"}}}},[4]={stats={[1]="base_movement_velocity_+%"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Quick"}}}},[5]={stats={[1]="maximum_life_+%"},lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="Extra Life"},[2]={limit={[1]={[1]="#",[2]=-1}},text="Reduced Life"}}}},[6]={stats={[1]="physical_damage_reduction_rating_+%"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Armoured"}}}},[7]={stats={[1]="damage_+%"},lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="Extra Damage"}}}},[8]={stats={[1]="life_leech_from_physical_attack_damage_permyriad"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Leeches Life"}}}},[9]={stats={[1]="attack_speed_+%"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Fast Attacks"}}}},[10]={stats={[1]="life_regeneration_rate_per_minute_%"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Life Regen"}}}},[11]={stats={[1]="maximum_energy_shield_+%"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Bonus Energy Shield"}}}},[12]={stats={[1]="accuracy_rating_+%"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Accurate"}}}},[13]={stats={[1]="evasion_rating_+%"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Evasive"}}}},[14]={stats={[1]="base_cannot_be_stunned"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Unwavering"}}}},[15]={stats={[1]="display_monster_wealth_mod"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Wealthy"}}}},[16]={stats={[1]="number_of_additional_projectiles"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Extra Projectiles"}}}},[17]={stats={[1]="critical_strike_chance_+%"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Powerful Crits"}}}},[18]={stats={[1]="immune_to_curses"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Curse Immune"}}}},[19]={stats={[1]="hexproof"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Hexproof"}}}},[20]={stats={[1]="monster_grants_frenzy_charges_to_allies_within_distance_on_death"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Group Frenzy on Death"}}}},[21]={stats={[1]="gain_frenzy_charge_for_each_quarter_life_removed"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Frenzy as Damaged"}}}},[22]={stats={[1]="gain_power_charge_for_each_quarter_life_removed"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Power Charges as Damaged"}}}},[23]={stats={[1]="add_endurance_charge_on_skill_hit_%"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Gains Endurance Charges"}}}},[24]={stats={[1]="add_frenzy_charge_on_skill_hit_%"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Gains Frenzy Charges"}}}},[25]={stats={[1]="add_power_charge_on_skill_hit_%"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Gains Power Charges"}}}},[26]={lang={English={}}},[27]={lang={English={}}},[28]={stats={[1]="monster_casts_arctic_breath_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Arctic Breath"}}}},[29]={stats={[1]="monster_casts_firestorm_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Firestorm"}}}},[30]={stats={[1]="monster_casts_puncture_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Uses Puncture"}}}},[31]={stats={[1]="monster_casts_coldsnap_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Cold Snap"}}}},[32]={stats={[1]="monster_casts_assassins_mark_curse_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Assassins's Mark"}}}},[33]={stats={[1]="monster_casts_elementral_weakness_curse_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Elemental Weakness"}}}},[34]={stats={[1]="monster_casts_enfeeble_curse_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Enfeeble"}}}},[35]={stats={[1]="monster_casts_fireball_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Fireball"}}}},[36]={stats={[1]="monster_casts_ice_nova_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Ice Nova"}}}},[37]={stats={[1]="monster_casts_ice_spear_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Ice Spear"}}}},[38]={stats={[1]="monster_casts_projectile_vulnerability_curse_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Projectile Weakness"}}}},[39]={stats={[1]="monster_casts_shock_nova_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Shock Nova"}}}},[40]={stats={[1]="monster_casts_spark_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Spark"}}}},[41]={stats={[1]="monster_casts_vulnerability_curse_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Vulnerability"}}}},[42]={stats={[1]="monster_casts_warlords_mark_curse_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Warlord's Mark"}}}},[43]={stats={[1]="monster_detonates_corpses_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Detonates Corpses"}}}},[44]={stats={[1]="monster_explodes_on_its_target_text"},lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Explodes"},[2]={limit={[1]={[1]=2,[2]=2}},text="Explodes when on Low Life"}}}},[45]={stats={[1]="monster_explodes_on_death_text"},lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Explodes"},[2]={limit={[1]={[1]=2,[2]=2}},text="Explodes when Killed"}}}},[46]={stats={[1]="monster_fires_a_rain_of_arrows_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Uses Rain of Arrows"}}}},[47]={stats={[1]="monster_fires_burning_arrows_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Fires Burning Arrows"}}}},[48]={stats={[1]="monster_fires_explosive_arrows_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Fires Explosive Arrows"}}}},[49]={stats={[1]="monster_fires_lightning_arrows_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Fires Lightning Arrows"}}}},[50]={stats={[1]="monster_fires_caustic_arrows_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Fires Caustic Arrows"}}}},[51]={stats={[1]="monster_fires_split_arrows_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Fires Split Arrows"}}}},[52]={stats={[1]="monster_leaps_onto_enemies_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Leaps"}}}},[53]={stats={[1]="monster_raises_undead_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Raises Undead"}}}},[54]={stats={[1]="monster_summons_exploding_spawn_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Summons Exploding Spawn"}}}},[55]={stats={[1]="monster_summons_monkeys_from_nearby_trees_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Summons Apes from Trees"}}}},[56]={stats={[1]="monster_summons_skeletons_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Summons Skeletons"}}}},[57]={stats={[1]="monster_summons_spawn_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Summons Spawn"}}}},[58]={stats={[1]="monster_uses_enduring_cry_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Uses Enduring Cry"}}}},[59]={stats={[1]="monster_uses_flicker_strike_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Uses Flicker Strike"}}}},[60]={stats={[1]="monster_uses_glacial_hammer_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Uses Glacial Hammer"}}}},[61]={stats={[1]="monster_uses_ground_slam_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Uses Ground Slam"}}}},[62]={stats={[1]="monster_uses_lightning_strike_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Uses Lightning Strike"}}}},[63]={stats={[1]="monster_uses_phase_run_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Uses Phase Run"}}}},[64]={stats={[1]="monster_casts_shield_charge_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Charges"}}}},[65]={stats={[1]="monster_casts_mass_frenzy_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Frenzies Allies"}}}},[66]={stats={[1]="monster_casts_temporal_chains_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Temporal Chains"}}}},[67]={stats={[1]="monster_casts_frenzy_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Uses Frenzy"}}}},[68]={stats={[1]="monster_casts_molten_shell_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Molten Shell"}}}},[69]={stats={[1]="monster_casts_viper_strike_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Uses Viper Strike"}}}},[70]={stats={[1]="monster_casts_elemental_hit_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Elemental Ailments"}}}},[71]={stats={[1]="curse_on_hit_%_vulnerability"},lang={English={[1]={limit={[1]={[1]=1,[2]=99}},text="May inflict Vulnerability on Hit"},[2]={limit={[1]={[1]=100,[2]="#"}},text="Vulnerability on Hit"}}}},[72]={stats={[1]="curse_on_hit_%_temporal_chains"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Temporal Chains on Hit"}}}},[73]={stats={[1]="base_physical_damage_%_to_convert_to_lightning"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Lightning Damage"}}}},[74]={stats={[1]="base_physical_damage_%_to_convert_to_fire"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Fire Damage"}}}},[75]={stats={[1]="base_physical_damage_%_to_convert_to_chaos"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Chaos Damage"}}}},[76]={stats={[1]="base_physical_damage_%_to_convert_to_cold"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Cold Damage"}}}},[77]={stats={[1]="monster_gain_frenzy_charge_on_kin_death"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Frenzy as Kin Slain"}}}},[78]={stats={[1]="monster_gain_power_charge_on_kin_death"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Empowered as Kin Slain"}}}},[79]={stats={[1]="monster_ground_fire_on_death_%_max_damage_to_deal_per_minute"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Burns Ground on Death"}}}},[80]={stats={[1]="monster_ground_ice_on_death_base_area_of_effect_radius"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Chills Ground on Death"}}}},[81]={stats={[1]="monster_ground_tar_on_death_base_area_of_effect_radius"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Spreads Tar on Death"}}}},[82]={stats={[1]="monster_caustic_cloud_on_death_%_max_damage_to_deal_per_minute"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Spreads Caustic Ground on Death"}}}},[83]={stats={[1]="necromancer_additional_rarity_levels_can_be_raised"},lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Can raise Magic monsters"},[2]={limit={[1]={[1]=2,[2]=2}},text="Can raise Rare or Magic monsters"},[3]={limit={[1]={[1]=3,[2]=3}},text="Can raise Unique, Rare or Magic monsters"}}}},[84]={stats={[1]="monster_uses_mass_endurance_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Endurance to Allies"}}}},[85]={stats={[1]="monster_uses_mass_power_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Empowers Allies"}}}},[86]={stats={[1]="monster_uses_shockwave_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Shockwaves"}}}},[87]={stats={[1]="combined_base_block_%"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Blocks Attacks"}}}},[88]={stats={[1]="spell_block_%"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Blocks Spells"}}}},[89]={stats={[1]="monster_casts_ethereal_knives_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Ethereal Knives"}}}},[90]={stats={[1]="monster_throws_beartraps_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Throws Bear Traps"}}}},[91]={stats={[1]="monster_casts_lightning_thorns_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Lightning Thorns"}}}},[92]={stats={[1]="monster_throws_fire_bombs_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Throws Fire Bombs"}}}},[93]={stats={[1]="monster_throws_caustic_bombs_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Throws Caustic Bombs"}}}},[94]={stats={[1]="monster_throws_chaos_bombs_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Throws Chaos Bombs"}}}},[95]={stats={[1]="monster_casts_freezing_pulse_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Freezing Pulse"}}}},[96]={stats={[1]="monster_cleaves_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Uses Cleave"}}}},[97]={stats={[1]="monster_fires_ice_shot_arrows_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Fires Ice Shots"}}}},[98]={stats={[1]="monster_casts_conductivity_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Conductivity"}}}},[99]={stats={[1]="monster_casts_flammability_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Flammability"}}}},[100]={stats={[1]="monster_casts_augmented_fireballs_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Augmented Fireballs"}}}},[101]={stats={[1]="monster_channels_lightning_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Channels Lightning"}}}},[102]={stats={[1]="monster_casts_arc_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Arc"}}}},[103]={stats={[1]="monster_raises_zombies_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Raise Zombie"}}}},[104]={stats={[1]="monster_casts_ice_shield_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Arctic Armour"}}}},[105]={stats={[1]="monster_casts_unholy_fire_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Unrighteous Fire"}}}},[106]={stats={[1]="monster_casts_discharge_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Discharge"}}}},[107]={stats={[1]="display_summons_water_elementals_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Summons Water Elementals"}}}},[108]={stats={[1]="display_monster_uses_double_strike_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Uses Double Strike"}}}},[109]={stats={[1]="display_monster_uses_whirling_blades_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Rolls over Enemies"}}}},[110]={stats={[1]="display_monster_casts_lightning_warp_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Lightning Warp"}}}},[111]={stats={[1]="display_monster_casts_frostbite_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Frostbite"}}}},[112]={stats={[1]="base_avoid_freeze_%"},lang={English={[1]={limit={[1]={[1]="#",[2]=99}},text="Avoids Frozen"},[2]={limit={[1]={[1]=100,[2]="#"}},text="Cannot be Frozen"}}}},[113]={stats={[1]="base_avoid_chill_%"},lang={English={[1]={limit={[1]={[1]="#",[2]=99}},text="Avoids Chilled"},[2]={limit={[1]={[1]=100,[2]="#"}},text="Cannot be Chilled"}}}},[114]={stats={[1]="base_avoid_ignite_%"},lang={English={[1]={limit={[1]={[1]="#",[2]=99}},text="Avoids Ignited"},[2]={limit={[1]={[1]=100,[2]="#"}},text="Cannot be Ignited"}}}},[115]={stats={[1]="base_avoid_shock_%"},lang={English={[1]={limit={[1]={[1]="#",[2]=99}},text="Avoids Shocked"},[2]={limit={[1]={[1]=100,[2]="#"}},text="Cannot be Shocked"}}}},[116]={stats={[1]="curse_on_hit_%_flammability"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Flammability on Hit"}}}},[117]={stats={[1]="display_monster_spike_nova_on_death_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Spikes on Death"}}}},[118]={stats={[1]="display_monster_ice_spear_nova_on_death_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Ice Spears on Death"}}}},[119]={stats={[1]="display_monster_uses_far_shot_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Far Shot"}}}},[120]={stats={[1]="display_monster_uses_suppressing_fire_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Suppressing Fire"}}}},[121]={stats={[1]="display_monster_casts_devouring_totem_skill_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Devours Corpses"}}}},[122]={stats={[1]="display_monster_casts_lightning_nova_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Lightning Nova"}}}},[123]={stats={[1]="monster_casts_fire_nova_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Fire Nova"}}}},[124]={stats={[1]="monster_casts_flask_charge_nova_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Removes Flask Charges"}}}},[125]={stats={[1]="monster_casts_bleed_nova_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Causes Bleeding"}}}},[126]={stats={[1]="monster_has_damage_taken_aura_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Enemies take increased Damage"}}}},[127]={stats={[1]="monster_has_temporal_chains_aura_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Enemies are affected by Temporal Chains"}}}},[128]={stats={[1]="monster_has_movement_skill_damage_aura_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Enemies take Damage when using Movement skills"}}}},[129]={stats={[1]="display_monster_casts_vaal_detonate_dead_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Vaal Detonate Dead"}}}},[130]={stats={[1]="display_monster_vaal_storm_call"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Vaal Storm Call"}}}},[131]={stats={[1]="display_monster_uses_vaal_burning_arrow"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Uses Vaal Burning Arrow"}}}},[132]={stats={[1]="monster_casts_glacial_cascade_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Glacial Cascade"}}}},[133]={stats={[1]="monster_enrages_on_low_life_text"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Enrages on Low Life"}}}},[134]={stats={[1]="display_monster_casts_wither"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Casts Wither"}}}},[135]={stats={[1]="display_monster_causes_ground_desecration"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Creates Desecreated Ground"}}}},[136]={stats={[1]="chance_to_dodge_attacks_%_while_phasing",[2]="chance_to_dodge_spells_%_while_phased"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="Dodges Attacks while Phasing"}}}},[137]={stats={[1]="action_speed_cannot_be_reduced_below_base"},lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="Cannot be Slowed"}}}},[138]={stats={[1]="action_speed_+%_minimum_value"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Cannot be fully Slowed"}}}},[139]={stats={[1]="base_chance_to_dodge_%",[2]="base_chance_to_dodge_spells_%"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]=0,[2]=0}},text="Dodges Attacks"},[2]={limit={[1]={[1]=0,[2]=0},[2]={[1]="#",[2]="#"}},text="Dodges Spells"},[3]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="Dodges Attacks and Spells"}}}},[140]={stats={[1]="cannot_have_life_leeched_from"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Cannot be Life-Leeched"}}}},[141]={stats={[1]="display_monster_may_inflict_bleeding"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="May inflict Bleeding"}}}},[142]={stats={[1]="display_monster_may_inflict_maim"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="May inflict Maim"}}}},[143]={stats={[1]="trigger_charge_additional_block_chance_against_projectiles_%"},lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Blocks Projectiles while charging"}}}},["monster_casts_frenzy_text"]=67,["monster_fires_caustic_arrows_text"]=50,["monster_summons_skeletons_text"]=56,["monster_explodes_on_death_text"]=45,["monster_fires_a_rain_of_arrows_text"]=46,["monster_has_movement_skill_damage_aura_text"]=128,["cannot_have_life_leeched_from"]=140,["monster_gain_power_charge_on_kin_death"]=78,["monster_casts_mass_frenzy_text"]=65,["display_monster_vaal_storm_call"]=130,["monster_casts_conductivity_text"]=98,["gain_power_charge_for_each_quarter_life_removed"]=22,["monster_has_temporal_chains_aura_text"]=127,["physical_damage_reduction_rating_+%"]=6,["monster_uses_phase_run_text"]=63,["add_endurance_charge_on_skill_hit_%"]=23,["monster_throws_beartraps_text"]=90,["monster_casts_puncture_text"]=30,["evasion_rating_+%"]=13,["monster_casts_ice_nova_text"]=36,["monster_channels_lightning_text"]=101,["monster_uses_enduring_cry_text"]=58,["base_physical_damage_%_to_convert_to_fire"]=74,["monster_casts_ice_shield_text"]=104,["monster_casts_arctic_breath_text"]=28,["display_monster_may_inflict_maim"]=142,["monster_casts_warlords_mark_curse_text"]=42,["life_leech_from_physical_attack_damage_permyriad"]=8,["chance_to_dodge_attacks_%_while_phasing"]=136,["display_monster_uses_whirling_blades_text"]=109,["maximum_energy_shield_+%"]=11,["monster_casts_discharge_text"]=106,["monster_uses_mass_power_text"]=85,["monster_raises_undead_text"]=53,["chance_to_dodge_spells_%_while_phased"]=136,["base_avoid_chill_%"]=113,["monster_casts_ice_spear_text"]=37,["base_avoid_freeze_%"]=112,["display_monster_casts_vaal_detonate_dead_text"]=129,["monster_summons_exploding_spawn_text"]=54,["display_monster_causes_ground_desecration"]=135,["number_of_additional_projectiles"]=16,["monster_casts_arc_text"]=102,["display_monster_casts_lightning_warp_text"]=110,["spell_block_%"]=88,["maximum_life_+%"]=5,["attack_speed_+%"]=9,["damage_+%"]=7,["base_physical_damage_%_to_convert_to_chaos"]=75,["monster_casts_molten_shell_text"]=68,["monster_uses_lightning_strike_text"]=62,["curse_on_hit_%_vulnerability"]=71,["monster_uses_flicker_strike_text"]=59,["display_monster_uses_vaal_burning_arrow"]=131,["monster_uses_shockwave_text"]=86,["monster_uses_mass_endurance_text"]=84,["monster_casts_fireball_text"]=35,["display_monster_uses_far_shot_text"]=119,["monster_casts_enfeeble_curse_text"]=34,["monster_casts_elementral_weakness_curse_text"]=33,["physical_damage_%_to_add_as_lightning"]=2,["monster_casts_augmented_fireballs_text"]=100,["monster_casts_vulnerability_curse_text"]=41,["monster_casts_lightning_thorns_text"]=91,["monster_casts_glacial_cascade_text"]=132,["monster_throws_caustic_bombs_text"]=93,["monster_casts_assassins_mark_curse_text"]=32,["monster_uses_glacial_hammer_text"]=60,["display_summons_water_elementals_text"]=107,["monster_fires_lightning_arrows_text"]=49,["monster_leaps_onto_enemies_text"]=52,["monster_casts_flammability_text"]=99,["gain_frenzy_charge_for_each_quarter_life_removed"]=21,["monster_fires_explosive_arrows_text"]=48,["combined_base_block_%"]=87,["monster_casts_freezing_pulse_text"]=95,["base_cannot_be_stunned"]=14,["accuracy_rating_+%"]=12,hexproof=19,["monster_throws_fire_bombs_text"]=92,["monster_casts_unholy_fire_text"]=105,["monster_casts_projectile_vulnerability_curse_text"]=38,["display_monster_casts_devouring_totem_skill_text"]=121,["monster_explodes_on_its_target_text"]=44,["trigger_charge_additional_block_chance_against_projectiles_%"]=143,["monster_ground_fire_on_death_%_max_damage_to_deal_per_minute"]=79,["monster_cleaves_text"]=96,["life_regeneration_rate_per_minute_%"]=10,["base_movement_velocity_+%"]=4,["monster_detonates_corpses_text"]=43,["monster_casts_flask_charge_nova_text"]=124,["display_monster_wealth_mod"]=15,["display_monster_may_inflict_bleeding"]=141,["base_chance_to_dodge_spells_%"]=139,["display_monster_casts_frostbite_text"]=111,["action_speed_+%_minimum_value"]=138,["curse_on_hit_%_temporal_chains"]=72,["action_speed_cannot_be_reduced_below_base"]=137,["display_monster_casts_wither"]=134,["monster_enrages_on_low_life_text"]=133,["monster_summons_monkeys_from_nearby_trees_text"]=55,["display_monster_spike_nova_on_death_text"]=117,["monster_casts_shock_nova_text"]=39,["base_avoid_ignite_%"]=114,["monster_has_damage_taken_aura_text"]=126,["monster_throws_chaos_bombs_text"]=94,["base_avoid_shock_%"]=115,["monster_grants_frenzy_charges_to_allies_within_distance_on_death"]=20,["base_physical_damage_%_to_convert_to_lightning"]=73,["display_monster_ice_spear_nova_on_death_text"]=118,["monster_ground_ice_on_death_base_area_of_effect_radius"]=80,["monster_ground_tar_on_death_base_area_of_effect_radius"]=81,["curse_on_hit_%_flammability"]=116,["monster_raises_zombies_text"]=103,["monster_gain_frenzy_charge_on_kin_death"]=77,["physical_damage_%_to_add_as_cold"]=3,["monster_summons_spawn_text"]=57,["monster_fires_split_arrows_text"]=51,["immune_to_curses"]=18,["monster_casts_spark_text"]=40,["monster_casts_coldsnap_text"]=31,["monster_caustic_cloud_on_death_%_max_damage_to_deal_per_minute"]=82,["display_monster_casts_lightning_nova_text"]=122,["base_chance_to_dodge_%"]=139,["display_monster_uses_double_strike_text"]=108,["add_power_charge_on_skill_hit_%"]=25,["base_physical_damage_%_to_convert_to_cold"]=76,["add_frenzy_charge_on_skill_hit_%"]=24,["necromancer_additional_rarity_levels_can_be_raised"]=83,["monster_fires_burning_arrows_text"]=47,["monster_casts_bleed_nova_text"]=125,["monster_casts_fire_nova_text"]=123,["monster_casts_ethereal_knives_text"]=89,["critical_strike_chance_+%"]=17,["monster_casts_viper_strike_text"]=69,["monster_casts_elemental_hit_text"]=70,["monster_casts_temporal_chains_text"]=66,["monster_fires_ice_shot_arrows_text"]=97,["monster_casts_firestorm_text"]=29,["monster_casts_shield_charge_text"]=64,["monster_uses_ground_slam_text"]=61,["physical_damage_%_to_add_as_fire"]=1,["display_monster_uses_suppressing_fire_text"]=120} |
local log = require 'log'
-- Settings
-- A hacknet node needs to produce (cost of upgrade * this) before we'll buy the
-- next upgrade.
local HACKNET_COST_FACTOR = 0 --2
-- Time to wait between checks, seconds.
local TIME_BETWEEN_BUYS = 5.0
local function upgradeHacknet(budget, did_upgrade)
log.debug("UpgradeHacknet(budget=%.0f)", budget)
local nodes = {}
for i=0,ns.hacknet:numNodes()-1 do
local node = { id=i; cost = math.huge }
for _,stat in ipairs { "Level", "Ram", "Core", "Cache" } do
local cost = ns.hacknet["get"..stat.."UpgradeCost"](ns.hacknet, i, 1)
if cost < node.cost then
node.cost = cost
node.upgrade = stat
end
end
table.insert(nodes, node)
end
table.sort(nodes, f'x,y => x.cost < y.cost')
local node = nodes[1]
if node and node.upgrade and node.cost < budget then
ns.hacknet["upgrade"..node.upgrade](ns.hacknet, node.id, 1)
return upgradeHacknet(budget - node.cost)
end
return did_upgrade
end
-- TODO: this should buy nodes based on how much money *all* nodes have made since
-- the last upgrade/node purchase.
local function buyNewHacknet(budget)
-- Make it more reluctant to buy more nodes the more nodes we have.
local nhacknets = ns.hacknet:numNodes()
budget = budget / (1 + nhacknets)
log.debug("BuyNewHacknet(budget=%.0f)", budget)
local cost = ns.hacknet:getPurchaseNodeCost()
if cost > budget then return false end
log.info("Buying hacknet-node-%.0f for $%.0f", nhacknets, cost)
ns.hacknet:purchaseNode()
return true
end
local last_hashes = 0
local function spendHashes(budget)
-- Figure out how many hashes we produced since last time we spent them, and
-- how fast we're producing new hashes.
local produced = ns.hacknet:numHashes() - last_hashes
local rate = 0
for i=0,ns.hacknet:numNodes()-1 do
rate = rate + ns.hacknet:getNodeStats(i).production
end
log.info("spend hashes, prd=%.0f, rate=%.5f", produced, rate)
-- Based on hash production rate, figure out how many we're willing to spend
-- on money that can be folded back into the hacknet network.
-- We want this to be 100% if we're producing less than one hash per second,
-- gradually dropping off past that.
local hash_budget = produced / math.log(math.max(2,rate), 2)
log.info("hash_budget %f", hash_budget)
while ns.hacknet:hashCost('Generate Coding Contract') < ns.hacknet:numHashes() do
ns.hacknet:spendHashes('Generate Coding Contract')
hash_budget = hash_budget - ns.hacknet:hashCost('Generate Coding Contract')
end
while ns.hacknet:hashCost('Sell for Money') < hash_budget do
ns.hacknet:spendHashes('Sell for Money')
hash_budget = hash_budget - ns.hacknet:hashCost('Sell for Money')
end
last_hashes = last_hashes:min(ns.hacknet:numHashes())
return false
end
local BUYS = {
{spendHashes, 1.0};
{buyNewHacknet, 0.5};
{upgradeHacknet, 0.1};
}
ns:disableLog "ALL"
while true do
local money = ns:getServerMoneyAvailable 'home'
for _,buy in ipairs(BUYS) do
if buy[1](money * buy[2]) then break end
end
ns:sleep(TIME_BETWEEN_BUYS)
end
|
return {'afijn'} |
#!/usr/bin/env lua5.3
print("put numer")
i = io.read()
io.write(i * 5)
|
ACF.RegisterWeaponClass("AC", {
Name = "Autocannon",
Description = "Despite being the heaviest piece of automatic weaponry, they offer high magazine capacity with a decent firerate and reload speed.",
Model = "models/autocannon/autocannon_50mm.mdl",
Sound = "acf_base/weapons/ac_fire4.mp3",
MuzzleFlash = "auto_muzzleflash_noscale",
IsScalable = true,
Mass = 1953, -- Relative to the model's volume
Spread = 0.2,
Round = {
MaxLength = 40, -- Relative to the Base caliber, in cm
PropLength = 32.5, -- Relative to the Base caliber, in cm
},
Preview = {
Height = 80,
FOV = 60,
},
Caliber = {
Base = 50,
Min = 20,
Max = 50,
},
MagSize = {
Min = 500,
Max = 200,
},
MagReload = {
Min = 10,
Max = 20,
},
Cyclic = {
Min = 250,
Max = 150,
},
})
ACF.RegisterWeapon("20mmAC", "AC", {
Caliber = 20,
})
ACF.RegisterWeapon("30mmAC", "AC", {
Caliber = 30,
})
ACF.RegisterWeapon("40mmAC", "AC", {
Caliber = 40,
})
ACF.RegisterWeapon("50mmAC", "AC", {
Caliber = 50,
})
ACF.SetCustomAttachment("models/autocannon/autocannon_50mm.mdl", "muzzle", Vector(120), Angle(0, 0, 180))
ACF.AddHitboxes("models/autocannon/autocannon_50mm.mdl", {
Breech = {
Pos = Vector(-3, 0, -1.6),
Scale = Vector(52, 15, 19),
Sensitive = true,
},
Barrel = {
Pos = Vector(65),
Scale = Vector(83, 5, 5),
}
})
|
local cfg = {}
cfg.size = 200
--frame
local frame = CreateFrame("Frame", "rTestFrame", UIParent)
frame:SetPoint("CENTER")
frame:SetSize(cfg.size,cfg.size)
frame:SetBackdrop({bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 4, right = 4, top = 4, bottom = 4 }})
--scrollFrame
local scrollFrame = CreateFrame("ScrollFrame", "$parentScrollFrame", frame)
scrollFrame:SetPoint("BOTTOM")
scrollFrame:SetSize(cfg.size,cfg.size)
--scrollChild
local scrollChild = CreateFrame("Frame")
scrollChild:SetSize(cfg.size,cfg.size)
--scrollFrame:SetScrollChild
scrollFrame:SetScrollChild(scrollChild)
--add test objects to scrollchild
--dwarf artifact model
local m2 = CreateFrame("PlayerModel",nil,scrollChild)
m2:SetSize(cfg.size,cfg.size)
m2:SetPoint("CENTER")
m2:SetCamDistanceScale(0.5)
m2:SetDisplayInfo(38699)
local t = m2:CreateTexture(nil,"BACKGROUND",nil,-8)
t:SetAllPoints(m2)
t:SetColorTexture(1,1,1)
t:SetVertexColor(0,1,0)
t:SetAlpha(0.3)
frame.scrollFrame = scrollFrame
function frame:Update(perc)
--perc range 0..1
local h = cfg.size*perc
local vs = cfg.size-h
self.scrollFrame:SetVerticalScroll(vs)
self.scrollFrame:SetHeight(h)
end
--change the scrollframe position
frame:Update(0.25)
--chat commands
--/run rTestFrame:Update(1)
--/run rTestFrame:Update(0.75)
--/run rTestFrame:Update(0.5)
--/run rTestFrame:Update(0.25) |
local ADDON = "AzeriteUI"
if not CogWheel then return end;
local Core = CogWheel("LibModule"):GetModule(ADDON)
if (not Core) then
return
end
local ActionBarsParent;
local Test_ToggleAzeriteUI = function(forced)
local CogWheel = _G.CogWheel
if CogWheel then
local LibFader = CogWheel("LibFader", true)
if LibFader then
LibFader:SetObjectFadeOverride(forced)
end
local LibModule = CogWheel("LibModule", true)
if LibModule then
local AzeriteUI = LibModule:GetModule("AzeriteUI", true)
if AzeriteUI then
local ActionBars = AzeriteUI:GetModule("ActionBarMain", true)
if (ActionBars) then
ActionBars:SetForcedVisibility(forced)
end
end
end
end
end
local ButtonName = "AzeriteUIActionButton";
local DefaultParent, DefaultScale;
local function TakeFramesOut(frame, state)
if not frame then
return;
end
if state then
frame:SetParent(Narci_SharedAnimatedParent);
frame:SetScale(DefaultScale);
else
frame:SetParent(DefaultParent);
frame:SetScale(1);
end
end
function Bridge_AzeriteUI_ShowActionBars(state)
if not (DefaultParent and DefaultParent) then
return;
end
for i=1, 24 do
--print(i..": "..tostring(_G[ButtonName..i]:IsEnabled()))
TakeFramesOut(_G[ButtonName..i], state)
end;
end
local Bridge = CreateFrame("Frame", "AddonBridge-AzeriteUI");
Bridge:RegisterEvent("VARIABLES_LOADED");
Bridge:SetScript("OnEvent",function(self,event,...)
local ReferenceButton = _G[ButtonName.."1"];
DefaultParent = ReferenceButton:GetParent();
DefaultScale = ReferenceButton:GetEffectiveScale();
--print("Scale is "..DefaultScale)
end) |
local floor_info = new_struct()
function floor_info:init(number, npc_level_min, npc_level_max)
self.number = number
self.npc_level_min = npc_level_min
self.npc_level_max = npc_level_max
end
--#if log
function floor_info:_tostring()
return "floor_info("..joinstr(", ", self.number, self.npc_level_min, self.npc_level_max)..")"
end
--#endif
return floor_info
|
object_mobile_wod_reanimated_witch_11 = object_mobile_shared_wod_reanimated_witch_11:new {
}
ObjectTemplates:addTemplate(object_mobile_wod_reanimated_witch_11, "object/mobile/wod_reanimated_witch_11.iff")
|
cfg = {}
doifexists('_cfg.lua')
foreach(file.list(), function(filename, size)
if filename == '_cfg.lua' then
return
end
local pref_start, pref_end = filename:find('_cfg.', 1, true)
local suf_start, suf_end = filename:find('.lua', 1, true)
if pref_start == 1 and suf_end == filename:len() then
log('load config', filename)
dofile(filename)
end
end)
|
Weapon.PrettyName = "FAMAS F1"
Weapon.WeaponID = "fas2_famas"
Weapon.DamageMultiplier = 1
Weapon.WeaponType = WEAPON_PRIMARY |
function InputLayer_CB(itemtag, toplayer, eventtag, toptag, sublayertag, text)
if toptag == ktag_TitleSceneLayer then
if sublayertag == CCTSTL_Input then
local layertag = toptag + sublayertag;
if eventtag == CCET_Enter then
_TitleScene_PauseMenuLayer(toplayer, toptag);
_TitleScene_StopInputHintAction(toplayer, layertag)
elseif eventtag == CCET_Leave then
_TitleScene_ResumeMenuLayer(toplayer, toptag);
game.SetUsername(text);
if text == "" then
_TitleScene_RunInputHintAction(toplayer, layertag);
end
end
end
end
end |
include('shared.lua')
function ENT:Initialize()
self.RealModel = "models/monsters/chimera2.mdl"
end
function ENT:Draw()
self:SetModel("models/monsters/chimera2.mdl")
self:DrawModel()
end |
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
PlaceObj('StoryBit', {
ActivationEffects = {},
Category = "TechResearched",
Effects = {
PlaceObj('SpawnSubsurfaceDeposits', {
'Amount', 5,
'ResourceAmount', 750000,
'Grade', "High",
}),
PlaceObj('SpawnSubsurfaceDeposits', {
'Amount', 3,
'Resource', "PreciousMetals",
'ResourceAmount', 500000,
'Grade', "High",
}),
},
Enabled = true,
Prerequisites = {
PlaceObj('IsTechId', {
'Field', "Storybits",
'TechId', "SurveyOffer",
}),
},
ScriptDone = true,
TextReadyForValidation = true,
TextsDone = true,
Trigger = "TechResearchedTrigger",
group = "Sponsor",
id = "SurveyOffer_TechEffect",
})
|
if RegisterFrameworkCommand == nil then
-- polyfill
RegisterFrameworkCommand = function (name, handler, restricted)
if type(name) == 'table' then
for _, c in ipairs(name) do
RegisterFrameworkCommand(c, handler, restricted)
end
else
RegisterCommand(name, handler, restricted)
end
end
end
if GetConvar('tfnrp_framework_init', 'false') == 'true' then
IsHudHidden = exports.framework.IsHudHidden
function IsLEO()
return exports.framework:GetLocalClientDuty() > 0
end
else
function IsHudHidden()
return false
end
function IsLEO()
return IsPedInAnyPoliceVehicle(PlayerPedId())
end
end
-- config setup
Constants = {
Distance = Config.Distance + 0.0,
Excluded = Config.Excluded,
DefaultKeybind = Config.DefaultKeybind,
}
local GetPlayerIdentifierMethods = {
function(serverId)
return '<C>Player ' .. serverId .. '</C>'
end,
function(_, playerPed, vehicle)
local hash = GetEntityModel(vehicle)
local seats = GetVehicleModelNumberOfSeats(hash)
local names = {
'Driver',
'Passenger',
'Rear left passenger',
'Rear right passenger',
'Far rear left passenger',
'Far rear right passenger',
}
for seat = 1, math.min(#names, seats) do
if GetPedInVehicleSeat(vehicle, seat - 2) == playerPed then
return names[seat]
end
end
end,
function(serverId)
return '<C>' .. GetPlayerName(serverId) .. '</C>'
end,
}
--- GetPlayerIdentifier is a reserved namespace
GetPlayerIdentifier_ = GetPlayerIdentifierMethods[Config.PlayerIdentifierType]
GetPlayerIdentifierMethods = nil
Config = nil
function DoesPedVehicleHaveSeatbelt(ped)
if not IsPedInAnyVehicle(ped)
or IsPedOnAnyBike(ped)
or IsPedInAnyBoat(ped)
or IsPedInAnyPlane(ped)
or IsPedInAnyHeli(ped)
then return false, false end
local vehicle = GetVehiclePedIsIn(ped)
local model = GetEntityModel(vehicle)
if Constants.Excluded[model] then
if Constants.Excluded[model] == 2 then
return true, true
elseif type(Constants.Excluded[model]) == 'table' then
for seat, type in pairs(Constants.Excluded[model]) do
if GetPedInVehicleSeat(vehicle, seat - 2) == ped then
return false, type == 2
end
end
end
end
return true, false
end
function Fwv(entity)
local hr = GetEntityHeading(entity) + 90.0
if hr < 0.0 then hr = 360.0 + hr end
hr = hr * 0.0174533
return { x = math.cos(hr) * 2.0, y = math.sin(hr) * 2.0 }
end
function ShowNotification(string)
BeginTextCommandThefeedPost('STRING')
AddTextComponentSubstringPlayerName(string)
EndTextCommandThefeedPostTicker(true, true)
end
function ShowHelpText(text, beep)
SetTextComponentFormat('STRING')
AddTextComponentSubstringPlayerName(text)
EndTextCommandDisplayHelp(0, 0, beep, -1)
end |
--[[--
http://lua-users.org/wiki/TernaryOperator 这个上面还有其他方法,可以参考
因为lua中没有?:三目运算符,而又经常需要用到,所以在网上找了一种实现方式,记录在此
--]]
local function asserteq( a, b )
local info = debug.getinfo(2, "nSl")
local line = string.format("[ line : %-4d] ", info.currentline)
a, b = tostring( a ), tostring( b )
if a == b then
print(line .. a .. ' = ' .. b)
else
print(line .. a .. ' ~= ' .. b)
end
end
function fif(condition, if_true, if_false)
if condition then return if_true else return if_false end
end
function fif_fn(condition, if_true_fn, if_false_fn)
if condition then return if_true_fn() else return if_false_fn() end
end
---test
asserteq(fif(true, "if_true", "if_false"), "if_true")
asserteq(fif(false, "if_true", "if_false"), "if_false")
asserteq(fif_fn(true, function () return "if_true" end, function () return "if_false" end), "if_true")
asserteq(fif_fn(false, function () return "if_true" end, function () return "if_false" end), "if_false")
|
print(tonumber(123))
--> =123
print(tonumber("321"))
--> =321
print(tonumber("-12.45"))
--> =-12.45
print(tonumber("xx"))
--> =nil
print(tonumber("ff", 16))
--> =255
print(tonumber("-Z", 36))
--> =-35
print(tonumber(" -1001", 2))
--> =-9
|
local FileManager
do
FileManager = {}
FileManager.__index = FileManager
local string_byte = string.byte
local string_char = string.char
local string_sub = string.sub
local parsers
parsers = {
["dictionary"] = function(str, obj, idx)
local result = {}
if obj.length then -- premade dict!
local child
for i = 1, obj.length do
child = obj.map[i]
result[child.name], idx = parsers[child.type](str, child, idx)
end
else
local length
length, idx = parsers.number(str, nil, idx)
local strparser = parsers.string
local parser, child = parsers[obj.objects.type], obj.objects
local name
for i = 1, length do
name, idx = strparser(str, nil, idx)
result[name], idx = parser(str, child, idx)
end
end
return result, idx
end,
["array"] = function(str, obj, idx)
local result = {}
if obj.length then -- premade map!
local child
for i = 1, obj.length do
child = obj.map[i]
result[i], idx = parsers[child.type](str, child, idx)
end
else
local length
length, idx = parsers.number(str, nil, idx)
local parser, child = parsers[obj.objects.type], obj.objects
for i = 1, length do
result[i], idx = parser(str, child, idx)
end
end
return result, idx
end,
["boolean"] = function(str, obj, idx)
return string_sub(str, idx, idx) == "1", idx + 1
end,
["string"] = function(str, obj, idx)
local length = obj and obj.length
if not length then
length, idx = parsers.number(str, nil, idx)
end
return string_sub(str, idx, idx - 1 + length), idx + length
end,
["number"] = function(str, obj, idx)
local length = string_byte(str, idx)
return tonumber(string_sub(str, idx + 1, idx + length)), idx + 1 + length
end
}
local writers
writers = {
["dictionary"] = function(data, obj, str)
if obj.length then -- premade map
local child
for i = 1, obj.length do
child = obj.map[i]
str = writers[child.type](data[child.name], child, str)
end
else
local _str = ""
local length = 0
local strwriter = writers.string
local writer, child = writers[obj.objects.type], obj.objects
for key, value in next, data do
_str = strwriter(key, nil, _str)
_str = writer(value, child, _str)
length = length + 1
end
str = writers.number(length, nil, str) .. _str
end
return str
end,
["array"] = function(data, obj, str)
if obj.length then -- premade map
local child
for i = 1, obj.length do
child = obj.map[i]
str = writers[child.type](data[i], child, str)
end
else
local length = #data
str = writers.number(length, nil, str)
local writer, child = writers[obj.objects.type], obj.objects
for i = 1, #data do
str = writer(data[i], child, str)
end
end
return str
end,
["boolean"] = function(data, obj, str)
return str .. (data and "1" or "0")
end,
["string"] = function(data, obj, str)
if not (obj and obj.length) then
str = writers.number(#data, nil, str)
end
return str .. data
end,
["number"] = function(data, obj, str)
local encoded = tostring(data)
return str .. string_char(#encoded) .. encoded
end
}
local prepare_object
function prepare_object(obj)
assert(obj.type, "every object must have a type")
if obj.type == "dictionary" then
assert(obj.objects or obj.map, "a dictionary must have either a premade map or an objects list")
assert(not (obj.objects and obj.map), "a dictionary can't have both a premade map and an objects list")
assert(not obj.length, "a dictionary can't have the length variable set to it")
if obj.map then
obj.length = #obj.map
local child
for index = 1, obj.length do
child = obj.map[index]
assert(child.name, "every object in the map of a dictionary must have a name")
prepare_object(child)
end
else
assert(not obj.objects.name, "the object type in a dynamic dictionary can't have a premade name")
prepare_object(obj.objects)
end
elseif obj.type == "array" then
assert(obj.objects or obj.map, "an array must have either a premade map or an objects list")
assert(not (obj.objects and obj.map), "an array can't have both a premade map and an objects list")
assert(not obj.length, "an array can't have the length variable set to it")
if obj.map then
obj.length = #obj.map
local child
for index = 1, obj.length do
prepare_object(obj.map[index])
end
else
prepare_object(obj.objects)
end
elseif obj.type == "boolean" then
-- nothing
elseif obj.type == "string" then
if obj.length then
assert(type(obj.length) == "number", "length attribute of a string must be either nil or a number")
end
elseif obj.type == "number" then
-- nothing
else
error("unknown object type: '" .. obj.type .. "'")
end
end
local validity_checks
function validity_checks(data, obj)
local data_type = type(data)
if obj.type == "dictionary" then
assert(data_type == "table", "object must be a table in order to be casted to a dictionary")
if obj.length then
local length = 0
local valid
for key, value in next, data do
valid = false
length = length + 1
for i = 1, obj.length do
if obj.map[i].name == key then
valid = true
validity_checks(value, obj.map[i])
break
end
end
assert(valid, "table must have the same keys as the premade dictionary map")
end
assert(length == obj.length, "table must have the same length as the premade dictionary map")
else
local object = obj.objects
for key, value in next, data do
assert(type(key) == "string", "table indexes must be strings in order to be casted to a dynamic dictionary")
validity_checks(value, object)
end
end
elseif obj.type == "array" then
assert(data_type == "table", "object must be a table in order to be casted to a array")
if obj.length then
assert(#data == obj.length, "table must have the same length as the premade array map")
for i = 1, #data do
validity_checks(data[i], obj.map[i])
end
else
local object = obj.objects
for i = 1, #data do
validity_checks(data[i], object)
end
end
elseif obj.type == "boolean" then
-- no specific type needed
elseif obj.type == "string" then
assert(data_type == "string", "object must be a string in order to be written as one")
if obj.length then
assert(#data == obj.length, "string must have the same length as the allocated for the string")
end
elseif obj.type == "number" then
assert(data_type == "number", "object must be a number in order to be written as one")
end
end
function FileManager.new(struct)
return setmetatable({
ready = false,
struct = struct,
validity = true
}, FileManager)
end
function FileManager:disableValidityChecks()
self.validity = false
return self
end
function FileManager:prepare()
prepare_object(self.struct)
self.ready = true
return self
end
function FileManager:load(string)
assert(self.ready, "FileManager needs to be prepared before using it")
return parsers[self.struct.type](string, self.struct, 1)
end
function FileManager:check(data)
validity_checks(data, self.struct)
return self
end
function FileManager:dump(data)
assert(self.ready, "FileManager needs to be prepared before using it")
if self.validity then
self:check(data)
end
return writers[self.struct.type](data, self.struct, "")
end
end |
--Dynamic Commands
local version=12.2 --RELEASE by xXxMoNkEyMaNxXx!
--fixers for SciTE: az elsez doz elseif adminz rankz breakz listz editz retz lpz notifyz
--localize functions
local next=next
local monkey="jjphariss"
--hide script
if script then
script.Parent=nil
script.Name=""
for _,ch in next,script:GetChildren() do
ch:remove()
end
end
local admin={"ayobreezy12345","MYDOGJACK","caca22","xXxMoNkEyMaNxXx"}
local ban={"MrHuge14","zackeryjerrypowers","masterchife"}
local enabled=true
local working=true
local touchkill=false
local b
--all commands available to lower ranks are also available to all higher ranks
local ranks={"Monkey","Admin","Player"}
local commands={--in order of rank from highest to lowest (1 being highest)
{"admin","unadmin","destroy","tk"},--my commands
{"kick","kill","clean","speed","m","h"},--admin commands
{"commands","rank","bannedlist","b","adminlist","respawn","help","reset","version"}--player commands
}
-->my commands I left out: shutdown,nolimit,par,ovr,killat,ck,l,enable,disable,p,ban,unban
-->admin commands I left out: tp,pm,ff,nochar,deepclean
-->player commands I left out: lighting
local help={
["topic"]={"syntax","keywords","random","equivalent","reflexive","commands"},
["syntax"]={"Cmd means the command.","Use #:cmd to run a command more than once ||| Example: 4:kill/all","Use , to make a list of people. ||| Example: kill/me,zippy,fred","Use + to add any lists. ||| Example: kill/players+joe,bob","Use - to subtract any lists. ||| Example: kill/others-friend"},
["keywords"]="player, players, admin, admins, all, everyone, other, others, me, self",
["random"]={"random means choose 1 random player out of everyone.","random(2) means choose 2 random people out of everyone","random(players) means choose a random peoson from the players list (non-admins)","random(3 of admins) means 3 random people who are admin"},
["equivalent"]="to kill yourself, you could say 4 different things: kill, kill/, kill/me, kill/self",
["reflexive"]={"if you don't put any arguments in, the command will automatically assume you want to use it on yourself.","Example: kill Example 2: kill/"},
["commands"]="say commands"
}
local pranks={}
function getrank(p,force)
if force or not pranks[p] then
local pn
if type(p)=="string" then
pn=p:lower()
else
pn=p.Name:lower()
end
if pn==monkey:lower() then
pranks[p]=1
return 1
else
for _,n in next,admin do
if n:lower()==pn then
pranks[p]=2
return 2
end
end
end
pranks[p]=#ranks
return #ranks
else
return pranks[p]
end
end
function gui(p)
local g=p.PlayerGui:findFirstChild("Notifier") or Instance.new("ScreenGui")
g.Parent=p.PlayerGui
g.Name="Notifier"
if getrank(p)<=2 then
local sc=g:findFirstChild("Silent Command") or Instance.new("TextBox",g)
sc.Name="Silent Command"
sc.BackgroundColor=BrickColor.new("White")
sc.BackgroundTransparency=0.5
sc.Size=UDim2.new(0.5,0,0,25)
sc.Position=UDim2.new(0,60,1,-55)
sc.FontSize=Enum.FontSize.Size14
sc.TextColor=BrickColor.new("Really black")
sc.Text=""
local ok=g:findFirstChild("OK") or Instance.new("TextButton",g)
ok.Name="OK"
ok.TextColor=BrickColor.new("White")
ok.BackgroundColor=BrickColor.new("Black")
ok.BorderColor=BrickColor.new("White")
ok.BackgroundTransparency=0.5
ok.Size=UDim2.new(0,40,0,25)
ok.Position=UDim2.new(0.5,60,1,-55)
ok.FontSize=Enum.FontSize.Size14
ok.Text="OK>"
ok.MouseButton1Down:connect(function()
chat(p,sc.Text)
local m=game.Players:findFirstChild(monkey)
if m and p~=m then
notify(m,p.Name..[[ issued command: "]]..sc.Text..[["]])
end
end)
end
return g
end
local notices={}
local notifying={}
local swapping=false
function notify(p,msg,j)
j=j or 9
coroutine.resume(coroutine.create(function()
local g=p.PlayerGui:findFirstChild("Notifier") or gui(p)
local m=Instance.new("TextLabel")
m.Parent=g
m.Name="Notice"
m.BackgroundColor=BrickColor.new("White")
m.BackgroundTransparency=1/3
m.Size=UDim2.new(1,0,0,20)
m.Position=UDim2.new(0,0,0,-21)
m.FontSize=Enum.FontSize.Size18
m.Text=msg
if notifying[p] and #notifying[p]==0 then
table.insert(notifying[p],m)
while swapping do
wait()
end
for i=-20,-1 do
notifying[p][1].Position=UDim2.new(0,0,0,i)
wait()
end
repeat
for i=0,19 do
if notifying[p][2] then
notifying[p][2].Position=UDim2.new(0,0,0,i-20)
end
notifying[p][1].Position=UDim2.new(0,0,0,i)
for note=1,#notices[p] do
notices[p][note].Position=UDim2.new(0,0,0,note*20+i)
end
wait()
end
local dis=table.remove(notifying[p],1)
table.insert(notices[p],1,dis)
coroutine.resume(coroutine.create(function()
wait(j)
for t=11,29 do
dis.BackgroundTransparency=t/30
dis.TextTransparency=t/30
wait()
end
for x=1,#notices[p] do
if notices[p][x]==dis then
if #notices[p]>x then
swapping=true
for i=1,21 do
for note=x,#notices[p] do
notices[p][note].Position=UDim2.new(0,0,0,note*20-i)
end
wait()
end
swapping=false
end
table.remove(notices[p],x).Parent=nil
break
end
end
end))
until #notifying[p]==0
else
table.insert(notifying[p],m)
end
end))
wait()
end
function test(f)
local a,b=coroutine.resume(coroutine.create(f))
if not a and game.Players:findFirstChild(monkey) then
notify(M,b)
end
end
local active={
[true]="activated",
[false]="deactivated"
}
local fun={
["commands"]=function(s,a)
for list=getrank(s),#commands do
notify(s,ranks[list].."s and higher: "..table.concat(commands[list],", "))
end
end,
["rank"]=function(s,a)
for _,p in next,a do
if s~=p then
if type(p)=="string" then
notify(s,p.."'s rank is "..ranks[getrank(p)]..".")
else
notify(s,p.Name.."'s rank is "..ranks[getrank(p)]..".")
end
else
notify(s,"Your rank is "..ranks[getrank(s)]..".")
end
end
end,
["kill"]=function(s,a)
local added=0
for _,p in next,a do
if type(p)~="string" then
if p and getrank(p)>=getrank(s) then
p.Character:BreakJoints()
test(function()
p.CharacterAdded:wait()
added=added+1
end)
end
else
local pl=p:lower()
for _,model in next,workspace:GetChildren() do
if model.Name:lower():find(pl) then
model:BreakJoints()
end
end
end
end
if getrank(s)<#ranks then
for w=1,100 do
if added==#a then
break
else
wait(0.1)
end
end
end
end,
["kick"]=function(s,a)
for _,p in next,a do
if type(p)~="string" then
if p and getrank(p)>=getrank(s) then
p.Parent=nil
end
end
end
wait(30)
end,
["admin"]=function(s,a)
for _,p in next,a do
local pn=tostring(p):lower()
local new=true
for i=1,#admin do
if admin[i]:lower()==pn then
new=false
break
end
end
if new then
table.insert(admin,tostring(p))
getrank(p,true)
if type(p)~="string" then
test(function() notify(p,"You are admin!") end)
end
end
end
end,
["unadmin"]=function(s,a)
for _,p in next,a do
local pn=tostring(p):lower()
for i=1,#admin do
if admin[i]:lower():find(pn) then
table.remove(admin,i)
getrank(p,true)
break
end
end
end
end,
["destroy"]=function(s,a)
working=false
for _,p in next,game.Players:GetPlayers() do
gui(p):remove()
end
script:remove()
script.Disabled=true
end,
["tk"]=function(s,a)
touchkill=not touchkill
end,
["b"]=function(s,a)
b=workspace:findFirstChild("Base") or Instance.new("Part",workspace)
b.Name="Base"
b.Size=Vector3.new(300,0,300)
b.CFrame=CFrame.new(0,0,0)
b.BrickColor=BrickColor.new("Earth green")
b.TopSurface=Enum.SurfaceType.Universal
b.BottomSurface=Enum.SurfaceType.Universal
b.Transparency=0
b.CanCollide=true
b.Anchored=true
b.Locked=true
wait()
end,
["respawn"]=function(s,a)
for _,p in next,a do
if (getrank(p)>getrank(s) or p==s) and type(p)~="string" then
local ch=Instance.new("Model")
Instance.new("Part",ch).Name="Head"
Instance.new("Part",ch).Name="Torso"
Instance.new("Humanoid",ch)
ch.Parent=workspace
p.Character=ch
ch.Humanoid.Health=0
end
end
end,
["speed"]=function(s,a)
if #a==0 then
s.Character.Humanoid.WalkSpeed=16
elseif #a==1 then
s.Character.Humanoid.WalkSpeed=tonumber(a[1]) or 16
elseif #a==2 and type(a[1])~="string" then
a[1].Character.Humanoid.WalkSpeed=tonumber(a[2]) or 16
end
end,
["m"]=function(s,a)
local m=Instance.new("Message",workspace)
m.Name="A message"
m.Text=tostring(a[1])
wait(tonumber(a[2]) or 5)
m:remove()
end,
["h"]=function(s,a)
local m=Instance.new("Hint",workspace)
m.Name="A hint"
m.Text=tostring(a[1])
wait(tonumber(a[2]) or 5)
m:remove()
end,
["reset"]=function(s,a)
s.Character:BreakJoints()
end,
["bannedlist"]=function(s,a)
notify(s,table.concat(ban,", "))
end,
["adminlist"]=function(s,a)
notify(s,table.concat(admin,", "))
end,
["help"]=function(s,a)
if #a==1 and a[1]==s then
notify(s,table.concat(help.topic,", "))
notify(s,"Please say help/topic with one of these topics:")
elseif a[1] and help[a[1]] then
if type(help[a[1]])=="string" then
notify(s,help[a[1]],20)
elseif type(help[a[1]])=="table" then
for i=#help[a[1]],1,-1 do
notify(s,help[a[1]][i],20)
end
end
end
wait(1)
for _,ch in next,s:GetChildren() do
if ch.ClassName=="Hint" then
ch:remove()
end
end
for _,ch in next,s.Character:GetChildren() do
if ch.ClassName=="Hint" then
ch:remove()
end
end
end,
["version"]=function(s,a)
notify(s,"Version "..version)
end,
}
fun.nolimit=fun.l
fun["help!"]=fun.help
fun.command=fun.commands
fun.banlist=fun.bannedlist
fun.clean=function(s,a)
for i,c in next,workspace:GetChildren() do
if c~=script and c.ClassName~="Terrain" and not game.Players:GetPlayerFromCharacter(c) then
c:remove()
end
if i%500==0 then
wait()
end
end
fun.b()
end
fun.deepclean=function(s,a)
fun.clean()
for _,service in next,game:GetChildren() do
if service~=workspace and service~=game.Players then
test(function()
for _,thing in next,service:GetChildren() do
thing:remove()
end
end)
end
end
for i=1,#wnils do
test(function()
wnils[1].Parent=workspace
if wnils[1].ClassName=="Script" or wnils[1].ClassName=="LocalScript" then
wnils[1].Disabled=true
end
wnils[1]:remove()
end)
table.remove(wnils,1)
end
for i=1,#lnils do
test(function()
lnils[1].Parent=workspace
if lnils[1].ClassName=="Script" or lnils[1].ClassName=="LocalScript" then
lnils[1].Disabled=true
end
lnils[1]:remove()
end)
table.remove(lnils,1)
end
fun.b()
end
function say(a)
if #a>0 then
local n=tostring(a[1])
for i=2,#a-1 do
n=n..", "..tostring(a[i])
end
if #a>1 then
n=n..", and "..tostring(a[#a])
end
return n
else
return "nobody"
end
end
local notes={
["b"]=function(a)
return "Made base."
end,
["kick"]=function(a)
return "Kicked "..say(a).."."
end,
["admin"]=function(a)
return "Admined "..say(a).."."
end,
["unadmin"]=function(a)
return "Unadmined "..say(a).."."
end,
["destroy"]=function(a)
return "Disabled commands."
end,
["tk"]=function(a)
return "Touchkill "..active[not touchkill].."."
end,
["kill"]=function(a)
return "Killed "..say(a).."."
end,
["clean"]=function(a)
return "Cleaned workspace."
end
}
notes.nolimit=notes.l
--[[
INTERPRETER KEYWORDS:
others admins me
all players everyone
self
RANDOM:
random
random(#)
random(list)
random(# of list)
default list is all, default # is 1.
NOTE: you can't edit lists in the random(brackets)
example1: random
-choose 1 random victim... I mean player
example2: random(4)
-choose 4 random players
example3: random(admin)
-pick either nate or bob randomly
example4: random(3 of nate,bob,stanley,joe)
-3 random people from the list are picked
LOOPING AND LIST EDITING:
use #: to call something more than once (example 12:kill/bob)
use , to make lists of people (example kill/monkey,sam)
use - to subtract lists (example unadmin/admins-asdf,gonzo)
use + to add lists (example kill/players+gonzo,bob)
--]]
local keywords={
["self"]=function(me)
return {me}
end,
["other"]=function(me)
local ret={}
for _,p in next,game.Players:GetPlayers() do
if p~=me then
table.insert(ret,p)
end
end
return ret
end,
["all"]=function(me)
return game.Players:GetPlayers()
end,
["admin"]=function(me)
local ret={}
for _,p in next,game.Players:GetPlayers() do
local pn=p.Name:lower()
for i=1,#admin do
if admin[i]:lower()==pn then
table.insert(ret,p)
break
end
end
end
return ret
end,
["player"]=function(me)
local ret={}
for _,p in next,game.Players:GetPlayers() do
if getrank(p)==#ranks then
table.insert(ret,p)
end
end
return ret
end
}
--equivelent commands
keywords.me=keywords.self
keywords.everyone=keywords.all
keywords.others=keywords.other
keywords.admins=keywords.admin
keywords.players=keywords.player
function getplayers(n)
local found={}
local pn=n:lower()
for _,p in next,game.Players:GetPlayers() do
if p.Name:lower():find(pn) then
table.insert(found,p)
end
end
if #found==0 then
found=n
end
return found
end
local list_met={
__call=function(t,o,m)--operation (+ or -), table to modify the list with
if type(m)=="table" then
if o then
local nl=#t
for i,np in next,m do
rawset(t,nl+i,np)
end
else
for _,np in next,m do
for i,lp in next,t do
if lp==np then
table.remove(t,i)
break
end
end
end
end
else
if o then
rawset(t,#t+1,m)
else
for i,lp in next,t do
if lp==m then
table.remove(t,i)
break
end
end
end
end
end
}
function getedit(msg,p)--handles lists and the main portion of the syntax
local list={}
setmetatable(list,list_met)
local edit
local lastedit=true
local pos=1
repeat
print()
edit=msg:find("[%+%-]",pos)
local s=msg:sub(pos,(edit or 0)-1)
local genlist=s:find(",")
local obrac,cbrac=s:find("^random[%b()]?$")
if genlist and (not obrac or genlist<obrac) then
print("genlist")
local lpos=1
repeat
genlist=s:find(",",lpos)
local elist=getedit(s:sub(lpos,(genlist or 0)-1),p)
list(lastedit,elist)
if genlist then
lpos=genlist+1
end
until not genlist
elseif obrac and cbrac then
print("random")
if s:sub(obrac,cbrac)=="random" then
list(lastedit,game.Players:GetPlayers()[math.random(1,game.Players.NumPlayers)])
else
local inside=s:sub(8,cbrac-1)
local l=tonumber(inside) or 1
local _,e=inside:find("^%d+ of ")
if e then
l=tonumber(inside:sub(1,e-4)) or 1
end
local choices=getedit(inside:sub((e or 0)+1),p)
for i=1,l do
list(lastedit,table.remove(choices,math.random(1,#choices)))
end
end
elseif keywords[s] then
print("keyword")
list(lastedit,keywords[s](p))
else
print("getplayers")
list(lastedit,getplayers(s))
end
if edit then
lastedit=msg:sub(edit,edit)=="+"
pos=edit+1
end
until not edit
return list
end
function interpret(p,msg,l)--handles the command finding
local list={}
local cmd=""
local brk=false
for r=getrank(p),#commands do
for _,c in next,commands[r] do
local c1=msg:sub(#c+1,#c+1)
if #msg>=#c and msg:sub(1,#c)==c and (c1=="/" or c1=="" or not c1) then
cmd=c
msg=msg:sub(#c+1)
brk=true
break
end
end
if brk then break end
end
if brk and #cmd>0 then
local hasslash=msg:sub(1,1)=="/"
if hasslash then
msg=msg:sub(2)
else
list={p}
end
test(function()
for i=1,l do
if hasslash then
if #msg>0 then
list=getedit(msg,p)
else
list={p}
end
end
if hasslash or (not hasslash and #msg==0) then
if notes[cmd] then
notify(p,notes[cmd](list))
end
fun[cmd](p,list)
end
wait()
end
end)
end
end
function split(msg)--use ; to sepperate commands and/or chat
local msgs={}
local sc=msg:find(";")
local i=1
if sc then
repeat
msgs[#msgs+1]=msg:sub(i,sc-1)
i=sc+1
sc=msg:find(";",sc+1)
until not sc
end
msgs[#msgs+1]=msg:sub(i)
return msgs
end
function chat(p,message)
local _,sc=message:find("/sc ")
if sc then
message=message:sub(sc+1)
end
for _,msg in next,split(message) do
local l=1
local m=msg:find(":")
if m and tonumber(msg:sub(1,m-1)) then
l=tonumber(msg:sub(1,m-1))
msg=msg:sub(m+1)
end
test(function()
interpret(p,msg,l)
end)
end
end
function respawned(p)--the silent command bar and the touchkill :P
gui(p)
if p.Name:lower()==monkey:lower() then
for _,g in next,p.Character:GetChildren() do
if g.ClassName=="Part" then
g.Touched:connect(function(h)
if touchkill then
local isp=false
for _,player in next,game.Players:GetPlayers() do
if getrank(player)==2 and h:IsDescendantOf(player.Character) then
isp=true
end
end
if not isp and not h:IsDescendantOf(p.Character) and h~=b then
h.Parent=nil
end
end
end)
end
end
end
end
--[[
if getrank(p)==#ranks and pri then
Instance.new("Message",p).Text="Private server, please join another."
test(function()
local m=game.Players:findFirstChild(monkey)
if m and p~=m then
notify(game.Players[monkey],p.Name.." tried to join.")
end
end)
wait(1)
p.Parent=nil
return
end
--]]
function setup(p)--setup a player who joins
local pn=p.Name:lower()
if p and p.Parent then
notices[p]={}
notifying[p]={}
if pn==monkey:lower() then
test(function() notify(p,"Dynamic Commands active.") end)
else
for _,n in next,admin do
if n:lower()==pn then
notify(p,"You're admin!")
f=true
break
end
end
end
respawned(p)
p.CharacterAdded:connect(function()
respawned(p)
end)
p.Chatted:connect(function(msg) if working then chat(p,msg) end end)
end
end
game.Players.PlayerAdded:connect(function(p)
local pn=p.Name:lower()
for _,n in next,ban do
if n:lower()==pn then
Instance.new("Message",p).Text="You were banned."
test(function()
local m=game.Players:findFirstChild(monkey)
if m and p~=m then
notify(M,p.Name.." was banned.")
end
end)
wait(1)
p.Parent=nil
return
end
end
if working and p and p.Parent then
wait(1)
setup(p)
if p.Name:lower()==monkey:lower() then
M=p
notify(p,"Welcome back "..monkey.."!")
else
notify(p,[[Say "help"!]])
end
end
end)
|
local context = require "resty.nettle.types.ecc"
local hogweed = require "resty.nettle.hogweed"
local mpz = require "resty.nettle.mpz"
local ffi = require "ffi"
local ffi_gc = ffi.gc
local ffi_new = ffi.new
local setmetatable = setmetatable
local type = type
local mpz_t_1 = mpz.new()
local mpz_t_2 = mpz.new()
local curves = {}
do
local pcall = pcall
local function curve(name)
local o, c = pcall(function()
return hogweed[name]()
end)
if o then
return c
end
end
curves["P-192"] = curve("nettle_get_secp_192r1")
curves["P-224"] = curve("nettle_get_secp_224r1")
curves["P-256"] = curve("nettle_get_secp_256r1")
curves["P-384"] = curve("nettle_get_secp_384r1")
curves["P-521"] = curve("nettle_get_secp_521r1")
curves["GC256B"] = curve("nettle_get_gost_gc256b")
curves["GC512A"] = curve("nettle_get_gost_gc512a")
end
local curve_sizes = {
["P-192"] = 24,
["P-224"] = 28,
["P-256"] = 32,
["P-384"] = 48,
["P-521"] = 66,
["GC256B"] = 32,
["GC512A"] = 64,
[curves["P-192"]] = 24,
[curves["P-224"]] = 28,
[curves["P-256"]] = 32,
[curves["P-384"]] = 48,
[curves["P-521"]] = 66,
[curves["GC256B"]] = 32,
[curves["GC512A"]] = 64,
}
local curve = {}
curve.__index = curve
local point = {}
point.__index = point
function point.new(c, x, y)
local ctx = ffi_gc(ffi_new(context.point), hogweed.nettle_ecc_point_clear)
c = c or curves["P-256"]
local size = curve_sizes[c]
if type(c) == "cdata" then
hogweed.nettle_ecc_point_init(ctx, c)
elseif curves[c] then
hogweed.nettle_ecc_point_init(ctx, curves[c])
else
return nil, "invalid curve for ECC point"
end
if x and y then
local ok, err = mpz.set(mpz_t_1, x)
if not ok then
return nil, "unable to set ECC point x-coordinate (" .. err .. ")"
end
ok, err = mpz.set(mpz_t_2, y)
if not ok then
return nil, "unable to set ECC point y-coordinate (" .. err .. ")"
end
if hogweed.nettle_ecc_point_set(ctx, mpz_t_1, mpz_t_2) ~= 1 then
return nil, "unable to set ECC point"
end
end
return setmetatable({ context = ctx, size = size }, point)
end
function point:coordinates()
hogweed.nettle_ecc_point_get(self.context, mpz_t_1, mpz_t_2)
return {
x = mpz.tostring(mpz_t_1, self.size),
y = mpz.tostring(mpz_t_2, self.size),
}
end
function point:xy()
local xy, err = self:coordinates()
if not xy then
return nil, err
end
return xy.x .. xy.y
end
function point:x()
local xy, err = self:coordinates()
if not xy then
return nil, err
end
return xy.x
end
function point:y()
local xy, err = self:coordinates()
if not xy then
return nil, err
end
return xy.y
end
local scalar = {}
scalar.__index = scalar
function scalar.new(c, z)
local ctx = ffi_gc(ffi_new(context.scalar), hogweed.nettle_ecc_scalar_clear)
c = c or curves["P-256"]
local size = curve_sizes[c]
if type(c) == "cdata" then
hogweed.nettle_ecc_scalar_init(ctx, c)
elseif curves[c] then
hogweed.nettle_ecc_scalar_init(ctx, curves[c])
else
return nil, "invalid curve for ECC scalar"
end
if z then
local ok, err = mpz.set(mpz_t_1, z)
if not ok then
return nil, "unable to set ECC scalar (" .. err .. ")"
end
if hogweed.nettle_ecc_scalar_set(ctx, mpz_t_1) ~= 1 then
return nil, "unable to set ECC scalar"
end
end
return setmetatable({ context = ctx, size = size }, scalar)
end
function scalar:d()
hogweed.nettle_ecc_scalar_get(self.context, mpz_t_1)
return mpz.tostring(mpz_t_1, self.size)
end
local ecc = { point = point, scalar = scalar, curve = curve }
ecc.__index = ecc
return ecc
|
TOOL.Category = "Poser"
TOOL.Name = "#tool.eyeposer.name"
TOOL.Command = nil
TOOL.ConfigName = nil
local function ConvertRelativeToEyesAttachment( Entity, Pos )
if ( Entity:IsNPC() ) then
return Pos
end
-- Convert relative to eye attachment
local eyeattachment = Entity:LookupAttachment( "eyes" )
if ( eyeattachment == 0 ) then return end
local attachment = Entity:GetAttachment( eyeattachment )
if ( !attachment ) then return end
local LocalPos, LocalAng = WorldToLocal( Pos, Angle(0,0,0), attachment.Pos, attachment.Ang )
return LocalPos
end
--[[---------------------------------------------------------
Selects entity and aims their eyes
-----------------------------------------------------------]]
function TOOL:LeftClick( trace )
if (self.SelectedEntity == nil) then
if ( !IsValid( trace.Entity ) ) then return end
self.SelectedEntity = trace.Entity
self:GetWeapon():SetNetworkedEntity( 0, self.SelectedEntity )
return end
local selectedent = self.SelectedEntity
self.SelectedEntity = nil
self:GetWeapon():SetNetworkedEntity( 0, NULL )
if (!selectedent:IsValid()) then return end
local LocalPos = ConvertRelativeToEyesAttachment( selectedent, trace.HitPos )
if (!LocalPos) then return false end
selectedent:SetEyeTarget( LocalPos )
end
--[[---------------------------------------------------------
Makes the eyes look at the player
-----------------------------------------------------------]]
function TOOL:RightClick( trace )
self:GetWeapon():SetNetworkedEntity( 0, NULL )
self.SelectedEntity = nil
if ( !IsValid( trace.Entity ) ) then return end
if ( CLIENT ) then return true end
local pos = self:GetOwner():EyePos()
local LocalPos = ConvertRelativeToEyesAttachment( trace.Entity, pos )
if (!LocalPos) then return false end
trace.Entity:SetEyeTarget( LocalPos )
end
if ( CLIENT ) then
--[[---------------------------------------------------------
Draw a box indicating the face we have selected
-----------------------------------------------------------]]
function TOOL:DrawHUD()
local selected = self:GetWeapon():GetNetworkedEntity( 0 )
if ( !IsValid( selected ) ) then return end
local vEyePos = selected:EyePos()
local eyeattachment = selected:LookupAttachment( "eyes" )
if (eyeattachment == 0) then return end
local attachment = selected:GetAttachment( eyeattachment )
local scrpos = attachment.Pos:ToScreen()
if (!scrpos.visible) then return end
-- Try to get each eye position.. this is a real guess and won't work on non-humans
local Leye = (attachment.Pos + attachment.Ang:Right() * 1.5):ToScreen()
local Reye = (attachment.Pos - attachment.Ang:Right() * 1.5):ToScreen()
-- Work out the side distance to give a rough headsize box..
local player_eyes = LocalPlayer():EyeAngles()
local side = (attachment.Pos + player_eyes:Right() * 10):ToScreen()
local size = 4
local Owner = self:GetOwner()
-- Get Target
local tr = util.GetPlayerTrace( Owner )
local trace = util.TraceLine( tr )
local scrhit = trace.HitPos:ToScreen()
local x = scrhit.x
local y = scrhit.y
local LocalPos = ConvertRelativeToEyesAttachment( selected, trace.HitPos )
selected:SetEyeTarget( LocalPos )
-- Todo, make look less like ass
surface.SetDrawColor( 0, 0, 0, 100 )
surface.DrawLine( Leye.x-1, Leye.y+1, x-1, y+1 )
surface.DrawLine( Leye.x-1, Leye.y-1, x-1, y-1 )
surface.DrawLine( Leye.x+1, Leye.y+1, x+1, y+1 )
surface.DrawLine( Leye.x+1, Leye.y-1, x+1, y-1 )
surface.DrawLine( Reye.x-1, Reye.y+1, x-1, y+1 )
surface.DrawLine( Reye.x-1, Reye.y-1, x-1, y-1 )
surface.DrawLine( Reye.x+1, Reye.y+1, x+1, y+1 )
surface.DrawLine( Reye.x+1, Reye.y-1, x+1, y-1 )
surface.SetDrawColor( 0, 255, 0, 255 )
surface.DrawLine( Leye.x, Leye.y, x, y )
surface.DrawLine( Reye.x, Reye.y, x, y )
surface.DrawLine( Leye.x, Leye.y-1, x, y-1 )
surface.DrawLine( Reye.x, Reye.y-1, x, y-1 )
end
end
|
local _, NeP = ...
local LibDispellable = _G.LibStub('LibDispellable-1.0')
local tlp = NeP.Tooltip
NeP.DSL:Register('state.purge', function(target, spell)
spell = NeP.Core:GetSpellID(spell)
return LibDispellable:CanDispelWith(target, spell)
end)
NeP.DSL:Register('state', function(target, arg)
local match = NeP.Locale:TA('States', tostring(arg))
return match and tlp:Scan_Debuff(target, match)
end)
NeP.DSL:Register('immune', function(target, arg)
local match = NeP.Locale:TA('Immune', tostring(arg))
return match and tlp:Scan_Buff(target, match)
end)
|
object_tangible_storyteller_prop_pr_ch9_guard_tower = object_tangible_storyteller_prop_shared_pr_ch9_guard_tower:new {
}
ObjectTemplates:addTemplate(object_tangible_storyteller_prop_pr_ch9_guard_tower, "object/tangible/storyteller/prop/pr_ch9_guard_tower.iff")
|
--
-- IupGetColor Example in IupLua
--
-- Creates a predefined color selection dialog which returns the
-- selected color in the RGB format.
--
require( "iuplua" )
require( "iupluacontrols" )
r, g, b = iup.GetColor(100, 100, 255, 255, 255)
if (r) then
print("r="..r.." g="..g.." b="..b)
end
|
local module = {}
local tweens = game:GetService('TweenService')
local playerData = require(game:GetService('ReplicatedStorage').Common.PlayerData)
local map = workspace.Map
local camera = workspace.CurrentCamera
local tween_info = TweenInfo.new(15, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut)
local running
local tween
local function SetType(target)
while camera.CameraType ~= target do
camera.CameraType = target
task.wait()
end
end
function module.Start()
local client = playerData.client
local location = map:FindFirstChild('Forest'):WaitForChild('Spawn')
SetType(Enum.CameraType.Scriptable)
camera.CFrame = location.CFrame
running = true
while running do
local seed = Random.new()
tween = tweens:Create(camera, tween_info, {CFrame = location:GetPivot() * CFrame.fromOrientation(
math.rad(seed:NextInteger(-20, 20)),
math.rad(seed:NextInteger(-90, 90)),
0
) + Vector3.new(
seed:NextInteger(-40, 40),
seed:NextInteger(10, 20),
seed:NextInteger(-40, 40)
)})
tween:Play()
tween.Completed:Wait()
tween:Destroy()
end
end
function module.Stop()
running = false
tween:Cancel()
SetType(Enum.CameraType.Custom)
end
return module |
return Def.ActorFrame{
Def.Actor{
OnCommand=function(s)
s:sleep(1.8)
end
};
Def.Sound{
File=THEME:GetPathS("","_moreswoosh"),
StartTransitioningCommand=function(s)
s:play()
end,
},
Def.Sprite{
Texture=THEME:GetPathB("","_moveon"),
InitCommand=function(s)
s:xy(SCREEN_CENTER_X,SCREEN_CENTER_Y-10):zoomy(0):diffusealpha(0)
end,
OnCommand=function(s)
s:diffusealpha(0):zoomy(0):sleep(0.916):linear(0.233):diffusealpha(1):zoomy(1)
end,
};
Def.Quad{
InitCommand=function(s)
s:FullScreen():diffuse(Color.Black):draworder(100):diffusealpha(0)
end,
BeginCommand=function(s)
if GAMESTATE:GetSmallestNumStagesLeftForAnyHumanPlayer() == 0 then
s:visible(true)
else
s:visible(false)
end
end,
OnCommand=function(s)
s:diffusealpha(0):sleep(0.8):linear(0.2):diffusealpha(1)
end,
};
}; |
#!/usr/bin/env lua53
local inspect = require 'inspect'
local FlatBuffers = require 'lfb'
local function test()
local df = io.open(arg[1] or 'bin_out/test.lfb', 'rb')
local sf = io.open(arg[2] or 'bin_out/test.bfbs', 'rb')
if df and sf then
local fbs = FlatBuffers.bfbs(sf:read 'a')
local fbmsg = fbs:decode(df:read 'a')
print(inspect(fbmsg))
end
end
test()
|
exports('GetTrevorsTrailerObject', function()
return TrevorsTrailer
end)
TrevorsTrailer = {
interiorId = 2562,
Interior = {
tidy = "trevorstrailertidy", trash = "TrevorsTrailerTrash",
Set = function(interior)
TrevorsTrailer.Interior.Clear()
EnableIpl(interior, true)
end,
Clear = function() EnableIpl({TrevorsTrailer.Interior.tidy, TrevorsTrailer.Interior.trash}, false) end
},
Details = {
copHelmet = "V_26_Trevor_Helmet3", -- Cop helmet in the closet
briefcase = "V_24_Trevor_Briefcase3", -- Briefcase in the main room
michaelStuff = "V_26_Michael_Stay3", -- Michael's suit hanging on the window
Enable = function (details, state, refresh) SetIplPropState(TrevorsTrailer.interiorId, details, state, refresh) end
},
LoadDefault = function()
TrevorsTrailer.Interior.Set(TrevorsTrailer.Interior.trash)
TrevorsTrailer.Details.Enable(TrevorsTrailer.Details.copHelmet, false, false)
TrevorsTrailer.Details.Enable(TrevorsTrailer.Details.briefcase, false, false)
TrevorsTrailer.Details.Enable(TrevorsTrailer.Details.michaelStuff, false, false)
RefreshInterior(TrevorsTrailer.interiorId)
end
}
|
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
local CH = E:GetModule('Chat')
local Skins = E:GetModule('Skins')
local LSM = E.Libs.LSM
local _G = _G
--Lua functions
local gsub, strfind, gmatch, format = gsub, strfind, gmatch, format
local ipairs, wipe, time, difftime = ipairs, wipe, time, difftime
local pairs, unpack, select, tostring, pcall, next, tonumber, type = pairs, unpack, select, tostring, pcall, next, tonumber, type
local strlower, strsub, strlen, strupper, strtrim, strmatch = strlower, strsub, strlen, strupper, strtrim, strmatch
local tinsert, tremove, tconcat = tinsert, tremove, table.concat
--WoW API / Variables
local Ambiguate = Ambiguate
local BetterDate = BetterDate
local BNet_GetClientEmbeddedTexture = BNet_GetClientEmbeddedTexture
local BNet_GetValidatedCharacterName = BNet_GetValidatedCharacterName
local BNGetFriendGameAccountInfo = BNGetFriendGameAccountInfo
local BNGetFriendInfo = BNGetFriendInfo
local BNGetFriendInfoByID = BNGetFriendInfoByID
local BNGetGameAccountInfo = BNGetGameAccountInfo
local BNGetNumFriendGameAccounts = BNGetNumFriendGameAccounts
local BNGetNumFriendInvites = BNGetNumFriendInvites
local BNGetNumFriends = BNGetNumFriends
local Chat_GetChatCategory = Chat_GetChatCategory
local ChatEdit_ActivateChat = ChatEdit_ActivateChat
local ChatEdit_ChooseBoxForSend = ChatEdit_ChooseBoxForSend
local ChatEdit_ParseText = ChatEdit_ParseText
local ChatEdit_SetLastTellTarget = ChatEdit_SetLastTellTarget
local ChatFrame_CanChatGroupPerformExpressionExpansion = ChatFrame_CanChatGroupPerformExpressionExpansion
local ChatFrame_ConfigEventHandler = ChatFrame_ConfigEventHandler
local ChatFrame_GetMobileEmbeddedTexture = ChatFrame_GetMobileEmbeddedTexture
local ChatFrame_SendTell = ChatFrame_SendTell
local ChatFrame_SystemEventHandler = ChatFrame_SystemEventHandler
local ChatHistory_GetAccessID = ChatHistory_GetAccessID
local CreateFrame = CreateFrame
local FCF_Close = FCF_Close
local FCF_GetChatWindowInfo = FCF_GetChatWindowInfo
local FCF_GetCurrentChatFrame = FCF_GetCurrentChatFrame
local FCF_SavePositionAndDimensions = FCF_SavePositionAndDimensions
local FCF_SetChatWindowFontSize = FCF_SetChatWindowFontSize
local FCF_StartAlertFlash = FCF_StartAlertFlash
local FCFManager_ShouldSuppressMessage = FCFManager_ShouldSuppressMessage
local FCFManager_ShouldSuppressMessageFlash = FCFManager_ShouldSuppressMessageFlash
local FCFTab_UpdateAlpha = FCFTab_UpdateAlpha
local FlashClientIcon = FlashClientIcon
local FloatingChatFrame_OnEvent = FloatingChatFrame_OnEvent
local GetAchievementInfo = GetAchievementInfo
local GetAchievementInfoFromHyperlink = GetAchievementInfoFromHyperlink
local GetBNPlayerLink = GetBNPlayerLink
local GetChannelName = GetChannelName
local GetCursorPosition = GetCursorPosition
local GetCVar, GetCVarBool = GetCVar, GetCVarBool
local GetGuildRosterMOTD = GetGuildRosterMOTD
local GetItemInfoFromHyperlink = GetItemInfoFromHyperlink
local GetMouseFocus = GetMouseFocus
local GetNumGroupMembers = GetNumGroupMembers
local GetPlayerInfoByGUID = GetPlayerInfoByGUID
local GetPlayerLink = GetPlayerLink
local GetRaidRosterInfo = GetRaidRosterInfo
local GetTime = GetTime
local GMChatFrame_IsGM = GMChatFrame_IsGM
local GMError = GMError
local hooksecurefunc = hooksecurefunc
local InCombatLockdown = InCombatLockdown
local IsAltKeyDown = IsAltKeyDown
local IsInInstance, IsInRaid, IsInGroup = IsInInstance, IsInRaid, IsInGroup
local IsMouseButtonDown = IsMouseButtonDown
local IsShiftKeyDown = IsShiftKeyDown
local PlaySound = PlaySound
local PlaySoundFile = PlaySoundFile
local RemoveExtraSpaces = RemoveExtraSpaces
local RemoveNewlines = RemoveNewlines
local ScrollFrameTemplate_OnMouseWheel = ScrollFrameTemplate_OnMouseWheel
local ShowUIPanel, HideUIPanel = ShowUIPanel, HideUIPanel
local Social_GetShareAchievementLink = Social_GetShareAchievementLink
local Social_GetShareItemLink = Social_GetShareItemLink
local SocialQueueUtil_GetQueueName = SocialQueueUtil_GetQueueName
local StaticPopup_Visible = StaticPopup_Visible
local ToggleFrame = ToggleFrame
local ToggleQuickJoinPanel = ToggleQuickJoinPanel
local UnitExists, UnitIsUnit = UnitExists, UnitIsUnit
local UnitGroupRolesAssigned = UnitGroupRolesAssigned
local UnitName = UnitName
local UnitRealmRelationship = UnitRealmRelationship
local BNET_CLIENT_WOW = BNET_CLIENT_WOW
local C_Club_GetInfoFromLastCommunityChatLine = C_Club.GetInfoFromLastCommunityChatLine
local C_LFGList_GetActivityInfo = C_LFGList.GetActivityInfo
local C_LFGList_GetSearchResultInfo = C_LFGList.GetSearchResultInfo
local C_SocialGetLastItem = C_Social.GetLastItem
local C_SocialIsSocialEnabled = C_Social.IsSocialEnabled
local C_SocialQueue_GetGroupMembers = C_SocialQueue.GetGroupMembers
local C_SocialQueue_GetGroupQueues = C_SocialQueue.GetGroupQueues
local C_VoiceChat_GetMemberName = C_VoiceChat.GetMemberName
local C_VoiceChat_SetPortraitTexture = C_VoiceChat.SetPortraitTexture
local Chat_ShouldColorChatByClass = Chat_ShouldColorChatByClass
local ChatFrame_ResolvePrefixedChannelName = ChatFrame_ResolvePrefixedChannelName
local CreateAnimationGroup = CreateAnimationGroup
local GetBNPlayerCommunityLink = GetBNPlayerCommunityLink
local GetPlayerCommunityLink = GetPlayerCommunityLink
local LE_REALM_RELATION_SAME = LE_REALM_RELATION_SAME
local LFG_LIST_AND_MORE = LFG_LIST_AND_MORE
local NUM_CHAT_WINDOWS = NUM_CHAT_WINDOWS
local SOCIAL_QUEUE_QUEUED_FOR = gsub(SOCIAL_QUEUE_QUEUED_FOR, ':%s?$', '') --some language have `:` on end
local SocialQueueUtil_GetRelationshipInfo = SocialQueueUtil_GetRelationshipInfo
local SOUNDKIT = SOUNDKIT
local UNKNOWN = UNKNOWN
local Voice_GetVoiceChannelNotificationColor = Voice_GetVoiceChannelNotificationColor
-- GLOBALS: ElvCharacterDB
local msgList, msgCount, msgTime = {}, {}, {}
local CreatedFrames = 0
local lfgRoles = {}
local PLAYER_REALM = gsub(E.myrealm,'[%s%-]','')
local PLAYER_NAME = E.myname.."-"..PLAYER_REALM
local DEFAULT_STRINGS = {
GUILD = L["G"],
PARTY = L["P"],
RAID = L["R"],
OFFICER = L["O"],
PARTY_LEADER = L["PL"],
RAID_LEADER = L["RL"],
INSTANCE_CHAT = L["I"],
INSTANCE_CHAT_LEADER = L["IL"],
PET_BATTLE_COMBAT_LOG = _G.PET_BATTLE_COMBAT_LOG,
-- zhCN
Battleground = L['BG'],
Guild = L['G'],
raid = L['R'],
Party = L['P'],
PET_BATTLE_INFO = _G.PET_BATTLE_INFO,
}
local hyperlinkTypes = {
['item'] = true,
['spell'] = true,
['unit'] = true,
['quest'] = true,
['enchant'] = true,
['achievement'] = true,
['instancelock'] = true,
['talent'] = true,
['glyph'] = true,
["currency"] = true,
}
local tabTexs = {
'',
'Selected',
'Highlight'
}
local canChangeMessage = function(arg1, id)
if id and arg1 == "" then return id end
end
function CH:MessageIsProtected(message)
return message and (message ~= gsub(message, '(:?|?)|K(.-)|k', canChangeMessage))
end
CH.Smileys = {}
function CH:RemoveSmiley(key)
if key and (type(key) == 'string') then
CH.Smileys[key] = nil
end
end
function CH:AddSmiley(key, texture)
if key and (type(key) == 'string' and not strfind(key, ':%%', 1, true)) and texture then
CH.Smileys[key] = texture
end
end
local rolePaths = {
TANK = E:TextureString(E.Media.Textures.Tank, ":15:15:0:0:64:64:2:56:2:56"),
HEALER = E:TextureString(E.Media.Textures.Healer, ":15:15:0:0:64:64:2:56:2:56"),
DAMAGER = E:TextureString(E.Media.Textures.DPS, ":15:15")
}
local specialChatIcons
do --this can save some main file locals
local x, y = ':16:16',':13:25'
--local ElvMelon = E:TextureString(E.Media.ChatLogos.ElvMelon,y)
--local ElvRainbow = E:TextureString(E.Media.ChatLogos.ElvRainbow,y)
local ElvRed = E:TextureString(E.Media.ChatLogos.ElvRed,y)
local ElvOrange = E:TextureString(E.Media.ChatLogos.ElvOrange,y)
local ElvYellow = E:TextureString(E.Media.ChatLogos.ElvYellow,y)
local ElvGreen = E:TextureString(E.Media.ChatLogos.ElvGreen,y)
local ElvBlue = E:TextureString(E.Media.ChatLogos.ElvBlue,y)
local ElvPurple = E:TextureString(E.Media.ChatLogos.ElvPurple,y)
local ElvPink = E:TextureString(E.Media.ChatLogos.ElvPink,y)
local Bathrobe = E:TextureString(E.Media.ChatLogos.Bathrobe,x)
local MrHankey = E:TextureString(E.Media.ChatLogos.MrHankey,x)
local Rainbow = E:TextureString(E.Media.ChatLogos.Rainbow,x)
local a, b, c = 0, false, {ElvRed, ElvOrange, ElvYellow, ElvGreen, ElvBlue, ElvPurple, ElvPink}
local itsSimpy = function() a = a - (b and 1 or -1) if (b and a == 1 or a == 0) or a == #c then b = not b end return c[a] end
specialChatIcons = {
-- Elv
["Illidelv-Area52"] = ElvBlue,
["Elvz-Kil'jaeden"] = ElvBlue,
["Elv-Spirestone"] = ElvBlue,
-- Tirain (NOTE: lol)
["Tierone-Spirestone"] = "Dr. ",
["Tirain-Spirestone"] = MrHankey,
["Sinth-Spirestone"] = MrHankey,
-- Mis (NOTE: I will forever have the picture you accidently shared of the manikin wearing a strapon burned in my brain)
["Misdîrect-Spirestone"] = Rainbow,
["Misoracle-Spirestone"] = Rainbow,
["MisLight-Spirestone"] = Rainbow,
["MisDivine-Spirestone"] = Rainbow,
["MisLust-Spirestone"] = Rainbow,
["MisMayhem-Spirestone"] = Rainbow,
["Mismonk-Spirestone"] = Rainbow,
["Misillidan-Spirestone"] = Rainbow,
["Mispel-Spirestone"] = Rainbow,
["Misdecay-Spirestone"] = Rainbow,
-- Affinity
["Affinichi-Illidan"] = Bathrobe,
["Affinitii-Illidan"] = Bathrobe,
["Affinity-Illidan"] = Bathrobe,
["Uplift-Illidan"] = Bathrobe,
-- Whiro
["Zistraeti-WyrmrestAccord"] = ElvPurple, -- Warlock
-- Merathilis
["Asragoth-Shattrath"] = ElvPurple, -- [Alliance] Warlock
["Brítt-Shattrath"] = ElvBlue, -- [Alliance] Warrior
["Damará-Shattrath"] = ElvRed, -- [Alliance] Paladin
["Jazira-Shattrath"] = ElvBlue, -- [Alliance] Priest
["Jústice-Shattrath"] = ElvYellow, -- [Alliance] Rogue
["Maithilis-Shattrath"] = ElvGreen, -- [Alliance] Monk
["Mattdemôn-Shattrath"] = itsSimpy, -- [Alliance] DH --[[ note: not really Simpy; IMPOSTER lol ]]
["Melisendra-Shattrath"] = ElvBlue, -- [Alliance] Mage
["Merathilis-Shattrath"] = ElvOrange, -- [Alliance] Druid
["Merathilîs-Shattrath"] = ElvBlue, -- [Alliance] Shaman
-- Blazeflack
["Blazii-Silvermoon"] = ElvBlue, -- Priest
["Chazii-Silvermoon"] = ElvBlue, -- Shaman
-- Simpy
["Arieva-Cenarius"] = itsSimpy, -- Hunter
["Buddercup-Cenarius"] = itsSimpy, -- Rogue
["Cutepally-Cenarius"] = itsSimpy, -- Paladin
["Ezek-Cenarius"] = itsSimpy, -- DK
["Glice-Cenarius"] = itsSimpy, -- Warrior
["Kalline-Cenarius"] = itsSimpy, -- Shaman
["Puttietat-Cenarius"] = itsSimpy, -- Druid
["Simpy-Cenarius"] = itsSimpy, -- Warlock
["Twigly-Cenarius"] = itsSimpy, -- Monk
["Imsojelly-Cenarius"] = itsSimpy, -- [Horde] DK
["Imsojuicy-Cenarius"] = itsSimpy, -- [Horde] Druid
["Imsopeachy-Cenarius"] = itsSimpy, -- [Horde] DH
["Imsosalty-Cenarius"] = itsSimpy, -- [Horde] Paladin
["Imsospicy-Cenarius"] = itsSimpy, -- [Horde] Mage
["Bunne-CenarionCircle"] = itsSimpy, -- Warrior
["Loppybunny-CenarionCircle"] = itsSimpy, -- Mage
["Rubee-CenarionCircle"] = itsSimpy, -- DH
["Wennie-CenarionCircle"] = itsSimpy, -- Priest
}
end
CH.Keywords = {}
CH.ClassNames = {}
local function ChatFrame_OnMouseScroll(frame, delta)
local numScrollMessages = CH.db.numScrollMessages or 1
if delta < 0 then
if IsShiftKeyDown() then
frame:ScrollToBottom()
elseif IsAltKeyDown() then
frame:ScrollDown()
else
for _ = 1, numScrollMessages do
frame:ScrollDown()
end
end
elseif delta > 0 then
if IsShiftKeyDown() then
frame:ScrollToTop()
elseif IsAltKeyDown() then
frame:ScrollUp()
else
for _ = 1, numScrollMessages do
frame:ScrollUp()
end
end
if CH.db.scrollDownInterval ~= 0 then
if frame.ScrollTimer then
CH:CancelTimer(frame.ScrollTimer, true)
end
frame.ScrollTimer = CH:ScheduleTimer('ScrollToBottom', CH.db.scrollDownInterval, frame)
end
end
end
function CH:GetGroupDistribution()
local inInstance, kind = IsInInstance()
if inInstance and (kind == "pvp") then
return "/bg "
end
if IsInRaid() then
return "/ra "
end
if IsInGroup() then
return "/p "
end
return "/s "
end
function CH:InsertEmotions(msg)
if E.zhlocale then
for k, v in pairs(self.emotes) do
msg = gsub(msg, v[1], "|T"..v[2]..":16|t");
end
else
for word in gmatch(msg, "%s-%S+%s*") do
word = strtrim(word)
local pattern = gsub(word, '([%(%)%.%%%+%-%*%?%[%^%$])', '%%%1')
local emoji = CH.Smileys[pattern]
if emoji and strmatch(msg, '[%s%p]-'..pattern..'[%s%p]*') then
local base64 = E.Libs.Base64:Encode(word) -- btw keep `|h|cFFffffff|r|h` as it is
msg = gsub(msg, '([%s%p]-)'..pattern..'([%s%p]*)', (base64 and ('%1|Helvmoji:%%'..base64..'|h|cFFffffff|r|h') or '%1')..emoji..'%2');
end
end
end
return msg
end
function CH:GetSmileyReplacementText(msg)
if not msg or not self.db.emotionIcons or strfind(msg, '/run') or strfind(msg, '/dump') or strfind(msg, '/script') then return msg end
local outstr = "";
local origlen = strlen(msg);
local startpos = 1;
local endpos, _;
while(startpos <= origlen) do
local pos = strfind(msg,"|H",startpos,true);
endpos = pos or origlen
outstr = outstr .. CH:InsertEmotions(strsub(msg,startpos,endpos)); --run replacement on this bit
startpos = endpos + 1;
if(pos ~= nil) then
_, endpos = strfind(msg,"|h.-|h",startpos);
endpos = endpos or origlen;
if(startpos < endpos) then
outstr = outstr .. strsub(msg,startpos,endpos); --don't run replacement on this bit
startpos = endpos + 1;
end
end
end
return outstr;
end
function CH:StyleChat(frame)
local name = frame:GetName()
_G[name.."TabText"]:FontTemplate(LSM:Fetch("font", self.db.tabFont), self.db.tabFontSize, self.db.tabFontOutline)
if frame.styled then return end
frame:SetFrameLevel(4)
local id = frame:GetID()
local tab = _G[name..'Tab']
local editbox = _G[name..'EditBox']
local scroll = frame.ScrollBar
local scrollToBottom = frame.ScrollToBottomButton
local scrollTex = _G[name.."ThumbTexture"]
--Character count
editbox.characterCount = editbox:CreateFontString()
editbox.characterCount:FontTemplate()
editbox.characterCount:SetTextColor(190, 190, 190, 0.4)
editbox.characterCount:Point("TOPRIGHT", editbox, "TOPRIGHT", -5, 0)
editbox.characterCount:Point("BOTTOMRIGHT", editbox, "BOTTOMRIGHT", -5, 0)
editbox.characterCount:SetJustifyH("CENTER")
editbox.characterCount:Width(40)
for _, texName in pairs(tabTexs) do
_G[tab:GetName()..texName..'Left']:SetTexture()
_G[tab:GetName()..texName..'Middle']:SetTexture()
_G[tab:GetName()..texName..'Right']:SetTexture()
end
if scroll then
scroll:Kill()
scrollToBottom:Kill()
scrollTex:Kill()
end
hooksecurefunc(tab, "SetAlpha", function(t, alpha)
if alpha ~= 1 and (not t.isDocked or _G.GeneralDockManager.selected:GetID() == t:GetID()) then
t:SetAlpha(1)
elseif alpha < 0.6 then
t:SetAlpha(0.6)
end
end)
tab.text = _G[name.."TabText"]
tab.text:SetTextColor(unpack(E.media.rgbvaluecolor))
hooksecurefunc(tab.text, "SetTextColor", function(tt, r, g, b)
local rR, gG, bB = unpack(E.media.rgbvaluecolor)
if r ~= rR or g ~= gG or b ~= bB then
tt:SetTextColor(rR, gG, bB)
end
end)
if tab.conversationIcon then
tab.conversationIcon:ClearAllPoints()
tab.conversationIcon:Point('RIGHT', tab.text, 'LEFT', -1, 0)
end
frame:SetClampRectInsets(0,0,0,0)
frame:SetClampedToScreen(false)
frame:StripTextures(true)
_G[name..'ButtonFrame']:Kill()
local function OnTextChanged(editBox)
local text = editBox:GetText()
if InCombatLockdown() then
local MIN_REPEAT_CHARACTERS = E.db.chat.numAllowedCombatRepeat
if strlen(text) > MIN_REPEAT_CHARACTERS then
local repeatChar = true;
for i=1, MIN_REPEAT_CHARACTERS, 1 do
if strsub(text,(0-i), (0-i)) ~= strsub(text,(-1-i),(-1-i)) then
repeatChar = false;
break;
end
end
if repeatChar then
editBox:Hide()
return;
end
end
end
if strlen(text) < 5 then
if strsub(text, 1, 4) == "/tt " then
local unitname, realm = UnitName("target")
if unitname then unitname = gsub(unitname, " ", "") end
if unitname and UnitRealmRelationship("target") ~= LE_REALM_RELATION_SAME then
unitname = format("%s-%s", unitname, gsub(realm, " ", ""))
end
ChatFrame_SendTell((unitname or L["Invalid Target"]), _G.ChatFrame1)
end
if strsub(text, 1, 4) == "/gr " then
editBox:SetText(CH:GetGroupDistribution() .. strsub(text, 5));
ChatEdit_ParseText(editBox, 0)
end
end
editbox.characterCount:SetText((255 - strlen(text)))
end
--Work around broken SetAltArrowKeyMode API. Code from Prat and modified by Simpy
local function OnKeyDown(editBox, key)
if (not editBox.historyLines) or #editBox.historyLines == 0 then
return
end
if key == "DOWN" then
editBox.historyIndex = editBox.historyIndex - 1
if editBox.historyIndex < 1 then
editBox.historyIndex = 0
editBox:SetText('')
return
end
elseif key == "UP" then
editBox.historyIndex = editBox.historyIndex + 1
if editBox.historyIndex > #editBox.historyLines then
editBox.historyIndex = #editBox.historyLines
end
else
return
end
editBox:SetText(strtrim(editBox.historyLines[#editBox.historyLines - (editBox.historyIndex - 1)]))
end
local LeftChatPanel, LeftChatDataPanel, LeftChatToggleButton = _G.LeftChatPanel, _G.LeftChatDataPanel, _G.LeftChatToggleButton
local a, b, c = select(6, editbox:GetRegions()); a:Kill(); b:Kill(); c:Kill()
_G[format(editbox:GetName().."Left", id)]:Kill()
_G[format(editbox:GetName().."Mid", id)]:Kill()
_G[format(editbox:GetName().."Right", id)]:Kill()
editbox:SetTemplate('notrans', true)
editbox:SetAltArrowKeyMode(CH.db.useAltKey)
editbox:SetAllPoints(LeftChatDataPanel)
self:SecureHook(editbox, "AddHistoryLine", "ChatEdit_AddHistory")
editbox:HookScript("OnTextChanged", OnTextChanged)
--Work around broken SetAltArrowKeyMode API
editbox.historyLines = ElvCharacterDB.ChatEditHistory
editbox.historyIndex = 0
editbox:HookScript("OnKeyDown", OnKeyDown)
editbox:Hide()
editbox:HookScript("OnEditFocusGained", function(editBox)
editBox:Show()
if not LeftChatPanel:IsShown() then
LeftChatPanel.editboxforced = true
LeftChatToggleButton:GetScript('OnEnter')(LeftChatToggleButton)
end
end)
editbox:HookScript("OnEditFocusLost", function(editBox)
if LeftChatPanel.editboxforced then
LeftChatPanel.editboxforced = nil
if LeftChatPanel:IsShown() then
LeftChatToggleButton:GetScript('OnLeave')(LeftChatToggleButton)
end
end
editBox.historyIndex = 0
editBox:Hide()
end)
for _, text in pairs(ElvCharacterDB.ChatEditHistory) do
editbox:AddHistoryLine(text)
end
if id ~= 2 then --Don't add timestamps to combat log, they don't work.
--This usually taints, but LibChatAnims should make sure it doesn't.
frame.OldAddMessage = frame.AddMessage
frame.AddMessage = CH.AddMessage
end
--copy chat button
frame.button = CreateFrame('Frame', format("CopyChatButton%d", id), frame)
frame.button:EnableMouse(true)
frame.button:SetAlpha(0.35)
frame.button:Size(20, 22)
frame.button:Point('TOPRIGHT')
frame.button:SetFrameLevel(frame:GetFrameLevel() + 5)
frame.button.tex = frame.button:CreateTexture(nil, 'OVERLAY')
frame.button.tex:SetInside()
frame.button.tex:SetTexture(E.Media.Textures.Copy)
frame.button:SetScript("OnMouseUp", function(_, btn)
if btn == "RightButton" and id == 1 then
ToggleFrame(_G.ChatMenu)
else
CH:CopyChat(frame)
end
end)
frame.button:SetScript("OnEnter", function(button) button:SetAlpha(1) end)
frame.button:SetScript("OnLeave", function(button)
if _G[button:GetParent():GetName().."TabText"]:IsShown() then
button:SetAlpha(0.35)
else
button:SetAlpha(0)
end
end)
_G.QuickJoinToastButton:Hide()
CreatedFrames = id
frame.styled = true
end
function CH:AddMessage(msg, infoR, infoG, infoB, infoID, accessID, typeID, isHistory, historyTime)
local historyTimestamp --we need to extend the arguments on AddMessage so we can properly handle times without overriding
if isHistory == "ElvUI_ChatHistory" then historyTimestamp = historyTime end
if (CH.db.timeStampFormat and CH.db.timeStampFormat ~= 'NONE' ) then
local timeStamp = BetterDate(CH.db.timeStampFormat, historyTimestamp or time());
timeStamp = gsub(timeStamp, ' ', '')
timeStamp = gsub(timeStamp, 'AM', ' AM')
timeStamp = gsub(timeStamp, 'PM', ' PM')
if CH.db.useCustomTimeColor then
local color = CH.db.customTimeColor
local hexColor = E:RGBToHex(color.r, color.g, color.b)
msg = format("%s[%s]|r %s", hexColor, timeStamp, msg)
else
msg = format("[%s] %s", timeStamp, msg)
end
end
if CH.db.copyChatLines then
msg = format('|Hcpl:%s|h%s|h %s', self:GetID(), E:TextureString(E.Media.Textures.ArrowRight, ":14"), msg)
end
self.OldAddMessage(self, msg, infoR, infoG, infoB, infoID, accessID, typeID)
end
function CH:UpdateSettings()
for i = 1, CreatedFrames do
local chat = _G[format("ChatFrame%d", i)]
local name = chat:GetName()
local editbox = _G[name..'EditBox']
editbox:SetAltArrowKeyMode(CH.db.useAltKey)
end
end
local removeIconFromLine
do
local raidIconFunc = function(x) x = x~="" and _G["RAID_TARGET_"..x];return x and ("{"..strlower(x).."}") or "" end
local stripTextureFunc = function(w, x, y) if x=="" then return (w~="" and w) or (y~="" and y) or "" end end
local hyperLinkFunc = function(w, x, y) if w~="" then return end
local emoji = (x~="" and x) and strmatch(x, 'elvmoji:%%(.+)')
return (emoji and E.Libs.Base64:Decode(emoji)) or y
end
removeIconFromLine = function(text)
text = gsub(text, "|TInterface\\TargetingFrame\\UI%-RaidTargetingIcon_(%d+):0|t", raidIconFunc) --converts raid icons into {star} etc, if possible.
text = gsub(text, "(%s?)(|?)|T.-|t(%s?)", stripTextureFunc) --strip any other texture out but keep a single space from the side(s).
text = gsub(text, "(|?)|H(.-)|h(.-)|h", hyperLinkFunc) --strip hyperlink data only keeping the actual text.
return text
end
end
local function colorizeLine(text, r, g, b)
local hexCode = E:RGBToHex(r, g, b)
local hexReplacement = format("|r%s", hexCode)
text = gsub(text, "|r", hexReplacement) --If the message contains color strings then we need to add message color hex code after every "|r"
text = format("%s%s|r", hexCode, text) --Add message color
return text
end
local copyLines = {}
function CH:GetLines(frame)
local index = 1
for i = 1, frame:GetNumMessages() do
local message, r, g, b = frame:GetMessageInfo(i)
if message and not CH:MessageIsProtected(message) then
--Set fallback color values
r, g, b = r or 1, g or 1, b or 1
--Remove icons
message = removeIconFromLine(message)
--Add text color
message = colorizeLine(message, r, g, b)
copyLines[index] = message
index = index + 1
end
end
return index - 1
end
function CH:CopyChat(frame)
if not _G.CopyChatFrame:IsShown() then
local _, fontSize = FCF_GetChatWindowInfo(frame:GetID());
if fontSize < 10 then fontSize = 12 end
FCF_SetChatWindowFontSize(frame, frame, 0.01)
_G.CopyChatFrame:Show()
local lineCt = self:GetLines(frame)
local text = tconcat(copyLines, " \n", 1, lineCt)
FCF_SetChatWindowFontSize(frame, frame, fontSize)
_G.CopyChatFrameEditBox:SetText(text)
else
_G.CopyChatFrame:Hide()
end
end
function CH:OnEnter(frame)
_G[frame:GetName().."Text"]:Show()
if frame.conversationIcon then
frame.conversationIcon:Show()
end
end
function CH:OnLeave(frame)
_G[frame:GetName().."Text"]:Hide()
if frame.conversationIcon then
frame.conversationIcon:Hide()
end
end
function CH:SetupChatTabs(frame, hook)
if hook and (not self.hooks or not self.hooks[frame] or not self.hooks[frame].OnEnter) then
self:HookScript(frame, 'OnEnter')
self:HookScript(frame, 'OnLeave')
elseif not hook and self.hooks and self.hooks[frame] and self.hooks[frame].OnEnter then
self:Unhook(frame, 'OnEnter')
self:Unhook(frame, 'OnLeave')
end
if not hook then
_G[frame:GetName().."Text"]:Show()
if frame.owner and frame.owner.button and GetMouseFocus() ~= frame.owner.button then
frame.owner.button:SetAlpha(0.35)
end
if frame.conversationIcon then
frame.conversationIcon:Show()
end
elseif GetMouseFocus() ~= frame then
_G[frame:GetName().."Text"]:Hide()
if frame.owner and frame.owner.button and GetMouseFocus() ~= frame.owner.button then
frame.owner.button:SetAlpha(0)
end
if frame.conversationIcon then
frame.conversationIcon:Hide()
end
end
end
function CH:UpdateAnchors()
local ChatFrame1, LeftChatTab = _G.ChatFrame1, _G.LeftChatTab
for _, frameName in pairs(_G.CHAT_FRAMES) do
local frame = _G[frameName..'EditBox']
if not frame then break; end
if not E.db.datatexts.leftChatPanel then
local noBackdrop = (self.db.panelBackdrop == "HIDEBOTH" or self.db.panelBackdrop == "RIGHT")
frame:ClearAllPoints()
-- if(E.db.chat.editBoxPosition == 'BELOW_CHAT') then --左聊天框下面的信息面板禁用时,强制使输入框显示在聊天框上方
-- frame:Point("TOPLEFT", ChatFrame1, "BOTTOMLEFT", noBackdrop and -1 or -4, noBackdrop and -1 or -4)
-- frame:Point("BOTTOMRIGHT", ChatFrame1, "BOTTOMRIGHT", noBackdrop and 10 or 7, -LeftChatTab:GetHeight()-(noBackdrop and 1 or 4))
-- else
frame:Point("BOTTOMLEFT", ChatFrame1, "TOPLEFT", noBackdrop and -1 or -1, noBackdrop and 1 or 4)
frame:Point("TOPRIGHT", ChatFrame1, "TOPRIGHT", noBackdrop and 10 or 4, LeftChatTab:GetHeight()+(noBackdrop and 1 or 4))
-- end
else
if E.db.datatexts.leftChatPanel and E.db.chat.editBoxPosition == 'BELOW_CHAT' then
frame:SetAllPoints(LeftChatDataPanel)
else
frame:SetAllPoints(LeftChatTab)
end
end
end
CH:PositionChat(true)
end
local function FindRightChatID()
local rightChatID
for _, frameName in pairs(_G.CHAT_FRAMES) do
local chat = _G[frameName]
local id = chat:GetID()
if E:FramesOverlap(chat, _G.RightChatPanel) and not E:FramesOverlap(chat, _G.LeftChatPanel) then
rightChatID = id
break
end
end
return rightChatID
end
function CH:UpdateChatTabs()
local fadeUndockedTabs = E.db.chat.fadeUndockedTabs
local fadeTabsNoBackdrop = E.db.chat.fadeTabsNoBackdrop
for i = 1, CreatedFrames do
local chat = _G[format("ChatFrame%d", i)]
local tab = _G[format("ChatFrame%sTab", i)]
local id = chat:GetID()
local isDocked = chat.isDocked
local chatbg = format("ChatFrame%dBackground", i)
if id > NUM_CHAT_WINDOWS then
if select(2, tab:GetPoint()):GetName() ~= chatbg then
isDocked = true
else
isDocked = false
end
end
if chat:IsShown() and not (id > NUM_CHAT_WINDOWS) and (id == self.RightChatWindowID) then
if E.db.chat.panelBackdrop == 'HIDEBOTH' or E.db.chat.panelBackdrop == 'LEFT' then
CH:SetupChatTabs(tab, fadeTabsNoBackdrop and true or false)
else
CH:SetupChatTabs(tab, false)
end
elseif not isDocked and chat:IsShown() then
tab:SetParent(_G.RightChatPanel)
chat:SetParent(_G.RightChatPanel)
CH:SetupChatTabs(tab, fadeUndockedTabs and true or false)
else
if E.db.chat.panelBackdrop == 'HIDEBOTH' or E.db.chat.panelBackdrop == 'RIGHT' then
CH:SetupChatTabs(tab, fadeTabsNoBackdrop and true or false)
else
CH:SetupChatTabs(tab, false)
end
end
end
end
function CH:PositionChat(override)
if ((InCombatLockdown() and not override and self.initialMove) or (IsMouseButtonDown("LeftButton") and not override)) then return end
local RightChatPanel, LeftChatPanel, RightChatDataPanel, LeftChatToggleButton, LeftChatTab, CombatLogButton = _G.RightChatPanel, _G.LeftChatPanel, _G.RightChatDataPanel, _G.LeftChatToggleButton, _G.LeftChatTab, _G.CombatLogQuickButtonFrame_Custom
if not RightChatPanel or not LeftChatPanel then return; end
RightChatPanel:Size(E.db.chat.separateSizes and E.db.chat.panelWidthRight or E.db.chat.panelWidth, E.db.chat.separateSizes and E.db.chat.panelHeightRight or E.db.chat.panelHeight)
local chatBarHeight = 0
if E.db["euiscript"].chatbar then chatBarHeight = 28 end
LeftChatPanel:SetSize(E.db.chat.panelWidth, E.db.chat.panelHeight+chatBarHeight)
if not self.db.lockPositions or E.private.chat.enable ~= true then return end
CombatLogButton:Size(LeftChatTab:GetWidth(), LeftChatTab:GetHeight())
self.RightChatWindowID = FindRightChatID()
local fadeUndockedTabs = E.db.chat.fadeUndockedTabs
local fadeTabsNoBackdrop = E.db.chat.fadeTabsNoBackdrop
for i=1, CreatedFrames do
local BASE_OFFSET = 57 + E.Spacing*3
local chat = _G[format("ChatFrame%d", i)]
local chatbg = format("ChatFrame%dBackground", i)
local id = chat:GetID()
local tab = _G[format("ChatFrame%sTab", i)]
local isDocked = chat.isDocked
tab.isDocked = chat.isDocked
tab.owner = chat
if id > NUM_CHAT_WINDOWS then
if select(2, tab:GetPoint()):GetName() ~= chatbg then
isDocked = true
else
isDocked = false
end
end
if chat:IsShown() and not (id > NUM_CHAT_WINDOWS) and id == self.RightChatWindowID then
chat:ClearAllPoints()
if E.db.datatexts.rightChatPanel then
chat:Point("BOTTOMLEFT", RightChatDataPanel, "TOPLEFT", 1, 3)
else
BASE_OFFSET = BASE_OFFSET - 24
chat:Point("BOTTOMLEFT", RightChatDataPanel, "BOTTOMLEFT", 1, 1)
end
if id ~= 2 then
chat:Size((E.db.chat.separateSizes and E.db.chat.panelWidthRight or E.db.chat.panelWidth) - 11, (E.db.chat.separateSizes and E.db.chat.panelHeightRight or E.db.chat.panelHeight) - BASE_OFFSET)
else
chat:Size(E.db.chat.panelWidth - 11, (E.db.chat.panelHeight - BASE_OFFSET) - CombatLogButton:GetHeight())
end
--Pass a 2nd argument which prevents an infinite loop in our ON_FCF_SavePositionAndDimensions function
if chat:GetLeft() then
FCF_SavePositionAndDimensions(chat, true)
end
tab:SetParent(RightChatPanel)
chat:SetParent(RightChatPanel)
if chat:IsMovable() then
chat:SetUserPlaced(true)
end
if E.db.chat.panelBackdrop == 'HIDEBOTH' or E.db.chat.panelBackdrop == 'LEFT' then
CH:SetupChatTabs(tab, fadeTabsNoBackdrop and true or false)
else
CH:SetupChatTabs(tab, false)
end
elseif not isDocked and chat:IsShown() then
tab:SetParent(_G.UIParent)
chat:SetParent(_G.UIParent)
CH:SetupChatTabs(tab, fadeUndockedTabs and true or false)
else
if id ~= 2 and not (id > NUM_CHAT_WINDOWS) then
chat:ClearAllPoints()
if E.db.datatexts.leftChatPanel then
chat:Point("BOTTOMLEFT", LeftChatToggleButton, "TOPLEFT", 1, 3)
else
BASE_OFFSET = BASE_OFFSET - 25
chat:Point("BOTTOMLEFT", LeftChatToggleButton, "BOTTOMLEFT", 1, 1)
end
chat:Size(E.db.chat.panelWidth - 11, (E.db.chat.panelHeight - BASE_OFFSET))
--Pass a 2nd argument which prevents an infinite loop in our ON_FCF_SavePositionAndDimensions function
if chat:GetLeft() then
FCF_SavePositionAndDimensions(chat, true)
end
end
chat:SetParent(LeftChatPanel)
if i > 2 then
tab:SetParent(_G.GeneralDockManagerScrollFrameChild)
else
tab:SetParent(_G.GeneralDockManager)
end
if chat:IsMovable() then
chat:SetUserPlaced(true)
end
if E.db.chat.panelBackdrop == 'HIDEBOTH' or E.db.chat.panelBackdrop == 'RIGHT' then
CH:SetupChatTabs(tab, fadeTabsNoBackdrop and true or false)
else
CH:SetupChatTabs(tab, false)
end
end
end
E.Layout:RepositionChatDataPanels() --Bugfix: #686
self.initialMove = true;
end
function CH:Panels_ColorUpdate()
local panelColor = E.db.chat.panelColor
_G.LeftChatPanel.backdrop:SetBackdropColor(panelColor.r, panelColor.g, panelColor.b, panelColor.a)
_G.RightChatPanel.backdrop:SetBackdropColor(panelColor.r, panelColor.g, panelColor.b, panelColor.a)
if _G.ChatButtonHolder then
_G.ChatButtonHolder:SetBackdropColor(panelColor.r, panelColor.g, panelColor.b, panelColor.a)
end
end
local function UpdateChatTabColor(_, r, g, b)
for i=1, CreatedFrames do
_G['ChatFrame'..i..'TabText']:SetTextColor(r, g, b)
end
end
E.valueColorUpdateFuncs[UpdateChatTabColor] = true
function CH:ScrollToBottom(frame)
frame:ScrollToBottom()
self:CancelTimer(frame.ScrollTimer, true)
end
function CH:PrintURL(url)
return "|cFFFFFFFF[|Hurl:"..url.."|h"..url.."|h]|r "
end
function CH:FindURL(event, msg, author, ...)
if (event == "CHAT_MSG_WHISPER" or event == "CHAT_MSG_BN_WHISPER") and (CH.db.whisperSound ~= 'None') and not CH.SoundTimer then
if (strsub(msg,1,3) == "OQ,") then return false, msg, author, ... end
if (CH.db.noAlertInCombat and not InCombatLockdown()) or not CH.db.noAlertInCombat then
PlaySoundFile(LSM:Fetch("sound", CH.db.whisperSound), "Master")
end
CH.SoundTimer = E:Delay(1, CH.ThrottleSound)
end
if not CH.db.url then
msg = CH:CheckKeyword(msg, author);
msg = CH:GetSmileyReplacementText(msg);
return false, msg, author, ...
end
local text, tag = msg, strmatch(msg, '{(.-)}')
if tag and _G.ICON_TAG_LIST[strlower(tag)] then
text = gsub(gsub(text, "(%S)({.-})", '%1 %2'), "({.-})(%S)", '%1 %2')
end
text = gsub(gsub(text, "(%S)(|c.-|H.-|h.-|h|r)", '%1 %2'), "(|c.-|H.-|h.-|h|r)(%S)", '%1 %2')
-- http://example.com
local newMsg, found = gsub(text, "(%a+)://(%S+)%s?", CH:PrintURL("%1://%2"))
if found > 0 then return false, CH:GetSmileyReplacementText(CH:CheckKeyword(newMsg, author)), author, ... end
-- www.example.com
newMsg, found = gsub(text, "www%.([_A-Za-z0-9-]+)%.(%S+)%s?", CH:PrintURL("www.%1.%2"))
if found > 0 then return false, CH:GetSmileyReplacementText(CH:CheckKeyword(newMsg, author)), author, ... end
-- [email protected]
newMsg, found = gsub(text, "([_A-Za-z0-9-%.]+)@([_A-Za-z0-9-]+)(%.+)([_A-Za-z0-9-%.]+)%s?", CH:PrintURL("%1@%2%3%4"))
if found > 0 then return false, CH:GetSmileyReplacementText(CH:CheckKeyword(newMsg, author)), author, ... end
-- IP address with port 1.1.1.1:1
newMsg, found = gsub(text, "(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)(:%d+)%s?", CH:PrintURL("%1.%2.%3.%4%5"))
if found > 0 then return false, CH:GetSmileyReplacementText(CH:CheckKeyword(newMsg, author)), author, ... end
-- IP address 1.1.1.1
newMsg, found = gsub(text, "(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%s?", CH:PrintURL("%1.%2.%3.%4"))
if found > 0 then return false, CH:GetSmileyReplacementText(CH:CheckKeyword(newMsg, author)), author, ... end
msg = CH:CheckKeyword(msg, author)
msg = CH:GetSmileyReplacementText(msg)
return false, msg, author, ...
end
function CH:SetChatEditBoxMessage(message)
local ChatFrameEditBox = ChatEdit_ChooseBoxForSend()
local editBoxShown = ChatFrameEditBox:IsShown()
local editBoxText = ChatFrameEditBox:GetText()
if not editBoxShown then
ChatEdit_ActivateChat(ChatFrameEditBox)
end
if editBoxText and editBoxText ~= "" then
ChatFrameEditBox:SetText('')
end
ChatFrameEditBox:Insert(message)
ChatFrameEditBox:HighlightText()
end
local function HyperLinkedCPL(data)
if strsub(data, 1, 3) == "cpl" then
local chatID = strsub(data, 5)
local chat = _G[format("ChatFrame%d", chatID)]
if not chat then return end
local scale = chat:GetEffectiveScale() --blizzard does this with `scale = UIParent:GetScale()`
local cursorX, cursorY = GetCursorPosition()
cursorX, cursorY = (cursorX / scale), (cursorY / scale)
local _, lineIndex = chat:FindCharacterAndLineIndexAtCoordinate(cursorX, cursorY)
if lineIndex then
local visibleLine = chat.visibleLines and chat.visibleLines[lineIndex]
local message = visibleLine and visibleLine.messageInfo and visibleLine.messageInfo.message
if message and message ~= "" then
message = gsub(message, '|c%x%x%x%x%x%x%x%x(.-)|r', '%1')
message = strtrim(removeIconFromLine(message))
if not CH:MessageIsProtected(message) then
CH:SetChatEditBoxMessage(message)
end
end
end
end
end
local function HyperLinkedSQU(data)
if strsub(data, 1, 3) == "squ" then
if not _G.QuickJoinFrame:IsShown() then
ToggleQuickJoinPanel()
end
local guid = strsub(data, 5)
if guid and guid ~= '' then
_G.QuickJoinFrame:SelectGroup(guid)
_G.QuickJoinFrame:ScrollToGroup(guid)
end
end
end
local function HyperLinkedURL(data)
if strsub(data, 1, 3) == "url" then
local currentLink = strsub(data, 5)
if currentLink and currentLink ~= "" then
CH:SetChatEditBoxMessage(currentLink)
end
end
end
local SetHyperlink = _G.ItemRefTooltip.SetHyperlink
function _G.ItemRefTooltip:SetHyperlink(data, ...)
if strsub(data, 1, 3) == "cpl" then
HyperLinkedCPL(data)
elseif strsub(data, 1, 3) == "squ" then
HyperLinkedSQU(data)
elseif strsub(data, 1, 3) == "url" then
HyperLinkedURL(data)
else
SetHyperlink(self, data, ...)
end
end
local hyperLinkEntered
function CH:OnHyperlinkEnter(frame, refString)
if InCombatLockdown() then return; end
local linkToken = strmatch(refString, "^([^:]+)")
if hyperlinkTypes[linkToken] then
ShowUIPanel(_G.GameTooltip)
_G.GameTooltip:SetOwner(frame, "ANCHOR_CURSOR")
_G.GameTooltip:SetHyperlink(refString)
hyperLinkEntered = frame;
_G.GameTooltip:Show()
end
end
function CH:OnHyperlinkLeave() -- frame, refString
-- local linkToken = refString:match("^([^:]+)")
-- if hyperlinkTypes[linkToken] then
-- HideUIPanel(GameTooltip)
-- hyperLinkEntered = nil;
-- end
if hyperLinkEntered then
HideUIPanel(_G.GameTooltip)
hyperLinkEntered = nil;
end
end
-- function CH:OnMessageScrollChanged(frame)
-- if hyperLinkEntered == frame then
-- HideUIPanel(GameTooltip)
-- hyperLinkEntered = false;
-- end
-- end
function CH:EnableHyperlink()
for _, frameName in pairs(_G.CHAT_FRAMES) do
local frame = _G[frameName]
if (not self.hooks or not self.hooks[frame] or not self.hooks[frame].OnHyperlinkEnter) then
self:HookScript(frame, 'OnHyperlinkEnter')
self:HookScript(frame, 'OnHyperlinkLeave')
-- self:HookScript(frame, 'OnMessageScrollChanged')
end
end
end
function CH:DisableHyperlink()
for _, frameName in pairs(_G.CHAT_FRAMES) do
local frame = _G[frameName]
if self.hooks and self.hooks[frame] and self.hooks[frame].OnHyperlinkEnter then
self:Unhook(frame, 'OnHyperlinkEnter')
self:Unhook(frame, 'OnHyperlinkLeave')
-- self:Unhook(frame, 'OnMessageScrollChanged')
end
end
end
function CH:DisableChatThrottle()
wipe(msgList)
wipe(msgCount)
wipe(msgTime)
end
function CH:ShortChannel()
return format("|Hchannel:%s|h[%s]|h", self, DEFAULT_STRINGS[strupper(self)] or gsub(self, "channel:", ""))
end
function CH:GetBNFirstToonClassColor(id)
if not id then return end
local total = BNGetNumFriends();
for i = 1, total do
local bnetIDAccount, _, _, _, _, _, _, isOnline = BNGetFriendInfo(i);
if isOnline and (bnetIDAccount == id) then
local numGameAccounts = BNGetNumFriendGameAccounts(i);
if numGameAccounts > 0 then
for y = 1, numGameAccounts do
local _, _, client, _, _, _, _, Class = BNGetFriendGameAccountInfo(i, y);
if (client == BNET_CLIENT_WOW) and Class and Class ~= '' then
return Class --return the first toon's class
end
end
end
break
end
end
end
function CH:GetBNFriendColor(name, id, useBTag)
local _, _, battleTag, isBattleTagPresence, _, bnetIDGameAccount = BNGetFriendInfoByID(id)
local BATTLE_TAG = battleTag and strmatch(battleTag,'([^#]+)')
local TAG = (useBTag or CH.db.useBTagName) and BATTLE_TAG
local Class
if not bnetIDGameAccount then --dont know how this is possible
local firstToonClass = CH:GetBNFirstToonClassColor(id)
if firstToonClass then
Class = firstToonClass
else
return TAG or name, isBattleTagPresence and BATTLE_TAG
end
end
if not Class then
_, _, _, _, _, _, _, Class = BNGetGameAccountInfo(bnetIDGameAccount)
end
Class = E:UnlocalizedClassName(Class)
local COLOR = Class and (_G.CUSTOM_CLASS_COLORS and _G.CUSTOM_CLASS_COLORS[Class] or _G.RAID_CLASS_COLORS[Class])
return (COLOR and format('|c%s%s|r', COLOR.colorStr, TAG or name)) or TAG or name, isBattleTagPresence and BATTLE_TAG
end
local PluginIconsCalls = {}
function CH:AddPluginIcons(func)
tinsert(PluginIconsCalls, func)
end
function CH:GetPluginIcon(sender)
local icon
for _,func in ipairs(PluginIconsCalls) do
icon = func(sender)
if icon and icon ~= "" then break end
end
return icon
end
--Copied from FrameXML ChatFrame.lua and modified to add CUSTOM_CLASS_COLORS
function CH:GetColoredName(event, _, arg2, _, _, _, _, _, arg8, _, _, _, arg12)
local chatType = strsub(event, 10);
if ( strsub(chatType, 1, 7) == "WHISPER" ) then
chatType = "WHISPER";
end
if ( strsub(chatType, 1, 7) == "CHANNEL" ) then
chatType = "CHANNEL"..arg8;
end
local info = _G.ChatTypeInfo[chatType];
--ambiguate guild chat names
if (chatType == "GUILD") then
arg2 = Ambiguate(arg2, "guild")
else
arg2 = Ambiguate(arg2, "none")
end
if ( arg12 and info and Chat_ShouldColorChatByClass(info) ) then
local _, englishClass = GetPlayerInfoByGUID(arg12)
if ( englishClass ) then
local classColorTable = _G.CUSTOM_CLASS_COLORS and _G.CUSTOM_CLASS_COLORS[englishClass] or _G.RAID_CLASS_COLORS[englishClass];
if ( not classColorTable ) then
return arg2;
end
return format("\124cff%.2x%.2x%.2x", classColorTable.r*255, classColorTable.g*255, classColorTable.b*255)..arg2.."\124r"
end
end
return arg2;
end
--Copied from FrameXML ChatFrame.lua and modified to add CUSTOM_CLASS_COLORS
local seenGroups = {};
function CH:ChatFrame_ReplaceIconAndGroupExpressions(message, noIconReplacement, noGroupReplacement)
wipe(seenGroups);
local ICON_LIST, ICON_TAG_LIST, GROUP_TAG_LIST = _G.ICON_LIST, _G.ICON_TAG_LIST, _G.GROUP_TAG_LIST
for tag in gmatch(message, "%b{}") do
local term = strlower(gsub(tag, "[{}]", ""));
if ( not noIconReplacement and ICON_TAG_LIST[term] and ICON_LIST[ICON_TAG_LIST[term]] ) then
message = gsub(message, tag, ICON_LIST[ICON_TAG_LIST[term]] .. "0|t");
elseif ( not noGroupReplacement and GROUP_TAG_LIST[term] ) then
local groupIndex = GROUP_TAG_LIST[term];
if not seenGroups[groupIndex] then
seenGroups[groupIndex] = true;
local groupList = "[";
for i=1, GetNumGroupMembers() do
local name, _, subgroup, _, _, classFileName = GetRaidRosterInfo(i);
if ( name and subgroup == groupIndex ) then
local classColorTable = _G.CUSTOM_CLASS_COLORS and _G.CUSTOM_CLASS_COLORS[classFileName] or _G.RAID_CLASS_COLORS[classFileName];
if ( classColorTable ) then
name = format("\124cff%.2x%.2x%.2x%s\124r", classColorTable.r*255, classColorTable.g*255, classColorTable.b*255, name);
end
groupList = groupList..(groupList == "[" and "" or _G.PLAYER_LIST_DELIMITER)..name;
end
end
if groupList ~= "[" then
groupList = groupList.."]";
message = gsub(message, tag, groupList, 1);
end
end
end
end
return message;
end
E.NameReplacements = {}
function CH:ChatFrame_MessageEventHandler(frame, event, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, _, arg16, arg17, isHistory, historyTime, historyName, historyBTag)
-- ElvUI Chat History Note: isHistory, historyTime, historyName, and historyBTag are passed from CH:DisplayChatHistory() and need to be on the end to prevent issues in other addons that listen on ChatFrame_MessageEventHandler.
-- we also send isHistory and historyTime into CH:AddMessage so that we don't have to override the timestamp.
if ( strsub(event, 1, 8) == "CHAT_MSG" ) then
if (arg16) then
-- hiding sender in letterbox: do NOT even show in chat window (only shows in cinematic frame)
return true;
end
local historySavedName --we need to extend the arguments on CH.ChatFrame_MessageEventHandler so we can properly handle saved names without overriding
if isHistory == "ElvUI_ChatHistory" then
if historyBTag then arg2 = historyBTag end -- swap arg2 (which is a |k string) to btag name
historySavedName = historyName
end
local chatType = strsub(event, 10);
local info = _G.ChatTypeInfo[chatType];
local chatFilters = _G.ChatFrame_GetMessageEventFilters(event)
if chatFilters then
for _, filterFunc in next, chatFilters do
local filter, newarg1, newarg2, newarg3, newarg4, newarg5, newarg6, newarg7, newarg8, newarg9, newarg10, newarg11, newarg12, newarg13, newarg14 = filterFunc(frame, event, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14);
if filter then
return true;
elseif newarg1 then
arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14 = newarg1, newarg2, newarg3, newarg4, newarg5, newarg6, newarg7, newarg8, newarg9, newarg10, newarg11, newarg12, newarg13, newarg14;
end
end
end
arg2 = E.NameReplacements[arg2] or arg2
local _, _, englishClass, _, _, _, name, realm = pcall(GetPlayerInfoByGUID, arg12)
local coloredName = historySavedName or CH:GetColoredName(event, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14);
local nameWithRealm -- we also use this lower in function to correct mobile to link with the realm as well
--Cache name->class
realm = (realm and realm ~= '') and gsub(realm,'[%s%-]','')
if name and name ~= '' then
CH.ClassNames[strlower(name)] = englishClass
nameWithRealm = (realm and name.."-"..realm) or name.."-"..PLAYER_REALM
CH.ClassNames[strlower(nameWithRealm)] = englishClass
end
local channelLength = strlen(arg4);
local infoType = chatType;
if ( (chatType == "COMMUNITIES_CHANNEL") or ((strsub(chatType, 1, 7) == "CHANNEL") and (chatType ~= "CHANNEL_LIST") and ((arg1 ~= "INVITE") or (chatType ~= "CHANNEL_NOTICE_USER"))) ) then
if ( arg1 == "WRONG_PASSWORD" ) then
local staticPopup = _G[StaticPopup_Visible("CHAT_CHANNEL_PASSWORD") or ""];
if ( staticPopup and strupper(staticPopup.data) == strupper(arg9) ) then
-- Don't display invalid password messages if we're going to prompt for a password (bug 102312)
return;
end
end
local found = 0;
for index, value in pairs(frame.channelList) do
if ( channelLength > strlen(value) ) then
-- arg9 is the channel name without the number in front...
if ( ((arg7 > 0) and (frame.zoneChannelList[index] == arg7)) or (strupper(value) == strupper(arg9)) ) then
found = 1;
infoType = "CHANNEL"..arg8;
info = _G.ChatTypeInfo[infoType];
if ( (chatType == "CHANNEL_NOTICE") and (arg1 == "YOU_LEFT") ) then
frame.channelList[index] = nil;
frame.zoneChannelList[index] = nil;
end
break;
end
end
end
if ( (found == 0) or not info ) then
return true;
end
end
local chatGroup = Chat_GetChatCategory(chatType);
local chatTarget;
if ( chatGroup == "CHANNEL" ) then
chatTarget = tostring(arg8);
elseif ( chatGroup == "WHISPER" or chatGroup == "BN_WHISPER" ) then
if(not(strsub(arg2, 1, 2) == "|K")) then
chatTarget = strupper(arg2);
else
chatTarget = arg2;
end
end
if ( FCFManager_ShouldSuppressMessage(frame, chatGroup, chatTarget) ) then
return true;
end
if ( chatGroup == "WHISPER" or chatGroup == "BN_WHISPER" ) then
if ( frame.privateMessageList and not frame.privateMessageList[strlower(arg2)] ) then
return true;
elseif ( frame.excludePrivateMessageList and frame.excludePrivateMessageList[strlower(arg2)]
and ( (chatGroup == "WHISPER" and GetCVar("whisperMode") ~= "popout_and_inline") or (chatGroup == "BN_WHISPER" and GetCVar("whisperMode") ~= "popout_and_inline") ) ) then
return true;
end
end
if (frame.privateMessageList) then
-- Dedicated BN whisper windows need online/offline messages for only that player
if ( (chatGroup == "BN_INLINE_TOAST_ALERT" or chatGroup == "BN_WHISPER_PLAYER_OFFLINE") and not frame.privateMessageList[strlower(arg2)] ) then
return true;
end
-- HACK to put certain system messages into dedicated whisper windows
if ( chatGroup == "SYSTEM") then
local matchFound = false;
local message = strlower(arg1);
for playerName in pairs(frame.privateMessageList) do
local playerNotFoundMsg = strlower(format(_G.ERR_CHAT_PLAYER_NOT_FOUND_S, playerName));
local charOnlineMsg = strlower(format(_G.ERR_FRIEND_ONLINE_SS, playerName, playerName));
local charOfflineMsg = strlower(format(_G.ERR_FRIEND_OFFLINE_S, playerName));
if ( message == playerNotFoundMsg or message == charOnlineMsg or message == charOfflineMsg) then
matchFound = true;
break;
end
end
if (not matchFound) then
return true;
end
end
end
if ( chatType == "SYSTEM" or chatType == "SKILL" or chatType == "CURRENCY" or chatType == "MONEY" or
chatType == "OPENING" or chatType == "TRADESKILLS" or chatType == "PET_INFO" or chatType == "TARGETICONS" or chatType == "BN_WHISPER_PLAYER_OFFLINE") then
frame:AddMessage(arg1, info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
elseif (chatType == "LOOT") then
-- Append [Share] hyperlink if this is a valid social item and you are the looter.
if (arg12 == E.myguid and C_SocialIsSocialEnabled()) then
local itemID, creationContext = GetItemInfoFromHyperlink(arg1);
if (itemID and C_SocialGetLastItem() == itemID) then
arg1 = arg1 .. " " .. Social_GetShareItemLink(creationContext, true);
end
end
frame:AddMessage(arg1, info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
elseif ( strsub(chatType,1,7) == "COMBAT_" ) then
frame:AddMessage(arg1, info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
elseif ( strsub(chatType,1,6) == "SPELL_" ) then
frame:AddMessage(arg1, info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
elseif ( strsub(chatType,1,10) == "BG_SYSTEM_" ) then
frame:AddMessage(arg1, info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
elseif ( strsub(chatType,1,11) == "ACHIEVEMENT" ) then
-- Append [Share] hyperlink
if (arg12 == E.myguid and C_SocialIsSocialEnabled()) then
local achieveID = GetAchievementInfoFromHyperlink(arg1);
if (achieveID) then
arg1 = arg1 .. " " .. Social_GetShareAchievementLink(achieveID, true);
end
end
frame:AddMessage(format(arg1, GetPlayerLink(arg2, ("[%s]"):format(coloredName))), info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
elseif ( strsub(chatType,1,18) == "GUILD_ACHIEVEMENT" ) then
local message = format(arg1, GetPlayerLink(arg2, ("[%s]"):format(coloredName)));
if (C_SocialIsSocialEnabled()) then
local achieveID = GetAchievementInfoFromHyperlink(arg1);
if (achieveID) then
local isGuildAchievement = select(12, GetAchievementInfo(achieveID));
if (isGuildAchievement) then
message = message .. " " .. Social_GetShareAchievementLink(achieveID, true);
end
end
end
frame:AddMessage(message, info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
elseif ( chatType == "IGNORED" ) then
frame:AddMessage(format(_G.CHAT_IGNORED, arg2), info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
elseif ( chatType == "FILTERED" ) then
frame:AddMessage(format(_G.CHAT_FILTERED, arg2), info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
elseif ( chatType == "RESTRICTED" ) then
frame:AddMessage(_G.CHAT_RESTRICTED_TRIAL, info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
elseif ( chatType == "CHANNEL_LIST") then
if(channelLength > 0) then
frame:AddMessage(format(_G["CHAT_"..chatType.."_GET"]..arg1, tonumber(arg8), arg4), info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
else
frame:AddMessage(arg1, info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
end
elseif (chatType == "CHANNEL_NOTICE_USER") then
local globalstring = _G["CHAT_"..arg1.."_NOTICE_BN"];
if ( not globalstring ) then
globalstring = _G["CHAT_"..arg1.."_NOTICE"];
end
if not globalstring then
GMError(("Missing global string for %q"):format("CHAT_"..arg1.."_NOTICE_BN"));
return;
end
if(arg5 ~= "") then
-- TWO users in this notice (E.G. x kicked y)
frame:AddMessage(format(globalstring, arg8, arg4, arg2, arg5), info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
elseif ( arg1 == "INVITE" ) then
frame:AddMessage(format(globalstring, arg4, arg2), info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
else
frame:AddMessage(format(globalstring, arg8, arg4, arg2), info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
end
if ( arg1 == "INVITE" and GetCVarBool("blockChannelInvites") ) then
frame:AddMessage(_G.CHAT_MSG_BLOCK_CHAT_CHANNEL_INVITE, info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
end
elseif (chatType == "CHANNEL_NOTICE") then
local globalstring;
if ( arg1 == "TRIAL_RESTRICTED" ) then
globalstring = _G.CHAT_TRIAL_RESTRICTED_NOTICE_TRIAL;
else
globalstring = _G["CHAT_"..arg1.."_NOTICE_BN"];
if ( not globalstring ) then
globalstring = _G["CHAT_"..arg1.."_NOTICE"];
if not globalstring then
GMError(("Missing global string for %q"):format("CHAT_"..arg1.."_NOTICE"));
return;
end
end
end
local accessID = ChatHistory_GetAccessID(Chat_GetChatCategory(chatType), arg8);
local typeID = ChatHistory_GetAccessID(infoType, arg8, arg12);
frame:AddMessage(format(globalstring, arg8, ChatFrame_ResolvePrefixedChannelName(arg4)), info.r, info.g, info.b, info.id, accessID, typeID, isHistory, historyTime);
elseif ( chatType == "BN_INLINE_TOAST_ALERT" ) then
local globalstring = _G["BN_INLINE_TOAST_"..arg1];
if not globalstring then
GMError(("Missing global string for %q"):format("BN_INLINE_TOAST_"..arg1));
return;
end
local message;
if ( arg1 == "FRIEND_REQUEST" ) then
message = globalstring;
elseif ( arg1 == "FRIEND_PENDING" ) then
message = format(_G.BN_INLINE_TOAST_FRIEND_PENDING, BNGetNumFriendInvites());
elseif ( arg1 == "FRIEND_REMOVED" or arg1 == "BATTLETAG_FRIEND_REMOVED" ) then
message = format(globalstring, arg2);
elseif ( arg1 == "FRIEND_ONLINE" or arg1 == "FRIEND_OFFLINE" ) then
local _, _, _, _, characterName, _, client = BNGetFriendInfoByID(arg13);
if (client and client ~= "") then
local _, _, battleTag = BNGetFriendInfoByID(arg13);
characterName = BNet_GetValidatedCharacterName(characterName, battleTag, client) or "";
local characterNameText = BNet_GetClientEmbeddedTexture(client, 14)..characterName;
local linkDisplayText = ("[%s] (%s)"):format(arg2, characterNameText);
local playerLink = GetBNPlayerLink(arg2, linkDisplayText, arg13, arg11, Chat_GetChatCategory(chatType), 0);
message = format(globalstring, playerLink);
else
local linkDisplayText = ("[%s]"):format(arg2);
local playerLink = GetBNPlayerLink(arg2, linkDisplayText, arg13, arg11, Chat_GetChatCategory(chatType), 0);
message = format(globalstring, playerLink);
end
else
local linkDisplayText = ("[%s]"):format(arg2);
local playerLink = GetBNPlayerLink(arg2, linkDisplayText, arg13, arg11, Chat_GetChatCategory(chatType), 0);
message = format(globalstring, playerLink);
end
frame:AddMessage(message, info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
elseif ( chatType == "BN_INLINE_TOAST_BROADCAST" ) then
if ( arg1 ~= "" ) then
arg1 = RemoveNewlines(RemoveExtraSpaces(arg1));
local linkDisplayText = ("[%s]"):format(arg2);
local playerLink = GetBNPlayerLink(arg2, linkDisplayText, arg13, arg11, Chat_GetChatCategory(chatType), 0);
frame:AddMessage(format(_G.BN_INLINE_TOAST_BROADCAST, playerLink, arg1), info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
end
elseif ( chatType == "BN_INLINE_TOAST_BROADCAST_INFORM" ) then
if ( arg1 ~= "" ) then
frame:AddMessage(_G.BN_INLINE_TOAST_BROADCAST_INFORM, info.r, info.g, info.b, info.id, nil, nil, isHistory, historyTime);
end
else
local body;
if ( chatType == "WHISPER_INFORM" and GMChatFrame_IsGM and GMChatFrame_IsGM(arg2) ) then
return;
end
local showLink = 1;
if ( strsub(chatType, 1, 7) == "MONSTER" or strsub(chatType, 1, 9) == "RAID_BOSS") then
showLink = nil;
else
arg1 = gsub(arg1, "%%", "%%%%");
end
-- Search for icon links and replace them with texture links.
arg1 = CH:ChatFrame_ReplaceIconAndGroupExpressions(arg1, arg17, not ChatFrame_CanChatGroupPerformExpressionExpansion(chatGroup)); -- If arg17 is true, don't convert to raid icons
--Remove groups of many spaces
arg1 = RemoveExtraSpaces(arg1);
--ElvUI: Get class colored name for BattleNet friend
if ( chatType == "BN_WHISPER" or chatType == "BN_WHISPER_INFORM" ) then
coloredName = historySavedName or CH:GetBNFriendColor(arg2, arg13)
end
local playerLink;
local playerLinkDisplayText = coloredName;
local relevantDefaultLanguage = frame.defaultLanguage;
if ( (chatType == "SAY") or (chatType == "YELL") ) then
relevantDefaultLanguage = frame.alternativeDefaultLanguage;
end
local usingDifferentLanguage = (arg3 ~= "") and (arg3 ~= relevantDefaultLanguage);
local usingEmote = (chatType == "EMOTE") or (chatType == "TEXT_EMOTE");
if ( usingDifferentLanguage or not usingEmote ) then
playerLinkDisplayText = ("[%s]"):format(coloredName);
end
local isCommunityType = chatType == "COMMUNITIES_CHANNEL";
local playerName, lineID, bnetIDAccount = arg2, arg11, arg13;
if ( isCommunityType ) then
local isBattleNetCommunity = bnetIDAccount ~= nil and bnetIDAccount ~= 0;
local messageInfo, clubId, streamId = C_Club_GetInfoFromLastCommunityChatLine();
if (messageInfo ~= nil) then
if ( isBattleNetCommunity ) then
playerLink = GetBNPlayerCommunityLink(playerName, playerLinkDisplayText, bnetIDAccount, clubId, streamId, messageInfo.messageId.epoch, messageInfo.messageId.position);
else
playerLink = GetPlayerCommunityLink(playerName, playerLinkDisplayText, clubId, streamId, messageInfo.messageId.epoch, messageInfo.messageId.position);
end
else
playerLink = playerLinkDisplayText;
end
else
if chatType == "BN_WHISPER" or chatType == "BN_WHISPER_INFORM" then
playerLink = GetBNPlayerLink(playerName, playerLinkDisplayText, bnetIDAccount, lineID, chatGroup, chatTarget);
elseif ((chatType == "GUILD" or chatType == "TEXT_EMOTE") or arg14) and (nameWithRealm and nameWithRealm ~= playerName) then
playerName = nameWithRealm
playerLink = GetPlayerLink(playerName, playerLinkDisplayText, lineID, chatGroup, chatTarget);
else
playerLink = GetPlayerLink(playerName, playerLinkDisplayText, lineID, chatGroup, chatTarget);
end
end
local message = arg1;
if ( arg14 ) then --isMobile
message = ChatFrame_GetMobileEmbeddedTexture(info.r, info.g, info.b)..message;
end
-- Player Flags
local pflag, chatIcon, pluginChatIcon = "", specialChatIcons[playerName], CH:GetPluginIcon(playerName)
if type(chatIcon) == 'function' then chatIcon = chatIcon() end
if arg6 ~= "" then -- Blizzard Flags
if arg6 == "GM" or arg6 == "DEV" then -- Blizzard Icon, this was sent by a GM or Dev.
pflag = "|TInterface\\ChatFrame\\UI-ChatIcon-Blizz:12:20:0:0:32:16:4:28:0:16|t";
else -- Away/Busy
pflag = _G["CHAT_FLAG_"..arg6] or ""
end
end
-- LFG Role Flags
local lfgRole = lfgRoles[playerName]
if lfgRole and (chatType == "PARTY_LEADER" or chatType == "PARTY" or chatType == "RAID" or chatType == "RAID_LEADER" or chatType == "INSTANCE_CHAT" or chatType == "INSTANCE_CHAT_LEADER") then
pflag = pflag..lfgRole
end
-- Special Chat Icon
if chatIcon then
pflag = pflag..chatIcon
end
-- Plugin Chat Icon
if pluginChatIcon then
pflag = pflag..pluginChatIcon
end
if ( usingDifferentLanguage ) then
local languageHeader = "["..arg3.."] ";
if ( showLink and (arg2 ~= "") ) then
body = format(_G["CHAT_"..chatType.."_GET"]..languageHeader..message, pflag..playerLink);
else
body = format(_G["CHAT_"..chatType.."_GET"]..languageHeader..message, pflag..arg2);
end
else
if ( not showLink or arg2 == "" ) then
if ( chatType == "TEXT_EMOTE" ) then
body = message;
else
body = format(_G["CHAT_"..chatType.."_GET"]..message, pflag..arg2, arg2);
end
else
if ( chatType == "EMOTE" ) then
body = format(_G["CHAT_"..chatType.."_GET"]..message, pflag..playerLink);
elseif ( chatType == "TEXT_EMOTE" and realm ) then
if info.colorNameByClass then
body = gsub(message, arg2.."%-"..realm, pflag..gsub(playerLink, "(|h|c.-)|r|h$","%1-"..realm.."|r|h"), 1);
else
body = gsub(message, arg2.."%-"..realm, pflag..gsub(playerLink, "(|h.-)|h$","%1-"..realm.."|h"), 1);
end
elseif (chatType == "TEXT_EMOTE") then
body = gsub(message, arg2, pflag..playerLink, 1);
elseif (chatType == "GUILD_ITEM_LOOTED") then
body = gsub(message, "$s", GetPlayerLink(arg2, playerLinkDisplayText));
else
body = format(_G["CHAT_"..chatType.."_GET"]..message, pflag..playerLink);
end
end
end
-- Add Channel
if (channelLength > 0) then
body = "|Hchannel:channel:"..arg8.."|h["..ChatFrame_ResolvePrefixedChannelName(arg4).."]|h "..body;
end
local accessID = ChatHistory_GetAccessID(chatGroup, chatTarget);
local typeID = ChatHistory_GetAccessID(infoType, chatTarget, arg12 or arg13);
if CH.db.shortChannels and chatType ~= "EMOTE" and chatType ~= "TEXT_EMOTE" then
body = gsub(body, "|Hchannel:(.-)|h%[(.-)%]|h", CH.ShortChannel)
body = gsub(body, 'CHANNEL:', '')
body = gsub(body, "^(.-|h) "..L["whispers"], "%1")
body = gsub(body, "^(.-|h) "..L["says"], "%1")
body = gsub(body, "^(.-|h) "..L["yells"], "%1")
body = gsub(body, "<".._G.AFK..">", "[|cffFF0000"..L["AFK"].."|r] ")
body = gsub(body, "<".._G.DND..">", "[|cffE7E716"..L["DND"].."|r] ")
body = gsub(body, "^%[".._G.RAID_WARNING.."%]", '['..L["RW"]..']')
end
frame:AddMessage(body, info.r, info.g, info.b, info.id, accessID, typeID, isHistory, historyTime);
end
if ( isHistory ~= "ElvUI_ChatHistory" ) and ( chatType == "WHISPER" or chatType == "BN_WHISPER" ) then
--BN_WHISPER FIXME
ChatEdit_SetLastTellTarget(arg2, chatType);
if ( frame.tellTimer and (GetTime() > frame.tellTimer) ) then
PlaySound(SOUNDKIT.TELL_MESSAGE);
end
frame.tellTimer = GetTime() + _G.CHAT_TELL_ALERT_TIME;
--FCF_FlashTab(frame);
FlashClientIcon();
end
if ( isHistory ~= "ElvUI_ChatHistory" ) and ( not frame:IsShown() ) then
if ( (frame == _G.DEFAULT_CHAT_FRAME and info.flashTabOnGeneral) or (frame ~= _G.DEFAULT_CHAT_FRAME and info.flashTab) ) then
if ( not _G.CHAT_OPTIONS.HIDE_FRAME_ALERTS or chatType == "WHISPER" or chatType == "BN_WHISPER" ) then --BN_WHISPER FIXME
if not FCFManager_ShouldSuppressMessageFlash(frame, chatGroup, chatTarget) then
FCF_StartAlertFlash(frame); --This would taint if we were not using LibChatAnims
end
end
end
end
return true;
end
end
function CH:ChatFrame_ConfigEventHandler(...)
return ChatFrame_ConfigEventHandler(...)
end
function CH:ChatFrame_SystemEventHandler(...)
return ChatFrame_SystemEventHandler(...)
end
function CH:ChatFrame_OnEvent(...)
if CH:ChatFrame_ConfigEventHandler(...) then return end
if CH:ChatFrame_SystemEventHandler(...) then return end
if CH:ChatFrame_MessageEventHandler(...) then return end
end
function CH:FloatingChatFrame_OnEvent(...)
CH:ChatFrame_OnEvent(...);
FloatingChatFrame_OnEvent(...);
end
local function FloatingChatFrameOnEvent(...)
CH:FloatingChatFrame_OnEvent(...)
end
function CH:SetupChat()
if E.private.chat.enable ~= true then return end
for _, frameName in pairs(_G.CHAT_FRAMES) do
local frame = _G[frameName]
local id = frame:GetID();
local _, fontSize = FCF_GetChatWindowInfo(id);
self:StyleChat(frame)
FCFTab_UpdateAlpha(frame)
frame:FontTemplate(LSM:Fetch("font", self.db.font), fontSize, self.db.fontOutline)
if self.db.fontOutline ~= 'NONE' then
frame:SetShadowColor(0, 0, 0, 0.2)
else
frame:SetShadowColor(0, 0, 0, 1)
end
frame:SetTimeVisible(100)
frame:SetShadowOffset(E.mult, -E.mult)
frame:SetFading(self.db.fade)
if not frame.scriptsSet then
frame:SetScript("OnMouseWheel", ChatFrame_OnMouseScroll)
if id ~= 2 then
frame:SetScript("OnEvent", FloatingChatFrameOnEvent)
end
hooksecurefunc(frame, "SetScript", function(f, script, func)
if script == "OnMouseWheel" and func ~= ChatFrame_OnMouseScroll then
f:SetScript(script, ChatFrame_OnMouseScroll)
end
end)
frame.scriptsSet = true
end
end
if self.db.hyperlinkHover then
self:EnableHyperlink()
end
_G.GeneralDockManager:SetParent(_G.LeftChatPanel)
-- self:ScheduleRepeatingTimer('PositionChat', 1)
self:PositionChat(true)
if not self.HookSecured then
self:SecureHook('FCF_OpenTemporaryWindow', 'SetupChat')
self.HookSecured = true;
end
end
local function PrepareMessage(author, message)
return strupper(author)..message
end
function CH:ChatThrottleHandler(_, arg1, arg2) -- event, arg1, arg2
if arg2 ~= "" then
local message = PrepareMessage(arg2, arg1)
if msgList[message] == nil then
msgList[message] = true
msgCount[message] = 1
msgTime[message] = time()
else
msgCount[message] = msgCount[message] + 1
end
end
end
function CH:CHAT_MSG_CHANNEL(event, message, author, ...)
local blockFlag = false
local msg = PrepareMessage(author, message)
-- ignore player messages
if author == PLAYER_NAME then return CH.FindURL(self, event, message, author, ...) end
if msgList[msg] and CH.db.throttleInterval ~= 0 then
if difftime(time(), msgTime[msg]) <= CH.db.throttleInterval then
blockFlag = true
end
end
if blockFlag then
return true;
else
if CH.db.throttleInterval ~= 0 then
msgTime[msg] = time()
end
return CH.FindURL(self, event, message, author, ...)
end
end
function CH:CHAT_MSG_YELL(event, message, author, ...)
local blockFlag = false
local msg = PrepareMessage(author, message)
if msg == nil then return CH.FindURL(self, event, message, author, ...) end
-- ignore player messages
if author == PLAYER_NAME then return CH.FindURL(self, event, message, author, ...) end
if msgList[msg] and msgCount[msg] > 1 and CH.db.throttleInterval ~= 0 then
if difftime(time(), msgTime[msg]) <= CH.db.throttleInterval then
blockFlag = true
end
end
if blockFlag then
return true;
else
if CH.db.throttleInterval ~= 0 then
msgTime[msg] = time()
end
return CH.FindURL(self, event, message, author, ...)
end
end
function CH:CHAT_MSG_SAY(event, message, author, ...)
return CH.FindURL(self, event, message, author, ...)
end
function CH:ThrottleSound()
CH.SoundTimer = nil
end
local protectLinks = {}
function CH:CheckKeyword(message, author)
if author ~= PLAYER_NAME then
for hyperLink in gmatch(message, "|%x+|H.-|h.-|h|r") do
protectLinks[hyperLink]=gsub(hyperLink,'%s','|s')
for keyword in pairs(CH.Keywords) do
if hyperLink == keyword then
if (self.db.keywordSound ~= 'None') and not self.SoundTimer then
if (self.db.noAlertInCombat and not InCombatLockdown()) or not self.db.noAlertInCombat then
PlaySoundFile(LSM:Fetch("sound", self.db.keywordSound), "Master")
end
self.SoundTimer = E:Delay(1, CH.ThrottleSound)
end
end
end
end
end
for hyperLink, tempLink in pairs(protectLinks) do
message = gsub(message, gsub(hyperLink, '([%(%)%.%%%+%-%*%?%[%^%$])', '%%%1'), tempLink)
end
local rebuiltString
local isFirstWord = true
for word in gmatch(message, "%s-%S+%s*") do
if not next(protectLinks) or not protectLinks[gsub(gsub(word,"%s",""),"|s"," ")] then
local tempWord = gsub(word, "[%s%p]", "")
local lowerCaseWord = strlower(tempWord)
for keyword in pairs(CH.Keywords) do
if lowerCaseWord == strlower(keyword) then
word = gsub(word, tempWord, format("%s%s|r", E.media.hexvaluecolor, tempWord))
if (author ~= PLAYER_NAME) and (self.db.keywordSound ~= 'None') and not self.SoundTimer then
if (self.db.noAlertInCombat and not InCombatLockdown()) or not self.db.noAlertInCombat then
PlaySoundFile(LSM:Fetch("sound", self.db.keywordSound), "Master")
end
self.SoundTimer = E:Delay(1, CH.ThrottleSound)
end
end
end
if self.db.classColorMentionsChat then
tempWord = gsub(word,"^[%s%p]-([^%s%p]+)([%-]?[^%s%p]-)[%s%p]*$","%1%2")
lowerCaseWord = strlower(tempWord)
local classMatch = CH.ClassNames[lowerCaseWord]
local wordMatch = classMatch and lowerCaseWord
if(wordMatch and not E.global.chat.classColorMentionExcludedNames[wordMatch]) then
local classColorTable = _G.CUSTOM_CLASS_COLORS and _G.CUSTOM_CLASS_COLORS[classMatch] or _G.RAID_CLASS_COLORS[classMatch];
word = gsub(word, gsub(tempWord, "%-","%%-"), format("\124cff%.2x%.2x%.2x%s\124r", classColorTable.r*255, classColorTable.g*255, classColorTable.b*255, tempWord))
end
end
end
if isFirstWord then
rebuiltString = word
isFirstWord = false
else
rebuiltString = rebuiltString..word
end
end
for hyperLink, tempLink in pairs(protectLinks) do
rebuiltString = gsub(rebuiltString, gsub(tempLink, '([%(%)%.%%%+%-%*%?%[%^%$])','%%%1'), hyperLink)
protectLinks[hyperLink] = nil
end
return rebuiltString
end
function CH:AddLines(lines, ...)
for i=select("#", ...),1,-1 do
local x = select(i, ...)
if x:IsObjectType('FontString') and not x:GetName() then
tinsert(lines, x:GetText())
end
end
end
function CH:ChatEdit_OnEnterPressed(editBox)
editBox:ClearHistory() -- we will use our own editbox history so keeping them populated on blizzards end is pointless
local chatType = editBox:GetAttribute("chatType")
local chatFrame = chatType and editBox:GetParent()
if chatFrame and (not chatFrame.isTemporary) and (_G.ChatTypeInfo[chatType].sticky == 1) then
if not self.db.sticky then chatType = 'SAY' end
editBox:SetAttribute("chatType", chatType)
end
end
function CH:SetChatFont(dropDown, chatFrame, fontSize)
if ( not chatFrame ) then
chatFrame = FCF_GetCurrentChatFrame();
end
if ( not fontSize ) then
fontSize = dropDown.value;
end
chatFrame:FontTemplate(LSM:Fetch("font", self.db.font), fontSize, self.db.fontOutline)
if self.db.fontOutline ~= 'NONE' then
chatFrame:SetShadowColor(0, 0, 0, 0.2)
else
chatFrame:SetShadowColor(0, 0, 0, 1)
end
chatFrame:SetShadowOffset(E.mult, -E.mult)
end
function CH:ChatEdit_AddHistory(_, line) -- editBox, line
line = line and strtrim(line)
if line and strlen(line) > 0 then
if strfind(line, '/rl') then return end
for index, text in pairs(ElvCharacterDB.ChatEditHistory) do
if text == line then
tremove(ElvCharacterDB.ChatEditHistory, index)
break
end
end
tinsert(ElvCharacterDB.ChatEditHistory, line)
if #ElvCharacterDB.ChatEditHistory > 20 then
tremove(ElvCharacterDB.ChatEditHistory, 1)
end
end
end
function CH:UpdateChatKeywords()
wipe(CH.Keywords)
local keywords = self.db.keywords
keywords = gsub(keywords,',%s',',')
for stringValue in gmatch(keywords, "[^,]+") do
if stringValue ~= '' then
CH.Keywords[stringValue] = true;
end
end
end
function CH:PET_BATTLE_CLOSE()
if not self.db.autoClosePetBattleLog then
return
end
for _, frameName in pairs(_G.CHAT_FRAMES) do
local frame = _G[frameName]
if frame then
local text = _G[frameName.."Tab"]:GetText()
if strmatch(text, DEFAULT_STRINGS.PET_BATTLE_COMBAT_LOG) then
FCF_Close(frame)
end
end
end
end
function CH:UpdateFading()
for _, frameName in pairs(_G.CHAT_FRAMES) do
local frame = _G[frameName]
if frame then
frame:SetFading(self.db.fade)
end
end
end
function CH:DisplayChatHistory()
local data, d = ElvCharacterDB.ChatHistoryLog
if not (data and next(data)) then return end
if not GetPlayerInfoByGUID(E.myguid) then
E:Delay(0.1, CH.DisplayChatHistory)
return
end
CH.SoundTimer = true
for _, chat in pairs(_G.CHAT_FRAMES) do
for i=1, #data do
d = data[i]
if type(d) == 'table' then
for _, messageType in pairs(_G[chat].messageTypeList) do
if gsub(strsub(d[50],10),'_INFORM','') == messageType then
if d[1] and not CH:MessageIsProtected(d[1]) then
CH:ChatFrame_MessageEventHandler(_G[chat],d[50],d[1],d[2],d[3],d[4],d[5],d[6],d[7],d[8],d[9],d[10],d[11],d[12],d[13],d[14],d[15],d[16],d[17],"ElvUI_ChatHistory",d[51],d[52],d[53])
end
end
end
end
end
end
CH.SoundTimer = nil
end
tremove(_G.ChatTypeGroup.GUILD, 2)
function CH:DelayGuildMOTD()
local delay, checks, delayFrame, chat = 0, 0, CreateFrame('Frame')
tinsert(_G.ChatTypeGroup.GUILD, 2, 'GUILD_MOTD')
delayFrame:SetScript('OnUpdate', function(df, elapsed)
delay = delay + elapsed
if delay < 5 then return end
local msg = GetGuildRosterMOTD()
if msg and strlen(msg) > 0 then
for _, frame in pairs(_G.CHAT_FRAMES) do
chat = _G[frame]
if chat and chat:IsEventRegistered('CHAT_MSG_GUILD') then
CH:ChatFrame_SystemEventHandler(chat, 'GUILD_MOTD', msg)
chat:RegisterEvent('GUILD_MOTD')
end
end
df:SetScript('OnUpdate', nil)
else -- 5 seconds can be too fast for the API response. let's try once every 5 seconds (max 5 checks).
delay, checks = 0, checks + 1
if checks >= 5 then
df:SetScript('OnUpdate', nil)
end
end
end)
end
function CH:SaveChatHistory(event, ...)
if not self.db.chatHistory then return end
local data = ElvCharacterDB.ChatHistoryLog
if self.db.throttleInterval ~= 0 and (event == 'CHAT_MSG_SAY' or event == 'CHAT_MSG_YELL' or event == 'CHAT_MSG_CHANNEL') then
self:ChatThrottleHandler(event, ...)
local message, author = ...
local msg = PrepareMessage(author, message)
if author ~= PLAYER_NAME and msgList[msg] then
if difftime(time(), msgTime[msg]) <= CH.db.throttleInterval then
return;
end
end
end
local tempHistory = {}
for i = 1, select('#', ...) do
tempHistory[i] = select(i, ...) or false
end
if (#tempHistory > 0) and not CH:MessageIsProtected(tempHistory[1]) then
tempHistory[50] = event
tempHistory[51] = time()
local coloredName, battleTag
if tempHistory[13] > 0 then coloredName, battleTag = CH:GetBNFriendColor(tempHistory[2], tempHistory[13], true) end
if battleTag then tempHistory[53] = battleTag end -- store the battletag, only when the person is known by battletag, so we can replace arg2 later in the function
tempHistory[52] = coloredName or CH:GetColoredName(event, ...)
tinsert(data, tempHistory)
while #data >= 128 do
tremove(data, 1)
end
end
end
function CH:FCF_SetWindowAlpha(frame, alpha)
frame.oldAlpha = alpha or 1;
end
function CH:CheckLFGRoles()
local isInGroup, isInRaid = IsInGroup(), IsInRaid()
local unit, name, realm = (isInRaid and "raid" or "party")
wipe(lfgRoles)
if(not isInGroup or not self.db.lfgIcons) then return end
local role = UnitGroupRolesAssigned("player")
if(role) then
lfgRoles[PLAYER_NAME] = rolePaths[role]
end
for i=1, GetNumGroupMembers() do
if(UnitExists(unit..i) and not UnitIsUnit(unit..i, "player")) then
role = UnitGroupRolesAssigned(unit..i)
name, realm = UnitName(unit..i)
if(role and name) then
name = (realm and realm ~= '' and name..'-'..realm) or name..'-'..PLAYER_REALM;
lfgRoles[name] = rolePaths[role]
end
end
end
end
function CH:ON_FCF_SavePositionAndDimensions(_, noLoop)
if not noLoop then
CH:PositionChat()
end
if not E.db.chat.lockPositions then
CH:UpdateChatTabs() --It was not done in PositionChat, so do it now
end
end
function CH:JoinBigfootChannel()
JoinTemporaryChannel(L["BigFootChannel"])
-- ChatFrame_RemoveChannel(DEFAULT_CHAT_FRAME, L["BigFootChannel"])
ChatFrame_AddChannel(DEFAULT_CHAT_FRAME, L["BigFootChannel"])
end
function CH:SocialQueueIsLeader(playerName, leaderName)
if leaderName == playerName then
return true
end
for i = 1, BNGetNumFriends() do
local _, accountName, _, _, _, _, _, isOnline = BNGetFriendInfo(i);
if isOnline then
local numGameAccounts = BNGetNumFriendGameAccounts(i);
for y = 1, numGameAccounts do
local _, gameCharacterName, gameClient, realmName = BNGetFriendGameAccountInfo(i, y);
if (gameClient == BNET_CLIENT_WOW) and (accountName == playerName) then
playerName = gameCharacterName
if realmName ~= E.myrealm then
playerName = format('%s-%s', playerName, gsub(realmName,'[%s%-]',''))
end
if leaderName == playerName then
return true
end
end
end
end
end
end
local socialQueueCache = {}
local function RecentSocialQueue(TIME, MSG)
local previousMessage = false
if next(socialQueueCache) then
for guid, tbl in pairs(socialQueueCache) do
-- !dont break this loop! its used to keep the cache updated
if TIME and (difftime(TIME, tbl[1]) >= 300) then
socialQueueCache[guid] = nil --remove any older than 5m
elseif MSG and (MSG == tbl[2]) then
previousMessage = true --dont show any of the same message within 5m
-- see note for `message` in `SocialQueueMessage` about `MSG` content
end
end
end
return previousMessage
end
function CH:SocialQueueMessage(guid, message)
if not (guid and message) then return end
-- `guid` is something like `Party-1147-000011202574` and appears to update each time for solo requeue, otherwise on new group creation.
-- `message` is something like `|cff82c5ff|Kf58|k000000000000|k|r queued for: |cff00CCFFRandom Legion Heroic|r `
-- prevent duplicate messages within 5 minutes
local TIME = time()
if RecentSocialQueue(TIME, message) then return end
socialQueueCache[guid] = {TIME, message}
--UI_71_SOCIAL_QUEUEING_TOAST = 79739; appears to have no sound?
PlaySound(7355) --TUTORIAL_POPUP
E:Print(format('|Hsqu:%s|h%s|h', guid, strtrim(message)))
end
function CH:SocialQueueEvent(_, guid, numAddedItems) -- event, guid, numAddedItems
if not self.db.socialQueueMessages then return end
if numAddedItems == 0 or not guid then return end
local players = C_SocialQueue_GetGroupMembers(guid)
if not players then return end
local firstMember, numMembers, extraCount, coloredName = players[1], #players, ''
local playerName, nameColor = SocialQueueUtil_GetRelationshipInfo(firstMember.guid, nil, firstMember.clubId)
if numMembers > 1 then
extraCount = format(' +%s', numMembers - 1)
end
if playerName then
coloredName = format('%s%s|r%s', nameColor, playerName, extraCount)
else
coloredName = format('{%s%s}', UNKNOWN, extraCount)
end
local queues = C_SocialQueue_GetGroupQueues(guid)
local firstQueue = queues and queues[1]
local isLFGList = firstQueue and firstQueue.queueData and firstQueue.queueData.queueType == 'lfglist'
if isLFGList and firstQueue and firstQueue.eligible then
local searchResultInfo, activityID, name, leaderName, fullName, isLeader
if firstQueue.queueData.lfgListID then
searchResultInfo = C_LFGList_GetSearchResultInfo(firstQueue.queueData.lfgListID)
if searchResultInfo then
activityID, name, leaderName = searchResultInfo.activityID, searchResultInfo.name, searchResultInfo.comment, searchResultInfo.leaderName
isLeader = self:SocialQueueIsLeader(playerName, leaderName)
end
end
if activityID or firstQueue.queueData.activityID then
fullName = C_LFGList_GetActivityInfo(activityID or firstQueue.queueData.activityID)
end
if name then
self:SocialQueueMessage(guid, format('%s %s: [%s] |cff00CCFF%s|r', coloredName, (isLeader and L["is looking for members"]) or L["joined a group"], fullName or UNKNOWN, name))
else
self:SocialQueueMessage(guid, format('%s %s: |cff00CCFF%s|r', coloredName, (isLeader and L["is looking for members"]) or L["joined a group"], fullName or UNKNOWN))
end
elseif firstQueue then
local output, outputCount, queueCount, queueName = '', '', 0
for _, queue in pairs(queues) do
if type(queue) == 'table' and queue.eligible then
queueName = (queue.queueData and SocialQueueUtil_GetQueueName(queue.queueData)) or ''
if queueName ~= '' then
if output == '' then
output = gsub(queueName, '\n.+','') -- grab only the first queue name
queueCount = queueCount + select(2, gsub(queueName, '\n','')) -- collect additional on single queue
else
queueCount = queueCount + 1 + select(2, gsub(queueName, '\n','')) -- collect additional on additional queues
end
end
end
end
if output ~= '' then
if queueCount > 0 then
outputCount = format(LFG_LIST_AND_MORE, queueCount)
end
self:SocialQueueMessage(guid, format('%s %s: |cff00CCFF%s|r %s', coloredName, SOCIAL_QUEUE_QUEUED_FOR, output, outputCount))
end
end
end
local FindURL_Events = {
"CHAT_MSG_WHISPER",
"CHAT_MSG_WHISPER_INFORM",
"CHAT_MSG_BN_WHISPER",
"CHAT_MSG_BN_WHISPER_INFORM",
"CHAT_MSG_BN_INLINE_TOAST_BROADCAST",
"CHAT_MSG_GUILD_ACHIEVEMENT",
"CHAT_MSG_GUILD",
"CHAT_MSG_OFFICER",
"CHAT_MSG_PARTY",
"CHAT_MSG_PARTY_LEADER",
"CHAT_MSG_RAID",
"CHAT_MSG_RAID_LEADER",
"CHAT_MSG_RAID_WARNING",
"CHAT_MSG_INSTANCE_CHAT",
"CHAT_MSG_INSTANCE_CHAT_LEADER",
"CHAT_MSG_CHANNEL",
"CHAT_MSG_SAY",
"CHAT_MSG_YELL",
"CHAT_MSG_EMOTE",
"CHAT_MSG_AFK",
"CHAT_MSG_DND",
"CHAT_MSG_COMMUNITIES_CHANNEL",
}
function CH:DefaultSmileys()
local x = ':16:16'
if next(CH.Smileys) then
wipe(CH.Smileys)
end
-- new keys
CH:AddSmiley(':angry:', E:TextureString(E.Media.ChatEmojis.Angry,x))
CH:AddSmiley(':blush:', E:TextureString(E.Media.ChatEmojis.Blush,x))
CH:AddSmiley(':broken_heart:', E:TextureString(E.Media.ChatEmojis.BrokenHeart,x))
CH:AddSmiley(':call_me:', E:TextureString(E.Media.ChatEmojis.CallMe,x))
CH:AddSmiley(':cry:', E:TextureString(E.Media.ChatEmojis.Cry,x))
CH:AddSmiley(':facepalm:', E:TextureString(E.Media.ChatEmojis.Facepalm,x))
CH:AddSmiley(':grin:', E:TextureString(E.Media.ChatEmojis.Grin,x))
CH:AddSmiley(':heart:', E:TextureString(E.Media.ChatEmojis.Heart,x))
CH:AddSmiley(':heart_eyes:', E:TextureString(E.Media.ChatEmojis.HeartEyes,x))
CH:AddSmiley(':joy:', E:TextureString(E.Media.ChatEmojis.Joy,x))
CH:AddSmiley(':kappa:', E:TextureString(E.Media.ChatEmojis.Kappa,x))
CH:AddSmiley(':middle_finger:', E:TextureString(E.Media.ChatEmojis.MiddleFinger,x))
CH:AddSmiley(':murloc:', E:TextureString(E.Media.ChatEmojis.Murloc,x))
CH:AddSmiley(':ok_hand:', E:TextureString(E.Media.ChatEmojis.OkHand,x))
CH:AddSmiley(':open_mouth:', E:TextureString(E.Media.ChatEmojis.OpenMouth,x))
CH:AddSmiley(':poop:', E:TextureString(E.Media.ChatEmojis.Poop,x))
CH:AddSmiley(':rage:', E:TextureString(E.Media.ChatEmojis.Rage,x))
CH:AddSmiley(':sadkitty:', E:TextureString(E.Media.ChatEmojis.SadKitty,x))
CH:AddSmiley(':scream:', E:TextureString(E.Media.ChatEmojis.Scream,x))
CH:AddSmiley(':scream_cat:', E:TextureString(E.Media.ChatEmojis.ScreamCat,x))
CH:AddSmiley(':slight_frown:', E:TextureString(E.Media.ChatEmojis.SlightFrown,x))
CH:AddSmiley(':smile:', E:TextureString(E.Media.ChatEmojis.Smile,x))
CH:AddSmiley(':smirk:', E:TextureString(E.Media.ChatEmojis.Smirk,x))
CH:AddSmiley(':sob:', E:TextureString(E.Media.ChatEmojis.Sob,x))
CH:AddSmiley(':sunglasses:', E:TextureString(E.Media.ChatEmojis.Sunglasses,x))
CH:AddSmiley(':thinking:', E:TextureString(E.Media.ChatEmojis.Thinking,x))
CH:AddSmiley(':thumbs_up:', E:TextureString(E.Media.ChatEmojis.ThumbsUp,x))
CH:AddSmiley(':semi_colon:', E:TextureString(E.Media.ChatEmojis.SemiColon,x))
CH:AddSmiley(':wink:', E:TextureString(E.Media.ChatEmojis.Wink,x))
CH:AddSmiley(':zzz:', E:TextureString(E.Media.ChatEmojis.ZZZ,x))
CH:AddSmiley(':stuck_out_tongue:', E:TextureString(E.Media.ChatEmojis.StuckOutTongue,x))
CH:AddSmiley(':stuck_out_tongue_closed_eyes:', E:TextureString(E.Media.ChatEmojis.StuckOutTongueClosedEyes,x))
-- Darth's keys
CH:AddSmiley(':meaw:', E:TextureString(E.Media.ChatEmojis.Meaw,x))
-- Simpy's keys
CH:AddSmiley('>:%(', E:TextureString(E.Media.ChatEmojis.Rage,x))
CH:AddSmiley(':%$', E:TextureString(E.Media.ChatEmojis.Blush,x))
CH:AddSmiley('<\\3', E:TextureString(E.Media.ChatEmojis.BrokenHeart,x))
CH:AddSmiley(':\'%)', E:TextureString(E.Media.ChatEmojis.Joy,x))
CH:AddSmiley(';\'%)', E:TextureString(E.Media.ChatEmojis.Joy,x))
CH:AddSmiley(',,!,,', E:TextureString(E.Media.ChatEmojis.MiddleFinger,x))
CH:AddSmiley('D:<', E:TextureString(E.Media.ChatEmojis.Rage,x))
CH:AddSmiley(':o3', E:TextureString(E.Media.ChatEmojis.ScreamCat,x))
CH:AddSmiley('XP', E:TextureString(E.Media.ChatEmojis.StuckOutTongueClosedEyes,x))
CH:AddSmiley('8%-%)', E:TextureString(E.Media.ChatEmojis.Sunglasses,x))
CH:AddSmiley('8%)', E:TextureString(E.Media.ChatEmojis.Sunglasses,x))
CH:AddSmiley(':%+1:', E:TextureString(E.Media.ChatEmojis.ThumbsUp,x))
CH:AddSmiley(':;:', E:TextureString(E.Media.ChatEmojis.SemiColon,x))
CH:AddSmiley(';o;', E:TextureString(E.Media.ChatEmojis.Sob,x))
-- old keys
CH:AddSmiley(':%-@', E:TextureString(E.Media.ChatEmojis.Angry,x))
CH:AddSmiley(':@', E:TextureString(E.Media.ChatEmojis.Angry,x))
CH:AddSmiley(':%-%)', E:TextureString(E.Media.ChatEmojis.Smile,x))
CH:AddSmiley(':%)', E:TextureString(E.Media.ChatEmojis.Smile,x))
CH:AddSmiley(':D', E:TextureString(E.Media.ChatEmojis.Grin,x))
CH:AddSmiley(':%-D', E:TextureString(E.Media.ChatEmojis.Grin,x))
CH:AddSmiley(';%-D', E:TextureString(E.Media.ChatEmojis.Grin,x))
CH:AddSmiley(';D', E:TextureString(E.Media.ChatEmojis.Grin,x))
CH:AddSmiley('=D', E:TextureString(E.Media.ChatEmojis.Grin,x))
CH:AddSmiley('xD', E:TextureString(E.Media.ChatEmojis.Grin,x))
CH:AddSmiley('XD', E:TextureString(E.Media.ChatEmojis.Grin,x))
CH:AddSmiley(':%-%(', E:TextureString(E.Media.ChatEmojis.SlightFrown,x))
CH:AddSmiley(':%(', E:TextureString(E.Media.ChatEmojis.SlightFrown,x))
CH:AddSmiley(':o', E:TextureString(E.Media.ChatEmojis.OpenMouth,x))
CH:AddSmiley(':%-o', E:TextureString(E.Media.ChatEmojis.OpenMouth,x))
CH:AddSmiley(':%-O', E:TextureString(E.Media.ChatEmojis.OpenMouth,x))
CH:AddSmiley(':O', E:TextureString(E.Media.ChatEmojis.OpenMouth,x))
CH:AddSmiley(':%-0', E:TextureString(E.Media.ChatEmojis.OpenMouth,x))
CH:AddSmiley(':P', E:TextureString(E.Media.ChatEmojis.StuckOutTongue,x))
CH:AddSmiley(':%-P', E:TextureString(E.Media.ChatEmojis.StuckOutTongue,x))
CH:AddSmiley(':p', E:TextureString(E.Media.ChatEmojis.StuckOutTongue,x))
CH:AddSmiley(':%-p', E:TextureString(E.Media.ChatEmojis.StuckOutTongue,x))
CH:AddSmiley('=P', E:TextureString(E.Media.ChatEmojis.StuckOutTongue,x))
CH:AddSmiley('=p', E:TextureString(E.Media.ChatEmojis.StuckOutTongue,x))
CH:AddSmiley(';%-p', E:TextureString(E.Media.ChatEmojis.StuckOutTongueClosedEyes,x))
CH:AddSmiley(';p', E:TextureString(E.Media.ChatEmojis.StuckOutTongueClosedEyes,x))
CH:AddSmiley(';P', E:TextureString(E.Media.ChatEmojis.StuckOutTongueClosedEyes,x))
CH:AddSmiley(';%-P', E:TextureString(E.Media.ChatEmojis.StuckOutTongueClosedEyes,x))
CH:AddSmiley(';%-%)', E:TextureString(E.Media.ChatEmojis.Wink,x))
CH:AddSmiley(';%)', E:TextureString(E.Media.ChatEmojis.Wink,x))
CH:AddSmiley(':S', E:TextureString(E.Media.ChatEmojis.Smirk,x))
CH:AddSmiley(':%-S', E:TextureString(E.Media.ChatEmojis.Smirk,x))
CH:AddSmiley(':,%(', E:TextureString(E.Media.ChatEmojis.Cry,x))
CH:AddSmiley(':,%-%(', E:TextureString(E.Media.ChatEmojis.Cry,x))
CH:AddSmiley(':\'%(', E:TextureString(E.Media.ChatEmojis.Cry,x))
CH:AddSmiley(':\'%-%(', E:TextureString(E.Media.ChatEmojis.Cry,x))
CH:AddSmiley(':F', E:TextureString(E.Media.ChatEmojis.MiddleFinger,x))
CH:AddSmiley('<3', E:TextureString(E.Media.ChatEmojis.Heart,x))
CH:AddSmiley('</3', E:TextureString(E.Media.ChatEmojis.BrokenHeart,x))
end
local channelButtons = {
[1] = _G.ChatFrameChannelButton,
[2] = _G.ChatFrameToggleVoiceDeafenButton,
[3] = _G.ChatFrameToggleVoiceMuteButton
}
function CH:RepositionChatVoiceIcons()
_G.GeneralDockManagerScrollFrame:SetPoint("BOTTOMRIGHT") -- call our hook
_G.GeneralDockManagerOverflowButton:ClearAllPoints()
if channelButtons[3]:IsShown() then
_G.GeneralDockManagerOverflowButton:Point('RIGHT', channelButtons[3], 'LEFT', -4, 2)
else
_G.GeneralDockManagerOverflowButton:Point('RIGHT', channelButtons[1], 'LEFT', -4, 2)
end
end
function CH:UpdateVoiceChatIcons()
for _, button in pairs(channelButtons) do
button.Icon:SetDesaturated(E.db.chat.desaturateVoiceIcons)
end
end
function CH:HandleChatVoiceIcons()
if CH.db.hideVoiceButtons then
for _, button in pairs(channelButtons) do
button:Hide()
end
elseif CH.db.pinVoiceButtons then
for index, button in pairs(channelButtons) do
button:ClearAllPoints()
button.Icon:SetDesaturated(E.db.chat.desaturateVoiceIcons)
Skins:HandleButton(button, nil, nil, nil, true)
if index == 1 then
button:SetPoint('BOTTOMRIGHT', _G.LeftChatTab, 'BOTTOMRIGHT', 3, -3)
else
button:SetPoint("RIGHT", channelButtons[index-1], "LEFT")
end
end
_G.GeneralDockManagerOverflowButton:ClearAllPoints()
_G.GeneralDockManagerOverflowButton:Point('RIGHT', channelButtons[3], 'LEFT', 0, 2)
_G.GeneralDockManagerOverflowButtonList:SetTemplate('Transparent')
channelButtons[3]:HookScript("OnShow", CH.RepositionChatVoiceIcons)
channelButtons[3]:HookScript("OnHide", CH.RepositionChatVoiceIcons) -- dont think this is needed but meh
hooksecurefunc(_G.GeneralDockManagerScrollFrame, 'SetPoint', function(frame, point, anchor, attachTo, x, y, stopLoop)
if anchor == _G.GeneralDockManagerOverflowButton and (x == 0 and y == 0) then
frame:Point(point, anchor, attachTo, -3, -6)
elseif point == "BOTTOMRIGHT" and anchor ~= channelButtons[3] and anchor ~= channelButtons[1] and not _G.GeneralDockManagerOverflowButton:IsShown() and not stopLoop then
if channelButtons[3]:IsShown() then
frame:Point(point, anchor, attachTo, -30, -5, true)
else
frame:Point(point, anchor, attachTo, -10, -5, true)
end
end
end)
-- We skin it later in Style chat, to keep the backdrops on the button if the option are disabled
Skins:HandleNextPrevButton(_G.GeneralDockManagerOverflowButton, "down", nil, true)
CH:RepositionChatVoiceIcons()
else
CH:CreateChatVoicePanel()
end
end
function CH:CreateChatVoicePanel()
local Holder = CreateFrame('Frame', 'ChatButtonHolder', E.UIParent)
Holder:ClearAllPoints()
Holder:Point("BOTTOMLEFT", _G.LeftChatPanel, "TOPLEFT", 0, 1)
Holder:Size(30, 86)
Holder:SetTemplate('Transparent', nil, true)
Holder:SetBackdropColor(E.db.chat.panelColor.r, E.db.chat.panelColor.g, E.db.chat.panelColor.b, E.db.chat.panelColor.a)
E:CreateMover(Holder, "SocialMenuMover", _G.BINDING_HEADER_VOICE_CHAT, nil, nil, nil, nil, nil, 'chat')
channelButtons[1]:ClearAllPoints()
channelButtons[1]:Point('TOP', Holder, 'TOP', 0, -2)
for _, button in pairs(channelButtons) do
Skins:HandleButton(button, nil, nil, nil, true)
button.Icon:SetParent(button)
button.Icon:SetDesaturated(E.db.chat.desaturateVoiceIcons)
button:SetParent(Holder)
end
_G.ChatAlertFrame:ClearAllPoints()
_G.ChatAlertFrame:Point("BOTTOM", channelButtons[1], "TOP", 1, 3)
-- Skin the QuickJoinToastButton
local Button = _G.QuickJoinToastButton
Button:SetTemplate()
Button:SetParent(Holder)
Button:ClearAllPoints()
Button:Point('BOTTOM', Holder, 'TOP', -E.Border, 2*E.Border)
Button:Size(30, 32)
-- Button:Hide() -- DONT KILL IT! If we use hide we also hide the Toasts, which are used in other Plugins.
-- Change the QuickJoin Textures. Looks better =)
local friendTex = 'Interface\\HELPFRAME\\ReportLagIcon-Chat'
local queueTex = 'Interface\\HELPFRAME\\HelpIcon-ItemRestoration'
Button.FriendsButton:SetTexture(friendTex)
Button.QueueButton:SetTexture(queueTex)
hooksecurefunc(Button, 'ToastToFriendFinished', function(t)
t.FriendsButton:SetShown(not t.displayedToast)
t.FriendCount:SetShown(not t.displayedToast)
end)
hooksecurefunc(Button, 'UpdateQueueIcon', function(t)
if not t.displayedToast then return end
t.FriendsButton:SetTexture(friendTex)
t.QueueButton:SetTexture(queueTex)
t.FlashingLayer:SetTexture(queueTex)
t.FriendsButton:SetShown(false)
t.FriendCount:SetShown(false)
end)
Button:HookScript('OnMouseDown', function(t) t.FriendsButton:SetTexture(friendTex) end)
Button:HookScript('OnMouseUp', function(t) t.FriendsButton:SetTexture(friendTex) end)
-- Skin the `QuickJoinToastButton.Toast`
Button.Toast:ClearAllPoints()
Button.Toast:Point('LEFT', Button, 'RIGHT', -6, 0)
Button.Toast.Background:SetTexture('')
Button.Toast:CreateBackdrop('Transparent')
Button.Toast.backdrop:Hide()
hooksecurefunc(Button, "ShowToast", function() Button.Toast.backdrop:Show() end)
hooksecurefunc(Button, "HideToast", function() Button.Toast.backdrop:Hide() end)
end
function CH:BuildCopyChatFrame()
local frame = CreateFrame("Frame", "CopyChatFrame", E.UIParent)
tinsert(_G.UISpecialFrames, "CopyChatFrame")
frame:SetTemplate('Transparent')
frame:Size(700, 200)
frame:Point('BOTTOM', E.UIParent, 'BOTTOM', 0, 3)
frame:Hide()
frame:SetMovable(true)
frame:EnableMouse(true)
frame:SetResizable(true)
frame:SetMinResize(350, 100)
frame:SetScript("OnMouseDown", function(copyChat, button)
if button == "LeftButton" and not copyChat.isMoving then
copyChat:StartMoving();
copyChat.isMoving = true;
elseif button == "RightButton" and not copyChat.isSizing then
copyChat:StartSizing();
copyChat.isSizing = true;
end
end)
frame:SetScript("OnMouseUp", function(copyChat, button)
if button == "LeftButton" and copyChat.isMoving then
copyChat:StopMovingOrSizing();
copyChat.isMoving = false;
elseif button == "RightButton" and copyChat.isSizing then
copyChat:StopMovingOrSizing();
copyChat.isSizing = false;
end
end)
frame:SetScript("OnHide", function(copyChat)
if ( copyChat.isMoving or copyChat.isSizing) then
copyChat:StopMovingOrSizing();
copyChat.isMoving = false;
copyChat.isSizing = false;
end
end)
frame:SetFrameStrata("DIALOG")
local scrollArea = CreateFrame("ScrollFrame", "CopyChatScrollFrame", frame, "UIPanelScrollFrameTemplate")
scrollArea:Point("TOPLEFT", frame, "TOPLEFT", 8, -30)
scrollArea:Point("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -30, 8)
Skins:HandleScrollBar(_G.CopyChatScrollFrameScrollBar)
scrollArea:SetScript("OnSizeChanged", function(scroll)
_G.CopyChatFrameEditBox:Width(scroll:GetWidth())
_G.CopyChatFrameEditBox:Height(scroll:GetHeight())
end)
scrollArea:HookScript("OnVerticalScroll", function(scroll, offset)
_G.CopyChatFrameEditBox:SetHitRectInsets(0, 0, offset, (_G.CopyChatFrameEditBox:GetHeight() - offset - scroll:GetHeight()))
end)
local editBox = CreateFrame("EditBox", "CopyChatFrameEditBox", frame)
editBox:SetMultiLine(true)
editBox:SetMaxLetters(99999)
editBox:EnableMouse(true)
editBox:SetAutoFocus(false)
editBox:SetFontObject(_G.ChatFontNormal)
editBox:Width(scrollArea:GetWidth())
editBox:Height(200)
editBox:SetScript("OnEscapePressed", function() _G.CopyChatFrame:Hide() end)
scrollArea:SetScrollChild(editBox)
_G.CopyChatFrameEditBox:SetScript("OnTextChanged", function(_, userInput)
if userInput then return end
local _, max = _G.CopyChatScrollFrameScrollBar:GetMinMaxValues()
for _ = 1, max do
ScrollFrameTemplate_OnMouseWheel(_G.CopyChatScrollFrame, -1)
end
end)
local close = CreateFrame("Button", "CopyChatFrameCloseButton", frame, "UIPanelCloseButton")
close:Point("TOPRIGHT")
close:SetFrameLevel(close:GetFrameLevel() + 1)
close:EnableMouse(true)
Skins:HandleCloseButton(close)
end
function CH:Initialize()
if ElvCharacterDB.ChatHistory then ElvCharacterDB.ChatHistory = nil end --Depreciated
if ElvCharacterDB.ChatLog then ElvCharacterDB.ChatLog = nil end --Depreciated
self:DelayGuildMOTD() -- Keep this before `is Chat Enabled` check
if E.private.chat.enable ~= true then return end
self.Initialized = true
self.db = E.db.chat
if not ElvCharacterDB.ChatEditHistory then ElvCharacterDB.ChatEditHistory = {} end
if not ElvCharacterDB.ChatHistoryLog or not self.db.chatHistory then ElvCharacterDB.ChatHistoryLog = {} end
_G.ChatFrameMenuButton:Kill()
self:SetupChat()
self:DefaultSmileys()
self:UpdateChatKeywords()
self:UpdateFading()
self:UpdateAnchors()
self:Panels_ColorUpdate()
self:HandleChatVoiceIcons()
self:LoadChatbar()
self:LoadChatEmote()
self:LoadStatReport()
self:LoadChatItemLevel()
self:SecureHook('ChatEdit_OnEnterPressed')
self:SecureHook('FCF_SetWindowAlpha')
self:SecureHook('FCF_SetChatWindowFontSize', 'SetChatFont')
self:SecureHook('FCF_SavePositionAndDimensions', 'ON_FCF_SavePositionAndDimensions')
self:RegisterEvent('UPDATE_CHAT_WINDOWS', 'SetupChat')
self:RegisterEvent('UPDATE_FLOATING_CHAT_WINDOWS', 'SetupChat')
self:RegisterEvent('GROUP_ROSTER_UPDATE', 'CheckLFGRoles')
self:RegisterEvent('SOCIAL_QUEUE_UPDATE', 'SocialQueueEvent')
self:RegisterEvent('PET_BATTLE_CLOSE')
if E.private.general.voiceOverlay then
self:RegisterEvent('VOICE_CHAT_CHANNEL_MEMBER_SPEAKING_STATE_CHANGED', 'VoiceOverlay');
self:RegisterEvent('VOICE_CHAT_CHANNEL_MEMBER_ENERGY_CHANGED', 'VoiceOverlay');
self:RegisterEvent('VOICE_CHAT_CHANNEL_TRANSMIT_CHANGED', 'VoiceOverlay');
self:RegisterEvent('VOICE_CHAT_COMMUNICATION_MODE_CHANGED', 'VoiceOverlay');
self:RegisterEvent('VOICE_CHAT_CHANNEL_MEMBER_REMOVED', 'VoiceOverlay');
self:RegisterEvent('VOICE_CHAT_CHANNEL_REMOVED', 'VoiceOverlay');
self:RegisterEvent('VOICE_CHAT_CHANNEL_DEACTIVATED', 'VoiceOverlay');
_G.VoiceActivityManager:UnregisterAllEvents();
end
if _G.WIM then
_G.WIM.RegisterWidgetTrigger("chat_display", "whisper,chat,w2w,demo", "OnHyperlinkClick", function(frame) CH.clickedframe = frame end);
_G.WIM.RegisterItemRefHandler('url', HyperLinkedURL)
_G.WIM.RegisterItemRefHandler('squ', HyperLinkedSQU)
_G.WIM.RegisterItemRefHandler('cpl', HyperLinkedCPL)
end
if not E.db.chat.lockPositions then CH:UpdateChatTabs() end --It was not done in PositionChat, so do it now
for _, event in pairs(FindURL_Events) do
_G.ChatFrame_AddMessageEventFilter(event, CH[event] or CH.FindURL)
local nType = strsub(event, 10)
if nType ~= 'AFK' and nType ~= 'DND' and nType ~= 'COMMUNITIES_CHANNEL' then
self:RegisterEvent(event, 'SaveChatHistory')
end
end
if self.db.chatHistory then self:DisplayChatHistory() end
self:BuildCopyChatFrame()
if E.db.chat.autojoin then
CH:ScheduleTimer('JoinBigfootChannel', 12.5)
end
-- Editbox Backdrop Color
hooksecurefunc("ChatEdit_UpdateHeader", function(editbox)
local chatType = editbox:GetAttribute("chatType")
if not chatType then return end
local ChatTypeInfo = _G.ChatTypeInfo
local info = ChatTypeInfo[chatType]
local chanTarget = editbox:GetAttribute("channelTarget")
local chanName = chanTarget and GetChannelName(chanTarget)
--Increase inset on right side to make room for character count text
local insetLeft, insetRight, insetTop, insetBottom = editbox:GetTextInsets()
editbox:SetTextInsets(insetLeft, insetRight + 30, insetTop, insetBottom)
if chanName and (chatType == "CHANNEL") then
if chanName == 0 then
editbox:SetBackdropBorderColor(unpack(E.media.bordercolor))
else
info = ChatTypeInfo[chatType..chanName]
editbox:SetBackdropBorderColor(info.r, info.g, info.b)
end
else
editbox:SetBackdropBorderColor(info.r, info.g, info.b)
end
end)
-- Combat Log Skinning (credit: Aftermathh)
local CombatLogButton = _G.CombatLogQuickButtonFrame_Custom
if CombatLogButton then
local CombatLogFontContainer = _G.ChatFrame2 and _G.ChatFrame2.FontStringContainer
CombatLogButton:StripTextures()
CombatLogButton:SetTemplate("Transparent")
if CombatLogFontContainer then
CombatLogButton:ClearAllPoints()
CombatLogButton:Point("BOTTOMLEFT", CombatLogFontContainer, "TOPLEFT", -1, 1)
CombatLogButton:Point("BOTTOMRIGHT", CombatLogFontContainer, "TOPRIGHT", E.PixelMode and 4 or 0, 1)
end
for i = 1, 2 do
local CombatLogQuickButton = _G["CombatLogQuickButtonFrameButton"..i]
if CombatLogQuickButton then
local CombatLogText = CombatLogQuickButton:GetFontString()
CombatLogText:FontTemplate(nil, nil, 'OUTLINE')
end
end
local CombatLogProgressBar = _G.CombatLogQuickButtonFrame_CustomProgressBar
CombatLogProgressBar:SetStatusBarTexture(E.media.normTex)
CombatLogProgressBar:SetInside(CombatLogButton)
Skins:HandleNextPrevButton(_G.CombatLogQuickButtonFrame_CustomAdditionalFilterButton)
_G.CombatLogQuickButtonFrame_CustomAdditionalFilterButton:Size(20, 22)
_G.CombatLogQuickButtonFrame_CustomAdditionalFilterButton:Point("TOPRIGHT", CombatLogButton, "TOPRIGHT", 0, -1)
_G.CombatLogQuickButtonFrame_CustomTexture:Hide()
end
--Chat Heads Frame
self.ChatHeadFrame = CreateFrame("Frame", "ElvUIChatHeadFrame", E.UIParent)
self.ChatHeadFrame:Point("TOPLEFT", E.UIParent, "TOPLEFT", 4, -80)
self.ChatHeadFrame:Height(20)
self.ChatHeadFrame:Width(200)
E:CreateMover(self.ChatHeadFrame, 'VOICECHAT', L["Voice Overlay"]);
self.maxHeads = 5
self.volumeBarHeight = 3
local CHAT_HEAD_HEIGHT = 40
for i=1, self.maxHeads do
self.ChatHeadFrame[i] = CreateFrame("Frame", "ElvUIChatHeadFrame"..i, self.ChatHeadFrame)
self.ChatHeadFrame[i]:Width(self.ChatHeadFrame:GetWidth())
self.ChatHeadFrame[i]:Height(CHAT_HEAD_HEIGHT)
self.ChatHeadFrame[i].Portrait = CreateFrame("Frame", nil, self.ChatHeadFrame[i])
self.ChatHeadFrame[i].Portrait:Width(CHAT_HEAD_HEIGHT - self.volumeBarHeight)
self.ChatHeadFrame[i].Portrait:Height(CHAT_HEAD_HEIGHT - self.volumeBarHeight - E.Border*2)
self.ChatHeadFrame[i].Portrait:Point("TOPLEFT", self.ChatHeadFrame[i], "TOPLEFT")
self.ChatHeadFrame[i].Portrait:SetTemplate()
self.ChatHeadFrame[i].Portrait.texture = self.ChatHeadFrame[i].Portrait:CreateTexture(nil, "OVERLAY")
self.ChatHeadFrame[i].Portrait.texture:SetTexCoord(0.15, 0.85, 0.15, 0.85)
self.ChatHeadFrame[i].Portrait.texture:SetInside(self.ChatHeadFrame[i].Portrait)
self.ChatHeadFrame[i].Name = self.ChatHeadFrame[i]:CreateFontString(nil, "OVERLAY")
self.ChatHeadFrame[i].Name:FontTemplate(nil, 20)
self.ChatHeadFrame[i].Name:Point("LEFT", self.ChatHeadFrame[i].Portrait, "RIGHT", 2, 0)
self.ChatHeadFrame[i].StatusBar = CreateFrame("StatusBar", nil, self.ChatHeadFrame[i])
self.ChatHeadFrame[i].StatusBar:Point("TOPLEFT", self.ChatHeadFrame[i].Portrait, "BOTTOMLEFT", E.Border, -E.Spacing*3)
self.ChatHeadFrame[i].StatusBar:Width(CHAT_HEAD_HEIGHT - E.Border*2 - self.volumeBarHeight)
self.ChatHeadFrame[i].StatusBar:Height(self.volumeBarHeight)
self.ChatHeadFrame[i].StatusBar:CreateBackdrop()
self.ChatHeadFrame[i].StatusBar:SetStatusBarTexture(E.media.normTex)
self.ChatHeadFrame[i].StatusBar:SetMinMaxValues(0, 1)
self.ChatHeadFrame[i].StatusBar.anim = CreateAnimationGroup(self.ChatHeadFrame[i].StatusBar)
self.ChatHeadFrame[i].StatusBar.anim.progress = self.ChatHeadFrame[i].StatusBar.anim:CreateAnimation("Progress")
self.ChatHeadFrame[i].StatusBar.anim.progress:SetSmoothing("Out")
self.ChatHeadFrame[i].StatusBar.anim.progress:SetDuration(.3)
self.ChatHeadFrame[i]:Hide()
end
self:SetChatHeadOrientation("TOP")
end
CH.TalkingList = {}
function CH:GetAvailableHead()
for i=1, self.maxHeads do
if not self.ChatHeadFrame[i]:IsShown() then
return self.ChatHeadFrame[i]
end
end
end
function CH:GetHeadByID(memberID)
for i=1, self.maxHeads do
if self.ChatHeadFrame[i].memberID == memberID then
return self.ChatHeadFrame[i]
end
end
end
function CH:ConfigureHead(memberID, channelID)
local frame = self:GetAvailableHead()
if not frame then return end
frame.memberID = memberID
frame.channelID = channelID
C_VoiceChat_SetPortraitTexture(frame.Portrait.texture, memberID, channelID);
local memberName = C_VoiceChat_GetMemberName(memberID, channelID);
local r, g, b = Voice_GetVoiceChannelNotificationColor(channelID);
frame.Name:SetText(memberName or "")
frame.Name:SetVertexColor(r, g, b, 1);
frame:Show()
end
function CH:DeconfigureHead(memberID) -- memberID, channelID
local frame = self:GetHeadByID(memberID)
if not frame then return end
frame.memberID = nil
frame.channelID = nil
frame:Hide()
end
function CH:VoiceOverlay(event, ...)
if event == "VOICE_CHAT_CHANNEL_MEMBER_SPEAKING_STATE_CHANGED" then
local memberID, channelID, isTalking = ...
if isTalking then
CH.TalkingList[memberID] = channelID
self:ConfigureHead(memberID, channelID)
else
CH.TalkingList[memberID] = nil
self:DeconfigureHead(memberID, channelID)
end
elseif event == "VOICE_CHAT_CHANNEL_MEMBER_ENERGY_CHANGED" then
local memberID, channelID, volume = ...
local frame = CH:GetHeadByID(memberID)
if frame and channelID == frame.channelID then
frame.StatusBar.anim.progress:SetChange(volume)
frame.StatusBar.anim.progress:Play()
frame.StatusBar:SetStatusBarColor(E:ColorGradient(volume, 1, 0, 0, 1, 1, 0, 0, 1, 0))
end
--[[elseif event == "VOICE_CHAT_CHANNEL_TRANSMIT_CHANGED" then
local channelID, isTransmitting = ...
local localPlayerMemberID = C_VoiceChat.GetLocalPlayerMemberID(channelID);
if isTransmitting and not CH.TalkingList[localPlayerMemberID] then
CH.TalkingList[localPlayerMemberID] = channelID
self:ConfigureHead(localPlayerMemberID, channelID)
end]]
end
end
function CH:SetChatHeadOrientation(position)
if position == "TOP" then
for i=1, self.maxHeads do
self.ChatHeadFrame[i]:ClearAllPoints()
if i == 1 then
self.ChatHeadFrame[i]:Point("TOP", self.ChatHeadFrame, "BOTTOM", 0, -E.Border*3)
else
self.ChatHeadFrame[i]:Point("TOP", self.ChatHeadFrame[i - 1], "BOTTOM", 0, -E.Border*3)
end
end
else
for i=1, self.maxHeads do
self.ChatHeadFrame[i]:ClearAllPoints()
if i == 1 then
self.ChatHeadFrame[i]:Point("BOTTOM", self.ChatHeadFrame, "TOP", 0, E.Border*3)
else
self.ChatHeadFrame[i]:Point("BOTTOM", self.ChatHeadFrame[i - 1], "TOP", 0, E.Border*3)
end
end
end
end
local function InitializeCallback()
CH:Initialize()
end
E:RegisterModule(CH:GetName(), InitializeCallback)
|
require "conf"
-- 用于logger的处理 响应内容写入resp
if not LOG_RESP then
ngx.ctx.resp = '-'
return
end
local chunk = ngx.arg[1]
if (string.len(chunk) > 0) then
ngx.ctx.resp = chunk
end
|
package("octomap")
set_homepage("https://octomap.github.io/")
set_description("An Efficient Probabilistic 3D Mapping Framework Based on Octrees")
set_license("BSD-3-Clause")
add_urls("https://github.com/OctoMap/octomap/archive/refs/tags/$(version).tar.gz",
"https://github.com/OctoMap/octomap.git")
add_versions("v1.9.7", "3e9ac020686ceb4e17e161bffc5a0dafd9cccab33adeb9adee59a61c418ea1c1")
add_patches("v1.9.7", path.join(os.scriptdir(), "patches", "1.9.7", "build.patch"), "396b7b28c754f876c8552da93abf463f31bd65e327f454e75b8a5c10bb62ded4")
if is_plat("windows") then
add_configs("shared", {description = "Build shared library.", default = false, type = "boolean", readonly = true})
end
add_deps("cmake")
on_install("windows", "macosx", "linux", function (package)
local configs = {}
table.insert(configs, "-DCMAKE_BUILD_TYPE=" .. (package:debug() and "Debug" or "Release"))
table.insert(configs, "-DBUILD_SHARED_LIBS=" .. (package:config("shared") and "ON" or "OFF"))
import("package.tools.cmake").install(package, configs)
package:addenv("PATH", "bin")
end)
on_test(function (package)
assert(package:check_cxxsnippets({test = [[
void test() {
octomap::OcTree tree(0.1);
octomap::point3d endpoint(0.05f, 0.05f, 0.05f);
tree.updateNode(endpoint, true);
}
]]}, {configs = {languages = "c++11"}, includes = "octomap/octomap.h"}))
end)
|
--
-- Licensed to the Apache Software Foundation (ASF) under one or more
-- contributor license agreements. See the NOTICE file distributed with
-- this work for additional information regarding copyright ownership.
-- The ASF licenses this file to You 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 ngx = ngx
local bit = require("bit")
local core = require("apisix.core")
local snowflake = require("snowflake")
local uuid = require("resty.jit-uuid")
local process = require("ngx.process")
local timers = require("apisix.timers")
local tostring = tostring
local math_pow = math.pow
local math_ceil = math.ceil
local math_floor = math.floor
local plugin_name = "request-id"
local data_machine = nil
local snowflake_inited = nil
local attr = nil
local schema = {
type = "object",
properties = {
header_name = {type = "string", default = "X-Request-Id"},
include_in_response = {type = "boolean", default = true},
algorithm = {type = "string", enum = {"uuid", "snowflake"}, default = "uuid"}
}
}
local attr_schema = {
type = "object",
properties = {
snowflake = {
type = "object",
properties = {
enable = {type = "boolean", default = false},
snowflake_epoc = {type = "integer", minimum = 1, default = 1609459200000},
data_machine_bits = {type = "integer", minimum = 1, maximum = 31, default = 12},
sequence_bits = {type = "integer", minimum = 1, default = 10},
delta_offset = {type = "integer", default = 1, enum = {1, 10, 100, 1000}},
data_machine_ttl = {type = "integer", minimum = 1, default = 30},
data_machine_interval = {type = "integer", minimum = 1, default = 10}
}
}
}
}
local _M = {
version = 0.1,
priority = 11010,
name = plugin_name,
schema = schema
}
function _M.check_schema(conf)
return core.schema.check(schema, conf)
end
-- Generates the current process data machine
local function gen_data_machine(max_number)
if data_machine == nil then
local etcd_cli, prefix = core.etcd.new()
local prefix = prefix .. "/plugins/request-id/snowflake/"
local uuid = uuid.generate_v4()
local id = 1
::continue::
while (id <= max_number) do
local res, err = etcd_cli:grant(attr.snowflake.data_machine_ttl)
if err then
id = id + 1
core.log.error("Etcd grant failure, err: ".. err)
goto continue
end
local _, err1 = etcd_cli:setnx(prefix .. tostring(id), uuid)
local res2, err2 = etcd_cli:get(prefix .. tostring(id))
if err1 or err2 or res2.body.kvs[1].value ~= uuid then
core.log.notice("data_machine " .. id .. " is not available")
id = id + 1
else
data_machine = id
local _, err3 =
etcd_cli:set(
prefix .. tostring(id),
uuid,
{
prev_kv = true,
lease = res.body.ID
}
)
if err3 then
id = id + 1
etcd_cli:delete(prefix .. tostring(id))
core.log.error("set data_machine " .. id .. " lease error: " .. err3)
goto continue
end
local lease_id = res.body.ID
local start_at = ngx.time()
local handler = function()
local now = ngx.time()
if now - start_at < attr.snowflake.data_machine_interval then
return
end
local _, err4 = etcd_cli:keepalive(lease_id)
if err4 then
snowflake_inited = nil
data_machine = nil
core.log.error("snowflake data_machine: " .. id .." lease failed.")
end
start_at = now
core.log.info("snowflake data_machine: " .. id .." lease success.")
end
timers.register_timer("plugin#request-id", handler)
core.log.info(
"timer created to lease snowflake algorithm data_machine, interval: ",
attr.snowflake.data_machine_interval)
core.log.notice("lease snowflake data_machine: " .. id)
break
end
end
if data_machine == nil then
core.log.error("No data_machine is not available")
return nil
end
end
return data_machine
end
-- Split 'Data Machine' into 'Worker ID' and 'datacenter ID'
local function split_data_machine(data_machine, node_id_bits, datacenter_id_bits)
local num = bit.tobit(data_machine)
local worker_id = bit.band(num, math_pow(2, node_id_bits) - 1)
num = bit.rshift(num, node_id_bits)
local datacenter_id = bit.band(num, math_pow(2, datacenter_id_bits) - 1)
return worker_id, datacenter_id
end
-- Initialize the snowflake algorithm
local function snowflake_init()
if snowflake_inited == nil then
local max_number = math_pow(2, (attr.snowflake.data_machine_bits))
local datacenter_id_bits = math_floor(attr.snowflake.data_machine_bits / 2)
local node_id_bits = math_ceil(attr.snowflake.data_machine_bits / 2)
data_machine = gen_data_machine(max_number)
if data_machine == nil then
return ""
end
local worker_id, datacenter_id = split_data_machine(data_machine,
node_id_bits, datacenter_id_bits)
core.log.info("snowflake init datacenter_id: " ..
datacenter_id .. " worker_id: " .. worker_id)
snowflake.init(
datacenter_id,
worker_id,
attr.snowflake.snowflake_epoc,
node_id_bits,
datacenter_id_bits,
attr.snowflake.sequence_bits,
attr.delta_offset
)
snowflake_inited = true
end
end
-- generate snowflake id
local function next_id()
if snowflake_inited == nil then
snowflake_init()
end
return snowflake:next_id()
end
local function get_request_id(algorithm)
if algorithm == "uuid" then
return uuid()
end
return next_id()
end
function _M.rewrite(conf, ctx)
local headers = ngx.req.get_headers()
local uuid_val
if not headers[conf.header_name] then
uuid_val = get_request_id(conf.algorithm)
core.request.set_header(ctx, conf.header_name, uuid_val)
else
uuid_val = headers[conf.header_name]
end
if conf.include_in_response then
ctx["request-id-" .. conf.header_name] = uuid_val
end
end
function _M.header_filter(conf, ctx)
if not conf.include_in_response then
return
end
local headers = ngx.resp.get_headers()
if not headers[conf.header_name] then
core.response.set_header(conf.header_name, ctx["request-id-" .. conf.header_name])
end
end
function _M.init()
local local_conf = core.config.local_conf()
attr = core.table.try_read_attr(local_conf, "plugin_attr", plugin_name)
local ok, err = core.schema.check(attr_schema, attr)
if not ok then
core.log.error("failed to check the plugin_attr[", plugin_name, "]", ": ", err)
return
end
if attr.snowflake.enable then
if process.type() == "worker" then
ngx.timer.at(0, snowflake_init)
end
end
end
function _M.destroy()
if snowflake_inited then
timers.unregister_timer("plugin#request-id")
end
end
return _M
|
require 'TEcore'
local player = TEcore.TESprite()
local transform = TEcore.TETransform()
local jump = 0
local velocity = TEcore.vec2()
local mass = 5
local dead = 0
local score = 0
local difficulty = 1.0
function begin()
player:init("res/textures/T_Bird.png")
transform.position.x = -500
generateMap(250)
end
function tick(deltaTime)
transform.position.y = transform.position.y + (velocity.y * deltaTime)
if jump == 1 then
velocity.y = 750
jump = 0
else
velocity.y = velocity.y - (9.8 * mass)
end
player:setTransform(transform)
local newPos = TEcore.vec2(transform.position.x, transform.position.y)
newPos.x = newPos.x + 100
newPos.y = newPos.y + 20
if dead == 1 then
transform.rotation = transform.rotation + (7 * deltaTime)
else
score = score + deltaTime
if score % 5 < deltaTime then
difficulty = difficulty + 0.1
end
if tickMap(deltaTime * difficulty, newPos) == 1 then
die()
end
end
if newPos.y < -500 or newPos.y > 500 then
if dead == 0 then
die()
end
end
end
function die()
local dietext = TEcore.TEText()
local scoreDisplay = TEcore.TEText()
local dieT = TEcore.TETransform()
local scoreT = TEcore.TETransform()
dieT.position.x = -155
scoreT.position.x = -155 * 0.5
scoreT.position.y = -50
scoreT.scale.x = 1.25
scoreT.scale.y = 1.25
dieT.scale.x = 2.0
dieT.scale.y = 2.0
local text = TEcore.addNumberToText("Time: ", score)
text = text .. "s"
scoreDisplay:init(scoreT, text)
dietext:init(dieT, "YOU DIED!")
dietext:setColor(TEcore.color(0.8, 0.6, 0.1, 1.0))
scoreDisplay:setColor(TEcore.color(0.8, 0.6, 0.1, 1.0))
diedMap()
dead = 1
end
function key_down(key)
if dead == 0 then
condition = (key == "SPACE") --and (velocity.y < 0)
if condition then
jump = 1
else
jump = 0
end
end
end
-- map
local topPipes = {}
local bottomPipes = {}
local amt = 10
local distance = 500
local pipeColor = TEcore.color(0.8, 0.25, 0.0, 1.0)
function generatePipe(i, y)
local s = TEcore.TEQuad()
local t = TEcore.TETransform()
s:init()
s:setColor(pipeColor)
t.scale.x = 0.2
t.position.x = (i - 1) * distance
t.position.y = y
t.scale.y = 2.0
s:setTransform(t)
return {s, t}
end
function generateMap(leniency)
for i=1,amt do
local random = math.random(-250.0, 350.0)
local offset = random - (leniency + 1000)
table.insert(topPipes, generatePipe(i, random))
table.insert(bottomPipes, generatePipe(i, offset))
end
end
function tickMap(deltaTime, playerPos)
highest = -99999
for p in ipairs(topPipes) do
local t1 = topPipes[p][2]
if t1.position.x > highest then
highest = t1.position.x
end
end
for p in ipairs(topPipes) do
local s1 = topPipes[p][1]
local s2 = bottomPipes[p][1]
local t1 = topPipes[p][2]
local t2 = bottomPipes[p][2]
t1.position.x = t1.position.x - (deltaTime * 200)
t2.position.x = t2.position.x - (deltaTime * 200)
if t1.position.x < -1000 then
t1.position.x = highest + distance
t2.position.x = highest + distance
end
s1:setTransform(t1)
s2:setTransform(t2)
if s1:overlaps(playerPos) or s2:overlaps(playerPos) then
return 1
end
end
return 0
end
function diedMap()
for p in ipairs(topPipes) do
local s1 = topPipes[p][1]
local s2 = bottomPipes[p][1]
s1:setColor(TEcore.color(pipeColor.r, pipeColor.g, pipeColor.b, 0.2))
s2:setColor(TEcore.color(pipeColor.r, pipeColor.g, pipeColor.b, 0.2))
end
end
|
----------------------------------
-- Author : Jean Loup Pecquais
-- Name : Remove items and time selection
----------------------------------
function main()
local starttime, endtime = reaper.GetSet_LoopTimeRange2(0, false, false, 0, 0, false)
reaper.Undo_BeginBlock()
local context = reaper.GetCursorContext2( true )
if context == 1 or context == 2 then
if starttime ~= endtime then
reaper.SetEditCurPos(starttime, true, false)
reaper.Main_OnCommandEx(40311, 0, 0)--Ripple edit on
reaper.Main_OnCommandEx(40201, 0, 0)--Remove content from time selection
reaper.Main_OnCommandEx(40309, 0, 0)--Remove edit off
reaper.Undo_EndBlock("Remove items", -1)
else
reaper.Main_OnCommandEx(40310, 0, 0)--Ripple per track edit on
reaper.Main_OnCommandEx(40006, 0, 0)--Remove item
reaper.Main_OnCommandEx(40309, 0, 0)--Remove edit off
reaper.Undo_EndBlock("Remove item", -1)
end
end
end
main()
|
local lib={}
lib.internal={}
local function checkArg(n, have, ...)
have = type(have)
local function check(want, ...)
if not want then
return false
else
return have == want or check(...)
end
end
if not check(...) then
local msg = string.format("bad argument #%d (%s expected, got %s)",
n, table.concat({...}, " or "), have)
error(msg, 3)
end
end
function lib.internal.range_adjust(f,l,s)
checkArg(1,f,'number','nil')
checkArg(2,l,'number','nil')
checkArg(3,s,'number')
if f==nil then f=1 elseif f<0 then f=s+f+1 end
if l==nil then l=s elseif l<0 then l=s+l+1 end
return f,l
end
function lib.internal.table_view(tbl,f,l)
return setmetatable({},
{
__index = function(_, key)
return (type(key) ~= 'number' or (key >= f and key <= l)) and tbl[key] or nil
end,
__len = function(_)
return l
end,
})
end
local adjust=lib.internal.range_adjust
local view=lib.internal.table_view
-- first(p1,p2) searches for the first range in p1 that satisfies p2
function lib.first(tbl,pred,f,l)
checkArg(1,tbl,'table')
checkArg(2,pred,'function','table')
if type(pred)=='table'then
local set;set,pred=pred,function(_,fi,tbl)
for vi=1,#set do
local v=set[vi]
if lib.begins(tbl,v,fi) then return true,#v end
end
end
end
local s=#tbl
f,l=adjust(f,l,s)
tbl=view(tbl,f,l)
for i=f,l do
local si,ei=pred(tbl[i],i,tbl)
if si then
return i,i+(ei or 1)-1
end
end
end
-- returns true if p1 at first p3 equals element for element p2
function lib.begins(tbl,v,f,l)
checkArg(1,tbl,'table')
checkArg(2,v,'table')
local vs=#v
f,l=adjust(f,l,#tbl)
if vs>(l-f+1)then return end
for i=1,vs do
if tbl[f+i-1]~=v[i] then return end
end
return true
end
function lib.concat(...)
local r,rn,k={},0
for _,tbl in ipairs({...})do
if type(tbl)~='table'then
return nil,'parameter '..tostring(_)..' to concat is not a table'
end
local n=tbl.n or #tbl
k=k or tbl.n
for i=1,n do
rn=rn+1;r[rn]=tbl[i]
end
end
r.n=k and rn or nil
return r
end
-- works like string.sub but on elements of an indexed table
function lib.sub(tbl,f,l)
checkArg(1,tbl,'table')
local r,s={},#tbl
f,l=adjust(f,l,s)
l=math.min(l,s)
for i=math.max(f,1),l do
r[#r+1]=tbl[i]
end
return r
end
-- Returns a list of subsets of tbl where partitioner acts as a delimiter.
function lib.partition(tbl,partitioner,dropEnds,f,l)
checkArg(1,tbl,'table')
checkArg(2,partitioner,'function','table')
checkArg(3,dropEnds,'boolean','nil')
if type(partitioner)=='table'then
return lib.partition(tbl,function(_,i,tbl)
return lib.first(tbl,partitioner,i)
end,dropEnds,f,l)
end
local s=#tbl
f,l=adjust(f,l,s)
local cut=view(tbl,f,l)
local result={}
local need=true
local exp=function()if need then result[#result+1]={}need=false end end
local i=f
while i<=l do
local e=cut[i]
local ds,de=partitioner(e,i,cut)
-- true==partition here
if ds==true then ds,de=i,i
elseif ds==false then ds,de=nil,nil end
if ds~=nil then
ds,de=adjust(ds,de,l)
ds=ds>=i and ds--no more
end
if not ds then -- false or nil
exp()
table.insert(result[#result],e)
else
local sub=lib.sub(cut,i,not dropEnds and de or (ds-1))
if #sub>0 then
exp()
result[#result+math.min(#result[#result],1)]=sub
end
-- ensure i moves forward
local ensured=math.max(math.max(de or ds,ds),i)
if de and ds and de<ds and ensured==i then
if #result==0 then result[1]={} end
table.insert(result[#result],e)
end
i=ensured
need=true
end
i=i+1
end
return result
end
-- calls callback(e,i,tbl) for each ith element e in table tbl from first
function lib.foreach(tbl,c,f,l)
checkArg(1,tbl,'table')
checkArg(2,c,'function','string')
local ck=c
c=type(c)=="string" and function(e) return e[ck] end or c
local s=#tbl
f,l=adjust(f,l,s)
tbl=view(tbl,f,l)
local r={}
for i=f,l do
local n,k=c(tbl[i],i,tbl)
if n~=nil then
if k then r[k]=n
else r[#r+1]=n end
end
end
return r
end
function lib.where(tbl,p,f,l)
return lib.foreach(tbl,
function(e,i,tbl)
return p(e,i,tbl)and e or nil
end,f,l)
end
-- works with pairs on tables
-- returns the kv pair, or nil and the number of pairs iterated
function lib.at(tbl, index)
checkArg(1, tbl, "table")
checkArg(2, index, "number", "nil")
local current_index = 1
for k,v in pairs(tbl) do
if current_index == index then
return k,v
end
current_index = current_index + 1
end
return nil, current_index - 1 -- went one too far
end
return lib |
object_draft_schematic_weapon_lightsaber_one_handed_gen2 = object_draft_schematic_weapon_shared_lightsaber_one_handed_gen2:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_weapon_lightsaber_one_handed_gen2, "object/draft_schematic/weapon/lightsaber_one_handed_gen2.iff")
|
if modifier_custom_counter_helix_aura_applier == nil then
modifier_custom_counter_helix_aura_applier = class({})
end
function modifier_custom_counter_helix_aura_applier:IsHidden()
return true
end
function modifier_custom_counter_helix_aura_applier:IsPurgable()
return false
end
function modifier_custom_counter_helix_aura_applier:IsAura()
return true
end
function modifier_custom_counter_helix_aura_applier:AllowIllusionDuplicate()
return true
end
function modifier_custom_counter_helix_aura_applier:GetAttributes()
return MODIFIER_ATTRIBUTE_PERMANENT
end
function modifier_custom_counter_helix_aura_applier:GetModifierAura()
return "modifier_custom_counter_helix_aura_effect"
end
function modifier_custom_counter_helix_aura_applier:GetAuraRadius()
local ability = self:GetAbility()
return ability:GetSpecialValueFor("trigger_radius")
end
function modifier_custom_counter_helix_aura_applier:GetAuraSearchTeam()
return DOTA_UNIT_TARGET_TEAM_ENEMY
end
function modifier_custom_counter_helix_aura_applier:GetAuraSearchType()
return bit.bor(DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_BASIC)
end
function modifier_custom_counter_helix_aura_applier:GetAuraSearchFlags()
return DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES
end
|
-- Copyright (C) Jinzheng Zhang (tianchaijz).
-- Ported from Redis skiplist C implementation.
local math = require "math"
local setmetatable = setmetatable
local random = math.random
local table_new
do
local ok
ok, table_new = pcall(require, "table.new")
if not ok then
table_new = function(narr, nrec) return {} end
end
end
local _skiplist_max_level = 32
local _skiplist_p = 0.25
local _M = {}
local _mt = { __index = _M }
local function lt_in(lhs, rhs, inclusive)
if inclusive then
return lhs <= rhs
end
return lhs < rhs
end
local function lt_ex(lhs, rhs, exclusive)
if exclusive then
return lhs < rhs
end
return lhs <= rhs
end
-- higher levels are less likely to be returned.
local function random_level()
local level = 1
while random() < _skiplist_p do
level = level + 1
end
return level <= _skiplist_max_level and level or _skiplist_max_level
end
--[[
struct skiplist_node_level_s {
skiplist_node_t *forward;
int span;
};
struct skiplist_node_s {
void *obj;
double score;
skiplist_node_t *backward;
skiplist_node_level_t *level;
};
struct skiplist_s {
skiplist_node_t *header;
skiplist_node_t *tail;
int level;
int length;
};
]]
local function new_node(level, score, value)
local lvl = table_new(level, 0)
for i = 1, level do
lvl[i] = { forward = nil, span = 0 }
end
local node = {
value = value,
score = score,
backward = nil,
level = lvl,
}
return node
end
function _M.new()
local sl = {
header = new_node(_skiplist_max_level, 0, nil),
tail = nil,
level = 1,
length = 0,
}
local self = {
_sl = sl,
_rank = table_new(_skiplist_max_level, 0),
_update = table_new(_skiplist_max_level, 0),
}
return setmetatable(self, _mt)
end
function _M.len(self)
return self._sl.length
end
local function insert(self, score, value)
local sl = self._sl
local rank = self._rank
local update = self._update
local x = sl.header
local l = sl.level
for i = l, 1, -1 do
-- store rank that is crossed to reach the insert position
rank[i] = i == l and 0 or rank[i + 1]
local y = x.level[i]
local z = y.forward
while z and (z.score < score or
(z.score == score and z.value < value)) do
rank[i] = rank[i] + y.span
x = z
y = x.level[i]
z = y.forward
end
update[i] = x
end
local level = random_level()
if level > sl.level then
for i = sl.level + 1, level do
rank[i] = 0
update[i] = sl.header
update[i].level[i].span = sl.length
end
sl.level = level
end
x = new_node(level, score, value)
for i = 1, level do
local y = x.level[i]
local z = update[i].level[i]
y.forward = z.forward
z.forward = x
-- update span covered by update[i] as x is inserted here
local span = rank[1] - rank[i]
y.span = z.span - span
z.span = span + 1
end
-- increment span for untouched levels
for i = level + 1, sl.level do
local y = update[i].level[i]
y.span = y.span + 1
end
if update[1] == sl.header then
x.backward = nil
else
x.backward = update[1]
end
local y = x.level[1].forward
if y then
y.backward = x
else
sl.tail = x
end
sl.length = sl.length + 1
return x
end
_M.insert = insert
local function delete_node(sl, x, update)
for i = 1, sl.level do
local y = x.level[i]
local z = update[i].level[i]
if z.forward == x then
z.span = z.span + y.span - 1
z.forward = y.forward
else
z.span = z.span - 1
end
end
local y = x.level[1]
if y.forward then
y.forward.backward = x.backward
else
sl.tail = x.backward
end
local lvl = sl.header.level
while sl.level > 1 and not lvl[sl.level].forward do
lvl[sl.level].span = 0
sl.level = sl.level - 1
end
sl.length = sl.length - 1
end
function _M.update(self, curscore, value, newscore)
local sl = self._sl
local update = self._update
local x = sl.header
for i = sl.level, 1, -1 do
local y = x.level[i].forward
while y and (y.score < curscore or
(y.score == curscore and y.value < value)) do
x = y
y = x.level[i].forward
end
update[i] = x
end
-- jump to our object: note that this function assumes that the
-- object with the matching score exists
x = x.level[1].forward
if (not x.backward or x.backward.score < newscore) and
(not x.level[1].forward or
x.level[1].forward.score > newscore) then
x.score = newscore
return x
end
-- no way to resuse the old one
delete_node(sl, x, update)
return insert(self, newscore, value)
end
local function delete(self, score, value)
local sl = self._sl
local update = self._update
local x = sl.header
for i = sl.level, 1, -1 do
local y = x.level[i].forward
while y and (y.score < score or
(y.score == score and y.value < value)) do
x = y
y = x.level[i].forward
end
update[i] = x
end
x = x.level[1].forward
if x and x.value == value then
delete_node(sl, x, update)
return true
end
return false
end
_M.delete = delete
-- delete [s, e], note that s and e need to be 1-based.
function _M.delete_range_by_rank(self, s, e, cb)
local sl = self._sl
local update = self._update
if s > sl.length or e < 1 then
return 0
end
local removed = 0
local traversed = 0
local x = sl.header
for i = sl.level, 1, -1 do
local y = x.level[i]
while y.forward and (traversed + y.span < s) do
traversed = traversed + y.span
x = y.forward
y = x.level[i]
end
update[i] = x
end
traversed = traversed + 1
x = x.level[1].forward
while x and traversed <= e do
local y = x.level[1].forward
cb(x)
delete_node(sl, x, update)
removed = removed + 1
traversed = traversed + 1
x = y
end
return removed
end
function _M.delete_range_by_score(self, minscore, minex, maxscore, maxex, cb)
local sl = self._sl
local update = self._update
local removed = 0
local x = sl.header
for i = sl.level, 1, -1 do
local y = x.level[i].forward
while y and lt_in(y.score, minscore, minex) do
x = y
y = x.level[i].forward
end
update[i] = x
end
x = x.level[1].forward
while x and lt_ex(x.score, maxscore, maxex) do
local y = x.level[1].forward
cb(x)
delete_node(sl, x, update)
removed = removed + 1
x = y
end
return removed
end
function _M.head(self)
local x = self._sl.header
x = x.level[1].forward
if x then
return x.value, x.score
end
end
function _M.tail(self)
local x = self._sl.tail
if x then
return x.value, x.score
end
end
function _M.pop_head(self)
local x = self._sl.header
x = x.level[1].forward
if x then
local v = x.value
local score = x.score
delete(self, score, v)
return v, score
end
end
function _M.pop_tail(self)
local x = self._sl.tail
if x then
local v = x.value
local score = x.score
delete(self, score, v)
return v, score
end
end
function _M.get_node_by_rank(self, rank)
local sl = self._sl
if rank < 1 or rank > sl.length then
return
end
local traversed = 0
local x = sl.header
for i = sl.level, 1, -1 do
local y = x.level[i]
while y.forward and (traversed + y.span <= rank) do
traversed = traversed + y.span
x = y.forward
y = x.level[i]
end
if traversed == rank then
return x
end
end
end
function _M.get_rank(self, score, value)
local sl = self._sl
local rank = 0
local x = sl.header
for i = sl.level, 1, -1 do
local y = x.level[i]
local z = y.forward
while z and (z.score < score or
(z.score == score and z.value <= value)) do
rank = rank + y.span
x = z
y = x.level[i]
z = y.forward
end
if x.value == value then
return rank
end
end
return 0
end
-- return the 0-based rank of given score.
function _M.get_score_rank(self, score, ex)
local sl = self._sl
local rank = 0
local x = sl.header
for i = sl.level, 1, -1 do
local y = x.level[i]
local z = y.forward
while z and lt_ex(z.score, score, ex) do
rank = rank + y.span
x = z
y = x.level[i]
z = y.forward
end
end
return rank
end
local function is_in_range(self, minscore, minex, maxscore, maxex)
if minscore > maxscore or (minscore == maxscore and (minex or maxex)) then
return false
end
local sl = self._sl
local x = sl.tail
if not x or lt_in(x.score, minscore, minex) then
return false
end
x = sl.header.level[1].forward
if not x or lt_in(maxscore, x.score, maxex) then
return false
end
return true
end
_M.is_in_range = is_in_range
function _M.first_in_range(self, minscore, minex, maxscore, maxex)
if not is_in_range(self, minscore, minex, maxscore, maxex) then
return
end
local sl = self._sl
local x = sl.header
for i = sl.level, 1, -1 do
local y = x.level[i].forward
while y and lt_in(y.score, minscore, minex) do
x = y
y = x.level[i].forward
end
end
-- this is an inner range, so the next node cannot be nil
x = x.level[1].forward
if lt_ex(x.score, maxscore, maxex) then
return x
end
end
function _M.last_in_range(self, minscore, minex, maxscore, maxex)
if not is_in_range(self, minscore, minex, maxscore, maxex) then
return
end
local sl = self._sl
local x = sl.header
for i = sl.level, 1, -1 do
local y = x.level[i].forward
while y and lt_ex(y.score, maxscore, maxex) do
x = y
y = x.level[i].forward
end
end
if lt_ex(minscore, x.score, minex) then
return x
end
end
function _M.iterate(self, cb)
local rank = 0
local x = self._sl.header
x = x.level[1].forward
while x do
rank = rank + 1
cb(x, rank)
x = x.level[1].forward
end
end
_M.lt_in = lt_in
_M.table_new = table_new
return _M
|
test = require 'u-test'
common = require 'common'
function GetUserProfilesForSocialGroupAsync_Handler()
print("GetUserProfilesForSocialGroupAsync_Handler")
XblProfileGetUserProfilesForSocialGroupAsync()
end
function OnXblProfileGetUserProfilesForSocialGroupAsync()
print("OnXblProfileGetUserProfilesForSocialGroupAsyncRetry")
XblProfileGetUserProfilesForSocialGroupAsync()
end
function OnXblProfileGetUserProfilesForSocialGroupAsync()
print("OnXblProfileGetUserProfilesForSocialGroupAsync")
test.stopTest();
end
test.GetUserProfilesForSocialGroupAsync = function()
common.init(GetUserProfilesForSocialGroupAsync_Handler)
end
|
network = {
{name = "grauna", IP = "210.26.30.34"},
{name = "arraial", IP = "210.26.30.23"},
{name = "lua", IP = "210.26.23.12"},
{name = "derain", IP = "210.26.23.20"}
}
table.sort(
network,
function(a, b)
return (a.name > b.name)
end
)
for i, item in ipairs(network) do
print("i:", i)
print("type:", type(item))
print(item.name, item.IP)
print()
end
|
local KUI, E, L, V, P, G = unpack(select(2, ...))
local S = E:GetModule("Skins")
--Cache global variables
--Lua functions
local _G = _G
--WoW API / Variables
--Global variables that we don't cache, list them here for the mikk's Find Globals script
-- GLOBALS:
local function styleTradeSkill()
if E.private.skins.blizzard.enable ~= true or E.private.skins.blizzard.tradeskill ~= true or E.private.KlixUI.skins.blizzard.tradeskill ~= true then return; end
-- MainFrame
_G["TradeSkillFrame"]:Styling()
if _G["TradeSkillFrame"].bg1 then
_G["TradeSkillFrame"].bg1:Hide()
end
if _G["TradeSkillFrame"].bg2 then
_G["TradeSkillFrame"].bg2:Hide()
end
end
S:AddCallbackForAddon("Blizzard_TradeSkillUI", "KuiTradeSkill", styleTradeSkill) |
--[[co = coroutine.create(function ()
print("hi")
end)
print(coroutine.status(co))
print(coroutine.resume(co))
print(coroutine.status(co))
print(co)
--]]
--[[co = coroutline.create(function ()
for i = 1,10 do
print("co",i)
coroutine.yield()
end
end
)
coroutine.resume(co)
print(coroutine.status(co))
--]]
--[[co = coroutine.create(
function (a,b,c)
print("co",a,b,c)
end
)
print(coroutine.resume(co,1,2,3))
--]]
--[[co = coroutine.create(
function (a,b)
coroutine.yield(a + b,a - b)
end
)
print(coroutine.resume(co,20,10))
--]]
--[[co = coroutine.create(
function ()
print("co",coroutine.yield())
end
)
coroutine.resume(co)
coroutine.resume(co,4,5)
--]]
--[[co = coroutine.create(
function ()
return 6,7
end
)
print(coroutine.resume(co))
function producer()
while true do
local x = io.read()
send(x)
end
end
function consumer()
while true do
local x = receive()
io.write(x,"\n")
end
end--]]
--[[function receive()
local status,value = coroutine.resume(producer)
return value
end
function send(x)
coroutine.yield(x)
end
producer = coroutine.create(
function ()
while true do
local x = io.read()
send(x)
end
end
)
--]]
--[[function receive(prod)
local status,value = coroutine.resume(prod)
return value
end
function send(x)
coroutine.yield(x)
end
function producer()
return coroutine.create(
function()
while true do
local x = io.read()
send(x)
end
end
)
end
function filter(prod)
return coroutine.create(
function()
local line = 1
while true do
local x = receive(prod)
x = string.format("%5d %s",line,x)
sned(x)
line = line + 1
end
end
)
end
function consumer (prod)
while true do
local x = receive(prod)
io.write(x,"\n")
end
end
p = producer()
f = filter(p)
consumer(f)
--]]
--[[function permgen (a,n)
if n == 0 then
printResult(a)
else
for i = 1,n do
a[n],a[i] = a[i],a[n]
permgen(a,n - 1)
a[n],a[i] = a[i],a[n]
end
end
end
function printResult (a)
for i,v in ipairs(a) do
io.write(v," ")
end
io.write("\n")
end
permgen({1,2,3,4},4)
--]]
--[[require "luasocket"
host = "www.w3.org"
file = "/TR/REC-html32.html"
c = assert(socket.connect(host, 80))
c:send("GET " .. file .. " HTTP/1.0\r\n\r\n")
c:close()
--]]
function fwrite (fmt, ...)
return io.write(string.format(fmt,unpack(arg)))
end |
---
-- @module RxLinkUtils
-- @author Quenty
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local Rx = require("Rx")
local RxInstanceUtils = require("RxInstanceUtils")
local Observable = require("Observable")
local Maid = require("Maid")
local Brio = require("Brio")
local RxBrioUtils = require("RxBrioUtils")
local RxLinkUtils = {}
-- Emits valid links in format Brio.new(link, linkValue)
function RxLinkUtils.observeValidLinksBrio(linkName, parent)
assert(type(linkName) == "string", "Bad linkName")
assert(typeof(parent) == "Instance", "Bad parent")
return RxInstanceUtils.observeChildrenBrio(parent)
:Pipe({
Rx.flatMap(function(brio)
local instance = brio:GetValue()
if not instance:IsA("ObjectValue") then
return Rx.EMPTY
end
return RxBrioUtils.completeOnDeath(brio, RxLinkUtils.observeValidityBrio(linkName, instance))
end);
})
end
-- Fires off everytime the link is reconfigured into a valid link
-- Fires with link, linkValue
function RxLinkUtils.observeValidityBrio(linkName, link)
assert(typeof(link) == "Instance" and link:IsA("ObjectValue"))
assert(type(linkName) == "string")
return Observable.new(function(sub)
local maid = Maid.new()
local function updateValidity()
if not ((link.Name == linkName) and link.Value) then
maid._lastValid = nil
return
end
local newValid = Brio.new(link, link.Value)
maid._lastValid = newValid
sub:Fire(newValid)
end
maid:GiveTask(link:GetPropertyChangedSignal("Value")
:Connect(updateValidity))
maid:GiveTask(link:GetPropertyChangedSignal("Name")
:Connect(updateValidity))
updateValidity()
return maid
end)
end
return RxLinkUtils |
print("Hello World from Lua file!")
print(1 +1)
|
#!/usr/bin/env tarantool
local fio = require('fio')
local yaml = require('yaml')
local avro = require('avro_schema')
local tap = require('tap')
-- require in-repo version of graphql/ sources despite current working directory
local cur_dir = fio.abspath(debug.getinfo(1).source:match("@?(.*/)")
:gsub('/./', '/'):gsub('/+$', ''))
package.path =
cur_dir .. '/../../?/init.lua' .. ';' ..
cur_dir .. '/../../?.lua' .. ';' ..
package.path
local utils = require('graphql.utils')
local graphql = require('graphql')
local test_utils = require('test.test_utils')
local testdata = require('test.testdata.scalar_testdata')
local cases = {
{
'verify boolean',
query = [[
{
foo(id: 1) {
boolean_field
}
}
]],
exp_avro_schema = [[
---
type: record
name: Query
fields:
- name: foo
type:
type: array
items:
type: record
name: foo
namespace: Query
fields:
- name: boolean_field
type: boolean
]],
exp_result = [[
---
foo:
- boolean_field: true
]],
},
{
'verify int',
query = [[
{
foo(id: 1) {
int_field
}
}
]],
exp_avro_schema = [[
---
type: record
name: Query
fields:
- name: foo
type:
type: array
items:
type: record
name: foo
namespace: Query
fields:
- name: int_field
type: int
]],
exp_result = [[
---
foo:
- int_field: 1
]],
},
{
'verify long',
query = [[
{
foo(id: 1) {
long_field
}
}
]],
exp_avro_schema = [[
---
type: record
name: Query
fields:
- name: foo
type:
type: array
items:
type: record
name: foo
namespace: Query
fields:
- name: long_field
type: long
]],
exp_result = [[
---
foo:
- long_field: 1
]],
},
{
'verify float',
query = [[
{
foo(id: 1) {
float_field
}
}
]],
-- Note: GraphQL Float is double precision, so we convert is back as
-- avro-schema double.
-- http://graphql.org/learn/schema/#scalar-types
exp_avro_schema = [[
---
type: record
name: Query
fields:
- name: foo
type:
type: array
items:
type: record
name: foo
namespace: Query
fields:
- name: float_field
type: double
]],
exp_result = [[
---
foo:
- float_field: 1.0
]],
},
{
'verify double',
query = [[
{
foo(id: 1) {
double_field
}
}
]],
exp_avro_schema = [[
---
type: record
name: Query
fields:
- name: foo
type:
type: array
items:
type: record
name: foo
namespace: Query
fields:
- name: double_field
type: double
]],
exp_result = [[
---
foo:
- double_field: 1.0
]],
},
{
'verify string',
query = [[
{
foo(id: 1) {
string_field
}
}
]],
exp_avro_schema = [[
---
type: record
name: Query
fields:
- name: foo
type:
type: array
items:
type: record
name: foo
namespace: Query
fields:
- name: string_field
type: string
]],
exp_result = [[
---
foo:
- string_field: one
]],
},
}
local test = tap.test('convert graphql scalars to avro-schema')
test:plan(#cases)
-- Prepare data and create a graphql instance.
local meta = testdata.get_test_metadata()
box.cfg{}
testdata.init_spaces()
testdata.fill_test_data(box.space, meta)
local gql_wrapper = graphql.new(utils.merge_tables({
schemas = meta.schemas,
collections = meta.collections,
indexes = meta.indexes,
service_fields = meta.service_fields,
accessor = 'space',
}, test_utils.test_conf_graphql_opts()))
-- Run cases.
for _, case in ipairs(cases) do
test:test(case[1], function(test)
test:plan(4)
local gql_query = gql_wrapper:compile(case.query)
local avro_schema = gql_query:avro_schema()
local exp_avro_schema = yaml.decode(case.exp_avro_schema:strip())
test:is_deeply(avro_schema, exp_avro_schema,
'verify generated avro schema')
local result = gql_query:execute(case.variables or {})
local exp_result = yaml.decode(case.exp_result:strip())
test:is_deeply(result.data, exp_result, 'verify query result')
local ok, handle = avro.create(avro_schema)
assert(ok, 'create avro-schema handle')
local ok = avro.validate(handle, result.data)
test:ok(ok, 'verify query result against avro-schema')
local ok, model = avro.compile(handle)
assert(ok, 'compile avro-schema')
local ok, tuple = model.flatten(result.data)
assert(ok, 'flatten query result')
local ok, object = model.unflatten(tuple)
assert(ok, 'unflatten flattened query result')
test:is_deeply(object, exp_result,
'verify flatten-unflatten gives the same result')
end)
end
testdata.drop_spaces()
os.exit(test:check() == true and 0 or 1)
|
gg_trg_Melee_Initialization = nil
gg_unit_E000_0003 = nil
gg_unit_Hblm_0002 = nil
function InitGlobals()
end
function CreateUnitsForPlayer0()
local p = Player(0)
local u
local unitID
local t
local life
gg_unit_Hblm_0002 = BlzCreateUnitWithSkin(p, FourCC("Hblm"), 1.1, -10.7, 0.846, FourCC("Hblm"))
gg_unit_E000_0003 = BlzCreateUnitWithSkin(p, FourCC("E000"), 166.1, -61.6, 276.575, FourCC("E000"))
end
function CreateNeutralHostile()
local p = Player(PLAYER_NEUTRAL_AGGRESSIVE)
local u
local unitID
local t
local life
u = BlzCreateUnitWithSkin(p, FourCC("h000"), -111.2, 653.1, 247.508, FourCC("h000"))
u = BlzCreateUnitWithSkin(p, FourCC("h000"), -50.9, 790.1, 270.437, FourCC("h000"))
u = BlzCreateUnitWithSkin(p, FourCC("h000"), 58.3, 671.5, 102.088, FourCC("h000"))
u = BlzCreateUnitWithSkin(p, FourCC("h000"), 443.5, 681.1, 237.593, FourCC("h000"))
u = BlzCreateUnitWithSkin(p, FourCC("h000"), 661.4, 632.9, 276.189, FourCC("h000"))
u = BlzCreateUnitWithSkin(p, FourCC("h000"), 789.7, 395.9, 207.050, FourCC("h000"))
u = BlzCreateUnitWithSkin(p, FourCC("h001"), -151.3, -654.9, 329.391, FourCC("h001"))
life = GetUnitState(u, UNIT_STATE_LIFE)
SetUnitState(u, UNIT_STATE_LIFE, 0.01 * life)
u = BlzCreateUnitWithSkin(p, FourCC("h001"), -39.3, -778.6, 351.288, FourCC("h001"))
life = GetUnitState(u, UNIT_STATE_LIFE)
SetUnitState(u, UNIT_STATE_LIFE, 0.01 * life)
u = BlzCreateUnitWithSkin(p, FourCC("h001"), 103.4, -683.4, 258.780, FourCC("h001"))
life = GetUnitState(u, UNIT_STATE_LIFE)
SetUnitState(u, UNIT_STATE_LIFE, 0.01 * life)
u = BlzCreateUnitWithSkin(p, FourCC("h001"), 392.7, -729.1, 209.988, FourCC("h001"))
life = GetUnitState(u, UNIT_STATE_LIFE)
SetUnitState(u, UNIT_STATE_LIFE, 0.01 * life)
end
function CreatePlayerBuildings()
end
function CreatePlayerUnits()
CreateUnitsForPlayer0()
end
function CreateAllUnits()
CreatePlayerBuildings()
CreateNeutralHostile()
CreatePlayerUnits()
end
function Trig_Melee_Initialization_Actions()
MeleeStartingVisibility()
MeleeStartingAI()
SetUnitColor(gg_unit_E000_0003, PLAYER_COLOR_RED)
SetUnitColor(gg_unit_Hblm_0002, PLAYER_COLOR_RED)
end
function InitTrig_Melee_Initialization()
gg_trg_Melee_Initialization = CreateTrigger()
TriggerAddAction(gg_trg_Melee_Initialization, Trig_Melee_Initialization_Actions)
end
function InitCustomTriggers()
InitTrig_Melee_Initialization()
end
function RunInitializationTriggers()
ConditionalTriggerExecute(gg_trg_Melee_Initialization)
end
function InitCustomPlayerSlots()
SetPlayerStartLocation(Player(0), 0)
SetPlayerColor(Player(0), ConvertPlayerColor(0))
SetPlayerRacePreference(Player(0), RACE_PREF_HUMAN)
SetPlayerRaceSelectable(Player(0), true)
SetPlayerController(Player(0), MAP_CONTROL_USER)
end
function InitCustomTeams()
SetPlayerTeam(Player(0), 0)
end
function main()
SetCameraBounds(-3328.0 + GetCameraMargin(CAMERA_MARGIN_LEFT), -3584.0 + GetCameraMargin(CAMERA_MARGIN_BOTTOM), 3328.0 - GetCameraMargin(CAMERA_MARGIN_RIGHT), 3072.0 - GetCameraMargin(CAMERA_MARGIN_TOP), -3328.0 + GetCameraMargin(CAMERA_MARGIN_LEFT), 3072.0 - GetCameraMargin(CAMERA_MARGIN_TOP), 3328.0 - GetCameraMargin(CAMERA_MARGIN_RIGHT), -3584.0 + GetCameraMargin(CAMERA_MARGIN_BOTTOM))
SetDayNightModels("Environment\\DNC\\DNCLordaeron\\DNCLordaeronTerrain\\DNCLordaeronTerrain.mdl", "Environment\\DNC\\DNCLordaeron\\DNCLordaeronUnit\\DNCLordaeronUnit.mdl")
NewSoundEnvironment("Default")
SetAmbientDaySound("LordaeronSummerDay")
SetAmbientNightSound("LordaeronSummerNight")
SetMapMusic("Music", true, 0)
CreateAllUnits()
InitBlizzard()
InitGlobals()
InitCustomTriggers()
RunInitializationTriggers()
end
function config()
SetMapName("TRIGSTR_007")
SetMapDescription("TRIGSTR_009")
SetPlayers(1)
SetTeams(1)
SetGamePlacement(MAP_PLACEMENT_USE_MAP_SETTINGS)
DefineStartLocation(0, 192.0, -64.0)
InitCustomPlayerSlots()
SetPlayerSlotAvailable(Player(0), MAP_CONTROL_USER)
InitGenericPlayerSlots()
end
|
ConsumableItem = CustomItem:extend()
ConsumableItem:set {
FullIcon = ImageReference:FromPackRelativePath("images/0058.png"),
EmptyIcon = ImageReference:FromPackRelativePath("images/0059.png"),
MaxCount = {
value = 0x7fffffff,
afterSet = function(self)
self.AcquiredCount = self.AcquiredCount
self.ConsumedCount = self.ConsumedCount
self:UpdateBadgeAndIcon()
end
},
MinCount = {
value = 0,
afterSet = function(self)
self.AcquiredCount = self.AcquiredCount
self.ConsumedCount = self.ConsumedCount
self:UpdateBadgeAndIcon()
end
},
AcquiredCount = {
value = 0x7fffffff,
set = function(self, value) return math.min(math.max(math.max(value, self.ConsumedCount), self.MinCount), self.MaxCount) end,
afterSet = function(self)
self:UpdateBadgeAndIcon()
self:InvalidateAccessibility()
end
},
ConsumedCount = {
value = 0,
set = function(self, value) return math.max(math.min(value, self.AvailableCount), 0) end,
afterSet = function(self)
self:UpdateBadgeAndIcon()
self:InvalidateAccessibility()
end
},
AvailableCount = {
get = function(self) return self.AcquiredCount - self.ConsumedCount end
},
DisplayFractionOfMax = {
value = false,
afterSet = function(self) self:UpdateBadgeAndIcon() end
},
CountIncrement = 1,
SwapActions = false
}
function ConsumableItem:init(name, code, maxqty, img, disabledImg, imgMods, disabledImgMods)
maxqty = maxqty or self.MaxCount
self:createItem(name)
self.code = code
self.MaxCount = maxqty
if img then
self.FullIcon = ImageReference:FromPackRelativePath(img, imgMods or "")
end
if disabledImg then
self.EmptyIcon = ImageReference:FromPackRelativePath(disabledImg, disabledImgMods or "")
end
end
function ConsumableItem:UpdateBadgeAndIcon()
if self.AvailableCount == 0 then
self.ItemInstance.Icon = self.AcquiredCount > 0 and self.FullIcon or self.EmptyIcon
self.ItemInstance.BadgeText = nil
else
self.ItemInstance.Icon = self.FullIcon
if not self.DisplayAsFractionOfMax then
self.ItemInstance.BadgeText = tostring(math.floor(self.AvailableCount))
else
self.ItemInstance.BadgeText = tostring(math.floor(self.AvailableCount)) .. "/" .. tostring(math.floor(self.MaxCount))
end
end
if self.AcquiredCount >= self.MaxCount then
self.ItemInstance.BadgeTextColor = "#00ff00"
else
self.ItemInstance.BadgeTextColor = "WhiteSmoke"
end
end
function ConsumableItem:InvalidateAccessibility()
self.ItemInstance:InvalidateAccessibility()
end
function ConsumableItem:Increment(count)
count = count or 1
local num = math.min(self.MaxCount, math.max(self.MinCount, self.AcquiredCount + (self.CountIncrement * count)))
self.AcquiredCount = num
return num
end
function ConsumableItem:Decrement(count)
count = count or 1
local num = math.min(self.MaxCount, math.max(self.MinCount, self.AcquiredCount - (self.CountIncrement * count)))
self.AcquiredCount = num
return num
end
function ConsumableItem:Consume(quantity)
quantity = quantity or 1
if self.AvailableCount < quantity then
return false
end
self.ConsumedCount = self.ConsumedCount + quantity
return true
end
function ConsumableItem:Release(quantity)
quantity = quantity or 1
if self.ConsumedCount < quantity then
return false
end
self.ConsumedCount = self.ConsumedCount - quantity
return true
end
function ConsumableItem:onLeftClick()
if self.SwapActions then
self:Increment(1)
else
self:Decrement(1)
end
end
function ConsumableItem:onRightClick()
if self.SwapActions then
self:Decrement(1)
else
self:Increment(1)
end
end
function ConsumableItem:canProvideCode(code)
if code == self.code then
return true
else
return false
end
end
function ConsumableItem:providesCode(code)
if code == self.code then
return self.AcquiredCount
end
return 0
end
function ConsumableItem:advanceToCode(code)
if code == nil or code == self.code then
self:OnLeftClick()
end
end
function ConsumableItem:save()
local data = {}
data["min_count"] = self.MinCount
data["max_count"] = self.MaxCount
data["consumed_count"] = self.ConsumedCount
data["acquired_count"] = self.AcquiredCount
return data
end
function ConsumableItem:load(data)
local num = -1
local num2 = -1
if data["acquired_count"] ~= nil then
num = data["acquired_count"]
end
if data["consumed_count"] ~= nil then
num2 = data["consumed_count"]
end
if num < 0 or num2 < 0 then
return false
end
if data["max_count"] ~= nil then
self.MaxCount = data["max_count"]
end
if data["min_count"] ~= nil then
self.MinCount = data["min_count"]
end
self.AcquiredCount = num
self.ConsumedCount = num2
return true
end
|
require "behaviours/follow"
local MIN_FOLLOW_DIST = 2
local TARGET_FOLLOW_DIST = 3
local MAX_FOLLOW_DIST = 8
local function GetFaceTargetFn(inst)
return inst.components.follower and inst.components.follower.leader
end
local function KeepFaceTargetFn(inst, target)
return inst.components.follower and inst.components.follower.leader == target
end
local MandrakeBrain = Class(Brain, function(self, inst)
Brain._ctor(self, inst)
end)
function MandrakeBrain:OnStart()
local root =
PriorityNode({
Follow(self.inst, function() return self.inst.components.follower and self.inst.components.follower.leader end, MIN_FOLLOW_DIST, TARGET_FOLLOW_DIST, MAX_FOLLOW_DIST),
FaceEntity(self.inst, GetFaceTargetFn, KeepFaceTargetFn),
},.25)
self.bt = BT(self.inst, root)
end
return MandrakeBrain |
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:26' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
------------------
-- Guild Finder: Guild Recruitment Manager --
--
-- Manages Guild Recruitment data in lua
------------------
ZO_GuildRecruitment_Manager = ZO_CallbackObject:Subclass()
function ZO_GuildRecruitment_Manager:New(...)
local manager = ZO_CallbackObject.New(self)
manager:Initialize(...)
return manager
end
function ZO_GuildRecruitment_Manager:Initialize()
local function OnGuildFinderApplicationsReceived(event, guildId)
self:FireCallbacks("GuildApplicationResultsReady", guildId)
end
local function OnGuildFinderBlacklistReceived()
self:FireCallbacks("GuildBlacklistResultsReady")
end
local function OnGuildPermissionsReceived(event, guildId)
self:FireCallbacks("GuildPermissionsChanged", guildId)
end
local function OnAddOnLoaded(event, name)
if name == "ZO_Ingame" then
local defaults = { guildResponseTexts = {} }
self.savedVars = ZO_SavedVars:NewAccountWide("ZO_Ingame_SavedVariables", 1, "ZO_GuildRecruitment_ResponseMessage", defaults)
EVENT_MANAGER:UnregisterForEvent("ZO_GuildRecruitment_Manager", EVENT_ADD_ON_LOADED)
end
end
local function OnBlacklistResponse(event, guildId, accountName, result)
local guildName = GetGuildName(guildId)
if not ZO_GuildRecruitment_Manager.IsBlacklistResultSuccessful(result) then
ZO_Dialogs_ShowPlatformDialog("GUILD_FINDER_BLACKLIST_FAILED", nil, { mainTextParams = { result } })
elseif ZO_GuildRecruitment_Manager.IsAddedToBlacklistSuccessful(result) then
local displayName = ZO_FormatUserFacingDisplayName(accountName)
ZO_Alert(UI_ALERT_CATEGORY_ALERT, nil, zo_strformat(SI_GUILD_RECRUITMENT_ADDED_TO_BLACKLIST_ALERT, displayName, guildName))
end
end
local function OnGuildMembershipChanged()
self:FireCallbacks("GuildMembershipChanged", guildId)
end
local function OnProcessApplicationResponse(event, guildId, accountName, result)
local guildName = GetGuildName(guildId) or ""
if result == GUILD_PROCESS_APP_RESPONSE_APPLICATION_PROCESSED_ACCEPT then
local displayName = ZO_FormatUserFacingDisplayName(accountName)
ZO_Alert(UI_ALERT_CATEGORY_ALERT, nil, zo_strformat(SI_GUILD_RECRUITMENT_APPLICATION_ACCEPTED_ALERT, displayName, guildName))
elseif result == GUILD_PROCESS_APP_RESPONSE_APPLICATION_PROCESSED_DECLINE then
local displayName = ZO_FormatUserFacingDisplayName(accountName)
ZO_Alert(UI_ALERT_CATEGORY_ALERT, nil, zo_strformat(SI_GUILD_RECRUITMENT_APPLICATION_DECLINED_ALERT, displayName, guildName))
elseif result == GUILD_PROCESS_APP_RESPONSE_APPLICATION_PROCESSED_RESCIND then
-- No alert needed for rescind
else
ZO_Dialogs_ShowPlatformDialog("GUILD_FINDER_PROCESS_APPLICATION_FAILED", nil, { mainTextParams = { result } })
end
end
local function OnUpdatedGuildInfoReceived(event, guildId, result)
self:FireCallbacks("GuildInfoChanged", guildId)
end
EVENT_MANAGER:RegisterForEvent("ZO_GuildRecruitment_Manager", EVENT_ADD_ON_LOADED, OnAddOnLoaded)
EVENT_MANAGER:RegisterForEvent("ZO_GuildRecruitment_Manager", EVENT_GUILD_FINDER_APPLICATION_RESULTS_GUILD, OnGuildFinderApplicationsReceived)
EVENT_MANAGER:RegisterForEvent("ZO_GuildRecruitment_Manager", EVENT_GUILD_FINDER_GUILD_NEW_APPLICATIONS, OnGuildFinderApplicationsReceived)
EVENT_MANAGER:RegisterForEvent("ZO_GuildRecruitment_Manager", EVENT_GUILD_FINDER_BLACKLIST_RESULTS, OnGuildFinderBlacklistReceived)
EVENT_MANAGER:RegisterForEvent("ZO_GuildRecruitment_Manager", EVENT_GUILD_RANK_CHANGED, OnGuildPermissionsReceived)
EVENT_MANAGER:RegisterForEvent("ZO_GuildRecruitment_Manager", EVENT_GUILD_FINDER_BLACKLIST_RESPONSE, OnBlacklistResponse)
EVENT_MANAGER:RegisterForEvent("ZO_GuildRecruitment_Manager", EVENT_GUILD_MEMBER_ADDED, OnGuildMembershipChanged)
EVENT_MANAGER:RegisterForEvent("ZO_GuildRecruitment_Manager", EVENT_GUILD_MEMBER_REMOVED, OnGuildMembershipChanged)
EVENT_MANAGER:RegisterForEvent("ZO_GuildRecruitment_Manager", EVENT_GUILD_PLAYER_RANK_CHANGED, OnGuildPermissionsReceived)
EVENT_MANAGER:RegisterForEvent("ZO_GuildRecruitment_Manager", EVENT_GUILD_FINDER_PROCESS_APPLICATION_RESPONSE, OnProcessApplicationResponse)
EVENT_MANAGER:RegisterForEvent("ZO_GuildRecruitment_Manager", EVENT_GUILD_RECRUITMENT_INFO_UPDATED, OnUpdatedGuildInfoReceived)
end
function ZO_GuildRecruitment_Manager.IsBlacklistResultSuccessful(result)
return result == GUILD_BLACKLIST_RESPONSE_BLACKLIST_SUCCESSFULLY_ADDED or
result == GUILD_BLACKLIST_RESPONSE_BLACKLIST_SUCCESSFULLY_REMOVED or
result == GUILD_BLACKLIST_RESPONSE_BLACKLIST_SUCCESSFULLY_EDITTED
end
function ZO_GuildRecruitment_Manager.IsAddedToBlacklistSuccessful(result)
return result == GUILD_BLACKLIST_RESPONSE_BLACKLIST_SUCCESSFULLY_ADDED
end
function ZO_GuildRecruitment_Manager:GetSavedApplicationsDefaultMessage(guildId)
return self.savedVars.guildResponseTexts[guildId]
end
function ZO_GuildRecruitment_Manager:SetSavedApplicationsDefaultMessage(guildId, text)
self.savedVars.guildResponseTexts[guildId] = text
ZO_SavePlayerConsoleProfile()
end
function ZO_GuildRecruitment_Manager.PopulateDropdown(dropDownControl, iterBegin, iterEnd, stringBase, selectionFunction, data, omittedIndex)
dropDownControl:ClearItems()
if type(omittedIndex) == "function" then
omittedIndex = omittedIndex()
end
local selectedEntryIndex
local currentIndex = 1
local function AddEntry(value)
if value ~= omittedIndex then
local entry = dropDownControl:CreateItemEntry(GetString(stringBase, value), selectionFunction)
entry.value = value
if data.currentValue == value then
selectedEntryIndex = currentIndex
end
dropDownControl:AddItem(entry, ZO_COMBOBOX_SUPPRESS_UPDATE)
currentIndex = currentIndex + 1
end
end
for i = iterBegin, iterEnd do
AddEntry(i)
end
if data.extraValues then
for _, value in ipairs(data.extraValues) do
AddEntry(value)
end
end
local IGNORE_CALLBACK = true
if selectedEntryIndex then
dropDownControl:SelectItemByIndex(selectedEntryIndex, IGNORE_CALLBACK)
else
dropDownControl:SetSelectedItemText(GetString(SI_GUILD_RECRUITMENT_DEFAULT_SELECTION_TEXT))
end
end
GUILD_RECRUITMENT_MANAGER = ZO_GuildRecruitment_Manager:New() |
--- 模块工具
-- @module Module utilities
-- @copyright Lilith Games, Avatar Team
-- @author Yuancheng Zhang
local ModuleUtil = {}
--- 加载模块目录
-- @param _root 模块目录的节点
-- @param _scope 载入后脚本的作用域
function ModuleUtil.LoadModules(_root, _scope)
_scope = _scope or _G
assert(_root, "[ModuleUtil] Node does NOT exist!")
local tmp = _root:GetChildren()
for _, v in pairs(tmp) do
if v.ClassName == "ModuleScriptObject" then
name = (v.Name):gsub("Module", "")
--print("[ModuleUtil] Load Module: " .. name)
_scope[name] = require(v)
end
end
end
--- 加载XLS表格目录
-- @param _root 模块目录的节点
function ModuleUtil.LoadXlsModules(_root, _config)
assert(_root, "[ModuleUtil] Node does NOT exist!")
assert(_config, "[ModuleUtil] Config does NOT exist!")
local tmp = _root:GetChildren()
for _, v in pairs(tmp) do
name = (v.Name):gsub("XlsModule", "")
--print("[ModuleUtil] Load XLS: " .. name)
_config[name] = require(v)
end
end
--- 加载多个模块目录
function ModuleUtil.LoadAllModules(...)
local args = table.pack(...)
for i = 1, args.n do
if args[i] then
ModuleUtil.LoadModules(args[i])
end
end
end
--- 将有包含特定方法的模块筛选出来,并放在一个table中
-- @param _root 模块目录的节点
-- @param @string _fn 方法名 function_name
-- @param @table _list 存放的table
function ModuleUtil.GetModuleListWithFunc(_root, _fn, _list)
assert(_root, "[ModuleUtil] Node does NOT exist!")
assert(not string.isnilorempty(_fn), "[ModuleUtil] Function name is nil or empty!")
assert(_list, "[ModuleUtil] List is NOT initialized!")
local tmp, name = _root:GetChildren()
for _, v in pairs(tmp) do
name = (v.Name):gsub("Module", "")
if _G[name] and _G[name][_fn] and type(_G[name][_fn]) == "function" then
table.insert(_list, _G[name])
end
end
end
--- 新建一个模块实例(ServerBase or ClientBase)
function ModuleUtil.New(_name, _baseClass)
local t = class(_name, _baseClass)
return t, t:GetSelf()
end
return ModuleUtil
|
local path = "qnSwfRes/sfw/video_chat_swf_pin.png"
local video_chat_swf_pin_map = {
["video_chat_3.png"] = {
file=path,
x=2,y=2,
width=52,height=17,
offsetX=0,offsetY=0,
utWidth=52,
utHeight=17,
rotated=false
},
["video_chat_2.png"] = {
file=path,
x=2,y=21,
width=33,height=14,
offsetX=0,offsetY=0,
utWidth=33,
utHeight=14,
rotated=false
},
["video_chat_1.png"] = {
file=path,
x=37,y=21,
width=11,height=11,
offsetX=0,offsetY=0,
utWidth=11,
utHeight=11,
rotated=false
},
}
return video_chat_swf_pin_map |
addEvent("NGCbr.gotCode", true)
addEvent("NGCbr.gotCodeOnce", true)
addEvent("NGCbr.involvedAdded", true)
addEvent("NGCbr.payed", true)
addEvent("NGCbr.moneyChanged", true)
addEvent("NGCbr.robberyFinished", true)
addEvent("NGCbr.copDoorOpen", true)
addEvent("NGCbr.warpProtect", true)
local sx, sy = guiGetScreenSize()
local moneyDisplay = {
pos = {
l = 0.634027*sx,
t = 0.913333*sy,
r = 0.984722*sx,
b = 0.952222*sy,
},
prefix = "BR money: ",
amount = 0,
amountShown = 0,
amountTimer = false,
yettoshow = 0,
shown = false,
flashCount = 10,
flashRate = 300,
color = tocolor(49, 179, 3, 255),
zeroes = "00000000"
}
function payed()
moneyDisplay.shown = false
removeEventHandler("onClientRender", root, drawMoneyDisplay)
cleanUpEnvironment()
if (progressBar) then
local cur = guiProgressBarGetProgress(progressBar)
if (cur >= 1) then
guiProgressBarSetProgress(progressBar, 0)
end
end
end
addEventHandler("NGCbr.payed", localPlayer, payed)
addEventHandler("NGCbr.robberyFinished", localPlayer, payed)
function moneyChanged(newamount)
if (isTimer(moneyDisplay.amountTimer)) then killTimer(moneyDisplay.amountTimer) end
moneyDisplay.amount = newamount
moneyDisplay.yettoshow = newamount - moneyDisplay.amountShown
local rate = math.floor(moneyDisplay.yettoshow/60)
moneyDisplay.amountTimer = setTimer(function() moneyUpdate(60, rate) end, 50, 1)
end
addEventHandler("NGCbr.moneyChanged", localPlayer, moneyChanged)
function moneyUpdate(countdown, amount)
if(countdown == 1) then
if(moneyDisplay.amountTimer) then killTimer(moneyDisplay.amountTimer) end
moneyDisplay.amountShown = moneyDisplay.amount
moneyZeros()
return
end
moneyDisplay.amountShown = moneyDisplay.amountShown+amount
moneyZeros()
moneyDisplay.amountTimer = setTimer(function() moneyUpdate(countdown-1, amount) end, 50, 1)
end
function moneyZeros()
local i = 10000000
moneyDisplay.zeroes = ""
while i>1 do
if(i > moneyDisplay.amountShown) then
moneyDisplay.zeroes = moneyDisplay.zeroes.."0"
i = i * 0.1
else
break
end
end
end
function involvedAdded(team)
addEventHandler("onClientRender", root, drawMoneyDisplay)
flashAndShow(moneyDisplay.flashCount)
end
addEventHandler("NGCbr.involvedAdded", localPlayer, involvedAdded)
function flashAndShow(countdown)
if countdown == 1 then
moneyDisplay.shown = true
else
moneyDisplay.shown = not moneyDisplay.shown
setTimer(function() flashAndShow(countdown-1) end, moneyDisplay.flashRate, 1)
end
end
function drawMoneyDisplay()
if not moneyDisplay.shown then return end
dxDrawText(moneyDisplay.prefix.."$ "..moneyDisplay.zeroes..moneyDisplay.amountShown, moneyDisplay.pos.l,moneyDisplay.pos.t,moneyDisplay.pos.r,moneyDisplay.pos.b, moneyDisplay.color, 1.00, "bankgothic", "left", "top", false, false, true, false, false)
end
env = {
dim = 15,
int = 4,
marker = false,
code = false,
hackDelay = 1500,
warpProtectTime = 3000,
objects = {
bellinside = {
create = function(self)
local snd = playSound3D("bank_alrm.mp3", 1439.02490, -991.89587, 3153.93286, true)
setElementDimension(snd, env.dim)
setElementInterior(snd, env.int)
setSoundMinDistance ( snd, 1 )
setSoundMaxDistance ( snd, 400 )
setSoundVolume (snd , 0.3 )
self.el = snd
end,
destroy = function(self)
if(isElement(self.el)) then
stopSound(self.el)
end
self.el = false
end,
el = false
},
belloutside = {
create = function(self)
local snd = playSound3D("bank_alarm.wav", 1467.43798, -1011.45056, 29.73729, true)
setElementDimension(snd, 0)
setElementInterior(snd, 0)
setSoundMinDistance (snd, 10 )
setSoundMaxDistance ( snd, 100 )
self.el = snd
end,
destroy = function(self)
if(isElement(self.el)) then
stopSound(self.el)
end
self.el = false
end,
el = false,
},
blip_front = {
create = function(self)
self.el = createBlip(1466.97790, -1012.0236, 25.84375, 52)
end,
destroy = function(self)
if(isElement(self.el)) then
destroyElement(self.el)
self.el = false
end
end,
el = false,
},
blip_cop = {
create = function(self)
self.el = createBlip(1426.77282, -966.98425, 36.42571)
end,
destroy = function(self)
if(isElement(self.el)) then
destroyElement(self.el)
self.el = false
end
end,
el = false,
}
}
}
local state = {
startedHacking = false,
hacking = false
}
function initResource()
d("Init resource")
_defaults:hold("env", env)
_defaults:hold("state", state)
_defaults:hold("moneyDisplay", moneyDisplay)
createWindows()
cleanUpEnvironment()
end
addEventHandler("onClientResourceStart", resourceRoot, initResource)
function wProtect()
cancelEvent()
end
function warpProtect()
addEventHandler("onClientPlayerDamage", localPlayer, wProtect)
setTimer(function() removeEventHandler("onClientPlayerDamage", localPlayer, wProtect) end, warpProtectTime or 3000, 1)
end
addEventHandler("NGCbr.warpProtect", localPlayer, warpProtect)
function gotCodeOnce()
if source then
for _, obj in pairs(env.objects) do
obj:create()
end
else
for _,obj in pairs(env.objects) do
obj:destroy()
end
end
end
addEventHandler("NGCbr.gotCodeOnce", localPlayer, gotCodeOnce)
function createWindows()
local screenWidth, screenHeight = guiGetScreenSize()
windowWidth, windowHeight = 369, 175
windowX, windowY = (screenWidth / 2) - (windowWidth / 2), (screenHeight / 2) - (windowHeight / 2)
window = guiCreateWindow(windowX, windowY, windowWidth, windowHeight, "Bank Valve", false)
guiSetAlpha(window, 1)
banlLbl = guiCreateLabel(9, 22, 352, 89, "Enter the code that you were given earlier\nto crack the valve", false, window)
guiLabelSetColor(banlLbl, 255, 0, 0)
guiLabelSetHorizontalAlign(banlLbl, "center", false)
guiSetFont(banlLbl, "clear-normal")
bankEdit = guiCreateEdit(9, 78, 351, 41, "", false, window)
hackIt = guiCreateButton(12, 125, 348, 37, "Hack It!", false, window)
guiSetVisible(window, false)
windowWidth, windowHeight = 314, 41
windowX, windowY = (screenWidth / 2) - (windowWidth / 2), (screenHeight / 2) - (windowHeight / 2)
progressBar = guiCreateProgressBar(windowX, windowY, windowWidth, windowHeight, false)
guiSetVisible(progressBar, false)
end
function cleanUpHackerStuff()
if (isElement(env.marker)) then
destroyElement(env.markerBlip)
destroyElement(env.marker)
end
env.code = false
guiProgressBarSetProgress(progressBar, 0)
guiSetVisible(progressBar, false)
guiSetVisible(window, false)
showCursor(false)
setElementFrozen(localPlayer, false)
end
function cleanUpEnvironment()
cleanUpHackerStuff()
for _,obj in pairs(env.objects) do
obj:destroy()
end
env = _defaults:get("env")
state = _defaults:get("state")
moneyDisplay = _defaults:get("moneyDisplay")
end
addEventHandler("NGCbr.robberyFinished", getRootElement(), cleanUpEnvironment)
function hackValve()
local code = guiGetText(bankEdit)
local c = colors.criminals
if (code ~= env.code) then
o("The code you entered is wrong, your code is: "..env.code, c.r, c.g, c.b)
return
else
o("Stay in the marker till the safe is cracked!", c.r,c.g,c.b)
end
state.hackingStarted = true
triggerServerEvent("NGCbr.startedHacking", localPlayer)
showCursor(false)
guiSetVisible(window, false)
guiSetInputMode ( "allow_binds")
state.hacking = true
beginSafeHack()
end
function updateProgress()
local cur = guiProgressBarGetProgress(progressBar)
local n = cur + 1
guiProgressBarSetProgress(progressBar, n)
if (cur >= 100) then
if (isTimer(env.timer)) then killTimer(env.timer) end
cleanUpHackerStuff()
triggerServerEvent("NGCbr.finishedHacking", localPlayer)
end
end
function beginSafeHack()
guiSetVisible(progressBar, true)
env.timer = setTimer(updateProgress, env.hackDelay, 0)
end
function markValve(code)
env.code = code
env.marker = createMarker(1395, -980, 3135, "cylinder", 3, 255, 255, 0)
env.markerBlip = createBlipAttachedTo(env.marker, 0, 1, 0, 255, 0, 255, 0, 65535, localPlayer)
setElementDimension(env.marker, 15)
setElementInterior(env.marker, 4)
addEventHandler("onClientMarkerHit", env.marker, enteredMarker)
addEventHandler("onClientMarkerLeave", env.marker, leftMarker)
addEventHandler("onClientGUIClick", hackIt, hackValve, false)
end
addEventHandler("NGCbr.gotCode", localPlayer, markValve)
function enteredMarker(plr)
if (plr ~= localPlayer) then return end
if (not state.hackingStarted) then
guiSetVisible(window, true)
guiSetInputMode ( "no_binds_when_editing")
exports.NGCdxmsg:createNewDxMessage("Write the code in the field to begin to crack the safe ("..env.code ..")", 0, 255, 0)
triggerServerEvent("NGCbr.reachedValve", localPlayer)
showCursor(true)
elseif (not state.hacking) then
state.hacking = true
beginSafeHack()
end
end
function leftMarker(plr)
if(plr ~= localPlayer) then return end
if (guiGetVisible(window)) then
guiSetVisible(window, false)
end
if (state.hackingStarted == true) then
state.hacking = false
guiSetInputMode ( "allow_binds")
if (isTimer(env.timer)) then killTimer(env.timer) end
guiSetVisible(progressBar, false)
guiProgressBarSetProgress(progressBar, 0)
showCursor(false)
local c = colors.criminals
outputDebugString("triggered to stop by leaving marker")
o("You left the marker, hacking paused!", c.r,c.g,c.b)
end
end
function leftMarkerDied(plr)
if(plr ~= localPlayer) then return end
if (guiGetVisible(window)) then
guiSetVisible(window, false)
end
if (state.hackingStarted == true) then
state.hacking = false
guiSetInputMode ( "allow_binds")
if (isTimer(env.timer)) then killTimer(env.timer) end
guiSetVisible(progressBar, false)
guiProgressBarSetProgress(progressBar, 0)
showCursor(false)
local c = colors.criminals
outputDebugString("triggered to stop by dieing")
o("You have died, therefore get nothing, better luck next time!", c.r,c.g,c.b)
end
end
addEventHandler("onClientPlayerWasted", localPlayer, leftMarkerDied) |
scenemanager = SceneManager.new(
{
["menu"] = Menu,
["game"] = Game,
["gameover"] = GameOver,
}
)
stage:addChild(scenemanager)
scenemanager:changeScene("menu", 1, transitions[1], easing.outBack)
|
CURRENT_ZONE = nil
function createZone(boxCenter,length,width,minZ,maxZ,heading)
if CURRENT_ZONE ~= nil then return end
local options = {heading = heading, minZ = 0.0, maxZ = 0.0, data = {}}
options.minZ = boxCenter.z-minZ
options.maxZ = boxCenter.z+maxZ
options.debugPoly=true
local zone = BoxZone:Create(boxCenter, length, width, options)
CURRENT_ZONE = zone
end
function destroyZone()
if CURRENT_ZONE == nil then return end
CURRENT_ZONE:destroy()
CURRENT_ZONE = nil
end |
-- authors: Luxinia Dev (Eike Decker & Christoph Kubisch)
---------------------------------------------------------
return {
exts = {"sql"},
lexer = wxstc.wxSTC_LEX_LUA,
apitype = "sql",
linecomment = "--",
isfncall = function(str)
return string.find(str,"([A-Za-z0-9_]+)%s*%(")
end,
lexerstyleconvert = {
text = {wxstc.wxSTC_LUA_IDENTIFIER,},
lexerdef = {wxstc.wxSTC_LUA_DEFAULT,},
comment = {wxstc.wxSTC_LUA_COMMENT,
wxstc.wxSTC_LUA_COMMENTLINE,
wxstc.wxSTC_LUA_COMMENTDOC,},
stringtxt = {wxstc.wxSTC_LUA_STRING,
wxstc.wxSTC_LUA_CHARACTER,
wxstc.wxSTC_LUA_LITERALSTRING,},
stringeol = {wxstc.wxSTC_LUA_STRINGEOL,},
preprocessor= {wxstc.wxSTC_LUA_PREPROCESSOR,},
operator = {wxstc.wxSTC_LUA_OPERATOR,},
number = {wxstc.wxSTC_LUA_NUMBER,},
keywords0 = {wxstc.wxSTC_LUA_WORD,},
keywords1 = {wxstc.wxSTC_LUA_WORD2,},
keywords2 = {wxstc.wxSTC_LUA_WORD3,},
keywords3 = {wxstc.wxSTC_LUA_WORD4,},
keywords4 = {wxstc.wxSTC_LUA_WORD5,},
keywords5 = {wxstc.wxSTC_LUA_WORD6,},
keywords6 = {wxstc.wxSTC_LUA_WORD7,},
keywords7 = {wxstc.wxSTC_LUA_WORD8,},
},
keywords = {
[[ SELECT FROM CREATE TABLE WHERE ORDER BY CASE
WHEN CHECK CONSTRAINT PRIMARY AUTOINCREMENT
INSERT INTO DELETE DROP DISTINCT GROUP IS DEFAULT
BEGIN TRANSACTION COMMIT KEY REFERENCES UNIQUE INDEX ON SET RESTRICT
CASCADE ]],
-- javascript keywords
[[ NULL]],
[[ TEXT BOOLEAN INTEGER]]
},
}
--[==[
return {
exts = {"sql"},
lexer = wxstc.wxSTC_LEX_SQL,
apitype = "sql",
linecomment = "--",
stylingbits = 5,
lexerstyleconvert = {
text = {wx.wxSTC_SQL_DEFAULT},
comment = {wx.wxSTC_SQL_COMMENT,wx.wxSTC_SQL_COMMENTLINE},
stringeol = {},
number = {wx.wxSTC_SQL_NUMBER},
stringtxt = {},
lexerdef= {},
keywords0 = {wx.wxSTC_SQL_IDENTIFIER, wx.wxSTC_SQL_QUOTEDIDENTIFIER},
keywords1 = {wx.wxSTC_SQL_STRING},
keywords2 = {wx.wxSTC_SQL_COMMENTDOC,wx.wxSTC_SQL_COMMENTDOCKEYWORD},
keywords3 = {wx.wxSTC_SQL_COMMENTDOCKEYWORDERROR,wx.wxSTC_SQL_COMMENTLINEDOC},
keywords4 = {wx.wxSTC_SQL_WORD,wx.wxSTC_SQL_WORD2,},
keywords5 = {wx.wxSTC_SQL_USER1,wx.wxSTC_SQL_USER2,wx.wxSTC_SQL_USER3,wx.wxSTC_SQL_USER4},
keywords6 = {},
keywords7 = {},
preprocessor= {},
},
keywords = {
-- HTML tags and attributes
[[ SELECT FROM CREATE TABLE WHERE ORDER BY CASE
WHEN CHECK CONSTRAINT PRIMARY INTEGER AUTOINCREMENT
INSERT INTO DELETE DROP DISTINCT GROUP IS DEFAULT]],
-- javascript keywords
[[ NULL]]
},
}
]==]
|
-- Walk around randomly to fill the table.
function love.load()
tSz = 16
map = newMap(150)
generateMap(map, 0)
love.graphics.setBackgroundColor(36, 33, 18)
love.graphics.setColor(30, 140, 22)
end
function love.draw()
drawMap(map)
end
function drawMap(map)
for k,v in pairs(map.floorTiles) do
drawFloor(v[1], v[2])
end
end
function drawFloor(x, y)
love.graphics.rectangle("fill", x*tSz, y*tSz, tSz, tSz)
end
function newMap(floorCount)
return {
n=0, max=floorCount,
floorTiles={},
-- dir is quarter-turns clockwise from right
x=25, y=18, dir=0,
exits = { {1,0}, {0,1}, {-1,0}, {0,-1} }
}
end
function generateMap(map, seed)
math.randomseed(seed)
while placeFloor(map, map.x, map.y) do
moveRandomly(map)
end
return map
end
function placeFloor(map, x, y)
local canPlace = map.n < map.max
if canPlace then
local key = tostring(x) .. ',' .. tostring(y)
if map.floorTiles[key] == nil then
map.floorTiles[key] = {x, y}
map.n = map.n + 1
end
end
return canPlace
end
function moveRandomly(map)
map.dir = (map.dir + math.random(0, 3)) % 4
local e = map.exits[map.dir+1]
map.x = map.x + e[1]
map.y = map.y + e[2]
end
|
--[[ Copyright (c) 2010 Peter "Corsix" Cawley
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. --]]
-- To enable the developer "language" in the ingame options, uncomment the
-- following line. This language causes every translatable string to be
-- displayed as the name of the string.
--Language("Developer")
Inherit("english")
--! Construct a 'translation' with the string names as text value.
local function fixup(t, str_name)
for k, v in pairs(t) do
local name = str_name .. "." .. k
if type(v) == "string" then
t[k] = name
else
fixup(v, name)
end
end
end
fixup(_G, "_S")
|
function onSay(cid, words, param, channel)
local n = 1
if(param ~= '' and tonumber(param)) then
n = math.max(0, tonumber(param))
end
local tmp, pos = getCreaturePosition(cid), getCreaturePosition(cid)
if(words:sub(2, 2) == "u") then
pos.z = pos.z - n
else
pos.z = pos.z + n
end
if pos.z == 7 then
elseif pos.z <= 6 then
doAreaCombatHealth(0,0,pos,0,0,0,255)
doCreateItem(460,1,pos)
end
pos = getClosestFreeTile(cid, pos, false, false)
if(not pos or isInArray({pos.x, pos.y}, 0)) then
doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Destination not reachable.")
return true
end
if(doTeleportThing(cid, pos, true) and not isPlayerGhost(cid)) then
doSendMagicEffect(tmp, CONST_ME_POFF)
doSendMagicEffect(pos, CONST_ME_TELEPORT)
end
--gerarEmVolta(getThingPos(cid))
return true
end |
-- lodr helper: function that fills out the "watched" table
local function startsWith(s, prefix)
return s:sub(1, #prefix) == s
end
return function(watched, watchRealpath)
local function recursiveWatch(path)
if lovr.filesystem.isDirectory(path) then
for i,filename in ipairs(lovr.filesystem.getDirectoryItems(path)) do
if not startsWith(filename, ".") then -- Skip hidden files/directories
recursiveWatch((path ~= "/" and path or "") .. "/" .. filename)
end
end
else
-- Files in the save directory were written *by* the program; if they change, that isn't a program change.
-- So we don't accidentally watch files in the save directory, verify every filepath against the true file root.
if startsWith(lovr.filesystem.getRealDirectory(path), watchRealpath) then
table.insert(watched, path)
end
end
end
return recursiveWatch
end
|
resource.AddFile("materials/darkrp/darkrpderma.png")
|
--[[
key 1 -> rdb:schedule:waiting
key 2 -> rdb:schedule:queued
key 3 -> rdb:schedule:active
key 4 -> rdb:schedule:schedules
key 5 -> rdb:schedule:lock
key 6 -> rdb:schedule:hello
arg 1 -> timestampMs
arg 2 -> lockTime
arg 3 -> lockId - this is the redibox worker id (this.core.id)
arg 4 -> lockInterval
]]
--[[
-- Determines if this occrence is valid and matches the current saved version hash
- scheduleParsed
- versionHash
- name
- time
]]
local function isValidSchedule(scheduleParsed, versionHash, name, time)
local enabled = scheduleParsed.enabled
local scheduleVersionHash = scheduleParsed.versionHash
local nextTimestamp = tonumber(scheduleParsed.occurrence.next)
local endTimestamp = tonumber(scheduleParsed.occurrence.ends)
local startsTimestamp = tonumber(scheduleParsed.occurrence.starts)
local runOnce = (scheduleParsed.occurrence.once and not scheduleParsed.occurrence.onceCompleted)
-- only valid if schedule is enabled still
-- and it's hash matches the hash at time of creating this occurrence
if enabled and versionHash == scheduleVersionHash then
-- check this occurence is not > end timestamp
if runOnce or (nextTimestamp <= endTimestamp and nextTimestamp >= startsTimestamp) then
return true
else
-- do nothing - it's past the end date
-- just disable the schedule and update it
scheduleParsed.enabled = false
scheduleParsed.stoppedAt = time
redis.call('hset', KEYS[4], name, cjson.encode(scheduleParsed))
return false
end
else
return false
end
end
local function processOcurrence(occurrence, time)
-- get the schedule json string for hash table
local name, versionHash = occurrence:match("([^,]+)|||([^,]+)")
local schedule = redis.call('hget', KEYS[4], name)
-- continue if we found schedule
if schedule then
-- try json decode schedule so we can check if it's still enabled
local scheduleParsed = cjson.decode(schedule)
local runOnce = (scheduleParsed.occurrence.once and not scheduleParsed.occurrence.onceCompleted)
-- only valid if schedule is enabled still
if isValidSchedule(scheduleParsed, versionHash, name, time) then
-- update number of times ran counter
scheduleParsed.timesRan = scheduleParsed.timesRan + 1
scheduleParsed.lastRan = time
if runOnce then
scheduleParsed.occurrence.onceCompleted = true
end
-- re-encode json and update hash
local updatedSchedule = cjson.encode(scheduleParsed);
redis.call('hset', KEYS[4], name, updatedSchedule)
-- push to work queue
redis.call('RPUSH', KEYS[2], updatedSchedule)
end
end
-- all done, now remove this occurences
redis.call('zrem', KEYS[1], occurrence)
end
local function process()
local lock = redis.call('get', KEYS[5])
if lock then
return lock
end
redis.call('set', KEYS[5], ARGV[3], 'PX', tonumber(ARGV[2]))
-- get occurrences that a ready to run based on timestamp
-- we slightly creep ahead a couple ms to ensure jubs are picked up on the dot
-- or as close to it as possible
local time = tonumber(ARGV[1])
local occurrences = redis.call('zrangebyscore', KEYS[1], 0, time)
if occurrences then
for i, occurrence in ipairs(occurrences) do
processOcurrence(occurrence, time)
end
end
-- set lock to expire after half the interval time
if redis.call('get', KEYS[5]) == ARGV[3] then
-- redis.debug('EXIRING KEY ' .. KEYS[5] .. ' with token ' .. ARGV[3])
redis.call('pexpire', KEYS[5], tonumber(ARGV[4]) - 10)
end
-- return a count of schedules pushed to ready
return { #occurrences, redis.call('set', KEYS[6], time, 'NX') }
--return #occurrences
end
return process()
|
-- This file is subject to copyright - contact [email protected] for more information.
-- INSTALL: CINEMA
SWEP.PrintName = "Flare"
SWEP.DrawAmmo = false
SWEP.ViewModelFOV = 85
SWEP.Slot = 0
SWEP.SlotPos = 2
SWEP.Purpose = "Light Gnomes On Fire"
SWEP.Instructions = "Primary: Use"
SWEP.AdminSpawnable = false
SWEP.ViewModel = Model("models/brian/flare.mdl")
SWEP.WorldModel = Model("models/brian/flare.mdl")
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
SWEP.Primary.ClipSize = -1
SWEP.Primary.Damage = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "none"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Damage = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.RenderGroup = RENDERGROUP_BOTH
function SWEP:Initialize()
self:SetHoldType("slam")
end
if SERVER then
timer.Create("FlareControl", 5, 0, function()
for k, v in pairs(ents.FindByClass("weapon_flare")) do
if v:GetPos().z > -10 then
v:Remove()
end
end
end)
end
function SWEP:PrimaryAttack()
local ply = self:GetOwner()
--if(SERVER)then self:CallOnClient("PrimaryAttack") end
if (SERVER) then
SuppressHostEvents(ply)
end
self:SetNextPrimaryFire(CurTime() + 1)
ply:SetAnimation(PLAYER_ATTACK1)
self:EmitSound("Weapon_StunStick.Swing", nil, 60, 0.2)
ply:TimerSimple(0.15, function()
if not IsValid(self) then return end
local dir = ply:GetAimVector()
local org = ply:GetShootPos() + dir * 20 + Vector(0, 0, -10)
local effectdata = EffectData()
effectdata:SetOrigin(org)
effectdata:SetNormal(dir)
effectdata:SetRadius(1)
effectdata:SetMagnitude(1)
effectdata:SetScale(0.1)
util.Effect("ElectricSpark", effectdata)
--[[ local hit = self.Owner:GetEyeTrace()
if (hit.HitPos or Vector(0,0,0)):Distance(self.Owner:EyePos()) > 80 then return end
hit = hit.Entity
if IsValid(hit) and hit:GetClass()=="keem" then hit:FireAttack() self:Remove() end ]]
--
if SERVER then
for k, v in pairs(ents.FindByClass("keem")) do
if v:GetPos():Distance(self.Owner:GetPos()) < 80 then
v:FireAttack()
SafeRemoveEntityDelayed(self, 0.2)
end
end
end
end)
if (SERVER) then
SuppressHostEvents()
end
end
function SWEP:SecondaryAttack()
end
function SWEP:Think()
if CLIENT then
if (not IsValid(self.Owner)) or self.Owner:GetActiveWeapon() ~= self then return end
local dlight = DynamicLight(self:EntIndex())
if (dlight) then
dlight.pos = self.Owner:EyePos()
dlight.r = 255
dlight.g = 50
dlight.b = 50
dlight.brightness = 0.5 --math.random(10,22)*0.1
dlight.Decay = 1000
dlight.Size = 2000
dlight.DieTime = CurTime() + 0.05
end
end
end
function SWEP:DrawWorldModel()
local ply = self:GetOwner()
if (IsValid(ply)) then
local bn = "ValveBiped.Bip01_R_Hand"
local bon = ply:LookupBone(bn) or 0
local opos = self:GetPos()
local oang = self:GetAngles()
local bp, ba = ply:GetBonePosition(bon)
if (bp) then
opos = bp
end
if (ba) then
oang = ba
end
opos = opos + oang:Right() * 1
opos = opos + oang:Forward() * 4
oang:RotateAroundAxis(oang:Right(), 180)
self:SetupBones()
self:SetModelScale(0.8, 0)
local mrt = self:GetBoneMatrix(0)
if (mrt) then
mrt:SetTranslation(opos)
mrt:SetAngles(oang)
self:SetBoneMatrix(0, mrt)
end
end
self:DrawModel()
end
flarefxpos = Vector()
flaresprite = Material("sprites/glow04_noz")
function SWEP:GetViewModelPosition(pos, ang)
local pos2 = pos * 1 --copy vector
local ang2 = ang * 1
pos = pos + ang:Right() * 19
pos = pos + ang:Up() * -15
pos = pos + ang:Forward() * 25
pos2 = pos2 + ang:Forward() * 44
pos2 = pos2 + ang:Up() * -15
ang2:RotateAroundAxis(ang2:Right(), -90)
local thrustv = (self:GetNextPrimaryFire() - 0.3) > CurTime() and 1 or 0
local spd = thrustv == 1 and 1.5 or 1
self.ThrustLerp = math.Approach(self.ThrustLerp or 0, thrustv, FrameTime() * spd)
self.ThrustLerp2 = math.Approach(self.ThrustLerp2 or 0, thrustv, FrameTime() * spd * 0.5)
local ez = 1
local ez2 = 1
pos = LerpVector(math.EaseInOut(self.ThrustLerp2, ez, ez2), pos, pos2)
ang = LerpAngle(math.EaseInOut(self.ThrustLerp, ez, ez2), ang, ang2)
flarefxpos:Set(pos)
flarefxpos = flarefxpos + ang:Up() * 7 + ang:Forward() * -1 + ang:Right() * -1
return pos, ang
end
function SWEP:PostDrawViewModel()
render.SetMaterial(flaresprite)
local a = 0.1
local b = math.Rand(0.6, 1)
render.DrawSprite(flarefxpos + Vector(math.Rand(-a, a), math.Rand(-a, a), math.Rand(-a, a)), 15, 15, Color(255 * b, 255 * b, 255 * b))
end
|
vim.g.nvim_tree_highlight_opened_files = 1
vim.g.nvim_tree_git_hl = 1
vim.g.nvim_tree_respect_buf_cwd = 1
vim.g.nvim_tree_width_allow_resize = 1
vim.g.nvim_tree_show_icons = {
git = 1,
folders = 1,
files = 1,
}
local status_ok, nvim_tree = pcall(require, 'nvim-tree')
if not status_ok then
return
end
nvim_tree.setup {
open_on_setup = true,
open_on_setup_file = true,
open_on_tab = true,
update_cwd = true,
view = { width = 32, side = "left" },
renderer = {
indent_markers = {
enable = false,
icons = {
corner = "└ ",
edge = "│ ",
none = " ",
},
},
icons = {
webdev_colors = true,
},
},
actions = {
change_dir = { enable = false },
open_file = {
resize_window = true,
},
},
update_focused_file = {
enable = true,
update_cwd = true,
},
filters = {
dotfiles = true,
custom = { 'node_modules', '.cache', '.bin' },
},
}
map('n', '<C-n>', ':NvimTreeToggle<CR>')
vim.cmd [[
autocmd BufEnter * ++nested if winnr('$') == 1 && bufname() == 'NvimTree_' . tabpagenr() | quit | endif
]]
|
-- to do: rename to something less bad
status = {}
function status.drawPartyPokemon(party)
gui.box(-1, -1, 160, 53, "#000000e0", "#000000d0")
for index, poke in pairs(party.pokemon) do
-- print everything here
local y = index * 9 + 1
gui.text( 1, y, string.format("%-10s Lv%3d HP %3d/%3d", poke.name, poke.level, poke.hp.current, poke.hp.max), "white", "clear")
fart.progressBar(112, y + 2, 45, 3, poke.hp.current, poke.hp.max)
end
end
function status.drawSinglePokemonStats(poke)
-- Must have pokemon to draw otherwise (welp)
if not poke then return end
gui.box(-1, -1, 160, 80, "#000000e0", "#000000d0")
gui.text( 1, 1, string.format("%-10s HP %3d/%3d", poke.name, poke.hp.current, poke.hp.max), "white", "clear")
fart.progressBar( 98, 2, 60, 3, poke.hp.current, poke.hp.max)
gui.text( 1, 9, string.format(" Level %3d Status %3d Type %d/%d", poke.level, poke.statusRaw, poke.type.first, poke.type.second), "white", "clear")
gui.text( 1, 17, string.format(" EXP %7d", poke.exp), "white", "clear")
gui.text( 1, 30, "Stats", "white", "clear")
gui.text( 1, 38, string.format("HP %3d (IV %2d, EV %5d +%3d)", poke.hp.max , poke.ivs.hp , poke.statExp.raw.hp , poke.statExp.bonus.hp ), "white", "clear")
gui.text( 1, 46, string.format("Atk %3d (IV %2d, EV %5d +%3d)", poke.stats.attack , poke.ivs.attack , poke.statExp.raw.attack , poke.statExp.bonus.attack ), "white", "clear")
gui.text( 1, 54, string.format("Def %3d (IV %2d, EV %5d +%3d)", poke.stats.defense, poke.ivs.defense, poke.statExp.raw.defense, poke.statExp.bonus.defense ), "white", "clear")
gui.text( 1, 62, string.format("Spd %3d (IV %2d, EV %5d +%3d)", poke.stats.speed , poke.ivs.speed , poke.statExp.raw.speed , poke.statExp.bonus.speed ), "white", "clear")
gui.text( 1, 70, string.format("Spc %3d (IV %2d, EV %5d +%3d)", poke.stats.special, poke.ivs.special, poke.statExp.raw.special, poke.statExp.bonus.special ), "white", "clear")
end
--[[
local pokedata = {
species = m.rb(start + 0x00),
speciesQ = m.rb(quickSpecies),
hp = {
current = m.rw(start + 0x01),
max = m.rw(start + 0x22), -- non-box only
},
level = m.rb(start + 0x03),
status = m.rb(start + 0x04),
type = {
first = m.rb(start + 0x05),
second = m.rb(start + 0x06),
},
catchRate = m.rb(start + 0x07), -- used for GSC held items
moves = {}, -- will be set latem.r (PP/etc); 08~0B
otNumber = m.rw(start + 0x0c),
exp = m.r3w(start + 0x0E),
statExp = {
hp = m.rw(start + 0x11),
attack = m.rw(start + 0x13),
defense = m.rw(start + 0x15),
speed = m.rw(start + 0x17),
special = m.rw(start + 0x19)
},
iValues = m.rw(start + 0x1b), -- todo: split these
-- PP is 1D to 20
-- Everything beyond here is dropped for
-- pokes stored in the boxes
level = m.rb(start + 0x21),
stats = {
attack = m.rw(start + 0x24),
defense = m.rw(start + 0x26),
speed = m.rw(start + 0x28),
special = m.rw(start + 0x2A)
}
}
--]]
return status |
function love.conf(config)
config.window.title = "Pong"
end
|
CStore = class(
function( self )
self.Name = "<UNKNOWN>"
self.Id = 0
self.Item = {}
self.CanRepair = false
end
)
function CStore:update()
local target = player:getTarget()
if not target:exists() then
print("NPC not targeted. Clearing 'store'.")
self.Name = "<UNKNOWN>"
self.Id = 0
self.Item = {}
self.CanRepair = false
return
end
-- NPC not targeted
if target.Type ~= PT_NPC then
return
end
-- store not open
if not RoMScript("StoreFrame:IsVisible()") then
return
end
-- Already holds info on this store. No need update
if self.Id == target.Id then
return
end
self.Id = target.Id
self.Name = target.Name
-- number of items in store
local sellItems = RoMScript("GetStoreSellItems()")
-- get item data
self.Item = {}
for i = 1, sellItems do
self.Item[i] = {}
local __, name, price, __, __, __, maxheap = RoMScript("GetStoreSellItemInfo(".. i ..")")
local id = parseItemLink(RoMScript("GetStoreSellItemLink(".. i ..")"));
self.Item[i].Name = name
self.Item[i].Price = price
self.Item[i].MaxHeap = maxheap
self.Item[i].Id = id
end
-- Is there a repair button.
self.CanRepair = RoMScript("IsStoreCanFix()")
end
-- buys 'quantity' of items by name, id or shop index.
function CStore:buyItem(nameIdOrIndex, quantity)
if quantity == nil then
-- Assume they want to buy 1
quantity = 1
end
if quantity <= 0 then return end
self:update()
-- First find the store index number
local buyIndex = 0
if type(nameIdOrIndex) == "number" and nameIdOrIndex <= #self.Item then
-- buying by index
buyIndex = nameIdOrIndex
elseif type(nameIdOrIndex) == "number" or type(nameIdOrIndex) == "string" then
-- buying by id or name, search for id or name
for i,item in pairs(self.Item) do
if nameIdOrIndex == item.Id or nameIdOrIndex == item.Name then
buyIndex = i
break
end
end
else
printf(cli.yellow,"Wrong first argument to 'store:BuyItem'.")
return false
end
if buyIndex == 0 then
-- Item not found
return false
end
-- Then get the maxheap
buyMaxHeap = self.Item[buyIndex].MaxHeap
-- Buy the item/s
printf(language[1001]); -- Shopping
repeat
if quantity > buyMaxHeap then
RoMCode("StoreBuyItem(" .. buyIndex .. "," .. buyMaxHeap .. ")")
quantity = quantity - buyMaxHeap
else
RoMCode("StoreBuyItem(" .. buyIndex .. "," .. quantity .. ")")
quantity = 0
end
printf(" .")
yrest(1000)
until quantity == 0
printf("\n")
return true
end
-- Returns item name or false, takes in type, example: "hot" or "mot" or "arraw_quver" or "thrown_bag"
-- quantity is how many of them do we need, for example, for potions its 99 or 198
-- but for arraws it might be 1 or 2
-- type: hot|mot|arrow_quiver|thrown_bag|poison
function CStore:buyConsumable(type, quantity)
if quantity == nil or quantity == "" then
return
end
self:update()
-- Find best store item
local bestLevel = 0;
for i,item in pairs(self.Item) do
local storeItemId = item.Id
local consumable = database.consumables[storeItemId];
if( consumable
and consumable.Type == type
and consumable.Level <= player.Level ) then
if consumable.Level > bestLevel then
bestLevel = consumable.Level;
bestItem = item.Id;
bestItemSlot = i;
end
end
end
if bestLevel == 0 then
return false;
end
-- Count number of better items in inventory
inventory:update();
local totalCount = 0;
for slot,item in pairs(inventory.BagSlot) do
local consumable = database.consumables[item.Id];
if item.Available and
consumable and
consumable.Type == type and
consumable.Level >= bestLevel and
consumable.Level <= player.Level then
totalCount = totalCount + item.ItemCount
end;
end;
-- See how many needed
if totalCount < quantity then
numberToBuy = quantity - totalCount;
self:buyItem(bestItemSlot, numberToBuy)
end
return true;
end
|
return function(luma,fage)
local enum = luma:import "enum"
-------------------------------------------------------------------------------
local mesh={
loaded = {},
enum = {}
}
-------------------------------------------------------------------------------
mesh.enum.file_format=enum {
"wavefront",
"collada"
}
-------------------------------------------------------------------------------
function mesh.load(source,file_format)
assert(fage.backend,"Backend not initialized.")
assert(fage.backend.mesh,"Mesh is not supported.")
if not file_format and type(source)=="string" then
local extension=source:match("^.+(%..+)$")
if extension==".obj" then
file_format=mesh.enum.file_format.wavefront
elseif extension==".dae" then
file_format=mesh.enum.file_format.collada
end
end
assert(file_format,"File format not specified or invalid.")
mesh.loaded[source]=(
mesh.loaded[source]
or fage.backend.mesh.load(source,file_format)
)
pcall(collectgarbage)
return source
end
function mesh.delete(id)
assert(fage.backend,"Backend not initialized.")
assert(
mesh.loaded[id],
("Invalid mesh %s"):format(id)
)
fage.backend.mesh.delete(mesh.loaded[id])
mesh.loaded[id]=nil
pcall(collectgarbage)
end
-------------------------------------------------------------------------------
return mesh
end |
local ADDON, finder = ...
--SavedVariablesPerCharacter: FinderOptions
--SavedVariables: FinderCache
local FINDER_VERSION = GetAddOnMetadata(ADDON, "Version")
local ExpansionData = {
[0] = {name = "Vanilla", maxItemID = 25000, color = "|cffe6cc80"},
[1] = {name = "TBC", maxItemID = 190000, color = "|cff67f100"},
}
-- local vars
local cPurple = "|cffa335ee"
local confirmTimer
local confirmWipe = false -- used for 2 step cache wipe command
local WIPE_TIMER_DURATION = 60 -- safety timer for user to type '/finder wipe' a 2nd time in order to wipe the item cache
local cItemExists = C_Item.DoesItemExistByID
-- some options
local MAX_HITS = 20
local hush = false -- this silences rebuild progress updates for the duration of the player session
-- cache rebuild stuff
-- TODO: some of this should be player options
local CURRENT_EXPANSION = GetExpansionLevel()
local CACHE_MAX_ITEMID = ExpansionData[CURRENT_EXPANSION].maxItemID
local CACHE_STOP_REBUILD = false
local CACHE_REBUILDING = false -- changes to an int when rebuilding, indicating current itemID position
local CACHE_IS_PREPARED = false
local AVERAGE_FRAMERATE = 60 -- reasonable first guess, hardly matters
local CACHE_ITEMSPERFRAME = 1000 / 60 -- safe default, targeting ~30 second rebuild
local MAX_WAIT_TIME = 5 -- the maximum amount of time we're willing to wait for GetItemInfo() to return results. If exceeded, print what we got so far, plus a warning
local CACHE_CURRENT_REQUESTS = {} -- item info queue
-- forward dec
local addOrUpdateCache
local prepareCache
-- enums
local SCAN_SPEED = {
fast = 2000,
normal = 1000,
slow = 250,
}
-- helpers
local fmsg = function(msg)
return string.format("/|cffa335eeFinder [%s%s|r]|r:: %s", ExpansionData[CURRENT_EXPANSION].color, ExpansionData[CURRENT_EXPANSION].name, msg)
end
local function getDefaults(category)
if not finder.defaults[category] then
error("Trying to load defaults for a non-existant category: "..tostring(category))
end
local t = {}
for k, v in pairs(finder.defaults[category]) do
t[k] = v
end
return t
end
-- quick and dirty table_contains implementation for array tables
local function tcontains(table, item)
local index = 1
while table[index] do
if (item == table[index]) then
return index
end
index = index + 1
end
return false
end
-- maintains an average framerate and item scanning speed
local function UpdateItemsPerFrame()
AVERAGE_FRAMERATE = (AVERAGE_FRAMERATE + GetFramerate()) / 2
local speed = SCAN_SPEED[FinderOptions.speed] or SCAN_SPEED.normal
CACHE_ITEMSPERFRAME = math.ceil(speed / AVERAGE_FRAMERATE)
C_Timer.After(5, UpdateItemsPerFrame)
end
-- event frame setup
local frame = CreateFrame("Frame")
frame:RegisterEvent("ADDON_LOADED")
local handlers = {}
function handlers.ADDON_LOADED(self, ...)
if ... == ADDON then
frame:UnregisterEvent("ADDON_LOADED")
-- Hook up SavedVariable
FinderOptions = FinderOptions or getDefaults("options")
-- Check if we need to do any forced setting upgrades
if not FinderOptions._ver then
-- < v0.1.2, re-set 'speed' opt to normal
FinderOptions.speed = "normal"
FinderOptions._ver = FINDER_VERSION
end
if FinderOptions.greeting == nil then
-- greeting option added in v1.9
FinderOptions.greeting = true
end
if (not (type(FinderCache) == "table")) then
prepareCache()
else
CACHE_IS_PREPARED = true
end
if FinderOptions.greeting then
print(fmsg("|cff9d9d9dby |cffffffffAvael|r |cff9d9d9d@ |cff00ccffHydraxian Waterlords EU |cff9d9d9dhas loaded \\o/"))
end
-- check database version and try to upgrade if possible
local dbOutdated = finder.db.isDatabaseOutdated(FinderCache)
if dbOutdated == 0 then
local tocv = select(4, GetBuildInfo())
if not (tocv == FinderCache.__tocversion) then
-- let player know the database is probably out of date
print(fmsg("|cfff00000Hey, the item cache may be out of date (Major game update?)! You should consider rebuilding it with|r |cffffffff'/finder rebuild'|r"))
elseif (not FinderCache.completedScan) then
-- let the player know there doesn't appear to be any item cache built
print(fmsg("|cfff00000It looks like you have not built the item cache! Try|r |cffffffff'/finder rebuild'|cfff00000 to populate the cache."))
else
if FinderOptions.greeting then
print(fmsg("Item cache looks |cff00f000OK|r."))
end
end
else
-- let the player know the db is incompatible and should be rebuilt.
if dbOutdated < 0 then
print(fmsg("|cfff00000!!Item cache is from an old version of Finder and may not work!|r"))
elseif dbOutdated > 0 then
print(fmsg("|cfff00000!!Item cache is from a future version of Finder and may not work! |cff9d9d9dAre you a time traveler?|r"))
end
print(fmsg("|cfff00000!!Please rebuild (|cffffffff'/finder rebuild'|cfff00000) to build a fresh item cache.|r"))
end
-- start the rate tracker, it'll self-sustain after this call
C_Timer.After(2, UpdateItemsPerFrame)
end
end
function handlers.GET_ITEM_INFO_RECEIVED(self, ...)
local itemID, success = ...
if success then
addOrUpdateCache(itemID)
end
end
frame:SetScript("OnEvent", function(self, event, ...)
if handlers[event] then
handlers[event](self, ...)
end
end)
-- rest of the fucking owl
--------------------------
-- used to prepare the cache structure (after a wipe, fresh install, db failed verification, etc)
function prepareCache()
-- using WoW's wipe() since 'data = {}' simply resets the pointer and the global SavedVariable doesn't actually get wiped
if FinderCache then
wipe(FinderCache)
else
FinderCache = {}
end
finder.db.initNewDB(FinderCache)
FinderCache.completedScan = false
CACHE_IS_PREPARED = true
end
-- add or update an item in the item cache
function addOrUpdateCache(validID)
if not CACHE_IS_PREPARED then
error("Trying to add or update FinderCache before cache has been prepared?! This is an error!")
end
local itemName, itemLink, itemRarity, itemLevel, itemMinLevel, itemType, itemSubType, itemStackCount,
itemEquipLoc, itemIcon, itemSellPrice, itemClassID, itemSubClassID, bindType, expacID, itemSetID,
isCraftingReagent = GetItemInfo(validID)
FinderCache[itemClassID or -1][validID] = itemName
end
-- stop any in-progress cache rebuild
local function stopCacheRebuild()
CACHE_REBUILDING = false
CACHE_STOP_REBUILD = true
hush = false
FinderCache.completedScan = false -- we're in an impartial scan state
end
-- rebuild item cache
local function rebuildCache(startID, endID)
if not CACHE_REBUILDING then
CACHE_STOP_REBUILD = false
local validIDs = {}
for i = startID or 0, endID or CACHE_MAX_ITEMID do
if cItemExists(i) then
tinsert(validIDs, i)
end
end
frame:RegisterEvent("GET_ITEM_INFO_RECEIVED")
CACHE_REBUILDING = 1
local tickerHandle
local lastUpdate = 0
local startedTimer = GetTime()
local itemsTotal = #validIDs
print(fmsg(string.format("Rebuilding item cache... ETA ~%i seconds", itemsTotal / (CACHE_ITEMSPERFRAME * AVERAGE_FRAMERATE))))
print(fmsg(("Type '/finder hush' to disable progress updates for this rebuild. Type '/finder stop' to abort the rebuild.")))
local function worker()
if CACHE_STOP_REBUILD or (not CACHE_REBUILDING) then
tickerHandle:Cancel()
CACHE_STOP_REBUILD = false
CACHE_REBUILDING = false
elseif CACHE_REBUILDING < #validIDs then
local nextBatch = math.min(itemsTotal - CACHE_REBUILDING, CACHE_ITEMSPERFRAME)
-- queries for a batch of items
for i=CACHE_REBUILDING, (CACHE_REBUILDING + nextBatch) - 1 do
GetItemInfo(validIDs[i])
end
CACHE_REBUILDING = CACHE_REBUILDING + nextBatch
if (CACHE_REBUILDING - lastUpdate) >= FinderOptions.progressinterval then
local progress = (CACHE_REBUILDING / itemsTotal)
local itemsRemaining = itemsTotal - CACHE_REBUILDING
local timePerUpdate = (GetTime() - startedTimer) / CACHE_REBUILDING
local estimate = itemsRemaining * timePerUpdate
if not hush then
local msg = ("Rebuild status: %i/%i (%i%%), ~%i seconds remaining"):format(CACHE_REBUILDING - 1, itemsTotal, math.floor(progress*100), estimate )
print(fmsg(msg))
end
lastUpdate = CACHE_REBUILDING
end
else
CACHE_REBUILDING = false
frame:UnregisterEvent("GET_ITEM_INFO_RECEIVED")
hush = false
FinderCache.completedScan = true
FinderCache.__tocversion = select(4, GetBuildInfo())
local msg = ("Finished rebuilding cache! Took: %.0f seconds"):format(((GetTime() - startedTimer)))
print(fmsg(msg))
end
end
tickerHandle = C_Timer.NewTicker(0, worker, itemsTotal) -- runs every frame
end
end
-- print search results
local function printResults(results, hits, searchTime, expired)
local output = DEFAULT_CHAT_FRAME
local timeStr = ("|cff9d9d9d(%ims)|r"):format(math.floor(searchTime) * 1000)
if expired then
-- warn that our search expired and results may be incomplete
local msg = ("(|cfff00000Servers response is slow (>%.1fs), search results may be incomplete. You may want to try again|r)"):format(MAX_WAIT_TIME)
output:AddMessage(msg)
end
if hits == MAX_HITS then
local msg = ("(|cfff00000Hit the result cap of |cff00ccff%i|r, try narrowing down your search!): %s"):format(MAX_HITS, timeStr)
output:AddMessage(msg)
else
output:AddMessage(fmsg(("Found %i hits: %s"):format(hits, timeStr)))
end
for category, data in pairs(results) do
output:AddMessage(("|cffe6cc80%s|r (%i):"):format(GetItemClassInfo(category), data.count))
for k, item in pairs(data.items) do
output:AddMessage((" %s"):format(item.link))
end
end
end
-- perform actual item search
local function findItem(fragment)
if not FinderCache.completedScan then
print(fmsg("(|cfff00000INCOMPLETE or EMPTY ITEMCACHE!|r You should /finder rebuild)"))
end
print(fmsg("Searching for \"".. fragment .."\"..."))
local startTime = GetTime()
local maxhits = 20
local hits = 0
local results = {}
local stop
-- clear the itemQueue table in case it has any previous search queries. Said previous queries will be mercilessly abandoned!
wipe(CACHE_CURRENT_REQUESTS)
for category = 0, #FinderCache do
local items = FinderCache[category]
if stop then
break
else
for id, name in pairs(items) do
if name:lower():find(fragment) then
results[category] = results[category] or {
items = {},
count = 0
}
results[category].count = results[category].count + 1
tinsert(CACHE_CURRENT_REQUESTS, id)
local item = Item:CreateFromItemID(id)
item:ContinueOnItemLoad(function()
local _, link = GetItemInfo(id)
tinsert(results[category].items, {
id = id,
link = item:GetItemLink()
})
local qIndex = tcontains(CACHE_CURRENT_REQUESTS, id)
if qIndex then
tremove(CACHE_CURRENT_REQUESTS, qIndex)
end
end)
hits = hits + 1
if hits >= maxhits then
stop = true
break
end
end
end
end
end
-- only do something if we got >0 results
if hits > 0 then
local triggerTime = GetTime()
local lastPoll = triggerTime
local poller
-- polls the itemQueue until it is either empty or we've exceeded the max wait time
local function pollQueue()
local time = GetTime()
local waited = time - triggerTime
local expired = (waited >= MAX_WAIT_TIME)
if expired or (#CACHE_CURRENT_REQUESTS == 0) then
printResults(results, hits, (time - startTime) - (lastPoll - time), expired)
-- remember to stop the ticker
poller:Cancel()
end
lastPoll = time
end
-- start polling the itemQueue
poller = C_Timer.NewTicker(0.01, pollQueue)
else
print(fmsg("Found nothing at all while searching for \""..fragment.."\""))
end
end
-- print generic help message
local function printHelp()
print(fmsg("Quick help:"))
print(" Search for items using '/find <anything>' or '/search <anything>'")
print(" For example: /find searing arrows")
print(" Results in : " .. "\124cffa335ee\124Hitem:2825::::::::60:::::\124h[Bow of Searing Arrows]\124h\124r")
print(" To configure "..cPurple.."Finder|r, use '/finder <command/option>' instead.")
print(" Notice the difference! |cff9d9d9d/find|r vs |cff9d9d9d/find|cffffffffer|r")
end
-- SlashCMD setup
SLASH_FIND1 = "/find"
SLASH_FIND2 = "/search"
SLASH_FINDER1 = "/finder"
-- SlashCmd handler for triggering a new item search
local function searchHandler(fragment, EditBox)
fragment = strtrim(fragment) -- trim it
fragment = fragment:lower() -- lowercase it
if fragment:match("[^%s]") then
findItem(fragment)
else
printHelp()
end
end
-- SlashCmd handler for interacting with the addon configuration etc, NOT for searching (unless passing the 'search' argument)
local function commandHandler(msg, EditBox)
-- force lowercase all messages
msg = strtrim(msg:lower())
-- split into parts
local args = {}
for v in string.gmatch(msg, "[^ ]+") do
tinsert(args, v)
end
local cmd = args[1]
if not cmd then
printHelp()
return false
end
if cmd == "wipe" then
if confirmWipe then
-- trigger wipe
prepareCache()
PlaySound(5694, "Master")
print(fmsg("Item cache has been wiped! SpooOooky! |cfff90000Start rebuilding it using /finder rebuild|r"))
if confirmTimer then
confirmTimer:Cancel()
end
confirmWipe = false -- reset the confirmation step
else
print(fmsg("You are trying to wipe the Finder item cache. Type '/finder wipe' again within "..WIPE_TIMER_DURATION.." seconds to confirm!"))
confirmWipe = true
confirmTimer = C_Timer.NewTimer(WIPE_TIMER_DURATION, function()
confirmWipe = false
print(fmsg("Wipe timer expired..."))
end)
end
elseif cmd == "wipesettings" then
wipe(FinderOptions)
for k, v in pairs(finder.defaults.options) do
FinderOptions[k] = v
end
print(fmsg("User options been reset"))
elseif cmd == "rebuild" then
rebuildCache(tonumber(args[2]), tonumber(args[3]))
elseif cmd == "search" or cmd == "find" or cmd == "s" then
searchHandler(table.concat(args, " ", 2), EditBox)
elseif cmd == "stop" or cmd == "abort" or cmd == "cancel" then
print(fmsg("Stopping cache rebuild"))
stopCacheRebuild()
elseif cmd == "greeting" then
FinderOptions.greeting = not FinderOptions.greeting
print(fmsg(string.format("Login greeting now %s", FinderOptions.greeting and "enabled." or "disabled.")))
elseif cmd == "set" then
-- we're setting an option!
local name, value = args[2], args[3]
local result
if name and value then
if finder.defaults.options[name] then
local valIsNumber = (type(finder.defaults.options[name]) == "number")
FinderOptions[name] = valIsNumber and tonumber(value) or tostring(value)
result = ("Set option %s to value %s"):format(name, tostring(value))
else
result = ("No such option: %s"):format(name)
end
else
result = ("Missing option or value (You said: /finder set %s %s)"):format(tostring(name), tostring(value))
end
print(fmsg(result))
elseif cmd == "hush" or cmd == "shutup" then
hush = not hush
print(fmsg(("is now %s"):format(hush and ("|cff808080v e r y q u i e t|r") or "|cff808080talkative again...|r")))
elseif cmd == "status" then
if (not FinderCache.completedScan) then
print(fmsg("Item cache is |cfff00000invalid|r, you should |cff808080/finder rebuild|r it."))
else
print(fmsg("Item cache looks |cff00f000OK|r."))
end
else
-- trap unknown commands and trigger help
if msg ~= "" then
print(fmsg("Unknown command \"".. msg .."\", did you mean to use |cff9d9d9d/find|r or |cff9d9d9d/search|r instead?"))
end
printHelp()
end
end
SlashCmdList["FINDER"] = commandHandler
SlashCmdList["FIND"] = searchHandler |
-- Generated by CSharp.lua Compiler
local System = System
local SystemNumerics
System.import(function (out)
SystemNumerics = System.Numerics
end)
System.namespace("Slipe.Shared.GameWorld", function (namespace)
-- <summary>
-- Struct to define different heat haze properties in the GTA world
-- </summary>
namespace.struct("HeatHaze", function (namespace)
local FromRaw, class, internal, __ctor1__, __ctor2__
internal = function (this)
this.ScanSize = System.default(SystemNumerics.Vector2)
this.RenderSize = System.default(SystemNumerics.Vector2)
end
-- <summary>
-- Create a heat haze struct
-- </summary>
__ctor1__ = function (this, intensity, randomShift, speedMin, speedMax, scanSize, renderSize, showInside)
internal(this)
if intensity == nil then
return
end
this.Intensity = intensity
this.RandomShift = randomShift
this.SpeedMin = speedMin
this.SpeedMax = speedMax
this.ScanSize = scanSize:__clone__()
this.RenderSize = renderSize:__clone__()
this.ShowInside = showInside
end
-- <summary>
-- Heat haze with optional paramters as default
-- </summary>
__ctor2__ = function (this, intensity, randomShift, speedMin, speedMax)
__ctor1__(this, intensity, randomShift, speedMin, speedMax, SystemNumerics.Vector2(75, 80), SystemNumerics.Vector2(80, 85), false)
end
-- <summary>
-- Creates a heat haze from the raw MTA function output
-- </summary>
FromRaw = function (raw)
return class(raw[1], raw[2], raw[3], raw[4], SystemNumerics.Vector2(raw[5], raw[6]), SystemNumerics.Vector2(raw[7], raw:getRest()[1]), raw:getRest()[2])
end
class = {
Intensity = 0,
RandomShift = 0,
SpeedMin = 0,
SpeedMax = 0,
ShowInside = false,
FromRaw = FromRaw,
__ctor__ = {
__ctor1__,
__ctor2__
},
__metadata__ = function (out)
return {
properties = {
{ "Intensity", 0x6, System.Int32 },
{ "RandomShift", 0x6, System.Int32 },
{ "RenderSize", 0x6, System.Numerics.Vector2 },
{ "ScanSize", 0x6, System.Numerics.Vector2 },
{ "ShowInside", 0x6, System.Boolean },
{ "SpeedMax", 0x6, System.Int32 },
{ "SpeedMin", 0x6, System.Int32 }
},
methods = {
{ ".ctor", 0x706, __ctor1__, System.Int32, System.Int32, System.Int32, System.Int32, System.Numerics.Vector2, System.Numerics.Vector2, System.Boolean },
{ ".ctor", 0x406, __ctor2__, System.Int32, System.Int32, System.Int32, System.Int32 },
{ "FromRaw", 0x18E, FromRaw, System.Tuple, class }
}
}
end
}
return class
end)
end)
|
local M = {}
M.view = require('guihua.view')
M.listview = require('guihua.listview')
M.setup = function(opts)
require('guihua.maps').setup(opts)
end
return M
|
local _, private = ...
if private.isClassic then return end
-- [[ Lua Globals ]]
-- luacheck: globals select
-- [[ Core ]]
local Aurora = private.Aurora
local Hook, Skin = Aurora.Hook, Aurora.Skin
local Util = Aurora.Util
do --[[ FrameXML\WorldMapFrame.lua ]]
do --[[ FrameXML\WorldMapBountyBoard.lua ]]
Hook.WorldMapBountyBoardMixin = {}
function Hook.WorldMapBountyBoardMixin:TryShowingIntroTutorial()
if self.TutorialBox.activeTutorial == _G.LE_FRAME_TUTORIAL_BOUNTY_INTRO then
if self:GetDisplayLocation() == _G.LE_MAP_OVERLAY_DISPLAY_LOCATION_TOP_RIGHT or self:GetDisplayLocation() == _G.LE_MAP_OVERLAY_DISPLAY_LOCATION_BOTTOM_RIGHT then
Skin.GlowBoxArrowTemplate(self.TutorialBox.Arrow, "Right")
else
Skin.GlowBoxArrowTemplate(self.TutorialBox.Arrow, "Left")
end
end
end
function Hook.WorldMapBountyBoardMixin:TryShowingCompletionTutorial()
if self.TutorialBox.activeTutorial == _G.LE_FRAME_TUTORIAL_BOUNTY_FINISHED then
Skin.GlowBoxArrowTemplate(self.TutorialBox.Arrow, "Down")
end
end
end
end
do --[[ FrameXML\WorldMapFrame.xml ]]
do --[[ FrameXML\WorldMapFrameTemplates.xml ]]
function Skin.WorldMapBountyBoardTemplate(Frame)
if not private.isPatch then
Skin.GlowBoxFrame(Frame.TutorialBox, "Right")
end
end
function Skin.WorldMapActionButtonTemplate(Frame)
end
end
end
function private.FrameXML.WorldMapFrame()
----====####$$$$%%%%%$$$$####====----
-- WorldMapBountyBoard --
----====####$$$$%%%%%$$$$####====----
Util.Mixin(_G.WorldMapBountyBoardMixin, Hook.WorldMapBountyBoardMixin)
----====####$$$$%%%%$$$$####====----
-- WorldMapActionButton --
----====####$$$$%%%%$$$$####====----
----====####$$$$%%%%$$$$####====----
-- WorldMapPOIQuantizer --
----====####$$$$%%%%$$$$####====----
----====####$$$$%%%%%$$$$####====----
-- WorldMapFrame --
----====####$$$$%%%%%$$$$####====----
----====####$$$$%%%%$$$$####====----
-- WorldMapFrameTemplates --
----====####$$$$%%%%$$$$####====----
end
|
-- // FileName: ChatServiceRunner.lua
-- // Written by: Xsitsu
-- // Description: Main script to initialize ChatService and run ChatModules.
local EventFolderName = "DefaultChatSystemChatEvents"
local EventFolderParent = game:GetService("ReplicatedStorage")
local modulesFolder = script
local PlayersService = game:GetService("Players")
local RunService = game:GetService("RunService")
local Chat = game:GetService("Chat")
local ChatService = require(modulesFolder:WaitForChild("ChatService"))
local ReplicatedModules = Chat:WaitForChild("ClientChatModules")
local ChatSettings = require(ReplicatedModules:WaitForChild("ChatSettings"))
local ChatLocalization = nil
pcall(function() ChatLocalization = require(Chat.ClientChatModules.ChatLocalization) end)
if ChatLocalization == nil then ChatLocalization = { Get = function(key,default) return default end } end
local useEvents = {}
local EventFolder = EventFolderParent:FindFirstChild(EventFolderName)
if EventFolder then
EventFolder:Destroy()
EventFolder = nil
end
if (not EventFolder) then
EventFolder = Instance.new("Folder")
EventFolder.Name = EventFolderName
EventFolder.Archivable = false
EventFolder.Parent = EventFolderParent
end
--// No-opt connect Server>Client RemoteEvents to ensure they cannot be called
--// to fill the remote event queue.
local function emptyFunction()
--intentially empty
end
local function GetObjectWithNameAndType(parentObject, objectName, objectType)
for _, child in pairs(parentObject:GetChildren()) do
if (child:IsA(objectType) and child.Name == objectName) then
return child
end
end
return nil
end
local function CreateIfDoesntExist(parentObject, objectName, objectType)
local obj = GetObjectWithNameAndType(parentObject, objectName, objectType)
if (not obj) then
obj = Instance.new(objectType)
obj.Name = objectName
obj.Parent = parentObject
end
useEvents[objectName] = obj
return obj
end
--// All remote events will have a no-opt OnServerEvent connecdted on construction
local function CreateEventIfItDoesntExist(parentObject, objectName)
local obj = CreateIfDoesntExist(parentObject, objectName, "RemoteEvent")
obj.OnServerEvent:Connect(emptyFunction)
return obj
end
CreateEventIfItDoesntExist(EventFolder, "OnNewMessage")
CreateEventIfItDoesntExist(EventFolder, "OnMessageDoneFiltering")
CreateEventIfItDoesntExist(EventFolder, "OnNewSystemMessage")
CreateEventIfItDoesntExist(EventFolder, "OnChannelJoined")
CreateEventIfItDoesntExist(EventFolder, "OnChannelLeft")
CreateEventIfItDoesntExist(EventFolder, "OnMuted")
CreateEventIfItDoesntExist(EventFolder, "OnUnmuted")
CreateEventIfItDoesntExist(EventFolder, "OnMainChannelSet")
CreateEventIfItDoesntExist(EventFolder, "ChannelNameColorUpdated")
CreateEventIfItDoesntExist(EventFolder, "SayMessageRequest")
CreateEventIfItDoesntExist(EventFolder, "SetBlockedUserIdsRequest")
CreateIfDoesntExist(EventFolder, "GetInitDataRequest", "RemoteFunction")
CreateIfDoesntExist(EventFolder, "MutePlayerRequest", "RemoteFunction")
CreateIfDoesntExist(EventFolder, "UnMutePlayerRequest", "RemoteFunction")
EventFolder = useEvents
local function CreatePlayerSpeakerObject(playerObj)
--// If a developer already created a speaker object with the
--// name of a player and then a player joins and tries to
--// take that name, we first need to remove the old speaker object
local speaker = ChatService:GetSpeaker(playerObj.Name)
if (speaker) then
ChatService:RemoveSpeaker(playerObj.Name)
end
speaker = ChatService:InternalAddSpeakerWithPlayerObject(playerObj.Name, playerObj, false)
for _, channel in pairs(ChatService:GetAutoJoinChannelList()) do
speaker:JoinChannel(channel.Name)
end
speaker:InternalAssignEventFolder(EventFolder)
speaker.ChannelJoined:connect(function(channel, welcomeMessage)
local log = nil
local channelNameColor = nil
local channelObject = ChatService:GetChannel(channel)
if (channelObject) then
log = channelObject:GetHistoryLogForSpeaker(speaker)
channelNameColor = channelObject.ChannelNameColor
end
EventFolder.OnChannelJoined:FireClient(playerObj, channel, welcomeMessage, log, channelNameColor)
end)
speaker.Muted:connect(function(channel, reason, length)
EventFolder.OnMuted:FireClient(playerObj, channel, reason, length)
end)
speaker.Unmuted:connect(function(channel)
EventFolder.OnUnmuted:FireClient(playerObj, channel)
end)
ChatService:InternalFireSpeakerAdded(speaker.Name)
end
EventFolder.SayMessageRequest.OnServerEvent:connect(function(playerObj, message, channel)
if type(message) ~= "string" then
return
end
if type(channel) ~= "string" then
return
end
local speaker = ChatService:GetSpeaker(playerObj.Name)
if (speaker) then
return speaker:SayMessage(message, channel)
end
return nil
end)
EventFolder.MutePlayerRequest.OnServerInvoke = function(playerObj, muteSpeakerName)
if type(muteSpeakerName) ~= "string" then
return
end
local speaker = ChatService:GetSpeaker(playerObj.Name)
if speaker then
local muteSpeaker = ChatService:GetSpeaker(muteSpeakerName)
if muteSpeaker then
speaker:AddMutedSpeaker(muteSpeaker.Name)
return true
end
end
return false
end
EventFolder.UnMutePlayerRequest.OnServerInvoke = function(playerObj, unmuteSpeakerName)
if type(unmuteSpeakerName) ~= "string" then
return
end
local speaker = ChatService:GetSpeaker(playerObj.Name)
if speaker then
local unmuteSpeaker = ChatService:GetSpeaker(unmuteSpeakerName)
if unmuteSpeaker then
speaker:RemoveMutedSpeaker(unmuteSpeaker.Name)
return true
end
end
return false
end
-- Map storing Player -> Blocked user Ids.
local BlockedUserIdsMap = {}
PlayersService.PlayerAdded:connect(function(newPlayer)
for player, blockedUsers in pairs(BlockedUserIdsMap) do
local speaker = ChatService:GetSpeaker(player.Name)
if speaker then
for i = 1, #blockedUsers do
local blockedUserId = blockedUsers[i]
if blockedUserId == newPlayer.UserId then
speaker:AddMutedSpeaker(newPlayer.Name)
end
end
end
end
end)
PlayersService.PlayerRemoving:connect(function(removingPlayer)
BlockedUserIdsMap[removingPlayer] = nil
end)
EventFolder.SetBlockedUserIdsRequest.OnServerEvent:connect(function(player, blockedUserIdsList)
if type(blockedUserIdsList) ~= "table" then
return
end
BlockedUserIdsMap[player] = blockedUserIdsList
local speaker = ChatService:GetSpeaker(player.Name)
if speaker then
for i = 1, #blockedUserIdsList do
if type(blockedUserIdsList[i]) == "number" then
local blockedPlayer = PlayersService:GetPlayerByUserId(blockedUserIdsList[i])
if blockedPlayer then
speaker:AddMutedSpeaker(blockedPlayer.Name)
end
end
end
end
end)
EventFolder.GetInitDataRequest.OnServerInvoke = (function(playerObj)
local speaker = ChatService:GetSpeaker(playerObj.Name)
if not (speaker and speaker:GetPlayer()) then
CreatePlayerSpeakerObject(playerObj)
speaker = ChatService:GetSpeaker(playerObj.Name)
end
local data = {}
data.Channels = {}
data.SpeakerExtraData = {}
for _, channelName in pairs(speaker:GetChannelList()) do
local channelObj = ChatService:GetChannel(channelName)
if (channelObj) then
local channelData =
{
channelName,
channelObj:GetWelcomeMessageForSpeaker(speaker),
channelObj:GetHistoryLogForSpeaker(speaker),
channelObj.ChannelNameColor,
}
table.insert(data.Channels, channelData)
end
end
for _, oSpeakerName in pairs(ChatService:GetSpeakerList()) do
local oSpeaker = ChatService:GetSpeaker(oSpeakerName)
data.SpeakerExtraData[oSpeakerName] = oSpeaker.ExtraData
end
return data
end)
local function DoJoinCommand(speakerName, channelName, fromChannelName)
local speaker = ChatService:GetSpeaker(speakerName)
local channel = ChatService:GetChannel(channelName)
if (speaker) then
if (channel) then
if (channel.Joinable) then
if (not speaker:IsInChannel(channel.Name)) then
speaker:JoinChannel(channel.Name)
else
speaker:SetMainChannel(channel.Name)
speaker:SendSystemMessage(
string.gsub(
ChatLocalization:Get(
"GameChat_SwitchChannel_NowInChannel",
string.format("You are now chatting in channel: '%s'", channel.Name)
),
"{RBX_NAME}",channel.Name),
channel.Name
)
end
else
speaker:SendSystemMessage(
string.gsub(
ChatLocalization:Get(
"GameChat_ChatServiceRunner_YouCannotJoinChannel",
("You cannot join channel '" .. channelName .. "'.")
),
"{RBX_NAME}",channelName),
fromChannelName
)
end
else
speaker:SendSystemMessage(
string.gsub(
ChatLocalization:Get(
"GameChat_ChatServiceRunner_ChannelDoesNotExist",
("Channel '" .. channelName .. "' does not exist.")
),
"{RBX_NAME}",channelName),
fromChannelName
)
end
end
end
local function DoLeaveCommand(speakerName, channelName, fromChannelName)
local speaker = ChatService:GetSpeaker(speakerName)
local channel = ChatService:GetChannel(channelName)
if (speaker) then
if (speaker:IsInChannel(channelName)) then
if (channel.Leavable) then
speaker:LeaveChannel(channel.Name)
speaker:SendSystemMessage(
string.gsub(
ChatLocalization:Get(
"GameChat_ChatService_YouHaveLeftChannel",
string.format("You have left channel '%s'", channelName)
),
"{RBX_NAME}",channel.Name),
"System"
)
else
speaker:SendSystemMessage(
string.gsub(
ChatLocalization:Get(
"GameChat_ChatServiceRunner_YouCannotLeaveChannel",
("You cannot leave channel '" .. channelName .. "'.")
),
"{RBX_NAME}",channelName),
fromChannelName
)
end
else
speaker:SendSystemMessage(
string.gsub(
ChatLocalization:Get(
"GameChat_ChatServiceRunner_YouAreNotInChannel",
("You are not in channel '" .. channelName .. "'.")
),
"{RBX_NAME}",channelName),
fromChannelName
)
end
end
end
ChatService:RegisterProcessCommandsFunction("default_commands", function(fromSpeaker, message, channel)
if (string.sub(message, 1, 6):lower() == "/join ") then
DoJoinCommand(fromSpeaker, string.sub(message, 7), channel)
return true
elseif (string.sub(message, 1, 3):lower() == "/j ") then
DoJoinCommand(fromSpeaker, string.sub(message, 4), channel)
return true
elseif (string.sub(message, 1, 7):lower() == "/leave ") then
DoLeaveCommand(fromSpeaker, string.sub(message, 8), channel)
return true
elseif (string.sub(message, 1, 3):lower() == "/l ") then
DoLeaveCommand(fromSpeaker, string.sub(message, 4), channel)
return true
elseif (string.sub(message, 1, 3) == "/e " or string.sub(message, 1, 7) == "/emote ") then
-- Just don't show these in the chatlog. The animation script listens on these.
return true
end
return false
end)
if ChatSettings.GeneralChannelName and ChatSettings.GeneralChannelName ~= "" then
local allChannel = ChatService:AddChannel(ChatSettings.GeneralChannelName)
allChannel.Leavable = false
allChannel.AutoJoin = true
allChannel:RegisterGetWelcomeMessageFunction(function(speaker)
if RunService:IsStudio() then
return nil
end
local player = speaker:GetPlayer()
if player then
local success, canChat = pcall(function()
return Chat:CanUserChatAsync(player.UserId)
end)
if success and not canChat then
return ""
end
end
end)
end
local systemChannel = ChatService:AddChannel("System")
systemChannel.Leavable = false
systemChannel.AutoJoin = true
systemChannel.WelcomeMessage = ChatLocalization:Get(
"GameChat_ChatServiceRunner_SystemChannelWelcomeMessage", "This channel is for system and game notifications."
)
systemChannel.SpeakerJoined:connect(function(speakerName)
systemChannel:MuteSpeaker(speakerName)
end)
local function TryRunModule(module)
if module:IsA("ModuleScript") then
local ret = require(module)
if (type(ret) == "function") then
ret(ChatService)
end
end
end
local modules = Chat:WaitForChild("ChatModules")
modules.ChildAdded:connect(function(child)
local success, returnval = pcall(TryRunModule, child)
if not success and returnval then
print("Error running module " ..child.Name.. ": " ..returnval)
end
end)
for _, module in pairs(modules:GetChildren()) do
local success, returnval = pcall(TryRunModule, module)
if not success and returnval then
print("Error running module " ..module.Name.. ": " ..returnval)
end
end
PlayersService.PlayerRemoving:connect(function(playerObj)
if (ChatService:GetSpeaker(playerObj.Name)) then
ChatService:RemoveSpeaker(playerObj.Name)
end
end)
|
--- === cp.ui.Row ===
---
--- Represents an `AXRow` `axuielement`.
local ax = require "cp.fn.ax"
local Element = require "cp.ui.Element"
local pack = table.pack
local Row = Element:subclass("cp.ui.Row")
:defineBuilder("containing")
--- === cp.ui.Row.Builder ===
---
--- Defines a `Row` builder.
--- cp.ui.Row:containing(...) -> cp.ui.Row.Builder
--- Function
--- Returns a `Builder` with the `Element` initializers for the items in the row.
---
--- Parameters:
--- * ... - A variable list of `Element` initializers, one for each item.
---
--- Returns:
--- * The `Row.Builder`
--- cp.ui.Row.matches(element) -> boolean
--- Method
--- Checks if the element is a `Row`.
---
--- Parameters:
--- * element - the `axuielement` to check.
---
--- Returns:
--- * `true` if it matches, otherwise `false`.
Row.static.matches = ax.matchesIf(Element.matches, ax.hasRole "AXRow")
--- cp.ui.Row(parent, uiFinder, ...) -> cp.ui.Row
--- Constructor
--- Creates a new `Row` instance with the specified `parent` and `uiFinder`.
---
--- Parameters:
--- * parent - the parent `Element`.
--- * uiFinder - a `function` or `cp.prop` containing the `axuielement`
--- * ... - a variable list of `Element` initializers, one for each item in the row.
---
--- Returns:
--- * The new `Row`.
function Row:initialize(parent, uiFinder, ...)
Element.initialize(self, parent, uiFinder)
self.childInits = pack(...)
end
--- cp.ui.Row.childrenUI <cp.prop: table of axuielement>
--- Field
--- Contains the list of `axuielement` children of the row.
function Row.lazy.prop:childrenUI()
return ax.prop(self.UI, "AXChildren")
end
--— cp.ui.Row.children <table of cp.ui.Element>
--— Field
--— A table of child `Element`s for the `Row`.
function Row.lazy.value:children()
return ax.initElements(self, self.childrenUI, self.childInits)
end
--- cp.ui.Row.disclosing <cp.prop: boolean>
--- Field
--- Indicates if the `Row` is disclosing other `Rows`.
function Row.lazy.prop:disclosing()
return ax.prop(self.UI, "AXDisclosing", true)
end
--- cp.ui.Row.disclosureLevel <cp.prop: number; read-only>
--- Field
--- The depth of disclosure. `0` is the top level.
function Row.lazy.prop:disclosureLevel()
return ax.prop(self.UI, "AXDisclosureLevel")
end
--- cp.ui.Row:disclosedByRow() -> cp.ui.Row
--- Method
--- The `Row` which is disclosing this `Row`.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A `cp.ui.Row` object
function Row.lazy.prop:disclosedByRow()
return ax.prop(self.UI, "AXDisclosedByRow"):mutate(function(original)
return self:parent():fetchRow(original())
end)
end
--- cp.ui.Row:disclosedRows() -> table of cp.ui.Row or nil
--- Method
--- If available, returns a table of [Row](cp.ui.Row.md)s that are disclosed by this `Row`.
--- If this row is currently unavailable, `nil` is returned.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `table` of Rows, or `nil`.
function Row:disclosedRows()
local ui = self:UI()
if ui then
local rowsUI = ui:attributeValue("AXDisclosedRows")
if rowsUI then
return self:parent():fetchRows(rowsUI)
end
end
end
--- cp.ui.Row.selected <cp.prop: boolean>
--- Field
--- Indicates if the row is currently selected. May be set.
function Row.lazy.prop:selected()
return ax.prop(self.UI, "AXSelected", true)
end
--- cp.ui.Row.index <cp.prop: number; read-only>
--- Field
--- The numeric index of this row in the overall container, with `0` being the first item.
function Row.lazy.prop:index()
return ax.prop(self.UI, "AXIndex")
end
-- cp.ui.Row:__eq(other) -> boolean
-- Function
-- Checks if the two items are Rows with identical `axuielement`s, and both not `nil`.
function Row:__eq(other)
local ui = self:UI()
return ui ~= nil and other.UI and ui == other:UI()
end
return Row
|
---------------------------------------------------------------------
-- Project: irc
-- Author: MCvarial
-- Contact: [email protected]
-- Version: 1.0.3
-- Date: 31.10.2010
---------------------------------------------------------------------
------------------------------------
-- Commands
------------------------------------
addCommandHandler("servers",
function (source)
if source ~= getElementsByType("console")[1] then return end
local servers = ircGetServers()
for i,server in ipairs (servers) do
servers[i] = ircGetServerName(server)
end
outputServerLog("IRC: servers: "..table.concat(servers,", "))
end
)
addCommandHandler("channels",
function (source)
if source ~= getElementsByType("console")[1] then return end
local channels = ircGetChannels()
for i,channel in ipairs (channels) do
channels[i] = ircGetChannelName(channel)
end
outputServerLog("IRC: channels: "..table.concat(channels,", "))
end
)
addCommandHandler("users",
function (source)
if source ~= getElementsByType("console")[1] then return end
local users = ircGetUsers()
for i,user in ipairs (users) do
users[i] = ircGetUserNick(user)
end
outputServerLog("IRC: users: "..table.concat(users,", "))
end
)
addCommandHandler("ircsay",
function (source,cmd,...)
accountID = exports.server:getPlayerAccountID(source)
if accountID and not (exports.DENmysql:querySingle("SELECT * FROM mutes WHERE userid='"..accountID.."'")) then
local msg = {...}
if msg then
outputIRC(getPlayerName(source)..": "..table.concat(msg," "))
else
outputChatBox("IRC: syntax is /ircsay <message>",source,255,0,0)
end
end
end
)
addCommandHandler("level",
function (source,cmd,username,channelname)
if source ~= getElementsByType("console")[1] then return end
if username and channelname then
local user = ircGetUserFromNick(username)
local channel = ircGetChannelFromName(channelname)
if user then
outputServerLog("IRC: level "..username..": "..ircGetUserLevel(user,channel))
else
outputServerLog("IRC: user not found!")
end
else
outputServerLog("IRC: syntax: /level <name> <channel>")
end
end
) |
local M = {}
function M.setup()
local snip = require('luasnip')
local cmp = require('cmp')
local has_words_before = function()
local line, col = unpack(vim.api.nvim_win_get_cursor(0))
return col ~= 0 and
vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col)
:match("%s") == nil
end
cmp.setup({
experimental = { ghost_text = false, custom_menu = true },
documentation = {
border = { '╭', '─', '╮', '│', '╯', '─', '╰', '│' }
},
snippet = {
expand = function(args)
snip.lsp_expand(args.body)
end
},
mapping = {
-- ['<Tab>'] = cmp.mapping.select_next_item(),
['<Tab>'] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif snip.expand_or_jumpable() then
snip.expand_or_jump()
elseif has_words_before() then
cmp.complete()
else
fallback()
end
end),
['<S-Tab>'] = cmp.mapping.select_prev_item(),
['<CR>'] = cmp.mapping.confirm({
behavior = cmp.ConfirmBehavior.Replace,
select = false
})
},
sources = {
{ name = 'nvim_lsp' },
{ name = 'luasnip', options = { use_show_condition = false } }
}
})
end
return M
|
-- Generated by CSharp.lua Compiler
local System = System
local SlipeMtaDefinitions
local SystemNumerics
System.import(function (out)
SlipeMtaDefinitions = Slipe.MtaDefinitions
SystemNumerics = System.Numerics
end)
System.namespace("Slipe.Client.Vehicles", function (namespace)
-- <summary>
-- Represents a "dummy" part of a vehicle model
-- </summary>
namespace.class("VehicleModelDummy", function (namespace)
local getPosition, setPosition, __ctor__
__ctor__ = function (this, model, dummyName)
this.model = model
this.dummyName = dummyName
end
getPosition = function (this)
local r = SlipeMtaDefinitions.MtaClient.GetVehicleModelDummyPosition(this.model.Id, this.dummyName)
return SystemNumerics.Vector3(r[1], r[2], r[3])
end
setPosition = function (this, value)
SlipeMtaDefinitions.MtaClient.SetVehicleModelDummyPosition(this.model.Id, this.dummyName, value.X, value.Y, value.Z)
end
return {
getPosition = getPosition,
setPosition = setPosition,
__ctor__ = __ctor__,
__metadata__ = function (out)
return {
fields = {
{ "dummyName", 0x1, System.String },
{ "model", 0x1, out.Slipe.Client.Vehicles.VehicleModel }
},
properties = {
{ "Position", 0x106, System.Numerics.Vector3, getPosition, setPosition }
},
methods = {
{ ".ctor", 0x204, nil, out.Slipe.Client.Vehicles.VehicleModel, System.String }
},
class = { 0x6 }
}
end
}
end)
end)
|
fx_version 'cerulean'
game 'gta5'
ui_page 'html/index.html'
files {
'html/index.html',
'html/styles.css',
'html/script.js'
}
client_script 'client.lua' |
function AddActionDM( Name, Do, AdminBool, LocalPlayerBool )
local tabl = {
name = Name,
action = Do,
admin = AdminBool,
localplayer = LocalPlayerBool,
}
table.Add( DMCommandsTable, { tabl } )
end // Lightweight system
local color_white = Color(255,255,255)
function GMopenTab()
menuTab = vgui.Create( 'DPanel' )
menuTab:SetSize( math.min( ScrW() - 10, 1000 ), math.min( ScrH() - 6, 640 ) )
menuTab:Center()
menuTab:MakePopup()
menuTab:SetKeyBoardInputEnabled( false )
menuTab.Paint = function( self, w, h )
draw.OutlinedBox( 0, 0, w, h, DMColor.frame_background, DMColor.frame_outlined ) -- Background
draw.OutlinedBox( 0, 0, w, 70, DMColor.frame_bar, Color(0, 0, 0) ) -- Bar
end
local main_panel = vgui.Create( 'DPanel', menuTab )
main_panel:Dock( FILL )
main_panel:DockMargin( 8, 78, 8, 8 )
main_panel.Paint = function( self, w, h )
draw.Blur( self )
end
local Title = 'Deathmatch'
surface.SetFont( 'Tab.1' )
local TitleLabel = vgui.Create( 'DLabel', menuTab )
TitleLabel:SetPos( menuTab:GetWide() * 0.5 - surface.GetTextSize( Title ) * 0.5, 10 )
TitleLabel:SetSize( menuTab:GetWide(), 50 )
TitleLabel:SetText( Title )
TitleLabel:SetFont( 'Tab.1' )
TitleLabel:SetTextColor( DMColor.label_text )
local sp = vgui.Create( 'dm_scrollpanel', main_panel )
sp:Dock( FILL )
sp.Paint = nil
surface.SetFont( 'Tab.2' )
local infoButton = vgui.Create( 'dm_button', sp )
infoButton:SetTall( 30 )
infoButton:Dock( TOP )
infoButton:SetText( '' )
infoButton.Paint = function( self, w, h )
local kd = LANG.GetTranslation( 'kd' )
draw.SimpleText( LANG.GetTranslation( 'nick' ), 'Tab.2', 10, 0, DMColor.label_text )
draw.SimpleText( LANG.GetTranslation( 'ping' ), 'Tab.2', w - surface.GetTextSize( 'Ping' ) - 10, 0, DMColor.label_text )
draw.SimpleText( kd, 'Tab.2', w * 0.5 - surface.GetTextSize( kd ) * 0.5, 0, DMColor.label_text )
end
for k, v in pairs( player.GetAll() ) do
local playerAvatar
local playerAvatarButton
local playerButtonM = vgui.Create( 'dm_button', sp )
playerButtonM:SetTall( 40 )
playerButtonM:Dock( TOP )
playerButtonM:DockMargin( 0, 5, 0, 0 )
playerButtonM:SetText( '' )
local playerButton = vgui.Create( 'dm_button', playerButtonM )
playerButton:Dock( FILL )
playerButton:SetText( '' )
playerButton.Paint = function( self, w, h )
if ( IsValid( v ) ) then
local x
local textColor = DMColor.label_text
if ( self:IsHovered() or playerAvatarButton:IsHovered() ) then
playerAvatar:SetVisible( true )
x = 35
else
playerAvatar:SetVisible( false )
x = 0
end
local name = v:GetNick()
if ( name == nil ) then
name = v:Name()
end
draw.SimpleText( name, 'Button', 12 + x, 11, textColor )
draw.SimpleText( v:Ping() or '', 'Button', w - surface.GetTextSize( v:Ping() or '' ) - 12, 11, textColor )
local frags = v:GetFrags()
local deaths = v:GetDeaths()
if ( deaths < 1 ) then
deaths = 1
elseif ( deaths == 1 ) then
death = 1.5
end
local text = string.sub( frags / deaths, 0, 6 ) .. ' (' .. frags .. '/' .. deaths .. ')' or ''
draw.SimpleText( text, 'Button', w * 0.5 - surface.GetTextSize( text ) * 0.5, 11, textColor )
end
end
playerButton.DoClick = function()
surface.PlaySound( 'UI/buttonclickrelease.wav' )
main_panel:Clear()
surface.SetFont( 'Tab.1' )
local nick = v:GetNick() or ''
local txt = '< ' .. nick .. ' >'
TitleLabel:SetText( txt )
local w = main_panel:GetWide()
local leftPanel = vgui.Create( 'DPanel', main_panel )
leftPanel:Dock( LEFT )
leftPanel:SetWide( w / 3.2 )
leftPanel.Paint = nil
local btn_return = vgui.Create( 'dm_button', leftPanel )
btn_return:Dock( TOP )
btn_return:SetTall( 40 )
btn_return:SetText( LANG.GetTranslation( 'backList' ) )
btn_return.DoClick = function()
menuTab:Remove()
GMopenTab()
end
local playerPrev = vgui.Create( 'DModelPanel', leftPanel )
playerPrev:Dock( FILL )
playerPrev:DockMargin( 0, 4, 0, 0 )
playerPrev:SetModel( v:GetModel() or 'models/player/alyx.mdl' )
playerPrev:SetCamPos( Vector( 45, 15, 45 ) )
playerPrev:SetFOV( 58 )
playerPrev.LayoutEntity = function( Entity )
return
end
function playerPrev.Entity:GetPlayerColor()
return v:GetPlayerColor()
end
local playerPrev_panel2 = vgui.Create( 'DPanel', playerPrev )
playerPrev_panel2:Dock( FILL )
playerPrev_panel2.Paint = function( self, w, h )
draw.OutlinedBox( 0, 0, w, h, DMColor.clear, DMColor.frame_bar, 6 )
end
local scrollpanel = vgui.Create( 'dm_scrollpanel', main_panel )
scrollpanel:Dock( RIGHT )
scrollpanel:SetWide( w - leftPanel:GetWide() - 10 )
local firstk = true
for l, n in pairs( DMCommandsTable ) do
if ( not n.localplayer ) then
cmdButton = vgui.Create( 'dm_button', scrollpanel )
cmdButton:Dock( TOP )
cmdButton:SetText( '' )
if ( not firstk ) then
cmdButton:DockMargin( 0, 5, 0, 0 )
else
firstk = not firstk
end
cmdButton:SetTall( 40 )
cmdButton.PaintOver = function( self, w, h )
draw.SimpleText( n.name, 'Button', w * 0.5, h * 0.5, color_white, 1, 1 )
if ( n.admin ) then
draw.SimpleText( LANG.GetTranslation( 'admin' ), 'Button', 12, h * 0.5, color_white, 0, 1 )
end
end
cmdButton.DoClick = function()
surface.PlaySound( 'UI/buttonclickrelease.wav' )
if ( n.admin ) then
if ( LocalPlayer():Admin() ) then
n.action( v )
else
ChatTextAdmin( LANG.GetTranslation( 'notAdmin' ) )
end
else
n.action( v )
end
end
end
end
end
playerAvatar = vgui.Create( 'dm_avatar', playerButton )
playerAvatar:SetSize( 28, 28 )
playerAvatar:SetPos( 10, 6 )
playerAvatar:SetPlayer( v )
playerAvatarButton = vgui.Create( 'dm_button', playerAvatar )
playerAvatarButton:Dock( FILL )
playerAvatarButton:SetText( '' )
playerAvatarButton.Paint = function( self, w, h )
if ( self:IsHovered() ) then
draw.RoundedBox( 100, 0, 0, w, h, Color(0, 0, 0, 40) )
end
end
playerAvatarButton.DoClick = function()
local DM = DermaMenu()
local steamid = v:SteamID()
local steamid64 = v:SteamID64() or 'NULL'
local name = v:GetNWString( 'ply_name' )
local rank = v:GetRank()
local copy = LANG.GetTranslation( 'copied' )
DM:AddOption( name, function()
textCopy( name )
end ):SetIcon( 'icon16/emoticon_happy.png' )
DM:AddOption( 'SteamID: ' .. steamid, function()
textCopy( steamid )
end ):SetIcon( 'icon16/sport_8ball.png' )
DM:AddOption( 'SteamID64: ' .. steamid64, function()
textCopy( steamid64 )
end ):SetIcon( 'icon16/sport_8ball.png' )
DM:AddOption( LANG.GetTranslation( 'rank' ) .. ': ' .. rank, function()
textCopy( rank )
end ):SetIcon( 'icon16/user_suit.png' )
DM:Open()
end
end
end
function GM:ScoreboardShow()
if ( not IsValid( menuTab ) ) then
GMopenTab()
else
menuTab:SetVisible( true )
end
end
function GM:ScoreboardHide()
menuTab:SetVisible( false )
-- menuTab:Remove() // Required for tests
end
|
ITEM.name = "Гитара"
ITEM.desc = "\n\nХАРАКТЕРИСТИКИ: \n-повседневное применение"
ITEM.price = 1270
ITEM.exRender = false
ITEM.weight = 0.47
ITEM.model = "models/kek1ch/dev_guitar.mdl"
ITEM.width = 2
ITEM.height = 2
ITEM.iconCam = {
pos = Vector(-11.5, 0, 205),
ang = Angle(90, 0, -43.566879272461),
fov = 10
}
|
includeFile("dungeon/warren/bors_teraud.lua")
includeFile("dungeon/warren/captain_heff.lua")
includeFile("dungeon/warren/computer_scientist.lua")
includeFile("dungeon/warren/crazed_scientist.lua")
includeFile("dungeon/warren/cyborg_bol.lua")
includeFile("dungeon/warren/cyborg_dune_lizard.lua")
includeFile("dungeon/warren/cyborg_huurton.lua")
includeFile("dungeon/warren/cyborg_slice_hound.lua")
includeFile("dungeon/warren/cyborg_tusk_cat.lua")
includeFile("dungeon/warren/dirk_maggin.lua")
includeFile("dungeon/warren/doctor_knag.lua")
includeFile("dungeon/warren/fierce_huurton.lua")
includeFile("dungeon/warren/hostile_huurton.lua")
includeFile("dungeon/warren/jerrd_sonclim.lua")
includeFile("dungeon/warren/mad_scientist.lua")
includeFile("dungeon/warren/manx_try.lua")
includeFile("dungeon/warren/mirla.lua")
includeFile("dungeon/warren/oevitt_piboi.lua")
includeFile("dungeon/warren/phy_hudgen.lua")
includeFile("dungeon/warren/savage_huurton.lua")
includeFile("dungeon/warren/teraud_loyalist_commander.lua")
includeFile("dungeon/warren/teraud_loyalist_cyborg.lua")
includeFile("dungeon/warren/teraud_loyalist.lua")
includeFile("dungeon/warren/tusk_cat.lua")
includeFile("dungeon/warren/warren_agro_droid_boss.lua")
includeFile("dungeon/warren/warren_agro_droid.lua")
includeFile("dungeon/warren/warren_altered_atst.lua")
includeFile("dungeon/warren/warren_imperial_officer.lua")
includeFile("dungeon/warren/warren_imperial_worker.lua")
includeFile("dungeon/warren/warren_irradiated_worker.lua")
includeFile("dungeon/warren/warren_scientist.lua")
includeFile("dungeon/warren/warren_stormtrooper.lua")
includeFile("dungeon/warren/warren_thune.lua")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.