Add a texture on a sphere by Urhosharp - xamarin

I'm using Xamarin.Forms + Urhosharp, I've got a problem to set texture from an image on a sphere. The problem is that texture.Load or texture.SetData always returns false. I did try different methods like SetData, Load, resize texture and image (to a power of 2 number) and ... but none of them worked. Here is my code:
private async void CreateScene()
{
Input.SubscribeToTouchEnd(OnTouched);
_scene = new Scene();
_octree = _scene.CreateComponent<Octree>();
_plotNode = _scene.CreateChild();
var baseNode = _plotNode.CreateChild().CreateChild();
var plane = baseNode.CreateComponent<StaticModel>();
plane.Model = CoreAssets.Models.Sphere;
var cameraNode = _scene.CreateChild();
_camera = cameraNode.CreateComponent<Camera>();
cameraNode.Position = new Vector3(10, 15, 10) / 1.75f;
cameraNode.Rotation = new Quaternion(-0.121f, 0.878f, -0.305f, -0.35f);
Node lightNode = cameraNode.CreateChild();
var light = lightNode.CreateComponent<Light>();
light.LightType = LightType.Point;
light.Range = 100;
light.Brightness = 1.3f;
int size = 3;
baseNode.Scale = new Vector3(size * 1.5f, 1, size * 1.5f);
var imageStream = await new HttpClient().GetStreamAsync("some 512 * 512 jpg image");
var ms = new MemoryStream();
imageStream.CopyTo(ms);
var image = new Image();
var isLoaded = image.Load(new MemoryBuffer(ms));
if (!isLoaded)
{
throw new Exception();
}
var texture = new Texture2D();
//var isTextureLoaded = texture.Load(new MemoryBuffer(ms.ToArray()));
var isTextureLoaded = texture.SetData(image);
if (!isTextureLoaded)
{
throw new Exception();
}
var material = new Material();
material.SetTexture(TextureUnit.Diffuse, texture);
material.SetTechnique(0, CoreAssets.Techniques.Diff, 0, 0);
plane.SetMaterial(material);
try
{
await _plotNode.RunActionsAsync(new EaseBackOut(new RotateBy(2f, 0, 360, 0)));
}
catch (OperationCanceledException) { }
}
Please help!

To Create a material from a 2D Texture, you can use Material.FromImage .
Refer following documentation for more detail.
model.SetMaterial(Material.FromImage("earth.jpg"));
https://developer.xamarin.com/api/type/Urho.Material/
https://developer.xamarin.com/api/member/Urho.Material.FromImage/p/System.String/
private async void CreateScene()
{
_scene = new Scene();
_octree = _scene.CreateComponent<Octree>();
_plotNode = _scene.CreateChild();
var baseNode = _plotNode.CreateChild().CreateChild();
var plane = _plotNode.CreateComponent<StaticModel>();
plane.Model = CoreAssets.Models.Sphere;
plane.SetMaterial(Material.FromImage("earth.jpg"));
var cameraNode = _scene.CreateChild();
_camera = cameraNode.CreateComponent<Camera>();
cameraNode.Position = new Vector3(10, 15, 10) / 1.75f;
cameraNode.Rotation = new Quaternion(-0.121f, 0.878f, -0.305f, -0.35f);
Node lightNode = cameraNode.CreateChild();
var light = lightNode.CreateComponent<Light>();
light.LightType = LightType.Point;
light.Range = 100;
light.Brightness = 1.3f;
int size = 3;
baseNode.Scale = new Vector3(size * 1.5f, 1, size * 1.5f);
Renderer.SetViewport(0, new Viewport(_scene, _camera, null));
try
{
await _plotNode.RunActionsAsync(new EaseBackOut(new RotateBy(2f, 0, 360, 0)));
}
catch (OperationCanceledException) { }
}

Related

Ammo Threejs Breakable objects debis set material after breaking in fragments

