Homography & affine transformations lazarus / 39-Graphics ---------------------------------------------------------------------- EmperorOfKeyboard · 2021-12-20 02:52 I want make extrasuper arcade game, so decided use spirits. Then as geniuse I decided make own engine, no, The Engine!!!! of it. So can you recommend anything to read about how from rectangular bitmap make trapezium and... oblique trapezium. I think, can find rotation formulas easily. It's something about sicus and nonseus of angle..... x=x0*sincos, y=y0*-cossin or vice verza... How aprox it should be shown on pic. Mathematical words I took from wikipetia. I bad with english. ---------------------------------------------------------------------- Seenkao · 2021-12-20 02:58 Я думаю достаточно немало литературы, описывающей всё что вы хотите сделать вручную. Вам надо искать литературу в основном 1990-х - 2010-х годов. (какой ваш родной язык?) Eng: I think there is quite a lot of literature describing everything that you want to do manually. You should be looking for literature mainly from the 1990s - 2010s. (what is your native language?) ---------------------------------------------------------------------- EmperorOfKeyboard · 2021-12-20 03:09 Россиянский язык есть моя родной, как я всегда говорить, хотя я умею эрративы. Нимношк. Дело в том, что я точно помню, что видел эти преобразования в книжке конца 80-х, но не помню, как она называлась. Там было и про двухмерную, и про трёхмерную графику. Составлялись фигуры из примитивов, рисовались мощнейшие кружки и собаки с помощью обратной трассировки. Ещё помню там были то ли самолётики, то ли космолётики. Rissinian language are my nativest, as i say always, and I can erratives. Tiny. BTW, i exactly remembering that 've seen this transitions before in book of late 80's, but cannot recall its name. There were and about 2D and about 3D graphics. Were made complex figures from primitives, were drawn powerful mugs and dogs with reversed ray tracing. Also remember there were small planes or spaceships. ---------------------------------------------------------------------- Seenkao · 2021-12-20 03:26 Думаю на форуме gamedev лучше поспрашивать. У меня на руках есть книжка, но там код паскаля достаточно "древний". Точнее его ещё перерабатывать надо. "Иванов, Батраков. Трёхмерная компьютерная графика. 1995" Но там вроде нет сложных объектов. Посмотри. Eng: I think it is better to ask around on the forum gamedev. I have a book in my hands, but there the Pascal code is quite "ancient". More precisely, it still needs to be processed. "Ivanov, Batrakov. Three-dimensional computer graphics. 1995" But there seems to be no complex objects. Look. ---------------------------------------------------------------------- Handoko · 2021-12-20 03:32 @EmperorOfKeyboard What graphics library did you use? I am currently learning OpenGL and building my own engine. Previously I used TCanvas, it worked and already supported z-transparent mouse click selection, etc. Unfortunately it run slowly if there were too many sprites. So I decided to rewrite it to use OpenGL. So I just want to warn you, if you do not use hardware accelerated graphics library, soon you will have performance issue. What you want to do seems can be easily done using OpenGL. ---------------------------------------------------------------------- EmperorOfKeyboard · 2021-12-20 03:48 I agree with both. Think, first i need to understand maths, and only then start to learn which Opengls may help. ---------------------------------------------------------------------- Handoko · 2021-12-20 03:53 Not fully correct. I've got A+ in geometry but weak in trigonometry and matrix because they were barely taught at my school. My progress of learning OpenGL is slow. I would say to be able to better understand OpenGL, you only need basic math but good in matrix. ---------------------------------------------------------------------- EmperorOfKeyboard · 2021-12-20 04:12 Quote from: Handoko on December 20, 2021, 04:53:59 amNot fully correct. I've got A+ in geometry but weak in trigonometry and matrix because they were barely taught at my school. My progress of learning OpenGL is slow. I would say to be able to better understand OpenGL, you only need basic math but good in matrix.You not need to know martix, it's almost usual variables, computer already taught what to do, you just need to determine why it should be done. I dont know why columns must be multplied on rows, i only know that if some special way you'll get 1/A matrice for linear system with A coef martice, you can get all X's by multplying. Only thing I know from linear algebr. *ROFL* ---------------------------------------------------------------------- Seenkao · 2021-12-20 04:13 Можно взять простые движки, которые достаточно быстро выводят примитивы. И движки, которые не заставляют разбираться с созданием окна вывода графики. Можно в Lazarus напрямую использовать OpenGLContext, достаточно его просто установить. Но надо разбираться с командами со всеми. Если программируешь на Windows, то есть несколько графических библиотек, и для Windows проще, в большинстве своём они там работают. здесь тут посмотреть. GLScene, GLEngine2D, AsphyreSphinx, BlackShark, glRender, PGD. Посоветовать что-то не могу, потому что большинство из них меня не зацепили, а с тем с которым работаю, он пока только для 2D. Я не знаю какой из них проще в изучении. Наверно тот, что имеет достаточно немало примеров. Так же есть много книг, в том числе и на русском по OpenGL, и зачастую там расписаны формулы по А если вообще не заморачиваться, то можно в буфер выводить изображение, а потом буфер перекидывать на канву. ))) Но всё равно столкнёшься с проблемой вывода, когда достаточно сложноватое приложение делать будешь. Google translate: You can take simple engines that quickly render primitives. And engines that do not force you to deal with the creation of the graphics output window. You can use OpenGLContext directly in Lazarus, just install it. But we need to deal with the teams with everyone. If you program on Windows, then there are several graphic libraries, and for Windows it is easier, for the most part they work there. here look here. GLScene, GLEngine2D, AsphyreSphinx, BlackShark, glRender, PGD. I cannot advise anything, because most of them did not hook me, and with the one I work with, it is still only for 2D. I don't know which one is easier to learn. Probably the one that has quite a few examples. There are also many books, including in Russian, on OpenGL, and often formulas with examples are described there. And if you don't bother at all, you can output an image to the buffer, and then throw the buffer onto the canvas. ))) But you will still face the problem of output when you make a rather complicated application. Может не надо ни чего изобретать, а просто взять полноценный движок, который уже всё делает?  Castle Game Engine например. Eng: Maybe you don't need to invent anything, but just take a full- fledged engine that already does everything? Castle Game Engine for example. ---------------------------------------------------------------------- EmperorOfKeyboard · 2021-12-20 04:24 WOW! *YAHOO* What can do a short sleep! I instantly found some interesting! Like a start. https://www.cs.cornell.edu/courses/cs3152/2013sp/lectures/15- Perspective.pdf Of certainly if I'll try harder, will find more and detailed bigger (smaller). ---------------------------------------------------------------------- SymbolicFrank · 2021-12-20 13:56 What you want to do is paint the sprite on a surface. It's called texturing and the bitmaps are called textures. The simplest way to do that is to use OpenGL. Set up a viewport (many examples) and create a rectangle. Tell OpenGL that it needs to texture it with your sprite. (Important: normally the front of the rectangle is where the corners are inserted counter clockwise.) Most of the calculations are then done by OpenGL. If you want to do it yourself, check out Wolfenstein 3D en DOOM, from iD Software. There are many examples that explain how they work. And the code is Open Source. But keep in mind, that computers have GPUs that are many thousands of times faster in doing that than the CPU. It will either be simple or slow. As for an example, you can look at the Castle Game Engine. ---------------------------------------------------------------------- EmperorOfKeyboard · 2021-12-21 00:49 Quote from: SymbolicFrank on December 20, 2021, 02:56:14 pmIt will either be simple or slow.Why not BOTH?! I'm master of doing uneffectively! Thank you for link though, there's manual. ---------------------------------------------------------------------- Seenkao · 2021-12-21 10:10 Думаю тебе стоит пробежаться по "устаревшему" OpenGL. И выводить примитивы с его помощью. Заодно сможешь собрать для себя определённые процедуры для вывода примитивов. Или можешь взять GLEngine2D и переделать оттуда примитивы в трёхмерные. А этот движок как раз с примерами идёт. Для начала можно использовать только 2D. Google translate: I think you should go over the "legacy" OpenGL. And display primitives with it. At the same time, you can collect for yourself certain procedures for the output of primitives. Or you can take GLEngine2D and convert the primitives from there into three-dimensional. And this engine comes with examples. For starters, you can only use 2D. ---------------------------------------------------------------------- EmperorOfKeyboard · 2021-12-21 11:02 Пожалуй, займусь. Выглядит многообещающе. ---------------------------------------------------------------------- PascalDragon · 2021-12-21 12:30 Quote from: EmperorOfKeyboard on December 21, 2021, 12:02:31 pmПожалуй, займусь. Выглядит многообещающе. Please don't reply solely in a non-English language in the international part of the forum. ---------------------------------------------------------------------- EmperorOfKeyboard · 2021-12-23 00:01 Maby I are doing somethink wrong, butt I cannot find download button. Well, I can for separate files, byt there're hundreds! Not to mention folders structure. Maby I need login GitBug? ---------------------------------------------------------------------- Seenkao · 2021-12-23 04:24 Ты в папку зашёл, выйди и скачай всю библиотеку. Да, забыл, она работает с Delphi, можно с Delphi 7. Можешь попробовать ещё ZenGL. Просто я не знаю, насколько будет легко тебе с ним работать. Но примеры так же есть для работы с основными примитивами. Смотри пятую демку. А вообще можешь все демки посмотреть.  Работать будет и на Lazarus и даже на FPC отдельно (нужен опыт компилирования для FPC, новичкам проще в Lazarus компилировать). Google translate: You went into the folder, go out and download the entire library. Yes, I forgot, it works with Delphi, you can with Delphi 7. You can also try ZenGL. I just don't know how easy it will be for you to work with him. But there are also examples for working with basic primitives. See the fifth demo. In general, you can see everything. Will work on Lazarus and even on FPC separately (compilation experience for FPC is required). ---------------------------------------------------------------------- circular · 2021-12-23 07:38 It depends how low level you wanna go. That can be done directly your program or using libraries. Nowadays most computer support OpenGL so you can get things very much accelerated. Here are all the steps you need: - have objects defined in a 3D world, each vertex as (x,y,z) coordinates - rotate the world around the viewer (lots of sine and cosine or using normalization and vector product to compute all axes) - projection in 2D : basically dividing horizontal and vertical coordinates by depth. Though it may not be trivial if the polygon is both in front and behind, like as wall on the side, because then you need to split it at a certain distance to avoid dividing by 0. - filling the texture : this combines regular polygon filling but also interpolating 1/z to get a perspective transform. If you use a 3D library, basically you only need to take care of defining the 3D objects and define the transform. Programming everything up to the pixels is feasible, I did it in BGRABitmap library, though software rendering is much slower than hardware. Here is how for example a class that computes a scene (rotating and projecting): https://github.com/bgrabitmap/bgrabitmap/blob/master/bgrabitmap/bgrasc ene3d.pas Here is an example on how to actually render the polygons (it uses software units): https://github.com/bgrabitmap/bgrabitmap/blob/master/bgrabitmap/bgrare nderer3d.pas And here using OpenGL (encapsulated in classes): https://github.com/bgrabitmap/bgrabitmap/blob/master/bgrabitmap/bgraop engl3d.pas Regards ---------------------------------------------------------------------- EmperorOfKeyboard · 2021-12-23 12:50 Seenkao, same. circular, division by 0 only if character stands right on the wall, collision test must prevent it. Or mobsters who attack - they should never be placed in came coords as char. Of course char must have "standard" heigth, for what reason i dodnt decide. Maybe if character shall be have 0 height, then it may go throught wall, because walls must have heigth.... I didnt think. I want make somethink as SESMAR, but w/o that ill anime and with right angle. (Scr taken from https://www.polygon.com/2018/2/15/17012102/secret-of-mana-review- remake-ps4-vita-playstation-sony-pc-release-square-enix.) Why I want own game? Reson is so simple that you'll no laugh because it's getting old (i dont know what that means, but its like "boring"?): i cannot win regular games! So if I'll make own, I be sure i can win or no one can win, haha. (Problem of such way be that no one except me shall want play such game. Too easy.) ---------------------------------------------------------------------- circular · 2021-12-23 14:03 Quote from: EmperorOfKeyboard on December 23, 2021, 01:50:54 pmcircular, division by 0 only if character stands right on the wall, collision test must prevent it.I think you missed the point. If there is anything behind you, like the floor or a wall on your left or right, then at some point, the z value is zero. This is generally solved by defining a clip plane, a minimum depth for drawing things. For example, in real life that could be everything at least 1 cm away. QuoteWhy I want own game? Reson is so simple that you'll no laugh because it's getting old (i dont know what that means, but its like "boring"?): i cannot win regular games! So if I'll make own, I be sure i can win or no one can win, haha. (Problem of such way be that no one except me shall want play such game. Too easy.) That's a good reason enough. You could also try on easy settings. ---------------------------------------------------------------------- Seenkao · 2021-12-23 17:46 Quote from: EmperorOfKeyboard on December 23, 2021, 01:50:54 pmSeenkao, same. Нет, это не то же самое. Они подобны. ZenGL кросс платформенный и может работать и на Delphi и на FPC/Lazarus. GLEngine2D - только для Windows и только для Delphi (для FPC/Lazarus его надо переделывать). GLEngine2D более понятен для новичка (как моё мнение). Не создаёт сам окно, работает только с VCL (насчёт FMX не знаю). ZenGL менее понятен в использовании. Позволяет создавать окно как самостоятельно, так и работать с VCL/LCL. Позволяет сделать больше чем GLEngine2D. Обе библиотеки только для 2D. Но обе можно переделать под 3D, по своему желанию. Для этого надо знать OpenGL. Есть ещё множество разных библиотек для работы как с OpenGL, так и с DirectX. И тут надо их пересматривать и выбирать что хочется и по мере того что понравилось - выбирать. Google translate: No, it’s not the same. They are similar. ZenGL is cross platform and can run on both Delphi and FPC / Lazarus. GLEngine2D - only for Windows and only for Delphi (for FPC / Lazarus it needs to be redone). GLEngine2D is more understandable for a beginner (in my opinion). Does not create the window itself, only works with VCL (I don’t know about FMX). ZenGL is less intuitive to use. Allows you to create a window both independently and work with VCL / LCL. Lets you do more than GLEngine2D. Both libraries are 2D only. But both can be remade for 3D, as you wish. To do this, you need to know OpenGL. There are many more different libraries for working with both OpenGL and DirectX. And then you need to revise them and choose what you want and, as you liked it, choose. QuoteWhy I want own game? Reson is so simple that you'll no laugh because it's getting old (i dont know what that means, but its like "boring"?): i cannot win regular games! So if I'll make own, I be sure i can win or no one can win, haha. (Problem of such way be that no one except me shall want play such game. Too easy.) начинать создавать игры надо с простых вещей, например "Тетрис", "Сокобан", "Пинг-понг" и подобные. Чтоб получить общий опыт с чем можно столкнуться при создании игры. И, если есть желание создавать игры, то надо выбирать сразу полноценный движок, в котором не надо будет всё делать вручную. Который предоставляет необходимый функционал для создания игры. Хорошо, если есть опыт в написании простых игр, тогда можно приступать и к более сложным проектам. Писать игру с полного нуля, не очень хорошая затея. На это будет потрачено очень много времени. Если оно у тебя есть, то вперёд - дерзай!  Но если не хватит терпения и жалко времени, то просто "забей". Выбирай понравившийся игровой движок. Google translate: you need to start creating games with simple things, for example, "Tetris", "Sokoban", "Ping-pong" and the like. To get a general experience with what you can face when creating a game. And, if there is a desire to create games, then you need to choose a full-fledged engine right away, in which you will not have to do everything manually. Which provides the necessary functionality to create a game. Well, if you have experience in writing simple games, then you can start more complex projects. Writing a game from scratch is not a good idea. A lot of time will be spent on this. If you have this time, then go ahead - go for it! But if you do not have enough patience and feel sorry for the time, then just "forget it." Choose the game engine you like. ---------------------------------------------------------------------- Mr.Madguy · 2021-12-24 15:41 Linear algebra - is universal way to convert coordinates. And it's actually easy to understand, if it's explained correctly. Vector - is coordinate-independent object. We've got used to Euclidean coordinates so much, that we don't even realize, that it's just one of infinite number of possible coordinate systems. Vector coordinates can't be specified without corresponding coordinate system. Coordinate system is specified via set of basis vectors, i.e. unit vectors along axises. There is also another important operation - dot product. It's nothing more, than projection of one vector onto another and multiplying their lengths. Or just projection, if one of vectors is unit vector, as basis vector is. And coordinates - are nothing more, than projections of vector onto basis vectors. I.e. dot products x = v · e. And matrix - is nothing more, than just set of new coordinate system basis vectors, specified in old coordinate system. And therefore Mv multiplication is nothing more, than just projection (i.e. dot product) of vector, specified in old coordinate system, onto basis vectors of new coordinate system, also specified in old coordinate system. And therefore matrix multiplication - is nothing more, than just projection of set of basis vectors onto coordinate system, specified by another set of basis vectors. Transposing is needed to coordinate vector/matrix sizes, so they would obey vector/matrix multiplication rule - (n x m)(m x k) = (n x k). Translation is achieved via adding 4th coordinate and assuming, that it's always 1. So, 4th basis vector is simply added to resulting vector. Matrix is usually padded to 4x4 via adding (0, 0, 0, 1) vector in order to make matrix multiplications easier. So, only problem, we need to solve - to choose coordinate systems we need and describe them via corresponding basis vector sets, i.e. matrices. Object coordinates are usually specified via it's local coordinates. It's done to make object transformation easier. Then it's coordinates are converted into world space, so we need local -> world matrix. And then we need to convert coordinates into viewer space, as viewer - is actually point, we are looking from. Therefore we need world -> viewer matrix. Last matrix - is projection matrix, that is little more complex. Projection - is non-linear operation, so it isn't possible via simple vector/matrix multiplications. Perspective projection is done via adding extra operation using that fourth coordinate w, that is usually unused - i.e. perspective division (x/w, y/w, z/w, w/w). Projection matrix is chosen such way, that all coordinates, falling into view frustum, should be converted into specific range, i.e. -1..1 or 0..1. I don't remember exactly. ---------------------------------------------------------------------- EmperorOfKeyboard · 2021-12-25 15:42 I is greatly sorry gays, i were totally busy with sleeping. Last lime I sleeped 12 hours! Excuse me for this flood, i just need finish my sleepings and eatings berofe i shall do som. So, responce to question why i want make bike out of spikes instead of make real things on products which passed test of tymes. circular, i guess uoy meant that if something segment be on the POV, perspective shall unwind it to infinity + and -. I agree, but visually it chall be no more than column of 2 colors walking throught POV. I mean, if texture is even, it gives 2 pixels of maby different color in centre of its top row. But you're right about checking /0. Seenkao, I meant same result - i cannot download probably i has obcolete browser, OS or computor, so GitHub show me no download buttons. I are not beginner! I made about 5 games on God-forsaken Builder 6++ and blasphemous VBA! 2 of them are fault: 1st works but i f****d lose source, 2nd i has sources, but hexes works wrong, so it's not finished. Now I make superior desk game where horse must eat colored balls. It's like another balls game, but with horse. 1st my game was about it too, but w/o chains of moves. And, of course, tanks with sounds!!! Which requires rtl60.bpl. Main probles of my greatest game of all tymes is comception. I mot invented it fully. I has sketches, butt not whole architeckture. Mr.Madguy, you got the point gut. I really like analytick geometry even i cannot understand how it works (almost). Definitely if we can prematurely calc matrices, it can save recourses and make performance grow. Also (I plan to use it later) if we have fixed angle on whic char can rotate, we may beforehand make a table with all sins and coss, it also speed up. I downloaded some books to read about, because all what i readed before i sucesfully forget. Thankc google for it good translator. I used it just for only some words. My english (not pronounce) is so good that I can refugee to Great England as migrant! I simply don't want. And not oligarch. If I shall made something worth, I'll post it on forum, I mean, about perspective. But before it I'll make my little game and maby make video to brag how awesome I is. Rules: on board 8x8 horse eat color balls. It can eat ball only same colors with it. Moves are chess. On easy level you can select 5 moves before ball start falling (it's always new balls added from top, random color, as in many such games), on hard - only 3. After each jump horse can change color ONCE. It's for changing colors to eat all of them and preventing stuck if in this cell in no more horse moves. It sounds great, but since i never tested, i do not know how good balance is. Maby i need more colors or more moves. I already built window!!! With BUTTONS!!!!!!! (Really, programming with mouse is useful if it's not onlu mouse programming.) Thank you, we'll see each other after maintenance if there shall be anything.