Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

feat(w3ddevice): vehicle headlights light the ground on Direct3D 11

Olcay Seyganb2e5881c80fb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a52b249ed..a503f99d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -420,6 +420,7 @@ found and fixed — EA's own, not port damage.**
- 625 sharpened textures no longer turn black from the normal camera height. Their far-off copies were made by a tool that dimmed each one by how see-through it was, and some of these pictures are almost entirely see-through in a layer the game never shows, so the tech reinforcement pad in the middle of Twilight Flame drew pitch black unless you zoomed right in. Its far copy measured 1.5 out of 255 where the close one measured 118. They are made again the way EA made theirs, and the pad keeps its colour at every zoom.
- A damaged building looks damaged, not carved out of marble. The damaged and burning versions of a building's skin are separate pictures a quarter the size of the healthy one, and the surface detail made from them spread one blotch of soot into a hill across a whole wall panel, so a command centre under fire turned black and white. They draw flat now, and the panels, rivets and deck stripes show through the soot again.
- A tank keeps its surface detail when it fires. The flash of a gun, an explosion or a fire lights whatever stands next to it, and that light used to switch the whole model back to the old flat lighting for as long as it lasted, so every shot and every blast nearby wiped the relief off a vehicle for a moment. The flash is added on top now and the sun keeps drawing the detail.
+- Headlights light the road. On a night map a Humvee, an Avenger or a truck used to drive behind two glowing cones that lit nothing, and the ground in front of it stayed as dark as the rest of the map. Now the lamps throw a warm pool of light ahead of the vehicle that moves with it, across the ground, the buildings and the other units standing in it. Most of a map's trees and its water are not lit by it yet. The sixteen lit vehicles nearest the camera shine; an enemy's lamps show only where you can see the enemy. Twenty lit vehicles on Dark Night at 1920x1080 ran at 2.63ms a frame against 2.67ms without, which is inside the noise. It is part of the new picture: on the old renderer or the Classic graphics setting the lamps are the glowing cones they always were.
- A long thin texture loads at the size it was drawn at. Anything wider than eight to one used to be stretched onto a bigger, blurrier one, because that was the limit of a 2002 graphics card; the card is asked now, and modern ones have no such limit.
- Anything standing still keeps its shadow in the fog. A town you have already walked through used
to sit on flat ground the moment you looked away, buildings and derricks and walls with nothing
diff --git a/GeneralsMD/Code/Data/Cinema/headlights.txt b/GeneralsMD/Code/Data/Cinema/headlights.txt
new file mode 100644
index 000000000..0d3a1de8a
--- /dev/null
+++ b/GeneralsMD/Code/Data/Cinema/headlights.txt
@@ -0,0 +1,7 @@
+# Vehicle headlights on Dark Night, the camera for Scenarios/headlights.txt: the village square
+# from the south-west, the column of lit vehicles left of the tall tower with the paving in front of
+# them. The cut is repeated because one at the start of a match does not always hold. Shot at
+# frame 420 with -screenshot, and the frame-time runs keep it for 1200 frames.
+0.5 cut 1820 1740 0.9 45 14
+1.0 cut 1820 1740 0.9 45 14
+5.0 cut 1820 1740 0.9 45 14
diff --git a/GeneralsMD/Code/Data/Scenarios/headlights.txt b/GeneralsMD/Code/Data/Scenarios/headlights.txt
new file mode 100644
index 000000000..b6e59ec05
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/headlights.txt
@@ -0,0 +1,24 @@
+# Vehicle headlights on Dark Night: twenty vehicles of seat 0 with lamps (Humvees, Avengers, big
+# rigs, double-decker buses) and four Crusaders without drive onto the village square from the
+# south-west, so their lights fall across the paving, the towers and the trees round it, and on
+# each other. Used for the headlight before/after pictures and the frame-time measurement with
+# twenty lit vehicles in view.
+#
+# generals.exe -win -xres 1920 -yres 1080 -msaa 0 -quickstart -noshellmap -multiInstance
+# -noFPSLimit -map "Maps\Dark Night\Dark Night.map" -autoskirmish 2 -takeover -observer
+# -side 0 FactionAmerica -side 1 FactionChina -seed 1 -scenario headlights
+# -cinema headlights -turbo -screenshot 420 -maxframes 480
+#
+# 2026-10-05: 20 lit, the nearest 16 shining. Frame time without -turbo, -maxframes 1200, three
+# runs a side: 2.67ms a frame mean without the lights and 2.63ms with, CRC 0x1366F3D5 both.
+
+30 spawn 0 AmericaVehicleHumvee 10 1600 1640 35
+30 spawn 0 AmericaTankAvenger 6 1640 1540 40
+30 spawn 0 BigRig 2 1520 1720 50
+30 spawn 0 DoubleDeckerTourBus 2 1500 1600 50
+30 spawn 0 AmericaTankCrusader 4 1700 1480 40
+60 move 0 AmericaVehicleHumvee 1860 1800
+60 move 0 AmericaTankAvenger 1880 1720
+60 move 0 BigRig 1820 1840
+60 move 0 DoubleDeckerTourBus 1800 1760
+60 move 0 AmericaTankCrusader 1900 1660
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h
index 6819222fa..1dea9298e 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/Module/W3DModelDraw.h
@@ -358,6 +358,9 @@ public:
/// the draw method
virtual void doDrawModule(const Matrix3D* transformMtx);
+ /// Hands the frame's lit headlights to the Direct3D 11 frame, nearest the camera first. Once a
+ /// frame, after the smooth motion has placed every model and before anything is drawn.
+ static void lightHeadlights(const Vector3& cameraPosition);
virtual void setShadowsEnabled(Bool enable);
virtual void releaseShadows(void); ///< frees all shadow resources used by this module - used by Options screen.
virtual void allocateShadows(void); ///< create shadow resources if not already present. Used by Options screen.
@@ -527,6 +530,9 @@ private:
ParticleSystemIDVec m_particleSystemIDs; ///< The ID numbers of the particle systems currently running.
std::vector<ModelConditionInfo::HideShowSubObjInfo> m_subObjectVec;
Bool m_hideHeadlights;
+ Bool m_hasHeadlights; ///< the model has a HEADLIGHT sub-object, counted by hideAllHeadlights
+ Bool m_headlightQueued; ///< on lightHeadlights' list of lit models
+ UnsignedInt m_headlightPass; ///< the draw pass that last found its lights on
Bool m_pauseAnimation;
Int m_animationMode;
SmoothMotionTrack m_smoothMotion; ///< R1: the render object's last two logic transforms
@@ -542,6 +548,7 @@ private:
void adjustAnimSpeedToMovementSpeed();
static void hideAllMuzzleFlashes(const ModelConditionInfo* state, RenderObjClass* renderObject);
void hideAllHeadlights(Bool hide);
+ Bool headlightBeam(Vector3& origin, Vector3& direction, Real& reach) const;
#if defined(_DEBUG) || defined(_INTERNAL) //art wants to see buildings without flags as a test.
void hideGarrisonFlags(Bool hide);
#endif
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp
index 12d5b950e..adc103105 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp
@@ -76,8 +76,20 @@
#include "WW3D2/rendobj.h"
#include "WW3D2/mesh.h"
#include "WW3D2/meshmdl.h"
+#include "WW3D2/dx11runtime.h"
+#include "WW3D2/ffshader.h"
#include "Common/BitFlagsIO.h"
+#include <algorithm>
+
+/// Models whose headlights were showing the last time the drawables were drawn. A render pass
+/// draws them only when the logic clock has moved (W3DView::update), which with the frame rate
+/// uncapped is a few passes in ten, so the list is kept between draws and only a pass that drew
+/// something takes off what it did not draw (W3DModelDraw::lightHeadlights).
+static std::vector<W3DModelDraw*> s_headlightQueue;
+static UnsignedInt s_headlightPass = 1;
+static Bool s_headlightDrawn = FALSE;
+
#ifdef _INTERNAL
// for occasional debugging...
//#pragma optimize("", off)
@@ -1743,6 +1755,9 @@ W3DModelDraw::W3DModelDraw(Thing *thing, const ModuleData* moduleData) : DrawMod
int i;
m_animationMode = RenderObjClass::ANIM_MODE_LOOP;
m_hideHeadlights = true;
+ m_hasHeadlights = false;
+ m_headlightQueued = false;
+ m_headlightPass = 0;
m_pauseAnimation = false;
m_curState = NULL;
m_hexColor = 0;
@@ -1818,6 +1833,13 @@ void W3DModelDraw::onDrawableBoundToObject(void)
//-------------------------------------------------------------------------------------------------
W3DModelDraw::~W3DModelDraw(void)
{
+ if (m_headlightQueued)
+ {
+ std::vector<W3DModelDraw*>::iterator it = std::find(s_headlightQueue.begin(), s_headlightQueue.end(), this);
+ if (it != s_headlightQueue.end())
+ s_headlightQueue.erase(it);
+ }
+
if (m_trackRenderObject && TheTerrainTracksRenderObjClassSystem)
{
TheTerrainTracksRenderObjClassSystem->unbindTrack(m_trackRenderObject);
@@ -2386,11 +2408,31 @@ void W3DModelDraw::doDrawModule(const Matrix3D* transformMtx)
const W3DModelDrawModuleData *modData = getW3DModelDrawModuleData();
if ( modData->m_particlesAttachedToAnimatedBones )
- updateBonesForClientParticleSystems();// LORENZEN ADDED THIS
+ updateBonesForClientParticleSystems();// LORENZEN ADDED THIS
// IT REPOSITIONS PARTICLESYSTEMS TO TSTAY IN SYNC WITH ANIMATED BONES
-
+
handleClientRecoil();
+ // A vehicle on a night map lights what is in front of it (lightHeadlights). Drawable::draw has
+ // already returned for anything hidden, stealthed or under the shroud, so an enemy's lamps never
+ // show where the enemy does not. Rooftop lamps on buildings and aircraft lights stay beams only.
+ s_headlightDrawn = TRUE;
+ if (m_hasHeadlights && !m_hideHeadlights && m_renderObject && !m_renderObject->Is_Hidden()
+ && Direct3D11_Is_Active())
+ {
+ const Drawable* draw = getDrawable();
+ const Object* obj = draw->getObject();
+ if (!draw->isKindOf(KINDOF_STRUCTURE) && !draw->isKindOf(KINDOF_AIRCRAFT)
+ && (obj == NULL || !obj->isEffectivelyDead()))
+ {
+ m_headlightPass = s_headlightPass;
+ if (!m_headlightQueued)
+ {
+ m_headlightQueued = true;
+ s_headlightQueue.push_back(this);
+ }
+ }
+ }
}
//-------------------------------------------------------------------------------------------------
@@ -3166,20 +3208,164 @@ void W3DModelDraw::hideGarrisonFlags(Bool hide)
/** Hides all subobjects which are headlights. Used to disable lights on models during the day.*/
void W3DModelDraw::hideAllHeadlights(Bool hide)
{
+ m_hasHeadlights = false;
if (m_renderObject)
{
for (Int subObj = 0; subObj < m_renderObject->Get_Num_Sub_Objects(); subObj++)
- {
+ {
RenderObjClass* test = m_renderObject->Get_Sub_Object(subObj);
if (strstr(test->Get_Name(),"HEADLIGHT"))
{
test->Set_Hidden(hide);
+ m_hasHeadlights = true;
}
test->Release_Ref();
}
}
}
+//-------------------------------------------------------------------------------------------------
+/** Where this model's headlights shine from and which way, out of its visible HEADLIGHT beam meshes:
+ * the beam starts at the mesh's pivot and runs along whichever of its own axes reaches furthest
+ * from it, +Y on 84 of the 95 beams in W3DZH.big and +X on the Avenger and the train. The origin
+ * is the middle of the mesh across that axis, so a mesh holding both lamps puts one light between
+ * them. Several meshes are averaged into one light. FALSE when no beam is showing. */
+Bool W3DModelDraw::headlightBeam(Vector3& origin, Vector3& direction, Real& reach) const
+{
+ origin.Set(0.0f, 0.0f, 0.0f);
+ direction.Set(0.0f, 0.0f, 0.0f);
+ reach = 0.0f;
+ if (m_renderObject == NULL)
+ return FALSE;
+ Int beams = 0;
+ for (Int subObj = 0; subObj < m_renderObject->Get_Num_Sub_Objects(); subObj++)
+ {
+ RenderObjClass* test = m_renderObject->Get_Sub_Object(subObj);
+ if (!test->Is_Hidden() && strstr(test->Get_Name(), "HEADLIGHT"))
+ {
+ AABoxClass box;
+ test->Get_Obj_Space_Bounding_Box(box);
+ const Vector3 lo = box.Center - box.Extent;
+ const Vector3 hi = box.Center + box.Extent;
+ Int axis = 0;
+ Real length = 0.0f;
+ Real sign = 1.0f;
+ for (Int a = 0; a < 3; ++a)
+ {
+ if (hi[a] > length) { length = hi[a]; axis = a; sign = 1.0f; }
+ if (-lo[a] > length) { length = -lo[a]; axis = a; sign = -1.0f; }
+ }
+ // a lamp lens a unit long (the Thunderbolt's) lights nothing
+ if (length > 5.0f)
+ {
+ Vector3 start = box.Center;
+ start[axis] = (sign > 0.0f) ? lo[axis] : hi[axis];
+ Vector3 local(0.0f, 0.0f, 0.0f);
+ local[axis] = sign;
+ const Matrix3D& tm = test->Get_Transform();
+ Vector3 worldStart, worldWay;
+ Matrix3D::Transform_Vector(tm, start, &worldStart);
+ Matrix3D::Rotate_Vector(tm, local, &worldWay);
+ origin += worldStart;
+ direction += worldWay;
+ if (length > reach)
+ reach = length;
+ ++beams;
+ }
+ }
+ test->Release_Ref();
+ }
+ if (beams == 0 || direction.Length2() < 1e-6f)
+ return FALSE;
+ origin /= (Real)beams;
+ direction.Normalize();
+ return TRUE;
+}
+
+//-------------------------------------------------------------------------------------------------
+// ponytail: one spot light per vehicle and a fixed slot count; per-lamp lights or a tiled light
+// list if a convoy close to the camera ever needs more than HEADLIGHT_SLOTS.
+void W3DModelDraw::lightHeadlights(const Vector3& cameraPosition)
+{
+ // a pass that drew the drawables drops whatever it did not find lit
+ if (s_headlightDrawn)
+ {
+ size_t kept = 0;
+ for (size_t i = 0; i < s_headlightQueue.size(); ++i)
+ {
+ W3DModelDraw* draw = s_headlightQueue[i];
+ if (draw->m_headlightPass == s_headlightPass)
+ s_headlightQueue[kept++] = draw;
+ else
+ draw->m_headlightQueued = false;
+ }
+ s_headlightQueue.resize(kept);
+ s_headlightDrawn = FALSE;
+ ++s_headlightPass;
+ }
+
+ // Nearest the camera first, and only those the slots can hold get their beams worked out. The
+ // light only reaches the pixels of the Direct3D 11 frame's shadow-receiving programs, so the
+ // Classic graphics setting (no sun's map) and -d3d9 keep the beam meshes alone.
+ static std::vector< std::pair<Real, W3DModelDraw*> > nearest;
+ nearest.clear();
+ for (size_t i = 0; i < s_headlightQueue.size(); ++i)
+ {
+ W3DModelDraw* draw = s_headlightQueue[i];
+ const Coord3D* pos = draw->getDrawable()->getPosition();
+ const Real dx = pos->x - cameraPosition.X, dy = pos->y - cameraPosition.Y, dz = pos->z - cameraPosition.Z;
+ nearest.push_back(std::make_pair(dx * dx + dy * dy + dz * dz, draw));
+ }
+ std::sort(nearest.begin(), nearest.end());
+
+ // The light reaches two and a half beam meshes (the Humvee's is 39 units, so about 100), and its
+ // cone opens 32 degrees either side of the beam, which takes in both lamps' spread. The beam
+ // meshes do not agree on their pitch (the Humvee's leans up), so the light keeps only their
+ // heading and dips a fixed 11 degrees from it, onto the ground in front.
+ const Real CONE_EDGE_COS = 0.85f;
+ const Real REACH_PER_BEAM = 2.5f;
+ const Real TILT_DOWN = 0.2f;
+
+ float lights[HEADLIGHT_SLOTS][8];
+ unsigned count = 0;
+ // a model whose beams give no light does not take a slot from the next one out
+ for (size_t i = 0; i < nearest.size() && count < HEADLIGHT_SLOTS; ++i)
+ {
+ Vector3 origin, direction;
+ Real beam;
+ if (!nearest[i].second->headlightBeam(origin, direction, beam))
+ continue;
+ direction.Z = 0.0f;
+ if (direction.Length2() < 1e-4f)
+ continue; // a beam pointing straight up or down has no heading
+ direction.Normalize();
+ direction.Z = -TILT_DOWN;
+ direction.Normalize();
+ float* light = lights[count++];
+ light[0] = origin.X; light[1] = origin.Y; light[2] = origin.Z;
+ light[3] = WWMath::Clamp(beam * REACH_PER_BEAM, 60.0f, 200.0f);
+ light[4] = direction.X; light[5] = direction.Y; light[6] = direction.Z;
+ light[7] = CONE_EDGE_COS;
+ }
+ // A warm white lamp over the light the map's terrain is lit by: what a pixel the moon lit gains
+ // per unit of the lamp's light, channel by channel. Divided by each channel of the moon alone,
+ // Dark Night's blue one (0.29, 0.39, 0.87 summed) turned the lit ground orange, so each channel
+ // is taken halfway towards the moon's mean. The floor keeps a near black map from turning a
+ // lamp into a floodlight.
+ const Real LAMP[3] = { 1.6f, 1.48f, 1.25f };
+ const RGBColor& ambient = TheGlobalData->m_terrainAmbient[0];
+ const RGBColor& diffuse = TheGlobalData->m_terrainDiffuse[0];
+ const Real map[3] = { ambient.red + diffuse.red, ambient.green + diffuse.green, ambient.blue + diffuse.blue };
+ const Real mean = (map[0] + map[1] + map[2]) / 3.0f;
+ float gain[3];
+ for (Int c = 0; c < 3; ++c)
+ {
+ const Real moon = sqrtf((map[c] > 0.15f ? map[c] : 0.15f) * (mean > 0.15f ? mean : 0.15f));
+ gain[c] = LAMP[c] / moon;
+ }
+ Direct3D11_Set_Headlights(&lights[0][0], count, gain);
+}
+
//-------------------------------------------------------------------------------------------------
void W3DModelDraw::hideAllMuzzleFlashes(const ModelConditionInfo* state, RenderObjClass* renderObject)
{
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
index 8ef213205..15b669674 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
@@ -71,6 +71,7 @@ static void drawFramerateBar(void);
#include "GameClient/Drawable.h"
#include "W3DDevice/GameClient/W3DSmoothMotion.h"
+#include "W3DDevice/GameClient/Module/W3DModelDraw.h"
#include "GameLogic/Object.h"
#include "GameClient/Keyboard.h" // TheKeyboard; on Windows WinMain.h brought it too
#include "Platform/SleepMilliseconds.h"
@@ -2530,6 +2531,10 @@ AGAIN:
// R1: after the particles read the logic bones (Lorenzen's note above), before anything renders.
smoothMotionApply();
+ // After the smooth motion, so a lamp's light sits where its model is drawn this frame.
+ if (primaryW3DView && primaryW3DView->get3DCamera())
+ W3DModelDraw::lightHeadlights(primaryW3DView->get3DCamera()->Get_Position());
+
if (TheWaterRenderObj)
TheWaterRenderObj->updateRenderTargetTextures(primaryW3DView->get3DCamera()); //do a render into each texture
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
index bcfc8b62a..40c09a05c 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
@@ -324,6 +324,10 @@ DX11BackendClass::DX11BackendClass()
SmokeMapRefused = false;
SmokeMapFilled = false;
SmokeStrength = 0.0f;
+ memset(Headlights, 0, sizeof(Headlights));
+ HeadlightCount = 0;
+ memset(HeadlightGain, 0, sizeof(HeadlightGain));
+ set_identity(WorldFromClip);
for (unsigned stage = 0; stage < DX11_BACKEND_TEXTURE_STAGES; ++stage) {
set_identity(TextureTransforms[stage]);
}
@@ -1181,6 +1185,23 @@ void DX11BackendClass::Set_Terrain_Sun(const float direction[3])
ConstantsChanged = true;
}
+void DX11BackendClass::Set_Headlights(const float * lights, unsigned count, const float gain[3])
+{
+ if (count > HEADLIGHT_SLOTS) {
+ count = HEADLIGHT_SLOTS;
+ }
+ if (count == HeadlightCount && memcmp(HeadlightGain, gain, sizeof(HeadlightGain)) == 0
+ && (count == 0 || memcmp(Headlights, lights, sizeof(float) * 8 * count) == 0)) {
+ return;
+ }
+ if (count > 0) {
+ memcpy(Headlights, lights, sizeof(float) * 8 * count);
+ }
+ memcpy(HeadlightGain, gain, sizeof(HeadlightGain));
+ HeadlightCount = count;
+ ConstantsChanged = true;
+}
+
void DX11BackendClass::Set_Vertex_Format(DWORD fvf)
{
if (VertexFormat != fvf) {
@@ -2247,6 +2268,7 @@ void DX11BackendClass::Upload_Pixel_Constants()
multiply(world_to_camera, Projection, scene_clip);
if (invert(scene_clip, clip_to_world)) {
multiply(clip_to_world, SunViewProjection, ShadowFromClip);
+ memcpy(WorldFromClip, clip_to_world, sizeof(WorldFromClip));
memcpy(ShadowFromClipView, world_to_camera, sizeof(View));
memcpy(ShadowFromClipProjection, Projection, sizeof(Projection));
ShadowFromClipValid = true;
@@ -2270,6 +2292,13 @@ void DX11BackendClass::Upload_Pixel_Constants()
pixel_block.ShadowSoftness[1] = ShadowTexelsPerGap;
pixel_block.ShadowSoftness[2] = ShadowUnitsPerDepth;
pixel_block.ShadowSoftness[3] = ShadowSkyFill;
+ memcpy(pixel_block.WorldFromClip, WorldFromClip, sizeof(pixel_block.WorldFromClip));
+ pixel_block.HeadlightParameters[0] = static_cast<float>(HeadlightCount);
+ memcpy(&pixel_block.HeadlightParameters[1], HeadlightGain, sizeof(HeadlightGain));
+ for (unsigned slot = 0; slot < HeadlightCount; ++slot) {
+ memcpy(pixel_block.HeadlightPosition[slot], &Headlights[slot][0], sizeof(float) * 4);
+ memcpy(pixel_block.HeadlightDirection[slot], &Headlights[slot][4], sizeof(float) * 4);
+ }
}
/* The sky a metal surface mirrors. There is no cubemap: the colour is the map's own sunlight,
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
index 16c9d8bf8..78da50c83 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
@@ -98,6 +98,12 @@ public:
// light is baked into the vertices, so its bump is shaded against this.
void Set_Terrain_Sun(const float direction[3]);
+ // The vehicle headlights for the frame, eight floats a light: world position, reach, world
+ // direction, cosine of the cone's edge. Past HEADLIGHT_SLOTS the rest are dropped; the caller
+ // sorts them nearest first. Zero lights leaves every program's pixels as they were. The gain
+ // is what a pixel gains per channel per unit of light (HEADLIGHT_SAMPLING).
+ void Set_Headlights(const float * lights, unsigned count, const float gain[3]);
+
// The engine bound a texture at this stage that has no D3D11 copy - a render target it drew
// into, most often. Sampling white there paints a full screen quad over the frame, so a draw
// that reads one is refused instead.
@@ -339,6 +345,13 @@ private:
// what is behind it, zero on a frame without; the same for a particle shading itself; one
// for a draw in camera space; and the power on the self-shade.
float VolumeParameters[4];
+ // The headlights (HEADLIGHT_SAMPLING): the pixel's way back to the world, how many slots
+ // are lit and the gain per channel, then each slot's position and reach and its direction
+ // and cone edge.
+ float WorldFromClip[16];
+ float HeadlightParameters[4];
+ float HeadlightPosition[HEADLIGHT_SLOTS][4];
+ float HeadlightDirection[HEADLIGHT_SLOTS][4];
};
// A model under directional lights, drawn by generated programs.
bool Normal_Mapped() const;
@@ -426,6 +439,7 @@ private:
// kept until one of them changes, because an inverse a draw does not need is an inverse nobody
// should pay for.
float ShadowFromClip[16];
+ float WorldFromClip[16];
float ShadowFromClipView[16];
float ShadowFromClipProjection[16];
bool ShadowFromClipValid;
@@ -457,6 +471,10 @@ private:
bool SmokeMapRefused;
bool SmokeMapFilled;
float SmokeStrength;
+ // Set_Headlights' slots, eight floats each, how many are lit and the gain per channel.
+ float Headlights[HEADLIGHT_SLOTS][8];
+ unsigned HeadlightCount;
+ float HeadlightGain[3];
bool Make_Smoke_Map();
void Release_Smoke_Map();
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
index 6441f5ce5..ab077b8b5 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
@@ -290,6 +290,13 @@ void Direct3D11_Set_Terrain_Sun(const float direction[3])
}
}
+void Direct3D11_Set_Headlights(const float * lights, unsigned count, const float gain[3])
+{
+ if (Active) {
+ Backend.Set_Headlights(lights, count, gain);
+ }
+}
+
unsigned long long Direct3D11_Normal_Mapped_Draws()
{
return Active ? Backend.Normal_Mapped_Draw_Count() : 0;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
index c40050f2f..42790b3dd 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
@@ -120,6 +120,10 @@ void Direct3D11_Mirror_Normal_Map(struct IDirect3DBaseTexture9 * normal_map);
// The way the sun's light travels, world space, for the bumped terrain. Set once a frame.
void Direct3D11_Set_Terrain_Sun(const float direction[3]);
+// The vehicle headlights for the frame, nearest the camera first, eight floats each: world
+// position, reach, world direction, cosine of the cone's edge; and what a pixel gains per channel
+// per unit of their light. A Direct3D 9 run ignores them.
+void Direct3D11_Set_Headlights(const float * lights, unsigned count, const float gain[3]);
unsigned long long Direct3D11_Normal_Mapped_Draws();
// The sun's depth buffer. Between Begin and End every draw lands in it and nowhere else, which is
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
index 24e21aa22..44659a8a4 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
@@ -63,6 +63,7 @@ void Direct3D11_Normal_Maps_Enable(bool) {}
bool Direct3D11_Normal_Maps_Active() { return false; }
void Direct3D11_Mirror_Normal_Map(struct IDirect3DBaseTexture9 *) {}
void Direct3D11_Set_Terrain_Sun(const float [3]) {}
+void Direct3D11_Set_Headlights(const float *, unsigned, const float [3]) {}
unsigned long long Direct3D11_Normal_Mapped_Draws() { return 0; }
bool Direct3D11_Begin_Shadow_Map(unsigned) { return false; }
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
index 7f11628ee..2841b10ab 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
@@ -305,18 +305,68 @@ const unsigned NORMAL_MAPPED_LIGHTS = 4;
" else sun = sun_reaching(position);\n" \
" return sun * smoke_reaching(position);\n" \
"}\n" \
+ "\n" \
+ HEADLIGHT_SAMPLING
+
+// Vehicle headlights on a night map, Direct3D 11 only and riding on the smoke's text for that
+// reason: one spot light per lit vehicle, the nearest HEADLIGHT_SLOTS to the camera
+// (W3DModelDraw::lightHeadlights). Each slot is a world position with the reach in w and a world
+// direction with the cosine of the cone's edge in w. The pixel goes back to the world through
+// WorldFromClip, the inverse of the matrix it was drawn with, and its facing comes from the
+// derivatives because the generated programs carry no normal to the pixel half. The light is a
+// gain on the pixel rather than an addition: what the map's own light left at black (the shroud,
+// a black texel) stays black, and a count of zero leaves every pixel exactly as it was. The gain
+// per channel (HeadlightParameters.yzw) is the lamp's warm white over the map's own terrain light,
+// so a pixel the blue moon lit gains what the lamp would have given its texture: under a cold moon
+// the red channel gains most and the lit ground turns warm. The derivatives are taken before the
+// loop, outside any flow control.
+#define HEADLIGHT_SLOTS 16
+#define HEADLIGHT_SLOTS_TEXT "16"
+#define HEADLIGHT_SAMPLING \
+ "float3 headlight_reaching(float4 position)\n" \
+ "{\n" \
+ " float2 ndc = float2(position.x * ShadowViewport.x * 2.0 - 1.0,\n" \
+ " 1.0 - position.y * ShadowViewport.y * 2.0);\n" \
+ " float4 world = mul(float4(ndc, position.z, 1.0), WorldFromClip);\n" \
+ " world.xyz /= world.w;\n" \
+ " float3 facing = cross(ddx(world.xyz), ddy(world.xyz));\n" \
+ " float3 surface = facing * rsqrt(max(dot(facing, facing), 1e-20));\n" \
+ " float light = 0.0;\n" \
+ " int count = (int)HeadlightParameters.x;\n" \
+ " [loop] for (int i = 0; i < count; ++i) {\n" \
+ " float3 to = world.xyz - HeadlightPosition[i].xyz;\n" \
+ " float reach = HeadlightPosition[i].w;\n" \
+ " float dist = length(to);\n" \
+ " if (dist >= reach) continue;\n" \
+ " float3 way = to / max(dist, 0.001);\n" \
+ " float edge = HeadlightDirection[i].w;\n" \
+ " float cone = smoothstep(edge, lerp(edge, 1.0, 0.6), dot(way, HeadlightDirection[i].xyz));\n" \
+ " float near = dist / reach;\n" \
+ " float fall = 1.0 - near * near;\n" \
+ " light += cone * fall * (0.4 + 0.6 * abs(dot(surface, way)));\n" \
+ " }\n" \
+ " // a knee, so a dozen cones over one square do not wash it out white\n" \
+ " light = 2.0 * light / (2.0 + light);\n" \
+ " return light * HeadlightParameters.yzw;\n" \
+ "}\n" \
"\n"
-// The constant block's field for it, declared after SkyUp: DX11BackendClass::PixelConstantBlock.
+// The constant block's fields for it, declared after SkyUp: DX11BackendClass::PixelConstantBlock.
#define VOLUMETRIC_CONSTANTS \
- " float4 VolumeParameters;\n"
+ " float4 VolumeParameters;\n" \
+ " row_major float4x4 WorldFromClip;\n" \
+ " float4 HeadlightParameters;\n" \
+ " float4 HeadlightPosition[" HEADLIGHT_SLOTS_TEXT "];\n" \
+ " float4 HeadlightDirection[" HEADLIGHT_SLOTS_TEXT "];\n"
// SHADOW_APPLY with the smoke in it. A particle takes the shade whatever its own brightness: the
// threshold is there for ground under the shroud, and on smoke it tied the shade to the colour, so
// the fire's glow, lifting a dark plume over the threshold, made it take more shade and go darker.
+// The headlights come after the shade: a shadow is the sun's, and a lamp shines into it.
#define VOLUMETRIC_SHADOW_APPLY SHADOW_LIT \
" if (VolumeParameters.z > 0.5) shadow_lit = 1.0;\n" \
- " current.rgb *= lerp(1.0, light_reaching(input.Position), shadow_lit);\n"
+ " current.rgb *= lerp(1.0, light_reaching(input.Position), shadow_lit);\n" \
+ " current.rgb = saturate(current.rgb * (1.0 + headlight_reaching(input.Position)));\n"
// The HLSL for one description, or false when the description names an operation or an argument
// this does not generate. A refusal is not a failure: the caller keeps the fixed-function path for