Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation on 18/02/20 in all areas

  1. Good news, everyone! I think some of you had already heard about my project Oblivion Lost: Online(or The Exclusion Zone now). Today I have decided to release all the things around this project. All the resources are published right now. Enjoy it because it was made with LOVE! Comes with batteries included! The link: https://github.com/tederis/theexzone
    1 point
  2. elseif isObjectInACLGroup("user." .. account, aclGetGroup("Everyone")) then cancelEvent(true) outputChatBox("#000000║#ffffff✘ #ff0000Jᴏ#ffff00ɢᴀᴅ#00ff00ᴏʀ#ffffff ✘#000000║ - #FFFFFF"..name.."#FFFFFf:#FFFFFF "..text, root, 255, 255, 255, true) outputServerLog("CHAT: [ Jogador ] " .. name .. ": " .. text) Essa parte toda do Everyone deve ser a última. Isso é erro de lógica. Uma vez que Everyone são TODOS os jogadores, assim que o jogador entra ali, nada mais é executado a partir do Alpha.
    1 point
  3. Almoost. for k,v in pairs(getElementsByType('blip')) do local blipPosX,blipPosY = getElementPosition(v) local blipX,blipY = getMapCord(v) local rotationBetween = findRotation(playerX,playerY,blipPosX,blipPosY) local distanceBetween_GAME = getDistanceBetweenPoints2D (playerX,playerY,blipPosX,blipPosY) local distanceBetween_PIXELS = distanceBetween_GAME * (3072/6000) -- distance * (map image size / game world size) -- in this case, now we use getPointFromDistanceRotation to calculate pixels, and not ingame coordinates local blipScreenX,blipScreenY = getPointFromDistanceRotation(x+s/2,x+s/2,distanceBetween_PIXELS,rotationBetween) blipScreenX = math.max(x, math.min(x+s, blipScreenX)) blipScreenY = math.max(y, math.min(y+s, blipScreenY)) dxDrawImage(blipScreenX- 10, blipScreenY - 10, 20, 20, 'player.png'); -- I don't have blip images yet end Something like this, but it's a bit difficult to say exactly without testing it... (btw are you hungarian? If yes, I can tell you in hungarian, in more detail)
    1 point
  4. تسلم , كنت مسويها من سنه و اعتزلت
    1 point
  5. مبدع الصراحه وظيفه جميله ومفيده ♥
    1 point
  6. Não faz sentido você remover resources desnecessários... Você não usa, mas pode haver algum script que utilize... Enfim... Pode apenas restaurar o serviço em sua hospedagem e mover pro ftp os arquivos que você usa...
    1 point
  7. 1 point
  8. حبيبي يب ضض ، بفضل الله قم بفضل المبرمجين امثالكم زيك وزي كريم وديبو والخخخ .. قدرنا نصل لهذه المرحلة ..
    1 point
  9. https://wiki.multitheftauto.com/wiki/IsPedReloadingWeapon ?
    1 point
  10. تسلم ضض الك اسهام بالمود يقلب
    1 point
  11. please head to this forum instead, this section is for client/server support only: https://forum.multitheftauto.com/forum/71-scripting/
    1 point
  12. Dead topic sad function FormatSize ( size ) local Sizes = { { 9 , 'GB' } , { 7 , 'MB' } , { 4 , 'KB' } , { 1 , 'B' } } if size and tonumber ( size ) and size:len ( ) > 0 then local size = tostring ( size ) for _ , value in ipairs ( Sizes ) do if size:len ( ) >= value [ 1 ] then return ( size:sub ( 1 , size:len ( ) , ( value [ 1 ] >= 9 and - 9 or value [ 1 ] - 1 ) ) .. '.' .. size:sub ( 2 , size:len ( ) - ( ( value [ 1 ] == 9 and - 7 ) or ( value [ 1 ] == 7 and - 4 ) or ( value [ 1 ] == 4 and - 1 ) ) ) .. ' ' .. value [ 2 ] ) end end end return size end FormatSize : وظيفه تحول لك الحجم الي GB/MB/KB/B
    1 point
  13. BOM VEJO MUITOS SERVER SERVIDOR USANDO ESSE COMANDO MAIS TENTEI CRIAR ELE MAIS NAO RESPONDE UM JOGADOR COM VTR SPAWNADO ELE PODERIA USAR /DESTRUIR PARA DESFAZER DA VTR SPAWNADO TENTEI FAZER ALGUÉM CONFERE ? public OnPlayerCommandText(playerid, cmdtext[]) { // Primeiro, o script obtém o ID do veículo do carro atual e o destrói ao digitar / destroyveh if(strcmp(cmdtext, "/destroyveh", true) == 0) { new currentveh; currentveh = GetPlayerVehicleID(playerid); DestroyVehicle(currentveh); return 1; } return 0; }
    1 point
  14. Administrator Applications are now open until the upcoming Sunday, 16 February, if you're interested in becoming one of our staff members please visit our forums: http://forum.mta.advanced-gaming.org/viewforum.php?f=6
    1 point
  15. Our forums are now up, feel free to visit them by clicking here.
    1 point
  16. That's already a thing, you just need knowledge on how to setup a server.
    1 point
  17. Nice to see the 31.8k playerbase figure on December 15, just some solid proof that GTA:SA is still not ready to die. Keep it up guys and happy holidays!
    1 point
  18. Introduction This guide intends to teach 3ds Max users the basics and more advanced ways of working with Vertex Colors, in order to achieve lighting solutions for enhanced quality of game models, or blend several textures together using Vertex alpha. A lot of games utilises vertex colors to accomplish lighting or blending effects, which usually impacts the performance less than model shaders. Types of shaders such as Texture Splatting are pixel based techniques for rendering multiple textures onto a model, where each texture e.g earth, grass, gravel, has their own color on the splat map. This however may use up significantly more resources than its alternatives in some cases. As result, game developers may move their aim towards Vertex Alpha and Color rather than geometry shaders. Vertex Color works almost the same way, however it renders per vertex and not per pixel unlike shaders do. This may result in very poor results if the geometry is not subdivided at the places it is painted at. Besides texture blending, vertex colors are also widely used in games for fake lighting baked into models. This is due to some game engines not supporting Ray Tracing or other rendering, or they simply prefer using vertex colors over per-pixel lighting. In GTA:SA the only light rendering is done by vertex colors and 2DFX. In the days that the game was developed, vertex colors was a more sustainable rendering method over other options. Table of contents Different model lighting depending on game time Importance of vertex colors Importance of vertex illumination Basics of per-vertex Radiosity workflow Hard surface prelighting Faking ambient occlusion Texture blending with Vertex Alpha The vertexPaint modifier Extracting channel info Working with several VertexPaint modifiers Different model lighting depending on game time Game models use two vertex channels for lighting. Vertex color is displayed around 06:00 - 20:00. Vertex illumination is displayed outside that timeframe, that is, between 20:00 and 06:00. Between these timeframes, the two channels blends into eachother, creating a realistic daytime and nighttime visualization of the map. Remembering which channel is used for what can be a little troubling, on top of the many other things. Artists could consider Vertex Color = daytime, Vertex Illumination = nighttime. Below are various demonstrations of vertex color and illumination channels. Importance of vertex colors Below video demonstrates the effects of not prelighting game models for GTA:SA. The results are very easy to differ from prelit models, as the only depth seen on the models is made by the diffuse maps, which usually does not add sufficient shadows. That is where the artist may consider prelighting his model. As seen on the video, first footage is of San Fierro chunk without diffuse maps (textures) nor vertex colors. This results in completely white meshes. If however, the artist decides to utilise vertex colors, the model will have a lot greater depth added, without the need to bake light into textures at the expense of computer memory. The video's contents are 1:1 to how San Fierro would be rendered in-game around 12:00. No post processing or edits made to the models. Compression methods, post processing, sky and fog done by the Renderware engine will make it a tad different though. Below screenshot is taken from a Dust2 model ripped from Counter Strike. It shows how the vertex channel brings shadows and ambient occlusion into the model. If it did not have the vertex channel changes made, it would be completely flat, corridors would have no depth whatsoever, only some by the difference between the textures. Importance of vertex illumination Not all models use fancy colors like the pirate assets by Las Venturas strip. A lot of models use the same, though slightly darkened, version of vertex colors for the vertex illumination channel. The result of this is a darker object during night and brighter during day. Perhaps some has some highlights that are cast from streetlights and other light sources that appear during nighttime. Some models, notably light objects use vertex colors in conjunction with 2DFX in order to create realistic light with a real light source. Below example is a runway light. The white version is during day time, where the inner light mesh (the extruded part) is grey to represent an deactivated light. The red version is during night time, where the top surface has light reflected onto it, together with a corona image, more commonly known as 2D billboard or sprites. The corona acts as the light source and creates a bloom alike effect. (Not seen in image) Basics of per-vertex To get a somewhat understanding of how vertex colors work, below demonstration should be helpful. The triangle's top left vertex is painted blue, top right painted green and bottom painted red. This creates an RGB blend display of the triangle. The planar model has its bottom vertices painted black while the top ones are white. This creates more of a gradient across the entire model.To put the difference between per-vertex lighting and per-pixel lighting short, Vertex based lighting creates a gradient from one vertex towards the nearest one(s), and stops there. If a model has only 4 vertices, it is not possible to have circular or very detailed IES-like lighting, as the model would have only 4 points that can have light data. Pixel based lighting can have as many abstract details as artist wishes. It works as if there is a grayscale image on top of the model with a different blend mode, or dynamic lighting based on world models, hence the two are called per-vertex and per-pixel. Radiosity workflow Tired of painting vertex colors onto models with silly brushes all day? 3ds Max has an amazing light renderer, which can produce stunning renders and best of all, stunning prelights. As if it was made for GTA:SA era games! Not to forget, a 3rd party Max script was made to make the workflow a lot less difficult - can be found on: http://www.scriptspot.com/3ds-max/scripts/vertex-color-tools-1. With this script, artists can with a few clicks create a skylight, ground plane (for AO), then render a radiosity solution in less than a minute total. No more setting up radiosity settings, only a few adjustments to your likings if needed. I use it all the time myself, and in fact, I learned to create beautiful prelights by using this tool with radiosity rendering. Before moving on, ParoXum's Radiosity tutorial and the Radiosity wikipedia page contains extra information that is not covered in this thread, for instance particular use of point lights. For that reason they may be benefitable to read through. WARNING! Pressing the AO button on the Vertex Color Tool script, ALL materials will be reset to standard. This can not be reversed! Adding to the above. Make sure to create a backup Max project file prior to working with Radiosity. Use the backup Max project file for vertex colors, leave original file for modeling! This process is covered in the guide. Hard surface prelighting Most artists starting out with vertex colors have probably grown tired of selecting faces of a model, then painting a different value onto each to replicate a hard surface look. As it turns out, this is not an efficient way. The model will look odd if the artist has not put enough time (hours with sweat) into it. That is where automating it with Radiosity rendering is a fantastic solution. To get started, download the following FBX scene https://cdn.discordapp.com/attachments/308956559201796097/632340906170908673/demo.zip. Each point contains a spoiler with a video clip. For those who would like to mess around with the final result of mine, download FBX here: https://cdn.discordapp.com/attachments/308956559201796097/632559814387695626/demo_result.zip (video below) Important thing to note, when using Radiosity for prelights, the shading/lighting which is baked into the model entirely depends on the smoothing of the model. If it's set to Auto Smooth value 2 the shading will resemble 3ds Max's shading 'facets', while if the model has only one smoothing group, the shading will be incredibly smooth and generally won't have any facet shading. San Andreas models generally had very low smoothing value for its models at their creation, judging by their hard surface appearence. If a modeler were to create models that blend in with the game environment, they should strongly consider the above. Video tutorial: Text tutorial: Import the file Click the 3ds max upper left corner, at Import hover over the arrow for a drop down menu to appear. Click Import. Click the demo.FBX. Ensure to include Smoothing Groups on import, and units setup in Meters. Reset X, Y, Z positions to 0, 0, 0. At import the model is not centered. Create light Navigate to Create tab, click the gears icon, finally select the Daylight button. Max will ask if it can set an exposure control flag (not a country flag bleh), click Yes. Click anywhere, this sets the compass. Then, drag the mouse up into the sky, press LMB to spawn the daylight system. The compass position is not important. Alter light Navigate to Modify tab, change Sunlight from Standard to IES Sun. Likewise for sky, make it IES Sky. On Sun Parameters uncheck Shadows. Ensure the sun's state is On. On IES Sky Parameters it is possible to modify the intensity of the sky, as well as the sun. Some of the settings that affect the sun is whether the weather is clear or clouded. Leave default. On hierarchy list, select the Daylight001 item. While on Modify tab, click the Setup button for setting the scene weather. As the light system works like real daylight, the lower the number of hours, the darker the scene. Set hours at 9, month at 9, orbital scale at 320-360. Initiate the radiosity solution by running Vertex Color Tools Ver1.0. Press the AO button. Keep in mind, that this will remove all materials and cannot be reversed with undo. The render setup window opens. Another window from Rendering > Exposure Control is needed. On Exposure Control, change from none to Logarithmic. Tick on the Exterior daylight checkbox, which is required due to scene using a daylight system. Optionally, start rendering previews via the Exposure Control window. These previews are very low resolution and may help visualise the lighting. Or, real renders by SHIFT Q, although this may take significantly more time and processing power. On Render Setup window, reset value of Indirect Lighting Filtering. Increase the Direct Lighting Filtering to a value of 8. Under Radiosity Meshing Parameters tick the Include Skylight checkbox. Under Rendering Parameters select Re-Use Direct Illumination from Radiosity Solution. On Render Setup window, make sure to press Reset, to then start a clean rendering with the updated settings. Click Start. This may be an incredibly slow process, even on high end computers. If it gets stuck, set quality to less. It does not really have much of an impact for GTA:SA light anyway. Voila, done. The final result will be displayed in viewport. The result is equal to what is seen in-game during day hours. If something looks off, go back and tweak settings. Bake Radiosity lighting solution into vertex channel. Navigate to Utility tab, click More..., select Assign Vertex Colors. Upon scrolling down the utility tab, the Vertex Colors settings appear. Vertex Color is for day time, Vertex Illumination is for night time. Choose Vertex Color. Set light model as Lighting + Diffuse. Set Color Assignment as whichever seen fit. On Rendering options, enable Mapping and Radiosity, Reuse Direct Illum. from solution. Finally, click Assign to Selected View vertex color result in viewport. On the VertexPaint modifier, select the channel that was just modified. On the VertexPaint GUI, click the shaded box to the left. This displays the model with only vertex channel rendering, no other 3D shading will be used. Further tweaking If one wishes night time lighting, the best to do is render a new radiosity solution with less sun and daylight intensity, in order to darken the scene. Eventually change to clouded or mess with weather settings. The new radiosity solution will be equally the same as the one for daytime, although a tad darker. When rendered, assign to illumination channel. The letters can be painted for night time to look extra cool. This is where painting by buckets onto face selections of the mesh can come in handy, using the VertexPaint modifier. Odd looking shadows can be fixed up with the blur brush (VertexPaint modifier). Those who are able to get results with the above Radiosity workflow, may utilise their knowledge and take prelighting a next step with other types of lights, in order to create environment lights such as shadows for light poles, torches, buildings etc. Point lights, more specifically Free Light, were used a lot in the ship model further down the topic. Scene lighting is generally hit and miss. There are many settings which may need to be changed e.g scale of daylight and smoothing groups of models, in order to get the right look. Faking ambient occlusion Vertices can easily store ambient occlusion details, negating the need for geometry shaders. Some models may require additional geometry through subdividing the mesh, in order to achieve proper ambient occlusion details with vertex colors. The type of light used is usually skylight or daylight, this creates subtle shadows around corners and creaks, as well as maintaining global lighting. The below model has vertex AO baked by using a Skylight with the following settings. *you can eventually utilise a plane as ground for the ambient occlusion to calculate a lot better. The above practise can be used for GTA:SA assets as well, some settings may require to be tweaked first though. Prelighting in general is trial and error unless the artist has a solid background with lighting and rendering. Generally though, ambient occlusion should not be the only layer for lighting a model. Hard surface lighting as well as adding point lights is highly recommended. Without these, models with AO will still look rather flat in most cases, as there is not much definition between corners, other than soft shadows. Adding point lights to radiosity render will also give the lighting a more natural feeling, this can be done by adjusting the temporature of the light or its color. Combining point lights (free light, omni light, etcetera) with 2DFX can give stunning results. Texture blending with Vertex Alpha Texture blending on MTA was thought to only be possible by shaders, e.g texture splatmap. Instead, we can now blend textures using Vertex Alpha channel. On December 27 2019 we discovered that Vertex Alpha works without need for additional scripting (MTA Discord #modelling). We also need to thank Deniska for writing this guide (gtamaps) on vertex alpha plus creating a maxscript that exports vAlpha channel! Vertex Alpha works based on grayscale values just like alpha masks. Any vertex that's black will not be rendered - any vertex that's not black will be rendered. White is fully opaque, while the greyer it gets, the more transparency is made. Vertex Alpha will not render water behind its faces, so it's important to place an opaque object behind the vertex alpha mesh. This must be a separate model, not part of the mesh that uses vertex alpha. As with vertex prelights, vertex alpha needs geometry to work with. It's highly recommended to turbosmooth/subdivide the mesh so that you can paint in more detail. In the video below, I show how quickly the vertex alpha can be added to your models, and once that's done, you can export the model using the script from this page. Create a plane primitive. Give it 16x16 segments. Convert it to editable mesh. Give it the material that needs to blend using alpha. Set opacity of material to 98. Add a VertexPaint modifier. Select the vertex alpha channel. Use paint bucket with black color, 100 intensity, to paint entire mesh black. Add a secondary vertexpaint modifier. Grab your brush, adjust its size and strength. Begin painting a path from one end to another. Use the blur brush to finetune the semi-transparent edges of your path. Sharp edges ain't good. Looks OK? Start the export-script. You don't need to collapse your modifiers when exporting. Keep them in stack for later adjustments. Export with MMC. Remember to always set alphaTransparency enabled when replacing the model, or else only part of alpha will show. If you want to use another DFF script (for a higher quality dff), simply copy paste the sections e.g "Extra Vertex Colors" via RWanalyze. (Script will break (in which case, close script and run again) if you try to export vertex colors without having first assigned vertex colors/illumination to the model via its respective channels) List of model ID's that use the flag 68 (NO_ZBUFFER_WRITE(64) + DRAW_LAST(4)), which is required for Vertex Alpha: 2728, 3872, 3910, 4227, 4636, 4637, 7892, 9831, 9896, 9897, 11678, 11679, 11680, 11681, 13494, 13495, 13496, 13497, 13498, 13499, 13500, 13501, 13502, 13503, 13504, 13505, 13506, 13507, 13508, 13509, 13510, 13511, 13512, 13513, 13514, 13515, 13516, 13517, 13518, 13519, 13520, 13521, 13522, 13523, 13524, 13525, 13526, 13527, 13528, 13529, 13530, 13531, 13532, 13533, 13534, 13535, 13536, 13537, 13538, 13539, 13540, 13541, 13542, 13543, 13544, 13545, 13546, 13547, 13548, 13549, 13550, 13551, 13552, 13553, 13554, 13555, 13556, 13557, 13558, 13559, 13560, 13561, 13563, 16375, 16445, 16498, 16623, 16676, 16677, 16733, 16734, 16753, 16754, 16756, 16757, 16758, 16783, 16784, 17436, 17437, 17438, 17439, 17440, 17441, 17442, 17443, 17444, 17448, 17450, 17451, 17451, 17452, 17458, 17459, 17460, 17461, 17462, 17463, 17464, 17465, 17466, 17467, 17468, 17469, 17470, 17474, 17524, 18073, 18112, 18610, 18611, 18612, 18613, 18614, 18615, 18616, 18617, 18618, 18619, 18620, 18621, 18622, 18623, 18624, 18625, 18626, 18627, 18628, 18629, 18630, List of model ID's that use the flag 64 (NO_ZBUFFER_WRITE(64)) which are not tested, but might work for Vertex Alpha: 1315, 2981, 4712, 4724, 4554, 8004, 8044, 11306, 14765, Below are a few examples of how vertex alpha can be used to blend several textures together. Above image courtesy: worsas @ project tamriel (see link for more) 128x128 textures, 8192 polygons (can be a lot less!) You can probably create something a lot better than this. Time to get creative! If you're looking for additional inspiration, see the videos in spoiler. Note: The below spoiler contains information that does not apply to vertex alpha method, but instead to vertex colors. This requires shaders, since SA uses the colors for lighting, but is a decent alternative if the model use lighting shaders. The vertexPaint modifier VertexPaint is the modifier that houses the WIP vertex colors, illumination and alpha modifications. It may be accessed on Modifiers tab. While it is open, it allows the artist to do various changes to the vertex channels. Ranging from painting with the use of brushes, to refining vertex colors by blurring, adjusting hue, saturation, lightness etcetera. This is a very powerful tool, despite not having been updated for years. To get started, the modifier works with a float GUI with all of its necessary functions in it. It is worth noting that the modifier can not change existing vertex channel data, only the data that is stored in the modifier. That means it is not possible to import a GTA:SA asset and modify the hue of the vertex color channel. For an exhaustive list of what the modifier offers, check Autodesk's page on the VertexPaint Modifier. Brief explanation of what the modifier has to offer, from top to bottom: Extracting channel info For whatever reason, an artist may want to copy the vertex channel data, that is, the custom vertex information, and paste that onto their latest version of the mesh. This could be due to an irreversible action that would prevent the artist from undoing the lighting changes on present model, resulting in work lost and having to redo it all over again. Although this may seem like a promising solution to regain old channel data, it can generate problems if the two models contain different geometry counts. Below steps explains how to copy/paste data. Navigate to Utilities tab, click the More button, after which, click Channel info. At last, press the button that appeared on the bottom of the utilities tab. At first, the Channel Info GUI may seem complicated; but it really is not. The only information to look out for is the ID column and Channel Name column. The Num Verts, Faces etc. are only important to verify that the two model contains the same model geometry count. In the above example, the model has no custom channel data. The -2:Alpha, -1:Illum and 0:vc are the types of channel info's that are relevant for GTA:SA, although the Alpha data currently isn not compatible with MTA. To copy data, simply select either of the rows and press the Copy button. Then, highlight the present model, select the corresponding channel and paste. Working with several VertexPaint modifiers On more advanced tasks it may be necessary to use multiple VertexPaint modifiers stacked onto the model. Artist may find it helpful if they are doing several versions of prelighting for their model and wants to go through each result, picking the one that suits them the most. This means that each type of radiosity lighting solution will be stored in its own modifier, allowing artists to go through all of them and delete the poor ones. Having multiple modifiers on stack can also improve workflow by utilising each modifiers for each element of the model, such as Modifier1 for bonfire logs, Modifier2 for bonfire shadows, Modifier3 for ambient occlusion, Modifier4 for moonlight etc. Modifiers can also be renamed to quickly tell the artist what they are representing. The model can have as many modifiers in its stack as the artist wishes (or until the software times out), and they do not require to be collapsed when exporting the model to MTA. This means that the modeler simply needs to select the model, export it and load into MTA. Modifiers can then be collapsed to stack when job's done, however, it is strongly recommended to keep them in stack for future, in case of parts requiring rework. Below model may give a good look into just how much it helps to utilise multiple modifiers. The ship has its own modifier for virtually any type of light emmitting source. The rectangular screens to the right are symmetrical on the other side, so there is one modifier that represents those 6 rectangular emmissive screens. Same goes for the cyan U-shaped engravement, which uses its own independant modifier, and so on. This allowed to change the engravement prelight from initially dark blue to cyan, by not affecting other lights when modifying the hue, as the modifier was only used by that particular area. The stack works like so: By clicking the bottom modifier, only that one's layer will show. If clicking the one above it, assuming it is same channel, it will show both of them. Now, if clicking the top modifier, it will show all layers e.g the rest 4 that are associated with Vertex Illum channel. It will only display the channel that is selected on the right most panel. (This depends on version of Max)
    1 point
  19. Lua tutorial for absolute beginners This tutorial can also be viewed on GitHub This tutorial aims to teach the Lua scripting language to those with 0 previous experience with programming / scripting. This guide will start with explaining some Lua concepts, and will later on move to explaining MTA:SA specific concepts. Table of contents: Lua Scripts Variables Data types Operators If statements Functions Return values scopes & locals For loops Tables Iterators (pairs/ipairs) Callbacks Anonymous functions MTA Server & Resources Server vs client MTA functions & wiki Elements (userdata) Command handlers Event handlers predefined globals server <-> client communication Now what? Lua This part of the tutorial discusses Lua itself. No MTA-specific concepts will be discussed here. Scripts The Lua scripting language is a language which is interpreted by a "Lua interpreter". MTA:SA's resources use such an interpreter to run Lua code. For the beginning of this tutorial you can use the online Lua interpreter available on https://www.Lua.org/demo.html. Any code in the Lua part of the tutorial can be run on this website. Lua is written in "plain text". This means it exists of regular characters like any other text you are writing. To edit Lua files you will require a text editor. You could use Notepad, but there are many far better alternatives. My personal favourite is Visual Studio Code, but there are many other good options, to name a few: Atom, sublime text, notepad++ Lua files are usually saved with the .Lua file extension Variables The first concept we're going to discuss is variables. Variables allow you to store a value in your code. For example: x = 10 print(x) print(x) will output the value of the x variable. We will get into what exactly print is later in the tutorial. Variables can have any name you want, as long as you follow some specific rules. variable names must start with a letter (lower or upper case), or an underscore (_) variable names may contain letters (lower and upper case), numbers and underscores. x = 10 y = 20 z = 30 print(x) print(y) print(z) The convention in Lua is to name your variables in "camelCase". This means if a variable exists of multiple words you start every word with a capital letter, except for the first one. camelCaseVariable = 5 Data types So far we've seen variables used to store numeric values, but there are many different types of data Lua can handle. These are: number Any numeric value string A piece of text, a string is surrounded by " or '. For example "Hello world" or 'Hello world' boolean A boolean is a data type that has only 2 options, true and false. nil nil is a value indicating nothing. It's the absence of a value. (Not the be confused with 0) table Tables will be discussed later in the tutorial userdata Userdata will be discussed later in the tutorial function Functions will be discussed later in the tutorial thread Threads are out of scope for this tutorial and won't be discussed So we can use these different data types, and store them in variables: numberVariable = 10 stringVariable = "Hello world" booleanVariable = true nilVariable = nil Operators Operators are symbols in Lua which can be used to do "things" with variables. Here's a list of operators and an example for each: + operator Adds two values together x = 10 + 10 print(x) y = 20 print(y) z = x + y print(z) - operator Subtracts a value from another value x = 10 - 10 print(x) * operator Multiplies two values x = 10 * 10 print(x) / operator Divides a value by another value x = 10 / 10 print(x) % operator This is the "modulo" operator. This will divide a value by another, and return the leftover. x = 10 % 4 print(x) The result of this is 2 and operator The and operator will return true if both variables are "truthy". Otherwise it returns false (A "truthy" value is anything except for false and nil) x = true and false print(x) y = true and true print(y) or operator The and operator will return true if one of the variables are "truthy". Otherwise it returns false x = true or false print(x) y = false or false print(y) == operator The == (equals) operator will return true if both of the variables are the same. Otherwise it returns false x = "hey there" == "hello there" print(x) y = 150 == 150 print(y) ~= operator The ~= (does not equal) operator will return true if both variables are not the same. Otherwise it returns false x = "hey there" ~= "hello there" print(x) y = 150 ~= 150 print(y) > operator The > (greater than) operator will return true if the first value is greater than the second value. Otherwise it returns false x = 10 > 5 print(x) y = 10 > 15 print(y) y = 10 > 10 print(y) >= operator The >= (greater than or equals) operator will return true if the first value is greater than, or equal to, the second value. Otherwise it returns false x = 10 > 5 print(x) y = 10 > 15 print(y) y = 10 > 10 print(y) < operator The < (less than) operator will return true if the first value is less than the second value. Otherwise it returns false x = 10 < 5 print(x) y = 10 < 15 print(y) y = 10 < 10 print(y) <= operator The <= (less than or equals) operator will return true if the first value is less than, or equal to, the second value. Otherwise it returns false x = 10 < 5 print(x) y = 10 < 15 print(y) y = 10 < 10 print(y) .. operator The .. (string concatanation) operator allows you to add two strings together. x = "Hello" z = "World!" combined = x .. " " .. z print(combined) If statements An if statement allows your code to decide to do something, or not. Depending on a value. Often times if statements are used in combination with some of the above operators. An if statement is written as : if <expression> then <code> end x = 10 if x > 5 then print("X is higher than 5") end Any code between then and end will only be executed when the expression is true. You might also have noticed that the code between the then and end is moved over a bit to the right. This is called "indentation". Whenever we open a new scope (scopes will be discussed later in the tutorial) we move our code to the right. This is usually done by either a tab or several spaces . Many code editors will convert a tab to spaces. Else Within an if statement, you can also add an else block. The code in such a block will be executed when the code in the if block is not executed. x = 10 if x > 5 then print("X is higher than 5") else print("X is not higher than 5") end Elseif If you want to do multiple if statements, you can use an elseif: x = 15 if x > 10 then print("X is higher than 10") end if x > 5 then print("X is higher than 5") end x = 15 if x > 10 then print("X is higher than 10") elseif x > 5 then print("X is higher than 5") end The difference between the first example and the second is that if x is higher than 10 in the first example both lines "X is higher than 10" and "X is higher than 5" will be output. Whilst in the second example only "X is higher than 10" will be output. And if statement must always start with an if, can contain multiple elseifs, and may only have one else. name = "NanoBob" if name == "NanoBob" then print("Hello world!") elseif name == "Brophy" then print("Black 123") elseif name == "Tombaa" then print("Stupid") else print("I have no idea") end Functions Functions allow you to write less code, by reusing pieces of code. The syntax to create a function is function <name>(<parameters>) <code> end function foo() print("Hello world #1") print("Hello world #2") end In order to execute code in the function, you "call" the function. You do this by writing the function name followed by (). function foo() print("Hello world #1") print("Hello world #2") end foo() foo() foo() Functions also allow you to send a variable to the function, for it to do something with. This is what's called a function parameter. Function parameters are defined in the brackets () after the function name. function foo(x) print(x) end foo(10) foo("50") You may notice that this looks a lot like the print() we have been using. This is because print is a built-in Lua function. Return values A function not only can execute code, it can also give something back to where it was called. This is called a return value. In order to return something from a function you use the return keyword. function foo() return 10 end x = foo() print(x) print(foo()) Just like in an if statement, all code within a function is indented. Now let's combine everything we have learnt so far: function foo(x) if x > 10 then return "X is higher than 10" elseif x > 5 then return "X is higher than 5" else return "X is not higher than 5" end end y = foo(15) print(y) print(foo(10)) print(foo(0)) Scopes & locals We quickly encountered scopes before, and said we indent our code whenever we enter a new scope. But scopes allow you to do more than that. Most importantly, "local" variables. A local variable is only available in the scope it was defined in (or scopes that were created from within that scope) You can create a new scope using a do block (functions and if statements also have their own scope). do local x = 5 print(x) end print(x) do local x = 5 do local y = 10 print(x) print(y) end print(y) end For loops (For) loops are ways in scripting / programming to have code executed multiple times, without having to write the same thing multiple times. An example of such a loop: for i = 1, 10 do print(i) end The first part : i = 1, 10 defines a variable called i. Which start at 1. This will be incremented by 1, until it reaches 10. The code within the loop then can use this variable. You can also increment with a different number than 1 (including negative numbers) using this construct. for i = 20, 0, -2 do print(i) end This code sample will start with i at 20, and keep adding -2 (thus subtracting 2), until it reaches 0 Tables Tables are a datatype in Lua which allows for lists of things. Here's an example: x = { [1] = 100, [2] = 200, [3] = 300 } print(x[1]) print(x[2]) print(x[3]) Tables consist of key/value pairs. In the example above the key 1, has the value 100, 2 has the value 200, and 3 has the value 300. You can get the value in a table, by putting the key in between square brackets []. Like in print(x[1]). x = { 100, 200, 300 } print(x[1]) print(x[2]) print(x[3]) You can choose to not include the keys in a table. Doing so will automatically add numbers as keys, starting at 1. So the above example would be the exact same as the first example. Table keys and values can be of any data type, including other tables. This allows you to create (very) complex table structures. t = { [1] = { 100, 200, 300 }, ["x"] = 100, [true] = "something" } print(t["x"]) print(t[true]) print(t[1][1]) print(t[1][2]) print(t[1][3]) When using a string as the key in a table, you can leave out the square brackets and the quotes. This goes for both when defining the table, and for indexing it (getting a value from it). For example t = { x = 100, y = 200, z = 300 } print(t.x) print(t.y) print(t.z) A table's values can be modified / set after creating the table as well. t = {} t[1] = 10 t[2] = 20 t[3] = 30 t["x"] = "banana" t[true] = false t.x = "banana" When using tables you will often want to add something to the "end" of a table. This is most common when you are using tables with numeric keys. In order to do this you can use a # to get the amount of items currently in the table. t = { 10, 20, 30 } t[#t + 1] = 40 This will store the value 40 on the key 4 , because #t is 3. Iterators (pairs/ipairs) Iterators are a mechanism that allow you to make a loop, which goes over a set of values. Writing your own iterators won't be discussed in this tutorial. But there are two functions which are often used to create an iterator to iterate over a table. These are pairs and ipairs. t = { 10, 20, 30, 40, 50 } for key, value in ipairs(t) do print(key, value) end The difference between pairs and ipairs is the order in which the key/value pairs are iterated over, and which of the key/value pairs are iterated over. Where ipairs will always use numeric keys, starting at 1, and going up by 1 every time, until there is no entry in the table. This also means it won't iterate over anything key that is not numeric. t = { ["x"] = 5, [1] = 10, [2] = 20, [3] = 30, [5] = 50, } for key, value in ipairs(t) do print(key, value) end A pairs loop will iterate over any value in a table, but the order is not guaranteed. Meaning that between different runs of the script the order could be different. t = { ["x"] = 5, [1] = 10, [2] = 20, [3] = 30, [5] = 50, } for key, value in pairs(t) do print(key, value) end Callbacks Callbacks are when you pass a function as an argument to another function. To have the function you passed be called later on. This is used often within MTA. An example of a Lua function which uses a callback is table.sort. table.sort will sort a tables values, by default these values are sorted numerically. But you can use a callback to change this behaviour. values = { 5, 4, 3, 6, 8, 1, 2, 9, 7 } function sortFunction(a, b) return b > a end function reverseSortFunction(a, b) return a > b end table.sort(values, sortFunction) print("Sorted: ") for _, v in ipairs(values) do print(v) end table.sort(values, reverseSortFunction) print("\nReverse sorted: ") for _, v in ipairs(values) do print(v) end In the first call to table.sort (table.sort(values, sortFunction)) you can see the sortFunction function is passed as second argument to the function. Note that we don't write sortFunction() here (notice the brackets difference) because that would call the sortFunction function, and pass its return value to table.sort. table.sort will then call this function when it compares two different values, this function should return true or false depending on whether its second argument (b in this case) is larger than it's first argument (a), in the context of sorting. Anonymous functions It is also possible to use an "anonymous function" when passing a callback to a function. values = { 5, 4, 3, 6, 8, 1, 2, 9, 7 } table.sort(values, function(a, b) return b > a end) print("Sorted: ") for _, v in ipairs(values) do print(v) end table.sort(values, function(a, b) return a > b end) print("\nReverse sorted: ") for _, v in ipairs(values) do print(v) end MTA This part of the tutorial discusses MTA specific constructs. Code in this part of the tutorial won't run in the online Lua interpreter. You will need to set up a (local) server for this. Server & Resources By default when installing MTA:SA a server is installed as well. This server is located in the "server" directory of your MTA directory. This is usually at C:\Program Files (x86)\MTA San Andreas 1.5\server. This directory contains an MTA server.exe file, running this file will start a server. Scripts on a server are grouped by resources, a single resource can consist of multiple script files and other assets such as images, sounds, fonts, mods and more. Resources are placed in your mods\deathmatch\resources folder in your server folder. A resource is always in its own directory. A resource must always have a single meta.xml file. This file tells the server (among others) what script files to load. A typical meta.xml file looks like this: <meta> <script src="vehicleSystem.Lua" type="server"/> <script src="vehicleMods.Lua" type="client"/> </meta> You will need an entry for every .Lua file you want to have executed on the server. You can start a resource by typing start <resource name> in the server console (the window that opened when you started MTA Server.exe). The resource name is the name of the directory your meta.xml is in. (This may not have spaces). Starting a resource will start running the Lua scripts, if you've changed your scripts you will need to restart the resource for the changes to take effect. (restart <resource name>). Server vs client Lua code can be executed in one of two places. The server, or the client. Server sided scripts are executed on the actual machine that is running the MTA server.exe process. Client sided scripts are executed on the computer of every player that connects to your server. Server sided and client sided scripts have a distinct difference in responsibility and possibility. Some functions for example are only available on the client, whilst others are available only on the server (and many on both). Note: Some of these functions which are available both server sided and client sided are different on server and client MTA functions & wiki In plain Lua there's not much you can do to affect a game engine like MTA:SA. This is why MTA:SA offers a (large) list of functions available for you to use in your scripts which interact with the actual GTA world. You can find a list of all of these, what they do and how to use them on the MTA wiki. Server sided functions Client sided functions shared functions An example of such a function is createObject(). This function will create a physical object in the game. The wiki page contains information on how to use it (what arguments it expects, and in what order). And often shows an example of how to use it. createObject(1337, 0, 0, 3) Elements (userdata) At the start of this tutorial we quickly mentioned userdata data types. These are data types configurable by the implementation of Lua. In this case, MTA. MTA uses userdata to represent "elements". Many things in MTA are elements, like objects, markers, peds, players, user interfaces, vehicles, etc. On the MTA wiki you will notice many functions either return elements, or require an element as arguments. A list of different types of elements can be found on the MTA wiki. Elements also have a hierarchical structure to them. Elements can have a "parent", and multiple "children". This will result in a tree of elements, the element at the top of this tree (and thus the grandparent of all elements) is called the root element. Command handlers Often times in MTA you want certain things to happen when a player enters a command. This is done using command handlers, command handlers use a callback, which we previously discussed. The wiki contains a page for the addCommandHandler() function. For this example we will be using the server side version. function handler(player, command, argument) outputChatBox("You entered " .. command) if argument ~= nil then outputChatBox("You used the argument " .. argument, player) end end addCommandHandler("banana", handler) This example also uses the outputChatBox() function, this will output a piece of text to the chat.(in this case, only for the player who executed the command) The callback function passed to addCommandHandler will be called every time a player uses the /banana command ingame. Event handlers Besides having your script do things when a user executes a command you likely want the game to respond to many different types of things that happen in the game. Like players taking damage, coming close to something, etc. These things are called events. Whenever an event is triggered you can run a piece of Lua code. You do this using event handlers. Event handlers are created using the addEventHandler(). The first argument to the addEventHandler() function is the string name of the event. These can be found on the MTA wiki as well. Server sided events Client sided events An event is always triggered for a specific element, for example "onPlayerWasted" is triggered on the player that was wasted (killed). You can attach an event handler to a single element to only have your callback function be called when the event is triggered on that specific element. But you could also use the root element here and your function will be called for every element the event is triggered on. function handlePlayerDeath() outputChatBox("You died!!", source) end addEventHandler("onPlayerWasted", getRootElement(), handlePlayerDeath) The getRootElement() function used in this example returns the root element discussed earlier. You can also see source is used in this code snippet, we'll talk about that some more in the next section. predefined globals MTA has some predifined global variables for you to use in your script. A list of them can be found on the wiki. Here's a couple notable ones and what they're used for root The root element, same as the return value of getRootElement()) source The element an event handler was called on. An event's wiki page always describes what the event source will be for the event. localPlayer The player element for the player whose client the script is running on. (Thus only available client sided) client Will be discussed in the next section server <-> client communication As stated earlier in this tutorial scripts can run either on the server, or one of the connected clients. However often times you would want to trigger something on the server from a client, or the other way around. An example of this would be when the user clicks the login button on a GUI (Graphical user interface) the server should try to log that person in, and send him back whether or not this was successful. This can be done using events. MTA allows you to create and trigger your own events, and these events can be triggered from server to client (and the other way around). You can do this using the addEvent() function. Once an event has been added (and marked as remotely triggerable by passing true as second argument to addEvent()) you can call it from server/client. You do this using [triggerClientEvent()]https://wiki.multitheftauto.com/wiki/TriggerClientEvent() and triggerServerEvent() respectively. Server sided: function handlePlayerLogin(username, password) outputChatBox("You tried to log in with the username " .. username, client) end addEvent("LuaTutorial.Login", true) addEventHandler("LuaTutorial.Login", root, handlePlayerLogin) Client sided: function pretendLogin() triggerServerEvent("LuaTutorial.Login", localPlayer, "username", "password") end pretendLogin() This example will trigger the "LuaTutorial.Login" event from the client sided script. And passes the "username" and "password" arguments to the event. The server then handles this event in the handlePlayerLogin() function, which in our case just outputs something to the chatbox. In this example you can see the previously mentioned client global variable. This variable is set to the player element corresponding to the client the event was triggered from. (And is thus only usable when used in an event handler which has been triggered from a client). Now what? With this information you should be able to start scripting, and making things in MTA! If you didn't understand it all in one go, or you have any more questions there is no shame in that! You can find myself and many others willing to help you with your scripting questions in the #scripting channel on the MTA discord. Another good source for programming / scripting related questions is stack overflow.
    1 point
  20. Está iniciando seu servidor ou começando scripting no MTA? Aqui será listado tudo o que você precisa para aprender desde configurar seu servidor, ACL, colocar resources, até aprender Lua no MTA e criar scripts para modificar o jogo por meio da programação. Se você é totalmente leigo no assunto você também verá links que irá te introduzir no nível básico da programação, basta ter o mínimo de esforço e acompanhar os tutoriais aqui mostrados. Se você já têm uma noção de programação, encontrará tutoriais que irão te ajudar a se aprofundar na programação Lua e ter uma boa experiência de Scripting no MTA. Informações relacionadas ao MTA Se você busca configurar corretamente o seu Servidor e entender como as coisas funcionam, estes links serão de grande ajuda: Links traduzidos para português Manual do Servidor ACL - Lista de Controle de Acesso Resources (ou Recursos) - O que são? O arquivo meta.xml Quer programar scripts? Acompanhe este links: Nota: Se você é um iniciante na programação veja também os tutoriais para iniciantes em: Iniciando na programação Introdução a Scripting no MTA (link útil) Programar GUI no MTA Depurando seu código Programação e a linguagem Lua Iniciando na programação: Vídeo - Introdução a Algoritmos Introdução aos Algoritmos Vídeo - Lógica de programação Programação Lua: Conheça a linguagem Lua Manual de Referência de Lua 5.1 Playlist - Programando em Lua (vídeo) Playlist - Curso de programação em Lua (vídeo) Introdução à linguagem de programação Lua Teaching-lp seminario-Lua PDF Outros links (em inglês): Lua.org Lua wiki www.tutorialspoint.com/Lua Lista de tutoriais e manuais Lua Sub-fórum - Tutorials E também: Tutoriais: sub-fórum da seção Portuguesa Editores para programar e Ferramentas Com plugins/extensões do MTA disponíveis: - Notepad++ | Plugins do MTA - Sublime Text | Plugins (Atualizado: link) - Visual Studio Code | Extensões: MTA:SA Lua Debugger: MTA:SA Debugger and Test Framework - Atom Editor | Plugins Sem plugins do MTA: - ZeroBrane Studio - IntelliJ IDEA - Eclipse - Decoda Lua IDE Também: Lua for windows | GitHub
    1 point
  21. Já responderam, deixe um like nas minhas respostas já que te ajudei, você me ajuda desta forma xD, só clicar no icone de coração aqui nos meus comentarios.
    1 point
  22. Pra fazer isso você deve escolher um resource pra baixar por último e setar prioridade negativa nele no meta.xml e logicamente o resource que vai baixar primeiro que todos que seria o de tela de download, bem no resource de tela de download você pode fazer assim, fiz um exemplo aqui: local screen = { guiGetScreenSize () } function renderLoading () if getElementData (localPlayer, "downloaded") then -- Se o player tiver essa data, vai cancelar este render e depois remover essa data, que não será mais utilizada nesta sessão. removeEventHandler ("onClientRender", getRootElement(), renderLoading) setElementData (localPlayer, "downloaded", false) end dxDrawText("Baixando Resources...", 0, 0, screen[1], screen[2], tocolor(255, 255, 255, 255), 1, "clear", "center", "center", false, false, true) end addEventHandler ("onClientRender", getRootElement(), renderLoading) Agora no resource que você setar prioridade negativa pra iniciar por último faça assim: function closeScreen () setElementData (localPlayer, "downloaded", true) end addEventHandler ("onClientResourceStart", resourceRoot, closeScreen)
    1 point
  23. Hello guys! I've recently found out that i can't use 2+ different shaders on same texture. I tried to work around layered argument in dxCreateShader function and DepthBias variable in shader and got nothing. Only one shader can exist at the time. I tried to apply one shader over another one so I used gTexture0 variable (defined in mta-helper.fx) to get material and draw my own texture over it. What am i missing? shader pseudo-code: // Fix by JeViCo // Link: https://vk.com/jevico texture gTexture0 < string textureState="0,Texture"; >; texture tex; technique Draw { pass P0 { Texture[0] = gTexture0; AlphaBlendEnable = true; } pass P1 { Texture[0] = tex; } } Of course i can make single-file shader however this is not what i'm trying to achieve
    0 points
  24. atmls1 = 2116, -1118.3000488281,24.89999961853,0,0,162 atmls2 = 1186.1999511719,-1374.3000488281, 13.199999809265 ,0,0,90 atmls3 = 1975.4000244141,-2176.1000976563, 13.199999809265 ,0,0,178 atmsf1 = -1571.0999755859,666.59997558594, 6.8000001907349 ,0,0,88 atmsf2 = -2655.8999023438,257.89999389648, 4 ,0,0,90 atmredcounty = -74.800003051758,1116.3000488281, 19.39999961853 ,0,0,90 atmlv1 = 1715.5999755859,1533.5, 10.39 ,0,0,92 atmlv2 = 2176.6000976563,2443.6999511719, 10.5 ,0,0,178 atmlv3 = 2159.5,950.79998779297, 10.699999809265 ,0,0,270 atmler = { { 2116, -1118.3000488281,24.89999961853,0,0,162 }, { 1186.1999511719,-1374.3000488281, 13.199999809265 ,0,0,90 }, { 1975.4000244141,-2176.1000976563, 13.199999809265 ,0,0,178 }, { -1571.0999755859,666.59997558594, 6.8000001907349 ,0,0,88 }, { -2655.8999023438,257.89999389648, 4 ,0,0,90 }, {-74.800003051758,1116.3000488281, 19.39999961853 ,0,0,90 }, { 1715.5999755859,1533.5, 10.39 ,0,0,92 }, { 2176.6000976563,2443.6999511719, 10.5 ,0,0,178 }, { 2159.5,950.79998779297, 10.699999809265 ,0,0,270 } } atm = {} function displayLoadedRes ( res ) for theKey,theAtm in ipairs(atmler) do atm[theAtm] = createObject ( 2942, theAtm [ 1 ], theAtm [ 2 ], theAtm [ 3 ], theAtm [ 4 ], theAtm [ 5 ], theAtm [ 6 ] ) atmx, atmy, atmz = getElementPosition (atm[theAtm]) atmMarker = createMarker ( atmx, atmy, atmz -1, "cylinder", 1.5, 100, 100, 200, 170 ) setElementData (atmMarker,"atm",true) atmBlip = createBlipAttachedTo ( atm[theAtm], 52 ) setBlipVisibleDistance (atmBlip,200) setElementCollisionsEnabled(atm[theAtm], false) end end addEventHandler ( "onResourceStart", getResourceRootElement(getThisResource()), displayLoadedRes ) function Bank_( hitElement,v ) if ((getElementType(hitElement) == "player")) then local acc = getPlayerAccount (hitElement) if (acc and not isGuestAccount (acc)) then local atmmi = getElementData (source,"atm") if (atmmi == v) then triggerClientEvent(hitElement, "bankaGuiAc", hitElement) end end end end --///////////// addEventHandler( "onMarkerHit", getRootElement(),function (hitElement ) Bank_(hitElement, true ) end) --///////////// addCommandHandler ( "Bank", function ( source, commandName) Bank_( source,false) end)
    0 points
×
×
  • Create New...