10 Replies - 702 Views - Last Post: 01 August 2013 - 11:22 AM Rate Topic: -----

#1 masar77  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 28-May 09

Apply texture to sphere in Direct3d 11

Posted 30 July 2013 - 03:49 PM

I'm trying to apply a texture to sphere. I have used a 3d modelling software to create the sphere with vertices, normals and texcoords exported as .obj file. I parse the file and create a vertex buffer with the data. IDE is Visual C++ 2012. The texture is a 512x256 jpg of earth, it looks grainy and it flickers. Been experimenting with different UV mappings without luck.

Posted Image

This is how a load it:
	D3DX11CreateShaderResourceViewFromFile(dev,        // the Direct3D device
		L"earth.jpg",    
		NULL,           
		NULL,           
		&pTexture,      
		NULL);          
	devcon->PSSetShaderResources(0, 1, &pTexture);



Parsing the obj file:
	if (fileIn) {
		while (fileIn) {
			VERTEX vertex;
			inChar = fileIn.get();
			std::wstring string;
			switch (inChar)
			{		
			case '#':
				inChar = fileIn.get();
				while(inChar != '\n')
					inChar = fileIn.get();
				break;
			case 'v':
				inChar = fileIn.get();
				if (inChar == ' ')	//v - vert position
				{
					fileIn >> x >> y >> z;						
					vVector.push_back(D3DXVECTOR3(x, y, z));
					vertCount++;
				}
				else if(inChar == 'n')	//vn - vert normal
				{
					fileIn >> x >> y >> z;						
					nVector.push_back(D3DXVECTOR3(x, y, z));					
					normCount++;
				}
				else if(inChar == 't')	//vt - vert tex coords
				{			
					fileIn >> u >> v;						
					tVector.push_back(D3DXVECTOR2(u, v));
					texCount++;
				}
				break;
			case 'f': // assuming vectors are filled..
				inChar = fileIn.get();
				if (inChar != ' ')
					break;
				while (!fileIn.eof()) {
					std::getline(fileIn, string);

					size_t pos = 0;
					while((pos = string.find(L"/", pos)) != std::string::npos)
					{
						string.replace(pos, 1, L" ");
						pos++;
					}
					if (string.find(L"f ") != std::wstring::npos)
						string = string.replace(0, 2, L"");
					std::wistringstream iss(string);
					iss.seekg(0, std::ios::beg);
					while (iss >> i) {
						iVector.push_back(i);
					}
				}
				break;
			}
		}
	}

	int vv, vt, vn;
	for (i = 0; i < iVector.size(); i += 3) {
		vv  = iVector.at(i) - 1;
		vt = iVector.at(i + 1) - 1;
		vn = iVector.at(i + 2) - 1;
		VERTEX vertex;
		vertex.X = vVector.at(vv).x;
		vertex.Y = vVector.at(vv).y;
		vertex.Z = vVector.at(vv).z;
		vertex.U = tVector.at(vt).x;
		vertex.V = tVector.at(vt).y;
		vertex.Normal.x = nVector.at(vn).x;
		vertex.Normal.y = nVector.at(vn).y;
		vertex.Normal.z = nVector.at(vn).z;
		vector.push_back(vertex);
	}
	VERTEX vertex;
	vertex.X = 0.0f;
	vertex.Y = 0.0f;
	vertex.Z = 0.0f;
	vector.push_back(vertex);
	wss << L"v: " << vertCount << L" vn: " << normCount << L" vt: " << texCount << L"\n";
	OutputDebugString(wss.str().c_str());
	fileIn.close();



The pixel shader:
	float4 outputColor = (1.0f, 0.0f, 1.0f, 1.0f);
	if (calc == 0) {
		outputColor = lightAmbient;
		float3 lightVector = lightPos.xyz - input.worldPosition.xyz;
		float3 normalVector = input.normal.xyz;
		float distance = length(lightVector);
		//if (distance > range) 
			//return outputColor;
		float diffuseBrightness = saturate(dot(normalize(normalVector), normalize(lightVector)));
		outputColor += diffuseBrightness;
		//outputColor *= lightAtt.x + (lightAtt.y * distance) + (lightAtt.z * (distance * distance));
		outputColor = saturate(outputColor);
			
		outputColor *= Texture.Sample(ss, input.texcoord);
	}
	return outputColor;



The obj file is here

Any ideas what I'm doing wrong? Help appreciated.

This post has been edited by masar77: 30 July 2013 - 03:53 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Apply texture to sphere in Direct3d 11

#2 anonymous26  Icon User is offline

  • D.I.C Lover

Reputation: 1
  • View blog
  • Posts: 3,638
  • Joined: 26-November 10

Re: Apply texture to sphere in Direct3d 11

Posted 30 July 2013 - 06:23 PM

Was this code taken from an example somewhere?
Was This Post Helpful? 0
  • +
  • -

#3 masar77  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 28-May 09

Re: Apply texture to sphere in Direct3d 11

Posted 31 July 2013 - 01:53 AM

View PostButchDean, on 30 July 2013 - 07:23 PM, said:

Was this code taken from an example somewhere?


It is built on a tutorial I walked through here
It covers mapping a cube but not a sphere.