i have initially breakable object with nice texture material loaded.
After breaking in fragments lost original material and load some default material.
Any suggest?
I use code from threejs example with ammo:
Source code:
import * as THREE from "three";
import {ConvexObjectBreaker} from "../jsm/misc/ConvexObjectBreaker";
import {updatePhysics} from "./updater";
export class MagicPhysics {
// Physics variables
gravityConstant = 7.8;
collisionConfiguration;
dispatcher;
broadphase;
solver;
physicsWorld;
margin = 0.05;
convexBreaker = new ConvexObjectBreaker();
// Rigid bodies include all movable objects
rigidBodies = [];
pos = new THREE.Vector3();
quat = new THREE.Quaternion();
transformAux1;
tempBtVec3_1;
objectsToRemove = [];
// Player
ammoTmpPos;
ammoTmpQuat;
tmpTrans;
numObjectsToRemove = 0;
impactPoint = new THREE.Vector3();
impactNormal = new THREE.Vector3();
// kinekt type of movement
kMoveDirection = {left: 0, right: 0, forward: 0, back: 0};
// velocity type of movement
moveDirection = {left: 0, right: 0, forward: 0, back: 0};
tmpPos = new THREE.Vector3();
tmpQuat = new THREE.Quaternion();
constructor(options) {
console.log("MagicPhysics =>", options)
this.updatePhysics = updatePhysics.bind(this);
this.config = options.config;
}
initPhysics() {
// Physics configuration
this.collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
this.dispatcher = new Ammo.btCollisionDispatcher(this.collisionConfiguration);
this.broadphase = new Ammo.btDbvtBroadphase();
const solver = new Ammo.btSequentialImpulseConstraintSolver();
this.physicsWorld = new Ammo.btDiscreteDynamicsWorld(
this.dispatcher,
this.broadphase,
solver,
this.collisionConfiguration
);
this.physicsWorld.setGravity(new Ammo.btVector3(0, -this.gravityConstant, 0));
this.transformAux1 = new Ammo.btTransform();
this.tempBtVec3_1 = new Ammo.btVector3(0, 0, 0);
}
createRigidBody(object, physicsShape, mass, pos, quat, vel, angVel) {
if(pos) {
object.position.copy(pos);
} else {
pos = object.position;
}
if(quat) {
object.quaternion.copy(quat);
} else {
quat = object.quaternion;
}
const transform = new Ammo.btTransform();
transform.setIdentity();
transform.setOrigin(new Ammo.btVector3(pos.x, pos.y, pos.z));
transform.setRotation(
new Ammo.btQuaternion(quat.x, quat.y, quat.z, quat.w)
);
const motionState = new Ammo.btDefaultMotionState(transform);
const localInertia = new Ammo.btVector3(0, 0, 0);
physicsShape.calculateLocalInertia(mass, localInertia);
const rbInfo = new Ammo.btRigidBodyConstructionInfo(
mass,
motionState,
physicsShape,
localInertia
);
const body = new Ammo.btRigidBody(rbInfo);
body.setFriction(0.5);
if(vel) {
body.setLinearVelocity(new Ammo.btVector3(vel.x, vel.y, vel.z));
}
if(angVel) {
body.setAngularVelocity(
new Ammo.btVector3(angVel.x, angVel.y, angVel.z)
);
}
object.userData.physicsBody = body;
object.userData.collided = false;
this.scene.add(object);
if(mass > 0) {
this.rigidBodies.push(object);
// Disable deactivation
body.setActivationState(4);
}
this.physicsWorld.addRigidBody(body);
return body;
}
createConvexHullPhysicsShape(coords) {
const shape = new Ammo.btConvexHullShape();
for(let i = 0, il = coords.length;i < il;i += 3) {
this.tempBtVec3_1.setValue(coords[i], coords[i + 1], coords[i + 2]);
const lastOne = i >= il - 3;
shape.addPoint(this.tempBtVec3_1, lastOne);
}
return shape;
}
createParalellepipedWithPhysics(sx, sy, sz, mass, pos, quat, material) {
const object = new THREE.Mesh(
new THREE.BoxGeometry(sx, sy, sz, 1, 1, 1),
material
);
const shape = new Ammo.btBoxShape(
new Ammo.btVector3(sx * 0.5, sy * 0.5, sz * 0.5)
);
shape.setMargin(this.margin);
this.createRigidBody(object, shape, mass, pos, quat);
return object;
}
createDebrisFromBreakableObject(object) {
object.castShadow = true;
object.receiveShadow = true;
const shape = this.createConvexHullPhysicsShape(
object.geometry.attributes.position.array
);
shape.setMargin(this.margin);
const body = this.createRigidBody(
object,
shape,
object.userData.mass,
null,
null,
object.userData.velocity,
object.userData.angularVelocity
);
// Set pointer back to the three object only in the debris objects
const btVecUserData = new Ammo.btVector3(0, 0, 0);
btVecUserData.threeObject = object;
body.setUserPointer(btVecUserData);
}
removeDebris(object) {
this.scene.remove(object);
this.physicsWorld.removeRigidBody(object.userData.physicsBody);
}
}

Add Image in Word Open SDK + dotnet core

I am trying to add an image to the word document using dotnet core and Open SDK library. Followed the exact same instruction as per the MSDN article. The code runs ok, but while trying to open document its says the document is corrupted.
Microsoft Doc
Used the OpenSDK Productivity tool and validated the document. Showing this error
Have confirmed that the Image Type are same. Not able to understand whats wrong.
private const string RefrenceKeyWord = "rId";
static void Main(string[] args)
{
InsertAPicture(document, fileName);
}
public static void InsertAPicture(string document, string fileName)
{
Int64Value imageWidth = 5731510L;
Int64Value imageHeight = 3820795L;
//using (var image = new Bitmap(fileName))
//{
// imageWidth = image.GetWidthInEMUs() / 10;
// imageHeight = image.GetHeightInEMUs() / 10;
//}
using (WordprocessingDocument wordprocessingDocument =
WordprocessingDocument.Open(document, true))
{
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Png);
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
imagePart.FeedData(stream);
}
//## start of new Code ##
var maxId = mainPart.Parts
.Where(p => p.RelationshipId.StartsWith(RefrenceKeyWord))
.Select(p =>
Convert.ToInt32(p.RelationshipId.Replace(RefrenceKeyWord,
"")))
.Max();
mainPart.ChangeIdOfPart(imagePart, $"{RefrenceKeyWord}{maxId + 1}");
//## end of new Code ##
AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart), imageWidth, imageHeight);
}
}
private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId, Int64Value width, Int64Value height)
{
// Define the reference of the image.
var element =
new Drawing(
new DW.Inline(
new DW.Extent() { Cx = width, Cy = height },
new DW.EffectExtent()
{
LeftEdge = 0L,
TopEdge = 0L,
RightEdge = 2540L,
BottomEdge = 8255L
},
new DW.DocProperties()
{
Id = (UInt32Value)1U,
Name = "Picture 1",
},
new DW.NonVisualGraphicFrameDrawingProperties(
new A.GraphicFrameLocks() { NoChangeAspect = true }),
new A.Graphic(
new A.GraphicData(
new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{
Id = (UInt32Value)0U,
Name = "Picture 1"
},
new PIC.NonVisualPictureDrawingProperties(new A.PictureLocks() { NoChangeAspect = true, NoChangeArrowheads = true })),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{
Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}",
})
)
{
Embed = relationshipId,
//CompressionState =
//A.BlipCompressionValues.Print
},
new A.Stretch(
new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(
new A.Offset() { X = 0L, Y = 0L },
new A.Extents() { Cx = width, Cy = height }),
new A.PresetGeometry(
new A.AdjustValueList()
)
{ Preset = A.ShapeTypeValues.Rectangle }))
)
{ Uri = "https://schemas.openxmlformats.org/drawingml/2006/picture" })
)
{
DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U,
EditId = "50D07946"
});
SectionProperties sectPr = (SectionProperties)wordDoc.MainDocumentPart.Document.Body.ChildElements.Last();
// var p = wordDoc.MainDocumentPart.RootElement;
// var p1 = wordDoc.MainDocumentPart.Document.Body.FirstChild;
var p1 = new Paragaph(new Run(element));
// Append the reference to body, the element should be in a Run.
wordDoc.MainDocumentPart.Document.Body.InsertBefore(p1, sectPr);
}

When I create pdf with itextg from ListView only the same listview child appears

I am trying to create a pdf from listview items. This is my listview:
This is the result:
Below is my code:
ListView def = (ListView) findViewById(R.id.ist);
ListAdapter adapter = def.getAdapter();
int itemscount = adapter.getCount();
/*int itemsposition = adapter.getItem(position);*/
Toast.makeText(getApplicationContext(), itemscount + " temaxia", Toast.LENGTH_LONG).show();
int allitemsheight = 0;
List<Bitmap> bmps = new ArrayList<Bitmap>();
for (int i = 0; i < itemscount ; i++) {
View childView = adapter.getView(i, null, def);
/*View childView = def.getChildAt(1);*/
childView.measure(View.MeasureSpec.makeMeasureSpec(def.getWidth(),
View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
childView.layout(0, 0, childView.getMeasuredWidth(),
childView.getMeasuredHeight());
childView.setDrawingCacheEnabled(true);
childView.buildDrawingCache();
childView.getDrawingCache();
/*bmps.add(childView.getDrawingCache());
allitemsheight+=childView.getMeasuredHeight();*/
Bitmap bigbitmap = Bitmap.createBitmap(def.getMeasuredWidth(),
childView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas bigcanvas = new Canvas(bigbitmap);
def.draw(bigcanvas);
Paint paint = new Paint();
bigcanvas.drawBitmap(bigbitmap,0,childView.getMeasuredHeight(),paint);
bigbitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.scalePercent(45, 60);
myImg.setAlignment(Image.ALIGN_CENTER);
// add image to document
doc.add(myImg);
doc.add( new Paragraph());
}
I just cant find why it only gets childview in first position despite it is inside a for loop. Can anyone help me? Thanks.
I changed all the consept to: Create a big image from all childviews and then cut it to multiple pages A4 size.See below....NOTICE that first doc is never opened and never closed,but after creating image document is opened and closed properly ...............
File file = new File(dir, flname + ".pdf");
FileOutputStream fOut = new FileOutputStream(file);
FileOutputStream fOut2 = new FileOutputStream(file);
pdfWriter.getInstance(doc, fOut);
// open the document
/* doc.open();*/
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//////////////////////
ListView def = (ListView) findViewById(R.id.ist);
ListAdapter adapter = def.getAdapter();
int itemscount = adapter.getCount();
/*int itemsposition = adapter.getItem(position);*/
Toast.makeText(getApplicationContext(), itemscount + " temaxia", Toast.LENGTH_LONG).show();
View childView =null;
int allitemsheight = 0;
List<Bitmap> bmps = new ArrayList<Bitmap>();
for (int i = 0; i < itemscount ; i++) {
childView = adapter.getView(i,null,def);
/*childView = def.getChildAt(i);*/
childView.measure(View.MeasureSpec.makeMeasureSpec(def.getWidth(),
View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
childView.layout(0, 0, childView.getMeasuredWidth(),
childView.getMeasuredHeight());
childView.setDrawingCacheEnabled(true);
childView.buildDrawingCache();
/*childView.getDrawingCache();*/
bmps.add(childView.getDrawingCache());
allitemsheight+=childView.getMeasuredHeight();
}
Bitmap bigbitmap = Bitmap.createBitmap(def.getMeasuredWidth(),
allitemsheight , Bitmap.Config.ARGB_8888);
Paint paint = new Paint();
Canvas bigcanvas = new Canvas(bigbitmap);
for (int i = 0; i < bmps.size(); i++) {
Bitmap bmp = bmps.get(i);
bigcanvas.drawBitmap(bmp, 0, iHeight, paint);
/*bigcanvas.drawColor(Color.WHITE);
def.draw(bigcanvas);*/
iHeight+=bmp.getHeight();
bmp.recycle();
bmp=null;
}
bigbitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.scalePercent(45, 60);
myImg.setAlignment(Image.ALIGN_CENTER);
/*if(myImg.getWidth() >= doc.getPageSize().getWidth() || myImg.getHeight() >= doc.getPageSize().getHeight()){
myImg.scaleToFit(doc.getPageSize());
doc.newPage();
}
myImg.setAbsolutePosition((doc.getPageSize().getWidth() - myImg.getScaledWidth()) / BaseField.BORDER_WIDTH_MEDIUM, (doc.getPageSize().getHeight() - myImg.getScaledHeight()) / BaseField.BORDER_WIDTH_MEDIUM);
doc.add(myImg);
doc.add( new Paragraph());*/
///////////////////////////////////////
/////////////////////////////////////////
/////////////////////////////////////
Document document = new Document();
PdfWriter pdfWriter2 = PdfWriter.getInstance(document, fOut2);
document.open();
PdfContentByte content = pdfWriter2.getDirectContent();
myImg.scaleAbsolute(PageSize.A4);
myImg.setAbsolutePosition(0, 0);
float width = PageSize.A4.getWidth();
float heightRatio = myImg.getHeight() * width / myImg.getWidth();
int nPages = (int) (heightRatio / PageSize.A4.getHeight());
float difference = heightRatio % PageSize.A4.getHeight();
while (nPages >= 0) {
document.newPage();
content.addImage(myImg, width, 0, 0, heightRatio, 0, -((--nPages * PageSize.A4.getHeight()) + difference));
}
document.close();
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
} finally {
/*doc.close();*/
}

Resizing dynamically loaded images Flash AS3

I have a series of banners (standard sizes) which all need to load the same corresponding image for each slide. I can load them fine but I want the image to match the size of the container MC that the image is being loaded to, is that possible? Either that or to set the height/width manually...
Everything I have tried doesnt work, here is the code for the working state (where it just loads the image which stretches across the stage)
Code:
var myImage:String = dynamicContent.Profile[0].propImage.Url;
function myImageLoader(file:String, x:Number, y:Number):StudioLoader{
var myImageLoader:StudioLoader = new StudioLoader();
var request:URLRequest = new URLRequest(file);
myImageLoader.load(request);
myImageLoader.x = -52;
myImageLoader.y =-30;
return myImageLoader;
}
propImage1.addChild(loadImage(enabler.getUrl(myImage),-20,0));
You can resize your loaded image after the Event.COMPLETE on the LoaderInfo (contentLoaderInfo) of your URLLoader is fired, so you can do like this :
var request:URLRequest = new URLRequest('http://www.example.com/image.jpg');
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, on_loadComplete);
function on_loadComplete(e:Event):void {
var image:DisplayObject = loader.content;
image.x = 100;
image.y = 100;
image.width = 300;
image.height = 200;
addChild(image);
}
loader.load(request);
Edit :
load_image('http://www.example.com/image.jpg');
function load_image(url){
var request:URLRequest = new URLRequest(url);
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, on_loadComplete);
function on_loadComplete(e:Event):void {
add_image(loader.content);
}
loader.load(request);
}
function add_image(image:DisplayObject, _x:int = 0, _y:int = 0, _width:int = 100, _height:int = 100){
image.x = _x;
image.y = _y;
image.width = _width;
image.height = _height;
addChild(image);
}
Hope that can help.

Visifire.Charts How to disable vertical lines. WP

Chart is created by code. But I can't disable vertical lines in chart.
It is a code of creating chart:
public void CreateChart() {
CleanChart();
visiChart = new Chart()
{
ToolTipEnabled = true,
Width = 400,
Height = 200,
Padding = new Thickness(0),
Margin = new Thickness(0, 6, 0, -12),
Background = new SolidColorBrush(Colors.White),
};
ChartGrid grid = new ChartGrid()
{
Enabled = false
};
DataSeries dataSeries = new DataSeries();
DataPoint dataPoint;
Axis yAx = new Axis()
{
AxisLabels = new AxisLabels() { Enabled = false },
Grids = new ChartGridCollection() {grid}
};
int i = 0;
var deps = App.CurrentAgreement.Deposits.Deposit.Where(x => x.DepositIliv + x.DepositLink > 0).ToList();
foreach (var dep in deps) {
dataPoint = new DataPoint();
dataPoint.YValue = dep.DepositIliv + dep.DepositLink + dep.UValue + dep.WarrantyValue;
dataPoint.XValue = i;
i++;
dataPoint.LabelText = dataPoint.YValue.Out();
dataPoint.AxisXLabel = DateTime.Parse(dep.DepositDate).ToString("MMM yyyy");
dataPoint.MouseLeftButtonUp += dataPoint_MouseLeftButtonUp;
dataSeries.DataPoints.Add(dataPoint);
}
dataSeries.LabelEnabled = true;
dataSeries.RenderAs = RenderAs.Column;
dataSeries.Color = new SolidColorBrush(Colors.Green);
visiChart.Series.Add(dataSeries);
visiChart.AxesY.Add(yAx);
ChartPlaceHolder.Children.Add(visiChart);
}
But i dont need vertical lines visible. It is a screen of chart.
How i can disable lines??
Help me, please.
You have to disable the Grid lines from AxisX also.
Example:
ChartGrid grid = new ChartGrid()
{
Enabled = false
};
Axis xAx = new Axis();
xAx.Grids.Add(grid);
visiChart.AxesX.Add(xAx);

Resources