seglinerenderer.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. /*
  2. ** Command & Conquer Renegade(tm)
  3. ** Copyright 2025 Electronic Arts Inc.
  4. **
  5. ** This program is free software: you can redistribute it and/or modify
  6. ** it under the terms of the GNU General Public License as published by
  7. ** the Free Software Foundation, either version 3 of the License, or
  8. ** (at your option) any later version.
  9. **
  10. ** This program is distributed in the hope that it will be useful,
  11. ** but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ** GNU General Public License for more details.
  14. **
  15. ** You should have received a copy of the GNU General Public License
  16. ** along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. /***********************************************************************************************
  19. *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S ***
  20. ***********************************************************************************************
  21. * *
  22. * Project Name : ww3d *
  23. * *
  24. * $Archive:: /Commando/Code/ww3d2/seglinerenderer.cpp $*
  25. * *
  26. * Original Author:: Greg Hjelstrom *
  27. * *
  28. * $Author:: Jani_p $*
  29. * *
  30. * $Modtime:: 11/24/01 6:20p $*
  31. * *
  32. * $Revision:: 4 $*
  33. * *
  34. *---------------------------------------------------------------------------------------------*
  35. * Functions: *
  36. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  37. #if 1
  38. #include "seglinerenderer.h"
  39. #include "ww3d.h"
  40. #include "rinfo.h"
  41. #include "dx8wrapper.h"
  42. #include "sortingrenderer.h"
  43. #include "vp.h"
  44. #include "vector3i.h"
  45. #include "random.h"
  46. #include "v3_rnd.h"
  47. #include "meshgeometry.h"
  48. /* We have chunking logic which handles N segments at a time. To simplify the subdivision logic,
  49. ** we will ensure that N is a power of two and that N >= 2^MAX_SEGLINE_SUBDIV_LEVELS, so that the
  50. ** subdivision logic can be inside the chunking loop.
  51. */
  52. #if MAX_SEGLINE_SUBDIV_LEVELS > 7
  53. #define SEGLINE_CHUNK_SIZE (1 << MAX_SEGLINE_SUBDIV_LEVELS)
  54. #else
  55. #define SEGLINE_CHUNK_SIZE (128)
  56. #endif
  57. #define MAX_SEGLINE_POINT_BUFFER_SIZE (1 + SEGLINE_CHUNK_SIZE)
  58. // This macro depends on the assumption that each line segment is two polys.
  59. #define MAX_SEGLINE_POLY_BUFFER_SIZE (SEGLINE_CHUNK_SIZE * 2)
  60. SegLineRendererClass::SegLineRendererClass(void) :
  61. Texture(NULL),
  62. Shader(ShaderClass::_PresetAdditiveSpriteShader),
  63. Width(0.0f),
  64. Color(Vector3(1,1,1)),
  65. Opacity(1.0f),
  66. SubdivisionLevel(0),
  67. NoiseAmplitude(0.0f),
  68. MergeAbortFactor(1.5f),
  69. TextureTileFactor(1.0f),
  70. LastUsedSyncTime(WW3D::Get_Sync_Time()),
  71. CurrentUVOffset(0.0f,0.0f),
  72. UVOffsetDeltaPerMS(0.0f, 0.0f),
  73. Bits(DEFAULT_BITS)
  74. {
  75. }
  76. SegLineRendererClass::SegLineRendererClass(const SegLineRendererClass & that) :
  77. Texture(NULL),
  78. Shader(ShaderClass::_PresetAdditiveSpriteShader),
  79. Width(0.0f),
  80. Color(Vector3(1,1,1)),
  81. Opacity(1.0f),
  82. SubdivisionLevel(0),
  83. NoiseAmplitude(0.0f),
  84. MergeAbortFactor(1.5f),
  85. TextureTileFactor(1.0f),
  86. LastUsedSyncTime(that.LastUsedSyncTime),
  87. CurrentUVOffset(0.0f,0.0f),
  88. UVOffsetDeltaPerMS(0.0f, 0.0f),
  89. Bits(DEFAULT_BITS)
  90. {
  91. *this = that;
  92. }
  93. SegLineRendererClass & SegLineRendererClass::operator = (const SegLineRendererClass & that)
  94. {
  95. if (this != &that) {
  96. REF_PTR_SET(Texture,that.Texture);
  97. Shader = that.Shader;
  98. Width = that.Width;
  99. Color = that.Color;
  100. Opacity = that.Opacity;
  101. SubdivisionLevel = that.SubdivisionLevel;
  102. NoiseAmplitude = that.NoiseAmplitude;
  103. MergeAbortFactor = that.MergeAbortFactor;
  104. TextureTileFactor = that.TextureTileFactor;
  105. LastUsedSyncTime = that.LastUsedSyncTime;
  106. CurrentUVOffset = that.CurrentUVOffset;
  107. UVOffsetDeltaPerMS = that.UVOffsetDeltaPerMS;
  108. Bits = that.Bits;
  109. }
  110. return *this;
  111. }
  112. SegLineRendererClass::~SegLineRendererClass(void)
  113. {
  114. REF_PTR_RELEASE(Texture);
  115. }
  116. void SegLineRendererClass::Init(const W3dEmitterLinePropertiesStruct & props)
  117. {
  118. // translate the flags
  119. Set_Merge_Intersections(props.Flags & W3D_ELINE_MERGE_INTERSECTIONS);
  120. Set_Freeze_Random(props.Flags & W3D_ELINE_FREEZE_RANDOM);
  121. Set_Disable_Sorting(props.Flags & W3D_ELINE_DISABLE_SORTING);
  122. Set_End_Caps(props.Flags & W3D_ELINE_END_CAPS);
  123. int texture_mode = ((props.Flags & W3D_ELINE_TEXTURE_MAP_MODE_MASK) >> W3D_ELINE_TEXTURE_MAP_MODE_OFFSET);
  124. switch (texture_mode)
  125. {
  126. case W3D_ELINE_UNIFORM_WIDTH_TEXTURE_MAP:
  127. Set_Texture_Mapping_Mode(UNIFORM_WIDTH_TEXTURE_MAP);
  128. break;
  129. case W3D_ELINE_UNIFORM_LENGTH_TEXTURE_MAP:
  130. Set_Texture_Mapping_Mode(UNIFORM_LENGTH_TEXTURE_MAP);
  131. break;
  132. case W3D_ELINE_TILED_TEXTURE_MAP:
  133. Set_Texture_Mapping_Mode(TILED_TEXTURE_MAP);
  134. break;
  135. };
  136. // install all other settings
  137. Set_Current_Subdivision_Level(props.SubdivisionLevel);
  138. Set_Noise_Amplitude(props.NoiseAmplitude);
  139. Set_Merge_Abort_Factor(props.MergeAbortFactor);
  140. Set_Texture_Tile_Factor(props.TextureTileFactor);
  141. Set_UV_Offset_Rate(Vector2(props.UPerSec,props.VPerSec));
  142. }
  143. void SegLineRendererClass::Set_Texture(TextureClass *texture)
  144. {
  145. REF_PTR_SET(Texture,texture);
  146. }
  147. TextureClass * SegLineRendererClass::Get_Texture(void) const
  148. {
  149. if (Texture != NULL) {
  150. Texture->Add_Ref();
  151. }
  152. return Texture;
  153. }
  154. void SegLineRendererClass::Set_Current_UV_Offset(const Vector2 & offset)
  155. {
  156. CurrentUVOffset = offset;
  157. }
  158. void SegLineRendererClass::Set_Texture_Tile_Factor(float factor)
  159. {
  160. if (factor > 8.0f) {
  161. factor = 8.0f;
  162. WWDEBUG_SAY(("Texture Tile Factor too large in SegLineRendererClass!\r\n"));
  163. } else {
  164. factor = MAX(factor, 0.0f);
  165. }
  166. TextureTileFactor = factor;
  167. }
  168. void SegLineRendererClass::Reset_Line(void)
  169. {
  170. LastUsedSyncTime = WW3D::Get_Sync_Time();
  171. CurrentUVOffset.Set(0.0f,0.0f);
  172. }
  173. void SegLineRendererClass::Render
  174. (
  175. RenderInfoClass & rinfo,
  176. const Matrix3D & transform,
  177. unsigned int num_points,
  178. Vector3 * points,
  179. const SphereClass & obj_sphere
  180. )
  181. {
  182. Matrix4 view;
  183. DX8Wrapper::Get_Transform(D3DTS_VIEW,view);
  184. Matrix4 identity(true);
  185. DX8Wrapper::Set_Transform(D3DTS_WORLD,identity);
  186. DX8Wrapper::Set_Transform(D3DTS_VIEW,identity);
  187. /*
  188. ** Handle texture UV offset animation (done once for entire line).
  189. */
  190. unsigned int delta = WW3D::Get_Sync_Time() - LastUsedSyncTime;
  191. float del = (float)delta;
  192. Vector2 uv_offset = CurrentUVOffset + UVOffsetDeltaPerMS * del;
  193. // ensure offsets are in [0, 1] range:
  194. uv_offset.X = uv_offset.X - floor(uv_offset.X);
  195. uv_offset.Y = uv_offset.Y - floor(uv_offset.Y);
  196. // Update state
  197. CurrentUVOffset = uv_offset;
  198. LastUsedSyncTime = WW3D::Get_Sync_Time();
  199. // Used later
  200. TextureMapMode map_mode = Get_Texture_Mapping_Mode();
  201. /*
  202. ** Process line geometry:
  203. */
  204. // This has been tweaked to produce empirically good results.
  205. const float parallel_factor = 0.9f;
  206. // We reduce the chunk size to take account of subdivision levels (so that the # of points
  207. // after subdivision will be no higher than the allowed maximum). We know this will not reduce
  208. // the chunk size below 2, since the chunk size must be at least two to the power of the
  209. // maximum allowable number of subdivisions. The plus 1 is because #points = #segments + 1.
  210. unsigned int chunk_size = (SEGLINE_CHUNK_SIZE >> SubdivisionLevel) + 1;
  211. if (chunk_size > num_points) chunk_size = num_points;
  212. // Chunk through the points (we increment by chunk_size - 1 because the last point of this
  213. // chunk must be reused as the first point of the next chunk. This is also the reason we stop
  214. // when chidx = NumPoints - 1: the last point has already been processed in the previous
  215. // iteration so we don't need another one).
  216. for (unsigned int chidx = 0; chidx < num_points - 1; chidx += (chunk_size - 1)) {
  217. unsigned int point_cnt = num_points - chidx;
  218. point_cnt = MIN(point_cnt, chunk_size);
  219. // We use these different loop indices (which loop INSIDE a chunk) to improve readability:
  220. unsigned int pidx; // Point index
  221. unsigned int sidx; // Segment index
  222. unsigned int iidx; // Intersection index
  223. /*
  224. ** Transform points in chunk from objectspace to eyespace:
  225. */
  226. Vector3 xformed_pts[MAX_SEGLINE_POINT_BUFFER_SIZE];
  227. Matrix3D view2( view[0].X,view[0].Y,view[0].Z,view[0].W,
  228. view[1].X,view[1].Y,view[1].Z,view[1].W,
  229. view[2].X,view[2].Y,view[2].Z,view[2].W);
  230. Matrix3D modelview=view2*transform;
  231. VectorProcessorClass::Transform(&xformed_pts[0],
  232. &points[chidx], modelview, point_cnt);
  233. /*
  234. ** Prepare v parameter per point - used for texture mapping (esp. tiled mapping mode)
  235. */
  236. float base_tex_v[MAX_SEGLINE_POINT_BUFFER_SIZE];
  237. float u_values[2];
  238. switch (map_mode) {
  239. case UNIFORM_WIDTH_TEXTURE_MAP:
  240. for (pidx = 0; pidx < point_cnt; pidx++) {
  241. // All 0
  242. base_tex_v[pidx] = 0.0f;
  243. }
  244. u_values[0] = 0.0f;
  245. u_values[1] = 1.0f;
  246. break;
  247. case UNIFORM_LENGTH_TEXTURE_MAP:
  248. for (pidx = 0; pidx < point_cnt; pidx++) {
  249. // Increasing V
  250. base_tex_v[pidx] = (float)(pidx + chidx) * TextureTileFactor;
  251. }
  252. u_values[0] = 0.0f;
  253. u_values[1] = 0.0f;
  254. break;
  255. case TILED_TEXTURE_MAP:
  256. for (pidx = 0; pidx < point_cnt; pidx++) {
  257. // Increasing V
  258. base_tex_v[pidx] = (float)(pidx + chidx) * TextureTileFactor;
  259. }
  260. u_values[0] = 0.0f;
  261. u_values[1] = 1.0f;
  262. break;
  263. }
  264. /*
  265. ** Fractal noise recursive subdivision:
  266. ** We find the midpoint for each section, apply a random offset, and recurse. We also find
  267. ** the average V coordinate of the endpoints which is the midpoint V (for tiled texture
  268. ** mapping).
  269. */
  270. Vector3 xformed_subdiv_pts[MAX_SEGLINE_POINT_BUFFER_SIZE];
  271. float subdiv_tex_v[MAX_SEGLINE_POINT_BUFFER_SIZE];
  272. unsigned int sub_point_cnt;
  273. subdivision_util(point_cnt, xformed_pts, base_tex_v, &sub_point_cnt, xformed_subdiv_pts, subdiv_tex_v);
  274. // Start using subdivided points from now on
  275. Vector3 *points = xformed_subdiv_pts;
  276. float *tex_v = subdiv_tex_v;
  277. point_cnt = sub_point_cnt;
  278. /*
  279. ** Calculate line segment edge planes:
  280. */
  281. // For each line segment find the two silhouette planes from eyepoint to the line segment
  282. // cylinder. To simplify we do not find the tangent planes but intersect the cylinder with a
  283. // plane passing through its axis and perpendicular to the eye vector, find the edges of the
  284. // resulting rectangle, and create planes through these edges and the eyepoint.
  285. // Note that these planes are represented as a single normal rather than a normal and a
  286. // distance; this is because they pass through the origin (eyepoint) so their distance is
  287. // always zero.
  288. // Since the line has thickness, each segment has two edges. We name these 'top' and
  289. // 'bottom' - note however that the top/bottom distinction does not relate to screen
  290. // up/down and remains consistent throughout the segmented line.
  291. enum SegmentEdge {
  292. FIRST_EDGE = 0, // For loop conditions
  293. TOP_EDGE = 0, // Top Edge
  294. BOTTOM_EDGE = 1, // Bottom Edge
  295. MAX_EDGE = 1, // For loop conditions
  296. NUM_EDGES = 2 // For array allocations
  297. };
  298. bool switch_edges = false;
  299. // We have dummy segments for "before the first point" and "after the last point" - in these
  300. // segments the top and bottom edge are the same - they are a perpendicular plane defined by
  301. // the endpoint vertices. This is so we can merge intersections properly for the first and
  302. // last points.
  303. struct LineSegment {
  304. Vector3 StartPlane;
  305. Vector3 EdgePlane[NUM_EDGES];
  306. };
  307. // # segments = numpoints + 1 (numpoints - 1, plus two dummy segments)
  308. LineSegment segment[MAX_SEGLINE_POINT_BUFFER_SIZE + 1];
  309. // Intersections. This has data for two edges (top or bottom) intersecting.
  310. struct LineSegmentIntersection {
  311. unsigned int PointCount; // How many points does this intersection represent
  312. unsigned int NextSegmentID; // ID of segment after this intersection
  313. Vector3 Direction; // Calculated intersection direction line
  314. Vector3 Point; // Averaged 3D point on the line which this represents
  315. float TexV; // Averaged texture V coordinate of points
  316. bool Fold; // Does the line fold over at this intersection?
  317. bool Parallel; // Edges at this intersection are parallel (or almost-)
  318. };
  319. // Used to calculate the edge planes
  320. float radius = Width * 0.5f;
  321. // The number of intersections is the number of points minus 2. However, we store
  322. // intersection records for the first and last point, even though they are not really
  323. // intersections. The reason we do this is for the intersection merging - the vertices for
  324. // the first and last points can get merged just like any other intersection. Also, we have
  325. // a dummy intersection record before the first point - this is because we want "previous
  326. // segments" for the first point and each intersection only has an index for the next
  327. // segment.
  328. LineSegmentIntersection intersection[MAX_SEGLINE_POINT_BUFFER_SIZE + 1][NUM_EDGES];
  329. for (sidx = 1; sidx < point_cnt; sidx++) { // #segments = #points - 1 (+ 2 dummy segments)
  330. Vector3 &curr_point = points[sidx - 1];
  331. Vector3 &next_point = points[sidx];
  332. // We temporarily store the segment direction in the segment's StartPlane (since it is
  333. // used to calculate the StartPlane later).
  334. Vector3 &segdir = segment[sidx].StartPlane;
  335. segdir = next_point - curr_point;
  336. segdir.Normalize();
  337. // Find nearest point on infinite line to eye (origin)
  338. Vector3 nearest = curr_point + segdir * -Vector3::Dot_Product(segdir, curr_point);
  339. // Find top and bottom points on cylinder
  340. Vector3 offset;
  341. Vector3::Cross_Product(segdir, nearest, &offset);
  342. offset.Normalize();
  343. Vector3 top = curr_point + offset * radius;
  344. Vector3 bottom = curr_point + offset * -radius;
  345. // Find planes through top/bottom points and eyepoint. In addition to the two points, we
  346. // know that the planes are parallel to the line segment.
  347. Vector3 top_normal;
  348. Vector3::Cross_Product(top, segdir, &top_normal);
  349. top_normal.Normalize();
  350. segment[sidx].EdgePlane[TOP_EDGE] = top_normal;
  351. Vector3 bottom_normal;
  352. Vector3::Cross_Product(segdir, bottom, &bottom_normal);
  353. bottom_normal.Normalize();
  354. segment[sidx].EdgePlane[BOTTOM_EDGE] = bottom_normal;
  355. // If the visual angle between the previous and current line segments (we use the angle
  356. // between the planes defined by each line segment and the eyepoint) is less than 90
  357. // degrees, switch the top and bottom edges for the current and subsequent segments and
  358. // mark the intersection as having a fold
  359. if (sidx > 1) {
  360. Vector3 prev_plane;
  361. Vector3::Cross_Product(points[sidx - 2], curr_point, &prev_plane);
  362. prev_plane.Normalize();
  363. Vector3 curr_plane;
  364. Vector3::Cross_Product(curr_point, next_point, &curr_plane);
  365. curr_plane.Normalize();
  366. if (Vector3::Dot_Product(prev_plane, curr_plane) < 0.0f) {
  367. switch_edges = !switch_edges;
  368. intersection[sidx][TOP_EDGE].Fold = true;
  369. intersection[sidx][BOTTOM_EDGE].Fold = true;
  370. } else {
  371. intersection[sidx][TOP_EDGE].Fold = false;
  372. intersection[sidx][BOTTOM_EDGE].Fold = false;
  373. }
  374. }
  375. if (switch_edges) {
  376. // We switch signs so the normals will always point inwards
  377. segment[sidx].EdgePlane[TOP_EDGE] = -bottom_normal;
  378. segment[sidx].EdgePlane[BOTTOM_EDGE] = -top_normal;
  379. }
  380. }
  381. // The two dummy segments for the clipping edges of the first and last real segments will be
  382. // defined later, with the first and last intersections.
  383. /*
  384. ** Calculate segment edge intersections:
  385. */
  386. unsigned int numsegs = point_cnt - 1; // Doesn't include the two dummy segments
  387. unsigned int num_intersections[NUM_EDGES];
  388. // These include the 1st, last point "intersections", not the pre-first dummy intersection
  389. num_intersections[TOP_EDGE] = point_cnt;
  390. num_intersections[BOTTOM_EDGE] = point_cnt;
  391. // Initialize pre-first point dummy intersection record (only NextSegmentID will be used).
  392. intersection[0][TOP_EDGE].PointCount = 0; // Should never be used
  393. intersection[0][TOP_EDGE].NextSegmentID = 0; // Points to first dummy segment
  394. intersection[0][TOP_EDGE].Direction.Set(1,0,0); // Should never be used
  395. intersection[0][TOP_EDGE].Point.Set(0,0,0); // Should never be used
  396. intersection[0][TOP_EDGE].TexV = 0.0f; // Should never be used
  397. intersection[0][TOP_EDGE].Fold = true; // Should never be used
  398. intersection[0][TOP_EDGE].Parallel = false; // Should never be used
  399. intersection[0][BOTTOM_EDGE].PointCount = 0; // Should never be used
  400. intersection[0][BOTTOM_EDGE].NextSegmentID = 0; // Points to first dummy segment
  401. intersection[0][BOTTOM_EDGE].Point.Set(0,0,0); // Should never be used
  402. intersection[0][BOTTOM_EDGE].TexV = 0.0f; // Should never be used
  403. intersection[0][BOTTOM_EDGE].Direction.Set(1,0,0); // Should never be used
  404. intersection[0][BOTTOM_EDGE].Fold = true; // Should never be used
  405. intersection[0][BOTTOM_EDGE].Parallel = false; // Should never be used
  406. // Initialize first point "intersection" record.
  407. intersection[1][TOP_EDGE].PointCount = 1;
  408. intersection[1][TOP_EDGE].NextSegmentID = 1;
  409. intersection[1][TOP_EDGE].Point = points[0];
  410. intersection[1][TOP_EDGE].TexV = tex_v[0];
  411. intersection[1][TOP_EDGE].Fold = true;
  412. intersection[1][TOP_EDGE].Parallel = false;
  413. intersection[1][BOTTOM_EDGE].PointCount = 1;
  414. intersection[1][BOTTOM_EDGE].NextSegmentID = 1;
  415. intersection[1][BOTTOM_EDGE].Point = points[0];
  416. intersection[1][BOTTOM_EDGE].TexV = tex_v[0];
  417. intersection[1][BOTTOM_EDGE].Fold = true;
  418. intersection[1][BOTTOM_EDGE].Parallel = false;
  419. // Find closest point to 1st top/bottom segment edge plane, and convert to direction vector
  420. // and dummy segment edge plane.
  421. Vector3 top;
  422. Vector3 bottom;
  423. Vector3 &first_point = points[0];
  424. Vector3 *first_plane = &(segment[1].EdgePlane[0]);
  425. top = first_point - first_plane[TOP_EDGE] * Vector3::Dot_Product(first_plane[TOP_EDGE], first_point);
  426. top.Normalize();
  427. intersection[1][TOP_EDGE].Direction = top;
  428. bottom = first_point - first_plane[BOTTOM_EDGE] * Vector3::Dot_Product(first_plane[BOTTOM_EDGE], first_point);
  429. bottom.Normalize();
  430. intersection[1][BOTTOM_EDGE].Direction = bottom;
  431. Vector3 segdir = points[1] - points[0];
  432. segdir.Normalize(); // Is this needed? Probably not - remove later when all works
  433. Vector3 start_pl;
  434. Vector3::Cross_Product(top, bottom, &start_pl);
  435. start_pl.Normalize();
  436. float dp = Vector3::Dot_Product(segdir, start_pl);
  437. if (dp > 0.0f) {
  438. segment[0].StartPlane = segment[0].EdgePlane[TOP_EDGE] = segment[0].EdgePlane[BOTTOM_EDGE] = start_pl;
  439. } else {
  440. segment[0].StartPlane = segment[0].EdgePlane[TOP_EDGE] = segment[0].EdgePlane[BOTTOM_EDGE] = -start_pl;
  441. }
  442. // Initialize StartPlane for the first "real" segment
  443. segment[1].StartPlane = segment[0].StartPlane;
  444. // Initialize last point "intersection" record.
  445. unsigned int last_isec = num_intersections[TOP_EDGE]; // Same # top, bottom intersections
  446. intersection[last_isec][TOP_EDGE].PointCount = 1;
  447. intersection[last_isec][TOP_EDGE].NextSegmentID = numsegs + 1; // Last dummy segment
  448. intersection[last_isec][TOP_EDGE].Point = points[point_cnt - 1];
  449. intersection[last_isec][TOP_EDGE].TexV = tex_v[point_cnt - 1];
  450. intersection[last_isec][TOP_EDGE].Fold = true;
  451. intersection[last_isec][TOP_EDGE].Parallel = false;
  452. intersection[last_isec][BOTTOM_EDGE].PointCount = 1;
  453. intersection[last_isec][BOTTOM_EDGE].NextSegmentID = numsegs + 1;// Last dummy segment
  454. intersection[last_isec][BOTTOM_EDGE].Point = points[point_cnt - 1];
  455. intersection[last_isec][BOTTOM_EDGE].TexV = tex_v[point_cnt - 1];
  456. intersection[last_isec][BOTTOM_EDGE].Fold = true;
  457. intersection[last_isec][BOTTOM_EDGE].Parallel = false;
  458. // Find closest point to last top/bottom segment edge plane, and convert to direction vector
  459. // and dummy segment edge vector
  460. Vector3 &last_point = points[point_cnt - 1];
  461. Vector3 *last_plane = &(segment[numsegs].EdgePlane[0]);
  462. top = last_point - last_plane[TOP_EDGE] * Vector3::Dot_Product(last_plane[TOP_EDGE], last_point);
  463. top.Normalize();
  464. intersection[last_isec][TOP_EDGE].Direction = top;
  465. bottom = last_point - last_plane[BOTTOM_EDGE] * Vector3::Dot_Product(last_plane[BOTTOM_EDGE], last_point);
  466. bottom.Normalize();
  467. intersection[last_isec][BOTTOM_EDGE].Direction = bottom;
  468. segdir = points[point_cnt - 1] - points[point_cnt - 2];
  469. segdir.Normalize(); // Is this needed? Probably not - remove later when all works
  470. Vector3::Cross_Product(top, bottom, &start_pl);
  471. start_pl.Normalize();
  472. dp = Vector3::Dot_Product(segdir, start_pl);
  473. if (dp > 0.0f) {
  474. segment[numsegs + 1].StartPlane = segment[numsegs + 1].EdgePlane[TOP_EDGE] =
  475. segment[numsegs + 1].EdgePlane[BOTTOM_EDGE] = start_pl;
  476. } else {
  477. segment[numsegs + 1].StartPlane = segment[numsegs + 1].EdgePlane[TOP_EDGE] =
  478. segment[numsegs + 1].EdgePlane[BOTTOM_EDGE] = -start_pl;
  479. }
  480. // Calculate midpoint segment intersections. There are 2 segment intersections for each
  481. // point: top and bottom (due to the fact that the segments have width, so they have a top
  482. // edge and a bottom edge). Note that the top/bottom distinction does not relate to screen
  483. // up/down. Since each segment edge is represented by a plane passing through the origin
  484. // (eyepoint), the intersection of two such is a line passing through the origin, which is
  485. // represented as a normalized direction vector.
  486. // We use both segment intersections to define the startplane for the segment which begins
  487. // at that intersection.
  488. float vdp;
  489. for (iidx = 2; iidx < num_intersections[TOP_EDGE]; iidx++) {
  490. // Relevant midpoint:
  491. Vector3 &midpoint = points[iidx - 1];
  492. float mid_tex_v = tex_v[iidx - 1];
  493. // Initialize misc. fields
  494. intersection[iidx][TOP_EDGE].PointCount = 1;
  495. intersection[iidx][TOP_EDGE].NextSegmentID = iidx;
  496. intersection[iidx][TOP_EDGE].Point = midpoint;
  497. intersection[iidx][TOP_EDGE].TexV = mid_tex_v;
  498. intersection[iidx][BOTTOM_EDGE].PointCount = 1;
  499. intersection[iidx][BOTTOM_EDGE].NextSegmentID = iidx;
  500. intersection[iidx][BOTTOM_EDGE].Point = midpoint;
  501. intersection[iidx][BOTTOM_EDGE].TexV = mid_tex_v;
  502. // Intersection calculation: if the top/bottom planes of both adjoining segments are not
  503. // very close to being parallel, intersect them to get top/bottom intersection lines. If
  504. // the planes are almost parallel, pick one, find the point on the plane closest to the
  505. // midpoint, and convert that point to a line direction vector.
  506. // Top:
  507. vdp = Vector3::Dot_Product(segment[iidx - 1].EdgePlane[TOP_EDGE], segment[iidx].EdgePlane[TOP_EDGE]);
  508. if (fabs(vdp) < parallel_factor) {
  509. // Not parallel - intersect planes to get line (get vector, normalize it, ensure it is
  510. // pointing towards the midpoint)
  511. Vector3::Cross_Product(segment[iidx - 1].EdgePlane[TOP_EDGE], segment[iidx].EdgePlane[TOP_EDGE],
  512. &(intersection[iidx][TOP_EDGE].Direction));
  513. intersection[iidx][TOP_EDGE].Direction.Normalize();
  514. if (Vector3::Dot_Product(intersection[iidx][TOP_EDGE].Direction, midpoint) < 0.0f) {
  515. intersection[iidx][TOP_EDGE].Direction = -intersection[iidx][TOP_EDGE].Direction;
  516. }
  517. intersection[iidx][TOP_EDGE].Parallel = false;
  518. } else {
  519. // Parallel (or almost): find point on av. plane closest to midpoint, convert to line
  520. // Ensure average calculation is numerically stable:
  521. Vector3 pl;
  522. if (vdp > 0.0f) {
  523. pl = segment[iidx - 1].EdgePlane[TOP_EDGE] + segment[iidx].EdgePlane[TOP_EDGE];
  524. } else {
  525. pl = segment[iidx - 1].EdgePlane[TOP_EDGE] - segment[iidx].EdgePlane[TOP_EDGE];
  526. }
  527. pl.Normalize();
  528. intersection[iidx][TOP_EDGE].Direction = midpoint - pl * Vector3::Dot_Product(pl, midpoint);
  529. intersection[iidx][TOP_EDGE].Direction.Normalize();
  530. intersection[iidx][TOP_EDGE].Parallel = true;
  531. }
  532. // Bottom:
  533. vdp = Vector3::Dot_Product(segment[iidx - 1].EdgePlane[BOTTOM_EDGE], segment[iidx].EdgePlane[BOTTOM_EDGE]);
  534. if (fabs(vdp) < parallel_factor) {
  535. // Not parallel - intersect planes to get line (get vector, normalize it, ensure it is
  536. // pointing towards the midpoint)
  537. Vector3::Cross_Product(segment[iidx - 1].EdgePlane[BOTTOM_EDGE], segment[iidx].EdgePlane[BOTTOM_EDGE],
  538. &(intersection[iidx][BOTTOM_EDGE].Direction));
  539. intersection[iidx][BOTTOM_EDGE].Direction.Normalize();
  540. if (Vector3::Dot_Product(intersection[iidx][BOTTOM_EDGE].Direction, midpoint) < 0.0f) {
  541. intersection[iidx][BOTTOM_EDGE].Direction = -intersection[iidx][BOTTOM_EDGE].Direction;
  542. }
  543. intersection[iidx][BOTTOM_EDGE].Parallel = false;
  544. } else {
  545. // Parallel (or almost): find point on av. plane closest to midpoint, convert to line
  546. // Ensure average calculation is numerically stable:
  547. Vector3 pl;
  548. if (vdp > 0.0f) {
  549. pl = segment[iidx - 1].EdgePlane[BOTTOM_EDGE] + segment[iidx].EdgePlane[BOTTOM_EDGE];
  550. } else {
  551. pl = segment[iidx - 1].EdgePlane[BOTTOM_EDGE] - segment[iidx].EdgePlane[BOTTOM_EDGE];
  552. }
  553. pl.Normalize();
  554. intersection[iidx][BOTTOM_EDGE].Direction = midpoint - pl * Vector3::Dot_Product(pl, midpoint);
  555. intersection[iidx][BOTTOM_EDGE].Direction.Normalize();
  556. intersection[iidx][BOTTOM_EDGE].Parallel = true;
  557. }
  558. // Find StartPlane:
  559. Vector3::Cross_Product(intersection[iidx][TOP_EDGE].Direction, intersection[iidx][BOTTOM_EDGE].Direction, &start_pl);
  560. start_pl.Normalize();
  561. dp = Vector3::Dot_Product(segment[iidx].StartPlane, start_pl);
  562. if (dp > 0.0f) {
  563. segment[iidx].StartPlane = start_pl;
  564. } else {
  565. segment[iidx].StartPlane = -start_pl;
  566. }
  567. } // for iidx
  568. /*
  569. ** Intersection merging: when an intersection is inside an adjacent segment and certain
  570. ** other conditions hold true, we need to merge intersections to avoid visual glitches
  571. ** caused by the polys folding over on themselves.
  572. */
  573. if (Is_Merge_Intersections()) {
  574. // Since we are merging the intersections in-place, we have two index variables, a "read
  575. // index" and a "write index".
  576. unsigned int iidx_r;
  577. unsigned int iidx_w;
  578. // The merges will be repeated in multiple passes until none are performed. The reason
  579. // for this is that one merge may cause the need for another merge elsewhere.
  580. bool merged = true;
  581. while (merged) {
  582. merged = false;
  583. SegmentEdge edge;
  584. for (edge = FIRST_EDGE; edge <= MAX_EDGE; edge = (SegmentEdge)((int)edge + 1)) {
  585. // Merge top and bottom edge intersections: loop through the intersections from the
  586. // first intersection to the penultimate intersection, for each intersection check
  587. // if it needs to be merged with the next one (which is why the loop doesn't go all
  588. // the way to the last intersection). We start at 1 because 0 is the dummy
  589. // "pre-first-point" intersection.
  590. unsigned int num_isects = num_intersections[edge]; // Capture here because will change inside loop
  591. for (iidx_r = 1, iidx_w = 1; iidx_r < num_isects; iidx_r++, iidx_w++) {
  592. // Check for either of two possible reasons to merge this intersection with the
  593. // next: either the segment on the far side of the next intersection overlaps
  594. // this intersection, or the previous segment overlaps the next intersection.
  595. // Note that some other conditions need to be true as well.
  596. // Note: iidx_r is used for anything at or after the current position, iidx_w is
  597. // used for anything before the current position (previous positions have
  598. // potentially already been merged).
  599. // Note: iidx_r is used for anything at or after the current position, iidx_w is
  600. // used for anything before the current position (previous positions have
  601. // potentially already been merged).
  602. LineSegmentIntersection *curr_int = &(intersection[iidx_r][edge]);
  603. LineSegmentIntersection *next_int = &(intersection[iidx_r + 1][edge]);
  604. LineSegmentIntersection *write_int = &(intersection[iidx_w][edge]);
  605. LineSegmentIntersection *prev_int = &(intersection[iidx_w - 1][edge]);
  606. LineSegment *next_seg = &(segment[next_int->NextSegmentID]);
  607. LineSegment *curr_seg = &(segment[curr_int->NextSegmentID]);
  608. LineSegment *prev_seg = &(segment[prev_int->NextSegmentID]);
  609. // If this intersection is inside both the start plane and the segment edge
  610. // plane of the segment after the next intersection, merge this edge
  611. // intersection and the next. We repeat merging until no longer needed.
  612. // NOTE - we do not merge across a fold.
  613. while ( (!next_int->Fold &&
  614. (Vector3::Dot_Product(curr_int->Direction, next_seg->StartPlane) > 0.0f) &&
  615. (Vector3::Dot_Product(curr_int->Direction, next_seg->EdgePlane[edge]) > 0.0f )) ||
  616. (!curr_int->Fold &&
  617. (Vector3::Dot_Product(next_int->Direction, -curr_seg->StartPlane) > 0.0f) &&
  618. (Vector3::Dot_Product(next_int->Direction, prev_seg->EdgePlane[edge]) > 0.0f )) ) {
  619. // First calculate location of merged intersection - this is so we can abort
  620. // the merge if it yields funky results.
  621. // Find mean point (weighted so all points have same weighting)
  622. unsigned int new_count = curr_int->PointCount + next_int->PointCount;
  623. float oo_new_count = 1.0f / (float)new_count;
  624. float curr_factor = oo_new_count * (float)curr_int->PointCount;
  625. float next_factor = oo_new_count * (float)curr_int->PointCount;
  626. Vector3 new_point = curr_int->Point * curr_factor + next_int->Point * next_factor;
  627. float new_tex_v = curr_int->TexV * curr_factor + next_int->TexV * next_factor;
  628. // Calculate new intersection direction by intersecting prev_seg with next_seg
  629. bool new_parallel;
  630. Vector3 new_direction;
  631. vdp = Vector3::Dot_Product(prev_seg->EdgePlane[edge], next_seg->EdgePlane[edge]);
  632. if (fabs(vdp) < parallel_factor) {
  633. // Not parallel - intersect planes to get line (get vector, normalize it,
  634. // ensure it is pointing towards the current point)
  635. Vector3::Cross_Product(prev_seg->EdgePlane[edge], next_seg->EdgePlane[edge], &new_direction);
  636. new_direction.Normalize();
  637. if (Vector3::Dot_Product(new_direction, new_point) < 0.0f) {
  638. new_direction = -new_direction;
  639. }
  640. new_parallel = false;
  641. } else {
  642. // Parallel (or almost). If the current intersection is not parallel, take
  643. // the average plane and intersect it with the skipped plane. If the
  644. // current intersection is parallel, find the average plane, and find the
  645. // direction vector on it closest to the current intersections direction
  646. // vector.
  647. // Ensure average calculation is numerically stable:
  648. Vector3 pl;
  649. if (vdp > 0.0f) {
  650. pl = prev_seg->EdgePlane[edge] + next_seg->EdgePlane[edge];
  651. } else {
  652. pl = prev_seg->EdgePlane[edge] - next_seg->EdgePlane[edge];
  653. }
  654. pl.Normalize();
  655. if (curr_int->Parallel) {
  656. new_direction = new_direction - pl * Vector3::Dot_Product(pl, new_direction);
  657. new_direction.Normalize();
  658. } else {
  659. Vector3::Cross_Product(curr_seg->EdgePlane[edge], pl, &new_direction);
  660. new_direction.Normalize();
  661. }
  662. new_parallel = true;
  663. }
  664. // Now check to see if the merge caused any funky results - if so abort it.
  665. // Currently we check to see if the distance of the direction from the two
  666. // points is larger than the radius times the merge_abort factor.
  667. if (MergeAbortFactor > 0.0f) {
  668. float abort_dist = radius * MergeAbortFactor;
  669. float abort_dist2 = abort_dist * abort_dist;
  670. Vector3 diff_curr = curr_int->Point -
  671. new_direction * Vector3::Dot_Product(curr_int->Point, new_direction);
  672. if (diff_curr.Length2() > abort_dist2) break;
  673. Vector3 next_curr = next_int->Point -
  674. new_direction * Vector3::Dot_Product(next_int->Point, new_direction);
  675. if (next_curr.Length2() > abort_dist2) break;
  676. }
  677. // Merge edge intersections (curr_int and next_int) into curr_int
  678. merged = true;
  679. curr_int->Direction = new_direction;
  680. curr_int->Parallel = new_parallel;
  681. curr_int->Point = new_point;
  682. curr_int->TexV = new_tex_v;
  683. curr_int->PointCount = new_count;
  684. curr_int->NextSegmentID = next_int->NextSegmentID;
  685. curr_int->Fold = curr_int->Fold || next_int->Fold;
  686. // Decrement number of edge intersections
  687. num_intersections[edge]--;
  688. // Advance iidx_r to shift subsequent entries backwards in result.
  689. iidx_r++;
  690. // If we are at the end then break:
  691. if (iidx_r == num_isects) {
  692. break;
  693. }
  694. // Advance next_int and next_seg.
  695. next_int = &(intersection[iidx_r + 1][edge]);
  696. next_seg = &(segment[next_int->NextSegmentID]);
  697. } // while <merging needed>
  698. // Copy from "read index" to "write index"
  699. write_int->PointCount = curr_int->PointCount;
  700. write_int->NextSegmentID = curr_int->NextSegmentID;
  701. write_int->Point = curr_int->Point;
  702. write_int->TexV = curr_int->TexV;
  703. write_int->Direction = curr_int->Direction;
  704. write_int->Fold = curr_int->Fold;
  705. } // for iidx
  706. // If iidx_r is exactly equal to num_isects (rather than being larger by one) at this
  707. // point, this means that the last intersection was not merged with the previous one. In
  708. // this case, we need to do one last copy:
  709. if (iidx_r == num_isects) {
  710. LineSegmentIntersection *write_int = &(intersection[iidx_w][edge]);
  711. LineSegmentIntersection *curr_int = &(intersection[iidx_r][edge]);
  712. write_int->PointCount = curr_int->PointCount;
  713. write_int->NextSegmentID = curr_int->NextSegmentID;
  714. write_int->Point = curr_int->Point;
  715. write_int->TexV = curr_int->TexV;
  716. write_int->Direction = curr_int->Direction;
  717. write_int->Fold = curr_int->Fold;
  718. }
  719. #ifdef ENABLE_WWDEBUGGING
  720. // Testing code - ensure total PointCount fits the number of points
  721. unsigned int total_cnt = 0;
  722. for (unsigned int nidx = 0; nidx <= num_intersections[edge]; nidx++) {
  723. total_cnt += intersection[nidx][edge].PointCount;
  724. }
  725. assert(total_cnt == point_cnt);
  726. #endif
  727. } // for edge
  728. } // while (merged)
  729. } // if (Is_Merge_Intersections())
  730. /*
  731. ** Find vertex positions, generate vertices and triangles:
  732. ** Since we can have top/bottom intersections merged, we need to skip points if both the top
  733. ** and bottom intersections are merged, generate triangle fans if one of the sides is merged
  734. ** and the other isnt, and generate triangle strips otherwise.
  735. */
  736. // Configure vertex array and setup renderer.
  737. unsigned int vnum = num_intersections[TOP_EDGE] + num_intersections[BOTTOM_EDGE];
  738. VertexFormatXYZDUV1 *vArray=new VertexFormatXYZDUV1[vnum];
  739. TriIndex v_index_array[MAX_SEGLINE_POLY_BUFFER_SIZE];
  740. // Vertex and triangle indices
  741. unsigned int vidx = 0;
  742. unsigned int tidx = 0;
  743. // GENERALIZE FOR WHEN NO TEXTURE (DO NOT SET UV IN THESE CASES? NEED TO GENERALIZE FOR DIFFERENT TEXTURING MODES ANYWAY).
  744. // "Prime the pump" with two vertices (pick nearest point on each direction line):
  745. Vector3 &top_dir = intersection[1][TOP_EDGE].Direction;
  746. top = top_dir * Vector3::Dot_Product(points[0], top_dir);
  747. Vector3 &bottom_dir = intersection[1][BOTTOM_EDGE].Direction;
  748. bottom = bottom_dir * Vector3::Dot_Product(points[0], bottom_dir);
  749. vArray[vidx].x = top.X;
  750. vArray[vidx].y = top.Y;
  751. vArray[vidx].z = top.Z;
  752. vArray[vidx].u1 = u_values[0] + uv_offset.X;
  753. vArray[vidx].v1 = intersection[1][TOP_EDGE].TexV + uv_offset.Y;
  754. vidx++;
  755. vArray[vidx].x = bottom.X;
  756. vArray[vidx].y = bottom.Y;
  757. vArray[vidx].z = bottom.Z;
  758. vArray[vidx].u1 = u_values[1] + uv_offset.X;
  759. vArray[vidx].v1 = intersection[1][BOTTOM_EDGE].TexV + uv_offset.Y;
  760. vidx++;
  761. unsigned int last_top_vidx = 0;
  762. unsigned int last_bottom_vidx = 1;
  763. // Loop over intersections, create new vertices and triangles.
  764. unsigned int top_int_idx = 1; // Skip "pre-first-point" dummy intersection
  765. unsigned int bottom_int_idx = 1; // Skip "pre-first-point" dummy intersection
  766. pidx = 0;
  767. unsigned int residual_top_points = intersection[1][TOP_EDGE].PointCount;
  768. unsigned int residual_bottom_points = intersection[1][BOTTOM_EDGE].PointCount;
  769. // Reduce both pointcounts by the same amount so the smaller one is 1 (skip points)
  770. unsigned int delta = MIN(residual_top_points, residual_bottom_points) - 1;
  771. residual_top_points -= delta;
  772. residual_bottom_points -= delta;
  773. pidx += delta;
  774. for (; ; ) {
  775. if (residual_top_points == 1 && residual_bottom_points == 1) {
  776. // Advance both intersections, creating a tristrip segment
  777. v_index_array[tidx].I = last_top_vidx;
  778. v_index_array[tidx].J = last_bottom_vidx;
  779. v_index_array[tidx].K = vidx;
  780. tidx++;
  781. v_index_array[tidx].I = last_bottom_vidx;
  782. v_index_array[tidx].J = vidx + 1;
  783. v_index_array[tidx].K = vidx;
  784. tidx++;
  785. last_top_vidx = vidx;
  786. last_bottom_vidx = vidx + 1;
  787. // Advance both intersections.
  788. top_int_idx++;
  789. bottom_int_idx++;
  790. residual_top_points = intersection[top_int_idx][TOP_EDGE].PointCount;
  791. residual_bottom_points = intersection[bottom_int_idx][BOTTOM_EDGE].PointCount;
  792. // Advance point index (must do here because the new point index is used below):
  793. pidx++;
  794. // Generate two vertices for next point by picking nearest point on each direction line
  795. Vector3 &top_dir = intersection[top_int_idx][TOP_EDGE].Direction;
  796. top = top_dir * Vector3::Dot_Product(points[pidx], top_dir);
  797. Vector3 &bottom_dir = intersection[bottom_int_idx][BOTTOM_EDGE].Direction;
  798. bottom = bottom_dir * Vector3::Dot_Product(points[pidx], bottom_dir);
  799. vArray[vidx].x = top.X;
  800. vArray[vidx].y = top.Y;
  801. vArray[vidx].z = top.Z;
  802. vArray[vidx].u1 = u_values[0] + uv_offset.X;
  803. vArray[vidx].v1 = intersection[top_int_idx][TOP_EDGE].TexV + uv_offset.Y;
  804. vidx++;
  805. vArray[vidx].x = bottom.X;
  806. vArray[vidx].y = bottom.Y;
  807. vArray[vidx].z = bottom.Z;
  808. vArray[vidx].u1 = u_values[1] + uv_offset.X;
  809. vArray[vidx].v1 = intersection[bottom_int_idx][BOTTOM_EDGE].TexV + uv_offset.Y;
  810. vidx++;
  811. } else {
  812. // Exactly one of the pointcounts is greater than one - advance it and draw one triangle
  813. if (residual_top_points > 1) {
  814. // Draw one triangle (fan segment)
  815. v_index_array[tidx].I = last_top_vidx;
  816. v_index_array[tidx].J = last_bottom_vidx;
  817. v_index_array[tidx].K = vidx;
  818. tidx++;
  819. last_bottom_vidx = vidx;
  820. // Advance bottom intersection only
  821. residual_top_points--;
  822. bottom_int_idx++;
  823. residual_bottom_points = intersection[bottom_int_idx][BOTTOM_EDGE].PointCount;
  824. // Advance point index (must do here because the new point index is used below):
  825. pidx++;
  826. // Generate bottom vertex by picking nearest point on bottom direction line
  827. Vector3 &bottom_dir = intersection[bottom_int_idx][BOTTOM_EDGE].Direction;
  828. bottom = bottom_dir * Vector3::Dot_Product(points[pidx], bottom_dir);
  829. vArray[vidx].x = bottom.X;
  830. vArray[vidx].y = bottom.Y;
  831. vArray[vidx].z = bottom.Z;
  832. vArray[vidx].u1 = u_values[1] + uv_offset.X;
  833. vArray[vidx].v1 = intersection[bottom_int_idx][BOTTOM_EDGE].TexV + uv_offset.Y;
  834. vidx++;
  835. } else {
  836. // residual_bottom_points > 1
  837. // Draw one triangle (fan segment)
  838. v_index_array[tidx].I = last_top_vidx;
  839. v_index_array[tidx].J = last_bottom_vidx;
  840. v_index_array[tidx].K = vidx;
  841. tidx++;
  842. last_top_vidx = vidx;
  843. // Advance top intersection only
  844. residual_bottom_points--;
  845. top_int_idx++;
  846. residual_top_points = intersection[top_int_idx][TOP_EDGE].PointCount;
  847. // Advance point index (must do here because the new point index is used below):
  848. pidx++;
  849. // Generate top vertex by picking nearest point on top direction line
  850. Vector3 &top_dir = intersection[top_int_idx][TOP_EDGE].Direction;
  851. top = top_dir * Vector3::Dot_Product(points[pidx], top_dir);
  852. vArray[vidx].x = top.X;
  853. vArray[vidx].y = top.Y;
  854. vArray[vidx].z = top.Z;
  855. vArray[vidx].u1 = u_values[0] + uv_offset.X;
  856. vArray[vidx].v1 = intersection[top_int_idx][TOP_EDGE].TexV + uv_offset.Y;
  857. vidx++;
  858. }
  859. }
  860. // Reduce both pointcounts by the same amount so the smaller one is 1 (skip points)
  861. delta = MIN(residual_top_points, residual_bottom_points) - 1;
  862. residual_top_points -= delta;
  863. residual_bottom_points -= delta;
  864. pidx += delta;
  865. // Exit conditions
  866. if ( (top_int_idx >= num_intersections[TOP_EDGE] && residual_top_points == 1) ||
  867. (bottom_int_idx >= num_intersections[BOTTOM_EDGE] && residual_bottom_points == 1)) {
  868. // Debugging check - if either intersection index is before end, both of them should be
  869. // and the points should be before the end.
  870. assert(top_int_idx == num_intersections[TOP_EDGE]);
  871. assert(bottom_int_idx == num_intersections[BOTTOM_EDGE]);
  872. assert(pidx == point_cnt - 1);
  873. break;
  874. }
  875. }
  876. /*
  877. ** Set color, opacity, vertex flags:
  878. */
  879. // If color is not white or opacity not 100%, enable gradient in shader and in renderer - otherwise disable.
  880. unsigned int rgba;
  881. rgba=DX8Wrapper::Convert_Color(Color,Opacity);
  882. bool rgba_all=(rgba==0xFFFFFFFF);
  883. // Enable sorting if sorting has not been disabled and line is translucent and alpha testing is not enabled.
  884. bool sorting = (!Is_Sorting_Disabled()) && (Shader.Get_Dst_Blend_Func() != ShaderClass::DSTBLEND_ZERO && Shader.Get_Alpha_Test() == ShaderClass::ALPHATEST_DISABLE);
  885. ShaderClass shader = Shader;
  886. shader.Set_Cull_Mode(ShaderClass::CULL_MODE_DISABLE);
  887. VertexMaterialClass *mat;
  888. if (!rgba_all) {
  889. shader.Set_Primary_Gradient(ShaderClass::GRADIENT_MODULATE);
  890. for (vidx = 0; vidx < vnum; vidx++) vArray[vidx].diffuse=rgba;
  891. mat=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE);
  892. } else {
  893. shader.Set_Primary_Gradient(ShaderClass::GRADIENT_DISABLE);
  894. mat=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_NODIFFUSE);
  895. }
  896. // If Texture is non-NULL enable texturing in shader - otherwise disable.
  897. if (Texture) {
  898. shader.Set_Texturing(ShaderClass::TEXTURING_ENABLE);
  899. } else {
  900. shader.Set_Texturing(ShaderClass::TEXTURING_DISABLE);
  901. }
  902. /*
  903. ** Render
  904. */
  905. DynamicVBAccessClass Verts((sorting?BUFFER_TYPE_DYNAMIC_SORTING:BUFFER_TYPE_DYNAMIC_DX8),dynamic_fvf_type,vnum);
  906. // Copy in the data to the VB
  907. {
  908. DynamicVBAccessClass::WriteLockClass Lock(&Verts);
  909. unsigned int i;
  910. unsigned char *vb=(unsigned char*)Lock.Get_Formatted_Vertex_Array();
  911. const FVFInfoClass& fvfinfo=Verts.FVF_Info();
  912. for (i=0; i<vnum; i++)
  913. {
  914. // Copy Locations
  915. ((Vector3*)(vb+fvfinfo.Get_Location_Offset()))->X=vArray[i].x;
  916. ((Vector3*)(vb+fvfinfo.Get_Location_Offset()))->Y=vArray[i].y;
  917. ((Vector3*)(vb+fvfinfo.Get_Location_Offset()))->Z=vArray[i].z;
  918. *(unsigned int*)(vb+fvfinfo.Get_Diffuse_Offset())=vArray[i].diffuse;
  919. ((Vector2*)(vb+fvfinfo.Get_Tex_Offset(0)))->U=vArray[i].u1;
  920. ((Vector2*)(vb+fvfinfo.Get_Tex_Offset(0)))->V=vArray[i].v1;
  921. vb+=fvfinfo.Get_FVF_Size();
  922. }
  923. } // copy
  924. DynamicIBAccessClass ib_access((sorting?BUFFER_TYPE_DYNAMIC_SORTING:BUFFER_TYPE_DYNAMIC_DX8),tidx*3);
  925. {
  926. unsigned int i;
  927. DynamicIBAccessClass::WriteLockClass lock(&ib_access);
  928. unsigned short* inds=lock.Get_Index_Array();
  929. for (i=0; i<tidx; i++)
  930. {
  931. *inds++=v_index_array[i].I;
  932. *inds++=v_index_array[i].J;
  933. *inds++=v_index_array[i].K;
  934. }
  935. }
  936. DX8Wrapper::Set_Index_Buffer(ib_access,0);
  937. DX8Wrapper::Set_Vertex_Buffer(Verts);
  938. DX8Wrapper::Set_Material(mat);
  939. DX8Wrapper::Set_Texture(0,Texture);
  940. DX8Wrapper::Set_Shader(shader);
  941. if (sorting) {
  942. SortingRendererClass::Insert_Triangles(obj_sphere,0,tidx,0,vnum);
  943. } else {
  944. DX8Wrapper::Draw_Triangles(0,tidx,0,vnum);
  945. }
  946. REF_PTR_RELEASE(mat);
  947. delete [] vArray;
  948. } // Chunking loop
  949. DX8Wrapper::Set_Transform(D3DTS_VIEW,view);
  950. }
  951. void SegLineRendererClass::subdivision_util(unsigned int point_cnt, const Vector3 *xformed_pts,
  952. const float *base_tex_v, unsigned int *p_sub_point_cnt, Vector3 *xformed_subdiv_pts,
  953. float *subdiv_tex_v)
  954. {
  955. // CAUTION: freezing the random offsets will make it more readily apparent that the offsets
  956. // are in camera space rather than worldspace.
  957. int freeze_random = Is_Freeze_Random();
  958. Random3Class randomize;
  959. const float oo_int_max = 1.0f / (float)INT_MAX;
  960. Vector3SolidBoxRandomizer randomizer(Vector3(1,1,1));
  961. Vector3 randvec(0,0,0);
  962. unsigned int sub_pidx = 0;
  963. struct SegLineSubdivision {
  964. Vector3 StartPos;
  965. Vector3 EndPos;
  966. float StartTexV; // V texture coordinate of start point
  967. float EndTexV; // V texture coordinate of end point
  968. float Rand;
  969. unsigned int Level; // Subdivision level
  970. };
  971. SegLineSubdivision stack[2 * MAX_SEGLINE_SUBDIV_LEVELS]; // Maximum number needed
  972. int tos = 0;
  973. for (unsigned int pidx = 0; pidx < point_cnt - 1; pidx++) {
  974. // Subdivide the (pidx, pidx + 1) segment. Produce pidx and all subdivided points up to
  975. // (not including) pidx + 1.
  976. tos = 0;
  977. stack[0].StartPos = xformed_pts[pidx];
  978. stack[0].EndPos = xformed_pts[pidx + 1];
  979. stack[0].StartTexV = base_tex_v[pidx];
  980. stack[0].EndTexV = base_tex_v[pidx + 1];
  981. stack[0].Rand = NoiseAmplitude;
  982. stack[0].Level = 0;
  983. for (; tos >= 0;) {
  984. if (stack[tos].Level == SubdivisionLevel) {
  985. // Generate point location and texture V coordinate
  986. xformed_subdiv_pts[sub_pidx] = stack[tos].StartPos;
  987. subdiv_tex_v[sub_pidx++] = stack[tos].StartTexV;
  988. // Pop
  989. tos--;
  990. } else {
  991. // Recurse down: pop existing entry and push two subdivided ones.
  992. if (freeze_random) {
  993. randvec.Set(randomize * oo_int_max, randomize * oo_int_max, randomize * oo_int_max);
  994. } else {
  995. randomizer.Get_Vector(randvec);
  996. }
  997. stack[tos + 1].StartPos = stack[tos].StartPos;
  998. stack[tos + 1].EndPos = (stack[tos].StartPos + stack[tos].EndPos) * 0.5f + randvec * stack[tos].Rand;
  999. stack[tos + 1].StartTexV = stack[tos].StartTexV;
  1000. stack[tos + 1].EndTexV = (stack[tos].StartTexV + stack[tos].EndTexV) * 0.5f;
  1001. stack[tos + 1].Rand = stack[tos].Rand * 0.5f;
  1002. stack[tos + 1].Level = stack[tos].Level + 1;
  1003. stack[tos].StartPos = stack[tos + 1].EndPos;
  1004. // stack[tos].EndPos already has the right value
  1005. stack[tos].StartTexV = stack[tos + 1].EndTexV;
  1006. // stack[tos].EndTexV already has the right value
  1007. stack[tos].Rand = stack[tos + 1].Rand;
  1008. stack[tos].Level = stack[tos + 1].Level;
  1009. tos++;
  1010. }
  1011. }
  1012. }
  1013. // Last point
  1014. xformed_subdiv_pts[sub_pidx] = xformed_pts[point_cnt - 1];
  1015. subdiv_tex_v[sub_pidx++] = base_tex_v[point_cnt - 1];
  1016. // Output:
  1017. *p_sub_point_cnt = sub_pidx;
  1018. }
  1019. #endif //0