Here's the all of the shader code:
cbuffer ConstantBuffer
{
	float4x4 matFinal;
	float4x4 matWorld;
	float4x4 matRotate;
	float4 lightDir;
	float4 lightPos;
	float4 lightAtt;
	float4 lightAmbient;
	float4 lightDiffuse;
	float4 pos[2];
	float range;
	uint calc;
}

Texture2D Texture;
SamplerState ss;

struct VOut
{
	float4 position : SV_POSITION;
	float4 worldPosition : POSITION;
	float4 normal : NORMAL;
	float2 texcoord : TEXCOORD;    // texture coordinates
};

VOut VShader(float4 position : POSITION, float4 normal : NORMAL, float2 texcoord : TEXCOORD)
{
	VOut output;
	output.position = mul(matFinal, position);    // transform the vertex from 3D to 2D
	output.worldPosition = mul(matWorld, position);
	output.normal = mul(matRotate, normal);
	output.texcoord = texcoord;    // set the texture coordinates, unmodified
	if (calc == 1) {
		float distance0 = sqrt((output.position.x - pos[0].x)*(output.position.x - pos[0].x) 
			+  (output.position.y - pos[0].y)*(output.position.y - pos[0].y)
			+  (output.position.z - pos[0].z)*(output.position.z - pos[0].z));
		float distance1 = sqrt((output.position.x - pos[1].x)*(output.position.x - pos[1].x) 
			+  (output.position.y - pos[1].y)*(output.position.y - pos[1].y)
			+  (output.position.z - pos[1].z)*(output.position.z - pos[1].z));
		float coef = 1.0f;
		float pull = coef * 1.0f / distance0 / distance0;
		output.position = output.position + pull * pos[0];
		pull = coef * 1.0f / distance1 / distance1;
		output.position += output.position + pull * pos[1];

	}
	return output;
}

float4 PShader(VOut input) : SV_TARGET
{
	float4 outputColor = (1.0f, 0.0f, 1.0f, 1.0f);
	if (calc == 0) {
		outputColor = lightAmbient;
		float3 lightVector = lightPos.xyz - input.worldPosition.xyz;
		float3 normalVector = input.normal.xyz;
		float distance = length(lightVector);
		//if (distance > range) 
			//return outputColor;
		float diffuseBrightness = saturate(dot(normalize(normalVector), normalize(lightVector)));
		outputColor += diffuseBrightness;
		//outputColor *= lightAtt.x + (lightAtt.y * distance) + (lightAtt.z * (distance * distance));
		outputColor = saturate(outputColor);
			
		outputColor *= Texture.Sample(ss, input.texcoord);
	}
	return outputColor;
}


This post has been edited by masar77: 31 July 2013 - 01:59 AM

Was This Post Helpful? 0
  • +
  • -

#4 anonymous26  Icon User is offline

  • D.I.C Lover

Reputation: 1
  • View blog
  • Posts: 3,638
  • Joined: 26-November 10

Re: Apply texture to sphere in Direct3d 11

Posted 31 July 2013 - 04:03 AM

So it works with a cube okay? If so, find a sphere example that works and compare to see where you went wrong.
Was This Post Helpful? 0
  • +
  • -

#5 BBeck  Icon User is offline

  • Here to help.
  • member icon


Reputation: 586
  • View blog
  • Posts: 1,306
  • Joined: 24-April 12

Re: Apply texture to sphere in Direct3d 11

Posted 31 July 2013 - 05:52 AM

This is an unbelievably convoluted shader. (Convoluted is my 10 cent word of the day, or week actually.)


What is this shader supposed to do? I can see that it is supposed to draw a textured object, but the code is 100 times more complex than that. In addition to drawing an object with a texture on it with lighting, what is it trying to do? I see all the light parameters you are passing in through the Constant Buffer. But I'm unsure what pos, calc, and the mat parameters are supposed to be doing. I'm guessing that mat parameters are supposed to allow you to animate the texture?

I can't get into the example/website you posted because I'm not a member. So, I can't see the original code.

Your outputColor output looks wrong to me. That's a vector times a vector, I believe. I'm pretty certain there is no such thing. I'm surprised it compiles. I believe both colors are 4D vectors. And it says its multiplying them together? It's not a dot or cross product, but actual multiplication? I would think that combining two colors would be addition with the danger of over saturating (blowing out) one or more of the colors.


outputColor *= Texture.Sample(ss, input.texcoord);




In one of the few examples of code that I have that does this, it LERPs the two colors together.

I am trying to find a good example of a basic 3D shader and I can't seem to find one for some odd reason. I would have thought that I would have had one in some of my own code, but everything I'm finding is more complex, such as my water shader. Most of the really good examples I have are in books and I can't just paste the example in. And when I googled it, I'm amazed that almost all the examples that come up on the first couple of pages are XNA. XNA really is the environment to learn HLSL in.

This blog looks really good. I only glanced over it and did not read it. But I can tell at a glance that it looks like something that I should probably read and has a fairly in depth discussion of shading.


