Blinn–Phong reflection model

The Blinn–Phong reflection model, also called the modified Phong reflection model, is a modification developed by Jim Blinn to the Phong reflection model.[1]

Blinn–Phong is a shading model used in OpenGL and Direct3D's fixed-function pipeline (before Direct3D 10 and OpenGL 3.1), and is carried out on each vertex as it passes down the graphics pipeline; pixel values between vertices are interpolated by Gouraud shading by default, rather than the more computationally-expensive Phong shading.[2]

Description

Vectors for calculating Phong and Blinn–Phong shading

In Phong shading, one must continually recalculate the dot product between a viewer (V) and the beam from a light-source (L) reflected (R) on a surface.

If, instead, one calculates a halfway vector between the viewer and light-source vectors,

can be replaced with , where is the normalized surface normal. In the above equation, and are both normalized vectors, and is a solution to the equation where is the Householder matrix that reflects a point in the hyperplane that contains the origin and has the normal

This dot product represents the cosine of an angle that is half of the angle represented by Phong's dot product if V, L, N and R all lie in the same plane. This relation between the angles remains approximately true when the vectors don't lie in the same plane, especially when the angles are small. The angle between N and H is therefore sometimes called the halfway angle.

Considering that the angle between the halfway vector and the surface normal is likely to be smaller than the angle between R and V used in Phong's model (unless the surface is viewed from a very steep angle for which it is likely to be larger), and since Phong is using an exponent can be set such that is closer to the former expression.

For front-lit surfaces (specular reflections on surfaces facing the viewer), will result in specular highlights that very closely match the corresponding Phong reflections. However, while the Phong reflections are always round for a flat surface, the Blinn–Phong reflections become elliptical when the surface is viewed from a steep angle. This can be compared to the case where the sun is reflected in the sea close to the horizon, or where a far away street light is reflected in wet pavement, where the reflection will always be much more extended vertically than horizontally.[3]

Visual comparison: Blinn–Phong highlights are larger than Phong with the same exponent, but by lowering the exponent, they can become nearly equivalent.

Additionally, while it can be seen as an approximation to the Phong model, it produces more accurate models of empirically determined bidirectional reflectance distribution functions than Phong for many types of surfaces.[4]

Efficiency

Blinn-Phong will be faster than Phong in the case where the viewer and light are treated to be very remote, such as approaching or at infinity. This is the case for directional lights and orthographic/isometric cameras. In this case, the halfway vector is independent of position and surface curvature simply because the halfway vector is dependent on the direction to viewer's position and the direction to the light's position, which individually converge at this remote distance, hence the halfway vector can be thought of as constant in this case. therefore can be computed once for each light and then used for the entire frame, or indeed while light and viewpoint remain in the same relative position. The same is not true with Phong's method of using the reflection vector which depends on the surface curvature and must be recalculated for each pixel of the image (or for each vertex of the model in the case of vertex lighting). In 3D scenes with perspective cameras, this optimization is not possible.

Code samples

High-Level Shading Language code sample

This sample in High-Level Shading Language is a method of determining the diffuse and specular light from a point light. The light structure, position in space of the surface, view direction vector and the normal of the surface are passed through. A Lighting structure is returned;

The below also needs to clamp certain dot products to zero in the case of negative answers. Without that, light heading away from the camera is treated the same way as light heading towards it. For the specular calculation, an incorrect "halo" of light glancing off the edges of an object and away from the camera might appear as bright as the light directly being reflected towards the camera.

struct Lighting
{
    float3 Diffuse;
    float3 Specular;
};

struct PointLight
{
	float3 position;
	float3 diffuseColor;
	float  diffusePower;
	float3 specularColor;
	float  specularPower;
};

Lighting GetPointLight(PointLight light, float3 pos3D, float3 viewDir, float3 normal)
{
	Lighting OUT;
	if (light.diffusePower > 0)
	{
		float3 lightDir = light.position - pos3D; //3D position in space of the surface
		float distance = length(lightDir);
		lightDir = lightDir / distance; // = normalize(lightDir);
		distance = distance * distance;

		//Intensity of the diffuse light. Saturate to keep within the 0-1 range.
		float NdotL = dot(normal, lightDir);
		float diffuseIntensity = saturate(NdotL);

		// Calculate the diffuse light factoring in light color, power and the attenuation
		OUT.Diffuse = diffuseIntensity * light.diffuseColor * light.diffusePower / distance;

		//Calculate the half vector between the light vector and the view vector.
		float3 H = normalize(lightDir + viewDir);

		//Intensity of the specular light
		float NdotH = dot(normal, H);
		float specularIntensity = pow(saturate(NdotH), specularHardness);

		//Sum up the specular light factoring
		OUT.Specular = specularIntensity * light.specularColor * light.specularPower / distance; 
	}
	return OUT;
}

OpenGL Shading Language code sample

This sample in the OpenGL Shading Language consists of two code files, or shaders. The first one is a so-called vertex shader and implements Phong shading, which is used to interpolate the surface normal between vertices. The second shader is a so-called fragment shader and implements the Blinn–Phong shading model in order to determine the diffuse and specular light from a point light source.

Vertex shader

This vertex shader implements Phong shading:

attribute vec3 inputPosition;
attribute vec3 inputNormal;

uniform mat4 projection, modelview, normalMat;

varying vec3 normalInterp;
varying vec3 vertPos;

void main() {
    gl_Position = projection * modelview * vec4(inputPosition, 1.0);
    vec4 vertPos4 = modelview * vec4(inputPosition, 1.0);
    vertPos = vec3(vertPos4) / vertPos4.w;
    normalInterp = vec3(normalMat * vec4(inputNormal, 0.0));
}

Fragment shader

This fragment shader implements the Blinn–Phong shading model[5] and gamma correction:

precision mediump float;

in vec3 normalInterp;
in vec3 vertPos;

uniform int mode;

const vec3 lightPos = vec3(1.0, 1.0, 1.0);
const vec3 lightColor = vec3(1.0, 1.0, 1.0);
const float lightPower = 40.0;
const vec3 ambientColor = vec3(0.1, 0.0, 0.0);
const vec3 diffuseColor = vec3(0.5, 0.0, 0.0);
const vec3 specColor = vec3(1.0, 1.0, 1.0);
const float shininess = 16.0;
const float screenGamma = 2.2; // Assume the monitor is calibrated to the sRGB color space

void main() {

  vec3 normal = normalize(normalInterp);
  vec3 lightDir = lightPos - vertPos;
  float distance = dot(lightDir, lightDir);
  lightDir = normalize(lightDir);

  float lambertian = max(dot(lightDir, normal), 0.0);
  float specular = 0.0;

  if (lambertian > 0.0) {

    vec3 viewDir = normalize(-vertPos);

    // this is blinn phong
    vec3 halfDir = normalize(lightDir + viewDir);
    float specAngle = max(dot(halfDir, normal), 0.0);
    specular = pow(specAngle, shininess);
       
    // this is phong (for comparison)
    if (mode == 2) {
      vec3 reflectDir = reflect(-lightDir, normal);
      specAngle = max(dot(reflectDir, viewDir), 0.0);
      // note that the exponent is different here
      specular = pow(specAngle, shininess/4.0);
    }
  }
  vec3 colorLinear = ambientColor +
                     diffuseColor * lambertian * lightColor * lightPower / distance +
                     specColor * specular * lightColor * lightPower / distance;
  // apply gamma correction (assume ambientColor, diffuseColor and specColor
  // have been linearized, i.e. have no gamma correction in them)
  vec3 colorGammaCorrected = pow(colorLinear, vec3(1.0 / screenGamma));
  // use the gamma corrected color in the fragment
  gl_FragColor = vec4(colorGammaCorrected, 1.0);
}

The colors ambientColor, diffuseColor and specColor are not supposed to be gamma corrected. If they are colors obtained from gamma-corrected image files (JPEG, PNG, etc.), they need to be linearized before working with them, which is done by scaling the channel values to the range [0, 1] and raising them to the gamma value of the image, which for images in the sRGB color space can be assumed to be about 2.2 (even though for this specific color space, a simple power relation is just an approximation of the actual transformation). Modern graphics APIs have the ability to perform this gamma correction automatically when sampling from a texture or writing to a framebuffer.[6]

See also

References

  1. ^ James F. Blinn (1977). "Models of light reflection for computer synthesized pictures". Proceedings of the 4th annual conference on Computer graphics and interactive techniques. pp. 192–198. CiteSeerX 10.1.1.131.7741. doi:10.1145/563858.563893. ISBN 9781450373555. S2CID 8043767.
  2. ^ Shreiner, Dave; The Khronos OpenGL ARB Working Group (2010). "The Mathematics of Lighting". OpenGL programming guide : the official guide to learning OpenGL, version 3.0 and 3.1 (7th ed.). Pearson Education, Inc. pp. 240–245. ISBN 978-0-321-55262-4.
  3. ^ Krus, Kristofer (2014), Wave Model and Watercraft Model for Simulation of Sea State, Linköping University, p. 97
  4. ^ Ngan, Addy; Durand, Frédo; Matusik, Wojciech (2004). "Experimental validation of analytical BRDF models". ACM SIGGRAPH 2004 Sketches on - SIGGRAPH '04. ACM Press. p. 90. doi:10.1145/1186223.1186336. ISBN 1-59593-836-2. S2CID 9259363. Retrieved 23 April 2019.
  5. ^ "WebGL Example: Phong / Blinn Phong Shading". www.mathematik.uni-marburg.de. Retrieved 2019-09-13.
  6. ^ Framebuffer khronos.org

Read other articles:

Rita Sargsián Información personalNombre de nacimiento Ռիտա Դադայան Nombre en armenio Ռիտա Ալեքսանդրի Սարգսյան Nacimiento 6 de marzo de 1962 Stepanakert, Óblast autónomo del Alto Karabaj (Unión Soviética)Fallecimiento 20 de noviembre de 2020 (58 años)Ereván (Armenia)Causa de muerte COVID-19Nacionalidad ArmeniaLengua materna Armenio FamiliaCónyuge Serzh Sargsyán (1983-2020) Información profesionalOcupación Política y profesora de música Cargo...

Shire of Tambellup Local Government Area van Australië Locatie van Shire of Tambellup in West-Australië Situering Staat West-Australië Hoofdplaats Tambellup Coördinaten 34°2'28ZB, 117°38'31OL Algemene informatie Oppervlakte 1436,3 km² Inwoners 702 (juni 2007)[1] Overig Wards 3 Website www.tambellup.wa.gov.au (en) Portaal    Australië Shire of Tambellup was een Local Government Area (LGA) in Australië in de staat West-Australië. Shire of Tambellup telde in 2007, 702...

De FDGB-Pokal 1985–1986 was de 35ste editie van de strijd om de Oost-Duitse voetbalbeker. De beker werd voor de vierde keer in de clubgeschiedenis gewonnen door 1. FC Lokomotive Leipzig, dat in de finale met 5-1 won van 1. FC Union Berlin. Schema kwartfinale halve finale finale                                        1. FC Union Berlin 3 1 4    BSG Motor Nordhausen 0 2 2    ...

