small3dlib.h 86 KB

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