I don't know how much you know or don't know about High Level Shader Language. I don't have a shader that does exactly what you are trying to do. This one is quite a bit more simple. It's a sprite shader. It does not try to do anything but flat lighting (nothing directional,etc.) but its extensively commented to explain how it works. It might be helpful in understanding shaders, if you do not understand HLSL. It's very basic. It simply draws a texture across the model. It's designed to draw a rectangular texture across a rectangular model (a sprite), but it should, in theory at least, draw any textured model.
//================================================================================================================
//	BasicSpriteShader.fx
//================================================================================================================
//	Purpose: To draw 2D sprites.
//
//	Notes:
//		This is a basic vertex & pixel shader that can be used to draw 2D sprites. It is very simple and 
//	straight forward because drawing sprites is very simple and straight forward. You can use this shader
//	as the only shader you will ever need for drawing 2D sprites. You may eventually want to define your
//	own shaders for special effects, but my point is that you don't have to. This one shader should do 
//	almost EVERYTHING you will EVER want to do with sprites. Shaders are about 3D, not 2D. So, you're not
//	really all that likely to need another shader for 2D work. The only reason you need it at all is 
//	because they took the Sprite drawing abilities out of DirectX and so you have to have a shader for
//	something even as simple as drawing a sprite to the screen. But basically, all sprites are drawn to 
//	the screen in the exact same way (even to the point that DX USED to have a sprite drawing function).
//
//		So don't overthink this. I've commented this code like crazy to help you understand how it works,
//	but honestly, you don't even really need to know how it works if you just know how to compile it and use
//	it in your code.
//
//		And that brings me to my next point, feel free to use this as if it were your own. As game programmers
//	we sometime get a little "hung up" on who owns what code and not plagerizing someone else. That's great
//	that you don't want to steal or plagerize someone else's code, but this is now YOUR code.
//
//		First of all, its my code that I wrote, and I'm giving you full permission to use it in any private or
//	commercial project you work on EVER. All I ask is that you realize I'm giving it to the whole world and not
//	just you. So, don't be surprised if it turns up in someone else's code as well.
//
//		And second - I'm no lawyer but, I'm PRETTY SURE that you cannot copyright, trademark, or patent something 
//	that is so simple as to be straight forward and obvious. This code is so simple and straight forward that 
//	claiming ownership of it would be like claiming ownership of the word "the" and trying to get people to pay 
//	you every time the speak or write the word "the". Can you see where a lawyer might laugh himself half to
//	death on that one?
//
//		So feel free to use this code "as is" or modified in any project you have either commercial or private.
//
//		Make certain that under Properties-->Item Type this file is set to "Does not participate in build" or
//	you will get an error because it tries to compile it at the wrong time; it is intended to compile at run-time.
//	That's only an issue if the file is added to the project in Solution Explorer, which it doesn't have to be.
//
//================================================================================================================


//================================================================================================================
//	cbuffer is used to specify a "Constant Buffer", which is so named
// due to the fact that the contents of the buffer never change through 
// the various stages of the shader. This buffer will change every time 
// a draw call is made. In other words the value will change for every
// sprite drawn on the screen within a single frame.
//
//	The name "WorldViewProjectionMatrixBuffer" doesn't affect anything
// in this example and can be changed.
//
//	All Constant Buffers have global scope and thus the value can be
// seen from anywhere in the shader code. I believe b0 is a standard 
// register for all Constant Buffers (obviously incremented if there is
// more than one Constant Buffer.
//
//	I believe the buffer is passed over in a very raw form, and that
// because of that any names such as "WorldViewProjectionMatrix" defined
// here are unconnected to any names outside of the shader code. My 
// understanding is that we are telling the shader how to read or interpret
// the buffer and that the names given for the elements are in no way 
// connected to anything outside of the shader. But keep in mind that they
// are global and seen everywhere inside the shader due to being declared
// in a Constant Buffer.
//
//
//================================================================================================================
cbuffer WorldViewProjectionMatrixBuffer : register(b0)
{
    matrix WorldViewProjectionMatrix;
};

Texture2D SpriteTexture : register(t0);				//Contains the image for the sprite.
SamplerState TextureSamplerState : register(s0);	//Contains for the Sampler that knows how to interpret the image.


struct VertexShaderInput						//Defines how the vertex info is going to be comming in.
{
    float4 Position  : POSITION;				//Vertex coordinate in 3D space.
    float2 UVCoordinates : TEXCOORD0;			//UV coordinate to map texture to the vertices of the triangles.
};

struct PixelShaderInput							//Defines how the pixel info is going to be comming in.
{
    float4 Position  : SV_POSITION;				//Vertex coordinates in 2D/screen space.
    float2 UVCoordinates : TEXCOORD0;			//UV coordinates in 2D/screen space.
};


PixelShaderInput VertexShaderCodeStart(VertexShaderInput Vertex)
//================================================================================================================
// VertexShaderCodeStart()
//
// Purpose:
//		As a vertex shader to place the vertex being given in the scene and translate it to the 2D screen.
//
// Returns: VertexShaderOutput - Feeds into the Pixel shader after going through the rasterizer.
//
// Notes:
//		This is about as straight forward as you can get in a vertex shader. Almost every vertex shader you see
//	from now on will have AT LEAST this code.
//
//		All it does is fill the VertexShaderOutput structure with the position of the vertex comming in after it
//	positions it in the 3D sceen, adjusts it for camera position, and projects it to a 2D surface that matches
//	the size of the screen (for the back buffer). In other words it just applies the World*View*Projection matrix
//	to the incomming vertex.
//
//		The VertexShaderOutput IS of type PixelShaderInput. So, basically it just passes it over to the pixel 
//	shader straight through. However, the rasterizer stage is inbetween the vertex shader and pixel shader.
//
//		The UV coordinates assigned to the given vertex are passed straight on through to the pixel shader. These
//	are the coordinates that define what point of the texture is "pinned" to the given vertex.
//
//		The output of the vertex shader here is sent to the rasterizer. You're basically sending individual
//	vertices with their accompanying data to the rasterizer after those vertices have been flattened out onto
//	a 2D plane (by the projection matrix). So what the rasterizer gets is vertices in 2D, rather than 3D, but its
//	still just getting vertices and not actual triangles. The vertex shader is sending the rasterizer all the 
//  data it needs to shade in the trianglular area(s) between vertices. 
//
//		So, you're sending output to the rasterizer, which shades in the - now - 2D triangles of the mesh/model.
//	The output for the vertex shader is the same as the input for the pixel shader, EXCEPT that if you pay good
//	attention you'll notice the semantic changes from Position to SV_Position inside the vertex shader from
//	input to output. In the vertex shader you're going from 3D to 2D with the exact same vertices. Then the 
//	rasterizer shades in triangle between these vertices. It sends each pixel that will be drawn on the screen
//	to the pixel shader. So, the input of the pixel shader is screen coordinates for the given pixel. You send
//	vertices from the vertex shader and yet the input of the pixel shader in the exact same structure is the
//	2D position of the given pixel on the screen. So, your vertex position that you sent will be the same when
//	it reaches the pixel shader. However, you will be getting the individual pixels that form the surface(s) of 
//	the triangle(s) that form your mesh/model as well. So, you send the positions of the vertices. Then the 
//	rasterizer creates pixels in between the vertices to shade in your 2D triangles. And the pixel shader
//	receives ALL of the pixels that will be drawn on the screen.
//
//		In this particular case, this shader was designed to draw 2D sprites. So your mesh/model is what is
//	known as a "quad". A quad is just a rectangle formed out of two triangles. So, the vertex shader is sent
//	the four vertices that form the two triangles. It flattens those out to 2D, because in our code they
//	are actually 3D and they are not placed in the scene or moved to simulate the camera. The World matrix
//	places it in the 3D world. The view matrix simulates a camera and places it so that it is oriented to 
//	simulate the movements of a camera (which you probably won't be moving the camera much for 2D stuff). And
//	the projection matrix "projects" the 3D scene onto a 2D surface for drawing.
//
//		Here in the vertex shader, we received all three of those matrices already combined into one matrix
//	which is applied to every vertex here in the vertex shader.
//
//		So for sprite drawing here we just convert every vertex of the quad to it's proper 2D screen location
//	and send the converted vertices out to the rasterizer along with the UV coordinates supplied for every 
//	vertex. The UV coordinates match our (now) 2D quad with a 2D image that is comming in as "SpriteTexture".
//	The rasterizer will then "create" all the pixels for the screen in between the vertices, turning 4
//	vertices (or just the corner points of our quad) that form our two triangles into a rectangle of pixels
//	that will now be described in 2D screen coordinates. And those individual pixels is what the pixel shader
//	will receive.
//
//================================================================================================================
{
    PixelShaderInput VertexShaderOutput = (PixelShaderInput)0;	//Create output structure and set it to null.
    VertexShaderOutput.Position = mul(Vertex.Position, WorldViewProjectionMatrix);	//Apply matrix to the vertex.
    VertexShaderOutput.UVCoordinates = Vertex.UVCoordinates;

    return VertexShaderOutput;
}
//================================================================================================================


float4 PixelShaderCodeStart(PixelShaderInput Pixel) : SV_TARGET
//================================================================================================================
// PixelShaderCodeStart()
//
// Purpose:
//		As a pixel shader to place the vertex being given in the scene and translate it to the 2D screen.
//
// Parameters:
//		Pixel - Position and UV coordinate for a given 2D pixel.
//
// Returns: A colored pixel.
//
// Notes:
//		Again, this is about as straight forward as you can get in a pixel shader. The only way to make it more
//	simple would be to have it output one constant color. Instead, it's coloring the given pixel using the input
//	texture defined as "SpriteTexture". DX knows what a texture is and knows how to sample textures. So, we tell
//	it to sample the texture in SpriteTexture, with the sampler set with the settings defined in TextureSamplerState
//	and to feed the sampler the texel found at the UV coordinate being fed in. This matches up the texel in the
//	2D image to the correct position on the triangle, or model, being drawn.
//
//		A texel, of course, is a texture coordinate, or coordinate inside the image data. That may or may not
//	translate to a pixel on the screen as the image may be larger or smaller when displayed. UV coordinates map
//	texels to the geometry (triangle,model, etc.).
//
//		The entire goal of the pixel shader is to output what color the pixel given is to be drawn with.
//
//		So, the pixel shader here is receiving every pixel that will be drawn on the 2D screen. The position is
//	the 2D screen coordinate of the given pixel. And the UV coordinate is the matching UV coordinate that defines
//	which part of our texture/image matches this pixel that we are currently looking at.
//
//		So, using the sampler, it matches up a given pixel in our quad to a given texel in our sprite image. It
//	then sends the color of that texel to be drawn as the given pixel in the color of the texel.
//
//		The pixel position is not explicitly used here in this code, but you could use that information for
//	special effects. For example, a blur special effect might want to use the pixel position to sample other
//	nearby pixels and you would need to know this pixel's position in order to know the positions of the 
//	surrounding pixel. But here we're just mapping pixels directly to the texels in the sprite image.
//
//================================================================================================================
{
    return SpriteTexture.Sample(TextureSamplerState, Pixel.UVCoordinates);
}
//================================================================================================================





