I am trying to make my 3d object to move. Using default vs2022 template I managed to import model from .ply file and load to pixelshader / vertexshader. Object is displaying on screen, but I have no idea how could I move it. I know I can edit all verticies but I think there is other way of doing it using Matrix.
I was trying to do
XMStoreFloat4x4(&m_constantBufferData.model, XMMatrixTranslation(0.5f, 0.0f, 0.0f));
But It shreded textures.
Upper image is after move.
Can someone help me and explain how to do this?
Camera Initialize:
void Sample3DSceneRenderer::CreateWindowSizeDependentResources()
{
Size outputSize = m_deviceResources->GetOutputSize();
float aspectRatio = outputSize.Width / outputSize.Height;
float fovAngleY = 70.0f * XM_PI / 180.0f;
if (aspectRatio < 1.0f)
{
fovAngleY *= 2.0f;
}
XMMATRIX perspectiveMatrix = XMMatrixPerspectiveFovRH(
fovAngleY,
aspectRatio,
0.01f,
100.0f
);
XMFLOAT4X4 orientation = m_deviceResources->GetOrientationTransform3D();
XMMATRIX orientationMatrix = XMLoadFloat4x4(&orientation);
XMStoreFloat4x4(
&m_constantBufferData.projection,
XMMatrixTranspose(perspectiveMatrix * orientationMatrix)
);
static const XMVECTORF32 eye = { 0.0f, 0.7f, 8.0f, 0.0f };
static const XMVECTORF32 at = { 0.0f, -0.1f, 0.0f, 0.0f };
static const XMVECTORF32 up = { 0.0f, 1.0f, 0.0f, 0.0f };
XMStoreFloat4x4(&m_constantBufferData.view, XMMatrixTranspose(XMMatrixLookAtRH(eye, at, up)));
}
void Sample3DSceneRenderer::Move()
{
XMStoreFloat4x4(&m_constantBufferData.model, XMMatrixTranslation(0.5f, 0.0f, 0.0f));
}
I am trying to apply a texture to my 3D model with Three JS.
I tried a lot of ways from the Three JS Examples but for any reasons nothing is working.
Here is how I apply the texture to my model:
//LOADING TEXTURE
var textureLoader = new THREE.TextureLoader();
var diffuse = textureLoader.load( "models/Carbon.png" );
diffuse.encoding = THREE.sRGBEncoding;
diffuse.wrapS = THREE.RepeatWrapping;
diffuse.wrapT = THREE.RepeatWrapping;
diffuse.repeat.x = 1;
diffuse.repeat.y = 1;
var normalMap = textureLoader.load( "models/Carbon_Normal.png" );
normalMap.wrapS = THREE.RepeatWrapping;
normalMap.wrapT = THREE.RepeatWrapping;
var material = new THREE.MeshPhysicalMaterial({
roughness: 0.5,
clearcoat: 1.0,
clearcoatRoughness: 0.1,
map: diffuse,
normalMap: normalMap
});
// LOADING MODEL
var loader = new THREE.GLTFLoader();
loader.load("models/stairs.gltf", function(gltf){
model = gltf.scene
model.traverse((newModel) => {
if (newModel.isMesh){
newModel.material = material;
newModel.castShadow = true;
newModel.receiveShadow = true;
}
});
scene.add(model);
});
I appreciate any help!
When loading a texture for a glTF model, you have to set Texture.flipY to false to satisfy the uv convention of glTF.
diffuse.flipY = false;
normalMap.flipY = false;
Besides, you always have to ensure that your model has texture coordinates. You can do this by checking if the geometries of your meshes have an uv attribute. If this attribute is missing, I suggest you generate texture coordinates in a DCC tool like Blender.
three.js R112
I want to apply a texture to only a specified portion of the face of a cube - not the whole face. I want to do this multiple times to the same face. For example, I want to put texture1.jpg on the top right corner of the face, texture2.jpg on the lower right corner, texture3.jpg on the upper left corner, and texture4.jpg in the middle.
I want to be able to do this without creating new meshes for each portion.
I am experiencing performance issues related to having to create a new mesh for each portion of texture, and if I could just do it by somehow placing "decals" on a single mesh, the whole thing would run smoother.
You can combine textures at custom THREE.ShaderMAterial:
<script id="cubeFragmentShader" type="x-shader/x-fragment">
uniform vec2 aMin;
uniform vec2 aMax;
varying vec2 vUv;
uniform sampler2D texture;
uniform sampler2D texture2;
void main() {
vec2 position = vUv;
if (vUv.x<aMin.x || vUv.x>aMax.x || vUv.y<aMin.y || vUv.y>aMax.y) {
gl_FragColor = texture2D( texture2, position );
} else {
position -= aMin;
position.x /= aMax.x - aMin.x;
position.y /= aMax.y - aMin.y;
gl_FragColor = texture2D( texture, position );
}
}
</script>
http://jsfiddle.net/fj2r9b55/
I drew multiple images on a canvas in different spots and then exported the canvas as a URL, which I added as a textured material to a Mesh:
var scene = new THREE.Scene();
var sceneWidth = window.innerWidth;
var sceneHeight = window.innerHeight;
var camera = new THREE.PerspectiveCamera(45, sceneWidth/sceneHeight, 0.1, 3000);
var controls = new THREE.OrbitControls(camera);
var raycaster = new THREE.Raycaster();
var renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setClearColor( 0xcccccc, 1);
renderer.setSize(sceneWidth, sceneHeight);
document.getElementById("content").appendChild(renderer.domElement);
var canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 900;
var ctx = canvas.getContext("2d");
var imgs = [];
imgs.push(loadImage('http://uobot.com/demo/1.jpg', main));
imgs.push(loadImage('http://uobot.com/demo/2.jpg', main));
imgs.push(loadImage('http://uobot.com/demo/3.jpg', main));
var imagesLoaded = 0;
function main() {
imagesLoaded ++;
if(imagesLoaded == imgs.length) {
for(var i in imgs) {
ctx.drawImage(imgs[i], 0, i*100);
}
var dataUrl = canvas.toDataURL();
var texture = THREE.ImageUtils.loadTexture(dataUrl);
texture.needsUpdate = true;
texture.minFilter = THREE.LinearFilter;
var material = new THREE.MeshPhongMaterial( {
map: texture,
specular: 0x050505,
shininess: 0
});
var object = new THREE.Mesh(new THREE.PlaneGeometry(10, 60, 1, 1), material);
scene.add(object);
}
}
function loadImage(src, onload) {
var img = new Image();
img.onload = onload;
img.src = src;
return img;
}
Three.js r62
I have a scene from .obj file with a few meshes.
https://dl.dropboxusercontent.com/u/8913924/terrain/index.html
I try to apply a texture to the "terrain" object.
Result is an invisible/transparent texture.
(if a texture applied to any other objects in the scene - everything seems ok)
check the demo above.
Notes:
.mtl file is empty;
Upload a texture and apply the one to all the objects of the scene:
/* prepare the texture */
var texture = THREE.ImageUtils.loadTexture( 'crate.gif' );
texture.needsUpdate = true;
Apply this texture to terrain and all other objects:
if ( ('string' == typeof o.type) && ( 'terrain' == o.type)){
/*work with terrain*/
//object.children[i].material = object.children[i].material.clone();
object.children[i] = new THREE.Mesh (object.children[i].geometry.clone(), object.children[i].material.clone());
object.children[i].material.color.setHex(0xffffff);
object.children[i].material.map = texture;
object.children[i].material.ownMaterial = true;
//console.log('terrain colored');
} else {
/*work with all other objects*/
object.children[i].material = object.children[i].material.clone();
object.children[i].material.ownMaterial = true;
object.children[i].material.map = texture;
}
When running this XNA application it should display a rotated rectangle that moves from top-left corner to bottom-right corner.
It looks like my F# version is noticeably much slower. It seems that the Draw method skips a lot of frames.
I am using VS 2012 RC, XNA 4.0, .NET 4.5, F# 3.0. I am trying to make it as functional as possible.
What could be the reason for poor performance?
C#:
class Program
{
static void Main(string[] args)
{
using (var game = new FlockGame())
{
game.Run();
}
}
}
public class FlockGame : Game
{
private GraphicsDeviceManager graphics;
private DrawingManager drawingManager;
private Vector2 position = Vector2.Zero;
public FlockGame()
{
graphics = new GraphicsDeviceManager(this);
}
protected override void Initialize()
{
drawingManager = new DrawingManager(graphics.GraphicsDevice);
this.IsFixedTimeStep = false;
}
protected override void Update(GameTime gameTime)
{
position = new Vector2(position.X + 50.1f * (float)gameTime.ElapsedGameTime.TotalSeconds,
position.Y + 50.1f * (float)gameTime.ElapsedGameTime.TotalSeconds);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
//this.GraphicsDevice.Clear(Color.Lavender)
drawingManager.DrawRectangle(position, new Vector2(100.0f, 100.0f), 0.7845f, Color.Red);
base.Draw(gameTime);
}
}
public class DrawingManager
{
private GraphicsDevice GraphicsDevice;
private Effect Effect;
public DrawingManager(GraphicsDevice graphicsDevice)
{
GraphicsDevice = graphicsDevice;
this.Effect =
new BasicEffect(this.GraphicsDevice)
{
VertexColorEnabled = true,
Projection = Matrix.CreateOrthographicOffCenter(0.0f, this.GraphicsDevice.Viewport.Width,
this.GraphicsDevice.Viewport.Height, 0.0f, 0.0f, 1.0f)
};
}
private VertexPositionColor[] GetRectangleVertices (Vector2 center, Vector2 size, float radians, Color color)
{
var halfSize = size/2.0f;
var topLeft = -halfSize;
var bottomRight = halfSize;
var topRight = new Vector2(bottomRight.X, topLeft.Y);
var bottomLeft = new Vector2(topLeft.X, bottomRight.Y);
topLeft = Vector2.Transform(topLeft, Matrix.CreateRotationZ(radians)) + center;
topRight = Vector2.Transform(topRight, Matrix.CreateRotationZ(radians)) + center;
bottomRight = Vector2.Transform(bottomRight, Matrix.CreateRotationZ(radians)) + center;
bottomLeft = Vector2.Transform(bottomLeft, Matrix.CreateRotationZ(radians)) + center;
return new VertexPositionColor[]
{
new VertexPositionColor(new Vector3(topLeft, 0.0f), color),
new VertexPositionColor(new Vector3(topRight, 0.0f), color),
new VertexPositionColor(new Vector3(topRight, 0.0f), color),
new VertexPositionColor(new Vector3(bottomRight, 0.0f), color),
new VertexPositionColor(new Vector3(bottomRight, 0.0f), color),
new VertexPositionColor(new Vector3(bottomLeft, 0.0f), color),
new VertexPositionColor(new Vector3(bottomLeft, 0.0f), color),
new VertexPositionColor(new Vector3(topLeft, 0.0f), color)
};
}
public void DrawRectangle(Vector2 center, Vector2 size, float radians, Color color)
{
var vertices = GetRectangleVertices(center, size, radians, color);
foreach (var pass in this.Effect.CurrentTechnique.Passes)
{
pass.Apply();
this.GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList, vertices, 0, vertices.Length/2);
}
}
}
F#:
namespace Flocking
module FlockingProgram =
open System
open Flocking
[<STAThread>]
[<EntryPoint>]
let Main _ =
use g = new FlockGame()
g.Run()
0
//------------------------------------------------------------------------------
namespace Flocking
open System
open System.Diagnostics
open Microsoft.Xna.Framework
open Microsoft.Xna.Framework.Graphics
open Microsoft.Xna.Framework.Input
type public FlockGame() as this =
inherit Game()
let mutable graphics = new GraphicsDeviceManager(this)
let mutable drawingManager = null
let mutable position = Vector2.Zero
override Game.LoadContent() =
drawingManager <- new Rendering.DrawingManager(graphics.GraphicsDevice)
this.IsFixedTimeStep <- false
override Game.Update gameTime =
position <- Vector2(position.X + 50.1f * float32 gameTime.ElapsedGameTime.TotalSeconds,
position.Y + 50.1f * float32 gameTime.ElapsedGameTime.TotalSeconds)
base.Update gameTime
override Game.Draw gameTime =
//this.GraphicsDevice.Clear(Color.Lavender)
Rendering.DrawRectangle(drawingManager, position, Vector2(100.0f, 100.0f), 0.7845f, Color.Red)
base.Draw gameTime
//------------------------------------------------------------------------------
namespace Flocking
open System
open System.Collections.Generic
open Microsoft.Xna.Framework
open Microsoft.Xna.Framework.Graphics
open Microsoft.Xna.Framework.Input
module Rendering =
[<AllowNullLiteral>]
type DrawingManager (graphicsDevice : GraphicsDevice) =
member this.GraphicsDevice = graphicsDevice
member this.Effect =
new BasicEffect(this.GraphicsDevice,
VertexColorEnabled = true,
Projection = Matrix.CreateOrthographicOffCenter(0.0f,
float32 this.GraphicsDevice.Viewport.Width,
float32 this.GraphicsDevice.Viewport.Height,
0.0f, 0.0f, 1.0f))
let private GetRectangleVertices (center:Vector2, size:Vector2, radians:float32, color:Color) =
let halfSize = size / 2.0f
let mutable topLeft = -halfSize
let mutable bottomRight = halfSize
let mutable topRight = new Vector2(bottomRight.X, topLeft.Y)
let mutable bottomLeft = new Vector2(topLeft.X, bottomRight.Y)
topLeft <- Vector2.Transform(topLeft, Matrix.CreateRotationZ(radians)) + center
topRight <- Vector2.Transform(topRight, Matrix.CreateRotationZ(radians)) + center
bottomRight <- Vector2.Transform(bottomRight, Matrix.CreateRotationZ(radians)) + center
bottomLeft <- Vector2.Transform(bottomLeft, Matrix.CreateRotationZ(radians)) + center
[|
new VertexPositionColor(new Vector3(topLeft, 0.0f), color)
new VertexPositionColor(new Vector3(topRight, 0.0f), color)
new VertexPositionColor(new Vector3(topRight, 0.0f), color)
new VertexPositionColor(new Vector3(bottomRight, 0.0f), color)
new VertexPositionColor(new Vector3(bottomRight, 0.0f), color)
new VertexPositionColor(new Vector3(bottomLeft, 0.0f), color)
new VertexPositionColor(new Vector3(bottomLeft, 0.0f), color)
new VertexPositionColor(new Vector3(topLeft, 0.0f), color)
|]
let DrawRectangle (drawingManager:DrawingManager, center:Vector2, size:Vector2, radians:float32, color:Color) =
let vertices = GetRectangleVertices(center, size, radians, color)
for pass in drawingManager.Effect.CurrentTechnique.Passes do
pass.Apply()
drawingManager.GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList, vertices, 0, vertices.Length/2)
This is a guess; I know nothing about this domain, but the Effect property is creating a new BasicEffect object every time it is read; maybe you want to initialize that object once with a let inside the constructor and then return that object?