American anti-pornography nonprofit organization Fight the New DrugFormation2009; 14 years ago (2009)Legal status501(c)(3) organization[1]PurposeNonpartisan, secular, non-legislative, and nonprofit anti-pornography & anti-sexual-exploitation organization.HeadquartersSalt Lake City, Utah, United StatesWebsitefightthenewdrug.org Fight the New Drug (FTND) is a nonprofit, secular, and non-legislative anti-pornography organization that is based in Utah.[2][...

2011 American filmThe ZoneFilm posterDirected byJoe SwanbergWritten byJoe SwanbergProduced byJoe SwanbergStarring Sophia Takal Lawrence Michael Levine Kate Lyn Sheil Kentucker Audley Joe Swanberg Adam Wingard Kris Swanberg Dustin Guy Defa Cinematography Joe Swanberg Adam Wingard Edited byJoe SwanbergProductioncompanySwanberry ProductionsRelease date November 3, 2011 (2011-11-03) (AFI Fest) Running time70 minutesCountryUnited StatesLanguageEnglish The Zone is a 2011 American...

For the mountain in Antarctica, see Mount Madison (Antarctica). Mount MadisonEast elevation of Mount Madison, seen from New Hampshire Route 16Highest pointElevation5,367 ft (1,636 m)Prominence466 ft (142 m)[1]Parent peakMount John Quincy Adams[1]ListingWhite Mountain 4000-FootersCoordinates44°19′42″N 71°16′40″W / 44.32833°N 71.27778°W / 44.32833; -71.27778[2]GeographyShow map of New HampshireShow map of the U...

Ukrainian far-right politician and military commander In this name that follows Eastern Slavic naming conventions, the patronymic is Yevheniyovych and the family name is Biletsky. Andriy BiletskyАндрій БілецькийBiletsky in 2017Leader of National CorpsIncumbentAssumed office 14 October 2016People's Deputy of UkraineIn office27 November 2014 – 24 July 2019Preceded byOleksandr Bryhynets [uk]Succeeded byMaryana BezuhlaConstituencyKyiv, No. 217Command...

International airport in San Jose, California, United States serving the Bay Area This article is about the airport in California, United States. For other airports, see San Jose Airport (disambiguation). San Jose Mineta International AirportIATA: SJCICAO: KSJCFAA LID: SJCSummaryAirport typePublicOwner/OperatorCity of San JoseServesBay AreaLocationSan Jose, California, U.S.Opened1939; 84 years ago (1939)Focus city forAlaska Airlines[1]Elevation AMSL62 ft / ...

Archivo:LiriodepueblajpgV.M. Mª de Jesús de Tomelín, 'Lirio de Puebla'. Este artículo o sección necesita referencias que aparezcan en una publicación acreditada.Este aviso fue puesto el 5 de julio de 2013. Venerable Madre Sor María de Jesús de Tomelín, O.I.C La Venerable Madre Sor María De Jesús, El Lirio de PueblaInformación personalNacimiento 21 de febrero de 1579Puebla de los Ángeles, Nueva EspañaFallecimiento 11 de junio de 1637Puebla de los Ángeles, Nueva EspañaInformaci�...

2018 murder in Rio de Janeiro, Brazil Assassination of Marielle FrancoFuneral at Pedro Ernesto PalaceLocationEstácio, Rio de Janeiro, BrazilDateMarch 14, 2018 (2018-03-14)(5 years ago) 09:30 pm (UTC-3)TargetMarielle Franco Anderson GomesWeaponsHK MP5Deaths2Injured1No. of participants2 (Ronnie Lessa, Élcio Vieira de Queiroz) The assassination of Marielle Franco and Anderson Gomes was a crime which took place on March 14, 2018, in Estácio, the central region of the city. ...

Bernhard KohlAustrian bicycle racer Bernhard Kohl during the Nightrace .07 in Waidhofen an der Ybbs on 24 August 2007Personal informationFull nameBernhard KohlBorn (1982-01-04) 4 January 1982 (age 41)Vienna, AustriaHeight1.72 m (5 ft 8 in)Weight61 kg (134 lb)Team informationCurrent teamRetiredDisciplineRoadRoleRiderRider typeClimberAmateur teams2002Elk Haus2003–2004Rabobank GSIII Professional teams2005–2006T-Mobile Team2007–2008Gerolsteiner M...

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Gobabeb – news · newspapers · books · scholar · JSTOR (June 2021) (Learn how and when to remove this template message) Research station in the Namib Desert 23°33′S 15°02′E / 23.550°S 15.033°E / -23.550; 15.033 Aerial view of Goba...

1986 single by Pet Shop Boys This article is about the Pet Shop Boys song. For other songs, see Suburbia (disambiguation) § Songs. This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Suburbia song – news · newspapers · books · scholar · JSTOR (May 2011) (Learn how and when to remove this template mess...

Easter foods, decorations, and traditional folk dress, 2014 Easter in Poland, a public holiday,[1] is one of that country's major holidays, often compared in importance to Christmas.[2]: 30 [3]: 111 [4]: 309 [5][6] Associated with it are many specific customs and traditions.[1][7] Easter has been celebrated in Poland since the country's Christianization in the Middle Ages.[1]...

2014 mixtape by Kevin GatesLuca Brasi 2Mixtape by Kevin GatesReleasedDecember 14, 2014Recorded2014GenreHip hopLength63:15LabelBread Winners' AssociationAtlanticProducerBig Hurt TracksNic NacMark KragenRed on da TrackCapo RedTouchdownBeat ZombieThe RunnersThe MonarchRico LoveDiego AveBobby JohnsonD-TownB.o.BKane BeatzJMikeTODAYEarl & EFRESHM3N IIIGo GrizzlyP-Lo (of The Invasion)Mark Nilan Jr.Jaque BeatsDeezyPresident JeffThe FeatherstonesKevin Gates chronology By Any Means(2014) Lu...

Men's freestyle 55 kg at the 2010 Asian GamesVenueHuagong GymnasiumDate23 November 2010Competitors16 from 16 nationsMedalists  Dilshod Mansurov   Uzbekistan Yang Kyong-il   North Korea Yasuhiro Inaba   Japan Kim Hyo-sub   South Korea← 20062014 → Wrestling at the2010 Asian GamesFreestyleGreco-RomanWomen55 kg55 kg48 kg60 kg60 kg55 kg66 kg66 kg63 kg74 kg74 kg72 kg84 kg84 kg96 kg96 kg120 kg120 kg...

American library organization Illinois Library AssociationAbbreviationILAFormation1896Headquarters33 W. Grand Ave., Suite 401Chicago, IL 60654-6799Membership 3,000Executive DirectorDiane B. FootePresidentMelissa GardnerMain organExecutive BoardBudget $2.7 millionStaff 4Websiteila.org The Illinois Library Association (ILA) is the eighth oldest library association in the world and the third largest state library association in the United States. It is headquartered in Chicago. History The first...

For the French novelist, see Charles Paul de Kock This article includes a list of references, related reading, or external links, but its sources remain unclear because it lacks inline citations. Please help to improve this article by introducing more precise citations. (March 2019) (Learn how and when to remove this template message) Paul de Cock by Joseph-Benoît Suvée, Groeningemuseum Paul Jozef de Cock (21 June 1724, Bruges - 29 December 1801, Bruges) was a Flemish architect and painter....

Former baseball park in Houston, Texas West End ParkWest End Park in 1914 during a game between Houston and New YorkLocation601 Andrews StreetHouston, TexasCoordinates29°45′18″N 95°22′28″W / 29.75493°N 95.37443°W / 29.75493; -95.37443Public transitSan Felipe lineOwnerHouston Buffaloes (1905–1928)Houston Board of Education (1928–1940s)Capacity2,500Record attendance8,300SurfaceGrassConstructionBroke ground1905OpenedApril 1, 1905Renovated1908Closed194...

American rock band Muffs redirects here. For the band's debut album, see The Muffs (album). For the professor of the Bible and religion, see Yochanan Muffs. The MuffsThe Muffs in 2014Background informationOriginLos AngelesGenres Pop punk power pop garage punk[1] Years active 1991–1999 2002–2004 2012–2019 LabelsWarner Bros., Sympathy for the Record Industry, Sub Pop, Reprise, Oglio, Five Foot Two, Honest Don's, Burger RecordsPast membersKim ShattuckCriss CrassMelanie VammenJim La...