Here is an example shader that I "believe" does exactly what you're trying to do, although I'm not sure what you're trying to do. It comes from NVidia's website from their shader library. It also looks overly convoluted (never miss a chance to use your 10 cent word of the day) and complicated. But it presumably works. Glancing over it, it seems to have a lot of the values that you are passing in through the Constant Buffer hard coded. It would be much better to pass them in through the CB like you are doing. And it's written for DX10, if that matters at all. This is the shader called "NightFall".


/*********************************************************************NVMH3****
*******************************************************************************
$Revision$

Copyright NVIDIA Corporation 2008
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED
*AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS
BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES
WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS,
BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY
LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

% Day/Night Earth Shader -- Apply to a Sphere!
% This example uses two textures for the same surface and modulates between
% them for the light/dark lighting transitions, rather than ramping-off to
% black.
keywords: lighting texture animation


keywords: DirectX10
// Note that this version has twin versions of all techniques,
//   so that this single effect file can be used in *either*
//   DirectX9 or DirectX10

To learn more about shading, shaders, and to bounce ideas off other shader
    authors and users, visit the NVIDIA Shader Library Forums at:

    http://developer.nvidia.com/forums/

*******************************************************************************
******************************************************************************/

/*****************************************************************/
/*** HOST APPLICATION IDENTIFIERS ********************************/
/*** Potentially predefined by varying host environments *********/
/*****************************************************************/

// #define _XSI_		/* predefined when running in XSI */
// #define TORQUE		/* predefined in TGEA 1.7 and up */
// #define _3DSMAX_		/* predefined in 3DS Max */
#ifdef _3DSMAX_
int ParamID = 0x0003;		/* Used by Max to select the correct parser */
#endif /* _3DSMAX_ */
#ifdef _XSI_
#define Main Static		/* Technique name used for export to XNA */
#endif /* _XSI_ */

#ifndef FXCOMPOSER_VERSION	/* for very old versions */
#define FXCOMPOSER_VERSION 180
#endif /* FXCOMPOSER_VERSION */

#ifndef DIRECT3D_VERSION
#define DIRECT3D_VERSION 0x900
#endif /* DIRECT3D_VERSION */

#define FLIP_TEXTURE_Y	/* Different in OpenGL & DirectX */

/*****************************************************************/
/*** EFFECT-SPECIFIC CODE BEGINS HERE ****************************/
/*****************************************************************/

/******* Lighting Macros *******/
/** To use "Object-Space" lighting definitions, change these two macros: **/
#define LIGHT_COORDS "World"
// #define OBJECT_SPACE_LIGHTS /* Define if LIGHT_COORDS is "Object" */

float Script : STANDARDSGLOBAL <
    string UIWidget = "none";
    string ScriptClass = "object";
    string ScriptOrder = "standard";
    string ScriptOutput = "color";
    string Script = "Technique=Technique?Main:Main10;";
> = 0.8;

/**** UNTWEAKABLES: Hidden & Automatically-Tracked Parameters **********/

// transform object vertices to world-space:
float4x4 gWorldXf : World < string UIWidget="None"; >;
// transform object normals, tangents, & binormals to world-space:
float4x4 gWorldITXf : WorldInverseTranspose < string UIWidget="None"; >;
// transform object vertices to view space and project them in perspective:
float4x4 gWvpXf : WorldViewProjection < string UIWidget="None"; >;
// provide tranform from "view" or "eye" coords back to world-space:
float4x4 gViewIXf : ViewInverse < string UIWidget="None"; >;

float gTimer : TIME <string UIWidget="None";>;

///////////////////////////////////////////////////////////////
/// TWEAKABLES ////////////////////////////////////////////////
///////////////////////////////////////////////////////////////

// Directional Lamp 0 ///////////
// apps should expect this to be normalized
float3 gLamp0Dir : DIRECTION <
    string Object = "DirectionalLight0";
    string UIName =  "Lamp 0 Direction";
    string Space = (LIGHT_COORDS);
> = {1.0f,0.0f,-1.0f};
float3 gLamp0Color : SPECULAR <
    string UIName =  "Lamp 0";
    string Object = "DirectionalLight0";
    string UIWidget = "Color";
> = {1.0f,1.0f,1.0f};


// Ambient Light
float3 gAmbiColor : AMBIENT <
    string UIName =  "Ambient Light";
    string UIWidget = "Color";
> = {0.07f,0.07f,0.07f};

float gSpeed <
    string UIWidget = "slider";
    float UIMin = 0.0;
    float UIMax = 1;
    float UIStep = 0.01;
    string UIName = "Rotation";
> = 0.2;

float gKd <
    string UIWidget = "slider";
    float UIMin = 0.0;
    float UIMax = 1.5;
    float UIStep = 0.01;
    string UIName = "Diffuse";
> = 1.0;

float gKs <
    string UIWidget = "slider";
    float UIMin = 0.0;
    float UIMax = 1.5;
    float UIStep = 0.01;
    string UIName = "Specular";
