Merge branch 'nightly' into organizing

This commit is contained in:
Vortrex
2022-06-14 05:56:46 -05:00
145 changed files with 33748 additions and 15824 deletions

View File

@@ -7,6 +7,7 @@
// TYPE: Client (JavaScript)
// ===========================================================================
// Init AFK script
function initAFKScript() {
logToConsole(LOG_DEBUG, "[VRR.AFK]: Initializing AFK script ...");
logToConsole(LOG_DEBUG, "[VRR.AFK]: AFK script initialized!");
@@ -14,14 +15,16 @@ function initAFKScript() {
// ===========================================================================
// Process stuff when game loses focus
function processLostFocusAFK(event) {
sendServerNewAFKStatus(true);
}
// ===========================================================================
// Process stuff when game gains focus
function processFocusAFK(event) {
sendServerNewAFKStatus(false);
sendServerNewAFKStatus(false);
}
// ===========================================================================

View File

@@ -7,69 +7,142 @@
// TYPE: Client (JavaScript)
// ===========================================================================
function makePedPlayAnimation(pedId, animGroup, animId, animType, animSpeed, loop, loopNoControl, freezeLastFrame, returnToOriginalPosition, freezePlayer) {
logToConsole(LOG_DEBUG, `[VRR.Animation] Playing animation ${animGroup}/${animId} for ped ${pedId}`);
if(getGame() < VRR_GAME_GTA_IV) {
if(animType == VRR_ANIMTYPE_NORMAL || animType == VRR_ANIMTYPE_SURRENDER) {
if(getGame() == VRR_GAME_GTA_VC || getGame() == VRR_GAME_GTA_SA) {
getElementFromId(pedId).clearAnimations();
} else {
getElementFromId(pedId).clearObjective();
}
getElementFromId(pedId).addAnimation(animGroup, animId);
function makePedPlayAnimation(pedId, animationSlot, positionOffset) {
let ped = getElementFromId(pedId);
if(getElementFromId(pedId) == localPlayer && freezePlayer == true) {
inAnimation = true;
setLocalPlayerControlState(false, false);
localPlayer.collisionsEnabled = false;
}
} else if(animType == VRR_ANIMTYPE_BLEND) {
getElementFromId(pedId).position = getElementFromId(pedId).position;
getElementFromId(pedId).blendAnimation(animGroup, animId, animSpeed);
}
} else {
natives.requestAnims(animGroup);
natives.taskPlayAnimNonInterruptable(getElementFromId(pedId), animId, animGroup, animSpeed, loop, loopNoControl, freezeLastFrame, returnToOriginalPosition, -1);
}
if(ped == null) {
return false;
}
let animationData = getAnimationData(animationSlot);
logToConsole(LOG_DEBUG, `[VRR.Animation] Playing animation ${animationData[0]} for ped ${pedId}`);
let freezePlayer = false;
switch(animationData.moveType) {
case VRR_ANIMMOVE_FORWARD: {
setElementCollisionsEnabled(ped, false);
if(ped.isSyncer) {
setElementPosition(ped, getPosInFrontOfPos(getElementPosition(pedId), fixAngle(getElementHeading(pedId)), positionOffset));
}
freezePlayer = true;
break;
}
case VRR_ANIMMOVE_BACK: {
setElementCollisionsEnabled(pedId, false);
if(ped.isSyncer) {
setElementPosition(pedId, getPosBehindPos(getElementPosition(pedId), fixAngle(getElementHeading(pedId)), positionOffset));
}
freezePlayer = true;
break;
}
case VRR_ANIMMOVE_LEFT: {
setElementCollisionsEnabled(pedId, false);
if(ped.isSyncer) {
setElementPosition(pedId, getPosToLeftOfPos(getElementPosition(pedId), fixAngle(getElementHeading(pedId)), positionOffset));
}
freezePlayer = true;
break;
}
case VRR_ANIMMOVE_RIGHT: {
setElementCollisionsEnabled(pedId, false);
if(ped.isSyncer) {
setElementPosition(pedId, getPosToRightOfPos(getElementPosition(pedId), fixAngle(getElementHeading(pedId)), positionOffset));
}
freezePlayer = true;
break;
}
default: {
break;
}
}
if(getGame() < VRR_GAME_GTA_IV) {
if(animationData.animType == VRR_ANIMTYPE_NORMAL || animationData.animType == VRR_ANIMTYPE_SURRENDER) {
if(getGame() == VRR_GAME_GTA_VC || getGame() == VRR_GAME_GTA_SA) {
ped.clearAnimations();
} else {
ped.clearObjective();
}
ped.addAnimation(animationData.groupId, animationData.animId);
if(ped == localPlayer && freezePlayer == true) {
inAnimation = true;
setLocalPlayerControlState(false, false);
localPlayer.collisionsEnabled = false;
}
} else if(animationData.animType == VRR_ANIMTYPE_BLEND) {
ped.position = ped.position;
ped.blendAnimation(animationData.groupId, animationData.animId, animationData.animSpeed);
}
} else {
natives.requestAnims(animationData.groupId);
natives.taskPlayAnimNonInterruptable(ped, animationData.groupId, animationData.animId, animationData.animSpeed, boolToInt(animationData.infiniteLoop), boolToInt(animationData.infiniteLoopNoMovement), boolToInt(animationData.dontReturnToStartCoords), boolToInt(animationData.freezeLastFrame), -1);
}
}
// ===========================================================================
function forcePedAnimation(pedId, animGroup, animId, animType, animSpeed, loop, loopNoControl, freezeLastFrame, returnToOriginalPosition) {
if(getGame() < VRR_GAME_GTA_IV) {
forcedAnimation = [animGroup, animId];
getElementFromId(pedId).position = getElementFromId(pedId).position;
getElementFromId(pedId).addAnimation(animGroup, animId);
function forcePedAnimation(pedId, animSlot) {
let ped = getElementFromId(pedId);
if(getElementFromId(pedId) == localPlayer) {
inAnimation = true;
setLocalPlayerControlState(false, false);
localPlayer.collisionsEnabled = false;
}
}
if(ped == null) {
return false;
}
let animationData = getAnimationData(animSlot);
if(getGame() < VRR_GAME_GTA_IV) {
ped.position = ped.position;
ped.addAnimation(animationData.groupId, animationData.animId);
if(ped == localPlayer) {
inAnimation = true;
setLocalPlayerControlState(false, false);
localPlayer.collisionsEnabled = false;
}
} else {
natives.requestAnims(animationData.groupId);
natives.taskPlayAnimNonInterruptable(ped, animationData.groupId, animationData.animId, animationData.animSpeed, boolToInt(animationData.infiniteLoop), boolToInt(animationData.infiniteLoopNoMovement), boolToInt(animationData.dontReturnToStartCoords), boolToInt(animationData.freezeLastFrame), -1);
}
}
// ===========================================================================
function makePedStopAnimation(pedId) {
if(getElementFromId(pedId) == null) {
return false;
}
let ped = getElementFromId(pedId);
if(getGame() != VRR_GAME_GTA_IV) {
if(getGame() == VRR_GAME_GTA_VC || getGame() == VRR_GAME_GTA_SA) {
getElementFromId(pedId).clearAnimations();
} else {
getElementFromId(pedId).clearObjective();
}
}
if(ped == null) {
return false;
}
if(getElementFromId(pedId) == localPlayer) {
if(getGame() != VRR_GAME_GTA_IV) {
localPlayer.collisionsEnabled = true;
}
setLocalPlayerControlState(true, false);
}
if(getGame() != VRR_GAME_GTA_IV) {
if(getGame() == VRR_GAME_GTA_VC || getGame() == VRR_GAME_GTA_SA) {
ped.clearAnimations();
} else {
ped.clearObjective();
}
}
if(ped == localPlayer) {
if(getGame() != VRR_GAME_GTA_IV) {
localPlayer.collisionsEnabled = true;
}
setLocalPlayerControlState(true, false);
}
}
// ===========================================================================
/**
* @param {number} animationSlot - The slot index of the animation
* @return {AnimationData} The animation's data (array)
*/
function getAnimationData(animationSlot, gameId = getGame()) {
return getGameConfig().animations[gameId][animationSlot];
}
// ===========================================================================

View File

@@ -8,85 +8,84 @@
// ===========================================================================
class BusinessData {
constructor(businessId, name, entrancePosition, blipModel, pickupModel, hasInterior, hasItems) {
this.index = -1;
this.businessId = businessId;
this.name = name;
this.entrancePosition = entrancePosition;
this.blipModel = blipModel;
this.pickupModel = pickupModel;
this.hasInterior = hasInterior;
this.hasItems = hasItems;
this.blipId = -1;
}
constructor(businessId, name, entrancePosition, blipModel, pickupModel, hasInterior, hasItems) {
this.index = -1;
this.businessId = businessId;
this.name = name;
this.entrancePosition = entrancePosition;
this.blipModel = blipModel;
this.pickupModel = pickupModel;
this.hasInterior = hasInterior;
this.hasItems = hasItems;
this.blipId = -1;
this.labelInfoType = 0;
}
}
// ===========================================================================
function receiveBusinessFromServer(businessId, name, entrancePosition, blipModel, pickupModel, hasInterior, hasItems) {
logToConsole(LOG_DEBUG, `[VRR.Business] Received business ${businessId} (${name}) from server`);
if(getGame() == VRR_GAME_GTA_IV) {
if(getBusinessData(businessId) != false) {
let businessData = getBusinessData(businessId);
businessData.name = name;
businessData.entrancePosition = entrancePosition;
businessData.blipModel = blipModel;
businessData.pickupModel = pickupModel;
businessData.hasInterior = hasInterior;
businessData.hasItems = hasItems;
logToConsole(LOG_DEBUG, `[VRR.Business] Received business ${businessId} (${name}) from server`);
logToConsole(LOG_DEBUG, `[VRR.Business] Business ${businessId} already exists. Checking blip ...`);
if(blipModel == -1) {
if(businessData.blipId != -1) {
logToConsole(LOG_DEBUG, `[VRR.Business] Business ${businessId}'s blip has been removed by the server`);
natives.removeBlipAndClearIndex(getBusinessData(businessId).blipId);
businessData.blipId = -1;
//businesses.splice(businessData.index, 1);
//setAllBusinessDataIndexes();
} else {
logToConsole(LOG_DEBUG, `[VRR.Business] Business ${businessId}'s blip is unchanged`);
}
} else {
if(businessData.blipId != -1) {
logToConsole(LOG_DEBUG, `[VRR.Business] Business ${businessId}'s blip has been changed by the server`);
natives.setBlipCoordinates(businessData.blipId, businessData.entrancePosition);
natives.changeBlipSprite(businessData.blipId, businessData.blipModel);
natives.setBlipMarkerLongDistance(businessData.blipId, false);
natives.setBlipAsShortRange(tempBusinessData.blipId, true);
natives.changeBlipNameFromAscii(businessData.blipId, `${businessData.name.substr(0, 24)}${(businessData.name.length > 24) ? " ...": ""}`);
} else {
let blipId = natives.addBlipForCoord(entrancePosition);
if(blipId) {
businessData.blipId = blipId;
natives.changeBlipSprite(businessData.blipId, businessData.blipModel);
natives.setBlipMarkerLongDistance(businessData.blipId, false);
natives.setBlipAsShortRange(tempBusinessData.blipId, true);
natives.changeBlipNameFromAscii(businessData.blipId, `${businessData.name.substr(0, 24)}${(businessData.name.length > 24) ? " ...": ""}`);
}
logToConsole(LOG_DEBUG, `[VRR.Business] Business ${businessId}'s blip has been added by the server (Model ${blipModel}, ID ${blipId})`);
}
}
} else {
logToConsole(LOG_DEBUG, `[VRR.Business] Business ${businessId} doesn't exist. Adding ...`);
let tempBusinessData = new BusinessData(businessId, name, entrancePosition, blipModel, pickupModel, hasInterior, hasItems);
if(blipModel != -1) {
let blipId = natives.addBlipForCoord(entrancePosition);
if(blipId) {
tempBusinessData.blipId = blipId;
natives.changeBlipSprite(tempBusinessData.blipId, blipModel);
natives.setBlipMarkerLongDistance(tempBusinessData.blipId, false);
natives.setBlipAsShortRange(tempBusinessData.blipId, true);
natives.changeBlipNameFromAscii(tempBusinessData.blipId, `${name.substr(0, 24)}${(name.length > 24) ? " ...": ""}`);
}
logToConsole(LOG_DEBUG, `[VRR.Business] Business ${businessId}'s blip has been added by the server (Model ${blipModel}, ID ${blipId})`);
} else {
logToConsole(LOG_DEBUG, `[VRR.Business] Business ${businessId} has no blip.`);
}
businesses.push(tempBusinessData);
setAllBusinessDataIndexes();
}
}
if(!areServerElementsSupported()) {
if(getBusinessData(businessId) != false) {
let businessData = getBusinessData(businessId);
businessData.name = name;
businessData.entrancePosition = entrancePosition;
businessData.blipModel = blipModel;
businessData.pickupModel = pickupModel;
businessData.hasInterior = hasInterior;
businessData.hasItems = hasItems;
logToConsole(LOG_DEBUG, `[VRR.Business] Business ${businessId} already exists. Checking blip ...`);
if(blipModel == -1) {
if(businessData.blipId != -1) {
logToConsole(LOG_DEBUG, `[VRR.Business] Business ${businessId}'s blip has been removed by the server`);
if(getGame() == VRR_GAME_GTA_IV) {
natives.removeBlipAndClearIndex(getBusinessData(businessId).blipId);
} else {
destroyElement(getElementFromId(blipId));
}
businessData.blipId = -1;
//businesses.splice(businessData.index, 1);
//setAllBusinessDataIndexes();
} else {
logToConsole(LOG_DEBUG, `[VRR.Business] Business ${businessId}'s blip is unchanged`);
}
} else {
if(businessData.blipId != -1) {
logToConsole(LOG_DEBUG, `[VRR.Business] Business ${businessId}'s blip has been changed by the server`);
if(getGame() == VRR_GAME_GTA_IV) {
natives.setBlipCoordinates(businessData.blipId, businessData.entrancePosition);
natives.changeBlipSprite(businessData.blipId, businessData.blipModel);
natives.setBlipMarkerLongDistance(businessData.blipId, false);
natives.setBlipAsShortRange(tempBusinessData.blipId, true);
natives.changeBlipNameFromAscii(businessData.blipId, `${businessData.name.substr(0, 24)}${(businessData.name.length > 24) ? " ...": ""}`);
}
} else {
let blipId = createGameBlip(tempBusinessData.blipModel, tempBusinessData.entrancePosition, tempBusinessData.name);
if(blipId != -1) {
tempBusinessData.blipId = blipId;
}
logToConsole(LOG_DEBUG, `[VRR.Business] Business ${businessId}'s blip has been added by the server (Model ${blipModel}, ID ${blipId})`);
}
}
} else {
logToConsole(LOG_DEBUG, `[VRR.Business] Business ${businessId} doesn't exist. Adding ...`);
let tempBusinessData = new BusinessData(businessId, name, entrancePosition, blipModel, pickupModel, hasInterior, hasItems);
if(blipModel != -1) {
let blipId = createGameBlip(tempBusinessData.blipModel, tempBusinessData.entrancePosition, tempBusinessData.name);
if(blipId != -1) {
tempBusinessData.blipId = blipId;
}
logToConsole(LOG_DEBUG, `[VRR.Business] Business ${businessId}'s blip has been added by the server (Model ${blipModel}, ID ${blipId})`);
} else {
logToConsole(LOG_DEBUG, `[VRR.Business] Business ${businessId} has no blip.`);
}
getServerData().businesses.push(tempBusinessData);
setAllBusinessDataIndexes();
}
}
}
// ===========================================================================
@@ -96,23 +95,26 @@ function receiveBusinessFromServer(businessId, name, entrancePosition, blipModel
* @return {BusinessData} The business's data (class instance)
*/
function getBusinessData(businessId) {
//let tempBusinessData = businesses.find((b) => b.businessId == businessId);
//return (typeof tempBusinessData != "undefined") ? tempBusinessData[0] : false;
for(let i in businesses) {
if(businesses[i].businessId == businessId) {
return businesses[i];
}
}
//let tempBusinessData = businesses.find((b) => b.businessId == businessId);
//return (typeof tempBusinessData != "undefined") ? tempBusinessData[0] : false;
return false;
let businesses = getServerData().businesses;
for(let i in businesses) {
if(businesses[i].businessId == businessId) {
return businesses[i];
}
}
return false;
}
// ===========================================================================
function setAllBusinessDataIndexes() {
for(let i in businesses) {
businesses[i].index = i;
}
for(let i in getServerData().businesses) {
getServerData().businesses[i].index = i;
}
}
// ===========================================================================

View File

@@ -16,92 +16,156 @@ let maxChatBoxHistory = 500;
let scrollAmount = 1;
let maxChatBoxLines = 6;
let chatAutoHideDelay = 0;
let chatLastUse = 0;
let scrollUpKey = false;
let scrollDownKey = false;
// ===========================================================================
function initChatBoxScript() {
logToConsole(LOG_DEBUG, "[VRR.ChatBox]: Initializing chatbox script ...");
scrollUpKey = getKeyIdFromParams("pageup");
scrollDownKey = getKeyIdFromParams("pagedown");
bindChatBoxKeys();
logToConsole(LOG_DEBUG, "[VRR.ChatBox]: Chatbox script initialized!");
logToConsole(LOG_DEBUG, "[VRR.ChatBox]: Initializing chatbox script ...");
scrollUpKey = getKeyIdFromParams("pageup");
scrollDownKey = getKeyIdFromParams("pagedown");
bindChatBoxKeys();
logToConsole(LOG_DEBUG, "[VRR.ChatBox]: Chatbox script initialized!");
}
// ===========================================================================
function bindChatBoxKeys() {
bindKey(toInteger(scrollUpKey), KEYSTATE_DOWN, chatBoxScrollUp);
bindKey(toInteger(scrollDownKey), KEYSTATE_DOWN, chatBoxScrollDown);
bindKey(toInteger(scrollUpKey), KEYSTATE_DOWN, chatBoxScrollUp);
bindKey(toInteger(scrollDownKey), KEYSTATE_DOWN, chatBoxScrollDown);
}
// ===========================================================================
function unBindChatBoxKeys() {
unbindKey(toInteger(scrollUpKey));
unbindKey(toInteger(scrollDownKey));
unbindKey(toInteger(scrollUpKey));
unbindKey(toInteger(scrollDownKey));
}
// ===========================================================================
function receiveChatBoxMessageFromServer(messageString, colour) {
if(bottomMessageIndex => chatBoxHistory.length-1) {
message(messageString, colour);
bottomMessageIndex = chatBoxHistory.length-1;
}
addToChatBoxHistory(messageString, colour);
logToConsole(LOG_DEBUG, `[VRR.ChatBox]: Received chatbox message from server: ${messageString}`);
// Just in case it's hidden by auto hide
//setChatWindowEnabled(true);
let colouredString = replaceColoursInMessage(messageString);
logToConsole(LOG_DEBUG, `[VRR.ChatBox]: Changed colours in string: ${colouredString}`);
addToChatBoxHistory(colouredString, colour);
//if(bottomMessageIndex >= chatBoxHistory.length-1) {
message(colouredString, colour);
bottomMessageIndex = chatBoxHistory.length-1;
//}
chatLastUse = getCurrentUnixTimestamp();
}
// ===========================================================================
function setChatScrollLines(amount) {
scrollAmount = amount;
scrollAmount = amount;
}
// ===========================================================================
function setChatAutoHideDelay(delay) {
chatAutoHideDelay = delay*1000;
}
// ===========================================================================
function addToChatBoxHistory(messageString, colour) {
chatBoxHistory.push([messageString, colour]);
chatBoxHistory.push([messageString, colour]);
}
// ===========================================================================
function chatBoxScrollUp() {
if(bottomMessageIndex > maxChatBoxLines) {
bottomMessageIndex = bottomMessageIndex-scrollAmount;
updateChatBox();
}
if(bottomMessageIndex > maxChatBoxLines) {
bottomMessageIndex = bottomMessageIndex-scrollAmount;
updateChatBox();
}
}
// ===========================================================================
function chatBoxScrollDown() {
if(bottomMessageIndex < chatBoxHistory.length-1) {
bottomMessageIndex = bottomMessageIndex+scrollAmount;
updateChatBox();
}
if(bottomMessageIndex < chatBoxHistory.length-1) {
bottomMessageIndex = bottomMessageIndex+scrollAmount;
updateChatBox();
}
}
// ===========================================================================
function clearChatBox() {
for(let i = 0 ; i <= maxChatBoxLines ; i++) {
message("", COLOUR_WHITE);
}
for(let i = 0 ; i <= maxChatBoxLines ; i++) {
message("", COLOUR_WHITE);
}
}
// ===========================================================================
function updateChatBox() {
clearChatBox();
for(let i = bottomMessageIndex-maxChatBoxLines ; i <= bottomMessageIndex ; i++) {
if(typeof chatBoxHistory[i] != "undefined") {
message(chatBoxHistory[i][0], chatBoxHistory[i][1]);
} else {
message("", COLOUR_WHITE);
}
}
clearChatBox();
for(let i = bottomMessageIndex-maxChatBoxLines ; i <= bottomMessageIndex ; i++) {
if(typeof chatBoxHistory[i] != "undefined") {
message(chatBoxHistory[i][0], chatBoxHistory[i][1]);
} else {
message("", COLOUR_WHITE);
}
}
chatLastUse = getCurrentUnixTimestamp();
}
// ===========================================================================
function processMouseWheelForChatBox(mouseId, deltaCoordinates, flipped) {
// There isn't a way to detect whether chat input is active, but mouse cursor is forced shown when typing so ¯\_(ツ)_/¯
if(!gui.cursorEnabled) {
return false;
}
if(!flipped) {
if(deltaCoordinates.y > 0) {
chatBoxScrollUp();
} else {
chatBoxScrollDown();
}
} else {
if(deltaCoordinates.y > 0) {
chatBoxScrollDown();
} else {
chatBoxScrollUp();
}
}
}
// ===========================================================================
function checkChatAutoHide() {
return false;
// Make sure chat input isn't active
if(gui.cursorEnabled) {
return false;
}
// Don't process auto-hide if it's disabled
if(chatAutoHideDelay == 0) {
return false;
}
if(getCurrentUnixTimestamp()-chatLastUse >= chatAutoHideDelay) {
setChatWindowEnabled(false);
}
}
// ===========================================================================

View File

@@ -8,58 +8,58 @@
// ===========================================================================
function getCustomImage(imageName) {
let contentResource = findResourceByName(getGameConfig().extraContentResource[getGame()]);
if(contentResource != null) {
if(contentResource.isStarted) {
let image = contentResource.exports.getCustomImage(imageName);
if(image != null) {
return image;
}
}
}
return false;
let contentResource = findResourceByName(getGameConfig().extraContentResource[getGame()]);
if(contentResource != null) {
if(contentResource.isStarted) {
let image = contentResource.exports.getCustomImage(imageName);
if(image != null) {
return image;
}
}
}
return false;
}
// ===========================================================================
function getCustomFont(fontName) {
let contentResource = findResourceByName(getGameConfig().extraContentResource[getGame()]);
if(contentResource != null) {
if(contentResource.isStarted) {
let font = contentResource.exports.getCustomFont(fontName);
if(font != null) {
return font;
}
}
}
return false;
let contentResource = findResourceByName(getGameConfig().extraContentResource[getGame()]);
if(contentResource != null) {
if(contentResource.isStarted) {
let font = contentResource.exports.getCustomFont(fontName);
if(font != null) {
return font;
}
}
}
return false;
}
// ===========================================================================
function getCustomAudio(audioName) {
let contentResource = findResourceByName(getGameConfig().extraContentResource[getGame()]);
if(contentResource != null) {
if(contentResource.isStarted) {
let audioFile = contentResource.exports.getCustomAudio(audioName);
if(audioFile != null) {
return audioFile;
}
}
}
return false;
let contentResource = findResourceByName(getGameConfig().extraContentResource[getGame()]);
if(contentResource != null) {
if(contentResource.isStarted) {
let audioFile = contentResource.exports.getCustomAudio(audioName);
if(audioFile != null) {
return audioFile;
}
}
}
return false;
}
// ===========================================================================
function playCustomAudio(audioName, volume = 0.5, loop = false) {
let contentResource = findResourceByName(getGameConfig().extraContentResource[getGame()]);
if(contentResource != null) {
if(contentResource.isStarted) {
contentResource.exports.playCustomAudio(audioName, volume, loop);
}
}
return false;
let contentResource = findResourceByName(getGameConfig().extraContentResource[getGame()]);
if(contentResource != null) {
if(contentResource.isStarted) {
contentResource.exports.playCustomAudio(audioName, volume, loop);
}
}
return false;
}
// ===========================================================================

View File

@@ -8,222 +8,248 @@
// ===========================================================================
function initEventScript() {
logToConsole(LOG_DEBUG, "[VRR.Event]: Initializing event script ...");
addCustomEvents();
addAllEventHandlers();
logToConsole(LOG_DEBUG, "[VRR.Event]: Event script initialized!");
logToConsole(LOG_DEBUG, "[VRR.Event]: Initializing event script ...");
addCustomEvents();
addAllEventHandlers();
logToConsole(LOG_DEBUG, "[VRR.Event]: Event script initialized!");
}
// ===========================================================================
function addCustomEvents() {
addEvent("OnLocalPlayerEnterSphere", 1);
addEvent("OnLocalPlayerExitSphere", 1);
addEvent("OnLocalPlayerEnteredVehicle", 1);
addEvent("OnLocalPlayerExitedVehicle", 1);
addEvent("OnLocalPlayerSwitchWeapon", 2);
addEvent("OnLocalPlayerEnterSphere", 1);
addEvent("OnLocalPlayerExitSphere", 1);
addEvent("OnLocalPlayerEnteredVehicle", 1);
addEvent("OnLocalPlayerExitedVehicle", 1);
addEvent("OnLocalPlayerSwitchWeapon", 2);
}
// ===========================================================================
function addAllEventHandlers() {
bindEventHandler("OnResourceStart", thisResource, onResourceStart);
bindEventHandler("OnResourceReady", thisResource, onResourceReady);
bindEventHandler("OnResourceStop", thisResource, onResourceStop);
bindEventHandler("OnResourceStart", thisResource, onResourceStart);
bindEventHandler("OnResourceReady", thisResource, onResourceReady);
bindEventHandler("OnResourceStop", thisResource, onResourceStop);
addEventHandler("OnProcess", onProcess);
addEventHandler("OnKeyUp", onKeyUp);
addEventHandler("OnDrawnHUD", onDrawnHUD);
addEventHandler("OnProcess", onProcess);
addEventHandler("OnKeyUp", onKeyUp);
addEventHandler("OnDrawnHUD", onDrawnHUD);
addEventHandler("OnPedWasted", onPedWasted);
addEventHandler("OnPedWasted", onPedWasted);
addEventHandler("OnElementStreamIn", onElementStreamIn);
addEventHandler("OnElementStreamIn", onElementStreamIn);
addEventHandler("OnLocalPlayerEnteredVehicle", onLocalPlayerEnteredVehicle);
addEventHandler("OnLocalPlayerExitedVehicle", onLocalPlayerExitedVehicle);
addEventHandler("OnLocalPlayerEnterSphere", onLocalPlayerEnterSphere);
addEventHandler("OnLocalPlayerExitSphere", onLocalPlayerExitSphere);
addEventHandler("OnLocalPlayerSwitchWeapon", onLocalPlayerSwitchWeapon);
addEventHandler("OnLocalPlayerEnteredVehicle", onLocalPlayerEnteredVehicle);
addEventHandler("OnLocalPlayerExitedVehicle", onLocalPlayerExitedVehicle);
addEventHandler("OnLocalPlayerEnterSphere", onLocalPlayerEnterSphere);
addEventHandler("OnLocalPlayerExitSphere", onLocalPlayerExitSphere);
addEventHandler("OnLocalPlayerSwitchWeapon", onLocalPlayerSwitchWeapon);
addEventHandler("OnPedInflictDamage", onPedInflictDamage);
addEventHandler("OnPedInflictDamage", onPedInflictDamage);
addEventHandler("OnLostFocus", onLostFocus);
addEventHandler("OnFocus", onFocus);
addEventHandler("OnLostFocus", onLostFocus);
addEventHandler("OnFocus", onFocus);
addEventHandler("OnCameraProcess", onCameraProcess);
addEventHandler("OnCameraProcess", onCameraProcess);
addEventHandler("OnMouseWheel", onMouseWheel);
addEventHandler("OnEntityProcess", onEntityProcess);
}
// ===========================================================================
function onResourceStart(event, resource) {
sendResourceStartedSignalToServer();
setUpInitialGame();
garbageCollectorInterval = setInterval(collectAllGarbage, 1000*60);
sendResourceStartedSignalToServer();
//garbageCollectorInterval = setInterval(collectAllGarbage, 1000*60);
}
// ===========================================================================
function onResourceStop(event, resource) {
sendResourceStoppedSignalToServer();
sendResourceStoppedSignalToServer();
}
// ===========================================================================
function onResourceReady(event, resource) {
sendResourceReadySignalToServer();
sendResourceReadySignalToServer();
}
// ===========================================================================
function onProcess(event, deltaTime) {
if(localPlayer == null) {
return false;
}
if (localPlayer == null) {
return false;
}
if(!isSpawned) {
return false;
}
if (!isSpawned) {
return false;
}
processSync();
processLocalPlayerControlState();
processLocalPlayerVehicleControlState();
processLocalPlayerSphereEntryExitHandling();
processLocalPlayerVehicleEntryExitHandling();
processJobRouteSphere();
forceLocalPlayerEquippedWeaponItem();
processWantedLevelReset();
processGameSpecifics();
processNearbyPickups();
processVehiclePurchasing();
processVehicleBurning();
//checkChatBoxAutoHide(); // Will be uncommented on 1.4.0 GTAC update
//processVehicleFires();
processSync();
processLocalPlayerControlState();
processLocalPlayerVehicleControlState();
processLocalPlayerSphereEntryExitHandling();
processLocalPlayerVehicleEntryExitHandling();
processJobRouteSphere();
forceLocalPlayerEquippedWeaponItem();
processWantedLevelReset();
processGameSpecifics();
processNearbyPickups();
processVehiclePurchasing();
//processVehicleFires();
}
// ===========================================================================
function onKeyUp(event, keyCode, scanCode, keyModifiers) {
processSkinSelectKeyPress(keyCode);
//processKeyDuringAnimation();
processGUIKeyPress(keyCode);
processToggleGUIKeyPress(keyCode);
processSkinSelectKeyPress(keyCode);
//processKeyDuringAnimation();
processGUIKeyPress(keyCode);
processToggleGUIKeyPress(keyCode);
}
// ===========================================================================
function onDrawnHUD(event) {
if(!renderHUD) {
return false;
}
if (!renderHUD) {
return false;
}
if(localPlayer == null) {
return false;
}
if (localPlayer == null) {
return false;
}
processSmallGameMessageRendering();
processScoreBoardRendering();
processLabelRendering();
processLogoRendering();
processItemActionRendering();
processSkinSelectRendering();
processNameTagRendering();
processInteriorLightsRendering();
processSmallGameMessageRendering();
processScoreBoardRendering();
processLabelRendering();
processLogoRendering();
processItemActionRendering();
processSkinSelectRendering();
processNameTagRendering();
processInteriorLightsRendering();
}
// ===========================================================================
function onPedWasted(event, wastedPed, killerPed, weapon, pedPiece) {
logToConsole(LOG_DEBUG, `[VRR.Event] Ped ${wastedPed.name} died`);
wastedPed.clearWeapons();
logToConsole(LOG_DEBUG, `[VRR.Event] Ped ${wastedPed.name} died`);
wastedPed.clearWeapons();
}
// ===========================================================================
function onElementStreamIn(event, element) {
syncElementProperties(element);
syncElementProperties(element);
}
// ===========================================================================
function onLocalPlayerExitedVehicle(event, vehicle, seat) {
logToConsole(LOG_DEBUG, `[VRR.Event] Local player exited vehicle`);
sendNetworkEventToServer("vrr.onPlayerExitVehicle", getVehicleForNetworkEvent(vehicle), seat);
logToConsole(LOG_DEBUG, `[VRR.Event] Local player exited vehicle`);
sendNetworkEventToServer("vrr.onPlayerExitVehicle", getVehicleForNetworkEvent(vehicle), seat);
if(inVehicleSeat) {
parkedVehiclePosition = false;
parkedVehicleHeading = false;
}
if (inVehicleSeat) {
parkedVehiclePosition = false;
parkedVehicleHeading = false;
}
}
// ===========================================================================
function onLocalPlayerEnteredVehicle(event, vehicle, seat) {
logToConsole(LOG_DEBUG, `[VRR.Event] Local player entered vehicle`);
logToConsole(LOG_DEBUG, `[VRR.Event] Local player entered vehicle`);
sendNetworkEventToServer("vrr.onPlayerEnterVehicle", getVehicleForNetworkEvent(vehicle), seat);
sendNetworkEventToServer("vrr.onPlayerEnterVehicle", getVehicleForNetworkEvent(vehicle), seat);
if(areServerElementsSupported()) {
if(inVehicleSeat == 0) {
inVehicle.engine = false;
if(!inVehicle.engine) {
parkedVehiclePosition = inVehicle.position;
parkedVehicleHeading = inVehicle.heading;
}
}
}
if (areServerElementsSupported()) {
//if(inVehicleSeat == 0) {
//setVehicleEngine(vehicle, false);
//if(!inVehicle.engine) {
// parkedVehiclePosition = inVehicle.position;
// parkedVehicleHeading = inVehicle.heading;
//}
//}
}
}
// ===========================================================================
function onPedInflictDamage(event, damagedEntity, damagerEntity, weaponId, healthLoss, pedPiece) {
//let damagerEntityString = (!isNull(damagedEntity)) ? `${damagerEntity.name} (${damagerEntity.name}, ${damagerEntity.type} - ${typeof damagerEntity})` : `Unknown ped`;
//let damagedEntityString = (!isNull(damagedEntity)) ? `${damagedEntity.name} (${damagedEntity.name}, ${damagedEntity.type} - ${typeof damagedEntity})` : `Unknown ped`;
//logToConsole(LOG_DEBUG, `[VRR.Event] ${damagerEntityString} damaged ${damagedEntityString}'s '${pedPiece} with weapon ${weaponId}`);
if(!isNull(damagedEntity) && !isNull(damagerEntity)) {
if(damagedEntity.isType(ELEMENT_PLAYER)) {
if(damagedEntity == localPlayer) {
//if(!weaponDamageEnabled[damagerEntity.name]) {
event.preventDefault();
sendNetworkEventToServer("vrr.weaponDamage", damagerEntity.name, weaponId, pedPiece, healthLoss);
//}
}
}
}
//let damagerEntityString = (!isNull(damagedEntity)) ? `${damagerEntity.name} (${damagerEntity.name}, ${damagerEntity.type} - ${typeof damagerEntity})` : `Unknown ped`;
//let damagedEntityString = (!isNull(damagedEntity)) ? `${damagedEntity.name} (${damagedEntity.name}, ${damagedEntity.type} - ${typeof damagedEntity})` : `Unknown ped`;
//logToConsole(LOG_DEBUG, `[VRR.Event] ${damagerEntityString} damaged ${damagedEntityString}'s '${pedPiece} with weapon ${weaponId}`);
if (!isNull(damagedEntity) && !isNull(damagerEntity)) {
if (damagedEntity.isType(ELEMENT_PLAYER)) {
if (damagedEntity == localPlayer) {
//if(!weaponDamageEnabled[damagerEntity.name]) {
preventDefaultEventAction(event);
sendNetworkEventToServer("vrr.weaponDamage", damagerEntity.name, weaponId, pedPiece, healthLoss);
//}
}
}
}
}
// ===========================================================================
function onLocalPlayerEnterSphere(event, sphere) {
logToConsole(LOG_DEBUG, `[VRR.Event] Local player entered sphere`);
if(sphere == jobRouteLocationSphere) {
enteredJobRouteSphere();
}
logToConsole(LOG_DEBUG, `[VRR.Event] Local player entered sphere`);
if (sphere == jobRouteLocationSphere) {
enteredJobRouteSphere();
}
}
// ===========================================================================
function onLocalPlayerExitSphere(event, sphere) {
logToConsole(LOG_DEBUG, `[VRR.Event] Local player exited sphere`);
logToConsole(LOG_DEBUG, `[VRR.Event] Local player exited sphere`);
}
// ===========================================================================
function onLostFocus(event) {
processLostFocusAFK();
processLostFocusAFK();
}
// ===========================================================================
function onFocus(event) {
processFocusAFK();
processFocusAFK();
}
// ===========================================================================
function onLocalPlayerSwitchWeapon(oldWeapon, newWeapon) {
}
// ===========================================================================
function onCameraProcess(event) {
}
// ===========================================================================
function onMouseWheel(event, mouseId, deltaCoordinates, flipped) {
processMouseWheelForChatBox(mouseId, deltaCoordinates, flipped);
}
// ===========================================================================
function onEntityProcess(event, entity) {
if (!isSpawned) {
return false;
}
//if(entity.isType(ELEMENT_PED) && !entity.isType(ELEMENT_PLAYER)) {
// processNPCMovement(entity);
//}
}
// ===========================================================================

65
scripts/client/gps.js Normal file
View File

@@ -0,0 +1,65 @@
// ===========================================================================
// Vortrex's Roleplay Resource
// https://github.com/VortrexFTW/gtac_roleplay
// ===========================================================================
// FILE: gps.js
// DESC: Provides GPS functions and usage
// TYPE: Client (JavaScript)
// ===========================================================================
let gpsBlip = null;
let gpsBlipBlinkTimes = 0;
let gpsBlipBlinkAmount = 0;
let gpsBlipBlinkInterval = 500;
let gpsBlipBlinkTimer = null;
// ===========================================================================
function showGPSLocation(position, colour) {
logToConsole(LOG_DEBUG, `[VRR.GPS] Showing gps location`);
if(getMultiplayerMod() == VRR_MPMOD_GTAC) {
if(getGame() == VRR_GAME_GTA_SA) {
// Server-side spheres don't show in GTA SA for some reason.
gpsSphere = game.createPickup(1318, position, 1);
} else {
gpsSphere = game.createSphere(position, 3);
gpsSphere.colour = colour;
}
if(gpsBlip != null) {
destroyElement(gpsBlip);
}
// Blinking is bugged if player hit the spot before it stops blinking.
blinkGPSBlip(10, position, colour);
gpsBlip = game.createBlip(position, 0, 2, colour);
}
}
// ===========================================================================
function blinkGPSBlip(times, position, colour) {
gpsBlipBlinkTimes = times;
gpsBlipBlinkTimer = setInterval(function() {
if(gpsBlip != null) {
destroyElement(gpsBlip);
gpsBlip = null;
} else {
gpsBlip = game.createBlip(position, 0, 2, colour);
}
if(gpsBlipBlinkAmount >= gpsBlipBlinkTimes) {
if(gpsBlip != null) {
destroyElement(gpsBlip);
gpsBlip = null;
}
gpsBlipBlinkAmount = 0;
gpsBlipBlinkTimes = 0;
gpsBlip = game.createBlip(position, 0, 2, colour);
clearInterval(gpsBlipBlinkTimer);
}
}, gpsBlipBlinkInterval);
}
// ===========================================================================

View File

@@ -12,7 +12,7 @@ var app = {};
let mainFont = "Roboto"; // "Arial"
//let mainLogoPath = (typeof gta == "undefined") ? "files/images/mafiac-logo.png" : "files/images/gtac-logo.png";
let mainLogoPath = "files/images/server-logo.png";
let mainLogoPath = "files/images/asshat-logo.png";
let primaryColour = [200, 200, 200];
let secondaryColour = [16, 16, 16];
@@ -29,27 +29,6 @@ let textInputAlpha = 180;
let guiReady = false;
let guiSubmitKey = false;
let guiLeftKey = false;
let guiRightKey = false;
let guiUpKey = false;
let guiDownKey = false;
// ===========================================================================
let placesOfOrigin = [
"Liberty City",
"Vice City",
"Los Santos",
"San Fierro",
"Las Venturas",
"San Andreas",
"Blaine County",
"Red County",
"Bone County",
"Other",
];
// ===========================================================================
let characterData = [];
@@ -81,11 +60,19 @@ function initGUI() {
initListGUI();
initResetPasswordGUI();
initChangePasswordGUI();
initLocaleChooserGUI();
closeAllWindows();
guiReady = true;
logToConsole(LOG_DEBUG, `[VRR.GUI] All GUI created successfully!`);
loadLocaleConfig();
loadAllLocaleStrings();
resetGUIStrings();
resetLocaleChooserOptions();
sendNetworkEventToServer("vrr.guiReady", true);
};
@@ -102,9 +89,10 @@ function closeAllWindows() {
characterSelect.window.shown = false;
twoFactorAuth.window.shown = false;
listDialog.window.shown = false;
resetPassword.window.shown = false;
passwordReset.window.shown = false;
passwordChange.window.shown = false;
localeChooser.window.shown = false;
mexui.setInput(false);
mexui.focusedControl = false;
@@ -113,56 +101,62 @@ function closeAllWindows() {
guiRightKey = false;
guiUpKey = false;
guiDownKey = false;
setChatWindowEnabled(true);
}
// ===========================================================================
function isAnyGUIActive() {
if(!guiReady) {
if (!guiReady) {
return false;
}
if(infoDialog.window.shown == true) {
if (infoDialog.window.shown == true) {
return true;
}
if(yesNoDialog.window.shown == true) {
if (yesNoDialog.window.shown == true) {
return true;
}
if(errorDialog.window.shown == true) {
if (errorDialog.window.shown == true) {
return true;
}
if(register.window.shown == true) {
if (register.window.shown == true) {
return true;
}
if(login.window.shown == true) {
if (login.window.shown == true) {
return true;
}
if(newCharacter.window.shown == true) {
if (newCharacter.window.shown == true) {
return true;
}
if(characterSelect.window.shown == true) {
if (characterSelect.window.shown == true) {
return true;
}
if(twoFactorAuth.window.shown == true) {
if (twoFactorAuth.window.shown == true) {
return true;
}
if(listDialog.window.shown == true) {
if (listDialog.window.shown == true) {
return true;
}
if(resetPassword.window.shown == true) {
if (passwordReset.window.shown == true) {
return true;
}
if(passwordChange.window.shown == true) {
if (passwordChange.window.shown == true) {
return true;
}
if (localeChooser.window.shown == true) {
return true;
}
@@ -171,150 +165,63 @@ function isAnyGUIActive() {
// ===========================================================================
addNetworkEventHandler("vrr.showCharacterSelect", function(firstName, lastName, cash, clan, lastPlayed, skinId) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Received request from server to show character selection window`);
showCharacterSelectGUI(firstName, lastName, cash, clan, lastPlayed, skinId);
});
// ===========================================================================
addNetworkEventHandler("vrr.switchCharacterSelect", function(firstName, lastName, cash, clan, lastPlayed, skinId) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Received request from server to update character selection window with new info`);
switchCharacterSelectGUI(firstName, lastName, cash, clan, lastPlayed, skinId);
});
// ===========================================================================
addNetworkEventHandler("vrr.showError", function(errorMessage, errorTitle) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Received request from server to show error window`);
showError(errorMessage, errorTitle);
});
// ===========================================================================
addNetworkEventHandler("vrr.showPrompt", function(promptMessage, promptTitle) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Received request from server to show prompt window`);
showYesNoPromptGUI(promptMessage, promptTitle);
});
// ===========================================================================
addNetworkEventHandler("vrr.showInfo", function(infoMessage) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Received request from server to show info dialog`);
showInfo(infoMessage);
});
// ===========================================================================
addNetworkEventHandler("vrr.loginSuccess", function() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Received signal of successful login from server`);
loginSuccess();
});
// ===========================================================================
addNetworkEventHandler("vrr.characterSelectSuccess", function() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Received signal of successful character selection from server`);
characterSelectSuccess();
setChatWindowEnabled(true);
});
// ===========================================================================
addNetworkEventHandler("vrr.loginFailed", function(remainingAttempts) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Received signal of failed login from server`);
loginFailed(remainingAttempts);
});
// ===========================================================================
addNetworkEventHandler("vrr.registrationSuccess", function() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Received signal of successful registration from server`);
registrationSuccess();
});
// ===========================================================================
addNetworkEventHandler("vrr.registrationFailed", function(errorMessage) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Received signal of failed registration from server`);
registrationFailed(errorMessage);
});
// ===========================================================================
addNetworkEventHandler("vrr.newCharacterFailed", function(errorMessage) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Received signal of failed registration from server`);
newCharacterFailed(errorMessage);
});
// ===========================================================================
addNetworkEventHandler("vrr.changePassword", function() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Received signal to change password from server`);
showChangePasswordGUI();
});
// ===========================================================================
addNetworkEventHandler("vrr.showResetPasswordCodeInput", function() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Received signal to input reset password code from server`);
resetPasswordCodeInputGUI();
});
// ===========================================================================
addNetworkEventHandler("vrr.guiColour", function(red1, green1, blue1, red2, green2, blue2, red3, green3, blue3) {
function setGUIColours(red1, green1, blue1, red2, green2, blue2, red3, green3, blue3) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Received new GUI colours from server: ${red1}, ${green1}, ${blue1} / ${red2}, ${green2}, ${blue2} / ${red3}, ${green3}, ${blue3}`);
primaryColour = [red1, green1, blue1];
secondaryColour = [red2, green2, blue2];
primaryTextColour = [red3, green3, blue3];
focusedColour = [red1+focusedColourOffset, green1+focusedColourOffset, blue1+focusedColourOffset];
focusedColour = [red1 + focusedColourOffset, green1 + focusedColourOffset, blue1 + focusedColourOffset];
initGUI();
});
// ===========================================================================
addNetworkEventHandler("vrr.guiInit", function() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Initializing MexUI app`);
//initGUI();
sendNetworkEventToServer("vrr.guiReady", true);
});
}
// ===========================================================================
function hideAllGUI() {
closeAllWindows();
setChatWindowEnabled(true);
closeAllWindows();
setChatWindowEnabled(true);
guiSubmitKey = false;
}
// ===========================================================================
function processGUIKeyPress(keyCode) {
if(!isAnyGUIActive()) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Processing key press: ${keyCode}`);
if (!isAnyGUIActive()) {
logToConsole(LOG_DEBUG, `[VRR.GUI] GUI is not active. Cancelling keypress processing.`);
return false;
}
if(keyCode == SDLK_RETURN || keyCode == SDLK_RETURN2) {
if(guiSubmitKey != false) {
guiSubmitKey();
if (keyCode == SDLK_RETURN || keyCode == SDLK_RETURN2) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Key press is submit (${guiSubmitKey})`);
if (guiSubmitKey != false) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Calling submit key function`);
guiSubmitKey.call();
}
} else if(keyCode == getKeyIdFromParams("left") || keyCode == getKeyIdFromParams("a")) {
if(guiLeftKey != false) {
guiLeftKey();
} else if (keyCode == getKeyIdFromParams("left") || keyCode == getKeyIdFromParams("a")) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Key press is left (${guiLeftKey})`);
if (guiLeftKey != false) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Calling left key function`);
guiLeftKey.call();
}
} else if(keyCode == getKeyIdFromParams("right") || keyCode == getKeyIdFromParams("d")) {
if(guiRightKey != false) {
guiRightKey();
} else if (keyCode == getKeyIdFromParams("right") || keyCode == getKeyIdFromParams("d")) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Key press is right (${guiRightKey})`);
if (guiRightKey != false) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Calling right key function`);
guiRightKey.call();
}
} else if(keyCode == getKeyIdFromParams("down") || keyCode == getKeyIdFromParams("s")) {
if(guiDownKey != false) {
guiDownKey();
} else if (keyCode == getKeyIdFromParams("down") || keyCode == getKeyIdFromParams("s")) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Key press is down (${guiDownKey})`);
if (guiDownKey != false) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Calling down key function`);
guiDownKey.call();
}
} else if(keyCode == getKeyIdFromParams("up") || keyCode == getKeyIdFromParams("w")) {
if(guiUpKey != false) {
guiUpKey();
} else if (keyCode == getKeyIdFromParams("up") || keyCode == getKeyIdFromParams("w")) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Key press is up (${guiUpKey})`);
if (guiUpKey != false) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Calling up key function`);
guiUpKey.call();
}
}
}
@@ -322,9 +229,55 @@ function processGUIKeyPress(keyCode) {
// ===========================================================================
function processToggleGUIKeyPress(keyCode) {
if(keyCode == disableGUIKey) {
if (keyCode == disableGUIKey) {
sendNetworkEventToServer("vrr.toggleGUI");
}
}
// ===========================================================================
function resetGUIStrings() {
// Login GUI
login.messageLabel.text = getLocaleString("GUILoginWindowLabelEnterPassword");
login.passwordInput.placeholder = getLocaleString("GUILoginWindowPasswordPlaceholder");
login.loginButton.text = toUpperCase(getLocaleString("GUILoginWindowSubmitButton"));
login.forgotPasswordButton.text = toUpperCase(getLocaleString("GUILoginWindowResetPasswordButton"));
login.resetPasswordLabel.text = getLocaleString("GUILoginWindowForgotPasswordLabel");
// Register GUI
register.messageLabel.text = getLocaleString("GUIRegisterWindowLabelCreateAccount");
register.passwordInput.placeholder = getLocaleString("GUIRegisterWindowPasswordPlaceholder");
register.confirmPasswordInput.placeholder = getLocaleString("GUIRegisterWindowConfirmPasswordPlaceholder");
register.emailInput.placeholder = getLocaleString("GUIRegisterWindowEmailPlaceholder");
register.registerButton.text = toUpperCase(getLocaleString("GUIRegisterWindowSubmitButton"));
// Change Password GUI
passwordChange.window.title = toUpperCase(getLocaleString("GUIChangePasswordWindowTitle"));
passwordChange.messageLabel.text = getLocaleString("GUIChangePasswordPasswordLabel");
passwordChange.passwordInput.placeholder = getLocaleString("GUIChangePasswordPasswordPlaceholder");
passwordChange.confirmPasswordInput.placeholder = getLocaleString("GUIChangePasswordConfirmPasswordPlaceholder");
passwordChange.submitButton.text = toUpperCase(getLocaleString("GUIChangePasswordSubmitButton"));
// Reset Password GUI
passwordReset.messageLabel.text = toUpperCase(getLocaleString("GUIResetPasswordConfirmEmailLabel"));
passwordReset.emailInput.placeholder = getLocaleString("GUIResetPasswordEmailPlaceholder");
passwordReset.resetPasswordButton.text = toUpperCase(getLocaleString("GUIResetPasswordSubmitButton"));
passwordReset.backToLoginButton.text = toUpperCase(getLocaleString("GUIResetPasswordLoginButton"));
passwordReset.backToLoginLabel.text = getLocaleString("GUIResetPasswordRememberMessage");
// Character Selection GUI
characterSelect.window.title = toUpperCase(getLocaleString("GUICharacterSelectWindowTitle"));
characterSelect.cashText.text = getLocaleString("GUICharacterSelectMoneyLabel", "0");
characterSelect.clanText.text = getLocaleString("GUICharacterSelectClanLabel", "None");
characterSelect.lastPlayedText.text = getLocaleString("GUICharacterSelectLastPlayedLabel", "Never");
characterSelect.previousCharacterButton.text = toUpperCase(getLocaleString("GUIPreviousCharacterButton"));
characterSelect.nextCharacterButton.text = toUpperCase(getLocaleString("GUINextCharacterButton"));
characterSelect.selectCharacterButton.text = toUpperCase(getLocaleString("GUIPlayAsCharacterButton"));
characterSelect.newCharacterButton.text = toUpperCase(getLocaleString("GUINewCharacterButton"));
// Character Creation GUI
newCharacter.messageLabel.text = getLocaleString("GUINewCharacterMessageLabel");
newCharacter.firstNameInput.placeholder = getLocaleString("GUINewCharacterFirstNamePlaceholder");
newCharacter.lastNameInput.placeholder = getLocaleString("GUINewCharacterLastNamePlaceholder");
newCharacter.createCharacterButton.text = toUpperCase(getLocaleString("GUINewCharacterSubmitButton"));
}

View File

@@ -19,8 +19,8 @@ let passwordChange = {
// ===========================================================================
function initChangePasswordGUI() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Creating password change GUI ...`);
passwordChange.window = mexui.window(game.width/2-130, game.height/2-125, 300, 250, 'Change Password', {
logToConsole(LOG_DEBUG, `[VRR.GUI] Creating password change GUI ...`);
passwordChange.window = mexui.window(game.width / 2 - 130, game.height / 2 - 125, 300, 250, 'Change Password', {
main: {
backgroundColour: toColour(secondaryColour[0], secondaryColour[1], secondaryColour[2], windowAlpha),
transitionTime: 500,
@@ -36,16 +36,17 @@ function initChangePasswordGUI() {
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], windowTitleAlpha),
}
});
passwordChange.window.titleBarIconSize = toVector2(0,0);
passwordChange.window.titleBarIconSize = toVector2(0, 0);
passwordChange.window.titleBarHeight = 0;
passwordChange.window.titleBarShown = false;
passwordChange.window.image(85, -10, 140, 140, mainLogoPath, {
passwordChange.window.image(100, 20, 75, 75, mainLogoPath, {
focused: {
borderColour: toColour(0, 0, 0, 0),
},
});
passwordChange.messageLabel = passwordChange.window.text(20, 75, 260, 20, 'Enter a new password', {
passwordChange.messageLabel = passwordChange.window.text(20, 95, 260, 20, 'Enter a new password', {
main: {
textSize: 10.0,
textAlign: 0.5,
@@ -132,14 +133,17 @@ function checkChangePassword() {
// ===========================================================================
function showChangePasswordGUI() {
function showChangePasswordGUI(errorMessage) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Showing change password window`);
closeAllWindows();
setChatWindowEnabled(false);
mexui.setInput(true);
passwordChange.window.shown = true;
passwordChange.messageLabel = errorMessage;
mexui.focusedControl = passwordChange.passwordInput;
guiSubmitKey = checkChangePassword;
showLocaleChooserGUI(new Vec2(getScreenWidth() / 2 - (localeChooser.window.size.x / 2), passwordChange.window.position.y + passwordChange.window.size.y + 20));
}
// ===========================================================================

View File

@@ -24,23 +24,26 @@ let characterSelect = {
function initCharacterSelectGUI() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Creating character select GUI ...`);
characterSelect.window = mexui.window(game.width/2-215, game.height/2-83, 430, 190, 'Select Character', {
characterSelect.window = mexui.window(game.width/2-215, game.height/2-83, 430, 190, 'SELECT CHARACTER', {
main: {
backgroundColour: toColour(secondaryColour[0], secondaryColour[1], secondaryColour[2], windowAlpha),
},
title: {
textSize: 12.0,
textColour: toColour(0, 0, 0, 0),
textSize: 12.0,
textFont: mainFont,
textColour: toColour(0, 0, 0, 255),
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], windowTitleAlpha),
},
icon: {
textSize: 12.0,
textColour: toColour(0, 0, 0, 0),
textSize: 10.0,
textFont: mainFont,
textColour: toColour(0, 0, 0, 255),
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], windowTitleAlpha),
}
});
characterSelect.window.titleBarIconSize = toVector2(0,0);
characterSelect.window.titleBarHeight = 0;
characterSelect.window.titleBarIconSize = toVector2(0, 0);
characterSelect.window.titleBarIconShown = false;
characterSelect.window.titleBarHeight = 30;
characterSelect.nameText = characterSelect.window.text(5, 40, 200, 25, 'Lastname, Firstname', {
main: {
@@ -163,6 +166,12 @@ function showCharacterSelectGUI(firstName, lastName, cash, clan, lastPlayed, ski
characterSelect.lastPlayedText.text = `Last Played: ${lastPlayed}`;
characterSelect.skinImage = characterSelect.window.image(310, 32, 100, 90, "files/images/skins/none.png");
characterSelect.window.shown = true;
guiSubmitKey = selectThisCharacter;
guiLeftKey = selectPreviousCharacter;
guiRightKey = selectNextCharacter;
showLocaleChooserGUI(new Vec2(getScreenWidth()/2-(localeChooser.window.size.x/2), characterSelect.window.position.y+characterSelect.window.size.y+20));
}
// ===========================================================================
@@ -211,6 +220,7 @@ function switchCharacterSelectGUI(firstName, lastName, cash, clan, lastPlayed, s
characterSelect.skinImage = (getGame() == VRR_GAME_GTA_III) ? characterSelect.window.image(310, 32, 100, 90, `files/images/skins/gta3/${getSkinImage(skinId)}.png`) : characterSelect.window.image(310, 32, 100, 90, "files/images/skins/none.png");
characterSelect.window.shown = true;
guiSubmitKey = selectThisCharacter;
guiLeftKey = selectPreviousCharacter;
guiRightKey = selectNextCharacter;

View File

@@ -8,13 +8,13 @@
// ===========================================================================
let clanManager = {
window: null,
generalTab: null,
ranksTab: null,
membersTab: null,
vehiclesTab: null,
businessesTab: null,
housesTab: null,
window: null,
generalTab: null,
ranksTab: null,
membersTab: null,
vehiclesTab: null,
businessesTab: null,
housesTab: null,
};
// ===========================================================================

View File

@@ -16,59 +16,61 @@ let errorDialog = {
// ===========================================================================
function initErrorDialogGUI() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Creating error GUI ...`);
errorDialog.window = mexui.window(game.width/2-200, game.height/2-70, 500, 140, 'ERROR', {
main: {
backgroundColour: toColour(secondaryColour[0], secondaryColour[1], secondaryColour[2], windowAlpha),
transitionTime: 500,
},
title: {
textSize: 11.0,
textColour: toColour(primaryTextColour[0], primaryTextColour[1], primaryTextColour[2], 255),
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], windowTitleAlpha),
},
icon: {
textSize: 0.0,
textColour: toColour(0, 0, 0, 0),
backgroundColour: toColour(0, 0, 0, 0),
},
});
logToConsole(LOG_DEBUG, `[VRR.GUI] Creating error GUI ...`);
errorDialog.window = mexui.window(getScreenWidth()/2-200, getScreenHeight()/2-70, 400, 140, 'ERROR', {
main: {
backgroundColour: toColour(secondaryColour[0], secondaryColour[1], secondaryColour[2], windowAlpha),
transitionTime: 500,
},
title: {
textSize: 11.0,
textColour: toColour(primaryTextColour[0], primaryTextColour[1], primaryTextColour[2], 255),
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], windowTitleAlpha),
},
icon: {
textSize: 0.0,
textColour: toColour(0, 0, 0, 0),
backgroundColour: toColour(0, 0, 0, 0),
},
});
errorDialog.messageLabel = errorDialog.window.text(15, 50, 470, 75, 'Error Message', {
main: {
textSize: 10.0,
textAlign: 0.5,
textColour: toColour(255, 255, 255, 255),
textFont: mainFont,
},
focused: {
borderColour: toColour(0, 0, 0, 0),
},
});
errorDialog.messageLabel = errorDialog.window.text(15, 50, 370, 20, 'Error Message', {
main: {
textSize: 10.0,
textAlign: 0.5,
textColour: toColour(255, 255, 255, 255),
textFont: mainFont,
},
focused: {
borderColour: toColour(0, 0, 0, 0),
},
});
errorDialog.okayButton = errorDialog.window.button(5, 105, 390, 30, 'OK', {
main: {
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], buttonAlpha),
textColour: toColour(primaryTextColour[0], primaryTextColour[1], primaryTextColour[2], 255),
textSize: 10.0,
textFont: mainFont,
textAlign: 0.5,
},
focused: {
borderColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], 255),
},
}, closeErrorDialog);
logToConsole(LOG_DEBUG, `[VRR.GUI] Created error GUI ...`);
errorDialog.okayButton = errorDialog.window.button(5, 105, 390, 30, 'OK', {
main: {
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], buttonAlpha),
textColour: toColour(primaryTextColour[0], primaryTextColour[1], primaryTextColour[2], 255),
textSize: 10.0,
textFont: mainFont,
textAlign: 0.5,
},
focused: {
borderColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], 255),
},
}, closeErrorDialog);
logToConsole(LOG_DEBUG, `[VRR.GUI] Created error GUI ...`);
}
// ===========================================================================
function showErrorGUI(errorMessage, errorTitle) {
function showErrorGUI(errorMessage, errorTitle, buttonText) {
closeAllWindows();
logToConsole(LOG_DEBUG, `[VRR.GUI] Showing error window. Error: ${errorTitle} - ${errorMessage}`);
setChatWindowEnabled(false);
mexui.setInput(true);
errorDialog.messageLabel.text = errorMessage;
errorDialog.okayButton.text = buttonText;
errorDialog.window.title = errorTitle;
errorDialog.window.shown = true;
}

View File

@@ -17,7 +17,7 @@ let infoDialog = {
function initInfoDialogGUI() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Creating info dialog GUI ...`);
infoDialog.window = mexui.window(game.width/2-200, game.height/2-70, 400, 140, 'Information', {
infoDialog.window = mexui.window(getScreenWidth()/2-200, getScreenHeight()/2-70, 400, 140, 'Information', {
main: {
backgroundColour: toColour(secondaryColour[0], secondaryColour[1], secondaryColour[2], windowAlpha),
},
@@ -70,11 +70,13 @@ function closeInfoDialog() {
// ===========================================================================
function showInfo(infoMessage, infoTitle) {
function showInfoGUI(infoMessage, infoTitle, buttonText) {
closeAllWindows();
logToConsole(LOG_DEBUG, `[VRR.GUI] Showing info dialog window. Info: ${infoTitle} - ${infoMessage}`);
mexui.setInput(true);
infoDialog.messageLabel.text = infoMessage;
infoDialog.okayButton.text = buttonText;
infoDialog.window.title = infoTitle;
infoDialog.window.shown = true;
}

View File

@@ -0,0 +1,116 @@
// ===========================================================================
// Vortrex's Roleplay Resource
// https://github.com/VortrexFTW/gtac_roleplay
// ===========================================================================
// FILE: localechooser.js
// DESC: Provides locale chooser GUI
// TYPE: Client (JavaScript)
// ===========================================================================
let localeChooser = {
window: null,
flagImages: [],
activeRingImages: [],
};
let flagImageSize = toVector2(30, 30);
let flagImageGap = toVector2(5, 5);
// ===========================================================================
function initLocaleChooserGUI() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Creating locale chooser GUI ...`);
localeChooser.window = mexui.window(game.width/2-200, game.height-150, 60, 60, 'Choose a language', {
main: {
backgroundColour: toColour(secondaryColour[0], secondaryColour[1], secondaryColour[2], 0),
},
title: {
textSize: 11.0,
textColour: toColour(primaryTextColour[0], primaryTextColour[1], primaryTextColour[2], 255),
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], windowTitleAlpha),
},
icon: {
textSize: 0.0,
textColour: toColour(0, 0, 0, 0),
backgroundColour: toColour(0, 0, 0, 0),
},
});
localeChooser.window.titleBarShown = false;
loadLocaleConfig();
logToConsole(LOG_DEBUG, `[VRR.GUI] Created locale chooser GUI`);
}
// ===========================================================================
function closeLocaleChooserGUI() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Closing locale chooser window`);
localeChooser.window.shown = false;
mexui.setInput(false);
}
// ===========================================================================
function showLocaleChooserGUI(position = toVector2(0.0, 0.0)) {
if(position.x != 0.0 && position.y != 0.0) {
localeChooser.window.position = position;
} else {
localeChooser.window.position = toVector2((getScreenWidth()/2)-(localeChooser.window.size.x/2), getScreenHeight()-100);
}
//closeAllWindows();
logToConsole(LOG_DEBUG, `[VRR.GUI] Showing locale chooser window`);
mexui.setInput(true);
localeChooser.window.shown = true;
}
// ===========================================================================
function toggleLocaleChooserGUI() {
if(localeChooser.window.shown) {
closeLocaleChooserGUI();
} else {
showLocaleChooserGUI();
}
}
// ===========================================================================
function localeChooserSetLocale(localeId) {
logToConsole(LOG_DEBUG|LOG_WARN, `[VRR.GUI] Asking server to change locale to ${localeId}`);
sendLocaleSelectToServer(localeId);
}
// ===========================================================================
function resetLocaleChooserOptions() {
logToConsole(LOG_DEBUG|LOG_WARN, `[VRR.GUI] Resetting locale chooser options`);
// let tempLocaleOptions = getServerData().localeOptions; // getAvailableLocaleOptions();
let tempLocaleOptions = getAvailableLocaleOptions();
localeChooser.window.size = toVector2((tempLocaleOptions.length*(flagImageSize.x+flagImageGap.x))+flagImageGap.x, flagImageSize.y+flagImageGap.y*2);
localeChooser.window.position = toVector2((getScreenWidth()/2)-(localeChooser.window.size.x/2), getScreenHeight()-100);
for(let i in localeChooser.flagImages) {
localeChooser.flagImages[i].remove();
}
for(let i in tempLocaleOptions) {
let imagePath = `files/images/flags/${tempLocaleOptions[i].flagImageFile}`;
localeChooser.flagImages[i] = localeChooser.window.image((i*(flagImageSize.x+flagImageGap.x))+flagImageGap.x, flagImageGap.y, flagImageSize.x, flagImageSize.y, imagePath, {
focused: {
borderColour: toColour(0, 0, 0, 0),
},
}, function() {
localeChooserSetLocale(tempLocaleOptions[i].id);
});
logToConsole(LOG_DEBUG|LOG_WARN, `[VRR.GUI] Created locale chooser option ${tempLocaleOptions[i].englishName} with image ${imagePath}`);
//localeChooser.activeRingImages.push(activeRingImage);
}
}
// ===========================================================================

View File

@@ -11,7 +11,6 @@ let login = {
window: null,
logoImage: null,
messageLabel: null,
passwordLabel: null,
passwordInput: null,
loginButton: null,
forgotPasswordButton: null,
@@ -20,9 +19,31 @@ let login = {
// ===========================================================================
let loginHTML =
`<html>
<head>
<title>Asshat Gaming Roleplay: Login</title>
<style type="text/css" rel="stylesheet">
.input-box
{
font-family: "Roboto";
font-size: 14px;
border-style: solid;
border-colour: #0066AA;
border-radius: 2px;
color: #0066AA;
};
</style>
</head>
<body>
</body>
</html>`;
// ===========================================================================
function initLoginGUI() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Creating login GUI ...`);
login.window = mexui.window(game.width/2-150, game.height/2-135, 300, 275, 'LOGIN', {
login.window = mexui.window(getScreenWidth()/2-150, getScreenHeight()/2-135, 300, 275, 'LOGIN', {
main: {
backgroundColour: toColour(secondaryColour[0], secondaryColour[1], secondaryColour[2], windowAlpha),
transitionTime: 500,
@@ -41,8 +62,9 @@ function initLoginGUI() {
});
login.window.titleBarIconSize = toVector2(0,0);
login.window.titleBarHeight = 0;
login.window.titleBarShown = false;
login.logoImage = login.window.image(5, 20, 290, 100, mainLogoPath, {
login.logoImage = login.window.image(100, 20, 100, 100, mainLogoPath, {
focused: {
borderColour: toColour(0, 0, 0, 0),
},
@@ -96,7 +118,7 @@ function initLoginGUI() {
},
}, checkLogin);
login.forgotPasswordButton = login.window.button(200, 240, 80, 15, 'RESET PASS', {
login.forgotPasswordButton = login.window.button(180, 240, 100, 15, 'RESET PASS', {
main: {
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], buttonAlpha),
textColour: toColour(0, 0, 0, 255),
@@ -109,7 +131,7 @@ function initLoginGUI() {
},
}, switchToPasswordResetGUI);
login.resetPasswordLabel = login.window.text(125, 240, 60, 15, 'Forgot your password?', {
login.resetPasswordLabel = login.window.text(110, 240, 60, 15, 'Forgot your password?', {
main: {
textSize: 8.0,
textAlign: 1.0,
@@ -134,6 +156,8 @@ function showLoginGUI() {
login.window.shown = true;
mexui.focusedControl = login.passwordInput;
guiSubmitKey = checkLogin;
showLocaleChooserGUI(new Vec2(getScreenWidth()/2-(localeChooser.window.size.x/2), login.window.position.y+login.window.size.y+20));
//showSmallGameMessage(`If you don't have a mouse cursor, press ${toUpperCase(getKeyNameFromId(disableGUIKey))} to disable GUI`, COLOUR_WHITE, 7500);
}
@@ -164,9 +188,10 @@ function loginSuccess() {
// ===========================================================================
function switchToPasswordResetGUI() {
closeAllWindows();
logToConsole(LOG_DEBUG, `[VRR.GUI] Showing password reset dialog window`);
showResetPasswordGUI();
//closeAllWindows();
//logToConsole(LOG_DEBUG, `[VRR.GUI] Showing password reset dialog window`);
//showResetPasswordGUI();
sendNetworkEventToServer("vrr.checkResetPassword", "");
return false;
}

View File

@@ -9,106 +9,108 @@
let newCharacter = {
window: null,
messageLabel: null,
firstNameInput: null,
lastNameInput: null,
skinDropDown: null,
spawnAreaDropDown: null,
createButton: null,
mainLogoImage: null,
createCharacterButton: null,
mainLogoImage: null,
};
// ===========================================================================
function initNewCharacterGUI() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Creating new character GUI ...`);
newCharacter.window = mexui.window(game.width/2-130, game.height/2-115, 300, 230, 'New Character', {
main: {
backgroundColour: toColour(secondaryColour[0], secondaryColour[1], secondaryColour[2], windowAlpha),
transitionTime: 500,
},
title: {
textSize: 0.0,
textColour: toColour(0, 0, 0, 0),
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], windowTitleAlpha),
},
icon: {
textSize: 0.0,
textColour: toColour(0, 0, 0, 0),
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], windowTitleAlpha),
}
});
newCharacter.window.titleBarIconSize = toVector2(0,0);
newCharacter.window.titleBarHeight = 0;
logToConsole(LOG_DEBUG, `[VRR.GUI] Creating new character GUI ...`);
newCharacter.window = mexui.window(getScreenWidth()/2-130, getScreenHeight()/2-115, 300, 230, 'NEW CHARACTER', {
main: {
backgroundColour: toColour(secondaryColour[0], secondaryColour[1], secondaryColour[2], windowAlpha),
transitionTime: 500,
},
title: {
textSize: 12.0,
textFont: mainFont,
textColour: toColour(0, 0, 0, 0),
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], windowTitleAlpha),
},
icon: {
textSize: 0.0,
textColour: toColour(0, 0, 0, 0),
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], windowTitleAlpha),
}
});
newCharacter.window.titleBarIconSize = toVector2(0, 0);
newCharacter.window.titleBarIconShown = false;
newCharacter.window.titleBarShown = false;
newCharacter.window.titleBarHeight = 30;
newCharacter.mainLogoImage = newCharacter.window.image(5, 20, 290, 80, mainLogoPath, {
focused: {
borderColour: toColour(0, 0, 0, 0),
},
});
newCharacter.mainLogoImage = newCharacter.window.image(80, 20, 80, 80, mainLogoPath, {
focused: {
borderColour: toColour(0, 0, 0, 0),
},
});
newCharacter.messageLabel = newCharacter.window.text(20, 100, 260, 20, 'Name your character', {
main: {
textSize: 10.0,
textAlign: 0.5,
textColour: toColour(200, 200, 200, 255),
textFont: mainFont,
},
focused: {
borderColour: toColour(0, 0, 0, 0),
},
});
newCharacter.messageLabel = newCharacter.window.text(20, 100, 260, 20, 'Name your character', {
main: {
textSize: 10.0,
textAlign: 0.5,
textColour: toColour(200, 200, 200, 255),
textFont: mainFont,
},
focused: {
borderColour: toColour(0, 0, 0, 0),
},
});
newCharacter.firstNameInput = newCharacter.window.textInput(20, 125, 260, 25, '', {
main: {
backgroundColour: toColour(0, 0, 0, 120),
textColour: toColour(200, 200, 200, 255),
textSize: 10.0,
textFont: mainFont,
},
caret: {
lineColour: toColour(255, 255, 255, 255),
},
placeholder: {
backgroundColour: toColour(0, 0, 0, 120),
textColour: toColour(200, 200, 200, 200),
textSize: 10.0,
textFont: mainFont,
}
});
newCharacter.firstNameInput.placeholder = "First Name";
newCharacter.firstNameInput = newCharacter.window.textInput(20, 125, 260, 25, '', {
main: {
backgroundColour: toColour(0, 0, 0, 120),
textColour: toColour(200, 200, 200, 255),
textSize: 10.0,
textFont: mainFont,
},
caret: {
lineColour: toColour(255, 255, 255, 255),
},
placeholder: {
backgroundColour: toColour(0, 0, 0, 120),
textColour: toColour(200, 200, 200, 200),
textSize: 10.0,
textFont: mainFont,
}
});
newCharacter.firstNameInput.placeholder = "First Name";
newCharacter.lastNameInput = newCharacter.window.textInput(20, 155, 260, 25, '', {
main: {
backgroundColour: toColour(0, 0, 0, 120),
textColour: toColour(200, 200, 200, 255),
textSize: 10.0,
textFont: mainFont,
},
caret: {
lineColour: toColour(255, 255, 255, 255),
},
placeholder: {
backgroundColour: toColour(0, 0, 0, 120),
textColour: toColour(150, 150, 150, 200),
textSize: 10.0,
textFont: mainFont,
}
});
newCharacter.lastNameInput.placeholder = "Last Name";
newCharacter.lastNameInput = newCharacter.window.textInput(20, 155, 260, 25, '', {
main: {
backgroundColour: toColour(0, 0, 0, 120),
textColour: toColour(200, 200, 200, 255),
textSize: 10.0,
textFont: mainFont,
},
caret: {
lineColour: toColour(255, 255, 255, 255),
},
placeholder: {
backgroundColour: toColour(0, 0, 0, 120),
textColour: toColour(150, 150, 150, 200),
textSize: 10.0,
textFont: mainFont,
}
});
newCharacter.lastNameInput.placeholder = "Last Name";
newCharacter.createCharacterButton = newCharacter.window.button(20, 185, 260, 25, 'CREATE CHARACTER', {
main: {
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], buttonAlpha),
textColour: toColour(255, 255, 255, 255),
textSize: 10.0,
textFont: mainFont,
textAlign: 0.5,
},
focused: {
borderColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], buttonAlpha),
},
}, checkNewCharacter);
logToConsole(LOG_DEBUG, `[VRR.GUI] Created new character GUI`);
newCharacter.createCharacterButton = newCharacter.window.button(20, 185, 260, 25, 'CREATE CHARACTER', {
main: {
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], buttonAlpha),
textColour: toColour(255, 255, 255, 255),
textSize: 10.0,
textFont: mainFont,
textAlign: 0.5,
},
focused: {
borderColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], buttonAlpha),
},
}, checkNewCharacter);
logToConsole(LOG_DEBUG, `[VRR.GUI] Created new character GUI`);
}
// ===========================================================================
@@ -133,8 +135,6 @@ function newCharacterFailed(errorMessage) {
function checkNewCharacter() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Checking new character with server ...`);
let skinId = false;
if(newCharacter.firstNameInput.lines[0].length < 2) {
return false;
}
@@ -157,8 +157,10 @@ function showNewCharacterGUI() {
setChatWindowEnabled(false);
mexui.setInput(true);
newCharacter.window.shown = true;
mexui.focusedInput = newCharacter.firstNameInput;
guiSubmitButton = checkNewCharacter;
mexui.focusedInput = newCharacter.firstNameInput;
guiSubmitKey = checkNewCharacter;
showLocaleChooserGUI(new Vec2(getScreenWidth()/2-(localeChooser.window.size.x/2), newCharacter.window.position.y+newCharacter.window.size.y+20));
}
// ===========================================================================

View File

@@ -21,7 +21,7 @@ let register = {
function initRegisterGUI() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Creating register GUI ...`);
register.window = mexui.window(game.width/2-150, game.height/2-150, 300, 300, 'Register', {
register.window = mexui.window(getScreenWidth()/2-150, getScreenHeight()/2-150, 300, 300, 'Register', {
main: {
backgroundColour: toColour(secondaryColour[0], secondaryColour[1], secondaryColour[2], windowAlpha),
transitionTime: 500,
@@ -39,8 +39,9 @@ function initRegisterGUI() {
});
register.window.titleBarIconSize = toVector2(0,0);
register.window.titleBarHeight = 0;
register.window.titleBarShown = false;
register.window.image(5, 20, 290, 80, mainLogoPath, {
register.window.image(100, 20, 100, 100, mainLogoPath, {
focused: {
borderColour: toColour(0, 0, 0, 0),
},
@@ -160,6 +161,9 @@ function showRegistrationGUI() {
register.window.shown = true;
mexui.focusedControl = register.passwordInput;
guiSubmitKey = checkRegistration;
showLocaleChooserGUI(new Vec2(getScreenWidth()/2-(localeChooser.window.size.x/2), register.window.position.y+register.window.size.y+20));
//showSmallGameMessage(`If you don't have a mouse cursor, press ${toUpperCase(getKeyNameFromId(disableGUIKey))} to disable GUI`, COLOUR_WHITE, 7500);
}

View File

@@ -7,11 +7,10 @@
// TYPE: Client (JavaScript)
// ===========================================================================
let resetPassword = {
let passwordReset = {
window: null,
logoImage: null,
messageLabel: null,
emailLabel: null,
emailInput: null,
resetPasswordButton: null,
backToLoginButton: null,
@@ -21,8 +20,8 @@ let resetPassword = {
// ===========================================================================
function initResetPasswordGUI() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Creating password reset GUI ...`);
resetPassword.window = mexui.window(game.width/2-150, game.height/2-130, 300, 260, 'RESET PASSWORD', {
logToConsole(LOG_DEBUG, `[VRR.GUI] Creating password reset GUI ...`);
passwordReset.window = mexui.window(getScreenWidth() / 2 - 150, getScreenHeight() / 2 - 135, 300, 275, 'RESET PASSWORD', {
main: {
backgroundColour: toColour(secondaryColour[0], secondaryColour[1], secondaryColour[2], windowAlpha),
transitionTime: 500,
@@ -39,16 +38,17 @@ function initResetPasswordGUI() {
borderColour: toColour(0, 0, 0, 0),
},
});
resetPassword.window.titleBarIconSize = toVector2(0,0);
resetPassword.window.titleBarHeight = 0;
passwordReset.window.titleBarIconSize = toVector2(0, 0);
passwordReset.window.titleBarHeight = 0;
passwordReset.window.titleBarShown = false;
resetPassword.logoImage = resetPassword.window.image(5, 20, 290, 80, mainLogoPath, {
passwordReset.logoImage = passwordReset.window.image(100, 20, 100, 100, mainLogoPath, {
focused: {
borderColour: toColour(0, 0, 0, 0),
},
});
resetPassword.messageLabel = resetPassword.window.text(20, 135, 260, 20, 'Please confirm your email', {
passwordReset.messageLabel = passwordReset.window.text(20, 135, 260, 20, 'Please confirm your email', {
main: {
textSize: 10.0,
textAlign: 0.5,
@@ -60,7 +60,7 @@ function initResetPasswordGUI() {
},
});
resetPassword.emailInput = resetPassword.window.textInput(20, 170, 260, 25, '', {
passwordReset.emailInput = passwordReset.window.textInput(20, 170, 260, 25, '', {
main: {
backgroundColour: toColour(0, 0, 0, 120),
borderColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], textInputAlpha),
@@ -80,9 +80,9 @@ function initResetPasswordGUI() {
borderColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], 255),
},
});
resetPassword.emailInput.placeholder = "Email";
passwordReset.emailInput.placeholder = "Email";
resetPassword.resetPasswordButton = resetPassword.window.button(20, 205, 260, 30, 'RESET PASSWORD', {
passwordReset.resetPasswordButton = passwordReset.window.button(20, 205, 260, 30, 'RESET PASSWORD', {
main: {
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], buttonAlpha),
textColour: toColour(primaryTextColour[0], primaryTextColour[1], primaryTextColour[2], 255),
@@ -95,7 +95,7 @@ function initResetPasswordGUI() {
},
}, checkResetPassword);
resetPassword.backToLoginButton = resetPassword.window.button(200, 240, 80, 15, 'LOGIN', {
passwordReset.backToLoginButton = passwordReset.window.button(200, 240, 80, 15, 'LOGIN', {
main: {
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], buttonAlpha),
textColour: toColour(primaryTextColour[0], primaryTextColour[1], primaryTextColour[2], 255),
@@ -108,7 +108,7 @@ function initResetPasswordGUI() {
},
}, switchToLoginGUI);
resetPassword.backToLoginLabel = resetPassword.window.text(125, 240, 60, 15, 'Remember your password?', {
passwordReset.backToLoginLabel = passwordReset.window.text(110, 240, 60, 15, 'Remember your password?', {
main: {
textSize: 8.0,
textAlign: 1.0,
@@ -130,48 +130,66 @@ function showResetPasswordGUI() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Showing password reset window`);
setChatWindowEnabled(false);
mexui.setInput(true);
resetPassword.window.shown = true;
mexui.focusedControl = resetPassword.emailInput;
guiSubmitButton = checkResetPassword;
passwordReset.window.shown = true;
mexui.focusedControl = passwordReset.emailInput;
guiSubmitKey = checkResetPassword;
showLocaleChooserGUI(new Vec2(getScreenWidth() / 2 - (localeChooser.window.size.x / 2), passwordReset.window.position.y + passwordReset.window.size.y + 20));
//showSmallGameMessage(`If you don't have a mouse cursor, press ${toUpperCase(getKeyNameFromId(disableGUIKey))} to disable GUI`, COLOUR_WHITE, 7500);
}
// ===========================================================================
function checkResetPassword() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Checking password reset with server ...`);
sendNetworkEventToServer("vrr.checkResetPassword", resetPassword.emailInput.lines[0]);
logToConsole(LOG_DEBUG, `[VRR.GUI] Checking password reset with server (${passwordReset.emailInput.lines[0]}) ...`);
sendNetworkEventToServer("vrr.checkResetPassword", passwordReset.emailInput.lines[0]);
}
// ===========================================================================
function resetPasswordFailed(errorMessage) {
logToConsole(LOG_DEBUG, `[VRR.GUI] Server reports password reset failed`);
resetPassword.messageLabel.text = errorMessage;
resetPassword.messageLabel.styles.main.textColour = toColour(180, 32, 32, 255);
resetPassword.emailInput.text = "";
passwordReset.messageLabel.text = errorMessage;
passwordReset.messageLabel.styles.main.textColour = toColour(180, 32, 32, 255);
passwordReset.emailInput.text = "";
}
// ===========================================================================
function resetPasswordCodeInputGUI() {
logToConsole(LOG_DEBUG, `[VRR.GUI] Server reports password reset was successful`);
resetPassword.messageLabel.text = "Check your email for a verification code";
resetPassword.messageLabel.styles.main.textColour = toColour(180, 32, 32, 255);
resetPassword.emailInput.text = "";
resetPassword.emailInput.placeholder = "Verification Code";
guiSubmitButton = checkResetPassword;
logToConsole(LOG_DEBUG | LOG_WARN, `[VRR.GUI] Server reports password reset email confirmation was successful. Asking for code ...`);
closeAllWindows();
passwordReset.messageLabel.text = getLocaleString("GUIResetPasswordCodeInputLabel");
//passwordReset.messageLabel.styles.main.textColour = toColour(180, 32, 32, 255);
passwordReset.emailInput.lines[0] = "";
passwordReset.emailInput.placeholder = getLocaleString("GUIResetPasswordCodePlaceholder");
guiSubmitKey = checkResetPassword;
showResetPasswordGUI();
}
// ===========================================================================
function resetPasswordEmailInputGUI() {
logToConsole(LOG_DEBUG | LOG_WARN, `[VRR.GUI] Server reports password reset request was approved. Asking for email ...`);
closeAllWindows();
passwordReset.messageLabel.text = getLocaleString("GUIResetPasswordConfirmEmailLabel");
//passwordReset.messageLabel.styles.main.textColour = toColour(180, 32, 32, 255);
passwordReset.emailInput.text = "";
passwordReset.emailInput.placeholder = getLocaleString("GUIResetPasswordEmailPlaceholder");
guiSubmitKey = checkResetPassword;
showResetPasswordGUI();
}
// ===========================================================================
function switchToLoginGUI() {
guiSubmitKey = false;
closeAllWindows();
showLoginGUI();
closeAllWindows();
showLoginGUI();
}
// ===========================================================================

View File

@@ -48,7 +48,7 @@ function initYesNoDialogGUI() {
},
});
yesNoDialog.yesButton = yesNoDialog.window.button(5, 100, 197, 25, 'YES', {
yesNoDialog.yesButton = yesNoDialog.window.button(5, 105, 193, 30, 'YES', {
main: {
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], buttonAlpha),
textColour: toColour(primaryTextColour[0], primaryTextColour[1], primaryTextColour[2], 255),
@@ -61,7 +61,7 @@ function initYesNoDialogGUI() {
},
}, yesNoDialogAnswerYes);
yesNoDialog.noButton = yesNoDialog.window.button(202, 105, 197, 25, 'NO', {
yesNoDialog.noButton = yesNoDialog.window.button(203, 105, 192, 30, 'NO', {
main: {
backgroundColour: toColour(primaryColour[0], primaryColour[1], primaryColour[2], buttonAlpha),
textColour: toColour(primaryTextColour[0], primaryTextColour[1], primaryTextColour[2], 255),
@@ -78,11 +78,21 @@ function initYesNoDialogGUI() {
// ===========================================================================
function showYesNoPromptGUI(promptMessage, promptTitle) {
function showYesNoPromptGUI(promptMessage, promptTitle, yesButtonText, noButtonText) {
closeAllWindows();
logToConsole(LOG_DEBUG, `[VRR.GUI] Showing prompt window. Prompt: ${promptTitle} - ${promptMessage}`);
mexui.setInput(true);
yesNoDialog.messageLabel.text = "";
yesNoDialog.yesButton.text = "";
yesNoDialog.noButton.text = "";
yesNoDialog.window.title = "";
yesNoDialog.messageLabel.text = promptMessage;
yesNoDialog.yesButton.text = yesButtonText;
yesNoDialog.noButton.text = noButtonText;
yesNoDialog.window.title = promptTitle;
yesNoDialog.window.shown = true;
}

View File

@@ -8,56 +8,79 @@
// ===========================================================================
class HouseData {
constructor(houseId, entrancePosition, blipModel, pickupModel, hasInterior) {
this.index = -1;
this.houseId = houseId;
this.entrancePosition = entrancePosition;
this.blipModel = blipModel;
this.pickupModel = pickupModel;
this.hasInterior = hasInterior;
this.blipId = -1;
}
constructor(houseId, description, entrancePosition, blipModel, pickupModel, hasInterior) {
this.index = -1;
this.houseId = houseId;
this.description = description;
this.entrancePosition = entrancePosition;
this.blipModel = blipModel;
this.pickupModel = pickupModel;
this.hasInterior = hasInterior;
this.blipId = -1;
}
}
// ===========================================================================
function receiveHouseFromServer(houseId, entrancePosition, blipModel, pickupModel, hasInterior) {
if(getGame() == VRR_GAME_GTA_IV) {
if(getHouseData(houseId) != false) {
if(blipModel == -1) {
natives.removeBlipAndClearIndex(getHouseData(houseId).blipId);
getHouseData(houseId).blipId = -1;
//houses.splice(getHouseData(houseId).index, 1);
//setAllHouseDataIndexes();
} else {
if(getHouseData(houseId).blipId != -1) {
natives.setBlipCoordinates(getHouseData(houseId).blipId, getHouseData(houseId).entrancePosition);
natives.changeBlipSprite(getHouseData(houseId).blipId, getHouseData(houseId).blipModel);
//natives.changeBlipNameFromAscii(getHouseData(houseId).blipId, `${name.substr(0, 24)}${(name.length > 24) ? " ...": ""}`);
} else {
let blipId = natives.addBlipForCoord(entrancePosition);
if(blipId) {
getHouseData(houseId).blipId = blipId;
natives.changeBlipSprite(blipId, blipModel);
natives.setBlipMarkerLongDistance(blipId, false);
}
}
}
} else {
let tempHouseData = new HouseData(houseId, entrancePosition, blipModel, pickupModel, hasInterior, hasItems);
if(blipModel != -1) {
let blipId = natives.addBlipForCoord(entrancePosition);
if(blipId) {
tempHouseData.blipId = blipId;
natives.changeBlipSprite(blipId, blipModel);
natives.setBlipMarkerLongDistance(blipId, false);
//natives.changeBlipNameFromAscii(blipId, `${name.substr(0, 24)}${(name.length > 24) ? " ...": ""}`);
}
}
houses.push(tempHouseData);
setAllHouseDataIndexes();
}
}
function receiveHouseFromServer(houseId, description, entrancePosition, blipModel, pickupModel, hasInterior) {
logToConsole(LOG_DEBUG, `[VRR.House] Received house ${houseId} (${name}) from server`);
if(!areServerElementsSupported()) {
if(getHouseData(houseId) != false) {
let houseData = getHouseData(houseId);
houseData.description = description;
houseData.entrancePosition = entrancePosition;
houseData.blipModel = blipModel;
houseData.pickupModel = pickupModel;
houseData.hasInterior = hasInterior;
logToConsole(LOG_DEBUG, `[VRR.House] House ${houseId} already exists. Checking blip ...`);
if(blipModel == -1) {
if(houseData.blipId != -1) {
logToConsole(LOG_DEBUG, `[VRR.House] House ${houseId}'s blip has been removed by the server`);
if(getGame() == VRR_GAME_GTA_IV) {
natives.removeBlipAndClearIndex(getHouseData(houseId).blipId);
} else {
destroyElement(getElementFromId(blipId));
}
houseData.blipId = -1;
} else {
logToConsole(LOG_DEBUG, `[VRR.House] House ${houseId}'s blip is unchanged`);
}
} else {
if(houseData.blipId != -1) {
logToConsole(LOG_DEBUG, `[VRR.House] House ${houseId}'s blip has been changed by the server`);
if(getGame() == VRR_GAME_GTA_IV) {
natives.setBlipCoordinates(houseData.blipId, houseData.entrancePosition);
natives.changeBlipSprite(houseData.blipId, houseData.blipModel);
natives.setBlipMarkerLongDistance(houseData.blipId, false);
natives.setBlipAsShortRange(houseData.blipId, true);
natives.changeBlipNameFromAscii(houseData.blipId, `${houseData.name.substr(0, 24)}${(houseData.name.length > 24) ? " ...": ""}`);
}
} else {
let blipId = createGameBlip(houseData.blipModel, houseData.entrancePosition, houseData.name);
if(blipId != -1) {
houseData.blipId = blipId;
}
logToConsole(LOG_DEBUG, `[VRR.House] House ${houseId}'s blip has been added by the server (Model ${blipModel}, ID ${blipId})`);
}
}
} else {
logToConsole(LOG_DEBUG, `[VRR.House] House ${houseId} doesn't exist. Adding ...`);
let tempHouseData = new HouseData(houseId, description, entrancePosition, blipModel, pickupModel, hasInterior);
if(blipModel != -1) {
let blipId = createGameBlip(tempHouseData.blipModel, tempHouseData.entrancePosition, "House");
if(blipId != -1) {
tempHouseData.blipId = blipId;
}
logToConsole(LOG_DEBUG, `[VRR.House] House ${houseId}'s blip has been added by the server (Model ${blipModel}, ID ${blipId})`);
} else {
logToConsole(LOG_DEBUG, `[VRR.House] House ${houseId} has no blip.`);
}
getServerData().houses.push(tempHouseData);
setAllHouseDataIndexes();
}
}
}
// ===========================================================================
@@ -66,17 +89,23 @@ function receiveHouseFromServer(houseId, entrancePosition, blipModel, pickupMode
* @param {number} houseId - The ID of the house (initially provided by server)
* @return {HouseData} The house's data (class instance)
*/
function getHouseData(houseId) {
let tempHouseData = houses.find((h) => h.houseId == houseId);
return (typeof tempHouseData != "undefined") ? tempHouseData : false;
function getHouseData(houseId) {
let houses = getServerData().houses;
for(let i in houses) {
if(houses[i].houseId == houseId) {
return houses[i];
}
}
return false;
}
// ===========================================================================
function setAllHouseDataIndexes() {
for(let i in houses) {
houses[i].index = i;
}
for(let i in getServerData().houses) {
getServerData().houses[i].index = i;
}
}
// ===========================================================================

View File

@@ -1,34 +0,0 @@
// For RAGEMP only
// Shared Scripts
require("../scripts/shared/const.js");
require("../scripts/shared/utilities.js");
require("../scripts/shared/gamedata.js");
// Multiplayer Mod (Wrapped Natives)
require("scripts/client/native/ragemp.js");
// Client Scripts
require("scripts/client/gui.js");
require("scripts/client/main.js");
require("scripts/client/nametag.js");
require("scripts/client/sync.js");
require("scripts/client/scoreboard.js");
require("scripts/client/keybind.js");
require("scripts/client/chatbox.js");
require("scripts/client/label.js");
require("scripts/client/skin-select.js");
require("scripts/client/server.js");
require("scripts/client/job.js");
require("scripts/client/event.js");
require("scripts/client/item.js");
require("scripts/client/utilities.js");
require("scripts/client/messaging.js");
require("scripts/client/logo.js");
require("scripts/client/afk.js");
require("scripts/client/mousecam.js");
require("scripts/client/radio.js");
require("scripts/client/animation.js");
// Startup
require("scripts/client/startup.js");

View File

@@ -23,40 +23,40 @@ function initItemScript() {
// ===========================================================================
function processItemActionRendering() {
if(renderItemActionDelay) {
if(itemActionDelayEnabled) {
let finishTime = itemActionDelayStart+itemActionDelayDuration;
if(sdl.ticks >= finishTime) {
itemActionDelayEnabled = false;
itemActionDelayDuration = 0;
itemActionDelayStart = 0;
tellServerItemActionDelayComplete();
} else {
let currentTick = sdl.ticks-itemActionDelayStart;
let progressPercent = Math.ceil(currentTick*100/itemActionDelayDuration);
let width = Math.ceil(getPercentage(itemActionDelaySize.x, progressPercent));
if(renderItemActionDelay) {
if(itemActionDelayEnabled) {
let finishTime = itemActionDelayStart+itemActionDelayDuration;
if(sdl.ticks >= finishTime) {
itemActionDelayEnabled = false;
itemActionDelayDuration = 0;
itemActionDelayStart = 0;
tellServerItemActionDelayComplete();
} else {
let currentTick = sdl.ticks-itemActionDelayStart;
let progressPercent = Math.ceil(currentTick*100/itemActionDelayDuration);
let width = Math.ceil(getPercentage(itemActionDelaySize.x, progressPercent));
let backgroundColour = toColour(0, 0, 0, 255);
graphics.drawRectangle(null, [itemActionDelayPosition.x-(itemActionDelaySize.x/2)-1, itemActionDelayPosition.y-(itemActionDelaySize.y/2)-1], [itemActionDelaySize.x+2, itemActionDelaySize.y+2], backgroundColour, backgroundColour, backgroundColour, backgroundColour);
graphics.drawRectangle(null, [itemActionDelayPosition.x-(itemActionDelaySize.x/2), itemActionDelayPosition.y-(itemActionDelaySize.y/2)-2], [width, itemActionDelaySize.y], COLOUR_LIME, COLOUR_LIME, COLOUR_LIME, COLOUR_LIME);
}
}
}
let backgroundColour = toColour(0, 0, 0, 255);
graphics.drawRectangle(null, [itemActionDelayPosition.x-(itemActionDelaySize.x/2)-1, itemActionDelayPosition.y-(itemActionDelaySize.y/2)-1], [itemActionDelaySize.x+2, itemActionDelaySize.y+2], backgroundColour, backgroundColour, backgroundColour, backgroundColour);
graphics.drawRectangle(null, [itemActionDelayPosition.x-(itemActionDelaySize.x/2), itemActionDelayPosition.y-(itemActionDelaySize.y/2)-2], [width, itemActionDelaySize.y], COLOUR_LIME, COLOUR_LIME, COLOUR_LIME, COLOUR_LIME);
}
}
}
}
// ===========================================================================
function updatePlayerHotBar(activeSlot, itemsArray) {
logToConsole(LOG_DEBUG, `[VRR.Main] Updating hotbar`);
logToConsole(LOG_DEBUG, `[VRR.Main] Updating hotbar`);
}
// ===========================================================================
function showItemActionDelay(duration) {
itemActionDelayDuration = duration;
itemActionDelayStart = sdl.ticks;
itemActionDelayEnabled = true;
logToConsole(LOG_DEBUG, `Item action delay started. Duration: ${itemActionDelayDuration}, Start: ${itemActionDelayStart}, Rendering Enabled: ${renderItemActionDelay}`);
itemActionDelayDuration = duration;
itemActionDelayStart = sdl.ticks;
itemActionDelayEnabled = true;
logToConsole(LOG_DEBUG, `Item action delay started. Duration: ${itemActionDelayDuration}, Start: ${itemActionDelayStart}, Rendering Enabled: ${renderItemActionDelay}`);
}
// ===========================================================================

View File

@@ -12,6 +12,26 @@ let localPlayerWorking = false;
let jobRouteLocationBlip = null;
let jobRouteLocationSphere = null;
let jobBlipBlinkAmount = 0;
let jobBlipBlinkTimes = 10;
let jobBlipBlinkInterval = 500;
let jobBlipBlinkTimer = null;
// ===========================================================================
class JobData {
constructor(jobId, jobLocationId, name, position, blipModel, pickupModel) {
this.index = -1;
this.jobId = jobId;
this.jobLocationId = jobLocationId;
this.name = name;
this.position = position;
this.blipModel = blipModel;
this.pickupModel = pickupModel;
this.blipId = -1;
}
}
// ===========================================================================
function initJobScript() {
@@ -22,74 +42,182 @@ function initJobScript() {
// ===========================================================================
function setLocalPlayerJobType(tempJobType) {
logToConsole(LOG_DEBUG, `[VRR.Main] Set local player job type to ${tempJobType}`);
localPlayerJobType = tempJobType;
logToConsole(LOG_DEBUG, `[VRR.Job] Set local player job type to ${tempJobType}`);
localPlayerJobType = tempJobType;
}
// ===========================================================================
function setLocalPlayerWorkingState(tempWorking) {
logToConsole(LOG_DEBUG, `[VRR.Main] Setting working state to ${tempWorking}`);
localPlayerWorking = tempWorking;
logToConsole(LOG_DEBUG, `[VRR.Job] Setting working state to ${tempWorking}`);
localPlayerWorking = tempWorking;
}
// ===========================================================================
function showJobRouteLocation(position, colour) {
logToConsole(LOG_DEBUG, `[VRR.Job] Showing job route location`);
if(getMultiplayerMod() == VRR_MPMOD_GTAC) {
if(game.game == VRR_GAME_GTA_SA) {
jobRouteLocationSphere = game.createPickup(1318, position, 1);
} else {
jobRouteLocationSphere = game.createSphere(position, 3);
jobRouteLocationSphere.colour = colour;
}
logToConsole(LOG_DEBUG, `[VRR.Job] Showing job route location`);
if(getMultiplayerMod() == VRR_MPMOD_GTAC) {
if(getGame() == VRR_GAME_GTA_SA) {
// Server-side spheres don't show in GTA SA for some reason.
jobRouteLocationSphere = game.createPickup(1318, position, 1);
} else {
jobRouteLocationSphere = game.createSphere(position, 3);
jobRouteLocationSphere.colour = colour;
}
if(jobRouteLocationBlip != null) {
destroyElement(jobRouteLocationBlip);
}
if(jobRouteLocationBlip != null) {
destroyElement(jobRouteLocationBlip);
}
blinkJobRouteLocationBlip(10, position, colour);
}
// Blinking is bugged if player hit the spot before it stops blinking.
blinkJobRouteLocationBlip(10, position, colour);
jobRouteLocationBlip = game.createBlip(position, 0, 2, colour);
}
}
// ===========================================================================
function enteredJobRouteSphere() {
logToConsole(LOG_DEBUG, `[VRR.Job] Entered job route sphere`);
tellServerPlayerArrivedAtJobRouteLocation();
destroyElement(jobRouteLocationSphere);
destroyElement(jobRouteLocationBlip);
jobRouteLocationSphere = null;
jobRouteLocationBlip = null;
logToConsole(LOG_DEBUG, `[VRR.Job] Entered job route sphere`);
clearInterval(jobBlipBlinkTimer);
jobBlipBlinkAmount = 0;
jobBlipBlinkTimes = 0;
if(jobRouteLocationBlip != null) {
destroyElement(jobRouteLocationBlip);
jobRouteLocationBlip = null;
}
if(jobRouteLocationSphere != null) {
destroyElement(jobRouteLocationSphere);
jobRouteLocationSphere = null;
}
tellServerPlayerArrivedAtJobRouteLocation();
}
// ===========================================================================
function blinkJobRouteLocationBlip(times, position, colour) {
for(let i = 1 ; i <= times ; i++) {
setTimeout(function() {
if(jobRouteLocationBlip != null) {
destroyElement(jobRouteLocationBlip);
jobRouteLocationBlip = null;
} else {
jobRouteLocationBlip = game.createBlip(position, 0, 2, colour);
}
}, 500*i);
}
jobBlipBlinkTimes = times;
jobBlipBlinkTimer = setInterval(function() {
if(jobRouteLocationBlip != null) {
destroyElement(jobRouteLocationBlip);
jobRouteLocationBlip = null;
} else {
jobRouteLocationBlip = game.createBlip(position, 0, 2, colour);
}
setTimeout(function() {
jobRouteLocationBlip = game.createBlip(position, 0, 2, colour);
}, 500*times+1);
if(jobBlipBlinkAmount >= jobBlipBlinkTimes) {
if(jobRouteLocationBlip != null) {
destroyElement(jobRouteLocationBlip);
jobRouteLocationBlip = null;
}
jobBlipBlinkAmount = 0;
jobBlipBlinkTimes = 0;
jobRouteLocationBlip = game.createBlip(position, 0, 2, colour);
clearInterval(jobBlipBlinkTimer);
}
}, jobBlipBlinkInterval);
}
// ===========================================================================
function hideJobRouteLocation() {
destroyElement(jobRouteLocationSphere);
destroyElement(jobRouteLocationBlip);
jobRouteLocationSphere = null;
jobRouteLocationBlip = null;
destroyElement(jobRouteLocationSphere);
destroyElement(jobRouteLocationBlip);
jobRouteLocationSphere = null;
jobRouteLocationBlip = null;
}
// ===========================================================================
function receiveJobFromServer(jobId, jobLocationId, name, position, blipModel, pickupModel) {
logToConsole(LOG_DEBUG, `[VRR.Job] Received job ${jobId} (${name}) from server`);
if(getGame() == VRR_GAME_GTA_IV) {
if(getJobData(jobId) != false) {
let jobData = getJobData(jobId);
jobData.jobLocationId = jobLocationId;
jobData.name = name;
jobData.position = position;
jobData.blipModel = blipModel;
jobData.pickupModel = pickupModel;
logToConsole(LOG_DEBUG, `[VRR.Job] Job ${jobId} already exists. Checking blip ...`);
if(blipModel == -1) {
if(jobData.blipId != -1) {
logToConsole(LOG_DEBUG, `[VRR.Job] Job ${jobId}'s blip has been removed by the server`);
if(getGame() == VRR_GAME_GTA_IV) {
natives.removeBlipAndClearIndex(getJobData(jobId).blipId);
} else {
destroyElement(getElementFromId(blipId));
}
jobData.blipId = -1;
} else {
logToConsole(LOG_DEBUG, `[VRR.Job] Job ${jobId}'s blip is unchanged`);
}
} else {
if(jobData.blipId != -1) {
logToConsole(LOG_DEBUG, `[VRR.Job] Job ${jobId}'s blip has been changed by the server`);
if(getGame() == VRR_GAME_GTA_IV) {
natives.setBlipCoordinates(jobData.blipId, jobData.position);
natives.changeBlipSprite(jobData.blipId, jobData.blipModel);
natives.setBlipMarkerLongDistance(jobData.blipId, false);
natives.setBlipAsShortRange(jobData.blipId, true);
natives.changeBlipNameFromAscii(jobData.blipId, `${jobData.name.substr(0, 24)}${(jobData.name.length > 24) ? " ...": ""}`);
}
} else {
let blipId = createGameBlip(jobData.blipModel, jobData.position, jobData.name);
if(blipId != -1) {
jobData.blipId = blipId;
}
logToConsole(LOG_DEBUG, `[VRR.Job] Job ${jobId}'s blip has been added by the server (Model ${blipModel}, ID ${blipId})`);
}
}
} else {
logToConsole(LOG_DEBUG, `[VRR.Job] Job ${jobId} doesn't exist. Adding ...`);
let tempJobData = new JobData(jobId, jobLocationId, name, position, blipModel, pickupModel);
if(blipModel != -1) {
let blipId = createGameBlip(blipModel, tempJobData.position, tempJobData.name);
if(blipId != -1) {
tempJobData.blipId = blipId;
}
logToConsole(LOG_DEBUG, `[VRR.Job] Job ${jobId}'s blip has been added by the server (Model ${blipModel}, ID ${blipId})`);
} else {
logToConsole(LOG_DEBUG, `[VRR.Job] Job ${jobId} has no blip.`);
}
getServerData().jobs.push(tempJobData);
setAllJobDataIndexes();
}
}
}
// ===========================================================================
/**
* @param {number} job - The ID of the job (initially provided by server)
* @return {JobData} The job's data (class instance)
*/
function getJobData(jobId) {
for(let i in getServerData().jobs) {
if(getServerData().jobs[i].jobId == jobId) {
return getServerData().jobs[i];
}
}
return false;
}
// ===========================================================================
function setAllJobDataIndexes() {
for(let i in getServerData().jobs) {
jobs[i].index = i;
}
}
// ===========================================================================

View File

@@ -1,14 +1,14 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"moduleResolution": "classic"
},
"include": [
"*.js",
"gui/*.js",
"native/*.js",
"../shared/*.js",
"../third-party/mexui/*"
]
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"moduleResolution": "classic"
},
"include": [
"*.js",
"gui/*.js",
"native/*.js",
"../shared/*.js",
"../third-party/mexui/*"
]
}

View File

@@ -23,71 +23,71 @@ function initKeyBindScript() {
// ===========================================================================
function bindAccountKey(key, keyState) {
logToConsole(LOG_DEBUG, `[VRR.KeyBind]: Binded key ${toUpperCase(getKeyNameFromId(key))} (${key})`);
keyBinds.push(toInteger(key));
bindKey(toInteger(key), keyState, function(event) {
if(isAnyGUIActive()) {
return false;
}
logToConsole(LOG_DEBUG, `[VRR.KeyBind]: Binded key ${toUpperCase(getKeyNameFromId(key))} (${key})`);
keyBinds.push(toInteger(key));
bindKey(toInteger(key), keyState, function(event) {
if(isAnyGUIActive()) {
return false;
}
if(hasKeyBindDelayElapsed()) {
if(canLocalPlayerUseKeyBinds()) {
logToConsole(LOG_DEBUG, `[VRR.KeyBind]: Using keybind for key ${toUpperCase(getKeyNameFromId(key))} (${key})`);
lastKeyBindUse = sdl.ticks;
tellServerPlayerUsedKeyBind(key);
} else {
logToConsole(LOG_DEBUG, `[VRR.KeyBind]: Failed to use keybind for key ${toUpperCase(getKeyNameFromId(key))} (${key}) - Not allowed to use keybinds!`);
}
} else {
logToConsole(LOG_DEBUG, `[VRR.KeyBind]: Failed to use keybind for key ${toUpperCase(getKeyNameFromId(key))} (${key}) - Not enough time has passed since last keybind use!`);
}
});
if(hasKeyBindDelayElapsed()) {
if(canLocalPlayerUseKeyBinds()) {
logToConsole(LOG_DEBUG, `[VRR.KeyBind]: Using keybind for key ${toUpperCase(getKeyNameFromId(key))} (${key})`);
lastKeyBindUse = sdl.ticks;
tellServerPlayerUsedKeyBind(key);
} else {
logToConsole(LOG_DEBUG, `[VRR.KeyBind]: Failed to use keybind for key ${toUpperCase(getKeyNameFromId(key))} (${key}) - Not allowed to use keybinds!`);
}
} else {
logToConsole(LOG_DEBUG, `[VRR.KeyBind]: Failed to use keybind for key ${toUpperCase(getKeyNameFromId(key))} (${key}) - Not enough time has passed since last keybind use!`);
}
});
}
// ===========================================================================
function unBindAccountKey(key) {
logToConsole(LOG_DEBUG, `[VRR.KeyBind]: Unbinded key ${toUpperCase(getKeyNameFromId(key))} (${key})`);
unbindKey(key);
keyBinds.splice(keyBinds.indexOf(key), 1);
return true;
logToConsole(LOG_DEBUG, `[VRR.KeyBind]: Unbinded key ${toUpperCase(getKeyNameFromId(key))} (${key})`);
unbindKey(key);
keyBinds.splice(keyBinds.indexOf(key), 1);
return true;
}
// ===========================================================================
function hasKeyBindDelayElapsed() {
if(sdl.ticks-lastKeyBindUse >= keyBindDelayTime) {
return true;
}
if(sdl.ticks-lastKeyBindUse >= keyBindDelayTime) {
return true;
}
return false;
return false;
}
// ===========================================================================
function canLocalPlayerUseKeyBinds() {
if(isAnyGUIActive()) {
return false;
}
if(isAnyGUIActive()) {
return false;
}
if(!isSpawned) {
return false;
}
if(!isSpawned) {
return false;
}
if(itemActionDelayEnabled) {
return false;
}
if(itemActionDelayEnabled) {
return false;
}
return true;
return true;
}
// ===========================================================================
function clearKeyBinds() {
for(let i in keyBinds) {
unbindKey(keyBinds[i]);
}
keyBinds = [];
for(let i in keyBinds) {
unbindKey(keyBinds[i]);
}
keyBinds = [];
}
// ===========================================================================

View File

@@ -42,268 +42,343 @@ function initLabelScript() {
// ===========================================================================
function initLabelPropertyNameFont() {
return lucasFont.createDefaultFont(16.0, "Roboto", "Regular");
return lucasFont.createDefaultFont(16.0, "Roboto", "Regular");
}
// ===========================================================================
function initLabelPropertyLockedFont() {
return lucasFont.createDefaultFont(12.0, "Roboto", "Light");
return lucasFont.createDefaultFont(12.0, "Roboto", "Light");
}
// ===========================================================================
function initLabelJobNameFont() {
return lucasFont.createDefaultFont(16.0, "Roboto", "Regular");
return lucasFont.createDefaultFont(16.0, "Roboto", "Regular");
}
// ===========================================================================
function initLabelJobHelpFont() {
return lucasFont.createDefaultFont(10.0, "Roboto", "Light");
return lucasFont.createDefaultFont(10.0, "Roboto", "Light");
}
// ===========================================================================
function renderPropertyEntranceLabel(name, position, locked, isBusiness, price, rentPrice, labelInfoType) {
if(localPlayer == null) {
return false;
}
if(localPlayer == null) {
return false;
}
if(propertyLabelNameFont == null) {
return false;
}
}
if(propertyLabelLockedFont == null) {
return false;
}
}
let tempPosition = position;
tempPosition.z = tempPosition.z + propertyLabelHeight;
let screenPosition = getScreenFromWorldPosition(tempPosition);
if(getGame() == VRR_GAME_GTA_IV) {
if(!natives.doesViewportExist(natives.getGameViewportId())) {
logToConsole(LOG_INFO, "[VRR.Label]: Game viewport does not exist!");
return false;
}
if(screenPosition.x < 0 || screenPosition.x > game.width) {
return false;
}
if(!natives.isViewportActive(natives.getGameViewportId())) {
logToConsole(LOG_INFO, "[VRR.Label]: Game viewport is not active!");
return false;
}
}
let text = "";
if(price > "0") {
text = `For sale: $${price}`;
let size = propertyLabelLockedFont.measure(text, game.width, 0.0, 0.0, propertyLabelLockedFont.size, true, true);
propertyLabelLockedFont.render(text, [screenPosition.x-size[0]/2, screenPosition.y-size[1]/2], game.width, 0.0, 0.0, propertyLabelLockedFont.size, toColour(200, 200, 200, 255), false, true, false, true);
let tempPosition = position;
tempPosition.z = tempPosition.z + propertyLabelHeight;
let screenPosition = new Vec3(0.0, 0.0, 0.0);
if(getGame() == VRR_GAME_GTA_IV) {
screenPosition = natives.getViewportPositionOfCoord(tempPosition, natives.getGameViewportId());
} else {
screenPosition = getScreenFromWorldPosition(tempPosition);
}
screenPosition.y -= propertyLabelPriceOffset;
}
if(screenPosition.x < 0 || screenPosition.x > game.width) {
return false;
}
text = "";
if(rentPrice != "0") {
text = `For rent: $${rentPrice} every payday`;
let size = propertyLabelLockedFont.measure(text, game.width, 0.0, 0.0, propertyLabelLockedFont.size, true, true);
propertyLabelLockedFont.render(text, [screenPosition.x-size[0]/2, screenPosition.y-size[1]/2], game.width, 0.0, 0.0, propertyLabelLockedFont.size, toColour(200, 200, 200, 255), false, true, false, true);
let text = "";
if(price > "0") {
text = getLocaleString("PropertyForSaleLabel", price);
let size = propertyLabelLockedFont.measure(text, game.width, 0.0, 0.0, propertyLabelLockedFont.size, true, true);
propertyLabelLockedFont.render(text, [screenPosition.x-size[0]/2, screenPosition.y-size[1]/2], game.width, 0.0, 0.0, propertyLabelLockedFont.size, toColour(200, 200, 200, 255), false, true, false, true);
screenPosition.y -= propertyLabelPriceOffset;
}
screenPosition.y -= propertyLabelPriceOffset;
}
text = "";
if(rentPrice != "0") {
text = getLocaleString("PropertyForRentLabel", rentPrice);
let size = propertyLabelLockedFont.measure(text, game.width, 0.0, 0.0, propertyLabelLockedFont.size, true, true);
propertyLabelLockedFont.render(text, [screenPosition.x-size[0]/2, screenPosition.y-size[1]/2], game.width, 0.0, 0.0, propertyLabelLockedFont.size, toColour(200, 200, 200, 255), false, true, false, true);
if(isBusiness) {
text = (locked) ? "CLOSED" : "OPEN";
} else {
text = (locked) ? "LOCKED" : "UNLOCKED";
}
screenPosition.y -= propertyLabelPriceOffset;
}
if(!locked && labelInfoType != VRR_PROPLABEL_INFO_NONE) {
let infoText = "";
switch(labelInfoType) {
case VRR_PROPLABEL_INFO_ENTER:
if(enterPropertyKey) {
infoText = `Press ${toUpperCase(getKeyNameFromId(enterPropertyKey))} to enter`;
} else {
infoText = `Use /enter to enter`;
}
break;
if(isBusiness) {
text = (locked) ? toUpperCase(getLocaleString("Closed")) : toUpperCase(getLocaleString("Open"));
} else {
text = (locked) ? toUpperCase(getLocaleString("Locked")) : toUpperCase(getLocaleString("Unlocked"));
}
case VRR_PROPLABEL_INFO_BUY:
infoText = `Use /buy to purchase items`;
break;
if(!locked && labelInfoType != VRR_PROPLABEL_INFO_NONE) {
let infoText = "";
switch(labelInfoType) {
case VRR_PROPLABEL_INFO_ENTER: {
if(enterPropertyKey) {
infoText = getLocaleString("PropertyEnterKeyPressLabel", toUpperCase(getKeyNameFromId(enterPropertyKey)));
} else {
infoText = getLocaleString("PropertyEnterCommandLabel", "/enter");
}
break;
}
case VRR_PROPLABEL_INFO_BUYBIZ:
infoText = `Use /buy to purchase items`;
break;
case VRR_PROPLABEL_INFO_BUY: {
infoText = getLocaleString("BusinessBuyItemsLabel", "/buy");
break;
}
//case VRR_PROPLABEL_INFO_RENTBIZ:
// infoText = `Use /bizrent to buy this business`;
// break;
case VRR_PROPLABEL_INFO_BUYBIZ: {
infoText = getLocaleString("BuyBusinessLabel", "/bizbuy");
break;
}
case VRR_PROPLABEL_INFO_BUYHOUSE:
infoText = `Use /housebuy to buy this house`;
break;
case VRR_PROPLABEL_INFO_BUYHOUSE: {
infoText = getLocaleString("BuyHouseLabel", "/housebuy");
break;
}
case VRR_PROPLABEL_INFO_RENTHOUSE:
infoText = `Use /houserent to rent this house`;
break;
case VRR_PROPLABEL_INFO_RENTHOUSE: {
infoText = getLocaleString("RentHouseLabel", "/houserent");
break;
}
case VRR_PROPLABEL_INFO_ENTERVEH:
infoText = "Enter a vehicle in the parking lot to buy it";
break;
case VRR_PROPLABEL_INFO_ENTERVEHICLE: {
infoText = getLocaleString("VehicleDealershipLabel");
break;
}
case VRR_PROPLABEL_INFO_NONE:
default:
infoText = "";
break;
}
if(getDistance(localPlayer.position, position) <= renderLabelDistance-2) {
let size = propertyLabelLockedFont.measure(infoText, game.width, 0.0, 0.0, propertyLabelLockedFont.size, true, true);
propertyLabelLockedFont.render(infoText, [screenPosition.x-size[0]/2, screenPosition.y-size[1]/2], game.width, 0.0, 0.0, propertyLabelLockedFont.size, toColour(234, 198, 126, 255), false, true, false, true);
screenPosition.y -= propertyLabelLockedOffset;
}
}
default: {
if(enterPropertyKey) {
infoText = getLocaleString("PropertyEnterKeyPressLabel", toUpperCase(getKeyNameFromId(enterPropertyKey)));
} else {
infoText = getLocaleString("PropertyEnterCommandLabel", "/enter");
}
break;
}
}
if(getDistance(localPlayer.position, position) <= renderLabelDistance-2) {
let size = propertyLabelLockedFont.measure(infoText, game.width, 0.0, 0.0, propertyLabelLockedFont.size, true, true);
propertyLabelLockedFont.render(infoText, [screenPosition.x-size[0]/2, screenPosition.y-size[1]/2], game.width, 0.0, 0.0, propertyLabelLockedFont.size, toColour(234, 198, 126, 255), false, true, false, true);
screenPosition.y -= propertyLabelLockedOffset;
}
}
let size = propertyLabelLockedFont.measure(text, game.width, 0.0, 0.0, propertyLabelLockedFont.size, true, true);
propertyLabelLockedFont.render(text, [screenPosition.x-size[0]/2, screenPosition.y-size[1]/2], game.width, 0.0, 0.0, propertyLabelLockedFont.size, (locked) ? lockedColour : unlockedColour, false, true, false, true);
let size = propertyLabelLockedFont.measure(text, game.width, 0.0, 0.0, propertyLabelLockedFont.size, true, true);
propertyLabelLockedFont.render(text, [screenPosition.x-size[0]/2, screenPosition.y-size[1]/2], game.width, 0.0, 0.0, propertyLabelLockedFont.size, (locked) ? lockedColour : unlockedColour, false, true, false, true);
screenPosition.y -= propertyLabelNameOffset;
screenPosition.y -= propertyLabelNameOffset;
text = name || " ";
size = propertyLabelNameFont.measure(text, game.width, 0.0, 0.0, propertyLabelNameFont.size, true, true);
propertyLabelNameFont.render(text, [screenPosition.x-size[0]/2, screenPosition.y-size[1]/2], game.width, 0.0, 0.0, propertyLabelNameFont.size, (isBusiness) ? toColour(0, 153, 255, 255) : toColour(17, 204, 17, 255), false, true, false, true);
text = name || " ";
size = propertyLabelNameFont.measure(text, game.width, 0.0, 0.0, propertyLabelNameFont.size, true, true);
propertyLabelNameFont.render(text, [screenPosition.x-size[0]/2, screenPosition.y-size[1]/2], game.width, 0.0, 0.0, propertyLabelNameFont.size, (isBusiness) ? toColour(0, 153, 255, 255) : toColour(17, 204, 17, 255), false, true, false, true);
}
// -------------------------------------------------------------------------
function renderPropertyExitLabel(position) {
if(localPlayer == null) {
return false;
}
if(localPlayer == null) {
return false;
}
if(propertyLabelNameFont == null) {
return false;
}
}
if(propertyLabelLockedFont == null) {
return false;
}
let tempPosition = position;
tempPosition.z = tempPosition.z + propertyLabelHeight;
let screenPosition = getScreenFromWorldPosition(tempPosition);
if(getGame() == VRR_GAME_GTA_IV) {
if(!natives.doesViewportExist(natives.getGameViewportId())) {
logToConsole(LOG_INFO, "[VRR.Label]: Game viewport does not exist!");
return false;
}
if(screenPosition.x < 0 || screenPosition.x > game.width) {
return false;
}
if(!natives.isViewportActive(natives.getGameViewportId())) {
logToConsole(LOG_INFO, "[VRR.Label]: Game viewport is not active!");
return false;
}
}
let text = "EXIT";
let size = propertyLabelNameFont.measure(text, game.width, 0.0, 0.0, propertyLabelNameFont.size, true, true);
propertyLabelNameFont.render(text, [screenPosition.x-size[0]/2, screenPosition.y-size[1]/2], game.width, 0.0, 0.0, propertyLabelNameFont.size, COLOUR_WHITE, false, true, false, true);
let tempPosition = position;
tempPosition.z = tempPosition.z + propertyLabelHeight;
let screenPosition = new Vec3(0.0, 0.0, 0.0);
if(getGame() == VRR_GAME_GTA_IV) {
screenPosition = natives.getViewportPositionOfCoord(tempPosition, natives.getGameViewportId());
} else {
screenPosition = getScreenFromWorldPosition(tempPosition);
}
if(screenPosition.x < 0 || screenPosition.x > game.width) {
return false;
}
let text = "EXIT";
let size = propertyLabelNameFont.measure(text, game.width, 0.0, 0.0, propertyLabelNameFont.size, true, true);
propertyLabelNameFont.render(text, [screenPosition.x-size[0]/2, screenPosition.y-size[1]/2], game.width, 0.0, 0.0, propertyLabelNameFont.size, COLOUR_WHITE, false, true, false, true);
}
// -------------------------------------------------------------------------
function renderJobLabel(name, position, jobType) {
if(localPlayer == null) {
return false;
}
if(localPlayer == null) {
return false;
}
if(jobNameLabelFont == null) {
return false;
}
}
if(jobHelpLabelFont == null) {
return false;
}
let tempPosition = position;
tempPosition.z = tempPosition.z + propertyLabelHeight;
let screenPosition = getScreenFromWorldPosition(tempPosition);
if(getGame() == VRR_GAME_GTA_IV) {
if(!natives.doesViewportExist(natives.getGameViewportId())) {
logToConsole(LOG_INFO, "[VRR.Label]: Game viewport does not exist!");
return false;
}
if(screenPosition.x < 0 || screenPosition.x > game.width) {
return false;
}
if(!natives.isViewportActive(natives.getGameViewportId())) {
logToConsole(LOG_INFO, "[VRR.Label]: Game viewport is not active!");
return false;
}
}
let text = "";
if(jobType == localPlayerJobType) {
if(localPlayerWorking) {
text = "Use /uniform and /equip for job stuff, or /stopwork to go off duty";
} else {
text = "Use /startwork to go on duty";
}
} else {
if(localPlayerJobType == 0) {
text = "Use /takejob to work here";
} else {
text = "You already have a job. Use /quitjob if you want this one";
}
}
let tempPosition = position;
tempPosition.z = tempPosition.z + propertyLabelHeight;
let screenPosition = new Vec3(0.0, 0.0, 0.0);
if(getGame() == VRR_GAME_GTA_IV) {
screenPosition = natives.getViewportPositionOfCoord(tempPosition, natives.getGameViewportId());
} else {
screenPosition = getScreenFromWorldPosition(tempPosition);
}
let size = jobHelpLabelFont.measure(text, game.width, 0.0, 0.0, jobHelpLabelFont.size, true, true);
jobHelpLabelFont.render(text, [screenPosition.x-size[0]/2, screenPosition.y-size[1]/2], game.width, 0.0, 0.0, jobHelpLabelFont.size, COLOUR_YELLOW, false, true, false, true);
if(screenPosition.x < 0 || screenPosition.x > game.width) {
return false;
}
screenPosition.y -= 18;
let text = "";
if(jobType == localPlayerJobType) {
if(localPlayerWorking) {
text = getLocaleString("JobEquipAndUniformLabel", "/equip", "/uniform", "/stopwork");
} else {
text = getLocaleString("StartWorkLabel", "/startwork");
}
} else {
if(localPlayerJobType == 0) {
text = getLocaleString("TakeJobLabel", "/takejob");
} else {
text = getLocaleString("NotYourJobLabel", "/quitjob");
}
}
text = name + " Job";
size = jobNameLabelFont.measure(text, game.width, 0.0, 0.0, jobNameLabelFont.size, true, true);
jobNameLabelFont.render(text, [screenPosition.x-size[0]/2, screenPosition.y-size[1]/2], game.width, 0.0, 0.0, jobNameLabelFont.size, COLOUR_WHITE, false, true, false, true);
let size = jobHelpLabelFont.measure(text, game.width, 0.0, 0.0, jobHelpLabelFont.size, true, true);
jobHelpLabelFont.render(text, [screenPosition.x-size[0]/2, screenPosition.y-size[1]/2], game.width, 0.0, 0.0, jobHelpLabelFont.size, COLOUR_YELLOW, false, true, false, true);
screenPosition.y -= 18;
text = getLocaleString("JobLabel", name);
size = jobNameLabelFont.measure(text, game.width, 0.0, 0.0, jobNameLabelFont.size, true, true);
jobNameLabelFont.render(text, [screenPosition.x-size[0]/2, screenPosition.y-size[1]/2], game.width, 0.0, 0.0, jobNameLabelFont.size, COLOUR_WHITE, false, true, false, true);
}
// -------------------------------------------------------------------------
function processLabelRendering() {
if(renderLabels) {
if(!areServerElementsSupported()) {
if(localPlayer != null) {
for(let i in businesses) {
if(getDistance(localPlayer.position, businesses[i].entrancePosition) <= 75.0) {
natives.drawColouredCylinder(getPosBelowPos(businesses[i].entrancePosition, 1.0), 0.0, 0.0, 0, 153, 255, 255);
}
}
}
}
if(areWorldLabelsSupported()) {
if(localPlayer != null) {
let pickups = getElementsByType(ELEMENT_PICKUP);
for(let i in pickups) {
if(pickups[i].getData("vrr.label.type") != null) {
if(getDistance(localPlayer.position, pickups[i].position) <= renderLabelDistance) {
if(!pickups[i].isOnScreen) {
let price = "0";
let rentPrice = "0";
let labelInfoType = VRR_PROPLABEL_INFO_NONE;
if(pickups[i].getData("vrr.label.price") != null) {
price = makeLargeNumberReadable(pickups[i].getData("vrr.label.price"));
}
if(pickups[i].getData("vrr.label.rentprice") != null) {
rentPrice = makeLargeNumberReadable(pickups[i].getData("vrr.label.rentprice"));
}
if(pickups[i].getData("vrr.label.help") != null) {
labelInfoType = pickups[i].getData("vrr.label.help");
}
switch(pickups[i].getData("vrr.label.type")) {
case VRR_LABEL_BUSINESS:
renderPropertyEntranceLabel(pickups[i].getData("vrr.label.name"), pickups[i].position, pickups[i].getData("vrr.label.locked"), true, price, rentPrice, labelInfoType);
break;
case VRR_LABEL_HOUSE:
renderPropertyEntranceLabel("House", pickups[i].position, pickups[i].getData("vrr.label.locked"), false, price, rentPrice, labelInfoType);
break;
case VRR_LABEL_JOB:
renderJobLabel(pickups[i].getData("vrr.label.name"), pickups[i].position, pickups[i].getData("vrr.label.jobType"));
break;
case VRR_LABEL_EXIT:
renderPropertyExitLabel(pickups[i].position);
break;
}
}
}
}
}
}
}
}
if(renderLabels) {
if(!areServerElementsSupported()) {
if(localPlayer != null) {
getServerData().businesses.forEach((business) => {
if(getDistance(localPlayer.position, business.entrancePosition) <= 75.0) {
natives.drawColouredCylinder(getPosBelowPos(business.entrancePosition, 1.0), 0.0, 0.0, 0, 153, 255, 255);
//renderPropertyEntranceLabel(business.name, business.entrancePosition, business.locked, true, makeLargeNumberReadable(business.price), makeLargeNumberReadable(business.rentPrice), business.labelInfoType);
}
});
getServerData().houses.forEach((house) => {
if(getDistance(localPlayer.position, house.entrancePosition) <= 75.0) {
natives.drawColouredCylinder(getPosBelowPos(house.entrancePosition, 1.0), 0.0, 0.0, 0, 200, 0, 255);
//renderPropertyEntranceLabel("House", house.entrancePosition, house.locked, true, makeLargeNumberReadable(house.price), makeLargeNumberReadable(house.rentPrice), 0);
}
});
getServerData().jobs.forEach((job) => {
if(getDistance(localPlayer.position, job.position) <= 75.0) {
natives.drawColouredCylinder(getPosBelowPos(job.position, 1.0), 0.0, 0.0, 255, 255, 0, 255);
//renderJobLabel(job.name, job.position, job.jobType);
}
});
}
}
if(areWorldLabelsSupported()) {
if(localPlayer != null) {
let pickups = getElementsByType(ELEMENT_PICKUP);
for(let i in pickups) {
if(pickups[i].getData("vrr.label.type") != null) {
if(getDistance(localPlayer.position, pickups[i].position) <= renderLabelDistance) {
if(!pickups[i].isOnScreen) {
let price = "0";
let rentPrice = "0";
let labelInfoType = VRR_PROPLABEL_INFO_NONE;
if(pickups[i].getData("vrr.label.price") != null) {
price = makeLargeNumberReadable(pickups[i].getData("vrr.label.price"));
}
if(pickups[i].getData("vrr.label.rentprice") != null) {
rentPrice = makeLargeNumberReadable(pickups[i].getData("vrr.label.rentprice"));
}
if(pickups[i].getData("vrr.label.help") != null) {
labelInfoType = pickups[i].getData("vrr.label.help");
}
switch(pickups[i].getData("vrr.label.type")) {
case VRR_LABEL_BUSINESS: {
renderPropertyEntranceLabel(pickups[i].getData("vrr.label.name"), pickups[i].position, pickups[i].getData("vrr.label.locked"), true, price, rentPrice, labelInfoType);
break;
}
case VRR_LABEL_HOUSE: {
renderPropertyEntranceLabel(pickups[i].getData("vrr.label.name"), pickups[i].position, pickups[i].getData("vrr.label.locked"), false, price, rentPrice, labelInfoType);
break;
}
case VRR_LABEL_JOB: {
renderJobLabel(pickups[i].getData("vrr.label.name"), pickups[i].position, pickups[i].getData("vrr.label.jobType"));
break;
}
case VRR_LABEL_EXIT: {
renderPropertyExitLabel(pickups[i].position);
break;
}
}
}
}
}
}
}
}
}
}
// -------------------------------------------------------------------------

62
scripts/client/locale.js Normal file
View File

@@ -0,0 +1,62 @@
// ===========================================================================
// Vortrex's Roleplay Resource
// https://github.com/VortrexFTW/gtac_roleplay
// ===========================================================================
// FILE: locale.js
// DESC: Provides locale functions and usage
// TYPE: Client (JavaScript)
// ===========================================================================
function getLocaleString(stringName, ...args) {
if(typeof getServerData().localeStrings[localLocaleId][stringName] == undefined) {
return "";
}
let tempString = getServerData().localeStrings[localLocaleId][stringName];
if(tempString == "" || tempString == null || tempString == undefined) {
return "";
}
for(let i = 1; i <= args.length; i++) {
tempString = tempString.replace(`{${i}}`, args[i-1]);
}
return tempString;
}
// ===========================================================================
function getAvailableLocaleOptions() {
return getServerData().localeOptions.filter(localeOption => localeOption.requiresUnicode == false);
}
// ===========================================================================
function loadLocaleConfig() {
let configFile = loadTextFile("config/client/locale.json");
getServerData().localeOptions = JSON.parse(configFile);
}
// ===========================================================================
function loadAllLocaleStrings() {
let localeOptions = getServerData().localeOptions;
for(let i in localeOptions) {
logToConsole(LOG_INFO, `[VRR.Locale] Loading locale strings for ${localeOptions[i].englishName} (${i})`);
let localeFile = loadTextFile(`locale/${localeOptions[i].stringsFile}`);
let localeData = JSON.parse(localeFile);
getServerData().localeStrings[i] = localeData;
}
}
// ===========================================================================
function setLocale(tempLocaleId) {
logToConsole(LOG_DEBUG, `[VRR.Locale] Setting locale to ${tempLocaleId} (${getServerData().localeOptions[tempLocaleId].englishName})`);
localLocaleId = tempLocaleId;
resetGUIStrings();
}
// ===========================================================================

View File

@@ -15,38 +15,38 @@ let logoSize = toVector2(128, 128);
function initLogoScript() {
logToConsole(LOG_DEBUG, "[VRR.Logo]: Initializing logo script ...");
//logoImage = loadLogoImage();
//logoImage = loadLogoImage();
logToConsole(LOG_DEBUG, "[VRR.Logo]: Logo script initialized!");
}
// ===========================================================================
function loadLogoImage() {
let logoStream = openFile(mainLogoPath);
let tempLogoImage = null;
if(logoStream != null) {
tempLogoImage = graphics.loadPNG(logoStream);
logoStream.close();
}
let logoStream = openFile(mainLogoPath);
let tempLogoImage = null;
if(logoStream != null) {
tempLogoImage = graphics.loadPNG(logoStream);
logoStream.close();
}
return tempLogoImage;
return tempLogoImage;
}
// ===========================================================================
function processLogoRendering() {
if(renderLogo) {
if(logoImage != null) {
graphics.drawRectangle(logoImage, logoPos, logoSize);
}
}
if(renderLogo) {
if(logoImage != null) {
graphics.drawRectangle(logoImage, logoPos, logoSize);
}
}
}
// ===========================================================================
function setServerLogoRenderState(state) {
logToConsole(LOG_DEBUG, `[VRR.Main] Server logo ${(state) ? "enabled" : "disabled"}`);
renderLogo = state;
logToConsole(LOG_DEBUG, `[VRR.Main] Server logo ${(state) ? "enabled" : "disabled"}`);
renderLogo = state;
}
// ===========================================================================

View File

@@ -7,6 +7,9 @@
// TYPE: Client (JavaScript)
// ===========================================================================
let resourceReady = false;
let resourceStarted = false;
let inSphere = false;
let inVehicle = false;
let inVehicleSeat = false;
@@ -27,7 +30,7 @@ let renderHotBar = true;
let renderItemActionDelay = true;
let renderInteriorLights = true;
let logLevel = LOG_ERROR|LOG_WARN|LOG_INFO;
let logLevel = LOG_INFO|LOG_DEBUG|LOG_VERBOSE;
let weaponDamageEnabled = {};
let weaponDamageEvent = {};
@@ -66,12 +69,24 @@ let vehiclePurchasePosition = null;
let forceWantedLevel = 0;
let guiSubmitKey = false;
let guiLeftKey = false;
let guiRightKey = false;
let guiUpKey = false;
let guiDownKey = false;
// Pre-cache all allowed skins
let allowedSkins = getAllowedSkins(getGame());
let businesses = [];
let houses = [];
let jobs = [];
let vehicles = [];
let localLocaleId = 0;
// ===========================================================================
let serverData = {
houses: [],
businesses: [],
localeStrings: [],
localeOptions: [],
vehicles: [],
jobs: [],
};
// ===========================================================================

View File

@@ -7,7 +7,14 @@
// TYPE: Client (JavaScript)
// ===========================================================================
let smallGameMessageFont = null;
let bigGameMessageFonts = {};
let bigGameMessageFontName = "";
let bigGameMessageText = "";
let bigGameMessageColour = COLOUR_WHITE;
let bigGameMessageTimer = null;
let smallGameMessageFonts = {};
let smallGameMessageFontName = "";
let smallGameMessageText = "";
let smallGameMessageColour = COLOUR_WHITE;
let smallGameMessageTimer = null;
@@ -16,64 +23,73 @@ let smallGameMessageTimer = null;
function initMessagingScript() {
logToConsole(LOG_DEBUG, "[VRR.Messaging]: Initializing messaging script ...");
smallGameMessageFont = loadSmallGameMessageFont();
smallGameMessageFonts = loadSmallGameMessageFonts();
bigGameMessageFonts = loadSmallGameMessageFonts();
logToConsole(LOG_DEBUG, "[VRR.Messaging]: Messaging script initialized!");
}
// ===========================================================================
function loadSmallGameMessageFont() {
let tempSmallGameMessageFont = null;
let fontStream = openFile("files/fonts/pricedown.ttf");
if(fontStream != null) {
tempSmallGameMessageFont = lucasFont.createFont(fontStream, 20.0);
fontStream.close();
}
function loadSmallGameMessageFonts() {
let tempSmallGameMessageFonts = {};
let fontStream = openFile("files/fonts/pricedown.ttf");
if(fontStream != null) {
tempSmallGameMessageFonts["Pricedown"] = lucasFont.createFont(fontStream, 20.0);
fontStream.close();
}
return tempSmallGameMessageFont;
tempSmallGameMessageFonts["Roboto"] = lucasFont.createDefaultFont(20.0, "Roboto");
tempSmallGameMessageFonts["RobotoLight"] = lucasFont.createDefaultFont(20.0, "Roboto", "Light");
return tempSmallGameMessageFonts;
}
// ===========================================================================
function loadBigGameMessageFont() {
let tempBigGameMessageFont = null;
let fontStream = openFile("files/fonts/pricedown.ttf");
if(fontStream != null) {
tempBigGameMessageFont = lucasFont.createFont(fontStream, 28.0);
fontStream.close();
}
let tempBigGameMessageFonts = {};
let fontStream = openFile("files/fonts/pricedown.ttf");
if(fontStream != null) {
tempBigGameMessageFonts["Pricedown"] = lucasFont.createFont(fontStream, 28.0);
fontStream.close();
}
return tempBigGameMessageFont;
tempBigGameMessageFonts["Roboto"] = lucasFont.createDefaultFont(28.0, "Roboto");
tempBigGameMessageFonts["RobotoLight"] = lucasFont.createDefaultFont(28.0, "Roboto", "Light");
return tempBigGameMessageFonts;
}
// ===========================================================================
function processSmallGameMessageRendering() {
if(renderSmallGameMessage) {
if(smallGameMessageFont != null) {
if(smallGameMessageFont != "") {
smallGameMessageFont.render(smallGameMessageText, [0, game.height-90], game.width, 0.5, 0.0, smallGameMessageFont.size, smallGameMessageColour, true, true, false, true);
}
}
}
if(renderSmallGameMessage) {
if(smallGameMessageText != "") {
if(smallGameMessageFonts[smallGameMessageFontName] != null) {
smallGameMessageFonts[smallGameMessageFontName].render(smallGameMessageText, [0, game.height-90], game.width, 0.5, 0.0, smallGameMessageFonts[smallGameMessageFontName].size, smallGameMessageColour, true, true, false, true);
}
}
}
}
// ===========================================================================
function showSmallGameMessage(text, colour, duration) {
logToConsole(LOG_DEBUG, `[VRR.Messaging] Showing small game message '${text}' for ${duration}ms`);
if(smallGameMessageText != "") {
clearTimeout(smallGameMessageTimer);
}
function showSmallGameMessage(text, colour, duration, fontName) {
logToConsole(LOG_DEBUG, `[VRR.Messaging] Showing small game message '${text}' using font ${fontName} for ${duration}ms`);
if(smallGameMessageText != "") {
clearTimeout(smallGameMessageTimer);
}
smallGameMessageColour = colour;
smallGameMessageText = text;
smallGameMessageFontName = fontName;
smallGameMessageColour = colour;
smallGameMessageText = text;
smallGameMessageTimer = setTimeout(function() {
smallGameMessageText = "";
smallGameMessageColour = COLOUR_WHITE;
smallGameMessageTimer = null;
}, duration);
smallGameMessageTimer = setTimeout(function() {
smallGameMessageText = "";
smallGameMessageColour = COLOUR_WHITE;
smallGameMessageTimer = null;
smallGameMessageFontName = "";
}, duration);
}
// ===========================================================================

View File

@@ -20,7 +20,7 @@ function SetStandardControlsEnabled(bEnabled)
if (game.standardControls === undefined)
{
console.warn("game.standardControls not implemented");
logToConsole(LOG_WARN, "game.standardControls not implemented");
return;
}
game.standardControls = bEnabled;
@@ -93,7 +93,7 @@ function GetMouseSensitivity()
{
if (game.getMouseSensitivity === undefined)
{
//console.error("game.getMouseSensitivity not implemented");
//logToConsole(LOG_ERROR, "game.getMouseSensitivity not implemented");
return [0.0025,0.003];
}
let MouseSensitivity = game.getMouseSensitivity();
@@ -124,7 +124,7 @@ function ProcessLineOfSight(vecStartX, vecStartY, vecStartZ, vecEndX, vecEndY, v
{
if (game.processLineOfSight === undefined)
{
console.warn("game.processLineOfSight not implemented");
logToConsole(LOG_WARN, "game.processLineOfSight not implemented");
return [null];
}
let Result = game.processLineOfSight([vecStartX, vecStartY, vecStartZ], [vecEndX, vecEndY, vecEndZ], bCheckBuildings, bCheckVehicles, bCheckPeds, bCheckObjects, bCheckDummies, bCheckSeeThroughStuff, bIgnoreSomeObjectsForCamera);
@@ -632,10 +632,10 @@ function update()
addEventHandler("OnCameraProcess", (event) =>
{
if(mouseCameraEnabled) {
update();
event.preventDefault();
}
if(mouseCameraEnabled) {
update();
event.preventDefault();
}
});
function toggleMouseCamera() {

View File

@@ -48,11 +48,11 @@ function updatePlayerNameTag(clientName, characterName, colour, paused, ping) {
playerPaused[clientName] = paused;
playerPing[clientName] = ping;
if(game.game == VRR_GAME_GTA_IV) {
if(getGame() == VRR_GAME_GTA_IV) {
let client = getPlayerFromParams(clientName);
if(client != false) {
if(client.player != null) {
client.player.setNametag(characterName, colour);
if(getPlayerPed(client) != null) {
getPlayerPed(client).setNametag(characterName, colour);
}
}
}
@@ -74,14 +74,14 @@ function drawNametag(x, y, health, armour, text, ping, alpha, distance, colour,
alpha *= 0.75;
let width = nametagWidth;
health = Math.max(0.0, Math.min(1.0, health));
armour = Math.max(0.0, Math.min(1.0, armour));
armour = Math.max(0.0, Math.min(1.0, armour));
// Starts at bottom and works it's way up
// -------------------------------------------
// Health Bar
// Starts at bottom and works it's way up
// -------------------------------------------
// Health Bar
if(getMultiplayerMod() == VRR_MPMOD_GTAC) {
if(game.game == VRR_GAME_GTA_III) {
if(getGame() == VRR_GAME_GTA_III) {
// Mickey Hamfists is ridiculously tall. Raise the nametag for him a bit
if(skin == 109) {
y -= 20;
@@ -104,7 +104,7 @@ function drawNametag(x, y, health, armour, text, ping, alpha, distance, colour,
graphics.drawRectangle(null, [hx+2, hy+2], [(width-4)*health, 10-6], colour, colour, colour, colour);
}
// Armour Bar
// Armour Bar
if (armour > 0.0)
{
// Go up 10 pixels to draw the next part
@@ -119,16 +119,16 @@ function drawNametag(x, y, health, armour, text, ping, alpha, distance, colour,
y -= 20;
// Nametag
// Nametag
if(nametagFont != null) {
let size = nametagFont.measure(text, game.width, 0.0, 0.0, nametagFont.size, false, false);
nametagFont.render(text, [x-size[0]/2, y-size[1]/2], game.width, 0.0, 0.0, nametagFont.size, colour, false, false, false, true);
}
// Go up another 10 pixels for the next part
y -= 20;
// Go up another 10 pixels for the next part
y -= 20;
// AFK Status
// AFK Status
if(afkStatusFont != null) {
if(afk) {
let size = afkStatusFont.measure("PAUSED", game.width, 0.0, 0.0, afkStatusFont.size, false, false);
@@ -139,7 +139,7 @@ function drawNametag(x, y, health, armour, text, ping, alpha, distance, colour,
// ===========================================================================
function updateNametags(element) {
function updateNametag(element) {
if(!areWorldLabelsSupported()) {
return false;
}
@@ -147,10 +147,11 @@ function updateNametags(element) {
if(localPlayer != null) {
let playerPos = localPlayer.position;
let elementPos = element.position;
let client = getClientFromPlayerElement(element);
elementPos[2] += 0.9;
//if(typeof element.getComponentPosition()) {
let screenPos = getScreenFromWorldPosition(elementPos);
if (screenPos[2] >= 0.0) {
let health = element.health/100.0;
@@ -173,27 +174,29 @@ function updateNametags(element) {
}
if(element.type == ELEMENT_PLAYER) {
let name = element.name;
let colour = COLOUR_WHITE;
let name = element.name;
let colour = COLOUR_WHITE;
let paused = false;
let ping = -1;
if(typeof playerNames[element.name] != "undefined") {
name = playerNames[element.name];
}
if(element.isType(ELEMENT_PLAYER)) {
if(typeof playerNames[element.name] != "undefined") {
name = playerNames[element.name];
}
if(typeof playerPaused[element.name] != "undefined") {
paused = playerPaused[element.name];
}
if(typeof playerPaused[element.name] != "undefined") {
paused = playerPaused[element.name];
}
if(typeof playerColours[element.name] != "undefined") {
colour = playerColours[element.name];
if(typeof playerColours[element.name] != "undefined") {
colour = playerColours[element.name];
}
if(typeof playerPing[element.name] != "undefined") {
ping = playerPing[element.name];
}
}
if(typeof playerPing[element.name] != "undefined") {
ping = playerPing[element.name];
}
drawNametag(screenPos[0], screenPos[1], health, armour, name, ping, 1.0-distance/nametagDistance, distance, colour, paused, element.skin);
}
}
@@ -205,7 +208,7 @@ function updateNametags(element) {
function getClientFromPlayer(player) {
getClients().forEach(function(client) {
if(client.player == player) {
if(getPlayerPed(client) == player) {
return client;
}
});
@@ -214,13 +217,13 @@ function getClientFromPlayer(player) {
// ===========================================================================
function processNameTagRendering(event) {
//if(game.game >= GAME_GTA_IV) {
//if(getGame() >= GAME_GTA_IV) {
// return false;
//}
getElementsByType(ELEMENT_PLAYER).forEach(function(player) {
if(player != localPlayer) {
updateNametags(player);
getElementsByType(ELEMENT_PED).forEach(function(ped) {
if(ped != localPlayer) {
updateNametag(ped);
}
});
}
@@ -231,4 +234,10 @@ function createColour(alpha, red, green, blue) {
return alpha << 24 | red << 16 | green << 8 | blue;
}
// ===========================================================================
function setNameTagDistance(distance) {
nametagDistance = distance;
}
// ===========================================================================

View File

@@ -7,58 +7,89 @@
// TYPE: Server (JavaScript)
// ===========================================================================
let disconnectReasons = [
"Lost Connection",
"Disconnected",
"Unsupported Client",
"Wrong Game",
"Incorrect Password",
"Unsupported Executable",
"Disconnected",
"Banned",
"Failed",
"Invalid Name",
"Crashed",
"Modified Game"
];
// ===========================================================================
function sendNetworkEventToPlayer(networkEvent, client, ...args) {
triggerNetworkEvent.apply(null, networkEvent, client, args);
triggerNetworkEvent.apply(null, networkEvent, client, args);
}
// ===========================================================================
function getPlayerPosition() {
return localPlayer.position;
return localPlayer.position;
}
// ===========================================================================
function setPlayerPosition(position) {
localPlayer.position = position;
if(getGame() == VRR_GAME_GTA_IV) {
natives.setCharCoordinates(localPlayer, position);
} else {
localPlayer.position = position;
}
}
// ===========================================================================
function getElementPosition(element) {
return element.position;
function getElementPosition(elementId) {
return getElementFromId(elementId).position;
}
// ===========================================================================
function setElementPosition(element, position) {
if(!element.isSyncer) {
return false;
}
element.position = position;
function getElementHeading(elementId) {
return getElementFromId(elementId).heading;
}
// ===========================================================================
function deleteGameElement(element, position) {
if(!element.isOwner) {
return false;
}
function setElementPosition(elementId, position) {
if(getElementFromId(elementId) == null) {
return false;
}
destroyGameElement(element);
if(!getElementFromId(elementId).isSyncer) {
return false;
}
getElementFromId(elementId).position = position;
}
// ===========================================================================
function deleteGameElement(elementId, position) {
if(!getElementFromId(elementId).isOwner) {
return false;
}
destroyGameElement(getElementFromId(elementId));
}
// ===========================================================================
function createGameVehicle(modelIndex, position, heading) {
return game.createVehicle(getGameConfig().vehicles[getGame()][modelIndex][0], position, heading);
return game.createVehicle(getGameConfig().vehicles[getGame()][modelIndex][0], position, heading);
}
// ===========================================================================
function addNetworkEventHandler(eventName, handlerFunction) {
addNetworkHandler(eventName, handlerFunction);
addNetworkHandler(eventName, handlerFunction);
}
// ===========================================================================
@@ -101,7 +132,7 @@ function getClientsInRange(position, distance) {
// ===========================================================================
function getCiviliansInRange(position, distance) {
return getElementsByType(ELEMENT_PED).filter(x => !x.isType(ELEMENT_PLAYER) && getElementPosition(x).position.distance(position) <= distance);
return getElementsByType(ELEMENT_PED).filter(x => !x.isType(ELEMENT_PLAYER) && x.position.distance(position) <= distance);
}
// ===========================================================================
@@ -113,7 +144,7 @@ function getPlayersInRange(position, distance) {
// ===========================================================================
function getElementsByTypeInRange(elementType, position, distance) {
return getElementsByType(elementType).filter(x => getElementPosition(x).position.distance(position) <= distance);
return getElementsByType(elementType).filter(x => x.position.distance(position) <= distance);
}
// ===========================================================================
@@ -124,6 +155,12 @@ function getClosestCivilian(position) {
// ===========================================================================
function getClosestPlayer(position) {
return getElementsByType(ELEMENT_PLAYER).reduce((i, j) => ((i.position.distance(position) <= j.position.distance(position)) ? i : j));
}
// ===========================================================================
function is2dPositionOnScreen(pos2d) {
return pos2d.x >= 0 && pos2d.y >= 0 && pos2d.x <= game.width && pos2d.y <= game.height;
}
@@ -141,4 +178,523 @@ function getVehiclesInRange(position, range) {
return inRangeVehicles;
}
// ===========================================================================
function createGameBlip(blipModel, position, name = "") {
if(getGame() == VRR_GAME_GTA_IV) {
let blipId = natives.addBlipForCoord(position);
if(blipId) {
natives.changeBlipSprite(blipId, blipModel);
natives.setBlipMarkerLongDistance(blipId, false);
natives.setBlipAsShortRange(blipId, true);
natives.changeBlipNameFromAscii(blipId, `${name.substr(0, 24)}${(name.length > 24) ? " ...": ""}`);
return blipId;
}
}
return -1;
}
// ===========================================================================
function setEntityData(entity, dataName, dataValue, syncToClients = true) {
if(entity != null) {
return entity.setData(dataName, dataValue);
}
}
// ===========================================================================
function setVehicleEngine(vehicleId, state) {
getElementFromId(vehicleId).engine = state;
}
// ===========================================================================
function setVehicleLights(vehicleId, state) {
getElementFromId(vehicleId).lights = state;
}
// ===========================================================================
function repairVehicle(syncId) {
getVehicleFromSyncId(syncId).fix();
}
// ===========================================================================
function syncVehicleProperties(vehicle) {
if(doesEntityDataExist(vehicle, "vrr.lights")) {
let lightStatus = getEntityData(vehicle, "vrr.lights");
vehicle.lights = lightStatus;
}
if(doesEntityDataExist(vehicle, "vrr.invincible")) {
let invincible = getEntityData(vehicle, "vrr.invincible");
element.setProofs(invincible, invincible, invincible, invincible, invincible);
}
if(doesEntityDataExist(vehicle, "vrr.panelStatus")) {
let panelsStatus = getEntityData(vehicle, "vrr.panelStatus");
for(let i in panelsStatus) {
vehicle.setPanelStatus(i, panelsStatus[i]);
}
}
if(doesEntityDataExist(vehicle, "vrr.wheelStatus")) {
let wheelsStatus = getEntityData(vehicle, "vrr.wheelStatus");
for(let i in wheelsStatus) {
vehicle.setWheelStatus(i, wheelsStatus[i]);
}
}
if(doesEntityDataExist(vehicle, "vrr.lightStatus")) {
let lightStatus = getEntityData(vehicle, "vrr.lightStatus");
for(let i in lightStatus) {
vehicle.setLightStatus(i, lightStatus[i]);
}
}
if(doesEntityDataExist(vehicle, "vrr.suspensionHeight")) {
let suspensionHeight = getEntityData(vehicle, "vrr.suspensionHeight");
vehicle.setSuspensionHeight(suspensionHeight);
}
if(getGame() == VRR_GAME_GTA_SA) {
let allUpgrades = getGameConfig().vehicleUpgrades[getGame()];
for(let i in allUpgrades) {
vehicle.removeUpgrade(i);
}
if(doesEntityDataExist(vehicle, "vrr.upgrades")) {
let upgrades = getEntityData(vehicle, "vrr.upgrades");
for(let i in upgrades) {
if(upgrades[i] != 0) {
vehicle.addUpgrade(upgrades[i]);
}
}
}
}
if(getGame() == VRR_GAME_GTA_SA || getGame() == VRR_GAME_GTA_IV) {
if(doesEntityDataExist(vehicle, "vrr.livery")) {
let livery = getEntityData(vehicle, "vrr.livery");
if(getGame() == VRR_GAME_GTA_SA) {
vehicle.setPaintJob(livery);
} else if(getGame() == VRR_GAME_GTA_IV) {
vehicle.livery = livery;
}
}
}
}
// ===========================================================================
function removeEntityData(entity, dataName) {
if(entity != null) {
return entity.removeData(dataName);
}
return null;
}
// ===========================================================================
function doesEntityDataExist(entity, dataName) {
if(entity != null) {
return (entity.getData(dataName) != null);
}
return null;
}
// ===========================================================================
function syncCivilianProperties(civilian) {
if(getGame() == VRR_GAME_GTA_III) {
if(doesEntityDataExist(civilian, "vrr.scale")) {
let scaleFactor = getEntityData(civilian, "vrr.scale");
let tempMatrix = civilian.matrix;
tempMatrix.setScale(toVector3(scaleFactor.x, scaleFactor.y, scaleFactor.z));
let tempPosition = civilian.position;
civilian.matrix = tempMatrix;
tempPosition.z += scaleFactor.z;
civilian.position = tempPosition;
}
}
if(getGame() == VRR_GAME_GTA_SA) {
if(doesEntityDataExist(civilian, "vrr.fightStyle")) {
let fightStyle = getEntityData(civilian, "vrr.fightStyle");
civilian.setFightStyle(fightStyle[0], fightStyle[1]);
}
}
if(getGame() == VRR_GAME_GTA_III) {
if(doesEntityDataExist(civilian, "vrr.walkStyle")) {
let walkStyle = getEntityData(civilian, "vrr.walkStyle");
civilian.walkStyle = walkStyle;
}
}
if(getGame() == VRR_GAME_GTA_IV) {
if(doesEntityDataExist(civilian, "vrr.bodyPropHair")) {
let bodyPropHair = getEntityData(civilian, "vrr.bodyPropHair");
civilian.changeBodyProp(0, bodyPropHair[0], bodyPropHair[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropHead")) {
let bodyPropHead = getEntityData(civilian, "vrr.bodyPropHead");
civilian.changeBodyProp(1, bodyPropHead[0], bodyPropHead[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropEyes")) {
let bodyPropEyes = getEntityData(civilian, "vrr.bodyPropEyes");
civilian.changeBodyProp(1, bodyPropEyes[0], bodyPropEyes[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropLeftHand")) {
let bodyPropLeftHand = getEntityData(civilian, "vrr.bodyPropLeftHand");
civilian.changeBodyProp(1, bodyPropLeftHand[0], bodyPropLeftHand[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropRightHand")) {
let bodyPropRightHand = getEntityData(civilian, "vrr.bodyPropRightHand");
civilian.changeBodyProp(1, bodyPropRightHand[0], bodyPropRightHand[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropLeftWrist")) {
let bodyPropLeftWrist = getEntityData(civilian, "vrr.bodyPropLeftWrist");
civilian.changeBodyProp(1, bodyPropLeftWrist[0], bodyPropLeftWrist[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropRightWrist")) {
let bodyPropRightWrist = getEntityData(civilian, "vrr.bodyPropRightWrist");
civilian.changeBodyProp(1, bodyPropRightWrist[0], bodyPropRightWrist[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropRightWrist")) {
let bodyPropRightWrist = getEntityData(civilian, "vrr.bodyPropRightWrist");
civilian.changeBodyProp(1, bodyPropRightWrist[0], bodyPropRightWrist[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropHip")) {
let bodyPropHip = getEntityData(civilian, "vrr.bodyPropHip");
civilian.changeBodyProp(1, bodyPropHip[0], bodyPropHip[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropLeftFoot")) {
let bodyPropLeftFoot = getEntityData(civilian, "vrr.bodyPropLeftFoot");
civilian.changeBodyProp(1, bodyPropLeftFoot[0], bodyPropLeftFoot[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropRightFoot")) {
let bodyPropRightFoot = getEntityData(civilian, "vrr.bodyPropRightFoot");
civilian.changeBodyProp(1, bodyPropRightFoot[0], bodyPropRightFoot[1]);
}
}
if(doesEntityDataExist(civilian, "vrr.anim")) {
let animData = getEntityData(vehicle, "vrr.anim");
civilian.addAnimation(animData[0], animData[1]);
}
}
// ===========================================================================
function preventDefaultEventAction(event) {
event.preventDefault();
}
// ===========================================================================
function syncPlayerProperties(player) {
if(getGame() == VRR_GAME_GTA_III) {
if(doesEntityDataExist(player, "vrr.scale")) {
let scaleFactor = getEntityData(player, "vrr.scale");
let tempMatrix = player.matrix;
tempMatrix.setScale(toVector3(scaleFactor.x, scaleFactor.y, scaleFactor.z));
let tempPosition = player.position;
player.matrix = tempMatrix;
tempPosition.z += scaleFactor.z;
player.position = tempPosition;
}
}
if(getGame() == VRR_GAME_GTA_SA) {
if(doesEntityDataExist(player, "vrr.fightStyle")) {
let fightStyle = getEntityData(player, "vrr.fightStyle");
player.setFightStyle(fightStyle[0], fightStyle[1]);
}
}
//if(getGame() == VRR_GAME_GTA_SA) {
// if(doesEntityDataExist(player, "vrr.walkStyle")) {
// let walkStyle = getEntityData(player, "vrr.walkStyle");
// player.walkStyle = walkStyle;
// }
//}
if(getGame() == VRR_GAME_GTA_IV) {
if(doesEntityDataExist(player, "vrr.bodyPartHair")) {
let bodyPartHead = getEntityData(player, "vrr.bodyPartHair");
player.changeBodyPart(0, bodyPartHead[0], bodyPartHair[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPartHead")) {
let bodyPartHead = getEntityData(player, "vrr.bodyPartHead");
player.changeBodyPart(1, bodyPartHead[0], bodyPartHead[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPartUpper")) {
let bodyPartUpper = getEntityData(player, "vrr.bodyPartUpper");
player.changeBodyPart(1, bodyPartUpper[0], bodyPartUpper[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPartLower")) {
let bodyPartLower = getEntityData(player, "vrr.bodyPartLower");
player.changeBodyPart(1, bodyPartLower[0], bodyPartLower[1]);
}
}
if(getGame() == VRR_GAME_GTA_IV) {
if(doesEntityDataExist(player, "vrr.bodyPropHair")) {
let bodyPropHair = getEntityData(player, "vrr.bodyPropHair");
player.changeBodyProp(0, bodyPropHair[0], bodyPropHair[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropHead")) {
let bodyPropHead = getEntityData(player, "vrr.bodyPropHead");
player.changeBodyProp(1, bodyPropHead[0], bodyPropHead[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropEyes")) {
let bodyPropEyes = getEntityData(player, "vrr.bodyPropEyes");
player.changeBodyProp(1, bodyPropEyes[0], bodyPropEyes[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropLeftHand")) {
let bodyPropLeftHand = getEntityData(player, "vrr.bodyPropLeftHand");
player.changeBodyProp(1, bodyPropLeftHand[0], bodyPropLeftHand[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropRightHand")) {
let bodyPropRightHand = getEntityData(player, "vrr.bodyPropRightHand");
player.changeBodyProp(1, bodyPropRightHand[0], bodyPropRightHand[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropLeftWrist")) {
let bodyPropLeftWrist = getEntityData(player, "vrr.bodyPropLeftWrist");
player.changeBodyProp(1, bodyPropLeftWrist[0], bodyPropLeftWrist[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropRightWrist")) {
let bodyPropRightWrist = getEntityData(player, "vrr.bodyPropRightWrist");
player.changeBodyProp(1, bodyPropRightWrist[0], bodyPropRightWrist[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropRightWrist")) {
let bodyPropRightWrist = getEntityData(player, "vrr.bodyPropRightWrist");
player.changeBodyProp(1, bodyPropRightWrist[0], bodyPropRightWrist[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropHip")) {
let bodyPropHip = getEntityData(player, "vrr.bodyPropHip");
player.changeBodyProp(1, bodyPropHip[0], bodyPropHip[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropLeftFoot")) {
let bodyPropLeftFoot = getEntityData(player, "vrr.bodyPropLeftFoot");
player.changeBodyProp(1, bodyPropLeftFoot[0], bodyPropLeftFoot[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropRightFoot")) {
let bodyPropRightFoot = getEntityData(player, "vrr.bodyPropRightFoot");
player.changeBodyProp(1, bodyPropRightFoot[0], bodyPropRightFoot[1]);
}
}
}
// ===========================================================================
function syncObjectProperties(object) {
if(getGame() == VRR_GAME_GTA_III || getGame() == VRR_GAME_GTA_VC) {
if(doesEntityDataExist(object, "vrr.scale")) {
let scaleFactor = getEntityData(object, "vrr.scale");
let tempMatrix = object.matrix;
tempMatrix.setScale(toVector3(scaleFactor.x, scaleFactor.y, scaleFactor.z));
let tempPosition = object.position;
object.matrix = tempMatrix;
tempPosition.z += scaleFactor.z;
object.position = tempPosition;
}
}
}
// ===========================================================================
function consolePrint(text) {
console.log(text);
}
// ===========================================================================
function consoleWarn(text) {
console.warn(text);
}
// ===========================================================================
function consoleError(text) {
console.error(text);
}
// ===========================================================================
function getPlayerName(client) {
return client.name;
}
// ===========================================================================
function getGame() {
return game.game;
}
// ===========================================================================
function getPlayerId(client) {
return client.index;
}
// ===========================================================================
function syncElementProperties(element) {
if(doesEntityDataExist(element, "vrr.interior")) {
if(typeof element.interior != "undefined") {
element.interior = getEntityData(element, "vrr.interior");
}
}
switch(element.type) {
case ELEMENT_VEHICLE:
syncVehicleProperties(element);
break;
case ELEMENT_PED:
syncCivilianProperties(element);
break;
case ELEMENT_PLAYER:
syncPlayerProperties(element);
break;
case ELEMENT_OBJECT:
syncObjectProperties(element);
break;
default:
break;
}
}
// ===========================================================================
function getPlayerPed(client) {
return client.player;
}
// ===========================================================================
function getScreenWidth() {
return game.width;
}
// ===========================================================================
function getScreenHeight() {
return game.height;
}
// ===========================================================================
// ===========================================================================
function openAllGarages() {
switch(getGame()) {
case VRR_GAME_GTA_III:
for(let i=0;i<=26;i++) {
openGarage(i);
game.NO_SPECIAL_CAMERA_FOR_THIS_GARAGE(i);
}
break;
case VRR_GAME_GTA_VC:
for(let i=0;i<=32;i++) {
openGarage(i);
game.NO_SPECIAL_CAMERA_FOR_THIS_GARAGE(i);
}
break;
case VRR_GAME_GTA_SA:
for(let i=0;i<=44;i++) {
openGarage(i);
}
break;
default:
break;
}
}
// ===========================================================================
function closeAllGarages() {
switch(getGame()) {
case VRR_GAME_GTA_III:
for(let i=0;i<=26;i++) {
closeGarage(i);
game.NO_SPECIAL_CAMERA_FOR_THIS_GARAGE(i);
}
break;
case VRR_GAME_GTA_VC:
for(let i=0;i<=32;i++) {
closeGarage(i);
game.NO_SPECIAL_CAMERA_FOR_THIS_GARAGE(i);
}
break;
case VRR_GAME_GTA_SA:
for(let i=0;i<=44;i++) {
closeGarage(i);
}
break;
default:
break;
}
}
// ===========================================================================
function setPedInvincible(ped, state) {
ped.invincible = state;
}
// ===========================================================================
function setPedLookAt(ped, position) {
if(getGame() == VRR_GAME_GTA_SA) {
ped.lookAt(position, 10000);
return true;
} else {
setElementHeading(ped.id, getHeadingFromPosToPos(getElementPosition(ped.id), position));
}
}
// ===========================================================================
function setElementHeading(elementId, heading) {
getElementFromId(elementId).heading = heading;
}
// ===========================================================================

19
scripts/client/npc.js Normal file
View File

@@ -0,0 +1,19 @@
// ===========================================================================
// Vortrex's Roleplay Resource
// https://github.com/VortrexFTW/gtac_roleplay
// ===========================================================================
// FILE: npc.js
// DESC: Provides NPC functions and processing
// TYPE: Client (JavaScript)
// ===========================================================================
function processNPCMovement(npc) {
//if(npc.isSyncer == true) {
if(getEntityData(npc, "vrr.lookAtClosestPlayer") == true) {
let closestPlayer = getClosestPlayer(getElementPosition(npc.id));
setPedLookAt(npc, getElementPosition(closestPlayer.id));
}
//}
}
// ===========================================================================

View File

@@ -8,39 +8,39 @@
// ===========================================================================
function playStreamingRadio(url, loop, volume, element = false) {
if(streamingRadio != null) {
streamingRadio.stop();
}
if(streamingRadio != null) {
streamingRadio.stop();
}
streamingRadioVolume = volume;
streamingRadioVolume = volume;
streamingRadio = audio.createSoundFromURL(url, loop);
streamingRadio.volume = volume/100;
streamingRadio.play();
streamingRadio = audio.createSoundFromURL(url, loop);
streamingRadio.volume = volume/100;
streamingRadio.play();
}
// ===========================================================================
function stopStreamingRadio() {
if(streamingRadio != null) {
streamingRadio.stop();
}
streamingRadio = null;
if(streamingRadio != null) {
streamingRadio.stop();
}
streamingRadio = null;
}
// ===========================================================================
function setStreamingRadioVolume(volume) {
if(streamingRadio != null) {
streamingRadioVolume = volume;
streamingRadio.volume = volume/100;
}
if(streamingRadio != null) {
streamingRadioVolume = volume;
streamingRadio.volume = volume/100;
}
}
// ===========================================================================
function playAudioFile(audioName, loop, volume) {
playCustomAudio(audioName, volume/100, loop);
findResourceByName("connectedrp-extra").exports.playCustomAudio(audioName, volume/100, loop);
}
// ===========================================================================

View File

@@ -43,7 +43,7 @@ function processScoreBoardRendering() {
}
if(renderScoreBoard) {
if(isKeyDown(SDLK_TAB)) {
if(isKeyDown(SDLK_TAB)) {
if(scoreBoardListFont != null && scoreBoardTitleFont != null) {
let scoreboardStart = (game.height/2)-(Math.floor(getClients().length/2)*20);
let titleSize = scoreBoardTitleFont.measure("PLAYERS", game.width, 0.0, 1.0, 10, false, false);

View File

@@ -8,197 +8,251 @@
// ===========================================================================
function initServerScript() {
logToConsole(LOG_DEBUG, "[VRR.Server]: Initializing server script ...");
addAllNetworkHandlers();
logToConsole(LOG_DEBUG, "[VRR.Server]: Server script initialized!");
logToConsole(LOG_DEBUG, "[VRR.Server]: Initializing server script ...");
addAllNetworkHandlers();
logToConsole(LOG_DEBUG, "[VRR.Server]: Server script initialized!");
}
// ===========================================================================
function addAllNetworkHandlers() {
logToConsole(LOG_DEBUG, "[VRR.Server]: Adding network handlers ...");
logToConsole(LOG_DEBUG, "[VRR.Server]: Adding network handlers ...");
addNetworkEventHandler("vrr.smallGameMessage", showSmallGameMessage);
addNetworkEventHandler("vrr.working", setLocalPlayerWorkingState);
addNetworkEventHandler("vrr.jobType", setLocalPlayerJobType);
addNetworkEventHandler("vrr.passenger", enterVehicleAsPassenger);
// Chat history
addNetworkEventHandler("m", receiveChatBoxMessageFromServer); // Not prefixed with VRR to make it as small as possible
addNetworkEventHandler("vrr.chatScrollLines", setChatScrollLines);
addNetworkEventHandler("vrr.chatAutoHideDelay", setChatAutoHideDelay);
addNetworkEventHandler("vrr.freeze", setLocalPlayerFrozenState);
addNetworkEventHandler("vrr.control", setLocalPlayerControlState);
addNetworkEventHandler("vrr.fadeCamera", fadeLocalCamera);
addNetworkEventHandler("vrr.removeFromVehicle", removeLocalPlayerFromVehicle);
addNetworkEventHandler("vrr.clearPeds", clearLocalPlayerOwnedPeds);
addNetworkEventHandler("vrr.restoreCamera", restoreLocalCamera);
addNetworkEventHandler("vrr.cameraLookAt", setLocalCameraLookAt);
addNetworkEventHandler("vrr.logo", setServerLogoRenderState);
addNetworkEventHandler("vrr.ambience", setCityAmbienceState);
addNetworkEventHandler("vrr.runCode", runClientCode);
addNetworkEventHandler("vrr.clearWeapons", clearLocalPlayerWeapons);
addNetworkEventHandler("vrr.giveWeapon", giveLocalPlayerWeapon);
addNetworkEventHandler("vrr.position", setLocalPlayerPosition);
addNetworkEventHandler("vrr.heading", setLocalPlayerHeading);
addNetworkEventHandler("vrr.interior", setLocalPlayerInterior);
addNetworkEventHandler("vrr.minuteDuration", setMinuteDuration);
addNetworkEventHandler("vrr.showJobRouteLocation", showJobRouteLocation);
addNetworkEventHandler("vrr.hideJobRouteLocation", hideJobRouteLocation);
addNetworkEventHandler("vrr.snow", setSnowState);
addNetworkEventHandler("vrr.health", setLocalPlayerHealth);
addNetworkEventHandler("vrr.enterPropertyKey", setEnterPropertyKey);
addNetworkEventHandler("vrr.skinSelect", toggleSkinSelect);
addNetworkEventHandler("vrr.hotbar", updatePlayerHotBar);
addNetworkEventHandler("vrr.pedSpeech", playPedSpeech);
addNetworkEventHandler("vrr.clearPedState", clearLocalPedState);
addNetworkEventHandler("vrr.drunkEffect", setLocalPlayerDrunkEffect);
addNetworkEventHandler("vrr.showItemActionDelay", showItemActionDelay);
addNetworkEventHandler("vrr.set2DRendering", setPlayer2DRendering);
addNetworkEventHandler("vrr.mouseCursor", toggleMouseCursor);
addNetworkEventHandler("vrr.mouseCamera", toggleMouseCamera);
addNetworkEventHandler("vrr.mouseCameraForce", setMouseCameraState);
addNetworkEventHandler("vrr.weaponDamageEnabled", setPlayerWeaponDamageEnabled);
addNetworkEventHandler("vrr.weaponDamageEvent", setPlayerWeaponDamageEvent);
addNetworkEventHandler("vrr.spawned", onServerSpawnedPlayer);
addNetworkEventHandler("vrr.money", setLocalPlayerCash);
addNetworkEventHandler("vrr.armour", setLocalPlayerArmour);
addNetworkEventHandler("vrr.wantedLevel", forceLocalPlayerWantedLevel);
// Messaging (like textdraws and stuff)
addNetworkEventHandler("vrr.smallGameMessage", showSmallGameMessage);
addNetworkEventHandler("vrr.delKeyBind", unBindAccountKey);
addNetworkEventHandler("vrr.addKeyBind", bindAccountKey);
addNetworkEventHandler("vrr.clearKeyBinds", clearKeyBinds);
// Job
addNetworkEventHandler("vrr.job", receiveJobFromServer);
addNetworkEventHandler("vrr.working", setLocalPlayerWorkingState);
addNetworkEventHandler("vrr.jobType", setLocalPlayerJobType);
addNetworkEventHandler("vrr.showJobRouteLocation", showJobRouteLocation);
addNetworkEventHandler("vrr.hideJobRouteLocation", hideJobRouteLocation);
addNetworkEventHandler("vrr.nametag", updatePlayerNameTag);
addNetworkEventHandler("vrr.ping", updatePlayerPing);
// Local player states and values
addNetworkEventHandler("vrr.restoreCamera", restoreLocalCamera);
addNetworkEventHandler("vrr.cameraLookAt", setLocalCameraLookAt);
addNetworkEventHandler("vrr.freeze", setLocalPlayerFrozenState);
addNetworkEventHandler("vrr.control", setLocalPlayerControlState);
addNetworkEventHandler("vrr.fadeCamera", fadeLocalCamera);
addNetworkEventHandler("vrr.removeFromVehicle", removeLocalPlayerFromVehicle);
addNetworkEventHandler("vrr.clearWeapons", clearLocalPlayerWeapons);
addNetworkEventHandler("vrr.giveWeapon", giveLocalPlayerWeapon);
addNetworkEventHandler("vrr.position", setLocalPlayerPosition);
addNetworkEventHandler("vrr.heading", setLocalPlayerHeading);
addNetworkEventHandler("vrr.interior", setLocalPlayerInterior);
addNetworkEventHandler("vrr.spawned", onServerSpawnedLocalPlayer);
addNetworkEventHandler("vrr.money", setLocalPlayerCash);
addNetworkEventHandler("vrr.armour", setLocalPlayerArmour);
addNetworkEventHandler("vrr.localPlayerSkin", setLocalPlayerSkin);
addNetworkEventHandler("vrr.pedSpeak", makeLocalPlayerPedSpeak);
addNetworkEventHandler("vrr.infiniteRun", setLocalPlayerInfiniteRun);
addNetworkEventHandler("vrr.playerCop", setLocalPlayerAsCopState);
addNetworkEventHandler("vrr.health", setLocalPlayerHealth);
addNetworkEventHandler("vrr.wantedLevel", setLocalPlayerWantedLevel);
addNetworkEventHandler("vrr.playerPedId", sendLocalPlayerNetworkIdToServer);
addNetworkEventHandler("vrr.ped", setLocalPlayerPedPartsAndProps);
addNetworkEventHandler("vrr.spawn", serverRequestedLocalPlayerSpawn);
addNetworkEventHandler("vrr.clearPedState", clearLocalPedState);
addNetworkEventHandler("vrr.drunkEffect", setLocalPlayerDrunkEffect);
addNetworkEventHandler("vrr.m", receiveChatBoxMessageFromServer);
addNetworkEventHandler("vrr.chatScrollLines", setChatScrollLines);
// Vehicle
addNetworkEventHandler("vrr.vehicle", receiveVehicleFromServer);
addNetworkEventHandler("vrr.veh.lights", setVehicleLights);
addNetworkEventHandler("vrr.veh.engine", setVehicleEngine);
addNetworkEventHandler("vrr.veh.repair", repairVehicle);
addNetworkEventHandler("vrr.radioStream", playStreamingRadio);
addNetworkEventHandler("vrr.audioFileStream", playAudioFile);
addNetworkEventHandler("vrr.stopRadioStream", stopStreamingRadio);
addNetworkEventHandler("vrr.radioVolume", setStreamingRadioVolume);
// Radio
addNetworkEventHandler("vrr.radioStream", playStreamingRadio);
addNetworkEventHandler("vrr.audioFileStream", playAudioFile);
addNetworkEventHandler("vrr.stopRadioStream", stopStreamingRadio);
addNetworkEventHandler("vrr.radioVolume", setStreamingRadioVolume);
addNetworkEventHandler("vrr.veh.lights", setVehicleLights);
addNetworkEventHandler("vrr.veh.engine", setVehicleEngine);
addNetworkEventHandler("vrr.veh.repair", repairVehicle);
// Key Bindings
addNetworkEventHandler("vrr.delKeyBind", unBindAccountKey);
addNetworkEventHandler("vrr.addKeyBind", bindAccountKey);
addNetworkEventHandler("vrr.clearKeyBinds", clearKeyBinds);
addNetworkEventHandler("vrr.pedAnim", makePedPlayAnimation);
addNetworkEventHandler("vrr.pedStopAnim", makePedStopAnimation);
addNetworkEventHandler("vrr.localPlayerSkin", setLocalPlayerSkin);
addNetworkEventHandler("vrr.forcePedAnim", forcePedAnimation);
addNetworkEventHandler("vrr.hideAllGUI", hideAllGUI);
addNetworkEventHandler("vrr.clientInfo", serverRequestedClientInfo);
addNetworkEventHandler("vrr.interiorLights", updateInteriorLightsState);
// Weapon Damage
addNetworkEventHandler("vrr.weaponDamageEnabled", setPlayerWeaponDamageEnabled);
addNetworkEventHandler("vrr.weaponDamageEvent", setPlayerWeaponDamageEvent);
addNetworkEventHandler("vrr.syncElement", forceSyncElementProperties);
addNetworkEventHandler("vrr.elementPosition", setElementPosition);
addNetworkEventHandler("vrr.elementCollisions", setElementCollisionsEnabled);
// GUI
addNetworkEventHandler("vrr.showRegistration", showRegistrationGUI);
addNetworkEventHandler("vrr.showNewCharacter", showNewCharacterGUI);
addNetworkEventHandler("vrr.showLogin", showLoginGUI);
addNetworkEventHandler("vrr.2fa", showTwoFactorAuthGUI);
addNetworkEventHandler("vrr.showResetPasswordCodeInput", resetPasswordCodeInputGUI);
addNetworkEventHandler("vrr.showResetPasswordEmailInput", resetPasswordEmailInputGUI);
addNetworkEventHandler("vrr.showChangePassword", showChangePasswordGUI);
addNetworkEventHandler("vrr.showCharacterSelect", showCharacterSelectGUI);
addNetworkEventHandler("vrr.switchCharacterSelect", switchCharacterSelectGUI);
addNetworkEventHandler("vrr.showError", showErrorGUI);
addNetworkEventHandler("vrr.showInfo", showInfoGUI);
addNetworkEventHandler("vrr.showPrompt", showYesNoPromptGUI);
addNetworkEventHandler("vrr.loginSuccess", loginSuccess);
addNetworkEventHandler("vrr.characterSelectSuccess", characterSelectSuccess);
addNetworkEventHandler("vrr.loginFailed", loginFailed);
addNetworkEventHandler("vrr.registrationSuccess", registrationSuccess);
addNetworkEventHandler("vrr.registrationFailed", registrationFailed);
addNetworkEventHandler("vrr.newCharacterFailed", newCharacterFailed);
addNetworkEventHandler("vrr.changePassword", showChangePasswordGUI);
addNetworkEventHandler("vrr.showLocaleChooser", showLocaleChooserGUI);
addNetworkEventHandler("vrr.guiColour", setGUIColours);
addNetworkEventHandler("vrr.vehBuyState", setVehiclePurchaseState);
// Business
addNetworkEventHandler("vrr.business", receiveBusinessFromServer);
addNetworkEventHandler("vrr.showRegistration", showRegistrationGUI);
addNetworkEventHandler("vrr.showNewCharacter", showNewCharacterGUI);
addNetworkEventHandler("vrr.showLogin", showLoginGUI);
// House
addNetworkEventHandler("vrr.house", receiveHouseFromServer);
addNetworkEventHandler("vrr.logLevel", setLogLevel);
addNetworkEventHandler("vrr.infiniteRun", setLocalPlayerInfiniteRun);
// GPS
addNetworkEventHandler("vrr.showGPSBlip", showGPSLocation);
addNetworkEventHandler("vrr.business", receiveBusinessFromServer);
addNetworkEventHandler("vrr.house", receiveHouseFromServer);
// Locale
addNetworkEventHandler("vrr.locale", setLocale);
addNetworkEventHandler("vrr.localeChooser", toggleLocaleChooserGUI);
addNetworkEventHandler("vrr.holdObject", makePedHoldObject);
addNetworkEventHandler("vrr.playerPedId", sendLocalPlayerNetworkIdToServer);
addNetworkEventHandler("vrr.ped", setLocalPlayerPedPartsAndProps);
// Misc
addNetworkEventHandler("vrr.mouseCursor", toggleMouseCursor);
addNetworkEventHandler("vrr.mouseCamera", toggleMouseCamera);
addNetworkEventHandler("vrr.clearPeds", clearLocalPlayerOwnedPeds);
addNetworkEventHandler("vrr.passenger", enterVehicleAsPassenger);
addNetworkEventHandler("vrr.logo", setServerLogoRenderState);
addNetworkEventHandler("vrr.ambience", setCityAmbienceState);
addNetworkEventHandler("vrr.runCode", runClientCode);
addNetworkEventHandler("vrr.minuteDuration", setMinuteDuration);
addNetworkEventHandler("vrr.snow", setSnowState);
addNetworkEventHandler("vrr.enterPropertyKey", setEnterPropertyKey);
addNetworkEventHandler("vrr.skinSelect", toggleSkinSelect);
addNetworkEventHandler("vrr.hotbar", updatePlayerHotBar);
addNetworkEventHandler("vrr.showItemActionDelay", showItemActionDelay);
addNetworkEventHandler("vrr.set2DRendering", set2DRendering);
addNetworkEventHandler("vrr.mouseCameraForce", setMouseCameraState);
addNetworkEventHandler("vrr.logLevel", setLogLevel);
addNetworkEventHandler("vrr.hideAllGUI", hideAllGUI);
addNetworkEventHandler("vrr.nametag", updatePlayerNameTag);
addNetworkEventHandler("vrr.nametagDistance", setNameTagDistance);
addNetworkEventHandler("vrr.ping", updatePlayerPing);
addNetworkEventHandler("vrr.anim", makePedPlayAnimation);
addNetworkEventHandler("vrr.stopAnim", makePedStopAnimation);
addNetworkEventHandler("vrr.forceAnim", forcePedAnimation);
addNetworkEventHandler("vrr.clientInfo", serverRequestedClientInfo);
addNetworkEventHandler("vrr.interiorLights", updateInteriorLightsState);
addNetworkEventHandler("vrr.cutsceneInterior", setCutsceneInterior);
addNetworkEventHandler("vrr.syncElement", forceSyncElementProperties);
addNetworkEventHandler("vrr.elementPosition", setElementPosition);
addNetworkEventHandler("vrr.elementCollisions", setElementCollisionsEnabled);
addNetworkEventHandler("vrr.vehBuyState", setVehiclePurchaseState);
addNetworkEventHandler("vrr.holdObject", makePedHoldObject);
}
// ===========================================================================
function sendResourceReadySignalToServer() {
sendNetworkEventToServer("vrr.clientReady");
sendNetworkEventToServer("vrr.clientReady");
}
// ===========================================================================
function sendResourceStartedSignalToServer() {
sendNetworkEventToServer("vrr.clientStarted");
sendNetworkEventToServer("vrr.clientStarted");
}
// ===========================================================================
function sendResourceStoppedSignalToServer() {
if(isConnected) {
sendNetworkEventToServer("vrr.clientStopped");
}
if(isConnected) {
sendNetworkEventToServer("vrr.clientStopped");
}
}
// ===========================================================================
function setPlayer2DRendering(hudState, labelState, smallGameMessageState, scoreboardState, hotBarState, itemActionDelayState) {
logToConsole(LOG_DEBUG, `[VRR.Main] Updating render states (HUD: ${hudState}, Labels: ${labelState}, Bottom Text: ${smallGameMessageState}, Scoreboard: ${scoreboardState}, HotBar: ${hotBarState}, Item Action Delay: ${itemActionDelayState})`);
renderHUD = hudState;
function set2DRendering(hudState, labelState, smallGameMessageState, scoreboardState, hotBarState, itemActionDelayState) {
logToConsole(LOG_DEBUG, `[VRR.Main] Updating render states (HUD: ${hudState}, Labels: ${labelState}, Bottom Text: ${smallGameMessageState}, Scoreboard: ${scoreboardState}, HotBar: ${hotBarState}, Item Action Delay: ${itemActionDelayState})`);
renderHUD = hudState;
if(getGame() == VRR_GAME_GTA_IV) {
natives.displayCash(hudState);
natives.displayAmmo(hudState);
natives.displayHud(hudState);
natives.displayRadar(hudState);
natives.displayAreaName(hudState);
} else {
if(typeof setHUDEnabled != "undefined") {
setHUDEnabled(hudState);
}
}
if(getGame() == VRR_GAME_GTA_IV) {
natives.displayCash(hudState);
natives.displayAmmo(hudState);
natives.displayHud(hudState);
natives.displayRadar(hudState);
natives.displayAreaName(hudState);
} else {
if(typeof setHUDEnabled != "undefined") {
setHUDEnabled(hudState);
}
}
renderLabels = labelState;
renderSmallGameMessage = smallGameMessageState;
renderScoreBoard = scoreboardState;
renderHotBar = hotBarState;
renderItemActionDelay = itemActionDelayState;
renderLabels = labelState;
renderSmallGameMessage = smallGameMessageState;
renderScoreBoard = scoreboardState;
renderHotBar = hotBarState;
renderItemActionDelay = itemActionDelayState;
}
// ===========================================================================
function onServerSpawnedPlayer(state) {
logToConsole(LOG_DEBUG, `[VRR.Main] Setting spawned state to ${state}`);
isSpawned = state;
if(state) {
setUpInitialGame();
calledDeathEvent = false;
}
function onServerSpawnedLocalPlayer(state) {
logToConsole(LOG_DEBUG, `[VRR.Main] Setting spawned state to ${state}`);
isSpawned = state;
setUpInitialGame();
if(state) {
setTimeout(function() {
calledDeathEvent = false;
}, 1000);
getElementsByType(ELEMENT_PED).filter(ped => !ped.isType(ELEMENT_PLAYER)).forEach(ped => {
syncCivilianProperties(ped);
});
getElementsByType(ELEMENT_PLAYER).forEach(player => {
syncPlayerProperties(player);
});
getElementsByType(ELEMENT_VEHICLE).forEach(vehicle => {
syncVehicleProperties(vehicle);
});
}
}
// ===========================================================================
function tellServerPlayerUsedKeyBind(key) {
sendNetworkEventToServer("vrr.useKeyBind", key);
sendNetworkEventToServer("vrr.useKeyBind", key);
}
// ===========================================================================
function tellServerPlayerArrivedAtJobRouteLocation() {
sendNetworkEventToServer("vrr.arrivedAtJobRouteLocation");
sendNetworkEventToServer("vrr.arrivedAtJobRouteLocation");
}
// ===========================================================================
function tellServerItemActionDelayComplete() {
sendNetworkEventToServer("vrr.itemActionDelayComplete");
sendNetworkEventToServer("vrr.itemActionDelayComplete");
}
// ===========================================================================
function sendServerClientInfo() {
let clientVersion = "0.0.0.0";
if(typeof CLIENT_VERSION_MAJOR != "undefined") {
clientVersion = `${CLIENT_VERSION_MAJOR}.${CLIENT_VERSION_MINOR}.${CLIENT_VERSION_PATCH}.${CLIENT_VERSION_BUILD}`;
}
sendNetworkEventToServer("vrr.clientInfo", clientVersion, game.width, game.height);
let clientVersion = "0.0.0.0";
if(typeof CLIENT_VERSION_MAJOR != "undefined") {
clientVersion = `${CLIENT_VERSION_MAJOR}.${CLIENT_VERSION_MINOR}.${CLIENT_VERSION_PATCH}.${CLIENT_VERSION_BUILD}`;
}
sendNetworkEventToServer("vrr.clientInfo", clientVersion, game.width, game.height);
}
// ===========================================================================
function sendServerNewAFKStatus(state) {
sendNetworkEventToServer("vrr.afk", state);
sendNetworkEventToServer("vrr.afk", state);
}
// ===========================================================================
@@ -210,109 +264,153 @@ function anchorBoat(vehicleId) {
// ===========================================================================
function setEnterPropertyKey(key) {
enterPropertyKey = key;
enterPropertyKey = key;
}
// ===========================================================================
function serverRequestedClientInfo() {
sendServerClientInfo();
sendServerClientInfo();
}
// ===========================================================================
function updateInteriorLightsState(state) {
interiorLightsEnabled = state;
interiorLightsEnabled = state;
}
// ===========================================================================
function forceSyncElementProperties(elementId) {
if(getElementFromId(elementId) == null) {
return false;
}
if(getElementFromId(elementId) == null) {
return false;
}
syncElementProperties(getElementFromId(elementId));
}
// ===========================================================================
function setElementPosition(elementId, position) {
if(getElementFromId(elementId) == null) {
return false;
}
if(!getElementFromId(elementId).isSyncer) {
return false;
}
getElementFromId(elementId).position = position;
syncElementProperties(getElementFromId(elementId));
}
// ===========================================================================
function setElementCollisionsEnabled(elementId, state) {
if(getElementFromId(elementId) == null) {
return false;
}
if(getElementFromId(elementId) == null) {
return false;
}
getElementFromId(elementId).collisionsEnabled = state;
getElementFromId(elementId).collisionsEnabled = state;
}
// ===========================================================================
function setLocalPlayerArmour(armour) {
if(typeof localPlayer.armour != "undefined") {
localPlayer.armour = armour;
}
if(typeof localPlayer.armour != "undefined") {
localPlayer.armour = armour;
}
}
// ===========================================================================
function forceLocalPlayerWantedLevel(wantedLevel) {
forceWantedLevel = toInteger(wantedLevel);
function setLocalPlayerWantedLevel(wantedLevel) {
forceWantedLevel = toInteger(wantedLevel);
}
// ===========================================================================
function setLogLevel(level) {
logLevel = level;
logLevel = level;
}
// ===========================================================================
function setLocalPlayerInfiniteRun(state) {
if(localPlayer != null) {
if(getGame() == VRR_GAME_GTA_III || getGame() == VRR_GAME_GTA_VC) {
game.SET_PLAYER_NEVER_GETS_TIRED(game.GET_PLAYER_ID(), boolToInt(state));
}
}
if(localPlayer != null) {
if(getGame() == VRR_GAME_GTA_III || getGame() == VRR_GAME_GTA_VC) {
game.SET_PLAYER_NEVER_GETS_TIRED(game.GET_PLAYER_ID(), boolToInt(state));
}
}
}
// ===========================================================================
function setLocalPlayerSkin(skinId) {
if(getGame() == VRR_GAME_GTA_IV) {
natives.changePlayerModel(natives.getPlayerId(), skinId);
//localPlayer.skin = allowedSkins[skinSelectorIndex][0];
//localPlayer.modelIndex = allowedSkins[skinSelectorIndex][0];
} else {
localPlayer.skin = skinId;
}
logToConsole(LOG_INFO, `[VRR.Server] Setting locale player skin to ${skinId}`);
if(getGame() == VRR_GAME_GTA_IV) {
natives.changePlayerModel(natives.getPlayerId(), skinId);
} else {
localPlayer.skin = skinId;
}
}
// ===========================================================================
function makePedHoldObject(pedId, modelIndex) {
if(getGame() == VRR_GAME_GTA_IV) {
natives.givePedAmbientObject(natives.getPedFromNetworkId(pedId), getGameConfig().objects[getGame()][modelIndex][1])
}
if(getGame() == VRR_GAME_GTA_IV) {
natives.givePedAmbientObject(natives.getPedFromNetworkId(pedId), getGameConfig().objects[getGame()][modelIndex][1])
}
}
// ===========================================================================
function sendLocalPlayerNetworkIdToServer() {
sendNetworkEventToServer("vrr.playerPedId", natives.getNetworkIdFromPed(localPlayer));
sendNetworkEventToServer("vrr.playerPedId", natives.getNetworkIdFromPed(localPlayer));
}
// ===========================================================================
function setCutsceneInterior(cutsceneName) {
if(getGame() == VRR_GAME_GTA_IV) {
if(cutsceneName == "") {
natives.clearCutscene();
} else {
if(natives.isInteriorScene()) {
natives.clearCutscene();
}
natives.initCutscene(cutsceneName);
}
}
}
// ===========================================================================
function makeLocalPlayerPedSpeak(speechName) {
if(getGame() == VRR_GAME_GTA_IV) {
// if player is in vehicle, allow megaphone (if last arg is "1", it will cancel megaphone echo)
// Only speeches with _MEGAPHONE will have the bullhorn effect
// Afaik it only works on police voices anyway
if(localPlayer.vehicle != null) {
natives.sayAmbientSpeech(localPlayer, speechName, true, false, 0);
} else {
natives.sayAmbientSpeech(localPlayer, speechName, true, false, 1);
}
} else if(getGame() == VRR_GAME_GTA_III || getGame() == VRR_GAME_GTA_VC) {
// Don't have a way to get the ped ref ID and can't use ped in arg
//game.SET_CHAR_SAY(game.GET_PLAYER_ID(), int);
}
}
// ===========================================================================
function setLocalPlayerAsCopState(state) {
if(getGame() == VRR_GAME_GTA_IV) {
natives.setPlayerAsCop(natives.getPlayerId(), state);
natives.setPoliceIgnorePlayer(natives.getPlayerId(), state);
}
}
// ===========================================================================
function serverRequestedLocalPlayerSpawn(skinId, position) {
if(getGame() == VRR_GAME_GTA_IV) {
natives.createPlayer(skinId, position);
//if(isCustomCameraSupported()) {
// game.restoreCamera(true);
//}
}
}
// ===========================================================================
function sendLocaleSelectToServer(localeId) {
sendNetworkEventToServer("vrr.localeSelect", localeId);
}
// ===========================================================================

View File

@@ -45,95 +45,111 @@ function loadSkinSelectMessageFontBottom() {
function processSkinSelectKeyPress(keyCode) {
if(usingSkinSelector) {
if(keyCode == SDLK_PAGEUP) {
if(skinSelectorIndex >= allowedSkins.length-1) {
skinSelectorIndex = 1;
} else {
skinSelectorIndex = skinSelectorIndex + 1;
}
logToConsole(LOG_DEBUG, `Switching to skin ${allowedSkins[skinSelectorIndex][1]} (Index: ${skinSelectorIndex}, Skin: ${allowedSkins[skinSelectorIndex][0]})`);
skinSelectMessageTextTop = allowedSkins[skinSelectorIndex][1];
if(getGame() == VRR_GAME_GTA_IV) {
//natives.changePlayerModel(natives.getPlayerId(), allowedSkins[skinSelectorIndex][0]);
//localPlayer.skin = allowedSkins[skinSelectorIndex][0];
//localPlayer.modelIndex = allowedSkins[skinSelectorIndex][0];
} else {
localPlayer.skin = allowedSkins[skinSelectorIndex][0];
}
} else if(keyCode == SDLK_PAGEDOWN) {
if(skinSelectorIndex <= 0) {
skinSelectorIndex = allowedSkins.length-1;
} else {
skinSelectorIndex = skinSelectorIndex - 1;
}
logToConsole(LOG_DEBUG, `Switching to skin ${allowedSkins[skinSelectorIndex][1]} (Index: ${skinSelectorIndex}, Skin: ${allowedSkins[skinSelectorIndex][0]})`);
skinSelectMessageTextTop = allowedSkins[skinSelectorIndex][1];
if(getGame() == VRR_GAME_GTA_IV) {
//natives.changePlayerModel(natives.getPlayerId(), allowedSkins[skinSelectorIndex][0]);
//localPlayer.skin = allowedSkins[skinSelectorIndex][0];
//localPlayer.modelIndex = allowedSkins[skinSelectorIndex][0];
} else {
localPlayer.skin = allowedSkins[skinSelectorIndex][0];
}
} else if(keyCode == SDLK_RETURN) {
sendNetworkEventToServer("vrr.skinSelected", skinSelectorIndex);
toggleSkinSelect(false);
return true;
} else if(keyCode == SDLK_BACKSPACE) {
sendNetworkEventToServer("vrr.skinSelected", -1);
toggleSkinSelect(false);
return true;
}
localPlayer.heading = skinSelectHeading;
}
if(keyCode == SDLK_PAGEUP) {
if(skinSelectorIndex >= allowedSkins.length-1) {
skinSelectorIndex = 1;
} else {
skinSelectorIndex = skinSelectorIndex + 1;
}
logToConsole(LOG_DEBUG, `Switching to skin ${allowedSkins[skinSelectorIndex][1]} (Index: ${skinSelectorIndex}, Skin: ${allowedSkins[skinSelectorIndex][0]})`);
skinSelectMessageTextTop = allowedSkins[skinSelectorIndex][1];
if(getGame() == VRR_GAME_GTA_IV) {
let skinId = allowedSkins[skinSelectorIndex][0];
if(natives.isModelInCdimage(skinId)) {
natives.requestModel(skinId);
natives.loadAllObjectsNow();
if(natives.hasModelLoaded(skinId)) {
natives.changePlayerModel(natives.getPlayerId(), skinId);
}
}
} else {
localPlayer.skin = allowedSkins[skinSelectorIndex][0];
}
} else if(keyCode == SDLK_PAGEDOWN) {
if(skinSelectorIndex <= 0) {
skinSelectorIndex = allowedSkins.length-1;
} else {
skinSelectorIndex = skinSelectorIndex - 1;
}
logToConsole(LOG_DEBUG, `Switching to skin ${allowedSkins[skinSelectorIndex][1]} (Index: ${skinSelectorIndex}, Skin: ${allowedSkins[skinSelectorIndex][0]})`);
skinSelectMessageTextTop = allowedSkins[skinSelectorIndex][1];
if(getGame() == VRR_GAME_GTA_IV) {
let skinId = allowedSkins[skinSelectorIndex][0];
if(natives.isModelInCdimage(skinId)) {
natives.requestModel(skinId);
natives.loadAllObjectsNow();
if(natives.hasModelLoaded(skinId)) {
natives.changePlayerModel(natives.getPlayerId(), skinId);
}
}
} else {
localPlayer.skin = allowedSkins[skinSelectorIndex][0];
}
} else if(keyCode == SDLK_RETURN) {
sendNetworkEventToServer("vrr.skinSelected", skinSelectorIndex);
toggleSkinSelect(false);
return true;
} else if(keyCode == SDLK_BACKSPACE) {
sendNetworkEventToServer("vrr.skinSelected", -1);
toggleSkinSelect(false);
return true;
}
localPlayer.heading = skinSelectHeading;
}
}
// ===========================================================================
function processSkinSelectRendering() {
if(usingSkinSelector) {
if(skinSelectMessageFontTop != null && skinSelectMessageFontBottom != null) {
if(skinSelectMessageTextTop != "" && skinSelectMessageTextBottom != "") {
skinSelectMessageFontTop.render(skinSelectMessageTextTop, [0, game.height-100], game.width, 0.5, 0.0, skinSelectMessageFontTop.size, skinSelectMessageColourTop, true, true, false, true);
skinSelectMessageFontBottom.render(skinSelectMessageTextBottom, [0, game.height-65], game.width, 0.5, 0.0, skinSelectMessageFontBottom.size, skinSelectMessageColourBottom, true, true, false, true);
}
}
}
if(skinSelectMessageFontTop != null && skinSelectMessageFontBottom != null) {
if(skinSelectMessageTextTop != "" && skinSelectMessageTextBottom != "") {
skinSelectMessageFontTop.render(skinSelectMessageTextTop, [0, game.height-100], game.width, 0.5, 0.0, skinSelectMessageFontTop.size, skinSelectMessageColourTop, true, true, false, true);
skinSelectMessageFontBottom.render(skinSelectMessageTextBottom, [0, game.height-65], game.width, 0.5, 0.0, skinSelectMessageFontBottom.size, skinSelectMessageColourBottom, true, true, false, true);
}
}
}
}
// ===========================================================================
function toggleSkinSelect(state) {
if(state) {
skinSelectorIndex = getAllowedSkinIndexFromSkin(localPlayer.skin);
if(!skinSelectorIndex) {
skinSelectorIndex = 0;
}
if(state) {
skinSelectorIndex = getAllowedSkinIndexFromSkin(localPlayer.skin);
if(!skinSelectorIndex) {
skinSelectorIndex = 0;
}
usingSkinSelector = true;
skinSelectPosition = localPlayer.position;
skinSelectHeading = localPlayer.heading;
usingSkinSelector = true;
skinSelectPosition = localPlayer.position;
skinSelectHeading = localPlayer.heading;
if(isCustomCameraSupported()) {
let tempPosition = localPlayer.position;
tempPosition.z += 0.5;
let frontCameraPosition = getPosInFrontOfPos(tempPosition, localPlayer.heading, 3);
game.setCameraLookAt(frontCameraPosition, localPlayer.position, true);
}
if(isCustomCameraSupported()) {
let tempPosition = localPlayer.position;
tempPosition.z += 0.5;
let frontCameraPosition = getPosInFrontOfPos(tempPosition, localPlayer.heading, 3);
game.setCameraLookAt(frontCameraPosition, localPlayer.position, true);
}
if(getGame() == VRR_GAME_GTA_IV) {
//natives.changePlayerModel(natives.getPlayerId(), allowedSkins[skinSelectorIndex][0]);
localPlayer.skin = allowedSkins[skinSelectorIndex][0];
} else {
localPlayer.skin = allowedSkins[skinSelectorIndex][0];
}
skinSelectMessageTextTop = allowedSkins[skinSelectorIndex][1];
setLocalPlayerControlState(false, false);
} else {
usingSkinSelector = false;
setLocalPlayerControlState(false, false);
}
if(getGame() == VRR_GAME_GTA_IV) {
let skinId = allowedSkins[skinSelectorIndex][0];
if(natives.isModelInCdimage(skinId)) {
natives.requestModel(skinId);
natives.loadAllObjectsNow();
if(natives.hasModelLoaded(skinId)) {
natives.changePlayerModel(natives.getPlayerId(), skinId);
}
}
} else {
localPlayer.skin = allowedSkins[skinSelectorIndex][0];
}
skinSelectMessageTextTop = allowedSkins[skinSelectorIndex][1];
setLocalPlayerControlState(false, false);
} else {
usingSkinSelector = false;
setLocalPlayerControlState(false, false);
}
}
// ===========================================================================

View File

@@ -8,162 +8,192 @@
// ===========================================================================
function initClientScripts() {
initGUIScript();
initNameTagScript();
initScoreBoardScript();
initMessagingScript();
initServerScript();
initLogoScript();
initLabelScript();
initChatBoxScript();
initAFKScript();
initKeyBindScript();
initEventScript();
initSkinSelectScript();
initGUIScript();
initNameTagScript();
initScoreBoardScript();
initMessagingScript();
initServerScript();
initLogoScript();
initLabelScript();
initChatBoxScript();
initAFKScript();
initKeyBindScript();
initEventScript();
initSkinSelectScript();
}
// ===========================================================================
function setUpInitialGame() {
if(getGame() == VRR_GAME_GTA_III) {
game.SET_PLAYER_NEVER_GETS_TIRED(game.GET_PLAYER_ID(), 0);
game.setGameStat(STAT_PROGRESSMADE, 9999);
game.setGameStat(STAT_TOTALPROGRESSINGAME, 9999);
game.SET_CAR_DENSITY_MULTIPLIER(3.0);
game.SET_PED_DENSITY_MULTIPLIER(3.0);
game.onMission = true;
SetStandardControlsEnabled(true);
return true;
}
if(getGame() == VRR_GAME_GTA_III) {
logToConsole(LOG_DEBUG|LOG_WARN, "Setting up initial game stuff for GTA III ...");
if(getGame() == VRR_GAME_GTA_VC) {
game.SET_PLAYER_NEVER_GETS_TIRED(game.GET_PLAYER_ID(), 0);
game.setGameStat(STAT_PROGRESSMADE, 9999);
game.setGameStat(STAT_TOTALPROGRESSINGAME, 9999);
game.SET_CAR_DENSITY_MULTIPLIER(3.0);
game.SET_PED_DENSITY_MULTIPLIER(3.0);
// Turn off unlimited sprint
game.SET_PLAYER_NEVER_GETS_TIRED(game.GET_PLAYER_ID(), 0);
game.REQUEST_ANIMATION("bikev");
game.REQUEST_ANIMATION("bikeh");
game.REQUEST_ANIMATION("biked");
game.REQUEST_ANIMATION("knife");
game.REQUEST_ANIMATION("python");
game.REQUEST_ANIMATION("shotgun");
game.REQUEST_ANIMATION("buddy");
game.REQUEST_ANIMATION("tec");
game.REQUEST_ANIMATION("uzi");
game.REQUEST_ANIMATION("rifle");
game.REQUEST_ANIMATION("m60");
game.REQUEST_ANIMATION("sniper");
game.REQUEST_ANIMATION("grenade");
game.REQUEST_ANIMATION("flame");
game.REQUEST_ANIMATION("medic");
game.REQUEST_ANIMATION("sunbathe");
//game.REQUEST_ANIMATION("playidles");
game.REQUEST_ANIMATION("riot");
game.REQUEST_ANIMATION("strip");
game.REQUEST_ANIMATION("lance");
game.REQUEST_ANIMATION("skate");
// Set completed game progress
game.setGameStat(STAT_PROGRESSMADE, 9999);
game.setGameStat(STAT_TOTALPROGRESSINGAME, 9999);
game.LOAD_ALL_MODELS_NOW();
game.onMission = true;
SetStandardControlsEnabled(true);
return true;
}
// Traffic and ped density
//game.SET_CAR_DENSITY_MULTIPLIER(3.0); // No visual effect. Needs tweaking and testing.
//game.SET_PED_DENSITY_MULTIPLIER(3.0); // No visual effect. Needs tweaking and testing.
if(getGame() == VRR_GAME_GTA_SA) {
game.setGameStat(STAT_WEAPONTYPE_PISTOL_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_PISTOL_SILENCED_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_DESERT_EAGLE_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_SHOTGUN_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_SAWNOFF_SHOTGUN_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_SPAS12_SHOTGUN_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_MICRO_UZI_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_MP5_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_AK47_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_M4_SKILL, 400);
game.setGameStat(STAT_DRIVING_SKILL, 9999);
game.setGameStat(STAT_FAT, 9999);
game.setGameStat(STAT_ENERGY, 9999);
game.setGameStat(STAT_CYCLE_SKILL, 9999);
game.setGameStat(STAT_BIKE_SKILL, 9999);
game.setGameStat(STAT_GAMBLING, 9999);
game.setGameStat(STAT_PROGRESS_MADE, 9999);
game.setGameStat(STAT_RESPECT, 0);
game.setGameStat(STAT_RESPECT_TOTAL, 0);
game.setGameStat(STAT_SEX_APPEAL, 0);
game.setGameStat(STAT_STAMINA, 9999);
game.setGameStat(STAT_TOTAL_PROGRESS, 9999);
game.setGameStat(STAT_UNDERWATER_STAMINA, 9999);
game.setGameStat(STAT_BODY_MUSCLE, 9999);
// Disables taxi/vigilante/etc and other start mission triggers
game.onMission = true;
game.setDefaultInteriors(false);
game.onMission = true;
return true;
}
// Provided by mouse camera script (mousecam.js)
SetStandardControlsEnabled(true);
} else if(getGame() == VRR_GAME_GTA_VC) {
logToConsole(LOG_DEBUG|LOG_WARN, "Setting up initial game stuff for GTA Vice City ...");
if(getGame() == VRR_GAME_GTA_IV) {
natives.allowEmergencyServices(false);
natives.setCreateRandomCops(true);
natives.setMaxWantedLevel(0);
natives.setWantedMultiplier(0.0);
natives.allowPlayerToCarryNonMissionObjects(natives.getPlayerId(), true);
natives.setPlayerTeam(natives.getPlayerId(), 0);
natives.loadAllObjectsNow();
natives.setCellphoneRanked(false);
natives.setOverrideNoSprintingOnPhoneInMultiplayer(false);
natives.setSyncWeatherAndGameTime(false);
natives.usePlayerColourInsteadOfTeamColour(true);
natives.disablePauseMenu(true);
natives.allowReactionAnims(localPlayer, true);
natives.allowGameToPauseForStreaming(false);
natives.allowStuntJumpsToTrigger(false);
natives.setPickupsFixCars(false);
// Turn off unlimited sprint
game.SET_PLAYER_NEVER_GETS_TIRED(game.GET_PLAYER_ID(), 0);
// HUD and Display
//natives.displayCash(false);
//natives.displayAmmo(false);
//natives.displayHud(false);
//natives.displayRadar(false);
//natives.displayAreaName(false);
//natives.displayPlayerNames(false);
natives.setPoliceRadarBlips(false);
natives.removeTemporaryRadarBlipsForPickups();
natives.displayNonMinigameHelpMessages(false);
natives.setDisplayPlayerNameAndIcon(natives.getPlayerId(), false);
// Set completed game progress
game.setGameStat(STAT_PROGRESSMADE, 99999);
game.setGameStat(STAT_TOTALPROGRESSINGAME, 99999);
// Item/Money Dropping
natives.setMoneyCarriedByAllNewPeds(0);
natives.setDeadPedsDropWeapons(false);
natives.setPlayersDropMoneyInNetworkGame(false);
// Traffic and ped density
//game.SET_CAR_DENSITY_MULTIPLIER(3.0); // No visual effect. Needs tweaking and testing.
//game.SET_PED_DENSITY_MULTIPLIER(3.0); // No visual effect. Needs tweaking and testing.
// Population
//natives.dontSuppressAnyCarModels(5.0);
//natives.dontSuppressAnyPedModels(5.0);
//natives.forceGenerateParkedCarsTooCloseToOthers(true);
//natives.setParkedCarDensityMultiplier(5.0);
//natives.setRandomCarDensityMultiplier(5.0);
//natives.setPedDensityMultiplier(5.0);
//natives.setCarDensityMultiplier(5.0);
//natives.setScenarioPedDensityMultiplier(5.0, 5.0);
natives.switchRandomTrains(true);
natives.switchRandomBoats(true);
natives.switchAmbientPlanes(true);
natives.switchMadDrivers(false);
// Load all anim libs
game.REQUEST_ANIMATION("bikev");
game.REQUEST_ANIMATION("bikeh");
game.REQUEST_ANIMATION("biked");
game.REQUEST_ANIMATION("knife");
game.REQUEST_ANIMATION("python");
game.REQUEST_ANIMATION("shotgun");
game.REQUEST_ANIMATION("buddy");
game.REQUEST_ANIMATION("tec");
game.REQUEST_ANIMATION("uzi");
game.REQUEST_ANIMATION("rifle");
game.REQUEST_ANIMATION("m60");
game.REQUEST_ANIMATION("sniper");
game.REQUEST_ANIMATION("grenade");
game.REQUEST_ANIMATION("flame");
game.REQUEST_ANIMATION("medic");
game.REQUEST_ANIMATION("sunbathe");
//game.REQUEST_ANIMATION("playidles");
game.REQUEST_ANIMATION("riot");
game.REQUEST_ANIMATION("strip");
game.REQUEST_ANIMATION("lance");
game.REQUEST_ANIMATION("skate");
natives.requestAnims("DANCING");
return true;
}
//game.LOAD_ALL_MODELS_NOW();
// Disables taxi/vigilante/etc and other start mission triggers
game.onMission = true;
if(getGame() == VRR_GAME_MAFIA_ONE) {
game.mapEnabled = false;
game.setTrafficEnabled(false);
return true;
}
// Provided by mouse camera script (mousecam.js)
SetStandardControlsEnabled(true);
} else if(getGame() == VRR_GAME_GTA_SA) {
logToConsole(LOG_DEBUG|LOG_WARN, "Setting up initial game stuff for GTA San Andreas ...");
// Turn weapon skills down a bit
game.setGameStat(STAT_WEAPONTYPE_PISTOL_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_PISTOL_SILENCED_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_DESERT_EAGLE_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_SHOTGUN_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_SAWNOFF_SHOTGUN_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_SPAS12_SHOTGUN_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_MICRO_UZI_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_MP5_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_AK47_SKILL, 400);
game.setGameStat(STAT_WEAPONTYPE_M4_SKILL, 400);
// Pro driving skill
game.setGameStat(STAT_DRIVING_SKILL, 9999);
// Only visual for CJ, but affects all peds fight speed, bicycle hop, etc
game.setGameStat(STAT_FAT, 9999);
game.setGameStat(STAT_ENERGY, 9999);
game.setGameStat(STAT_CYCLE_SKILL, 9999);
game.setGameStat(STAT_BIKE_SKILL, 9999);
game.setGameStat(STAT_GAMBLING, 9999);
game.setGameStat(STAT_PROGRESS_MADE, 9999);
game.setGameStat(STAT_RESPECT, 0);
game.setGameStat(STAT_RESPECT_TOTAL, 0);
game.setGameStat(STAT_SEX_APPEAL, 0);
game.setGameStat(STAT_STAMINA, 9999);
game.setGameStat(STAT_TOTAL_PROGRESS, 9999);
game.setGameStat(STAT_UNDERWATER_STAMINA, 9999);
game.setGameStat(STAT_BODY_MUSCLE, 9999);
// Disables default yellow cone at doors for entering places in singleplayer
game.setDefaultInteriors(false);
// Disables taxi/vigilante/etc and other start mission triggers
game.onMission = true;
} else if(getGame() == VRR_GAME_GTA_IV) {
natives.allowEmergencyServices(false);
natives.setCreateRandomCops(true);
natives.setMaxWantedLevel(0);
natives.setWantedMultiplier(0.0);
natives.allowPlayerToCarryNonMissionObjects(natives.getPlayerId(), true);
natives.setPlayerTeam(natives.getPlayerId(), 0);
natives.loadAllObjectsNow();
natives.setCellphoneRanked(false);
natives.setOverrideNoSprintingOnPhoneInMultiplayer(false);
natives.setSyncWeatherAndGameTime(false);
natives.usePlayerColourInsteadOfTeamColour(true);
natives.disablePauseMenu(true);
//natives.allowReactionAnims(localPlayer, false);
natives.allowGameToPauseForStreaming(false);
natives.allowStuntJumpsToTrigger(false);
natives.setPickupsFixCars(false);
natives.forceFullVoice(localPlayer);
// HUD and Display
//natives.displayCash(false);
//natives.displayAmmo(false);
//natives.displayHud(false);
//natives.displayRadar(false);
//natives.displayAreaName(false);
natives.displayPlayerNames(true);
natives.setPoliceRadarBlips(false);
natives.removeTemporaryRadarBlipsForPickups();
natives.displayNonMinigameHelpMessages(false);
natives.setDisplayPlayerNameAndIcon(natives.getPlayerId(), true);
// Item/Money Dropping
natives.setMoneyCarriedByAllNewPeds(0);
natives.setDeadPedsDropWeapons(false);
natives.setPlayersDropMoneyInNetworkGame(false);
// Population
//natives.dontSuppressAnyCarModels(5.0);
//natives.dontSuppressAnyPedModels(5.0);
//natives.forceGenerateParkedCarsTooCloseToOthers(true);
//natives.setParkedCarDensityMultiplier(5.0);
//natives.setRandomCarDensityMultiplier(5.0);
//natives.setPedDensityMultiplier(5.0);
//natives.setCarDensityMultiplier(5.0);
//natives.setScenarioPedDensityMultiplier(5.0, 5.0);
natives.switchRandomTrains(true);
natives.switchRandomBoats(true);
natives.switchAmbientPlanes(true);
natives.switchMadDrivers(false);
// Singleplayer Cellphone
//natives.requestScript("spcellphone");
//natives.startNewScript("spcellphone", 0);
// Script "v-blockedscripts" blocks the mpcellphone scripts
natives.setMessagesWaiting(false); // Seems to have no effect
natives.setMobilePhoneRadioState(false);
// Animation libraries
natives.requestAnims("DANCING");
// Some last steps
//natives.loadAllObjectsNow();
} else if(getGame() == VRR_GAME_MAFIA_ONE) {
game.mapEnabled = false;
game.setTrafficEnabled(false);
}
}
// ===========================================================================
initClientScripts();
// ===========================================================================
// ===========================================================================

View File

@@ -8,430 +8,432 @@
// ===========================================================================
function processSync(event, deltaTime) {
if(localPlayer != null) {
if(!areServerElementsSupported()) {
sendNetworkEventToServer("vrr.plr.pos", localPlayer.position);
sendNetworkEventToServer("vrr.plr.rot", localPlayer.heading);
if(localPlayer != null) {
if(!areServerElementsSupported()) {
sendNetworkEventToServer("vrr.plr.pos", (localPlayer.vehicle != null) ? localPlayer.vehicle.position : localPlayer.position);
sendNetworkEventToServer("vrr.plr.rot", (localPlayer.vehicle != null) ? localPlayer.vehicle.heading : localPlayer.heading);
//if(localPlayer.vehicle != null) {
// sendNetworkEventToServer("vrr.veh.pos", getVehicleForNetworkEvent(localPlayer.vehicle), localPlayer.vehicle.position);
// sendNetworkEventToServer("vrr.veh.rot", getVehicleForNetworkEvent(localPlayer.vehicle), localPlayer.vehicle.heading);
//}
}
//if(localPlayer.vehicle != null) {
// sendNetworkEventToServer("vrr.veh.pos", getVehicleForNetworkEvent(localPlayer.vehicle), localPlayer.vehicle.position);
// sendNetworkEventToServer("vrr.veh.rot", getVehicleForNetworkEvent(localPlayer.vehicle), localPlayer.vehicle.heading);
//}
}
if(localPlayer.health <= 0) {
if(!calledDeathEvent) {
logToConsole(LOG_DEBUG, `Local player died`);
localPlayer.clearWeapons();
calledDeathEvent = true;
sendNetworkEventToServer("vrr.playerDeath");
}
}
if(localPlayer.health <= 0) {
if(!calledDeathEvent) {
logToConsole(LOG_DEBUG, `Local player died`);
localPlayer.clearWeapons();
calledDeathEvent = true;
sendNetworkEventToServer("vrr.playerDeath");
}
}
}
if(streamingRadioElement) {
streamingRadio.position = getElementPosition(streamingRadioElement);
//streamingRadio.volume = getStreamingRadioVolumeForPosition(streamingRadio.position);
}
}
if(localPlayer.health <= 0) {
if(!calledDeathEvent) {
logToConsole(LOG_DEBUG, `Local player died`);
localPlayer.clearWeapons();
calledDeathEvent = true;
sendNetworkEventToServer("vrr.playerDeath");
}
}
if(streamingRadioElement) {
streamingRadio.position = getElementPosition(streamingRadioElement.id);
//streamingRadio.volume = getStreamingRadioVolumeForPosition(streamingRadio.position);
}
}
// ===========================================================================
function setVehicleEngine(vehicleId, state) {
getElementFromId(vehicleId).engine = state;
getElementFromId(vehicleId).engine = state;
}
// ===========================================================================
function setVehicleLights(vehicleId, state) {
if(getGame() != VRR_GAME_MAFIA_ONE) {
if(!state) {
getElementFromId(vehicleId).lightStatus = 2;
} else {
getElementFromId(vehicleId).lightStatus = 1;
}
} else if(getGame() == VRR_GAME_GTA_IV) {
if(!state) {
natives.forceCarLights(natives.getVehicleFromNetworkId(vehicleId, 0));
} else {
natives.forceCarLights(natives.getVehicleFromNetworkId(vehicleId, 1));
}
} else {
if(!state) {
getElementFromId(vehicleId).lights = false;
} else {
getElementFromId(vehicleId).lights = true;
}
}
if(getGame() != VRR_GAME_MAFIA_ONE) {
if(!state) {
getElementFromId(vehicleId).lightStatus = 2;
} else {
getElementFromId(vehicleId).lightStatus = 1;
}
} else if(getGame() == VRR_GAME_GTA_IV) {
if(!state) {
natives.forceCarLights(natives.getVehicleFromNetworkId(vehicleId, 0));
} else {
natives.forceCarLights(natives.getVehicleFromNetworkId(vehicleId, 1));
}
} else {
if(!state) {
getElementFromId(vehicleId).lights = false;
} else {
getElementFromId(vehicleId).lights = true;
}
}
}
// ===========================================================================
function repairVehicle(syncId) {
getVehicleFromSyncId(syncId).fix();
getVehicleFromSyncId(syncId).fix();
}
// ===========================================================================
function syncVehicleProperties(vehicle) {
if(!areServerElementsSupported()) {
return false;
}
if(!areServerElementsSupported()) {
return false;
}
if(doesEntityDataExist(vehicle, "vrr.lights")) {
let lightStatus = getEntityData(vehicle, "vrr.lights");
if(!lightStatus) {
vehicle.lightStatus = 2;
} else {
vehicle.lightStatus = 1;
}
}
if(doesEntityDataExist(vehicle, "vrr.lights")) {
let lightStatus = getEntityData(vehicle, "vrr.lights");
if(!lightStatus) {
vehicle.lightStatus = 2;
} else {
vehicle.lightStatus = 1;
}
}
if(doesEntityDataExist(vehicle, "vrr.invincible")) {
let invincible = getEntityData(vehicle, "vrr.invincible");
element.setProofs(invincible, invincible, invincible, invincible, invincible);
}
if(doesEntityDataExist(vehicle, "vrr.invincible")) {
let invincible = getEntityData(vehicle, "vrr.invincible");
element.setProofs(invincible, invincible, invincible, invincible, invincible);
}
if(doesEntityDataExist(vehicle, "vrr.panelStatus")) {
let panelsStatus = getEntityData(vehicle, "vrr.panelStatus");
for(let i in panelsStatus) {
vehicle.setPanelStatus(i, panelsStatus[i]);
}
}
if(doesEntityDataExist(vehicle, "vrr.panelStatus")) {
let panelsStatus = getEntityData(vehicle, "vrr.panelStatus");
for(let i in panelsStatus) {
vehicle.setPanelStatus(i, panelsStatus[i]);
}
}
if(doesEntityDataExist(vehicle, "vrr.wheelStatus")) {
let wheelsStatus = getEntityData(vehicle, "vrr.wheelStatus");
for(let i in wheelsStatus) {
vehicle.setWheelStatus(i, wheelsStatus[i]);
}
}
if(doesEntityDataExist(vehicle, "vrr.wheelStatus")) {
let wheelsStatus = getEntityData(vehicle, "vrr.wheelStatus");
for(let i in wheelsStatus) {
vehicle.setWheelStatus(i, wheelsStatus[i]);
}
}
if(doesEntityDataExist(vehicle, "vrr.lightStatus")) {
let lightStatus = getEntityData(vehicle, "vrr.lightStatus");
for(let i in lightStatus) {
vehicle.setLightStatus(i, lightStatus[i]);
}
}
if(doesEntityDataExist(vehicle, "vrr.lightStatus")) {
let lightStatus = getEntityData(vehicle, "vrr.lightStatus");
for(let i in lightStatus) {
vehicle.setLightStatus(i, lightStatus[i]);
}
}
if(doesEntityDataExist(vehicle, "vrr.suspensionHeight")) {
let suspensionHeight = getEntityData(vehicle, "vrr.suspensionHeight");
vehicle.setSuspensionHeight(suspensionHeight);
}
if(doesEntityDataExist(vehicle, "vrr.suspensionHeight")) {
let suspensionHeight = getEntityData(vehicle, "vrr.suspensionHeight");
vehicle.setSuspensionHeight(suspensionHeight);
}
if(getGame() == VRR_GAME_GTA_SA) {
let allUpgrades = getGameConfig().vehicleUpgrades[getGame()];
for(let i in allUpgrades) {
vehicle.removeUpgrade(i);
}
if(getGame() == VRR_GAME_GTA_SA) {
//let allUpgrades = getGameConfig().vehicleUpgrades[getGame()];
//for(let i in allUpgrades) {
// vehicle.removeUpgrade(i);
//}
if(doesEntityDataExist(vehicle, "vrr.upgrades")) {
let upgrades = getEntityData(vehicle, "vrr.upgrades");
for(let i in upgrades) {
if(upgrades[i] != 0) {
vehicle.addUpgrade(upgrades[i]);
}
}
}
}
if(doesEntityDataExist(vehicle, "vrr.upgrades")) {
let upgrades = getEntityData(vehicle, "vrr.upgrades");
for(let i in upgrades) {
if(upgrades[i] != 0) {
vehicle.addUpgrade(upgrades[i]);
}
}
}
}
if(getGame() == VRR_GAME_GTA_SA || getGame() == VRR_GAME_GTA_IV) {
if(doesEntityDataExist(vehicle, "vrr.livery")) {
let livery = getEntityData(vehicle, "vrr.livery");
if(getGame() == VRR_GAME_GTA_SA) {
vehicle.setPaintJob(livery);
} else if(getGame() == VRR_GAME_GTA_IV) {
vehicle.livery = livery;
}
}
}
if(getGame() == VRR_GAME_GTA_SA || getGame() == VRR_GAME_GTA_IV) {
if(doesEntityDataExist(vehicle, "vrr.livery")) {
let livery = getEntityData(vehicle, "vrr.livery");
if(getGame() == VRR_GAME_GTA_SA) {
vehicle.setPaintJob(livery);
} else if(getGame() == VRR_GAME_GTA_IV) {
vehicle.livery = livery;
}
}
}
}
// ===========================================================================
function syncCivilianProperties(civilian) {
if(!areServerElementsSupported()) {
return false;
}
if(!areServerElementsSupported()) {
return false;
}
if(getGame() == VRR_GAME_GTA_III) {
if(doesEntityDataExist(civilian, "vrr.scale")) {
let scaleFactor = getEntityData(civilian, "vrr.scale");
let tempMatrix = civilian.matrix;
tempMatrix.setScale(toVector3(scaleFactor.x, scaleFactor.y, scaleFactor.z));
let tempPosition = civilian.position;
civilian.matrix = tempMatrix;
tempPosition.z += scaleFactor.z;
civilian.position = tempPosition;
}
}
if(getGame() == VRR_GAME_GTA_III) {
if(doesEntityDataExist(civilian, "vrr.scale")) {
let scaleFactor = getEntityData(civilian, "vrr.scale");
let tempMatrix = civilian.matrix;
tempMatrix.setScale(toVector3(scaleFactor.x, scaleFactor.y, scaleFactor.z));
let tempPosition = civilian.position;
civilian.matrix = tempMatrix;
tempPosition.z += scaleFactor.z;
civilian.position = tempPosition;
}
}
if(getGame() == VRR_GAME_GTA_SA) {
if(doesEntityDataExist(civilian, "vrr.fightStyle")) {
let fightStyle = getEntityData(civilian, "vrr.fightStyle");
civilian.setFightStyle(fightStyle[0], fightStyle[1]);
}
}
if(getGame() == VRR_GAME_GTA_SA) {
if(doesEntityDataExist(civilian, "vrr.fightStyle")) {
let fightStyle = getEntityData(civilian, "vrr.fightStyle");
civilian.setFightStyle(fightStyle[0], fightStyle[1]);
}
}
if(getGame() == VRR_GAME_GTA_III) {
if(doesEntityDataExist(civilian, "vrr.walkStyle")) {
let walkStyle = getEntityData(civilian, "vrr.walkStyle");
civilian.walkStyle = walkStyle;
}
}
if(getGame() == VRR_GAME_GTA_III) {
if(doesEntityDataExist(civilian, "vrr.walkStyle")) {
let walkStyle = getEntityData(civilian, "vrr.walkStyle");
civilian.walkStyle = walkStyle;
}
}
if(getGame() == VRR_GAME_GTA_IV) {
if(doesEntityDataExist(civilian, "vrr.bodyPropHair")) {
let bodyPropHair = getEntityData(civilian, "vrr.bodyPropHair");
civilian.changeBodyProp(0, bodyPropHair[0], bodyPropHair[1]);
}
if(getGame() == VRR_GAME_GTA_IV) {
if(doesEntityDataExist(civilian, "vrr.bodyPropHair")) {
let bodyPropHair = getEntityData(civilian, "vrr.bodyPropHair");
civilian.changeBodyProp(0, bodyPropHair[0], bodyPropHair[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropHead")) {
let bodyPropHead = getEntityData(civilian, "vrr.bodyPropHead");
civilian.changeBodyProp(1, bodyPropHead[0], bodyPropHead[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropHead")) {
let bodyPropHead = getEntityData(civilian, "vrr.bodyPropHead");
civilian.changeBodyProp(1, bodyPropHead[0], bodyPropHead[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropEyes")) {
let bodyPropEyes = getEntityData(civilian, "vrr.bodyPropEyes");
civilian.changeBodyProp(1, bodyPropEyes[0], bodyPropEyes[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropEyes")) {
let bodyPropEyes = getEntityData(civilian, "vrr.bodyPropEyes");
civilian.changeBodyProp(1, bodyPropEyes[0], bodyPropEyes[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropLeftHand")) {
let bodyPropLeftHand = getEntityData(civilian, "vrr.bodyPropLeftHand");
civilian.changeBodyProp(1, bodyPropLeftHand[0], bodyPropLeftHand[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropLeftHand")) {
let bodyPropLeftHand = getEntityData(civilian, "vrr.bodyPropLeftHand");
civilian.changeBodyProp(1, bodyPropLeftHand[0], bodyPropLeftHand[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropRightHand")) {
let bodyPropRightHand = getEntityData(civilian, "vrr.bodyPropRightHand");
civilian.changeBodyProp(1, bodyPropRightHand[0], bodyPropRightHand[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropRightHand")) {
let bodyPropRightHand = getEntityData(civilian, "vrr.bodyPropRightHand");
civilian.changeBodyProp(1, bodyPropRightHand[0], bodyPropRightHand[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropLeftWrist")) {
let bodyPropLeftWrist = getEntityData(civilian, "vrr.bodyPropLeftWrist");
civilian.changeBodyProp(1, bodyPropLeftWrist[0], bodyPropLeftWrist[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropLeftWrist")) {
let bodyPropLeftWrist = getEntityData(civilian, "vrr.bodyPropLeftWrist");
civilian.changeBodyProp(1, bodyPropLeftWrist[0], bodyPropLeftWrist[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropRightWrist")) {
let bodyPropRightWrist = getEntityData(civilian, "vrr.bodyPropRightWrist");
civilian.changeBodyProp(1, bodyPropRightWrist[0], bodyPropRightWrist[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropRightWrist")) {
let bodyPropRightWrist = getEntityData(civilian, "vrr.bodyPropRightWrist");
civilian.changeBodyProp(1, bodyPropRightWrist[0], bodyPropRightWrist[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropRightWrist")) {
let bodyPropRightWrist = getEntityData(civilian, "vrr.bodyPropRightWrist");
civilian.changeBodyProp(1, bodyPropRightWrist[0], bodyPropRightWrist[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropRightWrist")) {
let bodyPropRightWrist = getEntityData(civilian, "vrr.bodyPropRightWrist");
civilian.changeBodyProp(1, bodyPropRightWrist[0], bodyPropRightWrist[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropHip")) {
let bodyPropHip = getEntityData(civilian, "vrr.bodyPropHip");
civilian.changeBodyProp(1, bodyPropHip[0], bodyPropHip[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropHip")) {
let bodyPropHip = getEntityData(civilian, "vrr.bodyPropHip");
civilian.changeBodyProp(1, bodyPropHip[0], bodyPropHip[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropLeftFoot")) {
let bodyPropLeftFoot = getEntityData(civilian, "vrr.bodyPropLeftFoot");
civilian.changeBodyProp(1, bodyPropLeftFoot[0], bodyPropLeftFoot[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropLeftFoot")) {
let bodyPropLeftFoot = getEntityData(civilian, "vrr.bodyPropLeftFoot");
civilian.changeBodyProp(1, bodyPropLeftFoot[0], bodyPropLeftFoot[1]);
}
if(doesEntityDataExist(civilian, "vrr.bodyPropRightFoot")) {
let bodyPropRightFoot = getEntityData(civilian, "vrr.bodyPropRightFoot");
civilian.changeBodyProp(1, bodyPropRightFoot[0], bodyPropRightFoot[1]);
}
}
if(doesEntityDataExist(civilian, "vrr.bodyPropRightFoot")) {
let bodyPropRightFoot = getEntityData(civilian, "vrr.bodyPropRightFoot");
civilian.changeBodyProp(1, bodyPropRightFoot[0], bodyPropRightFoot[1]);
}
}
if(doesEntityDataExist(civilian, "vrr.anim")) {
let animData = getEntityData(vehicle, "vrr.anim");
civilian.addAnimation(animData[0], animData[1]);
}
if(doesEntityDataExist(civilian, "vrr.anim")) {
let animationSlot = getEntityData(civilian, "vrr.anim");
let animationData = getAnimationData(animationSlot);
civilian.addAnimation(animationData.groupId, animationData.animId);
}
}
// ===========================================================================
function syncPlayerProperties(player) {
if(!areServerElementsSupported()) {
return false;
}
if(!areServerElementsSupported()) {
return false;
}
if(getGame() == VRR_GAME_GTA_III) {
if(doesEntityDataExist(player, "vrr.scale")) {
let scaleFactor = getEntityData(player, "vrr.scale");
let tempMatrix = player.matrix;
tempMatrix.setScale(toVector3(scaleFactor.x, scaleFactor.y, scaleFactor.z));
let tempPosition = player.position;
player.matrix = tempMatrix;
tempPosition.z += scaleFactor.z;
player.position = tempPosition;
}
}
if(getGame() == VRR_GAME_GTA_III) {
if(doesEntityDataExist(player, "vrr.scale")) {
let scaleFactor = getEntityData(player, "vrr.scale");
let tempMatrix = player.matrix;
tempMatrix.setScale(toVector3(scaleFactor.x, scaleFactor.y, scaleFactor.z));
let tempPosition = player.position;
player.matrix = tempMatrix;
tempPosition.z += scaleFactor.z;
player.position = tempPosition;
}
}
if(getGame() == VRR_GAME_GTA_SA) {
if(doesEntityDataExist(player, "vrr.fightStyle")) {
let fightStyle = getEntityData(player, "vrr.fightStyle");
player.setFightStyle(fightStyle[0], fightStyle[1]);
}
}
if(getGame() == VRR_GAME_GTA_SA) {
if(doesEntityDataExist(player, "vrr.fightStyle")) {
let fightStyle = getEntityData(player, "vrr.fightStyle");
player.setFightStyle(fightStyle[0], fightStyle[1]);
}
}
//if(getGame() == VRR_GAME_GTA_SA) {
// if(doesEntityDataExist(player, "vrr.walkStyle")) {
// let walkStyle = getEntityData(player, "vrr.walkStyle");
// player.walkStyle = walkStyle;
// }
//}
//if(getGame() == VRR_GAME_GTA_SA) {
// if(doesEntityDataExist(player, "vrr.walkStyle")) {
// let walkStyle = getEntityData(player, "vrr.walkStyle");
// player.walkStyle = walkStyle;
// }
//}
if(getGame() == VRR_GAME_GTA_IV) {
if(doesEntityDataExist(player, "vrr.bodyPartHair")) {
let bodyPartHead = getEntityData(player, "vrr.bodyPartHair");
player.changeBodyPart(0, bodyPartHead[0], bodyPartHair[1]);
}
if(getGame() == VRR_GAME_GTA_IV) {
if(doesEntityDataExist(player, "vrr.bodyPartHair")) {
let bodyPartHead = getEntityData(player, "vrr.bodyPartHair");
player.changeBodyPart(0, bodyPartHead[0], bodyPartHair[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPartHead")) {
let bodyPartHead = getEntityData(player, "vrr.bodyPartHead");
player.changeBodyPart(1, bodyPartHead[0], bodyPartHead[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPartHead")) {
let bodyPartHead = getEntityData(player, "vrr.bodyPartHead");
player.changeBodyPart(1, bodyPartHead[0], bodyPartHead[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPartUpper")) {
let bodyPartUpper = getEntityData(player, "vrr.bodyPartUpper");
player.changeBodyPart(1, bodyPartUpper[0], bodyPartUpper[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPartUpper")) {
let bodyPartUpper = getEntityData(player, "vrr.bodyPartUpper");
player.changeBodyPart(1, bodyPartUpper[0], bodyPartUpper[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPartLower")) {
let bodyPartLower = getEntityData(player, "vrr.bodyPartLower");
player.changeBodyPart(1, bodyPartLower[0], bodyPartLower[1]);
}
}
if(doesEntityDataExist(player, "vrr.bodyPartLower")) {
let bodyPartLower = getEntityData(player, "vrr.bodyPartLower");
player.changeBodyPart(1, bodyPartLower[0], bodyPartLower[1]);
}
}
if(getGame() == VRR_GAME_GTA_IV) {
if(doesEntityDataExist(player, "vrr.bodyPropHair")) {
let bodyPropHair = getEntityData(player, "vrr.bodyPropHair");
player.changeBodyProp(0, bodyPropHair[0], bodyPropHair[1]);
}
if(getGame() == VRR_GAME_GTA_IV) {
if(doesEntityDataExist(player, "vrr.bodyPropHair")) {
let bodyPropHair = getEntityData(player, "vrr.bodyPropHair");
player.changeBodyProp(0, bodyPropHair[0], bodyPropHair[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropHead")) {
let bodyPropHead = getEntityData(player, "vrr.bodyPropHead");
player.changeBodyProp(1, bodyPropHead[0], bodyPropHead[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropHead")) {
let bodyPropHead = getEntityData(player, "vrr.bodyPropHead");
player.changeBodyProp(1, bodyPropHead[0], bodyPropHead[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropEyes")) {
let bodyPropEyes = getEntityData(player, "vrr.bodyPropEyes");
player.changeBodyProp(1, bodyPropEyes[0], bodyPropEyes[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropEyes")) {
let bodyPropEyes = getEntityData(player, "vrr.bodyPropEyes");
player.changeBodyProp(1, bodyPropEyes[0], bodyPropEyes[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropLeftHand")) {
let bodyPropLeftHand = getEntityData(player, "vrr.bodyPropLeftHand");
player.changeBodyProp(1, bodyPropLeftHand[0], bodyPropLeftHand[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropLeftHand")) {
let bodyPropLeftHand = getEntityData(player, "vrr.bodyPropLeftHand");
player.changeBodyProp(1, bodyPropLeftHand[0], bodyPropLeftHand[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropRightHand")) {
let bodyPropRightHand = getEntityData(player, "vrr.bodyPropRightHand");
player.changeBodyProp(1, bodyPropRightHand[0], bodyPropRightHand[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropRightHand")) {
let bodyPropRightHand = getEntityData(player, "vrr.bodyPropRightHand");
player.changeBodyProp(1, bodyPropRightHand[0], bodyPropRightHand[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropLeftWrist")) {
let bodyPropLeftWrist = getEntityData(player, "vrr.bodyPropLeftWrist");
player.changeBodyProp(1, bodyPropLeftWrist[0], bodyPropLeftWrist[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropLeftWrist")) {
let bodyPropLeftWrist = getEntityData(player, "vrr.bodyPropLeftWrist");
player.changeBodyProp(1, bodyPropLeftWrist[0], bodyPropLeftWrist[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropRightWrist")) {
let bodyPropRightWrist = getEntityData(player, "vrr.bodyPropRightWrist");
player.changeBodyProp(1, bodyPropRightWrist[0], bodyPropRightWrist[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropRightWrist")) {
let bodyPropRightWrist = getEntityData(player, "vrr.bodyPropRightWrist");
player.changeBodyProp(1, bodyPropRightWrist[0], bodyPropRightWrist[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropRightWrist")) {
let bodyPropRightWrist = getEntityData(player, "vrr.bodyPropRightWrist");
player.changeBodyProp(1, bodyPropRightWrist[0], bodyPropRightWrist[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropRightWrist")) {
let bodyPropRightWrist = getEntityData(player, "vrr.bodyPropRightWrist");
player.changeBodyProp(1, bodyPropRightWrist[0], bodyPropRightWrist[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropHip")) {
let bodyPropHip = getEntityData(player, "vrr.bodyPropHip");
player.changeBodyProp(1, bodyPropHip[0], bodyPropHip[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropHip")) {
let bodyPropHip = getEntityData(player, "vrr.bodyPropHip");
player.changeBodyProp(1, bodyPropHip[0], bodyPropHip[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropLeftFoot")) {
let bodyPropLeftFoot = getEntityData(player, "vrr.bodyPropLeftFoot");
player.changeBodyProp(1, bodyPropLeftFoot[0], bodyPropLeftFoot[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropLeftFoot")) {
let bodyPropLeftFoot = getEntityData(player, "vrr.bodyPropLeftFoot");
player.changeBodyProp(1, bodyPropLeftFoot[0], bodyPropLeftFoot[1]);
}
if(doesEntityDataExist(player, "vrr.bodyPropRightFoot")) {
let bodyPropRightFoot = getEntityData(player, "vrr.bodyPropRightFoot");
player.changeBodyProp(1, bodyPropRightFoot[0], bodyPropRightFoot[1]);
}
}
}
// ===========================================================================
function syncObjectProperties(object) {
if(!areServerElementsSupported()) {
return false;
}
if(getGame() == VRR_GAME_GTA_III || getGame() == VRR_GAME_GTA_VC) {
if(doesEntityDataExist(object, "vrr.scale")) {
let scaleFactor = getEntityData(object, "vrr.scale");
let tempMatrix = object.matrix;
tempMatrix.setScale(toVector3(scaleFactor.x, scaleFactor.y, scaleFactor.z));
let tempPosition = object.position;
object.matrix = tempMatrix;
tempPosition.z += scaleFactor.z;
object.position = tempPosition;
}
}
if(doesEntityDataExist(player, "vrr.bodyPropRightFoot")) {
let bodyPropRightFoot = getEntityData(player, "vrr.bodyPropRightFoot");
player.changeBodyProp(1, bodyPropRightFoot[0], bodyPropRightFoot[1]);
}
}
}
// ===========================================================================
function syncElementProperties(element) {
if(!areServerElementsSupported()) {
return false;
}
if(!areServerElementsSupported()) {
return false;
}
if(doesEntityDataExist(element, "vrr.interior")) {
if(typeof element.interior != "undefined") {
element.interior = getEntityData(element, "vrr.interior");
}
}
if(doesEntityDataExist(element, "vrr.interior")) {
if(typeof element.interior != "undefined") {
element.interior = getEntityData(element, "vrr.interior");
}
}
switch(element.type) {
case ELEMENT_VEHICLE:
syncVehicleProperties(element);
break;
if(getGame() == VRR_GAME_MAFIA_ONE) {
switch(element.type) {
case ELEMENT_VEHICLE:
syncVehicleProperties(element);
break;
case ELEMENT_PED:
syncCivilianProperties(element);
break;
case ELEMENT_PED:
syncCivilianProperties(element);
break;
case ELEMENT_PLAYER:
syncPlayerProperties(element);
break;
case ELEMENT_PLAYER:
syncPlayerProperties(element);
break;
case ELEMENT_OBJECT:
syncObjectProperties(element);
break;
default:
break;
}
} else {
switch(element.type) {
case ELEMENT_VEHICLE:
syncVehicleProperties(element);
break;
case ELEMENT_PED:
syncCivilianProperties(element);
break;
case ELEMENT_PLAYER:
syncPlayerProperties(element);
break;
default:
break;
}
}
default:
break;
}
}
// ===========================================================================
function receiveHouseFromServer(houseId, entrancePosition, blipModel, pickupModel, hasInterior) {
if(getGame() == VRR_GAME_GTA_IV) {
}
if(getGame() == VRR_GAME_GTA_IV) {
}
}
// ===========================================================================
function setLocalPlayerPedPartsAndProps(parts, props) {
for(let i in parts) {
localPlayer.changeBodyPart(parts[i][0], parts[i][1], parts[i][2]);
}
for(let i in parts) {
localPlayer.changeBodyPart(parts[i][0], parts[i][1], parts[i][2]);
}
for(let j in props) {
localPlayer.changeBodyProp(props[j][0], props[j][1]);
}
for(let j in props) {
localPlayer.changeBodyProp(props[j][0], props[j][1]);
}
}
// ===========================================================================

File diff suppressed because it is too large Load Diff

131
scripts/client/vehicle.js Normal file
View File

@@ -0,0 +1,131 @@
// ===========================================================================
// Vortrex's Roleplay Resource
// https://github.com/VortrexFTW/gtac_roleplay
// ===========================================================================
// FILE: vehicle.js
// DESC: Provides vehicle functions and arrays with data
// TYPE: Client (JavaScript)
// ===========================================================================
class VehicleData {
constructor(vehicleId, model, position, heading, colour1, colour2, colour3, colour4, locked, lights, engine, licensePlate) {
this.index = -1;
this.vehicleId = vehicleId;
this.model = model;
this.position = position;
this.heading = heading;
this.colour1 = colour1;
this.colour2 = colour2;
this.colour3 = colour3;
this.colour4 = colour4;
this.pickupModel = pickupModel;
this.locked = locked;
this.lights = lights;
this.engine = engine;
this.licensePlate = licensePlate;
this.ivNetworkId = -1;
}
}
// ===========================================================================
function receiveVehicleFromServer(vehicleId, position, model, colour1, colour2, colour3 = 0, colour4 = 0, locked = false, lights = false, engine = false, licensePlate = "") {
logToConsole(LOG_DEBUG, `[VRR.Vehicle] Received vehicle ${vehicleId} (${getVehicleNameFromModel(model, getGame())}) from server`);
if(getGame() != VRR_GAME_GTA_IV) {
return false;
}
if(getVehicleData(vehicleId) != false) {
let vehicleData = getVehicleData(vehicleId);
//vehicleData.position = position;
//vehicleData.heading = heading;
//vehicleData.model
vehicleData.colour1 = colour1;
vehicleData.colour2 = colour2;
vehicleData.colour3 = colour3;
vehicleData.colour4 = colour4;
vehicleData.engine = engine;
vehicleData.lights = lights;
vehicleData.locked = locked;
vehicleData.licensePlate = "";
let vehicle = natives.getVehicleFromNetworkId(vehicleId.ivNetworkId);
} else {
//logToConsole(LOG_DEBUG, `[VRR.Vehicle] Vehicle ${vehicleId} doesn't exist. Adding ...`);
//let tempVehicleData = new VehicleData(vehicleId, name, position, blipModel, pickupModel);
//vehicles.push(tempVehicleData);
//setAllJobDataIndexes();
}
}
// ===========================================================================
function processVehiclePurchasing() {
if(vehiclePurchaseState == VRR_VEHBUYSTATE_TESTDRIVE) {
if(getLocalPlayerVehicle() == false) {
vehiclePurchaseState = VRR_VEHBUYSTATE_EXITVEH;
sendNetworkEventToServer("vrr.vehBuyState", VRR_VEHBUYSTATE_EXITVEH);
return false;
} else {
if(vehiclePurchasing == getLocalPlayerVehicle()) {
if(getDistance(getLocalPlayerVehicle().position, vehiclePurchasePosition) >= 25) {
vehiclePurchaseState = VRR_VEHBUYSTATE_FARENOUGH;
sendNetworkEventToServer("vrr.vehBuyState", VRR_VEHBUYSTATE_FARENOUGH);
}
} else {
vehiclePurchaseState = VRR_VEHBUYSTATE_WRONGVEH;
sendNetworkEventToServer("vrr.vehBuyState", VRR_VEHBUYSTATE_WRONGVEH);
}
}
}
}
// ===========================================================================
function processVehicleBurning() {
getElementsByType(ELEMENT_VEHICLE).filter(vehicle => vehicle.isSyncer && vehicle.health < 250).forEach((vehicle) => {
vehicle.health = 250;
});
}
// ===========================================================================
function setVehiclePurchaseState(state, vehicleId, position) {
vehiclePurchaseState = state;
if(vehicleId != null) {
vehiclePurchasing = getElementFromId(vehicleId);
} else {
vehiclePurchasing = null;
}
vehiclePurchasePosition = position;
}
// ===========================================================================
/**
* @param {number} vehicleId - The ID of the job (initially provided by server)
* @return {VehicleData} The vehicle's data (class instance)
*/
function getVehicleData(vehicleId) {
for(let i in getServerData().vehicles) {
if(getServerData().vehicles[i].vehicleId == vehicleId) {
return getServerData().vehicles[i];
}
}
return false;
}
// ===========================================================================
function setAllVehicleDataIndexes() {
for(let i in getServerData().vehicles) {
getServerData().vehicles[i].index = i;
}
}
// ===========================================================================

View File

@@ -8,30 +8,30 @@
// ===========================================================================
function getPlayerAccentText(client) {
return getPlayerCurrentSubAccount(client).accent;
return getPlayerCurrentSubAccount(client).accent;
}
// ===========================================================================
function setPlayerAccentText(client, text) {
getPlayerCurrentSubAccount(client).accent = text;
getPlayerCurrentSubAccount(client).accent = text;
}
// ===========================================================================
function doesPlayerHaveAccent(client) {
return (getPlayerCurrentSubAccount(client).accent != "");
return (getPlayerCurrentSubAccount(client).accent != "");
}
// ===========================================================================
function getPlayerAccentInlineOutput(client) {
let outputText = "";
if(doesPlayerHaveAccent(client)) {
outputText = `[${getPlayerAccentText(client)}] `;
}
let outputText = "";
if(doesPlayerHaveAccent(client)) {
outputText = `[${getPlayerAccentText(client)}] `;
}
return outputText;
return outputText;
}
// ===========================================================================
@@ -63,7 +63,7 @@ function listAccentsCommand(command, params, client) {
let chunkedList = splitArrayIntoChunks(accentList, 8);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "AccentList")));
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "AccentsListHeader")));
for(let i in chunkedList) {
messagePlayerInfo(client, chunkedList[i].join(", "));
}
@@ -91,7 +91,7 @@ function getAccentFromParams(params) {
function reloadAccentConfigurationCommand(command, params, client) {
getGlobalConfig().accents = loadAccentConfig();
messageAdmins(`${client.name} {MAINCOLOUR}has reloaded the accent list`);
messageAdmins(`{adminOrange}${getPlayerName(client)} {MAINCOLOUR}has reloaded the accent list`);
}
// ===========================================================================
@@ -111,7 +111,7 @@ function addAccentCommand(command, params, client) {
getGlobalConfig().accents.push(newAccentName);
saveAccentConfig();
messageAdmins(`${client.name}{MAINCOLOUR} added a new accent: ${newAccentName}`);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} added a new accent: {ALTCOLOUR}${newAccentName}{MAINCOLOUR}`);
}
// ===========================================================================
@@ -131,7 +131,7 @@ function removeAccentCommand(command, params, client) {
getGlobalConfig().accents.push(newAccentName);
saveAccentConfig();
messageAdmins(`${client.name}{MAINCOLOUR} added a new accent: ${newAccentName}`);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} removed an accent: {ALTCOLOUR}${newAccentName}{MAINCOLOUR}`);
}
// ===========================================================================

File diff suppressed because it is too large Load Diff

View File

@@ -20,17 +20,17 @@ function playPlayerAnimationCommand(command, params, client) {
return false;
}
let animationSlot = getAnimationFromParams(getParam(params, " ", 1));
let animationPositionOffset = 1;
let animationSlot = getAnimationFromParams(getParam(params, " ", 1));
let animationPositionOffset = 1;
if(!animationSlot) {
messagePlayerError(client, getLocaleString(client, "AnimationNotFound"));
messagePlayerInfo(client, getLocaleString(client, "AnimationHelpTip"), `{ALTCOLOUR}/animlist{MAINCOLOUR}`);
messagePlayerError(client, getLocaleString(client, "InvalidAnimation"));
messagePlayerInfo(client, getLocaleString(client, "AnimationCommandTip", `{ALTCOLOUR}/animlist{MAINCOLOUR}`));
return false;
}
if(toInteger(animationPositionOffset) < 0 || toInteger(animationPositionOffset) > 3) {
messagePlayerError(client, getLocaleString(client, "AnimationInvalidDistance"));
messagePlayerError(client, getLocaleString(client, "InvalidAnimationDistance"));
return false;
}
@@ -39,7 +39,7 @@ let animationSlot = getAnimationFromParams(getParam(params, " ", 1));
}
if(isPlayerHandCuffed(client) || isPlayerTazed(client) || isPlayerInForcedAnimation(client)) {
messagePlayerError(client, `You aren't able to do that`);
messagePlayerError(client, getLocaleString(client, "UnableToDoThat"));
return false;
}
@@ -51,26 +51,26 @@ let animationSlot = getAnimationFromParams(getParam(params, " ", 1));
function stopPlayerAnimationCommand(command, params, client) {
if(isPlayerHandCuffed(client) || isPlayerTazed(client) || isPlayerInForcedAnimation(client)) {
messagePlayerError(client, `You aren't able to do that`);
messagePlayerError(client, getLocaleString(client, "UnableToDoThat"));
return false;
}
setPlayerPosition(client, getPlayerData(client).currentAnimationPositionReturnTo);
makePedStopAnimation(getPlayerData(client).ped);
makePedStopAnimation(getPlayerPed(client));
getPlayerData(client).currentAnimation = -1;
getPlayerData(client).currentAnimationPositionOffset = false;
getPlayerData(client).currentAnimationPositionReturnTo = false;
getPlayerData(client).animationStart = 0;
getPlayerData(client).animationStart = 0;
getPlayerData(client).animationForced = false;
setPlayerMouseCameraState(client, false);
//setPlayerMouseCameraState(client, false);
}
// ===========================================================================
function showAnimationListCommand(command, params, client) {
let animList = getGameConfig().animations[getServerGame()].map(function(x) { return x[0]; });
let animList = getGameConfig().animations[getGame()].map(function(x) { return x.name; });
let chunkedList = splitArrayIntoChunks(animList, 10);
@@ -87,8 +87,8 @@ function showAnimationListCommand(command, params, client) {
* @param {number} animationSlot - The slot index of the animation
* @return {Array} The animation's data (array)
*/
function getAnimationData(animationSlot, gameId = getServerGame()) {
return getGameConfig().animations[gameId][animationSlot];
function getAnimationData(animationSlot, gameId = getGame()) {
return getGameConfig().animations[gameId][animationSlot];
}
// ===========================================================================
@@ -100,14 +100,14 @@ function isPlayerInForcedAnimation(client) {
// ===========================================================================
function makePlayerPlayAnimation(client, animationSlot, offsetPosition = 1) {
getPlayerData(client).currentAnimation = animationSlot;
getPlayerData(client).currentAnimation = animationSlot;
getPlayerData(client).currentAnimationPositionOffset = offsetPosition;
getPlayerData(client).currentAnimationPositionReturnTo = getPlayerPosition(client);
getPlayerData(client).animationStart = getCurrentUnixTimestamp();
getPlayerData(client).animationStart = getCurrentUnixTimestamp();
getPlayerData(client).animationForced = false;
makePedPlayAnimation(getPlayerData(client).ped, animationSlot, offsetPosition);
makePedPlayAnimation(getPlayerPed(client), animationSlot, offsetPosition);
setEntityData(getPlayerPed(client), "vrr.anim", animationSlot, true);
//if(getAnimationData(animationSlot)[9] != VRR_ANIMMOVE_NONE) {
// if(getGame() < VRR_GAME_GTA_SA) {
// setPlayerMouseCameraState(client, true);
@@ -118,40 +118,41 @@ function makePlayerPlayAnimation(client, animationSlot, offsetPosition = 1) {
// ===========================================================================
function forcePlayerPlayAnimation(client, animationSlot, offsetPosition = 1) {
getPlayerData(client).currentAnimation = animationSlot;
getPlayerData(client).currentAnimation = animationSlot;
getPlayerData(client).currentAnimationPositionOffset = offsetPosition;
getPlayerData(client).currentAnimationPositionReturnTo = getPlayerPosition(client);
getPlayerData(client).animationStart = getCurrentUnixTimestamp();
getPlayerData(client).animationStart = getCurrentUnixTimestamp();
getPlayerData(client).animationForced = true;
setPlayerControlState(client, false);
forcePedAnimation(getPlayerData(client).ped, animationSlot, offsetPosition);
forcePedAnimation(getPlayerPed(client), animationSlot, offsetPosition);
}
// ===========================================================================
function makePlayerStopAnimation(client) {
//setPlayerPosition(client, getPlayerData(client).currentAnimationPositionReturnTo);
makePedStopAnimation(getPlayerData(client).ped);
makePedStopAnimation(getPlayerPed(client));
getPlayerData(client).currentAnimation = -1;
getPlayerData(client).currentAnimationPositionOffset = false;
getPlayerData(client).currentAnimationPositionReturnTo = false;
getPlayerData(client).animationStart = 0;
getPlayerData(client).animationStart = 0;
getPlayerData(client).animationForced = false;
}
// ===========================================================================
function getAnimationFromParams(params) {
let animations = getGameConfig().animations[getGame()];
if(isNaN(params)) {
for(let i in getGameConfig().animations[getServerGame()]) {
if(toLowerCase(getGameConfig().animations[getServerGame()][i][0]).indexOf(toLowerCase(params)) != -1) {
for(let i in animations) {
if(toLowerCase(animations[i].name).indexOf(toLowerCase(params)) != -1) {
return i;
}
}
} else {
if(typeof getGameConfig().animations[getServerGame()][params] != "undefined") {
if(typeof getGameConfig().animations[getGame()][params] != "undefined") {
return toInteger(params);
}
}

View File

@@ -8,14 +8,14 @@
// ===========================================================================
function initAntiCheatScript() {
logToConsole(LOG_DEBUG, "[VRR.AntiCheat]: Initializing anticheat script ...");
logToConsole(LOG_DEBUG, "[VRR.AntiCheat]: Initializing anticheat script ...");
logToConsole(LOG_DEBUG, "[VRR.AntiCheat]: Anticheat script initialized!");
}
// ===========================================================================
function clearPlayerStateToEnterExitProperty(client) {
if(getPlayerData(client).pedState != VRR_PEDSTATE_READY) {
if(getPlayerData(client).pedState != VRR_PEDSTATE_READY) {
if(getPlayerData(client).pedState == VRR_PEDSTATE_ENTERINGVEHICLE) {
sendPlayerClearPedState(client);
getPlayerData(client).pedState = VRR_PEDSTATE_READY;

View File

@@ -25,7 +25,7 @@ class BanData {
this.name = "";
this.reason = "";
if(dbAssoc) {
if (dbAssoc) {
this.databaseId = toInteger(dbAssoc["ban_id"]);
this.type = dbAssoc["ban_type"];
this.detail = toInteger(dbAssoc["ban_detail"]);
@@ -38,291 +38,283 @@ class BanData {
// ===========================================================================
function initBanScript() {
logToConsole(LOG_INFO, "[VRR.Ban]: Initializing ban script ...");
logToConsole(LOG_INFO, "[VRR.Ban]: Ban script initialized!");
logToConsole(LOG_INFO, "[VRR.Ban]: Initializing ban script ...");
logToConsole(LOG_INFO, "[VRR.Ban]: Ban script initialized!");
}
// ===========================================================================
function accountBanCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let reason = splitParams.slice(1).join(" ");
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let reason = splitParams.slice(1).join(" ");
if(!targetClient) {
messagePlayerError(client, "That player is not connected!")
return false;
}
// Prevent banning admins with really high permissions
if(doesPlayerHaveStaffPermission(targetClient, "ManageServer") || doesPlayerHaveStaffPermission(targetClient, "Developer")) {
messagePlayerError(client, getLocaleString(client, "CantBanPlayer"));
return false;
if (!targetClient) {
messagePlayerError(client, "That player is not connected!")
return false;
}
logToConsole(LOG_WARN, `[VRR.Ban]: ${getPlayerDisplayForConsole(targetClient)} (${getPlayerData(targetClient).accountData.name}) account was banned by ${getPlayerDisplayForConsole(client)}. Reason: ${reason}`);
// Prevent banning admins with really high permissions
if (doesPlayerHaveStaffPermission(targetClient, "ManageServer") || doesPlayerHaveStaffPermission(targetClient, "Developer")) {
messagePlayerError(client, getLocaleString(client, "CantBanPlayer"));
return false;
}
messageAdminAction(`{ALTCOLOUR}${getPlayerData(targetClient).currentSubAccountData.name} {MAINCOLOUR}has been account banned.`);
logToConsole(LOG_WARN, `[VRR.Ban]: ${getPlayerDisplayForConsole(targetClient)} (${getPlayerData(targetClient).accountData.name}) account was banned by ${getPlayerDisplayForConsole(client)}. Reason: ${reason}`);
announceAdminAction(`PlayerAccountBanned`, `{ALTCOLOUR}${getPlayerName(targetClient)}{MAINCOLOUR}`);
banAccount(getPlayerData(targetClient).accountData.databaseId, getPlayerData(client).accountData.databaseId, reason);
disconnectPlayer(client);
getPlayerData(targetClient).customDisconnectReason = `Banned - ${reason}`;
disconnectPlayer(targetClient);
}
// ===========================================================================
function subAccountBanCommand(command, params, client, fromDiscord) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let reason = splitParams.slice(1).join(" ");
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let reason = splitParams.slice(1).join(" ");
if(!targetClient) {
messagePlayerError(client, "That player is not connected!")
return false;
}
if (!targetClient) {
messagePlayerError(client, "That player is not connected!")
return false;
}
// Prevent banning admins with really high permissions
if(doesPlayerHaveStaffPermission(targetClient, "ManageServer") || doesPlayerHaveStaffPermission(targetClient, "Developer")) {
if (doesPlayerHaveStaffPermission(targetClient, "ManageServer") || doesPlayerHaveStaffPermission(targetClient, "Developer")) {
messagePlayerError(client, getLocaleString(client, "CantBanPlayer"));
return false;
}
}
logToConsole(LOG_WARN, `[VRR.Ban]: ${getPlayerDisplayForConsole(targetClient)} (${getPlayerData(targetClient).accountData.name})'s subaccount was banned by ${getPlayerDisplayForConsole(client)}. Reason: ${reason}`);
logToConsole(LOG_WARN, `[VRR.Ban]: ${getPlayerDisplayForConsole(targetClient)} (${getPlayerData(targetClient).accountData.name})'s subaccount was banned by ${getPlayerDisplayForConsole(client)}. Reason: ${reason}`);
messageAdminAction(`{ALTCOLOUR}${getPlayerData(targetClient).currentSubAccountData.name} {MAINCOLOUR}has been character banned.`);
banSubAccount(getPlayerData(targetClient).currentSubAccountData.databaseId, getPlayerData(client).accountData.databaseId, reason);
announceAdminAction(`PlayerCharacterBanned`, `{ALTCOLOUR}${getPlayerName(targetClient)}{MAINCOLOUR}`);
banSubAccount(getPlayerData(targetClient).currentSubAccountData.databaseId, getPlayerData(client).accountData.databaseId, reason);
disconnectPlayer(client);
getPlayerData(targetClient).customDisconnectReason = `Banned - ${reason}`;
disconnectPlayer(targetClient);
}
// ===========================================================================
function ipBanCommand(command, params, client, fromDiscord) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
}
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let reason = splitParams.slice(1).join(" ");
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let reason = splitParams.slice(1).join(" ");
if(!targetClient) {
messagePlayerError(client, "That player is not connected!")
return false;
}
if (!targetClient) {
messagePlayerError(client, "That player is not connected!")
return false;
}
// Prevent banning admins with really high permissions
if(doesPlayerHaveStaffPermission(targetClient, "ManageServer") || doesPlayerHaveStaffPermission(targetClient, "Developer")) {
if (doesPlayerHaveStaffPermission(targetClient, "ManageServer") || doesPlayerHaveStaffPermission(targetClient, "Developer")) {
messagePlayerError(client, getLocaleString(client, "CantBanPlayer"));
return false;
}
}
messageAdminAction(`{ALTCOLOUR}${getPlayerData(targetClient).currentSubAccountData.name} {MAINCOLOUR}has been IP banned.`);
banIPAddress(targetClient.ip, getPlayerData(client).accountData.databaseId, reason);
announceAdminAction(`PlayerIPBanned`, `{ALTCOLOUR}${getPlayerName(targetClient)}{MAINCOLOUR}`);
banIPAddress(getPlayerIP(targetClient), getPlayerData(client).accountData.databaseId, reason);
server.banIP(targetClient.ip);
targetClient.disconnect();
getPlayerData(targetClient).customDisconnectReason = `IP Banned - ${reason}`;
serverBanIP(getPlayerIP(targetClient));
disconnectPlayer(targetClient);
}
// ===========================================================================
function subNetBanCommand(command, params, client, fromDiscord) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
}
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let octetAmount = Number(getParam(params, " ", 2));
let reason = splitParams.slice(2).join(" ");
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let octetAmount = Number(getParam(params, " ", 2));
let reason = splitParams.slice(2).join(" ");
if(!targetClient) {
messagePlayerError(client, "That player is not connected!")
return false;
}
if (!targetClient) {
messagePlayerError(client, "That player is not connected!")
return false;
}
// Prevent banning admins with really high permissions
if(doesPlayerHaveStaffPermission(targetClient, "ManageServer") || doesPlayerHaveStaffPermission(targetClient, "Developer")) {
if (doesPlayerHaveStaffPermission(targetClient, "ManageServer") || doesPlayerHaveStaffPermission(targetClient, "Developer")) {
messagePlayerError(client, getLocaleString(client, "CantBanPlayer"));
return false;
}
}
messageAdminAction(`{ALTCOLOUR}${getPlayerData(targetClient).currentSubAccountData.name} {MAINCOLOUR}has been subnet banned`);
banSubNet(targetClient.ip, getSubNet(targetClient.ip, octetAmount), getPlayerData(client).accountData.databaseId, reason);
announceAdminAction(`PlayerSubNetBanned`, `{ALTCOLOUR}${getPlayerName(client)}{MAINCOLOUR}`);
banSubNet(getPlayerIP(targetClient), getSubNet(getPlayerIP(targetClient), octetAmount), getPlayerData(client).accountData.databaseId, reason);
server.banIP(targetClient.ip);
getPlayerData(client).customDisconnectReason = `IP Subnet Banned - ${reason}`;
serverBanIP(getPlayerIP(targetClient));
}
// ===========================================================================
function banAccount(accountId, adminAccountId, reason) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let safeReason = dbConnection.escapetoString(reason);
let dbQuery = queryDatabase(dbConnection, `INSERT INTO ban_main (ban_type, ban_detail, ban_who_banned, ban_reason) VALUES (${VRR_BANTYPE_ACCOUNT}, ${accountId}, ${adminAccountId}, '${safeReason}');`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
let dbConnection = connectToDatabase();
if (dbConnection) {
let safeReason = dbConnection.escapetoString(reason);
let dbQuery = queryDatabase(dbConnection, `INSERT INTO ban_main (ban_type, ban_detail, ban_who_banned, ban_reason) VALUES (${VRR_BANTYPE_ACCOUNT}, ${accountId}, ${adminAccountId}, '${safeReason}');`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
return false;
return false;
}
// ===========================================================================
function banSubAccount(subAccountId, adminAccountId, reason) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let safeReason = dbConnection.escapetoString(reason);
let dbQuery = queryDatabase(dbConnection, `INSERT INTO ban_main (ban_type, ban_detail, ban_who_banned, ban_reason) VALUES (${VRR_BANTYPE_SUBACCOUNT}, ${subAccountId}, ${adminAccountId}, '${safeReason}');`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
let dbConnection = connectToDatabase();
if (dbConnection) {
let safeReason = dbConnection.escapetoString(reason);
let dbQuery = queryDatabase(dbConnection, `INSERT INTO ban_main (ban_type, ban_detail, ban_who_banned, ban_reason) VALUES (${VRR_BANTYPE_SUBACCOUNT}, ${subAccountId}, ${adminAccountId}, '${safeReason}');`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
return false;
return false;
}
// ===========================================================================
function banIPAddress(ipAddress, adminAccountId, reason) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let safeReason = dbConnection.escapetoString(reason);
let dbQuery = queryDatabase(dbConnection, `INSERT INTO ban_main (ban_type, ban_detail, ban_who_banned, ban_reason) VALUES (${VRR_BANTYPE_IPADDRESS}, INET_ATON(${ipAddress}), ${adminAccountId}, '${safeReason}');`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
let dbConnection = connectToDatabase();
if (dbConnection) {
let safeReason = dbConnection.escapetoString(reason);
let dbQuery = queryDatabase(dbConnection, `INSERT INTO ban_main (ban_type, ban_detail, ban_who_banned, ban_reason) VALUES (${VRR_BANTYPE_IPADDRESS}, INET_ATON(${ipAddress}), ${adminAccountId}, '${safeReason}');`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
return false;
return false;
}
// ===========================================================================
function banSubNet(ipAddressStart, ipAddressEnd, adminAccountId, reason) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let safeReason = dbConnection.escapetoString(reason);
let dbQuery = queryDatabase(dbConnection, `INSERT INTO ban_main (ban_type, ban_ip_start, ban_ip_end, ban_who_banned, ban_reason) VALUES (${VRR_BANTYPE_SUBNET}, INET_ATON(${ipAddressStart}), INET_ATON(${ipAddressEnd}), ${adminAccountId}, '${safeReason}');`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
let dbConnection = connectToDatabase();
if (dbConnection) {
let safeReason = dbConnection.escapetoString(reason);
let dbQuery = queryDatabase(dbConnection, `INSERT INTO ban_main (ban_type, ban_ip_start, ban_ip_end, ban_who_banned, ban_reason) VALUES (${VRR_BANTYPE_SUBNET}, INET_ATON(${ipAddressStart}), INET_ATON(${ipAddressEnd}), ${adminAccountId}, '${safeReason}');`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
return false;
return false;
}
// ===========================================================================
function unbanAccount(accountId, adminAccountId) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE ban_main SET ban_who_removed=${adminAccountId}, ban_removed=1 WHERE ban_type=${VRR_BANTYPE_ACCOUNT} AND ban_detail=${accountId}`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
let dbConnection = connectToDatabase();
if (dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE ban_main SET ban_who_removed=${adminAccountId}, ban_removed=1 WHERE ban_type=${VRR_BANTYPE_ACCOUNT} AND ban_detail=${accountId}`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
return false;
return false;
}
// ===========================================================================
function unbanSubAccount(subAccountId, adminAccountId) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE ban_main SET ban_who_removed=${adminAccountId}, ban_removed=1 WHERE ban_type=${VRR_BANTYPE_SUBACCOUNT} AND ban_detail=${subAccountId}`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
let dbConnection = connectToDatabase();
if (dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE ban_main SET ban_who_removed=${adminAccountId}, ban_removed=1 WHERE ban_type=${VRR_BANTYPE_SUBACCOUNT} AND ban_detail=${subAccountId}`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
return false;
return false;
}
// ===========================================================================
function unbanIPAddress(ipAddress, adminAccountId) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE ban_main SET ban_who_removed=${adminAccountId}, ban_removed=1 WHERE ban_type=${VRR_BANTYPE_IPADDRESS} AND ban_detail=INET_ATON(${ipAddress})`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
let dbConnection = connectToDatabase();
if (dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE ban_main SET ban_who_removed=${adminAccountId}, ban_removed=1 WHERE ban_type=${VRR_BANTYPE_IPADDRESS} AND ban_detail=INET_ATON(${ipAddress})`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
return false;
return false;
}
// ===========================================================================
function unbanSubNet(ipAddressStart, ipAddressEnd, adminAccountId) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE ban_main SET ban_who_removed=${adminAccountId}, ban_removed=1 WHERE ban_type=${VRR_BANTYPE_SUBNET} AND ban_ip_start=INET_ATON(${ipAddressStart}) AND ban_ip_end=INET_ATON(${ipAddressEnd})`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
let dbConnection = connectToDatabase();
if (dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE ban_main SET ban_who_removed=${adminAccountId}, ban_removed=1 WHERE ban_type=${VRR_BANTYPE_SUBNET} AND ban_ip_start=INET_ATON(${ipAddressStart}) AND ban_ip_end=INET_ATON(${ipAddressEnd})`);
freeDatabaseQuery(dbQuery);
dbConnection.close();
return true;
}
return false;
return false;
}
// ===========================================================================
function isAccountBanned(accountId) {
let bans = getServerData().bans;
for(let i in bans) {
if(bans[i].type == VRR_BANTYPE_ACCOUNT) {
if(bans[i].detail == accountId) {
return true;
}
}
}
let bans = getServerData().bans.filter(ban => ban.type === VRR_BANTYPE_ACCOUNT && ban.detail === accountId);
if (bans.length > 0) {
return true;
}
return false;
return false;
}
// ===========================================================================
function isSubAccountBanned(subAccountId) {
let bans = getServerData().bans;
for(let i in bans) {
if(bans[i].type == VRR_BANTYPE_SUBACCOUNT) {
if(bans[i].detail == subAccountId) {
return true;
}
}
}
let bans = getServerData().bans.filter(ban => ban.type === VRR_BANTYPE_SUBACCOUNT && ban.detail === subAccountId);
if (bans.length > 0) {
return true;
}
return false;
return false;
}
// ===========================================================================
function isIpAddressBanned(ipAddress) {
let bans = getServerData().bans;
for(let i in bans) {
if(bans[i].type == VRR_BANTYPE_IPADDRESS) {
if(bans[i].detail == ipAddress) {
return true;
}
}
}
let bans = getServerData().bans.filter(ban => ban.type === VRR_BANTYPE_IPADDRESS && ban.detail === ipAddress);
if (bans.length > 0) {
return true;
}
return false;
return false;
}
// ===========================================================================

View File

@@ -7,8 +7,6 @@
// TYPE: Server (JavaScript)
// ===========================================================================
// ===========================================================================
let serverBitFlags = {
staffFlags: {},
moderationFlags: {},
@@ -21,7 +19,6 @@ let serverBitFlags = {
npcTriggerTypeFlags: {},
npcTriggerConditionTypesFlags: {},
npcTriggerResponseTypeFlags: {},
serverSettings: {}
};
// ===========================================================================
@@ -41,6 +38,8 @@ let serverBitFlagKeys = {
"ManageWorld",
"ManageAntiCheat",
"Developer",
"ManageNPCs",
"ManageRaces",
],
moderationFlagKeys: [
"None",
@@ -119,6 +118,8 @@ let serverBitFlagKeys = {
"NoRandomTips",
"NoActionTips",
],
// Not going to be used. Use trigger, condition, and response stuff in trigger.js
npcTriggerTypeKeys: [
"None",
"FarProximity", // Comes within a far distance of NPC
@@ -219,26 +220,6 @@ let serverBitFlagKeys = {
"ShowItemsAfterPurchase",
"BuyCommandAfterEnterBusiness",
],
serverSettingsKeys: [
"None",
"GUI",
"ServerLogo",
"FallingSnow",
"GroundSnow",
"Anticheat",
"CheckGameScripts",
"GameScriptBlackList",
"GameScriptWhiteList",
"JobBlips",
"JobPickups",
"BusinessBlips",
"BusinessPickups",
"HouseBlips",
"HousePickups",
"DiscordBot",
"RealTime",
"Testing",
],
};
// ===========================================================================
@@ -255,47 +236,12 @@ function initBitFlagScript() {
serverBitFlags.npcTriggerTypes = createBitFlagTable(serverBitFlagKeys.npcTriggerTypeKeys);
serverBitFlags.npcTriggerConditionTypes = createBitFlagTable(serverBitFlagKeys.npcTriggerConditionTypeKeys);
serverBitFlags.npcTriggerResponseTypes = createBitFlagTable(serverBitFlagKeys.npcTriggerResponseTypeKeys);
serverBitFlags.serverSettings = createBitFlagTable(serverBitFlagKeys.serverSettingsKeys);
logToConsole(LOG_INFO, "[VRR.BitFlag]: Bit flag script initialized successfully!");
return true;
}
// ===========================================================================
function createBitFlagTable(keyNames) {
let bitVal = 0;
let bitTable = {};
let incVal = 1;
for(let i in keyNames) {
let key = keyNames[i];
bitTable[key] = bitVal;
bitVal = 1 << incVal;
incVal++;
}
return bitTable;
}
// ===========================================================================
function hasBitFlag(allFlags, checkForFlag) {
if(allFlags == 0) {
return false;
}
if(allFlags == -1) {
return true;
}
if((allFlags & checkForFlag) == checkForFlag) {
return true;
}
return false;
}
// ===========================================================================
function doesPlayerHaveStaffPermission(client, requiredFlags) {
if(isConsole(client)) {
return true;
@@ -311,15 +257,15 @@ function doesPlayerHaveStaffPermission(client, requiredFlags) {
}
// -1 is automatic override (having -1 for staff flags is basically god mode admin level)
if(staffFlags == getStaffFlagValue("All")) {
return true;
}
if(staffFlags == getStaffFlagValue("All")) {
return true;
}
if(hasBitFlag(staffFlags, requiredFlags)) {
return true;
}
if(hasBitFlag(staffFlags, requiredFlags)) {
return true;
}
return false;
return false;
}
// ===========================================================================
@@ -341,22 +287,22 @@ function doesPlayerHaveClanPermission(client, requiredFlags) {
clanFlags = getPlayerCurrentSubAccount(client).clanFlags | getClanRankFlags(getPlayerCurrentSubAccount(client).clanRank);
// -1 is automatic override (having -1 for staff flags is basically god mode admin level)
if(clanFlags == getClanFlagValue("All")) {
return true;
}
if(clanFlags == getClanFlagValue("All")) {
return true;
}
if(hasBitFlag(clanFlags, requiredFlags)) {
return true;
}
if(hasBitFlag(clanFlags, requiredFlags)) {
return true;
}
return false;
return false;
}
// ===========================================================================
function getStaffFlagValue(flagName) {
if(flagName == "All") {
return -1;
if(flagName == "All") {
return -1;
}
if(typeof serverBitFlags.staffFlags[flagName] == "undefined") {
@@ -369,8 +315,8 @@ function getStaffFlagValue(flagName) {
// ===========================================================================
function getClanFlagValue(flagName) {
if(flagName == "All") {
return -1;
if(flagName == "All") {
return -1;
}
if(typeof getServerBitFlags().clanFlags[flagName] == "undefined") {
@@ -383,8 +329,8 @@ function getClanFlagValue(flagName) {
// ===========================================================================
function getAccountSettingsFlagValue(flagName) {
if(flagName == "All") {
return -1;
if(flagName == "All") {
return -1;
}
if(typeof serverBitFlags.accountSettingsFlags[flagName] == "undefined") {
@@ -397,8 +343,8 @@ function getAccountSettingsFlagValue(flagName) {
// ===========================================================================
function getModerationFlagValue(flagName) {
if(flagName == "All") {
return -1;
if(flagName == "All") {
return -1;
}
if(typeof serverBitFlags.moderationFlags[flagName] == "undefined") {
@@ -410,20 +356,6 @@ function getModerationFlagValue(flagName) {
// ===========================================================================
function getServerSettingsFlagValue(flagName) {
if(flagName == "All") {
return -1;
}
if(typeof serverBitFlags.serverSettings[flagName] == "undefined") {
return false;
}
return serverBitFlags.serverSettings[flagName];
}
// ===========================================================================
function givePlayerStaffFlag(client, flagName) {
if(!getStaffFlagValue(flagName)) {
return false;
@@ -447,18 +379,6 @@ function takePlayerStaffFlag(client, flagName) {
// ===========================================================================
function addBitFlag(allFlags, flagValue) {
return allFlags | flagValue;
}
// ===========================================================================
function removeBitFlag(allFlags, flagValue) {
return allFlags ^ flagValue;
}
// ===========================================================================
function takePlayerStaffFlag(client, flagName) {
if(!getStaffFlagValue(flagName)) {
return false;
@@ -487,20 +407,4 @@ function getServerBitFlagKeys() {
return serverBitFlagKeys;
}
// ===========================================================================
function createBitwiseTable(tableKeys) {
let bitVal = 0;
let bitTable = {};
let incVal = 1;
for(let i in tableKeys) {
let key = tableKeys[i];
bitTable[key] = bitVal;
bitVal = 1 << incVal;
incVal++;
}
return bitTable;
}
// ===========================================================================

File diff suppressed because it is too large Load Diff

View File

@@ -16,30 +16,36 @@ function initChatScript() {
// ===========================================================================
function processPlayerChat(client, messageText) {
if(!getPlayerData(client)) {
messagePlayerError(client, "You need to login before you can chat!");
return false;
}
if(!isConsole(client)) {
if(!getPlayerData(client)) {
messagePlayerError(client, getLocaleString(client, "MustBeLoggedInAndSpawnedToChat"));
return false;
}
if(!isPlayerLoggedIn(client)) {
messagePlayerError(client, "You need to login before you can chat!");
return false;
}
if(!isPlayerLoggedIn(client)) {
messagePlayerError(client, getLocaleString(client, "MustBeLoggedInAndSpawnedToChat"));
return false;
}
if(!isPlayerSpawned(client)) {
messagePlayerError(client, "You need to spawn before you can chat!");
return false;
}
if(!isPlayerSpawned(client)) {
messagePlayerError(client, getLocaleString(client, "MustBeLoggedInAndSpawnedToChat"));
return false;
}
if(isPlayerMuted(client)) {
messagePlayerError(client, "You are muted and can't chat!");
return false;
}
if(isPlayerMuted(client)) {
messagePlayerError(client, getLocaleString(client, "MutedCantChat"));
return false;
}
messageText = messageText.substring(0, 128);
messageText = messageText.substring(0, 128);
messagePlayerNormal(null, `💬 ${getCharacterFullName(client)}: {MAINCOLOUR}${messageText}`, getPlayerColour(client));
messageDiscordChatChannel(`💬 ${getCharacterFullName(client)}: ${messageText}`);
} else {
messagePlayerNormal(null, `🛡️ (ADMIN) - ${messageText}`);
}
/*
let clients = getClients();
/*
let clients = getClients();
for(let i in clients) {
let translatedText;
translatedText = await translateMessage(messageText, getPlayerData(client).locale, getPlayerData(clients[i]).locale);
@@ -47,9 +53,9 @@ function processPlayerChat(client, messageText) {
let original = (getPlayerData(client).locale == getPlayerData(clients[i]).locale) ? `` : ` {ALTCOLOUR}(${messageText})`;
messagePlayerNormal(clients[i], `💬 ${getCharacterFullName(client)}: [#FFFFFF]${translatedText}${original}`, clients[i], getColourByName("mediumGrey"));
}
*/
messagePlayerNormal(null, `💬 ${getCharacterFullName(client)}: ${messageText}`);
//messageDiscordChatChannel(`💬 ${getCharacterFullName(client)}: ${messageText}`);
*/
//messageDiscordChatChannel(`💬 ${getCharacterFullName(client)}: ${messageText}`);
}
// ===========================================================================
@@ -68,7 +74,7 @@ function meActionCommand(command, params, client) {
function doActionCommand(command, params, client) {
if(isPlayerMuted(client)) {
messagePlayerError(client, "You are muted and can't chat!");
messagePlayerError(client, getLocaleString(client, "MutedCantChat"));
return false;
}
@@ -85,7 +91,7 @@ function doActionCommand(command, params, client) {
function shoutCommand(command, params, client) {
if(isPlayerMuted(client)) {
messagePlayerError(client, "You are muted and can't chat!");
messagePlayerError(client, getLocaleString(client, "MutedCantChat"));
return false;
}
@@ -102,7 +108,7 @@ function shoutCommand(command, params, client) {
function megaphoneChatCommand(command, params, client) {
if(isPlayerMuted(client)) {
messagePlayerError(client, "You are muted and can't chat!");
messagePlayerError(client, getLocaleString(client, "MutedCantChat"));
return false;
}
@@ -112,7 +118,7 @@ function megaphoneChatCommand(command, params, client) {
}
if(!canPlayerUseMegaphone(client)) {
messagePlayerError(client, "You must have a megaphone item or be in an emergency vehicle!");
messagePlayerError(client, getLocaleString(client, "CantUseMegaphone"));
return false;
}
@@ -124,7 +130,7 @@ function megaphoneChatCommand(command, params, client) {
function talkCommand(command, params, client) {
if(isPlayerMuted(client)) {
messagePlayerError(client, "You are muted and can't chat!");
messagePlayerError(client, getLocaleString(client, "MutedCantChat"));
return false;
}
@@ -141,7 +147,7 @@ function talkCommand(command, params, client) {
function whisperCommand(command, params, client) {
if(isPlayerMuted(client)) {
messagePlayerError(client, "You are muted and can't chat!");
messagePlayerError(client, getLocaleString(client, "MutedCantChat"));
return false;
}
@@ -158,7 +164,7 @@ function whisperCommand(command, params, client) {
function adminChatCommand(command, params, client) {
if(isPlayerMuted(client)) {
messagePlayerError(client, "You are muted and can't chat!");
messagePlayerError(client, getLocaleString(client, "MutedCantChat"));
return false;
}
@@ -167,14 +173,14 @@ function adminChatCommand(command, params, client) {
return false;
}
messageAdmins(`{jobYellow}[Admin Chat] {ALTCOLOUR}${getPlayerName(client)} [#CCCCCC](${getPlayerStaffTitle(client)}){MAINCOLOUR}: ${params}`);
messageAdmins(`{jobYellow}[Admin Chat] {ALTCOLOUR}${getPlayerName(client)}: ${params}`);
}
// ===========================================================================
function clanChatCommand(command, params, client) {
if(isPlayerMuted(client)) {
messagePlayerError(client, "You are muted and can't chat!");
messagePlayerError(client, getLocaleString(client, "MutedCantChat"));
return false;
}

View File

@@ -106,8 +106,6 @@ class ClanMemberData {
function initClanScript() {
logToConsole(LOG_INFO, "[VRR.Clan]: Initializing clans script ...");
getServerData().clans = loadClansFromDatabase();
setAllClanDataIndexes();
logToConsole(LOG_INFO, "[VRR.Clan]: Clan script initialized successfully!");
return true;
}
@@ -130,7 +128,7 @@ function loadClansFromDatabase() {
//tempClanData.members = loadClanMembersFromDatabase(tempClanData.databaseId);
tempClanData.ranks = loadClanRanksFromDatabase(tempClanData.databaseId);
tempClans.push(tempClanData);
logToConsole(LOG_VERBOSE, `[VRR.Clan]: Clan '${tempClanData.name}' loaded from database successfully!`);
logToConsole(LOG_DEBUG, `[VRR.Clan]: Clan '${tempClanData.name}' loaded from database successfully!`);
}
}
freeDatabaseQuery(dbQuery);
@@ -211,7 +209,7 @@ function createClanRank(clanId, rankId, rankName) {
let rankIndex = getClanData(clanId).ranks.push(tempClanRankData);
setAllClanDataIndexes();
saveAllClanRanksToDatabase(clanId);
saveClanRanksToDatabase(clanId);
return rankIndex;
}
@@ -223,7 +221,7 @@ function removeClanRank(clanId, rankId) {
return false;
}
quickDatabaseQuery(`DELETE FROM clan_rank WHERE clan_rank_id = ${tempClanRankData.database}`);
quickDatabaseQuery(`UPDATE clan_rank SET clan_rank_deleted = 1, clan_rank_when_deleted = UNIX_TIMESTAMP(), clan_rank_who_deleted = ${getPlayerData(client).accountData.databaseId} WHERE biz_id ${tempClanRankData.database}`);
getClanData(clanId).ranks.splice(tempClanRankData.index, 1);
}
@@ -241,7 +239,7 @@ function listClansCommand(command, params, client) {
let chunkedList = splitArrayIntoChunks(nameList, 5);
messagePlayerInfo(client, `{clanOrange}== {jobYellow}Clans {clanOrange}====================================`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderClansList")));
for(let i in chunkedList) {
messagePlayerInfo(client, chunkedList[i].join(", "));
@@ -268,7 +266,7 @@ function listClanRanksCommand(command, params, client) {
let chunkedList = splitArrayIntoChunks(rankNameList, 5);
messagePlayerInfo(client, `{clanOrange}== {jobYellow}Clan Ranks (${getClanData(clanId).name}) {clanOrange}=====================`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderClanRanksList")));
for(let i in chunkedList) {
messagePlayerInfo(client, chunkedList[i].join(", "));
@@ -290,7 +288,7 @@ function createClanCommand(command, params, client) {
// Create clan without owner. Can set owner with /clanowner afterward
createClan(params);
messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}created clan {clanOrange}${params}`);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} created clan {clanOrange}${params}`);
}
// ===========================================================================
@@ -308,8 +306,8 @@ function deleteClanCommand(command, params, client) {
return false;
}
messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}deleted clan {clanOrange}${getClanData(clanId).name}`);
deleteClan(clanId);
messageAdmins(`{adminOrange}${getPlayerName(client)} {MAINCOLOUR}deleted clan {clanOrange}${getClanData(clanId).name}`);
deleteClan(clanId, getPlayerData(client).accountData.databaseId);
}
// ===========================================================================
@@ -339,10 +337,13 @@ function setClanOwnerCommand(command, params, client) {
}
getClanData(clanId).owner = getPlayerCurrentSubAccount(targetClient).databaseId;
getClanData(clanId).needsSaved = true;
getPlayerCurrentSubAccount(targetClient).clan = getClanData(clanId).databaseId;
getPlayerCurrentSubAccount(targetClient).clanFlags = getClanFlagValue("All");
messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}set clan {clanOrange}${getClanData(clanId).name} {MAINCOLOUR}owner to {ALTCOLOUR}${getCharacterFullName(targetClient)}`);
//messageAdmins(`{adminOrange}${getPlayerName(client)} {MAINCOLOUR}set clan {clanOrange}${getClanData(clanId).name} {MAINCOLOUR}owner to {ALTCOLOUR}${getCharacterFullName(targetClient)}`);
messagePlayerSuccess(client, `You changed the clan owner to {ALTCOLOUR}${getCharacterFullName(targetClient)}`);
}
// ===========================================================================
@@ -365,9 +366,11 @@ function setClanTagCommand(command, params, client) {
return false;
}
getClanData(clanId).params = params;
getClanData(clanId).tag = params;
getClanData(clanId).needsSaved = true;
messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}set clan {clanOrange}${getClanData(clanId).index} {MAINCOLOUR}tag to {ALTCOLOUR}${params}`);
//messageAdmins(`{adminOrange}${getPlayerName(client)} {MAINCOLOUR}set clan {clanOrange}${getClanData(clanId).index} {MAINCOLOUR}tag to {ALTCOLOUR}${params}`);
messagePlayerSuccess(client, `You changed the clan tag to {ALTCOLOUR}${params}`);
}
// ===========================================================================
@@ -391,8 +394,10 @@ function setClanNameCommand(command, params, client) {
}
getClanData(clanId).name = params;
getClanData(clanId).needsSaved = true;
messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}set clan {clanOrange}${getClanData(clanId).index} {MAINCOLOUR}name to {ALTCOLOUR}${params}`);
//messageAdmins(`{adminOrange}${getPlayerName(client)} {MAINCOLOUR}set clan {clanOrange}${getClanData(clanId).index} {MAINCOLOUR}name to {ALTCOLOUR}${params}`);
messagePlayerSuccess(client, `You changed the clan name to {ALTCOLOUR}${params}`);
}
// ===========================================================================
@@ -453,8 +458,9 @@ function deleteClanRankCommand(command, params, client) {
}
removeClanRank(clanId, rankId);
getClanData(clanId).needsSaved = true;
messagePlayerSuccess(client, `You removed the {ALTCOLOUR}${tempRankName} {MAINCOLOUR}rank`);
messagePlayerSuccess(client, `You removed the {ALTCOLOUR}${tempRankName}{MAINCOLOUR} rank`);
}
// ===========================================================================
@@ -496,7 +502,7 @@ function setClanMemberTagCommand(command, params, client) {
}
}
getPlayerCurrentSubAccount(targetClient).ClanTag = getParam(params, " ", 2);
getPlayerCurrentSubAccount(targetClient).clanTag = getParam(params, " ", 2);
messagePlayerSuccess(client, `You set {ALTCOLOUR}${getCharacterFullName(targetClient)}'s {MAINCOLOUR}clan tag to {ALTCOLOUR}${getParam(params, " ", 2)}`);
messagePlayerAlert(client, `{ALTCOLOUR}${getCharacterFullName(targetClient)} {MAINCOLOUR}set your clan tag to {ALTCOLOUR}${getParam(params, " ", 2)}`);
@@ -530,7 +536,8 @@ function setClanRankTagCommand(command, params, client) {
}
}
getServerData().clans[clanId].rankId[rankId].customTag = newTag;
getClanRankData(clanId, rankId).customTag = newTag;
getClanRankData(clanId, rankId).needsSaved = true;
}
// ===========================================================================
@@ -578,7 +585,8 @@ function setClanRankLevelCommand(command, params, client) {
return false;
}
getServerData().clans[clanId].rankId[rankId].level = toInteger(newLevel);
getClanRankData(clanId, rankId).level = toInteger(newLevel);
getClanRankData(clanId, rankId).needsSaved = true;
}
// ===========================================================================
@@ -717,7 +725,8 @@ function addClanRankFlagCommand(command, params, client) {
let flagValue = getClanFlagValue(getParam(params, " ", 2));
addBitFlag(getClanRankData(clanId, rankId).flags, flagValue);
getClanRankData(clanId, rankId).flags = addBitFlag(getClanRankData(clanId, rankId).flags, flagValue);
getClanRankData(clanId, rankId).needsSaved = true;
messagePlayerSuccess(client, `You added the {ALTCOLOUR}${getParam(params, " ", 2)} {MAINCOLOUR}clan flag to rank {ALTCOLOUR}${getClanRankData(clanId, rankId).name}`);
}
@@ -755,7 +764,8 @@ function removeClanRankFlagCommand(command, params, client) {
let flagValue = getClanFlagValue(getParam(params, " ", 2));
removeBitFlag(getClanRankData(clanId, rankId).flags, flagValue);
getClanRankData(clanId, rankId).flags = removeBitFlag(getClanRankData(clanId, rankId).flags, flagValue);
getClanRankData(clanId, rankId).needsSaved = true;
messagePlayerSuccess(client, `You removed the {ALTCOLOUR}${getParam(params, " ", 2)} {MAINCOLOUR}clan flag from rank {ALTCOLOUR}${getClanRankData(clanId, rankId).name}`);
}
@@ -799,8 +809,7 @@ function showClanRankFlagsCommand(command, params, client) {
let chunkedList = splitArrayIntoChunks(flagList, 6);
messagePlayerInfo(client, `{clanOrange}== {jobYellow}Clan Rank Flags (${getClanRankData(clanId, rankId).name}){clanOrange}===================`);
makeChatBoxSectionHeader(client, getLocaleString(client, "ClanRankFlags"), getClanRankData(clanId, rankId).name);
for(let i in chunkedList) {
messagePlayerInfo(client, chunkedList[i].join("{MAINCOLOUR}, "));
}
@@ -881,6 +890,7 @@ function setClanRankTitleCommand(command, params, client) {
let oldRankName = getClanRankData(clanId, rankId).name;
getClanRankData(clanId, rankId).name = getParam(params, " ", 2);
getClanRankData(clanId, rankId).needsSaved = true;
messagePlayerSuccess(client, `You changed the name of rank ${rankId} from {ALTCOLOUR}${oldRankName} {MAINCOLOUR}to {ALTCOLOUR}${params}`);
}
@@ -941,7 +951,7 @@ function setClanMemberRankCommand(command, params, client) {
let oldClanRank = getClanRankData(clanId, getPlayerClanRank(targetClient));
getPlayerCurrentSubAccount(targetClient).clanRank = getClanRankData(clanId, rankId).databaseId;
getPlayerCurrentSubAccount(targetClient).clanRankIndex = rankId;
messagePlayerSuccess(client, `You changed {ALTCOLOUR}${getCharacterFullName(targetClient)}'s {MAINCOLOUR}rank from {ALTCOLOUR}${oldClanRank.name} {MAINCOLOUR}to {ALTCOLOUR}${getClanRankData(clanId, rankId).name}`);
messagePlayerSuccess(client, `You changed {ALTCOLOUR}${getCharacterFullName(targetClient)}'s{MAINCOLOUR} rank from {ALTCOLOUR}${oldClanRank.name}{MAINCOLOUR} to {ALTCOLOUR}${getClanRankData(clanId, rankId).name}`);
}
// ===========================================================================
@@ -966,12 +976,12 @@ function createClan(name) {
// ===========================================================================
function deleteClan(clanId) {
saveClansToDatabase();
function deleteClan(clanId, whoDeleted = 0) {
//saveAllClansToDatabase();
let dbConnection = connectToDatabase();
if(dbConnection) {
let dbQuery = queryDatabase(dbConnection, `UPDATE clan_main SET clan_deleted = 1 WHERE clan_id = ${clanId}`);
let dbQuery = queryDatabase(dbConnection, `UPDATE clan_main SET clan_deleted = 1, clan_when_deleted = UNIX_TIMESTAMP, clan_who_deleted = ${whoDeleted} WHERE clan_id = ${clanId}`);
freeDatabaseQuery(dbQuery);
disconnectFromDatabase(dbConnection);
@@ -1024,12 +1034,20 @@ function doesClanIdExist(clanId) {
// ===========================================================================
function reloadAllClans() {
if(getServerConfig().devServer) {
return false;
}
getServerData().clans = loadClansFromDatabase();
}
// ===========================================================================
function saveAllClanRanksToDatabase(clanId) {
function saveClanRanksToDatabase(clanId) {
if(getServerConfig().devServer) {
return false;
}
let ranks = getServerData().clans[clanId].ranks;
for(let i in ranks) {
saveClanRankToDatabase(clanId, i);
@@ -1045,9 +1063,13 @@ function saveClanToDatabase(clanId) {
return false;
}
if(!tempClanData.needsSaved) {
return false;
}
if(tempClanData.databaseId == -1) {
return false;
}
if(!tempClanData.needsSaved) {
return false;
}
let dbConnection = connectToDatabase();
if(dbConnection) {
@@ -1079,7 +1101,7 @@ function saveClanToDatabase(clanId) {
disconnectFromDatabase(dbConnection);
}
saveAllClanRanksToDatabase(clanId);
saveClanRanksToDatabase(clanId);
return true;
}
@@ -1091,41 +1113,41 @@ function saveClanToDatabase(clanId) {
function saveClanRankToDatabase(clanId, rankId) {
let tempClanRankData = getClanRankData(clanId, rankId);
if(!tempClanRankData.needsSaved) {
return false;
}
if(!tempClanRankData.needsSaved) {
return false;
}
let dbConnection = connectToDatabase();
if(dbConnection) {
let safeName = escapeDatabaseString(dbConnection, tempClanRankData.name);
let safeTag = escapeDatabaseString(dbConnection, tempClanRankData.customTag);
//let safeTitle = escapeDatabaseString(dbConnection, tempClanRankData.name);
let safeName = escapeDatabaseString(dbConnection, tempClanRankData.name);
let safeTag = escapeDatabaseString(dbConnection, tempClanRankData.customTag);
//let safeTitle = escapeDatabaseString(dbConnection, tempClanRankData.name);
let data = [
["clan_rank_name", safeName],
["clan_rank_clan", tempClanRankData.clan],
["clan_rank_custom_tag", safeTag],
//["clan_rank_title", safeTitle],
["clan_rank_flags", tempClanRankData.flags],
["clan_rank_level", tempClanRankData.level],
["clan_rank_enabled", boolToInt(tempClanRankData.enabled)],
];
let data = [
["clan_rank_name", safeName],
["clan_rank_clan", tempClanRankData.clan],
["clan_rank_custom_tag", safeTag],
//["clan_rank_title", safeTitle],
["clan_rank_flags", tempClanRankData.flags],
["clan_rank_level", tempClanRankData.level],
["clan_rank_enabled", boolToInt(tempClanRankData.enabled)],
];
let dbQuery = null;
if(tempClanRankData.databaseId == 0) {
let queryString = createDatabaseInsertQuery("clan_rank", data);
dbQuery = queryDatabase(dbConnection, queryString);
getClanRankData(clanId, rankId).databaseId = getDatabaseInsertId(dbConnection);
getClanRankData(clanId, rankId).needsSaved = false;
} else {
let queryString = createDatabaseUpdateQuery("clan_rank", data, `clan_rank_id=${tempClanRankData.databaseId} LIMIT 1`);
dbQuery = queryDatabase(dbConnection, queryString);
getClanRankData(clanId, rankId).needsSaved = false;
}
let dbQuery = null;
if(tempClanRankData.databaseId == 0) {
let queryString = createDatabaseInsertQuery("clan_rank", data);
dbQuery = queryDatabase(dbConnection, queryString);
getClanRankData(clanId, rankId).databaseId = getDatabaseInsertId(dbConnection);
getClanRankData(clanId, rankId).needsSaved = false;
} else {
let queryString = createDatabaseUpdateQuery("clan_rank", data, `clan_rank_id=${tempClanRankData.databaseId} LIMIT 1`);
dbQuery = queryDatabase(dbConnection, queryString);
getClanRankData(clanId, rankId).needsSaved = false;
}
freeDatabaseQuery(dbQuery);
disconnectFromDatabase(dbConnection);
return true;
freeDatabaseQuery(dbQuery);
disconnectFromDatabase(dbConnection);
return true;
}
return false;
@@ -1169,6 +1191,10 @@ function setClanRankTitle(clanId, rankId, title) {
// ===========================================================================
function saveAllClansToDatabase() {
if(getServerConfig().devServer) {
return false;
}
for(let i in getServerData().clans) {
saveClanToDatabase(i);
}
@@ -1231,6 +1257,11 @@ function getClanRankIdFromDatabaseId(clanId, databaseId) {
// ===========================================================================
/**
* @param {number} clanId - The data index of the clan
* @param {number} clanRankId - The data index of the clan rank
* @return {ClanRankData} The clan rank's data (class instance)
*/
function getClanRankData(clanId, rankId) {
return getServerData().clans[clanId].ranks[rankId];
}
@@ -1287,7 +1318,7 @@ function showClanFlagListCommand(command, params, client) {
return false;
}
let rankId = getClanRankFromParams(clanId, getParam(params, " ", 1));
let rankId = getClanRankFromParams(clanId, getParam(params, " ", 1));
if(!getClanRankData(clanId, rankId)) {
messagePlayerError(client, getLocaleString(client, "ClanRankInvalid"));
@@ -1310,6 +1341,12 @@ let rankId = getClanRankFromParams(clanId, getParam(params, " ", 1));
}
*/
// ===========================================================================
/**
* @param {String} params - The params to search for
* @return {Number} The data index of a matching clan
*/
function getClanFromParams(params) {
if(isNaN(params)) {
for(let i in getServerData().clans) {
@@ -1328,6 +1365,11 @@ function getClanFromParams(params) {
// ===========================================================================
/**
* @param {Number} clanId - The clan ID to search ranks for
* @param {String} params - The params to search for
* @return {Number} The data index of a matching clan
*/
function getClanRankFromParams(clanId, params) {
if(isNaN(params)) {
for(let i in getClanData(clanId).ranks) {

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -10,7 +10,7 @@
/**
* @class Representing data for server configuration
*/
class ServerData {
class ServerData {
constructor(dbAssoc = false) {
this.databaseId = 0;
this.needsSaved = false;
@@ -86,7 +86,7 @@
sendAdminEvents: true,
};
if(dbAssoc) {
if (dbAssoc) {
this.databaseId = dbAssoc["svr_id"];
this.newCharacter = {
spawnPosition: toVector3(dbAssoc["svr_newchar_pos_x"], dbAssoc["svr_newchar_pos_y"], dbAssoc["svr_newchar_pos_z"]),
@@ -95,7 +95,7 @@
bank: dbAssoc["svr_newchar_bank"],
skin: dbAssoc["svr_newchar_skin"],
},
this.settings = toInteger(dbAssoc["svr_settings"]);
this.settings = toInteger(dbAssoc["svr_settings"]);
this.connectCameraPosition = toVector3(dbAssoc["svr_connectcam_pos_x"], dbAssoc["svr_connectcam_pos_y"], dbAssoc["svr_connectcam_pos_z"]);
this.connectCameraLookAt = toVector3(dbAssoc["svr_connectcam_lookat_x"], dbAssoc["svr_connectcam_lookat_y"], dbAssoc["svr_connectcam_lookat_z"]);
@@ -127,13 +127,18 @@
};
let serverConfig = false;
let databaseConfig = false;
let emailConfig = false;
let gameConfig = false;
// ===========================================================================
let globalConfig = {
keyBind: [],
economy: {},
database: {},
locale: {},
accents: {},
discord: {},
email: {},
accountPasswordHash: "SHA512",
npcFarProximity: 100,
npcMediumProximity: 40,
@@ -150,7 +155,6 @@ let globalConfig = {
stopWorkingDistance: 10,
spawnCarDistance: 5,
payAndSprayDistance: 5,
keyBind: [],
exitPropertyDistance: 3.0,
enterPropertyDistance: 3.0,
businessDimensionStart: 5000,
@@ -186,64 +190,107 @@ let globalConfig = {
],
vehicleInactiveRespawnDelay: 1800000, // 20 minutes
chatSectionHeaderLength: 96,
economy: {},
locales: [],
accents: [],
useServerSideVehiclePurchaseCheck: false,
useServerSideVehiclePurchaseCheck: true,
useServerSideVehicleBurnCheck: false,
businessPickupStreamInDistance: 100,
businessPickupStreamOutDistance: 120,
housePickupStreamInDistance: 100,
housePickupStreamOutDistance: 120,
jobPickupStreamInDistance: 100,
jobPickupStreamOutDistance: 120,
businessBlipStreamInDistance: 150,
businessBlipStreamOutDistance: 200,
houseBlipStreamInDistance: 100,
houseBlipStreamOutDistance: 120,
jobBlipStreamInDistance: -1,
jobBlipStreamOutDistance: -1,
playerBlipStreamInDistance: -1,
playerBlipStreamOutDistance: -1,
handcuffPlayerDistance: 3,
firstAidKitPlayerDistance: 3,
droppedItemPickupRange: 2,
passwordRequiredCapitals: 0,
passwordRequiredNumbers: 0,
passwordRequiredSymbols: 0,
minChatLines: 1,
maxChatLines: 6,
};
// ===========================================================================
function initConfigScript() {
logToConsole(LOG_INFO, "[VRR.Config]: Initializing config script ...");
logToConsole(LOG_DEBUG, "[VRR.Config]: Loading global config ...");
loadGlobalConfig();
logToConsole(LOG_INFO, "[VRR.Config]: Loading server config ...");
serverConfig = loadServerConfigFromGameAndPort(server.game, server.port, getMultiplayerMod());
logToConsole(LOG_INFO, "[VRR.Config]: Applying server config ...");
getServerConfig().fallingSnow = intToBool(toInteger(server.getCVar("vrr_fallingsnow")));
getServerConfig().groundSnow = intToBool(toInteger(server.getCVar("vrr_groundsnow")));
getServerConfig().useGUI = intToBool(toInteger(server.getCVar("vrr_gui")));
getServerConfig().showLogo = false;
getServerConfig().testerOnly = intToBool(toInteger(server.getCVar("vrr_testeronly")));
getServerConfig().discordEnabled = false;
getServerConfig().createJobPickups = intToBool(toInteger(server.getCVar("vrr_jobpickups")));
getServerConfig().createBusinessPickups = intToBool(toInteger(server.getCVar("vrr_businesspickups")));
getServerConfig().createHousePickups = intToBool(toInteger(server.getCVar("vrr_housepickups")));
getServerConfig().createJobBlips = intToBool(toInteger(server.getCVar("vrr_jobblips")));
getServerConfig().createBusinessBlips = intToBool(toInteger(server.getCVar("vrr_businessblips")));
getServerConfig().createHouseBlips = intToBool(toInteger(server.getCVar("vrr_houseblips")));
getServerConfig().useRealTime = intToBool(toInteger(server.getCVar("vrr_realtime")));
getServerConfig().antiCheat.enabled = intToBool(toInteger(server.getCVar("vrr_anticheat")));
applyConfigToServer(serverConfig);
logToConsole(LOG_DEBUG, "[VRR.Config]: Server config applied successfully!");
logToConsole(LOG_INFO, "[VRR.Config]: Config script initialized!");
}
// ===========================================================================
function loadGlobalConfig() {
getGlobalConfig().economy = loadEconomyConfig();
getGlobalConfig().locale = loadLocaleConfig();
getGlobalConfig().accents = loadAccentConfig();
logToConsole(LOG_DEBUG, "[VRR.Config] Loading global configuration ...");
try {
getGlobalConfig().database = loadDatabaseConfig();
} catch (error) {
logToConsole(LOG_ERROR, `[VRR.Config] Failed to load global configuration. Error: ${error}`);
thisResource.stop();
}
try {
getGlobalConfig().economy = loadEconomyConfig();
} catch (error) {
logToConsole(LOG_ERROR, `[VRR.Config] Failed to load economy configuration. Error: ${error}`);
thisResource.stop();
}
try {
getGlobalConfig().locale = loadLocaleConfig();
} catch (error) {
logToConsole(LOG_ERROR, `[VRR.Config] Failed to load locale configuration. Error: ${error}`);
thisResource.stop();
}
try {
getGlobalConfig().accents = loadAccentConfig();
} catch (error) {
logToConsole(LOG_ERROR, `[VRR.Config] Failed to load accent configuration. Error: ${error}`);
thisResource.stop();
}
try {
getGlobalConfig().discord = loadDiscordConfig();
} catch (error) {
logToConsole(LOG_ERROR, `[VRR.Config] Failed to load discord configuration. Error: ${error}`);
thisResource.stop();
}
try {
getGlobalConfig().keyBind = loadKeyBindConfig();
} catch (error) {
logToConsole(LOG_ERROR, `[VRR.Config] Failed to load keybind configuration. Error: ${error}`);
thisResource.stop();
}
try {
getGlobalConfig().email = loadEmailConfig();
} catch (error) {
logToConsole(LOG_ERROR, `[VRR.Config] Failed to load email configuration. Error: ${error}`);
thisResource.stop();
}
logToConsole(LOG_DEBUG, "[VRR.Config] Loaded global configuration successfully!");
}
// ===========================================================================
function loadServerConfigFromGameAndPort(gameId, port, mpMod) {
function loadServerConfigFromGameAndPort(gameId, port) {
let dbConnection = connectToDatabase();
if(dbConnection) {
let dbQueryString = `SELECT * FROM svr_main WHERE svr_game = ${gameId} AND svr_port = ${port} AND svr_mpmod = ${mpMod} LIMIT 1;`;
if (dbConnection) {
let dbQueryString = `SELECT * FROM svr_main WHERE svr_game = ${gameId} AND svr_port = ${port} LIMIT 1;`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
if(dbQuery.numRows > 0) {
if (dbQuery) {
if (dbQuery.numRows > 0) {
let dbAssoc = fetchQueryAssoc(dbQuery);
let tempServerConfigData = new ServerData(dbAssoc);
let tempServerConfigData = new ServerConfigData(dbAssoc);
freeDatabaseQuery(dbQuery);
return tempServerConfigData;
}
@@ -257,13 +304,13 @@ function loadServerConfigFromGameAndPort(gameId, port, mpMod) {
function loadServerConfigFromId(tempServerId) {
let dbConnection = connectToDatabase();
if(dbConnection) {
if (dbConnection) {
let dbQueryString = `SELECT * FROM svr_main WHERE svr_id = ${tempServerId} LIMIT 1;`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
if(dbQuery.numRows > 0) {
if (dbQuery) {
if (dbQuery.numRows > 0) {
let dbAssoc = fetchQueryAssoc(dbQuery);
let tempServerConfigData = new ServerData(dbAssoc);
let tempServerConfigData = new ServerConfigData(dbAssoc);
freeDatabaseQuery(dbQuery);
return tempServerConfigData;
}
@@ -276,12 +323,15 @@ function loadServerConfigFromId(tempServerId) {
// ===========================================================================
function applyConfigToServer(tempServerConfig) {
if(isTimeSupported()) {
logToConsole(LOG_INFO, "[VRR.Config]: Applying server config ...");
logToConsole(LOG_DEBUG, "[VRR.Config]: Server config applied successfully!");
if (isTimeSupported()) {
logToConsole(LOG_DEBUG, `[VRR.Config]: Setting time to to ${tempServerConfig.hour}:${tempServerConfig.minute} with minute duration of ${tempServerConfig.minuteDuration}`);
setGameTime(tempServerConfig.hour, tempServerConfig.minute, tempServerConfig.minuteDuration);
}
if(isWeatherSupported()) {
if (isWeatherSupported()) {
logToConsole(LOG_DEBUG, `[VRR.Config]: Setting weather to ${tempServerConfig.weather}`);
game.forceWeather(tempServerConfig.weather);
}
@@ -293,11 +343,11 @@ function applyConfigToServer(tempServerConfig) {
function saveServerConfigToDatabase() {
logToConsole(LOG_DEBUG, `[VRR.Config]: Saving server ${getServerConfig().databaseId} configuration to database ...`);
if(getServerConfig().needsSaved) {
if (getServerConfig().needsSaved) {
let dbConnection = connectToDatabase();
if(dbConnection) {
if (dbConnection) {
let data = [
["svr_settings", toInteger(getServerConfig().settings)],
//["svr_settings", toInteger(getServerConfig().settings)],
["svr_start_time_hour", getServerConfig().hour],
["svr_start_time_min", getServerConfig().minute],
["svr_start_weather", getServerConfig().weather],
@@ -333,6 +383,17 @@ function saveServerConfigToDatabase() {
["svr_charselect_vw", getServerConfig().characterSelectDimension],
["svr_inflation_multiplier", getServerConfig().inflationMultiplier],
["svr_intro_music", getServerConfig().introMusicURL],
["svr_gui", getServerConfig().useGUI],
["svr_logo", getServerConfig().showLogo],
["svr_snow_falling", getServerConfig().fallingSnow],
["svr_snow_ground", getServerConfig().groundSnow],
["svr_biz_blips", getServerConfig().createBusinessBlips],
["svr_biz_pickups", getServerConfig().createBusinessPickups],
["svr_house_blips", getServerConfig().createHouseBlips],
["svr_house_pickups", getServerConfig().createHousePickups],
["svr_job_blips", getServerConfig().createJobBlips],
["svr_job_pickups", getServerConfig().createJobPickups],
["svr_nametag_distance", getServerConfig().nameTagDistance],
];
let dbQuery = null;
@@ -352,7 +413,7 @@ function saveServerConfigToDatabase() {
/**
*
* @return {ServerData} - Server configuration data
* @return {ServerConfigData} - Server configuration data
*
*/
function getServerConfig() {
@@ -391,7 +452,7 @@ function getServerId() {
*
*/
function setTimeCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
@@ -399,27 +460,27 @@ function setTimeCommand(command, params, client) {
let hour = toInteger(getParam(params, " ", 1));
let minute = toInteger(getParam(params, " ", 2)) || 0;
if(hour > 23 || hour < 0) {
if (hour > 23 || hour < 0) {
messagePlayerError(client, "The hour must be between 0 and 23!");
return false;
}
}
if(minute > 59 || minute < 0) {
if (minute > 59 || minute < 0) {
messagePlayerError(client, "The minute must be between 0 and 59!");
return false;
}
}
getServerConfig().hour = hour;
getServerConfig().minute = minute;
game.time.hour = getServerConfig().hour;
game.time.minute = getServerConfig().minute;
game.time.hour = getServerConfig().hour;
game.time.minute = getServerConfig().minute;
//checkServerGameTime();
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} set the time to ${makeReadableTime(hour, minute)}`);
announceAdminAction("ServerTimeSet", getPlayerName(client), makeReadableTime(hour, minute));
return true;
}
@@ -436,18 +497,18 @@ function setTimeCommand(command, params, client) {
*
*/
function setMinuteDurationCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let minuteDuration = toInteger(params);
let minuteDuration = toInteger(params);
getServerConfig().minuteDuration = minuteDuration;
setTimeMinuteDuration(null, minuteDuration);
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} set the minute duration to ${minuteDuration}ms`);
announceAdminAction("ServerMinuteDurationSet", getPlayerName(client), makeReadableTime(hour, minute));
return true;
}
@@ -463,25 +524,25 @@ function setMinuteDurationCommand(command, params, client) {
*
*/
function setWeatherCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let weatherId = getWeatherFromParams(getParam(params, " ", 1));
if(!weatherId) {
if (!weatherId) {
messagePlayerError(client, `That weather ID or name is invalid!`);
return false;
}
}
game.forceWeather(toInteger(weatherId));
game.forceWeather(toInteger(weatherId));
getServerConfig().weather = weatherId;
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} set the weather to {ALTCOLOUR}${getGameConfig().weatherNames[getServerGame()][toInteger(weatherId)]}`);
updateServerRules();
announceAdminAction("ServerWeatherSet", getPlayerName(client), getGameConfig().weatherNames[getGame()][toInteger(weatherId)]);
updateServerRules();
return true;
}
@@ -497,13 +558,13 @@ function setWeatherCommand(command, params, client) {
*
*/
function setSnowingCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let splitParams = params.split(" ");
let falling = toInteger(getParam(params, " ", 1));
let falling = toInteger(getParam(params, " ", 1));
let ground = toInteger(getParam(params, " ", 2));
getServerConfig().fallingSnow = intToBool(falling);
@@ -513,8 +574,8 @@ function setSnowingCommand(command, params, client) {
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned falling snow ${getBoolRedGreenInlineColour(falling)}${getOnOffFromBool(falling)} {MAINCOLOUR}and ground snow ${getBoolRedGreenInlineColour(ground)}${getOnOffFromBool(ground)}`);
updateServerRules();
announceAdminAction("ServerSnowSet", getPlayerName(client), `${getBoolRedGreenInlineColour(falling)}${getOnOffFromBool(falling)}`, `${getBoolRedGreenInlineColour(ground)}${getOnOffFromBool(ground)}`);
updateServerRules();
return true;
}
@@ -530,27 +591,27 @@ function setSnowingCommand(command, params, client) {
*
*/
function setServerGUIColoursCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let splitParams = params.split(" ");
let colourRed = toInteger(getParam(params, " ", 1)) || 255;
let colourRed = toInteger(getParam(params, " ", 1)) || 255;
let colourGreen = toInteger(getParam(params, " ", 2)) || 255;
let colourBlue = toInteger(getParam(params, " ", 3)) || 255;
getServerConfig().guiColour = [colourRed, colourGreen, colourBlue];
let clients = getClients();
for(let i in clients) {
for (let i in clients) {
sendPlayerGUIColours(clients[i]);
}
getServerConfig().needsSaved = true;
//messageAdminAction(`${getPlayerName(client)} ${getInlineChatColourByName("orange")}set the server ${getBoolRedGreenInlineColour(fallingSnow)}${getOnOffFromBool(fallingSnow)} ${getInlineChatColourByName("orange")}and ground snow ${getBoolRedGreenInlineColour(groundSnow)}${getOnOffFromBool(groundSnow)}`);
//updateServerRules();
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} has set the server GUI colours to ${colourRed}, ${colourGreen}, ${colourBlue}`);
//updateServerRules();
return true;
}
@@ -571,8 +632,8 @@ function toggleServerLogoCommand(command, params, client) {
updatePlayerShowLogoState(null, getServerConfig().useLogo);
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned the server logo image ${getBoolRedGreenInlineColour(doesServerHaveServerLogoEnabled())}${toUpperCase(getOnOffFromBool(getServerConfig().useLogo))}`);
updateServerRules();
announceAdminAction(`ServerLogoSet`, `{adminOrange}${getPlayerName(client)}{MAINCOLOUR}`, `${getBoolRedGreenInlineColour(getServerConfig().useLogo)}${toUpperCase(getOnOffFromBool(getServerConfig().useLogo))}`);
updateServerRules();
return true;
}
@@ -587,11 +648,11 @@ function toggleServerLogoCommand(command, params, client) {
* @return {bool} Whether or not the command was successful
*
*/
function toggleServerJobBlipsCommand(command, params, client) {
function toggleServerJobBlipsCommand(command, params, client) {
getServerConfig().createJobBlips = !getServerConfig().createJobBlips;
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned ${getBoolRedGreenInlineColour(doesServerHaveJobBlipsEnabled())}${toUpperCase(getOnOffFromBool(getServerConfig().createJobBlips))} {MAINCOLOUR}all job blips`);
announceAdminAction("ServerJobBlipsSet", `{adminOrange}${getPlayerName(client)}{MAINCOLOUR}`, `${getBoolRedGreenInlineColour(getServerConfig().createJobBlips)}${toUpperCase(getOnOffFromBool(getServerConfig().createJobBlips))}{MAINCOLOUR}`);
resetAllJobBlips();
return true;
}
@@ -607,11 +668,11 @@ function toggleServerLogoCommand(command, params, client) {
* @return {bool} Whether or not the command was successful
*
*/
function toggleServerJobPickupsCommand(command, params, client) {
function toggleServerJobPickupsCommand(command, params, client) {
getServerConfig().createJobPickups = !getServerConfig().createJobPickups;
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned ${getBoolRedGreenInlineColour(doesServerHaveJobPickupsEnabled())}${toUpperCase(getOnOffFromBool(getServerConfig().createJobPickups))} {MAINCOLOUR}all job pickups`);
announceAdminAction("ServerJobPickupsSet", `{adminOrange}${getPlayerName(client)}{MAINCOLOUR}`, `${getBoolRedGreenInlineColour(getServerConfig().createJobPickups)}${toUpperCase(getOnOffFromBool(getServerConfig().createJobPickups))}{MAINCOLOUR}`);
resetAllJobPickups();
return true;
}
@@ -627,11 +688,11 @@ function toggleServerLogoCommand(command, params, client) {
* @return {bool} Whether or not the command was successful
*
*/
function toggleServerBusinessBlipsCommand(command, params, client) {
getServerConfig().createBusinessBlips = !getServerConfig().createBusinessBlips;
function toggleServerBusinessBlipsCommand(command, params, client) {
getServerConfig().createBusinessBlips = !getServerConfig().createBusinessBlips;
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned ${getBoolRedGreenInlineColour(doesServerHaveBusinessBlipsEnabled())}${toUpperCase(getOnOffFromBool(getServerConfig().createBusinessBlips))} {MAINCOLOUR}all business blips`);
announceAdminAction("ServerBusinessBlipsSet", `{adminOrange}${getPlayerName(client)}{MAINCOLOUR}`, `${getBoolRedGreenInlineColour(getServerConfig().createBusinessBlips)}${toUpperCase(getOnOffFromBool(getServerConfig().createBusinessBlips))}{MAINCOLOUR}`);
resetAllBusinessBlips();
return true;
}
@@ -647,11 +708,11 @@ function toggleServerLogoCommand(command, params, client) {
* @return {bool} Whether or not the command was successful
*
*/
function toggleServerBusinessPickupsCommand(command, params, client) {
getServerConfig().createBusinessPickups = !getServerConfig().createBusinessPickups;
function toggleServerBusinessPickupsCommand(command, params, client) {
getServerConfig().createBusinessPickups = !getServerConfig().createBusinessPickups;
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned ${getBoolRedGreenInlineColour(doesServerHaveBusinessPickupsEnabled())}${toUpperCase(getOnOffFromBool(getServerConfig().createBusinessPickups))} {MAINCOLOUR}all business pickups`);
announceAdminAction("ServerBusinessPickupsSet", `{adminOrange}${getPlayerName(client)}{MAINCOLOUR}`, `${getBoolRedGreenInlineColour(getServerConfig().createBusinessPickups)}${toUpperCase(getOnOffFromBool(getServerConfig().createBusinessPickups))}{MAINCOLOUR}`);
resetAllBusinessPickups();
return true;
}
@@ -667,11 +728,11 @@ function toggleServerLogoCommand(command, params, client) {
* @return {bool} Whether or not the command was successful
*
*/
function toggleServerHouseBlipsCommand(command, params, client) {
getServerConfig().createHouseBlips = !getServerConfig().createHouseBlips;
function toggleServerHouseBlipsCommand(command, params, client) {
getServerConfig().createHouseBlips = !getServerConfig().createHouseBlips;
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned ${getBoolRedGreenInlineColour(doesServerHaveHouseBlipsEnabled())}${toUpperCase(getOnOffFromBool(getServerConfig().createHouseBlips))} {MAINCOLOUR}all house blips`);
announceAdminAction("ServerHouseBlipsSet", `{adminOrange}${getPlayerName(client)}{MAINCOLOUR}`, `${getBoolRedGreenInlineColour(getServerConfig().createHouseBlips)}${toUpperCase(getOnOffFromBool(getServerConfig().createHouseBlips))}{MAINCOLOUR}`);
resetAllHouseBlips();
return true;
}
@@ -687,11 +748,11 @@ function toggleServerLogoCommand(command, params, client) {
* @return {bool} Whether or not the command was successful
*
*/
function toggleServerHousePickupsCommand(command, params, client) {
function toggleServerHousePickupsCommand(command, params, client) {
getServerConfig().createHousePickups = !getServerConfig().createHousePickups;
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned ${getBoolRedGreenInlineColour(doesServerHaveHousePickupsEnabled())}${toUpperCase(getOnOffFromBool(getServerConfig().createHousePickups))} {MAINCOLOUR}all house pickups`);
announceAdminAction("ServerHousePickupsSet", `{adminOrange}${getPlayerName(client)}{MAINCOLOUR}`, `${getBoolRedGreenInlineColour(getServerConfig().createHousePickups)}${toUpperCase(getOnOffFromBool(getServerConfig().createHousePickups))}{MAINCOLOUR}`);
resetAllHousePickups();
return true;
}
@@ -712,8 +773,8 @@ function toggleServerGUICommand(command, params, client) {
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned GUI ${toLowerCase(getOnOffFromBool(doesServerHaveGUIEnabled()))} for this server`);
updateServerRules();
announceAdminAction(`ServerGUISet`, `${getPlayerName(client)}{MAINCOLOUR}`, `${getBoolRedGreenInlineColour(getServerConfig().useGUI)}${toUpperCase(getOnOffFromBool(getServerConfig().useGUI))}{MAINCOLOUR}`);
updateServerRules();
return true;
}
@@ -730,12 +791,13 @@ function toggleServerGUICommand(command, params, client) {
*/
function toggleServerUseRealWorldTimeCommand(command, params, client) {
getServerConfig().useRealTime = !getServerConfig().useRealTime;
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}turned real-world time ${getServerConfig().useRealTime} for this server (GMT ${addPositiveNegativeSymbol(getServerConfig().realTimeZone)})`);
//announceAdminAction(`${getPlayerName(client)}{MAINCOLOUR} turned real-world time ${getServerConfig().useRealTime} for this server (GMT ${addPositiveNegativeSymbol(getServerConfig().realTimeZone)})`);
updateServerGameTime();
updateServerRules();
updateServerRules();
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} turned real-world time ${getOnOffFromBool(getServerConfig().useRealTime)} for this server (GMT ${addPositiveNegativeSymbol(getServerConfig().realTimeZone)})`);
return true;
}
@@ -751,17 +813,19 @@ function toggleServerUseRealWorldTimeCommand(command, params, client) {
*
*/
function setServerRealWorldTimeZoneCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
getServerConfig().realTimeZone = toInteger(params);
getServerConfig().realTimeZone = toInteger(params);
getServerConfig().needsSaved = true;
messageAdminAction(`${getPlayerName(client)} {MAINCOLOUR}set the time zone for in-game's real-world time to GMT ${addPositiveNegativeSymbol(getServerConfig().realTimeZone)}`);
//announceAdminAction(`${getPlayerName(client)} {MAINCOLOUR}set the time zone for in-game's real-world time to GMT ${addPositiveNegativeSymbol(getServerConfig().realTimeZone)}`);
updateServerGameTime();
updateServerRules();
updateServerRules();
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} set the timezone for in-game real-world time to GMT ${addPositiveNegativeSymbol(getServerConfig().realTimeZone)}`);
return true;
}
@@ -781,7 +845,8 @@ function reloadServerConfigurationCommand(command, params, client) {
applyConfigToServer(serverConfig);
updateServerRules();
messagePlayerSuccess(client, `You reloaded the server configuration!`);
messagePlayerSuccess(client, `You reloaded the server configuration!`);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} reloaded the server config`);
return true;
}
@@ -797,8 +862,8 @@ function reloadServerConfigurationCommand(command, params, client) {
*
*/
function reloadEmailConfigurationCommand(command, params, client) {
emailConfig = loadEmailConfiguration();
messagePlayerSuccess(client, `You reloaded the email configuration!`);
getGlobalConfig().email = loadEmailConfig();
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} reloaded the email config`);
return true;
}
@@ -814,19 +879,43 @@ function reloadEmailConfigurationCommand(command, params, client) {
*
*/
function reloadDatabaseConfigurationCommand(command, params, client) {
if(databaseConfig.usePersistentConnection && isDatabaseConnected(persistentDatabaseConnection)) {
console.warn(`[VRR.Database] Closing persistent database connection`);
if (getDatabaseConfig().usePersistentConnection && isDatabaseConnected(persistentDatabaseConnection)) {
logToConsole(LOG_WARN, `[VRR.Database] Closing persistent database connection`);
persistentDatabaseConnection.close();
persistentDatabaseConnection = null;
}
databaseEnabled = false;
databaseConfig = loadEmailConfig();
messagePlayerSuccess(client, `You reloaded the database configuration!`);
getGlobalConfig().database = loadDatabaseConfig();
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} reloaded the database config`);
databaseEnabled = true;
if(databaseConfig.usePersistentConnection) {
if (getDatabaseConfig().usePersistentConnection) {
connectToDatabase();
}
return true;
}
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function setServerNameTagDistanceCommand(command, params, client) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
getServerConfig().nameTagDistance = toFloat(params);
getServerConfig().needsSaved = true;
sendNameTagDistanceToClient(null, getServerConfig().nameTagDistance);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} set the name tag distance to ${getServerConfig().nameTagDistance}`);
return true;
}
@@ -839,8 +928,9 @@ function getServerIntroMusicURL() {
// ===========================================================================
function loadLocaleConfig() {
logToConsole(LOG_DEBUG, "[VRR.Config] Loading locale configuration");
let localeConfig = JSON.parse(loadTextFile(`config/locale.json`));
if(localeConfig != null) {
if (localeConfig != null) {
return localeConfig;
}
}
@@ -848,8 +938,9 @@ function loadLocaleConfig() {
// ===========================================================================
function loadEconomyConfig() {
logToConsole(LOG_DEBUG, "[VRR.Config] Loading economy configuration");
let economyConfig = JSON.parse(loadTextFile(`config/economy.json`));
if(economyConfig != null) {
if (economyConfig != null) {
return economyConfig;
}
}
@@ -857,14 +948,59 @@ function loadEconomyConfig() {
// ===========================================================================
function loadAccentConfig() {
logToConsole(LOG_DEBUG, "[VRR.Config] Loading accents configuration");
let accentConfig = JSON.parse(loadTextFile(`config/accents.json`));
if(accentConfig != null) {
if (accentConfig != null) {
return accentConfig;
}
}
// ===========================================================================
function loadDiscordConfig() {
logToConsole(LOG_DEBUG, "[VRR.Config] Loading discord configuration");
let discordConfig = JSON.parse(loadTextFile(`config/discord.json`));
if (discordConfig != null) {
return discordConfig;
}
return false;
}
// ===========================================================================
function loadDatabaseConfig() {
logToConsole(LOG_DEBUG, "[VRR.Config] Loading database configuration");
let databaseConfig = JSON.parse(loadTextFile("config/database.json"));
if (databaseConfig != null) {
return databaseConfig;
}
return false;
}
// ===========================================================================
function loadKeyBindConfig() {
logToConsole(LOG_DEBUG, "[VRR.Config] Loading keybind configuration");
let keyBindConfig = JSON.parse(loadTextFile("config/keybind.json"));
if (keyBindConfig != null) {
return keyBindConfig;
}
return false;
}
// ===========================================================================
function loadEmailConfig() {
logToConsole(LOG_DEBUG, "[VRR.Config] Loading email configuration");
let emailConfig = JSON.parse(loadTextFile("config/email.json"));
if (emailConfig != null) {
return emailConfig;
}
return false;
}
// ===========================================================================
function doesServerHaveGUIEnabled() {
return getServerConfig().useGUI;
}
@@ -901,7 +1037,7 @@ function doesServerHaveJobPickupsEnabled() {
// ===========================================================================
function doesServerHaveBusinesBlipsEnabled() {
function doesServerHaveBusinessBlipsEnabled() {
return getServerConfig().createBusinessBlips;
}
@@ -929,4 +1065,22 @@ function doesServerHaveGroundSnowEnabled() {
return getServerConfig().groundSnow;
}
// ===========================================================================
function getDatabaseConfig() {
return getGlobalConfig().database;
}
// ===========================================================================
function loadServerConfig() {
logToConsole(LOG_DEBUG, "[VRR.Config] Loading server configuration");
try {
serverConfig = loadServerConfigFromGameAndPort(getGame(), getServerPort());
} catch (error) {
logToConsole(LOG_ERROR, `[VRR.Config] Could not load server configuration for game ${getGame()} and port ${getServerPort}`);
thisResource.stop();
}
}
// ===========================================================================

View File

@@ -7,52 +7,69 @@
// TYPE: Server (JavaScript)
// ===========================================================================
let scriptVersion = "1.0";
let scriptVersion = "1.1";
let serverStartTime = 0;
let logLevel = LOG_INFO;
let logLevel = LOG_INFO|LOG_DEBUG|LOG_VERBOSE; // LOG_ERROR|LOG_WARN;
let playerResourceReady = new Array(server.maxClients).fill(false);
let playerResourceStarted = new Array(server.maxClients).fill(false);
let playerInitialized = new Array(server.maxClients).fill(false);
let playerGUI = new Array(server.maxClients).fill(false);
// ===========================================================================
/**
* @typedef {Object} ServerData
* @property {Array.<VehicleData>} vehicles
* @property {Array.<ClientData>} clients
* @property {Array.<BusinessData>} businesses
* @property {Array.<HouseData>} houses
* @property {Array.<HouseData>} commands
* @property {Array.<ItemData>} items
* @property {Array.<ItemTypeData>} itemTypes
* @property {Array.<ClanData>} clans
* @property {Array} localeStrings
* @property {Array.<NPCData>} npcs
* @property {Array.<RaceData>} races
* @property {Array.<JobData>} jobs
* @property {Array.<Gates>} gates
* @property {Array} groundItemCache
* @property {Array} groundPlantCache
* @property {Array} purchasingVehicleCache
* @property {Array} rentingVehicleCache
*/
let serverData = {
vehicles: [],
clients: new Array(128),
businesses: [],
houses: [],
commands: {},
groundItemCache: [],
groundPlantCache: [],
items: [],
itemTypes: [],
clans: [],
antiCheat: {
//whiteListedGameScripts: [],
//blackListedGameScripts: [],
},
localeStrings: {},
cachedTranslations: [],
cachedTranslationFrom: [],
//triggers: [],
npcs: [],
races: [],
jobs: [],
gates: [],
groundItemCache: [],
groundPlantCache: [],
purchasingVehicleCache: [],
rentingVehicleCache: [],
};
// ===========================================================================
// Pre-cache allowed skins
let allowedSkins = getAllowedSkins(getGame());
// ===========================================================================
function initServerData() {
}
// ===========================================================================
/**
*
* @return {ServerData}
*
*/
function getServerData() {
return serverData;
}
// ===========================================================================
function getModNatives() {
return modNatives;
}
// ===========================================================================

View File

@@ -15,9 +15,60 @@ let persistentDatabaseConnection = null;
function initDatabaseScript() {
logToConsole(LOG_INFO, "[VRR.Database]: Initializing database script ...");
databaseConfig = loadDatabaseConfiguration();
logToConsole(LOG_INFO, "[VRR.Database]: Database script initialized successfully!");
}
// ===========================================================================
function createDatabaseInsertQuery(tableName, data) {
let fields = [];
let values = [];
for(let i in data) {
if(data[i][1] != "undefined" && data[i][1] != NaN && data[i][0] != 'NaN') {
if(data[i][1] != "undefined" && data[i][1] != NaN && data[i][1] != 'NaN') {
fields.push(data[i][0]);
if(typeof data[i][1] == "string") {
if(data[i][1] == "{UNIXTIMESTAMP}") {
values.push("UNIX_TIMESTAMP()");
} else {
values.push(`'${data[i][1]}'`);
}
} else {
values.push(data[i][1]);
}
}
}
}
let queryString = `INSERT INTO ${tableName} (${fields.join(", ")}) VALUES (${values.join(", ")})`;
return queryString;
}
// ===========================================================================
function createDatabaseUpdateQuery(tableName, data, whereClause) {
let values = [];
for(let i in data) {
if(data[i][0] != "undefined" && data[i][0] != NaN && data[i][0] != 'NaN') {
if(data[i][1] != "undefined" && data[i][1] != NaN && data[i][1] != 'NaN') {
if(typeof data[i][1] == "string") {
if(data[i][1] == "{UNIXTIMESTAMP}") {
values.push(`${data[i][0]}=UNIX_TIMESTAMP()`);
} else {
values.push(`${data[i][0]}='${data[i][1]}'`);
}
} else {
values.push(`${data[i][0]}=${data[i][1]}`);
}
}
}
}
let queryString = `UPDATE ${tableName} SET ${values.join(", ")} WHERE ${whereClause}`;
return queryString;
}
// ===========================================================================

View File

@@ -152,7 +152,7 @@ function addLogLevelCommand(command, params, client) {
sendPlayerLogLevel(null, logLevel);
messageAdminAction(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}enabled log level {ALTCOLOUR}${toLowerCase(params)}`);
messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}enabled log level {ALTCOLOUR}${toLowerCase(params)}`);
return true;
}
@@ -222,7 +222,7 @@ function removeLogLevelCommand(command, params, client) {
sendPlayerLogLevel(null, logLevel);
messageAdminAction(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}disabled log level {ALTCOLOUR}${toLowerCase(params)}`);
messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}disabled log level {ALTCOLOUR}${toLowerCase(params)}`);
return true;
}
@@ -263,7 +263,7 @@ function simulateCommandForPlayerCommand(command, params, client) {
}
getCommand(toLowerCase(tempCommand)).handlerFunction(tempCommand, tempParams, targetClient);
messagePlayerSuccess(client, `The command string {ALTCOLOUR}/${tempCommand} ${tempParams}{MAINCOLOUR} has been simulated for {ALTCOLOUR}${targetgetPlayerName(client)}`);
messagePlayerSuccess(client, `The command string {ALTCOLOUR}/${tempCommand} ${tempParams}{MAINCOLOUR} has been simulated for {ALTCOLOUR}${getPlayerName(targetClient)}`);
return true;
}
@@ -324,8 +324,8 @@ function executeServerCodeCommand(command, params, client) {
messagePlayerSuccess(client, "Server code executed!");
messagePlayerNormal(client, `Code: ${params}`, COLOUR_YELLOW);
messagePlayerNormal(client, `Returns: ${returnValue}`, COLOUR_YELLOW);
console.log(returnValue);
messagePlayerNormal(client, `Returns: ${returnValue} (${typeof returnValue})`, COLOUR_YELLOW);
logToConsole(LOG_INFO, `Server code executed by ${getPlayerDisplayForConsole(client)}: ${params}`);
return true;
}
@@ -337,6 +337,7 @@ function executeClientCodeCommand(command, params, client) {
return false;
}
let splitParams = params.split(" ");
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let targetCode = splitParams.slice(1).join(" ");
@@ -350,10 +351,10 @@ function executeClientCodeCommand(command, params, client) {
return false;
}
sendRunCodeToClient(client, targetClient, targetCode, client.index);
sendRunCodeToClient(targetClient, targetCode, client);
messagePlayerSuccess(client, "Executing client code for " + toString(targetgetPlayerName(client)) + "!");
messagePlayerNormal(client, "Code: " + targetCode);
messagePlayerSuccess(client, `Executing client code for ${getPlayerName(targetClient)}`);
messagePlayerNormal(client, `Code: ${targetCode}`);
return true;
}
@@ -380,23 +381,87 @@ function setPlayerTesterStatusCommand(command, params, client) {
let enabled = hasBitFlag(getPlayerData(targetClient).accountData.flags.moderation, getModerationFlagValue("IsTester"));
messageAdminAction(`{ALTCOLOUR}${client.name} ${getBoolRedGreenInlineColour(enabled)}${toUpperCase(getEnabledDisabledFromBool(enabled))} {ALTCOLOUR}${targetClient.name}'s {MAINCOLOUR}tester status`)
messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} ${getBoolRedGreenInlineColour(enabled)}${toUpperCase(getEnabledDisabledFromBool(enabled))} {ALTCOLOUR}${getPlayerName(targetClient)}'s {MAINCOLOUR}tester status`)
return true;
}
// ===========================================================================
function saveAllServerDataCommand(command, params, client) {
messageAdmins(`{clanOrange}Vortrex has forced a manual save of all data. Initiating ...`);
saveAllServerDataToDatabase();
messageAdmins(`{clanOrange}All server data saved to database successfully!`);
function testPromptGUICommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let targetClient = getPlayerFromParams(params);
if(!targetClient) {
messagePlayerError(client, getLocaleString(client, "InvalidPlayer"));
return false;
}
showPlayerPromptGUI(targetClient, "Testing the two button prompt GUI", "Testing", getLocaleString(client, "Yes"), getLocaleString(client, "No"))
return true;
}
// ===========================================================================
function testInfoGUICommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let targetClient = getPlayerFromParams(params);
if(!targetClient) {
messagePlayerError(client, getLocaleString(client, "InvalidPlayer"));
return false;
}
showPlayerInfoGUI(targetClient, "Testing the info dialog GUI", "Testing", "Ok");
return true;
}
// ===========================================================================
function testErrorGUICommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let targetClient = getPlayerFromParams(params);
if(!targetClient) {
messagePlayerError(client, getLocaleString(client, "InvalidPlayer"));
return false;
}
showPlayerErrorGUI(targetClient, "Testing the error dialog GUI", "Testing", "Ok");
return true;
}
// ===========================================================================
function saveServerDataCommand(command, params, client) {
messageAdmins(`{adminOrange}Vortrex{MAINCOLOUR} has forced a manual save of all data. Initiating ...`);
saveServerDataToDatabase();
messageAdmins(`{MAINCOLOUR}All server data saved to database successfully!`);
return true;
}
// ===========================================================================
function testEmailCommand(command, params, client) {
sendEmail(params, "Player", "Test email", "Just testing the SMTP module for the server!");
try {
messagePlayerAlert(client, `Sending test email to ${params}`);
sendEmail(params, "Player", "Test email", "Just testing the SMTP module for the server!");
} catch(error) {
messagePlayerError(client, "The email could not be sent! Error: ${error}");
return false;
}
return true;
}
@@ -404,34 +469,32 @@ function testEmailCommand(command, params, client) {
function restartGameModeCommand(command, params, client) {
messagePlayerNormal(null, `The server game mode is restarting!`, getColourByName("orange"));
consoleCommand("/refresh");
thisResource.restart();
return true;
}
// ===========================================================================
function clientRunCodeFail(client, returnTo, code) {
function clientRunCodeFail(client, returnTo, error) {
let returnClient = getClientFromIndex(returnTo);
if(!returnClient) {
return false;
}
messagePlayerError(returnClient, `Client code failed to execute for ${getPlayerName(client)}!`);
messagePlayerNormal(returnClient, `Code: ${code}`, getColourByName("yellow"));
messagePlayerError(returnClient, `(${getPlayerName(client)}). Error: ${error}`);
}
// ===========================================================================
function clientRunCodeSuccess(client, returnTo, returnVal, code) {
function clientRunCodeSuccess(client, returnTo, returnVal) {
let returnClient = getClientFromIndex(returnTo);
if(!returnClient) {
return false;
}
messagePlayerSuccess(returnClient, `Client code executed for ${getPlayerName(client)}!`);
messagePlayerNormal(returnClient, `Code: ${code}`, getColourByName("yellow"));
messagePlayerNormal(returnClient, `Returns: ${returnVal}`, getColourByName("yellow"));
//messagePlayerSuccess(returnClient, `Client code executed for ${getPlayerName(client)}!`);
//messagePlayerNormal(returnClient, `Code: ${code}`, getColourByName("yellow"));
messagePlayerNormal(returnClient, `(${getPlayerName(client)}) Code returns: ${returnVal}`, getColourByName("white"));
}
// ===========================================================================
@@ -572,9 +635,9 @@ function streamAudioNameToAllPlayersCommand(command, params, client) {
// ===========================================================================
function fixAllServerBlipsCommand(command, params, client) {
deleteAllBusinessBlips();
deleteAllJobBlips();
deleteAllHouseBlips();
deleteAllBusinessBlips();
deleteAllJobBlips();
deleteAllHouseBlips();
let blips = getElementsByType(ELEMENT_BLIP);
blips.forEach((blip) => {
@@ -610,7 +673,44 @@ function resetAllServerAmbienceElementsCommand(command, params, client) {
function reloadEconomyConfigurationCommand(command, params, client) {
getGlobalConfig().economy = loadEconomyConfig();
messageAdmins(`${client.name} {MAINCOLOUR}has reloaded the economy settings`);
messageAdmins(`{adminOrange}${getPlayerName(client)} {MAINCOLOUR}has reloaded the economy settings`);
}
// ===========================================================================
function showLocalePickerTestCommand(command, params, client) {
showLocaleChooserForPlayer(client);
}
// ===========================================================================
function executeDatabaseQueryCommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
if(!targetClient) {
messagePlayerError(client, "That player was not found!");
return false;
}
if(targetCode == "") {
messagePlayerError(client, "You didn't enter any code!");
return false;
}
let success = quickDatabaseQuery(params);
if(!success) {
messagePlayerAlert(client, `Database query failed to execute: {ALTCOLOUR}${query}`);
} else if(typeof success != "boolean") {
messagePlayeSuccess(client, `Database query successful: {ALTCOLOUR}${query}`);
messagePlayerInfo(client, `Returns: ${success}`);
} else {
messagePlayerSuccess(client, `Database query successful: {ALTCOLOUR}${query}`);
}
return true;
}
// ===========================================================================

View File

@@ -16,31 +16,31 @@ function initDiscordScript() {
/*
addEventHandler("OnDiscordCommand", function(command, params, discordUser) {
let commandData = getCommand(command);
let commandData = getCommand(command);
if(!commandData) {
messagePlayerError(discordUser, "That command does not exist!");
return false;
}
if(!commandData) {
messagePlayerError(discordUser, "That command does not exist!");
return false;
}
if(isCommandAllowedOnDiscord(command)) {
messagePlayerError(discordUser, "That command can not be used on Discord!");
return false;
}
if(isCommandAllowedOnDiscord(command)) {
messagePlayerError(discordUser, "That command can not be used on Discord!");
return false;
}
if(doesClientHavePermission(discordUser, getCommandRequiredPermissions(command))) {
messagePlayerError(discordUser, "You do not have permission to use that command!");
return false;
}
if(doesClientHavePermission(discordUser, getCommandRequiredPermissions(command))) {
messagePlayerError(discordUser, "You do not have permission to use that command!");
return false;
}
commandData.handlerFunction(command, params, discordUser);
commandData.handlerFunction(command, params, discordUser);
});
*/
// ===========================================================================
function messageDiscordUser(discordUser, messageText) {
let socketData = JSON.stringify({
let socketData = JSON.stringify({
type: "chat.message.text",
payload: {
author: discordUser.name,
@@ -53,88 +53,118 @@ function messageDiscordUser(discordUser, messageText) {
// ===========================================================================
function sendDiscordSocketData(socketData) {
if(!getDiscordSocket()) {
return false;
}
if (!getDiscordSocket()) {
return false;
}
getDiscordSocket().send(module.hash.encodeBase64(socketData) + "\r\n");
getDiscordSocket().send(module.hash.encodeBase64(socketData) + "\r\n");
}
// ===========================================================================
function isClientFromDiscord(client) {
if(client == null) {
return false;
}
if (client == null) {
return false;
}
if(client instanceof Client) {
return false;
} else {
return true;
}
if (client instanceof Client) {
return false;
} else {
return true;
}
}
// ===========================================================================
function getDiscordSocket() {
return false;
return false;
}
// ===========================================================================
function getDiscordUserData(discordUserId) {
return loadAccountFromDiscordUserId(discordUserId);
return loadAccountFromDiscordUserId(discordUserId);
}
// ===========================================================================
function messageDiscordChatChannel(message) {
if(!getServerConfig().discordConfig.sendChat) {
return false;
}
function messageDiscordChatChannel(messageString) {
if (getServerConfig().devServer == true) {
return false;
}
message = removeColoursInMessage(message);
console.warn(message);
let payloadData = {
"username": "Chat",
"content": message,
};
if (!getGlobalConfig().discord.sendChat) {
return false;
}
triggerWebHook(getServerConfig().discordConfig.chatChannelWebHookURL, JSON.stringify(payloadData));
if (!getServerConfig().discord.sendChat) {
return false;
}
messageString = removeColoursInMessage(messageString);
triggerDiscordWebHook(messageString, getServerId(), VRR_DISCORD_WEBHOOK_LOG);
}
// ===========================================================================
function messageDiscordAdminChannel(message) {
if(!getServerConfig().discordConfig.sendAdminEvents) {
return false;
}
function messageDiscordEventChannel(messageString) {
if (getServerConfig().devServer == true) {
return false;
}
message = removeColoursInMessage(message);
console.warn(message);
let payloadData = {
"username": "Admin Event",
"content": message,
};
if (!getGlobalConfig().discord.sendEvents) {
return false;
}
triggerWebHook(getServerConfig().discordConfig.adminChannelWebHookURL, JSON.stringify(payloadData));
if (!getServerConfig().discord.sendEvents) {
return false;
}
messageString = removeColoursInMessage(messageString);
triggerDiscordWebHook(messageString, getServerId(), VRR_DISCORD_WEBHOOK_LOG);
}
// ===========================================================================
function messageDiscordEventChannel(message) {
if(!getServerConfig().discordConfig.sendEvents) {
return false;
}
function messageDiscordAdminChannel(messageString) {
if (getServerConfig().devServer == true) {
return false;
}
message = removeColoursInMessage(message);
console.warn(message);
let payloadData = {
"username": "Event",
"content": message,
};
if (!getGlobalConfig().discord.sendAdmin) {
return false;
}
triggerWebHook(getServerConfig().discordConfig.eventChannelWebHookURL, JSON.stringify(payloadData));
if (!getServerConfig().discord.sendAdmin) {
return false;
}
messageString = removeColoursInMessage(messageString);
triggerDiscordWebHook(messageString, getServerId(), VRR_DISCORD_WEBHOOK_ADMIN);
}
// ===========================================================================
function triggerDiscordWebHook(messageString, serverId = getServerId(), type = VRR_DISCORD_WEBHOOK_LOG) {
if (!getGlobalConfig().discord.webhook.enabled) {
return false;
}
let tempURL = getGlobalConfig().discord.webhook.webhookBaseURL;
tempURL = tempURL.replace("{0}", encodeURI(messageString));
tempURL = tempURL.replace("{1}", serverId);
tempURL = tempURL.replace("{2}", type);
tempURL = tempURL.replace("{3}", getGlobalConfig().discord.webhook.pass);
httpGet(
tempURL,
"",
function (data) {
},
function (data) {
}
);
}
// ===========================================================================

View File

@@ -15,13 +15,13 @@ function initEconomyScript() {
// ===========================================================================
function getTimeDisplayUntilPlayerPayDay(client) {
return getTimeDifferenceDisplay(sdl.ticks-getPlayerData(client).payDayTickStart);
return getTimeDifferenceDisplay(sdl.ticks - getPlayerData(client).payDayTickStart);
}
// ===========================================================================
function applyServerInflationMultiplier(value) {
return toInteger(Math.round(value*getServerConfig().inflationMultiplier))
return toInteger(Math.round(value * getServerConfig().inflationMultiplier))
}
// ===========================================================================
@@ -30,42 +30,47 @@ function playerPayDay(client) {
let wealth = calculateWealth(client);
let grossIncome = getPlayerData(client).payDayAmount;
// Passive income
grossIncome = grossIncome + getGlobalConfig().economy.passiveIncomePerPayDay;
// Passive income
grossIncome = Math.round(grossIncome + getGlobalConfig().economy.passiveIncomePerPayDay);
// Payday bonus
grossIncome = grossIncome*getGlobalConfig().economy.grossIncomeMultiplier;
// Payday bonus
grossIncome = Math.round(grossIncome * getGlobalConfig().economy.grossIncomeMultiplier);
let incomeTaxAmount = calculateIncomeTax(wealth);
// Double bonus
if (isDoubleBonusActive()) {
grossIncome = Math.round(grossIncome * 2);
}
let netIncome = grossIncome-incomeTaxAmount;
let incomeTaxAmount = Math.round(calculateIncomeTax(wealth));
let netIncome = Math.round(grossIncome - incomeTaxAmount);
messagePlayerAlert(client, "== Payday! =============================");
messagePlayerInfo(client, `Paycheck: {ALTCOLOUR}$${grossIncome}`);
messagePlayerInfo(client, `Taxes: {ALTCOLOUR}$${incomeTaxAmount}`);
messagePlayerInfo(client, `You receive: {ALTCOLOUR}$${netIncome}`);
if(netIncome < incomeTaxAmount) {
if (netIncome < incomeTaxAmount) {
let totalCash = getPlayerCash(client);
let canPayNow = totalCash+netIncome;
if(incomeTaxAmount <= canPayNow) {
let canPayNow = totalCash + netIncome;
if (incomeTaxAmount <= canPayNow) {
takePlayerCash(client, canPayNow);
messagePlayerInfo(client, `You covered the remaining taxes with {ALTCOLOUR}$${canPayNow} {MAINCOLOUR}in cash.`);
messagePlayerAlert(client, `{orange}You lost money since your taxes are more than your paycheck!`);
messagePlayerAlert(client, `{orange}If you don't have enough cash to cover taxes on next paycheck, you will lose stuff!`);
messagePlayerInfo(client, `{orange}${getLocaleString(client, "RemainingTaxPaidInCash", `{ALTCOLOUR}${canPayNow}{MAINCOLOUR}`)}`);
messagePlayerAlert(client, `{orange}${getLocaleString(client, "LostMoneyFromTaxes")}`);
messagePlayerAlert(client, `{orange}${getLocaleString(client, "NextPaycheckRepossessionWarning")}`);
} else {
messagePlayerInfo(client, `{orange}You don't have enough cash to pay your taxes!`);
messagePlayerInfo(client, `{orange}${getLocaleString(client, "NotEnoughCashForTax")}`);
takePlayerCash(client, canPayNow);
let vehicleCount = getAllVehiclesOwnedByPlayer(client).length;
let houseCount = getAllHousesOwnedByPlayer(client).length;
let businessCount = getAllBusinessesOwnedByPlayer(client).length;
attemptRepossession(client, incomeTaxAmount-canPayNow);
attemptRepossession(client, incomeTaxAmount - canPayNow);
let newVehicleCount = getAllVehiclesOwnedByPlayer(client).length;
let newHouseCount = getAllHousesOwnedByPlayer(client).length;
let newBusinessCount = getAllBusinessesOwnedByPlayer(client).length;
messagePlayerInfo(client, `{orange}You lost ${newVehicleCount-vehicleCount} vehicles, ${newHouseCount-houseCount} houses, and ${newBusinessCount-businessCount} businesses to cover the remaining tax.`);
messagePlayerInfo(client, `{orange}${getLocaleString(client, "AssetsRepossessedForTaxes", newVehicleCount - vehicleCount, newHouseCount - houseCount, newBusinessCount - businessCount)}`);
}
}
@@ -79,55 +84,55 @@ function calculateWealth(client) {
let houses = getAllHousesOwnedByPlayer(client);
let businesses = getAllBusinessesOwnedByPlayer(client);
let vehicleUpKeep = applyServerInflationMultiplier(vehicles.length*getGlobalConfig().economy.upKeepCosts.upKeepPerVehicle);
let houseUpKeep = applyServerInflationMultiplier(houses.length*getGlobalConfig().economy.upKeepCosts.upKeepPerHouse);
let businessUpKeep = applyServerInflationMultiplier(businesses.length*getGlobalConfig().economy.upKeepCosts.upKeepPerBusiness);
let vehicleUpKeep = applyServerInflationMultiplier(vehicles.length * getGlobalConfig().economy.upKeepCosts.upKeepPerVehicle);
let houseUpKeep = applyServerInflationMultiplier(houses.length * getGlobalConfig().economy.upKeepCosts.upKeepPerHouse);
let businessUpKeep = applyServerInflationMultiplier(businesses.length * getGlobalConfig().economy.upKeepCosts.upKeepPerBusiness);
return vehicleUpKeep+houseUpKeep+businessUpKeep;
return vehicleUpKeep + houseUpKeep + businessUpKeep;
}
// ===========================================================================
function calculateIncomeTax(amount) {
return amount*getGlobalConfig().economy.incomeTaxRate;
return amount * getGlobalConfig().economy.incomeTaxRate;
}
// ===========================================================================
function forcePlayerPayDayCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let targetClient = getPlayerFromParams(params);
if(!targetClient) {
if (!targetClient) {
messagePlayerError(client, "That player is not connected!");
return false;
}
messageAdmins(`${client.name} gave ${targetClient.name} an instant payday`);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} gave {ALTCOLOUR}${getPlayerName(targetClient)}{MAINCOLOUR} an instant payday`);
playerPayDay(targetClient);
}
// ===========================================================================
function setPayDayBonusMultiplier(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let newMultiplier = params;
if(isNaN(newMultiplier)) {
messagePlayerError(client, getLocaleString(client, "AmountNotNumber"));
return false;
}
if (isNaN(newMultiplier)) {
messagePlayerError(client, getLocaleString(client, "AmountNotNumber"));
return false;
}
getGlobalConfig().economy.grossIncomeMultiplier = newMultiplier;
getGlobalConfig().economy.grossIncomeMultiplier = newMultiplier;
messageAdminAction(`${client.name} set payday bonus to ${newMultiplier*100}%`);
announceAdminAction(`PaydayBonusSet`, `{adminOrange}${getPlayerName(client)}{MAINCOLOUR}`, `{ALTCOLOUR}${newMultiplier * 100}%{MAINCOLOUR}`);
}
// ===========================================================================
@@ -142,7 +147,7 @@ function taxInfoCommand(command, params, client) {
function wealthInfoCommand(command, params, client) {
let wealth = calculateWealth(client);
messagePlayerInfo(client, `Your wealth is: $${wealth}. Use {ALTCOLOUR}/help wealth {MAINCOLOUR}for more information.`);
messagePlayerInfo(client, `Your wealth is: {ALTCOLOUR}$${wealth}{MAINCOLOUR}. Use {ALTCOLOUR}/help wealth {MAINCOLOUR}for more information.`);
}
// ===========================================================================
@@ -150,28 +155,30 @@ function wealthInfoCommand(command, params, client) {
function attemptRepossession(client, totalToPay) {
let leftToPay = totalToPay;
while(leftToPay > 0) {
while (leftToPay > 0) {
let repossessionValue = repossessFirstAsset(client);
leftToPay = leftToPay - repossessionValue;
}
return true;
}
// ===========================================================================
function repossessFirstAsset(client) {
let vehicles = getAllVehiclesOwnedByPlayer(client);
if(vehicles.length > 0) {
deleteVehicle(vehicles[0])
if (vehicles.length > 0) {
deleteVehicle(vehicles[0]);
return getGlobalConfig().economy.upKeepCosts.upKeepPerVehicle;
}
let houses = getAllHousesOwnedByPlayer(client);
if(houses.length > 0) {
if (houses.length > 0) {
deleteHouse(houses[0].index);
return getGlobalConfig().economy.upKeepCosts.upKeepPerHouse;
}
let businesses = getAllBusinessesOwnedByPlayer(client);
if(businesses.length > 0) {
if (businesses.length > 0) {
deleteBusiness(businesses[0].index);
return getGlobalConfig().economy.upKeepCosts.upKeepPerBusiness;
}
@@ -193,4 +200,16 @@ function getAllBusinessesOwnedByPlayer(client) {
function getAllHousesOwnedByPlayer(client) {
return getServerData().houses.filter((h) => h.ownerType == VRR_HOUSEOWNER_PLAYER && h.ownerId == getPlayerCurrentSubAccount(client).databaseId);
}
}
// ===========================================================================
function isDoubleBonusActive() {
if (isWeekend()) {
return true;
}
return false;
}
// ===========================================================================

View File

@@ -8,47 +8,38 @@
// ===========================================================================
function initEmailScript() {
if(!checkForSMTPModule()) {
return false;
}
logToConsole(LOG_INFO, "[VRR.Email]: Initializing email script ...");
emailConfig = loadEmailConfiguration();
logToConsole(LOG_INFO, "[VRR.Email]: Email script initialized successfully!");
}
// ===========================================================================
function sendEmail(toEmail, toName, subject, body) {
if(!checkForSMTPModule()) {
return false;
}
async function sendEmail(toEmail, toName, subject, body) {
if (!checkForSMTPModule()) {
return false;
}
module.smtp.send(
getEmailConfig().smtp.host,
getEmailConfig().smtp.port,
intToBool(getEmailConfig().smtp.useTLS),
getEmailConfig().smtp.username,
getEmailConfig().smtp.password,
toEmail,
toName,
subject,
body,
getEmailConfig().smtp.from,
getEmailConfig().smtp.fromName);
}
// ===========================================================================
function loadEmailConfiguration() {
let emailConfigFile = loadTextFile("config/email.json");
return JSON.parse(emailConfigFile);
Promise.resolve().then(() => {
module.smtp.send(
getEmailConfig().smtp.host,
getEmailConfig().smtp.port,
intToBool(getEmailConfig().smtp.useTLS),
getEmailConfig().smtp.username,
getEmailConfig().smtp.password,
toEmail,
toName,
subject,
body,
getEmailConfig().smtp.from,
getEmailConfig().smtp.fromName
);
});
}
// ===========================================================================
function getEmailConfig() {
return emailConfig;
return getGlobalConfig().email;
}
// ===========================================================================

File diff suppressed because it is too large Load Diff

View File

@@ -17,71 +17,76 @@ const VRR_GATEOWNER_PUBLIC = 5; // Public gate. Technically not
const VRR_GATEOWNER_BUSINESS = 6; // Owned by a business. Back lots, unloading areas, and other stuff like that
const VRR_GATEOWNER_HOUSE = 7; // Owned by a house. Like for mansions with closed private areas.
function initGateScript() {
logToConsole(LOG_INFO, `[VRR.Gate]: Initializing gate script ...`);
logToConsole(LOG_INFO, `[VRR.Gate]: Gate script initialized successfully!`);
}
// ===========================================================================
function doesPlayerHaveGateKeys(client, vehicle) {
let gateData = getGateData(vehicle);
if(gateData.ownerType == VRR_GATEOWNER_PUBLIC) {
if (gateData.ownerType == VRR_GATEOWNER_PUBLIC) {
return true;
}
if(gateData.ownerType == VRR_GATEOWNER_PLAYER) {
if(gateData.ownerId == getPlayerCurrentSubAccount(client).databaseId) {
if (gateData.ownerType == VRR_GATEOWNER_PLAYER) {
if (gateData.ownerId == getPlayerCurrentSubAccount(client).databaseId) {
return true;
}
}
if(gateData.ownerType == VRR_GATEOWNER_CLAN) {
if(doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageClans"))) {
if (gateData.ownerType == VRR_GATEOWNER_CLAN) {
if (doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageClans"))) {
return true;
}
if(gateData.ownerId == getPlayerCurrentSubAccount(client).clan) {
if(gateData.clanRank <= getPlayerCurrentSubAccount(client).clanRank) {
if (gateData.ownerId == getPlayerCurrentSubAccount(client).clan) {
if (gateData.clanRank <= getPlayerCurrentSubAccount(client).clanRank) {
return true;
}
}
}
if(gateData.ownerType == VRR_GATEOWNER_FACTION) {
if(doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageFactions"))) {
if (gateData.ownerType == VRR_GATEOWNER_FACTION) {
if (doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageFactions"))) {
return true;
}
if(gateData.ownerId == getPlayerCurrentSubAccount(client).faction) {
if(gateData.factionRank <= getPlayerCurrentSubAccount(client).factionRank) {
if (gateData.ownerId == getPlayerCurrentSubAccount(client).faction) {
if (gateData.factionRank <= getPlayerCurrentSubAccount(client).factionRank) {
return true;
}
}
}
if(gateData.ownerType == VRR_GATEOWNER_JOB) {
if(doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageJobs"))) {
if (gateData.ownerType == VRR_GATEOWNER_JOB) {
if (doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageJobs"))) {
return true;
}
if(gateData.ownerId == getPlayerCurrentSubAccount(client).job) {
if (gateData.ownerId == getPlayerCurrentSubAccount(client).job) {
return true;
}
}
if(gateData.ownerType == VRR_GATEOWNER_BUSINESS) {
if(doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageBusinesses"))) {
if (gateData.ownerType == VRR_GATEOWNER_BUSINESS) {
if (doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageBusinesses"))) {
return true;
}
if(canPlayerManageBusiness(client, getBusinessIdFromDatabaseId(gateData.ownerId))) {
if (canPlayerManageBusiness(client, getBusinessIdFromDatabaseId(gateData.ownerId))) {
return true;
}
}
if(gateData.ownerType == VRR_GATEOWNER_HOUSE) {
if(doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageHouses"))) {
if (gateData.ownerType == VRR_GATEOWNER_HOUSE) {
if (doesPlayerHaveStaffPermission(client, getStaffFlagValue("ManageHouses"))) {
return true;
}
if(canPlayerManageHouse(client, getHouseIdFromDatabaseId(gateData.ownerId))) {
if (canPlayerManageHouse(client, getHouseIdFromDatabaseId(gateData.ownerId))) {
return true;
}
}
@@ -92,19 +97,19 @@ function doesPlayerHaveGateKeys(client, vehicle) {
// ===========================================================================
function getGateData(gateId) {
if(typeof getServerData().gates[gateId] != "undefined") {
return getServerData().gates[gateId];
}
if (typeof getServerData().gates[gateId] != "undefined") {
return getServerData().gates[gateId];
}
return false;
return false;
}
// ===========================================================================
function getClosestGate(position) {
let closest = 0;
for(let i in getServerData().gates[getServerGame()]) {
if(getDistance(getServerData().gates[i].position, position) < getDistance(getServerData().gates[closest].position, position)) {
for (let i in getServerData().gates[getGame()]) {
if (getDistance(getServerData().gates[i].position, position) < getDistance(getServerData().gates[closest].position, position)) {
closest = i;
}
}
@@ -117,11 +122,11 @@ function getClosestGate(position) {
function triggerGateCommand(command, params, client) {
let closestGate = getClosestGate(getPlayerPosition(client));
if(!getGateData(closestGate)) {
if (!getGateData(closestGate)) {
messagePlayerError(client, getLocaleString(client, "InvalidGate"));
}
if(!canPlayerUseGate(client, closestGate)) {
if (!doesPlayerHaveGateKeys(client, closestGate)) {
messagePlayerError(client, getLocaleString(client, "NoGateAccess"));
return false;
}
@@ -129,4 +134,103 @@ function triggerGateCommand(command, params, client) {
triggerGate(getGateData(closestGate).scriptName);
}
// ===========================================================================
function saveAllGatesToDatabase() {
if (getServerConfig().devServer) {
return false;
}
for (let i in getServerData().gates) {
saveGateToDatabase(i);
}
}
// ===========================================================================
function saveGateToDatabase(gateId) {
if (getGateData(gateId) == null) {
// Invalid gate data
return false;
}
let tempGateData = getGateData(gateId);
if (tempGateData.databaseId == -1) {
// Temp gate, no need to save
return false;
}
if (!tempGateData.needsSaved) {
// Gate hasn't changed. No need to save.
return false;
}
logToConsole(LOG_VERBOSE, `[VRR.Gate]: Saving gate ${tempGateData.databaseId} to database ...`);
let dbConnection = connectToDatabase();
if (dbConnection) {
let safeGateName = escapeDatabaseString(tempGateData.name);
let safeGateScriptName = escapeDatabaseString(tempGateData.scriptName);
let data = [
["gate_server", getServerId()],
["gate_name", safeGateName],
["gate_script_name", safeGateScriptName],
["gate_owner_type", toInteger(tempGateData.ownerType)],
["gate_owner_id", toInteger(tempGateData.ownerId)],
["gate_pos_x", toFloat(tempGateData.position.x)],
["gate_pos_y", toFloat(tempGateData.position.y)],
["gate_pos_z", toFloat(tempGateData.position.z)],
["gate_radius", toFloat(tempGateData.radius)],
];
let dbQuery = null;
if (tempGateData.databaseId == 0) {
let queryString = createDatabaseInsertQuery("gate_main", data);
dbQuery = queryDatabase(dbConnection, queryString);
tempGateData.databaseId = getDatabaseInsertId(dbConnection);
tempGateData.needsSaved = false;
} else {
let queryString = createDatabaseUpdateQuery("gate_main", data, `gate_id=${tempGateData.databaseId}`);
dbQuery = queryDatabase(dbConnection, queryString);
tempGateData.needsSaved = false;
}
freeDatabaseQuery(dbQuery);
disconnectFromDatabase(dbConnection);
return true;
}
logToConsole(LOG_VERBOSE, `[VRR.Gate]: Saved gate ${gateDataId} to database!`);
return true;
}
// ===========================================================================
function loadGatesFromDatabase() {
logToConsole(LOG_INFO, "[VRR.Gate]: Loading gates from database ...");
let tempGates = [];
let dbConnection = connectToDatabase();
let dbAssoc;
if (dbConnection) {
let dbQuery = queryDatabase(dbConnection, `SELECT * FROM gate_main WHERE gate_server = ${getServerId()}`);
if (dbQuery) {
if (dbQuery.numRows > 0) {
while (dbAssoc = fetchQueryAssoc(dbQuery)) {
let tempGateData = new GateData(dbAssoc);
tempGates.push(tempGateData);
logToConsole(LOG_DEBUG, `[VRR.Gate]: Gate '${tempGateData.name}' loaded from database successfully!`);
}
}
freeDatabaseQuery(dbQuery);
}
disconnectFromDatabase(dbConnection);
}
logToConsole(LOG_INFO, `[VRR.Gate]: ${tempGates.length} gates loaded from database successfully!`);
return tempGates;
}
// ===========================================================================

View File

@@ -22,121 +22,251 @@ function initGUIScript() {
// ===========================================================================
function playerPromptAnswerNo(client) {
if(getPlayerData(client).promptType == VRR_PROMPT_NONE) {
return false;
}
if (getPlayerData(client).promptType == VRR_PROMPT_NONE) {
return false;
}
logToConsole(LOG_DEBUG, `[VRR.GUI] ${getPlayerDisplayForConsole(client)} answered NO to their prompt (${getPlayerData(client).promptType})`);
logToConsole(LOG_DEBUG, `[VRR.GUI] ${getPlayerDisplayForConsole(client)} answered NO to their prompt (${getPlayerData(client).promptType})`);
switch(getPlayerData(client).promptType) {
case VRR_PROMPT_CREATEFIRSTCHAR:
logToConsole(LOG_DEBUG, `${getPlayerDisplayForConsole(client)} chose not to create a first character. Kicking them from the server ...`);
showPlayerErrorGUI(client, "You don't have a character to play. Goodbye!", "No Characters");
setTimeout(function() { client.disconnect(); }, 5000);
break;
switch (getPlayerData(client).promptType) {
case VRR_PROMPT_CREATEFIRSTCHAR:
logToConsole(LOG_DEBUG, `${getPlayerDisplayForConsole(client)} chose not to create a first character. Kicking them from the server ...`);
showPlayerErrorGUI(client, "You don't have a character to play. Goodbye!", "No Characters");
getPlayerData(targetClient).customDisconnectReason = `Kicked - Didn't create a character`;
setTimeout(function () { disconnectPlayer(client); }, 5000);
break;
case VRR_PROMPT_BIZORDER:
if(getPlayerData(client).businessOrderAmount > 0) {
if(canPlayerUseGUI(client)) {
showPlayerErrorGUI(client, "You canceled the order.", "Business Order Canceled");
} else {
logToConsole(LOG_DEBUG, `${getPlayerDisplayForConsole(client)} canceled the order of ${getPlayerData(client).businessOrderAmount} ${getPlayerData(client).businessOrderItem} at ${getPlayerData(client).businessOrderCost/getPlayerData(client).businessOrderAmount} each for business ${getBusinessData(getPlayerData(client).businessOrderBusiness)}`);
messagePlayerError(client, "You canceled the order!");
}
} else {
showPlayerErrorGUI(client, "You aren't ordering anything for a business!", "Business Order Canceled");
}
break;
case VRR_PROMPT_BIZORDER:
if (getPlayerData(client).businessOrderAmount > 0) {
if (canPlayerUseGUI(client)) {
showPlayerErrorGUI(client, "You canceled the order.", "Business Order Canceled");
} else {
logToConsole(LOG_DEBUG, `${getPlayerDisplayForConsole(client)} canceled the order of ${getPlayerData(client).businessOrderAmount} ${getPlayerData(client).businessOrderItem} at ${getPlayerData(client).businessOrderCost / getPlayerData(client).businessOrderAmount} each for business ${getBusinessData(getPlayerData(client).businessOrderBusiness)}`);
messagePlayerError(client, "You canceled the order!");
}
} else {
showPlayerErrorGUI(client, "You aren't ordering anything for a business!", "Business Order Canceled");
}
break;
default:
break;
}
default:
break;
}
getPlayerData(client).promptType = VRR_PROMPT_NONE;
getPlayerData(client).promptType = VRR_PROMPT_NONE;
}
// ===========================================================================
function playerPromptAnswerYes(client) {
if(getPlayerData(client).promptType == VRR_PROMPT_NONE) {
return false;
}
if (getPlayerData(client).promptType == VRR_PROMPT_NONE) {
return false;
}
logToConsole(LOG_DEBUG, `[VRR.GUI] ${getPlayerDisplayForConsole(client)} answered YES to their prompt (${getPlayerData(client).promptType})`);
logToConsole(LOG_DEBUG, `[VRR.GUI] ${getPlayerDisplayForConsole(client)} answered YES to their prompt (${getPlayerData(client).promptType})`);
switch(getPlayerData(client).promptType) {
case VRR_PROMPT_CREATEFIRSTCHAR:
showPlayerNewCharacterGUI(client);
break;
switch (getPlayerData(client).promptType) {
case VRR_PROMPT_CREATEFIRSTCHAR: {
showPlayerNewCharacterGUI(client);
break;
}
case VRR_PROMPT_BIZORDER:
if(getPlayerData(client).businessOrderAmount > 0) {
if(getBusinessData(getPlayerData(client).businessOrderBusiness).till < getPlayerData(client).businessOrderCost) {
logToConsole(LOG_DEBUG, `[VRR.GUI] ${getPlayerDisplayForConsole(client)} failed to order ${getPlayerData(client).businessOrderAmount} ${getItemTypeData(getPlayerData(client).businessOrderItem).name} at ${getPlayerData(client).businessOrderCost/getPlayerData(client).businessOrderAmount} each for business ${getBusinessData(getPlayerData(client).businessOrderBusiness).name} (Reason: Not enough money in business till)`);
showPlayerErrorGUI(client, "This business doesn't have enough money! Deposit some using /bizdeposit", "Business Order Canceled");
getPlayerData(client).businessOrderAmount = 0;
getPlayerData(client).businessOrderBusiness = false;
getPlayerData(client).businessOrderItem = -1;
getPlayerData(client).businessOrderValue = -1;
} else {
logToConsole(LOG_DEBUG, `[VRR.GUI] ${getPlayerDisplayForConsole(client)} successfully ordered ${getPlayerData(client).businessOrderAmount} ${getItemTypeData(getPlayerData(client).businessOrderItem).name} at ${getPlayerData(client).businessOrderCost/getPlayerData(client).businessOrderAmount} each for business ${getBusinessData(getPlayerData(client).businessOrderBusiness).name}`);
showPlayerInfoGUI(client, `You ordered ${getPlayerData(client).businessOrderAmount} ${getItemTypeData(getPlayerData(client).businessOrderItem).name} (${getItemValueDisplay(getPlayerData(client).businessOrderItem, getPlayerData(client).businessOrderValue)}) for ${getPlayerData(client).businessOrderCost}!`, "Business Order Successful");
createItem(getPlayerData(client).businessOrderItem, getPlayerData(client).businessOrderValue, VRR_ITEM_OWNER_BIZFLOOR, getBusinessData(getPlayerData(client).businessOrderBusiness).databaseId, getPlayerData(client).businessOrderAmount);
cacheBusinessItems(getPlayerData(client).businessOrderBusiness);
getBusinessData(getPlayerData(client).businessOrderBusiness).till -= getPlayerData(client).businessOrderCost;
updateBusinessPickupLabelData(getPlayerData(client).businessOrderBusiness);
getPlayerData(client).businessOrderAmount = 0;
getPlayerData(client).businessOrderBusiness = false;
getPlayerData(client).businessOrderItem = -1;
getPlayerData(client).businessOrderValue = -1;
case VRR_PROMPT_BIZORDER: {
if (getPlayerData(client).businessOrderAmount > 0) {
if (getBusinessData(getPlayerData(client).businessOrderBusiness).till < getPlayerData(client).businessOrderCost) {
logToConsole(LOG_DEBUG, `[VRR.GUI] ${getPlayerDisplayForConsole(client)} failed to order ${getPlayerData(client).businessOrderAmount} ${getItemTypeData(getPlayerData(client).businessOrderItem).name} at ${getPlayerData(client).businessOrderCost / getPlayerData(client).businessOrderAmount} each for business ${getBusinessData(getPlayerData(client).businessOrderBusiness).name} (Reason: Not enough money in business till)`);
showPlayerErrorGUI(client, "This business doesn't have enough money! Deposit some using /bizdeposit", "Business Order Canceled");
getPlayerData(client).businessOrderAmount = 0;
getPlayerData(client).businessOrderBusiness = false;
getPlayerData(client).businessOrderItem = -1;
getPlayerData(client).businessOrderValue = -1;
} else {
logToConsole(LOG_DEBUG, `[VRR.GUI] ${getPlayerDisplayForConsole(client)} successfully ordered ${getPlayerData(client).businessOrderAmount} ${getItemTypeData(getPlayerData(client).businessOrderItem).name} at ${getPlayerData(client).businessOrderCost / getPlayerData(client).businessOrderAmount} each for business ${getBusinessData(getPlayerData(client).businessOrderBusiness).name}`);
showPlayerInfoGUI(client, `You ordered ${getPlayerData(client).businessOrderAmount} ${getItemTypeData(getPlayerData(client).businessOrderItem).name} (${getItemValueDisplay(getPlayerData(client).businessOrderItem, getPlayerData(client).businessOrderValue)}) for ${getPlayerData(client).businessOrderCost}!`, "Business Order Successful");
createItem(getPlayerData(client).businessOrderItem, getPlayerData(client).businessOrderValue, VRR_ITEM_OWNER_BIZFLOOR, getBusinessData(getPlayerData(client).businessOrderBusiness).databaseId, getPlayerData(client).businessOrderAmount);
cacheBusinessItems(getPlayerData(client).businessOrderBusiness);
getBusinessData(getPlayerData(client).businessOrderBusiness).till -= getPlayerData(client).businessOrderCost;
updateBusinessPickupLabelData(getPlayerData(client).businessOrderBusiness);
getPlayerData(client).businessOrderAmount = 0;
getPlayerData(client).businessOrderBusiness = false;
getPlayerData(client).businessOrderItem = -1;
getPlayerData(client).businessOrderValue = -1;
}
} else {
showPlayerErrorGUI(client, ``, `Business Order Canceled`);
}
break;
}
}
} else {
showPlayerErrorGUI(client, `You aren't ordering anything for a business!`, `Business Order Canceled`);
}
break;
case VRR_PROMPT_GIVEVEHTOCLAN: {
if (!isPlayerInAnyVehicle(client)) {
messagePlayerError(client, getLocaleString(client, "MustBeInVehicle"));
return false;
}
default:
break;
}
if (!getVehicleData(getPlayerVehicle(client))) {
messagePlayerError(client, getLocaleString(client, "RandomVehicleCommandsDisabled"));
return false;
}
getPlayerData(client).promptType = VRR_PROMPT_NONE;
if (getVehicleData(getPlayerVehicle(client)).ownerType != VRR_VEHOWNER_PLAYER) {
messagePlayerError(client, getLocaleString(client, "MustOwnVehicle"));
return false;
}
if (getVehicleData(getPlayerVehicle(client)).ownerId != getPlayerCurrentSubAccount(client).databaseId) {
messagePlayerError(client, getLocaleString(client, "MustOwnVehicle"));
return false;
}
getVehicleData(getPlayerVehicle(client)).ownerType = VRR_VEHOWNER_CLAN;
getVehicleData(getPlayerVehicle(client)).ownerId = getPlayerCurrentSubAccount(client).clan;
messagePlayerSuccess(client, getLocaleString(client, "GaveVehicleToClan", getVehicleName(getPlayerVehicle(client))));
//messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}set their {vehiclePurple}${getVehicleName(vehicle)} {MAINCOLOUR}owner to the {clanOrange}${getClanData(clanId).name} {MAINCOLOUR}clan`);
break;
}
case VRR_PROMPT_GIVEHOUSETOCLAN: {
let houseId = getPlayerHouse(client);
if (!houseId) {
messagePlayerError(client, getLocaleString(client, "InvalidHouse"));
return false;
}
if (getHouseData(houseId).ownerType != VRR_VEHOWNER_PLAYER) {
messagePlayerError(client, getLocaleString(client, "MustOwnHouse"));
return false;
}
if (getHouseData(houseId).ownerId != getPlayerCurrentSubAccount(client).databaseId) {
messagePlayerError(client, getLocaleString(client, "MustOwnHouse"));
return false;
}
getHouseData(houseId).ownerType = VRR_HOUSEOWNER_CLAN;
getHouseData(houseId).ownerId = getPlayerCurrentSubAccount(client).clan;
messagePlayerSuccess(client, getLocaleString(client, "GaveHouseToClan"));
//messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}set their {vehiclePurple}${getVehicleName(vehicle)} {MAINCOLOUR}owner to the {clanOrange}${getClanData(clanId).name} {MAINCOLOUR}clan`);
break;
}
case VRR_PROMPT_GIVEBIZTOCLAN: {
let businessId = getPlayerBusiness(client);
if (!businessId) {
messagePlayerError(client, getLocaleString(client, "InvalidBusiness"));
return false;
}
if (getBusinessData(businessId).ownerType != VRR_VEHOWNER_PLAYER) {
messagePlayerError(client, getLocaleString(client, "MustOwnBusiness"));
return false;
}
if (getBusinessData(businessId).ownerId != getPlayerCurrentSubAccount(client).databaseId) {
messagePlayerError(client, getLocaleString(client, "MustOwnBusiness"));
return false;
}
getBusinessData(businessId).ownerType = VRR_BIZOWNER_CLAN;
getBusinessData(businessId).ownerId = getPlayerCurrentSubAccount(client).clan;
messagePlayerSuccess(client, getLocaleString(client, "GaveBusinessToClan"));
//messageAdmins(`{ALTCOLOUR}${getPlayerName(client)} {MAINCOLOUR}set their {vehiclePurple}${getVehicleName(vehicle)} {MAINCOLOUR}owner to the {clanOrange}${getClanData(clanId).name} {MAINCOLOUR}clan`);
break;
}
case VRR_PROMPT_BUYHOUSE: {
let houseId = getPlayerHouse(client);
if (!houseId) {
messagePlayerError(client, getLocaleString(client, "InvalidHouse"));
return false;
}
if (getHouseData(houseId).buyPrice <= 0) {
messagePlayerError(client, getLocaleString(client, "HouseNotForSale"));
return false;
}
if (getPlayerCurrentSubAccount(client).cash < getHouseData(houseId).buyPrice) {
messagePlayerError(client, getLocaleString(client, "HousePurchaseNotEnoughMoney"));
return false;
}
getHouseData(houseId).ownerType = VRR_HOUSEOWNER_PLAYER;
getHouseData(houseId).ownerId = getPlayerCurrentSubAccount(client).databaseId;
getHouseData(houseId).buyPrice = 0;
getHouseData(houseId).needsSaved = true;
updateHousePickupLabelData(houseId);
messageDiscordEventChannel(`🏘️ ${getCharacterFullName(client)} is now the owner of *${getHouseData(houseId).description}*!`);
messagePlayerSuccess(client, `🏘️ You are now the owner of {houseGreen}${getHouseData(houseId).description}`);
break;
}
case VRR_PROMPT_BUYBIZ: {
let businessId = getPlayerBusiness(client);
if (!businessId) {
messagePlayerError(client, getLocaleString(client, "InvalidBusiness"));
return false;
}
if (getBusinessData(businessId).buyPrice <= 0) {
messagePlayerError(client, getLocaleString(client, "BusinessNotForSale"));
return false;
}
if (getPlayerCurrentSubAccount(client).cash < getBusinessData(businessId).buyPrice) {
messagePlayerError(client, getLocaleString(client, "BusinessPurchaseNotEnoughMoney"));
return false;
}
getBusinessData(businessId).ownerType = VRR_BIZOWNER_PLAYER;
getBusinessData(businessId).ownerId = getPlayerCurrentSubAccount(client).databaseId;
getBusinessData(businessId).buyPrice = 0;
getBusinessData(businessId).needsSaved = true;
updateBusinessPickupLabelData(businessId);
messageDiscordEventChannel(`🏢 ${getCharacterFullName(client)} is now the owner of *${getBusinessData(businessId).name}*!`);
messagePlayerSuccess(client, `🏢 You are now the owner of {businessBlue}${getBusinessData(businessId).name}`);
break;
}
default: {
submitBugReport(client, `[AUTOMATED REPORT] Unknown prompt type: ${getPlayerData(client).promptType}`);
break;
}
}
getPlayerData(client).promptType = VRR_PROMPT_NONE;
}
// ===========================================================================
function canPlayerUseGUI(client) {
return (doesServerHaveGUIEnabled() && doesPlayerHaveGUIEnabled(client));
return (doesServerHaveGUIEnabled() && doesPlayerHaveGUIEnabled(client));
}
// ===========================================================================
function playerPromptAnswerYesCommand(command, params, client) {
playerPromptAnswerYes(client);
playerPromptAnswerYes(client);
}
// ===========================================================================
function playerPromptAnswerNoCommand(command, params, client) {
playerPromptAnswerNo(client);
playerPromptAnswerNo(client);
}
// ===========================================================================
function playerToggledGUI(client) {
toggleAccountGUICommand("gui", "", client);
}
// ===========================================================================
function showPlayerChangePasswordGUI(client) {
sendNetworkEventToPlayer("vrr.changePassword", client);
toggleAccountGUICommand("gui", "", client);
}
// ===========================================================================
function showPlayerTwoFactorAuthenticationGUI(client) {
sendNetworkEventToPlayer("vrr.2fa", client);
sendNetworkEventToPlayer("vrr.2fa", client);
}
// ===========================================================================

View File

@@ -15,144 +15,144 @@ function initHelpScript() {
// ===========================================================================
let randomTips = [
`{MAINCOLOUR}Look for yellow dots on your map for job locations.`,
`{MAINCOLOUR}You can set custom key binds. Use {ALTCOLOUR}/help keys {MAINCOLOUR} for details.`,
`{MAINCOLOUR}Use /notips if you don't want to see tips and extra information`,
`{MAINCOLOUR}You can edit your keybinds using {ALTCOLOUR}/bindkey and /unbindkey`,
`{MAINCOLOUR}Press to see your inventory, and use number keys to select an item`,
`{MAINCOLOUR}Use /buy at a business to purchase items.`,
`{MAINCOLOUR}Found a bug? Report it with {ALTCOLOUR}/bug`,
`{MAINCOLOUR}Have an idea or suggestion for the server? Let the devs know using {ALTCOLOUR}/idea`,
`{MAINCOLOUR}Want to buy a business? Use /bizbuy at one for sale`,
`{MAINCOLOUR}Want to buy a house? Use /housebuy at one for sale`,
`{MAINCOLOUR}Want to buy a vehicle? Visit a dealership and enter one for info on how to buy it!`,
`{MAINCOLOUR}Switch to any of your characters with {ALTCOLOUR}/switchchar`,
`{MAINCOLOUR}Use {ALTCOLOUR}/iplogin {MAINCOLOUR}to automatically login when connecting with the same IP`,
`{MAINCOLOUR}Use {ALTCOLOUR}/houselights or /bizlights {MAINCOLOUR}to turn on/off the lights in your house or business`,
`{MAINCOLOUR}Use {ALTCOLOUR}/radiostation {MAINCOLOUR}to play an internet radio station in your car, house, or business`,
//`{MAINCOLOUR}Lower your car windows with /windows {ALTCOLOUR} to play the vehicle's internet radio station {ALTCOLOUR}(/radiostation) {MAINCOLOUR}to nearby players`,
//`{MAINCOLOUR}Lower your car windows with /windows {ALTCOLOUR} to play the vehicle's internet radio station {ALTCOLOUR}(/radiostation) {MAINCOLOUR}to nearby players`,
//`{MAINCOLOUR}Tax is based on your total wealth. This includes money, vehicles, businesses and more.`,
//`{MAINCOLOUR}Don't go broke because of a hospital bill! Get insured today by visiting an insurance agency!`,
//`{MAINCOLOUR}Don't go broke because your car was destroyed. Visit an insurance agency today!`,
//`{MAINCOLOUR}You can find most locations by using {ALTCOLOUR}/gps`,
//`{MAINCOLOUR}Want to advertise your business? Visit the news station and place an /ad today!`,
//`{MAINCOLOUR}You can change your quick item display. Choices are GTAV-style pie menu or Minecraft-style hotbar`,
//`{MAINCOLOUR}Hold [#0066FF]E {MAINCOLOUR}to hail a nearby taxi if you need a ride.`,
//`{MAINCOLOUR}Press [#0066FF]G {MAINCOLOUR}to enter a vehicle as passenger.`,
//`{MAINCOLOUR}Banks can provide loans. Use {ALTCOLOUR}/help loans {MAINCOLOUR} for more details.`,
`{MAINCOLOUR}Want to make a clan? Use {ALTCOLOUR}/help clans {MAINCOLOUR} for details.`,
`{MAINCOLOUR}Legal weapons can be purchased at any ammunation.`,
`{MAINCOLOUR}Look for yellow dots on your map for job locations.`,
`{MAINCOLOUR}You can set custom key binds. Use {ALTCOLOUR}/info keys {MAINCOLOUR} for details.`,
`{MAINCOLOUR}Use /notips if you don't want to see tips and extra information`,
`{MAINCOLOUR}You can edit your keybinds using {ALTCOLOUR}/bindkey and /unbindkey`,
`{MAINCOLOUR}Press to see your inventory, and use number keys to select an item`,
`{MAINCOLOUR}Use /buy at a business to purchase items.`,
`{MAINCOLOUR}Found a bug? Report it with {ALTCOLOUR}/bug`,
`{MAINCOLOUR}Have an idea or suggestion for the server? Let the devs know using {ALTCOLOUR}/idea`,
`{MAINCOLOUR}Want to buy a business? Use /bizbuy at one for sale`,
`{MAINCOLOUR}Want to buy a house? Use /housebuy at one for sale`,
`{MAINCOLOUR}Want to buy a vehicle? Visit a dealership and enter one for info on how to buy it!`,
`{MAINCOLOUR}Switch to any of your characters with {ALTCOLOUR}/switchchar`,
`{MAINCOLOUR}Use {ALTCOLOUR}/iplogin {MAINCOLOUR}to automatically login when connecting with the same IP`,
`{MAINCOLOUR}Use {ALTCOLOUR}/houselights or /bizlights {MAINCOLOUR}to turn on/off the lights in your house or business`,
`{MAINCOLOUR}Use {ALTCOLOUR}/radiostation {MAINCOLOUR}to play an internet radio station in your car, house, or business`,
//`{MAINCOLOUR}Lower your car windows with /windows {ALTCOLOUR} to play the vehicle's internet radio station {ALTCOLOUR}(/radiostation) {MAINCOLOUR}to nearby players`,
//`{MAINCOLOUR}Lower your car windows with /windows {ALTCOLOUR} to play the vehicle's internet radio station {ALTCOLOUR}(/radiostation) {MAINCOLOUR}to nearby players`,
//`{MAINCOLOUR}Tax is based on your total wealth. This includes money, vehicles, businesses and more.`,
//`{MAINCOLOUR}Don't go broke because of a hospital bill! Get insured today by visiting an insurance agency!`,
//`{MAINCOLOUR}Don't go broke because your car was destroyed. Visit an insurance agency today!`,
//`{MAINCOLOUR}You can find most locations by using {ALTCOLOUR}/gps`,
//`{MAINCOLOUR}Want to advertise your business? Visit the news station and place an /ad today!`,
//`{MAINCOLOUR}You can change your quick item display. Choices are GTAV-style pie menu or Minecraft-style hotbar`,
//`{MAINCOLOUR}Hold [#0066FF]E {MAINCOLOUR}to hail a nearby taxi if you need a ride.`,
//`{MAINCOLOUR}Press [#0066FF]G {MAINCOLOUR}to enter a vehicle as passenger.`,
//`{MAINCOLOUR}Banks can provide loans. Use {ALTCOLOUR}/info loans {MAINCOLOUR} for more details.`,
`{MAINCOLOUR}Want to make a clan? Use {ALTCOLOUR}/info clans {MAINCOLOUR} for details.`,
`{MAINCOLOUR}Legal weapons can be purchased at any ammunation.`,
];
// ===========================================================================
function helpCommand(command, params, client) {
if(areParamsEmpty(params)) {
showMainHelpMessage(client);
return false;
}
showMainHelpMessage(client);
return false;
}
let splitParams = params.split(" ");
let splitParams = params.split(" ");
switch(toLowerCase(getParam(params, " ", 1))) {
case "account":
showAccountHelpMessage(client);
break;
switch(toLowerCase(getParam(params, " ", 1))) {
case "account":
showAccountHelpMessage(client);
break;
case "vehicle":
case "veh":
case "vehs":
case "vehicles":
case "car":
case "cars":
showVehicleHelpMessage(client);
break;
case "vehicle":
case "veh":
case "vehs":
case "vehicles":
case "car":
case "cars":
showVehicleHelpMessage(client);
break;
case "dealership":
showVehicleDealershipHelpMessage(client);
break;
case "dealership":
showVehicleDealershipHelpMessage(client);
break;
case "business":
showBusinessHelpMessage(client);
break;
case "business":
showBusinessHelpMessage(client);
break;
case "job":
showJobHelpMessage(client);
break;
case "job":
showJobHelpMessage(client);
break;
case "chat":
showChatHelpMessage(client);
break;
case "chat":
showChatHelpMessage(client);
break;
case "rules":
showRulesHelpMessage(client);
break;
case "rules":
showRulesHelpMessage(client);
break;
case "website":
showWebsiteHelpMessage(client);
break;
case "website":
showWebsiteHelpMessage(client);
break;
case "discord":
showDiscordHelpMessage(client);
break;
case "discord":
showDiscordHelpMessage(client);
break;
case "anim":
case "anims":
case "animation":
case "animations":
showAnimationHelpMessage(client);
break;
case "anim":
case "anims":
case "animation":
case "animations":
showAnimationHelpMessage(client);
break;
case "skin":
case "skins":
case "clothes":
showClothesHelpMessage(client);
break;
case "skin":
case "skins":
case "clothes":
showClothesHelpMessage(client);
break;
case "key":
case "keys":
case "keybinds":
case "keybind":
case "bindkey":
case "bindkeys":
showBindKeysHelpMessage(client);
break;
case "key":
case "keys":
case "keybinds":
case "keybind":
case "bindkey":
case "bindkeys":
showBindKeysHelpMessage(client);
break;
case "command":
case "cmd":
showCommandHelpMessage(client, getParam(params, " ", 2));
break;
case "command":
case "cmd":
showCommandHelpMessage(client, getParam(params, " ", 2));
break;
case "clan":
case "clans":
case "group":
case "groups":
case "faction":
case "factions":
case "family":
case "families":
showClanHelpMessage(client);
break;
case "clan":
case "clans":
case "group":
case "groups":
case "faction":
case "factions":
case "family":
case "families":
showClanHelpMessage(client);
break;
case "radio":
case "radiostations":
case "music":
showRadioHelpMessage(client);
break;
case "radio":
case "radiostations":
case "music":
showRadioHelpMessage(client);
break;
case "economy":
case "wealth":
case "tax":
case "taxes":
case "payday":
showWealthAndTaxHelpMessage(client);
break;
case "economy":
case "wealth":
case "tax":
case "taxes":
case "payday":
showWealthAndTaxHelpMessage(client);
break;
default:
showMainHelpMessage(client);
break;
}
default:
showMainHelpMessage(client);
break;
}
}
// == Account Help =============================
@@ -184,188 +184,188 @@ function helpCommand(command, params, client) {
// ===========================================================================
function showMainHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderHelpMainList")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Use /help <category> for commands and info. Example: {ALTCOLOUR}/help vehicle`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Help Categories: [#A9A9A9]account, command, vehicle, job, chat, rules, website, animation`);
messagePlayerNormal(client, `{clanOrange}• [#A9A9A9]skin, mechanic, dealership, discord, colour, keybind`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HelpMainListHeader")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Use /info <category> for commands and info. Example: {ALTCOLOUR}/info vehicle`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Help Categories: [#A9A9A9]account, command, vehicle, job, chat, rules, website, animation`);
messagePlayerNormal(client, `{clanOrange}• [#A9A9A9]skin, mechanic, dealership, discord, colour, keybind`);
}
// ===========================================================================
function showAccountHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderAccountHelp")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Do not share your password with anybody else.`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Use {ALTCOLOUR}/changepass{MAINCOLOUR} to change your password.`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Some settings you can use: {ALTCOLOUR}/gui, /logo, /iplogin, /autolastchar, /2fa, /loginalert`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderAccountHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AccountHelp", 0));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AccountHelp", 1, `{ALTCOLOUR}/changepass{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AccountHelp", 2, `{ALTCOLOUR}/gui, /logo, /iplogin, /autolastchar, /2fa, /loginalert{MAINCOLOUR}`));
}
// ===========================================================================
function showVehicleHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderVehicleHelp")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Visit dealerships to buy new vehicles (Use {ALTCOLOUR}/help dealership {MAINCOLOUR}for more info.)`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Some commands: {ALTCOLOUR}/lock, /engine, /lights, /trunk, /rentveh, /buyveh, /rentprice, /buyprice`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Your personal vehicles will save wherever you or somebody else leaves them!`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Visit a mechanic garage to repair, colour, and tune up your car! {ALTCOLOUR}/help mechanic {MAINCOLOUR} for info`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Don't forget to register and insure your vehicle! Use {ALTCOLOUR}/gps {MAINCOLOUR}to find a DMV for this.`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderVehicleHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "VehicleHelp", 0, `{ALTCOLOUR}/info dealership{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "VehicleHelp", 1, `{ALTCOLOUR}/lock, /engine, /lights, /trunk, /rentveh, /buyveh, /rentprice, /buyprice{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "VehicleHelp", 2));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "VehicleHelp", 3, `{ALTCOLOUR}/info mechanic{MAINCOLOUR}`));
}
// ===========================================================================
function showVehicleDealershipHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderVehicleDealershipHelp")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Visit a vehicle dealer to buy new vehicles. Use {ALTCOLOUR}/gps {MAINCOLOUR}to find one.`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}At the dealer, simply enter a car you want to buy, and the price will be shown to you`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}If you want to buy the vehicle and have enough money, use {ALTCOLOUR}/buyveh {MAINCOLOUR}and you will be given keys`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}A new car for sale will appear when you drive away from the dealer.`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderVehicleDealershipHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "VehicleDealershipHelp", 0, `{ALTCOLOUR}/gps{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "VehicleDealershipHelp", 1));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "VehicleDealershipHelp", 1, `{ALTCOLOUR}/buyveh{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "VehicleDealershipHelp", 2));
}
// ===========================================================================
function showJobHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderJobHelp")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Visit job locations get a job and earn money. Look for yellow spots on the map`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}At a job location, use {ALTCOLOUR}/takejob {MAINCOLOUR}to get the job. Use {ALTCOLOUR}/quitjob {MAINCOLOUR}to quit your job`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Use {ALTCOLOUR}/startwork {MAINCOLOUR}to begin working. You can also get a job {ALTCOLOUR}/uniform and {ALTCOLOUR}/equipment`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Most job vehicles are locked. Use {ALTCOLOUR}/lock {MAINCOLOUR}near one to enter it.`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}When entering a job vehicle, information on how to do the job will be shown to you.`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderJobHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "JobHelp", 0));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "JobHelp", 1, `{ALTCOLOUR}/takejob{MAINCOLOUR}`, `{ALTCOLOUR}/quitjob{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "JobHelp", 2, `{ALTCOLOUR}/lock{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "JobHelp", 3));
}
// ===========================================================================
function showChatHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderChatHelp")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}There are two main types of chat: out-of-character (OOC) and in-character (IC)`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Mixing these two types is not proper roleplay. See {ALTCOLOUR}/rules {MAINCOLOUR}for info.`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Some chat commands: {ALTCOLOUR}/dm /whisper /talk /shout /me.`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Some have shorter names available ({ALTCOLOUR}/t {MAINCOLOUR}for talk, {ALTCOLOUR}/s {MAINCOLOUR}for shout, etc)`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderChatHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ChatHelp", 0, `{ALTCOLOUR}/buy {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ChatHelp", 1, `{ALTCOLOUR}/rules{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ChatHelp", 2, `{ALTCOLOUR}/dm /whisper /talk /shout /me{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ChatHelp", 3, `{ALTCOLOUR}/t{MAINCOLOUR}`, `{ALTCOLOUR}/s{MAINCOLOUR}`));
}
// ===========================================================================
function showRulesHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderServerRulesList")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 0));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 1));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 2));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 3));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 4), `{ALTCOLOUR}/help language {MAINCOLOUR}`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderServerRulesList")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 0));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 1));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 2));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 3));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RulesHelp", 4), `{ALTCOLOUR}/info language {MAINCOLOUR}`);
}
// ===========================================================================
function showWebsiteHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderWebsiteInfo")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}${server.getRule("Website")}`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderWebsiteInfo")));
messagePlayerHelpContent(client, `{MAINCOLOUR}${server.getRule("Website")}`);
}
// ===========================================================================
function showDiscordHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderDiscordInfo")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}${server.getRule("Website")}`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderDiscordInfo")));
messagePlayerHelpContent(client, `{MAINCOLOUR}${server.getRule("Discord")}`);
}
// ===========================================================================
function showAnimationHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderAnimationHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AnimationHelp", 0, `{ALTCOLOUR}/buy {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AnimationHelp", 1, `{ALTCOLOUR}/an {MAINCOLOUR}`, `{ALTCOLOUR}/anim {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AnimationHelp", 2, `{ALTCOLOUR}/animlist {MAINCOLOUR}`));
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderAnimationHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AnimationHelp", 0, `{ALTCOLOUR}/buy {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AnimationHelp", 1, `{ALTCOLOUR}/an {MAINCOLOUR}`, `{ALTCOLOUR}/anim {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "AnimationHelp", 2, `{ALTCOLOUR}/animlist {MAINCOLOUR}`));
}
// ===========================================================================
function showClothesHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderSkinHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "SkinHelp", 0, `{ALTCOLOUR}/buy {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "SkinHelp", 1, `{ALTCOLOUR}/help items {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "SkinHelp", 2));
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderSkinHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "SkinHelp", 0, `{ALTCOLOUR}/buy {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "SkinHelp", 1, `{ALTCOLOUR}/info items {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "SkinHelp", 2));
}
// ===========================================================================
function showBindKeysHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderBindableKeysHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 0, `{ALTCOLOUR}/keybinds {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 1, `{ALTCOLOUR}/bindkey {MAINCOLOUR}`, `{ALTCOLOUR}/unbindkey {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 2, `{ALTCOLOUR}K {MAINCOLOUR}`, `{ALTCOLOUR}L {MAINCOLOUR}`, `{ALTCOLOUR}J {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 3, `{ALTCOLOUR}I {MAINCOLOUR}`, `{ALTCOLOUR}1-9 {MAINCOLOUR}`, `{ALTCOLOUR}0 {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 4, `{ALTCOLOUR}U {MAINCOLOUR}`, `{ALTCOLOUR}O {MAINCOLOUR}`, `{ALTCOLOUR}P {MAINCOLOUR}`));
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderBindableKeysHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 0, `{ALTCOLOUR}/keybinds {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 1, `{ALTCOLOUR}/bindkey {MAINCOLOUR}`, `{ALTCOLOUR}/unbindkey {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 2, `{ALTCOLOUR}K{MAINCOLOUR}`, `{ALTCOLOUR}L{MAINCOLOUR}`, `{ALTCOLOUR}J{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 3, `{ALTCOLOUR}I{MAINCOLOUR}`, `{ALTCOLOUR}1-9{MAINCOLOUR}`, `{ALTCOLOUR}0{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "KeyBindHelp", 4, `{ALTCOLOUR}U{MAINCOLOUR}`, `{ALTCOLOUR}O{MAINCOLOUR}`, `{ALTCOLOUR}P{MAINCOLOUR}`));
}
// ===========================================================================
function showBusinessHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderBusinessHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "BusinessHelp", 0));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "BusinessHelp", 1));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "BusinessHelp", 2, `{ALTCOLOUR}/bizorder, /bizlock, /bizlights, /radiostation, /bizitemprice, /bizbuyprice, /bizfee, /biztill, /bizwithdraw, /bizdeposit`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "BusinessHelp", 3));
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderBusinessHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "BusinessHelp", 0));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "BusinessHelp", 1));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "BusinessHelp", 2, `{ALTCOLOUR}/bizorder, /bizlock, /bizlights, /radiostation, /bizitemprice, /bizbuyprice, /bizfee, /biztill, /bizwithdraw, /bizdeposit`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "BusinessHelp", 3));
}
// ===========================================================================
function showClanHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderClanHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ClanHelp", 0));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ClanHelp", 1));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ClanHelp", 2, `{ALTCOLOUR}/clan, /clanmotd, /clanname, /clanowner, /clanhouse, /clanbiz, /claninvite, /clanuninvite, /clansetrank`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ClanHelp", 3, `{ALTCOLOUR}/clanranks, /clanflags, /clanaddrank, /clandelrank, /clanaddrankflag, /clandelrankflag, /clanaddmemberflag, /clandelmemberflag`));
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderClanHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ClanHelp", 0));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ClanHelp", 1));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ClanHelp", 2, `{ALTCOLOUR}/clan, /clanmotd, /clanname, /clanowner, /clanhouse, /clanbiz, /claninvite, /clanuninvite, /clansetrank`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "ClanHelp", 3, `{ALTCOLOUR}/clanranks, /clanflags, /clanaddrank, /clandelrank, /clanaddrankflag, /clandelrankflag, /clanaddmemberflag, /clandelmemberflag`));
}
// ===========================================================================
function showRadioHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderRadioHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RadioHelp", 0, `{ALTCOLOUR}/radiostation {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RadioHelp", 1, `{ALTCOLOUR}/radiostations {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RadioHelp", 2, `{ALTCOLOUR}/radiovolume {MAINCOLOUR}`));
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderRadioHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RadioHelp", 0, `{ALTCOLOUR}/radiostation {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RadioHelp", 1, `{ALTCOLOUR}/radiostations {MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "RadioHelp", 2, `{ALTCOLOUR}/radiovolume {MAINCOLOUR}`));
}
// ===========================================================================
function showWealthAndTaxHelpMessage(client) {
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderWealthandTaxHelp")));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Your taxes on payday are ${100*getGlobalConfig().economy.incomeTaxRate}% of your calculated wealth.`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Your calculated wealth is a total sum based on how many vehicles, houses, and businesses you have.`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Each vehicle is {ALTCOLOUR}${getGlobalConfig().economy.upKeepCosts.upKeepPerVehicle}, {MAINCOLOUR}each house is {ALTCOLOUR}${getGlobalConfig().economy.upKeepCosts.upKeepPerHouse}, {MAINCOLOUR}and each business is {ALTCOLOUR}${getGlobalConfig().economy.upKeepCosts.upKeepPerBusiness}`);
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Use {ALTCOLOUR}/wealth {MAINCOLOUR}to see your current wealth, and {ALTCOLOUR}/tax {MAINCOLOUR}to see how much you'll pay in tax each payday`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderWealthandTaxHelp")));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "WealthAndTaxHelp", 0, `{ALTCOLOUR}${100*getGlobalConfig().economy.incomeTaxRate}%{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "WealthAndTaxHelp", 1));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "WealthAndTaxHelp", 2, `{ALTCOLOUR}${getGlobalConfig().economy.upKeepCosts.upKeepPerVehicle}{MAINCOLOUR}`, `{ALTCOLOUR}${getGlobalConfig().economy.upKeepCosts.upKeepPerHouse}{MAINCOLOUR}`, `{ALTCOLOUR}${getGlobalConfig().economy.upKeepCosts.upKeepPerBusiness}{MAINCOLOUR}`));
messagePlayerHelpContent(client, getGroupedLocaleString(client, "WealthAndTaxHelp", 3, `{ALTCOLOUR}/wealth{MAINCOLOUR}`, `{ALTCOLOUR}/tax{MAINCOLOUR}`));
}
// ===========================================================================
function showCommandHelpMessage(client, commandName) {
if(!commandName) {
messagePlayerSyntax(client, `${getCommandSyntaxText("help")}command <command name>`);
return false;
}
if(!commandName) {
messagePlayerSyntax(client, `${getCommandSyntaxText("help")}command <command name>`);
return false;
}
commandName = toLowerCase(commandName);
commandName = commandName.trim();
commandName = toLowerCase(commandName);
commandName = commandName.trim();
if(commandName.slice(0, 1) == "/") {
commandName = commandName.slice(1);
}
if(commandName.slice(0, 1) == "/") {
commandName = commandName.slice(1);
}
let command = getCommandData(commandName);
let aliases = getCommandAliasesNames(command);
let command = getCommandData(commandName);
let aliases = getCommandAliasesNames(command);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderCommandInfo", commandName)));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Description: ${command.description}`);
messagePlayerInfo(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderCommandInfo", commandName)));
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Description: ${command.helpDescription}`);
if(aliases.length > 0) {
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Aliases: ${aliases.join(", ")}`);
} else {
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Aliases: (None)`);
}
if(aliases.length > 0) {
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Aliases: ${aliases.join(", ")}`);
} else {
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Aliases: (None)`);
}
//messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Usable on Discord: ${getYesNoFromBool(command.allowOnDiscord)}`);
//messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Usable on Discord: ${getYesNoFromBool(command.allowOnDiscord)}`);
//if(doesPlayerHaveStaffPermission(client, getStaffFlagValue("BasicModeration"))) {
// messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Usable on Discord: ${getYesNoFromBool(command.allowOnDiscord)}`);
//}
//if(doesPlayerHaveStaffPermission(client, getStaffFlagValue("BasicModeration"))) {
// messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}Usable on Discord: ${getYesNoFromBool(command.allowOnDiscord)}`);
//}
}
// ===========================================================================
@@ -380,7 +380,7 @@ function showCommandHelpMessage(client, commandName) {
*
*/
function helpGetCarCommand(command, params, client) {
messagePlayerAlert(client, `You can buy a car by visiting a vehicle dealership. Use {ALTCOLOUR}/help vehicle {MAINCOLOUR}for more info.`);
messagePlayerAlert(client, getLocaleString(client, "CarCommandHelp", `{ALTCOLOUR}/info vehicle{MAINCOLOUR}`));
}
// ===========================================================================
@@ -395,7 +395,8 @@ function helpGetCarCommand(command, params, client) {
*
*/
function helpGetSkinCommand(command, params, client) {
messagePlayerAlert(client, `You can change your skin by visiting a clothes store. Use {ALTCOLOUR}/help skin {MAINCOLOUR}for more info.`);
messagePlayerAlert(client, getLocaleString(client, "SkinCommandHelp", `{ALTCOLOUR}/info skin{MAINCOLOUR}`));
messagePlayerAlert(client, ``);
}
// ===========================================================================

File diff suppressed because it is too large Load Diff

View File

@@ -1,85 +0,0 @@
// Shared Scripts
require("../scripts/shared/const.js");
require("../scripts/shared/utilities.js");
require("../scripts/shared/gamedata.js");
// Multiplayer Mod (Wrapped Natives)
require("scripts/server/native/ragemp.js");
// Server Scripts
require("scripts/server/class.js");
require("scripts/server/accent.js");
require("scripts/server/account.js");
require("scripts/server/animation.js");
require("scripts/server/anticheat.js");
require("scripts/server/ban.js");
require("scripts/server/bitflag.js");
require("scripts/server/business.js");
require("scripts/server/chat.js");
require("scripts/server/clan.js");
require("scripts/server/client.js");
require("scripts/server/colour.js");
require("scripts/server/const.js");
require("scripts/server/database.js");
require("scripts/server/developer.js");
require("scripts/server/discord.js");
require("scripts/server/economy.js");
require("scripts/server/email.js");
require("scripts/server/event.js");
require("scripts/server/fishing.js");
require("scripts/server/gui.js");
require("scripts/server/help.js");
require("scripts/server/house.js");
require("scripts/server/item.js");
require("scripts/server/job.js");
require("scripts/server/keybind.js");
require("scripts/server/locale.js");
require("scripts/server/messaging.js");
require("scripts/server/misc.js");
require("scripts/server/npc.js");
require("scripts/server/staff.js");
require("scripts/server/radio.js");
require("scripts/server/security.js");
require("scripts/server/subaccount.js");
require("scripts/server/timers.js");
require("scripts/server/trigger.js");
require("scripts/server/utilities.js");
require("scripts/server/vehicle.js");
require("scripts/server/config.js");
require("scripts/server/core.js");
require("scripts/server/command.js");
// Server Business Scripts
require("scripts/server/business/bakery.js");
require("scripts/server/business/bar.js");
require("scripts/server/business/burger.js");
require("scripts/server/business/clothing.js");
require("scripts/server/business/club.js");
require("scripts/server/business/fuel.js");
require("scripts/server/business/mechanic.js");
require("scripts/server/business/pizza.js");
require("scripts/server/business/restaurant.js");
require("scripts/server/business/vehicle.js");
require("scripts/server/business/weapon.js");
// Server Job Scripts
require("scripts/server/job/bus.js");
require("scripts/server/job/drug.js");
require("scripts/server/job/fire.js");
require("scripts/server/job/garbage.js");
require("scripts/server/job/medic.js");
require("scripts/server/job/police.js");
require("scripts/server/job/taxi.js");
require("scripts/server/job/weapon.js");
// Server Item Scripts
require("scripts/server/item/food.js");
require("scripts/server/item/drink.js");
require("scripts/server/item/walkie-talkie.js");
require("scripts/server/item/phone.js");
require("scripts/server/item/handcuff.js");
require("scripts/server/item/rope.js");
require("scripts/server/item/tazer.js");
// Startup
require("scripts/server/startup.js");

File diff suppressed because it is too large Load Diff

View File

@@ -10,27 +10,27 @@
// ===========================================================================
function isPlayerHandCuffed(client) {
return (getPlayerData(client).pedState == VRR_PEDSTATE_BINDED);
return (getPlayerData(client).pedState == VRR_PEDSTATE_BINDED);
}
// ===========================================================================
function handCuffPlayer(client) {
getPlayerData(client).pedState = VRR_PEDSTATE_BINDED;
setPlayerControlState(client, false);
getPlayerData(client).pedState = VRR_PEDSTATE_BINDED;
setPlayerControlState(client, false);
}
// ===========================================================================
function unHandCuffPlayer(client) {
getPlayerData(client).pedState = VRR_PEDSTATE_READY;
setPlayerControlState(client, true);
getPlayerData(client).pedState = VRR_PEDSTATE_READY;
setPlayerControlState(client, true);
}
// ===========================================================================
function isPlayerSurrendered(client) {
return true; //(getPlayerData(client).pedState == VRR_PEDSTATE_TAZED || getPlayerData(client).pedState == VRR_PEDSTATE_HANDSUP);
return true; //(getPlayerData(client).pedState == VRR_PEDSTATE_TAZED || getPlayerData(client).pedState == VRR_PEDSTATE_HANDSUP);
}
// ===========================================================================

View File

@@ -8,48 +8,48 @@
// ===========================================================================
function getItemWithPhoneNumber(phoneNumber) {
for(let i in getServerData().items) {
if(getItemTypeData(getItemData(i).itemTypeIndex).useType == VRR_ITEM_USETYPE_PHONE) {
if(getItemData(i).value == phoneNumber) {
return i;
}
}
}
return -1;
for(let i in getServerData().items) {
if(getItemTypeData(getItemData(i).itemTypeIndex).useType == VRR_ITEM_USETYPE_PHONE) {
if(getItemData(i).value == phoneNumber) {
return i;
}
}
}
return -1;
}
// ===========================================================================
function isPhoneItemEnabled(itemIndex) {
return getItemData(itemIndex).enabled;
return getItemData(itemIndex).enabled;
}
// ===========================================================================
function ringPhoneForNearbyPlayers(itemIndex) {
/*
if(isPhoneItemEnabled(itemIndex)) {
switch(getItemData(itemIndex).ownerType) {
case VRR_ITEM_OWNER_GROUND:
playRingtoneForPlayersInRange(getItemData(itemIndex).position, getItemData(i).extra);
break;
/*
if(isPhoneItemEnabled(itemIndex)) {
switch(getItemData(itemIndex).ownerType) {
case VRR_ITEM_OWNER_GROUND:
playRingtoneForPlayersInRange(getItemData(itemIndex).position, getItemData(i).extra);
break;
case VRR_ITEM_OWNER_VEHTRUNK:
playRingtoneForPlayersInRange(getVehiclePosition(getItemData(itemIndex).ownerId), getItemData(i).extra);
break;
case VRR_ITEM_OWNER_VEHTRUNK:
playRingtoneForPlayersInRange(getVehiclePosition(getItemData(itemIndex).ownerId), getItemData(i).extra);
break;
case VRR_ITEM_OWNER_VEHDASH:
playRingtoneForPlayersInRange(getVehiclePosition(getItemData(itemIndex).ownerId), getItemData(i).extra);
break;
}
}
*/
case VRR_ITEM_OWNER_VEHDASH:
playRingtoneForPlayersInRange(getVehiclePosition(getItemData(itemIndex).ownerId), getItemData(i).extra);
break;
}
}
*/
}
// ===========================================================================
function phoneTransmit(radioFrequency, messageText, transmittingPlayer) {
phoneOutgoingToNearbyPlayers(transmittingPlayer, messageText);
phoneOutgoingToNearbyPlayers(transmittingPlayer, messageText);
}
// ===========================================================================

View File

@@ -10,21 +10,21 @@
// ===========================================================================
function isPlayerTied(client) {
return (getPlayerData(client).pedState == VRR_PEDSTATE_BINDED);
return (getPlayerData(client).pedState == VRR_PEDSTATE_BINDED);
}
// ===========================================================================
function ropeTiePlayer(client) {
getPlayerData(client).pedState = VRR_PEDSTATE_BINDED;
setPlayerControlState(client, false);
getPlayerData(client).pedState = VRR_PEDSTATE_BINDED;
setPlayerControlState(client, false);
}
// ===========================================================================
function ropeUnTiePlayer(client) {
getPlayerData(client).pedState = VRR_PEDSTATE_READY;
setPlayerControlState(client, true);
getPlayerData(client).pedState = VRR_PEDSTATE_READY;
setPlayerControlState(client, true);
}
// ===========================================================================

View File

@@ -10,34 +10,34 @@
// ===========================================================================
function isPlayerTazed(client) {
return (getPlayerData(client).pedState == VRR_PEDSTATE_TAZED);
return (getPlayerData(client).pedState == VRR_PEDSTATE_TAZED);
}
// ===========================================================================
function tazePlayer(client) {
getPlayerData(client).pedState = VRR_PEDSTATE_TAZED;
setPlayerControlState(client, false);
getPlayerData(client).pedState = VRR_PEDSTATE_TAZED;
setPlayerControlState(client, false);
let animationId = getAnimationFromParams("tazed");
if(animationId != false) {
forcePlayerPlayAnimation(client, animationId);
}
let animationId = getAnimationFromParams("tazed");
if(animationId != false) {
forcePlayerPlayAnimation(client, animationId);
}
setTimeout(function() {
unTazePlayer(client);
doActionToNearbyPlayers(client, `The tazer effect wears off`);
}, getGlobalConfig().tazerEffectDuration);
setTimeout(function() {
unTazePlayer(client);
doActionToNearbyPlayers(client, `The tazer effect wears off`);
}, getGlobalConfig().tazerEffectDuration);
}
// ===========================================================================
function unTazePlayer(client) {
getPlayerData(client).pedState = VRR_PEDSTATE_READY;
getPlayerData(client).pedState = VRR_PEDSTATE_READY;
setPlayerControlState(client, true);
setPlayerPosition(client, getPlayerData(client).currentAnimationPositionReturnTo);
makePedStopAnimation(getPlayerData(client).ped);
setPlayerControlState(client, true);
setPlayerPosition(client, getPlayerData(client).currentAnimationPositionReturnTo);
makePedStopAnimation(getPlayerData(client).ped);
}

View File

@@ -16,15 +16,15 @@ function getPlayerActiveWalkieTalkieFrequency(client) {
return getItemData(getPlayerData(client).hotBarItems[walkieTalkieSlot]).value;
}
}
}
}
return false;
return false;
}
// ===========================================================================
function walkieTalkieTransmit(radioFrequency, messageText, transmittingPlayer) {
walkieTalkieOutgoingToNearbyPlayers(transmittingPlayer, messageText);
walkieTalkieOutgoingToNearbyPlayers(transmittingPlayer, messageText);
//let clients = getServerData().items;
//for(let i in clients) {

File diff suppressed because it is too large Load Diff

View File

@@ -8,157 +8,157 @@
// ===========================================================================
function policeTazerCommand(command, params, client) {
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
return true;
return true;
}
// ===========================================================================
function policeCuffCommand(command, params, client) {
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
return true;
return true;
}
// ===========================================================================
function policeArrestCommand(command, params, client) {
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
return true;
return true;
}
// ===========================================================================
function policeSearchCommand(command, params, client) {
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
return true;
return true;
}
// ===========================================================================
function policeDragCommand(command, params, client) {
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
return true;
return true;
}
// ===========================================================================
function policeDetainCommand(command, params, client) {
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!canPlayerUsePoliceJob(client)) {
messagePlayerError(client, "You are not allowed to use the police job.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_POLICE)) {
messagePlayerError(client, "You don't have a police job.");
return false;
}
return true;
return true;
}
// ===========================================================================

View File

@@ -8,25 +8,25 @@
// ===========================================================================
function taxiSetFareCommand(command, params, client) {
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUseJobs(client)) {
messagePlayerError(client, "You are not allowed to use jobs.");
return false;
}
if(!canPlayerUseTaxiJob(client)) {
messagePlayerError(client, "You are not allowed to use the taxi job.");
return false;
}
if(!canPlayerUseTaxiJob(client)) {
messagePlayerError(client, "You are not allowed to use the taxi job.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!isPlayerWorking(client)) {
messagePlayerError(client, "You are not working! Use /startwork first.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_TAXI)) {
messagePlayerError(client, "You don't have a taxi job.");
return false;
}
if(!doesPlayerHaveJobType(client, VRR_JOB_TAXI)) {
messagePlayerError(client, "You don't have a taxi job.");
return false;
}
return true;
}

View File

@@ -1,16 +1,16 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"moduleResolution": "classic"
"module": "commonjs",
"target": "es6",
"moduleResolution": "classic"
},
"include": [
"*.js",
"job/*.js",
"business/*.js",
"item/*.js",
"npc/*.js",
"native/*.js",
"../shared/*.js"
"*.js",
"job/*.js",
"business/*.js",
"item/*.js",
"npc/*.js",
"native/*.js",
"../shared/*.js"
]
}

View File

@@ -36,197 +36,188 @@ class KeyBindData {
function initKeyBindScript() {
logToConsole(LOG_INFO, "[VRR.KeyBind]: Initializing key bind script ...");
getGlobalConfig().keyBind = loadKeyBindConfiguration();
logToConsole(LOG_INFO, "[VRR.KeyBind]: Key bind script initialized!");
}
// ===========================================================================
function addKeyBindCommand(command, params, client) {
let splitParams = params.split(" ");
let splitParams = params.split(" ");
let keyId = getKeyIdFromParams(getParam(params, " ", 1));
let tempCommand = getParam(params, " ", 2);
let tempParams = (splitParams.length > 2) ? splitParams.slice(2).join(" ") : "";
let keyId = getKeyIdFromParams(getParam(params, " ", 1));
let tempCommand = getParam(params, " ", 2);
let tempParams = (splitParams.length > 2) ? splitParams.slice(2).join(" ") : "";
if(!keyId) {
messagePlayerError(client, "The key ID or name you input is invalid!");
messagePlayerTip(client, "Use simple key names, letters, or numbers. Don't add spaces.");
messagePlayerInfo(client, `Examples: {ALTCOLOUR}1, 2, a, b, numplus, num1, f1, f2, pageup, delete, insert, rightshift, leftctrl`);
return false;
}
if(!keyId) {
messagePlayerError(client, "The key ID or name you input is invalid!");
messagePlayerTip(client, "Use simple key names, letters, or numbers. Don't add spaces.");
messagePlayerInfo(client, `Examples: {ALTCOLOUR}1, 2, a, b, numplus, num1, f1, f2, pageup, delete, insert, rightshift, leftctrl`);
return false;
}
if(!keyId) {
messagePlayerError(client, "That key name/id is invalid!");
return false;
}
if(!keyId) {
messagePlayerError(client, "That key name/id is invalid!");
return false;
}
if(areParamsEmpty(tempCommand)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
if(areParamsEmpty(tempCommand)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
addPlayerKeyBind(client, keyId, tempCommand, tempParams);
messagePlayerSuccess(client, `You binded the {ALTCOLOUR}${toUpperCase(getKeyNameFromId(keyId))} {MAINCOLOUR}key to command: {ALTCOLOUR}/${tempCommand} ${tempParams}`);
addPlayerKeyBind(client, keyId, tempCommand, tempParams);
messagePlayerSuccess(client, `You binded the {ALTCOLOUR}${toUpperCase(getKeyNameFromId(keyId))} {MAINCOLOUR}key to command: {ALTCOLOUR}/${tempCommand} ${tempParams}`);
}
// ===========================================================================
function removeKeyBindCommand(command, params, client) {
let splitParams = params.split(" ");
let keyId = getKeyIdFromParams(getParam(params, " ", 1));
let keyId = getKeyIdFromParams(getParam(params, " ", 1));
if(!keyId) {
messagePlayerError(client, "The key ID or name you input is invalid!");
messagePlayerTip(client, "Use simple key names, letters, or numbers. Don't add spaces.");
messagePlayerInfo(client, `Examples: {ALTCOLOUR}1, 2, a, b, numplus, num1, f1, f2, pageup, delete, insert, rightshift, leftctrl`);
return false;
}
if(!keyId) {
messagePlayerError(client, "The key ID or name you input is invalid!");
messagePlayerTip(client, "Use simple key names, letters, or numbers. Don't add spaces.");
messagePlayerInfo(client, `Examples: {ALTCOLOUR}1, 2, a, b, numplus, num1, f1, f2, pageup, delete, insert, rightshift, leftctrl`);
return false;
}
if(!keyId) {
messagePlayerError(client, "That key name/id is invalid!");
return false;
}
if(!keyId) {
messagePlayerError(client, "That key name/id is invalid!");
return false;
}
removePlayerKeyBind(client, keyId);
messagePlayerSuccess(client, `You removed the keybind for the {ALTCOLOUR}${toUpperCase(getKeyNameFromId(keyId))} {MAINCOLOUR}key`);
removePlayerKeyBind(client, keyId);
messagePlayerSuccess(client, `You removed the keybind for the {ALTCOLOUR}${toUpperCase(getKeyNameFromId(keyId))} {MAINCOLOUR}key`);
}
// ===========================================================================
function addPlayerKeyBind(client, keys, command, params, tempKey = false) {
let keyBindData = new KeyBindData(false, keys, `${command} ${params}`);
if(tempKey == true) {
keyBindData.databaseId = -1;
}
let keyBindData = new KeyBindData(false, keys, `${command} ${params}`);
if(tempKey == true) {
keyBindData.databaseId = -1;
}
getPlayerData(client).keyBinds.push(keyBindData);
sendAddAccountKeyBindToClient(client, keys, (keys.length > 1) ? VRR_KEYSTATE_COMBO : VRR_KEYSTATE_UP);
getPlayerData(client).keyBinds.push(keyBindData);
sendAddAccountKeyBindToClient(client, keys, (keys.length > 1) ? VRR_KEYSTATE_COMBO : VRR_KEYSTATE_UP);
if(!doesPlayerHaveKeyBindsDisabled(client) && doesPlayerHaveKeyBindForCommand(client, "enter")) {
let keyId = getPlayerKeyBindForCommand(client, "enter");
logToConsole(LOG_DEBUG, `[VRR.Event] Sending custom enter property key ID (${keyId.key}, ${toUpperCase(getKeyNameFromId(keyId.key))}) to ${getPlayerDisplayForConsole(client)}`);
sendPlayerEnterPropertyKey(client, keyId.key);
} else {
sendPlayerEnterPropertyKey(client, false);
}
if(!doesPlayerHaveKeyBindsDisabled(client) && doesPlayerHaveKeyBindForCommand(client, "enter")) {
let keyId = getPlayerKeyBindForCommand(client, "enter");
logToConsole(LOG_DEBUG, `[VRR.Event] Sending custom enter property key ID (${keyId.key}, ${toUpperCase(getKeyNameFromId(keyId.key))}) to ${getPlayerDisplayForConsole(client)}`);
sendPlayerEnterPropertyKey(client, keyId.key);
} else {
sendPlayerEnterPropertyKey(client, false);
}
}
// ===========================================================================
function removePlayerKeyBind(client, keyId) {
if(isPlayerLoggedIn(client)) {
quickDatabaseQuery(`DELETE FROM acct_hotkey WHERE acct_hotkey_acct = ${getPlayerData(client).accountData.databaseId} AND acct_hotkey_key = ${keyId}`);
}
//if(isPlayerLoggedIn(client)) {
// quickDatabaseQuery(`DELETE FROM acct_hotkey WHERE acct_hotkey_acct = ${getPlayerData(client).accountData.databaseId} AND acct_hotkey_key = ${keyId}`);
//}
for(let i in getPlayerData(client).keyBinds) {
if(getPlayerData(client).keyBinds[i].key == keyId) {
getPlayerData(client).keyBinds.splice(i, 1);
}
}
sendRemoveAccountKeyBindToClient(client, keyId);
//for(let i in getPlayerData(client).keyBinds) {
// if(getPlayerData(client).keyBinds[i].key == keyId) {
// getPlayerData(client).keyBinds.splice(i, 1);
// }
//}
getPlayerData(client).keyBinds = getPlayerData(client).keyBinds.filter(keyBind => keyBind.key != keyId);
sendRemoveAccountKeyBindToClient(client, keyId);
if(!doesPlayerHaveKeyBindsDisabled(client) && doesPlayerHaveKeyBindForCommand(client, "enter")) {
let keyId = getPlayerKeyBindForCommand(client, "enter");
logToConsole(LOG_DEBUG, `[VRR.Event] Sending custom enter property key ID (${keyId.key}, ${toUpperCase(getKeyNameFromId(keyId.key))}) to ${getPlayerDisplayForConsole(client)}`);
sendPlayerEnterPropertyKey(client, keyId.key);
} else {
sendPlayerEnterPropertyKey(client, false);
}
if(!doesPlayerHaveKeyBindsDisabled(client) && doesPlayerHaveKeyBindForCommand(client, "enter")) {
let keyId = getPlayerKeyBindForCommand(client, "enter");
logToConsole(LOG_DEBUG, `[VRR.Event] Sending custom enter property key ID (${keyId.key}, ${toUpperCase(getKeyNameFromId(keyId.key))}) to ${getPlayerDisplayForConsole(client)}`);
sendPlayerEnterPropertyKey(client, keyId.key);
} else {
sendPlayerEnterPropertyKey(client, false);
}
}
// ===========================================================================
function doesPlayerHaveKeyBindForCommand(client, command) {
for(let i in getPlayerData(client).keyBinds) {
if(toLowerCase(getPlayerData(client).keyBinds[i].commandString.split(" ")[0]) == toLowerCase(command)) {
return true;
}
}
return false;
for(let i in getPlayerData(client).keyBinds) {
if(toLowerCase(getPlayerData(client).keyBinds[i].commandString.split(" ")[0]) == toLowerCase(command)) {
return true;
}
}
return false;
}
// ===========================================================================
function getPlayerKeyBindForCommand(client, command) {
for(let i in getPlayerData(client).keyBinds) {
if(toLowerCase(getPlayerData(client).keyBinds[i].commandString.split(" ")[0]) == toLowerCase(command)) {
return getPlayerData(client).keyBinds[i];
}
}
return false;
for(let i in getPlayerData(client).keyBinds) {
if(toLowerCase(getPlayerData(client).keyBinds[i].commandString.split(" ")[0]) == toLowerCase(command)) {
return getPlayerData(client).keyBinds[i];
}
}
return false;
}
// ===========================================================================
function doesPlayerHaveKeyBindForKey(client, key) {
for(let i in getPlayerData(client).keyBinds) {
if(getPlayerData(client).keyBinds[i].key == key) {
return true;
}
}
return false;
for(let i in getPlayerData(client).keyBinds) {
if(getPlayerData(client).keyBinds[i].key == key) {
return true;
}
}
return false;
}
// ===========================================================================
function doesPlayerHaveKeyBindsDisabled(client) {
return hasBitFlag(getPlayerData(client).accountData.settings, getAccountSettingsFlagValue("NoKeyBinds"));
return hasBitFlag(getPlayerData(client).accountData.settings, getAccountSettingsFlagValue("NoKeyBinds"));
}
// ===========================================================================
function getPlayerKeyBindForKey(client, key) {
for(let i in getPlayerData(client).keyBinds) {
if(getPlayerData(client).keyBinds[i].key == key) {
return getPlayerData(client).keyBinds[i];
}
}
return false;
for(let i in getPlayerData(client).keyBinds) {
if(getPlayerData(client).keyBinds[i].key == key) {
return getPlayerData(client).keyBinds[i];
}
}
return false;
}
// ===========================================================================
function playerUsedKeyBind(client, key) {
if(!isPlayerLoggedIn(client)) {
return false;
}
if(!isPlayerLoggedIn(client)) {
return false;
}
if(!isPlayerSpawned(client)) {
return false;
}
if(!isPlayerSpawned(client)) {
return false;
}
logToConsole(LOG_DEBUG, `[VRR.KeyBind] ${getPlayerDisplayForConsole(client)} used keybind ${toUpperCase(getKeyNameFromId(key))} (${key})`);
if(!doesPlayerHaveKeyBindsDisabled(client) && doesPlayerHaveKeyBindForKey(client, key)) {
let keyBindData = getPlayerKeyBindForKey(client, key);
if(keyBindData.enabled) {
let splitCommandString = keyBindData.commandString.split(" ");
let tempCommand = splitCommandString[0];
let tempParams = "";
if(splitCommandString.length > 1) {
tempParams = splitCommandString.slice(1).join(" ");
}
getCommand(toLowerCase(tempCommand)).handlerFunction(tempCommand, tempParams, client);
//triggerEvent("OnPlayerCommand", null, tempCommand, tempParams, client);
}
}
logToConsole(LOG_DEBUG, `[VRR.KeyBind] ${getPlayerDisplayForConsole(client)} used keybind ${toUpperCase(getKeyNameFromId(key))} (${key})`);
if(!doesPlayerHaveKeyBindsDisabled(client) && doesPlayerHaveKeyBindForKey(client, key)) {
let keyBindData = getPlayerKeyBindForKey(client, key);
if(keyBindData.enabled) {
let splitCommandString = keyBindData.commandString.split(" ");
let tempCommand = splitCommandString[0];
let tempParams = "";
if(splitCommandString.length > 1) {
tempParams = splitCommandString.slice(1).join(" ");
}
getCommand(toLowerCase(tempCommand)).handlerFunction(tempCommand, tempParams, client);
//triggerEvent("OnPlayerCommand", null, tempCommand, tempParams, client);
}
}
}
// ===========================================================================
function sendAccountKeyBindsToClient(client) {
sendClearKeyBindsToClient(client);
for(let i in getPlayerData(client).keyBinds) {
sendAddAccountKeyBindToClient(client, getPlayerData(client).keyBinds[i].key, getPlayerData(client).keyBinds[i].keyState);
}
}
// ===========================================================================
function loadKeyBindConfiguration() {
let keyBindConfigFile = loadTextFile("config/keybind.json");
return JSON.parse(keyBindConfigFile);
sendClearKeyBindsToClient(client);
for(let i in getPlayerData(client).keyBinds) {
sendAddAccountKeyBindToClient(client, getPlayerData(client).keyBinds[i].key, getPlayerData(client).keyBinds[i].keyState);
}
}
// ===========================================================================

View File

@@ -7,93 +7,112 @@
// TYPE: Server (JavaScript)
// ===========================================================================
let translateURL = "http://api.mymemory.translated.net/get?de={3}&q={0}&langpair={1}|{2}";
// ===========================================================================
function initLocaleScript() {
logToConsole(LOG_INFO, "[VRR.Locale]: Initializing locale script ...");
getServerData().localeStrings = loadAllLocaleStrings();
// Translation Cache
getServerData().cachedTranslations = new Array(getGlobalConfig().locale.locales.length);
getServerData().cachedTranslationFrom = new Array(getGlobalConfig().locale.locales.length);
getServerData().cachedTranslationFrom.fill([]);
getServerData().cachedTranslations.fill(getServerData().cachedTranslationFrom);
getGlobalConfig().locale.defaultLanguageId = getLocaleFromParams(getGlobalConfig().locale.defaultLanguageId);
logToConsole(LOG_INFO, "[VRR.Locale]: Initializing locale script ...");
logToConsole(LOG_INFO, "[VRR.Locale]: Locale script initialized!");
}
// ===========================================================================
function getLocaleString(client, stringName, ...args) {
let tempString = getRawLocaleString(stringName, getPlayerData(client).locale);
if(tempString == "") {
submitBugReport(client, `(AUTOMATED REPORT) Locale string "${stringName}" is missing for "${getPlayerLocaleName(client)}"`);
}
let tempString = getRawLocaleString(stringName, getPlayerData(client).locale);
if(tempString == "" || tempString == null || typeof tempString == "undefined") {
logToConsole(LOG_WARN, `[VRR.Locale] Locale string missing for ${stringName} on language ${getLocaleData(getPlayerData(client).locale).englishName}`);
submitBugReport(client, `(AUTOMATED REPORT) Locale string "${stringName}" is missing for "${getPlayerLocaleName(client)}"`);
return "";
}
tempString = replaceColoursInMessage(tempString);
for(let i = 1; i <= args.length; i++) {
tempString = tempString.replace(`{${i}}`, args[i-1]);
}
for(let i = 1; i <= args.length; i++) {
tempString = tempString.replace(`{${i}}`, args[i-1]);
}
return tempString;
}
return tempString;
// ===========================================================================
function getLanguageLocaleString(localeId, stringName, ...args) {
let tempString = getRawLocaleString(stringName, localeId);
if(tempString == "" || tempString == null || typeof tempString == "undefined") {
logToConsole(LOG_WARN, `[VRR.Locale] Locale string missing for ${stringName} on language ${getLocaleData(getPlayerData(client).locale).englishName}`);
submitBugReport(client, `(AUTOMATED REPORT) Locale string "${stringName}" is missing for "${getPlayerLocaleName(client)}"`);
}
for(let i = 1; i <= args.length; i++) {
tempString = tempString.replace(`{${i}}`, args[i-1]);
}
return tempString;
}
// ===========================================================================
function getGroupedLocaleString(client, stringName, index, ...args) {
let tempString = getRawGroupedLocaleString(stringName, getPlayerData(client).locale, index);
tempString = replaceColoursInMessage(tempString);
let tempString = getRawGroupedLocaleString(stringName, getPlayerData(client).locale, index);
for(let i = 1; i <= args.length; i++) {
tempString = tempString.replace(`{${i}}`, args[i-1]);
}
for(let i = 1; i <= args.length; i++) {
tempString = tempString.replace(`{${i}}`, args[i-1]);
}
return tempString;
return tempString;
}
// ===========================================================================
function getRawLocaleString(stringName, localeName) {
return getLocaleStrings()[localeName][stringName];
function getRawLocaleString(stringName, localeId) {
return getLocaleStrings()[localeId][stringName];
//if(findResourceByName("agrp_locale").exports.doesLocaleStringExist(localeId, stringName) == false) {
// return "";
//}
//let tempString = findResourceByName("agrp_locale").exports.getRawLocaleString(localeId, stringName);
//if(tempString == "" || tempString == null || tempString == undefined) {
// return "";
//}
}
// ===========================================================================
function getRawGroupedLocaleString(stringName, localeName, index) {
return getLocaleStrings()[localeName][stringName][index];
function getRawGroupedLocaleString(stringName, localeId, index) {
return getLocaleStrings()[localeId][stringName][index];
//if(findResourceByName("agrp_locale").exports.doesLocaleStringExist(localeId, stringName) == false) {
// return "";
//}
//let tempString = findResourceByName("agrp_locale").exports.getRawLocaleString(localeId, stringName);
//if(tempString == "" || tempString == null || tempString == undefined) {
// return "";
//}
}
// ===========================================================================
function getPlayerLocaleName(client) {
let localeId = getPlayerData(client).locale;
return getLocales()[localeId][0];
let localeId = getPlayerData(client).locale;
return getLocales()[localeId].englishName;
}
// ===========================================================================
function loadAllLocaleStrings() {
let tempLocaleStrings = {};
let tempLocaleStrings = {};
let locales = getGlobalConfig().locale.locales;
for(let i in locales) {
let localeData = locales[i];
let localeFile = JSON.parse(loadTextFile(`locale/${localeData[1]}.json`));
tempLocaleStrings[i] = localeFile;
}
let locales = getGlobalConfig().locale.locales;
for(let i in locales) {
let localeData = locales[i];
let localeFile = JSON.parse(loadTextFile(`locale/${localeData.stringsFile}`));
tempLocaleStrings[i] = localeFile;
}
return tempLocaleStrings;
return tempLocaleStrings;
}
// ===========================================================================
function getLocaleStrings() {
return getServerData().localeStrings;
return getServerData().localeStrings;
}
// ===========================================================================
@@ -102,11 +121,11 @@ function getLocaleFromParams(params) {
let locales = getLocales();
if(isNaN(params)) {
for(let i in locales) {
if(toLowerCase(locales[i][2]).indexOf(toLowerCase(params)) != -1) {
if(toLowerCase(locales[i].isoCode).indexOf(toLowerCase(params)) != -1) {
return i;
}
if(toLowerCase(locales[i][0]).indexOf(toLowerCase(params)) != -1) {
if(toLowerCase(locales[i].englishName).indexOf(toLowerCase(params)) != -1) {
return i;
}
}
@@ -118,7 +137,7 @@ function getLocaleFromParams(params) {
// ===========================================================================
function getLocales() {
return getGlobalConfig().locale.locales;
return getGlobalConfig().locale.locales;
}
// ===========================================================================
@@ -141,61 +160,63 @@ function setLocaleCommand(command, params, client) {
return false;
}
let localeId = getLocaleFromParams(params);
let localeId = getLocaleFromParams(params);
if(!getLocaleData(localeId)) {
messagePlayerInfo(client, getLocaleString(client, "InvalidLocale"));
return false;
}
if(!getLocaleData(localeId)) {
messagePlayerInfo(client, getLocaleString(client, "InvalidLocale"));
return false;
}
getPlayerData(client).accountData.locale = localeId;
getPlayerData(client).locale = localeId;
messagePlayerSuccess(client, getLocaleString(client, "LocaleChanged1"), getLocaleString(client, "LocaleNativeName"));
getPlayerData(client).accountData.locale = localeId;
getPlayerData(client).locale = localeId;
messagePlayerSuccess(client, getLocaleString(client, "LocaleChanged1", getLocaleString(client, "LocaleNativeName")));
sendPlayerLocaleStrings(client);
}
// ===========================================================================
function getLocaleData(localeId) {
if(typeof getLocales()[localeId] != "undefined") {
return getLocales()[localeId];
}
if(typeof getLocales()[localeId] != "undefined") {
return getLocales()[localeId];
}
return false;
return false;
}
// ===========================================================================
function reloadLocaleConfigurationCommand(command, params, client) {
getGlobalConfig().locale = loadLocaleConfig();
getServerData().localeStrings = loadAllLocaleStrings();
getServerData().localeStrings = loadAllLocaleStrings();
// Translation Cache
getServerData().cachedTranslations = new Array(getGlobalConfig().locale.locales.length);
getServerData().cachedTranslationFrom = new Array(getGlobalConfig().locale.locales.length);
getServerData().cachedTranslationFrom.fill([]);
getServerData().cachedTranslations.fill(getServerData().cachedTranslationFrom);
// Translation Cache
getServerData().cachedTranslations = new Array(getGlobalConfig().locale.locales.length);
getServerData().cachedTranslationFrom = new Array(getGlobalConfig().locale.locales.length);
getServerData().cachedTranslationFrom.fill([]);
getServerData().cachedTranslations.fill(getServerData().cachedTranslationFrom);
getGlobalConfig().locale.defaultLanguageId = getLocaleFromParams(getGlobalConfig().locale.defaultLanguage);
getGlobalConfig().locale.defaultLanguageId = getLocaleFromParams(getGlobalConfig().locale.defaultLanguage);
messageAdmins(`${client.name}{MAINCOLOUR} has reloaded the locale settings and texts`);
messageAdmins(`${getPlayerName(client)}{MAINCOLOUR} has reloaded the locale settings and texts`);
}
// ===========================================================================
async function translateMessage(messageText, translateFrom = getGlobalConfig().locale.defaultLanguageId, translateTo = getGlobalConfig().locale.defaultLanguageId) {
return new Promise(resolve => {
if(translateFrom == translateTo) {
resolve(messageText);
}
if(translateFrom == translateTo) {
resolve(messageText);
}
for(let i in cachedTranslations[translateFrom][translateTo]) {
if(cachedTranslations[translateFrom][translateTo][i][0] == messageText) {
logToConsole(LOG_DEBUG, `[Translate]: Using existing translation for ${getGlobalConfig().locale.locales[translateFrom][0]} to ${getGlobalConfig().locale.locales[translateTo][0]} - (${messageText}), (${cachedTranslations[translateFrom][translateTo][i][1]})`);
logToConsole(LOG_DEBUG, `[Translate]: Using existing translation for ${getGlobalConfig().locale.locales[translateFrom].englishName} to ${getGlobalConfig().locale.locales[translateTo].englishName} - (${messageText}), (${cachedTranslations[translateFrom][translateTo][i][1]})`);
resolve(cachedTranslations[translateFrom][translateTo][i][1]);
return true;
}
}
let thisTranslationURL = translateURL.format(encodeURI(messageText), toUpperCase(getGlobalConfig().locale.locales[translateFrom][2]), toUpperCase(getGlobalConfig().locale.locales[translateTo][2]), getGlobalConfig().locale.apiEmail);
let thisTranslationURL = getGlobalConfig().locale.translateURL.format(encodeURI(messageText), toUpperCase(getGlobalConfig().locale.locales[translateFrom].isoCode), toUpperCase(getGlobalConfig().locale.locales[translateTo].isoCode), getGlobalConfig().locale.apiEmail);
httpGet(
thisTranslationURL,
"",

View File

@@ -14,11 +14,16 @@ function initMessagingScript() {
// ===========================================================================
function messageAdminAction(messageText) {
messagePlayerNormal(null, `⚠️ ${messageText}`, getColourByName("orange"));
if(getServerConfig().discordEnabled) {
messageDiscord(`:warning: ${messageText}`);
}
function announceAdminAction(localeString, ...args) {
let clients = getClients();
for(let i in clients) {
let argsArray = [clients[i], localeString];
argsArray = argsArray.concat(args);
let messageText = getLocaleString.apply(null, argsArray);
messagePlayerNormal(clients[i], `⚠️ ${messageText}`, getColourByName("orange"));
}
messageDiscordEventChannel(getLanguageLocaleString.apply(null, [0, localeString].concat(args)));
}
// ===========================================================================
@@ -33,188 +38,195 @@ function messageAdminAction(messageText) {
*
*/
function messagePlayerNormal(client, messageText, colour = COLOUR_WHITE) {
if(isConsole(client) || client == null) {
logToConsole(LOG_INFO, `${removeColoursInMessage(messageText)}`);
}
//if(isConsole(client) || client == null) {
// logToConsole(LOG_INFO, `${removeColoursInMessage(messageText)}`);
//}
sendChatBoxMessageToPlayer(client, `${replaceColoursInMessage(messageText)}`, colour);
return true;
//messageText = replaceColoursInMessage(messageText);
//if(client == null) {
// message(messageText, colour);
//} else {
// messageClient(messageText, client, colour);
//}
sendChatBoxMessageToPlayer(client, messageText, colour);
return true;
}
// ===========================================================================
function messageAdmins(messageText, colour = getColourByName("softRed")) {
let plainMessage = removeColoursInMessage(messageText);
console.warn(`🛡️ ${plainMessage}`);
//
//logToConsole(LOG_WARN, `🛡️ ${plainMessage}`);
let clients = getClients();
for(let i in clients) {
if(doesPlayerHaveStaffPermission(clients[i], getStaffFlagValue("BasicModeration"))) {
messagePlayerNormal(clients[i], `🛡️ ${messageText}`, colour);
}
}
let clients = getClients();
for(let i in clients) {
if(doesPlayerHaveStaffPermission(clients[i], getStaffFlagValue("BasicModeration"))) {
messagePlayerNormal(clients[i], `🛡️ ${messageText}`, colour);
}
}
if(getServerConfig().discordConfig.sendAdminEvents) {
messageDiscordAdminChannel(plainMessage);
}
let plainMessage = removeColoursInMessage(messageText);
messageDiscordAdminChannel(plainMessage);
}
// ===========================================================================
function messagePlayerError(client, messageText) {
if(isConsole(client)) {
logToConsole(LOG_INFO, `${messageText}`);
return true;
}
if(isConsole(client)) {
logToConsole(LOG_INFO, `${messageText}`);
return true;
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `${messageText}`);
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `${messageText}`);
}
}
// ===========================================================================
function messagePlayerSyntax(client, messageText) {
if(isConsole(client)) {
logToConsole(LOG_INFO, `⌨️ ${messageText}`);
return true;
}
if(isConsole(client)) {
logToConsole(LOG_INFO, `⌨️ ${messageText}`);
return true;
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `⌨️ USAGE: {MAINCOLOUR} ${messageText}`, getColourByType("syntaxMessage"));
} else {
messageDiscordUser(client, `⌨️ ${messageText}`);
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `⌨️ USAGE: {MAINCOLOUR} ${messageText}`, getColourByType("syntaxMessage"));
} else {
messageDiscordUser(client, `⌨️ ${messageText}`);
}
}
// ===========================================================================
function messagePlayerAlert(client, messageText) {
if(isConsole(client)) {
logToConsole(LOG_INFO, `⚠️ ${messageText}`);
return true;
}
if(isConsole(client)) {
logToConsole(LOG_INFO, `⚠️ ${messageText}`);
return true;
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `⚠️ ${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `⚠️ ${messageText}`);
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `⚠️ ${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `⚠️ ${messageText}`);
}
}
// ===========================================================================
function messagePlayerSuccess(client, messageText) {
if(isConsole(client)) {
logToConsole(LOG_INFO, `✔️ ${messageText}`);
return true;
}
if(isConsole(client)) {
logToConsole(LOG_INFO, `✔️ ${messageText}`);
return true;
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `✔️ ${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `✔️ ${messageText}`);
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `✔️ ${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `✔️ ${messageText}`);
}
}
// ===========================================================================
function messagePlayerInfo(client, messageText) {
if(isConsole(client)) {
logToConsole(LOG_INFO, ` ${messageText}`);
return true;
}
if(isConsole(client)) {
logToConsole(LOG_INFO, ` ${messageText}`);
return true;
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, ` ${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `:information_source: ${messageText}`);
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, ` ${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `:information_source: ${messageText}`);
}
}
// ===========================================================================
function messagePlayerTip(client, messageText) {
if(isConsole(client)) {
logToConsole(LOG_INFO, ` ${messageText}`);
return true;
}
if(isConsole(client)) {
logToConsole(LOG_INFO, ` ${messageText}`);
return true;
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, ` ${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `:information_source: ${messageText}`);
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, ` ${messageText}`, getColourByName("white"));
} else {
messageDiscordUser(client, `:information_source: ${messageText}`);
}
}
// ===========================================================================
function messagePlayerTalk(client, talkingClient, messageText) {
messagePlayerNormal(client, `🗣️ ${getPlayerAccentInlineOutput(talkingClient)}${getClientSubAccountName(talkingClient)} says: ${messageText}`, getColourByType("talkMessage"));
messagePlayerNormal(client, `🗣️ ${getPlayerAccentInlineOutput(talkingClient)}${getClientSubAccountName(talkingClient)} says: ${messageText}`, getColourByType("talkMessage"));
}
// ===========================================================================
function messagePlayerWhisper(client, whisperingClient, messageText) {
messagePlayerNormal(client, `🤫 ${getPlayerAccentInlineOutput(whisperingClient)}${getClientSubAccountName(whisperingClient)} whispers: ${messageText}`, getColourByType("whisperMessage"));
messagePlayerNormal(client, `🤫 ${getPlayerAccentInlineOutput(whisperingClient)}${getClientSubAccountName(whisperingClient)} whispers: ${messageText}`, getColourByType("whisperMessage"));
}
// ===========================================================================
function messagePlayerMegaPhone(client, shoutingClient, messageText) {
messagePlayerNormal(client, `📢 ${getPlayerAccentInlineOutput(shoutingClient)}${getClientSubAccountName(shoutingClient)} (megaphone): ${messageText}!`, getColourByType("yellow"));
messagePlayerNormal(client, `📢 ${getPlayerAccentInlineOutput(shoutingClient)}${getClientSubAccountName(shoutingClient)} (megaphone): ${messageText}!`, getColourByType("yellow"));
}
// ===========================================================================
function messagePlayerShout(client, shoutingClient, messageText) {
messagePlayerNormal(client, `🗣️ ${getPlayerAccentInlineOutput(shoutingClient)}${getClientSubAccountName(shoutingClient)} shouts: ${messageText}!`, getColourByType("shoutMessage"));
messagePlayerNormal(client, `🗣️ ${getPlayerAccentInlineOutput(shoutingClient)}${getClientSubAccountName(shoutingClient)} shouts: ${messageText}!`, getColourByType("shoutMessage"));
}
// ===========================================================================
function messagePlayerDoAction(client, doingActionClient, messageText) {
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `${messageText} * (${getClientSubAccountName(doingActionClient)})`, getColourByType("doActionMessage"));
}
if(!isClientFromDiscord(client)) {
messagePlayerNormal(client, `${messageText} * (${getClientSubAccountName(doingActionClient)})`, getColourByType("doActionMessage"));
}
}
// ===========================================================================
function messagePlayerMeAction(client, doingActionClient, messageText) {
messagePlayerNormal(client, `${getClientSubAccountName(doingActionClient)} ${messageText}`, getColourByType("meActionMessage"));
messagePlayerNormal(client, `${getClientSubAccountName(doingActionClient)} ${messageText}`, getColourByType("meActionMessage"));
}
// ===========================================================================
function messagePlayerClanChat(client, clanChattingClient, messageText) {
messagePlayerNormal(client, `👥 ${getInlineChatColourByName("clanOrange")}${(getPlayerClanRankName(clanChattingClient) != false) ? getPlayerClanRankName(clanChattingClient) : "No Rank"} ${getCharacterFullName(clanChattingClient)} {MAINCOLOUR}says (clan): {ALTCOLOUR}${messageText}`, getColourByType("clanChatMessage"));
messagePlayerNormal(client, `👥 ${getInlineChatColourByName("clanOrange")}${(getPlayerClanRankName(clanChattingClient) != false) ? getPlayerClanRankName(clanChattingClient) : "No Rank"} ${getCharacterFullName(clanChattingClient)} {MAINCOLOUR}says (clan): {ALTCOLOUR}${messageText}`, getColourByType("clanChatMessage"));
}
// ===========================================================================
function messagePlayerAdminChat(client, adminChattingClient, messageText) {
messagePlayerNormal(client, `🛡️ [ADMIN CHAT] {ALTCOLOUR}${getPlayerData(adminChattingClient).accountData.staffTitle} [#CCCCCC]${getPlayerData(adminChattingClient).accountData.name}: {MAINCOLOUR}${messageText}`, getColourByType("orange"));
messagePlayerNormal(client, `🛡️ [ADMIN CHAT] {ALTCOLOUR}${getPlayerData(adminChattingClient).accountData.staffTitle} [#CCCCCC]${getPlayerData(adminChattingClient).accountData.name}: {MAINCOLOUR}${messageText}`, getColourByType("orange"));
}
// ===========================================================================
function messagePlayerNewbieTip(client, message) {
if(!hasBitFlag(getPlayerData(client).accountData.settings, getAccountSettingsFlagValue("NoActionTips"))) {
messagePlayerNormal(client, `💡 ${message}`);
}
if(!hasBitFlag(getPlayerData(client).accountData.settings, getAccountSettingsFlagValue("NoActionTips"))) {
messagePlayerNormal(client, `💡 ${message}`);
}
}
// ===========================================================================
function messagePlayerTimedRandomTip(client, message) {
if(isPlayerLoggedIn(client) && isPlayerSpawned(client)) {
if(!hasBitFlag(getPlayerData(client).accountData.settings, getAccountSettingsFlagValue("NoRandomTips"))) {
messagePlayerNormal(client, `💡 ${message}`);
}
}
if(isPlayerLoggedIn(client) && isPlayerSpawned(client)) {
if(!hasBitFlag(getPlayerData(client).accountData.settings, getAccountSettingsFlagValue("NoRandomTips"))) {
messagePlayerNormal(client, `💡 ${message}`);
}
}
}
// ===========================================================================
@@ -236,19 +248,18 @@ function clearChatBox(client) {
// ===========================================================================
function replaceEmojiInString(messageString) {
for(let i in emojiReplaceString) {
while(messageString.indexOf(emojiReplaceString[i][0]) != -1) {
messageString = messageString.replace(emojiReplaceString[i][0], emojiReplaceString[i][1]);
function messagePlayerHelpContent(client, messageString) {
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}${messageString}`);
}
// ===========================================================================
function messagePlayersInRace(raceId, message) {
for(let i in clients) {
if(getPlayerRace(clients[i]) == raceId) {
messagePlayerNormal(clients[i], message);
}
}
return messageString;
}
// ===========================================================================
function messagePlayerHelpContent(client, messageString) {
messagePlayerNormal(client, `{clanOrange}• {MAINCOLOUR}${messageString}`);
}
// ===========================================================================
// ===========================================================================

View File

@@ -74,43 +74,47 @@ function toggleMouseCursorCommand(command, params, client) {
// ===========================================================================
function toggleMouseCameraCommand(command, params, client) {
sendPlayerMouseCameraToggle(client);
if (getGame() != VRR_GAME_GTA_VC) {
sendPlayerMouseCameraToggle(client);
}
return true;
}
// ===========================================================================
function setNewCharacterSpawnPositionCommand(command, params, client) {
let position = client.player.position;
let position = getPlayerPosition(client);
let heading = getPlayerHeading(client);
getServerConfig().newCharacter.spawnPosition = position;
getServerConfig().newCharacter.spawnHeading = client.player.heading;
getServerConfig().newCharacter.spawnHeading = heading;
getServerConfig().needsSaved = true;
messagePlayerNormal(client, `The new character spawn position has been set to ${position.x.toFixed(2)}, ${position.y.toFixed(2)}, ${position.z.toFixed(2)}`)
messagePlayerNormal(client, `The new character spawn position has been set to ${position.x.toFixed(2)}, ${position.y.toFixed(2)}, ${position.z.toFixed(2)}`)
return true;
}
// ===========================================================================
function setNewCharacterMoneyCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let amount = toInteger(getParam(params, " ", 1)) || 1000;
let amount = toInteger(getParam(params, " ", 1)) || 1000;
getServerConfig().newCharacter.cash = amount;
getServerConfig().needsSaved = true;
messagePlayerNormal(client, `The new character money has been set to $${amount}`);
messagePlayerNormal(client, `The new character money has been set to $${amount}`);
return true;
}
// ===========================================================================
function setNewCharacterSkinCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
@@ -120,35 +124,35 @@ function setNewCharacterSkinCommand(command, params, client) {
getServerConfig().newCharacter.skin = skinId;
getServerConfig().needsSaved = true;
messagePlayerNormal(client, `The new character skin has been set to ${getSkinNameFromModel(skinId)} (Index ${skinId})`);
messagePlayerNormal(client, `The new character skin has been set to ${getSkinNameFromModel(skinId)} (Index ${skinId})`);
return true;
}
// ===========================================================================
function submitIdeaCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
submitIdea(client, params);
messagePlayerNormal(client, `Your suggestion/idea has been sent to the developers!`);
messagePlayerNormal(client, `Your suggestion/idea has been sent to the developers!`);
return true;
}
// ===========================================================================
function submitBugReportCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
submitBugReport(client, params);
messagePlayerNormal(client, `Your bug report has been sent to the developers!`);
messagePlayerNormal(client, `Your bug report has been sent to the developers!`);
return true;
}
@@ -159,86 +163,86 @@ function enterExitPropertyCommand(command, params, client) {
let isEntrance = false;
let isBusiness = false;
if(areServerElementsSupported()) {
if(!getPlayerData(client).currentPickup) {
if (areServerElementsSupported()) {
if (!getPlayerData(client).currentPickup) {
return false;
}
let ownerType = getEntityData(getPlayerData(client).currentPickup, "vrr.owner.type");
let ownerId = getEntityData(getPlayerData(client).currentPickup, "vrr.owner.id");
switch(ownerType) {
switch (ownerType) {
case VRR_PICKUP_BUSINESS_ENTRANCE:
isBusiness = true;
isEntrance = true;
closestProperty = getServerData().businesses[ownerId];
break;
case VRR_PICKUP_BUSINESS_EXIT:
isBusiness = true;
isEntrance = false;
closestProperty = getServerData().businesses[ownerId];
break;
case VRR_PICKUP_HOUSE_ENTRANCE:
isBusiness = false;
isEntrance = true;
closestProperty = getServerData().houses[ownerId];
break;
case VRR_PICKUP_HOUSE_EXIT:
isBusiness = false;
isEntrance = false;
closestProperty = getServerData().houses[ownerId];
break;
default:
return false;
}
}
} else {
for(let i in getServerData().businesses) {
if(getPlayerDimension(client) == getGameConfig().mainWorldDimension[getGame()] && getPlayerInterior(client) == getGameConfig().mainWorldInterior[getGame()]) {
for (let i in getServerData().businesses) {
if (getPlayerDimension(client) == getGameConfig().mainWorldDimension[getGame()] && getPlayerInterior(client) == getGameConfig().mainWorldInterior[getGame()]) {
let businessId = getClosestBusinessEntrance(getPlayerPosition(client), getPlayerDimension(client));
isBusiness = true;
isEntrance = true;
closestProperty = getServerData().businesses[businessId];
closestProperty = getServerData().businesses[businessId];
} else {
let businessId = getClosestBusinessExit(getPlayerPosition(client), getPlayerDimension(client));
isBusiness = true;
isEntrance = false;
closestProperty = getServerData().businesses[businessId];
closestProperty = getServerData().businesses[businessId];
}
}
for(let j in getServerData().houses) {
if(getPlayerDimension(client) == getGameConfig().mainWorldDimension[getGame()] && getPlayerInterior(client) == getGameConfig().mainWorldInterior[getGame()]) {
for (let j in getServerData().houses) {
if (getPlayerDimension(client) == getGameConfig().mainWorldDimension[getGame()] && getPlayerInterior(client) == getGameConfig().mainWorldInterior[getGame()]) {
let houseId = getClosestHouseEntrance(getPlayerPosition(client), getPlayerDimension(client));
isBusiness = false;
isEntrance = true;
closestProperty = getServerData().businesses[houseId];
closestProperty = getServerData().businesses[houseId];
} else {
let houseId = getClosestHouseExit(getPlayerPosition(client), getPlayerDimension(client));
isBusiness = false;
isEntrance = false;
closestProperty = getServerData().businesses[houseId];
closestProperty = getServerData().businesses[houseId];
}
}
}
if(closestProperty == null) {
if (closestProperty == null) {
return false;
}
logToConsole(LOG_DEBUG, `${getPlayerDisplayForConsole(client)}'s closest door is ${(isBusiness) ? closestProperty.name : closestProperty.description} ${(isEntrance) ? "entrance" : "exit"}`);
if(isEntrance) {
if(getDistance(closestProperty.entrancePosition, getPlayerPosition(client)) <= getGlobalConfig().enterPropertyDistance) {
if(closestProperty.locked) {
if (isEntrance) {
if (getDistance(closestProperty.entrancePosition, getPlayerPosition(client)) <= getGlobalConfig().enterPropertyDistance) {
if (closestProperty.locked) {
meActionToNearbyPlayers(client, getLocaleString(client, "EnterExitPropertyDoorLocked", (isBusiness) ? getLocaleString(client, "Business") : getLocaleString(client, "House")));
return false;
}
if(!closestProperty.hasInterior) {
if (!closestProperty.hasInterior) {
messagePlayerAlert(client, getLocaleString(client, "PropertyNoInterior", (isBusiness) ? getLocaleString(client, "Business") : getLocaleString(client, "House")));
return false;
}
@@ -247,25 +251,27 @@ function enterExitPropertyCommand(command, params, client) {
getPlayerData(client).pedState = VRR_PEDSTATE_ENTERINGPROPERTY;
meActionToNearbyPlayers(client, getLocaleString(client, "EntersProperty", (isBusiness) ? getLocaleString(client, "Business") : getLocaleString(client, "House")));
if(isFadeCameraSupported()) {
if (isFadeCameraSupported()) {
fadeCamera(client, false, 1.0);
}
setTimeout(function() {
setPlayerPosition(client, closestProperty.exitPosition);
setPlayerHeading(client, closestProperty.exitRotation);
setTimeout(function () {
setPlayerInCutsceneInterior(client, closestProperty.exitCutscene);
setPlayerDimension(client, closestProperty.exitDimension);
setPlayerInterior(client, closestProperty.exitInterior);
setTimeout(function() {
if(isFadeCameraSupported()) {
setPlayerPosition(client, closestProperty.exitPosition);
setPlayerHeading(client, closestProperty.exitRotation);
setTimeout(function () {
if (isFadeCameraSupported()) {
fadeCamera(client, true, 1.0);
}
updateInteriorLightsForPlayer(client, closestProperty.interiorLights);
}, 1000);
//setPlayerInCutsceneInterior(client, closestProperty.exitCutscene);
//updateAllInteriorVehiclesForPlayer(client, closestProperty.exitInterior, closestProperty.exitDimension);
}, 1100);
if(closestProperty.streamingRadioStation != -1) {
if(getRadioStationData(closestProperty.streamingRadioStation)) {
if (closestProperty.streamingRadioStation != -1) {
if (getRadioStationData(closestProperty.streamingRadioStation)) {
playRadioStreamForPlayer(client, getRadioStationData(closestProperty.streamingRadioStation).url);
getPlayerData(client).streamingRadioStation = closestProperty.streamingRadioStation;
}
@@ -273,8 +279,8 @@ function enterExitPropertyCommand(command, params, client) {
return true;
}
} else {
if(getDistance(closestProperty.exitPosition, getPlayerPosition(client)) <= getGlobalConfig().exitPropertyDistance) {
if(closestProperty.locked) {
if (getDistance(closestProperty.exitPosition, getPlayerPosition(client)) <= getGlobalConfig().exitPropertyDistance) {
if (closestProperty.locked) {
meActionToNearbyPlayers(client, getLocaleString(client, "EnterExitPropertyDoorLocked", (isBusiness) ? getLocaleString(client, "Business") : getLocaleString(client, "House")));
return false;
}
@@ -282,25 +288,29 @@ function enterExitPropertyCommand(command, params, client) {
clearPlayerStateToEnterExitProperty(client)
meActionToNearbyPlayers(client, getLocaleString(client, "ExitsProperty", (isBusiness) ? getLocaleString(client, "Business") : getLocaleString(client, "House")));
if(isFadeCameraSupported()) {
if (isFadeCameraSupported()) {
fadeCamera(client, false, 1.0);
}
disableCityAmbienceForPlayer(client, true);
setTimeout(function() {
setTimeout(function () {
setPlayerInCutsceneInterior(client, closestProperty.entranceCutscene);
setPlayerPosition(client, closestProperty.entrancePosition);
setPlayerHeading(client, closestProperty.entranceRotation);
setPlayerDimension(client, closestProperty.entranceDimension);
setPlayerInterior(client, closestProperty.entranceInterior);
setTimeout(function() {
if(isFadeCameraSupported()) {
setTimeout(function () {
if (isFadeCameraSupported()) {
fadeCamera(client, true, 1.0);
}
updateInteriorLightsForPlayer(client, true);
}, 1000);
}, 1100);
//setPlayerInCutsceneInterior(client, closestProperty.entranceCutscene);
stopRadioStreamForPlayer(client);
getPlayerData(client).streamingRadioStation = -1;
//logToConsole(LOG_DEBUG, `[VRR.Misc] ${getPlayerDisplayForConsole(client)} exited business ${inBusiness.name}[${inBusiness.index}/${inBusiness.databaseId}]`);
return true;
}
@@ -314,37 +324,39 @@ function enterExitPropertyCommand(command, params, client) {
function getPlayerInfoCommand(command, params, client) {
let targetClient = client;
if(!areParamsEmpty(params)) {
if(doesPlayerHaveStaffPermission(client, getStaffFlagValue("BasicModeration"))) {
if (!areParamsEmpty(params)) {
if (doesPlayerHaveStaffPermission(client, getStaffFlagValue("BasicModeration"))) {
targetClient = getPlayerFromParams(params);
if(!getPlayerData(targetClient)) {
if (!getPlayerData(targetClient)) {
messagePlayerError(client, getLocaleString(client, "InvalidPlayer"));
return false;
}
}
}
messagePlayerNormal(client, `{clanOrange}== {jobYellow}Player Info {clanOrange}==============================`);
messagePlayerNormal(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderPlayerInfo")));
let clan = (getPlayerCurrentSubAccount(targetClient).clan != 0) ? `{ALTCOLOUR}${getClanData(getClanIdFromDatabaseId(getPlayerCurrentSubAccount(targetClient).clan)).name}[${getPlayerCurrentSubAccount(targetClient).clan}] (Rank: ${getClanRankData(getPlayerCurrentSubAccount(targetClient).clan, getPlayerCurrentSubAccount(targetClient).clanRank).name}[Level: ${getClanRankData(getPlayerCurrentSubAccount(targetClient).clan, getPlayerCurrentSubAccount(targetClient).clanRank).level}, DBID: ${getClanRankData(getPlayerCurrentSubAccount(targetClient).clan, getPlayerCurrentSubAccount(targetClient).clanRank).databaseId}` : `(None)`;
let job = (getPlayerCurrentSubAccount(targetClient).job != 0) ? `{ALTCOLOUR}${getJobData(getJobIdFromDatabaseId(getPlayerCurrentSubAccount(targetClient).job)).name}[${getPlayerCurrentSubAccount(targetClient).job}] (Rank: ${getPlayerCurrentSubAccount(targetClient).jobRank})` : `(None)`;
let stats = [
`{MAINCOLOUR}Account: {ALTCOLOUR}${getPlayerData(targetClient).accountData.name}[${getPlayerData(targetClient).accountData.databaseId}]`,
`{MAINCOLOUR}Character: {ALTCOLOUR}${getCharacterFullName(targetClient)}[${getPlayerCurrentSubAccount(targetClient).databaseId}]`,
`{MAINCOLOUR}Connected: {ALTCOLOUR}${getTimeDifferenceDisplay(Math.ceil(sdl.tick/1000), getPlayerData(targetClient).connectTime)} ago`,
`{MAINCOLOUR}Registered: ${getPlayerData(targetClient).accountData}`,
`{MAINCOLOUR}Game Version: {ALTCOLOUR}${targetClient.gameVersion}`,
`{MAINCOLOUR}Client Version: {ALTCOLOUR}${getPlayerData(targetClient).clientVersion}`,
`{MAINCOLOUR}Skin: {ALTCOLOUR}${getSkinNameFromModel(getPlayerCurrentSubAccount(targetClient).skin)}[${getPlayerCurrentSubAccount(targetClient).skin}]`,
`{MAINCOLOUR}Clan: {ALTCOLOUR}${clan}`,
`{MAINCOLOUR}Job: {ALTCOLOUR}${job}`,
let tempStats = [
["Account", `${getPlayerData(targetClient).accountData.name}[${getPlayerData(targetClient).accountData.databaseId}]`],
["Character", `${getCharacterFullName(targetClient)}[${getPlayerCurrentSubAccount(targetClient).databaseId}]`],
["Connected", `${getTimeDifferenceDisplay(getCurrentUnixTimestamp(), getPlayerData(targetClient).connectTime)} ago`],
["Registered", `${getPlayerData(targetClient).accountData.registerDate}`],
["Game Version", `${targetClient.gameVersion}`],
["Client Version", `${getPlayerData(targetClient).clientVersion}`],
["Skin", `${getSkinNameFromModel(getPlayerCurrentSubAccount(targetClient).skin)}[${getPlayerCurrentSubAccount(targetClient).skin}]`],
["Clan", `${clan}`],
["Job", `${job}`],
["Cash", `${getPlayerCurrentSubAccount(client).cash}`],
]
let stats = tempStats.map(stat => `{MAINCOLOUR}${stat[0]}: {ALTCOLOUR}${stat[1]}{MAINCOLOUR}`);
let chunkedList = splitArrayIntoChunks(stats, 6);
for(let i in chunkedList) {
for (let i in chunkedList) {
messagePlayerInfo(client, chunkedList[i].join(", "));
}
}
@@ -352,7 +364,11 @@ function getPlayerInfoCommand(command, params, client) {
// ===========================================================================
function playerChangeAFKState(client, afkState) {
getPlayerData(client).afk = afkState;
if (!getPlayerData(client)) {
return false;
}
getPlayerData(client).afk = afkState;
updateAllPlayerNameTags();
}
@@ -360,12 +376,12 @@ function playerChangeAFKState(client, afkState) {
function checkPlayerSpawning() {
let clients = getClients();
for(let i in clients) {
if(!isConsole(clients[i])) {
if(getPlayerData(clients[i])) {
if(getPlayerData(clients[i]).loggedIn) {
if(!getPlayerData(clients[i]).ped) {
if(clients[i].player != null) {
for (let i in clients) {
if (!isConsole(clients[i])) {
if (getPlayerData(clients[i])) {
if (isPlayerLoggedIn(clients[i])) {
if (!getPlayerData(clients[i]).ped) {
if (clients[i].player != null) {
//getPlayerData(clients[i]).ped = clients[i].player;
onPlayerSpawn(clients[i].player);
}
@@ -378,25 +394,28 @@ function checkPlayerSpawning() {
// ===========================================================================
function showPlayerPrompt(client, promptType, promptMessage, promptTitle) {
if(promptType == VRR_PROMPT_NONE) {
return false;
}
getPlayerData(client).promptType = promptType;
if(canPlayerUseGUI(client)) {
showPlayerPromptGUI(client, promptMessage, promptTitle);
function showPlayerPrompt(client, promptMessage, promptTitle, yesButtonText, noButtonText) {
if (canPlayerUseGUI(client)) {
showPlayerPromptGUI(client, promptMessage, promptTitle, yesButtonText, noButtonText);
} else {
messagePlayerNormal(client, `${promptMessage}`);
messagePlayerInfo(client, `{MAINCOLOUR}Use {ALTCOLOUR}/yes or {ALTCOLOUR}/no`);
messagePlayerInfo(client, getLocaleString(client, "PromptResponseTip", `{ALTCOLOUR}/yes{MAINCOLOUR}`, `{ALTCOLOUR}/no{MAINCOLOUR}`));
}
}
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function updateServerGameTime() {
if(isTimeSupported()) {
if (isTimeSupported()) {
game.time.hour = getServerConfig().hour;
game.time.minute = getServerConfig().minute;
}
@@ -404,16 +423,25 @@ function updateServerGameTime() {
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function listOnlineAdminsCommand(command, params, client) {
//== Admins ===================================
messagePlayerNormal(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderAdminsList")));
let admins = [];
let clients = getClients();
for(let i in clients) {
if(getPlayerData(clients[i])) {
if(typeof getPlayerData(clients[i]).accountData.flags.admin != "undefined") {
if(getPlayerData(clients[i]).accountData.flags.admin > 0 || getPlayerData(clients[i]).accountData.flags.admin == -1) {
for (let i in clients) {
if (getPlayerData(clients[i])) {
if (typeof getPlayerData(clients[i]).accountData.flags.admin != "undefined") {
if (getPlayerData(clients[i]).accountData.flags.admin > 0 || getPlayerData(clients[i]).accountData.flags.admin == -1) {
admins.push(`{ALTCOLOUR}[${getPlayerData(clients[i]).accountData.staffTitle}] {MAINCOLOUR}${getCharacterFullName(clients[i])}`);
}
}
@@ -421,79 +449,341 @@ function listOnlineAdminsCommand(command, params, client) {
}
let chunkedList = splitArrayIntoChunks(admins, 3);
for(let i in chunkedList) {
for (let i in chunkedList) {
messagePlayerInfo(client, chunkedList[i].join(", "));
}
}
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function stuckPlayerCommand(command, params, client) {
if((getCurrentUnixTimestamp()-getPlayerData(client).lastStuckCommand) < getGlobalConfig().stuckCommandInterval) {
messagePlayerError(client, "CantUseCommandYet");
return false;
}
if ((getCurrentUnixTimestamp() - getPlayerData(client).lastStuckCommand) < getGlobalConfig().stuckCommandInterval) {
messagePlayerError(client, "CantUseCommandYet");
return false;
}
let dimension = getPlayerDimension(client);
let interior = getPlayerInterior(client);
let dimension = getPlayerDimension(client);
let interior = getPlayerInterior(client);
messagePlayerAlert(client, getLocaleString(client, "FixingStuck"));
messagePlayerAlert(client, getLocaleString(client, "FixingStuck"));
if(getGameConfig().skinChangePosition[getServerGame()].length > 0) {
if(getPlayerData(client).returnToPosition != null && getPlayerData(client).returnToType == VRR_RETURNTO_TYPE_SKINSELECT) {
messagePlayerAlert(client, "You canceled the skin change.");
restorePlayerCamera(client);
if (getGameConfig().skinChangePosition[getGame()].length > 0) {
if (getPlayerData(client).returnToPosition != null && getPlayerData(client).returnToType == VRR_RETURNTO_TYPE_SKINSELECT) {
messagePlayerAlert(client, "You canceled the skin change.");
restorePlayerCamera(client);
setPlayerPosition(client, getPlayerData(client).returnToPosition);
setPlayerHeading(client, getPlayerData(client).returnToHeading);
setPlayerInterior(client, getPlayerData(client).returnToInterior);
setPlayerDimension(client, getPlayerData(client).returnToDimension);
setPlayerPosition(client, getPlayerData(client).returnToPosition);
setPlayerHeading(client, getPlayerData(client).returnToHeading);
setPlayerInterior(client, getPlayerData(client).returnToInterior);
setPlayerDimension(client, getPlayerData(client).returnToDimension);
getPlayerData(client).returnToPosition = null;
getPlayerData(client).returnToHeading = null;
getPlayerData(client).returnToInterior = null;
getPlayerData(client).returnToDimension = null;
getPlayerData(client).returnToPosition = null;
getPlayerData(client).returnToHeading = null;
getPlayerData(client).returnToInterior = null;
getPlayerData(client).returnToDimension = null;
getPlayerData(client).returnToType = VRR_RETURNTO_TYPE_NONE;
}
}
getPlayerData(client).returnToType = VRR_RETURNTO_TYPE_NONE;
}
}
//if(getPlayerData(client).returnToPosition != null && getPlayerData(client).returnToType == VRR_RETURNTO_TYPE_ADMINGET) {
// messagePlayerError(client, `You were teleported by an admin and can't use the stuck command`);
// return false;
//}
//if(getPlayerData(client).returnToPosition != null && getPlayerData(client).returnToType == VRR_RETURNTO_TYPE_ADMINGET) {
// messagePlayerError(client, `You were teleported by an admin and can't use the stuck command`);
// return false;
//}
if(dimension > 0) {
let businesses = getServerData().businesses;
for(let i in businesses) {
if(businesses[i].exitDimension == dimension) {
setPlayerPosition(client, businesses[i].entrancePosition);
setPlayerDimension(client, businesses[i].entranceDimension);
setPlayerInterior(client, businesses[i].entranceInterior);
if (dimension > 0) {
let businesses = getServerData().businesses;
for (let i in businesses) {
if (businesses[i].exitDimension == dimension) {
setPlayerPosition(client, businesses[i].entrancePosition);
setPlayerDimension(client, businesses[i].entranceDimension);
setPlayerInterior(client, businesses[i].entranceInterior);
return true;
}
}
return true;
}
}
let houses = getServerData().houses;
for(let i in houses) {
if(houses[i].exitDimension == dimension) {
setPlayerPosition(client, houses[i].entrancePosition);
setPlayerDimension(client, houses[i].entranceDimension);
setPlayerInterior(client, houses[i].entranceInterior);
let houses = getServerData().houses;
for (let i in houses) {
if (houses[i].exitDimension == dimension) {
setPlayerPosition(client, houses[i].entrancePosition);
setPlayerDimension(client, houses[i].entranceDimension);
setPlayerInterior(client, houses[i].entranceInterior);
return true;
}
}
} else {
setPlayerDimension(client, 1);
setPlayerDimension(client, getGameConfig().mainWorldDimension[getGame()]);
setPlayerInterior(client, getGameConfig().mainWorldInterior[getGame()]);
setPlayerPosition(client, getPosAbovePos(getPlayerPosition(client), 2.0));
}
return true;
}
}
} else {
setPlayerDimension(client, 1);
setPlayerDimension(client, getGameConfig().mainWorldDimension[getGame()]);
setPlayerInterior(client, getGameConfig().mainWorldInterior[getGame()]);
setPlayerPosition(client, getPosAbovePos(getPlayerPosition(client), 2.0));
}
setPlayerInterior(client, 0);
setPlayerDimension(client, 0);
setPlayerInterior(client, 0);
setPlayerDimension(client, 0);
}
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function playerPedSpeakCommand(command, params, client) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
makePlayerPedSpeak(client, params);
}
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function lockCommand(command, params, client) {
if (isPlayerInAnyVehicle(client)) {
let vehicle = getPlayerVehicle(client);
if (!getVehicleData(vehicle)) {
messagePlayerError(client, getLocaleString(client, "RandomVehicleCommandsDisabled"));
return false;
}
if (!isPlayerInFrontVehicleSeat(client)) {
messagePlayerError(client, getLocaleString(client, "MustBeInVehicleFrontSeat"));
return false;
}
getVehicleData(vehicle).locked = !getVehicleData(vehicle).locked;
setVehicleLocked(vehicle, getVehicleData(vehicle).locked);
getVehicleData(vehicle).needsSaved = true;
meActionToNearbyPlayers(client, `${toLowerCase(getLockedUnlockedFromBool(getVehicleData(vehicle).locked))} the ${getVehicleName(vehicle)}`);
return true;
} else {
let vehicle = getClosestVehicle(getPlayerPosition(client));
if (getDistance(getPlayerPosition(client), getVehiclePosition(vehicle)) <= getGlobalConfig().vehicleLockDistance) {
if (!getVehicleData(vehicle)) {
messagePlayerError(client, getLocaleString(client, "RandomVehicleCommandsDisabled"));
return false;
}
if (!doesPlayerHaveVehicleKeys(client, vehicle)) {
messagePlayerError(client, getLocaleString(client, "DontHaveVehicleKey"));
return false;
}
getVehicleData(vehicle).locked = !getVehicleData(vehicle).locked;
setVehicleLocked(vehicle, getVehicleData(vehicle).locked);
getVehicleData(vehicle).needsSaved = true;
meActionToNearbyPlayers(client, `${toLowerCase(getLockedUnlockedFromBool(getVehicleData(vehicle).locked))} the ${getVehicleName(vehicle)}`);
return true;
}
let businessId = getPlayerBusiness(client);
if (businessId != -1) {
if (!canPlayerManageBusiness(client, businessId)) {
messagePlayerError(client, getLocaleString(client, "CantModifyBusiness"));
return false;
}
getBusinessData(businessId).locked = !getBusinessData(businessId).locked;
updateBusinessPickupLabelData(businessId);
getBusinessData(businessId).needsSaved = true;
messagePlayerSuccess(client, `${getLockedUnlockedEmojiFromBool((getBusinessData(businessId).locked))} Business {businessBlue}${getBusinessData(businessId).name} {MAINCOLOUR}${getLockedUnlockedFromBool((getBusinessData(businessId).locked))}!`);
return true;
}
let houseId = getPlayerHouse(client);
if (houseId != -1) {
if (!canPlayerManageHouse(client, houseId)) {
messagePlayerError(client, getLocaleString(client, "CantModifyHouse"));
return false;
}
getHouseData(houseId).locked = !getHouseData(houseId).locked;
updateHousePickupLabelData(houseId);
getHouseData(houseId).needsSaved = true;
messagePlayerSuccess(client, `House {houseGreen}${getHouseData(houseId).description} {MAINCOLOUR}${getLockedUnlockedFromBool((getHouseData(houseId).locked))}!`);
return true;
}
}
}
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function lightsCommand(command, params, client) {
if (isPlayerInAnyVehicle(client)) {
let vehicle = getPlayerVehicle(client);
if (!getVehicleData(vehicle)) {
messagePlayerError(client, getLocaleString(client, "RandomVehicleCommandsDisabled"));
return false;
}
if (!isPlayerInFrontVehicleSeat(client)) {
messagePlayerError(client, getLocaleString(client, "MustBeInVehicleFrontSeat"));
return false;
}
getVehicleData(vehicle).lights = !getVehicleData(vehicle).lights;
setVehicleLights(vehicle, getVehicleData(vehicle).lights)
getVehicleData(vehicle).needsSaved = true;
meActionToNearbyPlayers(client, `turned ${toLowerCase(getOnOffFromBool(getVehicleData(vehicle).lights))} the ${getVehicleName(vehicle)}'s lights`);
} else {
/*
let vehicle = getClosestVehicle(getPlayerPosition(client));
if(vehicle != false) {
if(getDistance(getPlayerPosition(client), getVehiclePosition(vehicle)) <= getGlobalConfig().vehicleLockDistance) {
return false;
}
if(!getVehicleData(vehicle)) {
messagePlayerError(client, getLocaleString(client, "RandomVehicleCommandsDisabled"));
return false;
}
if(!doesPlayerHaveVehicleKeys(client, vehicle)) {
messagePlayerError(client, getLocaleString(client, "DontHaveVehicleKey"));
return false;
}
getVehicleData(vehicle).lights = !getVehicleData(vehicle).lights;
setVehicleLights(vehicle, getVehicleData(vehicle).lights);
getVehicleData(vehicle).needsSaved = true;
meActionToNearbyPlayers(client, `${toLowerCase(getLockedUnlockedFromBool(getVehicleData(vehicle).locked))} the ${getVehicleName(vehicle)}`);
return true;
}
*/
let businessId = getPlayerBusiness(client);
if (businessId != -1) {
if (!canPlayerManageBusiness(client, businessId)) {
messagePlayerError(client, getLocaleString(client, "CantModifyBusiness"));
return false;
}
getBusinessData(businessId).interiorLights = !getBusinessData(businessId).interiorLights;
getBusinessData(businessId).needsSaved = true;
let clients = getClients();
for (let i in clients) {
if (getPlayerBusiness(client) == getPlayerBusiness(clients[i]) && getPlayerDimension(clients[i]) == getBusinessData(businessId).exitDimension) {
updateInteriorLightsForPlayer(clients[i], getBusinessData(businessId).interiorLights);
}
}
meActionToNearbyPlayers(client, `turned ${toLowerCase(getOnOffFromBool((getBusinessData(businessId).interiorLights)))} on the business lights`);
return true;
}
let houseId = getPlayerHouse(client);
if (houseId != -1) {
if (!canPlayerManageHouse(client, houseId)) {
messagePlayerError(client, getLocaleString(client, "CantModifyHouse"));
return false;
}
getHouseData(houseId).interiorLights = !getHouseData(houseId).interiorLights;
getHouseData(houseId).needsSaved = true;
let clients = getClients();
for (let i in clients) {
if (getPlayerHouse(client) == getPlayerHouse(clients[i]) && getPlayerDimension(clients[i]) == getHouseData(houseId).exitDimension) {
updateInteriorLightsForPlayer(clients[i], getHouseData(houseId).interiorLights);
}
}
meActionToNearbyPlayers(client, `turned ${toLowerCase(getOnOffFromBool((getHouseData(houseId).interiorLights)))} on the house lights`);
return true;
}
}
}
// ===========================================================================
function resetPlayerBlip(client) {
deletePlayerBlip(client);
createPlayerBlip(client);
}
// ===========================================================================
function createPlayerBlip(client) {
if (!areServerElementsSupported()) {
return false;
}
if (!isGameFeatureSupported("attachedBlips")) {
return false;
}
if (getServerConfig().createPlayerBlips) {
return false;
}
let blip = createAttachedGameBlip(getPlayerPed(client), 0, 1, getPlayerColour(client));
if (blip) {
if (getGlobalConfig().playerBlipStreamInDistance == -1 || getGlobalConfig().playerBlipStreamOutDistance == -1) {
blip.netFlags.distanceStreaming = false;
} else {
setElementStreamInDistance(blip, getGlobalConfig().playerBlipStreamInDistance);
setElementStreamOutDistance(blip, getGlobalConfig().playerBlipStreamOutDistance);
}
getPlayerData(client).playerBlip = blip;
}
}
// ===========================================================================
function deletePlayerBlip(client) {
if (!isGameFeatureSupported("attachedBlips")) {
return false;
}
if (getPlayerData(client).playerBlip != null) {
deleteGameElement(getPlayerData(client).playerBlip);
getPlayerData(client).playerBlip = null;
}
}
// ===========================================================================

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -181,50 +181,42 @@ class NPCTriggerResponseData {
// ===========================================================================
function initNPCScript() {
getServerData().npcs = loadNPCsFromDatabase();
setAllNPCDataIndexes();
spawnAllNPCs();
logToConsole(LOG_INFO, "[VRR.NPC]: Initializing NPC script ...");
logToConsole(LOG_INFO, "[VRR.NPC]: NPC script initialized successfully!");
}
// ===========================================================================
/**
* @param {Ped} ped - The data index of the NPC
* @param {Number} npcId - The data index of the NPC
* @return {NPCData} The NPC's data (class instancee)
*/
function getNPCData(ped) {
if(ped.getData("vrr.dataIndex")) {
return ped.getData("vrr.dataIndex");
function getNPCData(npcId) {
if (typeof getServerData().npcs[npcId] != "undefined") {
return getServerData().npcs[npcId];
}
return false;
return false;
}
// ===========================================================================
function createNPCCommand(client, command, params) {
if(areParamsEmpty(params)) {
function createNPCCommand(command, params, client) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let skinId = getSkinModelIndexFromParams(params);
let skinIndex = getSkinModelIndexFromParams(params);
if(!skinId) {
messagePlayerError(client, `Invalid skin`);
if (!skinIndex) {
messagePlayerError(client, getLocaleString(client, "InvalidSkin"));
return false;
}
let position = getPosInFrontOfPos(getPlayerPosition(client), getPlayerHeading(client), 3);
let tempNPCData = new NPCData(false);
tempNPCData.position = position;
tempNPCData.heading = getPlayerHeading(client);
tempNPCData.skin = skinId;
let npcIndex = getServerData().npcs.push(tempNPCData);
spawnNPC(npcIndex-1);
let position = getPlayerPosition(client);
setPlayerPosition(client, getPosBehindPos(position, getPlayerHeading(client), 1.5))
let npcId = createNPC(skinIndex, position, getPlayerHeading(client), getPlayerInterior(client), getPlayerDimension(client));
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} created a {ALTCOLOUR}${getSkinNameFromIndex(getNPCData(npcId).skin)}{MAINCOLOUR} NPC!`);
}
// ===========================================================================
@@ -234,13 +226,13 @@ function loadNPCsFromDatabase() {
let dbConnection = connectToDatabase();
let tempNPCs = [];
let dbAssoc;
if(dbConnection) {
if (dbConnection) {
let dbQueryString = `SELECT * FROM npc_main WHERE npc_server = ${getServerId()} AND npc_enabled = 1`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
while(dbAssoc = fetchQueryAssoc(dbQuery)) {
if (dbQuery) {
while (dbAssoc = fetchQueryAssoc(dbQuery)) {
let tempNPCData = new NPCData(dbAssoc);
tempNPCData.triggers = loadNPCTriggersFromDatabase();
tempNPCData.triggers = loadNPCTriggersFromDatabase(tempNPCData.databaseId);
tempNPCs.push(tempNPCData);
}
freeDatabaseQuery(dbQuery);
@@ -259,11 +251,11 @@ function loadNPCTriggersFromDatabase(npcDatabaseId) {
let dbConnection = connectToDatabase();
let tempNPCTriggers = [];
let dbAssoc;
if(dbConnection) {
if (dbConnection) {
let dbQueryString = `SELECT * FROM npc_trig WHERE npc_trig_npc = ${npcDatabaseId} AND npc_trig_enabled = 1`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
while(dbAssoc = fetchQueryAssoc(dbQuery)) {
if (dbQuery) {
while (dbAssoc = fetchQueryAssoc(dbQuery)) {
let tempNPCTriggerData = new NPCTriggerData(dbAssoc);
tempNPCTriggerData.conditions = loadNPCTriggerConditionsFromDatabase(tempNPCTriggerData.databaseId);
tempNPCTriggerData.responses = loadNPCTriggerResponsesFromDatabase(tempNPCTriggerData.databaseId);
@@ -285,11 +277,11 @@ function loadNPCTriggerConditionsFromDatabase(npcTriggerDatabaseId) {
let dbConnection = connectToDatabase();
let tempNPCTriggerConditions = [];
let dbAssoc;
if(dbConnection) {
if (dbConnection) {
let dbQueryString = `SELECT * FROM npc_cond WHERE npc_cond_trig = ${npcTriggerDatabaseId} AND npc_cond_enabled = 1`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
while(dbAssoc = fetchQueryAssoc(dbQuery)) {
if (dbQuery) {
while (dbAssoc = fetchQueryAssoc(dbQuery)) {
let tempNPCTriggerConditionData = new NPCTriggerConditionData(dbAssoc);
tempNPCTriggerConditions.push(tempNPCTriggerConditionData);
}
@@ -309,11 +301,11 @@ function loadNPCTriggerResponsesFromDatabase(npcTriggerDatabaseId) {
let dbConnection = connectToDatabase();
let tempNPCTriggerResponses = [];
let dbAssoc;
if(dbConnection) {
if (dbConnection) {
let dbQueryString = `SELECT * FROM npc_resp WHERE npc_resp_trig = ${npcTriggerDatabaseId} AND npc_resp_enabled = 1`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
while(dbAssoc = fetchQueryAssoc(dbQuery)) {
if (dbQuery) {
while (dbAssoc = fetchQueryAssoc(dbQuery)) {
let tempNPCTriggerResponseData = new NPCTriggerResponseData(dbAssoc);
tempNPCTriggerResponses.push(tempNPCTriggerResponseData);
}
@@ -329,128 +321,118 @@ function loadNPCTriggerResponsesFromDatabase(npcTriggerDatabaseId) {
// ===========================================================================
function saveAllNPCsToDatabase() {
for(let i in getServerData().npcs) {
if (getServerConfig().devServer) {
return false;
}
for (let i in getServerData().npcs) {
saveNPCToDatabase(i);
}
}
// ===========================================================================
function saveNPCToDatabase(npc) {
if(getNPCData(vehicleDataId) == null) {
// Invalid vehicle data
function saveNPCToDatabase(npcDataId) {
if (getServerConfig().devServer) {
logToConsole(LOG_VERBOSE, `[VRR.NPC]: NPC ${npcDataId} can't be saved because server is running as developer only. Aborting save ...`);
return false;
}
let tempVehicleData = getServerData().vehicles[vehicleDataId];
if(tempVehicleData.databaseId == -1) {
// Temp vehicle, no need to save
if (getNPCData(npcDataId) == false) {
logToConsole(LOG_VERBOSE, `[VRR.NPC]: NPC ${npcDataId} data is invalid. Aborting save ...`);
return false;
}
if(!tempVehicleData.needsSaved) {
// Vehicle hasn't changed. No need to save.
let tempNPCData = getNPCData(npcDataId);
if (tempNPCData.databaseId == -1) {
logToConsole(LOG_VERBOSE, `[VRR.NPC]: NPC ${npcDataId} is a temp NPC. Aborting save ...`);
return false;
}
logToConsole(LOG_VERBOSE, `[VRR.Vehicle]: Saving vehicle ${tempVehicleData.databaseId} to database ...`);
if (!tempNPCData.needsSaved) {
logToConsole(LOG_VERBOSE, `[VRR.NPC]: NPC ${npcDataId} hasn't changed data. Aborting save ...`);
return false;
}
logToConsole(LOG_VERBOSE, `[VRR.NPC]: Saving NPC ${tempNPCData.databaseId} to database ...`);
let dbConnection = connectToDatabase();
if(dbConnection) {
if(tempVehicleData.vehicle != false) {
if(!tempVehicleData.spawnLocked) {
if(areServerElementsSupported()) {
tempVehicleData.spawnPosition = tempVehicleData.vehicle.position;
tempVehicleData.spawnRotation = tempVehicleData.vehicle.heading;
if (dbConnection) {
if (tempNPCData.ped != false) {
if (!tempNPCData.spawnLocked) {
if (areServerElementsSupported()) {
tempNPCData.position = tempNPCData.ped.position;
tempNPCData.heading = tempNPCData.ped.heading;
} else {
tempVehicleData.spawnPosition = tempVehicleData.syncPosition;
tempVehicleData.spawnRotation = tempVehicleData.syncHeading;
tempNPCData.position = tempNPCData.syncPosition;
tempNPCData.heading = tempNPCData.syncHeading;
}
}
}
let safeAnimationName = escapeDatabaseString(dbConnection, tempNPCData.animationName);
let safeName = escapeDatabaseString(dbConnection, tempNPCData.name);
let data = [
["veh_server", getServerId()],
["veh_model", toInteger(tempVehicleData.model)],
["veh_owner_type", toInteger(tempVehicleData.ownerType)],
["veh_owner_id", toInteger(tempVehicleData.ownerId)],
["veh_locked", boolToInt(tempVehicleData.locked)],
["veh_spawn_lock", boolToInt(tempVehicleData.spawnLocked)],
["veh_buy_price", toInteger(tempVehicleData.buyPrice)],
["veh_rent_price", toInteger(tempVehicleData.rentPrice)],
["veh_pos_x", toFloat(tempVehicleData.spawnPosition.x)],
["veh_pos_y", toFloat(tempVehicleData.spawnPosition.y)],
["veh_pos_z", toFloat(tempVehicleData.spawnPosition.z)],
["veh_rot_z", toFloat(tempVehicleData.spawnRotation)],
["veh_col1", toInteger(tempVehicleData.colour1)],
["veh_col2", toInteger(tempVehicleData.colour2)],
["veh_col3", toInteger(tempVehicleData.colour3)],
["veh_col4", toInteger(tempVehicleData.colour4)],
["veh_col1_isrgb", boolToInt(tempVehicleData.colour1IsRGBA)],
["veh_col2_isrgb", boolToInt(tempVehicleData.colour2IsRGBA)],
["veh_col3_isrgb", boolToInt(tempVehicleData.colour3IsRGBA)],
["veh_col4_isrgb", boolToInt(tempVehicleData.colour4IsRGBA)],
["veh_extra1", tempVehicleData.extras[0]],
["veh_extra2", tempVehicleData.extras[1]],
["veh_extra3", tempVehicleData.extras[2]],
["veh_extra4", tempVehicleData.extras[3]],
["veh_extra5", tempVehicleData.extras[4]],
["veh_extra6", tempVehicleData.extras[5]],
["veh_extra7", tempVehicleData.extras[6]],
["veh_extra8", tempVehicleData.extras[7]],
["veh_extra9", tempVehicleData.extras[8]],
["veh_extra10", tempVehicleData.extras[9]],
["veh_extra11", tempVehicleData.extras[10]],
["veh_extra12", tempVehicleData.extras[11]],
["veh_extra13", tempVehicleData.extras[12]],
["veh_engine", intToBool(tempVehicleData.engine)],
["veh_lights", intToBool(tempVehicleData.lights)],
["veh_health", toInteger(tempVehicleData.health)],
["veh_damage_engine", toInteger(tempVehicleData.engineDamage)],
["veh_damage_visual", toInteger(tempVehicleData.visualDamage)],
["veh_dirt_level", toInteger(tempVehicleData.dirtLevel)],
["veh_int", toInteger(tempVehicleData.interior)],
["veh_vw", toInteger(tempVehicleData.dimension)],
["veh_livery", toInteger(tempVehicleData.livery)],
["npc_server", getServerId()],
["npc_skin", toInteger(tempNPCData.skin)],
["npc_name", safeName],
["npc_owner_type", toInteger(tempNPCData.ownerType)],
["npc_owner_id", toInteger(tempNPCData.ownerId)],
["npc_pos_x", toFloat(tempNPCData.position.x)],
["npc_pos_y", toFloat(tempNPCData.position.y)],
["npc_pos_z", toFloat(tempNPCData.position.z)],
["npc_rot_z", toFloat(tempNPCData.heading)],
["npc_scale_x", toFloat(tempNPCData.scale.x)],
["npc_scale_y", toFloat(tempNPCData.scale.y)],
["npc_scale_z", toFloat(tempNPCData.scale.z)],
["npc_animation", safeAnimationName],
["npc_health", toInteger(tempNPCData.health)],
["npc_armour", toInteger(tempNPCData.armour)],
["npc_invincible", boolToInt(tempNPCData.invincible)],
["npc_heedthreats", boolToInt(tempNPCData.heedThreats)],
["npc_threats", toInteger(tempNPCData.threats)],
["npc_stay", boolToInt(tempNPCData.stay)],
["npc_type_flags", toInteger(tempNPCData.typeFlags)],
];
let dbQuery = null;
if(tempVehicleData.databaseId == 0) {
let queryString = createDatabaseInsertQuery("veh_main", data);
if (tempNPCData.databaseId == 0) {
let queryString = createDatabaseInsertQuery("npc_main", data);
dbQuery = queryDatabase(dbConnection, queryString);
getServerData().vehicles[vehicleDataId].databaseId = getDatabaseInsertId(dbConnection);
getServerData().vehicles[vehicleDataId].needsSaved = false;
tempNPCData.databaseId = getDatabaseInsertId(dbConnection);
tempNPCData.needsSaved = false;
} else {
let queryString = createDatabaseUpdateQuery("veh_main", data, `veh_id=${tempVehicleData.databaseId}`);
let queryString = createDatabaseUpdateQuery("npc_main", data, `npc_id=${tempNPCData.databaseId}`);
dbQuery = queryDatabase(dbConnection, queryString);
getServerData().vehicles[vehicleDataId].needsSaved = false;
tempNPCData.needsSaved = false;
}
freeDatabaseQuery(dbQuery);
disconnectFromDatabase(dbConnection);
return true;
}
logToConsole(LOG_VERBOSE, `[VRR.Vehicle]: Saved vehicle ${vehicleDataId} to database!`);
logToConsole(LOG_VERBOSE, `[VRR.NPC]: Saved NPC ${npcDataId} to database!`);
return false;
}
// ===========================================================================
function setAllNPCDataIndexes() {
for(let i in getServerData().npcs) {
function setNPCDataIndexes() {
for (let i in getServerData().npcs) {
getServerData().npcs[i].index = i;
for(let j in getServerData().npcs[i].triggers) {
for (let j in getServerData().npcs[i].triggers) {
getServerData().npcs[i].triggers[j].index = j;
getServerData().npcs[i].triggers[j].npcIndex = i;
for(let k in getServerData().npcs[i].triggers[j].conditions) {
for (let k in getServerData().npcs[i].triggers[j].conditions) {
getServerData().npcs[i].triggers[j].conditions[k].index = k;
getServerData().npcs[i].triggers[j].conditions[m].triggerIndex = j;
}
for(let m in getServerData().npcs[i].triggers[j].responses) {
for (let m in getServerData().npcs[i].triggers[j].responses) {
getServerData().npcs[i].triggers[j].responses[m].index = m;
getServerData().npcs[i].triggers[j].responses[m].triggerIndex = j;
}
@@ -461,19 +443,238 @@ function setAllNPCDataIndexes() {
// ===========================================================================
function spawnNPC(npcIndex) {
let civilian = createGameCivilian(getNPCData(npcIndex).model, getNPCData(npcIndex).spawnPosition, getNPCData(npcIndex).spawnRotation);
if(civilian) {
civilian.setData("vrr.dataIndex", npcIndex);
getNPCData(npcIndex).ped = civilian;
let npcData = getNPCData(npcIndex);
let ped = createGamePed(npcData.skin, npcData.position, npcData.rotation.z);
if (ped) {
getNPCData(npcIndex).ped = ped;
setEntityData(ped, "vrr.dataIndex", npcIndex, false);
if (npcData.animationName != "") {
let animationId = getAnimationFromParams(npcData.animationName);
if (animationId != false) {
setEntityData(ped, "vrr.anim", animationId, true);
}
}
setElementDimension(ped, npcData.dimension);
setElementInterior(ped, npcData.interior);
}
}
// ===========================================================================
function spawnAllNPCs() {
for(let i in getServerData().npcs) {
spawnNPC(npcIndex);
for (let i in getServerData().npcs) {
spawnNPC(i);
}
}
// ===========================================================================
function deleteNPCCommand(command, params, client) {
let closestNPC = getClosestNPC(getPlayerPosition(client), getPlayerDimension(client), getPlayerInterior(client));
if (!getNPCData(closestNPC)) {
messagePlayerError(client, getLocaleString(client, "InvalidNPC"));
return false;
}
let npcName = getNPCData(closestNPC).name;
deleteNPC(closestNPC);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} deleted NPC {npcPink}${npcName}`);
}
// ===========================================================================
function deleteNPC(npcId) {
quickDatabaseQuery(`DELETE FROM npc_main WHERE npc_id=${getNPCData(npcId).databaseId}`);
if (getNPCData(npcId)) {
if (getNPCData(npcId).ped != false) {
deleteEntity(getNPCData(npcId).ped);
}
getServerData().npcs.splice(npcId, 1);
}
setNPCDataIndexes();
}
// ===========================================================================
function setNPCAnimationCommand(command, params, client) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let closestNPC = getClosestNPC(getPlayerPosition(client), getPlayerDimension(client), getPlayerInterior(client));
let animationId = getAnimationFromParams(getParam(params, " ", 1));
let animationPositionOffset = 1;
if (!getNPCData(closestNPC)) {
messagePlayerError(client, getLocaleString(client, "InvalidNPC"));
return false;
}
if (!getAnimationData(animationId)) {
messagePlayerError(client, getLocaleString(client, "InvalidAnimation"));
return false;
}
if (areThereEnoughParams(params, 2, " ")) {
if (toInteger(animationPositionOffset) < 0 || toInteger(animationPositionOffset) > 3) {
messagePlayerError(client, getLocaleString(client, "InvalidAnimationDistance"));
return false;
}
animationPositionOffset = getParam(params, " ", 2);
}
getNPCData(closestNPC).animationName = getAnimationData(animationId).name;
getNPCData(closestNPC).needsSaved = true;
makePedPlayAnimation(getNPCData(closestNPC).ped, animationId, animationPositionOffset);
messagePlayerSuccess(client, getLocaleString(client, "NPCAnimationSet", `{ALTCOLOUR}${getNPCData(closestNPC).name}{MAINCOLOUR}`, `{ALTCOLOUR}${getAnimationData(animationId).name}{MAINCOLOUR}`));
}
// ===========================================================================
function setNPCNameCommand(command, params, client) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let closestNPC = getClosestNPC(getPlayerPosition(client), getPlayerDimension(client), getPlayerInterior(client));
let name = params;
if (!getNPCData(closestNPC)) {
messagePlayerError(client, getLocaleString(client, "InvalidNPC"));
return false;
}
let oldName = getNPCData(closestNPC).name;
getNPCData(closestNPC).name = name;
getNPCData(closestNPC).needsSaved = true;
setElementName(getNPCData(closestNPC).ped, name);
messagePlayerSuccess(client, getLocaleString(client, "NPCNameSet", `{ALTCOLOUR}${oldName}{MAINCOLOUR}`, `{ALTCOLOUR}${getNPCData(closestNPC).name}{MAINCOLOUR}`));
}
// ===========================================================================
function toggleNPCLookAtClosestPlayerCommand(command, params, client) {
let closestNPC = getClosestNPC(getPlayerPosition(client), getPlayerDimension(client), getPlayerInterior(client));
if (!getNPCData(closestNPC)) {
messagePlayerError(client, getLocaleString(client, "InvalidNPC"));
return false;
}
getNPCData(closestNPC).lookAtClosestPlayer = !getNPCData(closestNPC).lookAtClosestPlayer;
getNPCData(closestNPC).needsSaved = true;
setEntityData(getNPCData(closestNPC).ped, "vrr.lookAtClosestPlayer", getNPCData(closestNPC).lookAtClosestPlayer, true);
forcePlayerToSyncElementProperties(null, getNPCData(closestNPC).ped);
//messagePlayerSuccess(client, getLocaleString(client, "NPCLookAtClosestPlayerSet", `{ALTCOLOUR}${getNPCData(closestNPC).name}{MAINCOLOUR}));
}
// ===========================================================================
function getNPCInfoCommand(command, params, client) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let closestNPC = getClosestNPC(getPlayerPosition(client));
if (!getNPCData(closestNPC)) {
messagePlayerError(client, getLocaleString(client, "InvalidNPC"));
return false;
}
let npcData = getNPCData(closestNPC);
let ownerName = "Nobody";
let ownerType = "None";
switch (npcData.ownerType) {
case VRR_NPCOWNER_CLAN:
ownerName = getClanData(getClanIdFromDatabaseId(npcData.ownerId)).name;
ownerType = "clan";
break;
case VRR_NPCOWNER_JOB:
ownerName = getJobData(getJobIdFromDatabaseId(npcData.ownerId)).name;
ownerType = "job";
break;
case VRR_NPCOWNER_PLAYER:
let subAccountData = loadSubAccountFromId(npcData.ownerId);
ownerName = `${subAccountData.firstName} ${subAccountData.lastName} [${subAccountData.databaseId}]`;
ownerType = "player";
break;
case VRR_NPCOWNER_BIZ:
ownerName = getBusinessData(getBusinessIdFromDatabaseId(npcData.ownerId)).name;
ownerType = "business";
break;
case VRR_NPCOWNER_PUBLIC:
ownerName = "Nobody";
ownerType = "public";
break;
default:
break;
}
let tempStats = [
[`Skin`, `${getGameConfig().skins[npcData.skin][0]} (${getGameConfig().skins[npcData.skin][1]})`],
[`ID`, `${npcData.index}/${npcData.databaseId}`],
[`Owner`, `${ownerName} (${ownerType})`],
[`Animation`, `${npcData.animationName}`],
];
let stats = tempStats.map(stat => `{MAINCOLOUR}${stat[0]}: {ALTCOLOUR}${stat[1]}{MAINCOLOUR}`);
messagePlayerNormal(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderNPCInfo")));
let chunkedList = splitArrayIntoChunks(stats, 6);
for (let i in chunkedList) {
messagePlayerInfo(client, chunkedList[i].join(", "));
}
}
// ===========================================================================
function getClosestNPC(position, interior, dimension) {
let npcs = getServerData().npcs;
let closest = 0;
for (let i in npcs) {
if (getDistance(npcs[i].ped.position, position) < getDistance(npcs[closest].ped.position, position) && npcs[closest].interior == interior && npcs[closest].dimension == dimension) {
closest = i;
}
}
return closest;
}
// ===========================================================================
function createNPC(skinIndex, position, heading, interior, dimension) {
let tempNPCData = new NPCData(false);
tempNPCData.position = position;
tempNPCData.rotation = toVector3(0.0, 0.0, heading);
tempNPCData.skin = skinIndex;
tempNPCData.interior = interior;
tempNPCData.dimension = dimension;
tempNPCData.animationName = "";
tempNPCData.needsSaved = true;
let npcIndex = getServerData().npcs.push(tempNPCData);
setNPCDataIndexes();
spawnNPC(npcIndex - 1);
return npcIndex - 1;
}
// ===========================================================================

149
scripts/server/race.js Normal file
View File

@@ -0,0 +1,149 @@
// ===========================================================================
// Vortrex's Roleplay Resource
// https://github.com/VortrexFTW/gtac_roleplay
// ===========================================================================
// FILE: race.js
// DESC: Provides racing usage and functions
// TYPE: Server (JavaScript)
// ===========================================================================
function initRaceScript() {
logToConsole(LOG_INFO, "[VRR.Race]: Initializing race script ...");
logToConsole(LOG_INFO, "[VRR.Race]: Race script initialized successfully!");
}
// ===========================================================================
/**
* @param {Number} raceId - The data index of the race
* @return {RaceData} The race's data (class instance)
*/
function getRaceData(raceId) {
if(typeof getServerData().races[raceId] != "undefined") {
return getServerData().races[raceId];
}
return false;
}
// ===========================================================================
function setAllRaceDataIndexes() {
for(let i in getServerData().races) {
getServerData().races[i].index = i;
}
}
// ===========================================================================
function loadRacesFromDatabase() {
// To-do
return [];
}
// ===========================================================================
function saveRacesToDatabase() {
if(getServerConfig().devServer) {
return false;
}
for(let i in getServerData().races) {
saveRaceToDatabase(getServerData().races[i]);
}
}
// ===========================================================================
function saveRaceToDatabase(raceData) {
return true;
}
// ===========================================================================
function createRaceCommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let raceId = getRaceFromParams(params);
if(raceId == false) {
messagePlayerError(client, "A race with that name already exists!");
return false;
}
createRace(params);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} created race {ALTCOLOUR}${params}`);
}
// ===========================================================================
function createRaceCommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let raceId = createRace(params, getPlayerPosition(client));
getRaceData(raceId).enabled = false;
initRace(raceId);
joinRace(client, raceId);
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} created race {ALTCOLOUR}${params}`);
}
// ===========================================================================
function createRaceLocationCommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let raceId = getPlayerRace(client);
if(raceId == false) {
messagePlayerError(client, "You are not in a race!");
return false;
}
let raceLocationName = params;
createRaceLocation(raceId, raceLocationName, getPlayerPosition(client));
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} created race {ALTCOLOUR}${params}`);
}
// ===========================================================================
function createRaceLocationCommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let raceId = getPlayerRace(client);
if(raceId == false) {
messagePlayerError(client, "You are not in a race!");
return false;
}
let raceLocationName = params;
createRaceLocation(raceId, raceLocationName, getPlayerPosition(client));
messageAdmins(`{adminOrange}${getPlayerName(client)}{MAINCOLOUR} created race {ALTCOLOUR}${params}`);
}
// ===========================================================================
function stopRacingCommand(command, params, client) {
if(!isPlayerInARace(client)) {
messagePlayerError(client, "You aren't in a race!");
return false;
}
leaveRace(client);
messagePlayerSuccess(client, "You left the race!");
messagePlayersInRace(`${getCharacterFullName(client)} left the race!`);
checkRemainingPlayersInRace(raceId)
}
// ===========================================================================

View File

@@ -30,8 +30,6 @@ class RadioStationData {
function initRadioScript() {
logToConsole(LOG_INFO, "[VRR.Radio]: Initializing radio script ...");
getServerData().radioStations = loadRadioStationsFromDatabase();
setRadioStationIndexes();
logToConsole(LOG_INFO, "[VRR.Radio]: Radio script initialized successfully!");
return true;
}
@@ -62,6 +60,15 @@ function loadRadioStationsFromDatabase() {
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function playStreamingRadioCommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
@@ -77,13 +84,16 @@ function playStreamingRadioCommand(command, params, client) {
}
if(isPlayerInAnyVehicle(client)) {
if(!getVehicleData(getPlayerVehicle(client))) {
let vehicle = getPlayerVehicle(client);
if(!getVehicleData(vehicle)) {
messagePlayerError(client, getLocaleString(client, "RandomVehicleCommandsDisabled"));
return false;
}
if(radioStationId == 0) {
getVehicleData(getPlayerVehicle(client)).streamingRadioStation = -1;
getVehicleData(vehicle).streamingRadioStation = -1;
getVehicleData(vehicle).needsSaved = true;
getPlayerData(client).streamingRadioStation = -1;
meActionToNearbyPlayers(client, `turns off their vehicle's radio`);
@@ -96,13 +106,13 @@ function playStreamingRadioCommand(command, params, client) {
return false;
}
getVehicleData(getPlayerVehicle(client)).streamingRadioStation = radioStationId-1;
getVehicleData(vehicle).streamingRadioStation = radioStationId-1;
getPlayerData(client).streamingRadioStation = radioStationId-1;
meActionToNearbyPlayers(client, getLocaleString(client, "ActionVehicleRadioStationChange", getRadioStationData(radioStationId-1).name, getRadioStationData(radioStationId-1).genre));
let clients = getClients();
for(let i in clients) {
if(getPlayerVehicle(client) == getPlayerVehicle(clients[i])) {
if(vehicle == getPlayerVehicle(clients[i])) {
playRadioStreamForPlayer(clients[i], getRadioStationData(radioStationId-1).url, true, getPlayerStreamingRadioVolume(client));
}
}
@@ -111,6 +121,7 @@ function playStreamingRadioCommand(command, params, client) {
let houseId = getEntityData(client, "vrr.inHouse");
if(radioStationId == 0) {
getHouseData(houseId).streamingRadioStation = -1;
getHouseData(houseId).needsSaved = true;
getPlayerData(client).streamingRadioStation = -1;
meActionToNearbyPlayers(client, `turns off the house radio`);
@@ -122,6 +133,7 @@ function playStreamingRadioCommand(command, params, client) {
}
} else {
getHouseData(houseId).streamingRadioStation = radioStationId-1;
getHouseData(houseId).needsSaved = true;
getPlayerData(client).streamingRadioStation = radioStationId-1;
meActionToNearbyPlayers(client, getLocaleString(client, "ActionHouseRadioStationChange", getRadioStationData(radioStationId-1).name, getRadioStationData(radioStationId-1).genre));
@@ -136,6 +148,7 @@ function playStreamingRadioCommand(command, params, client) {
let businessId = getPlayerBusiness(client);
if(radioStationId == 0) {
getBusinessData(businessId).streamingRadioStation = -1;
getBusinessData(businessId).needsSaved = true;
getPlayerData(client).streamingRadioStation = -1;
meActionToNearbyPlayers(client, `turns off the business radio`);
@@ -147,6 +160,7 @@ function playStreamingRadioCommand(command, params, client) {
}
} else {
getBusinessData(businessId).streamingRadioStation = radioStationId-1;
getBusinessData(businessId).needsSaved = true;
getPlayerData(client).streamingRadioStation = radioStationId-1;
meActionToNearbyPlayers(client, getLocaleString(client, "ActionBusinessRadioStationChange", getRadioStationData(radioStationId-1).name, getRadioStationData(radioStationId-1).genre));
@@ -166,6 +180,15 @@ function playStreamingRadioCommand(command, params, client) {
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function setStreamingRadioVolumeCommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
@@ -206,6 +229,15 @@ function getPlayerStreamingRadioVolume(client) {
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function showRadioStationListCommand(command, params, client) {
let stationList = getServerData().radioStations.map(function(x) { return `{ALTCOLOUR}${toInteger(x.index)+1}: {MAINCOLOUR}${x.name}`; });
@@ -220,7 +252,7 @@ function showRadioStationListCommand(command, params, client) {
// ===========================================================================
function setRadioStationIndexes() {
function setAllRadioStationIndexes() {
for(let i in getServerData().radioStations) {
getServerData().radioStations[i].index = i;
}
@@ -228,19 +260,32 @@ function setRadioStationIndexes() {
// ===========================================================================
/**
* @param {number} radioStationId - The data index of the radio station
* @return {RadioStationData} The radio station's data (class instance)
*/
function getRadioStationData(radioStationId) {
return getServerData().radioStations[radioStationId];
}
// ===========================================================================
/**
* This is a command handler function.
*
* @param {string} command - The command name used by the player
* @param {string} params - The parameters/args string used with the command by the player
* @param {Client} client - The client/player that used the command
* @return {bool} Whether or not the command was successful
*
*/
function reloadAllRadioStationsCommand(command, params, client) {
stopRadioStreamForPlayer(null);
clearArray(getServerData().radioStations);
getServerData().radioStations = loadRadioStationsFromDatabase();
setRadioStationIndexes();
messageAdminAction(`All radio stations have been reloaded by an admin!`);
announceAdminAction(`AllRadioStationsReloaded`);
}
// ===========================================================================

File diff suppressed because it is too large Load Diff

View File

@@ -38,20 +38,28 @@ function initServerScripts() {
initEconomyScript();
initRadioScript();
initLocaleScript();
initCommandScript();
serverStartTime = getCurrentUnixTimestamp();
// Load config and stuff
loadGlobalConfig();
loadServerConfig();
applyConfigToServer(getServerConfig());
// Load all the server data
loadServerDataFromDatabase();
setAllServerDataIndexes();
createAllServerElements();
initAllClients();
initTimers();
serverStartTime = getCurrentUnixTimestamp();
}
// ===========================================================================
function checkForHashingModule() {
if(typeof module.hashing == "undefined") {
if (typeof module.hashing == "undefined") {
return false;
}
return true;
@@ -60,7 +68,7 @@ function checkForHashingModule() {
// ===========================================================================
function checkForMySQLModule() {
if(typeof module.mysql == "undefined") {
if (typeof module.mysql == "undefined") {
return false;
}
@@ -70,7 +78,7 @@ function checkForMySQLModule() {
// ===========================================================================
function checkForSMTPModule() {
if(typeof module.smtp == "undefined") {
if (typeof module.smtp == "undefined") {
return false;
}
@@ -82,21 +90,21 @@ function checkForSMTPModule() {
function checkForAllRequiredModules() {
logToConsole(LOG_DEBUG, "[VRR.Startup]: Checking for required modules ...");
if(!checkForHashingModule()) {
console.warn("[VRR.Startup]: Hashing module is not loaded!");
console.warn("[VRR.Startup]: This resource will now shutdown.");
if (!checkForHashingModule()) {
logToConsole(LOG_WARN, "[VRR.Startup]: Hashing module is not loaded!");
logToConsole(LOG_WARN, "[VRR.Startup]: This resource will now shutdown.");
thisResource.stop();
}
if(!checkForMySQLModule()) {
console.warn("[VRR.Startup]: MySQL module is not loaded!");
console.warn("[VRR.Startup]: This resource will now shutdown.");
if (!checkForMySQLModule()) {
logToConsole(LOG_WARN, "[VRR.Startup]: MySQL module is not loaded!");
logToConsole(LOG_WARN, "[VRR.Startup]: This resource will now shutdown.");
thisResource.stop();
}
if(!checkForSMTPModule()) {
console.warn("[VRR.Startup]: SMTP Email module is not loaded!");
console.warn("[VRR.Startup]: Email features will NOT be available!");
if (!checkForSMTPModule()) {
logToConsole(LOG_WARN, "[VRR.Startup]: SMTP Email module is not loaded!");
logToConsole(LOG_WARN, "[VRR.Startup]: Email features will NOT be available!");
}
logToConsole(LOG_DEBUG, "[VRR.Startup]: All required modules loaded!");
@@ -105,6 +113,72 @@ function checkForAllRequiredModules() {
// ===========================================================================
function loadServerDataFromDatabase() {
logToConsole(LOG_INFO, "[VRR.Config]: Loading server data ...");
// Always load these regardless of "test server" status
getServerData().localeStrings = loadAllLocaleStrings();
getServerData().allowedSkins = getAllowedSkins(getGame());
getServerData().itemTypes = loadItemTypesFromDatabase();
// Translation Cache
getServerData().cachedTranslations = new Array(getGlobalConfig().locale.locales.length);
getServerData().cachedTranslationFrom = new Array(getGlobalConfig().locale.locales.length);
getServerData().cachedTranslationFrom.fill([]);
getServerData().cachedTranslations.fill(getServerData().cachedTranslationFrom);
// Only load these if the server isn't a testing/dev server
if (!getServerConfig().devServer) {
getServerData().items = loadItemsFromDatabase();
getServerData().businesses = loadBusinessesFromDatabase();
getServerData().houses = loadHousesFromDatabase();
getServerData().vehicles = loadVehiclesFromDatabase();
getServerData().clans = loadClansFromDatabase();
getServerData().npcs = loadNPCsFromDatabase();
getServerData().races = loadRacesFromDatabase();
getServerData().radioStations = loadRadioStationsFromDatabase();
getServerData().gates = loadGatesFromDatabase();
getServerData().jobs = loadJobsFromDatabase();
}
getServerData().commands = loadCommands();
}
// ===========================================================================
function setAllServerDataIndexes() {
setAllItemTypeDataIndexes();
setAllItemDataIndexes();
setBusinessDataIndexes();
setHouseDataIndexes();
setAllClanDataIndexes();
setAllJobDataIndexes();
setNPCDataIndexes();
setAllRaceDataIndexes();
setAllRadioStationIndexes();
cacheAllGroundItems();
cacheAllBusinessItems();
cacheAllCommandsAliases();
}
// ===========================================================================
function createAllServerElements() {
createAllBusinessPickups();
createAllBusinessBlips();
createAllHousePickups();
createAllHouseBlips();
createAllJobPickups();
createAllJobBlips();
createAllGroundItemObjects();
spawnAllVehicles();
spawnAllNPCs();
addAllCommandHandlers();
}
// ===========================================================================
initServerScripts();
// ===========================================================================

View File

@@ -126,12 +126,12 @@ function initSubAccountScript() {
function loadSubAccountFromName(firstName, lastName) {
let dbConnection = connectToDatabase();
if(dbConnection) {
if (dbConnection) {
firstName = escapeDatabaseString(dbConnection, firstName);
lastName = escapeDatabaseString(dbConnection, lastName);
let dbQueryString = `SELECT * FROM sacct_main INNER JOIN sacct_svr ON sacct_svr.sacct_svr_sacct=sacct_main.sacct_id AND sacct_svr.sacct_svr_server=${getServerId()} WHERE sacct_name_first = '${firstName}' AND sacct_name_last = '${lastName}' LIMIT 1;`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
if (dbQuery) {
let dbAssoc = fetchQueryAssoc(dbQuery);
freeDatabaseQuery(dbQuery);
return new SubAccountData(dbAssoc);
@@ -146,10 +146,10 @@ function loadSubAccountFromName(firstName, lastName) {
function loadSubAccountFromId(subAccountId) {
let dbConnection = connectToDatabase();
if(dbConnection) {
if (dbConnection) {
let dbQueryString = `SELECT * FROM sacct_main INNER JOIN sacct_svr ON sacct_svr.sacct_svr_sacct=sacct_main.sacct_id AND sacct_svr.sacct_svr_server=${getServerId()} WHERE sacct_id = ${subAccountId} LIMIT 1;`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
if (dbQuery) {
let dbAssoc = fetchQueryAssoc(dbQuery);
freeDatabaseQuery(dbQuery);
return new SubAccountData(dbAssoc);
@@ -165,31 +165,31 @@ function loadSubAccountFromId(subAccountId) {
function loadSubAccountsFromAccount(accountId) {
let tempSubAccounts = [];
let dbAssoc = false;
if(accountId > 0) {
if (accountId > 0) {
let dbConnection = connectToDatabase();
if(dbConnection) {
if (dbConnection) {
let dbQueryString = `SELECT * FROM sacct_main INNER JOIN sacct_svr ON sacct_svr.sacct_svr_sacct=sacct_main.sacct_id AND sacct_svr.sacct_svr_server=${getServerId()} WHERE sacct_acct = ${accountId} AND sacct_server = ${getServerId()}`;
let dbQuery = queryDatabase(dbConnection, dbQueryString);
if(dbQuery) {
while(dbAssoc = fetchQueryAssoc(dbQuery)) {
if (dbQuery) {
while (dbAssoc = fetchQueryAssoc(dbQuery)) {
let tempSubAccount = new SubAccountData(dbAssoc);
// Make sure skin is valid
if(tempSubAccount.skin == -1) {
if (tempSubAccount.skin == -1) {
tempSubAccount.skin = getServerConfig().newCharacter.skin;
}
// Check if clan and rank are still valid
if(tempSubAccount.clan != 0) {
if (tempSubAccount.clan != 0) {
let clanId = getClanIdFromDatabaseId(tempSubAccount.clan);
if(!getClanData(clanId)) {
if (!getClanData(clanId)) {
tempSubAccount.clan = 0;
tempSubAccount.clanRank = 0;
tempSubAccount.clanTitle = "";
tempSubAccount.clanFlags = 0;
} else {
let rankId = getClanRankIdFromDatabaseId(clanId, tempSubAccount.clanRank);
if(!getClanRankData(clanId, rankId)) {
if (!getClanRankData(clanId, rankId)) {
tempSubAccount.clanRank = 0;
}
}
@@ -211,7 +211,7 @@ function loadSubAccountsFromAccount(accountId) {
function saveSubAccountToDatabase(subAccountData) {
let dbConnection = connectToDatabase();
if(dbConnection) {
if (dbConnection) {
let safeClanTag = escapeDatabaseString(dbConnection, subAccountData.ClanTag);
let safeClanTitle = escapeDatabaseString(dbConnection, subAccountData.clanTitle);
let safeFirstName = escapeDatabaseString(dbConnection, subAccountData.firstName);
@@ -281,7 +281,7 @@ function saveSubAccountToDatabase(subAccountData) {
["sacct_svr_hd_prop_rightwrist_model", subAccountData.bodyProps.rightWrist[0]],
["sacct_svr_hd_prop_rightwrist_texture", subAccountData.bodyProps.rightWrist[1]],
["sacct_svr_hd_prop_hip_model", subAccountData.bodyProps.hip[0]],
["sacct_svr_hd_prop_hip_texture",subAccountData.bodyProps.hip[1]],
["sacct_svr_hd_prop_hip_texture", subAccountData.bodyProps.hip[1]],
["sacct_svr_hd_prop_leftfoot_model", subAccountData.bodyProps.leftFoot[0]],
["sacct_svr_hd_prop_leftfoot_texture", subAccountData.bodyProps.leftFoot[1]],
["sacct_svr_hd_prop_rightfoot_model", subAccountData.bodyProps.rightFoot[0]],
@@ -295,7 +295,7 @@ function saveSubAccountToDatabase(subAccountData) {
freeDatabaseQuery(dbQuery);
disconnectFromDatabase(dbConnection);
}
}
}
// ===========================================================================
@@ -306,7 +306,7 @@ function createSubAccount(accountId, firstName, lastName) {
let dbConnection = connectToDatabase();
let dbQuery = false;
if(dbConnection) {
if (dbConnection) {
firstName = fixCharacterName(firstName);
lastName = fixCharacterName(lastName);
let safeFirstName = escapeDatabaseString(dbConnection, firstName);
@@ -314,13 +314,13 @@ function createSubAccount(accountId, firstName, lastName) {
dbQuery = queryDatabase(dbConnection, `INSERT INTO sacct_main (sacct_acct, sacct_name_first, sacct_name_last, sacct_pos_x, sacct_pos_y, sacct_pos_z, sacct_rot_z, sacct_cash, sacct_server, sacct_health, sacct_when_made, sacct_when_lastlogin) VALUES (${accountId}, '${safeFirstName}', '${safeLastName}', ${getServerConfig().newCharacter.spawnPosition.x}, ${getServerConfig().newCharacter.spawnPosition.y}, ${getServerConfig().newCharacter.spawnPosition.z}, ${getServerConfig().newCharacter.spawnHeading}, ${getServerConfig().newCharacter.money}, ${getServerId()}, 100, CURRENT_TIMESTAMP(), 0)`);
//if(dbQuery) {
if(getDatabaseInsertId(dbConnection) > 0) {
let dbInsertId = getDatabaseInsertId(dbConnection);
createDefaultSubAccountServerData(dbInsertId, getServerConfig().newCharacter.skin);
let tempSubAccount = loadSubAccountFromId(dbInsertId);
return tempSubAccount;
}
//freeDatabaseQuery(dbQuery);
if (getDatabaseInsertId(dbConnection) > 0) {
let dbInsertId = getDatabaseInsertId(dbConnection);
createDefaultSubAccountServerData(dbInsertId, getServerConfig().newCharacter.skin);
let tempSubAccount = loadSubAccountFromId(dbInsertId);
return tempSubAccount;
}
//freeDatabaseQuery(dbQuery);
//}
disconnectFromDatabase(dbConnection);
}
@@ -333,21 +333,21 @@ function createSubAccount(accountId, firstName, lastName) {
function showCharacterSelectToClient(client) {
getPlayerData(client).switchingCharacter = true;
if(doesPlayerHaveAutoSelectLastCharacterEnabled(client)) {
if(getPlayerData(client).subAccounts.length > 0) {
if (doesPlayerHaveAutoSelectLastCharacterEnabled(client)) {
if (getPlayerData(client).subAccounts.length > 0) {
logToConsole(LOG_DEBUG, `[VRR.SubAccount] ${getPlayerDisplayForConsole(client)} is being auto-spawned as character ID ${getPlayerLastUsedSubAccount(client)}`);
selectCharacter(client, getPlayerLastUsedSubAccount(client));
return true;
}
}
if(doesServerHaveGUIEnabled() && doesPlayerHaveGUIEnabled(client)) {
if (doesServerHaveGUIEnabled() && doesPlayerHaveGUIEnabled(client)) {
getPlayerData(client).currentSubAccount = 0;
logToConsole(LOG_DEBUG, `[VRR.SubAccount] Setting ${getPlayerDisplayForConsole(client)}'s character to ID ${getPlayerData(client).currentSubAccount}`);
let tempSubAccount = getPlayerData(client).subAccounts[0];
let ClanName = (tempSubAccount.clan != 0) ? getClanData(getClanIdFromDatabaseId(tempSubAccount.clan)).name : "None";
let lastPlayedText = (tempSubAccount.lastLogin != 0) ? `${msToTime(getCurrentUnixTimestamp()-tempSubAccount.lastLogin)} ago` : "Never";
showPlayerCharacterSelectGUI(client, tempSubAccount.firstName, tempSubAccount.lastName, tempSubAccount.cash, ClanName, lastPlayedText, getGameConfig().skins[getGame()][tempSubAccount.skin][0]);
let clanName = (tempSubAccount.clan != 0) ? getClanData(getClanIdFromDatabaseId(tempSubAccount.clan)).name : "None";
let lastPlayedText = (tempSubAccount.lastLogin != 0) ? `${msToTime(getCurrentUnixTimestamp() - tempSubAccount.lastLogin)} ago` : "Never";
showPlayerCharacterSelectGUI(client, tempSubAccount.firstName, tempSubAccount.lastName, tempSubAccount.cash, clanName, lastPlayedText, getGameConfig().skins[getGame()][tempSubAccount.skin][0]);
//spawnPlayer(client, getServerConfig().characterSelectPedPosition, getServerConfig().characterSelectPedHeading, getPlayerCurrentSubAccount(client).skin, getServerConfig().characterSelectInterior, getServerConfig().characterSelectDimension);
//setTimeout(function() {
@@ -355,16 +355,12 @@ function showCharacterSelectToClient(client) {
//}, 500);
logToConsole(LOG_DEBUG, `[VRR.SubAccount] ${getPlayerDisplayForConsole(client)} is being shown the character select GUI`);
} else {
//let emojiNumbers = ["➊", "➋", "➌", "➍", "➎", "➏", "➐", "➑", "➒"];
//let emojiNumbers = ["①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨"];
//let emojiNumbers = ["1⃣", "2⃣", "3⃣", "4⃣", "5⃣", "6⃣", "7⃣", "8⃣", "9⃣"];
messagePlayerNormal(client, `You have the following characters. Use /usechar <id> to select one:`, getColourByName("teal"));
getPlayerData(client).subAccounts.forEach(function(subAccount, index) {
let tempSubAccount = getPlayerData(client).subAccounts[0];
//let clanName = (tempSubAccount.clan != 0) ? getClanData(getClanIdFromDatabaseId(tempSubAccount.clan)).name : "None";
let lastPlayedText = (tempSubAccount.lastLogin != 0) ? `${msToTime(getCurrentUnixTimestamp()-tempSubAccount.lastLogin)} ago` : "Never";
messagePlayerNormal(client, `${index+1} • [#BBBBBB]${subAccount.firstName} ${subAccount.lastName} ($${tempSubAccount.cash}, ${lastPlayedText})`);
});
let charactersList = getPlayerData(client).subAccounts.map((sacct, index) => `{teal}${index + 1}: {ALTCOLOUR}${sacct.firstName} ${sacct.lastName}`);
let chunkedList = splitArrayIntoChunks(charactersList, 5);
messagePlayerNormal(client, makeChatBoxSectionHeader(getLocaleString(client, "HeaderCharactersListSelf")));
for (let i in chunkedList) {
messagePlayerNormal(client, chunkedList[i].join("{MAINCOLOUR}, "));
}
logToConsole(LOG_DEBUG, `[VRR.SubAccount] ${getPlayerDisplayForConsole(client)} is being shown the character select/list message (GUI disabled)`);
}
}
@@ -372,25 +368,25 @@ function showCharacterSelectToClient(client) {
// ===========================================================================
function checkNewCharacter(client, firstName, lastName) {
if(areParamsEmpty(firstName)) {
if (areParamsEmpty(firstName)) {
showPlayerNewCharacterFailedGUI(client, "First name cannot be blank!");
return false;
}
firstName = firstName.trim();
if(areParamsEmpty(lastName)) {
if (areParamsEmpty(lastName)) {
showPlayerNewCharacterFailedGUI(client, "Last name cannot be blank!");
return false;
}
lastName = lastName.trim();
if(doesNameContainInvalidCharacters(firstName) || doesNameContainInvalidCharacters(lastName)) {
logToConsole(LOG_WARN, `[VRR.Account] Subaccount ${firstName} ${lastName} could not be created (invalid characters in name)`);
if (doesNameContainInvalidCharacters(firstName) || doesNameContainInvalidCharacters(lastName)) {
logToConsole(LOG_INFO | LOG_WARN, `[VRR.Account] Subaccount ${firstName} ${lastName} could not be created (invalid characters in name)`);
showPlayerNewCharacterFailedGUI(client, "Invalid characters in name!");
return false;
}
if(getPlayerData(client).changingCharacterName) {
if (getPlayerData(client).changingCharacterName) {
getPlayerCurrentSubAccount(client).firstName = fixCharacterName(firstName);
getPlayerCurrentSubAccount(client).lastName = fixCharacterName(lastName);
updateAllPlayerNameTags(client);
@@ -399,8 +395,8 @@ function checkNewCharacter(client, firstName, lastName) {
}
let subAccountData = createSubAccount(getPlayerData(client).accountData.databaseId, firstName, lastName);
if(!subAccountData) {
if(doesServerHaveGUIEnabled() && doesPlayerHaveGUIEnabled(client)) {
if (!subAccountData) {
if (doesServerHaveGUIEnabled() && doesPlayerHaveGUIEnabled(client)) {
showPlayerNewCharacterFailedGUI(client, "Your character could not be created!");
} else {
messagePlayerError(client, "Your character could not be created!");
@@ -412,16 +408,15 @@ function checkNewCharacter(client, firstName, lastName) {
getPlayerData(client).subAccounts = loadSubAccountsFromAccount(getPlayerData(client).accountData.databaseId);
getPlayerData(client).currentSubAccount = 0;
getPlayerData(client).creatingCharacter = false;
let tempSubAccount = getPlayerData(client).subAccounts[0];
showCharacterSelectToClient(client);
}
// ===========================================================================
function checkPreviousCharacter(client) {
if(getPlayerData(client).subAccounts.length > 1) {
if(getPlayerData(client).currentSubAccount <= 0) {
getPlayerData(client).currentSubAccount = getPlayerData(client).subAccounts.length-1;
if (getPlayerData(client).subAccounts.length > 1) {
if (getPlayerData(client).currentSubAccount <= 0) {
getPlayerData(client).currentSubAccount = getPlayerData(client).subAccounts.length - 1;
} else {
getPlayerData(client).currentSubAccount--;
}
@@ -430,7 +425,7 @@ function checkPreviousCharacter(client) {
let tempSubAccount = getPlayerData(client).subAccounts[subAccountId];
let clanName = (tempSubAccount.clan != 0) ? getClanData(getClanIdFromDatabaseId(tempSubAccount.clan)).name : "None";
let lastPlayedText = (tempSubAccount.lastLogin != 0) ? `${msToTime(getCurrentUnixTimestamp()-tempSubAccount.lastLogin)} ago` : "Never";
let lastPlayedText = (tempSubAccount.lastLogin != 0) ? `${msToTime(getCurrentUnixTimestamp() - tempSubAccount.lastLogin)} ago` : "Never";
showPlayerCharacterSelectGUI(client, tempSubAccount.firstName, tempSubAccount.lastName, tempSubAccount.cash, clanName, lastPlayedText, getGameConfig().skins[getGame()][tempSubAccount.skin][0]);
logToConsole(LOG_DEBUG, `[VRR.SubAccount] Setting ${getPlayerDisplayForConsole(client)}'s character to ID ${getPlayerData(client).currentSubAccount}`);
@@ -440,8 +435,8 @@ function checkPreviousCharacter(client) {
// ===========================================================================
function checkNextCharacter(client) {
if(getPlayerData(client).subAccounts.length > 1) {
if(getPlayerData(client).currentSubAccount >= getPlayerData(client).subAccounts.length-1) {
if (getPlayerData(client).subAccounts.length > 1) {
if (getPlayerData(client).currentSubAccount >= getPlayerData(client).subAccounts.length - 1) {
getPlayerData(client).currentSubAccount = 0;
} else {
getPlayerData(client).currentSubAccount++;
@@ -451,7 +446,7 @@ function checkNextCharacter(client) {
let tempSubAccount = getPlayerData(client).subAccounts[subAccountId];
let clanName = (tempSubAccount.clan != 0) ? getClanData(getClanIdFromDatabaseId(tempSubAccount.clan)).name : "None";
let lastPlayedText = (tempSubAccount.lastLogin != 0) ? `${msToTime(getCurrentUnixTimestamp()-tempSubAccount.lastLogin)} ago` : "Never";
let lastPlayedText = (tempSubAccount.lastLogin != 0) ? `${msToTime(getCurrentUnixTimestamp() - tempSubAccount.lastLogin)} ago` : "Never";
showPlayerCharacterSelectGUI(client, tempSubAccount.firstName, tempSubAccount.lastName, tempSubAccount.cash, clanName, lastPlayedText, getGameConfig().skins[getGame()][tempSubAccount.skin][0]);
logToConsole(LOG_DEBUG, `[VRR.SubAccount] Setting ${getPlayerDisplayForConsole(client)}'s character to ID ${getPlayerData(client).currentSubAccount}`);
@@ -462,7 +457,7 @@ function checkNextCharacter(client) {
function selectCharacter(client, characterId = -1) {
logToConsole(LOG_DEBUG, `[VRR.SubAccount] ${getPlayerDisplayForConsole(client)} character select called (Character ID ${characterId})`);
if(characterId != -1) {
if (characterId != -1) {
logToConsole(LOG_DEBUG, `[VRR.SubAccount] ${getPlayerDisplayForConsole(client)} provided character ID (${characterId}) to spawn with`);
getPlayerData(client).currentSubAccount = characterId;
}
@@ -481,16 +476,20 @@ function selectCharacter(client, characterId = -1) {
//setPlayerCameraLookAt(client, getPosBehindPos(spawnPosition, spawnHeading, 5), spawnPosition);
getPlayerData(client).pedState = VRR_PEDSTATE_SPAWNING;
if(getGame() < VRR_GAME_GTA_IV) {
if (getGame() <= VRR_GAME_GTA_SA) {
spawnPlayer(client, spawnPosition, spawnHeading, getGameConfig().skins[getGame()][skin][0], spawnInterior, spawnDimension);
} else if(getGame() == VRR_GAME_GTA_IV) {
} else if (getGame() == VRR_GAME_GTA_IV) {
spawnPlayer(client, spawnPosition, spawnHeading, getGameConfig().skins[getGame()][skin][0], spawnInterior, spawnDimension);
//clearPlayerWeapons(client);
//setPlayerSkin(client, skin);
//setPlayerPosition(client, spawnPosition);
//setPlayerHeading(client, spawnHeading);
//setPlayerInterior(client, spawnInterior);
//setPlayerDimension(client, spawnDimension);
} else if(getGame() >= VRR_GAME_MAFIA_ONE) {
//restorePlayerCamera(client);
} else if (getGame() == VRR_GAME_MAFIA_ONE) {
//spawnPlayer(client, spawnPosition, spawnHeading, getGameConfig().skins[getGame()][skin][0]);
logToConsole(LOG_DEBUG, `[VRR.SubAccount] Spawning ${getPlayerDisplayForConsole(client)} as ${getGameConfig().skins[getGame()][skin][1]} (${getGameConfig().skins[getGame()][skin][0]})`);
spawnPlayer(client, getGameConfig().skins[getGame()][skin][0], spawnPosition, spawnHeading);
}
@@ -498,7 +497,7 @@ function selectCharacter(client, characterId = -1) {
logToConsole(LOG_DEBUG, `[VRR.SubAccount] Spawned ${getPlayerDisplayForConsole(client)} as character ID ${getPlayerData(client).currentSubAccount} with skin ${skin} (${spawnPosition.x}, ${spawnPosition.y}, ${spawnPosition.z})`);
setTimeout(function() {
setTimeout(function () {
onPlayerSpawn(client);
}, 500);
@@ -511,12 +510,12 @@ function selectCharacter(client, characterId = -1) {
function switchCharacterCommand(command, params, client) {
logToConsole(LOG_DEBUG, `[VRR.SubAccount] ${getPlayerDisplayForConsole(client)} is requesting to switch characters (current character: ${getCharacterFullName(client)} [${getPlayerData(client).currentSubAccount}/${getPlayerCurrentSubAccount(client).databaseId}])`);
if(!isPlayerSpawned(client)) {
if (!isPlayerSpawned(client)) {
logToConsole(LOG_WARN, `[VRR.SubAccount] ${getPlayerDisplayForConsole(client)} is not allowed to switch characters (not spawned)`);
return false;
}
if(isPlayerSwitchingCharacter(client)) {
if (isPlayerSwitchingCharacter(client)) {
logToConsole(LOG_WARN, `[VRR.SubAccount] ${getPlayerDisplayForConsole(client)} is not allowed to switch characters (already in switch char mode)`);
messagePlayerError(client, "You are already selecting/switching characters!");
return false;
@@ -528,12 +527,12 @@ function switchCharacterCommand(command, params, client) {
// ===========================================================================
function newCharacterCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let firstName = getParam(params, " ", 1);
let firstName = getParam(params, " ", 1);
let lastName = getParam(params, " ", 2);
checkNewCharacter(client, firstName, lastName);
@@ -542,19 +541,19 @@ let firstName = getParam(params, " ", 1);
// ===========================================================================
function useCharacterCommand(command, params, client) {
if(!getPlayerData(client).switchingCharacter) {
if (!getPlayerData(client).switchingCharacter) {
messagePlayerError(client, "Use /switchchar to save this character and return to the characters screen first!");
return false;
}
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let characterId = toInteger(params) || 1;
selectCharacter(client, characterId-1);
selectCharacter(client, characterId - 1);
}
// ===========================================================================
@@ -562,8 +561,8 @@ function useCharacterCommand(command, params, client) {
function getPlayerLastUsedSubAccount(client) {
let subAccounts = getPlayerData(client).subAccounts;
let lastUsed = 0;
for(let i in subAccounts) {
if(subAccounts[i].lastLogin > subAccounts[lastUsed].lastLogin) {
for (let i in subAccounts) {
if (subAccounts[i].lastLogin > subAccounts[lastUsed].lastLogin) {
lastUsed = i;
}
}
@@ -602,16 +601,16 @@ function isPlayerCreatingCharacter(client) {
*
*/
function getPlayerCurrentSubAccount(client) {
if(!getPlayerData(client)) {
if (!getPlayerData(client)) {
return false;
}
let subAccountId = getPlayerData(client).currentSubAccount;
if(subAccountId == -1) {
if (subAccountId == -1) {
return false;
}
if(typeof getPlayerData(client).subAccounts[subAccountId] == "undefined") {
if (typeof getPlayerData(client).subAccounts[subAccountId] == "undefined") {
return false;
}
@@ -628,67 +627,28 @@ function getClientSubAccountName(client) {
// ===========================================================================
function setFightStyleCommand(command, params, client) {
if(areParamsEmpty(params)) {
if (areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let fightStyleId = getFightStyleFromParams(params);
if(!fightStyle) {
if (!fightStyle) {
messagePlayerError(client, `That fight style doesn't exist!`);
messagePlayerError(client, `Fight styles: ${getGameConfig().fightStyles[getServerGame()].map(fs => fs[0]).join(", ")}`);
messagePlayerError(client, `Fight styles: ${getGameConfig().fightStyles[getGame()].map(fs => fs[0]).join(", ")}`);
return false;
}
if(!isPlayerAtGym(client)) {
if(!doesPlayerHaveStaffPermission(client, getStaffFlagValue("BasicModeration"))) {
if (!isPlayerAtGym(client)) {
if (!doesPlayerHaveStaffPermission(client, getStaffFlagValue("BasicModeration"))) {
messagePlayerError(client, `You need to be at a gym!`);
return false
}
}
setPlayerFightStyle(client, fightStyleId);
messagePlayerSuccess(client, `Your fight style has been set to ${getGameConfig().fightStyles[getServerGame()][fightStyleId][0]}`)
return true;
}
// ===========================================================================
function forceFightStyleCommand(command, params, client) {
if(areParamsEmpty(params)) {
messagePlayerSyntax(client, getCommandSyntaxText(command));
return false;
}
let targetClient = getPlayerFromParams(getParam(params, " ", 1));
let fightStyleId = getFightStyleFromParams(getParam(params, " ", 2));
//if(!targetClient) {
// messagePlayerError(client, `Player not found!`);
// return false;
//}
//if(!getPlayerData(targetClient)) {
// messagePlayerError(client, `Player not found!`);
// return false;
//}
//if(!isPlayerSpawned(targetClient)) {
// messagePlayerError(client, `That player isn't spawned`);
// return false;
//}
if(!fightStyleId) {
messagePlayerError(client, `That fight style doesn't exist!`);
messagePlayerError(client, `Fight styles: ${getGameConfig().fightStyles[getServerGame()].map(fs => fs[0]).join(", ")}`);
return false;
}
getPlayerCurrentSubAccount(client).fightStyle = fightStyleId;
setPlayerFightStyle(client, fightStyleId);
messagePlayerSuccess(client, `You set ${getCharacterFullName(targetClient)}'s fight style to ${getGameConfig().fightStyles[getServerGame()][fightStyleId][0]}`)
messagePlayerSuccess(client, `Your fight style has been set to ${getGameConfig().fightStyles[getGame()][fightStyleId][0]}`)
return true;
}
@@ -696,8 +656,8 @@ function forceFightStyleCommand(command, params, client) {
// ===========================================================================
function createDefaultSubAccountServerData(databaseId, thisServerSkin) {
for(let i = 1 ; i <= 5 ; i++) {
if(i == getServerId()) {
for (let i = 1; i <= 5; i++) {
if (i == getServerId()) {
let dbQueryString = `INSERT INTO sacct_svr (sacct_svr_sacct, sacct_svr_server, sacct_svr_skin) VALUES (${databaseId}, ${i}, ${thisServerSkin})`;
quickDatabaseQuery(dbQueryString);
} else {
@@ -727,5 +687,6 @@ function forcePlayerIntoSwitchCharacterScreen(client) {
getPlayerData(client).switchingCharacter = true;
showConnectCameraToPlayer(client);
showCharacterSelectToClient(client);
}

View File

@@ -11,70 +11,76 @@ let serverTimers = {};
// ===========================================================================
function saveAllServerDataToDatabase() {
if(getServerConfig().pauseSavingToDatabase) {
function saveServerDataToDatabase() {
if (getServerConfig().pauseSavingToDatabase) {
return false;
}
logToConsole(LOG_DEBUG, "[VRR.Utilities]: Saving all server data to database ...");
try {
saveAllClientsToDatabase();
} catch(error) {
logToConsole(LOG_ERROR, `Could not save clients to database: ${error}`);
saveAllPlayersToDatabase();
} catch (error) {
logToConsole(LOG_ERROR, `Could not save players to database: ${error}`);
}
try {
saveAllClansToDatabase();
} catch(error) {
} catch (error) {
logToConsole(LOG_ERROR, `Could not save clans to database: ${error}`);
}
try {
saveAllHousesToDatabase();
} catch(error) {
} catch (error) {
logToConsole(LOG_ERROR, `Could not save houses to database: ${error}`);
}
try {
saveAllBusinessesToDatabase();
} catch(error) {
} catch (error) {
logToConsole(LOG_ERROR, `Could not save businesses to database: ${error}`);
}
try {
saveServerConfigToDatabase();
} catch(error) {
logToConsole(LOG_ERROR, `Could not save server config to database: ${error}`);
}
try {
saveAllVehiclesToDatabase();
} catch(error) {
} catch (error) {
logToConsole(LOG_ERROR, `Could not save vehicles to database: ${error}`);
}
try {
saveAllItemTypesToDatabase();
} catch(error) {
} catch (error) {
logToConsole(LOG_ERROR, `Could not save item types to database: ${error}`);
}
try {
saveAllItemsToDatabase();
} catch(error) {
} catch (error) {
logToConsole(LOG_ERROR, `Could not save items to database: ${error}`);
}
try {
saveAllJobsToDatabase();
} catch(error) {
} catch (error) {
logToConsole(LOG_ERROR, `Could not save jobs to database: ${error}`);
}
try {
saveAllNPCsToDatabase();
} catch (error) {
logToConsole(LOG_ERROR, `Could not save NPCs to database: ${error}`);
}
try {
saveAllGatesToDatabase();
} catch (error) {
logToConsole(LOG_ERROR, `Could not save gates to database: ${error}`);
}
try {
saveServerConfigToDatabase();
} catch(error) {
} catch (error) {
logToConsole(LOG_ERROR, `Could not save server config to database: ${error}`);
}
@@ -85,10 +91,10 @@ function saveAllServerDataToDatabase() {
function initTimers() {
//if(!isDevelopmentServer()) {
serverTimers.updatePingsTimer = setInterval(updatePings, 5000);
serverTimers.oneMinuteTimer = setInterval(oneMinuteTimerFunction, 60000);
serverTimers.fifteenMinuteTimer = setInterval(tenMinuteTimerFunction, 600000);
serverTimers.thirtyMinuteTimer = setInterval(thirtyMinuteTimerFunction, 1800000);
serverTimers.updatePingsTimer = setInterval(updatePings, 5000);
serverTimers.oneMinuteTimer = setInterval(oneMinuteTimerFunction, 60000);
serverTimers.fifteenMinuteTimer = setInterval(tenMinuteTimerFunction, 600000);
serverTimers.thirtyMinuteTimer = setInterval(thirtyMinuteTimerFunction, 1800000);
//}
}
@@ -99,7 +105,7 @@ function oneMinuteTimerFunction() {
checkServerGameTime();
logToConsole(LOG_DEBUG, `[VRR.Event] Checking rentable vehicles`);
vehicleRentCheck();
checkVehicleRenting();
logToConsole(LOG_DEBUG, `[VRR.Event] Updating all player name tags`);
updateAllPlayerNameTags();
@@ -112,7 +118,7 @@ function oneMinuteTimerFunction() {
function tenMinuteTimerFunction() {
showRandomTipToAllPlayers();
saveAllServerDataToDatabase();
saveServerDataToDatabase();
checkInactiveVehicleRespawns();
}
@@ -124,19 +130,18 @@ function thirtyMinuteTimerFunction() {
// ===========================================================================
function vehicleRentCheck() {
// Loop through players, not vehicles. Much more efficient (and doesn't consume resources when no players are connected)
let clients = getClients();
for(let i in clients) {
if(isClientInitialized(clients[i])) {
if(getPlayerData(clients[i]) != false) {
if(isPlayerLoggedIn(clients[i] && isPlayerSpawned(clients[i]))) {
if(getPlayerData(clients[i]).rentingVehicle != false) {
if(getPlayerCurrentSubAccount(clients[i]).cash < getServerData().vehicles[getPlayerData(clients[i]).rentingVehicle].rentPrice) {
messagePlayerAlert(clients[i], `You do not have enough money to continue renting this vehicle!`);
stopRentingVehicle(clients[i]);
function checkVehicleRenting() {
let renting = getServerData().rentingVehicleCache;
for (let i in renting) {
if (isClientInitialized(renting[i])) {
if (getPlayerData(renting[i]) != false) {
if (isPlayerLoggedIn(renting[i] && isPlayerSpawned(renting[i]))) {
if (getPlayerData(renting[i]).rentingVehicle != false) {
if (getPlayerCurrentSubAccount(renting[i]).cash < getServerData().vehicles[getPlayerData(renting[i]).rentingVehicle].rentPrice) {
messagePlayerAlert(renting[i], `You do not have enough money to continue renting this vehicle!`);
stopRentingVehicle(renting[i]);
} else {
takePlayerCash(clients[i], getServerData().vehicles[getPlayerData(clients[i]).rentingVehicle].rentPrice);
takePlayerCash(renting[i], getServerData().vehicles[getPlayerData(renting[i]).rentingVehicle].rentPrice);
}
}
}
@@ -169,11 +174,11 @@ function vehicleRentCheck() {
function updatePings() {
let clients = getClients();
for(let i in clients) {
if(isClientInitialized(clients[i])) {
if(!clients[i].console) {
for (let i in clients) {
if (isClientInitialized(clients[i])) {
if (!clients[i].console) {
updatePlayerPing(clients[i]);
if(isPlayerSpawned(clients[i])) {
if (isPlayerSpawned(clients[i])) {
updatePlayerCash(clients[i]);
}
}
@@ -185,16 +190,16 @@ function updatePings() {
function checkServerGameTime() {
//if(!getServerConfig().useRealTime) {
if(getServerConfig().minute >= 59) {
getServerConfig().minute = 0;
if(getServerConfig().hour >= 23) {
getServerConfig().hour = 0;
} else {
getServerConfig().hour = getServerConfig().hour + 1;
}
if (getServerConfig().minute >= 59) {
getServerConfig().minute = 0;
if (getServerConfig().hour >= 23) {
getServerConfig().hour = 0;
} else {
getServerConfig().minute = getServerConfig().minute + 1;
getServerConfig().hour = getServerConfig().hour + 1;
}
} else {
getServerConfig().minute = getServerConfig().minute + 1;
}
//} else {
// let dateTime = getCurrentTimeStampWithTimeZone(getServerConfig().realTimeZone);
// getServerConfig().hour = dateTime.getHours();
@@ -208,9 +213,9 @@ function checkServerGameTime() {
function checkPayDays() {
let clients = getClients();
for(let i in clients) {
if(isClientInitialized(clients[i])) {
if(isPlayerLoggedIn(clients[i]) && isPlayerSpawned(clients[i])) {
for (let i in clients) {
if (isClientInitialized(clients[i])) {
if (isPlayerLoggedIn(clients[i]) && isPlayerSpawned(clients[i])) {
getPlayerData(clients[i]).payDayStart = sdl.ticks;
playerPayDay(clients[i]);
@@ -222,8 +227,8 @@ function checkPayDays() {
}
}
for(let i in getServerData().businesses) {
if(getBusinessData(i).ownerType != VRR_BIZOWNER_NONE && getBusinessData(i).ownerType != VRR_BIZOWNER_PUBLIC && getBusinessData(i).ownerType != VRR_BIZOWNER_FACTION) {
for (let i in getServerData().businesses) {
if (getBusinessData(i).ownerType != VRR_BIZOWNER_NONE && getBusinessData(i).ownerType != VRR_BIZOWNER_PUBLIC && getBusinessData(i).ownerType != VRR_BIZOWNER_FACTION) {
getBusinessData(i).till += 1000;
}
}
@@ -232,14 +237,14 @@ function checkPayDays() {
// ===========================================================================
function showRandomTipToAllPlayers() {
let tipId = getRandom(0, randomTips.length-1);
let clients = getClients();
for(let i in clients) {
if(isClientInitialized(clients[i])) {
if(isPlayerLoggedIn(clients[i]) && isPlayerSpawned(clients[i])) {
if(!doesPlayerHaveRandomTipsDisabled(clients[i])) {
messagePlayerTimedRandomTip(null, randomTips[tipId]);
for (let i in clients) {
if (isClientInitialized(clients[i])) {
if (isPlayerLoggedIn(clients[i]) && isPlayerSpawned(clients[i])) {
if (!doesPlayerHaveRandomTipsDisabled(clients[i])) {
let localeId = getPlayerLocaleId(clients[i]);
let tipId = getRandom(0, getServerData().localeStrings[localeId]["RandomTips"].length - 1);
messagePlayerTip(clients[i], getGroupedLocaleString(clients[i], "RandomTips", tipId));
}
}
}
@@ -250,19 +255,19 @@ function showRandomTipToAllPlayers() {
function checkInactiveVehicleRespawns() {
let vehicles = getElementsByType(ELEMENT_VEHICLE);
for(let i in vehicles) {
if(getVehicleData(vehicles[i] != false)) {
if(isVehicleUnoccupied(vehicles[i])) {
if(getVehicleData(vehicles[i]).lastActiveTime != false) {
if(getCurrentUnixTimestamp() - getVehicleData(vehicles[i]).lastActiveTime >= getGlobalConfig().vehicleInactiveRespawnDelay) {
respawnVehicle(vehicles[i]);
getVehicleData(vehicles[i]).lastActiveTime = false;
}
}
} else {
getVehicleData(vehicles[i]).lastActiveTime = getCurrentUnixTimestamp();
}
}
for (let i in vehicles) {
if (getVehicleData(vehicles[i] != false)) {
if (isVehicleUnoccupied(vehicles[i])) {
if (getVehicleData(vehicles[i]).lastActiveTime != false) {
if (getCurrentUnixTimestamp() - getVehicleData(vehicles[i]).lastActiveTime >= getGlobalConfig().vehicleInactiveRespawnDelay) {
respawnVehicle(vehicles[i]);
getVehicleData(vehicles[i]).lastActiveTime = false;
}
}
} else {
getVehicleData(vehicles[i]).lastActiveTime = getCurrentUnixTimestamp();
}
}
}
}

View File

@@ -8,44 +8,47 @@
// ===========================================================================
const triggerTypes = [
"onBusinessOwnerChange",
"onBusinessNameChange",
"onBusinessLockChange",
"onBusinessPlayerEnter",
"onBusinessPlayerExit",
"onBusinessBotEnter",
"onBusinessBotExit",
"onBusinessDamage",
"onBusinessRobbed",
"onBusinessPlayerPurchase",
"onBusinessBotPurchase",
"onHouseOwnerChange",
"onHouseNameChange",
"onHouseLockChange",
"onHousePlayerEnter",
"onHousePlayerExit",
"onHouseBotEnter",
"onHouseBotExit",
"onHouseDamage",
"onHouseRobbed",
"onVehicleOwnerChange",
"onVehiclePlayerEnter",
"onVehiclePlayerExit",
"onVehicleBotEnter",
"onVehicleBotExit",
"onVehicleCollision",
"onVehicleDamaged",
"onVehicleShot",
"onVehicleTrunkChange",
"onVehicleItemTaken",
"onVehicleItemStored",
"onVehicleEngineChange",
"onVehicleLightsChange",
"onVehicleSirenChange",
"onVehicleLockChange",
"onVehicleRepaired",
"onVehicleColourChange",
"onVehicleExtraChange",
"onBusinessOwnerChange",
"onBusinessNameChange",
"onBusinessLockChange",
"onBusinessPlayerEnter",
"onBusinessPlayerExit",
"onBusinessBotEnter",
"onBusinessBotExit",
"onBusinessDamage",
"onBusinessRobbed",
"onBusinessPlayerPurchase",
"onBusinessBotPurchase",
"onHouseOwnerChange",
"onHouseNameChange",
"onHouseLockChange",
"onHousePlayerEnter",
"onHousePlayerExit",
"onHouseBotEnter",
"onHouseBotExit",
"onHouseDamage",
"onHouseRobbed",
"onVehicleOwnerChange",
"onVehiclePlayerEnter",
"onVehiclePlayerExit",
"onVehicleBotEnter",
"onVehicleBotExit",
"onVehicleCollision",
"onVehicleDamaged",
"onVehicleShot",
"onVehicleTrunkChange",
"onVehicleItemTaken",
"onVehicleItemStored",
"onVehicleEngineChange",
"onVehicleLightsChange",
"onVehicleSirenChange",
"onVehicleLockChange",
"onVehicleRepaired",
"onVehicleColourChange",
"onVehicleExtraChange",
"onPlayerShout",
"onPlayerTalk",
"onPlayerWhisper",
];
// ===========================================================================

View File

@@ -10,8 +10,8 @@
// ===========================================================================
function startTutorial(client) {
getPlayerData(client).tutorialItem = createGroundItem(tutorialItem[0], tutorialItem[1], tutorialItem[3]);
getPlayerData(client).tutorialVehicle = createGroundItem(tutorialItem[0], tutorialItem[1], tutorialItem[3]);
getPlayerData(client).tutorialItem = createGroundItem(tutorialItem[0], tutorialItem[1], tutorialItem[3]);
getPlayerData(client).tutorialVehicle = createGroundItem(tutorialItem[0], tutorialItem[1], tutorialItem[3]);
}
// ===========================================================================

View File

@@ -7,30 +7,18 @@
// TYPE: Server (JavaScript)
// ===========================================================================
let disconnectReasons = [
"Lost Connection",
"Disconnected",
"Unsupported Client",
"Wrong Game",
"Incorrect Password",
"Unsupported Executable",
"Disconnected",
"Banned",
"Failed",
"Invalid Name",
"Crashed"
];
// ===========================================================================
function getPositionArea(position) {
if(typeof position == "Vec3") {
if (typeof position == "Vec3") {
position = vec3ToVec2(position);
}
let gameAreas = getGameAreas(getServerGame());
for(let i in gameAreas) {
if(isPositionInArea(position, gameAreas[i][1])) {
let gameAreas = getGameAreas(getGame());
for (let i in gameAreas) {
if (isPositionInArea(position, gameAreas[i][1])) {
return i;
}
}
@@ -42,7 +30,7 @@ function getPositionArea(position) {
function getAreaName(position) {
let areaId = getPositionArea(position);
if(!areaId) {
if (!areaId) {
return false;
}
@@ -62,9 +50,9 @@ function getGameAreas(gameId) {
* @return {ClientData} The player/client's data (class instancee)
*/
function getPlayerData(client) {
if(client != null) {
if(isClientInitialized(client)) {
return getServerData().clients[client.index];
if (client != null) {
if (isClientInitialized(client)) {
return getServerData().clients[getPlayerId(client)];
}
}
return false;
@@ -73,7 +61,7 @@ function getPlayerData(client) {
// ===========================================================================
function initAllClients() {
getClients().forEach(function(client) {
getClients().forEach(function (client) {
initClient(client);
});
}
@@ -82,26 +70,28 @@ function initAllClients() {
function updateServerRules() {
logToConsole(LOG_DEBUG, `[VRR.Utilities]: Updating all server rules ...`);
logToConsole(LOG_DEBUG, `[VRR.Utilities]: Time support: ${isTimeSupported()}`);
if(isTimeSupported()) {
if(getServerConfig() != false) {
if (isTimeSupported()) {
if (getServerConfig() != false) {
let value = makeReadableTime(getServerConfig().hour, getServerConfig().minute);
logToConsole(LOG_DEBUG, `[VRR.Utilities]: Setting server rule "Time" as ${value}`);
server.setRule("Time", value);
}
}
if(isWeatherSupported()) {
if(getServerConfig() != false) {
let value = getGameConfig().weatherNames[getServerGame()][getServerConfig().weather];
logToConsole(LOG_DEBUG, `[VRR.Utilities]: Setting server rule "Weather" as ${value}`);
server.setRule("Weather", value);
if (isWeatherSupported()) {
if (getServerConfig() != false) {
if (typeof getGameConfig().weatherNames[getGame()] != "undefined") {
let value = getGameConfig().weatherNames[getGame()][getServerConfig().weather];
logToConsole(LOG_DEBUG, `[VRR.Utilities]: Setting server rule "Weather" as ${value}`);
server.setRule("Weather", value);
}
}
}
if(isSnowSupported()) {
if(getServerConfig() != false) {
if (isSnowSupported()) {
if (getServerConfig() != false) {
let value = getYesNoFromBool(getServerConfig().fallingSnow);
logToConsole(LOG_DEBUG, `[VRR.Utilities]: Setting server rule "Snowing" as ${value}`);
server.setRule("Snowing", value);
@@ -113,14 +103,14 @@ function updateServerRules() {
// ===========================================================================
function getWeatherFromParams(params) {
if(isNaN(params)) {
for(let i in getGameConfig().weatherNames[getServerGame()]) {
if(toLowerCase(getGameConfig().weatherNames[getServerGame()][i]).indexOf(toLowerCase(params)) != -1) {
if (isNaN(params)) {
for (let i in getGameConfig().weatherNames[getGame()]) {
if (toLowerCase(getGameConfig().weatherNames[getGame()][i]).indexOf(toLowerCase(params)) != -1) {
return i;
}
}
} else {
if(typeof getGameConfig().weatherNames[getServerGame()][params] != "undefined") {
if (typeof getGameConfig().weatherNames[getGame()][params] != "undefined") {
return toInteger(params);
}
}
@@ -131,14 +121,14 @@ function getWeatherFromParams(params) {
// ===========================================================================
function getFightStyleFromParams(params) {
if(isNaN(params)) {
for(let i in getGameConfig().fightStyles[getServerGame()]) {
if(toLowerCase(getGameConfig().fightStyles[getServerGame()][i][0]).indexOf(toLowerCase(params)) != -1) {
if (isNaN(params)) {
for (let i in getGameConfig().fightStyles[getGame()]) {
if (toLowerCase(getGameConfig().fightStyles[getGame()][i][0]).indexOf(toLowerCase(params)) != -1) {
return i;
}
}
} else {
if(typeof getGameConfig().fightStyles[getServerGame()][params] != "undefined") {
if (typeof getGameConfig().fightStyles[getGame()][params] != "undefined") {
return toInteger(params);
}
}
@@ -149,42 +139,50 @@ function getFightStyleFromParams(params) {
// ===========================================================================
function getClosestHospital(position) {
let closest = 0;
for(let i in getGameConfig().hospitals[getServerGame()]) {
if(getDistance(getGameConfig().hospitals[getServerGame()][i].position, position) < getDistance(getGameConfig().hospitals[getServerGame()][closest].position, position)) {
closest = i;
if (typeof getGameConfig().hospitals[getGame()] == "undefined") {
return { position: getServerConfig().newCharacter.spawnPosition };
} else {
let closest = 0;
for (let i in getGameConfig().hospitals[getGame()]) {
if (getDistance(getGameConfig().hospitals[getGame()][i].position, position) < getDistance(getGameConfig().hospitals[getGame()][closest].position, position)) {
closest = i;
}
}
}
return getGameConfig().hospitals[getServerGame()][closest];
return getGameConfig().hospitals[getGame()][closest];
}
}
// ===========================================================================
function getClosestPoliceStation(position) {
let closest = 0;
for(let i in getGameConfig().policeStations[getServerGame()]) {
if(getDistance(getGameConfig().policeStations[getServerGame()][i].position, position) < getDistance(getGameConfig().policeStations[getServerGame()][closest].position, position)) {
closest = i;
if (typeof getGameConfig().policeStations[getGame()] == "undefined") {
return { position: getServerConfig().newCharacter.spawnPosition };
} else {
let closest = 0;
for (let i in getGameConfig().policeStations[getGame()]) {
if (getDistance(getGameConfig().policeStations[getGame()][i].position, position) < getDistance(getGameConfig().policeStations[getGame()][closest].position, position)) {
closest = i;
}
}
}
return getGameConfig().policeStations[getServerGame()][closest];
return getGameConfig().policeStations[getGame()][closest];
}
}
// ===========================================================================
function getPlayerDisplayForConsole(client) {
if(isNull(client)) {
if (isNull(client)) {
return "(Unknown client)";
}
return `${getPlayerName(client)}[${client.index}]`;
return `${getPlayerName(client)}[${getPlayerId(client)}]`;
}
// ===========================================================================
function getPlayerNameForNameTag(client) {
if(isPlayerSpawned(client)) {
if (isPlayerSpawned(client)) {
return `${getPlayerCurrentSubAccount(client).firstName} ${getPlayerCurrentSubAccount(client).lastName}`;
}
return getPlayerName(client);
@@ -193,7 +191,7 @@ function getPlayerNameForNameTag(client) {
// ===========================================================================
function isPlayerSpawned(client) {
if(!getPlayerData(client)) {
if (!getPlayerData(client)) {
return false;
}
return getPlayerData(client).spawned;
@@ -208,8 +206,8 @@ function getPlayerIsland(client) {
// ===========================================================================
function isAtPayAndSpray(position) {
for(let i in getGameConfig().payAndSprays[getServerGame()]) {
if(getDistance(position, getGameConfig().payAndSprays[getServerGame()][i]) <= getGlobalConfig().payAndSprayDistance) {
for (let i in getGameConfig().payAndSprays[getGame()]) {
if (getDistance(position, getGameConfig().payAndSprays[getGame()][i]) <= getGlobalConfig().payAndSprayDistance) {
return true;
}
}
@@ -222,15 +220,15 @@ function isAtPayAndSpray(position) {
function resetClientStuff(client) {
logToConsole(LOG_DEBUG, `[VRR.Utilities] Resetting client data for ${getPlayerDisplayForConsole(client)}`);
if(!getPlayerData(client)) {
if (!getPlayerData(client)) {
return false;
}
if(isPlayerOnJobRoute(client)) {
if (isPlayerOnJobRoute(client)) {
stopJobRoute(client, false, false);
}
if(getPlayerData(client).rentingVehicle) {
if (getPlayerData(client).rentingVehicle) {
stopRentingVehicle(client);
}
@@ -243,9 +241,9 @@ function resetClientStuff(client) {
function getPlayerFromCharacterId(subAccountId) {
let clients = getClients();
for(let i in clients) {
for(let j in getPlayerData(clients[i]).subAccounts) {
if(getPlayerData(clients[i]).subAccounts[j].databaseId == subAccountId) {
for (let i in clients) {
for (let j in getPlayerData(clients[i]).subAccounts) {
if (getPlayerData(clients[i]).subAccounts[j].databaseId == subAccountId) {
return clients[i];
}
}
@@ -258,11 +256,11 @@ function getPlayerFromCharacterId(subAccountId) {
function checkPlayerPedStates() {
let clients = getClients();
for(let i in clients) {
if(getPlayerData(clients[i])) {
if(getPlayerData(clients[i]).pedState) {
if(isPlayerInAnyVehicle(clients[i])) {
if(getPlayerData(clients[i]).pedState == VRR_PEDSTATE_EXITINGVEHICLE) {
for (let i in clients) {
if (getPlayerData(clients[i])) {
if (getPlayerData(clients[i]).pedState) {
if (isPlayerInAnyVehicle(clients[i])) {
if (getPlayerData(clients[i]).pedState == VRR_PEDSTATE_EXITINGVEHICLE) {
getPlayerData(clients[i]).pedState == VRR_PEDSTATE_READY;
}
}
@@ -274,11 +272,11 @@ function checkPlayerPedStates() {
// ===========================================================================
function showConnectCameraToPlayer(client) {
if(isFadeCameraSupported()) {
if (isFadeCameraSupported()) {
fadeCamera(client, true, 1);
}
if(isCustomCameraSupported()) {
if (isCustomCameraSupported()) {
//setPlayerInterior(client, 0);
//setPlayerDimension(client, 0);
setPlayerCameraLookAt(client, getServerConfig().connectCameraPosition, getServerConfig().connectCameraLookAt);
@@ -295,19 +293,16 @@ function showCharacterSelectCameraToPlayer(client) {
// ===========================================================================
function getClosestPlayer(position, exemptPlayer) {
//let clients = getClients();
//let closest = 0;
//for(let i in clients) {
// if(exemptClient != clients[i]) {
// if(getDistance(getPlayerPosition(clients[i]), position) < getDistance(getPlayerPosition(clients[closest]), position)) {
// closest = i;
// }
// }
//}
return getElementsByType(ELEMENT_PLAYER).filter((fp) => fp != exemptPlayer).reduce((i, j) => ((i.position.distance(position) <= j.position.distance(position)) ? i : j));
//return clients[closest];
let clients = getClients();
let closest = 0;
for (let i in clients) {
if (exemptClient != clients[i]) {
if (getDistance(getPlayerPosition(clients[i]), position) < getDistance(getPlayerPosition(clients[closest]), position)) {
closest = i;
}
}
}
return clients[closest];
}
// ===========================================================================
@@ -320,20 +315,20 @@ function isPlayerMuted(client) {
function getPlayerFromParams(params) {
let clients = getClients();
if(isNaN(params)) {
for(let i in clients) {
if(!clients[i].console) {
if(toLowerCase(clients[i].name).indexOf(toLowerCase(params)) != -1) {
if (isNaN(params)) {
for (let i in clients) {
if (!clients[i].console) {
if (toLowerCase(clients[i].name).indexOf(toLowerCase(params)) != -1) {
return clients[i];
}
if(toLowerCase(getCharacterFullName(clients[i])).indexOf(toLowerCase(params)) != -1) {
if (toLowerCase(getCharacterFullName(clients[i])).indexOf(toLowerCase(params)) != -1) {
return clients[i];
}
}
}
} else {
if(typeof clients[toInteger(params)] != "undefined") {
if (typeof clients[toInteger(params)] != "undefined") {
return clients[toInteger(params)];
}
}
@@ -344,7 +339,7 @@ function getPlayerFromParams(params) {
// ===========================================================================
function updateConnectionLogOnQuit(client, quitReasonId) {
if(getPlayerData(client) != false) {
if (getPlayerData(client) != false) {
quickDatabaseQuery(`UPDATE conn_main SET conn_when_disconnect=NOW(), conn_how_disconnect=${quitReasonId} WHERE conn_id = ${getPlayerData(client).sessionId}`);
}
}
@@ -358,12 +353,16 @@ function updateConnectionLogOnAuth(client, authId) {
// ===========================================================================
function updateConnectionLogOnClientInfoReceive(client, clientVersion, screenWidth, screenHeight) {
if (getPlayerData(client) != false) {
getPlayerData(client).clientVersion = clientVersion;
}
let dbConnection = connectToDatabase();
if(dbConnection) {
if (dbConnection) {
let safeClientVersion = escapeDatabaseString(dbConnection, clientVersion);
let safeScreenWidth = escapeDatabaseString(dbConnection, toString(screenWidth));
let safeScreenHeight = escapeDatabaseString(dbConnection, toString(screenHeight));
quickDatabaseQuery(`UPDATE conn_main SET conn_client_version='${safeClientVersion}', conn_screen_width='${safeScreenWidth}', conn_screen_height='${safeScreenHeight}' WHERE conn_id = ${getPlayerData(client).sessionId}`);
quickDatabaseQuery(`UPDATE conn_main SET conn_client_version='${safeClientVersion}', conn_screen_width='${safeScreenWidth}', conn_screen_height='${safeScreenHeight}' WHERE conn_id = ${getPlayerData(client).sessionId}`);
}
}
@@ -378,8 +377,8 @@ function generateRandomPhoneNumber() {
function doesNameContainInvalidCharacters(name) {
let disallowedCharacters = getGlobalConfig().subAccountNameAllowedCharacters;
name = toLowerCase(name);
for(let i = 0; i < name.length; i++) {
if(disallowedCharacters.toLowerCase().indexOf(name.charAt(i)) == -1) {
for (let i = 0; i < name.length; i++) {
if (disallowedCharacters.toLowerCase().indexOf(name.charAt(i)) == -1) {
return true;
}
}
@@ -395,29 +394,12 @@ function getClientFromSyncerId(syncerId) {
// ===========================================================================
async function triggerWebHook(webHookURL, payloadData) {
return new Promise(resolve => {
//console.warn(webHookURL);
httpGet(
webHookURL,
`data=${payloadData}`,
function(data) {
//console.warn(JSON.parse(data));
},
function(data) {
}
);
});
}
// ===========================================================================
function clearTemporaryVehicles() {
let vehicles = getElementsByType(ELEMENT_VEHICLE);
for(let i in vehicles) {
if(!getVehicleData(vehicles[i])) {
for (let i in vehicles) {
if (!getVehicleData(vehicles[i])) {
let occupants = vehicles[i].getOccupants();
for(let j in occupants) {
for (let j in occupants) {
destroyGameElement(occupants[j]);
}
destroyGameElement(vehicles[i]);
@@ -429,11 +411,11 @@ function clearTemporaryVehicles() {
function clearTemporaryPeds() {
let peds = getElementsByType(ELEMENT_PED);
for(let i in peds) {
if(peds[i].owner == -1) {
if(!peds[i].isType(ELEMENT_PLAYER)) {
if(peds[i].vehicle == null) {
if(!getNPCData(peds[i])) {
for (let i in peds) {
if (peds[i].owner == -1) {
if (!peds[i].isType(ELEMENT_PLAYER)) {
if (peds[i].vehicle == null) {
if (!getNPCData(peds[i])) {
destroyElement(peds[i]);
}
}
@@ -445,15 +427,16 @@ function clearTemporaryPeds() {
// ===========================================================================
function kickAllClients() {
getClients().forEach((client) => {
client.disconnect();
})
getClients().forEach((client) => {
getPlayerData(client).customDisconnectReason = `Kicked - All clients are being disconnected`;
disconnectPlayer(client);
})
}
// ===========================================================================
function updateTimeRule() {
if(isTimeSupported()) {
if (isTimeSupported()) {
server.setRule("Time", makeReadableTime(game.time.hour, game.time.minute));
}
}
@@ -461,7 +444,43 @@ function updateTimeRule() {
// ===========================================================================
function isClientInitialized(client) {
return (typeof getServerData().clients[client.index] != "undefined");
return (typeof getServerData().clients[getPlayerId(client)] != "undefined");
}
// ===========================================================================
function getPedForNetworkEvent(ped) {
if (getGame() == VRR_GAME_GTA_IV) {
return ped;
} else {
return ped.id;
}
}
// ===========================================================================
// Get how many times a player connected in the last month by name
function getPlayerConnectionsInLastMonthByName(name) {
let dbConnection = connectToDatabase();
if (dbConnection) {
let safeName = escapeDatabaseString(dbConnection, name);
let result = quickDatabaseQuery(`SELECT COUNT(*) AS count FROM conn_main WHERE conn_when_connect >= NOW() - INTERVAL 1 MONTH AND conn_name = '${safeName}'`);
if (result) {
return result[0].count;
}
}
return 0;
}
// ===========================================================================
function addPrefixNumberFill(number, amount) {
let numberString = toString(number);
while (numberString.length < amount) {
numberString = toString(`0${numberString}`);
}
return toString(numberString);
}
// ===========================================================================

File diff suppressed because it is too large Load Diff

View File

@@ -3,7 +3,7 @@
// https://github.com/VortrexFTW/gtac_roleplay
// ===========================================================================
// FILE: const.js
// DESC: Provides constants
// DESC: Provides shared constants
// TYPE: Shared (JavaScript)
// ===========================================================================
@@ -34,6 +34,7 @@ const VRR_GAME_GTA_III = 1;
const VRR_GAME_GTA_VC = 2;
const VRR_GAME_GTA_SA = 3;
const VRR_GAME_GTA_IV = 5;
const VRR_GAME_GTA_IV_EFLC = 6;
const VRR_GAME_GTA_V = 50;
const VRR_GAME_MAFIA_ONE = 10;
const VRR_GAME_MAFIA_TWO = 11;
@@ -80,6 +81,8 @@ const VRR_ANIMMOVE_RIGHT = 4;
const VRR_MPMOD_NONE = 0;
const VRR_MPMOD_GTAC = 1;
const VRR_MPMOD_MAFIAC = 2;
const VRR_MPMOD_OAKWOOD = 3;
const VRR_MPMOD_RAGEMP = 4;
// Business/House Game Script States
//const VRR_GAMESCRIPT_NONE = 0;
@@ -106,4 +109,29 @@ const VRR_ISLAND_LASVENTURAS = 1; // Las Venturas
const VRR_ISLAND_SANFIERRO = 2; // San Fierro
const VRR_ISLAND_REDCOUNTYNORTH = 4; // Red County North (spans all the way from Palamino/shore on the east east to border of Flint County on the west)
const VRR_ISLAND_BONECOUNTYNORTH = 5; // Bone County North (usually called Tierra Robada)
const VRR_ISLAND_BONECOUNTYSOUTH = 6; // Bone County South
const VRR_ISLAND_BONECOUNTYSOUTH = 6; // Bone County South
// Body Parts for Skin Select (IV for now, but might do other games when I can add accessory objects)
const VRR_SKINSELECT_NONE = 0;
const VRR_SKINSELECT_SKIN = 1;
const VRR_SKINSELECT_HAT = 2;
const VRR_SKINSELECT_HAIR = 3;
const VRR_SKINSELECT_EYES = 5;
const VRR_SKINSELECT_UPPER = 6;
const VRR_SKINSELECT_LOWER = 7;
const VRR_SKINSELECT_SHOES = 8;
const VRR_SKINSELECT_LEFTWRIST = 9;
const VRR_SKINSELECT_RIGHTWRIST = 10;
const VRR_SKINSELECT_LEFTHAND = 11;
const VRR_SKINSELECT_RIGHTHAND = 12;
const VRR_SKINSELECT_HEAD = 13;
// Action States for NPCs
const VRR_NPC_ACTION_NONE = 0;
const VRR_NPC_ACTION_ANIM = 1;
const VRR_NPC_ACTION_WALKTO = 2;
const VRR_NPC_ACTION_RUNTO = 3;
const VRR_NPC_ACTION_SPRINTTO = 4;
const VRR_NPC_ACTION_FOLLOW = 5;
const VRR_NPC_ACTION_DEFEND = 6;
const VRR_NPC_ACTION_GUARD_AREA = 7;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff