intro.bbdoc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. BlitzMax provides a set of vector structs for working with 2D, 3D, and 4D coordinates. These
  2. structs come in three variations for each dimension: #Double ( #SVec2D, #SVec3D, #SVec4D),
  3. #Float ( #SVec2F, #SVec3F, #SVec4F), and #Int ( #SVec2I, #SVec3I, #SVec4I).
  4. The choice of struct depends on the precision and coordinate system you require for your application.
  5. Vectors are used to represent positions, directions, and magnitudes in coordinate systems.
  6. ## 2D Vectors
  7. 2D vectors are represented by the #SVec2D, #SVec2F, and #SVec2I structs, each catering to
  8. different data types: #Double, #Float, and #Int, respectively. These structs consist of two
  9. components, x and y, which correspond to the horizontal and vertical coordinates in a 2D space.
  10. They are commonly used in 2D games, graphical applications, and geometric calculations.
  11. ### 2D Games
  12. In 2D games, vectors play an essential role in various aspects of game development,
  13. providing a powerful and efficient way to handle mathematical operations related to game
  14. objects such as characters, projectiles, and other interactive elements.
  15. **Positions** : Vectors are used to represent the position of game objects in a 2D space.
  16. The x and y components of the vector store the object's coordinates, which define its location
  17. on the screen. By manipulating these coordinates, game objects can be moved, placed, or
  18. arranged in relation to other objects and the game environment.
  19. In this example, the playerPos and targetPos are 2D vectors ( #SVec2F) representing the positions of
  20. the player object and the target object. The player object is moved by manipulating the x and y
  21. components of the playerPos vector based on the arrow keys pressed. We also check if the player
  22. object has reached the target object by calculating the distance between their positions using the
  23. #DistanceTo method. If the player reaches the target, the target object is moved to a new random position
  24. on the screen.
  25. ```blitzmax
  26. SuperStrict
  27. Framework sdl.sdlrendermax2d
  28. Import brl.random
  29. Graphics 800, 600, 0
  30. Local playerPos:SVec2F = New SVec2F(400, 300)
  31. Local targetPos:SVec2F = New SVec2F(Rand(50, 750), Rand(50, 550))
  32. While Not KeyHit(KEY_ESCAPE)
  33. Cls
  34. Local x:Float = playerPos.x
  35. Local y:Float = playerPos.y
  36. ' Update player position using arrow keys
  37. If KeyDown(KEY_LEFT) Then x :- 5
  38. If KeyDown(KEY_RIGHT) Then x :+ 5
  39. If KeyDown(KEY_UP) Then y :- 5
  40. If KeyDown(KEY_DOWN) Then y :+ 5
  41. ' Set playerPos with updated coordinates.
  42. playerPos = New SVec2F(x, y)
  43. ' Draw player
  44. SetColor 0, 255, 0
  45. DrawOval(playerPos.x - 10, playerPos.y - 10, 20, 20)
  46. ' Draw target
  47. SetColor 255, 0, 0
  48. DrawOval(targetPos.x - 5, targetPos.y - 5, 10, 10)
  49. ' Check if player reached the target
  50. If playerPos.DistanceTo(targetPos) < 15
  51. ' Move target to a new random position
  52. targetPos = New SVec2F(Rand(50, 750), Rand(50, 550))
  53. EndIf
  54. Flip
  55. Wend
  56. ```
  57. **Velocities and Accelerations** : Vectors can represent not only positions but also
  58. velocities and accelerations. In this context, the x and y components of the vector
  59. indicate the rate of change of an object's position or velocity, respectively. By adding
  60. velocity vectors to position vectors, game developers can create smooth and realistic motion
  61. for characters and other moving objects. Similarly, acceleration vectors can be used to simulate
  62. the effects of gravity, friction, and other forces on the motion of game objects.
  63. In this example, the `ballPos`, `ballVel`, and ballAcc are 2D vectors ( #SVec2F) representing the ball's position,
  64. velocity, and acceleration. We update the ball's position and velocity based on the acceleration
  65. (gravity) and time elapsed (`deltaTime`). When the ball hits the floor, we reverse its vertical
  66. velocity and apply a bounce coefficient to simulate the loss of energy during the bounce.
  67. ```blitzmax
  68. SuperStrict
  69. Framework SDL.SDLRenderMax2D
  70. Graphics 800, 600, 0
  71. Local ballPos:SVec2F = New SVec2F(400, 100)
  72. Local ballVel:SVec2F = New SVec2F(0, 0)
  73. Local ballAcc:SVec2F = New SVec2F(0, 9.81) ' Gravity
  74. Local ballRadius:Float = 20
  75. Local floorY:Float = 550
  76. Local deltaTime:Float = 1.0 / 60.0
  77. Local bounceCoefficient:Float = 0.8
  78. While Not KeyHit(KEY_ESCAPE)
  79. Cls
  80. ' Update ball velocity and position using acceleration and deltaTime
  81. ballVel = ballVel + (ballAcc * deltaTime)
  82. ballPos = ballPos + (ballVel * deltaTime)
  83. ' Bounce the ball off the floor
  84. If ballPos.y + ballRadius > floorY And ballVel.y > 0
  85. ballVel = New SVec2F(ballVel.x, -ballVel.y * bounceCoefficient)
  86. ballPos = New SVec2F(ballPos.x, floorY - ballRadius)
  87. EndIf
  88. ' Draw ball
  89. SetColor 0, 255, 0
  90. DrawOval(ballPos.x - ballRadius, ballPos.y - ballRadius, ballRadius * 2, ballRadius * 2)
  91. ' Draw floor
  92. SetColor 255, 255, 255
  93. DrawLine(0, floorY, 800, floorY)
  94. Flip
  95. Wend
  96. ```
  97. **Collision Detection and Resolution** : Vectors are crucial in detecting and resolving collisions
  98. between game objects. By comparing the positions and sizes of objects, developers can identify when
  99. two objects are overlapping or in close proximity, triggering a collision event. Vectors can also
  100. be used to calculate the response of objects upon collision, such as bouncing, sliding, or sticking
  101. together. This is achieved by reflecting or altering the velocity vectors of the colliding objects
  102. based on their properties, such as mass, elasticity, and friction.
  103. **Distances and Angles** : Vectors can be used to calculate distances and angles between objects,
  104. which is useful for various game mechanics, such as determining the line of sight for a character
  105. or measuring the range of a weapon. By subtracting the position vectors of two objects, developers
  106. can find the vector connecting them and calculate its length to obtain the distance between them.
  107. Additionally, the dot product and other vector operations can be used to determine the angle between
  108. two vectors, which is helpful for calculating relative orientations or aiming projectiles.
  109. In this example, the `characterPos` and `targetPos` are 2D vectors ( #SVec2F) representing the
  110. character's and target's positions. We calculate the connecting vector by subtracting the
  111. character's position from the target's position. We then use the `Length()` method to find the
  112. distance between them and the #ATan2() function to calculate the angle. The distance and angle
  113. are displayed on the screen.
  114. ```blitzmax
  115. SuperStrict
  116. Framework SDL.SDLRenderMax2D
  117. Import BRL.Math
  118. Graphics 800, 600, 0
  119. Local characterPos:SVec2F = New SVec2F(100, 300)
  120. Local targetPos:SVec2F = New SVec2F(700, 400)
  121. Local distance:Float
  122. Local angle:Float
  123. While Not KeyHit(KEY_ESCAPE)
  124. Cls
  125. ' Calculate the vector connecting the character and the target
  126. Local connectingVector:SVec2F = targetPos - characterPos
  127. ' Calculate the distance between the character and the target
  128. distance = connectingVector.Length()
  129. ' Calculate the angle between the character and the target
  130. angle = ATan2(connectingVector.y, connectingVector.x)
  131. ' Draw character
  132. SetColor 255, 0, 0
  133. DrawOval(characterPos.x - 10, characterPos.y - 10, 20, 20)
  134. ' Draw target
  135. SetColor 0, 255, 0
  136. DrawOval(targetPos.x - 10, targetPos.y - 10, 20, 20)
  137. ' Draw aiming line
  138. SetColor 255, 255, 255
  139. DrawLine(characterPos.x, characterPos.y, targetPos.x, targetPos.y)
  140. ' Display distance and angle
  141. SetColor 255, 255, 255
  142. DrawText("Distance: " + distance, 10, 10)
  143. DrawText("Angle: " + angle, 10, 30)
  144. Flip
  145. Wend
  146. ```
  147. In summary, 2D vectors are indispensable tools in game development, providing an efficient and
  148. flexible way to handle a wide range of mathematical operations related to game objects and their
  149. interactions within the game world.
  150. ### Graphical Applications
  151. In graphical applications, 2D vectors play a vital role in representing and manipulating various
  152. elements in a coordinate system. They enable developers to perform operations such as translation,
  153. rotation, and scaling, which are essential for rendering and adjusting graphics on the screen.
  154. **Points** : 2D vectors are used to represent points in a coordinate system, where the x and y
  155. components store the horizontal and vertical coordinates, respectively. Points are fundamental
  156. building blocks in graphical applications, as they define the vertices of lines, polygons, and other shapes.
  157. **Lines and Shapes** : By connecting points using vectors, developers can create lines, curves,
  158. and shapes in a graphical application. Vectors are used to store the vertices of these shapes
  159. and calculate properties such as their lengths, areas, and perimeters. Additionally, vector operations
  160. can be applied to determine intersections, containments, and other spatial relationships between different shapes.
  161. In this example, we define a function `CalculateLineLength` that takes two 2D points ( #SVec2D) as
  162. input, representing the start and end points of a line segment. The function calculates the
  163. connecting vector between the two points and returns its length.
  164. ```blitzmax
  165. SuperStrict
  166. Framework BRL.StandardIO
  167. Import BRL.Vector
  168. Local startPoint:SVec2D = New SVec2D(100, 300)
  169. Local endPoint:SVec2D = New SVec2D(700, 400)
  170. Local lineLength:Double = CalculateLineLength(startPoint, endPoint)
  171. Print "Line length: " + lineLength
  172. Function CalculateLineLength:Double(p1:SVec2D, p2:SVec2D)
  173. Local connectingVector:SVec2D = p2 - p1
  174. Return connectingVector.Length()
  175. End Function
  176. ```
  177. **Translation** : Translation is the process of moving a shape or a group of shapes from one location
  178. to another within the coordinate system. By adding a translation vector to the position vectors of
  179. the shape's vertices, developers can shift the shape by a specified amount in both horizontal and
  180. vertical directions. This operation is essential for animating objects, panning scenes, or aligning
  181. graphical elements.
  182. **Rotation** : Rotation is the process of rotating a shape or a group of shapes around a specific
  183. point in the coordinate system. By applying a rotation matrix, which can be derived from trigonometric
  184. functions or complex numbers, to the position vectors of the shape's vertices, developers can rotate
  185. the shape by a given angle. This operation is useful for creating effects such as spinning objects,
  186. rotating scenes, or adjusting the orientation of graphical elements.
  187. **Scaling** : Scaling is the process of resizing a shape or a group of shapes by a specified factor in
  188. the coordinate system. By multiplying the position vectors of the shape's vertices by a scaling vector,
  189. developers can uniformly or non-uniformly scale the shape in horizontal and vertical directions. This
  190. operation is crucial for zooming in and out, resizing objects, or adapting graphical elements to different
  191. screen resolutions or aspect ratios.
  192. In conclusion, 2D vectors are essential in graphical applications, providing a robust and efficient way
  193. to represent and manipulate various elements within a coordinate system. They enable developers to perform
  194. operations such as translation, rotation, and scaling, which are crucial for rendering and adjusting
  195. graphics on the screen.
  196. ### Geometric Calculations
  197. Geometric calculations play an essential role in numerous fields, including computer graphics, physics
  198. simulations, and engineering applications. 2D vectors are invaluable tools for solving problems related
  199. to distances, intersections, and areas of shapes, as well as performing linear algebra operations like
  200. dot products and matrix multiplications.
  201. **Distances** : Calculating distances between points, lines, and shapes is a common task in geometry.
  202. Using 2D vectors, developers can determine the distance between two points by finding the length of the
  203. vector representing the difference between their position vectors. Distances from points to lines or other
  204. shapes can also be computed using vector operations, such as projections and dot products.
  205. **Intersections** : Detecting intersections between lines, rays, and shapes is essential for various
  206. applications, including collision detection in games and ray tracing in computer graphics. Using 2D vectors,
  207. developers can apply algebraic and geometric techniques to determine if and where two elements intersect.
  208. For example, the intersection point of two lines can be found by solving a system of linear equations formed
  209. by their parametric equations, which are derived from their direction vectors.
  210. In this example, we define a `TLine` type that stores the start and end points of a line segment.
  211. The function `CalculateIntersection` takes two TLine objects as input and calculates their intersection
  212. point, if it exists. If the lines are parallel, the function returns #False.
  213. ```blitzmax
  214. SuperStrict
  215. Framework BRL.StandardIO
  216. Import BRL.Vector
  217. Local line1:TLine = New TLine(New SVec2D(100, 100), New SVec2D(700, 400))
  218. Local line2:TLine = New TLine(New SVec2D(400, 100), New SVec2D(200, 600))
  219. Local intersection:SVec2D
  220. Local result:Int = CalculateIntersection(line1, line2, intersection)
  221. If result Then
  222. Print "Intersection point: " + intersection.ToString()
  223. Else
  224. Print "Lines are parallel, no intersection"
  225. End If
  226. Type TLine
  227. Field startPoint:SVec2D
  228. Field endPoint:SVec2D
  229. Method New(startPoint:SVec2D, endPoint:SVec2D)
  230. self.startPoint = startPoint
  231. self.endPoint = endPoint
  232. End Method
  233. End Type
  234. Function CalculateIntersection:Int(line1:TLine, line2:TLine, intersection:SVec2D Var)
  235. Local v1:SVec2D = line1.endPoint - line1.startPoint
  236. Local v2:SVec2D = line2.endPoint - line2.startPoint
  237. Local crossProduct:Double = v1.x * v2.y - v1.y * v2.x
  238. If Abs(crossProduct) < 0.000001 Then
  239. Return False ' Lines are parallel
  240. End If
  241. Local t:Double = ((line1.startPoint.x - line2.startPoint.x) * v2.y - (line1.startPoint.y - line2.startPoint.y) * v2.x) / crossProduct
  242. intersection = line1.startPoint + v1 * t
  243. Return True
  244. End Function
  245. ```
  246. **Areas** : Computing the areas of shapes, such as triangles, polygons, and circles, often involves 2D
  247. vectors. For instance, the area of a triangle can be calculated using the cross product of two of its edge
  248. vectors, while the area of a polygon can be determined by summing the signed areas of its constituent
  249. triangles. Additionally, 2D vectors can be used to calculate the moments of inertia and centroids of shapes,
  250. which are essential properties in mechanics and engineering.
  251. **Dot Products** : The dot product is a fundamental operation in linear algebra that takes two vectors as
  252. input and returns a scalar value. In the context of 2D vectors, the dot product can be used to determine
  253. the angle between two vectors, project one vector onto another, or check if two vectors are perpendicular.
  254. Dot products are widely used in computer graphics for shading calculations and in physics simulations for
  255. force computations and collision responses.
  256. **Matrix Multiplications** : Matrix multiplication is another essential linear algebra operation that
  257. involves 2D vectors when dealing with transformations in a two-dimensional space. By multiplying a
  258. transformation matrix, such as a translation, rotation, or scaling matrix, with a position vector,
  259. developers can apply the corresponding transformation to a point, line, or shape in the coordinate
  260. system. Matrix multiplications are fundamental in computer graphics for rendering and animating scenes
  261. and in physics simulations for updating the positions and orientations of objects.
  262. ## 3D Vectors
  263. 3D vectors, represented by the #SVec3D, #SVec3F, and #SVec3I structs, have three components:
  264. x, y, and z, corresponding to coordinates in 3D space. They are essential in various applications,
  265. including 3D games, computer graphics, physics simulations, and engineering analyses. While some
  266. of the uses of 3D vectors overlap with those of 2D vectors, they extend to more complex scenarios
  267. and additional functionality.
  268. **3D Games and Animation** : In 3D games, vectors are crucial for defining the positions, velocities,
  269. accelerations, and orientations of game objects, such as characters, vehicles, and cameras.
  270. They also play a vital role in game mechanics like collision detection, pathfinding, and
  271. physics-based animations. In character animation, 3D vectors are used in skeleton-based systems
  272. for defining joint positions and rotations, enabling realistic and expressive movements.
  273. In this example, we define a `TGameObject` type with a position and velocity. The `Update` method is
  274. used to update the game object's position based on its velocity and a given time step (`dt`).
  275. It demonstrates moving the game object along a simple path using positions and velocities. The
  276. game object moves towards each point in the pathPoints array and switches
  277. to the next target when it gets close enough.
  278. ```blitzmax
  279. SuperStrict
  280. Framework BRL.StandardIO
  281. Import BRL.Vector
  282. Global pathPoints:SVec3D[] = [New SVec3D(0, 0, 0), New SVec3D(5, 10, 0), New SVec3D(10, 5, 0)]
  283. Global currentTargetIndex:Int = 0
  284. Local gameObject:TGameObject = New TGameObject(pathPoints[currentTargetIndex], New SVec3D(0, 0, 0))
  285. Local dt:Double = 0.5
  286. For Local i:Int = 1 To 30
  287. Local target:SVec3D = pathPoints[currentTargetIndex]
  288. Local direction:SVec3D = (target - gameObject.position).Normal()
  289. gameObject.velocity = direction * 1.5 ' Set the speed to 1.5 units per step
  290. gameObject.Update(dt)
  291. Print "Step: " + i + " | " + gameObject.ToString()
  292. If gameObject.position.DistanceTo(target) < 0.1 Then ' If the game object is close to the target, switch to the next target
  293. currentTargetIndex = (currentTargetIndex + 1) Mod pathPoints.Length
  294. End If
  295. Delay(200) ' Add a small delay for readability
  296. Next
  297. Type TGameObject
  298. Field position:SVec3D
  299. Field velocity:SVec3D
  300. Method New(position:SVec3D, velocity:SVec3D)
  301. self.position = position
  302. self.velocity = velocity
  303. End Method
  304. Method Update(dt:Double)
  305. self.position = self.position + self.velocity * dt
  306. End Method
  307. Method ToString:String()
  308. Return "Position: " + position.ToString() + " | Velocity: " + velocity.ToString()
  309. End Method
  310. End Type
  311. ```
  312. **Computer Graphics** : 3D vectors are the backbone of computer graphics, representing points,
  313. lines, and polygons in 3D space. They facilitate transformations, such as translation, rotation,
  314. and scaling, which are vital for rendering 3D models and scenes. In addition, 3D vectors are used
  315. in lighting calculations and surface shading, enabling the creation of realistic materials and textures.
  316. **Physics Simulations** : In physics simulations, 3D vectors are used to represent quantities like
  317. force, torque, and momentum. They enable calculations of physical properties, such as the center of
  318. mass and moments of inertia for rigid bodies. Moreover, 3D vectors are used in numerical methods like
  319. the Verlet integration and the Runge-Kutta method for simulating the motion of objects under various
  320. forces and constraints.
  321. This example demonstrates a simple Verlet integration for simulating the motion of a falling particle
  322. under gravity. The `TParticle` type contains position, previous position, and acceleration.
  323. The `Integrate` method updates the particle's position using Verlet integration. We create a particle
  324. and simulate its motion for 100 iterations, printing its position at each step.
  325. ```blitzmax
  326. SuperStrict
  327. Framework brl.standardio
  328. Import BRL.Vector
  329. Const deltaTime:Float = 0.01
  330. Const gravity:Float = -9.8
  331. Const numIterations:Int = 100
  332. Local p:TParticle = New TParticle(New SVec3F(0, 10, 0))
  333. For Local i:Int = 0 To numIterations - 1
  334. p.Integrate()
  335. Print "Iteration: " + (i + 1) + " Position: " + p.position.ToString()
  336. Next
  337. Type TParticle
  338. Field position:SVec3F
  339. Field previousPosition:SVec3F
  340. Field acceleration:SVec3F
  341. Method New(pos:SVec3F)
  342. position = pos
  343. previousPosition = pos
  344. acceleration = New SVec3F(0, gravity, 0)
  345. End Method
  346. Method Integrate()
  347. Local temp:SVec3F = position
  348. position = position * 2 - previousPosition + acceleration * deltaTime * deltaTime
  349. previousPosition = temp
  350. End Method
  351. End Type
  352. ```
  353. **Engineering Analyses** : 3D vectors play a significant role in engineering analyses, including structural,
  354. fluid dynamics, and thermal analyses. They are used to represent stress and strain tensors in structural
  355. mechanics, velocity and pressure fields in fluid dynamics, and temperature gradients in thermal analyses.
  356. Additionally, 3D vectors facilitate the visualization and interpretation of complex engineering data,
  357. like stress distributions and flow patterns.
  358. **Geospatial Applications** : In geospatial applications, 3D vectors are used to represent positions and
  359. displacements on Earth's surface and in its atmosphere. They facilitate calculations of distances, angles,
  360. and areas on the curved surface, as well as transformations between various coordinate systems, such as
  361. geographic, Cartesian, and spherical coordinates.
  362. **Cross Products** : Unlike 2D vectors, 3D vectors have a unique operation called the cross product.
  363. The cross product takes two input vectors and returns a new vector that is perpendicular to both input
  364. vectors and has a magnitude proportional to the sine of the angle between them. Cross products are used
  365. in numerous applications, including calculating surface normals, generating coordinate systems, and
  366. determining the torque produced by a force.
  367. 3D vectors are essential in various applications, extending the functionality of 2D vectors to more complex
  368. scenarios and additional operations.
  369. ## 4D Vectors
  370. 4D vectors, represented by the #SVec4D, #SVec4F, and #SVec4I structs, have four components: x, y, z,
  371. and w. While they can indeed represent points in 4D space, their primary use is for homogeneous
  372. coordinates in 3D graphics, along with other specialized applications.
  373. **Homogeneous Coordinates** : In 3D graphics, 4D vectors are employed to represent homogeneous coordinates,
  374. which enable affine transformations, such as translation, rotation, scaling, and perspective projection.
  375. By adding the w component to a 3D point, 4D vectors allow for these transformations to be represented
  376. by matrix multiplications, simplifying the overall process. Once the transformations are applied, the
  377. resulting 4D vector can be converted back to a 3D point by dividing the x, y, and z components by
  378. the w component.
  379. In this example, we define a `TTransformableObject` type with a 4D vector position to represent
  380. the object's position in homogeneous coordinates. The `ApplyTransformation` method applies a given
  381. transformation matrix to the object's position using the `Apply` method of #SMat4D. The `Get3DPosition`
  382. method converts the 4D vector back to a 3D point by dividing the x, y, and z components by the w component.
  383. We create a TransformableObject and use the #SMat4D struct functions `Translation`,
  384. `Rotation`, and `Scaling` to create translation, rotation, and scaling matrices. We then apply
  385. these transformations to the object and print its position after each transformation.
  386. ```blitzmax
  387. SuperStrict
  388. Framework BRL.StandardIO
  389. Import BRL.Vector
  390. Import BRL.Matrix
  391. Local obj:TTransformableObject = New TTransformableObject(New SVec3D(2.0, 3.0, 4.0))
  392. Local translationMatrix:SMat4D = SMat4D.Translation(New SVec3D(5.0, -2.0, 3.0))
  393. Local rotationMatrix:SMat4D = SMat4D.Rotation(New SVec3D(0.0, 1.0, 0.0), 45.0)
  394. Local scalingMatrix:SMat4D = SMat4D.Scaling(New SVec3D(2.0, 0.5, 1.5))
  395. Print "Original Position: " + obj.ToString()
  396. obj.ApplyTransformation(translationMatrix)
  397. Print "After Translation: " + obj.ToString()
  398. obj.ApplyTransformation(rotationMatrix)
  399. Print "After Rotation: " + obj.ToString()
  400. obj.ApplyTransformation(scalingMatrix)
  401. Print "After Scaling: " + obj.ToString()
  402. Type TTransformableObject
  403. Field position:SVec4D
  404. Method New(position:SVec3D)
  405. self.position = New SVec4D(position.x, position.y, position.z, 1.0)
  406. End Method
  407. Method ApplyTransformation(transformationMatrix:SMat4D)
  408. self.position = transformationMatrix.Apply(self.position)
  409. End Method
  410. Method Get3DPosition:SVec3D()
  411. Return New SVec3D(self.position.x / self.position.w, self.position.y / self.position.w, self.position.z / self.position.w)
  412. End Method
  413. Method ToString:String()
  414. Return "Position: " + Get3DPosition().ToString()
  415. End Method
  416. End Type
  417. ```
  418. **Perspective Projection** : Perspective projection is a crucial aspect of 3D rendering, as it creates
  419. the illusion of depth on a 2D screen. 4D vectors facilitate this process by allowing the perspective
  420. divide, which is a transformation that scales x, y, and z coordinates by the reciprocal of the w component.
  421. This division produces the desired depth effect, with objects appearing smaller as they move further away
  422. from the viewer.
  423. **Quaternions** : 4D vectors can also represent quaternions, which are mathematical constructs used for
  424. efficient 3D rotation calculations. In this context, the x, y, and z components correspond to the
  425. imaginary part of the quaternion, and the w component corresponds to the real part. Quaternions are
  426. particularly useful in computer graphics and robotics for avoiding gimbal lock, interpolating between
  427. orientations, and maintaining numerical stability.
  428. **Color Representation** : In computer graphics, 4D vectors can be used to represent colors with an
  429. additional alpha channel for transparency. The x, y, z, and w components correspond to the red, green,
  430. blue, and alpha values, respectively. This representation allows for color blending and modulation
  431. operations to be performed using vector arithmetic.
  432. **Splines and Curves** : 4D vectors can be employed to represent control points for splines and curves
  433. in higher-dimensional spaces. For example, in computer-aided design (CAD) and computer graphics,
  434. 4D vectors can define control points for NURBS (Non-uniform rational B-spline) surfaces or Bézier
  435. patches, enabling smooth and precise modeling of complex shapes.
  436. **Hyperplanes** : In machine learning and computational geometry, 4D vectors can be used to represent
  437. hyperplanes in 4D space. These hyperplanes can be employed for tasks like data classification,
  438. clustering, or nearest-neighbor searches in four-dimensional data sets.
  439. 4D vectors have specialized uses, primarily in homogeneous coordinates for 3D graphics, along with
  440. other applications such as perspective projection, quaternion representation, color representation,
  441. splines and curves, and hyperplanes. While sharing some similarities with 2D and 3D vectors,
  442. 4D vectors extend their functionality to accommodate unique scenarios and mathematical constructs.