> = 0.85;

float gSpecExpon : SpecularPower <
    string UIWidget = "slider";
    float UIMin = 1.0;
    float UIMax = 128.0;
    float UIStep = 1.0;
    string UIName = "Specular power";
> = 32.0;

float gBumpy <
    string UIWidget = "slider";
    float UIMin = 0.0;
    float UIMax = 10.0;
    float UIStep = 0.1;
    string UIName = "Bump Height";
> = 1.0;

////////////////////////////////////////////////////////
/// TEXTURES ///////////////////////////////////////////
////////////////////////////////////////////////////////

texture gDayTexture  <
    string ResourceName = "EarthDay.dds";
    string UIName =  "";
    string ResourceType = "2D";
>;

sampler2D gDaySampler = sampler_state {
    Texture = <gDayTexture>;
#if DIRECT3D_VERSION >= 0xa00
    Filter = MIN_MAG_MIP_LINEAR;
#else /* DIRECT3D_VERSION < 0xa00 */
    MinFilter = Linear;
    MipFilter = Linear;
    MagFilter = Linear;
#endif /* DIRECT3D_VERSION */
    AddressU = Clamp;
    AddressV = Clamp;
};
texture gNightTexture  <
    string ResourceName = "EarthMoonLit.dds";
    string UIName =  "";
    string ResourceType = "2D";
>;

sampler2D gNightSampler = sampler_state {
    Texture = <gNightTexture>;
#if DIRECT3D_VERSION >= 0xa00
    Filter = MIN_MAG_MIP_LINEAR;
#else /* DIRECT3D_VERSION < 0xa00 */
    MinFilter = Linear;
    MipFilter = Linear;
    MagFilter = Linear;
#endif /* DIRECT3D_VERSION */
    AddressU = Clamp;
    AddressV = Clamp;
};
texture gNormalTexture : NORMALMAP <
    string ResourceName = "earth_bump.dds";
    string UIName =  "";
    string ResourceType = "2D";
>;

sampler2D gNormalSampler = sampler_state {
    Texture = <gNormalTexture>;
#if DIRECT3D_VERSION >= 0xa00
    Filter = MIN_MAG_MIP_LINEAR;
#else /* DIRECT3D_VERSION < 0xa00 */
    MinFilter = Linear;
    MipFilter = Linear;
    MagFilter = Linear;
#endif /* DIRECT3D_VERSION */
    AddressU = Clamp;
    AddressV = Clamp;
};
texture gGlossTexture : SPECULARMAP <
    string ResourceName = "EarthSpec.dds";
    string UIName =  "";
    string ResourceType = "2D";
>;

sampler2D gGlossSampler = sampler_state {
    Texture = <gGlossTexture>;
#if DIRECT3D_VERSION >= 0xa00
    Filter = MIN_MAG_MIP_LINEAR;
#else /* DIRECT3D_VERSION < 0xa00 */
    MinFilter = Linear;
    MipFilter = Linear;
    MagFilter = Linear;
#endif /* DIRECT3D_VERSION */
    AddressU = Clamp;
    AddressV = Clamp;
};

/* data from application vertex buffer */
struct appdata {
    float3 Position	: POSITION;
    float4 UV		: TEXCOORD0;
    float4 Normal	: NORMAL;
    float4 Tangent	: TANGENT0;
    float4 Binormal	: BINORMAL0;
};

/* data passed from vertex shader to pixel shader */
struct vertexOutput {
    float4 HPosition	: POSITION;
    float2 UV		: TEXCOORD0;
    // The following values are passed in "World" coordinates since
    //   it tends to be the most flexible and easy for handling
    //   reflections, sky lighting, and other "global" effects.
    float3 LightVec	: TEXCOORD1;
    float3 WorldNormal	: TEXCOORD2;
    float3 WorldTangent	: TEXCOORD3;
    float3 WorldBinormal : TEXCOORD4;
    float3 WorldView	: TEXCOORD5;
};

/*********************************************************/
/*********** Virtual Machine *****************************/
/*********************************************************/

#include <include\\nvMatrix.fxh>

/*********************************************************/
/*********** vertex shader *******************************/
/*********************************************************/

// a very standard vertex shader, with the addition the timer-based
//      rotation
vertexOutput nightfallVS(appdata IN,
	uniform float4x4 WorldITXf, // our four standard "untweakable" xforms
	uniform float4x4 WorldXf,
	uniform float4x4 ViewIXf,
	uniform float4x4 WvpXf,
	uniform float3 LampDir,
    uniform float Timer,
    uniform float Speed
) {
    vertexOutput OUT;
    // rotation matrix created here
    float4x4 RXf = nvYRotateXf(Timer*Speed);
    float4x4 RnXf = mul(RXf,WorldITXf);
    // then use RnXf instead of WorldITXf
    OUT.WorldNormal = mul(IN.Normal,RnXf).xyz;
    OUT.WorldTangent = mul(IN.Tangent,RnXf).xyz;
    OUT.WorldBinormal = mul(IN.Binormal,RnXf).xyz;
    float4 Po = float4(IN.Position.xyz,1.0);	// object coordinates
    Po = mul(Po,RXf);
    float3 Pw = mul(Po,WorldXf).xyz;		// world coordinates
#ifdef FLIP_TEXTURE_Y
    OUT.UV = float2(IN.UV.x,(1.0-IN.UV.y));
#else /* !FLIP_TEXTURE_Y */
    OUT.UV = IN.UV.xy;
#endif /* !FLIP_TEXTURE_Y */
    OUT.WorldView = normalize(ViewIXf[3].xyz - Pw);	// obj coords
    OUT.LightVec = -normalize(LampDir).xyz;
    OUT.HPosition = mul(Po,WvpXf);	// screen clipspace coords
    return OUT;
}

