small3dlib.h 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815
  1. #ifndef SMALL3DLIB_H
  2. #define SMALL3DLIB_H
  3. /*
  4. Simple realtime 3D software rasterization renderer. It is fast, focused on
  5. resource-limited computers, located in a single C header file, with no
  6. dependencies, using only 32bit integer arithmetics.
  7. author: Miloslav Ciz
  8. license: CC0 1.0 (public domain)
  9. found at https://creativecommons.org/publicdomain/zero/1.0/
  10. + additional waiver of all IP
  11. version: 0.853d
  12. Before including the library, define S3L_PIXEL_FUNCTION to the name of the
  13. function you'll be using to draw single pixels (this function will be called
  14. by the library to render the frames). Also either init S3L_resolutionX and
  15. S3L_resolutionY or define S3L_RESOLUTION_X and S3L_RESOLUTION_Y.
  16. You'll also need to decide what rendering strategy and other settings you
  17. want to use, depending on your specific usecase. You may want to use a
  18. z-buffer (full or reduced, S3L_Z_BUFFER), sorted-drawing (S3L_SORT), or even
  19. none of these. See the description of the options in this file.
  20. The rendering itself is done with S3L_drawScene, usually preceded by
  21. S3L_newFrame (for clearing zBuffer etc.).
  22. The library is meant to be used in not so huge programs that use single
  23. translation unit and so includes both declarations and implementation at once.
  24. If you for some reason use multiple translation units (which include the
  25. library), you'll have to handle this yourself (e.g. create a wrapper, manually
  26. split the library into .c and .h etc.).
  27. --------------------
  28. This work's goal is to never be encumbered by any exclusive intellectual
  29. property rights. The work is therefore provided under CC0 1.0 + additional
  30. WAIVER OF ALL INTELLECTUAL PROPERTY RIGHTS that waives the rest of
  31. intellectual property rights not already waived by CC0 1.0. The WAIVER OF ALL
  32. INTELLECTUAL PROPERTY RGHTS is as follows:
  33. Each contributor to this work agrees that they waive any exclusive rights,
  34. including but not limited to copyright, patents, trademark, trade dress,
  35. industrial design, plant varieties and trade secrets, to any and all ideas,
  36. concepts, processes, discoveries, improvements and inventions conceived,
  37. discovered, made, designed, researched or developed by the contributor either
  38. solely or jointly with others, which relate to this work or result from this
  39. work. Should any waiver of such right be judged legally invalid or
  40. ineffective under applicable law, the contributor hereby grants to each
  41. affected person a royalty-free, non transferable, non sublicensable, non
  42. exclusive, irrevocable and unconditional license to this right.
  43. --------------------
  44. CONVENTIONS:
  45. This library should never draw pixels outside the specified screen
  46. boundaries, so you don't have to check this (that would cost CPU time)!
  47. You can safely assume that triangles are rasterized one by one and from top
  48. down, left to right (so you can utilize e.g. various caches), and if sorting
  49. is disabled the order of rasterization will be that specified in the scene
  50. structure and model arrays (of course, some triangles and models may be
  51. skipped due to culling etc.).
  52. Angles are in S3L_Units, a full angle (2 pi) is S3L_FRACTIONS_PER_UNITs.
  53. We use row vectors.
  54. In 3D space, a left-handed coord. system is used. One spatial unit is split
  55. into S3L_FRACTIONS_PER_UNIT fractions (fixed point arithmetic).
  56. y ^
  57. | _
  58. | /| z
  59. | /
  60. | /
  61. [0,0,0]-------> x
  62. Untransformed camera is placed at [0,0,0], looking forward along +z axis. The
  63. projection plane is centered at [0,0,0], stretrinch from
  64. -S3L_FRACTIONS_PER_UNIT to S3L_FRACTIONS_PER_UNIT horizontally (x),
  65. vertical size (y) depends on the aspect ratio (S3L_RESOLUTION_X and
  66. S3L_RESOLUTION_Y). Camera FOV is defined by focal length in S3L_Units.
  67. y ^
  68. | _
  69. | /| z
  70. ____|_/__
  71. | |/ |
  72. -----[0,0,0]-|-----> x
  73. |____|____|
  74. |
  75. |
  76. Rotations use Euler angles and are generally in the extrinsic Euler angles in
  77. ZXY order (by Z, then by X, then by Y). Positive rotation about an axis
  78. rotates CW (clock-wise) when looking in the direction of the axis.
  79. Coordinates of pixels on the screen start at the top left, from [0,0].
  80. There is NO subpixel accuracy (screen coordinates are only integer).
  81. Triangle rasterization rules are these (mostly same as OpenGL, D3D etc.):
  82. - Let's define:
  83. - left side:
  84. - not exactly horizontal, and on the left side of triangle
  85. - exactly horizontal and above the topmost
  86. (in other words: its normal points at least a little to the left or
  87. completely up)
  88. - right side: not left side
  89. - Pixel centers are at integer coordinates and triangle for drawing are
  90. specified with integer coordinates of pixel centers.
  91. - A pixel is rasterized:
  92. - if its center is inside the triangle OR
  93. - if its center is exactly on the triangle side which is left and at the
  94. same time is not on the side that's right (case of a triangle that's on
  95. a single line) OR
  96. - if its center is exactly on the triangle corner of sides neither of which
  97. is right.
  98. These rules imply among others:
  99. - Adjacent triangles don't have any overlapping pixels, nor gaps between.
  100. - Triangles of points that lie on a single line are NOT rasterized.
  101. - A single "long" triangle CAN be rasterized as isolated islands of pixels.
  102. - Transforming (e.g. mirroring, rotating by 90 degrees etc.) a result of
  103. rasterizing triangle A is NOT generally equal to applying the same
  104. transformation to triangle A first and then rasterizing it. Even the number
  105. of rasterized pixels is usually different.
  106. - If specifying a triangle with integer coordinates (which we are), then:
  107. - The bottom-most corner (or side) of a triangle is never rasterized
  108. (because it is connected to a right side).
  109. - The top-most corner can only be rasterized on completely horizontal side
  110. (otherwise it is connected to a right side).
  111. - Vertically middle corner is rasterized if and only if it is on the left
  112. of the triangle and at the same time is also not the bottom-most corner.
  113. */
  114. #include <stdint.h>
  115. #ifdef S3L_RESOLUTION_X
  116. #ifdef S3L_RESOLUTION_Y
  117. #define S3L_MAX_PIXELS (S3L_RESOLUTION_X * S3L_RESOLUTION_Y)
  118. #endif
  119. #endif
  120. #ifndef S3L_RESOLUTION_X
  121. #ifndef S3L_MAX_PIXELS
  122. #error Dynamic resolution set (S3L_RESOLUTION_X not defined), but\
  123. S3L_MAX_PIXELS not defined!
  124. #endif
  125. uint16_t S3L_resolutionX = 512; /**< If a static resolution is not set with
  126. S3L_RESOLUTION_X, this variable can be
  127. used to change X resolution at runtime,
  128. in which case S3L_MAX_PIXELS has to be
  129. defined (to allocate zBuffer etc.)! */
  130. #define S3L_RESOLUTION_X S3L_resolutionX
  131. #endif
  132. #ifndef S3L_RESOLUTION_Y
  133. #ifndef S3L_MAX_PIXELS
  134. #error Dynamic resolution set (S3L_RESOLUTION_Y not defined), but\
  135. S3L_MAX_PIXELS not defined!
  136. #endif
  137. uint16_t S3L_resolutionY = 512; /**< Same as S3L_resolutionX, but for Y
  138. resolution. */
  139. #define S3L_RESOLUTION_Y S3L_resolutionY
  140. #endif
  141. /** Units of measurement in 3D space. There is S3L_FRACTIONS_PER_UNIT in one
  142. spatial unit. By dividing the unit into fractions we effectively achieve a
  143. fixed point arithmetic. The number of fractions is a constant that serves as
  144. 1.0 in floating point arithmetic (normalization etc.). */
  145. typedef int32_t S3L_Unit;
  146. /** How many fractions a spatial unit is split into. This is NOT SUPPOSED TO
  147. BE REDEFINED, so rather don't do it (otherwise things may overflow etc.). */
  148. #define S3L_FRACTIONS_PER_UNIT 512
  149. typedef int16_t S3L_ScreenCoord;
  150. typedef uint16_t S3L_Index;
  151. #ifndef S3L_NEAR_CROSS_STRATEGY
  152. /** Specifies how the library will handle triangles that partially cross the
  153. near plane. These are problematic and require special handling. Possible
  154. values:
  155. 0: Strictly cull any triangle crossing the near plane. This will make such
  156. triangles disappear. This is good for performance or models viewed only
  157. from at least small distance.
  158. 1: Forcefully push the vertices crossing near plane in front of it. This is
  159. a cheap technique that can be good enough for displaying simple
  160. environments on slow devices, but texturing and geometric artifacts/warps
  161. will appear.
  162. 2: Geometrically correct the triangles crossing the near plane. This may
  163. result in some triangles being subdivided into two and is a little more
  164. expensive, but the results will be geometrically correct, even though
  165. barycentric correction is not performed so texturing artifacts will
  166. appear. Can be ideal with S3L_FLAT.
  167. 3: NOT IMPLEMENTED YET
  168. Perform both geometrical and barycentric correction of triangle crossing
  169. the near plane. This is significantly more expensive but results in
  170. correct rendering. */
  171. #define S3L_NEAR_CROSS_STRATEGY 0
  172. #endif
  173. #ifndef S3L_FLAT
  174. /** If on, disables computation of per-pixel values such as barycentric
  175. coordinates and depth -- these will still be available but will be the same
  176. for the whole triangle. This can be used to create flat-shaded renders and
  177. will be a lot faster. With this option on you will probably want to use
  178. sorting instead of z-buffer. */
  179. #define S3L_FLAT 0
  180. #endif
  181. #if S3L_FLAT
  182. #define S3L_COMPUTE_DEPTH 0
  183. #define S3L_PERSPECTIVE_CORRECTION 0
  184. // don't disable z-buffer, it makes sense to use it with no sorting
  185. #endif
  186. #ifndef S3L_PERSPECTIVE_CORRECTION
  187. /** Specifies what type of perspective correction (PC) to use. Remember this
  188. is an expensive operation! Possible values:
  189. 0: No perspective correction. Fastest, inaccurate from most angles.
  190. 1: Per-pixel perspective correction, accurate but very expensive.
  191. 2: Approximation (computing only at every S3L_PC_APPROX_LENGTHth pixel).
  192. Quake-style approximation is used, which only computes the PC after
  193. S3L_PC_APPROX_LENGTH pixels. This is reasonably accurate and fast. */
  194. #define S3L_PERSPECTIVE_CORRECTION 0
  195. #endif
  196. #ifndef S3L_PC_APPROX_LENGTH
  197. /** For S3L_PERSPECTIVE_CORRECTION == 2, this specifies after how many pixels
  198. PC is recomputed. Should be a power of two to keep up the performance.
  199. Smaller is nicer but slower. */
  200. #define S3L_PC_APPROX_LENGTH 32
  201. #endif
  202. #if S3L_PERSPECTIVE_CORRECTION
  203. #define S3L_COMPUTE_DEPTH 1 // PC inevitably computes depth, so enable it
  204. #endif
  205. #ifndef S3L_COMPUTE_DEPTH
  206. /** Whether to compute depth for each pixel (fragment). Some other options
  207. may turn this on automatically. If you don't need depth information, turning
  208. this off can save performance. Depth will still be accessible in
  209. S3L_PixelInfo, but will be constant -- equal to center point depth -- over
  210. the whole triangle. */
  211. #define S3L_COMPUTE_DEPTH 1
  212. #endif
  213. #ifndef S3L_Z_BUFFER
  214. /** What type of z-buffer (depth buffer) to use for visibility determination.
  215. Possible values:
  216. 0: Don't use z-buffer. This saves a lot of memory, but visibility checking
  217. won't be pixel-accurate and has to mostly be done by other means (typically
  218. sorting).
  219. 1: Use full z-buffer (of S3L_Units) for visibiltiy determination. This is the
  220. most accurate option (and also a fast one), but requires a big amount of
  221. memory.
  222. 2: Use reduced-size z-buffer (of bytes). This is fast and somewhat accurate,
  223. but inaccuracies can occur and a considerable amount of memory is
  224. needed. */
  225. #define S3L_Z_BUFFER 0
  226. #endif
  227. #ifndef S3L_REDUCED_Z_BUFFER_GRANULARITY
  228. /** For S3L_Z_BUFFER == 2 this sets the reduced z-buffer granularity. */
  229. #define S3L_REDUCED_Z_BUFFER_GRANULARITY 5
  230. #endif
  231. #ifndef S3L_STENCIL_BUFFER
  232. /** Whether to use stencil buffer for drawing -- with this a pixel that would
  233. be resterized over an already rasterized pixel (within a frame) will be
  234. discarded. This is mostly for front-to-back sorted drawing. */
  235. #define S3L_STENCIL_BUFFER 0
  236. #endif
  237. #ifndef S3L_SORT
  238. /** Defines how to sort triangles before drawing a frame. This can be used to
  239. solve visibility in case z-buffer is not used, to prevent overwriting already
  240. rasterized pixels, implement transparency etc. Note that for simplicity and
  241. performance a relatively simple sorting is used which doesn't work completely
  242. correctly, so mistakes can occur (even the best sorting wouldn't be able to
  243. solve e.g. intersecting triangles). Note that sorting requires a bit of extra
  244. memory -- an array of the triangles to sort -- the size of this array limits
  245. the maximum number of triangles that can be drawn in a single frame
  246. (S3L_MAX_TRIANGES_DRAWN). Possible values:
  247. 0: Don't sort triangles. This is fastest and doesn't use extra memory.
  248. 1: Sort triangles from back to front. This can in most cases solve visibility
  249. without requiring almost any extra memory compared to z-buffer.
  250. 2: Sort triangles from front to back. This can be faster than back to front
  251. because we prevent computing pixels that will be overwritten by nearer
  252. ones, but we need a 1b stencil buffer for this (enable S3L_STENCIL_BUFFER),
  253. so a bit more memory is needed. */
  254. #define S3L_SORT 0
  255. #endif
  256. #ifndef S3L_MAX_TRIANGES_DRAWN
  257. /** Maximum number of triangles that can be drawn in sorted modes. This
  258. affects the size of the cache used for triangle sorting. */
  259. #define S3L_MAX_TRIANGES_DRAWN 128
  260. #endif
  261. #ifndef S3L_NEAR
  262. /** Distance of the near clipping plane. Points in front or EXATLY ON this
  263. plane are considered outside the frustum. This must be >= 0. */
  264. #define S3L_NEAR (S3L_FRACTIONS_PER_UNIT / 4)
  265. #endif
  266. #if S3L_NEAR <= 0
  267. #define S3L_NEAR 1 // Can't be <= 0.
  268. #endif
  269. #ifndef S3L_NORMAL_COMPUTE_MAXIMUM_AVERAGE
  270. /** Affects the S3L_computeModelNormals function. See its description for
  271. details. */
  272. #define S3L_NORMAL_COMPUTE_MAXIMUM_AVERAGE 6
  273. #endif
  274. #ifndef S3L_FAST_LERP_QUALITY
  275. /** Quality (scaling) of SOME (stepped) linear interpolations. 0 will most
  276. likely be a tiny bit faster, but artifacts can occur for bigger tris, while
  277. higher values can fix this -- in theory all higher values will have the same
  278. speed (it is a shift value), but it mustn't be too high to prevent
  279. overflow. */
  280. #define S3L_FAST_LERP_QUALITY 11
  281. #endif
  282. /** Vector that consists of four scalars and can represent homogenous
  283. coordinates, but is generally also used as Vec3 and Vec2 for various
  284. purposes. */
  285. typedef struct
  286. {
  287. S3L_Unit x;
  288. S3L_Unit y;
  289. S3L_Unit z;
  290. S3L_Unit w;
  291. } S3L_Vec4;
  292. #define S3L_logVec4(v)\
  293. printf("Vec4: %d %d %d %d\n",((v).x),((v).y),((v).z),((v).w))
  294. static inline void S3L_initVec4(S3L_Vec4 *v);
  295. static inline void S3L_setVec4(S3L_Vec4 *v, S3L_Unit x, S3L_Unit y,
  296. S3L_Unit z, S3L_Unit w);
  297. static inline void S3L_vec3Add(S3L_Vec4 *result, S3L_Vec4 added);
  298. static inline void S3L_vec3Sub(S3L_Vec4 *result, S3L_Vec4 substracted);
  299. S3L_Unit S3L_vec3Length(S3L_Vec4 v);
  300. /** Normalizes Vec3. Note that this function tries to normalize correctly
  301. rather than quickly! If you need to normalize quickly, do it yourself in a
  302. way that best fits your case. */
  303. void S3L_normalizeVec3(S3L_Vec4 *v);
  304. /** Like S3L_normalizeVec3, but doesn't perform any checks on the input vector,
  305. which is faster, but can be very innacurate or overflowing. You are supposed
  306. to provide a "nice" vector (not too big or small). */
  307. static inline void S3L_normalizeVec3Fast(S3L_Vec4 *v);
  308. S3L_Unit S3L_vec2Length(S3L_Vec4 v);
  309. void S3L_crossProduct(S3L_Vec4 a, S3L_Vec4 b, S3L_Vec4 *result);
  310. static inline S3L_Unit S3L_dotProductVec3(S3L_Vec4 a, S3L_Vec4 b);
  311. /** Computes a reflection direction (typically used e.g. for specular component
  312. in Phong illumination). The input vectors must be normalized. The result will
  313. be normalized as well. */
  314. void S3L_reflect(S3L_Vec4 toLight, S3L_Vec4 normal, S3L_Vec4 *result);
  315. /** Determines the winding of a triangle, returns 1 (CW, clockwise), -1 (CCW,
  316. counterclockwise) or 0 (points lie on a single line). */
  317. static inline int8_t S3L_triangleWinding(
  318. S3L_ScreenCoord x0,
  319. S3L_ScreenCoord y0,
  320. S3L_ScreenCoord x1,
  321. S3L_ScreenCoord y1,
  322. S3L_ScreenCoord x2,
  323. S3L_ScreenCoord y2);
  324. typedef struct
  325. {
  326. S3L_Vec4 translation;
  327. S3L_Vec4 rotation; /**< Euler angles. Rortation is applied in this order:
  328. 1. z = by z (roll) CW looking along z+
  329. 2. x = by x (pitch) CW looking along x+
  330. 3. y = by y (yaw) CW looking along y+ */
  331. S3L_Vec4 scale;
  332. } S3L_Transform3D;
  333. #define S3L_logTransform3D(t)\
  334. printf("Transform3D: T = [%d %d %d], R = [%d %d %d], S = [%d %d %d]\n",\
  335. (t).translation.x,(t).translation.y,(t).translation.z,\
  336. (t).rotation.x,(t).rotation.y,(t).rotation.z,\
  337. (t).scale.x,(t).scale.y,(t).scale.z)
  338. static inline void S3L_initTransform3D(S3L_Transform3D *t);
  339. void S3L_lookAt(S3L_Vec4 pointTo, S3L_Transform3D *t);
  340. void S3L_setTransform3D(
  341. S3L_Unit tx,
  342. S3L_Unit ty,
  343. S3L_Unit tz,
  344. S3L_Unit rx,
  345. S3L_Unit ry,
  346. S3L_Unit rz,
  347. S3L_Unit sx,
  348. S3L_Unit sy,
  349. S3L_Unit sz,
  350. S3L_Transform3D *t);
  351. /** Converts rotation transformation to three direction vectors of given length
  352. (any one can be NULL, in which case it won't be computed). */
  353. void S3L_rotationToDirections(
  354. S3L_Vec4 rotation,
  355. S3L_Unit length,
  356. S3L_Vec4 *forw,
  357. S3L_Vec4 *right,
  358. S3L_Vec4 *up);
  359. /** 4x4 matrix, used mostly for 3D transforms. The indexing is this:
  360. matrix[column][row]. */
  361. typedef S3L_Unit S3L_Mat4[4][4];
  362. #define S3L_logMat4(m)\
  363. printf("Mat4:\n %d %d %d %d\n %d %d %d %d\n %d %d %d %d\n %d %d %d %d\n"\
  364. ,(m)[0][0],(m)[1][0],(m)[2][0],(m)[3][0],\
  365. (m)[0][1],(m)[1][1],(m)[2][1],(m)[3][1],\
  366. (m)[0][2],(m)[1][2],(m)[2][2],(m)[3][2],\
  367. (m)[0][3],(m)[1][3],(m)[2][3],(m)[3][3])
  368. /** Initializes a 4x4 matrix to identity. */
  369. static inline void S3L_initMat4(S3L_Mat4 m);
  370. void S3L_copyMat4(S3L_Mat4 src, S3L_Mat4 dst);
  371. void S3L_transposeMat4(S3L_Mat4 m);
  372. void S3L_makeTranslationMat(
  373. S3L_Unit offsetX,
  374. S3L_Unit offsetY,
  375. S3L_Unit offsetZ,
  376. S3L_Mat4 m);
  377. /** Makes a scaling matrix. DON'T FORGET: scale of 1.0 is set with
  378. S3L_FRACTIONS_PER_UNIT! */
  379. void S3L_makeScaleMatrix(
  380. S3L_Unit scaleX,
  381. S3L_Unit scaleY,
  382. S3L_Unit scaleZ,
  383. S3L_Mat4 m);
  384. /** Makes a matrix for rotation in the ZXY order. */
  385. void S3L_makeRotationMatrixZXY(
  386. S3L_Unit byX,
  387. S3L_Unit byY,
  388. S3L_Unit byZ,
  389. S3L_Mat4 m);
  390. void S3L_makeWorldMatrix(S3L_Transform3D worldTransform, S3L_Mat4 m);
  391. void S3L_makeCameraMatrix(S3L_Transform3D cameraTransform, S3L_Mat4 m);
  392. /** Multiplies a vector by a matrix with normalization by
  393. S3L_FRACTIONS_PER_UNIT. Result is stored in the input vector. */
  394. void S3L_vec4Xmat4(S3L_Vec4 *v, S3L_Mat4 m);
  395. /** Same as S3L_vec4Xmat4 but faster, because this version doesn't compute the
  396. W component of the result, which is usually not needed. */
  397. void S3L_vec3Xmat4(S3L_Vec4 *v, S3L_Mat4 m);
  398. /** Multiplies two matrices with normalization by S3L_FRACTIONS_PER_UNIT.
  399. Result is stored in the first matrix. The result represents a transformation
  400. that has the same effect as applying the transformation represented by m1 and
  401. then m2 (in that order). */
  402. void S3L_mat4Xmat4(S3L_Mat4 m1, S3L_Mat4 m2);
  403. typedef struct
  404. {
  405. S3L_Unit focalLength; ///< Defines the field of view (FOV).
  406. S3L_Transform3D transform;
  407. } S3L_Camera;
  408. void S3L_initCamera(S3L_Camera *camera);
  409. typedef struct
  410. {
  411. uint8_t backfaceCulling; /**< What backface culling to use. Possible
  412. values:
  413. - 0 none
  414. - 1 clock-wise
  415. - 2 counter clock-wise */
  416. int8_t visible; /**< Can be used to easily hide the model. */
  417. } S3L_DrawConfig;
  418. void S3L_initDrawConfig(S3L_DrawConfig *config);
  419. typedef struct
  420. {
  421. const S3L_Unit *vertices;
  422. S3L_Index vertexCount;
  423. const S3L_Index *triangles;
  424. S3L_Index triangleCount;
  425. S3L_Transform3D transform;
  426. S3L_Mat4 *customTransformMatrix; /**< This can be used to override the
  427. transform (if != 0) with a custom
  428. transform matrix, which is more
  429. general. */
  430. S3L_DrawConfig config;
  431. } S3L_Model3D; ///< Represents a 3D model.
  432. void S3L_initModel3D(
  433. const S3L_Unit *vertices,
  434. S3L_Index vertexCount,
  435. const S3L_Index *triangles,
  436. S3L_Index triangleCount,
  437. S3L_Model3D *model);
  438. typedef struct
  439. {
  440. S3L_Model3D *models;
  441. S3L_Index modelCount;
  442. S3L_Camera camera;
  443. } S3L_Scene; ///< Represent the 3D scene to be rendered.
  444. void S3L_initScene(
  445. S3L_Model3D *models,
  446. S3L_Index modelCount,
  447. S3L_Scene *scene);
  448. typedef struct
  449. {
  450. S3L_ScreenCoord x; ///< Screen X coordinate.
  451. S3L_ScreenCoord y; ///< Screen Y coordinate.
  452. S3L_Unit barycentric[3]; /**< Barycentric coords correspond to the three
  453. vertices. These serve to locate the pixel on a
  454. triangle and interpolate values between it's
  455. three points. Each one goes from 0 to
  456. S3L_FRACTIONS_PER_UNIT (including), but due to
  457. rounding error may fall outside this range (you
  458. can use S3L_correctBarycentricCoords to fix this
  459. for the price of some performance). The sum of
  460. the three coordinates will always be exactly
  461. S3L_FRACTIONS_PER_UNIT. */
  462. S3L_Index modelIndex; ///< Model index within the scene.
  463. S3L_Index triangleIndex; ///< Triangle index within the model.
  464. uint32_t triangleID; /**< Unique ID of the triangle withing the whole
  465. scene. This can be used e.g. by a cache to
  466. quickly find out if a triangle has changed. */
  467. S3L_Unit depth; ///< Depth (only if depth is turned on).
  468. S3L_Unit previousZ; /**< Z-buffer value (not necessarily world depth in
  469. S3L_Units!) that was in the z-buffer on the
  470. pixels position before this pixel was
  471. rasterized. This can be used to set the value
  472. back, e.g. for transparency. */
  473. S3L_ScreenCoord triangleSize[2]; /**< Rasterized triangle width and height,
  474. can be used e.g. for MIP mapping. */
  475. } S3L_PixelInfo; /**< Used to pass the info about a rasterized pixel
  476. (fragment) to the user-defined drawing func. */
  477. static inline void S3L_initPixelInfo(S3L_PixelInfo *p);
  478. /** Corrects barycentric coordinates so that they exactly meet the defined
  479. conditions (each fall into <0,S3L_FRACTIONS_PER_UNIT>, sum =
  480. S3L_FRACTIONS_PER_UNIT). Note that doing this per-pixel can slow the program
  481. down significantly. */
  482. static inline void S3L_correctBarycentricCoords(S3L_Unit barycentric[3]);
  483. // general helper functions
  484. static inline S3L_Unit S3L_abs(S3L_Unit value);
  485. static inline S3L_Unit S3L_min(S3L_Unit v1, S3L_Unit v2);
  486. static inline S3L_Unit S3L_max(S3L_Unit v1, S3L_Unit v2);
  487. static inline S3L_Unit S3L_clamp(S3L_Unit v, S3L_Unit v1, S3L_Unit v2);
  488. static inline S3L_Unit S3L_wrap(S3L_Unit value, S3L_Unit mod);
  489. static inline S3L_Unit S3L_nonZero(S3L_Unit value);
  490. static inline S3L_Unit S3L_zeroClamp(S3L_Unit value);
  491. S3L_Unit S3L_sin(S3L_Unit x);
  492. S3L_Unit S3L_asin(S3L_Unit x);
  493. static inline S3L_Unit S3L_cos(S3L_Unit x);
  494. S3L_Unit S3L_vec3Length(S3L_Vec4 v);
  495. S3L_Unit S3L_sqrt(S3L_Unit value);
  496. /** Projects a single point from 3D space to the screen space (pixels), which
  497. can be useful e.g. for drawing sprites. The w component of input and result
  498. holds the point size. If this size is 0 in the result, the sprite is outside
  499. the view. */
  500. void project3DPointToScreen(
  501. S3L_Vec4 point,
  502. S3L_Camera camera,
  503. S3L_Vec4 *result);
  504. /** Computes a normalized normal of given triangle. */
  505. void S3L_triangleNormal(S3L_Vec4 t0, S3L_Vec4 t1, S3L_Vec4 t2,
  506. S3L_Vec4 *n);
  507. /** Helper function for retrieving per-vertex indexed values from an array,
  508. e.g. texturing (UV) coordinates. The 'indices' array contains three indices
  509. for each triangle, each index pointing into 'values' array, which contains
  510. the values, each one consisting of 'numComponents' components (e.g. 2 for
  511. UV coordinates). The three values are retrieved into 'v0', 'v1' and 'v2'
  512. vectors (into x, y, z and w, depending on 'numComponents'). This function is
  513. meant to be used per-triangle (typically from a cache), NOT per-pixel, as it
  514. is not as fast as possible! */
  515. void S3L_getIndexedTriangleValues(
  516. S3L_Index triangleIndex,
  517. const S3L_Index *indices,
  518. const S3L_Unit *values,
  519. uint8_t numComponents,
  520. S3L_Vec4 *v0,
  521. S3L_Vec4 *v1,
  522. S3L_Vec4 *v2);
  523. /** Computes a normalized normal for every vertex of given model (this is
  524. relatively slow and SHOUDN'T be done each frame). The dst array must have a
  525. sufficient size preallocated! The size is: number of model vertices * 3 *
  526. sizeof(S3L_Unit). Note that for advanced allowing sharp edges it is not
  527. sufficient to have per-vertex normals, but must be per-triangle. This
  528. function doesn't support this.
  529. The function computes a normal for each vertex by averaging normals of
  530. the triangles containing the vertex. The maximum number of these triangle
  531. normals that will be averaged is set with
  532. S3L_NORMAL_COMPUTE_MAXIMUM_AVERAGE. */
  533. void S3L_computeModelNormals(S3L_Model3D model, S3L_Unit *dst,
  534. int8_t transformNormals);
  535. /** Interpolated between two values, v1 and v2, in the same ratio as t is to
  536. tMax. Does NOT prevent zero division. */
  537. static inline S3L_Unit S3L_interpolate(
  538. S3L_Unit v1,
  539. S3L_Unit v2,
  540. S3L_Unit t,
  541. S3L_Unit tMax);
  542. /** Same as S3L_interpolate but with v1 == 0. Should be faster. */
  543. static inline S3L_Unit S3L_interpolateFrom0(
  544. S3L_Unit v2,
  545. S3L_Unit t,
  546. S3L_Unit tMax);
  547. /** Like S3L_interpolate, but uses a parameter that goes from 0 to
  548. S3L_FRACTIONS_PER_UNIT - 1, which can be faster. */
  549. static inline S3L_Unit S3L_interpolateByUnit(
  550. S3L_Unit v1,
  551. S3L_Unit v2,
  552. S3L_Unit t);
  553. /** Same as S3L_interpolateByUnit but with v1 == 0. Should be faster. */
  554. static inline S3L_Unit S3L_interpolateByUnitFrom0(
  555. S3L_Unit v2,
  556. S3L_Unit t);
  557. static inline S3L_Unit S3L_distanceManhattan(S3L_Vec4 a, S3L_Vec4 b);
  558. /** Returns a value interpolated between the three triangle vertices based on
  559. barycentric coordinates. */
  560. static inline S3L_Unit S3L_interpolateBarycentric(
  561. S3L_Unit value0,
  562. S3L_Unit value1,
  563. S3L_Unit value2,
  564. S3L_Unit barycentric[3]);
  565. static inline void S3L_mapProjectionPlaneToScreen(
  566. S3L_Vec4 point,
  567. S3L_ScreenCoord *screenX,
  568. S3L_ScreenCoord *screenY);
  569. /** Draws a triangle according to given config. The vertices are specified in
  570. Screen Space space (pixels). If perspective correction is enabled, each
  571. vertex has to have a depth (Z position in camera space) specified in the Z
  572. component. */
  573. void S3L_drawTriangle(
  574. S3L_Vec4 point0,
  575. S3L_Vec4 point1,
  576. S3L_Vec4 point2,
  577. S3L_Index modelIndex,
  578. S3L_Index triangleIndex);
  579. /** This should be called before rendering each frame. The function clears
  580. buffers and does potentially other things needed for the frame. */
  581. void S3L_newFrame(void);
  582. void S3L_zBufferClear(void);
  583. void S3L_stencilBufferClear(void);
  584. /** Writes a value (not necessarily depth! depends on the format of z-buffer)
  585. to z-buffer (if enabled). Does NOT check boundaries! */
  586. void S3L_zBufferWrite(S3L_ScreenCoord x, S3L_ScreenCoord y, S3L_Unit value);
  587. /** Reads a value (not necessarily depth! depends on the format of z-buffer)
  588. from z-buffer (if enabled). Does NOT check boundaries! */
  589. S3L_Unit S3L_zBufferRead(S3L_ScreenCoord x, S3L_ScreenCoord y);
  590. static inline void S3L_rotate2DPoint(S3L_Unit *x, S3L_Unit *y, S3L_Unit angle);
  591. /** Predefined vertices of a cube to simply insert in an array. These come with
  592. S3L_CUBE_TRIANGLES and S3L_CUBE_TEXCOORDS. */
  593. #define S3L_CUBE_VERTICES(m)\
  594. /* 0 front, bottom, right */\
  595. m/2, -m/2, -m/2,\
  596. /* 1 front, bottom, left */\
  597. -m/2, -m/2, -m/2,\
  598. /* 2 front, top, right */\
  599. m/2, m/2, -m/2,\
  600. /* 3 front, top, left */\
  601. -m/2, m/2, -m/2,\
  602. /* 4 back, bottom, right */\
  603. m/2, -m/2, m/2,\
  604. /* 5 back, bottom, left */\
  605. -m/2, -m/2, m/2,\
  606. /* 6 back, top, right */\
  607. m/2, m/2, m/2,\
  608. /* 7 back, top, left */\
  609. -m/2, m/2, m/2
  610. #define S3L_CUBE_VERTEX_COUNT 8
  611. /** Predefined triangle indices of a cube, to be used with S3L_CUBE_VERTICES
  612. and S3L_CUBE_TEXCOORDS. */
  613. #define S3L_CUBE_TRIANGLES\
  614. 3, 0, 2, /* front */\
  615. 1, 0, 3,\
  616. 0, 4, 2, /* right */\
  617. 2, 4, 6,\
  618. 4, 5, 6, /* back */\
  619. 7, 6, 5,\
  620. 3, 7, 1, /* left */\
  621. 1, 7, 5,\
  622. 6, 3, 2, /* top */\
  623. 7, 3, 6,\
  624. 1, 4, 0, /* bottom */\
  625. 5, 4, 1
  626. #define S3L_CUBE_TRIANGLE_COUNT 12
  627. /** Predefined texture coordinates of a cube, corresponding to triangles (NOT
  628. vertices), to be used with S3L_CUBE_VERTICES and S3L_CUBE_TRIANGLES. */
  629. #define S3L_CUBE_TEXCOORDS(m)\
  630. 0,0, m,m, m,0,\
  631. 0,m, m,m, 0,0,\
  632. m,m, m,0, 0,m,\
  633. 0,m, m,0, 0,0,\
  634. m,0, 0,0, m,m,\
  635. 0,m, m,m, 0,0,\
  636. 0,0, 0,m, m,0,\
  637. m,0, 0,m, m,m,\
  638. 0,0, m,m, m,0,\
  639. 0,m, m,m, 0,0,\
  640. m,0, 0,m, m,m,\
  641. 0,0, 0,m, m,0
  642. //=============================================================================
  643. // privates
  644. #define S3L_UNUSED(what) (void)(what) ///< helper macro for unused vars
  645. #define S3L_HALF_RESOLUTION_X (S3L_RESOLUTION_X >> 1)
  646. #define S3L_HALF_RESOLUTION_Y (S3L_RESOLUTION_Y >> 1)
  647. #define S3L_PROJECTION_PLANE_HEIGHT\
  648. ((S3L_RESOLUTION_Y * S3L_FRACTIONS_PER_UNIT * 2) / S3L_RESOLUTION_X)
  649. #if S3L_Z_BUFFER == 1
  650. #define S3L_MAX_DEPTH 2147483647
  651. S3L_Unit S3L_zBuffer[S3L_MAX_PIXELS];
  652. #define S3L_zBufferFormat(depth) (depth)
  653. #elif S3L_Z_BUFFER == 2
  654. #define S3L_MAX_DEPTH 255
  655. uint8_t S3L_zBuffer[S3L_MAX_PIXELS];
  656. #define S3L_zBufferFormat(depth)\
  657. S3L_min(255,(depth) >> S3L_REDUCED_Z_BUFFER_GRANULARITY)
  658. #endif
  659. #if S3L_Z_BUFFER
  660. static inline int8_t S3L_zTest(
  661. S3L_ScreenCoord x,
  662. S3L_ScreenCoord y,
  663. S3L_Unit depth)
  664. {
  665. uint32_t index = y * S3L_RESOLUTION_X + x;
  666. depth = S3L_zBufferFormat(depth);
  667. #if S3L_Z_BUFFER == 2
  668. #define cmp <= /* For reduced z-buffer we need equality test, because
  669. otherwise pixels at the maximum depth (255) would never be
  670. drawn over the background (which also has the depth of
  671. 255). */
  672. #else
  673. #define cmp < /* For normal z-buffer we leave out equality test to not waste
  674. time by drawing over already drawn pixls. */
  675. #endif
  676. if (depth cmp S3L_zBuffer[index])
  677. {
  678. S3L_zBuffer[index] = depth;
  679. return 1;
  680. }
  681. #undef cmp
  682. return 0;
  683. }
  684. #endif
  685. S3L_Unit S3L_zBufferRead(S3L_ScreenCoord x, S3L_ScreenCoord y)
  686. {
  687. #if S3L_Z_BUFFER
  688. return S3L_zBuffer[y * S3L_RESOLUTION_X + x];
  689. #else
  690. S3L_UNUSED(x);
  691. S3L_UNUSED(y);
  692. return 0;
  693. #endif
  694. }
  695. void S3L_zBufferWrite(S3L_ScreenCoord x, S3L_ScreenCoord y, S3L_Unit value)
  696. {
  697. #if S3L_Z_BUFFER
  698. S3L_zBuffer[y * S3L_RESOLUTION_X + x] = value;
  699. #else
  700. S3L_UNUSED(x);
  701. S3L_UNUSED(y);
  702. S3L_UNUSED(value);
  703. #endif
  704. }
  705. #if S3L_STENCIL_BUFFER
  706. #define S3L_STENCIL_BUFFER_SIZE\
  707. ((S3L_RESOLUTION_X * S3L_RESOLUTION_Y - 1) / 8 + 1)
  708. uint8_t S3L_stencilBuffer[S3L_STENCIL_BUFFER_SIZE];
  709. static inline int8_t S3L_stencilTest(
  710. S3L_ScreenCoord x,
  711. S3L_ScreenCoord y)
  712. {
  713. uint32_t index = y * S3L_RESOLUTION_X + x;
  714. uint32_t bit = (index & 0x00000007);
  715. index = index >> 3;
  716. uint8_t val = S3L_stencilBuffer[index];
  717. if ((val >> bit) & 0x1)
  718. return 0;
  719. S3L_stencilBuffer[index] = val | (0x1 << bit);
  720. return 1;
  721. }
  722. #endif
  723. #define S3L_COMPUTE_LERP_DEPTH\
  724. (S3L_COMPUTE_DEPTH && (S3L_PERSPECTIVE_CORRECTION == 0))
  725. #define S3L_SIN_TABLE_LENGTH 128
  726. static const S3L_Unit S3L_sinTable[S3L_SIN_TABLE_LENGTH] =
  727. {
  728. /* 511 was chosen here as a highest number that doesn't overflow during
  729. compilation for S3L_FRACTIONS_PER_UNIT == 1024 */
  730. (0*S3L_FRACTIONS_PER_UNIT)/511, (6*S3L_FRACTIONS_PER_UNIT)/511,
  731. (12*S3L_FRACTIONS_PER_UNIT)/511, (18*S3L_FRACTIONS_PER_UNIT)/511,
  732. (25*S3L_FRACTIONS_PER_UNIT)/511, (31*S3L_FRACTIONS_PER_UNIT)/511,
  733. (37*S3L_FRACTIONS_PER_UNIT)/511, (43*S3L_FRACTIONS_PER_UNIT)/511,
  734. (50*S3L_FRACTIONS_PER_UNIT)/511, (56*S3L_FRACTIONS_PER_UNIT)/511,
  735. (62*S3L_FRACTIONS_PER_UNIT)/511, (68*S3L_FRACTIONS_PER_UNIT)/511,
  736. (74*S3L_FRACTIONS_PER_UNIT)/511, (81*S3L_FRACTIONS_PER_UNIT)/511,
  737. (87*S3L_FRACTIONS_PER_UNIT)/511, (93*S3L_FRACTIONS_PER_UNIT)/511,
  738. (99*S3L_FRACTIONS_PER_UNIT)/511, (105*S3L_FRACTIONS_PER_UNIT)/511,
  739. (111*S3L_FRACTIONS_PER_UNIT)/511, (118*S3L_FRACTIONS_PER_UNIT)/511,
  740. (124*S3L_FRACTIONS_PER_UNIT)/511, (130*S3L_FRACTIONS_PER_UNIT)/511,
  741. (136*S3L_FRACTIONS_PER_UNIT)/511, (142*S3L_FRACTIONS_PER_UNIT)/511,
  742. (148*S3L_FRACTIONS_PER_UNIT)/511, (154*S3L_FRACTIONS_PER_UNIT)/511,
  743. (160*S3L_FRACTIONS_PER_UNIT)/511, (166*S3L_FRACTIONS_PER_UNIT)/511,
  744. (172*S3L_FRACTIONS_PER_UNIT)/511, (178*S3L_FRACTIONS_PER_UNIT)/511,
  745. (183*S3L_FRACTIONS_PER_UNIT)/511, (189*S3L_FRACTIONS_PER_UNIT)/511,
  746. (195*S3L_FRACTIONS_PER_UNIT)/511, (201*S3L_FRACTIONS_PER_UNIT)/511,
  747. (207*S3L_FRACTIONS_PER_UNIT)/511, (212*S3L_FRACTIONS_PER_UNIT)/511,
  748. (218*S3L_FRACTIONS_PER_UNIT)/511, (224*S3L_FRACTIONS_PER_UNIT)/511,
  749. (229*S3L_FRACTIONS_PER_UNIT)/511, (235*S3L_FRACTIONS_PER_UNIT)/511,
  750. (240*S3L_FRACTIONS_PER_UNIT)/511, (246*S3L_FRACTIONS_PER_UNIT)/511,
  751. (251*S3L_FRACTIONS_PER_UNIT)/511, (257*S3L_FRACTIONS_PER_UNIT)/511,
  752. (262*S3L_FRACTIONS_PER_UNIT)/511, (268*S3L_FRACTIONS_PER_UNIT)/511,
  753. (273*S3L_FRACTIONS_PER_UNIT)/511, (278*S3L_FRACTIONS_PER_UNIT)/511,
  754. (283*S3L_FRACTIONS_PER_UNIT)/511, (289*S3L_FRACTIONS_PER_UNIT)/511,
  755. (294*S3L_FRACTIONS_PER_UNIT)/511, (299*S3L_FRACTIONS_PER_UNIT)/511,
  756. (304*S3L_FRACTIONS_PER_UNIT)/511, (309*S3L_FRACTIONS_PER_UNIT)/511,
  757. (314*S3L_FRACTIONS_PER_UNIT)/511, (319*S3L_FRACTIONS_PER_UNIT)/511,
  758. (324*S3L_FRACTIONS_PER_UNIT)/511, (328*S3L_FRACTIONS_PER_UNIT)/511,
  759. (333*S3L_FRACTIONS_PER_UNIT)/511, (338*S3L_FRACTIONS_PER_UNIT)/511,
  760. (343*S3L_FRACTIONS_PER_UNIT)/511, (347*S3L_FRACTIONS_PER_UNIT)/511,
  761. (352*S3L_FRACTIONS_PER_UNIT)/511, (356*S3L_FRACTIONS_PER_UNIT)/511,
  762. (361*S3L_FRACTIONS_PER_UNIT)/511, (365*S3L_FRACTIONS_PER_UNIT)/511,
  763. (370*S3L_FRACTIONS_PER_UNIT)/511, (374*S3L_FRACTIONS_PER_UNIT)/511,
  764. (378*S3L_FRACTIONS_PER_UNIT)/511, (382*S3L_FRACTIONS_PER_UNIT)/511,
  765. (386*S3L_FRACTIONS_PER_UNIT)/511, (391*S3L_FRACTIONS_PER_UNIT)/511,
  766. (395*S3L_FRACTIONS_PER_UNIT)/511, (398*S3L_FRACTIONS_PER_UNIT)/511,
  767. (402*S3L_FRACTIONS_PER_UNIT)/511, (406*S3L_FRACTIONS_PER_UNIT)/511,
  768. (410*S3L_FRACTIONS_PER_UNIT)/511, (414*S3L_FRACTIONS_PER_UNIT)/511,
  769. (417*S3L_FRACTIONS_PER_UNIT)/511, (421*S3L_FRACTIONS_PER_UNIT)/511,
  770. (424*S3L_FRACTIONS_PER_UNIT)/511, (428*S3L_FRACTIONS_PER_UNIT)/511,
  771. (431*S3L_FRACTIONS_PER_UNIT)/511, (435*S3L_FRACTIONS_PER_UNIT)/511,
  772. (438*S3L_FRACTIONS_PER_UNIT)/511, (441*S3L_FRACTIONS_PER_UNIT)/511,
  773. (444*S3L_FRACTIONS_PER_UNIT)/511, (447*S3L_FRACTIONS_PER_UNIT)/511,
  774. (450*S3L_FRACTIONS_PER_UNIT)/511, (453*S3L_FRACTIONS_PER_UNIT)/511,
  775. (456*S3L_FRACTIONS_PER_UNIT)/511, (459*S3L_FRACTIONS_PER_UNIT)/511,
  776. (461*S3L_FRACTIONS_PER_UNIT)/511, (464*S3L_FRACTIONS_PER_UNIT)/511,
  777. (467*S3L_FRACTIONS_PER_UNIT)/511, (469*S3L_FRACTIONS_PER_UNIT)/511,
  778. (472*S3L_FRACTIONS_PER_UNIT)/511, (474*S3L_FRACTIONS_PER_UNIT)/511,
  779. (476*S3L_FRACTIONS_PER_UNIT)/511, (478*S3L_FRACTIONS_PER_UNIT)/511,
  780. (481*S3L_FRACTIONS_PER_UNIT)/511, (483*S3L_FRACTIONS_PER_UNIT)/511,
  781. (485*S3L_FRACTIONS_PER_UNIT)/511, (487*S3L_FRACTIONS_PER_UNIT)/511,
  782. (488*S3L_FRACTIONS_PER_UNIT)/511, (490*S3L_FRACTIONS_PER_UNIT)/511,
  783. (492*S3L_FRACTIONS_PER_UNIT)/511, (494*S3L_FRACTIONS_PER_UNIT)/511,
  784. (495*S3L_FRACTIONS_PER_UNIT)/511, (497*S3L_FRACTIONS_PER_UNIT)/511,
  785. (498*S3L_FRACTIONS_PER_UNIT)/511, (499*S3L_FRACTIONS_PER_UNIT)/511,
  786. (501*S3L_FRACTIONS_PER_UNIT)/511, (502*S3L_FRACTIONS_PER_UNIT)/511,
  787. (503*S3L_FRACTIONS_PER_UNIT)/511, (504*S3L_FRACTIONS_PER_UNIT)/511,
  788. (505*S3L_FRACTIONS_PER_UNIT)/511, (506*S3L_FRACTIONS_PER_UNIT)/511,
  789. (507*S3L_FRACTIONS_PER_UNIT)/511, (507*S3L_FRACTIONS_PER_UNIT)/511,
  790. (508*S3L_FRACTIONS_PER_UNIT)/511, (509*S3L_FRACTIONS_PER_UNIT)/511,
  791. (509*S3L_FRACTIONS_PER_UNIT)/511, (510*S3L_FRACTIONS_PER_UNIT)/511,
  792. (510*S3L_FRACTIONS_PER_UNIT)/511, (510*S3L_FRACTIONS_PER_UNIT)/511,
  793. (510*S3L_FRACTIONS_PER_UNIT)/511, (510*S3L_FRACTIONS_PER_UNIT)/511
  794. };
  795. #define S3L_SIN_TABLE_UNIT_STEP\
  796. (S3L_FRACTIONS_PER_UNIT / (S3L_SIN_TABLE_LENGTH * 4))
  797. void S3L_initVec4(S3L_Vec4 *v)
  798. {
  799. v->x = 0; v->y = 0; v->z = 0; v->w = S3L_FRACTIONS_PER_UNIT;
  800. }
  801. void S3L_setVec4(S3L_Vec4 *v, S3L_Unit x, S3L_Unit y, S3L_Unit z, S3L_Unit w)
  802. {
  803. v->x = x;
  804. v->y = y;
  805. v->z = z;
  806. v->w = w;
  807. }
  808. void S3L_vec3Add(S3L_Vec4 *result, S3L_Vec4 added)
  809. {
  810. result->x += added.x;
  811. result->y += added.y;
  812. result->z += added.z;
  813. }
  814. void S3L_vec3Sub(S3L_Vec4 *result, S3L_Vec4 substracted)
  815. {
  816. result->x -= substracted.x;
  817. result->y -= substracted.y;
  818. result->z -= substracted.z;
  819. }
  820. void S3L_initMat4(S3L_Mat4 m)
  821. {
  822. #define M(x,y) m[x][y]
  823. #define S S3L_FRACTIONS_PER_UNIT
  824. M(0,0) = S; M(1,0) = 0; M(2,0) = 0; M(3,0) = 0;
  825. M(0,1) = 0; M(1,1) = S; M(2,1) = 0; M(3,1) = 0;
  826. M(0,2) = 0; M(1,2) = 0; M(2,2) = S; M(3,2) = 0;
  827. M(0,3) = 0; M(1,3) = 0; M(2,3) = 0; M(3,3) = S;
  828. #undef M
  829. #undef S
  830. }
  831. void S3L_copyMat4(S3L_Mat4 src, S3L_Mat4 dst)
  832. {
  833. for (uint8_t j = 0; j < 4; ++j)
  834. for (uint8_t i = 0; i < 4; ++i)
  835. dst[i][j] = src[i][j];
  836. }
  837. S3L_Unit S3L_dotProductVec3(S3L_Vec4 a, S3L_Vec4 b)
  838. {
  839. return (a.x * b.x + a.y * b.y + a.z * b.z) / S3L_FRACTIONS_PER_UNIT;
  840. }
  841. void S3L_reflect(S3L_Vec4 toLight, S3L_Vec4 normal, S3L_Vec4 *result)
  842. {
  843. S3L_Unit d = 2 * S3L_dotProductVec3(toLight,normal);
  844. result->x = (normal.x * d) / S3L_FRACTIONS_PER_UNIT - toLight.x;
  845. result->y = (normal.y * d) / S3L_FRACTIONS_PER_UNIT - toLight.y;
  846. result->z = (normal.z * d) / S3L_FRACTIONS_PER_UNIT - toLight.z;
  847. }
  848. void S3L_crossProduct(S3L_Vec4 a, S3L_Vec4 b, S3L_Vec4 *result)
  849. {
  850. result->x = a.y * b.z - a.z * b.y;
  851. result->y = a.z * b.x - a.x * b.z;
  852. result->z = a.x * b.y - a.y * b.x;
  853. }
  854. void S3L_triangleNormal(S3L_Vec4 t0, S3L_Vec4 t1, S3L_Vec4 t2, S3L_Vec4 *n)
  855. {
  856. #define ANTI_OVERFLOW 32
  857. t1.x = (t1.x - t0.x) / ANTI_OVERFLOW;
  858. t1.y = (t1.y - t0.y) / ANTI_OVERFLOW;
  859. t1.z = (t1.z - t0.z) / ANTI_OVERFLOW;
  860. t2.x = (t2.x - t0.x) / ANTI_OVERFLOW;
  861. t2.y = (t2.y - t0.y) / ANTI_OVERFLOW;
  862. t2.z = (t2.z - t0.z) / ANTI_OVERFLOW;
  863. #undef ANTI_OVERFLOW
  864. S3L_crossProduct(t1,t2,n);
  865. S3L_normalizeVec3(n);
  866. }
  867. void S3L_getIndexedTriangleValues(
  868. S3L_Index triangleIndex,
  869. const S3L_Index *indices,
  870. const S3L_Unit *values,
  871. uint8_t numComponents,
  872. S3L_Vec4 *v0,
  873. S3L_Vec4 *v1,
  874. S3L_Vec4 *v2)
  875. {
  876. uint32_t i0, i1;
  877. S3L_Unit *value;
  878. i0 = triangleIndex * 3;
  879. i1 = indices[i0] * numComponents;
  880. value = (S3L_Unit *) v0;
  881. if (numComponents > 4)
  882. numComponents = 4;
  883. for (uint8_t j = 0; j < numComponents; ++j)
  884. {
  885. *value = values[i1];
  886. i1++;
  887. value++;
  888. }
  889. i0++;
  890. i1 = indices[i0] * numComponents;
  891. value = (S3L_Unit *) v1;
  892. for (uint8_t j = 0; j < numComponents; ++j)
  893. {
  894. *value = values[i1];
  895. i1++;
  896. value++;
  897. }
  898. i0++;
  899. i1 = indices[i0] * numComponents;
  900. value = (S3L_Unit *) v2;
  901. for (uint8_t j = 0; j < numComponents; ++j)
  902. {
  903. *value = values[i1];
  904. i1++;
  905. value++;
  906. }
  907. }
  908. void S3L_computeModelNormals(S3L_Model3D model, S3L_Unit *dst,
  909. int8_t transformNormals)
  910. {
  911. S3L_Index vPos = 0;
  912. S3L_Vec4 n;
  913. n.w = 0;
  914. S3L_Vec4 ns[S3L_NORMAL_COMPUTE_MAXIMUM_AVERAGE];
  915. S3L_Index normalCount;
  916. for (uint32_t i = 0; i < model.vertexCount; ++i)
  917. {
  918. normalCount = 0;
  919. for (uint32_t j = 0; j < model.triangleCount * 3; j += 3)
  920. {
  921. if (
  922. (model.triangles[j] == i) ||
  923. (model.triangles[j + 1] == i) ||
  924. (model.triangles[j + 2] == i))
  925. {
  926. S3L_Vec4 t0, t1, t2;
  927. uint32_t vIndex;
  928. #define getVertex(n)\
  929. vIndex = model.triangles[j + n] * 3;\
  930. t##n.x = model.vertices[vIndex];\
  931. vIndex++;\
  932. t##n.y = model.vertices[vIndex];\
  933. vIndex++;\
  934. t##n.z = model.vertices[vIndex];
  935. getVertex(0)
  936. getVertex(1)
  937. getVertex(2)
  938. #undef getVertex
  939. S3L_triangleNormal(t0,t1,t2,&(ns[normalCount]));
  940. normalCount++;
  941. if (normalCount >= S3L_NORMAL_COMPUTE_MAXIMUM_AVERAGE)
  942. break;
  943. }
  944. }
  945. n.x = S3L_FRACTIONS_PER_UNIT;
  946. n.y = 0;
  947. n.z = 0;
  948. if (normalCount != 0)
  949. {
  950. // compute average
  951. n.x = 0;
  952. for (uint8_t i = 0; i < normalCount; ++i)
  953. {
  954. n.x += ns[i].x;
  955. n.y += ns[i].y;
  956. n.z += ns[i].z;
  957. }
  958. n.x /= normalCount;
  959. n.y /= normalCount;
  960. n.z /= normalCount;
  961. S3L_normalizeVec3(&n);
  962. }
  963. dst[vPos] = n.x;
  964. vPos++;
  965. dst[vPos] = n.y;
  966. vPos++;
  967. dst[vPos] = n.z;
  968. vPos++;
  969. }
  970. S3L_Mat4 m;
  971. S3L_makeWorldMatrix(model.transform,m);
  972. if (transformNormals)
  973. for (S3L_Index i = 0; i < model.vertexCount * 3; i += 3)
  974. {
  975. n.x = dst[i];
  976. n.y = dst[i + 1];
  977. n.z = dst[i + 2];
  978. S3L_vec4Xmat4(&n,m);
  979. dst[i] = n.x;
  980. dst[i + 1] = n.y;
  981. dst[i + 2] = n.z;
  982. }
  983. }
  984. void S3L_vec4Xmat4(S3L_Vec4 *v, S3L_Mat4 m)
  985. {
  986. S3L_Vec4 vBackup;
  987. vBackup.x = v->x;
  988. vBackup.y = v->y;
  989. vBackup.z = v->z;
  990. vBackup.w = v->w;
  991. #define dotCol(col)\
  992. ((vBackup.x * m[col][0]) +\
  993. (vBackup.y * m[col][1]) +\
  994. (vBackup.z * m[col][2]) +\
  995. (vBackup.w * m[col][3])) / S3L_FRACTIONS_PER_UNIT
  996. v->x = dotCol(0);
  997. v->y = dotCol(1);
  998. v->z = dotCol(2);
  999. v->w = dotCol(3);
  1000. }
  1001. void S3L_vec3Xmat4(S3L_Vec4 *v, S3L_Mat4 m)
  1002. {
  1003. S3L_Vec4 vBackup;
  1004. #undef dotCol
  1005. #define dotCol(col)\
  1006. (vBackup.x * m[col][0]) / S3L_FRACTIONS_PER_UNIT +\
  1007. (vBackup.y * m[col][1]) / S3L_FRACTIONS_PER_UNIT +\
  1008. (vBackup.z * m[col][2]) / S3L_FRACTIONS_PER_UNIT +\
  1009. m[col][3]
  1010. vBackup.x = v->x;
  1011. vBackup.y = v->y;
  1012. vBackup.z = v->z;
  1013. vBackup.w = v->w;
  1014. v->x = dotCol(0);
  1015. v->y = dotCol(1);
  1016. v->z = dotCol(2);
  1017. v->w = S3L_FRACTIONS_PER_UNIT;
  1018. }
  1019. #undef dotCol
  1020. S3L_Unit S3L_abs(S3L_Unit value)
  1021. {
  1022. return value * (((value >= 0) << 1) - 1);
  1023. }
  1024. S3L_Unit S3L_min(S3L_Unit v1, S3L_Unit v2)
  1025. {
  1026. return v1 >= v2 ? v2 : v1;
  1027. }
  1028. S3L_Unit S3L_max(S3L_Unit v1, S3L_Unit v2)
  1029. {
  1030. return v1 >= v2 ? v1 : v2;
  1031. }
  1032. S3L_Unit S3L_clamp(S3L_Unit v, S3L_Unit v1, S3L_Unit v2)
  1033. {
  1034. return v >= v1 ? (v <= v2 ? v : v2) : v1;
  1035. }
  1036. S3L_Unit S3L_zeroClamp(S3L_Unit value)
  1037. {
  1038. return (value * (value >= 0));
  1039. }
  1040. S3L_Unit S3L_wrap(S3L_Unit value, S3L_Unit mod)
  1041. {
  1042. return value >= 0 ? (value % mod) : (mod + (value % mod) - 1);
  1043. }
  1044. S3L_Unit S3L_nonZero(S3L_Unit value)
  1045. {
  1046. return (value + (value == 0));
  1047. }
  1048. S3L_Unit S3L_interpolate(S3L_Unit v1, S3L_Unit v2, S3L_Unit t, S3L_Unit tMax)
  1049. {
  1050. return v1 + ((v2 - v1) * t) / tMax;
  1051. }
  1052. S3L_Unit S3L_interpolateByUnit(S3L_Unit v1, S3L_Unit v2, S3L_Unit t)
  1053. {
  1054. return v1 + ((v2 - v1) * t) / S3L_FRACTIONS_PER_UNIT;
  1055. }
  1056. S3L_Unit S3L_interpolateByUnitFrom0(S3L_Unit v2, S3L_Unit t)
  1057. {
  1058. return (v2 * t) / S3L_FRACTIONS_PER_UNIT;
  1059. }
  1060. S3L_Unit S3L_interpolateFrom0(S3L_Unit v2, S3L_Unit t, S3L_Unit tMax)
  1061. {
  1062. return (v2 * t) / tMax;
  1063. }
  1064. S3L_Unit S3L_distanceManhattan(S3L_Vec4 a, S3L_Vec4 b)
  1065. {
  1066. return
  1067. S3L_abs(a.x - b.x) +
  1068. S3L_abs(a.y - b.y) +
  1069. S3L_abs(a.z - b.z);
  1070. }
  1071. void S3L_mat4Xmat4(S3L_Mat4 m1, S3L_Mat4 m2)
  1072. {
  1073. S3L_Mat4 mat1;
  1074. for (uint16_t row = 0; row < 4; ++row)
  1075. for (uint16_t col = 0; col < 4; ++col)
  1076. mat1[col][row] = m1[col][row];
  1077. for (uint16_t row = 0; row < 4; ++row)
  1078. for (uint16_t col = 0; col < 4; ++col)
  1079. {
  1080. m1[col][row] = 0;
  1081. for (uint16_t i = 0; i < 4; ++i)
  1082. m1[col][row] +=
  1083. (mat1[i][row] * m2[col][i]) / S3L_FRACTIONS_PER_UNIT;
  1084. }
  1085. }
  1086. S3L_Unit S3L_sin(S3L_Unit x)
  1087. {
  1088. x = S3L_wrap(x / S3L_SIN_TABLE_UNIT_STEP,S3L_SIN_TABLE_LENGTH * 4);
  1089. int8_t positive = 1;
  1090. if (x < S3L_SIN_TABLE_LENGTH)
  1091. {
  1092. }
  1093. else if (x < S3L_SIN_TABLE_LENGTH * 2)
  1094. {
  1095. x = S3L_SIN_TABLE_LENGTH * 2 - x - 1;
  1096. }
  1097. else if (x < S3L_SIN_TABLE_LENGTH * 3)
  1098. {
  1099. x = x - S3L_SIN_TABLE_LENGTH * 2;
  1100. positive = 0;
  1101. }
  1102. else
  1103. {
  1104. x = S3L_SIN_TABLE_LENGTH - (x - S3L_SIN_TABLE_LENGTH * 3) - 1;
  1105. positive = 0;
  1106. }
  1107. return positive ? S3L_sinTable[x] : -1 * S3L_sinTable[x];
  1108. }
  1109. S3L_Unit S3L_asin(S3L_Unit x)
  1110. {
  1111. x = S3L_clamp(x,-S3L_FRACTIONS_PER_UNIT,S3L_FRACTIONS_PER_UNIT);
  1112. int8_t sign = 1;
  1113. if (x < 0)
  1114. {
  1115. sign = -1;
  1116. x *= -1;
  1117. }
  1118. int16_t low = 0;
  1119. int16_t high = S3L_SIN_TABLE_LENGTH -1;
  1120. int16_t middle;
  1121. while (low <= high) // binary search
  1122. {
  1123. middle = (low + high) / 2;
  1124. S3L_Unit v = S3L_sinTable[middle];
  1125. if (v > x)
  1126. high = middle - 1;
  1127. else if (v < x)
  1128. low = middle + 1;
  1129. else
  1130. break;
  1131. }
  1132. middle *= S3L_SIN_TABLE_UNIT_STEP;
  1133. return sign * middle;
  1134. }
  1135. S3L_Unit S3L_cos(S3L_Unit x)
  1136. {
  1137. return S3L_sin(x + S3L_FRACTIONS_PER_UNIT / 4);
  1138. }
  1139. void S3L_correctBarycentricCoords(S3L_Unit barycentric[3])
  1140. {
  1141. barycentric[0] = S3L_clamp(barycentric[0],0,S3L_FRACTIONS_PER_UNIT);
  1142. barycentric[1] = S3L_clamp(barycentric[1],0,S3L_FRACTIONS_PER_UNIT);
  1143. S3L_Unit d = S3L_FRACTIONS_PER_UNIT - barycentric[0] - barycentric[1];
  1144. if (d < 0)
  1145. {
  1146. barycentric[0] += d;
  1147. barycentric[2] = 0;
  1148. }
  1149. else
  1150. barycentric[2] = d;
  1151. }
  1152. void S3L_makeTranslationMat(
  1153. S3L_Unit offsetX,
  1154. S3L_Unit offsetY,
  1155. S3L_Unit offsetZ,
  1156. S3L_Mat4 m)
  1157. {
  1158. #define M(x,y) m[x][y]
  1159. #define S S3L_FRACTIONS_PER_UNIT
  1160. M(0,0) = S; M(1,0) = 0; M(2,0) = 0; M(3,0) = 0;
  1161. M(0,1) = 0; M(1,1) = S; M(2,1) = 0; M(3,1) = 0;
  1162. M(0,2) = 0; M(1,2) = 0; M(2,2) = S; M(3,2) = 0;
  1163. M(0,3) = offsetX; M(1,3) = offsetY; M(2,3) = offsetZ; M(3,3) = S;
  1164. #undef M
  1165. #undef S
  1166. }
  1167. void S3L_makeScaleMatrix(
  1168. S3L_Unit scaleX,
  1169. S3L_Unit scaleY,
  1170. S3L_Unit scaleZ,
  1171. S3L_Mat4 m)
  1172. {
  1173. #define M(x,y) m[x][y]
  1174. M(0,0) = scaleX; M(1,0) = 0; M(2,0) = 0; M(3,0) = 0;
  1175. M(0,1) = 0; M(1,1) = scaleY; M(2,1) = 0; M(3,1) = 0;
  1176. M(0,2) = 0; M(1,2) = 0; M(2,2) = scaleZ; M(3,2) = 0;
  1177. M(0,3) = 0; M(1,3) = 0; M(2,3) = 0; M(3,3) = S3L_FRACTIONS_PER_UNIT;
  1178. #undef M
  1179. }
  1180. void S3L_makeRotationMatrixZXY(
  1181. S3L_Unit byX,
  1182. S3L_Unit byY,
  1183. S3L_Unit byZ,
  1184. S3L_Mat4 m)
  1185. {
  1186. byX *= -1;
  1187. byY *= -1;
  1188. byZ *= -1;
  1189. S3L_Unit sx = S3L_sin(byX);
  1190. S3L_Unit sy = S3L_sin(byY);
  1191. S3L_Unit sz = S3L_sin(byZ);
  1192. S3L_Unit cx = S3L_cos(byX);
  1193. S3L_Unit cy = S3L_cos(byY);
  1194. S3L_Unit cz = S3L_cos(byZ);
  1195. #define M(x,y) m[x][y]
  1196. #define S S3L_FRACTIONS_PER_UNIT
  1197. M(0,0) = (cy * cz) / S + (sy * sx * sz) / (S * S);
  1198. M(1,0) = (cx * sz) / S;
  1199. M(2,0) = (cy * sx * sz) / (S * S) - (cz * sy) / S;
  1200. M(3,0) = 0;
  1201. M(0,1) = (cz * sy * sx) / (S * S) - (cy * sz) / S;
  1202. M(1,1) = (cx * cz) / S;
  1203. M(2,1) = (cy * cz * sx) / (S * S) + (sy * sz) / S;
  1204. M(3,1) = 0;
  1205. M(0,2) = (cx * sy) / S;
  1206. M(1,2) = -1 * sx;
  1207. M(2,2) = (cy * cx) / S;
  1208. M(3,2) = 0;
  1209. M(0,3) = 0;
  1210. M(1,3) = 0;
  1211. M(2,3) = 0;
  1212. M(3,3) = S3L_FRACTIONS_PER_UNIT;
  1213. #undef M
  1214. #undef S
  1215. }
  1216. S3L_Unit S3L_sqrt(S3L_Unit value)
  1217. {
  1218. int8_t sign = 1;
  1219. if (value < 0)
  1220. {
  1221. sign = -1;
  1222. value *= -1;
  1223. }
  1224. uint32_t result = 0;
  1225. uint32_t a = value;
  1226. uint32_t b = 1u << 30;
  1227. while (b > a)
  1228. b >>= 2;
  1229. while (b != 0)
  1230. {
  1231. if (a >= result + b)
  1232. {
  1233. a -= result + b;
  1234. result = result + 2 * b;
  1235. }
  1236. b >>= 2;
  1237. result >>= 1;
  1238. }
  1239. return result * sign;
  1240. }
  1241. S3L_Unit S3L_vec3Length(S3L_Vec4 v)
  1242. {
  1243. return S3L_sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
  1244. }
  1245. S3L_Unit S3L_vec2Length(S3L_Vec4 v)
  1246. {
  1247. return S3L_sqrt(v.x * v.x + v.y * v.y);
  1248. }
  1249. void S3L_normalizeVec3(S3L_Vec4 *v)
  1250. {
  1251. #define SCALE 16
  1252. #define BOTTOM_LIMIT 16
  1253. #define UPPER_LIMIT 900
  1254. /* Here we try to decide if the vector is too small and would cause
  1255. inaccurate result due to very its inaccurate length. If so, we scale
  1256. it up. We can't scale up everything as big vectors overflow in length
  1257. calculations. */
  1258. if (
  1259. S3L_abs(v->x) <= BOTTOM_LIMIT &&
  1260. S3L_abs(v->y) <= BOTTOM_LIMIT &&
  1261. S3L_abs(v->z) <= BOTTOM_LIMIT)
  1262. {
  1263. v->x *= SCALE;
  1264. v->y *= SCALE;
  1265. v->z *= SCALE;
  1266. }
  1267. else if (
  1268. S3L_abs(v->x) > UPPER_LIMIT ||
  1269. S3L_abs(v->y) > UPPER_LIMIT ||
  1270. S3L_abs(v->z) > UPPER_LIMIT)
  1271. {
  1272. v->x /= SCALE;
  1273. v->y /= SCALE;
  1274. v->z /= SCALE;
  1275. }
  1276. #undef SCALE
  1277. #undef BOTTOM_LIMIT
  1278. #undef UPPER_LIMIT
  1279. S3L_Unit l = S3L_vec3Length(*v);
  1280. if (l == 0)
  1281. return;
  1282. v->x = (v->x * S3L_FRACTIONS_PER_UNIT) / l;
  1283. v->y = (v->y * S3L_FRACTIONS_PER_UNIT) / l;
  1284. v->z = (v->z * S3L_FRACTIONS_PER_UNIT) / l;
  1285. }
  1286. void S3L_normalizeVec3Fast(S3L_Vec4 *v)
  1287. {
  1288. S3L_Unit l = S3L_vec3Length(*v);
  1289. if (l == 0)
  1290. return;
  1291. v->x = (v->x * S3L_FRACTIONS_PER_UNIT) / l;
  1292. v->y = (v->y * S3L_FRACTIONS_PER_UNIT) / l;
  1293. v->z = (v->z * S3L_FRACTIONS_PER_UNIT) / l;
  1294. }
  1295. void S3L_initTransform3D(S3L_Transform3D *t)
  1296. {
  1297. S3L_initVec4(&(t->translation));
  1298. S3L_initVec4(&(t->rotation));
  1299. t->scale.x = S3L_FRACTIONS_PER_UNIT;
  1300. t->scale.y = S3L_FRACTIONS_PER_UNIT;
  1301. t->scale.z = S3L_FRACTIONS_PER_UNIT;
  1302. t->scale.w = 0;
  1303. }
  1304. /** Performs perspecive division (z-divide). Does NOT check for division by
  1305. zero. */
  1306. static inline void S3L_perspectiveDivide(S3L_Vec4 *vector,
  1307. S3L_Unit focalLength)
  1308. {
  1309. vector->x = (vector->x * focalLength) / vector->z;
  1310. vector->y = (vector->y * focalLength) / vector->z;
  1311. }
  1312. void project3DPointToScreen(
  1313. S3L_Vec4 point,
  1314. S3L_Camera camera,
  1315. S3L_Vec4 *result)
  1316. {
  1317. S3L_Mat4 m;
  1318. S3L_makeCameraMatrix(camera.transform,m);
  1319. S3L_Unit s = point.w;
  1320. point.w = S3L_FRACTIONS_PER_UNIT;
  1321. S3L_vec3Xmat4(&point,m);
  1322. point.z = S3L_nonZero(point.z);
  1323. S3L_perspectiveDivide(&point,camera.focalLength);
  1324. S3L_ScreenCoord x, y;
  1325. S3L_mapProjectionPlaneToScreen(point,&x,&y);
  1326. result->x = x;
  1327. result->y = y;
  1328. result->z = point.z;
  1329. result->w =
  1330. (point.z <= 0) ? 0 :
  1331. (
  1332. (s * camera.focalLength * S3L_RESOLUTION_X) /
  1333. (point.z * S3L_FRACTIONS_PER_UNIT)
  1334. );
  1335. }
  1336. void S3L_lookAt(S3L_Vec4 pointTo, S3L_Transform3D *t)
  1337. {
  1338. S3L_Vec4 v;
  1339. v.x = pointTo.x - t->translation.x;
  1340. v.y = pointTo.z - t->translation.z;
  1341. S3L_Unit dx = v.x;
  1342. S3L_Unit l = S3L_vec2Length(v);
  1343. dx = (v.x * S3L_FRACTIONS_PER_UNIT) / S3L_nonZero(l); // normalize
  1344. t->rotation.y = -1 * S3L_asin(dx);
  1345. if (v.y < 0)
  1346. t->rotation.y = S3L_FRACTIONS_PER_UNIT / 2 - t->rotation.y;
  1347. v.x = pointTo.y - t->translation.y;
  1348. v.y = l;
  1349. l = S3L_vec2Length(v);
  1350. dx = (v.x * S3L_FRACTIONS_PER_UNIT) / S3L_nonZero(l);
  1351. t->rotation.x = S3L_asin(dx);
  1352. }
  1353. void S3L_setTransform3D(
  1354. S3L_Unit tx,
  1355. S3L_Unit ty,
  1356. S3L_Unit tz,
  1357. S3L_Unit rx,
  1358. S3L_Unit ry,
  1359. S3L_Unit rz,
  1360. S3L_Unit sx,
  1361. S3L_Unit sy,
  1362. S3L_Unit sz,
  1363. S3L_Transform3D *t)
  1364. {
  1365. t->translation.x = tx;
  1366. t->translation.y = ty;
  1367. t->translation.z = tz;
  1368. t->rotation.x = rx;
  1369. t->rotation.y = ry;
  1370. t->rotation.z = rz;
  1371. t->scale.x = sx;
  1372. t->scale.y = sy;
  1373. t->scale.z = sz;
  1374. }
  1375. void S3L_initCamera(S3L_Camera *camera)
  1376. {
  1377. camera->focalLength = S3L_FRACTIONS_PER_UNIT;
  1378. S3L_initTransform3D(&(camera->transform));
  1379. }
  1380. void S3L_rotationToDirections(
  1381. S3L_Vec4 rotation,
  1382. S3L_Unit length,
  1383. S3L_Vec4 *forw,
  1384. S3L_Vec4 *right,
  1385. S3L_Vec4 *up)
  1386. {
  1387. S3L_Mat4 m;
  1388. S3L_makeRotationMatrixZXY(rotation.x,rotation.y,rotation.z,m);
  1389. if (forw != 0)
  1390. {
  1391. forw->x = 0;
  1392. forw->y = 0;
  1393. forw->z = length;
  1394. S3L_vec3Xmat4(forw,m);
  1395. }
  1396. if (right != 0)
  1397. {
  1398. right->x = length;
  1399. right->y = 0;
  1400. right->z = 0;
  1401. S3L_vec3Xmat4(right,m);
  1402. }
  1403. if (up != 0)
  1404. {
  1405. up->x = 0;
  1406. up->y = length;
  1407. up->z = 0;
  1408. S3L_vec3Xmat4(up,m);
  1409. }
  1410. }
  1411. void S3L_initPixelInfo(S3L_PixelInfo *p)
  1412. {
  1413. p->x = 0;
  1414. p->y = 0;
  1415. p->barycentric[0] = S3L_FRACTIONS_PER_UNIT;
  1416. p->barycentric[1] = 0;
  1417. p->barycentric[2] = 0;
  1418. p->modelIndex = 0;
  1419. p->triangleIndex = 0;
  1420. p->triangleID = 0;
  1421. p->depth = 0;
  1422. p->previousZ = 0;
  1423. }
  1424. void S3L_initModel3D(
  1425. const S3L_Unit *vertices,
  1426. S3L_Index vertexCount,
  1427. const S3L_Index *triangles,
  1428. S3L_Index triangleCount,
  1429. S3L_Model3D *model)
  1430. {
  1431. model->vertices = vertices;
  1432. model->vertexCount = vertexCount;
  1433. model->triangles = triangles;
  1434. model->triangleCount = triangleCount;
  1435. model->customTransformMatrix = 0;
  1436. S3L_initTransform3D(&(model->transform));
  1437. S3L_initDrawConfig(&(model->config));
  1438. }
  1439. void S3L_initScene(
  1440. S3L_Model3D *models,
  1441. S3L_Index modelCount,
  1442. S3L_Scene *scene)
  1443. {
  1444. scene->models = models;
  1445. scene->modelCount = modelCount;
  1446. S3L_initCamera(&(scene->camera));
  1447. }
  1448. void S3L_initDrawConfig(S3L_DrawConfig *config)
  1449. {
  1450. config->backfaceCulling = 2;
  1451. config->visible = 1;
  1452. }
  1453. #ifndef S3L_PIXEL_FUNCTION
  1454. #error Pixel rendering function (S3L_PIXEL_FUNCTION) not specified!
  1455. #endif
  1456. static inline void S3L_PIXEL_FUNCTION(S3L_PixelInfo *pixel); // forward decl
  1457. /** Serves to accelerate linear interpolation for performance-critical
  1458. code. Functions such as S3L_interpolate require division to compute each
  1459. interpolated value, while S3L_FastLerpState only requires a division for
  1460. the initiation and a shift for retrieving each interpolated value.
  1461. S3L_FastLerpState stores a value and a step, both scaled (shifted by
  1462. S3L_FAST_LERP_QUALITY) to increase precision. The step is being added to the
  1463. value, which achieves the interpolation. This will only be useful for
  1464. interpolations in which we need to get the interpolated value in every step.
  1465. BEWARE! Shifting a negative value is undefined, so handling shifting of
  1466. negative values has to be done cleverly. */
  1467. typedef struct
  1468. {
  1469. S3L_Unit valueScaled;
  1470. S3L_Unit stepScaled;
  1471. } S3L_FastLerpState;
  1472. #define S3L_getFastLerpValue(state)\
  1473. (state.valueScaled >> S3L_FAST_LERP_QUALITY)
  1474. #define S3L_stepFastLerp(state)\
  1475. state.valueScaled += state.stepScaled
  1476. static inline S3L_Unit S3L_interpolateBarycentric(
  1477. S3L_Unit value0,
  1478. S3L_Unit value1,
  1479. S3L_Unit value2,
  1480. S3L_Unit barycentric[3])
  1481. {
  1482. return
  1483. (
  1484. (value0 * barycentric[0]) +
  1485. (value1 * barycentric[1]) +
  1486. (value2 * barycentric[2])
  1487. ) / S3L_FRACTIONS_PER_UNIT;
  1488. }
  1489. void S3L_mapProjectionPlaneToScreen(
  1490. S3L_Vec4 point,
  1491. S3L_ScreenCoord *screenX,
  1492. S3L_ScreenCoord *screenY)
  1493. {
  1494. *screenX =
  1495. S3L_HALF_RESOLUTION_X +
  1496. (point.x * S3L_HALF_RESOLUTION_X) / S3L_FRACTIONS_PER_UNIT;
  1497. *screenY =
  1498. S3L_HALF_RESOLUTION_Y -
  1499. (point.y * S3L_HALF_RESOLUTION_X) / S3L_FRACTIONS_PER_UNIT;
  1500. }
  1501. void S3L_zBufferClear(void)
  1502. {
  1503. #if S3L_Z_BUFFER
  1504. for (uint32_t i = 0; i < S3L_RESOLUTION_X * S3L_RESOLUTION_Y; ++i)
  1505. S3L_zBuffer[i] = S3L_MAX_DEPTH;
  1506. #endif
  1507. }
  1508. void S3L_stencilBufferClear(void)
  1509. {
  1510. #if S3L_STENCIL_BUFFER
  1511. for (uint32_t i = 0; i < S3L_STENCIL_BUFFER_SIZE; ++i)
  1512. S3L_stencilBuffer[i] = 0;
  1513. #endif
  1514. }
  1515. void S3L_newFrame(void)
  1516. {
  1517. S3L_zBufferClear();
  1518. S3L_stencilBufferClear();
  1519. }
  1520. void S3L_drawTriangle(
  1521. S3L_Vec4 point0,
  1522. S3L_Vec4 point1,
  1523. S3L_Vec4 point2,
  1524. S3L_Index modelIndex,
  1525. S3L_Index triangleIndex)
  1526. {
  1527. S3L_PixelInfo p;
  1528. S3L_initPixelInfo(&p);
  1529. p.modelIndex = modelIndex;
  1530. p.triangleIndex = triangleIndex;
  1531. p.triangleID = (modelIndex << 16) | triangleIndex;
  1532. S3L_Vec4 *tPointSS, *lPointSS, *rPointSS; /* points in Screen Space (in
  1533. S3L_Units, normalized by
  1534. S3L_FRACTIONS_PER_UNIT) */
  1535. S3L_Unit *barycentric0; // bar. coord that gets higher from L to R
  1536. S3L_Unit *barycentric1; // bar. coord that gets higher from R to L
  1537. S3L_Unit *barycentric2; // bar. coord that gets higher from bottom up
  1538. // sort the vertices:
  1539. #define assignPoints(t,a,b)\
  1540. {\
  1541. tPointSS = &point##t;\
  1542. barycentric2 = &(p.barycentric[t]);\
  1543. if (S3L_triangleWinding(point##t.x,point##t.y,point##a.x,point##a.y,\
  1544. point##b.x,point##b.y) >= 0)\
  1545. {\
  1546. lPointSS = &point##a; rPointSS = &point##b;\
  1547. barycentric0 = &(p.barycentric[b]);\
  1548. barycentric1 = &(p.barycentric[a]);\
  1549. }\
  1550. else\
  1551. {\
  1552. lPointSS = &point##b; rPointSS = &point##a;\
  1553. barycentric0 = &(p.barycentric[a]);\
  1554. barycentric1 = &(p.barycentric[b]);\
  1555. }\
  1556. }
  1557. if (point0.y <= point1.y)
  1558. {
  1559. if (point0.y <= point2.y)
  1560. assignPoints(0,1,2)
  1561. else
  1562. assignPoints(2,0,1)
  1563. }
  1564. else
  1565. {
  1566. if (point1.y <= point2.y)
  1567. assignPoints(1,0,2)
  1568. else
  1569. assignPoints(2,0,1)
  1570. }
  1571. #undef assignPoints
  1572. #if S3L_FLAT
  1573. *barycentric0 = S3L_FRACTIONS_PER_UNIT / 3;
  1574. *barycentric1 = S3L_FRACTIONS_PER_UNIT / 3;
  1575. *barycentric2 = S3L_FRACTIONS_PER_UNIT - 2 * (S3L_FRACTIONS_PER_UNIT / 3);
  1576. #endif
  1577. p.triangleSize[0] = rPointSS->x - lPointSS->x;
  1578. p.triangleSize[1] =
  1579. (rPointSS->y > lPointSS->y ? rPointSS->y : lPointSS->y) - tPointSS->y;
  1580. // now draw the triangle line by line:
  1581. S3L_ScreenCoord splitY; // Y of the vertically middle point of the triangle
  1582. S3L_ScreenCoord endY; // bottom Y of the whole triangle
  1583. int splitOnLeft; /* whether splitY is the y coord. of left or right
  1584. point */
  1585. if (rPointSS->y <= lPointSS->y)
  1586. {
  1587. splitY = rPointSS->y;
  1588. splitOnLeft = 0;
  1589. endY = lPointSS->y;
  1590. }
  1591. else
  1592. {
  1593. splitY = lPointSS->y;
  1594. splitOnLeft = 1;
  1595. endY = rPointSS->y;
  1596. }
  1597. S3L_ScreenCoord currentY = tPointSS->y;
  1598. /* We'll be using an algorithm similar to Bresenham line algorithm. The
  1599. specifics of this algorithm are among others:
  1600. - drawing possibly NON-CONTINUOUS line
  1601. - NOT tracing the line exactly, but rather rasterizing one the right
  1602. side of it, according to the pixel CENTERS, INCLUDING the pixel
  1603. centers
  1604. The principle is this:
  1605. - Move vertically by pixels and accumulate the error (abs(dx/dy)).
  1606. - If the error is greater than one (crossed the next pixel center), keep
  1607. moving horizontally and substracting 1 from the error until it is less
  1608. than 1 again.
  1609. - To make this INTEGER ONLY, scale the case so that distance between
  1610. pixels is equal to dy (instead of 1). This way the error becomes
  1611. dx/dy * dy == dx, and we're comparing the error to (and potentially
  1612. substracting) 1 * dy == dy. */
  1613. int16_t
  1614. /* triangle side:
  1615. left right */
  1616. lX, rX, // current x position on the screen
  1617. lDx, rDx, // dx (end point - start point)
  1618. lDy, rDy, // dy (end point - start point)
  1619. lInc, rInc, // direction in which to increment (1 or -1)
  1620. lErr, rErr, // current error (Bresenham)
  1621. lErrCmp, rErrCmp, // helper for deciding comparison (> vs >=)
  1622. lErrAdd, rErrAdd, // error value to add in each Bresenham cycle
  1623. lErrSub, rErrSub; // error value to substract when moving in x direction
  1624. S3L_FastLerpState lSideFLS, rSideFLS;
  1625. #if S3L_COMPUTE_LERP_DEPTH
  1626. S3L_FastLerpState lDepthFLS, rDepthFLS;
  1627. #define initDepthFLS(s,p1,p2)\
  1628. s##DepthFLS.valueScaled = p1##PointSS->z << S3L_FAST_LERP_QUALITY;\
  1629. s##DepthFLS.stepScaled = ((p2##PointSS->z << S3L_FAST_LERP_QUALITY) -\
  1630. s##DepthFLS.valueScaled) / (s##Dy != 0 ? s##Dy : 1);
  1631. #else
  1632. #define initDepthFLS(s,p1,p2) ;
  1633. #endif
  1634. /* init side for the algorithm, params:
  1635. s - which side (l or r)
  1636. p1 - point from (t, l or r)
  1637. p2 - point to (t, l or r)
  1638. down - whether the side coordinate goes top-down or vice versa */
  1639. #define initSide(s,p1,p2,down)\
  1640. s##X = p1##PointSS->x;\
  1641. s##Dx = p2##PointSS->x - p1##PointSS->x;\
  1642. s##Dy = p2##PointSS->y - p1##PointSS->y;\
  1643. initDepthFLS(s,p1,p2)\
  1644. s##SideFLS.stepScaled = (S3L_FRACTIONS_PER_UNIT << S3L_FAST_LERP_QUALITY)\
  1645. / (s##Dy != 0 ? s##Dy : 1);\
  1646. s##SideFLS.valueScaled = 0;\
  1647. if (!down)\
  1648. {\
  1649. s##SideFLS.valueScaled =\
  1650. S3L_FRACTIONS_PER_UNIT << S3L_FAST_LERP_QUALITY;\
  1651. s##SideFLS.stepScaled *= -1;\
  1652. }\
  1653. s##Inc = s##Dx >= 0 ? 1 : -1;\
  1654. if (s##Dx < 0)\
  1655. {s##Err = 0; s##ErrCmp = 0;}\
  1656. else\
  1657. {s##Err = s##Dy; s##ErrCmp = 1;}\
  1658. s##ErrAdd = S3L_abs(s##Dx);\
  1659. s##ErrSub = s##Dy != 0 ? s##Dy : 1; /* don't allow 0, could lead to an
  1660. infinite substracting loop */
  1661. #define stepSide(s)\
  1662. while (s##Err - s##Dy >= s##ErrCmp)\
  1663. {\
  1664. s##X += s##Inc;\
  1665. s##Err -= s##ErrSub;\
  1666. }\
  1667. s##Err += s##ErrAdd;
  1668. initSide(r,t,r,1)
  1669. initSide(l,t,l,1)
  1670. #if S3L_PERSPECTIVE_CORRECTION
  1671. /* PC is done by linearly interpolating reciprocals from which the corrected
  1672. velues can be computed. See
  1673. http://www.lysator.liu.se/~mikaelk/doc/perspectivetexture/ */
  1674. #if S3L_PERSPECTIVE_CORRECTION == 1
  1675. #define Z_RECIP_NUMERATOR\
  1676. (S3L_FRACTIONS_PER_UNIT * S3L_FRACTIONS_PER_UNIT * S3L_FRACTIONS_PER_UNIT)
  1677. #elif S3L_PERSPECTIVE_CORRECTION == 2
  1678. #define Z_RECIP_NUMERATOR\
  1679. (S3L_FRACTIONS_PER_UNIT * S3L_FRACTIONS_PER_UNIT)
  1680. #endif
  1681. /* ^ This numerator is a number by which we divide values for the
  1682. reciprocals. For PC == 2 it has to be lower because linear interpolation
  1683. scaling would make it overflow -- this results in lower depth precision
  1684. in bigger distance for PC == 2. */
  1685. S3L_Unit
  1686. tPointRecipZ, lPointRecipZ, rPointRecipZ, /* Reciprocals of the depth of
  1687. each triangle point. */
  1688. lRecip0, lRecip1, rRecip0, rRecip1; /* Helper variables for swapping
  1689. the above after split. */
  1690. tPointRecipZ = Z_RECIP_NUMERATOR / S3L_nonZero(tPointSS->z);
  1691. lPointRecipZ = Z_RECIP_NUMERATOR / S3L_nonZero(lPointSS->z);
  1692. rPointRecipZ = Z_RECIP_NUMERATOR / S3L_nonZero(rPointSS->z);
  1693. lRecip0 = tPointRecipZ;
  1694. lRecip1 = lPointRecipZ;
  1695. rRecip0 = tPointRecipZ;
  1696. rRecip1 = rPointRecipZ;
  1697. #define manageSplitPerspective(b0,b1)\
  1698. b1##Recip0 = b0##PointRecipZ;\
  1699. b1##Recip1 = b1##PointRecipZ;\
  1700. b0##Recip0 = b0##PointRecipZ;\
  1701. b0##Recip1 = tPointRecipZ;
  1702. #else
  1703. #define manageSplitPerspective(b0,b1) ;
  1704. #endif
  1705. // clip to the screen in y dimension:
  1706. endY = S3L_min(endY,S3L_RESOLUTION_Y);
  1707. /* Clipping above the screen (y < 0) can't be easily done here, will be
  1708. handled inside the loop. */
  1709. while (currentY < endY) /* draw the triangle from top to bottom -- the
  1710. bottom-most row is left out because, following
  1711. from the rasterization rules (see start of the
  1712. file), it is to never be rasterized. */
  1713. {
  1714. if (currentY == splitY) // reached a vertical split of the triangle?
  1715. {
  1716. #define manageSplit(b0,b1,s0,s1)\
  1717. S3L_Unit *tmp = barycentric##b0;\
  1718. barycentric##b0 = barycentric##b1;\
  1719. barycentric##b1 = tmp;\
  1720. s0##SideFLS.valueScaled = (S3L_FRACTIONS_PER_UNIT\
  1721. << S3L_FAST_LERP_QUALITY) - s0##SideFLS.valueScaled;\
  1722. s0##SideFLS.stepScaled *= -1;\
  1723. manageSplitPerspective(s0,s1)
  1724. if (splitOnLeft)
  1725. {
  1726. initSide(l,l,r,0);
  1727. manageSplit(0,2,r,l)
  1728. }
  1729. else
  1730. {
  1731. initSide(r,r,l,0);
  1732. manageSplit(1,2,l,r)
  1733. }
  1734. }
  1735. stepSide(r)
  1736. stepSide(l)
  1737. if (currentY >= 0) /* clipping of pixels whose y < 0 (can't be easily done
  1738. outside the loop because of the Bresenham-like
  1739. algorithm steps) */
  1740. {
  1741. p.y = currentY;
  1742. // draw the horizontal line
  1743. #if !S3L_FLAT
  1744. S3L_Unit rowLength = S3L_nonZero(rX - lX - 1); // prevent zero div
  1745. #if S3L_PERSPECTIVE_CORRECTION
  1746. S3L_Unit lOverZ, lRecipZ, rOverZ, rRecipZ, lT, rT;
  1747. lT = S3L_getFastLerpValue(lSideFLS);
  1748. rT = S3L_getFastLerpValue(rSideFLS);
  1749. lOverZ = S3L_interpolateByUnitFrom0(lRecip1,lT);
  1750. lRecipZ = S3L_interpolateByUnit(lRecip0,lRecip1,lT);
  1751. rOverZ = S3L_interpolateByUnitFrom0(rRecip1,rT);
  1752. rRecipZ = S3L_interpolateByUnit(rRecip0,rRecip1,rT);
  1753. #else
  1754. S3L_FastLerpState b0FLS, b1FLS;
  1755. #if S3L_COMPUTE_LERP_DEPTH
  1756. S3L_FastLerpState depthFLS;
  1757. depthFLS.valueScaled = lDepthFLS.valueScaled;
  1758. depthFLS.stepScaled =
  1759. (rDepthFLS.valueScaled - lDepthFLS.valueScaled) / rowLength;
  1760. #endif
  1761. b0FLS.valueScaled = 0;
  1762. b1FLS.valueScaled = lSideFLS.valueScaled;
  1763. b0FLS.stepScaled = rSideFLS.valueScaled / rowLength;
  1764. b1FLS.stepScaled = -1 * lSideFLS.valueScaled / rowLength;
  1765. #endif
  1766. #endif
  1767. // clip to the screen in x dimension:
  1768. S3L_ScreenCoord rXClipped = S3L_min(rX,S3L_RESOLUTION_X),
  1769. lXClipped = lX;
  1770. if (lXClipped < 0)
  1771. {
  1772. lXClipped = 0;
  1773. #if !S3L_PERSPECTIVE_CORRECTION && !S3L_FLAT
  1774. b0FLS.valueScaled -= lX * b0FLS.stepScaled;
  1775. b1FLS.valueScaled -= lX * b1FLS.stepScaled;
  1776. #if S3L_COMPUTE_LERP_DEPTH
  1777. depthFLS.valueScaled -= lX * depthFLS.stepScaled;
  1778. #endif
  1779. #endif
  1780. }
  1781. #if S3L_PERSPECTIVE_CORRECTION
  1782. S3L_ScreenCoord i = lXClipped - lX; /* helper var to save one
  1783. substraction in the inner
  1784. loop */
  1785. #endif
  1786. #if S3L_PERSPECTIVE_CORRECTION == 2
  1787. S3L_FastLerpState
  1788. depthPC, // interpolates depth between row segments
  1789. b0PC, // interpolates barycentric0 between row segments
  1790. b1PC; // interpolates barycentric1 between row segments
  1791. /* ^ These interpolate values between row segments (lines of pixels
  1792. of S3L_PC_APPROX_LENGTH length). After each row segment perspective
  1793. correction is recomputed. */
  1794. depthPC.valueScaled =
  1795. (Z_RECIP_NUMERATOR /
  1796. S3L_nonZero(S3L_interpolate(lRecipZ,rRecipZ,i,rowLength)))
  1797. << S3L_FAST_LERP_QUALITY;
  1798. b0PC.valueScaled =
  1799. (
  1800. S3L_interpolateFrom0(rOverZ,i,rowLength)
  1801. * depthPC.valueScaled
  1802. ) / (Z_RECIP_NUMERATOR / S3L_FRACTIONS_PER_UNIT);
  1803. b1PC.valueScaled =
  1804. (
  1805. (lOverZ - S3L_interpolateFrom0(lOverZ,i,rowLength))
  1806. * depthPC.valueScaled
  1807. ) / (Z_RECIP_NUMERATOR / S3L_FRACTIONS_PER_UNIT);
  1808. int8_t rowCount = S3L_PC_APPROX_LENGTH;
  1809. #endif
  1810. #if S3L_Z_BUFFER
  1811. uint32_t zBufferIndex = p.y * S3L_RESOLUTION_X + lXClipped;
  1812. #endif
  1813. // draw the row -- inner loop:
  1814. for (S3L_ScreenCoord x = lXClipped; x < rXClipped; ++x)
  1815. {
  1816. int8_t testsPassed = 1;
  1817. #if S3L_STENCIL_BUFFER
  1818. if (!S3L_stencilTest(x,p.y))
  1819. testsPassed = 0;
  1820. #endif
  1821. p.x = x;
  1822. #if S3L_COMPUTE_DEPTH
  1823. #if S3L_PERSPECTIVE_CORRECTION == 1
  1824. p.depth = Z_RECIP_NUMERATOR /
  1825. S3L_nonZero(S3L_interpolate(lRecipZ,rRecipZ,i,rowLength));
  1826. #elif S3L_PERSPECTIVE_CORRECTION == 2
  1827. if (rowCount >= S3L_PC_APPROX_LENGTH)
  1828. {
  1829. // init the linear interpolation to the next PC correct value
  1830. rowCount = 0;
  1831. S3L_Unit nextI = i + S3L_PC_APPROX_LENGTH;
  1832. if (nextI < rowLength)
  1833. {
  1834. S3L_Unit nextDepthScaled =
  1835. (
  1836. Z_RECIP_NUMERATOR /
  1837. S3L_nonZero(S3L_interpolate(lRecipZ,rRecipZ,nextI,rowLength))
  1838. ) << S3L_FAST_LERP_QUALITY;
  1839. depthPC.stepScaled =
  1840. (nextDepthScaled - depthPC.valueScaled) / S3L_PC_APPROX_LENGTH;
  1841. S3L_Unit nextValue =
  1842. (
  1843. S3L_interpolateFrom0(rOverZ,nextI,rowLength)
  1844. * nextDepthScaled
  1845. ) / (Z_RECIP_NUMERATOR / S3L_FRACTIONS_PER_UNIT);
  1846. b0PC.stepScaled =
  1847. (nextValue - b0PC.valueScaled) / S3L_PC_APPROX_LENGTH;
  1848. nextValue =
  1849. (
  1850. (lOverZ - S3L_interpolateFrom0(lOverZ,nextI,rowLength))
  1851. * nextDepthScaled
  1852. ) / (Z_RECIP_NUMERATOR / S3L_FRACTIONS_PER_UNIT);
  1853. b1PC.stepScaled =
  1854. (nextValue - b1PC.valueScaled) / S3L_PC_APPROX_LENGTH;
  1855. }
  1856. else
  1857. {
  1858. /* A special case where we'd be interpolating outside the triangle.
  1859. It seems like a valid approach at first, but it creates a bug
  1860. in a case when the rasaterized triangle is near screen 0 and can
  1861. actually never reach the extrapolated screen position. So we
  1862. have to clamp to the actual end of the triangle here. */
  1863. S3L_Unit maxI = S3L_nonZero(rowLength - i);
  1864. S3L_Unit nextDepthScaled =
  1865. (
  1866. Z_RECIP_NUMERATOR /
  1867. S3L_nonZero(rRecipZ)
  1868. ) << S3L_FAST_LERP_QUALITY;
  1869. depthPC.stepScaled =
  1870. (nextDepthScaled - depthPC.valueScaled) / maxI;
  1871. S3L_Unit nextValue =
  1872. (
  1873. rOverZ
  1874. * nextDepthScaled
  1875. ) / (Z_RECIP_NUMERATOR / S3L_FRACTIONS_PER_UNIT);
  1876. b0PC.stepScaled =
  1877. (nextValue - b0PC.valueScaled) / maxI;
  1878. b1PC.stepScaled =
  1879. -1 * b1PC.valueScaled / maxI;
  1880. }
  1881. }
  1882. p.depth = S3L_getFastLerpValue(depthPC);
  1883. #else
  1884. p.depth = S3L_getFastLerpValue(depthFLS);
  1885. S3L_stepFastLerp(depthFLS);
  1886. #endif
  1887. #else // !S3L_COMPUTE_DEPTH
  1888. p.depth = (tPointSS->z + lPointSS->z + rPointSS->z) / 3;
  1889. #endif
  1890. #if S3L_Z_BUFFER
  1891. p.previousZ = S3L_zBuffer[zBufferIndex];
  1892. zBufferIndex++;
  1893. if (!S3L_zTest(p.x,p.y,p.depth))
  1894. testsPassed = 0;
  1895. #endif
  1896. if (testsPassed)
  1897. {
  1898. #if !S3L_FLAT
  1899. #if S3L_PERSPECTIVE_CORRECTION == 0
  1900. *barycentric0 = S3L_getFastLerpValue(b0FLS);
  1901. *barycentric1 = S3L_getFastLerpValue(b1FLS);
  1902. #elif S3L_PERSPECTIVE_CORRECTION == 1
  1903. *barycentric0 =
  1904. (
  1905. S3L_interpolateFrom0(rOverZ,i,rowLength)
  1906. * p.depth
  1907. ) / (Z_RECIP_NUMERATOR / S3L_FRACTIONS_PER_UNIT);
  1908. *barycentric1 =
  1909. (
  1910. (lOverZ - S3L_interpolateFrom0(lOverZ,i,rowLength))
  1911. * p.depth
  1912. ) / (Z_RECIP_NUMERATOR / S3L_FRACTIONS_PER_UNIT);
  1913. #elif S3L_PERSPECTIVE_CORRECTION == 2
  1914. *barycentric0 = S3L_getFastLerpValue(b0PC);
  1915. *barycentric1 = S3L_getFastLerpValue(b1PC);
  1916. #endif
  1917. *barycentric2 =
  1918. S3L_FRACTIONS_PER_UNIT - *barycentric0 - *barycentric1;
  1919. #endif
  1920. S3L_PIXEL_FUNCTION(&p);
  1921. } // tests passed
  1922. #if !S3L_FLAT
  1923. #if S3L_PERSPECTIVE_CORRECTION
  1924. i++;
  1925. #if S3L_PERSPECTIVE_CORRECTION == 2
  1926. rowCount++;
  1927. S3L_stepFastLerp(depthPC);
  1928. S3L_stepFastLerp(b0PC);
  1929. S3L_stepFastLerp(b1PC);
  1930. #endif
  1931. #else
  1932. S3L_stepFastLerp(b0FLS);
  1933. S3L_stepFastLerp(b1FLS);
  1934. #endif
  1935. #endif
  1936. } // inner loop
  1937. } // y clipping
  1938. #if !S3L_FLAT
  1939. S3L_stepFastLerp(lSideFLS);
  1940. S3L_stepFastLerp(rSideFLS);
  1941. #if S3L_COMPUTE_LERP_DEPTH
  1942. S3L_stepFastLerp(lDepthFLS);
  1943. S3L_stepFastLerp(rDepthFLS);
  1944. #endif
  1945. #endif
  1946. ++currentY;
  1947. } // row drawing
  1948. #undef manageSplit
  1949. #undef initPC
  1950. #undef initSide
  1951. #undef stepSide
  1952. #undef Z_RECIP_NUMERATOR
  1953. }
  1954. void S3L_rotate2DPoint(S3L_Unit *x, S3L_Unit *y, S3L_Unit angle)
  1955. {
  1956. if (angle < S3L_SIN_TABLE_UNIT_STEP)
  1957. return; // no visible rotation
  1958. S3L_Unit angleSin = S3L_sin(angle);
  1959. S3L_Unit angleCos = S3L_cos(angle);
  1960. S3L_Unit xBackup = *x;
  1961. *x =
  1962. (angleCos * (*x)) / S3L_FRACTIONS_PER_UNIT -
  1963. (angleSin * (*y)) / S3L_FRACTIONS_PER_UNIT;
  1964. *y =
  1965. (angleSin * xBackup) / S3L_FRACTIONS_PER_UNIT +
  1966. (angleCos * (*y)) / S3L_FRACTIONS_PER_UNIT;
  1967. }
  1968. void S3L_makeWorldMatrix(S3L_Transform3D worldTransform, S3L_Mat4 m)
  1969. {
  1970. S3L_makeScaleMatrix(
  1971. worldTransform.scale.x,
  1972. worldTransform.scale.y,
  1973. worldTransform.scale.z,
  1974. m);
  1975. S3L_Mat4 t;
  1976. S3L_makeRotationMatrixZXY(
  1977. worldTransform.rotation.x,
  1978. worldTransform.rotation.y,
  1979. worldTransform.rotation.z,
  1980. t);
  1981. S3L_mat4Xmat4(m,t);
  1982. S3L_makeTranslationMat(
  1983. worldTransform.translation.x,
  1984. worldTransform.translation.y,
  1985. worldTransform.translation.z,
  1986. t);
  1987. S3L_mat4Xmat4(m,t);
  1988. }
  1989. void S3L_transposeMat4(S3L_Mat4 m)
  1990. {
  1991. S3L_Unit tmp;
  1992. for (uint8_t y = 0; y < 3; ++y)
  1993. for (uint8_t x = 1 + y; x < 4; ++x)
  1994. {
  1995. tmp = m[x][y];
  1996. m[x][y] = m[y][x];
  1997. m[y][x] = tmp;
  1998. }
  1999. }
  2000. void S3L_makeCameraMatrix(S3L_Transform3D cameraTransform, S3L_Mat4 m)
  2001. {
  2002. S3L_makeTranslationMat(
  2003. -1 * cameraTransform.translation.x,
  2004. -1 * cameraTransform.translation.y,
  2005. -1 * cameraTransform.translation.z,
  2006. m);
  2007. S3L_Mat4 r;
  2008. S3L_makeRotationMatrixZXY(
  2009. cameraTransform.rotation.x,
  2010. cameraTransform.rotation.y,
  2011. cameraTransform.rotation.z,
  2012. r);
  2013. S3L_transposeMat4(r); // transposing creates an inverse transform
  2014. S3L_mat4Xmat4(m,r);
  2015. }
  2016. int8_t S3L_triangleWinding(
  2017. S3L_ScreenCoord x0,
  2018. S3L_ScreenCoord y0,
  2019. S3L_ScreenCoord x1,
  2020. S3L_ScreenCoord y1,
  2021. S3L_ScreenCoord x2,
  2022. S3L_ScreenCoord y2)
  2023. {
  2024. int32_t winding =
  2025. (y1 - y0) * (x2 - x1) - (x1 - x0) * (y2 - y1);
  2026. // ^ cross product for points with z == 0
  2027. return winding > 0 ? 1 : (winding < 0 ? -1 : 0);
  2028. }
  2029. /**
  2030. Checks if given triangle (in Screen Space) is at least partially visible,
  2031. i.e. returns false if the triangle is either completely outside the frustum
  2032. (left, right, top, bottom, near) or is invisible due to backface culling.
  2033. */
  2034. static inline int8_t S3L_triangleIsVisible(
  2035. S3L_Vec4 p0,
  2036. S3L_Vec4 p1,
  2037. S3L_Vec4 p2,
  2038. uint8_t backfaceCulling)
  2039. {
  2040. #define clipTest(c,cmp,v)\
  2041. (p0.c cmp (v) && p1.c cmp (v) && p2.c cmp (v))
  2042. if ( // outside frustum?
  2043. #if S3L_NEAR_CROSS_STRATEGY == 0
  2044. p0.z <= S3L_NEAR || p1.z <= S3L_NEAR || p2.z <= S3L_NEAR ||
  2045. // ^ partially in front of NEAR?
  2046. #else
  2047. clipTest(z,<=,S3L_NEAR) || // completely in front of NEAR?
  2048. #endif
  2049. clipTest(x,<,0) ||
  2050. clipTest(x,>=,S3L_RESOLUTION_X) ||
  2051. clipTest(y,<,0) ||
  2052. clipTest(y,>,S3L_RESOLUTION_Y)
  2053. )
  2054. return 0;
  2055. #undef clipTest
  2056. if (backfaceCulling != 0)
  2057. {
  2058. int8_t winding =
  2059. S3L_triangleWinding(p0.x,p0.y,p1.x,p1.y,p2.x,p2.y);
  2060. if ((backfaceCulling == 1 && winding > 0) ||
  2061. (backfaceCulling == 2 && winding < 0))
  2062. return 0;
  2063. }
  2064. return 1;
  2065. }
  2066. #if S3L_SORT != 0
  2067. typedef struct
  2068. {
  2069. uint8_t modelIndex;
  2070. S3L_Index triangleIndex;
  2071. uint16_t sortValue;
  2072. } _S3L_TriangleToSort;
  2073. _S3L_TriangleToSort S3L_sortArray[S3L_MAX_TRIANGES_DRAWN];
  2074. uint16_t S3L_sortArrayLength;
  2075. #endif
  2076. void _S3L_projectVertex(
  2077. const S3L_Model3D *model,
  2078. S3L_Index triangleIndex,
  2079. uint8_t vertex,
  2080. S3L_Mat4 projectionMatrix,
  2081. S3L_Vec4 *result)
  2082. {
  2083. uint32_t vertexIndex = model->triangles[triangleIndex * 3 + vertex] * 3;
  2084. result->x = model->vertices[vertexIndex];
  2085. result->y = model->vertices[vertexIndex + 1];
  2086. result->z = model->vertices[vertexIndex + 2];
  2087. result->w = S3L_FRACTIONS_PER_UNIT; // needed for translation
  2088. S3L_vec3Xmat4(result,projectionMatrix);
  2089. result->w = result->z;
  2090. /* We'll keep the non-clamped z in w for sorting. */
  2091. }
  2092. void _S3L_mapProjectedVertexToScreen(S3L_Vec4 *vertex, S3L_Unit focalLength)
  2093. {
  2094. vertex->z = vertex->z >= S3L_NEAR ? vertex->z : S3L_NEAR;
  2095. /* ^ This firstly prevents zero division in the follwoing z-divide and
  2096. secondly "pushes" vertices that are in front of near a little bit forward,
  2097. which makes them behave a bit better. If all three vertices end up exactly
  2098. on NEAR, the triangle will be culled. */
  2099. S3L_perspectiveDivide(vertex,focalLength);
  2100. S3L_ScreenCoord sX, sY;
  2101. S3L_mapProjectionPlaneToScreen(*vertex,&sX,&sY);
  2102. vertex->x = sX;
  2103. vertex->y = sY;
  2104. }
  2105. /**
  2106. Projects a triangle to the screen. If enabled, a triangle can be potentially
  2107. subdivided into two if it crosses the near plane, in which case two projected
  2108. triangles are returned (return value will be 1).
  2109. */
  2110. uint8_t _S3L_projectTriangle(
  2111. const S3L_Model3D *model,
  2112. S3L_Index triangleIndex,
  2113. S3L_Mat4 matrix,
  2114. uint32_t focalLength,
  2115. S3L_Vec4 transformed[6])
  2116. {
  2117. _S3L_projectVertex(model,triangleIndex,0,matrix,&(transformed[0]));
  2118. _S3L_projectVertex(model,triangleIndex,1,matrix,&(transformed[1]));
  2119. _S3L_projectVertex(model,triangleIndex,2,matrix,&(transformed[2]));
  2120. uint8_t result = 0;
  2121. #if S3L_NEAR_CROSS_STRATEGY == 2
  2122. uint8_t infront = 0;
  2123. uint8_t behind = 0;
  2124. uint8_t infrontI[3];
  2125. uint8_t behindI[3];
  2126. for (uint8_t i = 0; i < 3; ++i)
  2127. if (transformed[i].z < S3L_NEAR)
  2128. {
  2129. infrontI[infront] = i;
  2130. infront++;
  2131. }
  2132. else
  2133. {
  2134. behindI[behind] = i;
  2135. behind++;
  2136. }
  2137. #define interpolateVertex \
  2138. S3L_Unit ratio =\
  2139. ((transformed[be].z - S3L_NEAR) * S3L_FRACTIONS_PER_UNIT) /\
  2140. (transformed[be].z - transformed[in].z);\
  2141. transformed[in].x = transformed[be].x - \
  2142. ((transformed[be].x - transformed[in].x) * ratio) /\
  2143. S3L_FRACTIONS_PER_UNIT;\
  2144. transformed[in].y = transformed[be].y -\
  2145. ((transformed[be].y - transformed[in].y) * ratio) /\
  2146. S3L_FRACTIONS_PER_UNIT;\
  2147. transformed[in].z = S3L_NEAR;
  2148. if (infront == 2)
  2149. {
  2150. // shift the two vertices forward along the edge
  2151. for (uint8_t i = 0; i < 2; ++i)
  2152. {
  2153. uint8_t be = behindI[0], in = infrontI[i];
  2154. interpolateVertex
  2155. }
  2156. }
  2157. else if (infront == 1)
  2158. {
  2159. // create another triangle and do the shifts
  2160. transformed[3] = transformed[behindI[1]];
  2161. transformed[4] = transformed[infrontI[0]];
  2162. transformed[5] = transformed[infrontI[0]];
  2163. for (uint8_t i = 0; i < 2; ++i)
  2164. {
  2165. uint8_t be = behindI[i], in = i + 4;
  2166. interpolateVertex
  2167. }
  2168. transformed[infrontI[0]] = transformed[4];
  2169. _S3L_mapProjectedVertexToScreen(&transformed[3],focalLength);
  2170. _S3L_mapProjectedVertexToScreen(&transformed[4],focalLength);
  2171. _S3L_mapProjectedVertexToScreen(&transformed[5],focalLength);
  2172. result = 1;
  2173. }
  2174. #undef interpolateVertex
  2175. #endif // S3L_NEAR_CROSS_STRATEGY == 2
  2176. _S3L_mapProjectedVertexToScreen(&transformed[0],focalLength);
  2177. _S3L_mapProjectedVertexToScreen(&transformed[1],focalLength);
  2178. _S3L_mapProjectedVertexToScreen(&transformed[2],focalLength);
  2179. return result;
  2180. }
  2181. void S3L_drawScene(S3L_Scene scene)
  2182. {
  2183. S3L_Mat4 matFinal, matCamera;
  2184. S3L_Vec4 transformed[6]; // transformed triangle coords, for 2 triangles
  2185. const S3L_Model3D *model;
  2186. S3L_Index modelIndex, triangleIndex;
  2187. S3L_makeCameraMatrix(scene.camera.transform,matCamera);
  2188. #if S3L_SORT != 0
  2189. uint16_t previousModel = 0;
  2190. S3L_sortArrayLength = 0;
  2191. #endif
  2192. for (modelIndex = 0; modelIndex < scene.modelCount; ++modelIndex)
  2193. {
  2194. if (!scene.models[modelIndex].config.visible)
  2195. continue;
  2196. #if S3L_SORT != 0
  2197. if (S3L_sortArrayLength >= S3L_MAX_TRIANGES_DRAWN)
  2198. break;
  2199. previousModel = modelIndex;
  2200. #endif
  2201. if (scene.models[modelIndex].customTransformMatrix == 0)
  2202. S3L_makeWorldMatrix(scene.models[modelIndex].transform,matFinal);
  2203. else
  2204. {
  2205. S3L_Mat4 *m = scene.models[modelIndex].customTransformMatrix;
  2206. for (int8_t j = 0; j < 4; ++j)
  2207. for (int8_t i = 0; i < 4; ++i)
  2208. matFinal[i][j] = (*m)[i][j];
  2209. }
  2210. S3L_mat4Xmat4(matFinal,matCamera);
  2211. S3L_Index triangleCount = scene.models[modelIndex].triangleCount;
  2212. triangleIndex = 0;
  2213. model = &(scene.models[modelIndex]);
  2214. while (triangleIndex < triangleCount)
  2215. {
  2216. /* Some kind of cache could be used in theory to not project perviously
  2217. already projected vertices, but after some testing this was abandoned,
  2218. no gain was seen. */
  2219. uint8_t split = _S3L_projectTriangle(model,triangleIndex,matFinal,
  2220. scene.camera.focalLength,transformed);
  2221. if (S3L_triangleIsVisible(transformed[0],transformed[1],transformed[2],
  2222. model->config.backfaceCulling))
  2223. {
  2224. #if S3L_SORT == 0
  2225. // without sorting draw right away
  2226. S3L_drawTriangle(transformed[0],transformed[1],transformed[2],modelIndex,
  2227. triangleIndex);
  2228. if (split) // draw potential subtriangle
  2229. S3L_drawTriangle(transformed[3],transformed[4],transformed[5],
  2230. modelIndex, triangleIndex);
  2231. #else
  2232. S3L_UNUSED(split);
  2233. if (S3L_sortArrayLength >= S3L_MAX_TRIANGES_DRAWN)
  2234. break;
  2235. // with sorting add to a sort list
  2236. S3L_sortArray[S3L_sortArrayLength].modelIndex = modelIndex;
  2237. S3L_sortArray[S3L_sortArrayLength].triangleIndex = triangleIndex;
  2238. S3L_sortArray[S3L_sortArrayLength].sortValue = S3L_zeroClamp(
  2239. transformed[0].w + transformed[1].w + transformed[2].w) >> 2;
  2240. /* ^
  2241. The w component here stores non-clamped z.
  2242. As a simple approximation we sort by the triangle center point,
  2243. which is a mean coordinate -- we don't actually have to divide by 3
  2244. (or anything), that is unnecessary for sorting! We shift by 2 just
  2245. as a fast operation to prevent overflow of the sum over uint_16t. */
  2246. S3L_sortArrayLength++;
  2247. #endif
  2248. }
  2249. triangleIndex++;
  2250. }
  2251. }
  2252. #if S3L_SORT != 0
  2253. #if S3L_SORT == 1
  2254. #define cmp <
  2255. #else
  2256. #define cmp >
  2257. #endif
  2258. /* Sort the triangles. We use insertion sort, because it has many advantages,
  2259. especially for smaller arrays (better than bubble sort, in-place, stable,
  2260. simple, ...). */
  2261. for (int16_t i = 1; i < S3L_sortArrayLength; ++i)
  2262. {
  2263. _S3L_TriangleToSort tmp = S3L_sortArray[i];
  2264. int16_t j = i - 1;
  2265. while (j >= 0 && S3L_sortArray[j].sortValue cmp tmp.sortValue)
  2266. {
  2267. S3L_sortArray[j + 1] = S3L_sortArray[j];
  2268. j--;
  2269. }
  2270. S3L_sortArray[j + 1] = tmp;
  2271. }
  2272. #undef cmp
  2273. for (S3L_Index i = 0; i < S3L_sortArrayLength; ++i) // draw sorted triangles
  2274. {
  2275. modelIndex = S3L_sortArray[i].modelIndex;
  2276. triangleIndex = S3L_sortArray[i].triangleIndex;
  2277. model = &(scene.models[modelIndex]);
  2278. if (modelIndex != previousModel)
  2279. {
  2280. // only recompute the matrix when the model has changed
  2281. S3L_makeWorldMatrix(model->transform,matFinal);
  2282. S3L_mat4Xmat4(matFinal,matCamera);
  2283. previousModel = modelIndex;
  2284. }
  2285. /* Here we project the points again, which is redundant and slow as they've
  2286. already been projected above, but saving the projected points would
  2287. require a lot of memory, which for small resolutions could be even
  2288. worse than z-bufer. So this seems to be the best way memory-wise. */
  2289. uint8_t split = _S3L_projectTriangle(model,triangleIndex,matFinal,
  2290. scene.camera.focalLength,transformed);
  2291. S3L_drawTriangle(transformed[0],transformed[1],transformed[2],modelIndex,
  2292. triangleIndex);
  2293. if (split)
  2294. S3L_drawTriangle(transformed[3],transformed[4],transformed[5],
  2295. modelIndex, triangleIndex);
  2296. }
  2297. #endif
  2298. }
  2299. #endif // guard