/*********************************************************/
/*********** pixel shader ********************************/
/*********************************************************/

float4 nightfallPS(vertexOutput IN,
	uniform float Kd,
	uniform float Ks,
	uniform float SpecExpon,
	uniform float Bumpy,
	uniform float3 LampColor,
	uniform float3 AmbiColor,
	uniform sampler2D DaySampler,
	uniform sampler2D NightSampler,
	uniform sampler2D NormalSampler,
	uniform sampler2D GlossSampler
) : COLOR {
    float3 Nn = normalize(IN.WorldNormal);
    float3 Tn = normalize(IN.WorldTangent);
    float3 Bn = normalize(IN.WorldBinormal);
    float3 bumps = Bumpy * (tex2D(NormalSampler,IN.UV).xyz-(0.5).xxx);
    Nn += (bumps.x * Tn + bumps.y * Bn);
    Nn = normalize(Nn);
    float3 Vn = normalize(IN.WorldView);
    float3 Ln = IN.LightVec;
    float3 Hn = normalize(Vn + Ln);
    float hdn = dot(Hn,Nn);
    float ldn = dot(Ln,Nn);
    float4 litVec = lit(ldn,hdn,SpecExpon);
    float3 diffContrib = litVec.y * LampColor;
    float gloss = Ks * tex2D(GlossSampler,IN.UV).x;
    float3 specContrib = ((litVec.y * litVec.z * gloss) * LampColor);
    // add, incorporating ambient light term
    float3 dayTex = tex2D(DaySampler,IN.UV).xyz;
    float3 nitTex = tex2D(NightSampler,IN.UV).xyz;
    float3 result = dayTex*(Kd*diffContrib+AmbiColor) + specContrib;
    result += saturate(4*(-ldn-0.1))*nitTex;
    return float4(result.xyz,1.0);
}

///////////////////////////////////////
/// TECHNIQUES ////////////////////////
///////////////////////////////////////

#if DIRECT3D_VERSION >= 0xa00
//
// Standard DirectX10 Material State Blocks
//
RasterizerState DisableCulling { CullMode = NONE; };
DepthStencilState DepthEnabling { DepthEnable = TRUE; };
DepthStencilState DepthDisabling {
	DepthEnable = FALSE;
	DepthWriteMask = ZERO;
};
BlendState DisableBlend { BlendEnable[0] = FALSE; };

technique10 Main10 <
	string Script = "Pass=p0;";
> {
    pass p0 <
	string Script = "Draw=geometry;";
    > {
        SetVertexShader( CompileShader( vs_4_0, nightfallVS(gWorldITXf,gWorldXf,
				gViewIXf,gWvpXf,
			gLamp0Dir,
			gTimer,gSpeed) ) );
        SetGeometryShader( NULL );
        SetPixelShader( CompileShader( ps_4_0, nightfallPS(gKd,gKs,gSpecExpon,gBumpy,
			gLamp0Color,gAmbiColor,
			gDaySampler,gNightSampler,
			gNormalSampler,gGlossSampler) ) );
	    SetRasterizerState(DisableCulling);
	    SetDepthStencilState(DepthEnabling, 0);
	    SetBlendState(DisableBlend, float4( 0.0f, 0.0f, 0.0f, 0.0f ), 0xFFFFFFFF);
    }
}

#endif /* DIRECT3D_VERSION >= 0xa00 */

technique Main <
	string Script = "Pass=p0;";
> {
    pass p0 <
	string Script = "Draw=geometry;";
    > {
        VertexShader = compile vs_3_0 nightfallVS(gWorldITXf,gWorldXf,
				gViewIXf,gWvpXf,
			gLamp0Dir,
			gTimer,gSpeed);
		ZEnable = true;
		ZWriteEnable = true;
		ZFunc = LessEqual;
		AlphaBlendEnable = false;
		CullMode = None;
        PixelShader = compile ps_3_0 nightfallPS(gKd,gKs,gSpecExpon,gBumpy,
			gLamp0Color,gAmbiColor,
			gDaySampler,gNightSampler,
			gNormalSampler,gGlossSampler);
    }
}

/***************************** eof ***/



This post has been edited by BBeck: 31 July 2013 - 05:56 AM

Was This Post Helpful? 0
  • +
  • -

#6 masar77  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 28-May 09

Re: Apply texture to sphere in Direct3d 11

Posted 31 July 2013 - 06:30 AM

View PostButchDean, on 31 July 2013 - 05:03 AM, said:

So it works with a cube okay? If so, find a sphere example that works and compare to see where you went wrong.


It doesn't even work with a plane:
Posted Image

Obj file:
o Mesh
v 1 -1 0
v -1 -1 0
v -1 1 0
v 1 1 0
vn 0 0 1
vt 0 0
vt 1 0
vt 0 1
vt 1 1
mtllib cube.mtl
usemtl Default
g Default
f 2/1/1 1/2/1 3/3/1
f 4/4/1 3/3/1 1/2/1


Was This Post Helpful? 0
  • +
  • -

#7 masar77  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 28-May 09

Re: Apply texture to sphere in Direct3d 11

Posted 31 July 2013 - 06:46 AM

View PostBBeck, on 31 July 2013 - 06:52 AM, said:

This is an unbelievably convoluted shader. (Convoluted is my 10 cent word of the day, or week actually.)


What is this shader supposed to do? I can see that it is supposed to draw a textured object, but the code is 100 times more complex than that. In addition to drawing an object with a texture on it with lighting, what is it trying to do? I see all the light parameters you are passing in through the Constant Buffer. But I'm unsure what pos, calc, and the mat parameters are supposed to be doing. I'm guessing that mat parameters are supposed to allow you to animate the texture?

I can't get into the example/website you posted because I'm not a member. So, I can't see the original code.

Your outputColor output looks wrong to me. That's a vector times a vector, I believe. I'm pretty certain there is no such thing. I'm surprised it compiles. I believe both colors are 4D vectors. And it says its multiplying them together? It's not a dot or cross product, but actual multiplication? I would think that combining two colors would be addition with the danger of over saturating (blowing out) one or more of the colors.


outputColor *= Texture.Sample(ss, input.texcoord);




In one of the few examples of code that I have that does this, it LERPs the two colors together.

I am trying to find a good example of a basic 3D shader and I can't seem to find one for some odd reason. I would have thought that I would have had one in some of my own code, but everything I'm finding is more complex, such as my water shader. Most of the really good examples I have are in books and I can't just paste the example in. And when I googled it, I'm amazed that almost all the examples that come up on the first couple of pages are XNA. XNA really is the environment to learn HLSL in.

This blog looks really good. I only glanced over it and did not read it. But I can tell at a glance that it looks like something that I should probably read and has a fairly in depth discussion of shading.


I don't know how much you know or don't know about High Level Shader Language. I don't have a shader that does exactly what you are trying to do. This one is quite a bit more simple. It's a sprite shader. It does not try to do anything but flat lighting (nothing directional,etc.) but its extensively commented to explain how it works. It might be helpful in understanding shaders, if you do not understand HLSL. It's very basic. It simply draws a texture across the model. It's designed to draw a rectangular texture across a rectangular model (a sprite), but it should, in theory at least, draw any textured model.



Well, the code in the vertex shader inside the if-block is used for another rendering and is not used for the sphere, or as I previously posted, the plane. The lighting works as it should for solid object without a texture, so I don't think the problem is there. If you look at the plane which should like a 2d image of earth, does it tell you anything what could possibly be wrong?
Was This Post Helpful? 0
  • +
  • -

#8 masar77  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 28-May 09

Re: Apply texture to sphere in Direct3d 11

Posted 31 July 2013 - 07:02 AM

One thing that I noticed differs from the tutorial is this:
In the tutorial:
    D3DX11CompileFromFile(L"shaders.hlsl", 0, 0, "VShader", "vs_5_0", 0, 0, 0, &VS, 0, 0);
    D3DX11CompileFromFile(L"shaders.hlsl", 0, 0, "PShader", "ps_5_0", 0, 0, 0, &PS, 0, 0);



While I have this:
	result = D3DX11CompileFromFile(L"shader.hlsl", 0, 0, "VShader", "vs_4_0", 0, 0, 0, &VS, &errors, 0);
	if(FAILED(result))
	{
		OutputDebugString(L"Compile vertex failed..\n");
	}
	result = D3DX11CompileFromFile(L"shader.hlsl", 0, 0, "PShader", "ps_4_0", 0, 0, 0, &PS, &errors, 0);
	if(FAILED(result))
	{
		OutputDebugString(L"Compile pixel failed..\n");
	}



Version 4.0 instead of 5.0, my system does not support 5.0, could this cause problems?
Was This Post Helpful? 0
  • +
  • -

#9 masar77  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 28-May 09

Re: Apply texture to sphere in Direct3d 11

Posted 31 July 2013 - 07:22 AM

I got it to work now but I don't know why, I will post as soon as I know.
Was This Post Helpful? 0
  • +
  • -

#10 frostraver  Icon User is offline

  • D.I.C Head

Reputation: 11
  • View blog
  • Posts: 93
  • Joined: 11-September 12

Re: Apply texture to sphere in Direct3d 11

Posted 31 July 2013 - 01:24 PM

If you just want to draw a texture on your sphere, nothing more, you can just created the worlds simplest shader with a Texture lookup and a sample of that texture. That should be it.

So just this:
outputColor *= Texture.Sample(ss, input.texcoord);

like BBeck explained should be it. Then in your DirectX application you can fairly easy add the shader to your model. (I did this multiple times in DirectX10. If you want some more code or whatever just ask me and I'll see what I can do.)
BBeck is a more reliable source though.
Was This Post Helpful? 0
  • +
  • -

#11 masar77  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 28-May 09

Re: Apply texture to sphere in Direct3d 11

Posted 01 August 2013 - 11:22 AM

I'm starting from scratch with a new project, needed refactoring anyway. Don't know what the problem was.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1