text stringlengths 7 35.3M | id stringlengths 11 185 | metadata dict | __index_level_0__ int64 0 2.14k |
|---|---|---|---|
@import "_common"
@import "_sidebar"
@import "_markdown"
nav
height 5rem
background-color $main-bg-color
position absolute
width 100%
z-index 9999
img
width 140px
height 42px
float left
position absolute
margin-top 1rem
.nav-link
li
float right
padding 1.75rem 1rem
a
color $main-color
button
float right
margin-top 1rem
padding 0.75rem 1.25rem
background-color $main-color
color $contrast-color
border-radius 5px
margin-top 0.4rem
.container
margin 0 auto
max-width 80rem
padding 0rem 10rem 3rem 15rem
position relative
.sidebar
padding 2.187rem
padding-top 7rem
width 11.25rem
margin-left -15rem
float left
article
padding 7.75rem 7.75rem 0rem 3.25rem
margin-left 1.25rem
.sub-nav
position absolute
top 15rem
right 0
width 10rem
dl
dt
color #525252
font-weight 700
margin-bottom 1rem
padding-left 0.5rem
dd
margin-bottom 0.25rem
padding-left 0.5rem
overflow hidden
text-overflow ellipsis
dd.select
border-left:0.125rem #f4645f solid;
padding-left:0.375rem;
.footer
text-align center;
margin-top 2.75rem;
color: $sub-font-color
font-size 0.75rem
footer
background-color rgb(52,52,52)
height 3.125rem
padding 1.875rem
footer p
text-align center
color rgb(174,174,174)
font-size 0.8125rem
line-height 1.8
.disable
color rgb(175,175,175)
.disable:hover
color rgb(175,175,175)
text-decoration none
@media screen and (min-width: 960px)
.hiden-in-pc
display none
.hiden-in-phone
display inline
nav
button
margin-top 1rem
button:hover
background-color #dc504b
footer
padding 3.125rem
@media screen and (max-width: 960px)
.hiden-in-pc
display inline
.hiden-in-phone
display none
nav
height 3rem
position fixed
button
margin-top 0.4rem
padding 0.35rem 0.75rem
img
width 110px
height 30px
margin-top 0.5rem
.container
margin 0
padding 0rem 0rem 3rem 0rem
.sidebar
display none
article
padding 5.5rem 1.75rem 0.2rem 0.2rem
min-height 35rem | xLua/docs/source/themes/catlib/source/css/page.styl/0 | {
"file_path": "xLua/docs/source/themes/catlib/source/css/page.styl",
"repo_id": "xLua",
"token_count": 1362
} | 2,041 |
<p align="center">
<img src="https://i.imgur.com/x8rtGr4.gif" alt="3D Game Shaders For Beginners" title="3D Game Shaders For Beginners">
</p>
# 3D Game Shaders For Beginners
Interested in adding
textures,
lighting,
shadows,
normal maps,
glowing objects,
ambient occlusion,
reflections,
refractions,
and more to your 3D game?
Great!
Below is a collection of shading techniques that will take your game visuals to new heights.
I've explained each technique in such a way that you can take what you learn here and apply/port it to
whatever stack you use—be it Godot, Unity, Unreal, or something else.
For the glue in between the shaders,
I've chosen the fabulous Panda3D game engine and the OpenGL Shading Language (GLSL).
So if that is your stack, then you'll also get the benefit of learning how to use these
shading techniques with Panda3D and OpenGL specifically.
## Table Of Contents
- [Setup](sections/setup.md)
- [Building The Demo](sections/building-the-demo.md)
- [Running The Demo](sections/running-the-demo.md)
- [Reference Frames](sections/reference-frames.md)
- [GLSL](sections/glsl.md)
- [Render To Texture](sections/render-to-texture.md)
- [Texturing](sections/texturing.md)
- [Lighting](sections/lighting.md)
- [Blinn-Phong](sections/blinn-phong.md)
- [Fresnel Factor](sections/fresnel-factor.md)
- [Rim Lighting](sections/rim-lighting.md)
- [Cel Shading](sections/cel-shading.md)
- [Normal Mapping](sections/normal-mapping.md)
- [Deferred Rendering](sections/deferred-rendering.md)
- [Fog](sections/fog.md)
- [Blur](sections/blur.md)
- [Bloom](sections/bloom.md)
- [SSAO](sections/ssao.md)
- [Motion Blur](sections/motion-blur.md)
- [Chromatic Aberration](sections/chromatic-aberration.md)
- [Screen Space Reflection](sections/screen-space-reflection.md)
- [Screen Space Refraction](sections/screen-space-refraction.md)
- [Foam](sections/foam.md)
- [Flow Mapping](sections/flow-mapping.md)
- [Outlining](sections/outlining.md)
- [Depth Of Field](sections/depth-of-field.md)
- [Posterization](sections/posterization.md)
- [Pixelization](sections/pixelization.md)
- [Sharpen](sections/sharpen.md)
- [Dilation](sections/dilation.md)
- [Film Grain](sections/film-grain.md)
- [Lookup Table (LUT)](sections/lookup-table.md)
- [Gamma Correction](sections/gamma-correction.md)
## License
The included license applies only to the software portion of 3D Game Shaders For Beginners—
specifically the `.cxx`, `.vert`, and `.frag` source code files.
No other portion of 3D Game Shaders For Beginners has been licensed for use.
## Attributions
- [Kiwi Soda Font](https://fontenddev.com/fonts/kiwi-soda/)
## Copyright
(C) 2019 David Lettier
<br>
[lettier.com](https://www.lettier.com)
| 3d-game-shaders-for-beginners/README.md/0 | {
"file_path": "3d-game-shaders-for-beginners/README.md",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 896
} | 0 |
/*
(C) 2019 David Lettier
lettier.com
*/
#version 150
uniform vec2 gamma;
uniform sampler2D colorTexture;
out vec4 fragColor;
void main() {
vec2 texSize = textureSize(colorTexture, 0).xy;
vec2 texCoord = gl_FragCoord.xy / texSize;
fragColor = texture(colorTexture, texCoord);
fragColor.rgb = pow(fragColor.rgb, vec3(gamma.y));
}
| 3d-game-shaders-for-beginners/demonstration/shaders/fragment/gamma-correction.frag/0 | {
"file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/gamma-correction.frag",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 140
} | 1 |
/*
(C) 2019 David Lettier
lettier.com
*/
#version 150
uniform sampler2D colorTexture;
uniform sampler2D colorBlurTexture;
uniform sampler2D maskTexture;
out vec4 fragColor;
void main() {
vec2 texSize = textureSize(colorTexture, 0).xy;
vec2 texCoord = gl_FragCoord.xy / texSize;
vec4 mask = texture(maskTexture, texCoord);
vec4 color = texture(colorTexture, texCoord);
vec4 colorBlur = texture(colorBlurTexture, texCoord);
float amount = clamp(mask.r, 0.0, 1.0);
if (amount <= 0.0) { fragColor = vec4(0.0); return; }
float roughness = clamp(mask.g, 0.0, 1.0);
fragColor = mix(color, colorBlur, roughness) * amount;
}
| 3d-game-shaders-for-beginners/demonstration/shaders/fragment/reflection.frag/0 | {
"file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/reflection.frag",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 260
} | 2 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<meta name="description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta property="og:title" content="Blinn Phong | 3D Game Shaders For Beginners" />
<meta property="og:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta property="og:image" content="https://i.imgur.com/JIDwVTm.png" />
<meta name="twitter:title" content="Blinn Phong | 3D Game Shaders For Beginners" />
<meta name="twitter:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta name="twitter:image" content="https://i.imgur.com/JIDwVTm.png" />
<meta name="twitter:card" content="summary_large_image" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<meta name="author" content="David Lettier" />
<title>Blinn Phong | 3D Game Shaders For Beginners</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
</style>
<style>
code.sourceCode > span { display: inline-block; line-height: 1.25; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode { white-space: pre; position: relative; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
code.sourceCode { white-space: pre-wrap; }
code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
background-color: #232629;
color: #7a7c7d;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #7a7c7d; padding-left: 4px; }
div.sourceCode
{ color: #cfcfc2; background-color: #232629; }
@media screen {
code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span. { color: #cfcfc2; } /* Normal */
code span.al { color: #95da4c; } /* Alert */
code span.an { color: #3f8058; } /* Annotation */
code span.at { color: #2980b9; } /* Attribute */
code span.bn { color: #f67400; } /* BaseN */
code span.bu { color: #7f8c8d; } /* BuiltIn */
code span.cf { color: #fdbc4b; } /* ControlFlow */
code span.ch { color: #3daee9; } /* Char */
code span.cn { color: #27aeae; } /* Constant */
code span.co { color: #7a7c7d; } /* Comment */
code span.cv { color: #7f8c8d; } /* CommentVar */
code span.do { color: #a43340; } /* Documentation */
code span.dt { color: #2980b9; } /* DataType */
code span.dv { color: #f67400; } /* DecVal */
code span.er { color: #da4453; } /* Error */
code span.ex { color: #0099ff; } /* Extension */
code span.fl { color: #f67400; } /* Float */
code span.fu { color: #8e44ad; } /* Function */
code span.im { color: #27ae60; } /* Import */
code span.in { color: #c45b00; } /* Information */
code span.kw { color: #cfcfc2; } /* Keyword */
code span.op { color: #cfcfc2; } /* Operator */
code span.ot { color: #27ae60; } /* Other */
code span.pp { color: #27ae60; } /* Preprocessor */
code span.re { color: #2980b9; } /* RegionMarker */
code span.sc { color: #3daee9; } /* SpecialChar */
code span.ss { color: #da4453; } /* SpecialString */
code span.st { color: #f44f4f; } /* String */
code span.va { color: #27aeae; } /* Variable */
code span.vs { color: #da4453; } /* VerbatimString */
code span.wa { color: #da4453; } /* Warning */
</style>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p><a href="lighting.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="fresnel-factor.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p>
<h1 id="3d-game-shaders-for-beginners">3D Game Shaders For Beginners</h1>
<h2 id="blinn-phong">Blinn-Phong</h2>
<p align="center">
<img src="https://i.imgur.com/CFWEeGK.gif" alt="Blinn-Phong" title="Blinn-Phong">
</p>
<p>Blinn-Phong is a slight adjustment of the Phong model you saw in the <a href="lighting.html">lighting</a> section. It provides more plausible or realistic specular reflections. You'll notice that Blinn-Phong produces elliptical or elongated specular reflections versus the spherical specular reflections produced by the Phong model. In certain cases, Blinn-Phong can be more efficient to calculate than Phong.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb1-1"><a href="#cb1-1"></a> <span class="co">// ...</span></span>
<span id="cb1-2"><a href="#cb1-2"></a></span>
<span id="cb1-3"><a href="#cb1-3"></a> vec3 light = normal(lightPosition.xyz - vertexPosition.xyz);</span>
<span id="cb1-4"><a href="#cb1-4"></a> vec3 eye = normalize(-vertexPosition.xyz);</span>
<span id="cb1-5"><a href="#cb1-5"></a> vec3 halfway = normalize(light + eye);</span>
<span id="cb1-6"><a href="#cb1-6"></a></span>
<span id="cb1-7"><a href="#cb1-7"></a> <span class="co">// ...</span></span></code></pre></div>
<p>Instead of computing the reflection vector, compute the halfway or half angle vector. This vector is between the view/camera/eye and light direction vector.</p>
<p align="center">
<img src="https://i.imgur.com/vtqd1Ox.gif" alt="Blinn-Phong vs Phong" title="Blinn-Phong vs Phong">
</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb2-1"><a href="#cb2-1"></a> <span class="co">// ...</span></span>
<span id="cb2-2"><a href="#cb2-2"></a></span>
<span id="cb2-3"><a href="#cb2-3"></a> <span class="dt">float</span> specularIntensity = dot(normal, halfway);</span>
<span id="cb2-4"><a href="#cb2-4"></a></span>
<span id="cb2-5"><a href="#cb2-5"></a> <span class="co">// ...</span></span></code></pre></div>
<p>The specular intensity is now the dot product of the normal and halfway vector. In the Phong model, it is the dot product of the reflection and view vector.</p>
<p align="center">
<img src="https://i.imgur.com/WZQqxEH.png" alt="Full specular intensity." title="Full specular intensity.">
</p>
<p>The half angle vector (magenta arrow) will point in the same direction as the normal (green arrow) when the view vector (orange arrow) points in the same direction as the reflection vector (magenta arrow). In this case, both the Blinn-Phong and Phong specular intensity will be one.</p>
<p align="center">
<img src="https://i.imgur.com/kiSdJzt.png" alt="Blinn-Phong vs Phong" title="Blinn-Phong vs Phong">
</p>
<p>In other cases, the specular intensity for Blinn-Phong will be greater than zero while the specular intensity for Phong will be zero.</p>
<h3 id="source">Source</h3>
<ul>
<li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/src/main.cxx" target="_blank" rel="noopener noreferrer">main.cxx</a></li>
<li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/vertex/base.vert" target="_blank" rel="noopener noreferrer">base.vert</a></li>
<li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/base.frag" target="_blank" rel="noopener noreferrer">base.frag</a></li>
</ul>
<h2 id="copyright">Copyright</h2>
<p>(C) 2020 David Lettier <br> <a href="https://www.lettier.com">lettier.com</a></p>
<p><a href="lighting.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="fresnel-factor.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p>
</body>
</html>
| 3d-game-shaders-for-beginners/docs/blinn-phong.html/0 | {
"file_path": "3d-game-shaders-for-beginners/docs/blinn-phong.html",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 3782
} | 3 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<meta name="description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta property="og:title" content="GLSL | 3D Game Shaders For Beginners" />
<meta property="og:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta property="og:image" content="https://i.imgur.com/JIDwVTm.png" />
<meta name="twitter:title" content="GLSL | 3D Game Shaders For Beginners" />
<meta name="twitter:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta name="twitter:image" content="https://i.imgur.com/JIDwVTm.png" />
<meta name="twitter:card" content="summary_large_image" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<meta name="author" content="David Lettier" />
<title>GLSL | 3D Game Shaders For Beginners</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
</style>
<style>
code.sourceCode > span { display: inline-block; line-height: 1.25; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode { white-space: pre; position: relative; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
code.sourceCode { white-space: pre-wrap; }
code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
background-color: #232629;
color: #7a7c7d;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #7a7c7d; padding-left: 4px; }
div.sourceCode
{ color: #cfcfc2; background-color: #232629; }
@media screen {
code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span. { color: #cfcfc2; } /* Normal */
code span.al { color: #95da4c; } /* Alert */
code span.an { color: #3f8058; } /* Annotation */
code span.at { color: #2980b9; } /* Attribute */
code span.bn { color: #f67400; } /* BaseN */
code span.bu { color: #7f8c8d; } /* BuiltIn */
code span.cf { color: #fdbc4b; } /* ControlFlow */
code span.ch { color: #3daee9; } /* Char */
code span.cn { color: #27aeae; } /* Constant */
code span.co { color: #7a7c7d; } /* Comment */
code span.cv { color: #7f8c8d; } /* CommentVar */
code span.do { color: #a43340; } /* Documentation */
code span.dt { color: #2980b9; } /* DataType */
code span.dv { color: #f67400; } /* DecVal */
code span.er { color: #da4453; } /* Error */
code span.ex { color: #0099ff; } /* Extension */
code span.fl { color: #f67400; } /* Float */
code span.fu { color: #8e44ad; } /* Function */
code span.im { color: #27ae60; } /* Import */
code span.in { color: #c45b00; } /* Information */
code span.kw { color: #cfcfc2; } /* Keyword */
code span.op { color: #cfcfc2; } /* Operator */
code span.ot { color: #27ae60; } /* Other */
code span.pp { color: #27ae60; } /* Preprocessor */
code span.re { color: #2980b9; } /* RegionMarker */
code span.sc { color: #3daee9; } /* SpecialChar */
code span.ss { color: #da4453; } /* SpecialString */
code span.st { color: #f44f4f; } /* String */
code span.va { color: #27aeae; } /* Variable */
code span.vs { color: #da4453; } /* VerbatimString */
code span.wa { color: #da4453; } /* Warning */
</style>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p><a href="reference-frames.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="render-to-texture.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p>
<h1 id="3d-game-shaders-for-beginners">3D Game Shaders For Beginners</h1>
<h2 id="glsl">GLSL</h2>
<p align="center">
<img src="https://i.imgur.com/7b5MCBG.gif" alt="" title="">
</p>
<p>Instead of using the <a href="https://en.wikipedia.org/wiki/Fixed-function">fixed-function</a> pipeline, you'll be using the programmable GPU rendering pipeline. Since it is programmable, it is up to you to supply the programming in the form of shaders. A shader is a (typically small) program you write using a syntax reminiscent of C. The programmable GPU rendering pipeline has various different stages that you can program with shaders. The different types of shaders include vertex, tessellation, geometry, fragment, and compute. You'll only need to focus on the vertex and fragment stages for the techniques below.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb1-1"><a href="#cb1-1"></a><span class="er">#version 150</span></span>
<span id="cb1-2"><a href="#cb1-2"></a></span>
<span id="cb1-3"><a href="#cb1-3"></a><span class="dt">void</span> main() {}</span></code></pre></div>
<p>Here is a bare-bones GLSL shader consisting of the GLSL version number and the main function.</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb2-1"><a href="#cb2-1"></a><span class="er">#version 150</span></span>
<span id="cb2-2"><a href="#cb2-2"></a></span>
<span id="cb2-3"><a href="#cb2-3"></a>uniform mat4 p3d_ModelViewProjectionMatrix;</span>
<span id="cb2-4"><a href="#cb2-4"></a></span>
<span id="cb2-5"><a href="#cb2-5"></a>in vec4 p3d_Vertex;</span>
<span id="cb2-6"><a href="#cb2-6"></a></span>
<span id="cb2-7"><a href="#cb2-7"></a><span class="dt">void</span> main()</span>
<span id="cb2-8"><a href="#cb2-8"></a>{</span>
<span id="cb2-9"><a href="#cb2-9"></a> gl_Position = p3d_ModelViewProjectionMatrix * p3d_Vertex;</span>
<span id="cb2-10"><a href="#cb2-10"></a>}</span></code></pre></div>
<p>Here is a stripped down GLSL vertex shader that transforms an incoming vertex to clip space and outputs this new position as the vertex's homogeneous position. The <code>main</code> procedure doesn't return anything since it is <code>void</code> and the <code>gl_Position</code> variable is a built-in output.</p>
<p>Take note of the keywords <code>uniform</code> and <code>in</code>. The <code>uniform</code> keyword means this global variable is the same for all vertexes. Panda3D sets the <code>p3d_ModelViewProjectionMatrix</code> for you and it is the same matrix for each vertex. The <code>in</code> keyword means this global variable is being given to the shader. The vertex shader receives each vertex that makes up the geometry the vertex shader is attached to.</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb3-1"><a href="#cb3-1"></a><span class="er">#version 150</span></span>
<span id="cb3-2"><a href="#cb3-2"></a></span>
<span id="cb3-3"><a href="#cb3-3"></a>out vec4 fragColor;</span>
<span id="cb3-4"><a href="#cb3-4"></a></span>
<span id="cb3-5"><a href="#cb3-5"></a><span class="dt">void</span> main() {</span>
<span id="cb3-6"><a href="#cb3-6"></a> fragColor = vec4(<span class="dv">0</span>, <span class="dv">1</span>, <span class="dv">0</span>, <span class="dv">1</span>);</span>
<span id="cb3-7"><a href="#cb3-7"></a>}</span></code></pre></div>
<p>Here is a stripped down GLSL fragment shader that outputs the fragment color as solid green. Keep in mind that a fragment affects at most one screen pixel but a single pixel can be affected by many fragments.</p>
<p>Take note of the <code>out</code> keyword. The <code>out</code> keyword means this global variable is being set by the shader. The name <code>fragColor</code> is arbitrary so feel free to choose a different one.</p>
<p align="center">
<img src="https://i.imgur.com/V25UzMa.gif" alt="Output of the stripped down shaders." title="Output of the stripped down shaders.">
</p>
<p>This is the output of the two shaders shown above.</p>
<h2 id="copyright">Copyright</h2>
<p>(C) 2019 David Lettier <br> <a href="https://www.lettier.com">lettier.com</a></p>
<p><a href="reference-frames.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="render-to-texture.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p>
</body>
</html>
| 3d-game-shaders-for-beginners/docs/glsl.html/0 | {
"file_path": "3d-game-shaders-for-beginners/docs/glsl.html",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 3894
} | 4 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<meta name="description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta property="og:title" content="Sharpen | 3D Game Shaders For Beginners" />
<meta property="og:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta property="og:image" content="https://i.imgur.com/JIDwVTm.png" />
<meta name="twitter:title" content="Sharpen | 3D Game Shaders For Beginners" />
<meta name="twitter:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." />
<meta name="twitter:image" content="https://i.imgur.com/JIDwVTm.png" />
<meta name="twitter:card" content="summary_large_image" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<meta name="author" content="David Lettier" />
<title>Sharpen | 3D Game Shaders For Beginners</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
</style>
<style>
code.sourceCode > span { display: inline-block; line-height: 1.25; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode { white-space: pre; position: relative; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
code.sourceCode { white-space: pre-wrap; }
code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
background-color: #232629;
color: #7a7c7d;
}
pre.numberSource { margin-left: 3em; border-left: 1px solid #7a7c7d; padding-left: 4px; }
div.sourceCode
{ color: #cfcfc2; background-color: #232629; }
@media screen {
code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
code span. { color: #cfcfc2; } /* Normal */
code span.al { color: #95da4c; } /* Alert */
code span.an { color: #3f8058; } /* Annotation */
code span.at { color: #2980b9; } /* Attribute */
code span.bn { color: #f67400; } /* BaseN */
code span.bu { color: #7f8c8d; } /* BuiltIn */
code span.cf { color: #fdbc4b; } /* ControlFlow */
code span.ch { color: #3daee9; } /* Char */
code span.cn { color: #27aeae; } /* Constant */
code span.co { color: #7a7c7d; } /* Comment */
code span.cv { color: #7f8c8d; } /* CommentVar */
code span.do { color: #a43340; } /* Documentation */
code span.dt { color: #2980b9; } /* DataType */
code span.dv { color: #f67400; } /* DecVal */
code span.er { color: #da4453; } /* Error */
code span.ex { color: #0099ff; } /* Extension */
code span.fl { color: #f67400; } /* Float */
code span.fu { color: #8e44ad; } /* Function */
code span.im { color: #27ae60; } /* Import */
code span.in { color: #c45b00; } /* Information */
code span.kw { color: #cfcfc2; } /* Keyword */
code span.op { color: #cfcfc2; } /* Operator */
code span.ot { color: #27ae60; } /* Other */
code span.pp { color: #27ae60; } /* Preprocessor */
code span.re { color: #2980b9; } /* RegionMarker */
code span.sc { color: #3daee9; } /* SpecialChar */
code span.ss { color: #da4453; } /* SpecialString */
code span.st { color: #f44f4f; } /* String */
code span.va { color: #27aeae; } /* Variable */
code span.vs { color: #da4453; } /* VerbatimString */
code span.wa { color: #da4453; } /* Warning */
</style>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
<![endif]-->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p><a href="pixelization.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="dilation.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p>
<h1 id="3d-game-shaders-for-beginners">3D Game Shaders For Beginners</h1>
<h2 id="sharpen">Sharpen</h2>
<p align="center">
<img src="https://i.imgur.com/VFDKNvl.gif" alt="Sharpen" title="Sharpen">
</p>
<p>The sharpen effect increases the contrast at the edges of the image. This comes in handy when your graphics are bit too soft.</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb1-1"><a href="#cb1-1"></a> <span class="co">// ...</span></span>
<span id="cb1-2"><a href="#cb1-2"></a></span>
<span id="cb1-3"><a href="#cb1-3"></a> <span class="dt">float</span> amount = <span class="fl">0.8</span>;</span>
<span id="cb1-4"><a href="#cb1-4"></a></span>
<span id="cb1-5"><a href="#cb1-5"></a> <span class="co">// ...</span></span></code></pre></div>
<p>You can control how sharp the result is by adjusting the amount. An amount of zero leaves the image untouched. Try negative values for an odd look.</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb2-1"><a href="#cb2-1"></a> <span class="co">// ...</span></span>
<span id="cb2-2"><a href="#cb2-2"></a></span>
<span id="cb2-3"><a href="#cb2-3"></a> <span class="dt">float</span> neighbor = amount * -<span class="dv">1</span>;</span>
<span id="cb2-4"><a href="#cb2-4"></a> <span class="dt">float</span> center = amount * <span class="dv">4</span> + <span class="dv">1</span>;</span>
<span id="cb2-5"><a href="#cb2-5"></a></span>
<span id="cb2-6"><a href="#cb2-6"></a> <span class="co">// ...</span></span></code></pre></div>
<p>Neighboring fragments are multiplied by <code>amount * -1</code>. The current fragment is multiplied by <code>amount * 4 + 1</code>.</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb3-1"><a href="#cb3-1"></a> <span class="co">// ...</span></span>
<span id="cb3-2"><a href="#cb3-2"></a></span>
<span id="cb3-3"><a href="#cb3-3"></a> vec3 color =</span>
<span id="cb3-4"><a href="#cb3-4"></a> texture(sharpenTexture, vec2(gl_FragCoord.x + <span class="dv">0</span>, gl_FragCoord.y + <span class="dv">1</span>) / texSize).rgb</span>
<span id="cb3-5"><a href="#cb3-5"></a> * neighbor</span>
<span id="cb3-6"><a href="#cb3-6"></a></span>
<span id="cb3-7"><a href="#cb3-7"></a> + texture(sharpenTexture, vec2(gl_FragCoord.x - <span class="dv">1</span>, gl_FragCoord.y + <span class="dv">0</span>) / texSize).rgb</span>
<span id="cb3-8"><a href="#cb3-8"></a> * neighbor</span>
<span id="cb3-9"><a href="#cb3-9"></a> + texture(sharpenTexture, vec2(gl_FragCoord.x + <span class="dv">0</span>, gl_FragCoord.y + <span class="dv">0</span>) / texSize).rgb</span>
<span id="cb3-10"><a href="#cb3-10"></a> * center</span>
<span id="cb3-11"><a href="#cb3-11"></a> + texture(sharpenTexture, vec2(gl_FragCoord.x + <span class="dv">1</span>, gl_FragCoord.y + <span class="dv">0</span>) / texSize).rgb</span>
<span id="cb3-12"><a href="#cb3-12"></a> * neighbor</span>
<span id="cb3-13"><a href="#cb3-13"></a></span>
<span id="cb3-14"><a href="#cb3-14"></a> + texture(sharpenTexture, vec2(gl_FragCoord.x + <span class="dv">0</span>, gl_FragCoord.y - <span class="dv">1</span>) / texSize).rgb</span>
<span id="cb3-15"><a href="#cb3-15"></a> * neighbor</span>
<span id="cb3-16"><a href="#cb3-16"></a> ;</span>
<span id="cb3-17"><a href="#cb3-17"></a></span>
<span id="cb3-18"><a href="#cb3-18"></a> <span class="co">// ...</span></span></code></pre></div>
<p>The neighboring fragments are up, down, left, and right. After multiplying both the neighbors and the current fragment by their particular values, sum the result.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb4-1"><a href="#cb4-1"></a> <span class="co">// ...</span></span>
<span id="cb4-2"><a href="#cb4-2"></a></span>
<span id="cb4-3"><a href="#cb4-3"></a> fragColor = vec4(color, texture(sharpenTexture, texCoord).a);</span>
<span id="cb4-4"><a href="#cb4-4"></a></span>
<span id="cb4-5"><a href="#cb4-5"></a> <span class="co">// ...</span></span></code></pre></div>
<p>This sum is the final fragment color.</p>
<h3 id="source">Source</h3>
<ul>
<li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/src/main.cxx" target="_blank" rel="noopener noreferrer">main.cxx</a></li>
<li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/vertex/basic.vert" target="_blank" rel="noopener noreferrer">basic.vert</a></li>
<li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/sharpen.frag" target="_blank" rel="noopener noreferrer">sharpen.frag</a></li>
</ul>
<h2 id="copyright">Copyright</h2>
<p>(C) 2019 David Lettier <br> <a href="https://www.lettier.com">lettier.com</a></p>
<p><a href="pixelization.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="dilation.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p>
</body>
</html>
| 3d-game-shaders-for-beginners/docs/sharpen.html/0 | {
"file_path": "3d-game-shaders-for-beginners/docs/sharpen.html",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 4467
} | 5 |
[:arrow_backward:](deferred-rendering.md)
[:arrow_double_up:](../README.md)
[:arrow_up_small:](#)
[:arrow_down_small:](#copyright)
[:arrow_forward:](blur.md)
# 3D Game Shaders For Beginners
## Fog
<p align="center">
<img src="https://i.imgur.com/uNRxZl4.gif" alt="Fog" title="Fog">
</p>
Fog (or mist as it's called in Blender) adds atmospheric haze to a scene,
providing mystique and softening pop-ins (geometry suddenly entering into the camera's frustum).
```c
// ...
uniform vec4 color;
uniform vec2 nearFar;
// ...
```
To calculate the fog, you'll need its color, near distance, and far distance.
```c
// ...
uniform sampler2D positionTexture;
// ...
vec2 texSize = textureSize(positionTexture, 0).xy;
vec2 texCoord = gl_FragCoord.xy / texSize;
vec4 position = texture(positionTexture, texCoord);
// ...
```
In addition to the fog's attributes, you'll also need the fragment's vertex `position`.
```c
float fogMin = 0.00;
float fogMax = 0.97;
```
`fogMax` controls how much of the scene is still visible when the fog is most intense.
`fogMin` controls how much of the fog is still visible when the fog is least intense.
```c
// ...
float near = nearFar.x;
float far = nearFar.y;
float intensity =
clamp
( (position.y - near)
/ (far - near)
, fogMin
, fogMax
);
// ...
```
The example code uses a linear model for calculating the fog's intensity.
There's also an exponential model you could use.
The fog's intensity is `fogMin` before or at the start of the fog's `near` distance.
As the vertex `position` gets closer to the end of the fog's `far` distance, the `intensity` moves closer to `fogMax`.
For any vertexes after the end of the fog, the `intensity` is clamped to `fogMax`.
```c
// ...
fragColor = vec4(color.rgb, intensity);
// ...
```
Set the fragment's color to the fog `color` and the fragment's alpha channel to the `intensity`.
As `intensity` gets closer to one, you'll have less of the scene's color and more of the fog color.
When `intensity` reaches one, you'll have all fog color and nothing else.
```c
// ...
uniform sampler2D baseTexture;
uniform sampler2D fogTexture;
// ...
vec2 texSize = textureSize(baseTexture, 0).xy;
vec2 texCoord = gl_FragCoord.xy / texSize;
vec4 baseColor = texture(baseTexture, texCoord);
vec4 fogColor = texture(fogTexture, texCoord);
fragColor = baseColor;
// ...
fragColor = mix(fragColor, fogColor, min(fogColor.a, 1));
// ...
```
Normally you calculate the fog in the same shader that does the lighting calculations.
However, you can also break it out into its own framebuffer texture.
Here you see the fog color being applied to the rest of the scene much like you would apply a layer in GIMP.
This allows you to calculate the fog once instead calculating it in every shader that eventually needs it.
### Source
- [main.cxx](../demonstration/src/main.cxx)
- [basic.vert](../demonstration/shaders/vertex/basic.vert)
- [position.frag](../demonstration/shaders/fragment/position.frag)
- [normal.frag](../demonstration/shaders/fragment/normal.frag)
- [fog.frag](../demonstration/shaders/fragment/fog.frag)
- [outline.frag](../demonstration/shaders/fragment/outline.frag)
- [scene-combine.frag](../demonstration/shaders/fragment/scene-combine.frag)
## Copyright
(C) 2019 David Lettier
<br>
[lettier.com](https://www.lettier.com)
[:arrow_backward:](deferred-rendering.md)
[:arrow_double_up:](../README.md)
[:arrow_up_small:](#)
[:arrow_down_small:](#copyright)
[:arrow_forward:](blur.md)
| 3d-game-shaders-for-beginners/sections/fog.md/0 | {
"file_path": "3d-game-shaders-for-beginners/sections/fog.md",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 1233
} | 6 |
[:arrow_backward:](screen-space-reflection.md)
[:arrow_double_up:](../README.md)
[:arrow_up_small:](#)
[:arrow_down_small:](#copyright)
[:arrow_forward:](foam.md)
# 3D Game Shaders For Beginners
## Screen Space Refraction (SSR)
<p align="center">
<img src="https://i.imgur.com/8Mdcn4y.gif" alt="Screen Space Refraction" title="Screen Space Refraction">
</p>
Screen space refraction,
much like
[screen space reflection](screen-space-reflection.md),
adds a touch of realism you can't find anywhere else.
Glass, plastic, water, and other transparent/translucent materials spring to life.
[Screen space reflection](screen-space-reflection.md)
and screen space refraction work almost identically expect for one major difference.
Instead of using the reflected vector, screen space refraction uses the
[refracted vector](http://asawicki.info/news_1301_reflect_and_refract_functions.html).
It's a slight change in code but a big difference visually.
### Vertex Positions
Like SSAO, you'll need the vertex positions in view space.
Referrer back to [SSAO](ssao.md#vertex-positions) for details.
However,
unlike SSAO,
you'll need the scene's vertex positions with and without the refractive objects.
Refractive surfaces are translucent, meaning you can see through them.
Since you can see through them, you'll need the vertex positions behind the refractive surface.
Having both the foreground and background vertex positions will allow you to calculate
UV coordinates and depth.
### Vertex Normals
To compute the refractions, you'll need the scene's foreground vertex normals in view space.
The background vertex normals aren't needed unless you need to incorporate the background surface detail
while calculating the refracted UV coordinates and distances.
Referrer back to [SSAO](ssao.md#vertex-normals) for details.
<p align="center">
<img src="https://i.imgur.com/MZ2R8I6.gif" alt="Normal maps versus no normal maps." title="Normal maps versus no normal maps.">
</p>
Here you see the water refracting the light with and without normal maps.
If available, be sure to use the normal mapped normals instead of the vertex normals.
The smoother and flatter the surface, the harder it is to tell the light is being refracted.
There will be some distortion but not enough to make it worthwhile.
To use the normal maps instead,
you'll need to transform the normal mapped normals from tangent space to view space
just like you did in the [lighting](normal-mapping.md#fragment) calculations.
You can see this being done in [normal.frag](../demonstration/shaders/fragment/normal.frag).
### Position Transformations
<p align="center">
<img src="https://i.imgur.com/bXtXDyu.gif" alt="Position Transformations" title="Position Transformations">
</p>
Just like
[SSAO](ssao.md) and [screen space reflection](screen-space-reflection.md),
screen space refraction goes back and forth between the screen and view space.
You'll need the camera lens' projection matrix to transform points in view space to clip space.
From clip space, you'll have to transform the points again to UV space.
Once in UV space,
you can sample a vertex/fragment position from the scene
which will be the closest position in the scene to your sample.
This is the _screen space_ part in _screen space refraction_
since the "screen" is a texture UV mapped over a screen shaped rectangle.
### Refracted UV Coordinates
Recall that UV coordinates range from zero to one for both U and V.
The screen is just a 2D texture UV mapped over a screen-sized rectangle.
Knowing this, the example code doesn't actually need the final rendering of the scene
to compute the refraction.
It can instead calculate what UV coordinate each screen pixel will eventually use.
These calculated UV coordinates can be saved to a framebuffer texture
and used later when the scene has been rendered.
The process of refracting the UV coordinates is very similar to the process of
[reflecting the UV coordinates](screen-space-reflection.md#reflected-uv-coordinates).
Below are the adjustments you'll need to turn reflection into refraction.
```c
// ...
uniform sampler2D positionFromTexture;
uniform sampler2D positionToTexture;
uniform sampler2D normalFromTexture;
// ...
```
Reflection only deals with what is in front of the reflective surface.
Refraction, however, deals with what is behind the refractive surface.
To accommodate this, you'll need both the vertex positions of the scene
with the refracting surfaces taken out and the vertex positions of the scene
with the refracting surfaces left in.
<p align="center">
<img src="https://i.imgur.com/FjQtjsm.gif" alt="Without and with refractive surfaces." title="Without and with refractive surfaces.">
</p>
`positionFromTexture` are the scene's vertex positions with the refracting surfaces left in.
`positionToTexture` are the scene's vertex positions with the refracting surfaces taken out.
`normalFromTexture` are the scene's vertex normals with the refraction surfaces left in.
There's no need for the vertex normals behind the refractive surfaces unless
you want to incorporate the surface detail for the background geometry.
```c
// ...
uniform vec2 rior;
// ...
```
Refraction has one more adjustable parameter than reflection.
`rior` is the relative index of refraction or relative refractive index.
It is the ratio of the refraction indexes of two mediums.
So for example, going from water to air is `1 / 1.33 ≈ 0.75`.
The numerator is the refractive index of the medium the light is leaving and
the denominator is the refractive index of the medium the light is entering.
An `rior` of one means the light passes right through without being refracted or bent.
As `rior` grows, the refraction will become a
[reflection](https://en.wikipedia.org/wiki/Total_internal_reflection).
There's no requirement that `rior` must adhere to the real world.
The demo uses `1.05`.
This is completely unrealistic (light does not travel faster through water than air)
but the realistic setting produced too many artifacts.
In the end, the distortion only has to be believable—not realistic.
<p align="center">
<img src="https://i.imgur.com/dDOnobK.gif" alt="Adjusting the relative index of refraction." title="Adjusting the relative index of refraction.">
</p>
`rior` values above one tend to elongate the refraction while
numbers below one tend to shrink the refraction.
As it was with screen space reflection,
the screen doesn't have the entire geometry of the scene.
A refracted ray may march through the screen space and never hit a captured surface.
Or it may hit a surface but it's the backside not captured by the camera.
When this happened during reflection, the fragment was left blank.
This indicated no reflection or not enough information to determine a reflection.
Leaving the fragment blank was fine for reflection since the reflective surface would fill in the gaps.
<p align="center">
<img src="https://i.imgur.com/vcQDAYU.gif" alt="Refraction Holes" title="Refraction Holes">
</p>
For refraction, however, we must set the fragment to some UV.
If the fragment is left blank,
the refractive surface will contain holes that let the detail behind it come through.
This would be okay for a completely transparent surface but usually
the refractive surface will have some tint to it, reflection, etc.
```c
// ...
vec2 texSize = textureSize(positionFromTexture, 0).xy;
vec2 texCoord = gl_FragCoord.xy / texSize;
vec4 uv = vec4(texCoord.xy, 1, 1);
// ...
```
The best choice is to select the UV as if the `rior` was one.
This will leave the UV coordinate unchanged,
allowing the background to show through instead
of there being a hole in the refractive surface.
<p align="center">
<img src="https://i.imgur.com/9fybLUO.png" alt="Refraction UV Map" title="Refraction UV Map">
</p>
Here you see the refracted UV texture for the mill scene.
The wheel and waterway disturb what is otherwise a smooth gradient.
The disruptions shift the UV coordinates from their screen position to their refracted screen position.
```c
// ...
vec3 unitPositionFrom = normalize(positionFrom.xyz);
vec3 normalFrom = normalize(texture(normalFromTexture, texCoord).xyz);
vec3 pivot = normalize(refract(unitPositionFrom, normalFrom, rior.x));
// ...
```
The most important difference is the calculation of the refracted vector versus the reflected vector.
Both use the unit position and normal but `refract` takes an additional parameter specifying the relative refractive index.
```c
// ...
frag += increment;
uv.xy = frag / texSize;
positionTo = texture(positionToTexture, uv.xy);
// ...
```
The `positionTo`, sampled by the `uv` coordinates, uses the `positionToTexture`.
For reflection,
you only need one framebuffer texture containing the scene's interpolated vertex positions in view space.
However,
for refraction,
`positionToTexture` contains the vertex positions of the scene minus the refractive surfaces since
the refraction ray typically goes behind the surface.
If `positionFromTexture` and `positionToTexture` were the same for refraction,
the refracted ray would hit the refractive surface instead of what is behind it.
### Refraction Mask
<p align="center">
<img src="https://i.imgur.com/iuFYVWB.gif" alt="Material Specular" title="Material Specular">
</p>
You'll need a mask to filter out the non-refractive parts of the scene.
This mask will determine which fragment does and does not receive a refracted color.
You could use this mask during the refracted UV calculation step or later when you
actually sample the colors at the refracted UV coordinates.
The mill scene uses the models' material specular as a mask.
For the demo's purposes,
the specular map is sufficient but you may want to use a more specialized map.
Refer back to [screen space reflection](screen-space-reflection.md#specular-map) for how to render the specular map.
## Background Colors
<p align="center">
<img src="https://i.imgur.com/AmT9RrU.gif" alt="Background Colors" title="Background Colors">
</p>
You'll need to render the parts of the scene behind the refractive objects.
This can be done by hiding the refractive objects and then rendering the scene to a framebuffer texture.
### Foreground Colors
<p align="center">
<img src="https://i.imgur.com/6RPHULr.gif" alt="Foreground Colors" title="Foreground Colors">
</p>
```c
// ...
uniform sampler2D uvTexture;
uniform sampler2D refractionMaskTexture;
uniform sampler2D positionFromTexture;
uniform sampler2D positionToTexture;
uniform sampler2D backgroundColorTexture;
// ...
```
To render the actual refractions or foreground colors,
you'll need the refracted UV coordinates,
refraction mask,
the foreground and background vertex positions,
and the background colors.
```c
// ...
vec3 tintColor = vec3(0.27, 0.58, 0.92, 0.3);
float depthMax = 2;
// ...
```
`tintColor` and `depthMax` are adjustable parameters.
`tintColor` colorizes the background color.
`depthMax` ranges from zero to infinity.
When the distance between the foreground and background position reaches `depthMax`,
the foreground color will be the fully tinted background color.
At distance zero, the foreground will be the background color.
```c
// ...
vec2 texSize = textureSize(backgroundColorTexture, 0).xy;
vec2 texCoord = gl_FragCoord.xy / texSize;
vec4 uv = texture(uvTexture, texCoord);
vec4 mask = texture(maskTexture, texCoord);
vec4 positionFrom = texture(positionFromTexture, texCoord);
vec4 positionTo = texture(positionToTexture, uv.xy);
vec4 backgroundColor = texture(backgroundColorTexture, uv.xy);
if (refractionMask.r <= 0) { fragColor = vec4(0); return; }
// ...
```
Pull out the uv coordinates,
mask,
background position,
foreground position,
and the background color.
If the refraction mask is turned off for this fragment, return nothing.
```c
// ...
float depth = length(positionTo.xyz - positionFrom.xyz);
float mixture = clamp(depth / depthMax, 0, 1);
vec3 shallowColor = backgroundColor.rgb;
vec3 deepColor = mix(shallowColor, tintColor.rgb, tintColor.a);
vec3 foregroundColor = mix(shallowColor, deepColor, mixture);
// ...
```
<p align="center">
<img src="https://i.imgur.com/IEFKerB.gif" alt="Refraction Depth" title="Refraction Depth">
</p>
Calculate the depth or distance between the foreground position and the background position.
At zero depth, the foreground color will be the shallow color.
At `depthMax`, the foreground color will be the deep color.
The deep color is the background color tinted with `tintColor`.
```c
// ...
fragColor = mix(vec4(0), vec4(foregroundColor, 1), uv.b);
// ...
```
Recall that the blue channel, in the refracted UV texture, is set to the visibility.
The visibility declines as the refracted ray points back at the camera.
While the visibility should always be one, it is put here for completeness.
As the visibility lessens, the fragment color will receive less and less of the foreground color.
### Source
- [main.cxx](../demonstration/src/main.cxx)
- [base.vert](../demonstration/shaders/vertex/base.vert)
- [basic.vert](../demonstration/shaders/vertex/basic.vert)
- [position.frag](../demonstration/shaders/fragment/position.frag)
- [normal.frag](../demonstration/shaders/fragment/normal.frag)
- [material-specular.frag](../demonstration/shaders/fragment/material-specular.frag)
- [screen-space-refraction.frag](../demonstration/shaders/fragment/screen-space-refraction.frag)
- [refraction.frag](../demonstration/shaders/fragment/refraction.frag)
- [base-combine.frag](../demonstration/shaders/fragment/base-combine.frag)
## Copyright
(C) 2019 David Lettier
<br>
[lettier.com](https://www.lettier.com)
[:arrow_backward:](screen-space-reflection.md)
[:arrow_double_up:](../README.md)
[:arrow_up_small:](#)
[:arrow_down_small:](#copyright)
[:arrow_forward:](foam.md)
| 3d-game-shaders-for-beginners/sections/screen-space-refraction.md/0 | {
"file_path": "3d-game-shaders-for-beginners/sections/screen-space-refraction.md",
"repo_id": "3d-game-shaders-for-beginners",
"token_count": 3981
} | 7 |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="include\common\common_utils\EnumFlags.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\ExceptionUtils.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\json.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\MedianFilter.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\OnlineStats.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\optional.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\prettyprint.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\ProsumerQueue.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\RandomGenerator.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\ScheduledExecutor.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\sincos.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\type_utils.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\Utils.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\Common.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\CommonStructs.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\DelayLine.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\EarthUtils.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\FirstOrderFilter.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\FrequencyLimiter.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\GaussianMarkov.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\GeodeticConverter.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\LogFileWriter.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\StateReporter.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\StateReporterWrapper.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\UpdatableContainer.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\UpdatableObject.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\VectorMath.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\physics\Environment.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\physics\FastPhysicsEngine.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\physics\Kinematics.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\physics\PhysicsBody.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\physics\PhysicsBodyVertex.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\physics\PhysicsEngineBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\physics\World.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\sensors\barometer\BarometerBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\sensors\barometer\BarometerSimple.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\sensors\barometer\BarometerSimpleParams.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\sensors\gps\GpsBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\sensors\gps\GpsSimple.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\sensors\gps\GpsSimpleParams.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\sensors\imu\ImuBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\sensors\imu\ImuSimple.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\sensors\imu\ImuSimpleParams.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\sensors\magnetometer\MagnetometerBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\sensors\magnetometer\MagnetometerSimple.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\sensors\magnetometer\MagnetometerSimpleParams.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\sensors\SensorBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\ctpl_stl.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\AsyncTasker.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\StrictMode.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\safety\CubeGeoFence.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\safety\IGeoFence.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\safety\ObstacleMap.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\safety\SafetyEval.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\safety\SphereGeoFence.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\sensors\SensorCollection.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\FileSystem.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\ClockBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\ClockFactory.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\Timer.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\physics\DebugPhysicsBody.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\physics\PhysicsBodyWorld.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\physics\PhysicsWorld.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\SteppableClock.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\ScalableClock.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\MinWinDefines.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\MultiRotorPhysicsBody.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\MultiRotorParams.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\MultiRotorParamsFactory.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\RotorActuator.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\RotorParams.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\interfaces\CommonStructs.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\interfaces\IAxisController.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\interfaces\IBoard.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\interfaces\IBoardClock.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\interfaces\IBoardInputPins.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\interfaces\IBoardOutputPins.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\interfaces\IBoardSensors.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\interfaces\ICommLink.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\interfaces\IController.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\interfaces\IFirmware.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\interfaces\IGoal.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\interfaces\IOffboardApi.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\interfaces\IStateEstimator.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\interfaces\IUpdatable.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\AngleLevelController.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\AngleRateController.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\CascadeController.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\ConstantOutputController.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\Firmware.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\Mixer.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\OffboardApi.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\Params.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\PassthroughController.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\PidController.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\PositionController.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\RemoteControl.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\VelocityController.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\AirSimSimpleFlightBoard.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\AirSimSimpleFlightCommLink.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\AirSimSimpleFlightCommon.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\AirSimSimpleFlightEstimator.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\car\api\CarRpcLibAdaptors.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\car\api\CarRpcLibClient.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\car\api\CarRpcLibServer.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\api\MultirotorRpcLibAdaptors.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\api\MultirotorRpcLibClient.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\api\MultirotorRpcLibServer.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\api\RpcLibAdaptorsBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\car\api\CarApiBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\api\RpcLibServerBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\AirSimSettings.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\Settings.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\Waiter.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\ImageCaptureBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\sensors\SensorFactory.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\AdaptiveController.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\interfaces\IPidIntegrator.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\StdPidIntegrator.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\firmware\RungKuttaPidIntegrator.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\EarthCelestial.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\api\WorldApiBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\api\ApiServerBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\api\VehicleSimApiBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\api\WorldSimApiBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\api\MultirotorCommon.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\CancelToken.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\WorkerThread.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\api\VehicleApiBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\api\VehicleConnectorBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\PidController.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\mavlink\MavLinkMultirotorApi.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\SimpleFlightApi.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\mavlink\Px4MultiRotorParams.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\simple_flight\SimpleFlightQuadXParams.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\api\RpcLibClientBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\api\MultirotorApiBase.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\api\ApiProvider.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\Signal.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\UniqueValueMap.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\WindowsApisCommonPre.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\WindowsApisCommonPost.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\bitmap_image.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\ColorUtils.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\mavlink\ArduCopterSoloApi.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\vehicles\multirotor\firmwares\mavlink\ArduCopterSoloParams.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\common\common_utils\SmoothingFilter.hpp">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="src\safety\ObstacleMap.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\safety\SafetyEval.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\common\common_utils\FileSystem.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\vehicles\multirotor\api\MultirotorRpcLibServer.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\vehicles\car\api\CarRpcLibClient.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\vehicles\car\api\CarRpcLibServer.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\vehicles\multirotor\api\MultirotorRpcLibClient.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\api\RpcLibClientBase.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\api\RpcLibServerBase.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\vehicles\multirotor\api\MultirotorApiBase.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project> | AirSim/AirLib/AirLib.vcxproj.filters/0 | {
"file_path": "AirSim/AirLib/AirLib.vcxproj.filters",
"repo_id": "AirSim",
"token_count": 8497
} | 8 |
/*
Adopted from SunCalc by Vladimir Agafonkin
https://github.com/mourner/suncalc
*/
#ifndef airsim_core_EarthCelestial_hpp
#define airsim_core_EarthCelestial_hpp
#include "common/Common.hpp"
#include "EarthUtils.hpp"
#include <chrono>
#include <ctime>
namespace msr
{
namespace airlib
{
class EarthCelestial
{
public:
struct CelestialGlobalCoord
{
double declination;
double rightAscension;
double distance = Utils::nan<double>();
double parallacticAngle = Utils::nan<double>();
};
struct CelestialLocalCoord
{
double azimuth;
double altitude;
double distance = Utils::nan<double>();
double parallacticAngle = Utils::nan<double>();
};
struct CelestialPhase
{
double fraction;
double phase;
double angle;
};
public:
static CelestialLocalCoord getSunCoordinates(uint64_t date, double lat, double lng)
{
double lw = Utils::degreesToRadians(-lng);
double phi = Utils::degreesToRadians(lat);
double d = toDays(date);
CelestialGlobalCoord c = getGlobalSunCoords(d);
double H = siderealTime(d, lw) - c.rightAscension;
CelestialLocalCoord coord;
coord.azimuth = Utils::radiansToDegrees(azimuth(H, phi, c.declination)) + 180.0;
coord.altitude = Utils::radiansToDegrees(altitude(H, phi, c.declination));
return coord;
}
static CelestialLocalCoord getMoonCoordinates(uint64_t date, double lat, double lng)
{
double lw = Utils::degreesToRadians(-lng);
double phi = Utils::degreesToRadians(lat);
double d = toDays(date);
CelestialGlobalCoord c = getGlobalMoonCoords(d);
double H = siderealTime(d, lw) - c.rightAscension;
// formula 14.1 of "Astronomical Algorithms" 2nd edition by Jean Meeus (Willmann-Bell, Richmond) 1998.
double pa = std::atan2(std::sin(H), std::tan(phi) * std::cos(c.declination) - std::sin(c.declination) * std::cos(H));
double h = altitude(H, phi, c.declination);
h = h + astroRefraction(h); // altitude correction for refraction
CelestialLocalCoord coord;
coord.azimuth = Utils::radiansToDegrees(azimuth(H, phi, c.declination));
coord.altitude = Utils::radiansToDegrees(h);
coord.distance = c.distance;
coord.parallacticAngle = Utils::radiansToDegrees(pa);
return coord;
};
// calculations for illumination parameters of the moon,
// based on http://idlastro.gsfc.nasa.gov/ftp/pro/astro/mphase.pro formulas and
// Chapter 48 of "Astronomical Algorithms" 2nd edition by Jean Meeus (Willmann-Bell, Richmond) 1998.
static CelestialPhase getMoonPhase(uint64_t date)
{
double d = toDays(date);
CelestialGlobalCoord s = getGlobalSunCoords(d);
CelestialGlobalCoord m = getGlobalMoonCoords(d);
double sdist = EarthUtils::DistanceFromSun / 1000; // distance from Earth to Sun in km
double phi = std::acos(std::sin(s.declination) * std::sin(m.declination) + std::cos(s.declination) * std::cos(m.declination) * std::cos(s.rightAscension - m.rightAscension));
double inc = std::atan2(sdist * std::sin(phi), m.distance - sdist * std::cos(phi));
double angle = std::atan2(std::cos(s.declination) * std::sin(s.rightAscension - m.rightAscension), std::sin(s.declination) * std::cos(m.declination) - std::cos(s.declination) * std::sin(m.declination) * std::cos(s.rightAscension - m.rightAscension));
CelestialPhase moonPhase;
moonPhase.fraction = (1 + cos(inc)) / 2;
moonPhase.phase = 0.5 + 0.5 * inc * (angle < 0 ? -1 : 1) / M_PI;
moonPhase.angle = angle;
return moonPhase;
};
private:
static double toDays(uint64_t date)
{
static constexpr double kJulianDaysOnY2000 = 2451545;
static constexpr double kDaysToHours = 60 * 60 * 24;
static constexpr double kJulianDaysOnEpoch = 2440588;
double julian_days = date / kDaysToHours - 0.5 + kJulianDaysOnEpoch;
;
return julian_days - kJulianDaysOnY2000;
}
static double rightAscension(double l, double b)
{
return std::atan2(std::sin(l) * std::cos(EarthUtils::Obliquity) - std::tan(b) * std::sin(EarthUtils::Obliquity), std::cos(l));
}
static double declination(double l, double b)
{
return std::asin(std::sin(b) * std::cos(EarthUtils::Obliquity) + std::cos(b) * std::sin(EarthUtils::Obliquity) * std::sin(l));
}
static double azimuth(double H, double phi, double declination)
{
return std::atan2(std::sin(H), std::cos(H) * std::sin(phi) - std::tan(declination) * std::cos(phi));
}
static double altitude(double H, double phi, double declination)
{
return std::asin(std::sin(phi) * std::sin(declination) + std::cos(phi) * std::cos(declination) * std::cos(H));
}
static double siderealTime(double d, double lw)
{
return Utils::degreesToRadians((280.16 + 360.9856235 * d)) - lw;
}
static double astroRefraction(double h)
{
if (h < 0) // the following formula works for positive altitudes only.
h = 0; // if h = -0.08901179 a div/0 would occur.
// formula 16.4 of "Astronomical Algorithms" 2nd edition by Jean Meeus (Willmann-Bell, Richmond) 1998.
// 1.02 / tan(h + 10.26 / (h + 5.10)) h in degrees, result in arc minutes -> converted to rad:
return 0.0002967 / std::tan(h + 0.00312536 / (h + 0.08901179));
}
static double solarMeanAnomaly(double d)
{
return Utils::degreesToRadians((357.5291 + 0.98560028 * d));
}
static double eclipticLongitude(double M)
{
double C = Utils::degreesToRadians((1.9148 * std::sin(M) + 0.02 * std::sin(2 * M) + 0.0003 * std::sin(3 * M))); // equation of center
return M + C + EarthUtils::Perihelion + M_PI;
}
static CelestialGlobalCoord getGlobalSunCoords(double d)
{
double M = solarMeanAnomaly(d);
double L = eclipticLongitude(M);
CelestialGlobalCoord sunCoords;
sunCoords.declination = declination(L, 0);
sunCoords.rightAscension = rightAscension(L, 0);
return sunCoords;
}
// moon calculations, based on http://aa.quae.nl/en/reken/hemelpositie.html formulas
static CelestialGlobalCoord getGlobalMoonCoords(double d)
{
// geocentric ecliptic coordinates of the moon
double L = Utils::degreesToRadians((218.316 + 13.176396 * d)); // ecliptic longitude
double M = Utils::degreesToRadians((134.963 + 13.064993 * d)); // mean anomaly
double F = Utils::degreesToRadians((93.272 + 13.229350 * d)); // mean distance
double l = L + Utils::degreesToRadians(6.289 * std::sin(M)); // longitude
double b = Utils::degreesToRadians(5.128 * std::sin(F)); // latitude
double dt = 385001 - 20905 * std::cos(M); // distance to the moon in km
CelestialGlobalCoord moonCoords;
moonCoords.rightAscension = rightAscension(l, b);
moonCoords.declination = declination(l, b);
moonCoords.distance = dt;
return moonCoords;
}
};
}
} //namespace
#endif
| AirSim/AirLib/include/common/EarthCelestial.hpp/0 | {
"file_path": "AirSim/AirLib/include/common/EarthCelestial.hpp",
"repo_id": "AirSim",
"token_count": 3589
} | 9 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef air_VectorMath_hpp
#define air_VectorMath_hpp
#include <cmath>
#include "common/common_utils/Utils.hpp"
#include "common_utils/RandomGenerator.hpp"
STRICT_MODE_OFF
//if not using unaligned types then disable vectorization to avoid alignment issues all over the places
//#define EIGEN_DONT_VECTORIZE
#include "Eigen/Dense"
STRICT_MODE_ON
namespace msr
{
namespace airlib
{
template <class Vector3T, class QuaternionT, class RealT>
class VectorMathT
{
public:
//IMPORTANT: make sure fixed size vectorization types have no alignment assumption
//https://eigen.tuxfamily.org/dox/group__TopicUnalignedArrayAssert.html
typedef Eigen::Matrix<float, 1, 1> Vector1f;
typedef Eigen::Matrix<double, 1, 1> Vector1d;
typedef Eigen::Matrix<float, 2, 1, Eigen::DontAlign> Vector2f;
typedef Eigen::Matrix<double, 4, 1, Eigen::DontAlign> Vector2d;
typedef Eigen::Vector3f Vector3f;
typedef Eigen::Vector3d Vector3d;
typedef Eigen::Array3f Array3f;
typedef Eigen::Array3d Array3d;
typedef Eigen::Quaternion<float, Eigen::DontAlign> Quaternionf;
typedef Eigen::Quaternion<double, Eigen::DontAlign> Quaterniond;
typedef Eigen::Matrix<double, 3, 3> Matrix3x3d;
typedef Eigen::Matrix<float, 3, 3> Matrix3x3f;
typedef Eigen::AngleAxisd AngleAxisd;
typedef Eigen::AngleAxisf AngleAxisf;
typedef common_utils::Utils Utils;
//use different seeds for each component
//TODO: below we are using double instead of RealT because of VC++2017 bug in random implementation
typedef common_utils::RandomGenerator<RealT, std::normal_distribution<double>, 1> RandomGeneratorGausianXT;
typedef common_utils::RandomGenerator<RealT, std::normal_distribution<double>, 2> RandomGeneratorGausianYT;
typedef common_utils::RandomGenerator<RealT, std::normal_distribution<double>, 3> RandomGeneratorGausianZT;
typedef common_utils::RandomGenerator<RealT, std::uniform_real_distribution<RealT>, 1> RandomGeneratorXT;
typedef common_utils::RandomGenerator<RealT, std::uniform_real_distribution<RealT>, 2> RandomGeneratorYT;
typedef common_utils::RandomGenerator<RealT, std::uniform_real_distribution<RealT>, 3> RandomGeneratorZT;
struct Pose
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
Vector3T position = Vector3T::Zero();
QuaternionT orientation = QuaternionT(1, 0, 0, 0);
Pose()
{
}
Pose(const Vector3T& position_val, const QuaternionT& orientation_val)
{
orientation = orientation_val;
position = position_val;
}
friend Pose operator-(const Pose& lhs, const Pose& rhs)
{
return VectorMathT::subtract(lhs, rhs);
}
friend Pose operator+(const Pose& lhs, const Pose& rhs)
{
return VectorMathT::add(lhs, rhs);
}
friend bool operator==(const Pose& lhs, const Pose& rhs)
{
return lhs.position == rhs.position && lhs.orientation.coeffs() == rhs.orientation.coeffs();
}
friend bool operator!=(const Pose& lhs, const Pose& rhs)
{
return !(lhs == rhs);
;
}
static Pose nanPose()
{
static const Pose nan_pose(VectorMathT::nanVector(), VectorMathT::nanQuaternion());
return nan_pose;
}
static Pose zero()
{
static const Pose zero_pose(Vector3T::Zero(), QuaternionT(1, 0, 0, 0));
return zero_pose;
}
};
struct Transform
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
Vector3T translation;
QuaternionT rotation;
};
class RandomVectorT
{
public:
RandomVectorT()
{
}
RandomVectorT(RealT min_val, RealT max_val)
: rx_(min_val, max_val), ry_(min_val, max_val), rz_(min_val, max_val)
{
}
RandomVectorT(const Vector3T& min_val, const Vector3T& max_val)
: rx_(min_val.x(), max_val.x()), ry_(min_val.y(), max_val.y()), rz_(min_val.z(), max_val.z())
{
}
void reset()
{
rx_.reset();
ry_.reset();
rz_.reset();
}
Vector3T next()
{
return Vector3T(rx_.next(), ry_.next(), rz_.next());
}
private:
RandomGeneratorXT rx_;
RandomGeneratorYT ry_;
RandomGeneratorZT rz_;
};
class RandomVectorGaussianT
{
public:
RandomVectorGaussianT()
{
}
RandomVectorGaussianT(RealT mean, RealT stddev)
: rx_(mean, stddev), ry_(mean, stddev), rz_(mean, stddev)
{
}
RandomVectorGaussianT(const Vector3T& mean, const Vector3T& stddev)
: rx_(mean.x(), stddev.x()), ry_(mean.y(), stddev.y()), rz_(mean.z(), stddev.z())
{
}
void reset()
{
rx_.reset();
ry_.reset();
rz_.reset();
}
Vector3T next()
{
return Vector3T(rx_.next(), ry_.next(), rz_.next());
}
private:
RandomGeneratorGausianXT rx_;
RandomGeneratorGausianYT ry_;
RandomGeneratorGausianZT rz_;
};
public:
static float magnitude(const Vector2f& v)
{
return v.norm();
}
static RealT magnitude(const Vector3T& v)
{
return v.norm();
}
static Vector3T rotateVector(const Vector3T& v, const QuaternionT& q, bool assume_unit_quat)
{
unused(assume_unit_quat); // stop warning: unused parameter.
//More performant method is at http://gamedev.stackexchange.com/a/50545/20758
//QuaternionT vq(0, v.x(), v.y(), v.z());
//QuaternionT qi = assume_unit_quat ? q.conjugate() : q.inverse();
//return (q * vq * qi).vec();
return q._transformVector(v);
}
static Vector3T rotateVectorReverse(const Vector3T& v, const QuaternionT& q, bool assume_unit_quat)
{
//QuaternionT vq(0, v.x(), v.y(), v.z());
//QuaternionT qi = assume_unit_quat ? q.conjugate() : q.inverse();
//return (qi * vq * q).vec();
if (!assume_unit_quat)
return q.inverse()._transformVector(v);
else
return q.conjugate()._transformVector(v);
}
static QuaternionT rotateQuaternion(const QuaternionT& q, const QuaternionT& ref, bool assume_unit_quat)
{
if (assume_unit_quat) {
// conjugate and inverse are equivalent for unit-length quaternions,
// but the conjugate is less expensive to compute
QuaternionT ref_n = ref;
QuaternionT ref_n_i = ref.conjugate();
return ref_n * q * ref_n_i;
}
else {
QuaternionT ref_n = ref.normalized();
QuaternionT ref_n_i = ref.inverse();
return ref_n * q * ref_n_i;
}
}
static QuaternionT rotateQuaternionReverse(const QuaternionT& q, const QuaternionT& ref, bool assume_unit_quat)
{
if (assume_unit_quat) {
QuaternionT ref_n = ref;
QuaternionT ref_n_i = ref.conjugate();
return ref_n_i * q * ref_n;
}
else {
QuaternionT ref_n = ref.normalized();
QuaternionT ref_n_i = ref.inverse();
return ref_n_i * q * ref_n;
}
}
static Vector3T transformToBodyFrame(const Vector3T& v_world, const QuaternionT& q_world, bool assume_unit_quat = true)
{
return rotateVectorReverse(v_world, q_world, assume_unit_quat);
}
static Vector3T transformToBodyFrame(const Vector3T& v_world, const Pose& body_world, bool assume_unit_quat = true)
{
//translate
Vector3T translated = v_world - body_world.position;
//rotate
return transformToBodyFrame(translated, body_world.orientation, assume_unit_quat);
}
static Pose transformToBodyFrame(const Pose& pose_world, const Pose& body_world, bool assume_unit_quat = true)
{
//translate
Vector3T translated = pose_world.position - body_world.position;
//rotate vector
Vector3T v_body = transformToBodyFrame(translated, body_world.orientation, assume_unit_quat);
//rotate orientation
QuaternionT q_body = rotateQuaternionReverse(pose_world.orientation, body_world.orientation, assume_unit_quat);
return Pose(v_body, q_body);
}
static Vector3T transformToWorldFrame(const Vector3T& v_body, const QuaternionT& q_world, bool assume_unit_quat = true)
{
return rotateVector(v_body, q_world, assume_unit_quat);
}
static Vector3T transformToWorldFrame(const Vector3T& v_body, const Pose& body_world, bool assume_unit_quat = true)
{
//rotate
Vector3T v_world = transformToWorldFrame(v_body, body_world.orientation, assume_unit_quat);
//translate
return v_world + body_world.position;
}
//transform pose specified in body frame to world frame. The body frame in world coordinate is at body_world
static Pose transformToWorldFrame(const Pose& pose_body, const Pose& body_world, bool assume_unit_quat = true)
{
//rotate position
Vector3T v_world = transformToWorldFrame(pose_body.position, body_world.orientation, assume_unit_quat);
//rotate orientation
QuaternionT q_world = rotateQuaternion(pose_body.orientation, body_world.orientation, assume_unit_quat);
//translate
return Pose(v_world + body_world.position, q_world);
}
static QuaternionT negate(const QuaternionT& q)
{
//from Gazebo implementation
return QuaternionT(-q.w(), -q.x(), -q.y(), -q.z());
}
static Vector3T getRandomVectorFromGaussian(RealT stddev = 1, RealT mean = 0)
{
return Vector3T(
Utils::getRandomFromGaussian(stddev, mean),
Utils::getRandomFromGaussian(stddev, mean),
Utils::getRandomFromGaussian(stddev, mean));
}
static QuaternionT flipZAxis(const QuaternionT& q)
{
//quaternion formula comes from http://stackoverflow.com/a/40334755/207661
return QuaternionT(q.w(), -q.x(), -q.y(), q.z());
}
static void toEulerianAngle(const QuaternionT& q, RealT& pitch, RealT& roll, RealT& yaw)
{
//z-y-x rotation convention (Tait-Bryan angles)
//Apply yaw, pitch and roll in order to front vector (+X)
//http://www.sedris.org/wg8home/Documents/WG80485.pdf
//http://www.ctralie.com/Teaching/COMPSCI290/Materials/EulerAnglesViz/
RealT ysqr = q.y() * q.y();
// roll (x-axis rotation)
RealT t0 = +2.0f * (q.w() * q.x() + q.y() * q.z());
RealT t1 = +1.0f - 2.0f * (q.x() * q.x() + ysqr);
roll = std::atan2(t0, t1);
// pitch (y-axis rotation)
RealT t2 = +2.0f * (q.w() * q.y() - q.z() * q.x());
t2 = ((t2 > 1.0f) ? 1.0f : t2);
t2 = ((t2 < -1.0f) ? -1.0f : t2);
pitch = std::asin(t2);
// yaw (z-axis rotation)
RealT t3 = +2.0f * (q.w() * q.z() + q.x() * q.y());
RealT t4 = +1.0f - 2.0f * (ysqr + q.z() * q.z());
yaw = std::atan2(t3, t4);
}
static RealT angleBetween(const Vector3T& v1, const Vector3T& v2, bool assume_normalized = false)
{
Vector3T v1n = v1;
Vector3T v2n = v2;
if (!assume_normalized) {
v1n.normalize();
v2n.normalize();
}
return std::acos(v1n.dot(v2n));
}
static Vector3T toAngularVelocity(const QuaternionT& start, const QuaternionT& end, RealT dt)
{
if (dt == 0)
return Vector3T(0, 0, 0);
RealT p_s, r_s, y_s;
toEulerianAngle(start, p_s, r_s, y_s);
RealT p_e, r_e, y_e;
toEulerianAngle(end, p_e, r_e, y_e);
RealT p_rate = normalizeAngle(p_e - p_s, (RealT)(2 * M_PI)) / dt;
RealT r_rate = normalizeAngle(r_e - r_s, (RealT)(2 * M_PI)) / dt;
RealT y_rate = normalizeAngle(y_e - y_s, (RealT)(2 * M_PI)) / dt;
//TODO: optimize below
//Sec 1.3, https://ocw.mit.edu/courses/mechanical-engineering/2-154-maneuvering-and-control-of-surface-and-underwater-vehicles-13-49-fall-2004/lecture-notes/lec1.pdf
RealT wx = r_rate + 0 - y_rate * sinf(p_e);
RealT wy = 0 + p_rate * cosf(r_e) + y_rate * sinf(r_e) * cosf(p_e);
RealT wz = 0 - p_rate * sinf(r_e) + y_rate * cosf(r_e) * cosf(p_e);
return Vector3T(wx, wy, wz);
}
static Vector3T nanVector()
{
static const Vector3T val(std::numeric_limits<RealT>::quiet_NaN(), std::numeric_limits<RealT>::quiet_NaN(), std::numeric_limits<RealT>::quiet_NaN());
return val;
}
static QuaternionT nanQuaternion()
{
return QuaternionT(std::numeric_limits<RealT>::quiet_NaN(), std::numeric_limits<RealT>::quiet_NaN(), std::numeric_limits<RealT>::quiet_NaN(), std::numeric_limits<RealT>::quiet_NaN());
}
static bool hasNan(const Vector3T& v)
{
return std::isnan(v.x()) || std::isnan(v.y()) || std::isnan(v.z());
}
static bool hasNan(const QuaternionT& q)
{
return std::isnan(q.x()) || std::isnan(q.y()) || std::isnan(q.z()) || std::isnan(q.w());
}
static bool hasNan(const Pose& p)
{
return hasNan(p.position) || hasNan(p.orientation);
}
static QuaternionT addAngularVelocity(const QuaternionT& orientation, const Vector3T& angular_vel, RealT dt)
{
QuaternionT dq_unit = QuaternionT(0, angular_vel.x() * 0.5f, angular_vel.y() * 0.5f, angular_vel.z() * 0.5f) * orientation;
QuaternionT net_q(dq_unit.coeffs() * dt + orientation.coeffs());
return net_q.normalized();
}
//all angles in radians
static QuaternionT toQuaternion(RealT pitch, RealT roll, RealT yaw)
{
//z-y-x rotation convention (Tait-Bryan angles)
//http://www.sedris.org/wg8home/Documents/WG80485.pdf
QuaternionT q;
RealT t0 = std::cos(yaw * 0.5f);
RealT t1 = std::sin(yaw * 0.5f);
RealT t2 = std::cos(roll * 0.5f);
RealT t3 = std::sin(roll * 0.5f);
RealT t4 = std::cos(pitch * 0.5f);
RealT t5 = std::sin(pitch * 0.5f);
q.w() = t0 * t2 * t4 + t1 * t3 * t5;
q.x() = t0 * t3 * t4 - t1 * t2 * t5;
q.y() = t0 * t2 * t5 + t1 * t3 * t4;
q.z() = t1 * t2 * t4 - t0 * t3 * t5;
return q;
}
//from https://github.com/arpg/Gazebo/blob/master/gazebo/math/Pose.cc
static Vector3T coordPositionSubtract(const Pose& lhs, const Pose& rhs)
{
QuaternionT tmp(0,
lhs.position.x() - rhs.position.x(),
lhs.position.y() - rhs.position.y(),
lhs.position.z() - rhs.position.z());
tmp = rhs.orientation.inverse() * (tmp * rhs.orientation);
return tmp.vec();
}
static QuaternionT coordOrientationSubtract(const QuaternionT& lhs, const QuaternionT& rhs)
{
QuaternionT result(rhs.inverse() * lhs);
result.normalize();
return result;
}
static Vector3T coordPositionAdd(const Pose& lhs, const Pose& rhs)
{
QuaternionT tmp(0, lhs.position.x(), lhs.position.y(), lhs.position.z());
tmp = rhs.orientation * (tmp * rhs.orientation.inverse());
return tmp.vec() + rhs.position;
}
static QuaternionT coordOrientationAdd(const QuaternionT& lhs, const QuaternionT& rhs)
{
QuaternionT result(rhs * lhs);
result.normalize();
return result;
}
static Pose subtract(const Pose& lhs, const Pose& rhs)
{
return Pose(coordPositionSubtract(lhs, rhs), coordOrientationSubtract(lhs.orientation, rhs.orientation));
}
static Pose add(const Pose& lhs, const Pose& rhs)
{
return Pose(coordPositionAdd(lhs, rhs), coordOrientationAdd(lhs.orientation, rhs.orientation));
}
static std::string toString(const Vector3T& vect, const char* prefix = nullptr)
{
if (prefix)
return Utils::stringf("%s[%f, %f, %f]", prefix, vect[0], vect[1], vect[2]);
else
return Utils::stringf("[%f, %f, %f]", vect[0], vect[1], vect[2]);
}
static std::string toString(const QuaternionT& quaternion, bool add_eularian = false)
{
if (!add_eularian)
return Utils::stringf("[%f, %f, %f, %f]", quaternion.w(), quaternion.x(), quaternion.y(), quaternion.z());
else {
RealT pitch, roll, yaw;
toEulerianAngle(quaternion, pitch, roll, yaw);
return Utils::stringf("[%f, %f, %f, %f]-[%f, %f, %f]",
quaternion.w(),
quaternion.x(),
quaternion.y(),
quaternion.z(),
pitch,
roll,
yaw);
}
}
static std::string toString(const Vector2f& vect)
{
return Utils::stringf("[%f, %f]", vect[0], vect[1]);
}
static RealT getYaw(const QuaternionT& q)
{
return std::atan2(2.0f * (q.z() * q.w() + q.x() * q.y()), -1.0f + 2.0f * (q.w() * q.w() + q.x() * q.x()));
}
static RealT getPitch(const QuaternionT& q)
{
return std::asin(2.0f * (q.y() * q.w() - q.z() * q.x()));
}
static RealT getRoll(const QuaternionT& q)
{
return std::atan2(2.0f * (q.z() * q.y() + q.w() * q.x()), 1.0f - 2.0f * (q.x() * q.x() + q.y() * q.y()));
}
static RealT normalizeAngle(RealT angle, RealT max_angle = static_cast<RealT>(360))
{
angle = static_cast<RealT>(std::fmod(angle, max_angle));
if (angle > max_angle / 2)
return angle - max_angle;
else if (angle < -max_angle / 2)
return angle + max_angle;
else
return angle;
}
// assumes that angles are in 0-360 range
static bool isAngleBetweenAngles(RealT angle, RealT start_angle, RealT end_angle)
{
if (start_angle < end_angle) {
return (start_angle <= angle && angle <= end_angle);
}
else
return (start_angle <= angle || angle <= end_angle);
}
/**
* \brief Extracts the yaw part from a quaternion, using RPY / euler (z-y'-z'') angles.
* RPY rotates about the fixed axes in the order x-y-z,
* which is the same as euler angles in the order z-y'-x''.
*/
static RealT yawFromQuaternion(const QuaternionT& q)
{
return atan2(2.0 * (q.w() * q.z() + q.x() * q.y()),
1.0 - 2.0 * (q.y() * q.y() + q.z() * q.z()));
}
static QuaternionT quaternionFromYaw(RealT yaw)
{
return QuaternionT(Eigen::AngleAxis<RealT>(yaw, Vector3T::UnitZ()));
}
static QuaternionT toQuaternion(const Vector3T& axis, RealT angle)
{
//Alternative:
//auto s = std::sin(angle / 2);
//auto u = axis.normalized();
//return Quaternionr(std::cos(angle / 2), u.x() * s, u.y() * s, u.z() * s);
return QuaternionT(Eigen::AngleAxis<RealT>(angle, axis));
}
//linear interpolate
static QuaternionT lerp(const QuaternionT& from, const QuaternionT& to, RealT alpha)
{
QuaternionT r;
RealT n_alpha = 1 - alpha;
r.x() = n_alpha * from.x() + alpha * to.x();
r.y() = n_alpha * from.y() + alpha * to.y();
r.z() = n_alpha * from.z() + alpha * to.z();
r.w() = n_alpha * from.w() + alpha * to.w();
return r.normalized();
}
//spherical lerp
static QuaternionT slerp(const QuaternionT& from, const QuaternionT& to, RealT alpha)
{
/*
//below is manual way to do this
RealT n_alpha = 1 - alpha;
RealT theta = acos(from.x()*to.x() + from.y()*to.y() + from.z()*to.z() + from.w()*to.w());
//Check for theta > 0 to avoid division by 0.
if (theta > std::numeric_limits<RealT>::epsilon())
{
RealT sn = sin(theta);
RealT Wa = sin(n_alpha*theta) / sn;
RealT Wb = sin(alpha*theta) / sn;
QuaternionT r;
r.x() = Wa * from.x() + Wb * to.x();
r.y() = Wa * from.y() + Wb * to.y();
r.z() = Wa * from.z() + Wb * to.z();
r.w() = Wa * from.w() + Wb * to.w();
return r.normalized();
}
//Theta is almost 0. Return "to" quaternion.
//Alternatively, could also do lerp.
else {
return to.normalized();
}
*/
return from.slerp(alpha, to);
}
static Vector3T lerp(const Vector3T& from, const Vector3T& to, RealT alpha)
{
return (from + alpha * (to - from));
}
static Vector3T slerp(const Vector3T& from, const Vector3T& to, RealT alpha, bool assume_normalized)
{
Vector3T from_ortho, to_ortho;
RealT dot;
getPlaneOrthoVectors(from, to, assume_normalized, from_ortho, to_ortho, dot);
RealT theta = std::acos(dot) * alpha;
return from_ortho * std::cos(theta) + to_ortho * std::sin(theta);
}
static void getPlaneOrthoVectors(const Vector3T& from, const Vector3T& to, bool assume_normalized,
Vector3T& from_ortho, Vector3T& to_ortho, RealT& dot)
{
unused(from);
Vector3T to_n = to;
if (!assume_normalized) {
from_ortho.normalize();
to_n.normalize();
}
dot = from_ortho.dot(to_n);
dot = Utils::clip<RealT>(dot, -1, 1);
to_ortho = (to_n - from_ortho * dot).normalized();
}
static Vector3T slerpByAngle(const Vector3T& from, const Vector3T& to, RealT angle, bool assume_normalized = false)
{
Vector3T from_ortho, to_ortho;
RealT dot;
getPlaneOrthoVectors(from, to, assume_normalized, from_ortho, to_ortho, dot);
return from_ortho * std::cos(angle) + to_ortho * std::sin(angle);
}
static Vector3T nlerp(const Vector3T& from, const Vector3T& to, float alpha)
{
return lerp(from, to, alpha).normalized();
}
//assuming you are looking at front() vector, what rotation you need to look at destPoint?
static QuaternionT lookAt(const Vector3T& sourcePoint, const Vector3T& destPoint)
{
/*
//below is manual way to do this without Eigen
Vector3T toVector = (destPoint - sourcePoint);
toVector.normalize(); //this is important!
RealT dot = VectorMathT::front().dot(toVector);
RealT ang = std::acos(dot);
Vector3T axis = VectorMathT::front().cross(toVector);
if (axis == Vector3T::Zero())
axis = VectorMathT::up();
else
axis = axis.normalized();
return VectorMathT::toQuaternion(axis, ang);
*/
return QuaternionT::FromTwoVectors(VectorMathT::front(), destPoint - sourcePoint);
}
//what rotation we need to rotate "" vector to "to" vector (rotation is around intersection of two vectors)
static QuaternionT toQuaternion(const Vector3T& from, const Vector3T& to)
{
return QuaternionT::FromTwoVectors(from, to);
}
static const Vector3T front()
{
static Vector3T v(1, 0, 0);
return v;
}
static const Vector3T back()
{
static Vector3T v(-1, 0, 0);
return v;
}
static const Vector3T down()
{
static Vector3T v(0, 0, 1);
return v;
}
static const Vector3T up()
{
static Vector3T v(0, 0, -1);
return v;
}
static const Vector3T right()
{
static Vector3T v(0, 1, 0);
return v;
}
static const Vector3T left()
{
static Vector3T v(0, -1, 0);
return v;
}
};
typedef VectorMathT<Eigen::Vector3d, Eigen::Quaternion<double, Eigen::DontAlign>, double> VectorMathd;
typedef VectorMathT<Eigen::Vector3f, Eigen::Quaternion<float, Eigen::DontAlign>, float> VectorMathf;
}
} //namespace
#endif
| AirSim/AirLib/include/common/VectorMath.hpp/0 | {
"file_path": "AirSim/AirLib/include/common/VectorMath.hpp",
"repo_id": "AirSim",
"token_count": 13566
} | 10 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef airsim_core_FastPhysicsEngine_hpp
#define airsim_core_FastPhysicsEngine_hpp
#include "common/Common.hpp"
#include "physics/PhysicsEngineBase.hpp"
#include <iostream>
#include <sstream>
#include <fstream>
#include <memory>
#include "common/CommonStructs.hpp"
#include "common/SteppableClock.hpp"
#include <cinttypes>
namespace msr
{
namespace airlib
{
class FastPhysicsEngine : public PhysicsEngineBase
{
public:
FastPhysicsEngine(bool enable_ground_lock = true, Vector3r wind = Vector3r::Zero())
: enable_ground_lock_(enable_ground_lock), wind_(wind)
{
setName("FastPhysicsEngine");
}
//*** Start: UpdatableState implementation ***//
virtual void resetImplementation() override
{
for (PhysicsBody* body_ptr : *this) {
initPhysicsBody(body_ptr);
}
}
virtual void insert(PhysicsBody* body_ptr) override
{
PhysicsEngineBase::insert(body_ptr);
initPhysicsBody(body_ptr);
}
virtual void update() override
{
PhysicsEngineBase::update();
for (PhysicsBody* body_ptr : *this) {
updatePhysics(*body_ptr);
}
}
virtual void reportState(StateReporter& reporter) override
{
for (PhysicsBody* body_ptr : *this) {
reporter.writeValue("Phys", debug_string_.str());
reporter.writeValue("Is Grounded", body_ptr->isGrounded());
reporter.writeValue("Force (world)", body_ptr->getWrench().force);
reporter.writeValue("Torque (body)", body_ptr->getWrench().torque);
}
//call base
UpdatableObject::reportState(reporter);
}
//*** End: UpdatableState implementation ***//
// Set Wind, for API and Settings implementation
void setWind(const Vector3r& wind) override
{
wind_ = wind;
}
private:
void initPhysicsBody(PhysicsBody* body_ptr)
{
body_ptr->last_kinematics_time = clock()->nowNanos();
}
void updatePhysics(PhysicsBody& body)
{
TTimeDelta dt = clock()->updateSince(body.last_kinematics_time);
body.lock();
//get current kinematics state of the body - this state existed since last dt seconds
const Kinematics::State& current = body.getKinematics();
Kinematics::State next;
Wrench next_wrench;
//first compute the response as if there was no collision
//this is necessary to take in to account forces and torques generated by body
getNextKinematicsNoCollision(dt, body, current, next, next_wrench, wind_);
//if there is collision, see if we need collision response
const CollisionInfo collision_info = body.getCollisionInfo();
CollisionResponse& collision_response = body.getCollisionResponseInfo();
//if collision was already responded then do not respond to it until we get updated information
if (body.isGrounded() || (collision_info.has_collided && collision_response.collision_time_stamp != collision_info.time_stamp)) {
bool is_collision_response = getNextKinematicsOnCollision(dt, collision_info, body, current, next, next_wrench, enable_ground_lock_);
updateCollisionResponseInfo(collision_info, next, is_collision_response, collision_response);
//throttledLogOutput("*** has collision", 0.1);
}
//else throttledLogOutput("*** no collision", 0.1);
//Utils::log(Utils::stringf("T-VEL %s %" PRIu64 ": ",
// VectorMath::toString(next.twist.linear).c_str(), clock()->getStepCount()));
body.setWrench(next_wrench);
body.updateKinematics(next);
body.unlock();
//TODO: this is now being done in PawnSimApi::update. We need to re-think this sequence
//with below commented out - Arducopter GPS may not work.
//body.getEnvironment().setPosition(next.pose.position);
//body.getEnvironment().update();
}
static void updateCollisionResponseInfo(const CollisionInfo& collision_info, const Kinematics::State& next,
bool is_collision_response, CollisionResponse& collision_response)
{
collision_response.collision_time_stamp = collision_info.time_stamp;
++collision_response.collision_count_raw;
//increment counter if we didn't collided with high velocity (like resting on ground)
if (is_collision_response && next.twist.linear.squaredNorm() > kRestingVelocityMax * kRestingVelocityMax)
++collision_response.collision_count_non_resting;
}
//return value indicates if collision response was generated
static bool getNextKinematicsOnCollision(TTimeDelta dt, const CollisionInfo& collision_info, PhysicsBody& body,
const Kinematics::State& current, Kinematics::State& next, Wrench& next_wrench, bool enable_ground_lock)
{
/************************* Collision response ************************/
const real_T dt_real = static_cast<real_T>(dt);
//are we going away from collision? if so then keep using computed next state
if (collision_info.normal.dot(next.twist.linear) >= 0.0f)
return false;
/********** Core collision response ***********/
//get avg current velocity
const Vector3r vcur_avg = current.twist.linear + current.accelerations.linear * dt_real;
//get average angular velocity
const Vector3r angular_avg = current.twist.angular + current.accelerations.angular * dt_real;
//contact point vector
Vector3r r = collision_info.impact_point - collision_info.position;
//see if impact is straight at body's surface (assuming its box)
const Vector3r normal_body = VectorMath::transformToBodyFrame(collision_info.normal, current.pose.orientation);
const bool is_ground_normal = Utils::isApproximatelyEqual(std::abs(normal_body.z()), 1.0f, kAxisTolerance);
bool ground_collision = false;
const float z_vel = vcur_avg.z();
const bool is_landing = z_vel > std::abs(vcur_avg.x()) && z_vel > std::abs(vcur_avg.y());
real_T restitution = body.getRestitution();
real_T friction = body.getFriction();
if (is_ground_normal && is_landing
// So normal_body is the collision normal translated into body coords, why does an x==1 or y==1
// mean we are coliding with the ground???
// || Utils::isApproximatelyEqual(std::abs(normal_body.x()), 1.0f, kAxisTolerance)
// || Utils::isApproximatelyEqual(std::abs(normal_body.y()), 1.0f, kAxisTolerance)
) {
// looks like we are coliding with the ground. We don't want the ground to be so bouncy
// so we reduce the coefficient of restitution. 0 means no bounce.
// TODO: it would be better if we did this based on the material we are landing on.
// e.g. grass should be inelastic, but a hard surface like the road should be more bouncy.
restitution = 0;
// crank up friction with the ground so it doesn't try and slide across the ground
// again, this should depend on the type of surface we are landing on.
friction = 1;
//we have collided with ground straight on, we will fix orientation later
ground_collision = is_ground_normal;
}
//velocity at contact point
const Vector3r vcur_avg_body = VectorMath::transformToBodyFrame(vcur_avg, current.pose.orientation);
const Vector3r contact_vel_body = vcur_avg_body + angular_avg.cross(r);
/*
GafferOnGames - Collision response with columb friction
http://gafferongames.com/virtual-go/collision-response-and-coulomb-friction/
Assuming collision is with static fixed body,
impulse magnitude = j = -(1 + R)V.N / (1/m + (I'(r X N) X r).N)
Physics Part 3, Collision Response, Chris Hecker, eq 4(a)
http://chrishecker.com/images/e/e7/Gdmphys3.pdf
V(t+1) = V(t) + j*N / m
*/
const real_T impulse_mag_denom = 1.0f / body.getMass() +
(body.getInertiaInv() * r.cross(normal_body))
.cross(r)
.dot(normal_body);
const real_T impulse_mag = -contact_vel_body.dot(normal_body) * (1 + restitution) / impulse_mag_denom;
next.twist.linear = vcur_avg + collision_info.normal * (impulse_mag / body.getMass());
next.twist.angular = angular_avg + r.cross(normal_body) * impulse_mag;
//above would modify component in direction of normal
//we will use friction to modify component in direction of tangent
const Vector3r contact_tang_body = contact_vel_body - normal_body * normal_body.dot(contact_vel_body);
const Vector3r contact_tang_unit_body = contact_tang_body.normalized();
const real_T friction_mag_denom = 1.0f / body.getMass() +
(body.getInertiaInv() * r.cross(contact_tang_unit_body))
.cross(r)
.dot(contact_tang_unit_body);
const real_T friction_mag = -contact_tang_body.norm() * friction / friction_mag_denom;
const Vector3r contact_tang_unit = VectorMath::transformToWorldFrame(contact_tang_unit_body, current.pose.orientation);
next.twist.linear += contact_tang_unit * friction_mag;
next.twist.angular += r.cross(contact_tang_unit_body) * (friction_mag / body.getMass());
//TODO: implement better rolling friction
next.twist.angular *= 0.9f;
// there is no acceleration during collision response, this is a hack, but without it the acceleration cancels
// the computed impulse response too much and stops the vehicle from bouncing off the collided object.
next.accelerations.linear = Vector3r::Zero();
next.accelerations.angular = Vector3r::Zero();
next.pose = current.pose;
if (enable_ground_lock && ground_collision) {
float pitch, roll, yaw;
VectorMath::toEulerianAngle(next.pose.orientation, pitch, roll, yaw);
pitch = roll = 0;
next.pose.orientation = VectorMath::toQuaternion(pitch, roll, yaw);
//there is a lot of random angular velocity when vehicle is on the ground
next.twist.angular = Vector3r::Zero();
// also eliminate any linear velocity due to twist - since we are sitting on the ground there shouldn't be any.
next.twist.linear = Vector3r::Zero();
next.pose.position = collision_info.position;
body.setGrounded(true);
// but we do want to "feel" the ground when we hit it (we should see a small z-acc bump)
// equal and opposite our downward velocity.
next.accelerations.linear = -0.5f * body.getMass() * vcur_avg;
//throttledLogOutput("*** Triggering ground lock", 0.1);
}
else {
//else keep the orientation
next.pose.position = collision_info.position + (collision_info.normal * collision_info.penetration_depth) + next.twist.linear * (dt_real * kCollisionResponseCycles);
}
next_wrench = Wrench::zero();
//Utils::log(Utils::stringf("*** C-VEL %s: ", VectorMath::toString(next.twist.linear).c_str()));
return true;
}
void throttledLogOutput(const std::string& msg, double seconds)
{
TTimeDelta dt = clock()->elapsedSince(last_message_time);
const real_T dt_real = static_cast<real_T>(dt);
if (dt_real > seconds) {
Utils::log(msg);
last_message_time = clock()->nowNanos();
}
}
static Wrench getDragWrench(const PhysicsBody& body, const Quaternionr& orientation,
const Vector3r& linear_vel, const Vector3r& angular_vel_body, const Vector3r& wind_world)
{
//add linear drag due to velocity we had since last dt seconds + wind
//drag vector magnitude is proportional to v^2, direction opposite of velocity
//total drag is b*v + c*v*v but we ignore the first term as b << c (pg 44, Classical Mechanics, John Taylor)
//To find the drag force, we find the magnitude in the body frame and unit vector direction in world frame
//http://physics.stackexchange.com/questions/304742/angular-drag-on-body
//similarly calculate angular drag
//note that angular velocity, acceleration, torque are already in body frame
Wrench wrench = Wrench::zero();
const real_T air_density = body.getEnvironment().getState().air_density;
// Use relative velocity of the body wrt wind
const Vector3r relative_vel = linear_vel - wind_world;
const Vector3r linear_vel_body = VectorMath::transformToBodyFrame(relative_vel, orientation);
for (uint vi = 0; vi < body.dragVertexCount(); ++vi) {
const auto& vertex = body.getDragVertex(vi);
const Vector3r vel_vertex = linear_vel_body + angular_vel_body.cross(vertex.getPosition());
const real_T vel_comp = vertex.getNormal().dot(vel_vertex);
//if vel_comp is -ve then we cull the face. If velocity too low then drag is not generated
if (vel_comp > kDragMinVelocity) {
const Vector3r drag_force = vertex.getNormal() * (-vertex.getDragFactor() * air_density * vel_comp * vel_comp);
const Vector3r drag_torque = vertex.getPosition().cross(drag_force);
wrench.force += drag_force;
wrench.torque += drag_torque;
}
}
//convert force to world frame, leave torque to local frame
wrench.force = VectorMath::transformToWorldFrame(wrench.force, orientation);
return wrench;
}
static Wrench getBodyWrench(const PhysicsBody& body, const Quaternionr& orientation)
{
//set wrench sum to zero
Wrench wrench = Wrench::zero();
//calculate total force on rigid body's center of gravity
for (uint i = 0; i < body.wrenchVertexCount(); ++i) {
//aggregate total
const PhysicsBodyVertex& vertex = body.getWrenchVertex(i);
const auto& vertex_wrench = vertex.getWrench();
wrench += vertex_wrench;
//add additional torque due to force applies farther than COG
// tau = r X F
wrench.torque += vertex.getPosition().cross(vertex_wrench.force);
}
//convert force to world frame, leave torque to local frame
wrench.force = VectorMath::transformToWorldFrame(wrench.force, orientation);
return wrench;
}
static void getNextKinematicsNoCollision(TTimeDelta dt, PhysicsBody& body, const Kinematics::State& current,
Kinematics::State& next, Wrench& next_wrench, const Vector3r& wind)
{
const real_T dt_real = static_cast<real_T>(dt);
Vector3r avg_linear = Vector3r::Zero();
Vector3r avg_angular = Vector3r::Zero();
/************************* Get force and torque acting on body ************************/
//set wrench sum to zero
const Wrench body_wrench = getBodyWrench(body, current.pose.orientation);
if (body.isGrounded()) {
// make it stick to the ground until the magnitude of net external force on body exceeds its weight.
float external_force_magnitude = body_wrench.force.squaredNorm();
Vector3r weight = body.getMass() * body.getEnvironment().getState().gravity;
float weight_magnitude = weight.squaredNorm();
if (external_force_magnitude >= weight_magnitude) {
//throttledLogOutput("*** Losing ground lock due to body_wrench " + VectorMath::toString(body_wrench.force), 0.1);
body.setGrounded(false);
}
next_wrench.force = Vector3r::Zero();
next_wrench.torque = Vector3r::Zero();
next.accelerations.linear = Vector3r::Zero();
}
else {
//add linear drag due to velocity we had since last dt seconds + wind
//drag vector magnitude is proportional to v^2, direction opposite of velocity
//total drag is b*v + c*v*v but we ignore the first term as b << c (pg 44, Classical Mechanics, John Taylor)
//To find the drag force, we find the magnitude in the body frame and unit vector direction in world frame
avg_linear = current.twist.linear + current.accelerations.linear * (0.5f * dt_real);
avg_angular = current.twist.angular + current.accelerations.angular * (0.5f * dt_real);
const Wrench drag_wrench = getDragWrench(body, current.pose.orientation, avg_linear, avg_angular, wind);
next_wrench = body_wrench + drag_wrench;
//Utils::log(Utils::stringf("B-WRN %s: ", VectorMath::toString(body_wrench.force).c_str()));
//Utils::log(Utils::stringf("D-WRN %s: ", VectorMath::toString(drag_wrench.force).c_str()));
/************************* Update accelerations due to force and torque ************************/
//get new acceleration due to force - we'll use this acceleration in next time step
next.accelerations.linear = (next_wrench.force / body.getMass()) + body.getEnvironment().getState().gravity;
}
if (body.isGrounded()) {
// this stops vehicle from vibrating while it is on the ground doing nothing.
next.accelerations.angular = Vector3r::Zero();
next.twist.linear = Vector3r::Zero();
next.twist.angular = Vector3r::Zero();
}
else {
//get new angular acceleration
//Euler's rotation equation: https://en.wikipedia.org/wiki/Euler's_equations_(body_dynamics)
//we will use torque to find out the angular acceleration
//angular momentum L = I * omega
const Vector3r angular_momentum = body.getInertia() * avg_angular;
const Vector3r angular_momentum_rate = next_wrench.torque - avg_angular.cross(angular_momentum);
//new angular acceleration - we'll use this acceleration in next time step
next.accelerations.angular = body.getInertiaInv() * angular_momentum_rate;
/************************* Update pose and twist after dt ************************/
//Verlet integration: http://www.physics.udel.edu/~bnikolic/teaching/phys660/numerical_ode/node5.html
next.twist.linear = current.twist.linear + (current.accelerations.linear + next.accelerations.linear) * (0.5f * dt_real);
next.twist.angular = current.twist.angular + (current.accelerations.angular + next.accelerations.angular) * (0.5f * dt_real);
//if controller has bug, velocities can increase idenfinitely
//so we need to clip this or everything will turn in to infinity/nans
if (next.twist.linear.squaredNorm() > EarthUtils::SpeedOfLight * EarthUtils::SpeedOfLight) { //speed of light
next.twist.linear /= (next.twist.linear.norm() / EarthUtils::SpeedOfLight);
next.accelerations.linear = Vector3r::Zero();
}
//
//for disc of 1m radius which angular velocity translates to speed of light on tangent?
if (next.twist.angular.squaredNorm() > EarthUtils::SpeedOfLight * EarthUtils::SpeedOfLight) { //speed of light
next.twist.angular /= (next.twist.angular.norm() / EarthUtils::SpeedOfLight);
next.accelerations.angular = Vector3r::Zero();
}
}
computeNextPose(dt, current.pose, avg_linear, avg_angular, next);
//Utils::log(Utils::stringf("N-VEL %s %f: ", VectorMath::toString(next.twist.linear).c_str(), dt));
//Utils::log(Utils::stringf("N-POS %s %f: ", VectorMath::toString(next.pose.position).c_str(), dt));
}
static void computeNextPose(TTimeDelta dt, const Pose& current_pose, const Vector3r& avg_linear, const Vector3r& avg_angular, Kinematics::State& next)
{
real_T dt_real = static_cast<real_T>(dt);
next.pose.position = current_pose.position + avg_linear * dt_real;
//use angular velocty in body frame to calculate angular displacement in last dt seconds
real_T angle_per_unit = avg_angular.norm();
if (Utils::isDefinitelyGreaterThan(angle_per_unit, 0.0f)) {
//convert change in angle to unit quaternion
AngleAxisr angle_dt_aa = AngleAxisr(angle_per_unit * dt_real, avg_angular / angle_per_unit);
Quaternionr angle_dt_q = Quaternionr(angle_dt_aa);
/*
Add change in angle to previous orientation.
Proof that this is q0 * q1:
If rotated vector is qx*v*qx' then qx is attitude
Initially we have q0*v*q0'
Lets transform this to body coordinates to get
q0'*(q0*v*q0')*q0
Then apply q1 rotation on it to get
q1(q0'*(q0*v*q0')*q0)q1'
Then transform back to world coordinate
q0(q1(q0'*(q0*v*q0')*q0)q1')q0'
which simplifies to
q0(q1(v)q1')q0'
Thus new attitude is q0q1
*/
next.pose.orientation = current_pose.orientation * angle_dt_q;
if (VectorMath::hasNan(next.pose.orientation)) {
//Utils::DebugBreak();
Utils::log("orientation had NaN!", Utils::kLogLevelError);
}
//re-normalize quaternion to avoid accumulating error
next.pose.orientation.normalize();
}
else //no change in angle, because angular velocity is zero (normalized vector is undefined)
next.pose.orientation = current_pose.orientation;
}
private:
static constexpr uint kCollisionResponseCycles = 1;
static constexpr float kAxisTolerance = 0.25f;
static constexpr float kRestingVelocityMax = 0.1f;
static constexpr float kDragMinVelocity = 0.1f;
std::stringstream debug_string_;
bool enable_ground_lock_;
TTimePoint last_message_time;
Vector3r wind_;
};
}
} //namespace
#endif
| AirSim/AirLib/include/physics/FastPhysicsEngine.hpp/0 | {
"file_path": "AirSim/AirLib/include/physics/FastPhysicsEngine.hpp",
"repo_id": "AirSim",
"token_count": 10636
} | 11 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef msr_airlib_Barometer_hpp
#define msr_airlib_Barometer_hpp
#include <random>
#include "common/Common.hpp"
#include "common/EarthUtils.hpp"
#include "BarometerSimpleParams.hpp"
#include "BarometerBase.hpp"
#include "common/GaussianMarkov.hpp"
#include "common/DelayLine.hpp"
#include "common/FrequencyLimiter.hpp"
namespace msr
{
namespace airlib
{
class BarometerSimple : public BarometerBase
{
public:
BarometerSimple(const AirSimSettings::BarometerSetting& setting = AirSimSettings::BarometerSetting())
: BarometerBase(setting.sensor_name)
{
// initialize params
params_.initializeFromSettings(setting);
//GM process that would do random walk for pressure factor
pressure_factor_.initialize(params_.pressure_factor_tau, params_.pressure_factor_sigma, 0);
uncorrelated_noise_ = RandomGeneratorGausianR(0.0f, params_.uncorrelated_noise_sigma);
//correlated_noise_.initialize(params_.correlated_noise_tau, params_.correlated_noise_sigma, 0.0f);
//initialize frequency limiter
freq_limiter_.initialize(params_.update_frequency, params_.startup_delay);
delay_line_.initialize(params_.update_latency);
}
//*** Start: UpdatableState implementation ***//
virtual void resetImplementation() override
{
pressure_factor_.reset();
//correlated_noise_.reset();
uncorrelated_noise_.reset();
freq_limiter_.reset();
delay_line_.reset();
delay_line_.push_back(getOutputInternal());
}
virtual void update() override
{
BarometerBase::update();
freq_limiter_.update();
if (freq_limiter_.isWaitComplete()) {
delay_line_.push_back(getOutputInternal());
}
delay_line_.update();
if (freq_limiter_.isWaitComplete())
setOutput(delay_line_.getOutput());
}
//*** End: UpdatableState implementation ***//
virtual ~BarometerSimple() = default;
private: //methods
Output getOutputInternal()
{
Output output;
const GroundTruth& ground_truth = getGroundTruth();
auto altitude = ground_truth.environment->getState().geo_point.altitude;
auto pressure = EarthUtils::getStandardPressure(altitude);
//add drift in pressure, about 10m change per hour using default settings.
pressure_factor_.update();
pressure += pressure * pressure_factor_.getOutput();
//add noise in pressure (about 0.2m sigma)
pressure += uncorrelated_noise_.next();
output.pressure = pressure - EarthUtils::SeaLevelPressure + params_.qnh * 100.0f;
//apply altimeter formula
//https://en.wikipedia.org/wiki/Pressure_altitude
//TODO: use same formula as in driver code?
output.altitude = (1 - pow(pressure / EarthUtils::SeaLevelPressure, 0.190284f)) * 145366.45f * 0.3048f;
output.qnh = params_.qnh;
output.time_stamp = clock()->nowNanos();
return output;
}
private:
BarometerSimpleParams params_;
GaussianMarkov pressure_factor_;
//GaussianMarkov correlated_noise_;
RandomGeneratorGausianR uncorrelated_noise_;
FrequencyLimiter freq_limiter_;
DelayLine<Output> delay_line_;
};
}
} //namespace
#endif
| AirSim/AirLib/include/sensors/barometer/BarometerSimple.hpp/0 | {
"file_path": "AirSim/AirLib/include/sensors/barometer/BarometerSimple.hpp",
"repo_id": "AirSim",
"token_count": 1556
} | 12 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef msr_airlib_MagnetometerSimpleParams_hpp
#define msr_airlib_MagnetometerSimpleParams_hpp
#include "common/Common.hpp"
namespace msr
{
namespace airlib
{
struct MagnetometerSimpleParams
{
enum ReferenceSource
{
ReferenceSource_Constant,
ReferenceSource_DipoleModel
};
Vector3r noise_sigma = Vector3r(0.005f, 0.005f, 0.005f); //5 mgauss as per specs sheet (RMS is same as stddev) https://goo.gl/UOz6FT
real_T scale_factor = 1.0f;
Vector3r noise_bias = Vector3r(0.0f, 0.0f, 0.0f); //no offset as per specsheet (zero gauss level) https://goo.gl/UOz6FT
float ref_update_frequency = 0.2f; //Hz
//use dipole model if there is enough compute power available
bool dynamic_reference_source = true;
ReferenceSource ref_source = ReferenceSource::ReferenceSource_DipoleModel;
//bool dynamic_reference_source = false;
//ReferenceSource ref_source = ReferenceSource::ReferenceSource_Constant;
//see PX4 param reference for EKF: https://dev.px4.io/en/advanced/parameter_reference.html
real_T update_latency = 0.0f; //sec: from PX4 doc
real_T update_frequency = 50; //Hz
real_T startup_delay = 0; //sec
void initializeFromSettings(const AirSimSettings::MagnetometerSetting& settings)
{
const auto& json = settings.settings;
float noise = json.getFloat("NoiseSigma", noise_sigma.x());
noise_sigma = Vector3r(noise, noise, noise);
scale_factor = json.getFloat("ScaleFactor", scale_factor);
float bias = json.getFloat("NoiseBias", noise_bias.x());
noise_bias = Vector3r(bias, bias, bias);
update_latency = json.getFloat("UpdateLatency", update_latency);
update_frequency = json.getFloat("UpdateFrequency", update_frequency);
startup_delay = json.getFloat("StartupDelay", startup_delay);
}
};
}
} //namespace
#endif
| AirSim/AirLib/include/sensors/magnetometer/MagnetometerSimpleParams.hpp/0 | {
"file_path": "AirSim/AirLib/include/sensors/magnetometer/MagnetometerSimpleParams.hpp",
"repo_id": "AirSim",
"token_count": 862
} | 13 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef air_MultirotorRpcLibClient_hpp
#define air_MultirotorRpcLibClient_hpp
#include "common/Common.hpp"
#include <functional>
#include "common/CommonStructs.hpp"
#include "common/ImageCaptureBase.hpp"
#include "vehicles/multirotor/api/MultirotorApiBase.hpp"
#include "api/RpcLibClientBase.hpp"
#include "vehicles/multirotor/api/MultirotorCommon.hpp"
namespace msr
{
namespace airlib
{
class MultirotorRpcLibClient : public RpcLibClientBase
{
public:
MultirotorRpcLibClient(const string& ip_address = "localhost", uint16_t port = RpcLibPort, float timeout_sec = 60);
MultirotorRpcLibClient* takeoffAsync(float timeout_sec = 20, const std::string& vehicle_name = "");
MultirotorRpcLibClient* landAsync(float timeout_sec = 60, const std::string& vehicle_name = "");
MultirotorRpcLibClient* goHomeAsync(float timeout_sec = Utils::max<float>(), const std::string& vehicle_name = "");
MultirotorRpcLibClient* moveToGPSAsync(float latitude, float longitude, float altitude, float velocity, float timeout_sec = Utils::max<float>(),
DrivetrainType drivetrain = DrivetrainType::MaxDegreeOfFreedom, const YawMode& yaw_mode = YawMode(),
float lookahead = -1, float adaptive_lookahead = 1, const std::string& vehicle_name = "");
MultirotorRpcLibClient* moveByVelocityBodyFrameAsync(float vx, float vy, float vz, float duration,
DrivetrainType drivetrain = DrivetrainType::MaxDegreeOfFreedom, const YawMode& yaw_mode = YawMode(), const std::string& vehicle_name = "");
MultirotorRpcLibClient* moveByVelocityZBodyFrameAsync(float vx, float vy, float z, float duration,
DrivetrainType drivetrain = DrivetrainType::MaxDegreeOfFreedom, const YawMode& yaw_mode = YawMode(), const std::string& vehicle_name = "");
MultirotorRpcLibClient* moveByMotorPWMsAsync(float front_right_pwm, float rear_left_pwm, float front_left_pwm, float rear_right_pwm, float duration, const std::string& vehicle_name = "");
MultirotorRpcLibClient* moveByRollPitchYawZAsync(float roll, float pitch, float yaw, float z, float duration, const std::string& vehicle_name = "");
MultirotorRpcLibClient* moveByRollPitchYawThrottleAsync(float roll, float pitch, float yaw, float throttle, float duration, const std::string& vehicle_name = "");
MultirotorRpcLibClient* moveByRollPitchYawrateThrottleAsync(float roll, float pitch, float yaw_rate, float throttle, float duration, const std::string& vehicle_name = "");
MultirotorRpcLibClient* moveByRollPitchYawrateZAsync(float roll, float pitch, float yaw_rate, float z, float duration, const std::string& vehicle_name = "");
MultirotorRpcLibClient* moveByAngleRatesZAsync(float roll_rate, float pitch_rate, float yaw_rate, float z, float duration, const std::string& vehicle_name = "");
MultirotorRpcLibClient* moveByAngleRatesThrottleAsync(float roll_rate, float pitch_rate, float yaw_rate, float throttle, float duration, const std::string& vehicle_name = "");
MultirotorRpcLibClient* moveByVelocityAsync(float vx, float vy, float vz, float duration,
DrivetrainType drivetrain = DrivetrainType::MaxDegreeOfFreedom, const YawMode& yaw_mode = YawMode(), const std::string& vehicle_name = "");
MultirotorRpcLibClient* moveByVelocityZAsync(float vx, float vy, float z, float duration,
DrivetrainType drivetrain = DrivetrainType::MaxDegreeOfFreedom, const YawMode& yaw_mode = YawMode(), const std::string& vehicle_name = "");
MultirotorRpcLibClient* moveOnPathAsync(const vector<Vector3r>& path, float velocity, float timeout_sec = Utils::max<float>(),
DrivetrainType drivetrain = DrivetrainType::MaxDegreeOfFreedom, const YawMode& yaw_mode = YawMode(),
float lookahead = -1, float adaptive_lookahead = 1, const std::string& vehicle_name = "");
MultirotorRpcLibClient* moveToPositionAsync(float x, float y, float z, float velocity, float timeout_sec = Utils::max<float>(),
DrivetrainType drivetrain = DrivetrainType::MaxDegreeOfFreedom, const YawMode& yaw_mode = YawMode(),
float lookahead = -1, float adaptive_lookahead = 1, const std::string& vehicle_name = "");
MultirotorRpcLibClient* moveToZAsync(float z, float velocity, float timeout_sec = Utils::max<float>(),
const YawMode& yaw_mode = YawMode(), float lookahead = -1, float adaptive_lookahead = 1, const std::string& vehicle_name = "");
MultirotorRpcLibClient* moveByManualAsync(float vx_max, float vy_max, float z_min, float duration,
DrivetrainType drivetrain = DrivetrainType::MaxDegreeOfFreedom, const YawMode& yaw_mode = YawMode(), const std::string& vehicle_name = "");
MultirotorRpcLibClient* rotateToYawAsync(float yaw, float timeout_sec = Utils::max<float>(), float margin = 5, const std::string& vehicle_name = "");
MultirotorRpcLibClient* rotateByYawRateAsync(float yaw_rate, float duration, const std::string& vehicle_name = "");
MultirotorRpcLibClient* hoverAsync(const std::string& vehicle_name = "");
void setAngleLevelControllerGains(const vector<float>& kp, const vector<float>& ki, const vector<float>& kd, const std::string& vehicle_name = "");
void setAngleRateControllerGains(const vector<float>& kp, const vector<float>& ki, const vector<float>& kd, const std::string& vehicle_name = "");
void setVelocityControllerGains(const vector<float>& kp, const vector<float>& ki, const vector<float>& kd, const std::string& vehicle_name = "");
void setPositionControllerGains(const vector<float>& kp, const vector<float>& ki, const vector<float>& kd, const std::string& vehicle_name = "");
void moveByRC(const RCData& rc_data, const std::string& vehicle_name = "");
MultirotorState getMultirotorState(const std::string& vehicle_name = "");
RotorStates getRotorStates(const std::string& vehicle_name = "");
bool setSafety(SafetyEval::SafetyViolationType enable_reasons, float obs_clearance, SafetyEval::ObsAvoidanceStrategy obs_startegy,
float obs_avoidance_vel, const Vector3r& origin, float xy_length, float max_z, float min_z, const std::string& vehicle_name = "");
virtual MultirotorRpcLibClient* waitOnLastTask(bool* task_result = nullptr, float timeout_sec = Utils::nan<float>()) override;
virtual ~MultirotorRpcLibClient(); //required for pimpl
private:
struct impl;
std::unique_ptr<impl> pimpl_;
};
}
} //namespace
#endif
| AirSim/AirLib/include/vehicles/multirotor/api/MultirotorRpcLibClient.hpp/0 | {
"file_path": "AirSim/AirLib/include/vehicles/multirotor/api/MultirotorRpcLibClient.hpp",
"repo_id": "AirSim",
"token_count": 2848
} | 14 |
#pragma once
#include "interfaces/CommonStructs.hpp"
#include "interfaces/IBoardClock.hpp"
#include "interfaces/IAxisController.hpp"
#include "Params.hpp"
#include "PidController.hpp"
#include "common/common_utils/Utils.hpp"
#include <memory>
#include <string>
#include <exception>
namespace simple_flight
{
class AngleRateController : public IAxisController
{
public:
AngleRateController(Params* params, const IBoardClock* clock)
: params_(params), clock_(clock)
{
}
virtual void initialize(unsigned int axis, const IGoal* goal, const IStateEstimator* state_estimator) override
{
if (axis > 2)
throw std::invalid_argument("AngleRateController only supports axis 0-2 but it was " + std::to_string(axis));
axis_ = axis;
goal_ = goal;
state_estimator_ = state_estimator;
pid_.reset(new PidController<float>(clock_,
PidConfig<float>(params_->angle_rate_pid.p[axis], params_->angle_rate_pid.i[axis], params_->angle_rate_pid.d[axis])));
}
virtual void reset() override
{
IAxisController::reset();
pid_->reset();
output_ = TReal();
}
virtual void update() override
{
IAxisController::update();
pid_->setGoal(goal_->getGoalValue()[axis_]);
pid_->setMeasured(state_estimator_->getAngularVelocity()[axis_]);
pid_->update();
output_ = pid_->getOutput();
}
virtual TReal getOutput() override
{
return output_;
}
private:
unsigned int axis_;
const IGoal* goal_;
const IStateEstimator* state_estimator_;
TReal output_;
Params* params_;
const IBoardClock* clock_;
std::unique_ptr<PidController<float>> pid_;
};
} //namespace | AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/AngleRateController.hpp/0 | {
"file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/AngleRateController.hpp",
"repo_id": "AirSim",
"token_count": 753
} | 15 |
#pragma once
#include "IUpdatable.hpp"
#include "IBoardClock.hpp"
#include "IBoardInputPins.hpp"
#include "IBoardOutputPins.hpp"
#include "IBoardSensors.hpp"
namespace simple_flight
{
class IBoard : public IUpdatable
, public IBoardClock
, public IBoardInputPins
, public IBoardOutputPins
, public IBoardSensors
{
};
} //namespace | AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/interfaces/IBoard.hpp/0 | {
"file_path": "AirSim/AirLib/include/vehicles/multirotor/firmwares/simple_flight/firmware/interfaces/IBoard.hpp",
"repo_id": "AirSim",
"token_count": 140
} | 16 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//in header only mode, control library is not available
#ifndef AIRLIB_HEADER_ONLY
#include <thread>
#include "safety/ObstacleMap.hpp"
#include "common/common_utils/Utils.hpp"
namespace msr
{
namespace airlib
{
ObstacleMap::ObstacleMap(int ticks, bool odd_blindspots)
: distances_(ticks, Utils::max<float>() / 2), confidences_(ticks, 1), ticks_(ticks), blindspots_(ticks_, false) //init with all distances at max/2 (setting it to max can cause overflow later)
{
if (odd_blindspots)
for (uint i = 1; i < distances_.size(); i += 2)
blindspots_.at(i) = true;
}
//handles +/- tick and wraps around circle
//return value of this function is always >= 0 and < ticks_ (i.e. valid indices)
int ObstacleMap::wrap(int tick) const
{
int iw = tick % ticks_;
if (iw < 0)
iw = ticks_ + iw;
return iw;
}
void ObstacleMap::update(float distance, int tick, int window, float confidence)
{
std::lock_guard<std::mutex> lock(mutex_); //lock the map before update
//update the specified window on the map
for (int i = tick - window; i <= tick + window; ++i) {
int iw = wrap(i);
distances_[iw] = distance;
confidences_[iw] = confidence;
}
}
void ObstacleMap::update(float distances[], float confidences[])
{
std::lock_guard<std::mutex> lock(mutex_); //lock the map before update
std::copy(distances, distances + ticks_, std::begin(distances_));
std::copy(confidences, confidences + ticks_, std::begin(confidences_));
}
void ObstacleMap::setBlindspot(int tick, bool blindspot)
{
blindspots_.at(tick) = blindspot;
}
ObstacleMap::ObstacleInfo ObstacleMap::hasObstacle_(int from_tick, int to_tick) const
{
//make sure from <= to
if (from_tick > to_tick) {
//normalize the ticks so both are valid indices
from_tick = wrap(from_tick);
to_tick = wrap(to_tick);
//if from is still larger then
//to ticks is then added one full circle to make it larger than from_tick
if (from_tick > to_tick)
to_tick += ticks_;
}
//find closest obstacle in given window
ObstacleMap::ObstacleInfo obs;
obs.distance = Utils::max<float>();
obs.confidence = 0;
for (int i = from_tick; i <= to_tick; ++i) {
int iw = wrap(i);
if (obs.distance > distances_[iw]) {
obs.tick = iw;
obs.distance = distances_[iw];
obs.confidence = confidences_[iw];
}
}
return obs;
}
ObstacleMap::ObstacleInfo ObstacleMap::hasObstacle(int from_tick, int to_tick)
{
std::lock_guard<std::mutex> lock(mutex_); //lock the map before query
if (blindspots_.at(wrap(from_tick)))
from_tick--;
if (blindspots_.at(wrap(to_tick)))
to_tick++;
return hasObstacle_(from_tick, to_tick);
}
//search whole map to find closest obstacle
ObstacleMap::ObstacleInfo ObstacleMap::getClosestObstacle()
{
std::lock_guard<std::mutex> lock(mutex_);
return hasObstacle_(0, ticks_ - 1);
}
int ObstacleMap::getTicks() const
{
return ticks_;
}
int ObstacleMap::angleToTick(float angle_rad) const
{
return Utils::floorToInt(
((angle_rad * ticks_ / M_PIf) + 1) / 2);
}
float ObstacleMap::tickToAngleStart(int tick) const
{
return M_PIf * (2 * tick - 1) / ticks_;
}
float ObstacleMap::tickToAngleEnd(int tick) const
{
return M_PIf * (2 * tick + 1) / ticks_;
}
float ObstacleMap::tickToAngleMid(int tick) const
{
return 2 * M_PIf * tick / ticks_;
}
}
} //namespace
#endif
| AirSim/AirLib/src/safety/ObstacleMap.cpp/0 | {
"file_path": "AirSim/AirLib/src/safety/ObstacleMap.cpp",
"repo_id": "AirSim",
"token_count": 1778
} | 17 |
#ifndef msr_AirLibUnitTests_TestBase_hpp
#define msr_AirLibUnitTests_TestBase_hpp
#include <string>
#include <exception>
#include "common/common_utils/Utils.hpp"
namespace msr
{
namespace airlib
{
class TestBase
{
public:
virtual ~TestBase() = default;
virtual void run() = 0;
void testAssert(double lhs, double rhs, const std::string& message)
{
testAssert(lhs == rhs, message);
}
void testAssert(bool condition, const std::string& message)
{
if (!condition) {
common_utils::Utils::DebugBreak();
throw std::runtime_error(message.c_str());
}
}
};
}
}
#endif | AirSim/AirLibUnitTests/TestBase.hpp/0 | {
"file_path": "AirSim/AirLibUnitTests/TestBase.hpp",
"repo_id": "AirSim",
"token_count": 337
} | 18 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include <iostream>
#include <iomanip>
#include "common/Common.hpp"
#include "common/common_utils/ProsumerQueue.hpp"
#include "common/common_utils/FileSystem.hpp"
#include "common/ClockFactory.hpp"
#include "vehicles/multirotor/api/MultirotorRpcLibClient.hpp"
#include "vehicles/multirotor/api/MultirotorApiBase.hpp"
#include "RandomPointPoseGeneratorNoRoll.h"
#include "../../SGM/src/sgmstereo/sgmstereo.h"
#include "../../SGM/src/stereoPipeline/StateStereo.h"
#include "writePNG.h"
STRICT_MODE_OFF
#ifndef RPCLIB_MSGPACK
#define RPCLIB_MSGPACK clmdep_msgpack
#endif // !RPCLIB_MSGPACK
#include "rpc/rpc_error.h"
STRICT_MODE_ON
//NOTE: baseline (float B) and FOV (float fov) need to be set correctly!
class DataCollectorSGM
{
private:
//baseline * focal_length = depth * disparity
float fov = Utils::degreesToRadians(90.0f);
float B = 0.25;
float f = w / (2 * tan(fov / 2));
public:
DataCollectorSGM(std::string storage_dir)
: storage_dir_(storage_dir)
{
FileSystem::ensureFolder(storage_dir);
FileSystem::ensureFolder(FileSystem::combine(storage_dir, "left"));
FileSystem::ensureFolder(FileSystem::combine(storage_dir, "right"));
FileSystem::ensureFolder(FileSystem::combine(storage_dir, "depth_gt"));
FileSystem::ensureFolder(FileSystem::combine(storage_dir, "disparity_gt"));
FileSystem::ensureFolder(FileSystem::combine(storage_dir, "disparity_gt_viz"));
FileSystem::ensureFolder(FileSystem::combine(storage_dir, "depth_sgm"));
FileSystem::ensureFolder(FileSystem::combine(storage_dir, "disparity_sgm"));
FileSystem::ensureFolder(FileSystem::combine(storage_dir, "disparity_sgm_viz"));
FileSystem::ensureFolder(FileSystem::combine(storage_dir, "confidence_sgm"));
}
int generate(int num_samples)
{
msr::airlib::MultirotorRpcLibClient client;
client.confirmConnection();
client.reset();
std::vector<ImageRequest> request = {
ImageRequest("front_left", ImageType::Scene, false, false),
ImageRequest("front_right", ImageType::Scene, false, false),
ImageRequest("front_left", ImageType::DepthPlanar, true),
ImageRequest("front_left", ImageType::DisparityNormalized, true)
};
const std::vector<ImageResponse>& response_init = client.simGetImages(request);
w = response_init.at(0).width;
h = response_init.at(0).height;
msr::airlib::ClockBase* clock = msr::airlib::ClockFactory::get();
RandomPointPoseGeneratorNoRoll pose_generator(static_cast<int>(clock->nowNanos()));
std::fstream file_list(FileSystem::combine(storage_dir_, "files_list.txt"),
std::ios::out | std::ios::in | std::ios_base::app);
int sample = getImageCount(file_list);
p_state = new CStateStereo();
p_state->Initialize(params, h, w);
//Print SGM parameters
params.Print();
try {
while (sample < num_samples) {
pose_generator.next();
client.simSetVehiclePose(Pose(pose_generator.position, pose_generator.orientation), true);
const auto& collision_info = client.simGetCollisionInfo();
if (collision_info.has_collided) {
std::cout << "Collision at " << VectorMath::toString(collision_info.position) << std::endl;
continue;
}
++sample;
//Get into position
clock->sleep_for(0.5);
auto start_nanos = clock->nowNanos();
const std::vector<ImageResponse>& response = client.simGetImages(request);
if (response.size() != 4) {
std::cout << "Images were not received!" << std::endl;
start_nanos = clock->nowNanos();
continue;
}
ImagesResult result;
result.file_list = &file_list;
result.response = response;
result.sample = sample;
result.render_time = clock->elapsedSince(start_nanos);
;
result.storage_dir_ = storage_dir_;
result.position = pose_generator.position;
result.orientation = pose_generator.orientation;
processImages(&result);
}
}
catch (rpc::timeout& t) {
// will display a message like
// rpc::timeout: Timeout of 50ms while calling RPC function 'sleep'
std::cout << t.what() << std::endl;
}
return 0;
}
private:
typedef common_utils::FileSystem FileSystem;
typedef common_utils::Utils Utils;
typedef msr::airlib::VectorMath VectorMath;
typedef common_utils::RandomGeneratorF RandomGeneratorF;
typedef msr::airlib::Vector3r Vector3r;
typedef msr::airlib::Quaternionr Quaternionr;
typedef msr::airlib::Pose Pose;
typedef msr::airlib::ImageCaptureBase::ImageRequest ImageRequest;
typedef msr::airlib::ImageCaptureBase::ImageResponse ImageResponse;
typedef msr::airlib::ImageCaptureBase::ImageType ImageType;
std::string storage_dir_;
bool spawn_ue4 = false;
SGMOptions params;
CStateStereo* p_state;
//Image resolution
int w;
int h;
float dtime = 0;
private:
struct ImagesResult
{
std::vector<ImageResponse> response;
msr::airlib::TTimeDelta render_time;
std::string storage_dir_;
std::fstream* file_list;
int sample;
Vector3r position;
Quaternionr orientation;
};
static int getImageCount(std::fstream& file_list)
{
int sample = 0;
std::string line;
while (std::getline(file_list, line))
++sample;
if (file_list.eof())
file_list.clear(); //otherwise we can't do any further I/O
else if (file_list.bad()) {
throw std::runtime_error("Error occurred while reading files_list.txt");
}
return sample;
}
void processImages(ImagesResult* result)
{
msr::airlib::ClockBase* clock = msr::airlib::ClockFactory::get();
auto process_time = clock->nowNanos();
//Initialize file names
std::string left_file_name = Utils::stringf("left/%06d.png", result->sample);
std::string right_file_name = Utils::stringf("right/%06d.png", result->sample);
std::string depth_gt_file_name = Utils::stringf("depth_gt/%06d.pfm", result->sample);
std::string disparity_gt_file_name = Utils::stringf("disparity_gt/%06d.pfm", result->sample);
std::string disparity_gt_viz_file_name = Utils::stringf("disparity_gt_viz/%06d.png", result->sample);
std::string depth_sgm_file_name = Utils::stringf("depth_sgm/%06d.pfm", result->sample);
std::string disparity_sgm_file_name = Utils::stringf("disparity_sgm/%06d.pfm", result->sample);
std::string disparity_sgm_viz_file_name = Utils::stringf("disparity_sgm_viz/%06d.png", result->sample);
std::string confidence_sgm_file_name = Utils::stringf("confidence_sgm/%06d.png", result->sample);
//Initialize data containers
std::vector<uint8_t> left_img(h * w * 3);
std::vector<uint8_t> right_img(h * w * 3);
std::vector<float> gt_depth_data = result->response.at(2).image_data_float;
std::vector<float> gt_disparity_data = result->response.at(3).image_data_float;
std::vector<float> sgm_depth_data(h * w);
std::vector<float> sgm_disparity_data(h * w);
std::vector<uint8_t> sgm_confidence_data(h * w);
//Remove alpha from RGB images
int counter = 0;
for (int idx = 0; idx < (h * w * 4); idx++) {
if ((idx + 1) % 4 == 0) {
counter++;
continue;
}
left_img[idx - counter] = result->response.at(0).image_data_uint8[idx];
right_img[idx - counter] = result->response.at(1).image_data_uint8[idx];
}
//Get SGM disparity and confidence
p_state->ProcessFrameAirSim(result->sample, dtime, left_img, right_img);
//Get adjust SGM disparity and compute depth
for (int idx = 0; idx < (h * w); idx++) {
float d = p_state->dispMap[idx];
if (d < FLT_MAX) {
sgm_depth_data[idx] = -(B * f / d);
sgm_disparity_data[idx] = -d;
}
sgm_confidence_data[idx] = p_state->confMap[idx];
}
//Write files to disk
//Left and right RGB image
FILE* img_l = fopen(FileSystem::combine(result->storage_dir_, left_file_name).c_str(), "wb");
svpng(img_l, w, h, reinterpret_cast<const unsigned char*>(left_img.data()), 0);
fclose(img_l);
FILE* img_r = fopen(FileSystem::combine(result->storage_dir_, right_file_name).c_str(), "wb");
svpng(img_r, w, h, reinterpret_cast<const unsigned char*>(right_img.data()), 0);
fclose(img_r);
//GT disparity and depth
Utils::writePFMfile(gt_depth_data.data(), w, h, FileSystem::combine(result->storage_dir_, depth_gt_file_name));
denormalizeDisparity(gt_disparity_data, w);
Utils::writePFMfile(gt_disparity_data.data(), w, h, FileSystem::combine(result->storage_dir_, disparity_gt_file_name));
//SGM depth disparity and confidence
Utils::writePFMfile(sgm_depth_data.data(), w, h, FileSystem::combine(result->storage_dir_, depth_sgm_file_name));
Utils::writePFMfile(sgm_disparity_data.data(), w, h, FileSystem::combine(result->storage_dir_, disparity_sgm_file_name));
FILE* sgm_c = fopen(FileSystem::combine(result->storage_dir_, confidence_sgm_file_name).c_str(), "wb");
svpng(sgm_c, w, h, reinterpret_cast<const unsigned char*>(sgm_confidence_data.data()), 0, 1);
fclose(sgm_c);
//GT and SGM disparity for visualization
std::vector<uint8_t> sgm_disparity_viz(h * w * 3);
getColorVisualization(sgm_disparity_data, sgm_disparity_viz, h, w, 0.05f * w);
FILE* disparity_sgm = fopen(FileSystem::combine(result->storage_dir_, disparity_sgm_viz_file_name).c_str(), "wb");
svpng(disparity_sgm, w, h, reinterpret_cast<const unsigned char*>(sgm_disparity_viz.data()), 0);
fclose(disparity_sgm);
std::vector<uint8_t> gt_disparity_viz(h * w * 3);
getColorVisualization(gt_disparity_data, gt_disparity_viz, h, w, 0.05f * w);
FILE* disparity_gt = fopen(FileSystem::combine(result->storage_dir_, disparity_gt_viz_file_name).c_str(), "wb");
svpng(disparity_gt, w, h, reinterpret_cast<const unsigned char*>(gt_disparity_viz.data()), 0);
fclose(disparity_gt);
//Add all to file record
(*result->file_list) << left_file_name << "," << right_file_name << "," << depth_gt_file_name << "," << disparity_gt_file_name << "," << depth_sgm_file_name << "," << disparity_sgm_file_name << "," << confidence_sgm_file_name << std::endl;
std::cout << "Image #" << result->sample
<< " pos:" << VectorMath::toString(result->position)
<< " ori:" << VectorMath::toString(result->orientation)
<< " render time " << result->render_time * 1E3f << "ms"
<< " process time " << clock->elapsedSince(process_time) * 1E3f << " ms"
<< std::endl;
}
void getcolor(float d, float max_d, float& r, float& g, float& b)
{
float x = 6.0f;
float inc = x / max_d;
if (d < max_d)
x = d * inc;
else
x = max_d * inc;
r = 0.0f;
g = 0.0f;
b = 0.0f;
if ((0 <= x && x <= 1) || (5 <= x && x < 6))
r = 1.0f;
else if (4 <= x && x < 5)
r = x - 4;
else if (1 <= x && x < 2)
r = 1.0f - (x - 1);
if (1 <= x && x < 3)
g = 1.0f;
else if (0 <= x && x < 1)
g = x - 0;
else if (3 <= x && x < 4)
g = 1.0f - (x - 3);
if (3 <= x && x < 5)
b = 1.0f;
else if (2 <= x && x < 3)
b = x - 2;
else if (5 <= x && x < 6)
b = 1.0f - (x - 5);
}
template <typename T>
void getColorVisualization(T& img, std::vector<uint8_t>& img_viz, int h, int w, float max_val = 255)
{
for (int idx = 0; idx < (h * w); idx++) {
float r, g, b;
getcolor(img[idx], max_val, r, g, b);
img_viz[idx * 3] = (uint8_t)(r * 255);
img_viz[idx * 3 + 1] = (uint8_t)(g * 255);
img_viz[idx * 3 + 2] = (uint8_t)(b * 255);
}
}
template <typename T>
void getGrayVisualization(T& img, std::vector<uint8_t>& img_viz, int h, int w, int invert = 0, float scale = 1)
{
img_viz.resize(h * w);
for (int idx = 0; idx < (h * w); idx++) {
img_viz[idx] = (uint8_t)(invert ? scale / img[idx] : img[idx] * scale);
}
}
static void saveImageToFile(const std::vector<uint8_t>& image_data, const std::string& file_name)
{
std::ofstream file(file_name, std::ios::binary);
file.write((char*)image_data.data(), image_data.size());
file.close();
}
static void convertToPlanDepth(std::vector<float>& image_data, int width, int height, float f_px = 320)
{
float center_i = width / 2.0f - 1;
float center_j = height / 2.0f - 1;
for (int i = 0; i < width; ++i) {
for (int j = 0; j < height; ++j) {
float dist = std::sqrt((i - center_i) * (i - center_i) + (j - center_j) * (j - center_j));
float denom = (dist / f_px);
denom *= denom;
denom = std::sqrt(1 + denom);
image_data[j * width + i] /= denom;
}
}
}
static void convertToDisparity(std::vector<float>& image_data, float f_px = 320, float baseline_meters = 1)
{
for (int i = 0; i < image_data.size(); ++i) {
image_data[i] = f_px * baseline_meters * (1.0f / image_data[i]);
}
}
static void denormalizeDisparity(std::vector<float>& image_data, int width)
{
for (int i = 0; i < image_data.size(); ++i) {
image_data[i] = image_data[i] * width;
}
}
};
| AirSim/Examples/DataCollection/DataCollectorSGM.h/0 | {
"file_path": "AirSim/Examples/DataCollection/DataCollectorSGM.h",
"repo_id": "AirSim",
"token_count": 6815
} | 19 |
#pragma once
#include <memory>
#include "common/SteppableClock.hpp"
#include "physics/FastPhysicsEngine.hpp"
#include "physics/DebugPhysicsBody.hpp"
class StandAlonePhysics
{
public:
static void testCollision()
{
using namespace msr::airlib;
std::shared_ptr<SteppableClock> clock = std::make_shared<SteppableClock>();
ClockFactory::get(clock);
//init physics state
auto initial_kinematics = Kinematics::State::zero();
initial_kinematics.pose = Pose::zero();
initial_kinematics.pose.position.z() = -1;
msr::airlib::Environment::State initial_environment;
initial_environment.position = initial_kinematics.pose.position;
Environment environment(initial_environment);
Kinematics kinematics(initial_kinematics);
DebugPhysicsBody body;
body.initialize(&kinematics, &environment);
body.reset();
//create physics engine
FastPhysicsEngine physics;
physics.insert(&body);
physics.reset();
//run
unsigned int i = 0;
while (true) {
clock->step();
environment.update();
body.update();
physics.update();
++i;
CollisionInfo col;
constexpr real_T ground_level = -0.8f;
const auto& pos = body.getKinematics().pose.position;
Quaternionr orientation = body.getKinematics().pose.orientation;
Vector3r lowest_contact = pos + VectorMath::transformToWorldFrame(body.getShapeVertex(0), orientation);
for (uint svi = 1; svi < body.shapeVertexCount(); ++svi) {
Vector3r contact = pos + VectorMath::transformToWorldFrame(body.getShapeVertex(svi), orientation);
if (lowest_contact.z() < contact.z())
lowest_contact = contact;
}
real_T penetration = lowest_contact.z() - ground_level;
if (penetration >= 0) {
col.has_collided = true;
col.normal = Vector3r(0, 0, -1);
Vector3r r = lowest_contact - pos;
col.penetration_depth = penetration;
col.position = pos;
col.impact_point = lowest_contact;
std::cout << "Col: " << VectorMath::toString(col.impact_point) << std::endl;
}
else {
col.has_collided = false;
}
//col.has_collided = false;
body.setCollisionInfo(col);
}
}
}; | AirSim/Examples/StandAlonePhysics.hpp/0 | {
"file_path": "AirSim/Examples/StandAlonePhysics.hpp",
"repo_id": "AirSim",
"token_count": 1185
} | 20 |
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
</configuration>
| AirSim/LogViewer/LogViewer/App.config/0 | {
"file_path": "AirSim/LogViewer/LogViewer/App.config",
"repo_id": "AirSim",
"token_count": 78
} | 21 |
<UserControl x:Class="LogViewer.Controls.Console"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:LogViewer.Controls"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid Background="Black">
<RichTextBox x:Name="ConsoleTextBox" BorderThickness="0" PreviewKeyDown="OnConsoleKeyDown" Background="Black" Foreground="White"
Style="{StaticResource AppTextBox}" CaretBrush="LimeGreen" />
</Grid>
</UserControl>
| AirSim/LogViewer/LogViewer/Controls/Console.xaml/0 | {
"file_path": "AirSim/LogViewer/LogViewer/Controls/Console.xaml",
"repo_id": "AirSim",
"token_count": 356
} | 22 |
using LogViewer.Controls;
using LogViewer.Model;
using LogViewer.Model.ULog;
using LogViewer.Utilities;
using Microsoft.Maps.MapControl.WPF;
using Microsoft.Networking.Mavlink;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Xml.Linq;
namespace LogViewer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
const double MaxChartHeight = 400;
ProgressUtility progress;
List<IDataLog> logs = new List<IDataLog>();
ObservableCollection<Flight> allFlights = new ObservableCollection<Flight>();
DelayedActions delayedActions = new DelayedActions();
Quaternion initialAttitude;
MapPolyline currentFlight;
MavlinkLog currentFlightLog;
long lastAttitudeMessage;
List<LogEntry> mappedLogEntries;
MapLayer annotationLayer;
public MainWindow()
{
InitializeComponent();
UiDispatcher.Initialize();
this.progress = new ProgressUtility(MyProgress);
MyProgress.Visibility = Visibility.Collapsed;
UpdateButtons();
FlightView.ItemsSource = allFlights;
ConnectionPanel.DownloadCompleted += OnLogDownloadComplete;
ConnectionPanel.Connected += OnChannelConnected;
ConnectionPanel.Disconnected += OnChannelDisconnected;
this.Visibility = Visibility.Hidden;
RestoreSettings();
this.SizeChanged += OnWindowSizeChanged;
this.LocationChanged += OnWindowLocationChanged;
ChartStack.Visibility = Visibility.Collapsed;
ChartStack.ZoomChanged += OnZoomChanged;
initialAttitude = ModelViewer.ModelAttitude;
CameraPanel.Visibility = Visibility.Collapsed;
SystemConsole.Visibility = Visibility.Collapsed;
}
private void OnZoomChanged(object sender, EventArgs e)
{
double total = 0;
double count = 0;
foreach (var chart in ChartStack.FindCharts())
{
total += chart.GetVisibleCount();
count++;
}
ShowStatus(string.Format("zoom showing {0} data values", (int)(total / count)));
}
private void OnWindowLocationChanged(object sender, EventArgs e)
{
delayedActions.StartDelayedAction("SaveWindowLocation", SavePosition, TimeSpan.FromMilliseconds(1000));
}
private void OnWindowSizeChanged(object sender, SizeChangedEventArgs e)
{
delayedActions.StartDelayedAction("SaveWindowLocation", SavePosition, TimeSpan.FromMilliseconds(1000));
}
private async void RestoreSettings()
{
Settings settings = await ((App)App.Current).LoadSettings();
if (settings.WindowLocation.X != 0 && settings.WindowSize.Width != 0 && settings.WindowSize.Height != 0)
{
// make sure it is visible on the user's current screen configuration.
var bounds = new System.Drawing.Rectangle(
XamlExtensions.ConvertFromDeviceIndependentPixels(settings.WindowLocation.X),
XamlExtensions.ConvertFromDeviceIndependentPixels(settings.WindowLocation.Y),
XamlExtensions.ConvertFromDeviceIndependentPixels(settings.WindowSize.Width),
XamlExtensions.ConvertFromDeviceIndependentPixels(settings.WindowSize.Height));
var screen = System.Windows.Forms.Screen.FromRectangle(bounds);
bounds.Intersect(screen.WorkingArea);
this.Left = XamlExtensions.ConvertToDeviceIndependentPixels(bounds.X);
this.Top = XamlExtensions.ConvertToDeviceIndependentPixels(bounds.Y);
this.Width = XamlExtensions.ConvertToDeviceIndependentPixels(bounds.Width);
this.Height = XamlExtensions.ConvertToDeviceIndependentPixels(bounds.Height);
}
ConnectionPanel.DefaultUdpPort = settings.Port;
this.Visibility = Visibility.Visible;
}
async void SavePosition()
{
var bounds = this.RestoreBounds;
Settings settings = await ((App)App.Current).LoadSettings();
settings.WindowLocation = bounds.TopLeft;
settings.WindowSize = bounds.Size;
await settings.SaveAsync();
}
private async void OnChannelConnected(object sender, EventArgs e)
{
ConnectorControl.Connected = true;
QuadButton.IsChecked = true;
var channel = ConnectionPanel.Channel;
channel.MessageReceived += OnMavlinkMessageReceived;
SystemConsole.Channel = channel;
Settings settings = await ((App)App.Current).LoadSettings();
settings.Port = ConnectionPanel.DefaultUdpPort;
await settings.SaveAsync();
}
private void OnMavlinkMessageReceived(object sender, MavLinkMessage e)
{
if (currentFlightLog != null && !pauseRecording)
{
currentFlightLog.AddMessage(e);
}
switch (e.MsgId)
{
case MAVLink.MAVLINK_MSG_ID.ATTITUDE_QUATERNION:
{
// Only do this if drone is not sending MAVLINK_MSG_ID.ATTITUDE...
if (Environment.TickCount - lastAttitudeMessage > 1000)
{
var payload = (MAVLink.mavlink_attitude_quaternion_t)e.TypedPayload;
var q = new System.Windows.Media.Media3D.Quaternion(payload.q1, payload.q2, payload.q3, payload.q4);
UiDispatcher.RunOnUIThread(() =>
{
ModelViewer.ModelAttitude = initialAttitude * q;
});
}
break;
}
case MAVLink.MAVLINK_MSG_ID.ATTITUDE:
{
lastAttitudeMessage = Environment.TickCount;
var payload = (MAVLink.mavlink_attitude_t)e.TypedPayload;
Quaternion y = new Quaternion(new Vector3D(0, 0, 1), -payload.yaw * 180 / Math.PI);
Quaternion x = new Quaternion(new Vector3D(1, 0, 0), payload.pitch * 180 / Math.PI);
Quaternion z = new Quaternion(new Vector3D(0, 1, 0), payload.roll * 180 / Math.PI);
UiDispatcher.RunOnUIThread(() =>
{
ModelViewer.ModelAttitude = initialAttitude * (y * x * z);
});
break;
}
case MAVLink.MAVLINK_MSG_ID.HIL_STATE_QUATERNION:
{
var payload = (MAVLink.mavlink_hil_state_quaternion_t)e.TypedPayload;
Quaternion q = new Quaternion(payload.attitude_quaternion[0],
payload.attitude_quaternion[1],
payload.attitude_quaternion[2],
payload.attitude_quaternion[3]);
UiDispatcher.RunOnUIThread(() =>
{
ModelViewer.ModelAttitude = initialAttitude * q;
});
break;
}
case MAVLink.MAVLINK_MSG_ID.GLOBAL_POSITION_INT:
{
var payload = (MAVLink.mavlink_global_position_int_t)e.TypedPayload;
UiDispatcher.RunOnUIThread(() =>
{
MapLocation((double)payload.lat / 1e7, (double)payload.lon / 1e7);
});
break;
}
case MAVLink.MAVLINK_MSG_ID.SERIAL_CONTROL:
{
var ctrl = (MAVLink.mavlink_serial_control_t)e.TypedPayload;
if (ctrl.count > 0)
{
string text = System.Text.Encoding.ASCII.GetString(ctrl.data, 0, ctrl.count);
UiDispatcher.RunOnUIThread(() =>
{
SystemConsole.Write(text);
});
}
break;
}
case MAVLink.MAVLINK_MSG_ID.DATA_TRANSMISSION_HANDSHAKE:
if (showImageStream)
{
var p = (MAVLink.mavlink_data_transmission_handshake_t)e.TypedPayload;
incoming_image.size = p.size;
incoming_image.packets = p.packets;
incoming_image.payload = p.payload;
incoming_image.quality = p.jpg_quality;
incoming_image.type = p.type;
incoming_image.width = p.width;
incoming_image.height = p.height;
incoming_image.start = Environment.TickCount;
incoming_image.packetsArrived = 0;
incoming_image.data = new byte[incoming_image.size];
}
break;
case MAVLink.MAVLINK_MSG_ID.ENCAPSULATED_DATA:
if (showImageStream)
{
var img = (MAVLink.mavlink_encapsulated_data_t)e.TypedPayload;
int seq = img.seqnr;
uint pos = (uint)seq * (uint)incoming_image.payload;
// Check if we have a valid transaction
if (incoming_image.packets == 0 || incoming_image.size == 0)
{
// not expecting an image?
incoming_image.packetsArrived = 0;
break;
}
uint available = (uint)incoming_image.payload;
if (pos + available > incoming_image.size)
{
available = incoming_image.size - pos;
}
Array.Copy(img.data, 0, incoming_image.data, pos, available);
progress.ShowProgress(0, incoming_image.size, pos + available);
++incoming_image.packetsArrived;
//Debug.WriteLine("packet {0} of {1}, position {2} of {3}", incoming_image.packetsArrived, incoming_image.packets,
// pos + available, incoming_image.size);
// emit signal if all packets arrived
if (pos + available >= incoming_image.size)
{
// Restart state machine
incoming_image.packets = 0;
incoming_image.packetsArrived = 0;
byte[] saved = incoming_image.data;
incoming_image.data = null;
UiDispatcher.RunOnUIThread(() =>
{
progress.ShowProgress(0, 0, 0);
ShowImage(saved);
});
}
}
break;
}
}
private void ShowImage(byte[] image)
{
try
{
MemoryStream ms = new MemoryStream(image);
BitmapDecoder decoder = null;
MAVLink.MAVLINK_DATA_STREAM_TYPE type = (MAVLink.MAVLINK_DATA_STREAM_TYPE)incoming_image.type;
switch (type)
{
case MAVLink.MAVLINK_DATA_STREAM_TYPE.MAVLINK_DATA_STREAM_IMG_JPEG:
decoder = JpegBitmapDecoder.Create(ms, BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.None);
break;
case MAVLink.MAVLINK_DATA_STREAM_TYPE.MAVLINK_DATA_STREAM_IMG_BMP:
decoder = BitmapDecoder.Create(ms, BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.None);
break;
case MAVLink.MAVLINK_DATA_STREAM_TYPE.MAVLINK_DATA_STREAM_IMG_RAW8U:
var raw = Raw8UBitmapDecoder.Create(image, incoming_image.width, incoming_image.height);
BitmapFrame frame = raw.Frames[0];
ImageViewer.Source = frame;
break;
case MAVLink.MAVLINK_DATA_STREAM_TYPE.MAVLINK_DATA_STREAM_IMG_RAW32U:
//decoder = Raw8UBitmapDecoder.Create(ms, incoming_image.width, incoming_image.height);
break;
case MAVLink.MAVLINK_DATA_STREAM_TYPE.MAVLINK_DATA_STREAM_IMG_PGM:
//decoder = PgmBitmapDecoder.Create(ms, BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.None);
break;
case MAVLink.MAVLINK_DATA_STREAM_TYPE.MAVLINK_DATA_STREAM_IMG_PNG:
decoder = PngBitmapDecoder.Create(ms, BitmapCreateOptions.IgnoreImageCache, BitmapCacheOption.None);
break;
}
if (decoder != null && decoder.Frames.Count > 0)
{
BitmapFrame frame = decoder.Frames[0];
ImageViewer.Source = frame;
}
}
catch
{
}
}
private void OnChannelDisconnected(object sender, EventArgs e)
{
ConnectorControl.Connected = false;
SystemConsole.Channel = null;
}
private void OnLogDownloadComplete(object sender, string fileName)
{
ConnectionPanel.Visibility = Visibility.Collapsed;
Task.Run(async () => { await LoadBinaryFile(fileName); });
}
private async void OnOpenFile(object sender, RoutedEventArgs e)
{
OpenButton.IsEnabled = false;
Microsoft.Win32.OpenFileDialog fo = new Microsoft.Win32.OpenFileDialog();
fo.Filter = "mavlink files (*.mavlink)|*.mavlink|PX4 ulog Files (*.ulg)|*.ulg|CSV Files (*.csv)|*.csv|bin files (*.bin)|*.bin|JSON files (*.json)|*.json|KML files (*.kml)|*.kml";
fo.CheckFileExists = true;
fo.Multiselect = true;
if (fo.ShowDialog() == true)
{
SystemConsole.Show();
foreach (var file in fo.FileNames)
{
switch (System.IO.Path.GetExtension(file).ToLowerInvariant())
{
case ".csv":
await Task.Run(async () => { await LoadCsvFile(file); });
break;
case ".bin":
case ".px4log":
await Task.Run(async () => { await LoadBinaryFile(file); });
break;
case ".ulg":
case ".ulog":
await Task.Run(async () => { await LoadULogFile(file); });
break;
case ".mavlink":
await Task.Run(async () => { await LoadMavlinkFile(file); });
break;
case ".json":
await Task.Run(async () => { await LoadJSonFile(file); });
break;
case ".kml":
await Task.Run(async () => { await LoadKmlFile(file); });
break;
default:
MessageBox.Show("Do not know how to read files of type : " + System.IO.Path.GetExtension(file),
"Unsupported file extension", MessageBoxButton.OK, MessageBoxImage.Exclamation);
break;
}
UpdateTitle(System.IO.Path.GetFileName(file));
}
ShowTotalFlightTime();
}
OpenButton.IsEnabled = true;
}
string originalTitle;
private void UpdateTitle(string caption)
{
if (originalTitle == null)
{
originalTitle = this.Title;
}
if (string.IsNullOrEmpty(caption))
{
this.Title = originalTitle;
}
else
{
this.Title = originalTitle + " - " + caption;
}
}
private async Task LoadJSonFile(string file)
{
try
{
UiDispatcher.RunOnUIThread(() =>
{
SystemConsole.Show();
});
AppendMessage("Loading " + file);
ShowStatus("Loading " + file);
JSonDataLog data = new JSonDataLog();
await data.Load(file, progress);
//logs.Add(data);
ShowSchema();
LoadFlights(data);
}
catch (Exception ex)
{
AppendMessage("### Error loading json file: " + ex.Message);
}
ShowStatus("Done Loading " + file);
UpdateButtons();
}
private async Task LoadKmlFile(string file)
{
try
{
await Dispatcher.BeginInvoke(new Action(() =>
{
SystemConsole.Show();
})).Task;
AppendMessage("Loading " + file);
ShowStatus("Loading " + file);
XDocument doc = XDocument.Load(file);
KmlDataLog data = new Model.KmlDataLog();
data.Load(doc);
ShowSchema();
LoadFlights(data);
this.logs.Add(data);
}
catch (Exception ex)
{
AppendMessage("### Error loading KML file: " + ex.Message);
}
ShowStatus("Done Loading " + file);
UpdateButtons();
}
private async Task LoadULogFile(string file)
{
try
{
UiDispatcher.RunOnUIThread(() =>
{
SystemConsole.Show();
});
AppendMessage("Loading " + file);
ShowStatus("Loading " + file);
Px4ULog data = new Px4ULog();
await data.Load(file, progress);
logs.Add(data);
ShowSchema();
LoadFlights(data);
// remember successfully loaded log file.
Settings settings = await ((App)App.Current).LoadSettings();
settings.LastLogFile = file;
await settings.SaveAsync();
}
catch (Exception ex)
{
AppendMessage("### Error loading log: " + ex.Message);
}
ShowStatus("Done Loading " + file);
UpdateButtons();
}
private async Task LoadBinaryFile(string file)
{
try
{
UiDispatcher.RunOnUIThread(() =>
{
SystemConsole.Show();
});
AppendMessage("Loading " + file);
ShowStatus("Loading " + file);
Px4DataLog data = new Px4DataLog();
await data.Load(file, progress);
logs.Add(data);
ShowSchema();
LoadFlights(data);
// remember successfully loaded log file.
Settings settings = await ((App)App.Current).LoadSettings();
settings.LastLogFile = file;
await settings.SaveAsync();
}
catch (Exception ex)
{
AppendMessage("### Error loading log: " + ex.Message);
}
ShowStatus("Done Loading " + file);
UpdateButtons();
}
private void LoadFlights(IDataLog data)
{
UiDispatcher.RunOnUIThread(() =>
{
// add flights
Flight entireLog = new Flight()
{
Name = "Log " + logs.Count,
StartTime = DateTime.MinValue,
Duration = TimeSpan.MaxValue,
Log = data
};
allFlights.Add(entireLog);
foreach (var flight in data.GetFlights())
{
flight.Name = "Flight " + allFlights.Count;
allFlights.Add(flight);
if (!this.logs.Contains(flight.Log))
{
this.logs.Add(flight.Log);
}
AppendMessage("Motor started at {0} and ran for {1} ", flight.StartTime, flight.Duration);
}
if (myMap.Visibility == Visibility.Visible)
{
ShowMap();
}
});
}
private void ShowTotalFlightTime()
{
TimeSpan total = new TimeSpan();
foreach (Flight f in allFlights)
{
if (f.Name.StartsWith("Flight"))
{
total += f.Duration;
}
}
AppendMessage("Total flight time {0} ", total);
}
private void AppendMessage(string message, params object[] args)
{
UiDispatcher.RunOnUIThread(() =>
{
if (args == null || args.Length == 0)
{
SystemConsole.Write(message + "\n");
}
else
{
SystemConsole.Write(string.Format(message, args) + "\n");
}
});
}
private async Task LoadMavlinkFile(string file)
{
try
{
UiDispatcher.RunOnUIThread(() =>
{
SystemConsole.Show();
});
AppendMessage("Loading " + file);
ShowStatus("Loading " + file);
MavlinkLog data = new MavlinkLog();
await data.Load(file, progress);
logs.Add(data);
ShowSchema();
Debug.WriteLine(data.StartTime.ToString());
LoadFlights(data);
// remember successfully loaded log file.
Settings settings = await ((App)App.Current).LoadSettings();
settings.LastLogFile = file;
await settings.SaveAsync();
}
catch (Exception ex)
{
AppendMessage("### Error loading log: " + ex.Message);
}
ShowStatus("Done Loading " + file);
UpdateButtons();
}
private async Task LoadCsvFile(string file)
{
try
{
ShowStatus("Loading " + file);
CsvDataLog log = new CsvDataLog();
await log.Load(file, progress);
UiDispatcher.RunOnUIThread(() =>
{
FlightView.ItemsSource = new List<Flight>();
logs.Add(log);
ShowSchema();
});
}
catch (Exception ex)
{
ShowStatus(ex.Message);
}
ShowStatus("Done");
}
private void ShowSchema()
{
UiDispatcher.RunOnUIThread(() =>
{
LogItemSchema schema = null;
// todo: compute combined schema for selected logs, but for now just show the first one.
if (this.currentFlightLog != null)
{
schema = currentFlightLog.Schema;
}
foreach (var log in this.logs)
{
var s = log.Schema;
if (schema == null)
{
schema = s;
}
else
{
schema.Combine(s);
}
}
if (schema == null || !schema.HasChildren)
{
CategoryList.ItemsSource = null;
}
else
{
List<LogItemSchema> list = schema.CopyChildren();
list.Sort((a, b) => { return string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); });
CategoryList.ItemsSource = list;
}
});
}
private void ShowStatus(string message)
{
UiDispatcher.RunOnUIThread(() =>
{
StatusText.Text = message;
});
}
private void OnListItemSelected(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems != null && e.AddedItems.Count > 0)
{
LogItemSchema item = (LogItemSchema)e.AddedItems[0];
if (sender == CategoryList && item.HasChildren)
{
ListViewItem listItem = CategoryList.ItemContainerGenerator.ContainerFromItem(item) as ListViewItem;
if (listItem != null)
{
// make sure expander is toggled.
Expander expander = listItem.FindDescendantsOfType<Expander>().FirstOrDefault();
expander.IsExpanded = true;
}
}
else if (!item.HasChildren)
{
if (item.Parent == null)
{
GraphItem(item);
}
}
}
if (e.RemovedItems != null && e.RemovedItems.Count > 0)
{
LogItemSchema item = (LogItemSchema)e.RemovedItems[0];
if (sender == CategoryList && item.HasChildren)
{
ListViewItem listItem = CategoryList.ItemContainerGenerator.ContainerFromItem(item) as ListViewItem;
if (listItem != null)
{
Expander expander = listItem.FindDescendantsOfType<Expander>().FirstOrDefault();
expander.IsExpanded = false;
}
}
}
}
private void OnShowMap(object sender, RoutedEventArgs e)
{
ShowMap();
}
private void OnHideMap(object sender, RoutedEventArgs e)
{
myMap.Visibility = Visibility.Collapsed;
ChartStack.Visibility = Visibility.Visible;
}
List<Flight> GetSelectedFlights()
{
List<Flight> selected = new List<Model.Flight>();
foreach (Flight f in FlightView.SelectedItems)
{
selected.Add(f);
}
return selected;
}
double lastLat = 0;
double lastLon = 0;
private void MapLocation(double latitude, double longitude)
{
if (Math.Round(lastLat, 5) == Math.Round(latitude) && Math.Round(lastLon, 5) == Math.Round(longitude, 5))
{
// hasn't moved far enough yet...
return;
}
lastLat = latitude;
lastLon = longitude;
bool first = false;
if (currentFlight == null)
{
first = true;
currentFlight = new MapPolyline();
currentFlight.StrokeThickness = 4;
currentFlight.Stroke = new SolidColorBrush(Colors.Magenta);
currentFlight.Locations = new LocationCollection();
myMap.Children.Add(currentFlight);
}
currentFlight.Locations.Add(new Location() { Latitude = latitude, Longitude = longitude });
// make sure it's on top.
if (myMap.Children.IndexOf(currentFlight) < 0)
{
myMap.Children.Add(currentFlight);
}
else if (myMap.Children.IndexOf(currentFlight) != myMap.Children.Count - 1)
{
myMap.Children.Remove(currentFlight);
myMap.Children.Add(currentFlight);
}
if (currentFlight.Locations.Count > 1000)
{
// remove the older points.
currentFlight.Locations.RemoveAt(0);
}
if (first && myMap.Visibility == Visibility.Visible)
{
myMap.SetView(currentFlight.Locations, new Thickness(20.0), 0);
}
}
List<LogEntryGPS> mapData = null;
Pushpin GetOrCreateMapMarker(Location loc)
{
Pushpin mapMarker = null;
foreach (var child in myMap.Children)
{
if (child is Pushpin)
{
mapMarker = (Pushpin)child;
break;
}
}
if (mapMarker == null)
{
mapMarker = new Pushpin();
myMap.Children.Add(mapMarker);
}
mapMarker.Location = loc;
return mapMarker;
}
void ShowMap()
{
myMap.Children.Clear();
List<Flight> selected = GetSelectedFlights();
if (selected.Count == 0)
{
// show everything.
selected.Add(new Flight() { StartTime = DateTime.MinValue, Duration = TimeSpan.MaxValue });
}
mapData = new List<Utilities.LogEntryGPS>();
var glitchIcon = XamlExtensions.LoadImageResource("Assets.GpsGlitchIcon.png");
var imageLayer = new MapLayer();
myMap.Children.Add(imageLayer);
MapPolyline last = currentFlight;
foreach (IDataLog log in this.logs)
{
if (log != null)
{
bool gpsIsBad = false;
foreach (var flight in selected)
{
if (flight.Log == null || flight.Log == log)
{
MapPolyline line = new MapPolyline();
line.StrokeLineJoin = PenLineJoin.Round;
line.StrokeThickness = 4;
line.Stroke = new SolidColorBrush(GetRandomColor());
LocationCollection points = new LocationCollection();
mappedLogEntries = new List<Model.LogEntry>();
//Debug.WriteLine("time,\t\tlat,\t\tlong,\t\t\tnsat,\talt,\thdop,\tfix");
foreach (var row in log.GetRows("GPS", flight.StartTime, flight.Duration))
{
LogEntryGPS gps = new LogEntryGPS(row);
//Debug.WriteLine("{0},\t{1},\t{2},\t{3},\t\t{4:F2},\t{5},\t{6}", gps.GPSTime, gps.Lat, gps.Lon, gps.nSat, gps.Alt, gps.EPH, gps.Fix);
if (!(Math.Floor(gps.Lat) == 0 && Math.Floor(gps.Lon) == 0))
{
// map doesn't like negative altitudes.
double alt = gps.Alt;
if (alt < 0)
{
alt = 0;
}
mapData.Add(gps);
mappedLogEntries.Add(row);
var pos = new Location() { Altitude = alt, Latitude = gps.Lat, Longitude = gps.Lon };
points.Add(pos);
ulong time = (ulong)gps.GPSTime;
if (time != 0)
{
if ((gps.nSat < 5 || gps.EPH > 20))
{
if (!gpsIsBad)
{
gpsIsBad = true;
//Debug.WriteLine("{0},\t{1},\t{2},\t{3},\t\t{4:F2},\t{5},\t{6}", gps.GPSTime, gps.Lat, gps.Lon, gps.nSat, gps.Alt, gps.EPH, gps.Fix);
Image img = new Image();
img.Width = 30;
img.Height = 30;
img.Source = glitchIcon;
img.Stretch = Stretch.None;
img.ToolTip = "GPS Glitch!";
imageLayer.AddChild(img, pos, PositionOrigin.Center);
}
}
else
{
gpsIsBad = false;
}
}
}
}
if (points.Count > 0)
{
line.Locations = points;
myMap.Children.Add(line);
last = line;
}
}
}
}
}
// hide the stuff on top...
QuadButton.IsChecked = false;
ConsoleButton.IsChecked = false;
SystemConsole.Hide();
ChartStack.Visibility = Visibility.Collapsed;
myMap.Visibility = Visibility.Visible;
myMap.UpdateLayout();
if (last != null)
{
try
{
myMap.SetView(last.Locations, new Thickness(20.0), 0);
}
catch (Exception ex)
{
ShowStatus(ex.Message);
}
}
}
private LocationCollection GetBoundingBox(LocationCollection locations)
{
if (locations.Count == 0)
{
throw new Exception("Must provide at least one location");
}
Location first = locations.First();
double minLat = first.Latitude;
double maxLat = first.Latitude;
double minlong = first.Longitude;
double maxLong = first.Longitude;
foreach (Location i in locations)
{
minLat = Math.Min(minLat, i.Latitude);
maxLat = Math.Max(maxLat, i.Latitude);
minlong = Math.Min(minlong, i.Longitude);
maxLong = Math.Max(maxLong, i.Longitude);
}
var corners = new LocationCollection();
corners.Add(new Location(minLat, minlong));
corners.Add(new Location(minLat, minlong ));
corners.Add(new Location(minLat, minlong ));
corners.Add(new Location(minLat, minlong ));
return corners;
}
private void UpdateButtons()
{
UiDispatcher.RunOnUIThread(() =>
{
ShowMapButton.Visibility = Visibility.Visible;
});
}
HashSet<ListView> childLists = new HashSet<ListView>();
private void OnChildListItemSelected(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems != null && e.AddedItems.Count > 0 && e.OriginalSource == sender)
{
childLists.Add((ListView)sender);
LogItemSchema item = (LogItemSchema)e.AddedItems[0];
GraphItem(item);
}
}
IEnumerable<DataValue> GetSelectedDataValues(LogItemSchema schema)
{
List<Flight> selected = GetSelectedFlights();
bool everything = false;
if (selected.Count == 0)
{
// show everything.
everything = true;
selected.Add(new Flight() { StartTime = DateTime.MinValue, Duration = TimeSpan.MaxValue });
}
foreach (IDataLog log in this.logs)
{
if (log != null)
{
foreach (var flight in selected)
{
if (flight.Log == null || flight.Log == log)
{
foreach (var dv in log.GetDataValues(schema, flight.StartTime, flight.Duration))
{
yield return dv;
}
}
}
if (everything)
{
// the first Log contains everything, subsequent logs are the separate flights found.
break;
}
}
}
}
Thickness defaultChartMargin = new Thickness(0, 10, 0, 10);
Color GetRandomColor()
{
return new HlsColor((float)(rand.NextDouble() * 360), 0.85f, 0.85f).Color;
}
Random rand = new Random();
SimpleLineChart AddChart(LogItemSchema schema, IEnumerable<DataValue> values)
{
SimpleLineChart chart = new SimpleLineChart();
chart.ChartGenerated += OnNewChartGenerated;
chart.ClearAllAdornments += OnClearAllAdornments;
chart.DisplayMessage += OnShowMessage;
chart.PointerMoved += OnPointerMoved;
chart.Margin = defaultChartMargin;
chart.Focusable = false;
chart.Closed += OnChartClosed;
chart.LineColor = GetRandomColor();
chart.StrokeThickness = 1;
chart.Tag = schema;
InitializeChartData(schema, chart, values);
if (chart != null)
{
if (chartGroup != null)
{
chartGroup.AddChart(chart);
if (chartGroup.Parent == null)
{
ChartStack.AddChartGroup(chartGroup);
}
}
else
{
ChartStack.AddChart(chart);
}
LayoutCharts();
}
return chart;
}
private void OnPointerMoved(object sender, DataValue data)
{
if (data != null && mapData != null && myMap.Visibility == Visibility.Visible)
{
double time = data.X;
double dist = double.MaxValue;
int closest = 0;
int i = 0;
LogEntryGPS gps = null;
// find matching gps location in time.
foreach (var item in mapData)
{
double t = item.Timestamp;
double d = Math.Abs((double)(t - time));
if (dist == ulong.MaxValue || d < dist)
{
gps = item;
dist = d;
closest = i;
}
i++;
}
GetOrCreateMapMarker(new Location(gps.Lat, gps.Lon, gps.Alt));
}
}
private void OnShowMessage(object sender, string message)
{
SystemConsole.Write(message);
ConsoleButton.IsChecked = true;
SystemConsole.Show();
}
private void GraphItem(LogItemSchema schema)
{
if (schema.IsNumeric)
{
ChartStack.Visibility = Visibility.Visible;
ChartStack.UpdateLayout();
SimpleLineChart chart = null;
if (currentFlightLog != null && schema.Root == currentFlightLog.Schema)
{
List<DataValue> values = new List<DataValue>(currentFlightLog.GetDataValues(schema, DateTime.MinValue, TimeSpan.MaxValue));
chart = AddChart(schema, values);
if (!pauseRecording)
{
// now turn on live scrolling if we are recording...
chart.LiveScrolling = true;
// the X values are in microseconds (s0 the numerator is the speed of scrolling).
chart.LiveScrollingXScale = 50.0 / 1000000.0;
}
liveScrolling.Add(chart);
// now start watching the live update for new values that need to be added to this chart.
Task.Run(() =>
{
LiveUpdate(chart, currentFlightLog, schema);
});
}
else
{
var data = GetSelectedDataValues(schema);
if (data.Any())
{
chart = AddChart(schema, data);
}
ShowStatus(string.Format("Found {0} data values", data.Count()));
}
ConsoleButton.IsChecked = false;
SystemConsole.Hide();
}
else
{
StringBuilder sb = new StringBuilder();
string previous = null;
List<DataValue> unique = new List<Model.DataValue>();
foreach (var value in GetSelectedDataValues(schema))
{
if (!string.IsNullOrEmpty(value.Label))
{
if (previous != value.Label)
{
unique.Add(value);
sb.Append(((ulong)value.X).ToString());
sb.Append(": ");
sb.AppendLine(value.Label);
previous = value.Label;
}
}
}
SystemConsole.Write(sb.ToString());
ConsoleButton.IsChecked = true;
SystemConsole.Show();
}
}
private void AnnotateMap(LogItemSchema schema)
{
List<DataValue> unique = new List<Model.DataValue>();
if (schema.IsNumeric)
{
var data = GetSelectedDataValues(schema);
ShowStatus(string.Format("Found {0} data values", data.Count()));
if (data.Count() > 0)
{
double previous = 0;
{
// uniquify it.
foreach (var value in data)
{
if (value.Y != previous)
{
unique.Add(value);
previous = value.Y;
}
}
}
}
}
else
{
StringBuilder sb = new StringBuilder();
string previous = null;
foreach (var value in GetSelectedDataValues(schema))
{
if (!string.IsNullOrEmpty(value.Label))
{
if (previous != value.Label)
{
unique.Add(value);
sb.Append(value.X.ToString());
sb.Append(": ");
sb.AppendLine(value.Label);
previous = value.Label;
}
}
}
}
// if there are too many values, then limit it to an even spread of 100 items.
if (unique.Count > 100)
{
var summary = new List<Model.DataValue>();
double skip = (unique.Count / 100);
for (int i = 0, n = unique.Count; i < n; i++)
{
var value = unique[i];
if (i >= summary.Count * unique.Count / 100)
{
summary.Add(value);
}
}
unique = summary;
}
AnnotateMap(unique);
}
private void AnnotateMap(List<DataValue> unique)
{
if (this.mappedLogEntries == null || this.mappedLogEntries.Count == 0)
{
ShowMap();
}
if (this.mappedLogEntries == null || this.mappedLogEntries.Count == 0)
{
MessageBox.Show("Sorry, could not find GPS map info, so cannot annotate data on the map",
"GPS info is missing", MessageBoxButton.OK, MessageBoxImage.Exclamation);
return;
}
if (annotationLayer != null)
{
myMap.Children.Remove(annotationLayer);
}
annotationLayer = new MapLayer();
SolidColorBrush annotationBrush = new SolidColorBrush(Color.FromArgb(0x80, 0xff, 0xff, 0xB0));
foreach (var dv in unique)
{
LogEntry closest = null;
LogField field = dv.UserData as LogField;
if (field != null)
{
// csv log
LogEntry e = field.Parent;
closest = FindNearestMappedItem(e.Timestamp);
}
else
{
// px4 log?
Message msg = dv.UserData as Message;
if (msg != null)
{
closest = FindNearestMappedItem(msg.GetTimestamp());
}
else
{
// mavlink
MavlinkLog.Message mavmsg = dv.UserData as MavlinkLog.Message;
if (mavmsg != null)
{
closest = FindNearestMappedItem(mavmsg.Timestamp.Ticks / 10);
}
}
}
if (closest != null)
{
LogEntryGPS gps = new LogEntryGPS(closest);
// map doesn't like negative altitudes.
double alt = gps.Alt;
if (alt < 0)
{
alt = 0;
}
var pos = new Location() { Altitude = alt, Latitude = gps.Lat, Longitude = gps.Lon };
string label = dv.Label;
if (string.IsNullOrEmpty(label))
{
label = dv.Y.ToString();
}
annotationLayer.AddChild(new TextBlock(new Run(label) { Background = annotationBrush }), pos, PositionOrigin.BottomLeft);
}
}
myMap.Children.Add(annotationLayer);
SystemConsole.Hide();
ChartStack.Visibility = Visibility.Collapsed;
myMap.Visibility = Visibility.Visible;
myMap.UpdateLayout();
}
private LogEntry FindNearestMappedItem(double t)
{
LogEntry closest = null;
double bestDiff = 0;
// find nearest mapped location (nearest in time).
foreach (var mapped in this.mappedLogEntries)
{
var time = mapped.Timestamp;
var diff = Math.Abs((double)time - t);
if (closest == null || diff < bestDiff)
{
closest = mapped;
bestDiff = diff;
}
}
return closest;
}
private void OnNewChartGenerated(object sender, List<DataValue> e)
{
SimpleLineChart chart = (SimpleLineChart)sender;
AddChart((LogItemSchema)chart.Tag, e);
}
private void OnClearAllAdornments(object sender, EventArgs e)
{
foreach (var chart in ChartStack.FindCharts())
{
chart.ClearAdornments();
}
}
private void InitializeChartData(LogItemSchema schema, SimpleLineChart chart, IEnumerable<DataValue> values)
{
chart.SetData(new Model.DataSeries()
{
Name = schema.GetFullName(),
Values = new List<DataValue>(values)
});
}
private void LiveUpdate(SimpleLineChart chart, MavlinkLog currentFlightLog, LogItemSchema schema)
{
// this method is running on a background task and it's job is to read an infinite stream of
// data values from the log and show them in the live scrolling chart.
CancellationTokenSource canceller = new CancellationTokenSource();
chart.Closed += (s, e) =>
{
canceller.Cancel();
};
var query = currentFlightLog.LiveQuery(schema, canceller.Token);
foreach (DataValue item in query)
{
if (item == null)
{
return;
}
chart.SetCurrentValue(item);
}
chart.Closed += (sender, e) =>
{
canceller.Cancel();
};
Debug.WriteLine("LiveUpdate terminating on schema item " + schema.Name);
}
private void LayoutCharts()
{
// layout charts to fill the space available.
ChartStack.UpdateLayout();
double height = ChartStack.ActualHeight;
double count = ChartStack.ChartCount;
height -= (count * (defaultChartMargin.Top + defaultChartMargin.Bottom)); // remove margins
if (height < 0)
{
height = 0;
}
double chartHeight = Math.Min(MaxChartHeight, height / count);
bool found = false;
foreach (FrameworkElement c in ChartStack.Charts)
{
found = true;
c.Height = chartHeight;
}
// give all the charts the same min/max on the X dimension so that the charts are in sync (even when they are not grouped).
//ChartScaleInfo combined = null;
//foreach (SimpleLineChart chart in ChartStack.FindCharts())
//{
// var info = chart.ComputeScaleSelf();
// if (combined == null)
// {
// combined = info;
// }
// else
// {
// combined.Combine(info);
// }
//}
//// now set the min/max on each chart.
//foreach (SimpleLineChart chart in ChartStack.FindCharts())
//{
// chart.FixMinimumX = combined.minX;
// chart.FixMaximumX = combined.maxX;
// chart.InvalidateArrange();
//}
if (!found)
{
ChartStack.Visibility = Visibility.Collapsed;
}
}
private void OnChartClosed(object sender, EventArgs e)
{
SimpleLineChart chart = sender as SimpleLineChart;
ChartStack.RemoveChart(chart);
chart.LiveScrolling = false;
liveScrolling.Remove(chart);
LayoutCharts();
LogItemSchema item = (chart.Tag as LogItemSchema);
if (item != null)
{
UnselectCategory(item);
}
}
private void UnselectCategory(LogItemSchema item)
{
if (CategoryList.SelectedItems.Contains(item))
{
CategoryList.SelectedItems.Remove(item);
}
else
{
// might be a child category item...
foreach (var childList in childLists)
{
if (childList.SelectedItems.Contains(item))
{
childList.SelectedItems.Remove(item);
}
}
}
}
private void OnClear(object sender, RoutedEventArgs e)
{
ChartStack.ClearCharts();
liveScrolling.Clear();
logs.Clear();
CategoryList.SelectedItem = null;
allFlights.Clear();
if (currentFlightLog != null)
{
currentFlightLog.Clear();
logs.Add(currentFlightLog);
}
if (currentFlight != null)
{
currentFlight.Locations = new LocationCollection();
}
SystemConsole.Clear();
myMap.Children.Clear();
ImageViewer.Source = null;
ShowSchema();
UpdateTitle("");
}
private void OnFlightSelected(object sender, SelectionChangedEventArgs e)
{
UiDispatcher.RunOnUIThread(() =>
{
if (myMap.Visibility == Visibility.Visible)
{
ShowMap();
}
else
{
// todo: show sensor data pruned to this flight time...
foreach (LogItemSchema item in CategoryList.SelectedItems)
{
if (!item.HasChildren)
{
GraphItem(item);
}
}
}
});
}
private void OnFlightViewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
// remove this flight.
}
}
private void OnItemExpanded(object sender, RoutedEventArgs e)
{
Expander expander = (Expander)sender;
ListView childView = expander.Content as ListView;
if (childView != null && childView.ItemsSource == null)
{
LogItemSchema item = (LogItemSchema)expander.DataContext;
List<LogItemSchema> list = item.CopyChildren();
if (!item.IsArray)
{
list.Sort((a, b) => { return string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); });
}
childView.ItemsSource = list;
}
}
private void OnItemCollapsed(object sender, RoutedEventArgs e)
{
Expander expander = (Expander)sender;
Expander source = e.OriginalSource as Expander;
if (source != null && source != expander)
{
// bugbug: for some reason WPF also sends collapse event to all the parents
// but we want to ignore those.
return;
}
ListView childView = expander.Content as ListView;
if (childView != null)
{
childView.ItemsSource = null;
}
// todo: remove the graphs...
}
ChartGroup chartGroup;
private void OnGroupChecked(object sender, RoutedEventArgs e)
{
chartGroup = new ChartGroup() { HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch };
}
private void OnGroupUnchecked(object sender, RoutedEventArgs e)
{
chartGroup = null;
}
private void OnClearZoom(object sender, RoutedEventArgs e)
{
ChartStack.ResetZoom();
}
private void OnConnectorClick(object sender, MouseButtonEventArgs e)
{
ConnectionPanel.Start();
XamlExtensions.Flyout(ConnectionPanel);
}
private void OnOpenFileCommand(object sender, ExecutedRoutedEventArgs e)
{
OnOpenFile(sender, e);
}
private void OnShowQuad(object sender, RoutedEventArgs e)
{
ModelViewer.Visibility = Visibility.Visible;
ConsoleButton.IsChecked = false;
SendMessage(MAVLink.MAVLINK_MSG_ID.COMMAND_LONG,
new MAVLink.mavlink_command_long_t()
{
command = (ushort)MAVLink.MAV_CMD.SET_MESSAGE_INTERVAL,
param1 = (float)MAVLink.MAVLINK_MSG_ID.ATTITUDE_QUATERNION,
param2 = 50000
}
);
}
private void OnHideQuad(object sender, RoutedEventArgs e)
{
ModelViewer.Visibility = Visibility.Collapsed;
SendMessage(MAVLink.MAVLINK_MSG_ID.COMMAND_LONG,
new MAVLink.mavlink_command_long_t()
{
command = (ushort)MAVLink.MAV_CMD.SET_MESSAGE_INTERVAL,
param1 = (float)MAVLink.MAVLINK_MSG_ID.ATTITUDE_QUATERNION,
param2 = 500000
}
);
}
private void OnRecord(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
if (button.Tag != null)
{
// paused
button.Content = button.Tag;
button.Tag = null;
StopRecording();
}
else
{
// start recording.
button.Tag = button.Content;
button.Content = "\ue15b";
StartRecording();
}
}
void StartRecording()
{
if (currentFlightLog == null)
{
currentFlightLog = new MavlinkLog();
currentFlightLog.SchemaChanged += (s, args) =>
{
ShowSchema();
};
}
pauseRecording = false;
foreach (var chart in liveScrolling)
{
chart.LiveScrolling = true;
// the X values are in milliseconds (s0 the numerator is the speed of scrolling).
chart.LiveScrollingXScale = 5.0 / 1000.0;
}
}
bool pauseRecording;
List<SimpleLineChart> liveScrolling = new List<SimpleLineChart>();
void StopRecording()
{
pauseRecording = true;
foreach (var chart in liveScrolling)
{
chart.LiveScrolling = false;
}
}
private void OnShowCamera(object sender, RoutedEventArgs e)
{
CameraPanel.Visibility = Visibility.Visible;
showImageStream = true;
}
private void OnHideCamera(object sender, RoutedEventArgs e)
{
showImageStream = false;
CameraPanel.Visibility = Visibility.Collapsed;
}
private void ShowImageStream()
{
// show encapsulated data
}
bool showImageStream;
struct IncomingImage
{
public uint size; // Image size being transmitted (bytes)
public int packets; // Number of data packets being sent for this image
public int packetsArrived; // Number of data packets received
public int payload; // Payload size per transmitted packet (bytes). Standard is 254, and decreases when image resolution increases.
public int quality; // Quality of the transmitted image (percentage)
public int type; // Type of the transmitted image (BMP, PNG, JPEG, RAW 8 bit, RAW 32 bit)
public int width; // Width of the image stream
public int height; // Width of the image stream
public byte[] data; // Buffer for the incoming bytestream
public long start; // Time when we started receiving data
};
IncomingImage incoming_image = new IncomingImage();
public LogItemSchema rightClickedItem { get; private set; }
private void OnShowConsole(object sender, RoutedEventArgs e)
{
SystemConsole.Show();
}
#region System Console
private void OnHideConsole(object sender, RoutedEventArgs e)
{
SystemConsole.Hide();
}
void SendMessage(MAVLink.MAVLINK_MSG_ID id, object mavlinkPayload)
{
var channel = ConnectionPanel.Channel;
if (channel != null)
{
MavLinkMessage message = new MavLinkMessage();
message.ComponentId = (byte)MAVLink.MAV_COMPONENT.MAV_COMP_ID_MISSIONPLANNER;
message.SystemId = 255;
message.MsgId = id;
message.TypedPayload = mavlinkPayload;
channel.SendMessage(message);
}
}
#endregion
private void OnSettings(object sender, RoutedEventArgs e)
{
XamlExtensions.Flyout(AppSettingsPanel);
}
private void OnMapTest(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog fo = new Microsoft.Win32.OpenFileDialog();
fo.Filter = "CSV Files (*.csv)|*.csv";
fo.CheckFileExists = true;
fo.Multiselect = false;
if (fo.ShowDialog() == true)
{
LoadMapData(fo.FileName);
}
}
private void LoadMapData(string fileName)
{
// turn data into two lookup tables for easy access.
double[,] xmag = new double[180,360];
double[,] ymag = new double[180, 360];
using (StreamReader reader = new StreamReader(fileName))
{
string line = reader.ReadLine();
while (line != null)
{
string[] parts = line.Split('\t');
if (parts.Length == 5)
{
double lat, lon, x, y;
if (double.TryParse(parts[0], out lat))
{
lon = double.Parse(parts[1]);
x = double.Parse(parts[2]);
y = double.Parse(parts[3]);
lat += 90;
lon += 180;
xmag[(int)lat, (int)lon] = x;
ymag[(int)lat, (int)lon] = y;
}
}
line = reader.ReadLine();
}
}
DrawVectors(xmag, ymag);
}
class LocationComparer : IEqualityComparer<Location>
{
public bool Equals(Location x, Location y)
{
return x.Altitude == y.Altitude && x.Latitude == y.Latitude && x.Longitude == y.Longitude;
}
public int GetHashCode(Location obj)
{
return (int)(obj.Altitude + obj.Latitude + obj.Longitude);
}
}
private void DrawVectors(double[,] xmag, double[,] ymag)
{
// find guassian lines in the map and draw them so it looks like this:
// https://www.ngdc.noaa.gov/geomag/WMM/data/WMM2015/WMM2015_D_MERC.pdf
for (int i = 0; i < 180; i++)
{
for (int j = 0; j < 360; j++)
{
double x = xmag[i, j];
double y = ymag[i, j];
double latitude = i - 90;
double longitude = j - 180;
MapPolyline line = new MapPolyline();
line.StrokeThickness = 1;
line.Stroke = new SolidColorBrush(Colors.Red);
LocationCollection points = new LocationCollection();
Location pos = new Location() { Altitude = 0, Latitude = latitude, Longitude = longitude };
points.Add(pos);
// ok, we have a winner, pick this one and continue.
pos = new Location() { Latitude = latitude + (x*2), Longitude = longitude + (y*2) };
points.Add(pos);
line.Locations = points;
myMap.Children.Add(line);
}
}
}
private void OnPaste(object sender, ExecutedRoutedEventArgs e)
{
if (Clipboard.ContainsImage())
{
var image = Clipboard.GetImage();
ImageViewer.Source = image;
CameraPanel.Visibility = Visibility.Visible;
}
}
private void OnAnnotateItem(object sender, RoutedEventArgs e)
{
LogItemSchema item = this.rightClickedItem;
if (item != null)
{
AnnotateMap(item);
}
}
private void OnRightClickCategoryList(object sender, MouseButtonEventArgs e)
{
this.rightClickedItem = null;
Point pos = e.GetPosition(CategoryList);
DependencyObject dep = (DependencyObject)e.OriginalSource;
while ((dep != null) && !(dep is ListViewItem))
{
dep = VisualTreeHelper.GetParent(dep);
}
if (dep == null)
return;
ListViewItem listitem = (ListViewItem)dep;
LogItemSchema item = listitem.DataContext as LogItemSchema;
this.rightClickedItem = item;
}
}
}
| AirSim/LogViewer/LogViewer/MainWindow.xaml.cs/0 | {
"file_path": "AirSim/LogViewer/LogViewer/MainWindow.xaml.cs",
"repo_id": "AirSim",
"token_count": 38278
} | 23 |
using System;
using System.Windows.Media;
namespace LogViewer.Utilities
{
/// <summary>
/// Helper extensions for manipulating colors.
/// </summary>
public static class ColorExtensions
{
public static int GetBrightness(this Color color)
{
return ((color.R * 299) + (color.G * 587) + (color.B * 114)) / 1000;
}
public static int GetDifference(this Color color1, Color color2)
{
return Math.Abs(color1.R - color2.R) + Math.Abs(color1.G - color2.G) + Math.Abs(color1.B - color2.B);
}
public static bool HasGoodContrast(this Color color1, Color color2)
{
int b1 = color1.GetBrightness();
int b2 = color2.GetBrightness();
return (Math.Abs(b2 - b1) > 125 && color1.GetDifference(color2) > 400);
}
public static bool HasReasonableContrast(this Color color1, Color color2)
{
int b1 = color1.GetBrightness();
int b2 = color2.GetBrightness();
return (Math.Abs(b2 - b1) > 50 && color1.GetDifference(color2) > 100);
}
/// <summary>
/// Augment or reduce the Byte (RGB) by half of the delta between the Source and the target
/// </summary>
/// <param name="colorToken">Byte to start from</param>
/// <param name="colorTargetToken">Byte to tareget</param>
/// <returns>new byte value</returns>
private static byte DeltaColorToken(int colorToken, int colorTargetToken)
{
if (colorToken == colorTargetToken)
{
return (byte)colorToken;
}
if (colorToken > colorTargetToken)
{
int delta = colorToken - colorTargetToken;
return (byte)Math.Max(0, colorToken - (delta / 2));
}
else
{
int delta = colorTargetToken - colorToken;
return (byte)Math.Min(255, colorToken + (delta / 2));
}
}
/// <summary>
/// Bring a color closer to another color
/// </summary>
/// <param name="color1">color to move</param>
/// <param name="targetColor">targeted color</param>
/// <returns>new color</returns>
public static Color Interpolate(this Color color1, Color targetColor)
{
Color toReturn = color1;
toReturn.A = DeltaColorToken(toReturn.A, targetColor.A);
toReturn.R = DeltaColorToken(toReturn.R, targetColor.R);
toReturn.G = DeltaColorToken(toReturn.G, targetColor.G);
toReturn.B = DeltaColorToken(toReturn.B, targetColor.B);
return toReturn;
}
/// <summary>
/// Interpolate the color that is at the given target offset
/// </summary>
/// <param name="color1">The first color</param>
/// <param name="offset1">The position of the first color as a number between 0 and 1</param>
/// <param name="color2">The second color</param>
/// <param name="offset2">The position of the second color as a number between 0 and 1</param>
/// <param name="targetOffset">The target position we are trying to interpolate as a number between 0 and 1</param>
/// <returns>The color at the target offset</returns>
public static Color LinearInterpolate(this Color color1, double offset1, Color color2, double offset2, double targetOffset)
{
if (offset1 < 0 || offset1 > 1)
{
throw new ArgumentOutOfRangeException("offset1");
}
if (offset2 < 0 || offset2 > 1)
{
throw new ArgumentOutOfRangeException("offset1");
}
if (targetOffset < 0 || targetOffset > 1)
{
throw new ArgumentOutOfRangeException("offset1");
}
if (offset1 == offset2) return color1;
return Color.FromArgb((byte)LinearInterpolation(offset1, color1.A, offset2, color2.A, targetOffset),
(byte)LinearInterpolation(offset1, color1.R, offset2, color2.R, targetOffset),
(byte)LinearInterpolation(offset1, color1.G, offset2, color2.G, targetOffset),
(byte)LinearInterpolation(offset1, color1.B, offset2, color2.B, targetOffset));
}
/// <summary>
/// Get the contrast color for the given foreground and background colors
/// </summary>
/// <param name="foreground">The foreground color</param>
/// <param name="background">The background color</param>
/// <param name="alpha">The alpha-channel value to adjust the opacity of the resulting color</param>
/// <param name="lessStrict">Use less strict contrast setting</param>
/// <returns></returns>
public static Color GetContrastColor(this Color foreground, Color background, byte alpha, bool lessStrict = false)
{
Color result;
if (!foreground.HasReasonableContrast(background) ||
(!lessStrict && !foreground.HasGoodContrast(background)))
{
// pick white or black, whichever one has the greatest difference.
if (Colors.White.GetDifference(background) > Colors.Black.GetDifference(background))
{
result = Colors.White;
}
else
{
result = Colors.Black;
}
}
else
{
result = foreground;
}
// Adjust the alpha-channel (transparency) if necessary
if (result.A != alpha)
result.A = alpha;
return result;
}
/// <summary>
/// This method is similar to GetContrastColor, only it is less aggressive, it allows the
/// colors to get a bit closer before resorting to switching colors.
/// </summary>
/// <returns></returns>
public static Color GetReasonableContrastColor(this Color foreground, Color background)
{
// Now check the contrast.
if (!foreground.HasReasonableContrast(background))
{
// pick white or black, whichever one has the greatest difference.
if (Colors.White.GetDifference(background) > Colors.Black.GetDifference(background))
{
return Colors.White;
}
else
{
return Colors.Black;
}
}
return foreground;
}
/// <summary>
/// Interpolate the position on a line.
/// </summary>
/// <param name="x1">The first x coordinate</param>
/// <param name="y1">The first y coordinate</param>
/// <param name="x2">The second x coordinate</param>
/// <param name="y2">The second y coordinate</param>
/// <param name="x3">The third x coordinate</param>
/// <returns>return the value y3</returns>
private static double LinearInterpolation(double x1, double y1, double x2, double y2, double x3)
{
// horizontal line.
if (y1 == y2) return y1;
if (x2 == x1) return (y1 + y2) / 2;
// y = a + b.x
double b = (y2 - y1) / (x2 - x1);
double a = y1 - (b * x1);
return a + (b * x3);
}
}
}
| AirSim/LogViewer/LogViewer/Utilities/ColorExtensions.cs/0 | {
"file_path": "AirSim/LogViewer/LogViewer/Utilities/ColorExtensions.cs",
"repo_id": "AirSim",
"token_count": 3437
} | 24 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Networking.Mavlink
{
public class MavLinkMessage
{
public const byte Mavlink1Stx = 254;
public const byte Mavlink2Stx = 253;
public byte Magic { get; set; }
public byte Length { get; set; }
public byte IncompatFlags { get; set; } // flags that must be understood
public byte CompatFlags { get; set; } // flags that can be ignored if not understood
public byte SequenceNumber { get; set; }
public byte SystemId { get; set; }
public byte ComponentId { get; set; }
public MAVLink.MAVLINK_MSG_ID MsgId { get; set; }
public ushort Crc { get; set; }
public UInt64 Time { get; set; }
public byte[] Payload { get; set; }
public byte[] Signature { get; set; }
public byte ProtocolVersion { get; set; }
public object TypedPayload { get; set; }
public override string ToString()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this);
}
public byte[] Pack()
{
const byte MAVLINK_STX = 254;
Serialize();
int length = Payload.Length;
if (length + 7 > 255)
{
throw new Exception("Message is too long. Must be less than 248 bytes");
}
byte[] fullMessage = new byte[length + 8];
fullMessage[0] = MAVLINK_STX; // magic marker
fullMessage[1] = (byte)length;
fullMessage[2] = this.SequenceNumber;
fullMessage[3] = this.SystemId;
fullMessage[4] = this.ComponentId;
fullMessage[5] = (byte)this.MsgId;
Array.Copy(Payload, 0, fullMessage, 6, length);
this.Crc = crc_calculate();
fullMessage[6 + length] = (byte)(this.Crc);
fullMessage[6 + length + 1] = (byte)(this.Crc >> 8);
return fullMessage;
}
const int MAVLINK_STX_MAVLINK1 = 0xFE;
public void ReadHeader(BinaryReader reader)
{
ulong time = reader.ReadUInt64();
time = ConvertBigEndian(time);
byte magic = reader.ReadByte();
byte len = reader.ReadByte();
while (true)
{
// 253 for Mavlink 2.0.
if ((magic == 254 || magic == 253) && len <= 255)
{
// looks good.
break;
}
// shift to next byte looking for valid header
time = (time << 8);
time += magic;
magic = len;
len = reader.ReadByte();
}
Time = time;
Magic = magic;
Length = len;
SequenceNumber = reader.ReadByte();
SystemId = reader.ReadByte();
ComponentId = reader.ReadByte();
if (Magic == MAVLINK_STX_MAVLINK1)
{
MsgId = (MAVLink.MAVLINK_MSG_ID)reader.ReadByte();
}
else
{
// 24 bits
int a = reader.ReadByte();
int b = reader.ReadByte();
int c = reader.ReadByte();
MsgId = (MAVLink.MAVLINK_MSG_ID)(a + (b << 8) + (c << 16));
}
}
private ulong ConvertBigEndian(ulong v)
{
ulong result = 0;
ulong shift = v;
for (int i = 0; i < 8; i++)
{
ulong low = (shift & 0xff);
result = (result << 8) + low;
shift >>= 8;
}
return result;
}
public bool IsValidCrc(byte[] msg, int len)
{
ushort crc = crc_calculate(msg, len);
return crc == this.Crc;
}
public ushort crc_calculate()
{
return crc_calculate(this.Payload, this.Payload.Length);
}
private ushort crc_calculate(byte[] buffer, int len)
{
int msgid = (int)this.MsgId;
byte crc_extra = 0;
if (msgid < MAVLink.MAVLINK_MESSAGE_CRCS.Length)
{
crc_extra = MAVLink.MAVLINK_MESSAGE_CRCS[msgid];
}
ushort crcTmp = 0xffff; // X25_INIT_CRC;
// Start with the MAVLINK_CORE_HEADER_LEN bytes.
crcTmp = crc_accumulate((byte)this.Length, crcTmp);
if (this.Magic == MavLinkMessage.Mavlink2Stx)
{
crcTmp = crc_accumulate((byte)this.IncompatFlags, crcTmp);
crcTmp = crc_accumulate((byte)this.CompatFlags, crcTmp);
}
crcTmp = crc_accumulate((byte)this.SequenceNumber, crcTmp);
crcTmp = crc_accumulate((byte)this.SystemId, crcTmp);
crcTmp = crc_accumulate((byte)this.ComponentId, crcTmp);
crcTmp = crc_accumulate((byte)this.MsgId, crcTmp);
if (this.Magic == MavLinkMessage.Mavlink2Stx)
{
byte b = (byte)((uint)this.MsgId >> 8);
crcTmp = crc_accumulate(b, crcTmp);
b = (byte)((uint)this.MsgId >> 16);
crcTmp = crc_accumulate(b, crcTmp);
}
crcTmp = crc_accumulate(buffer, len, crcTmp);
return crc_accumulate(crc_extra, crcTmp);
}
static ushort crc_accumulate(byte[] msg, int len, ushort crcTmp)
{
for (int i = 0; i < len; i++)
{
crcTmp = crc_accumulate(msg[i], crcTmp);
}
return crcTmp;
}
static ushort crc_accumulate(byte data, ushort crcAccum)
{
/*Accumulate one byte of data into the CRC*/
byte tmp;
tmp = (byte)(data ^ (byte)(crcAccum & 0xff));
tmp ^= (byte)(tmp << 4);
return (ushort)((crcAccum >> 8) ^ (tmp << 8) ^ (tmp << 3) ^ (tmp >> 4));
}
public static Type GetMavlinkType(uint msgid)
{
if (msgid < MAVLink.MAVLINK_MESSAGE_INFO.Length)
{
return MAVLink.MAVLINK_MESSAGE_INFO[msgid];
}
return null;
}
public void Deserialize()
{
GCHandle handle = GCHandle.Alloc(this.Payload, GCHandleType.Pinned);
IntPtr ptr = handle.AddrOfPinnedObject();
var msgType = GetMavlinkType((uint)this.MsgId);
if (msgType != null)
{
object typed = Marshal.PtrToStructure(ptr, msgType);
this.TypedPayload = typed;
if (typed != null && typed.GetType() == typeof(MAVLink.mavlink_statustext_t))
{
// convert the byte[] text to something readable.
MAVLink.mavlink_statustext_t s = (MAVLink.mavlink_statustext_t)typed;
mavlink_statustext_t2 t2 = new mavlink_statustext_t2(s);
this.TypedPayload = t2;
}
}
}
internal void Serialize()
{
if (this.TypedPayload != null && this.Payload == null)
{
int size = Marshal.SizeOf(this.TypedPayload);
IntPtr ptr = Marshal.AllocCoTaskMem(size);
Marshal.StructureToPtr(this.TypedPayload, ptr, false);
byte[] block = new byte[size];
Marshal.Copy(ptr, block, 0, size);
Marshal.FreeCoTaskMem(ptr);
this.Payload = block;
this.Length = (byte)block.Length;
}
}
}
public class MavlinkChannel
{
IPort port;
byte seqno;
public MavlinkChannel()
{
// plug in our custom mavlink_simulator_telemetry message
int id = MAVLink.mavlink_telemetry.MessageId;
Type info = MavLinkMessage.GetMavlinkType((uint)id);
if (info != null && typeof(MAVLink.mavlink_telemetry) != info)
{
throw new Exception("The custom messageid " + id + " is already defined, so we can't use it for mavlink_simulator_telemetry");
}
else
{
MAVLink.MAVLINK_MESSAGE_INFO[id] = typeof(MAVLink.mavlink_telemetry);
}
}
public void Start(IPort port)
{
this.port = port;
Task.Run(() => ReceiveThread());
}
public void Stop()
{
IPort p = this.port;
if (p != null)
{
this.port = null;
p.Close();
}
}
public void SendMessage(MavLinkMessage msg)
{
msg.SequenceNumber = seqno++;
byte[] buffer = msg.Pack();
if (this.port == null)
{
throw new Exception("Please call Start to provide the mavlink Port we are using");
}
this.port.Write(buffer, buffer.Length);
}
public event EventHandler<MavLinkMessage> MessageReceived;
void ReceiveThread()
{
byte[] buffer = new byte[1];
const byte MAVLINK_IFLAG_SIGNED = 0x01;
const int MAVLINK_SIGNATURE_BLOCK_LEN = 13;
MavLinkMessage msg = null;
ReadState state = ReadState.Init;
int payloadPos = 0;
ushort crc = 0;
int signaturePos = 0;
uint msgid = 0;
int msgIdPos = 0;
int MaxPayloadLength = 255;
bool messageComplete = false;
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
try
{
while (this.port != null)
{
int len = this.port.Read(buffer, 1);
if (len == 1)
{
byte b = buffer[0];
switch (state)
{
case ReadState.Init:
if (b == MavLinkMessage.Mavlink1Stx)
{
state = ReadState.GotMagic;
msg = new MavLinkMessage();
msg.Time = (ulong)watch.ElapsedMilliseconds * 1000; // must be in microseconds
msg.Magic = MavLinkMessage.Mavlink1Stx;
payloadPos = 0;
msgIdPos = 0;
msgid = 0;
crc = 0;
messageComplete = false;
}
else if (b == MavLinkMessage.Mavlink2Stx)
{
state = ReadState.GotMagic;
msg = new MavLinkMessage();
msg.Time = (ulong)watch.ElapsedMilliseconds * 1000; // must be in microseconds
msg.Magic = MavLinkMessage.Mavlink2Stx;
payloadPos = 0;
msgIdPos = 0;
msgid = 0;
crc = 0;
messageComplete = false;
}
break;
case ReadState.GotMagic:
if (b > MaxPayloadLength)
{
state = ReadState.Init;
}
else
{
if (msg.Magic == MavLinkMessage.Mavlink1Stx)
{
msg.IncompatFlags = 0;
msg.CompatFlags = 0;
state = ReadState.GotCompatFlags;
}
else
{
msg.Length = b;
msg.Payload = new byte[msg.Length];
state = ReadState.GotLength;
}
}
break;
case ReadState.GotLength:
msg.IncompatFlags = b;
state = ReadState.GotIncompatFlags;
break;
case ReadState.GotIncompatFlags:
msg.CompatFlags = b;
state = ReadState.GotCompatFlags;
break;
case ReadState.GotCompatFlags:
msg.SequenceNumber = b;
state = ReadState.GotSequenceNumber;
break;
case ReadState.GotSequenceNumber:
msg.SystemId = b;
state = ReadState.GotSystemId;
break;
case ReadState.GotSystemId:
msg.ComponentId = b;
state = ReadState.GotComponentId;
break;
case ReadState.GotComponentId:
if (msg.Magic == MavLinkMessage.Mavlink1Stx)
{
msg.MsgId = (MAVLink.MAVLINK_MSG_ID)b;
if (msg.Length == 0)
{
// done!
state = ReadState.GotPayload;
}
else
{
state = ReadState.GotMessageId;
}
}
else
{
// msgid is 24 bits
switch(msgIdPos)
{
case 0:
msgid = b;
break;
case 1:
msgid |= ((uint)b << 8);
break;
case 2:
msgid |= ((uint)b << 16);
msg.MsgId = (MAVLink.MAVLINK_MSG_ID)msgid;
state = ReadState.GotMessageId;
break;
}
msgIdPos++;
}
break;
case ReadState.GotMessageId:
// read in the payload.
msg.Payload[payloadPos++] = b;
if (payloadPos == msg.Length)
{
state = ReadState.GotPayload;
}
break;
case ReadState.GotPayload:
crc = b;
state = ReadState.GotCrc1;
break;
case ReadState.GotCrc1:
crc = (ushort)((b << 8) + crc);
// ok, let's see if it's good.
msg.Crc = crc;
ushort found = crc;
if (msg.Payload != null)
{
found = msg.crc_calculate();
}
if (found != crc && crc != 0)
{
// bad crc!!
// reset for next message.
state = ReadState.Init;
}
else
{
if ((msg.IncompatFlags & MAVLINK_IFLAG_SIGNED) == MAVLINK_IFLAG_SIGNED)
{
signaturePos = 0;
msg.Signature = new byte[MAVLINK_SIGNATURE_BLOCK_LEN];
state = ReadState.GetSignature;
}
else
{
messageComplete = true;
}
}
break;
case ReadState.GetSignature:
msg.Signature[signaturePos++] = b;
if (signaturePos == MAVLINK_SIGNATURE_BLOCK_LEN)
{
// todo: check the signature.
messageComplete = true;
}
break;
}
if (messageComplete)
{
// try and deserialize the payload.
msg.Deserialize();
if (MessageReceived != null)
{
MessageReceived(this, msg);
}
// reset for next message.
state = ReadState.Init;
}
}
}
}
catch (Exception)
{
// port was closed
}
}
enum ReadState
{
Init,
GotMagic,
GotIncompatFlags,
GotCompatFlags,
GotLength,
GotSequenceNumber,
GotSystemId,
GotComponentId,
GotMessageId,
GotPayload,
GotCrc1,
GetSignature
}
}
public struct mavlink_statustext_t2
{
/// <summary> Severity of status. Relies on the definitions within RFC-5424. See enum MAV_SEVERITY. </summary>
public byte severity;
/// <summary> Status text message, without null termination character </summary>
public string text;
public mavlink_statustext_t2(MAVLink.mavlink_statustext_t s)
{
this.severity = s.severity;
this.text = null;
if (s.text != null)
{
int i = 0;
int n = s.text.Length;
for (i = 0; i < n; i++)
{
if (s.text[i] == 0)
{
break;
}
}
this.text = Encoding.UTF8.GetString(s.text, 0, i);
}
}
};
}
| AirSim/LogViewer/Networking/Mavlink/MavlinkChannel.cs/0 | {
"file_path": "AirSim/LogViewer/Networking/Mavlink/MavlinkChannel.cs",
"repo_id": "AirSim",
"token_count": 12942
} | 25 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace MavLinkComGenerator
{
static class MavlinkParser
{
public static MavLink Parse(string xmlFile)
{
using (var fs = new FileStream(xmlFile, FileMode.Open, FileAccess.Read))
{
XmlSerializer s = new XmlSerializer(typeof(MavLink));
MavLink mavlink = (MavLink)s.Deserialize(fs);
// unfortunately the <extensions/> sections in each <message> is not something the XmlSerializer can handle,
// so we have to post-process the MavLink tree with this additional information.
fs.Seek(0, SeekOrigin.Begin);
XDocument doc = XDocument.Load(fs);
foreach (XElement message in doc.Root.Element("messages").Elements("message"))
{
string id = (string)message.Attribute("id");
MavMessage msg = (from m in mavlink.messages where m.id == id select m).FirstOrDefault();
int count = 0;
foreach (XElement child in message.Elements())
{
string childName = child.Name.LocalName;
if (childName == "field")
{
count++;
}
else if (childName == "extensions")
{
msg.ExtensionPos = count;
break;
}
}
}
return mavlink;
}
}
}
}
| AirSim/MavLinkCom/MavLinkComGenerator/MavlinkParser.cs/0 | {
"file_path": "AirSim/MavLinkCom/MavLinkComGenerator/MavlinkParser.cs",
"repo_id": "AirSim",
"token_count": 985
} | 26 |
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26430.15
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MavLinkTest", "MavLinkTest.vcxproj", "{25EB67BE-468A-4AA5-910F-07EFD58C5516}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MavLinkCom", "..\MavLinkCom.vcxproj", "{8510C7A4-BF63-41D2-94F6-D8731D137A5A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM = Debug|ARM
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|ARM = Release|ARM
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{25EB67BE-468A-4AA5-910F-07EFD58C5516}.Debug|ARM.ActiveCfg = Debug|ARM
{25EB67BE-468A-4AA5-910F-07EFD58C5516}.Debug|ARM.Build.0 = Debug|ARM
{25EB67BE-468A-4AA5-910F-07EFD58C5516}.Debug|x64.ActiveCfg = Debug|x64
{25EB67BE-468A-4AA5-910F-07EFD58C5516}.Debug|x64.Build.0 = Debug|x64
{25EB67BE-468A-4AA5-910F-07EFD58C5516}.Debug|x86.ActiveCfg = Debug|Win32
{25EB67BE-468A-4AA5-910F-07EFD58C5516}.Debug|x86.Build.0 = Debug|Win32
{25EB67BE-468A-4AA5-910F-07EFD58C5516}.Release|ARM.ActiveCfg = Release|ARM
{25EB67BE-468A-4AA5-910F-07EFD58C5516}.Release|ARM.Build.0 = Release|ARM
{25EB67BE-468A-4AA5-910F-07EFD58C5516}.Release|x64.ActiveCfg = Release|x64
{25EB67BE-468A-4AA5-910F-07EFD58C5516}.Release|x64.Build.0 = Release|x64
{25EB67BE-468A-4AA5-910F-07EFD58C5516}.Release|x86.ActiveCfg = Release|Win32
{25EB67BE-468A-4AA5-910F-07EFD58C5516}.Release|x86.Build.0 = Release|Win32
{8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|ARM.ActiveCfg = Debug|ARM
{8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|ARM.Build.0 = Debug|ARM
{8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|x64.ActiveCfg = Debug|x64
{8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|x64.Build.0 = Debug|x64
{8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|x86.ActiveCfg = Debug|Win32
{8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Debug|x86.Build.0 = Debug|Win32
{8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|ARM.ActiveCfg = Release|ARM
{8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|ARM.Build.0 = Release|ARM
{8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|x64.ActiveCfg = Release|x64
{8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|x64.Build.0 = Release|x64
{8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|x86.ActiveCfg = Release|Win32
{8510C7A4-BF63-41D2-94F6-D8731D137A5A}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
| AirSim/MavLinkCom/MavLinkTest/MavLinkTest.sln/0 | {
"file_path": "AirSim/MavLinkCom/MavLinkTest/MavLinkTest.sln",
"repo_id": "AirSim",
"token_count": 1338
} | 27 |
#ifndef MavLinkCom_HighPriorityThread_hpp
#define MavLinkCom_HighPriorityThread_hpp
#include <thread>
#include <string>
namespace mavlink_utils
{
class CurrentThread
{
public:
// make the current thread run with maximum priority.
static bool setMaximumPriority();
// set a nice name on the current thread which aids in debugging.
static bool setThreadName(const std::string& name);
};
}
#endif | AirSim/MavLinkCom/common_utils/ThreadUtils.hpp/0 | {
"file_path": "AirSim/MavLinkCom/common_utils/ThreadUtils.hpp",
"repo_id": "AirSim",
"token_count": 133
} | 28 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef MavLinkCom_MavLinkTcpServer_hpp
#define MavLinkCom_MavLinkTcpServer_hpp
#include <string>
#include <memory>
#include "MavLinkConnection.hpp"
namespace mavlinkcom_impl
{
class MavLinkTcpServerImpl;
}
namespace mavlinkcom
{
class MavLinkTcpServer
{
public:
MavLinkTcpServer(const std::string& local_addr, int local_port);
~MavLinkTcpServer();
// This method accepts a new connection from a remote machine and gives that connection the given name.
// This is how you can build a TCP server by calling this method in a loop as long as you want to continue
// receiving new incoming connections.
std::shared_ptr<MavLinkConnection> acceptTcp(const std::string& nodeName);
public:
//needed for piml pattern
MavLinkTcpServer();
//MavLinkTcpServer(MavLinkTcpServer&&);
//MavLinkTcpServer& operator=(MavLinkTcpServer&&);
private:
std::shared_ptr<mavlinkcom_impl::MavLinkTcpServerImpl> impl_;
};
}
#endif
| AirSim/MavLinkCom/include/MavLinkTcpServer.hpp/0 | {
"file_path": "AirSim/MavLinkCom/include/MavLinkTcpServer.hpp",
"repo_id": "AirSim",
"token_count": 362
} | 29 |
#pragma once
// clang-format off
#include "string.h"
#include "mavlink_types.h"
/*
If you want MAVLink on a system that is native big-endian,
you need to define NATIVE_BIG_ENDIAN
*/
#ifdef NATIVE_BIG_ENDIAN
# define MAVLINK_NEED_BYTE_SWAP (MAVLINK_ENDIAN == MAVLINK_LITTLE_ENDIAN)
#else
# define MAVLINK_NEED_BYTE_SWAP (MAVLINK_ENDIAN != MAVLINK_LITTLE_ENDIAN)
#endif
#ifndef MAVLINK_STACK_BUFFER
#define MAVLINK_STACK_BUFFER 0
#endif
#ifndef MAVLINK_AVOID_GCC_STACK_BUG
# define MAVLINK_AVOID_GCC_STACK_BUG defined(__GNUC__)
#endif
#ifndef MAVLINK_ASSERT
#define MAVLINK_ASSERT(x)
#endif
#ifndef MAVLINK_START_UART_SEND
#define MAVLINK_START_UART_SEND(chan, length)
#endif
#ifndef MAVLINK_END_UART_SEND
#define MAVLINK_END_UART_SEND(chan, length)
#endif
/* option to provide alternative implementation of mavlink_helpers.h */
#ifdef MAVLINK_SEPARATE_HELPERS
#define MAVLINK_HELPER
/* decls in sync with those in mavlink_helpers.h */
#ifndef MAVLINK_GET_CHANNEL_STATUS
MAVLINK_HELPER mavlink_status_t* mavlink_get_channel_status(uint8_t chan);
#endif
MAVLINK_HELPER void mavlink_reset_channel_status(uint8_t chan);
MAVLINK_HELPER uint16_t mavlink_finalize_message_chan(mavlink_message_t* msg, uint8_t system_id, uint8_t component_id,
uint8_t chan, uint8_t min_length, uint8_t length, uint8_t crc_extra);
MAVLINK_HELPER uint16_t mavlink_finalize_message(mavlink_message_t* msg, uint8_t system_id, uint8_t component_id,
uint8_t min_length, uint8_t length, uint8_t crc_extra);
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS
MAVLINK_HELPER void _mav_finalize_message_chan_send(mavlink_channel_t chan, uint32_t msgid, const char *packet,
uint8_t min_length, uint8_t length, uint8_t crc_extra);
#endif
MAVLINK_HELPER uint16_t mavlink_msg_to_send_buffer(uint8_t *buffer, const mavlink_message_t *msg);
MAVLINK_HELPER void mavlink_start_checksum(mavlink_message_t* msg);
MAVLINK_HELPER void mavlink_update_checksum(mavlink_message_t* msg, uint8_t c);
MAVLINK_HELPER uint8_t mavlink_frame_char_buffer(mavlink_message_t* rxmsg,
mavlink_status_t* status,
uint8_t c,
mavlink_message_t* r_message,
mavlink_status_t* r_mavlink_status);
MAVLINK_HELPER uint8_t mavlink_frame_char(uint8_t chan, uint8_t c, mavlink_message_t* r_message, mavlink_status_t* r_mavlink_status);
MAVLINK_HELPER uint8_t mavlink_parse_char(uint8_t chan, uint8_t c, mavlink_message_t* r_message, mavlink_status_t* r_mavlink_status);
MAVLINK_HELPER uint8_t put_bitfield_n_by_index(int32_t b, uint8_t bits, uint8_t packet_index, uint8_t bit_index,
uint8_t* r_bit_index, uint8_t* buffer);
MAVLINK_HELPER const mavlink_msg_entry_t *mavlink_get_msg_entry(uint32_t msgid);
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS
MAVLINK_HELPER void _mavlink_send_uart(mavlink_channel_t chan, const char *buf, uint16_t len);
MAVLINK_HELPER void _mavlink_resend_uart(mavlink_channel_t chan, const mavlink_message_t *msg);
#endif
#else
#define MAVLINK_HELPER static inline
#include "mavlink_helpers.h"
#endif // MAVLINK_SEPARATE_HELPERS
/**
* @brief Get the required buffer size for this message
*/
static inline uint16_t mavlink_msg_get_send_buffer_length(const mavlink_message_t* msg)
{
if (msg->magic == MAVLINK_STX_MAVLINK1) {
return msg->len + MAVLINK_CORE_HEADER_MAVLINK1_LEN+1 + 2;
}
uint16_t signature_len = (msg->incompat_flags & MAVLINK_IFLAG_SIGNED)?MAVLINK_SIGNATURE_BLOCK_LEN:0;
return msg->len + MAVLINK_NUM_NON_PAYLOAD_BYTES + signature_len;
}
#if MAVLINK_NEED_BYTE_SWAP
static inline void byte_swap_2(char *dst, const char *src)
{
dst[0] = src[1];
dst[1] = src[0];
}
static inline void byte_swap_4(char *dst, const char *src)
{
dst[0] = src[3];
dst[1] = src[2];
dst[2] = src[1];
dst[3] = src[0];
}
static inline void byte_swap_8(char *dst, const char *src)
{
dst[0] = src[7];
dst[1] = src[6];
dst[2] = src[5];
dst[3] = src[4];
dst[4] = src[3];
dst[5] = src[2];
dst[6] = src[1];
dst[7] = src[0];
}
#elif !MAVLINK_ALIGNED_FIELDS
static inline void byte_copy_2(char *dst, const char *src)
{
dst[0] = src[0];
dst[1] = src[1];
}
static inline void byte_copy_4(char *dst, const char *src)
{
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = src[3];
}
static inline void byte_copy_8(char *dst, const char *src)
{
memcpy(dst, src, 8);
}
#endif
#define _mav_put_uint8_t(buf, wire_offset, b) buf[wire_offset] = (uint8_t)b
#define _mav_put_int8_t(buf, wire_offset, b) buf[wire_offset] = (int8_t)b
#define _mav_put_char(buf, wire_offset, b) buf[wire_offset] = b
#if MAVLINK_NEED_BYTE_SWAP
#define _mav_put_uint16_t(buf, wire_offset, b) byte_swap_2(&buf[wire_offset], (const char *)&b)
#define _mav_put_int16_t(buf, wire_offset, b) byte_swap_2(&buf[wire_offset], (const char *)&b)
#define _mav_put_uint32_t(buf, wire_offset, b) byte_swap_4(&buf[wire_offset], (const char *)&b)
#define _mav_put_int32_t(buf, wire_offset, b) byte_swap_4(&buf[wire_offset], (const char *)&b)
#define _mav_put_uint64_t(buf, wire_offset, b) byte_swap_8(&buf[wire_offset], (const char *)&b)
#define _mav_put_int64_t(buf, wire_offset, b) byte_swap_8(&buf[wire_offset], (const char *)&b)
#define _mav_put_float(buf, wire_offset, b) byte_swap_4(&buf[wire_offset], (const char *)&b)
#define _mav_put_double(buf, wire_offset, b) byte_swap_8(&buf[wire_offset], (const char *)&b)
#elif !MAVLINK_ALIGNED_FIELDS
#define _mav_put_uint16_t(buf, wire_offset, b) byte_copy_2(&buf[wire_offset], (const char *)&b)
#define _mav_put_int16_t(buf, wire_offset, b) byte_copy_2(&buf[wire_offset], (const char *)&b)
#define _mav_put_uint32_t(buf, wire_offset, b) byte_copy_4(&buf[wire_offset], (const char *)&b)
#define _mav_put_int32_t(buf, wire_offset, b) byte_copy_4(&buf[wire_offset], (const char *)&b)
#define _mav_put_uint64_t(buf, wire_offset, b) byte_copy_8(&buf[wire_offset], (const char *)&b)
#define _mav_put_int64_t(buf, wire_offset, b) byte_copy_8(&buf[wire_offset], (const char *)&b)
#define _mav_put_float(buf, wire_offset, b) byte_copy_4(&buf[wire_offset], (const char *)&b)
#define _mav_put_double(buf, wire_offset, b) byte_copy_8(&buf[wire_offset], (const char *)&b)
#else
#define _mav_put_uint16_t(buf, wire_offset, b) *(uint16_t *)&buf[wire_offset] = b
#define _mav_put_int16_t(buf, wire_offset, b) *(int16_t *)&buf[wire_offset] = b
#define _mav_put_uint32_t(buf, wire_offset, b) *(uint32_t *)&buf[wire_offset] = b
#define _mav_put_int32_t(buf, wire_offset, b) *(int32_t *)&buf[wire_offset] = b
#define _mav_put_uint64_t(buf, wire_offset, b) *(uint64_t *)&buf[wire_offset] = b
#define _mav_put_int64_t(buf, wire_offset, b) *(int64_t *)&buf[wire_offset] = b
#define _mav_put_float(buf, wire_offset, b) *(float *)&buf[wire_offset] = b
#define _mav_put_double(buf, wire_offset, b) *(double *)&buf[wire_offset] = b
#endif
/*
like memcpy(), but if src is NULL, do a memset to zero
*/
static inline void mav_array_memcpy(void *dest, const void *src, size_t n)
{
if (src == NULL) {
memset(dest, 0, n);
} else {
memcpy(dest, src, n);
}
}
/*
* Place a char array into a buffer
*/
static inline void _mav_put_char_array(char *buf, uint8_t wire_offset, const char *b, uint8_t array_length)
{
mav_array_memcpy(&buf[wire_offset], b, array_length);
}
/*
* Place a uint8_t array into a buffer
*/
static inline void _mav_put_uint8_t_array(char *buf, uint8_t wire_offset, const uint8_t *b, uint8_t array_length)
{
mav_array_memcpy(&buf[wire_offset], b, array_length);
}
/*
* Place a int8_t array into a buffer
*/
static inline void _mav_put_int8_t_array(char *buf, uint8_t wire_offset, const int8_t *b, uint8_t array_length)
{
mav_array_memcpy(&buf[wire_offset], b, array_length);
}
#if MAVLINK_NEED_BYTE_SWAP
#define _MAV_PUT_ARRAY(TYPE, V) \
static inline void _mav_put_ ## TYPE ##_array(char *buf, uint8_t wire_offset, const TYPE *b, uint8_t array_length) \
{ \
if (b == NULL) { \
memset(&buf[wire_offset], 0, array_length*sizeof(TYPE)); \
} else { \
uint16_t i; \
for (i=0; i<array_length; i++) { \
_mav_put_## TYPE (buf, wire_offset+(i*sizeof(TYPE)), b[i]); \
} \
} \
}
#else
#define _MAV_PUT_ARRAY(TYPE, V) \
static inline void _mav_put_ ## TYPE ##_array(char *buf, uint8_t wire_offset, const TYPE *b, uint8_t array_length) \
{ \
mav_array_memcpy(&buf[wire_offset], b, array_length*sizeof(TYPE)); \
}
#endif
_MAV_PUT_ARRAY(uint16_t, u16)
_MAV_PUT_ARRAY(uint32_t, u32)
_MAV_PUT_ARRAY(uint64_t, u64)
_MAV_PUT_ARRAY(int16_t, i16)
_MAV_PUT_ARRAY(int32_t, i32)
_MAV_PUT_ARRAY(int64_t, i64)
_MAV_PUT_ARRAY(float, f)
_MAV_PUT_ARRAY(double, d)
#define _MAV_RETURN_char(msg, wire_offset) (char)_MAV_PAYLOAD(msg)[wire_offset]
#define _MAV_RETURN_int8_t(msg, wire_offset) (int8_t)_MAV_PAYLOAD(msg)[wire_offset]
#define _MAV_RETURN_uint8_t(msg, wire_offset) (uint8_t)_MAV_PAYLOAD(msg)[wire_offset]
#if MAVLINK_NEED_BYTE_SWAP
#define _MAV_MSG_RETURN_TYPE(TYPE, SIZE) \
static inline TYPE _MAV_RETURN_## TYPE(const mavlink_message_t *msg, uint8_t ofs) \
{ TYPE r; byte_swap_## SIZE((char*)&r, &_MAV_PAYLOAD(msg)[ofs]); return r; }
_MAV_MSG_RETURN_TYPE(uint16_t, 2)
_MAV_MSG_RETURN_TYPE(int16_t, 2)
_MAV_MSG_RETURN_TYPE(uint32_t, 4)
_MAV_MSG_RETURN_TYPE(int32_t, 4)
_MAV_MSG_RETURN_TYPE(uint64_t, 8)
_MAV_MSG_RETURN_TYPE(int64_t, 8)
_MAV_MSG_RETURN_TYPE(float, 4)
_MAV_MSG_RETURN_TYPE(double, 8)
#elif !MAVLINK_ALIGNED_FIELDS
#define _MAV_MSG_RETURN_TYPE(TYPE, SIZE) \
static inline TYPE _MAV_RETURN_## TYPE(const mavlink_message_t *msg, uint8_t ofs) \
{ TYPE r; byte_copy_## SIZE((char*)&r, &_MAV_PAYLOAD(msg)[ofs]); return r; }
_MAV_MSG_RETURN_TYPE(uint16_t, 2)
_MAV_MSG_RETURN_TYPE(int16_t, 2)
_MAV_MSG_RETURN_TYPE(uint32_t, 4)
_MAV_MSG_RETURN_TYPE(int32_t, 4)
_MAV_MSG_RETURN_TYPE(uint64_t, 8)
_MAV_MSG_RETURN_TYPE(int64_t, 8)
_MAV_MSG_RETURN_TYPE(float, 4)
_MAV_MSG_RETURN_TYPE(double, 8)
#else // nicely aligned, no swap
#define _MAV_MSG_RETURN_TYPE(TYPE) \
static inline TYPE _MAV_RETURN_## TYPE(const mavlink_message_t *msg, uint8_t ofs) \
{ return *(const TYPE *)(&_MAV_PAYLOAD(msg)[ofs]);}
_MAV_MSG_RETURN_TYPE(uint16_t)
_MAV_MSG_RETURN_TYPE(int16_t)
_MAV_MSG_RETURN_TYPE(uint32_t)
_MAV_MSG_RETURN_TYPE(int32_t)
_MAV_MSG_RETURN_TYPE(uint64_t)
_MAV_MSG_RETURN_TYPE(int64_t)
_MAV_MSG_RETURN_TYPE(float)
_MAV_MSG_RETURN_TYPE(double)
#endif // MAVLINK_NEED_BYTE_SWAP
static inline uint16_t _MAV_RETURN_char_array(const mavlink_message_t *msg, char *value,
uint8_t array_length, uint8_t wire_offset)
{
memcpy(value, &_MAV_PAYLOAD(msg)[wire_offset], array_length);
return array_length;
}
static inline uint16_t _MAV_RETURN_uint8_t_array(const mavlink_message_t *msg, uint8_t *value,
uint8_t array_length, uint8_t wire_offset)
{
memcpy(value, &_MAV_PAYLOAD(msg)[wire_offset], array_length);
return array_length;
}
static inline uint16_t _MAV_RETURN_int8_t_array(const mavlink_message_t *msg, int8_t *value,
uint8_t array_length, uint8_t wire_offset)
{
memcpy(value, &_MAV_PAYLOAD(msg)[wire_offset], array_length);
return array_length;
}
#if MAVLINK_NEED_BYTE_SWAP
#define _MAV_RETURN_ARRAY(TYPE, V) \
static inline uint16_t _MAV_RETURN_## TYPE ##_array(const mavlink_message_t *msg, TYPE *value, \
uint8_t array_length, uint8_t wire_offset) \
{ \
uint16_t i; \
for (i=0; i<array_length; i++) { \
value[i] = _MAV_RETURN_## TYPE (msg, wire_offset+(i*sizeof(value[0]))); \
} \
return array_length*sizeof(value[0]); \
}
#else
#define _MAV_RETURN_ARRAY(TYPE, V) \
static inline uint16_t _MAV_RETURN_## TYPE ##_array(const mavlink_message_t *msg, TYPE *value, \
uint8_t array_length, uint8_t wire_offset) \
{ \
memcpy(value, &_MAV_PAYLOAD(msg)[wire_offset], array_length*sizeof(TYPE)); \
return array_length*sizeof(TYPE); \
}
#endif
_MAV_RETURN_ARRAY(uint16_t, u16)
_MAV_RETURN_ARRAY(uint32_t, u32)
_MAV_RETURN_ARRAY(uint64_t, u64)
_MAV_RETURN_ARRAY(int16_t, i16)
_MAV_RETURN_ARRAY(int32_t, i32)
_MAV_RETURN_ARRAY(int64_t, i64)
_MAV_RETURN_ARRAY(float, f)
_MAV_RETURN_ARRAY(double, d)
// clang-format on | AirSim/MavLinkCom/mavlink/protocol.h/0 | {
"file_path": "AirSim/MavLinkCom/mavlink/protocol.h",
"repo_id": "AirSim",
"token_count": 5829
} | 30 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "MavLinkMessages.hpp"
#include "MavLinkConnectionImpl.hpp"
#include "Utils.hpp"
#include "ThreadUtils.hpp"
#include "../serial_com/Port.h"
#include "../serial_com/SerialPort.hpp"
#include "../serial_com/UdpClientPort.hpp"
#include "../serial_com/TcpClientPort.hpp"
using namespace mavlink_utils;
using namespace mavlinkcom_impl;
MavLinkConnectionImpl::MavLinkConnectionImpl()
{
// add our custom telemetry message length.
telemetry_.crc_errors = 0;
telemetry_.handler_microseconds = 0;
telemetry_.messages_handled = 0;
telemetry_.messages_received = 0;
telemetry_.messages_sent = 0;
closed = true;
::memset(&mavlink_intermediate_status_, 0, sizeof(mavlink_status_t));
::memset(&mavlink_status_, 0, sizeof(mavlink_status_t));
// todo: if we support signing then initialize
// mavlink_intermediate_status_.signing callbacks
}
std::string MavLinkConnectionImpl::getName()
{
return name;
}
MavLinkConnectionImpl::~MavLinkConnectionImpl()
{
con_.reset();
close();
}
std::shared_ptr<MavLinkConnection> MavLinkConnectionImpl::createConnection(const std::string& nodeName, std::shared_ptr<Port> port)
{
// std::shared_ptr<MavLinkCom> owner, const std::string& nodeName
std::shared_ptr<MavLinkConnection> con = std::make_shared<MavLinkConnection>();
con->startListening(nodeName, port);
return con;
}
std::shared_ptr<MavLinkConnection> MavLinkConnectionImpl::connectLocalUdp(const std::string& nodeName, const std::string& localAddr, int localPort)
{
std::shared_ptr<UdpClientPort> socket = std::make_shared<UdpClientPort>();
socket->connect(localAddr, localPort, "", 0);
return createConnection(nodeName, socket);
}
std::shared_ptr<MavLinkConnection> MavLinkConnectionImpl::connectRemoteUdp(const std::string& nodeName, const std::string& localAddr, const std::string& remoteAddr, int remotePort)
{
std::string local = localAddr;
// just a little sanity check on the local address, if remoteAddr is localhost then localAddr must be also.
if (remoteAddr == "127.0.0.1") {
local = "127.0.0.1";
}
std::shared_ptr<UdpClientPort> socket = std::make_shared<UdpClientPort>();
socket->connect(local, 0, remoteAddr, remotePort);
return createConnection(nodeName, socket);
}
std::shared_ptr<MavLinkConnection> MavLinkConnectionImpl::connectTcp(const std::string& nodeName, const std::string& localAddr, const std::string& remoteIpAddr, int remotePort)
{
std::string local = localAddr;
// just a little sanity check on the local address, if remoteAddr is localhost then localAddr must be also.
if (remoteIpAddr == "127.0.0.1") {
local = "127.0.0.1";
}
std::shared_ptr<TcpClientPort> socket = std::make_shared<TcpClientPort>();
socket->connect(local, 0, remoteIpAddr, remotePort);
return createConnection(nodeName, socket);
}
std::string MavLinkConnectionImpl::acceptTcp(std::shared_ptr<MavLinkConnection> parent, const std::string& nodeName, const std::string& localAddr, int listeningPort)
{
std::string local = localAddr;
close();
std::shared_ptr<TcpClientPort> socket = std::make_shared<TcpClientPort>();
port = socket; // this is so that a call to close() can cancel this blocking accept call.
socket->accept(localAddr, listeningPort);
std::string remote = socket->remoteAddress();
socket->setNonBlocking();
socket->setNoDelay();
parent->startListening(nodeName, socket);
return remote;
}
std::shared_ptr<MavLinkConnection> MavLinkConnectionImpl::connectSerial(const std::string& nodeName, const std::string& portName, int baudRate, const std::string& initString)
{
std::shared_ptr<SerialPort> serial = std::make_shared<SerialPort>();
int hr = serial->connect(portName.c_str(), baudRate);
if (hr != 0)
throw std::runtime_error(Utils::stringf("Could not open the serial port %s, error=%d", portName.c_str(), hr));
// send this right away just in case serial link is not already configured
if (initString.size() > 0) {
serial->write(reinterpret_cast<const uint8_t*>(initString.c_str()), static_cast<int>(initString.size()));
}
return createConnection(nodeName, serial);
}
void MavLinkConnectionImpl::startListening(std::shared_ptr<MavLinkConnection> parent, const std::string& nodeName, std::shared_ptr<Port> connectedPort)
{
name = nodeName;
con_ = parent;
if (port != connectedPort) {
close();
port = connectedPort;
}
closed = false;
Utils::cleanupThread(read_thread);
read_thread = std::thread{ &MavLinkConnectionImpl::readPackets, this };
Utils::cleanupThread(publish_thread_);
publish_thread_ = std::thread{ &MavLinkConnectionImpl::publishPackets, this };
}
// log every message that is "sent" using sendMessage.
void MavLinkConnectionImpl::startLoggingSendMessage(std::shared_ptr<MavLinkLog> log)
{
sendLog_ = log;
}
void MavLinkConnectionImpl::stopLoggingSendMessage()
{
sendLog_ = nullptr;
}
// log every message that is "sent" using sendMessage.
void MavLinkConnectionImpl::startLoggingReceiveMessage(std::shared_ptr<MavLinkLog> log)
{
receiveLog_ = log;
}
void MavLinkConnectionImpl::stopLoggingReceiveMessage()
{
receiveLog_ = nullptr;
}
void MavLinkConnectionImpl::close()
{
closed = true;
if (port != nullptr) {
port->close();
port = nullptr;
}
if (read_thread.joinable()) {
read_thread.join();
}
if (publish_thread_.joinable()) {
msg_available_.post();
publish_thread_.join();
}
sendLog_ = nullptr;
receiveLog_ = nullptr;
}
bool MavLinkConnectionImpl::isOpen()
{
return !closed;
}
int MavLinkConnectionImpl::getTargetComponentId()
{
return this->other_component_id;
}
int MavLinkConnectionImpl::getTargetSystemId()
{
return this->other_system_id;
}
uint8_t MavLinkConnectionImpl::getNextSequence()
{
std::lock_guard<std::mutex> guard(buffer_mutex);
return next_seq++;
}
void MavLinkConnectionImpl::ignoreMessage(uint8_t message_id)
{
ignored_messageids.insert(message_id);
}
void MavLinkConnectionImpl::sendMessage(const MavLinkMessage& m)
{
if (ignored_messageids.find(m.msgid) != ignored_messageids.end())
return;
if (closed) {
return;
}
{
MavLinkMessage msg;
::memcpy(&msg, &m, sizeof(MavLinkMessage));
prepareForSending(msg);
if (sendLog_ != nullptr) {
sendLog_->write(msg);
}
mavlink_message_t message;
message.compid = msg.compid;
message.sysid = msg.sysid;
message.len = msg.len;
message.checksum = msg.checksum;
message.magic = msg.magic;
message.incompat_flags = msg.incompat_flags;
message.compat_flags = msg.compat_flags;
message.seq = msg.seq;
message.msgid = msg.msgid;
::memcpy(message.signature, msg.signature, 13);
::memcpy(message.payload64, msg.payload64, PayloadSize * sizeof(uint64_t));
std::lock_guard<std::mutex> guard(buffer_mutex);
unsigned len = mavlink_msg_to_send_buffer(message_buf, &message);
try {
port->write(message_buf, len);
}
catch (std::exception& e) {
throw std::runtime_error(Utils::stringf("MavLinkConnectionImpl: Error sending message on connection '%s', details: %s", name.c_str(), e.what()));
}
}
{
std::lock_guard<std::mutex> guard(telemetry_mutex_);
telemetry_.messages_sent++;
}
}
int MavLinkConnectionImpl::prepareForSending(MavLinkMessage& msg)
{
// as per https://github.com/mavlink/mavlink/blob/master/doc/MAVLink2.md
int seqno = getNextSequence();
bool mavlink1 = !supports_mavlink2_ && msg.protocol_version != 2;
bool signing = !mavlink1 && mavlink_status_.signing && (mavlink_status_.signing->flags & MAVLINK_SIGNING_FLAG_SIGN_OUTGOING);
uint8_t signature_len = signing ? MAVLINK_SIGNATURE_BLOCK_LEN : 0;
uint8_t header_len = MAVLINK_CORE_HEADER_LEN + 1;
uint8_t buf[MAVLINK_CORE_HEADER_LEN + 1];
if (mavlink1) {
msg.magic = MAVLINK_STX_MAVLINK1;
header_len = MAVLINK_CORE_HEADER_MAVLINK1_LEN + 1;
}
else {
msg.magic = MAVLINK_STX;
}
msg.seq = seqno;
msg.incompat_flags = 0;
if (signing) {
msg.incompat_flags |= MAVLINK_IFLAG_SIGNED;
}
msg.compat_flags = 0;
// pack the payload buffer.
char* payload = reinterpret_cast<char*>(&msg.payload64[0]);
int len = msg.len;
// calculate checksum
const mavlink_msg_entry_t* entry = mavlink_get_msg_entry(msg.msgid);
uint8_t crc_extra = 0;
int msglen = 0;
if (entry != nullptr) {
crc_extra = entry->crc_extra;
msglen = entry->min_msg_len;
}
if (msg.msgid == MavLinkTelemetry::kMessageId) {
msglen = MavLinkTelemetry::MessageLength; // mavlink doesn't know about our custom telemetry message.
}
if (len != msglen) {
if (mavlink1) {
throw std::runtime_error(Utils::stringf("Message length %d doesn't match expected length%d\n", len, msglen));
}
else {
// mavlink2 supports trimming the payload of trailing zeros so the messages
// are variable length as a result.
}
}
len = mavlink1 ? msglen : _mav_trim_payload(payload, msglen);
msg.len = len;
// form the header as a byte array for the crc
buf[0] = msg.magic;
buf[1] = msg.len;
if (mavlink1) {
buf[2] = msg.seq;
buf[3] = msg.sysid;
buf[4] = msg.compid;
buf[5] = msg.msgid & 0xFF;
}
else {
buf[2] = msg.incompat_flags;
buf[3] = msg.compat_flags;
buf[4] = msg.seq;
buf[5] = msg.sysid;
buf[6] = msg.compid;
buf[7] = msg.msgid & 0xFF;
buf[8] = (msg.msgid >> 8) & 0xFF;
buf[9] = (msg.msgid >> 16) & 0xFF;
}
msg.checksum = crc_calculate(&buf[1], header_len - 1);
crc_accumulate_buffer(&msg.checksum, payload, msg.len);
crc_accumulate(crc_extra, &msg.checksum);
// these macros use old style cast.
STRICT_MODE_OFF
mavlink_ck_a(&msg) = (uint8_t)(msg.checksum & 0xFF);
mavlink_ck_b(&msg) = (uint8_t)(msg.checksum >> 8);
STRICT_MODE_ON
if (signing) {
mavlink_sign_packet(mavlink_status_.signing,
reinterpret_cast<uint8_t*>(msg.signature),
reinterpret_cast<const uint8_t*>(message_buf),
header_len,
reinterpret_cast<const uint8_t*>(payload),
msg.len,
reinterpret_cast<const uint8_t*>(payload) + msg.len);
}
return msg.len + header_len + 2 + signature_len;
}
void MavLinkConnectionImpl::sendMessage(const MavLinkMessageBase& msg)
{
MavLinkMessage m;
msg.encode(m);
sendMessage(m);
}
int MavLinkConnectionImpl::subscribe(MessageHandler handler)
{
MessageHandlerEntry entry{ static_cast<int>(listeners.size() + 1), handler };
std::lock_guard<std::mutex> guard(listener_mutex);
listeners.push_back(entry);
snapshot_stale = true;
return entry.id;
}
void MavLinkConnectionImpl::unsubscribe(int id)
{
std::lock_guard<std::mutex> guard(listener_mutex);
for (auto ptr = listeners.begin(), end = listeners.end(); ptr != end; ptr++) {
if ((*ptr).id == id) {
listeners.erase(ptr);
snapshot_stale = true;
break;
}
}
}
void MavLinkConnectionImpl::joinLeftSubscriber(std::shared_ptr<MavLinkConnection> remote, std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& msg)
{
unused(connection);
// forward messages from our connected node to the remote proxy.
if (supports_mavlink2_) {
// tell the remote connection to expect mavlink2 messages.
remote->pImpl->supports_mavlink2_ = true;
}
remote->sendMessage(msg);
}
void MavLinkConnectionImpl::joinRightSubscriber(std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& msg)
{
unused(connection);
// forward messages from remote proxy to local connected node
this->sendMessage(msg);
}
void MavLinkConnectionImpl::join(std::shared_ptr<MavLinkConnection> remote, bool subscribeToLeft, bool subscribeToRight)
{
if (subscribeToLeft)
this->subscribe(std::bind(&MavLinkConnectionImpl::joinLeftSubscriber, this, remote, std::placeholders::_1, std::placeholders::_2));
if (subscribeToRight)
remote->subscribe(std::bind(&MavLinkConnectionImpl::joinRightSubscriber, this, std::placeholders::_1, std::placeholders::_2));
}
void MavLinkConnectionImpl::readPackets()
{
//CurrentThread::setMaximumPriority();
CurrentThread::setThreadName("MavLinkThread");
std::shared_ptr<Port> safePort = this->port;
mavlink_message_t msg;
mavlink_message_t msgBuffer; // intermediate state.
const int MAXBUFFER = 512;
uint8_t* buffer = new uint8_t[MAXBUFFER];
mavlink_intermediate_status_.parse_state = MAVLINK_PARSE_STATE_IDLE;
int channel = 0;
int hr = 0;
while (hr == 0 && con_ != nullptr && !closed) {
int read = 0;
if (safePort->isClosed()) {
// hmmm, wait till it is opened?
std::this_thread::sleep_for(std::chrono::milliseconds(10));
continue;
}
int count = safePort->read(buffer, MAXBUFFER);
if (count <= 0) {
// error? well let's try again, but we should be careful not to spin too fast and kill the CPU
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
for (int i = 0; i < count; i++) {
uint8_t frame_state = mavlink_frame_char_buffer(&msgBuffer, &mavlink_intermediate_status_, buffer[i], &msg, &mavlink_status_);
if (frame_state == MAVLINK_FRAMING_INCOMPLETE) {
continue;
}
else if (frame_state == MAVLINK_FRAMING_BAD_CRC) {
std::lock_guard<std::mutex> guard(telemetry_mutex_);
telemetry_.crc_errors++;
}
else if (frame_state == MAVLINK_FRAMING_OK) {
// pick up the sysid/compid of the remote node we are connected to.
if (other_system_id == -1) {
other_system_id = msg.sysid;
other_component_id = msg.compid;
}
if (mavlink_intermediate_status_.flags & MAVLINK_STATUS_FLAG_IN_MAVLINK1) {
// then this is a mavlink 1 message
}
else if (!supports_mavlink2_) {
// then this mavlink sender supports mavlink 2
supports_mavlink2_ = true;
}
if (con_ != nullptr && !closed) {
{
std::lock_guard<std::mutex> guard(telemetry_mutex_);
telemetry_.messages_received++;
}
// queue event for publishing.
{
std::lock_guard<std::mutex> guard(msg_queue_mutex_);
MavLinkMessage message;
message.compid = msg.compid;
message.sysid = msg.sysid;
message.len = msg.len;
message.checksum = msg.checksum;
message.magic = msg.magic;
message.incompat_flags = msg.incompat_flags;
message.compat_flags = msg.compat_flags;
message.seq = msg.seq;
message.msgid = msg.msgid;
message.protocol_version = supports_mavlink2_ ? 2 : 1;
::memcpy(message.signature, msg.signature, 13);
::memcpy(message.payload64, msg.payload64, PayloadSize * sizeof(uint64_t));
msg_queue_.push(message);
}
if (waiting_for_msg_) {
msg_available_.post();
}
}
}
else {
std::lock_guard<std::mutex> guard(telemetry_mutex_);
telemetry_.crc_errors++;
}
}
} //while
delete[] buffer;
} //readPackets
void MavLinkConnectionImpl::drainQueue()
{
MavLinkMessage message;
bool hasMsg = true;
while (hasMsg) {
hasMsg = false;
{
std::lock_guard<std::mutex> guard(msg_queue_mutex_);
if (!msg_queue_.empty()) {
message = msg_queue_.front();
msg_queue_.pop();
hasMsg = true;
}
}
if (!hasMsg) {
return;
}
if (receiveLog_ != nullptr) {
receiveLog_->write(message);
}
// publish the message from this thread, this is safer than publishing from the readPackets thread
// as it ensures we don't lose messages if the listener is slow.
if (snapshot_stale) {
// this is tricky, the clear has to be done outside the lock because it is destructing the handlers
// and the handler might try and call unsubscribe, which needs to be able to grab the lock, otherwise
// we would get a deadlock.
snapshot.clear();
std::lock_guard<std::mutex> guard(listener_mutex);
snapshot = listeners;
snapshot_stale = false;
}
auto end = snapshot.end();
if (message.msgid == static_cast<uint8_t>(MavLinkMessageIds::MAVLINK_MSG_ID_AUTOPILOT_VERSION)) {
MavLinkAutopilotVersion cap;
cap.decode(message);
if ((cap.capabilities & MAV_PROTOCOL_CAPABILITY_MAVLINK2) != 0) {
this->supports_mavlink2_ = true;
}
}
auto startTime = std::chrono::system_clock::now();
std::shared_ptr<MavLinkConnection> sharedPtr = std::shared_ptr<MavLinkConnection>(this->con_);
for (auto ptr = snapshot.begin(); ptr != end; ptr++) {
try {
(*ptr).handler(sharedPtr, message);
}
catch (std::exception& e) {
Utils::log(Utils::stringf("MavLinkConnectionImpl: Error handling message %d on connection '%s', details: %s",
message.msgid,
name.c_str(),
e.what()),
Utils::kLogLevelError);
}
}
{
auto endTime = std::chrono::system_clock::now();
auto diff = endTime - startTime;
long microseconds = static_cast<long>(std::chrono::duration_cast<std::chrono::microseconds>(diff).count());
std::lock_guard<std::mutex> guard(telemetry_mutex_);
telemetry_.messages_handled++;
telemetry_.handler_microseconds += microseconds;
}
}
}
void MavLinkConnectionImpl::publishPackets()
{
//CurrentThread::setMaximumPriority();
CurrentThread::setThreadName("MavLinkThread");
publish_thread_id_ = std::this_thread::get_id();
while (!closed) {
drainQueue();
waiting_for_msg_ = true;
msg_available_.wait();
waiting_for_msg_ = false;
}
}
bool MavLinkConnectionImpl::isPublishThread() const
{
return std::this_thread::get_id() == publish_thread_id_;
}
void MavLinkConnectionImpl::getTelemetry(MavLinkTelemetry& result)
{
std::lock_guard<std::mutex> guard(telemetry_mutex_);
result = telemetry_;
// reset counters
telemetry_.crc_errors = 0;
telemetry_.handler_microseconds = 0;
telemetry_.messages_handled = 0;
telemetry_.messages_received = 0;
telemetry_.messages_sent = 0;
if (telemetry_.wifiInterfaceName != nullptr) {
telemetry_.wifi_rssi = port->getRssi(telemetry_.wifiInterfaceName);
}
}
| AirSim/MavLinkCom/src/impl/MavLinkConnectionImpl.cpp/0 | {
"file_path": "AirSim/MavLinkCom/src/impl/MavLinkConnectionImpl.cpp",
"repo_id": "AirSim",
"token_count": 8967
} | 31 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef ONECORE
#include "MavLinkConnection.hpp"
#include <Windows.h>
#include <ObjIdl.h>
#include <SetupAPI.h>
#include <Cfgmgr32.h>
#include <propkey.h>
#include <string>
using namespace mavlinkcom;
using namespace mavlinkcom_impl;
// {4d36e978-e325-11ce-bfc1-08002be10318}
const GUID serialDeviceClass = { 0x4d36e978, 0xe325, 0x11ce, 0xBF, 0xC1, 0x08, 0x00, 0x2B, 0xE1, 0x03, 0x18 };
bool parseVidPid(std::wstring deviceId, int* vid, int* pid)
{
const wchar_t* ptr = deviceId.c_str();
const wchar_t* end = ptr + deviceId.size();
// parse out the VID number
const wchar_t* pos = wcsstr(ptr, L"\\VID_");
if (pos == NULL) {
return false;
}
wchar_t* numberEnd = NULL;
long c = wcstol(pos + 5, &numberEnd, 16);
*vid = (int)c;
// now the PID
pos = wcsstr(numberEnd, L"PID_");
if (pos == NULL) {
return false;
}
numberEnd = NULL;
c = wcstol(pos + 4, &numberEnd, 16);
*pid = (int)c;
return true;
}
void parseDisplayName(std::wstring displayName, SerialPortInfo* info)
{
info->displayName = displayName;
const wchar_t* ptr = displayName.c_str();
// parse out the VID number
const wchar_t* pos = wcsrchr(ptr, '(');
if (pos == NULL) {
return;
}
pos++; // skip '('
const wchar_t* end = wcschr(pos, ')');
if (end != NULL) {
info->portName = std::wstring(pos, (size_t)(end - pos));
}
}
std::vector<SerialPortInfo> MavLinkConnection::findSerialPorts(int vid, int pid)
{
bool debug = false;
std::vector<SerialPortInfo> result;
HDEVINFO classInfo = SetupDiGetClassDevsEx(&serialDeviceClass, NULL, NULL, DIGCF_PRESENT, NULL, NULL, NULL);
if (classInfo == INVALID_HANDLE_VALUE) {
return result;
}
SP_DEVINFO_DATA deviceInfo;
deviceInfo.cbSize = sizeof(SP_DEVINFO_DATA);
for (int devIndex = 0; SetupDiEnumDeviceInfo(classInfo, devIndex, &deviceInfo); devIndex++) {
ULONG size;
HRESULT hr = CM_Get_Device_ID_Size(&size, deviceInfo.DevInst, 0);
if (hr == CR_SUCCESS) {
std::wstring buffer(size + 1, '\0');
hr = CM_Get_Device_ID(deviceInfo.DevInst, (PWSTR)buffer.c_str(), size + 1, 0);
// examples:
// PX4: USB\VID_26AC&PID_0011\0
// FTDI cable: FTDIBUS\VID_0403+PID_6001+FTUAN9UJA\0000"
//printf("Found: %S\n", buffer.c_str());
int dvid = 0, dpid = 0;
if (parseVidPid(buffer, &dvid, &dpid) &&
((dvid == vid && dpid == pid) || (vid == 0 && pid == 0))) {
DWORD keyCount = 0;
if (!SetupDiGetDevicePropertyKeys(classInfo, &deviceInfo, NULL, 0, &keyCount, 0)) {
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
continue;
}
}
SerialPortInfo portInfo;
portInfo.pid = dpid;
portInfo.vid = dvid;
DEVPROPKEY* keyArray = new DEVPROPKEY[keyCount];
if (SetupDiGetDevicePropertyKeys(classInfo, &deviceInfo, keyArray, keyCount, &keyCount, 0)) {
for (DWORD j = 0; j < keyCount; j++) {
DEVPROPKEY* key = &keyArray[j];
bool isItemNameProperty = (key->fmtid == PKEY_ItemNameDisplay.fmtid && key->pid == PKEY_ItemNameDisplay.pid);
if (isItemNameProperty) {
ULONG bufferSize = 0;
DEVPROPTYPE propertyType;
CM_Get_DevNode_Property(deviceInfo.DevInst, &keyArray[j], &propertyType, NULL, &bufferSize, 0);
if (bufferSize > 0) {
BYTE* propertyBuffer = new BYTE[bufferSize];
hr = CM_Get_DevNode_Property(deviceInfo.DevInst, &keyArray[j], &propertyType, propertyBuffer, &bufferSize, 0);
if (hr == CR_SUCCESS) {
std::wstring displayName((WCHAR*)propertyBuffer);
parseDisplayName(displayName, &portInfo);
}
delete[] propertyBuffer;
}
}
}
}
result.push_back(portInfo);
delete[] keyArray;
}
}
}
return result;
}
#endif | AirSim/MavLinkCom/src/impl/windows/WindowsFindSerialPorts.cpp/0 | {
"file_path": "AirSim/MavLinkCom/src/impl/windows/WindowsFindSerialPorts.cpp",
"repo_id": "AirSim",
"token_count": 2359
} | 32 |
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27428.2043
MinimumVisualStudioVersion = 10.0.40219.1
Project("{888888A0-9F3D-457C-B088-3A5042F75D52}") = "PythonClient", "PythonClient.pyproj", "{E2049E20-B6DD-474E-8BCA-1C8DC54725AA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E2049E20-B6DD-474E-8BCA-1C8DC54725AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E2049E20-B6DD-474E-8BCA-1C8DC54725AA}.Release|Any CPU.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6D1D8A10-EB64-4019-BB38-93871124FD0C}
EndGlobalSection
EndGlobal
| AirSim/PythonClient/PythonClient.sln/0 | {
"file_path": "AirSim/PythonClient/PythonClient.sln",
"repo_id": "AirSim",
"token_count": 352
} | 33 |
import airsim
import cv2
import numpy as np
import os
import setup_path
import time
# Use below in settings.json with blocks environment
"""
{
"SettingsVersion": 1.2,
"SimMode": "Car",
"Vehicles": {
"Car1": {
"VehicleType": "PhysXCar",
"X": 4, "Y": 0, "Z": -2
},
"Car2": {
"VehicleType": "PhysXCar",
"X": -4, "Y": 0, "Z": -2
}
}
}
"""
# connect to the AirSim simulator
client = airsim.CarClient()
client.confirmConnection()
client.enableApiControl(True, "Car1")
client.enableApiControl(True, "Car2")
car_controls1 = airsim.CarControls()
car_controls2 = airsim.CarControls()
for idx in range(3):
# get state of the car
car_state1 = client.getCarState("Car1")
print("Car1: Speed %d, Gear %d" % (car_state1.speed, car_state1.gear))
car_state2 = client.getCarState("Car2")
print("Car1: Speed %d, Gear %d" % (car_state2.speed, car_state2.gear))
# go forward
car_controls1.throttle = 0.5
car_controls1.steering = 0.5
client.setCarControls(car_controls1, "Car1")
print("Car1: Go Forward")
car_controls2.throttle = 0.5
car_controls2.steering = -0.5
client.setCarControls(car_controls2, "Car2")
print("Car2: Go Forward")
time.sleep(3) # let car drive a bit
# go reverse
car_controls1.throttle = -0.5
car_controls1.is_manual_gear = True;
car_controls1.manual_gear = -1
car_controls1.steering = -0.5
client.setCarControls(car_controls1, "Car1")
print("Car1: Go reverse, steer right")
car_controls1.is_manual_gear = False; # change back gear to auto
car_controls1.manual_gear = 0
car_controls2.throttle = -0.5
car_controls2.is_manual_gear = True;
car_controls2.manual_gear = -1
car_controls2.steering = 0.5
client.setCarControls(car_controls2, "Car2")
print("Car2: Go reverse, steer right")
car_controls2.is_manual_gear = False; # change back gear to auto
car_controls2.manual_gear = 0
time.sleep(3) # let car drive a bit
# apply breaks
car_controls1.brake = 1
client.setCarControls(car_controls1, "Car1")
print("Car1: Apply break")
car_controls1.brake = 0 #remove break
car_controls2.brake = 1
client.setCarControls(car_controls2, "Car2")
print("Car2: Apply break")
car_controls2.brake = 0 #remove break
time.sleep(3) # let car drive a bit
# get camera images from the car
responses1 = client.simGetImages([
airsim.ImageRequest("0", airsim.ImageType.DepthVis), #depth visualization image
airsim.ImageRequest("1", airsim.ImageType.Scene, False, False)], "Car1") #scene vision image in uncompressed RGB array
print('Car1: Retrieved images: %d' % (len(responses1)))
responses2 = client.simGetImages([
airsim.ImageRequest("0", airsim.ImageType.Segmentation), #depth visualization image
airsim.ImageRequest("1", airsim.ImageType.Scene, False, False)], "Car2") #scene vision image in uncompressed RGB array
print('Car2: Retrieved images: %d' % (len(responses2)))
for response in responses1 + responses2:
filename = 'c:/temp/car_multi_py' + str(idx)
if response.pixels_as_float:
print("Type %d, size %d" % (response.image_type, len(response.image_data_float)))
airsim.write_pfm(os.path.normpath(filename + '.pfm'), airsim.get_pfm_array(response))
elif response.compress: #png format
print("Type %d, size %d" % (response.image_type, len(response.image_data_uint8)))
airsim.write_file(os.path.normpath(filename + '.png'), response.image_data_uint8)
else: #uncompressed array
print("Type %d, size %d" % (response.image_type, len(response.image_data_uint8)))
img1d = np.fromstring(response.image_data_uint8, dtype=np.uint8) # get numpy array
img_rgb = img1d.reshape(response.height, response.width, 3) # reshape array to 3 channel image array H X W X 3
cv2.imwrite(os.path.normpath(filename + '.png'), img_rgb) # write to png
#restore to original state
client.reset()
client.enableApiControl(False)
| AirSim/PythonClient/car/multi_agent_car.py/0 | {
"file_path": "AirSim/PythonClient/car/multi_agent_car.py",
"repo_id": "AirSim",
"token_count": 1711
} | 34 |
# In settings.json first activate computer vision mode:
# https://github.com/Microsoft/AirSim/blob/main/docs/image_apis.md#computer-vision-mode
import setup_path
import airsim
import pprint
client = airsim.VehicleClient()
client.confirmConnection()
# objects can be named in two ways:
# 1. In UE Editor, select and object and change its name to something else. Note that you must *change* its name because
# default name is auto-generated and varies from run-to-run.
# 2. OR you can do this: In UE Editor select the object and then go to "Actor" section, click down arrow to see "Tags" property and add a tag there.
#
# The simGetObjectPose and simSetObjectPose uses first object that has specified name OR tag.
# more info: https://answers.unrealengine.com/questions/543807/whats-the-difference-between-tag-and-tag.html
# https://answers.unrealengine.com/revisions/790629.html
# below works in Blocks environment
#------------------------------------ Get current pose ------------------------------------------------
# search object by name:
pose1 = client.simGetObjectPose("OrangeBall");
print("OrangeBall - Position: %s, Orientation: %s" % (pprint.pformat(pose1.position),
pprint.pformat(pose1.orientation)))
# search another object by tag
pose2 = client.simGetObjectPose("PulsingCone");
print("PulsingCone - Position: %s, Orientation: %s" % (pprint.pformat(pose2.position),
pprint.pformat(pose2.orientation)))
# search non-existent object
pose3 = client.simGetObjectPose("Non-Existent"); # should return nan pose
print("Non-Existent - Position: %s, Orientation: %s" % (pprint.pformat(pose3.position),
pprint.pformat(pose3.orientation)))
#------------------------------------ Set new pose ------------------------------------------------
# here we move with teleport enabled so collisions are ignored
pose1.position = pose1.position + airsim.Vector3r(-2, -2, -2)
success = client.simSetObjectPose("OrangeBall", pose1, True);
airsim.wait_key("OrangeBall moved. Success: %i" % (success))
# here we move with teleport enabled so collisions are not ignored
pose2.position = pose2.position + airsim.Vector3r(3, 3, -2)
success = client.simSetObjectPose("PulsingCone", pose2, False);
airsim.wait_key("PulsingCone moved. Success: %i" % (success))
# move non-existent object
success = client.simSetObjectPose("Non-Existent", pose2); # should return nan pose
airsim.wait_key("Non-Existent moved. Success: %i" % (success))
#------------------------------------ Get new pose ------------------------------------------------
pose1 = client.simGetObjectPose("OrangeBall");
print("OrangeBall - Position: %s, Orientation: %s" % (pprint.pformat(pose1.position),
pprint.pformat(pose1.orientation)))
# search another object by tag
pose2 = client.simGetObjectPose("PulsingCone");
print("PulsingCone - Position: %s, Orientation: %s" % (pprint.pformat(pose2.position),
pprint.pformat(pose2.orientation)))
# search non-existent object
pose3 = client.simGetObjectPose("Non-Existent"); # should return nan pose
print("Non-Existent - Position: %s, Orientation: %s" % (pprint.pformat(pose3.position),
pprint.pformat(pose3.orientation))) | AirSim/PythonClient/computer_vision/objects.py/0 | {
"file_path": "AirSim/PythonClient/computer_vision/objects.py",
"repo_id": "AirSim",
"token_count": 973
} | 35 |
import airsim
import time
def RunConsoleCmd(client, cmd):
client.simRunConsoleCommand(cmd)
print(f"Running Unreal Console cmd '{cmd}' and sleeping for 1 second")
time.sleep(1.0)
def RunCmdList(client):
RunConsoleCmd(client, 'stat fps')
RunConsoleCmd(client, 'stat unit')
RunConsoleCmd(client, 'stat unitGraph')
RunConsoleCmd(client, 'show COLLISION')
RunConsoleCmd(client, 'show CollisionVisibility')
RunConsoleCmd(client, 'stat game')
RunConsoleCmd(client, 'show COLLISION')
RunConsoleCmd(client, 'show CollisionVisibility')
RunConsoleCmd(client, 'stat game')
RunConsoleCmd(client, 'stat unitGraph')
RunConsoleCmd(client, 'stat unit')
RunConsoleCmd(client, 'stat fps')
def main():
client = airsim.client.MultirotorClient()
client.confirmConnection()
RunCmdList(client)
if __name__ == "__main__":
main()
| AirSim/PythonClient/environment/unreal_console_commands.py/0 | {
"file_path": "AirSim/PythonClient/environment/unreal_console_commands.py",
"repo_id": "AirSim",
"token_count": 314
} | 36 |
import setup_path
import airsim
client = airsim.MultirotorClient()
client.armDisarm(False)
| AirSim/PythonClient/multirotor/disarm.py/0 | {
"file_path": "AirSim/PythonClient/multirotor/disarm.py",
"repo_id": "AirSim",
"token_count": 30
} | 37 |
import setup_path
import airsim
import sys
import time
print("""This script is designed to fly on the streets of the Neighborhood environment
and assumes the unreal position of the drone is [160, -1500, 120].""")
client = airsim.MultirotorClient()
client.confirmConnection()
client.enableApiControl(True)
print("arming the drone...")
client.armDisarm(True)
state = client.getMultirotorState()
if state.landed_state == airsim.LandedState.Landed:
print("taking off...")
client.takeoffAsync().join()
else:
client.hoverAsync().join()
time.sleep(1)
state = client.getMultirotorState()
if state.landed_state == airsim.LandedState.Landed:
print("take off failed...")
sys.exit(1)
# AirSim uses NED coordinates so negative axis is up.
# z of -5 is 5 meters above the original launch point.
z = -5
print("make sure we are hovering at {} meters...".format(-z))
client.moveToZAsync(z, 1).join()
# see https://github.com/Microsoft/AirSim/wiki/moveOnPath-demo
# this method is async and we are not waiting for the result since we are passing timeout_sec=0.
print("flying on path...")
result = client.moveOnPathAsync([airsim.Vector3r(125,0,z),
airsim.Vector3r(125,-130,z),
airsim.Vector3r(0,-130,z),
airsim.Vector3r(0,0,z)],
12, 120,
airsim.DrivetrainType.ForwardOnly, airsim.YawMode(False,0), 20, 1).join()
# drone will over-shoot so we bring it back to the start point before landing.
client.moveToPositionAsync(0,0,z,1).join()
print("landing...")
client.landAsync().join()
print("disarming...")
client.armDisarm(False)
client.enableApiControl(False)
print("done.")
| AirSim/PythonClient/multirotor/path.py/0 | {
"file_path": "AirSim/PythonClient/multirotor/path.py",
"repo_id": "AirSim",
"token_count": 673
} | 38 |
###################################################################################################
#
# Project: Embedded Learning Library (ELL)
# File: wav_reader.py
# Authors: Chris Lovett
#
# Requires: Python 3.x
#
###################################################################################################
import audioop
import math
import wave
import numpy as np
import pyaudio
class WavReader:
def __init__(self, sample_rate=16000, channels=1, auto_scale=True):
""" Initialize the wav reader with the type of audio you want returned.
sample_rate Rate you want audio converted to (default 16 kHz)
channels Number of channels you want output (default 1)
auto_scale Whether to scale numbers to the range -1 to 1.
"""
self.input_stream = None
self.audio = pyaudio.PyAudio()
self.wav_file = None
self.requested_channels = int(channels)
self.requested_rate = int(sample_rate)
self.buffer_size = 0
self.sample_width = 0
self.read_size = None
self.dtype = None
self.auto_scale = auto_scale
self.audio_scale_factor = 1
self.tail = None
def open(self, filename, buffer_size, speaker=None):
""" open a wav file for reading
buffersize Number of audio samples to return on each read() call
speaker Optional output speaker to send converted audio to so you can hear it.
"""
self.speaker = speaker
# open a stream on the audio input file.
self.wav_file = wave.open(filename, "rb")
self.cvstate = None
self.read_size = int(buffer_size)
self.actual_channels = self.wav_file.getnchannels()
self.actual_rate = self.wav_file.getframerate()
self.sample_width = self.wav_file.getsampwidth()
# assumes signed integer used in raw audio, so for example, the max for 16bit is 2^15 (32768)
if self.auto_scale:
self.audio_scale_factor = 1 / pow(2, (8 * self.sample_width) - 1)
if self.requested_rate == 0:
raise Exception("Requested rate cannot be zero")
self.buffer_size = int(math.ceil((self.read_size * self.actual_rate) / self.requested_rate))
# convert int16 data to scaled floats
if self.sample_width == 1:
self.dtype = np.int8
elif self.sample_width == 2:
self.dtype = np.int16
elif self.sample_width == 4:
self.dtype = np.int32
else:
msg = "Unexpected sample width {}, can only handle 1, 2 or 4 byte audio"
raise Exception(msg.format(self.sample_width))
if speaker:
# configure output stream to match what we are resampling to...
audio_format = self.audio.get_format_from_width(self.sample_width)
speaker.open(audio_format, self.requested_channels, self.requested_rate)
def read_raw(self):
""" Reads the next chunk of audio (returns buffer_size provided to open)
It returns the raw data buffers converted to the target rate without any scaling.
"""
if self.wav_file is None:
return None
data = self.wav_file.readframes(self.buffer_size)
if len(data) == 0:
return None
if self.actual_rate != self.requested_rate:
# convert the audio to the desired recording rate
data, self.cvstate = audioop.ratecv(data, self.sample_width, self.actual_channels, self.actual_rate,
self.requested_rate, self.cvstate)
return self.get_requested_channels(data)
def get_requested_channels(self, data):
if self.requested_channels > self.actual_channels:
raise Exception("Cannot add channels, actual is {}, requested is {}".format(
self.actual_channels, self.requested_channels))
if self.requested_channels < self.actual_channels:
data = np.frombuffer(data, dtype=np.int16)
channels = []
# split into separate channels
for i in range(self.actual_channels):
channels += [data[i::self.actual_channels]]
# drop the channels we don't want
channels = channels[0:self.requested_channels]
# zip the resulting channels back up.
data = np.array(list(zip(*channels))).flatten()
# convert back to packed bytes in PCM 16 format
data = bytes(np.array(data, dtype=np.int16))
return data
def read(self):
""" Reads the next chunk of audio (returns buffer_size provided to open)
It returns the data converted to floating point numbers between -1 and 1, scaled by the range of
values possible for the given audio format.
"""
# deal with any accumulation of tails, if the tail grows to a full
# buffer then return it!
if self.tail is not None and len(self.tail) >= self.read_size:
data = self.tail[0:self.read_size]
self.tail = self.tail[self.read_size:]
return data
data = self.read_raw()
if data is None:
return None
if self.speaker:
self.speaker.write(data)
data = np.frombuffer(data, dtype=self.dtype).astype(float)
if self.tail is not None:
# we have a tail from previous frame, so prepend it
data = np.concatenate((self.tail, data))
# now the caller needs us to stick to our sample_size contract, but when
# rate conversion happens we can't be sure that 'data' is exactly that size.
if len(data) > self.read_size:
# usually one byte extra so add this to our accumulating tail
self.tail = data[self.read_size:]
data = data[0:self.read_size]
if len(data) < self.read_size:
# might have reached the end of a file, so pad with zeros.
zeros = np.zeros(self.read_size - len(data))
data = np.concatenate((data, zeros))
return data * self.audio_scale_factor
def close(self):
if self.wav_file:
self.wav_file.close()
self.wav_file = None
def is_closed(self):
return self.wav_file is None
| AirSim/PythonClient/multirotor/wav_reader.py/0 | {
"file_path": "AirSim/PythonClient/multirotor/wav_reader.py",
"repo_id": "AirSim",
"token_count": 2624
} | 39 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// by Sudipta Sinha
// adapted for AirSim by Matthias Mueller
#ifndef dsimage_h
#define dsimage_h
#include <stdio.h>
#include <limits.h>
#include <float.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
class DSI
{
public:
DSI()
{
m_cols = 0;
m_rows = 0;
m_planes = 0;
m_data = NULL;
}
void create(uint64_t cols, uint64_t rows, uint64_t planes)
{
m_cols = cols;
m_rows = rows;
m_planes = planes;
uint64_t pixelCount = m_cols * m_rows * m_planes;
m_data = (short*)_aligned_malloc(pixelCount * sizeof(short), 16);
if (!m_data) {
printf("[ERROR] not enough memory!\n");
exit(1);
}
}
void setzero()
{
uint64_t pixelCount = m_cols * m_rows * m_planes;
memset(m_data, 0, pixelCount * sizeof(short));
}
short operator()(uint64_t x, uint64_t y, uint64_t z) const
{
return m_data[(x + y * m_cols) * m_planes + z];
}
short& operator()(uint64_t x, uint64_t y, uint64_t z)
{
return m_data[(x + y * m_cols) * m_planes + z];
}
short* operator()(uint64_t x, uint64_t y) const
{
return &(m_data[(x + y * m_cols) * m_planes]);
}
void getDispMap(int confThreshold, int doSubPixRefinement, float* dispMap, unsigned char* confMap)
{
// first row
{
uint64_t offset = 0;
float* pDisp = &(dispMap[offset]);
unsigned char* pConf = &(confMap[offset]);
for (int x = 0; x < m_cols; x++) {
pDisp[x] = FLT_MAX;
pConf[x] = 0;
}
}
// last row
{
uint64_t offset = (m_rows - 1) * m_cols;
float* pDisp = &(dispMap[offset]);
unsigned char* pConf = &(confMap[offset]);
for (int x = 0; x < m_cols; x++) {
pDisp[x] = FLT_MAX;
pConf[x] = 0;
}
}
for (int y = 0; y < m_rows; y++) {
uint64_t offset = y * m_cols;
float* pDisp = &(dispMap[offset]);
unsigned char* pConf = &(confMap[offset]);
{
pDisp[0] = FLT_MAX;
pConf[0] = 0;
pDisp[m_cols - 1] = FLT_MAX;
pConf[m_cols - 1] = 0;
}
}
for (int y = 1; y < m_rows - 1; y++) {
uint64_t offset = y * m_cols;
float* pDisp = &(dispMap[offset]);
unsigned char* pConf = &(confMap[offset]);
#pragma omp parallel for schedule(dynamic, 1)
for (int x = 1; x < m_cols - 1; x++) {
int bestplane = (int)m_planes - 1;
short minval = SHRT_MAX;
short secondminval = SHRT_MAX;
short* pV = (*this)(x, y);
for (int d = 0; d < m_planes; d++) {
short val = pV[d];
if (val < minval) {
minval = val;
bestplane = d;
}
}
for (int d = 0; d < m_planes; d++) {
if (abs(d - bestplane) > 2) {
short val = pV[d];
if (val < secondminval) {
secondminval = val;
}
}
}
float distinctiveness1 = float(minval) / float(secondminval + 1e-9f);
float conf = (float)__min(__max(20.0f * log(1.0f / (distinctiveness1 * distinctiveness1)), 0.0f), 255.0f);
int Dim = (int)m_planes;
if (conf >= confThreshold) {
// Local quadratic fit of cost and subpixel refinement.
double rDisp = bestplane;
double rCost = minval;
if (doSubPixRefinement) {
if (bestplane >= 1 && bestplane < m_planes - 1) {
double yl = pV[bestplane - 1];
double xc = bestplane;
double yc = minval;
double yu = pV[bestplane + 1];
double d2 = yu - yc + yl - yc;
double d1 = 0.5 * (yu - yl);
if (fabs(d2) > fabs(d1)) {
rDisp = xc - d1 / d2;
rCost = yc + 0.5 * d1 * (rDisp - xc);
}
}
}
pDisp[x] = (float)(rDisp - Dim);
pConf[x] = (unsigned char)conf;
}
else {
pDisp[x] = FLT_MAX;
pConf[x] = 0;
}
}
}
}
~DSI()
{
free();
}
void free()
{
if (m_data != NULL)
_aligned_free(m_data);
m_data = NULL;
}
uint64_t m_cols;
uint64_t m_rows;
uint64_t m_planes;
short* m_data;
};
void getDispMap2(DSI& dv1, DSI& dv2, int confThreshold, float* dispMap, unsigned char* confMap);
#endif
#if 0
void dump(vt::CByteImg& left, vt::CByteImg& right, int flag)
{
int w = m_cols;
int h = m_rows;
for (int d = 0; d < m_planes; d++)
{
vt::CByteImg D;
D.Create(w, h);
D.Fill(byte(255));
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
{
D(j, i) = (*this)(j, i, d);
}
}
}
vt::wstring fn;
fn.format_with_resize(L"dsi%d/disp-%04d.png", flag, d);
vt::VtSaveImage(fn, D);
}
}
#endif | AirSim/SGM/src/sgmstereo/dsimage.h/0 | {
"file_path": "AirSim/SGM/src/sgmstereo/dsimage.h",
"repo_id": "AirSim",
"token_count": 3435
} | 40 |
#include "NedTransform.h"
NedTransform::NedTransform(const AirSimUnity::UnityTransform& global_transform)
: global_transform_(global_transform)
{
local_ned_offset_ = AirSimUnity::AirSimVector(0.0f, 0.0f, 0.0f);
}
NedTransform::NedTransform(const NedTransform& global_transform)
: global_transform_(global_transform.global_transform_)
{
}
| AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/NedTransform.cpp/0 | {
"file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/NedTransform.cpp",
"repo_id": "AirSim",
"token_count": 123
} | 41 |
#pragma once
#include "sensors/distance/DistanceSimple.hpp"
#include "../NedTransform.h"
class UnityDistanceSensor : public msr::airlib::DistanceSimple
{
private:
using Vector3r = msr::airlib::Vector3r;
using VectorMath = msr::airlib::VectorMath;
private:
std::string vehicle_name_;
const NedTransform* ned_transform_;
protected:
virtual msr::airlib::real_T getRayLength(const msr::airlib::Pose& pose) override;
public:
UnityDistanceSensor(std::string vehicle_name, const NedTransform* ned_transform);
}; | AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/UnitySensors/UnityDistanceSensor.h/0 | {
"file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/UnitySensors/UnityDistanceSensor.h",
"repo_id": "AirSim",
"token_count": 186
} | 42 |
#include "MultirotorPawnEvents.h"
MultirotorPawnEvents::ActuatorsSignal& MultirotorPawnEvents::getActuatorSignal()
{
return actuator_signal_;
} | AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/Vehicles/Multirotor/MultirotorPawnEvents.cpp/0 | {
"file_path": "AirSim/Unity/AirLibWrapper/AirsimWrapper/Source/Vehicles/Multirotor/MultirotorPawnEvents.cpp",
"repo_id": "AirSim",
"token_count": 57
} | 43 |
fileFormatVersion: 2
guid: d5746c3f216f7b84db940c7a63b44924
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:
| AirSim/Unity/UnityDemo/Assets/AirSimAssets/Materials/BoxMatte.mat.meta/0 | {
"file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Materials/BoxMatte.mat.meta",
"repo_id": "AirSim",
"token_count": 75
} | 44 |
fileFormatVersion: 2
guid: 4e4f776850f4b674b82eae8fffd345a3
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| AirSim/Unity/UnityDemo/Assets/AirSimAssets/Models.meta/0 | {
"file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Models.meta",
"repo_id": "AirSim",
"token_count": 71
} | 45 |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1001 &100100000
Prefab:
m_ObjectHideFlags: 1
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications: []
m_RemovedComponents: []
m_ParentPrefab: {fileID: 0}
m_RootGameObject: {fileID: 1785388642459644}
m_IsPrefabParent: 1
--- !u!1 &1785388642459644
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
serializedVersion: 5
m_Component:
- component: {fileID: 4839338518106128}
- component: {fileID: 20831533243704616}
- component: {fileID: 114452840078650500}
- component: {fileID: 114809665771648990}
m_Layer: 0
m_Name: RecorderCamera
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &4839338518106128
Transform:
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 1785388642459644}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!20 &20831533243704616
Camera:
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 1785388642459644}
m_Enabled: 0
serializedVersion: 2
m_ClearFlags: 1
m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0}
m_NormalizedViewPortRect:
serializedVersion: 2
x: 0
y: 0
width: 1
height: 1
near clip plane: 0.3
far clip plane: 1000
field of view: 90
orthographic: 0
orthographic size: 5
m_Depth: 0
m_CullingMask:
serializedVersion: 2
m_Bits: 4294966783
m_RenderingPath: -1
m_TargetTexture: {fileID: 0}
m_TargetDisplay: 0
m_TargetEye: 3
m_HDR: 0
m_AllowMSAA: 0
m_AllowDynamicResolution: 0
m_ForceIntoRT: 0
m_OcclusionCulling: 0
m_StereoConvergence: 10
m_StereoSeparation: 0.022
--- !u!114 &114452840078650500
MonoBehaviour:
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 1785388642459644}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 5d488591858471a4bbef459e45d9a839, type: 3}
m_Name:
m_EditorClassIdentifier:
--- !u!114 &114809665771648990
MonoBehaviour:
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 1785388642459644}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: c48225d48417d5d4cb478d7a050df49c, type: 3}
m_Name:
m_EditorClassIdentifier:
effect: 0
effectsShader: {fileID: 4800000, guid: e03150fb5e358274881026fc928ae40f, type: 3}
| AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs/RecorderCamera.prefab/0 | {
"file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Prefabs/RecorderCamera.prefab",
"repo_id": "AirSim",
"token_count": 1250
} | 46 |
using UnityEngine;
using UnityEngine.UI;
namespace AirSimUnity {
/// <summary>
/// HUD class that manage weather-related UI elements.
/// </summary>
public class WeatherHUD : MonoBehaviour {
[SerializeField] private RectTransform rootPanel = default;
[SerializeField] private Toggle weatherEnabledToggle = default;
[SerializeField] private WeatherHUDSlider snowSlider = default;
private void Start() {
rootPanel.gameObject.SetActive(false);
weatherEnabledToggle.onValueChanged.AddListener(OnWeatherEnabledToggleChanged);
snowSlider.OnValueChanged.AddListener(OnSnowSliderChanged);
}
private void OnValidate() {
Debug.Assert(rootPanel != null);
Debug.Assert(weatherEnabledToggle != null);
Debug.Assert(snowSlider != null);
}
private void Update() {
if (Input.GetKeyDown(KeyCode.F10)) {
rootPanel.gameObject.SetActive(!rootPanel.gameObject.activeSelf);
}
if (!rootPanel.gameObject.activeSelf) {
return;
}
Weather weather = AirSimGlobal.Instance.Weather;
weatherEnabledToggle.isOn = weather.IsWeatherEnabled;
snowSlider.Value = weather.ParamScalars[WeatherParamScalarCollection.WeatherParamScalar.Snow];
}
private void OnWeatherEnabledToggleChanged(bool isEnabled) {
AirSimGlobal.Instance.Weather.IsWeatherEnabled = isEnabled;
}
private void OnSnowSliderChanged(float value) {
AirSimGlobal.Instance.Weather.ParamScalars[WeatherParamScalarCollection.WeatherParamScalar.Snow] = value;
}
}
}
| AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/HUD/WeatherHUD.cs/0 | {
"file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/HUD/WeatherHUD.cs",
"repo_id": "AirSim",
"token_count": 711
} | 47 |
fileFormatVersion: 2
guid: 9cc58e6de68c02747a4aa12440551a3b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: -50
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Utilities/AirSimTick.cs.meta/0 | {
"file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Utilities/AirSimTick.cs.meta",
"repo_id": "AirSim",
"token_count": 95
} | 48 |
fileFormatVersion: 2
guid: f59d16aa1e7f4604fb096f0482db4819
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Weather/WeatherParamScalarCollection.cs.meta/0 | {
"file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Scripts/Weather/WeatherParamScalarCollection.cs.meta",
"repo_id": "AirSim",
"token_count": 95
} | 49 |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &7321015775731177144
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 2122546159185921841}
- component: {fileID: 8776546933388946425}
m_Layer: 0
m_Name: WeatherFX
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &2122546159185921841
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7321015775731177144}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 0.07692307, y: 0.07692307, z: 0.07692307}
m_Children:
- {fileID: 5661139042435920074}
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &8776546933388946425
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7321015775731177144}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 7ef6019d2a42db14cadb432a6c6cc7d7, type: 3}
m_Name:
m_EditorClassIdentifier:
snowParticleSystem: {fileID: 7137805003512388501}
--- !u!1001 &8301748675695978906
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 2122546159185921841}
m_Modifications:
- target: {fileID: 4442198055719098704, guid: 56587ec32694e684a97ecabef25d589d,
type: 3}
propertyPath: m_LocalPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4442198055719098704, guid: 56587ec32694e684a97ecabef25d589d,
type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4442198055719098704, guid: 56587ec32694e684a97ecabef25d589d,
type: 3}
propertyPath: m_LocalPosition.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4442198055719098704, guid: 56587ec32694e684a97ecabef25d589d,
type: 3}
propertyPath: m_LocalRotation.x
value: -0
objectReference: {fileID: 0}
- target: {fileID: 4442198055719098704, guid: 56587ec32694e684a97ecabef25d589d,
type: 3}
propertyPath: m_LocalRotation.y
value: -0
objectReference: {fileID: 0}
- target: {fileID: 4442198055719098704, guid: 56587ec32694e684a97ecabef25d589d,
type: 3}
propertyPath: m_LocalRotation.z
value: -0
objectReference: {fileID: 0}
- target: {fileID: 4442198055719098704, guid: 56587ec32694e684a97ecabef25d589d,
type: 3}
propertyPath: m_LocalRotation.w
value: 1
objectReference: {fileID: 0}
- target: {fileID: 4442198055719098704, guid: 56587ec32694e684a97ecabef25d589d,
type: 3}
propertyPath: m_RootOrder
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4442198055719098704, guid: 56587ec32694e684a97ecabef25d589d,
type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4442198055719098704, guid: 56587ec32694e684a97ecabef25d589d,
type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4442198055719098704, guid: 56587ec32694e684a97ecabef25d589d,
type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 4442198055719098717, guid: 56587ec32694e684a97ecabef25d589d,
type: 3}
propertyPath: m_Name
value: P_Weather_SnowFX
objectReference: {fileID: 0}
m_RemovedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 56587ec32694e684a97ecabef25d589d, type: 3}
--- !u!4 &5661139042435920074 stripped
Transform:
m_CorrespondingSourceObject: {fileID: 4442198055719098704, guid: 56587ec32694e684a97ecabef25d589d,
type: 3}
m_PrefabInstance: {fileID: 8301748675695978906}
m_PrefabAsset: {fileID: 0}
--- !u!198 &7137805003512388501 stripped
ParticleSystem:
m_CorrespondingSourceObject: {fileID: 1169581006881108495, guid: 56587ec32694e684a97ecabef25d589d,
type: 3}
m_PrefabInstance: {fileID: 8301748675695978906}
m_PrefabAsset: {fileID: 0}
| AirSim/Unity/UnityDemo/Assets/AirSimAssets/Weather/WeatherFX/Prefabs/WeatherFX.prefab/0 | {
"file_path": "AirSim/Unity/UnityDemo/Assets/AirSimAssets/Weather/WeatherFX/Prefabs/WeatherFX.prefab",
"repo_id": "AirSim",
"token_count": 2093
} | 50 |
fileFormatVersion: 2
guid: c7a2a8bd86543e4488e32b1cbfaefaa3
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| AirSim/Unity/UnityDemo/Assets/Scenes/WeatherTest.unity.meta/0 | {
"file_path": "AirSim/Unity/UnityDemo/Assets/Scenes/WeatherTest.unity.meta",
"repo_id": "AirSim",
"token_count": 67
} | 51 |
fileFormatVersion: 2
guid: 965a4c3cf8f0acb408f15384c947b3fd
NativeFormatImporter:
userData:
assetBundleName:
| AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Materials/SkyCarWheelGrey.mat.meta/0 | {
"file_path": "AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Materials/SkyCarWheelGrey.mat.meta",
"repo_id": "AirSim",
"token_count": 52
} | 52 |
fileFormatVersion: 2
guid: 9486e5d1d37e86246b9bd1e314a8a721
TextureImporter:
fileIDToRecycleName: {}
serializedVersion: 2
mipmaps:
mipMapMode: 0
enableMipMap: 1
linearTexture: 0
correctGamma: 0
fadeOut: 0
borderMipMap: 0
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 0
generateCubemap: 0
cubemapConvolution: 0
cubemapConvolutionSteps: 8
cubemapConvolutionExponent: 1.5
seamlessCubemap: 0
textureFormat: -1
maxTextureSize: 1024
textureSettings:
filterMode: 2
aniso: 2
mipBias: -1
wrapMode: -1
nPOTScale: 1
lightmap: 0
rGBM: 0
compressionQuality: 50
allowsAlphaSplitting: 0
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: -1
buildTargetSettings: []
spriteSheet:
sprites: []
outline: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:
| AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Textures/SkyCarWheelOcclusion.png.meta/0 | {
"file_path": "AirSim/Unity/UnityDemo/Assets/Standard Assets/Vehicles/Car/Textures/SkyCarWheelOcclusion.png.meta",
"repo_id": "AirSim",
"token_count": 502
} | 53 |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!78 &1
TagManager:
serializedVersion: 2
tags:
- CaptureCameras
- ViewCameras
layers:
- Default
- TransparentFX
- Ignore Raycast
-
- Water
- UI
-
-
- PostProcessing
- Vehicle
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
m_SortingLayers:
- name: Default
uniqueID: 0
locked: 0
| AirSim/Unity/UnityDemo/ProjectSettings/TagManager.asset/0 | {
"file_path": "AirSim/Unity/UnityDemo/ProjectSettings/TagManager.asset",
"repo_id": "AirSim",
"token_count": 229
} | 54 |
[/Script/Engine.InputSettings]
bAltEnterTogglesFullscreen=True
bF11TogglesFullscreen=True
bUseMouseForTouch=False
bEnableMouseSmoothing=True
bEnableFOVScaling=True
FOVScale=0.011110
DoubleClickTime=0.200000
bCaptureMouseOnLaunch=False
DefaultViewportMouseCaptureMode=NoCapture
bDefaultViewportMouseLock=False
DefaultViewportMouseLockMode=DoNotLock
bAlwaysShowTouchInterface=False
bShowConsoleOnFourFingerTap=True
DefaultTouchInterface=/Engine/MobileResources/HUD/DefaultVirtualJoysticks.DefaultVirtualJoysticks
ConsoleKey=None
-ConsoleKeys=Tilde
+ConsoleKeys=Tilde
| AirSim/Unreal/Environments/Blocks/Config/DefaultInput.ini/0 | {
"file_path": "AirSim/Unreal/Environments/Blocks/Config/DefaultInput.ini",
"repo_id": "AirSim",
"token_count": 171
} | 55 |
#! /bin/bash
# get path of current script: https://stackoverflow.com/a/39340259/207661
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
pushd "$SCRIPT_DIR" >/dev/null
set -e
set -x
# clean temporary unreal folders
rm -rf Binaries
rm -rf Intermediate
rm -rf Saved
rm -rf Plugins/AirSim/Binaries
rm -rf Plugins/AirSim/Intermediate
rm -rf Plugins/AirSim/Saved
rm -f CMakeLists.txt
rm -f Makefile
popd >/dev/null | AirSim/Unreal/Environments/Blocks/clean.sh/0 | {
"file_path": "AirSim/Unreal/Environments/Blocks/clean.sh",
"repo_id": "AirSim",
"token_count": 170
} | 56 |
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "GameFramework/GameUserSettings.h"
#include "AirSimGameMode.generated.h"
/**
*
*/
UCLASS()
class AIRSIM_API AAirSimGameMode : public AGameModeBase
{
public:
GENERATED_BODY()
virtual void StartPlay() override;
AAirSimGameMode(const FObjectInitializer& ObjectInitializer);
//private:
//UGameUserSettings* GetGameUserSettings();
};
| AirSim/Unreal/Plugins/AirSim/Source/AirSimGameMode.h/0 | {
"file_path": "AirSim/Unreal/Plugins/AirSim/Source/AirSimGameMode.h",
"repo_id": "AirSim",
"token_count": 174
} | 57 |
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "Particles/ParticleSystemComponent.h"
#include "UnrealImageCapture.h"
#include <vector>
#include <memory>
#include "common/Common.hpp"
#include "common/common_utils/Signal.hpp"
#include "common/CommonStructs.hpp"
#include "common/GeodeticConverter.hpp"
#include "PIPCamera.h"
#include "physics/Kinematics.hpp"
#include "NedTransform.h"
#include "common/AirSimSettings.hpp"
#include "SimJoyStick/SimJoyStick.h"
#include "api/VehicleApiBase.hpp"
#include "api/VehicleSimApiBase.hpp"
#include "common/common_utils/UniqueValueMap.hpp"
#include "PawnEvents.h"
class PawnSimApi : public msr::airlib::VehicleSimApiBase
{
public: //types
typedef msr::airlib::GeoPoint GeoPoint;
typedef msr::airlib::Vector2r Vector2r;
typedef msr::airlib::Vector3r Vector3r;
typedef msr::airlib::Pose Pose;
typedef msr::airlib::Quaternionr Quaternionr;
typedef msr::airlib::CollisionInfo CollisionInfo;
typedef msr::airlib::VectorMath VectorMath;
typedef msr::airlib::real_T real_T;
typedef msr::airlib::Utils Utils;
typedef msr::airlib::AirSimSettings::VehicleSetting VehicleSetting;
typedef msr::airlib::ImageCaptureBase ImageCaptureBase;
typedef msr::airlib::DetectionInfo DetectionInfo;
typedef msr::airlib::Kinematics Kinematics;
struct Params
{
APawn* pawn;
const NedTransform* global_transform;
PawnEvents* pawn_events;
common_utils::UniqueValueMap<std::string, APIPCamera*> cameras;
UClass* pip_camera_class;
UParticleSystem* collision_display_template;
msr::airlib::GeoPoint home_geopoint;
std::string vehicle_name;
Params()
{
}
Params(APawn* pawn_val, const NedTransform* global_transform_val, PawnEvents* pawn_events_val,
const common_utils::UniqueValueMap<std::string, APIPCamera*>& cameras_val, UClass* pip_camera_class_val,
UParticleSystem* collision_display_template_val, const msr::airlib::GeoPoint& home_geopoint_val,
const std::string& vehicle_name_val)
: pawn(pawn_val)
, global_transform(global_transform_val)
, pawn_events(pawn_events_val)
, cameras(cameras_val)
, pip_camera_class(pip_camera_class_val)
, collision_display_template(collision_display_template_val)
, home_geopoint(home_geopoint_val)
, vehicle_name(vehicle_name_val)
{
}
};
public: //implementation of VehicleSimApiBase
virtual void initialize() override;
virtual void resetImplementation() override;
virtual void update() override;
virtual const UnrealImageCapture* getImageCapture() const override;
virtual Pose getPose() const override;
virtual void setPose(const Pose& pose, bool ignore_collision) override;
virtual CollisionInfo getCollisionInfo() const override;
virtual CollisionInfo getCollisionInfoAndReset() override;
virtual int getRemoteControlID() const override;
virtual msr::airlib::RCData getRCData() const override;
virtual std::string getVehicleName() const override
{
return params_.vehicle_name;
}
virtual void toggleTrace() override;
virtual void setTraceLine(const std::vector<float>& color_rgba, float thickness) override;
virtual void updateRenderedState(float dt) override;
virtual void updateRendering(float dt) override;
virtual const msr::airlib::Kinematics::State* getGroundTruthKinematics() const override;
virtual void setKinematics(const msr::airlib::Kinematics::State& state, bool ignore_collision) override;
virtual const msr::airlib::Environment* getGroundTruthEnvironment() const override;
virtual std::string getRecordFileLine(bool is_header_line) const override;
virtual void reportState(msr::airlib::StateReporter& reporter) override;
protected: //additional interface for derived class
virtual void pawnTick(float dt);
void setPoseInternal(const Pose& pose, bool ignore_collision);
virtual msr::airlib::VehicleApiBase* getVehicleApiBase() const;
msr::airlib::Kinematics* getKinematics();
msr::airlib::Environment* getEnvironment();
public: //Unreal specific methods
PawnSimApi(const Params& params);
//returns one of the cameras attached to the pawn
const APIPCamera* getCamera(const std::string& camera_name) const;
APIPCamera* getCamera(const std::string& camera_name);
int getCameraCount();
virtual bool testLineOfSightToPoint(const msr::airlib::GeoPoint& point) const;
//if enabled, this would show some flares
void displayCollisionEffect(FVector hit_location, const FHitResult& hit);
//return the attached pawn
APawn* getPawn();
//get/set pose
//parameters in NED frame
void setDebugPose(const Pose& debug_pose);
FVector getUUPosition() const;
FRotator getUUOrientation() const;
const NedTransform& getNedTransform() const;
void possess();
void setRCForceFeedback(float rumble_strength, float auto_center);
private: //methods
bool canTeleportWhileMove() const;
void allowPassthroughToggleInput();
void detectUsbRc();
void setupCamerasFromSettings(const common_utils::UniqueValueMap<std::string, APIPCamera*>& cameras);
void createCamerasFromSettings();
//on collision, pawns should update this
void onCollision(class UPrimitiveComponent* MyComp, class AActor* Other, class UPrimitiveComponent* OtherComp,
bool bSelfMoved, FVector HitLocation, FVector HitNormal, FVector NormalImpulse, const FHitResult& Hit);
//these methods are for future usage
void plot(std::istream& s, FColor color, const Vector3r& offset);
PawnSimApi::Pose toPose(const FVector& u_position, const FQuat& u_quat) const;
void updateKinematics(float dt);
void setStartPosition(const FVector& position, const FRotator& rotator);
private: //vars
typedef msr::airlib::AirSimSettings AirSimSettings;
typedef msr::airlib::Environment Environment;
Params params_;
common_utils::UniqueValueMap<std::string, APIPCamera*> cameras_;
msr::airlib::GeoPoint home_geo_point_;
std::string vehicle_name_;
NedTransform ned_transform_;
FVector ground_trace_end_;
FVector ground_margin_;
std::unique_ptr<UnrealImageCapture> image_capture_;
std::string log_line_;
mutable msr::airlib::RCData rc_data_;
mutable SimJoyStick joystick_;
mutable SimJoyStick::State joystick_state_;
struct State
{
FVector start_location;
FRotator start_rotation;
FVector last_position;
FVector last_debug_position;
FVector current_position;
FVector current_debug_position;
FVector debug_position_offset;
bool tracing_enabled;
bool collisions_enabled;
bool passthrough_enabled;
bool was_last_move_teleport;
CollisionInfo collision_info;
FVector mesh_origin;
FVector mesh_bounds;
FVector ground_offset;
FVector transformation_offset;
};
State state_, initial_state_;
std::unique_ptr<msr::airlib::Kinematics> kinematics_;
std::unique_ptr<msr::airlib::Environment> environment_;
FColor trace_color_ = FColor::Purple;
float trace_thickness_ = 3.0f;
};
| AirSim/Unreal/Plugins/AirSim/Source/PawnSimApi.h/0 | {
"file_path": "AirSim/Unreal/Plugins/AirSim/Source/PawnSimApi.h",
"repo_id": "AirSim",
"token_count": 2755
} | 58 |
#include "SimModeBase.h"
#include "Recording/RecordingThread.h"
#include "Misc/MessageDialog.h"
#include "Misc/EngineVersion.h"
#include "Runtime/Launch/Resources/Version.h"
#include "UObject/ConstructorHelpers.h"
#include "Kismet/GameplayStatics.h"
#include "Misc/OutputDeviceNull.h"
#include "Engine/World.h"
#include <memory>
#include "AirBlueprintLib.h"
#include "common/AirSimSettings.hpp"
#include "common/ScalableClock.hpp"
#include "common/SteppableClock.hpp"
#include "SimJoyStick/SimJoyStick.h"
#include "common/EarthCelestial.hpp"
#include "sensors/lidar/LidarSimple.hpp"
#include "sensors/distance/DistanceSimple.hpp"
#include "Weather/WeatherLib.h"
#include "DrawDebugHelpers.h"
//TODO: this is going to cause circular references which is fine here but
//in future we should consider moving SimMode not derived from AActor and move
//it to AirLib and directly implement WorldSimApiBase interface
#include "WorldSimApi.h"
ASimModeBase* ASimModeBase::SIMMODE = nullptr;
ASimModeBase* ASimModeBase::getSimMode()
{
return SIMMODE;
}
ASimModeBase::ASimModeBase()
{
SIMMODE = this;
static ConstructorHelpers::FClassFinder<APIPCamera> external_camera_class(TEXT("Blueprint'/AirSim/Blueprints/BP_PIPCamera'"));
external_camera_class_ = external_camera_class.Succeeded() ? external_camera_class.Class : nullptr;
static ConstructorHelpers::FClassFinder<ACameraDirector> camera_director_class(TEXT("Blueprint'/AirSim/Blueprints/BP_CameraDirector'"));
camera_director_class_ = camera_director_class.Succeeded() ? camera_director_class.Class : nullptr;
static ConstructorHelpers::FObjectFinder<UParticleSystem> collision_display(TEXT("ParticleSystem'/AirSim/StarterContent/Particles/P_Explosion.P_Explosion'"));
if (!collision_display.Succeeded())
collision_display_template = collision_display.Object;
else
collision_display_template = nullptr;
static ConstructorHelpers::FClassFinder<APIPCamera> pip_camera_class_val(TEXT("Blueprint'/AirSim/Blueprints/BP_PIPCamera'"));
pip_camera_class = pip_camera_class_val.Succeeded() ? pip_camera_class_val.Class : nullptr;
PrimaryActorTick.bCanEverTick = true;
static ConstructorHelpers::FClassFinder<AActor> sky_sphere_class(TEXT("Blueprint'/Engine/EngineSky/BP_Sky_Sphere'"));
sky_sphere_class_ = sky_sphere_class.Succeeded() ? sky_sphere_class.Class : nullptr;
static ConstructorHelpers::FClassFinder<UUserWidget> loading_screen_class_find(TEXT("WidgetBlueprint'/AirSim/Blueprints/BP_LoadingScreenWidget'"));
if (loading_screen_class_find.Succeeded()) {
auto loading_screen_class = loading_screen_class_find.Class;
loading_screen_widget_ = CreateWidget<ULoadingScreenWidget>(this->GetWorld(), loading_screen_class);
}
else
loading_screen_widget_ = nullptr;
static ConstructorHelpers::FObjectFinder<UMaterial> domain_rand_mat_finder(TEXT("Material'/AirSim/HUDAssets/DomainRandomizationMaterial.DomainRandomizationMaterial'"));
if (domain_rand_mat_finder.Succeeded()) {
domain_rand_material_ = domain_rand_mat_finder.Object;
}
}
void ASimModeBase::toggleLoadingScreen(bool is_visible)
{
if (loading_screen_widget_ == nullptr)
return;
else {
UAirBlueprintLib::RunCommandOnGameThread([this, is_visible]() {
if (is_visible)
loading_screen_widget_->SetVisibility(ESlateVisibility::Visible);
else
loading_screen_widget_->SetVisibility(ESlateVisibility::Hidden);
},
true);
}
}
void ASimModeBase::BeginPlay()
{
Super::BeginPlay();
debug_reporter_.initialize(false);
debug_reporter_.reset();
//get player start
//this must be done from within actor otherwise we don't get player start
TArray<AActor*> pawns;
getExistingVehiclePawns(pawns);
bool have_existing_pawns = pawns.Num() > 0;
AActor* fpv_pawn = nullptr;
// Grab player location
FTransform player_start_transform;
FVector player_loc;
if (have_existing_pawns) {
fpv_pawn = pawns[0];
}
else {
APlayerController* player_controller = this->GetWorld()->GetFirstPlayerController();
fpv_pawn = player_controller->GetViewTarget();
}
player_start_transform = fpv_pawn->GetActorTransform();
player_loc = player_start_transform.GetLocation();
// Move the world origin to the player's location (this moves the coordinate system and adds
// a corresponding offset to all positions to compensate for the shift)
this->GetWorld()->SetNewWorldOrigin(FIntVector(player_loc) + this->GetWorld()->OriginLocation);
// Regrab the player's position after the offset has been added (which should be 0,0,0 now)
player_start_transform = fpv_pawn->GetActorTransform();
global_ned_transform_.reset(new NedTransform(player_start_transform,
UAirBlueprintLib::GetWorldToMetersScale(this)));
UAirBlueprintLib::GenerateAssetRegistryMap(this, asset_map);
world_sim_api_.reset(new WorldSimApi(this));
api_provider_.reset(new msr::airlib::ApiProvider(world_sim_api_.get()));
UAirBlueprintLib::setLogMessagesVisibility(getSettings().log_messages_visible);
setupPhysicsLoopPeriod();
setupClockSpeed();
setStencilIDs();
record_tick_count = 0;
setupInputBindings();
initializeTimeOfDay();
AirSimSettings::TimeOfDaySetting tod_setting = getSettings().tod_setting;
setTimeOfDay(tod_setting.enabled, tod_setting.start_datetime, tod_setting.is_start_datetime_dst, tod_setting.celestial_clock_speed, tod_setting.update_interval_secs, tod_setting.move_sun);
UAirBlueprintLib::LogMessage(TEXT("Press F1 to see help"), TEXT(""), LogDebugLevel::Informational);
setupVehiclesAndCamera();
FRecordingThread::init();
if (getSettings().recording_setting.enabled)
startRecording();
UWorld* World = GetWorld();
if (World) {
UWeatherLib::initWeather(World, spawned_actors_);
//UWeatherLib::showWeatherMenu(World);
}
UAirBlueprintLib::GenerateActorMap(this, scene_object_map);
loading_screen_widget_->AddToViewport();
loading_screen_widget_->SetVisibility(ESlateVisibility::Hidden);
}
const NedTransform& ASimModeBase::getGlobalNedTransform()
{
return *global_ned_transform_;
}
void ASimModeBase::checkVehicleReady()
{
for (auto& api : api_provider_->getVehicleApis()) {
if (api) { //sim-only vehicles may have api as null
std::string message;
if (!api->isReady(message)) {
UAirBlueprintLib::LogMessage("Vehicle was not initialized", "", LogDebugLevel::Failure);
if (message.size() > 0) {
UAirBlueprintLib::LogMessage(message.c_str(), "", LogDebugLevel::Failure);
}
UAirBlueprintLib::LogMessage("Tip: check connection info in settings.json", "", LogDebugLevel::Informational);
}
}
}
}
void ASimModeBase::setStencilIDs()
{
UAirBlueprintLib::SetMeshNamingMethod(getSettings().segmentation_setting.mesh_naming_method);
if (getSettings().segmentation_setting.init_method ==
AirSimSettings::SegmentationSetting::InitMethodType::CommonObjectsRandomIDs) {
UAirBlueprintLib::InitializeMeshStencilIDs(getSettings().segmentation_setting.override_existing);
}
//else don't init
}
void ASimModeBase::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
FRecordingThread::stopRecording();
FRecordingThread::killRecording();
world_sim_api_.reset();
api_provider_.reset();
api_server_.reset();
global_ned_transform_.reset();
CameraDirector = nullptr;
sky_sphere_ = nullptr;
sun_ = nullptr;
spawned_actors_.Empty();
vehicle_sim_apis_.clear();
Super::EndPlay(EndPlayReason);
}
void ASimModeBase::initializeTimeOfDay()
{
sky_sphere_ = nullptr;
sun_ = nullptr;
TArray<AActor*> sky_spheres;
UGameplayStatics::GetAllActorsOfClass(this->GetWorld(), sky_sphere_class_, sky_spheres);
if (sky_spheres.Num() > 1)
UAirBlueprintLib::LogMessage(TEXT("More than BP_Sky_Sphere were found. "),
TEXT("TimeOfDay settings would be applied to first one."),
LogDebugLevel::Failure);
if (sky_spheres.Num() >= 1) {
sky_sphere_ = sky_spheres[0];
static const FName sun_prop_name(TEXT("Directional light actor"));
auto* p = sky_sphere_class_->FindPropertyByName(sun_prop_name);
#if ENGINE_MINOR_VERSION > 24
FObjectProperty* sun_prop = CastFieldChecked<FObjectProperty>(p);
#else
UObjectProperty* sun_prop = Cast<UObjectProperty>(p);
#endif
UObject* sun_obj = sun_prop->GetObjectPropertyValue_InContainer(sky_sphere_);
sun_ = Cast<ADirectionalLight>(sun_obj);
if (sun_)
default_sun_rotation_ = sun_->GetActorRotation();
}
}
void ASimModeBase::setTimeOfDay(bool is_enabled, const std::string& start_datetime, bool is_start_datetime_dst,
float celestial_clock_speed, float update_interval_secs, bool move_sun)
{
bool enabled_currently = tod_enabled_;
if (is_enabled) {
if (!sun_) {
UAirBlueprintLib::LogMessage(TEXT("BP_Sky_Sphere was not found. "),
TEXT("TimeOfDay settings would be ignored."),
LogDebugLevel::Failure);
}
else {
sun_->GetRootComponent()->Mobility = EComponentMobility::Movable;
// this is a bit odd but given how advanceTimeOfDay() works currently,
// tod_sim_clock_start_ needs to be reset here.
tod_sim_clock_start_ = ClockFactory::get()->nowNanos();
tod_last_update_ = 0;
if (start_datetime != "")
tod_start_time_ = Utils::to_time_t(start_datetime, is_start_datetime_dst) * 1E9;
else
tod_start_time_ = std::time(nullptr) * 1E9;
}
}
else if (enabled_currently) {
// Going from enabled to disabled
if (sun_) {
setSunRotation(default_sun_rotation_);
UAirBlueprintLib::LogMessageString("DateTime: ", Utils::to_string(ClockFactory::get()->nowNanos() / 1E9), LogDebugLevel::Informational);
}
}
// do these in the end to ensure that advanceTimeOfDay() doesn't see
// any inconsistent state.
tod_enabled_ = is_enabled;
tod_celestial_clock_speed_ = celestial_clock_speed;
tod_update_interval_secs_ = update_interval_secs;
tod_move_sun_ = move_sun;
}
bool ASimModeBase::isPaused() const
{
return UGameplayStatics::IsGamePaused(this->GetWorld());
}
void ASimModeBase::pause(bool is_paused)
{
UGameplayStatics::SetGamePaused(this->GetWorld(), is_paused);
}
void ASimModeBase::continueForTime(double seconds)
{
//should be overridden by derived class
unused(seconds);
throw std::domain_error("continueForTime is not implemented by SimMode");
}
void ASimModeBase::continueForFrames(uint32_t frames)
{
//should be overriden by derived class
unused(frames);
throw std::domain_error("continueForFrames is not implemented by SimMode");
}
void ASimModeBase::setWind(const msr::airlib::Vector3r& wind) const
{
// should be overridden by derived class
unused(wind);
throw std::domain_error("setWind not implemented by SimMode");
}
std::unique_ptr<msr::airlib::ApiServerBase> ASimModeBase::createApiServer() const
{
//this will be the case when compilation with RPCLIB is disabled or simmode doesn't support APIs
return nullptr;
}
void ASimModeBase::setupClockSpeed()
{
//default setup - this should be overridden in derived modes as needed
float clock_speed = getSettings().clock_speed;
//setup clock in ClockFactory
std::string clock_type = getSettings().clock_type;
if (clock_type == "ScalableClock")
ClockFactory::get(std::make_shared<msr::airlib::ScalableClock>(clock_speed == 1 ? 1 : 1 / clock_speed));
else if (clock_type == "SteppableClock")
ClockFactory::get(std::make_shared<msr::airlib::SteppableClock>(
static_cast<msr::airlib::TTimeDelta>(msr::airlib::SteppableClock::DefaultStepSize * clock_speed)));
else
throw std::invalid_argument(common_utils::Utils::stringf(
"clock_type %s is not recognized", clock_type.c_str()));
}
void ASimModeBase::setupPhysicsLoopPeriod()
{
}
void ASimModeBase::Tick(float DeltaSeconds)
{
if (isRecording())
++record_tick_count;
advanceTimeOfDay();
showClockStats();
updateDebugReport(debug_reporter_);
drawLidarDebugPoints();
drawDistanceSensorDebugPoints();
Super::Tick(DeltaSeconds);
}
void ASimModeBase::showClockStats()
{
float clock_speed = getSettings().clock_speed;
if (clock_speed != 1) {
UAirBlueprintLib::LogMessageString("ClockSpeed config, actual: ",
Utils::stringf("%f, %f", clock_speed, ClockFactory::get()->getTrueScaleWrtWallClock()),
LogDebugLevel::Informational);
}
}
void ASimModeBase::advanceTimeOfDay()
{
const auto& settings = getSettings();
if (tod_enabled_ && sky_sphere_ && sun_ && tod_move_sun_) {
auto secs = ClockFactory::get()->elapsedSince(tod_last_update_);
if (secs > tod_update_interval_secs_) {
tod_last_update_ = ClockFactory::get()->nowNanos();
auto interval = ClockFactory::get()->elapsedSince(tod_sim_clock_start_) * tod_celestial_clock_speed_;
uint64_t cur_time = ClockFactory::get()->addTo(tod_start_time_, interval) / 1E9;
UAirBlueprintLib::LogMessageString("DateTime: ", Utils::to_string(cur_time), LogDebugLevel::Informational);
auto coord = msr::airlib::EarthCelestial::getSunCoordinates(cur_time, settings.origin_geopoint.home_geo_point.latitude, settings.origin_geopoint.home_geo_point.longitude);
setSunRotation(FRotator(-coord.altitude, coord.azimuth, 0));
}
}
}
void ASimModeBase::setSunRotation(FRotator rotation)
{
if (sun_ && sky_sphere_) {
UAirBlueprintLib::RunCommandOnGameThread([this, rotation]() {
sun_->SetActorRotation(rotation);
FOutputDeviceNull ar;
sky_sphere_->CallFunctionByNameWithArguments(TEXT("UpdateSunDirection"), ar, NULL, true);
},
true /*wait*/);
}
}
void ASimModeBase::reset()
{
//default implementation
UAirBlueprintLib::RunCommandOnGameThread([this]() {
for (auto& api : getApiProvider()->getVehicleSimApis()) {
api->reset();
}
},
true);
}
std::string ASimModeBase::getDebugReport()
{
return debug_reporter_.getOutput();
}
void ASimModeBase::setupInputBindings()
{
UAirBlueprintLib::EnableInput(this);
UAirBlueprintLib::BindActionToKey("InputEventResetAll", EKeys::BackSpace, this, &ASimModeBase::reset);
}
ECameraDirectorMode ASimModeBase::getInitialViewMode() const
{
return Utils::toEnum<ECameraDirectorMode>(getSettings().initial_view_mode);
}
const msr::airlib::AirSimSettings& ASimModeBase::getSettings() const
{
return AirSimSettings::singleton();
}
void ASimModeBase::initializeCameraDirector(const FTransform& camera_transform, float follow_distance)
{
TArray<AActor*> camera_dirs;
UAirBlueprintLib::FindAllActor<ACameraDirector>(this, camera_dirs);
if (camera_dirs.Num() == 0) {
//create director
FActorSpawnParameters camera_spawn_params;
camera_spawn_params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn;
camera_spawn_params.Name = "CameraDirector";
CameraDirector = this->GetWorld()->SpawnActor<ACameraDirector>(camera_director_class_,
camera_transform,
camera_spawn_params);
CameraDirector->setFollowDistance(follow_distance);
CameraDirector->setCameraRotationLagEnabled(false);
//create external camera required for the director
camera_spawn_params.Name = "ExternalCamera";
CameraDirector->ExternalCamera = this->GetWorld()->SpawnActor<APIPCamera>(external_camera_class_,
camera_transform,
camera_spawn_params);
}
else {
CameraDirector = static_cast<ACameraDirector*>(camera_dirs[0]);
}
}
void ASimModeBase::initializeExternalCameras()
{
FActorSpawnParameters camera_spawn_params;
camera_spawn_params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn;
const auto& transform = getGlobalNedTransform();
//for each camera in settings
for (const auto& camera_setting_pair : getSettings().external_cameras) {
const auto& setting = camera_setting_pair.second;
//get pose
FVector position = transform.fromLocalNed(setting.position) - transform.fromLocalNed(Vector3r::Zero());
FTransform camera_transform(FRotator(setting.rotation.pitch, setting.rotation.yaw, setting.rotation.roll),
position,
FVector(1., 1., 1.));
//spawn and attach camera to pawn
camera_spawn_params.Name = FName(("external_" + camera_setting_pair.first).c_str());
APIPCamera* camera = this->GetWorld()->SpawnActor<APIPCamera>(pip_camera_class, camera_transform, camera_spawn_params);
camera->setupCameraFromSettings(setting, transform);
//add on to our collection
external_cameras_.insert_or_assign(camera_setting_pair.first, camera);
}
}
bool ASimModeBase::toggleRecording()
{
if (isRecording())
stopRecording();
else
startRecording();
return isRecording();
}
void ASimModeBase::stopRecording()
{
FRecordingThread::stopRecording();
}
void ASimModeBase::startRecording()
{
FRecordingThread::startRecording(getSettings().recording_setting, getApiProvider()->getVehicleSimApis());
}
bool ASimModeBase::isRecording() const
{
return FRecordingThread::isRecording();
}
void ASimModeBase::toggleTraceAll()
{
for (auto sim_api : getApiProvider()->getVehicleSimApis()) {
auto* pawn_sim_api = static_cast<PawnSimApi*>(sim_api);
pawn_sim_api->toggleTrace();
}
}
const APIPCamera* ASimModeBase::getCamera(const msr::airlib::CameraDetails& camera_details) const
{
return camera_details.external ? getExternalCamera(camera_details.camera_name)
: getVehicleSimApi(camera_details.vehicle_name)->getCamera(camera_details.camera_name);
}
const UnrealImageCapture* ASimModeBase::getImageCapture(const std::string& vehicle_name, bool external) const
{
return external ? external_image_capture_.get() : getVehicleSimApi(vehicle_name)->getImageCapture();
}
//API server start/stop
void ASimModeBase::startApiServer()
{
if (getSettings().enable_rpc) {
#ifdef AIRLIB_NO_RPC
api_server_.reset();
#else
api_server_ = createApiServer();
#endif
try {
api_server_->start(false, spawned_actors_.Num() + 4);
}
catch (std::exception& ex) {
UAirBlueprintLib::LogMessageString("Cannot start RpcLib Server", ex.what(), LogDebugLevel::Failure);
}
}
else
UAirBlueprintLib::LogMessageString("API server is disabled in settings", "", LogDebugLevel::Informational);
}
void ASimModeBase::stopApiServer()
{
if (api_server_ != nullptr) {
api_server_->stop();
api_server_.reset(nullptr);
}
}
bool ASimModeBase::isApiServerStarted()
{
return api_server_ != nullptr;
}
void ASimModeBase::updateDebugReport(msr::airlib::StateReporterWrapper& debug_reporter)
{
debug_reporter.update();
debug_reporter.setEnable(EnableReport);
if (debug_reporter.canReport()) {
debug_reporter.clearReport();
for (auto& api : getApiProvider()->getVehicleSimApis()) {
PawnSimApi* vehicle_sim_api = static_cast<PawnSimApi*>(api);
msr::airlib::StateReporter& reporter = *debug_reporter.getReporter();
std::string vehicle_name = vehicle_sim_api->getVehicleName();
reporter.writeHeading(std::string("Vehicle: ").append(vehicle_name == "" ? "(default)" : vehicle_name));
vehicle_sim_api->reportState(reporter);
}
}
}
FRotator ASimModeBase::toFRotator(const msr::airlib::AirSimSettings::Rotation& rotation, const FRotator& default_val)
{
FRotator frotator = default_val;
if (!std::isnan(rotation.yaw))
frotator.Yaw = rotation.yaw;
if (!std::isnan(rotation.pitch))
frotator.Pitch = rotation.pitch;
if (!std::isnan(rotation.roll))
frotator.Roll = rotation.roll;
return frotator;
}
APawn* ASimModeBase::createVehiclePawn(const AirSimSettings::VehicleSetting& vehicle_setting)
{
//get UU origin of global NED frame
const FTransform uu_origin = getGlobalNedTransform().getGlobalTransform();
// compute initial pose
FVector spawn_position = uu_origin.GetLocation();
Vector3r settings_position = vehicle_setting.position;
if (!VectorMath::hasNan(settings_position))
spawn_position = getGlobalNedTransform().fromGlobalNed(settings_position);
FRotator spawn_rotation = toFRotator(vehicle_setting.rotation, uu_origin.Rotator());
std::string vehicle_name = vehicle_setting.vehicle_name;
//spawn vehicle pawn
FActorSpawnParameters pawn_spawn_params;
pawn_spawn_params.Name = FName(vehicle_name.c_str());
pawn_spawn_params.SpawnCollisionHandlingOverride =
ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn;
auto vehicle_bp_class = UAirBlueprintLib::LoadClass(
getSettings().pawn_paths.at(getVehiclePawnPathName(vehicle_setting)).pawn_bp);
APawn* spawned_pawn = static_cast<APawn*>(this->GetWorld()->SpawnActor(
vehicle_bp_class, &spawn_position, &spawn_rotation, pawn_spawn_params));
spawned_actors_.Add(spawned_pawn);
return spawned_pawn;
}
std::unique_ptr<PawnSimApi> ASimModeBase::createVehicleApi(APawn* vehicle_pawn)
{
initializeVehiclePawn(vehicle_pawn);
//create vehicle sim api
const auto& ned_transform = getGlobalNedTransform();
const auto& pawn_ned_pos = ned_transform.toLocalNed(vehicle_pawn->GetActorLocation());
const auto& home_geopoint = msr::airlib::EarthUtils::nedToGeodetic(pawn_ned_pos, getSettings().origin_geopoint);
const std::string vehicle_name(TCHAR_TO_UTF8(*(vehicle_pawn->GetName())));
PawnSimApi::Params pawn_sim_api_params(vehicle_pawn, &getGlobalNedTransform(), getVehiclePawnEvents(vehicle_pawn), getVehiclePawnCameras(vehicle_pawn), pip_camera_class, collision_display_template, home_geopoint, vehicle_name);
std::unique_ptr<PawnSimApi> vehicle_sim_api = createVehicleSimApi(pawn_sim_api_params);
auto vehicle_sim_api_p = vehicle_sim_api.get();
auto vehicle_api = getVehicleApi(pawn_sim_api_params, vehicle_sim_api_p);
getApiProvider()->insert_or_assign(vehicle_name, vehicle_api, vehicle_sim_api_p);
return vehicle_sim_api;
}
bool ASimModeBase::createVehicleAtRuntime(const std::string& vehicle_name, const std::string& vehicle_type,
const msr::airlib::Pose& pose, const std::string& pawn_path)
{
// Convert to lowercase as done during settings loading
const std::string vehicle_type_lower = Utils::toLower(vehicle_type);
if (!isVehicleTypeSupported(vehicle_type_lower)) {
Utils::log(Utils::stringf("Vehicle type %s is not supported in this game mode", vehicle_type.c_str()), Utils::kLogLevelWarn);
return false;
}
// TODO: Figure out a better way to add more fields
// Maybe allow passing a JSON string for the vehicle settings?
// Retroactively adjust AirSimSettings, so it's like we knew about this vehicle all along
AirSimSettings::singleton().addVehicleSetting(vehicle_name, vehicle_type_lower, pose, pawn_path);
const auto* vehicle_setting = getSettings().getVehicleSetting(vehicle_name);
auto spawned_pawn = createVehiclePawn(*vehicle_setting);
auto vehicle_sim_api = createVehicleApi(spawned_pawn);
// Usually physics registration happens at init, in ASimModeWorldBase::initializeForPlay(), but not in this case
registerPhysicsBody(vehicle_sim_api.get());
vehicle_sim_apis_.push_back(std::move(vehicle_sim_api));
return true;
}
void ASimModeBase::setupVehiclesAndCamera()
{
//get UU origin of global NED frame
const FTransform uu_origin = getGlobalNedTransform().getGlobalTransform();
//determine camera director camera default pose and spawn it
const auto& camera_director_setting = getSettings().camera_director;
FVector camera_director_position_uu = uu_origin.GetLocation() +
getGlobalNedTransform().fromLocalNed(camera_director_setting.position);
FTransform camera_transform(toFRotator(camera_director_setting.rotation, FRotator::ZeroRotator),
camera_director_position_uu);
initializeCameraDirector(camera_transform, camera_director_setting.follow_distance);
//find all vehicle pawns
{
TArray<AActor*> pawns;
getExistingVehiclePawns(pawns);
bool haveUEPawns = pawns.Num() > 0;
APawn* fpv_pawn = nullptr;
if (haveUEPawns) {
fpv_pawn = static_cast<APawn*>(pawns[0]);
}
else {
//add vehicles from settings
for (const auto& vehicle_setting_pair : getSettings().vehicles) {
//if vehicle is of type for derived SimMode and auto creatable
const auto& vehicle_setting = *vehicle_setting_pair.second;
if (vehicle_setting.auto_create &&
isVehicleTypeSupported(vehicle_setting.vehicle_type)) {
auto spawned_pawn = createVehiclePawn(vehicle_setting);
pawns.Add(spawned_pawn);
if (vehicle_setting.is_fpv_vehicle)
fpv_pawn = spawned_pawn;
}
}
}
//create API objects for each pawn we have
for (AActor* pawn : pawns) {
auto vehicle_pawn = static_cast<APawn*>(pawn);
auto vehicle_sim_api = createVehicleApi(vehicle_pawn);
std::string vehicle_name = vehicle_sim_api->getVehicleName();
if ((fpv_pawn == vehicle_pawn || !getApiProvider()->hasDefaultVehicle()) && vehicle_name != "")
getApiProvider()->makeDefaultVehicle(vehicle_name);
vehicle_sim_apis_.push_back(std::move(vehicle_sim_api));
}
}
// Create External Cameras
initializeExternalCameras();
external_image_capture_ = std::make_unique<UnrealImageCapture>(&external_cameras_);
if (getApiProvider()->hasDefaultVehicle()) {
//TODO: better handle no FPV vehicles scenario
getVehicleSimApi()->possess();
CameraDirector->initializeForBeginPlay(getInitialViewMode(), getVehicleSimApi()->getPawn(), getVehicleSimApi()->getCamera("fpv"), getVehicleSimApi()->getCamera("back_center"), nullptr);
}
else
CameraDirector->initializeForBeginPlay(getInitialViewMode(), nullptr, nullptr, nullptr, nullptr);
checkVehicleReady();
}
void ASimModeBase::registerPhysicsBody(msr::airlib::VehicleSimApiBase* physicsBody)
{
// derived class shoudl override this method to add new vehicle to the physics engine
}
void ASimModeBase::getExistingVehiclePawns(TArray<AActor*>& pawns) const
{
//derived class should override this method to retrieve types of pawns they support
}
bool ASimModeBase::isVehicleTypeSupported(const std::string& vehicle_type) const
{
//derived class should override this method to retrieve types of pawns they support
return false;
}
std::string ASimModeBase::getVehiclePawnPathName(const AirSimSettings::VehicleSetting& vehicle_setting) const
{
//derived class should override this method to retrieve types of pawns they support
return "";
}
PawnEvents* ASimModeBase::getVehiclePawnEvents(APawn* pawn) const
{
unused(pawn);
//derived class should override this method to retrieve types of pawns they support
return nullptr;
}
const common_utils::UniqueValueMap<std::string, APIPCamera*> ASimModeBase::getVehiclePawnCameras(APawn* pawn) const
{
unused(pawn);
//derived class should override this method to retrieve types of pawns they support
return common_utils::UniqueValueMap<std::string, APIPCamera*>();
}
void ASimModeBase::initializeVehiclePawn(APawn* pawn)
{
unused(pawn);
//derived class should override this method to retrieve types of pawns they support
}
std::unique_ptr<PawnSimApi> ASimModeBase::createVehicleSimApi(
const PawnSimApi::Params& pawn_sim_api_params) const
{
unused(pawn_sim_api_params);
auto sim_api = std::unique_ptr<PawnSimApi>();
sim_api->initialize();
return sim_api;
}
msr::airlib::VehicleApiBase* ASimModeBase::getVehicleApi(const PawnSimApi::Params& pawn_sim_api_params,
const PawnSimApi* sim_api) const
{
//derived class should override this method to retrieve types of pawns they support
return nullptr;
}
// Draws debug-points on main viewport for Lidar laser hits.
// Used for debugging only.
void ASimModeBase::drawLidarDebugPoints()
{
// Currently we are checking the sensor-collection instead of sensor-settings.
// Also using variables to optimize not checking the collection if not needed.
if (lidar_checks_done_ && !lidar_draw_debug_points_)
return;
if (getApiProvider() == nullptr)
return;
for (auto& sim_api : getApiProvider()->getVehicleSimApis()) {
PawnSimApi* pawn_sim_api = static_cast<PawnSimApi*>(sim_api);
std::string vehicle_name = pawn_sim_api->getVehicleName();
msr::airlib::VehicleApiBase* api = getApiProvider()->getVehicleApi(vehicle_name);
if (api != nullptr) {
msr::airlib::uint count_lidars = api->getSensors().size(SensorType::Lidar);
for (msr::airlib::uint i = 0; i < count_lidars; i++) {
// TODO: Is it incorrect to assume LidarSimple here?
const msr::airlib::LidarSimple* lidar =
static_cast<const msr::airlib::LidarSimple*>(api->getSensors().getByType(SensorType::Lidar, i));
if (lidar != nullptr && lidar->getParams().draw_debug_points) {
lidar_draw_debug_points_ = true;
msr::airlib::LidarData lidar_data = lidar->getOutput();
if (lidar_data.point_cloud.size() < 3)
return;
for (int j = 0; j < lidar_data.point_cloud.size(); j = j + 3) {
Vector3r point(lidar_data.point_cloud[j], lidar_data.point_cloud[j + 1], lidar_data.point_cloud[j + 2]);
FVector uu_point;
if (lidar->getParams().data_frame == AirSimSettings::kVehicleInertialFrame) {
uu_point = pawn_sim_api->getNedTransform().fromLocalNed(point);
}
else if (lidar->getParams().data_frame == AirSimSettings::kSensorLocalFrame) {
Vector3r point_w = VectorMath::transformToWorldFrame(point, lidar_data.pose, true);
uu_point = pawn_sim_api->getNedTransform().fromLocalNed(point_w);
}
else
throw std::runtime_error("Unknown requested data frame");
DrawDebugPoint(
this->GetWorld(),
uu_point,
5, // size
FColor::Green,
false, // persistent (never goes away)
0.03 // LifeTime: point leaves a trail on moving object
);
}
}
}
}
}
lidar_checks_done_ = true;
}
// Draw debug-point on main viewport for Distance sensor hit
void ASimModeBase::drawDistanceSensorDebugPoints()
{
if (getApiProvider() == nullptr)
return;
for (auto& sim_api : getApiProvider()->getVehicleSimApis()) {
PawnSimApi* pawn_sim_api = static_cast<PawnSimApi*>(sim_api);
std::string vehicle_name = pawn_sim_api->getVehicleName();
msr::airlib::VehicleApiBase* api = getApiProvider()->getVehicleApi(vehicle_name);
if (api != nullptr) {
msr::airlib::uint count_distance_sensors = api->getSensors().size(SensorType::Distance);
Pose vehicle_pose = pawn_sim_api->getGroundTruthKinematics()->pose;
for (msr::airlib::uint i = 0; i < count_distance_sensors; i++) {
const msr::airlib::DistanceSimple* distance_sensor =
static_cast<const msr::airlib::DistanceSimple*>(api->getSensors().getByType(SensorType::Distance, i));
if (distance_sensor != nullptr && distance_sensor->getParams().draw_debug_points) {
msr::airlib::DistanceSensorData distance_sensor_data = distance_sensor->getOutput();
// Find position of point hit
// Similar to UnrealDistanceSensor.cpp#L19
// order of Pose addition is important here because it also adds quaternions which is not commutative!
Pose distance_sensor_pose = distance_sensor_data.relative_pose + vehicle_pose;
Vector3r start = distance_sensor_pose.position;
Vector3r point = start + VectorMath::rotateVector(VectorMath::front(),
distance_sensor_pose.orientation,
true) *
distance_sensor_data.distance;
FVector uu_point = pawn_sim_api->getNedTransform().fromLocalNed(point);
DrawDebugPoint(
this->GetWorld(),
uu_point,
10, // size
FColor::Green,
false, // persistent (never goes away)
0.03 // LifeTime: point leaves a trail on moving object
);
}
}
}
}
}
| AirSim/Unreal/Plugins/AirSim/Source/SimMode/SimModeBase.cpp/0 | {
"file_path": "AirSim/Unreal/Plugins/AirSim/Source/SimMode/SimModeBase.cpp",
"repo_id": "AirSim",
"token_count": 14644
} | 59 |
#include "CarPawnApi.h"
#include "AirBlueprintLib.h"
#include "PhysXVehicleManager.h"
CarPawnApi::CarPawnApi(ACarPawn* pawn, const msr::airlib::Kinematics::State* pawn_kinematics,
msr::airlib::CarApiBase* vehicle_api)
: pawn_(pawn), pawn_kinematics_(pawn_kinematics), vehicle_api_(vehicle_api)
{
movement_ = pawn->GetVehicleMovement();
}
void CarPawnApi::updateMovement(const msr::airlib::CarApiBase::CarControls& controls)
{
last_controls_ = controls;
if (!controls.is_manual_gear && movement_->GetTargetGear() < 0)
movement_->SetTargetGear(0, true); //in auto gear we must have gear >= 0
if (controls.is_manual_gear && movement_->GetTargetGear() != controls.manual_gear)
movement_->SetTargetGear(controls.manual_gear, controls.gear_immediate);
movement_->SetThrottleInput(controls.throttle);
movement_->SetSteeringInput(controls.steering);
movement_->SetBrakeInput(controls.brake);
movement_->SetHandbrakeInput(controls.handbrake);
movement_->SetUseAutoGears(!controls.is_manual_gear);
}
msr::airlib::CarApiBase::CarState CarPawnApi::getCarState() const
{
msr::airlib::CarApiBase::CarState state(
movement_->GetForwardSpeed() / 100, //cm/s -> m/s
movement_->GetCurrentGear(),
movement_->GetEngineRotationSpeed(),
movement_->GetEngineMaxRotationSpeed(),
last_controls_.handbrake,
*pawn_kinematics_,
vehicle_api_->clock()->nowNanos());
return state;
}
void CarPawnApi::reset()
{
vehicle_api_->reset();
last_controls_ = msr::airlib::CarApiBase::CarControls();
auto phys_comps = UAirBlueprintLib::getPhysicsComponents(pawn_);
UAirBlueprintLib::RunCommandOnGameThread([this, &phys_comps]() {
for (auto* phys_comp : phys_comps) {
phys_comp->SetPhysicsAngularVelocityInDegrees(FVector::ZeroVector);
phys_comp->SetPhysicsLinearVelocity(FVector::ZeroVector);
phys_comp->SetSimulatePhysics(false);
}
movement_->ResetMoveState();
movement_->SetActive(false);
movement_->SetActive(true, true);
vehicle_api_->setCarControls(msr::airlib::CarApiBase::CarControls());
updateMovement(msr::airlib::CarApiBase::CarControls());
auto pv = movement_->PVehicle;
if (pv) {
pv->mWheelsDynData.setToRestState();
}
auto pvd = movement_->PVehicleDrive;
if (pvd) {
pvd->mDriveDynData.setToRestState();
}
},
true);
UAirBlueprintLib::RunCommandOnGameThread([this, &phys_comps]() {
for (auto* phys_comp : phys_comps)
phys_comp->SetSimulatePhysics(true);
},
true);
}
void CarPawnApi::update()
{
vehicle_api_->updateCarState(getCarState());
vehicle_api_->update();
}
CarPawnApi::~CarPawnApi() = default;
| AirSim/Unreal/Plugins/AirSim/Source/Vehicles/Car/CarPawnApi.cpp/0 | {
"file_path": "AirSim/Unreal/Plugins/AirSim/Source/Vehicles/Car/CarPawnApi.cpp",
"repo_id": "AirSim",
"token_count": 1319
} | 60 |
import airsim
import pprint
def print_state(client):
state = client.getMultirotorState()
s = pprint.pformat(state)
print("state: %s" % s)
imu_data = client.getImuData()
s = pprint.pformat(imu_data)
print("imu_data: %s" % s)
barometer_data = client.getBarometerData()
s = pprint.pformat(barometer_data)
print("barometer_data: %s" % s)
magnetometer_data = client.getMagnetometerData()
s = pprint.pformat(magnetometer_data)
print("magnetometer_data: %s" % s)
gps_data = client.getGpsData()
s = pprint.pformat(gps_data)
print("gps_data: %s" % s)
# connect to the AirSim simulator
client = airsim.MultirotorClient()
client.confirmConnection()
client.enableApiControl(True)
client.armDisarm(True)
print_state(client)
print('Takeoff')
client.takeoffAsync().join()
while True:
print_state(client)
print('Go to (-10, 10, -10) at 5 m/s')
client.moveToPositionAsync(-10, 10, -10, 5).join()
client.hoverAsync().join()
print_state(client)
print('Go to (0, 10, 0) at 5 m/s')
client.moveToPositionAsync(0, 10, 0, 5).join()
| AirSim/azure/app/multirotor.py/0 | {
"file_path": "AirSim/azure/app/multirotor.py",
"repo_id": "AirSim",
"token_count": 453
} | 61 |
#! /bin/bash
# get path of current script: https://stackoverflow.com/a/39340259/207661
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
pushd "$SCRIPT_DIR" >/dev/null
set -x
git clean -ffdx
git pull
set -e
./setup.sh
./build.sh | AirSim/clean_rebuild.sh/0 | {
"file_path": "AirSim/clean_rebuild.sh",
"repo_id": "AirSim",
"token_count": 107
} | 62 |
#!/bin/bash
set -x
if ! which unzip; then
sudo apt-get install unzip
fi
wget -c https://github.com/microsoft/AirSim/releases/download/v1.6.0-linux/Blocks.zip
unzip -q Blocks.zip
rm Blocks.zip
| AirSim/docker/download_blocks_env_binary.sh/0 | {
"file_path": "AirSim/docker/download_blocks_env_binary.sh",
"repo_id": "AirSim",
"token_count": 80
} | 63 |
# FAQ
---
## Windows build
* [How to force Unreal to use Visual Studio 2019?](#how-to-force-unreal-to-use-visual-studio-2019)
* [I get error: 'where' is not recognized as an internal or external command](#i-get-error-where-is-not-recognized-as-an-internal-or-external-command)
* [I'm getting error `<MyProject> could not be compiled. Try rebuilding from source manually`](#im-getting-error-myproject-could-not-be-compiled-try-rebuilding-from-source-manually)
* [I get `error C100 : An internal error has occurred in the compiler` when running build.cmd](#i-get-error-c100--an-internal-error-has-occurred-in-the-compiler-when-running-buildcmd)
* [I get error "'corecrt.h': No such file or directory" or "Windows SDK version 8.1 not found"](#i-get-error-corecrth-no-such-file-or-directory-or-windows-sdk-version-81-not-found)
* [How do I use PX4 firmware with AirSim?](#how-do-i-use-px4-firmware-with-airsim)
* [I made changes in Visual Studio but there is no effect](#i-made-changes-in-visual-studio-but-there-is-no-effect)
* [Unreal still uses VS2015 or I'm getting some link error](#unreal-still-uses-vs2015-or-im-getting-some-link-error)
---
## Linux build
* [I'm getting error `<MyProject> could not be compiled. Try rebuilding from source manually`.](#im-getting-error-myproject-could-not-be-compiled-try-rebuilding-from-source-manually)
* [Unreal crashed! How do I know what went wrong?](#unreal-crashed-how-do-i-know-what-went-wrong)
* [How do I use an IDE on Linux?](#how-do-i-use-an-ide-on-linux)
* [Can I cross compile for Linux from a Windows machine?](#can-i-cross-compile-for-linux-from-a-windows-machine)
* [What compiler and stdlib does AirSim use?](#what-compiler-and-stdlib-does-airsim-use)
* [What version of CMake does the AirSim build use?](#what-version-of-cmake-does-the-airsim-build-use)
* [Can I compile AirSim in BashOnWindows?](#can-i-compile-airsim-in-bashonwindows)
* [Where can I find more info on running Unreal on Linux?](#where-can-i-find-more-info-on-running-unreal-on-linux)
---
## Other
* [Packaging AirSim](#packaging-a-binary-including-the-airsim-plugin)
---
<!-- ======================================================================= -->
## Windows build
<!-- ======================================================================= -->
###### How to force Unreal to use Visual Studio 2019?
>If the default `update_from_git.bat` file results in VS 2017 project, then you may need to run the `C:\Program Files\Epic Games\UE_4.25\Engine\Binaries\DotNET\UnrealBuildTool.exe` tool manually, with the command line options `-projectfiles -project=<your.uproject> -game -rocket -progress -2019`.
>
>If you are upgrading from 4.18 to 4.25 you may also need to add `BuildSettingsVersion.V2` to your `*.Target.cs` and `*Editor.Target.cs` build files, like this:
>
>```c#
> public AirSimNHTestTarget(TargetInfo Target) : base(Target)
> {
> Type = TargetType.Game;
> DefaultBuildSettings = BuildSettingsVersion.V2;
> ExtraModuleNames.AddRange(new string[] { "AirSimNHTest" });
> }
>```
>
>You may also need to edit this file:
>
>```
>"%APPDATA%\Unreal Engine\UnrealBuildTool\BuildConfiguration.xml
>```
>
>And add this Compiler version setting:
>
>```xml
><Configuration xmlns="https://www.unrealengine.com/BuildConfiguration">
> <WindowsPlatform>
> <Compiler>VisualStudio2019</Compiler>
> </WindowsPlatform>
></Configuration>
>```
<!-- ======================================================================= -->
###### I get error: 'where' is not recognized as an internal or external command
>You have to add `C:\WINDOWS\SYSTEM32` to your PATH enviroment variable.
<!-- ======================================================================= -->
###### I'm getting error `<MyProject> could not be compiled. Try rebuilding from source manually`
>This will occur when there are compilation errors. Logs are stored in `<My-Project>\Saved\Logs` which can be used to figure out the problem.
>
>A common problem could be Visual Studio version conflict, AirSim uses VS 2019 while UE is using VS 2017, this can be found by searching for `2017` in the Log file. In that case, see the answer above.
>
>If you have modified the AirSim plugin files, then you can right-click the `.uproject` file, select `Generate Visual Studio solution file` and then open the `.sln` file in VS to fix the errors and build again.
<!-- ======================================================================= -->
###### I get `error C100 : An internal error has occurred in the compiler` when running build.cmd
>We have noticed this happening with VS version `15.9.0` and have checked-in a workaround in AirSim code. If you have this VS version, please make sure to pull the latest AirSim code.
<!-- ======================================================================= -->
###### I get error "'corecrt.h': No such file or directory" or "Windows SDK version 8.1 not found"
>Very likely you don't have [Windows SDK](https://developercommunity.visualstudio.com/content/problem/3754/cant-compile-c-program-because-of-sdk-81cant-add-a.html) installed with Visual Studio.
<!-- ======================================================================= -->
###### How do I use PX4 firmware with AirSim?
>By default, AirSim uses its own built-in firmware called [simple_flight](simple_flight.md). There is no additional setup if you just want to go with it. If you want to switch to using PX4 instead then please see [this guide](px4_setup.md).
<!-- ======================================================================= -->
###### I made changes in Visual Studio but there is no effect
>Sometimes the Unreal + VS build system doesn't recompile if you make changes to only header files. To ensure a recompile, make some Unreal based cpp file "dirty" like AirSimGameMode.cpp.
<!-- ======================================================================= -->
###### Unreal still uses VS2015 or I'm getting some link error
>Running several versions of VS can lead to issues when compiling UE projects. One problem that may arise is that UE will try to compile with an older version of VS which may or may not work. There are two settings in Unreal, one for for the engine and one for the project, to adjust the version of VS to be used.
>
>1. Edit -> Editor preferences -> General -> Source code -> Source Code Editor
>2. Edit -> Project Settings -> Platforms -> Windows -> Toolchain ->CompilerVersion
>
>In some cases, these settings will still not lead to the desired result and errors such as the following might be produced: LINK : fatal error LNK1181: cannot open input file 'ws2_32.lib'
>
>To resolve such issues the following procedure can be applied:
>
>1. Uninstall all old versions of VS using the [VisualStudioUninstaller](https://github.com/Microsoft/VisualStudioUninstaller/releases)
>2. Repair/Install VS 2019
>3. Restart machine and install Epic launcher and desired version of the engine
---
## Linux build
<!-- ======================================================================= -->
###### I'm getting error `<MyProject> could not be compiled. Try rebuilding from source manually`.
>This could either happen because of compile error or the fact that your gch files are outdated. Look in to your console window. Do you see something like below?
>
>`fatal error: file '/usr/include/linux/version.h''/usr/include/linux/version.h' has been modified since the precompiled header`
>
>If this is the case then look for *.gch file(s) that follows after that message, delete them and try again. Here's [relevant thread](https://answers.unrealengine.com/questions/412349/linux-ue4-build-precompiled-header-fatal-error.html) on Unreal Engine forums.
>
>If you see other compile errors in console then open up those source files and see if it is due to changes you made. If not, then report it as issue on GitHub.
<!-- ======================================================================= -->
###### Unreal crashed! How do I know what went wrong?
>Go to the `MyUnrealProject/Saved/Crashes` folder and search for the file `MyProject.log` within its subdirectories. At the end of this file you will see the stack trace and messages.
>You can also take a look at the `Diagnostics.txt` file.
<!-- ======================================================================= -->
###### How do I use an IDE on Linux?
>You can use Qt Creator or CodeLite. Instructions for Qt Creator are available [here](https://docs.unrealengine.com/en-US/SharingAndReleasing/Linux/BeginnerLinuxDeveloper/SettingUpQtCreator/index.html).
<!-- ======================================================================= -->
###### Can I cross compile for Linux from a Windows machine?
>Yes, you can, but we haven't tested it. You can find the instructions [here](https://docs.unrealengine.com/latest/INT/Platforms/Linux/GettingStarted/index.html).
<!-- ======================================================================= -->
###### What compiler and stdlib does AirSim use?
>We use the same compiler that Unreal Engine uses, **Clang 8**, and stdlib, **libc++**. AirSim's `setup.sh` will automatically download them.
<!-- ======================================================================= -->
###### What version of CMake does the AirSim build use?
>3.10.0 or higher. This is *not* the default in Ubuntu 16.04 so setup.sh installs it for you. You can check your CMake version using `cmake --version`. If you have an older version, follow [these instructions](cmake_linux.md) or see the [CMake website](https://cmake.org/install/).
<!-- ======================================================================= -->
###### Can I compile AirSim in BashOnWindows?
>Yes, however, you can't run Unreal from BashOnWindows. So this is kind of useful to check a Linux compile, but not for an end-to-end run.
>See the [BashOnWindows install guide](https://msdn.microsoft.com/en-us/commandline/wsl/install_guide).
>Make sure to have the latest version (Windows 10 Creators Edition) as previous versions had various issues.
>Also, don't invoke `bash` from `Visual Studio Command Prompt`, otherwise CMake might find VC++ and try and use that!
<!-- ======================================================================= -->
###### Where can I find more info on running Unreal on Linux?
>Start here: [Unreal on Linux](https://docs.unrealengine.com/latest/INT/Platforms/Linux/index.html)
>[Building Unreal on Linux](https://wiki.unrealengine.com/Building_On_Linux#Clang)
>[Unreal Linux Support](https://wiki.unrealengine.com/Linux_Support)
>[Unreal Cross Compilation](https://wiki.unrealengine.com/Compiling_For_Linux)
---
## Other
<!-- ======================================================================= -->
###### Packaging a binary including the AirSim plugin
>In order to package a custom environment with the AirSim plugin, there are a few project settings that are necessary for ensuring all required assets needed for AirSim are included inside the package. Under `Edit -> Project Settings... -> Project -> Packaging`, please ensure the following settings are configured properly:
>
>- `List of maps to include in a packaged build`: ensure one entry exists for `/AirSim/AirSimAssets`
>- `Additional Asset Directories to Cook`: ensure one entry exists for `/AirSim/HUDAssets`
| AirSim/docs/build_faq.md/0 | {
"file_path": "AirSim/docs/build_faq.md",
"repo_id": "AirSim",
"token_count": 3033
} | 64 |
AirSim provides a Python-based event camera simulator, aimed at performance and ability to run in real-time along with the sim.
#### Event cameras
An event camera is a special vision sensor that measures changes in logarithmic brightness and only reports 'events'. Each event is a set of four values that gets generated every time the absolute change in the logarithmic brightness exceeds a certain threshold. An event contains the timestamp of the measurement, pixel location (x and y coordinates) and the polarity: which is either +1/-1 based on whether the logarithmic brightness has increased or decreased. Most event cameras have a temporal resolution of the order of microseconds, making them significantly faster than RGB sensors, and also demonstrate a high dynamic range and low motion blur. More details about event cameras can be found in [this tutorial from RPG-UZH](http://rpg.ifi.uzh.ch/docs/scaramuzza/Tutorial_on_Event_Cameras_Scaramuzza.pdf)
#### AirSim event simulator
The AirSim event simulator uses two consecutive RGB images (converted to grayscale), and computes "past events" that would have occurred during the transition based on the change in log luminance between the images. These events are reported as a stream of bytes, following this format:
`<x> <y> <timestamp> <pol>`
x and y are the pixel locations of the event firing, timestamp is the global timestamp in microseconds and pol is either +1/-1 depending on whether the brightness increased or decreased. Along with this bytestream, an accumulation of events over a 2D frame is also constructed, known as an 'event image' that visualizes +1 events as red and -1 as blue pixels. An example event image is shown below:

#### Usage
An example script to run the event simulator alongside AirSim is located at https://github.com/microsoft/AirSim/blob/main/PythonClient/eventcamera_sim/test_event_sim.py. The following optional command-line arguments can be passed to this script.
```
args.width, args.height (float): Simulated event camera resolution
args.save (bool): Whether or not to save the event data to a file, args.debug (bool): Whether or not to display the simulated events as an image
```
The implementation of the actual event simulation, written in Python and numba, is at https://github.com/microsoft/AirSim/blob/main/PythonClient/eventcamera_sim/event_simulator.py. The event simulator is initialized as follows, with the arguments controlling the resolution of the camera.
```
from event_simulator import *
ev_sim = EventSimulator(W, H)
```
The actual computation of the events is triggered through an `image_callback` function, which is executed every time a new RGB image is obtained. The first time this function is called, due to the lack of a 'previous' image, it acts as an initialization of the event sim.
```
event_img, events = ev_sim.image_callback(img, ts_delta)
```
This function, which behaves similar to a callback (called every time a new image is received) returns an event image as a one dimensional array of +1/-1 values, thus indicating only whether events were seen at each pixel, but not the timing/number of events. This one dimensional array can be converted into the red/blue event image as seen in the function `convert_event_img_rgb`. `events` is a numpy array of events, each of format `<x> <y> <timestamp> <pol>`.
Through this function, the event sim computes the difference between the past and the current image, and computes a stream of events which is then returned as a numpy array. This can then be appended to a file.
There are quite a few parameters that can be tuned to achieve a level of visual fidelity/performance of the event simulation. The main factors to tune are the following:
1. The resolution of the camera.
2. The log luminance threshold `TOL` that determines whether or not a detected change counts as an event.
Note: There is also currently a max limit on the number of events generated per pair of images, which can also be tuned.
#### Algorithm
The working of the event simulator loosely follows this set of operations:
1. Take the difference between the log intensities of the current and previous frames.
2. Iterating over all pixels, calculate the polarity for each each pixel based on a threshold of change in log intensity.
3. Determine the number of events to be fired per pixel, based on extent of intensity change over the threshold. Let $N_{max}$ be the maximum number of events that can occur at a single pixel, then the total number of firings to be simulated at pixel location $u$ would be $N_e(u) = min(N_{max}, \frac{\Delta L(u)}{TOL})$.
4. Determine the timestamps for each interpolated event by interpolating between the amount of time that has elapsed between the captures of the previous and current images.
$t = t_{prev} + \frac{\Delta T}{N_e(u)}$
5. Generate the output bytestream by simulating events at every pixel and sort by timestamp.
| AirSim/docs/event_sim.md/0 | {
"file_path": "AirSim/docs/event_sim.md",
"repo_id": "AirSim",
"token_count": 1221
} | 65 |
# Setting up PX4 Software-in-Loop
The [PX4](http://dev.px4.io) software provides a "software-in-loop" simulation (SITL) version of
their stack that runs in Linux. If you are on Windows then you can use the [Cygwin
Toolchain](https://dev.px4.io/master/en/setup/dev_env_windows_cygwin.html) or you can use the
[Windows subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) and follow
the PX4 Linux toolchain setup.
If you are using WSL2 please read these [additional
instructions](px4_sitl_wsl2.md).
**Note** that every time you stop the unreal app you have to restart the `px4` app.
1. From your bash terminal follow [these steps for
Linux](https://docs.px4.io/master/en/dev_setup/dev_env_linux.html) and follow **all** the
instructions under `NuttX based hardware` to install prerequisites. We've also included our own
copy of the [PX4 build instructions](px4_build.md) which is a bit more concise about what we need
exactly.
2. Get the PX4 source code and build the posix SITL version of PX4:
```
mkdir -p PX4
cd PX4
git clone https://github.com/PX4/PX4-Autopilot.git --recursive
bash ./PX4-Autopilot/Tools/setup/ubuntu.sh --no-nuttx --no-sim-tools
cd PX4-Autopilot
```
And find the latest stable release from [https://github.com/PX4/PX4-Autopilot/releases](https://github.com/PX4/PX4-Autopilot/releases)
and checkout the source code matching that release, for example:
```
git checkout v1.11.3
```
3. Use following command to build and start PX4 firmware in SITL mode:
```
make px4_sitl_default none_iris
```
If you are using older version v1.8.* use this command instead: `make posix_sitl_ekf2 none_iris`.
4. You should see a message saying the SITL PX4 app is waiting for the simulator (AirSim) to connect.
You will also see information about which ports are configured for mavlink connection to the PX4 app.
The default ports have changed recently, so check them closely to make sure AirSim settings are correct.
```
INFO [simulator] Waiting for simulator to connect on TCP port 4560
INFO [init] Mixer: etc/mixers/quad_w.main.mix on /dev/pwm_output0
INFO [mavlink] mode: Normal, data rate: 4000000 B/s on udp port 14570 remote port 14550
INFO [mavlink] mode: Onboard, data rate: 4000000 B/s on udp port 14580 remote port 14540
```
Note: this is also an interactive PX4 console, type `help` to see the
list of commands you can enter here. They are mostly low level PX4
commands, but some of them can be useful for debugging.
5. Now edit [AirSim settings](settings.md) file to make sure you have matching UDP and TCP port settings:
```json
{
"SettingsVersion": 1.2,
"SimMode": "Multirotor",
"ClockType": "SteppableClock",
"Vehicles": {
"PX4": {
"VehicleType": "PX4Multirotor",
"UseSerial": false,
"LockStep": true,
"UseTcp": true,
"TcpPort": 4560,
"ControlPortLocal": 14540,
"ControlPortRemote": 14580,
"Sensors":{
"Barometer":{
"SensorType": 1,
"Enabled": true,
"PressureFactorSigma": 0.0001825
}
},
"Parameters": {
"NAV_RCL_ACT": 0,
"NAV_DLL_ACT": 0,
"COM_OBL_ACT": 1,
"LPE_LAT": 47.641468,
"LPE_LON": -122.140165
}
}
}
}
```
Notice the PX4 `[simulator]` is using TCP, which is why we need to add: `"UseTcp": true,`.
Notice we are also enabling `LockStep`, see [PX4 LockStep](px4_lockstep.md) for more
information. The `Barometer` setting keeps PX4 happy because the default AirSim barometer has a
bit too much noise generation. This setting clamps that down a bit which allows PX4 to achieve
GPS lock more quickly.
6. Open incoming TCP port 4560 and incoming UDP port 14540 using your firewall configuration.
7. Now run your Unreal AirSim environment and it should connect to SITL PX4 via TCP. You should see
a bunch of messages from the SITL PX4 window. Specifically, the following messages tell you that
AirSim is connected properly and GPS fusion is stable:
```
INFO [simulator] Simulator connected on UDP port 14560
INFO [mavlink] partner IP: 127.0.0.1
INFO [ecl/EKF] EKF GPS checks passed (WGS-84 origin set)
INFO [ecl/EKF] EKF commencing GPS fusion
```
If you do not see these messages then check your port settings.
8. You should also be able to use QGroundControl with SITL mode. Make sure there is no Pixhawk
hardware plugged in, otherwise QGroundControl will choose to use that instead. Note that as we
don't have a physical board, an RC cannot be connected directly to it. So the alternatives are
either use XBox 360 Controller or connect your RC using USB (for example, in case of FrSky
Taranis X9D Plus) or using trainer USB cable to your PC. This makes your RC look like a joystick.
You will need to do extra set up in QGroundControl to use virtual joystick for RC control. You
do not need to do this unless you plan to fly a drone manually in AirSim. Autonomous flight
using the Python API does not require RC, see `No Remote Control` below.
## Setting GPS origin
Notice the above settings are provided in the `params` section of the `settings.json` file:
```
"LPE_LAT": 47.641468,
"LPE_LON": -122.140165,
```
PX4 SITL mode needs to be configured to get the home location correct.
The home location needs to be set to the same coordinates defined in [OriginGeopoint](settings.md#origingeopoint).
You can also run the following in the SITL PX4 console window to check
that these values are set correctly.
```
param show LPE_LAT
param show LPE_LON
```
## Smooth Offboard Transitions
Notice the above setting is provided in the `params` section of the `settings.json` file:
```
"COM_OBL_ACT": 1
```
This tells the drone automatically hover after each offboard control command finishes (the default
setting is to land). Hovering is a smoother transition between multiple offboard commands. You can
check this setting by running the following PX4 console command:
```
param show COM_OBL_ACT
```
## Check the Home Position
If you are using DroneShell to execute commands (arm, takeoff, etc) then you should wait until the
Home position is set. You will see the PX4 SITL console output this message:
```
INFO [commander] home: 47.6414680, -122.1401672, 119.99
INFO [tone_alarm] home_set
```
Now DroneShell 'pos' command should report this position and the commands should be accepted by PX4.
If you attempt to takeoff without a home position you will see the message:
```
WARN [commander] Takeoff denied, disarm and re-try
```
After home position is set check the local position reported by 'pos' command :
```
Local position: x=-0.0326988, y=0.00656854, z=5.48506
```
If the z coordinate is large like this then takeoff might not work as expected. Resetting the SITL
and simulation should fix that problem.
## WSL 2
Windows Subsystem for Linux version 2 operates in a Virtual Machine. This requires
additional setup - see [additional instructions](px4_sitl_wsl2.md).
## No Remote Control
Notice the above setting is provided in the `params` section of the `settings.json` file:
```
"NAV_RCL_ACT": 0,
"NAV_DLL_ACT": 0,
```
This is required if you plan to fly the SITL mode PX4 with no remote control, just using python
scripts, for example. These parameters stop the PX4 from triggering "failsafe mode on" every time a
move command is finished. You can use the following PX4 command to check these values are set
correctly:
```
param show NAV_RCL_ACT
param show NAV_DLL_ACT
```
NOTE: Do `NOT` do this on a real drone as it is too dangerous to fly without these failsafe measures.
## Manually set parameters
You can also run the following in the PX4 console to set all these parameters manually:
```
param set NAV_RCL_ACT 0
param set NAV_DLL_ACT 0
```
## Setting up multi-vehicle simulation
You can simulate multiple drones in SITL mode using AirSim. However, this requires setting up
multiple instances of the PX4 firmware simulator to be able to listen for each vehicle's connection
on a separate TCP port (4560, 4561, etc). Please see [this dedicated page](px4_multi_vehicle.md) for
instructions on setting up multiple instances of PX4 in SITL mode.
## Using VirtualBox Ubuntu
If you want to run the above posix_sitl in a `VirtualBox Ubuntu` machine then it will have a
different ip address from localhost. So in this case you need to edit the [settings
file](settings.md) and change the UdpIp and SitlIp to the ip address of your virtual machine set the
LocalIpAddress to the address of your host machine running the Unreal engine.
## Remote Controller
There are several options for flying the simulated drone using a remote control or joystick like
xbox gamepad. See [remote controllers](remote_control.md#rc-setup-for-px4)
| AirSim/docs/px4_sitl.md/0 | {
"file_path": "AirSim/docs/px4_sitl.md",
"repo_id": "AirSim",
"token_count": 3190
} | 66 |
# Upgrading Settings
The settings schema in AirSim 1.2 is changed for more flexibility and cleaner interface. If you have older [settings.json](settings.md) file then you can either delete it and restart AirSim or use this guide to make manual upgrade.
## Quicker Way
We recommend simply deleting the [settings.json](settings.md) and add back the settings you need.
Please see [the doc](settings.md) for complete information on available settings.
## Changes
### UsageScenario
Previously we used `UsageScenario` to specify the `ComputerVision` mode. Now we use `"SimMode": "ComputerVision"` instead.
### CameraDefaults and Changing Camera Settings
Previously we had `CaptureSettings` and `NoiseSettings` in root. Now these are combined in new `CameraDefaults` element. The [schema for this element](settings.md#camera_settings) is later used to configure cameras on vehicle.
### Gimbal
The [Gimbal element](settings.md#Gimbal) (instead of old Gimble element) is now moved out of `CaptureSettings`.
### CameraID to CameraName
All settings now reference cameras by [name](image_apis.md#available_cameras) instead of ID.
### Using PX4
The new Vehicles element allows to specify which vehicles to create. To use PX4, please see [this section](settings.md#using_px4).
### AdditionalCameras
The old `AdditionalCameras` setting is now replaced by [Cameras element](settings.md#Common_Vehicle_Setting) within vehicle setting.
| AirSim/docs/upgrade_settings.md/0 | {
"file_path": "AirSim/docs/upgrade_settings.md",
"repo_id": "AirSim",
"token_count": 369
} | 67 |
#ifndef _PID_POSITION_CONTROLLER_SIMPLE_H_
#define _PID_POSITION_CONTROLLER_SIMPLE_H_
#include "common/common_utils/StrictMode.hpp"
STRICT_MODE_OFF //todo what does this do?
#ifndef RPCLIB_MSGPACK
#define RPCLIB_MSGPACK clmdep_msgpack
#endif // !RPCLIB_MSGPACK
#include "rpc/rpc_error.h"
STRICT_MODE_ON
#include "common/common_utils/FileSystem.hpp"
#include "vehicles/multirotor/api/MultirotorRpcLibClient.hpp"
#include "common/GeodeticConverter.hpp"
#include <ros/ros.h>
#include <tf2/LinearMath/Matrix3x3.h>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <nav_msgs/Odometry.h>
#include <math.h>
#include <airsim_ros_pkgs/VelCmd.h>
#include <airsim_ros_pkgs/SetLocalPosition.h>
#include <airsim_ros_pkgs/SetGPSPosition.h>
#include <airsim_ros_pkgs/GPSYaw.h>
#include <math_common.h>
#include <utils.h>
// todo nicer api
class PIDParams
{
public:
double kp_x;
double kp_y;
double kp_z;
double kp_yaw;
double kd_x;
double kd_y;
double kd_z;
double kd_yaw;
double reached_thresh_xyz;
double reached_yaw_degrees;
PIDParams()
: kp_x(0.5), kp_y(0.5), kp_z(0.5), kp_yaw(0.5), kd_x(0.1), kd_y(0.1), kd_z(0.1), kd_yaw(0.1), reached_thresh_xyz(0.5), reached_yaw_degrees(5.0)
{
}
bool load_from_rosparams(const ros::NodeHandle& nh);
};
// todo should be a common representation
struct XYZYaw
{
double x;
double y;
double z;
double yaw;
};
// todo should be a common representation
class DynamicConstraints
{
public:
double max_vel_horz_abs; // meters/sec
double max_vel_vert_abs;
double max_yaw_rate_degree;
DynamicConstraints()
: max_vel_horz_abs(1.0), max_vel_vert_abs(0.5), max_yaw_rate_degree(10.0)
{
}
bool load_from_rosparams(const ros::NodeHandle& nh);
};
class PIDPositionController
{
public:
PIDPositionController(const ros::NodeHandle& nh, const ros::NodeHandle& nh_private);
// ROS service callbacks
bool local_position_goal_srv_cb(airsim_ros_pkgs::SetLocalPosition::Request& request, airsim_ros_pkgs::SetLocalPosition::Response& response);
bool local_position_goal_srv_override_cb(airsim_ros_pkgs::SetLocalPosition::Request& request, airsim_ros_pkgs::SetLocalPosition::Response& response);
bool gps_goal_srv_cb(airsim_ros_pkgs::SetGPSPosition::Request& request, airsim_ros_pkgs::SetGPSPosition::Response& response);
bool gps_goal_srv_override_cb(airsim_ros_pkgs::SetGPSPosition::Request& request, airsim_ros_pkgs::SetGPSPosition::Response& response);
// ROS subscriber callbacks
void airsim_odom_cb(const nav_msgs::Odometry& odom_msg);
void home_geopoint_cb(const airsim_ros_pkgs::GPSYaw& gps_msg);
void update_control_cmd_timer_cb(const ros::TimerEvent& event);
void reset_errors();
void initialize_ros();
void compute_control_cmd();
void enforce_dynamic_constraints();
void publish_control_cmd();
void check_reached_goal();
private:
msr::airlib::GeodeticConverter geodetic_converter_;
static constexpr bool use_eth_lib_for_geodetic_conv_ = true;
ros::NodeHandle nh_;
ros::NodeHandle nh_private_;
DynamicConstraints constraints_;
PIDParams params_;
XYZYaw target_position_;
XYZYaw curr_position_;
XYZYaw prev_error_;
XYZYaw curr_error_;
bool has_home_geo_;
airsim_ros_pkgs::GPSYaw gps_home_msg_;
nav_msgs::Odometry curr_odom_;
airsim_ros_pkgs::VelCmd vel_cmd_;
bool reached_goal_;
bool has_goal_;
bool has_odom_;
bool got_goal_once_;
// todo check for odom msg being older than n sec
ros::Publisher airsim_vel_cmd_world_frame_pub_;
ros::Subscriber airsim_odom_sub_;
ros::Subscriber home_geopoint_sub_;
ros::ServiceServer local_position_goal_srvr_;
ros::ServiceServer local_position_goal_override_srvr_;
ros::ServiceServer gps_goal_srvr_;
ros::ServiceServer gps_goal_override_srvr_;
ros::Timer update_control_cmd_timer_;
};
#endif /* _PID_POSITION_CONTROLLER_SIMPLE_ */
| AirSim/ros/src/airsim_ros_pkgs/include/pd_position_controller_simple.h/0 | {
"file_path": "AirSim/ros/src/airsim_ros_pkgs/include/pd_position_controller_simple.h",
"repo_id": "AirSim",
"token_count": 1748
} | 68 |
bool wait_on_last_task
---
bool success
| AirSim/ros2/src/airsim_interfaces/srv/Takeoff.srv/0 | {
"file_path": "AirSim/ros2/src/airsim_interfaces/srv/Takeoff.srv",
"repo_id": "AirSim",
"token_count": 14
} | 69 |
<?xml version='1.0' encoding='utf-8'?>
<package format="3">
<name>airsim_ros_pkgs</name>
<version>0.0.1</version>
<description>ROS Wrapper over AirSim's C++ client library</description>
<maintainer email="ratneshmadaan@gmail.com">Ratnesh Madaan</maintainer>
<license>MIT</license>
<buildtool_depend>ament_cmake</buildtool_depend>
<member_of_group>rosidl_interface_packages</member_of_group>
<build_depend>geometry_msgs</build_depend>
<build_depend>image_transport</build_depend>
<build_depend>message_runtime</build_depend>
<build_depend>mavros_msgs</build_depend>
<build_depend>nav_msgs</build_depend>
<build_depend>rclcpp</build_depend>
<build_depend>rclpy</build_depend>
<build_depend>sensor_msgs</build_depend>
<build_depend>std_msgs</build_depend>
<build_depend>geographic_msgs</build_depend>
<build_depend>geometry_msgs</build_depend>
<build_depend>tf2_sensor_msgs</build_depend>
<depend>airsim_interfaces</depend>
<build_depend>builtin_interfaces</build_depend>
<exec_depend>builtin_interfaces</exec_depend>
<build_depend>rosidl_default_generators</build_depend>
<exec_depend>geometry_msgs</exec_depend>
<exec_depend>image_transport</exec_depend>
<exec_depend>message_generation</exec_depend>
<exec_depend>message_runtime</exec_depend>
<exec_depend>nav_msgs</exec_depend>
<exec_depend>rclcpp</exec_depend>
<exec_depend>rclpy</exec_depend>
<exec_depend>sensor_msgs</exec_depend>
<exec_depend>std_msgs</exec_depend>
<exec_depend>joy</exec_depend>
<buildtool_depend>rosidl_default_generators</buildtool_depend>
<exec_depend>rosidl_default_runtime</exec_depend>
<export>
<build_type>ament_cmake</build_type>
</export>
<buildtool_depend>ament_cmake</buildtool_depend>
</package>
| AirSim/ros2/src/airsim_ros_pkgs/package.xml/0 | {
"file_path": "AirSim/ros2/src/airsim_ros_pkgs/package.xml",
"repo_id": "AirSim",
"token_count": 670
} | 70 |
@echo off
REM //---------- set up variable ----------
setlocal
set ROOT_DIR=%~dp0
pushd %~dp0
:success
@echo "Task completed."
goto end
:failed
@echo "Task has failed."
goto end
:end
popd | AirSim/tools/template.bat/0 | {
"file_path": "AirSim/tools/template.bat",
"repo_id": "AirSim",
"token_count": 73
} | 71 |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
namespace AssetStudio.PInvoke
{
public static class DllLoader
{
public static void PreloadDll(string dllName)
{
var dllDir = GetDirectedDllDirectory();
// Not using OperatingSystem.Platform.
// See: https://www.mono-project.com/docs/faq/technical/#how-to-detect-the-execution-platform
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Win32.LoadDll(dllDir, dllName);
}
else
{
Posix.LoadDll(dllDir, dllName);
}
}
private static string GetDirectedDllDirectory()
{
var localPath = Process.GetCurrentProcess().MainModule.FileName;
var localDir = Path.GetDirectoryName(localPath);
var subDir = Environment.Is64BitProcess ? "x64" : "x86";
var directedDllDir = Path.Combine(localDir, subDir);
return directedDllDir;
}
private static class Win32
{
internal static void LoadDll(string dllDir, string dllName)
{
var dllFileName = $"{dllName}.dll";
var directedDllPath = Path.Combine(dllDir, dllFileName);
// Specify SEARCH_DLL_LOAD_DIR to load dependent libraries located in the same platform-specific directory.
var hLibrary = LoadLibraryEx(directedDllPath, IntPtr.Zero, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR);
if (hLibrary == IntPtr.Zero)
{
var errorCode = Marshal.GetLastWin32Error();
var exception = new Win32Exception(errorCode);
throw new DllNotFoundException(exception.Message, exception);
}
}
// HMODULE LoadLibraryExA(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags);
// HMODULE LoadLibraryExW(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr LoadLibraryEx(string lpLibFileName, IntPtr hFile, uint dwFlags);
private const uint LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x1000;
private const uint LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR = 0x100;
}
private static class Posix
{
internal static void LoadDll(string dllDir, string dllName)
{
string dllExtension;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
dllExtension = ".so";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
dllExtension = ".dylib";
}
else
{
throw new NotSupportedException();
}
var dllFileName = $"lib{dllName}{dllExtension}";
var directedDllPath = Path.Combine(dllDir, dllFileName);
const int ldFlags = RTLD_NOW | RTLD_GLOBAL;
var hLibrary = DlOpen(directedDllPath, ldFlags);
if (hLibrary == IntPtr.Zero)
{
var pErrStr = DlError();
// `PtrToStringAnsi` always uses the specific constructor of `String` (see dotnet/core#2325),
// which in turn interprets the byte sequence with system default codepage. On OSX and Linux
// the codepage is UTF-8 so the error message should be handled correctly.
var errorMessage = Marshal.PtrToStringAnsi(pErrStr);
throw new DllNotFoundException(errorMessage);
}
}
// OSX and most Linux OS use LP64 so `int` is still 32-bit even on 64-bit platforms.
// void *dlopen(const char *filename, int flag);
[DllImport("libdl", EntryPoint = "dlopen")]
private static extern IntPtr DlOpen([MarshalAs(UnmanagedType.LPStr)] string fileName, int flags);
// char *dlerror(void);
[DllImport("libdl", EntryPoint = "dlerror")]
private static extern IntPtr DlError();
private const int RTLD_LAZY = 0x1;
private const int RTLD_NOW = 0x2;
private const int RTLD_GLOBAL = 0x100;
}
}
}
| AssetStudio/AssetStudio.PInvoke/DllLoader.cs/0 | {
"file_path": "AssetStudio/AssetStudio.PInvoke/DllLoader.cs",
"repo_id": "AssetStudio",
"token_count": 2228
} | 72 |
using System;
namespace SevenZip.Compression.RangeCoder
{
struct BitTreeEncoder
{
BitEncoder[] Models;
int NumBitLevels;
public BitTreeEncoder(int numBitLevels)
{
NumBitLevels = numBitLevels;
Models = new BitEncoder[1 << numBitLevels];
}
public void Init()
{
for (uint i = 1; i < (1 << NumBitLevels); i++)
Models[i].Init();
}
public void Encode(Encoder rangeEncoder, UInt32 symbol)
{
UInt32 m = 1;
for (int bitIndex = NumBitLevels; bitIndex > 0; )
{
bitIndex--;
UInt32 bit = (symbol >> bitIndex) & 1;
Models[m].Encode(rangeEncoder, bit);
m = (m << 1) | bit;
}
}
public void ReverseEncode(Encoder rangeEncoder, UInt32 symbol)
{
UInt32 m = 1;
for (UInt32 i = 0; i < NumBitLevels; i++)
{
UInt32 bit = symbol & 1;
Models[m].Encode(rangeEncoder, bit);
m = (m << 1) | bit;
symbol >>= 1;
}
}
public UInt32 GetPrice(UInt32 symbol)
{
UInt32 price = 0;
UInt32 m = 1;
for (int bitIndex = NumBitLevels; bitIndex > 0; )
{
bitIndex--;
UInt32 bit = (symbol >> bitIndex) & 1;
price += Models[m].GetPrice(bit);
m = (m << 1) + bit;
}
return price;
}
public UInt32 ReverseGetPrice(UInt32 symbol)
{
UInt32 price = 0;
UInt32 m = 1;
for (int i = NumBitLevels; i > 0; i--)
{
UInt32 bit = symbol & 1;
symbol >>= 1;
price += Models[m].GetPrice(bit);
m = (m << 1) | bit;
}
return price;
}
public static UInt32 ReverseGetPrice(BitEncoder[] Models, UInt32 startIndex,
int NumBitLevels, UInt32 symbol)
{
UInt32 price = 0;
UInt32 m = 1;
for (int i = NumBitLevels; i > 0; i--)
{
UInt32 bit = symbol & 1;
symbol >>= 1;
price += Models[startIndex + m].GetPrice(bit);
m = (m << 1) | bit;
}
return price;
}
public static void ReverseEncode(BitEncoder[] Models, UInt32 startIndex,
Encoder rangeEncoder, int NumBitLevels, UInt32 symbol)
{
UInt32 m = 1;
for (int i = 0; i < NumBitLevels; i++)
{
UInt32 bit = symbol & 1;
Models[startIndex + m].Encode(rangeEncoder, bit);
m = (m << 1) | bit;
symbol >>= 1;
}
}
}
struct BitTreeDecoder
{
BitDecoder[] Models;
int NumBitLevels;
public BitTreeDecoder(int numBitLevels)
{
NumBitLevels = numBitLevels;
Models = new BitDecoder[1 << numBitLevels];
}
public void Init()
{
for (uint i = 1; i < (1 << NumBitLevels); i++)
Models[i].Init();
}
public uint Decode(RangeCoder.Decoder rangeDecoder)
{
uint m = 1;
for (int bitIndex = NumBitLevels; bitIndex > 0; bitIndex--)
m = (m << 1) + Models[m].Decode(rangeDecoder);
return m - ((uint)1 << NumBitLevels);
}
public uint ReverseDecode(RangeCoder.Decoder rangeDecoder)
{
uint m = 1;
uint symbol = 0;
for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++)
{
uint bit = Models[m].Decode(rangeDecoder);
m <<= 1;
m += bit;
symbol |= (bit << bitIndex);
}
return symbol;
}
public static uint ReverseDecode(BitDecoder[] Models, UInt32 startIndex,
RangeCoder.Decoder rangeDecoder, int NumBitLevels)
{
uint m = 1;
uint symbol = 0;
for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++)
{
uint bit = Models[startIndex + m].Decode(rangeDecoder);
m <<= 1;
m += bit;
symbol |= (bit << bitIndex);
}
return symbol;
}
}
}
| AssetStudio/AssetStudio/7zip/Compress/RangeCoder/RangeCoderBitTree.cs/0 | {
"file_path": "AssetStudio/AssetStudio/7zip/Compress/RangeCoder/RangeCoderBitTree.cs",
"repo_id": "AssetStudio",
"token_count": 1562
} | 73 |
/* Copyright 2015 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
namespace Org.Brotli.Dec
{
internal sealed class State
{
internal int runningState = Org.Brotli.Dec.RunningState.Uninitialized;
internal int nextRunningState;
internal readonly Org.Brotli.Dec.BitReader br = new Org.Brotli.Dec.BitReader();
internal byte[] ringBuffer;
internal readonly int[] blockTypeTrees = new int[3 * Org.Brotli.Dec.Huffman.HuffmanMaxTableSize];
internal readonly int[] blockLenTrees = new int[3 * Org.Brotli.Dec.Huffman.HuffmanMaxTableSize];
internal int metaBlockLength;
internal bool inputEnd;
internal bool isUncompressed;
internal bool isMetadata;
internal readonly Org.Brotli.Dec.HuffmanTreeGroup hGroup0 = new Org.Brotli.Dec.HuffmanTreeGroup();
internal readonly Org.Brotli.Dec.HuffmanTreeGroup hGroup1 = new Org.Brotli.Dec.HuffmanTreeGroup();
internal readonly Org.Brotli.Dec.HuffmanTreeGroup hGroup2 = new Org.Brotli.Dec.HuffmanTreeGroup();
internal readonly int[] blockLength = new int[3];
internal readonly int[] numBlockTypes = new int[3];
internal readonly int[] blockTypeRb = new int[6];
internal readonly int[] distRb = new int[] { 16, 15, 11, 4 };
internal int pos = 0;
internal int maxDistance = 0;
internal int distRbIdx = 0;
internal bool trivialLiteralContext = false;
internal int literalTreeIndex = 0;
internal int literalTree;
internal int j;
internal int insertLength;
internal byte[] contextModes;
internal byte[] contextMap;
internal int contextMapSlice;
internal int distContextMapSlice;
internal int contextLookupOffset1;
internal int contextLookupOffset2;
internal int treeCommandOffset;
internal int distanceCode;
internal byte[] distContextMap;
internal int numDirectDistanceCodes;
internal int distancePostfixMask;
internal int distancePostfixBits;
internal int distance;
internal int copyLength;
internal int copyDst;
internal int maxBackwardDistance;
internal int maxRingBufferSize;
internal int ringBufferSize = 0;
internal long expectedTotalSize = 0;
internal byte[] customDictionary = new byte[0];
internal int bytesToIgnore = 0;
internal int outputOffset;
internal int outputLength;
internal int outputUsed;
internal int bytesWritten;
internal int bytesToWrite;
internal byte[] output;
// Current meta-block header information.
// TODO: Update to current spec.
private static int DecodeWindowBits(Org.Brotli.Dec.BitReader br)
{
if (Org.Brotli.Dec.BitReader.ReadBits(br, 1) == 0)
{
return 16;
}
int n = Org.Brotli.Dec.BitReader.ReadBits(br, 3);
if (n != 0)
{
return 17 + n;
}
n = Org.Brotli.Dec.BitReader.ReadBits(br, 3);
if (n != 0)
{
return 8 + n;
}
return 17;
}
/// <summary>Associate input with decoder state.</summary>
/// <param name="state">uninitialized state without associated input</param>
/// <param name="input">compressed data source</param>
internal static void SetInput(Org.Brotli.Dec.State state, System.IO.Stream input)
{
if (state.runningState != Org.Brotli.Dec.RunningState.Uninitialized)
{
throw new System.InvalidOperationException("State MUST be uninitialized");
}
Org.Brotli.Dec.BitReader.Init(state.br, input);
int windowBits = DecodeWindowBits(state.br);
if (windowBits == 9)
{
/* Reserved case for future expansion. */
throw new Org.Brotli.Dec.BrotliRuntimeException("Invalid 'windowBits' code");
}
state.maxRingBufferSize = 1 << windowBits;
state.maxBackwardDistance = state.maxRingBufferSize - 16;
state.runningState = Org.Brotli.Dec.RunningState.BlockStart;
}
/// <exception cref="System.IO.IOException"/>
internal static void Close(Org.Brotli.Dec.State state)
{
if (state.runningState == Org.Brotli.Dec.RunningState.Uninitialized)
{
throw new System.InvalidOperationException("State MUST be initialized");
}
if (state.runningState == Org.Brotli.Dec.RunningState.Closed)
{
return;
}
state.runningState = Org.Brotli.Dec.RunningState.Closed;
Org.Brotli.Dec.BitReader.Close(state.br);
}
}
}
| AssetStudio/AssetStudio/Brotli/State.cs/0 | {
"file_path": "AssetStudio/AssetStudio/Brotli/State.cs",
"repo_id": "AssetStudio",
"token_count": 1509
} | 74 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AssetStudio
{
public abstract class Behaviour : Component
{
public byte m_Enabled;
protected Behaviour(ObjectReader reader) : base(reader)
{
m_Enabled = reader.ReadByte();
reader.AlignStream();
}
}
}
| AssetStudio/AssetStudio/Classes/Behaviour.cs/0 | {
"file_path": "AssetStudio/AssetStudio/Classes/Behaviour.cs",
"repo_id": "AssetStudio",
"token_count": 152
} | 75 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AssetStudio
{
public sealed class PlayerSettings : Object
{
public string companyName;
public string productName;
public PlayerSettings(ObjectReader reader) : base(reader)
{
if (version[0] > 5 || (version[0] == 5 && version[1] >= 4)) //5.4.0 nad up
{
var productGUID = reader.ReadBytes(16);
}
var AndroidProfiler = reader.ReadBoolean();
//bool AndroidFilterTouchesWhenObscured 2017.2 and up
//bool AndroidEnableSustainedPerformanceMode 2018 and up
reader.AlignStream();
int defaultScreenOrientation = reader.ReadInt32();
int targetDevice = reader.ReadInt32();
if (version[0] < 5 || (version[0] == 5 && version[1] < 3)) //5.3 down
{
if (version[0] < 5) //5.0 down
{
int targetPlatform = reader.ReadInt32(); //4.0 and up targetGlesGraphics
if (version[0] > 4 || (version[0] == 4 && version[1] >= 6)) //4.6 and up
{
var targetIOSGraphics = reader.ReadInt32();
}
}
int targetResolution = reader.ReadInt32();
}
else
{
var useOnDemandResources = reader.ReadBoolean();
reader.AlignStream();
}
if (version[0] > 3 || (version[0] == 3 && version[1] >= 5)) //3.5 and up
{
var accelerometerFrequency = reader.ReadInt32();
}
companyName = reader.ReadAlignedString();
productName = reader.ReadAlignedString();
}
}
}
| AssetStudio/AssetStudio/Classes/PlayerSettings.cs/0 | {
"file_path": "AssetStudio/AssetStudio/Classes/PlayerSettings.cs",
"repo_id": "AssetStudio",
"token_count": 919
} | 76 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AssetStudio
{
public enum EndianType
{
LittleEndian,
BigEndian
}
}
| AssetStudio/AssetStudio/EndianType.cs/0 | {
"file_path": "AssetStudio/AssetStudio/EndianType.cs",
"repo_id": "AssetStudio",
"token_count": 91
} | 77 |
using System;
using System.Runtime.InteropServices;
namespace AssetStudio
{
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct Quaternion : IEquatable<Quaternion>
{
public float X;
public float Y;
public float Z;
public float W;
public Quaternion(float x, float y, float z, float w)
{
X = x;
Y = y;
Z = z;
W = w;
}
public float this[int index]
{
get
{
switch (index)
{
case 0: return X;
case 1: return Y;
case 2: return Z;
case 3: return W;
default: throw new ArgumentOutOfRangeException(nameof(index), "Invalid Quaternion index!");
}
}
set
{
switch (index)
{
case 0: X = value; break;
case 1: Y = value; break;
case 2: Z = value; break;
case 3: W = value; break;
default: throw new ArgumentOutOfRangeException(nameof(index), "Invalid Quaternion index!");
}
}
}
public override int GetHashCode()
{
return X.GetHashCode() ^ (Y.GetHashCode() << 2) ^ (Z.GetHashCode() >> 2) ^ (W.GetHashCode() >> 1);
}
public override bool Equals(object other)
{
if (!(other is Quaternion))
return false;
return Equals((Quaternion)other);
}
public bool Equals(Quaternion other)
{
return X.Equals(other.X) && Y.Equals(other.Y) && Z.Equals(other.Z) && W.Equals(other.W);
}
public static float Dot(Quaternion a, Quaternion b)
{
return a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W;
}
private static bool IsEqualUsingDot(float dot)
{
return dot > 1.0f - kEpsilon;
}
public static bool operator ==(Quaternion lhs, Quaternion rhs)
{
return IsEqualUsingDot(Dot(lhs, rhs));
}
public static bool operator !=(Quaternion lhs, Quaternion rhs)
{
return !(lhs == rhs);
}
private const float kEpsilon = 0.000001F;
}
}
| AssetStudio/AssetStudio/Math/Quaternion.cs/0 | {
"file_path": "AssetStudio/AssetStudio/Math/Quaternion.cs",
"repo_id": "AssetStudio",
"token_count": 1333
} | 78 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AssetStudio
{
public class TypeTreeNode
{
public string m_Type;
public string m_Name;
public int m_ByteSize;
public int m_Index;
public int m_TypeFlags; //m_IsArray
public int m_Version;
public int m_MetaFlag;
public int m_Level;
public uint m_TypeStrOffset;
public uint m_NameStrOffset;
public ulong m_RefTypeHash;
public TypeTreeNode() { }
public TypeTreeNode(string type, string name, int level, bool align)
{
m_Type = type;
m_Name = name;
m_Level = level;
m_MetaFlag = align ? 0x4000 : 0;
}
}
}
| AssetStudio/AssetStudio/TypeTreeNode.cs/0 | {
"file_path": "AssetStudio/AssetStudio/TypeTreeNode.cs",
"repo_id": "AssetStudio",
"token_count": 364
} | 79 |
#define AS_API(ret_type)
| AssetStudio/AssetStudioFBXNative/cpp.hint/0 | {
"file_path": "AssetStudio/AssetStudioFBXNative/cpp.hint",
"repo_id": "AssetStudio",
"token_count": 11
} | 80 |
using System.Windows.Forms;
using AssetStudio;
namespace AssetStudioGUI
{
internal class AssetItem : ListViewItem
{
public Object Asset;
public SerializedFile SourceFile;
public string Container = string.Empty;
public string TypeString;
public long m_PathID;
public long FullSize;
public ClassIDType Type;
public string InfoText;
public string UniqueID;
public GameObjectTreeNode TreeNode;
public AssetItem(Object asset)
{
Asset = asset;
SourceFile = asset.assetsFile;
Type = asset.type;
TypeString = Type.ToString();
m_PathID = asset.m_PathID;
FullSize = asset.byteSize;
}
public void SetSubItems()
{
SubItems.AddRange(new[]
{
Container, //Container
TypeString, //Type
m_PathID.ToString(), //PathID
FullSize.ToString(), //Size
});
}
}
}
| AssetStudio/AssetStudioGUI/Components/AssetItem.cs/0 | {
"file_path": "AssetStudio/AssetStudioGUI/Components/AssetItem.cs",
"repo_id": "AssetStudio",
"token_count": 511
} | 81 |
using System;
using System.IO;
using System.Runtime.CompilerServices;
namespace SpirV
{
internal sealed class Reader
{
public Reader(BinaryReader reader)
{
reader_ = reader;
uint magicNumber = reader_.ReadUInt32();
if (magicNumber == Meta.MagicNumber)
{
littleEndian_ = true;
}
else if (Reverse(magicNumber) == Meta.MagicNumber)
{
littleEndian_ = false;
}
else
{
throw new Exception("Invalid magic number");
}
}
public uint ReadDWord()
{
if (littleEndian_)
{
return reader_.ReadUInt32 ();
}
else
{
return Reverse(reader_.ReadUInt32());
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static uint Reverse(uint u)
{
return (u << 24) | (u & 0xFF00U) << 8 | (u >> 8) & 0xFF00U | (u >> 24);
}
public bool EndOfStream => reader_.BaseStream.Position == reader_.BaseStream.Length;
private readonly BinaryReader reader_;
private readonly bool littleEndian_;
}
}
| AssetStudio/AssetStudioUtility/CSspv/Reader.cs/0 | {
"file_path": "AssetStudio/AssetStudioUtility/CSspv/Reader.cs",
"repo_id": "AssetStudio",
"token_count": 393
} | 82 |
using System;
using System.IO;
using System.Text;
namespace Smolv
{
public static class SmolvDecoder
{
public static int GetDecodedBufferSize(byte[] data)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
if (!CheckSmolHeader(data))
{
return 0;
}
int size = BitConverter.ToInt32(data, 5 * sizeof(uint));
return size;
}
public static int GetDecodedBufferSize(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanSeek)
{
throw new ArgumentException(nameof(stream));
}
if (stream.Position + HeaderSize > stream.Length)
{
return 0;
}
long initPosition = stream.Position;
stream.Position += HeaderSize - sizeof(uint);
int size = stream.ReadByte() | stream.ReadByte() << 8 | stream.ReadByte() << 16 | stream.ReadByte() << 24;
stream.Position = initPosition;
return size;
}
public static byte[] Decode(byte[] data)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
int bufferSize = GetDecodedBufferSize(data);
if (bufferSize == 0)
{
// invalid SMOL-V
return null;
}
byte[] output = new byte[bufferSize];
if (Decode(data, output))
{
return output;
}
return null;
}
public static bool Decode(byte[] data, byte[] output)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
int bufferSize = GetDecodedBufferSize(data);
if (bufferSize > output.Length)
{
return false;
}
using (MemoryStream outputStream = new MemoryStream(output))
{
return Decode(data, outputStream);
}
}
public static bool Decode(byte[] data, Stream outputStream)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
using (MemoryStream inputStream = new MemoryStream(data))
{
return Decode(inputStream, data.Length, outputStream);
}
}
public static bool Decode(Stream inputStream, int inputSize, Stream outputStream)
{
if (inputStream == null)
{
throw new ArgumentNullException(nameof(inputStream));
}
if (outputStream == null)
{
throw new ArgumentNullException(nameof(outputStream));
}
if (inputStream.Length < HeaderSize)
{
return false;
}
using (BinaryReader input = new BinaryReader(inputStream, Encoding.UTF8, true))
{
using (BinaryWriter output = new BinaryWriter(outputStream, Encoding.UTF8, true))
{
long inputEndPosition = input.BaseStream.Position + inputSize;
long outputStartPosition = output.BaseStream.Position;
// Header
output.Write(SpirVHeaderMagic);
input.BaseStream.Position += sizeof(uint);
uint version = input.ReadUInt32();
output.Write(version);
uint generator = input.ReadUInt32();
output.Write(generator);
int bound = input.ReadInt32();
output.Write(bound);
uint schema = input.ReadUInt32();
output.Write(schema);
int decodedSize = input.ReadInt32();
// Body
int prevResult = 0;
int prevDecorate = 0;
while (input.BaseStream.Position < inputEndPosition)
{
// read length + opcode
if (!ReadLengthOp(input, out uint instrLen, out SpvOp op))
{
return false;
}
bool wasSwizzle = op == SpvOp.VectorShuffleCompact;
if (wasSwizzle)
{
op = SpvOp.VectorShuffle;
}
output.Write((instrLen << 16) | (uint)op);
uint ioffs = 1;
// read type as varint, if we have it
if (op.OpHasType())
{
if (!ReadVarint(input, out uint value))
{
return false;
}
output.Write(value);
ioffs++;
}
// read result as delta+varint, if we have it
if (op.OpHasResult())
{
if (!ReadVarint(input, out uint value))
{
return false;
}
int zds = prevResult + ZigDecode(value);
output.Write(zds);
prevResult = zds;
ioffs++;
}
// Decorate: IDs relative to previous decorate
if (op == SpvOp.Decorate || op == SpvOp.MemberDecorate)
{
if (!ReadVarint(input, out uint value))
{
return false;
}
int zds = prevDecorate + unchecked((int)value);
output.Write(zds);
prevDecorate = zds;
ioffs++;
}
// Read this many IDs, that are relative to result ID
int relativeCount = op.OpDeltaFromResult();
bool inverted = false;
if (relativeCount < 0)
{
inverted = true;
relativeCount = -relativeCount;
}
for (int i = 0; i < relativeCount && ioffs < instrLen; ++i, ++ioffs)
{
if (!ReadVarint(input, out uint value))
{
return false;
}
int zd = inverted ? ZigDecode(value) : unchecked((int)value);
output.Write(prevResult - zd);
}
if (wasSwizzle && instrLen <= 9)
{
uint swizzle = input.ReadByte();
if (instrLen > 5) output.Write(swizzle >> 6);
if (instrLen > 6) output.Write((swizzle >> 4) & 3);
if (instrLen > 7) output.Write((swizzle >> 2) & 3);
if (instrLen > 8) output.Write(swizzle & 3);
}
else if (op.OpVarRest())
{
// read rest of words with variable encoding
for (; ioffs < instrLen; ++ioffs)
{
if (!ReadVarint(input, out uint value))
{
return false;
}
output.Write(value);
}
}
else
{
// read rest of words without any encoding
for (; ioffs < instrLen; ++ioffs)
{
if (input.BaseStream.Position + 4 > input.BaseStream.Length)
{
return false;
}
uint val = input.ReadUInt32();
output.Write(val);
}
}
}
if (output.BaseStream.Position != outputStartPosition + decodedSize)
{
// something went wrong during decoding? we should have decoded to exact output size
return false;
}
return true;
}
}
}
private static bool CheckSmolHeader(byte[] data)
{
if (!CheckGenericHeader(data, SmolHeaderMagic))
{
return false;
}
return true;
}
private static bool CheckGenericHeader(byte[] data, uint expectedMagic)
{
if (data == null)
{
return false;
}
if (data.Length < HeaderSize)
{
return false;
}
uint headerMagic = BitConverter.ToUInt32(data, 0 * sizeof(uint));
if (headerMagic != expectedMagic)
{
return false;
}
uint headerVersion = BitConverter.ToUInt32(data, 1 * sizeof(uint));
if (headerVersion < 0x00010000 || headerVersion > 0x00010300)
{
// only support 1.0 through 1.3
return false;
}
return true;
}
private static bool ReadVarint(BinaryReader input, out uint value)
{
uint v = 0;
int shift = 0;
while (input.BaseStream.Position < input.BaseStream.Length)
{
byte b = input.ReadByte();
v |= unchecked((uint)(b & 127) << shift);
shift += 7;
if ((b & 128) == 0)
{
break;
}
}
value = v;
// @TODO: report failures
return true;
}
private static bool ReadLengthOp(BinaryReader input, out uint len, out SpvOp op)
{
len = default;
op = default;
if (!ReadVarint(input, out uint value))
{
return false;
}
len = ((value >> 20) << 4) | ((value >> 4) & 0xF);
op = (SpvOp) (((value >> 4) & 0xFFF0) | (value & 0xF));
op = RemapOp(op);
len = DecodeLen(op, len);
return true;
}
/// <summary>
/// Remap most common Op codes (Load, Store, Decorate, VectorShuffle etc.) to be in < 16 range, for
/// more compact varint encoding. This basically swaps rarely used op values that are < 16 with the
/// ones that are common.
/// </summary>
private static SpvOp RemapOp(SpvOp op)
{
switch (op)
{
// 0: 24%
case SpvOp.Decorate:
return SpvOp.Nop;
case SpvOp.Nop:
return SpvOp.Decorate;
// 1: 17%
case SpvOp.Load:
return SpvOp.Undef;
case SpvOp.Undef:
return SpvOp.Load;
// 2: 9%
case SpvOp.Store:
return SpvOp.SourceContinued;
case SpvOp.SourceContinued:
return SpvOp.Store;
// 3: 7.2%
case SpvOp.AccessChain:
return SpvOp.Source;
case SpvOp.Source:
return SpvOp.AccessChain;
// 4: 5.0%
// Name - already small enum value - 5: 4.4%
// MemberName - already small enum value - 6: 2.9%
case SpvOp.VectorShuffle:
return SpvOp.SourceExtension;
case SpvOp.SourceExtension:
return SpvOp.VectorShuffle;
// 7: 4.0%
case SpvOp.MemberDecorate:
return SpvOp.String;
case SpvOp.String:
return SpvOp.MemberDecorate;
// 8: 0.9%
case SpvOp.Label:
return SpvOp.Line;
case SpvOp.Line:
return SpvOp.Label;
// 9: 3.9%
case SpvOp.Variable:
return (SpvOp)9;
case (SpvOp)9:
return SpvOp.Variable;
// 10: 3.9%
case SpvOp.FMul:
return SpvOp.Extension;
case SpvOp.Extension:
return SpvOp.FMul;
// 11: 2.5%
// ExtInst - already small enum value - 12: 1.2%
// VectorShuffleCompact - already small enum value - used for compact shuffle encoding
case SpvOp.FAdd:
return SpvOp.ExtInstImport;
case SpvOp.ExtInstImport:
return SpvOp.FAdd;
// 14: 2.2%
case SpvOp.TypePointer:
return SpvOp.MemoryModel;
case SpvOp.MemoryModel:
return SpvOp.TypePointer;
// 15: 1.1%
case SpvOp.FNegate:
return SpvOp.EntryPoint;
case SpvOp.EntryPoint:
return SpvOp.FNegate;
}
return op;
}
private static uint DecodeLen(SpvOp op, uint len)
{
len++;
switch (op)
{
case SpvOp.VectorShuffle:
len += 4;
break;
case SpvOp.VectorShuffleCompact:
len += 4;
break;
case SpvOp.Decorate:
len += 2;
break;
case SpvOp.Load:
len += 3;
break;
case SpvOp.AccessChain:
len += 3;
break;
}
return len;
}
private static int DecorationExtraOps(int dec)
{
// RelaxedPrecision, Block..ColMajor
if (dec == 0 || (dec >= 2 && dec <= 5))
{
return 0;
}
// Stream..XfbStride
if (dec >= 29 && dec <= 37)
{
return 1;
}
// unknown, encode length
return -1;
}
private static int ZigDecode(uint u)
{
return (u & 1) != 0 ? unchecked((int)(~(u >> 1))) : unchecked((int)(u >> 1));
}
public const uint SpirVHeaderMagic = 0x07230203;
/// <summary>
/// 'SMOL' ascii
/// </summary>
public const uint SmolHeaderMagic = 0x534D4F4C;
private const int HeaderSize = 6 * sizeof(uint);
}
}
| AssetStudio/AssetStudioUtility/Smolv/SmolvDecoder.cs/0 | {
"file_path": "AssetStudio/AssetStudioUtility/Smolv/SmolvDecoder.cs",
"repo_id": "AssetStudio",
"token_count": 4906
} | 83 |
# AssetStudio
[](https://ci.appveyor.com/project/Perfare/assetstudio/branch/master/artifacts)
**None of the repo, the tool, nor the repo owner is affiliated with, or sponsored or authorized by, Unity Technologies or its affiliates.**
AssetStudio is a tool for exploring, extracting and exporting assets and assetbundles.
## Features
* Support version:
* 3.4 - 2022.1
* Support asset types:
* **Texture2D** : convert to png, tga, jpeg, bmp
* **Sprite** : crop Texture2D to png, tga, jpeg, bmp
* **AudioClip** : mp3, ogg, wav, m4a, fsb. support convert FSB file to WAV(PCM)
* **Font** : ttf, otf
* **Mesh** : obj
* **TextAsset**
* **Shader**
* **MovieTexture**
* **VideoClip**
* **MonoBehaviour** : json
* **Animator** : export to FBX file with bound AnimationClip
## Requirements
- AssetStudio.net472
- [.NET Framework 4.7.2](https://dotnet.microsoft.com/download/dotnet-framework/net472)
- AssetStudio.net5
- [.NET Desktop Runtime 5.0](https://dotnet.microsoft.com/download/dotnet/5.0)
- AssetStudio.net6
- [.NET Desktop Runtime 6.0](https://dotnet.microsoft.com/download/dotnet/6.0)
## Usage
### Load Assets/AssetBundles
Use **File-Load file** or **File-Load folder**.
When AssetStudio loads AssetBundles, it decompresses and reads it directly in memory, which may cause a large amount of memory to be used. You can use **File-Extract file** or **File-Extract folder** to extract AssetBundles to another folder, and then read.
### Extract/Decompress AssetBundles
Use **File-Extract file** or **File-Extract folder**.
### Export Assets
use **Export** menu.
### Export Model
Export model from "Scene Hierarchy" using the **Model** menu.
Export Animator from "Asset List" using the **Export** menu.
#### With AnimationClip
Select model from "Scene Hierarchy" then select the AnimationClip from "Asset List", using **Model-Export selected objects with AnimationClip** to export.
Export Animator will export bound AnimationClip or use **Ctrl** to select Animator and AnimationClip from "Asset List", using **Export-Export Animator with selected AnimationClip** to export.
### Export MonoBehaviour
When you select an asset of the MonoBehaviour type for the first time, AssetStudio will ask you the directory where the assembly is located, please select the directory where the assembly is located, such as the `Managed` folder.
#### For Il2Cpp
First, use my another program [Il2CppDumper](https://github.com/Perfare/Il2CppDumper) to generate dummy dll, then when using AssetStudio to select the assembly directory, select the dummy dll folder.
## Build
* Visual Studio 2022 or newer
* **AssetStudioFBXNative** uses [FBX SDK 2020.2.1](https://www.autodesk.com/developer-network/platform-technologies/fbx-sdk-2020-2-1), before building, you need to install the FBX SDK and modify the project file, change include directory and library directory to point to the FBX SDK directory
## Open source libraries used
### Texture2DDecoder
* [Ishotihadus/mikunyan](https://github.com/Ishotihadus/mikunyan)
* [BinomialLLC/crunch](https://github.com/BinomialLLC/crunch)
* [Unity-Technologies/crunch](https://github.com/Unity-Technologies/crunch/tree/unity)
| AssetStudio/README.md/0 | {
"file_path": "AssetStudio/README.md",
"repo_id": "AssetStudio",
"token_count": 1014
} | 84 |
// File: crnlib.h - Advanced DXTn texture compression library.
// Copyright (c) 2010-2016 Richard Geldreich, Jr. All rights reserved.
// See copyright notice and license at the end of this file.
//
// This header file contains the public crnlib declarations for DXTn,
// clustered DXTn, and CRN compression/decompression.
//
// Note: This library does NOT need to be linked into your game executable if
// all you want to do is transcode .CRN files to raw DXTn bits at run-time.
// The crn_decomp.h header file library contains all the code necessary for
// decompression.
//
// Important: If compiling with gcc, be sure strict aliasing is disabled: -fno-strict-aliasing
#ifndef CRNLIB_H
#define CRNLIB_H
#ifdef _MSC_VER
#pragma warning (disable: 4127) // conditional expression is constant
#endif
#define CRNLIB_VERSION 104
#define CRNLIB_SUPPORT_ATI_COMPRESS 0
#define CRNLIB_SUPPORT_SQUISH 0
typedef unsigned char crn_uint8;
typedef unsigned short crn_uint16;
typedef unsigned int crn_uint32;
typedef signed char crn_int8;
typedef signed short crn_int16;
typedef signed int crn_int32;
typedef unsigned int crn_bool;
// crnlib can compress to these file types.
enum crn_file_type
{
// .CRN
cCRNFileTypeCRN = 0,
// .DDS using regular DXT or clustered DXT
cCRNFileTypeDDS,
cCRNFileTypeForceDWORD = 0xFFFFFFFF
};
// Supported compressed pixel formats.
// Basically all the standard DX9 formats, with some swizzled DXT5 formats
// (most of them supported by ATI's Compressonator), along with some ATI/X360 GPU specific formats.
enum crn_format
{
cCRNFmtInvalid = -1,
cCRNFmtDXT1 = 0,
cCRNFmtFirstValid = cCRNFmtDXT1,
// cCRNFmtDXT3 is not currently supported when writing to CRN - only DDS.
cCRNFmtDXT3,
cCRNFmtDXT5,
// Various DXT5 derivatives
cCRNFmtDXT5_CCxY, // Luma-chroma
cCRNFmtDXT5_xGxR, // Swizzled 2-component
cCRNFmtDXT5_xGBR, // Swizzled 3-component
cCRNFmtDXT5_AGBR, // Swizzled 4-component
// ATI 3DC and X360 DXN
cCRNFmtDXN_XY,
cCRNFmtDXN_YX,
// DXT5 alpha blocks only
cCRNFmtDXT5A,
cCRNFmtETC1,
cCRNFmtTotal,
cCRNFmtForceDWORD = 0xFFFFFFFF
};
// Various library/file format limits.
enum crn_limits
{
// Max. mipmap level resolution on any axis.
cCRNMaxLevelResolution = 4096,
cCRNMinPaletteSize = 8,
cCRNMaxPaletteSize = 8192,
cCRNMaxFaces = 6,
cCRNMaxLevels = 16,
cCRNMaxHelperThreads = 16,
cCRNMinQualityLevel = 0,
cCRNMaxQualityLevel = 255
};
// CRN/DDS compression flags.
// See the m_flags member in the crn_comp_params struct, below.
enum crn_comp_flags
{
// Enables perceptual colorspace distance metrics if set.
// Important: Be sure to disable this when compressing non-sRGB colorspace images, like normal maps!
// Default: Set
cCRNCompFlagPerceptual = 1,
// Enables (up to) 8x8 macroblock usage if set. If disabled, only 4x4 blocks are allowed.
// Compression ratio will be lower when disabled, but may cut down on blocky artifacts because the process used to determine
// where large macroblocks can be used without artifacts isn't perfect.
// Default: Set.
cCRNCompFlagHierarchical = 2,
// cCRNCompFlagQuick disables several output file optimizations - intended for things like quicker previews.
// Default: Not set.
cCRNCompFlagQuick = 4,
// DXT1: OK to use DXT1 alpha blocks for better quality or DXT1A transparency.
// DXT5: OK to use both DXT5 block types.
// Currently only used when writing to .DDS files, as .CRN uses only a subset of the possible DXTn block types.
// Default: Set.
cCRNCompFlagUseBothBlockTypes = 8,
// OK to use DXT1A transparent indices to encode black (assumes pixel shader ignores fetched alpha).
// Currently only used when writing to .DDS files, .CRN never uses alpha blocks.
// Default: Not set.
cCRNCompFlagUseTransparentIndicesForBlack = 16,
// Disables endpoint caching, for more deterministic output.
// Currently only used when writing to .DDS files.
// Default: Not set.
cCRNCompFlagDisableEndpointCaching = 32,
// If enabled, use the cCRNColorEndpointPaletteSize, etc. params to control the CRN palette sizes. Only useful when writing to .CRN files.
// Default: Not set.
cCRNCompFlagManualPaletteSizes = 64,
// If enabled, DXT1A alpha blocks are used to encode single bit transparency.
// Default: Not set.
cCRNCompFlagDXT1AForTransparency = 128,
// If enabled, the DXT1 compressor's color distance metric assumes the pixel shader will be converting the fetched RGB results to luma (Y part of YCbCr).
// This increases quality when compressing grayscale images, because the compressor can spread the luma error amoung all three channels (i.e. it can generate blocks
// with some chroma present if doing so will ultimately lead to lower luma error).
// Only enable on grayscale source images.
// Default: Not set.
cCRNCompFlagGrayscaleSampling = 256,
// If enabled, debug information will be output during compression.
// Default: Not set.
cCRNCompFlagDebugging = 0x80000000,
cCRNCompFlagForceDWORD = 0xFFFFFFFF
};
// Controls DXTn quality vs. speed control - only used when compressing to .DDS.
enum crn_dxt_quality
{
cCRNDXTQualitySuperFast,
cCRNDXTQualityFast,
cCRNDXTQualityNormal,
cCRNDXTQualityBetter,
cCRNDXTQualityUber,
cCRNDXTQualityTotal,
cCRNDXTQualityForceDWORD = 0xFFFFFFFF
};
// Which DXTn compressor to use when compressing to plain (non-clustered) .DDS.
enum crn_dxt_compressor_type
{
cCRNDXTCompressorCRN, // Use crnlib's ETC1 or DXTc block compressor (default, highest quality, comparable or better than ati_compress or squish, and crnlib's ETC1 is a lot fasterw with similiar quality to Erricson's)
cCRNDXTCompressorCRNF, // Use crnlib's "fast" DXTc block compressor
cCRNDXTCompressorRYG, // Use RYG's DXTc block compressor (low quality, but very fast)
#if CRNLIB_SUPPORT_ATI_COMPRESS
cCRNDXTCompressorATI,
#endif
#if CRNLIB_SUPPORT_SQUISH
cCRNDXTCompressorSquish,
#endif
cCRNTotalDXTCompressors,
cCRNDXTCompressorForceDWORD = 0xFFFFFFFF
};
// Progress callback function.
// Processing will stop prematurely (and fail) if the callback returns false.
// phase_index, total_phases - high level progress
// subphase_index, total_subphases - progress within current phase
typedef crn_bool (*crn_progress_callback_func)(crn_uint32 phase_index, crn_uint32 total_phases, crn_uint32 subphase_index, crn_uint32 total_subphases, void* pUser_data_ptr);
// CRN/DDS compression parameters struct.
struct crn_comp_params
{
inline crn_comp_params() { clear(); }
// Clear struct to default parameters.
inline void clear()
{
m_size_of_obj = sizeof(*this);
m_file_type = cCRNFileTypeCRN;
m_faces = 1;
m_width = 0;
m_height = 0;
m_levels = 1;
m_format = cCRNFmtDXT1;
m_flags = cCRNCompFlagPerceptual | cCRNCompFlagHierarchical | cCRNCompFlagUseBothBlockTypes;
for (crn_uint32 f = 0; f < cCRNMaxFaces; f++)
for (crn_uint32 l = 0; l < cCRNMaxLevels; l++)
m_pImages[f][l] = NULL;
m_target_bitrate = 0.0f;
m_quality_level = cCRNMaxQualityLevel;
m_dxt1a_alpha_threshold = 128;
m_dxt_quality = cCRNDXTQualityUber;
m_dxt_compressor_type = cCRNDXTCompressorCRN;
m_alpha_component = 3;
m_crn_adaptive_tile_color_psnr_derating = 2.0f;
m_crn_adaptive_tile_alpha_psnr_derating = 2.0f;
m_crn_color_endpoint_palette_size = 0;
m_crn_color_selector_palette_size = 0;
m_crn_alpha_endpoint_palette_size = 0;
m_crn_alpha_selector_palette_size = 0;
m_num_helper_threads = 0;
m_userdata0 = 0;
m_userdata1 = 0;
m_pProgress_func = NULL;
m_pProgress_func_data = NULL;
}
inline bool operator== (const crn_comp_params& rhs) const
{
#define CRNLIB_COMP(x) do { if ((x) != (rhs.x)) return false; } while(0)
CRNLIB_COMP(m_size_of_obj);
CRNLIB_COMP(m_file_type);
CRNLIB_COMP(m_faces);
CRNLIB_COMP(m_width);
CRNLIB_COMP(m_height);
CRNLIB_COMP(m_levels);
CRNLIB_COMP(m_format);
CRNLIB_COMP(m_flags);
CRNLIB_COMP(m_target_bitrate);
CRNLIB_COMP(m_quality_level);
CRNLIB_COMP(m_dxt1a_alpha_threshold);
CRNLIB_COMP(m_dxt_quality);
CRNLIB_COMP(m_dxt_compressor_type);
CRNLIB_COMP(m_alpha_component);
CRNLIB_COMP(m_crn_adaptive_tile_color_psnr_derating);
CRNLIB_COMP(m_crn_adaptive_tile_alpha_psnr_derating);
CRNLIB_COMP(m_crn_color_endpoint_palette_size);
CRNLIB_COMP(m_crn_color_selector_palette_size);
CRNLIB_COMP(m_crn_alpha_endpoint_palette_size);
CRNLIB_COMP(m_crn_alpha_selector_palette_size);
CRNLIB_COMP(m_num_helper_threads);
CRNLIB_COMP(m_userdata0);
CRNLIB_COMP(m_userdata1);
CRNLIB_COMP(m_pProgress_func);
CRNLIB_COMP(m_pProgress_func_data);
for (crn_uint32 f = 0; f < cCRNMaxFaces; f++)
for (crn_uint32 l = 0; l < cCRNMaxLevels; l++)
CRNLIB_COMP(m_pImages[f][l]);
#undef CRNLIB_COMP
return true;
}
// Returns true if the input parameters are reasonable.
inline bool check() const
{
if ( (m_file_type > cCRNFileTypeDDS) ||
(((int)m_quality_level < (int)cCRNMinQualityLevel) || ((int)m_quality_level > (int)cCRNMaxQualityLevel)) ||
(m_dxt1a_alpha_threshold > 255) ||
((m_faces != 1) && (m_faces != 6)) ||
((m_width < 1) || (m_width > cCRNMaxLevelResolution)) ||
((m_height < 1) || (m_height > cCRNMaxLevelResolution)) ||
((m_levels < 1) || (m_levels > cCRNMaxLevels)) ||
((m_format < cCRNFmtDXT1) || (m_format >= cCRNFmtTotal)) ||
((m_crn_color_endpoint_palette_size) && ((m_crn_color_endpoint_palette_size < cCRNMinPaletteSize) || (m_crn_color_endpoint_palette_size > cCRNMaxPaletteSize))) ||
((m_crn_color_selector_palette_size) && ((m_crn_color_selector_palette_size < cCRNMinPaletteSize) || (m_crn_color_selector_palette_size > cCRNMaxPaletteSize))) ||
((m_crn_alpha_endpoint_palette_size) && ((m_crn_alpha_endpoint_palette_size < cCRNMinPaletteSize) || (m_crn_alpha_endpoint_palette_size > cCRNMaxPaletteSize))) ||
((m_crn_alpha_selector_palette_size) && ((m_crn_alpha_selector_palette_size < cCRNMinPaletteSize) || (m_crn_alpha_selector_palette_size > cCRNMaxPaletteSize))) ||
(m_alpha_component > 3) ||
(m_num_helper_threads > cCRNMaxHelperThreads) ||
(m_dxt_quality > cCRNDXTQualityUber) ||
(m_dxt_compressor_type >= cCRNTotalDXTCompressors) )
{
return false;
}
return true;
}
// Helper to set/get flags from m_flags member.
inline bool get_flag(crn_comp_flags flag) const { return (m_flags & flag) != 0; }
inline void set_flag(crn_comp_flags flag, bool val) { m_flags &= ~flag; if (val) m_flags |= flag; }
crn_uint32 m_size_of_obj;
crn_file_type m_file_type; // Output file type: cCRNFileTypeCRN or cCRNFileTypeDDS.
crn_uint32 m_faces; // 1 (2D map) or 6 (cubemap)
crn_uint32 m_width; // [1,cCRNMaxLevelResolution], non-power of 2 OK, non-square OK
crn_uint32 m_height; // [1,cCRNMaxLevelResolution], non-power of 2 OK, non-square OK
crn_uint32 m_levels; // [1,cCRNMaxLevelResolution], non-power of 2 OK, non-square OK
crn_format m_format; // Output pixel format.
crn_uint32 m_flags; // see crn_comp_flags enum
// Array of pointers to 32bpp input images.
const crn_uint32* m_pImages[cCRNMaxFaces][cCRNMaxLevels];
// Target bitrate - if non-zero, the compressor will use an interpolative search to find the
// highest quality level that is <= the target bitrate. If it fails to find a bitrate high enough, it'll
// try disabling adaptive block sizes (cCRNCompFlagHierarchical flag) and redo the search. This process can be pretty slow.
float m_target_bitrate;
// Desired quality level.
// Currently, CRN and DDS quality levels are not compatible with eachother from an image quality standpoint.
crn_uint32 m_quality_level; // [cCRNMinQualityLevel, cCRNMaxQualityLevel]
// DXTn compression parameters.
crn_uint32 m_dxt1a_alpha_threshold;
crn_dxt_quality m_dxt_quality;
crn_dxt_compressor_type m_dxt_compressor_type;
// Alpha channel's component. Defaults to 3.
crn_uint32 m_alpha_component;
// Various low-level CRN specific parameters.
float m_crn_adaptive_tile_color_psnr_derating;
float m_crn_adaptive_tile_alpha_psnr_derating;
crn_uint32 m_crn_color_endpoint_palette_size; // [cCRNMinPaletteSize,cCRNMaxPaletteSize]
crn_uint32 m_crn_color_selector_palette_size; // [cCRNMinPaletteSize,cCRNMaxPaletteSize]
crn_uint32 m_crn_alpha_endpoint_palette_size; // [cCRNMinPaletteSize,cCRNMaxPaletteSize]
crn_uint32 m_crn_alpha_selector_palette_size; // [cCRNMinPaletteSize,cCRNMaxPaletteSize]
// Number of helper threads to create during compression. 0=no threading.
crn_uint32 m_num_helper_threads;
// CRN userdata0 and userdata1 members, which are written directly to the header of the output file.
crn_uint32 m_userdata0;
crn_uint32 m_userdata1;
// User provided progress callback.
crn_progress_callback_func m_pProgress_func;
void* m_pProgress_func_data;
};
// Mipmap generator's mode.
enum crn_mip_mode
{
cCRNMipModeUseSourceOrGenerateMips, // Use source texture's mipmaps if it has any, otherwise generate new mipmaps
cCRNMipModeUseSourceMips, // Use source texture's mipmaps if it has any, otherwise the output has no mipmaps
cCRNMipModeGenerateMips, // Always generate new mipmaps
cCRNMipModeNoMips, // Output texture has no mipmaps
cCRNMipModeTotal,
cCRNModeForceDWORD = 0xFFFFFFFF
};
const char* crn_get_mip_mode_desc(crn_mip_mode m);
const char* crn_get_mip_mode_name(crn_mip_mode m);
// Mipmap generator's filter kernel.
enum crn_mip_filter
{
cCRNMipFilterBox,
cCRNMipFilterTent,
cCRNMipFilterLanczos4,
cCRNMipFilterMitchell,
cCRNMipFilterKaiser, // Kaiser=default mipmap filter
cCRNMipFilterTotal,
cCRNMipFilterForceDWORD = 0xFFFFFFFF
};
const char* crn_get_mip_filter_name(crn_mip_filter f);
// Mipmap generator's scale mode.
enum crn_scale_mode
{
cCRNSMDisabled,
cCRNSMAbsolute,
cCRNSMRelative,
cCRNSMLowerPow2,
cCRNSMNearestPow2,
cCRNSMNextPow2,
cCRNSMTotal,
cCRNSMForceDWORD = 0xFFFFFFFF
};
const char* crn_get_scale_mode_desc(crn_scale_mode sm);
// Mipmap generator parameters.
struct crn_mipmap_params
{
inline crn_mipmap_params() { clear(); }
inline void clear()
{
m_size_of_obj = sizeof(*this);
m_mode = cCRNMipModeUseSourceOrGenerateMips;
m_filter = cCRNMipFilterKaiser;
m_gamma_filtering = true;
m_gamma = 2.2f;
// Default "blurriness" factor of .9 actually sharpens the output a little.
m_blurriness = .9f;
m_renormalize = false;
m_tiled = false;
m_max_levels = cCRNMaxLevels;
m_min_mip_size = 1;
m_scale_mode = cCRNSMDisabled;
m_scale_x = 1.0f;
m_scale_y = 1.0f;
m_window_left = 0;
m_window_top = 0;
m_window_right = 0;
m_window_bottom = 0;
m_clamp_scale = false;
m_clamp_width = 0;
m_clamp_height = 0;
}
inline bool check() const { return true; }
inline bool operator== (const crn_mipmap_params& rhs) const
{
#define CRNLIB_COMP(x) do { if ((x) != (rhs.x)) return false; } while(0)
CRNLIB_COMP(m_size_of_obj);
CRNLIB_COMP(m_mode);
CRNLIB_COMP(m_filter);
CRNLIB_COMP(m_gamma_filtering);
CRNLIB_COMP(m_gamma);
CRNLIB_COMP(m_blurriness);
CRNLIB_COMP(m_renormalize);
CRNLIB_COMP(m_tiled);
CRNLIB_COMP(m_max_levels);
CRNLIB_COMP(m_min_mip_size);
CRNLIB_COMP(m_scale_mode);
CRNLIB_COMP(m_scale_x);
CRNLIB_COMP(m_scale_y);
CRNLIB_COMP(m_window_left);
CRNLIB_COMP(m_window_top);
CRNLIB_COMP(m_window_right);
CRNLIB_COMP(m_window_bottom);
CRNLIB_COMP(m_clamp_scale);
CRNLIB_COMP(m_clamp_width);
CRNLIB_COMP(m_clamp_height);
return true;
#undef CRNLIB_COMP
}
crn_uint32 m_size_of_obj;
crn_mip_mode m_mode;
crn_mip_filter m_filter;
crn_bool m_gamma_filtering;
float m_gamma;
float m_blurriness;
crn_uint32 m_max_levels;
crn_uint32 m_min_mip_size;
crn_bool m_renormalize;
crn_bool m_tiled;
crn_scale_mode m_scale_mode;
float m_scale_x;
float m_scale_y;
crn_uint32 m_window_left;
crn_uint32 m_window_top;
crn_uint32 m_window_right;
crn_uint32 m_window_bottom;
crn_bool m_clamp_scale;
crn_uint32 m_clamp_width;
crn_uint32 m_clamp_height;
};
// -------- High-level helper function definitions for CDN/DDS compression.
#ifndef CRNLIB_MIN_ALLOC_ALIGNMENT
#define CRNLIB_MIN_ALLOC_ALIGNMENT sizeof(size_t) * 2
#endif
// Function to set an optional user provided memory allocation/reallocation/msize routines.
// By default, crnlib just uses malloc(), free(), etc. for all allocations.
typedef void* (*crn_realloc_func)(void* p, size_t size, size_t* pActual_size, bool movable, void* pUser_data);
typedef size_t (*crn_msize_func)(void* p, void* pUser_data);
void crn_set_memory_callbacks(crn_realloc_func pRealloc, crn_msize_func pMSize, void* pUser_data);
// Frees memory blocks allocated by crn_compress(), crn_decompress_crn_to_dds(), or crn_decompress_dds_to_images().
void crn_free_block(void *pBlock);
// Compresses a 32-bit/pixel texture to either: a regular DX9 DDS file, a "clustered" (or reduced entropy) DX9 DDS file, or a CRN file in memory.
// Input parameters:
// comp_params is the compression parameters struct, defined above.
// compressed_size will be set to the size of the returned memory block containing the output file.
// The returned block must be freed by calling crn_free_block().
// *pActual_quality_level will be set to the actual quality level used to compress the image. May be NULL.
// *pActual_bitrate will be set to the output file's effective bitrate, possibly taking into account LZMA compression. May be NULL.
// Return value:
// The compressed file data, or NULL on failure.
// compressed_size will be set to the size of the returned memory buffer.
// Notes:
// A "regular" DDS file is compressed using normal DXTn compression at the specified DXT quality level.
// A "clustered" DDS file is compressed using clustered DXTn compression to either the target bitrate or the specified integer quality factor.
// The output file is a standard DX9 format DDS file, except the compressor assumes you will be later losslessly compressing the DDS output file using the LZMA algorithm.
// A texture is defined as an array of 1 or 6 "faces" (6 faces=cubemap), where each "face" consists of between [1,cCRNMaxLevels] mipmap levels.
// Mipmap levels are simple 32-bit 2D images with a pitch of width*sizeof(uint32), arranged in the usual raster order (top scanline first).
// The image pixels may be grayscale (YYYX bytes in memory), grayscale/alpha (YYYA in memory), 24-bit (RGBX in memory), or 32-bit (RGBA) colors (where "X"=don't care).
// RGB color data is generally assumed to be in the sRGB colorspace. If not, be sure to clear the "cCRNCompFlagPerceptual" in the crn_comp_params struct!
void *crn_compress(const crn_comp_params &comp_params, crn_uint32 &compressed_size, crn_uint32 *pActual_quality_level = NULL, float *pActual_bitrate = NULL);
// Like the above function, except this function can also do things like generate mipmaps, and resize or crop the input texture before compression.
// The actual operations performed are controlled by the crn_mipmap_params struct members.
// Be sure to set the "m_gamma_filtering" member of crn_mipmap_params to false if the input texture is not sRGB.
void *crn_compress(const crn_comp_params &comp_params, const crn_mipmap_params &mip_params, crn_uint32 &compressed_size, crn_uint32 *pActual_quality_level = NULL, float *pActual_bitrate = NULL);
// Transcodes an entire CRN file to DDS using the crn_decomp.h header file library to do most of the heavy lifting.
// The output DDS file's format is guaranteed to be one of the DXTn formats in the crn_format enum.
// This is a fast operation, because the CRN format is explicitly designed to be efficiently transcodable to DXTn.
// For more control over decompression, see the lower-level helper functions in crn_decomp.h, which do not depend at all on crnlib.
void *crn_decompress_crn_to_dds(const void *pCRN_file_data, crn_uint32 &file_size);
// Decompresses an entire DDS file in any supported format to uncompressed 32-bit/pixel image(s).
// See the crnlib::pixel_format enum in inc/dds_defs.h for a list of the supported DDS formats.
// You are responsible for freeing each image block, either by calling crn_free_all_images() or manually calling crn_free_block() on each image pointer.
struct crn_texture_desc
{
crn_uint32 m_faces;
crn_uint32 m_width;
crn_uint32 m_height;
crn_uint32 m_levels;
crn_uint32 m_fmt_fourcc; // Same as crnlib::pixel_format
};
bool crn_decompress_dds_to_images(const void *pDDS_file_data, crn_uint32 dds_file_size, crn_uint32 **ppImages, crn_texture_desc &tex_desc);
// Frees all images allocated by crn_decompress_dds_to_images().
void crn_free_all_images(crn_uint32 **ppImages, const crn_texture_desc &desc);
// -------- crn_format related helpers functions.
// Returns the FOURCC format equivalent to the specified crn_format.
crn_uint32 crn_get_format_fourcc(crn_format fmt);
// Returns the crn_format's bits per texel.
crn_uint32 crn_get_format_bits_per_texel(crn_format fmt);
// Returns the crn_format's number of bytes per block.
crn_uint32 crn_get_bytes_per_dxt_block(crn_format fmt);
// Returns the non-swizzled, basic DXTn version of the specified crn_format.
// This is the format you would supply D3D or OpenGL.
crn_format crn_get_fundamental_dxt_format(crn_format fmt);
// -------- String helpers.
// Converts a crn_file_type to a string.
const char* crn_get_file_type_ext(crn_file_type file_type);
// Converts a crn_format to a string.
const char* crn_get_format_string(crn_format fmt);
// Converts a crn_dxt_quality to a string.
const char* crn_get_dxt_quality_string(crn_dxt_quality q);
// -------- Low-level DXTn 4x4 block compressor API
// crnlib's DXTn endpoint optimizer actually supports any number of source pixels (i.e. from 1 to thousands, not just 16),
// but for simplicity this API only supports 4x4 texel blocks.
typedef void *crn_block_compressor_context_t;
// Create a DXTn block compressor.
// This function only supports the basic/nonswizzled "fundamental" formats: DXT1, DXT3, DXT5, DXT5A, DXN_XY and DXN_YX.
// Avoid calling this multiple times if you intend on compressing many blocks, because it allocates some memory.
crn_block_compressor_context_t crn_create_block_compressor(const crn_comp_params ¶ms);
// Compresses a block of 16 pixels to the destination DXTn block.
// pDst_block should be 8 (for DXT1/DXT5A) or 16 bytes (all the others).
// pPixels should be an array of 16 crn_uint32's. Each crn_uint32 must be r,g,b,a (r is always first) in memory.
void crn_compress_block(crn_block_compressor_context_t pContext, const crn_uint32 *pPixels, void *pDst_block);
// Frees a DXTn block compressor.
void crn_free_block_compressor(crn_block_compressor_context_t pContext);
// Unpacks a compressed block to pDst_pixels.
// pSrc_block should be 8 (for DXT1/DXT5A) or 16 bytes (all the others).
// pDst_pixel should be an array of 16 crn_uint32's. Each uint32 will be r,g,b,a (r is always first) in memory.
// crn_fmt should be one of the "fundamental" formats: DXT1, DXT3, DXT5, DXT5A, DXN_XY and DXN_YX.
// The various swizzled DXT5 formats (such as cCRNFmtDXT5_xGBR, etc.) will be unpacked as if they where plain DXT5.
// Returns false if the crn_fmt is invalid.
bool crn_decompress_block(const void *pSrc_block, crn_uint32 *pDst_pixels, crn_format crn_fmt);
#endif // CRNLIB_H
//------------------------------------------------------------------------------
//
// crunch/crnlib uses a modified ZLIB license. Specifically, it's the same as zlib except that
// public credits for using the library are *required*.
//
// Copyright (c) 2010-2016 Richard Geldreich, Jr. All rights reserved.
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software.
//
// 2. If you use this software in a product, this acknowledgment in the product
// documentation or credits is required:
//
// "Crunch Library Copyright (c) 2010-2016 Richard Geldreich, Jr."
//
// 3. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 4. This notice may not be removed or altered from any source distribution.
//
//------------------------------------------------------------------------------
| AssetStudio/Texture2DDecoderNative/crunch/crnlib.h/0 | {
"file_path": "AssetStudio/Texture2DDecoderNative/crunch/crnlib.h",
"repo_id": "AssetStudio",
"token_count": 10389
} | 85 |
<Project>
<PropertyGroup>
<LangVersion>11.0</LangVersion>
<NoWarn>0169,0649,3021,8981</NoWarn>
</PropertyGroup>
</Project> | ET/DotNet/Directory.Build.props/0 | {
"file_path": "ET/DotNet/Directory.Build.props",
"repo_id": "ET",
"token_count": 62
} | 86 |
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace ET.Analyzer
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class EntityMethodDeclarationAnalyzer : DiagnosticAnalyzer
{
private const string Title = "实体类禁止声明方法";
private const string MessageFormat = "实体类: {0} 不能在类内部声明方法: {1}";
private const string Description = "实体类禁止声明方法.";
private static readonly DiagnosticDescriptor Rule =
new DiagnosticDescriptor(DiagnosticIds.EntityMethodDeclarationAnalyzerRuleId,
Title,
MessageFormat,
DiagnosticCategories.Hotfix,
DiagnosticSeverity.Error,
true,
Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
if (!AnalyzerGlobalSetting.EnableAnalyzer)
{
return;
}
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterCompilationStartAction((analysisContext =>
{
if (AnalyzerHelper.IsAssemblyNeedAnalyze(analysisContext.Compilation.AssemblyName,AnalyzeAssembly.AllModel))
{
analysisContext.RegisterSemanticModelAction((this.AnalyzeSemanticModel));
}
} ));
}
private void AnalyzeSemanticModel(SemanticModelAnalysisContext analysisContext)
{
foreach (var classDeclarationSyntax in analysisContext.SemanticModel.SyntaxTree.GetRoot().DescendantNodes<ClassDeclarationSyntax>())
{
var classTypeSymbol = analysisContext.SemanticModel.GetDeclaredSymbol(classDeclarationSyntax);
if (classTypeSymbol!=null)
{
Analyzer(analysisContext, classTypeSymbol);
}
}
}
private void Analyzer(SemanticModelAnalysisContext context, INamedTypeSymbol namedTypeSymbol)
{
// 筛选出实体类
if (namedTypeSymbol.BaseType?.ToString() != Definition.EntityType && namedTypeSymbol.BaseType?.ToString() != Definition.LSEntityType)
{
return;
}
// 忽略含有EnableMethod标签的实体类
if (namedTypeSymbol.HasAttribute(Definition.EnableMethodAttribute))
{
return;
}
foreach (var syntaxReference in namedTypeSymbol.DeclaringSyntaxReferences)
{
var classSyntax = syntaxReference.GetSyntax();
if (!(classSyntax is ClassDeclarationSyntax classDeclarationSyntax))
{
return;
}
foreach (var memberDeclarationSyntax in classDeclarationSyntax.Members)
{
// 筛选出类声明语法节点下的所有方法声明语法节点
if (memberDeclarationSyntax is MethodDeclarationSyntax methodDeclarationSyntax)
{
Diagnostic diagnostic = Diagnostic.Create(Rule, methodDeclarationSyntax.GetLocation(),namedTypeSymbol.Name,methodDeclarationSyntax.Identifier.Text);
context.ReportDiagnostic(diagnostic);
}
}
}
}
}
} | ET/Share/Analyzer/Analyzer/EntityMethodDeclarationAnalyzer.cs/0 | {
"file_path": "ET/Share/Analyzer/Analyzer/EntityMethodDeclarationAnalyzer.cs",
"repo_id": "ET",
"token_count": 1867
} | 87 |
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<IncludeBuildOutput>false</IncludeBuildOutput>
<Nullable>enable</Nullable>
<LangVersion>12</LangVersion>
</PropertyGroup>
<PropertyGroup>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoWarn>1701;1702;RS2008</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoWarn>1701;1702;RS2008</NoWarn>
</PropertyGroup>
<ItemGroup>
<Compile Include="../../Unity/Assets/Scripts/Core/Helper/StringHashHelper.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.0.1" PrivateAssets="all" />
<PackageReference Update="NETStandard.Library" PrivateAssets="all" />
</ItemGroup>
</Project>
| ET/Share/Analyzer/Share.Analyzer.csproj/0 | {
"file_path": "ET/Share/Analyzer/Share.Analyzer.csproj",
"repo_id": "ET",
"token_count": 478
} | 88 |
mkdir build64 & pushd build64
cmake -G "Visual Studio 16 2019" -A x64 ..
popd
cmake --build build64 --config Release
md Plugins\x86_64
copy /Y build64\Release\RecastDll.dll Plugins\x86_64\RecastDll.dll
rmdir /S /Q build64
pause
| ET/Share/Libs/RecastDll/make_win64.bat/0 | {
"file_path": "ET/Share/Libs/RecastDll/make_win64.bat",
"repo_id": "ET",
"token_count": 89
} | 89 |
# ET8-Luban
基于ET8.1集成了功能更完善的Luban(新版)配置工具,导出时支持自定义数据校验,为上线项目配置的数据安全提供了足够的保障。
**使用方式**:点击'ET-BuildTool-ExcelExporter',实际开发时建议自行扩展成按快捷键调用ToolsEditor.ExcelExporter()
**项目链接**:[ET8-Luban](https://github.com/EP-Toushirou/ET8-Luban) | ET/Store/LubanExtension.md/0 | {
"file_path": "ET/Store/LubanExtension.md",
"repo_id": "ET",
"token_count": 261
} | 90 |
fileFormatVersion: 2
guid: 3f452063ceb5f4150bbbfe795c0aca90
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Bundles/Config/UnitConfigCategory.bytes.meta/0 | {
"file_path": "ET/Unity/Assets/Bundles/Config/UnitConfigCategory.bytes.meta",
"repo_id": "ET",
"token_count": 65
} | 91 |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!29 &1
OcclusionCullingSettings:
m_ObjectHideFlags: 0
serializedVersion: 2
m_OcclusionBakeSettings:
smallestOccluder: 5
smallestHole: 0.25
backfaceThreshold: 100
m_SceneGUID: 00000000000000000000000000000000
m_OcclusionCullingData: {fileID: 0}
--- !u!104 &2
RenderSettings:
m_ObjectHideFlags: 0
serializedVersion: 9
m_Fog: 0
m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1}
m_FogMode: 3
m_FogDensity: 0.01
m_LinearFogStart: 0
m_LinearFogEnd: 300
m_AmbientSkyColor: {r: 0.6303525, g: 0.78416735, b: 0.9632353, a: 1}
m_AmbientEquatorColor: {r: 0.37802768, g: 0.49123016, b: 0.6764706, a: 1}
m_AmbientGroundColor: {r: 0.25373137, g: 0.25373137, b: 0.25373137, a: 1}
m_AmbientIntensity: 0.6
m_AmbientMode: 0
m_SubtractiveShadowColor: {r: 0, g: 0, b: 0, a: 1}
m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0}
m_HaloStrength: 0.5
m_FlareStrength: 1
m_FlareFadeSpeed: 3
m_HaloTexture: {fileID: 0}
m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0}
m_DefaultReflectionMode: 0
m_DefaultReflectionResolution: 128
m_ReflectionBounces: 1
m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 818345482}
m_IndirectSpecularColor: {r: 0.44294906, g: 0.4921276, b: 0.5718681, a: 1}
m_UseRadianceAmbientProbe: 0
--- !u!157 &4
LightmapSettings:
m_ObjectHideFlags: 0
serializedVersion: 12
m_GIWorkflowMode: 1
m_GISettings:
serializedVersion: 2
m_BounceScale: 1
m_IndirectOutputScale: 1
m_AlbedoBoost: 1
m_EnvironmentLightingMode: 0
m_EnableBakedLightmaps: 1
m_EnableRealtimeLightmaps: 0
m_LightmapEditorSettings:
serializedVersion: 12
m_Resolution: 1
m_BakeResolution: 10
m_AtlasSize: 1024
m_AO: 0
m_AOMaxDistance: 1
m_CompAOExponent: 0
m_CompAOExponentDirect: 0
m_ExtractAmbientOcclusion: 0
m_Padding: 2
m_LightmapParameters: {fileID: 0}
m_LightmapsBakeMode: 0
m_TextureCompression: 0
m_FinalGather: 0
m_FinalGatherFiltering: 1
m_FinalGatherRayCount: 1024
m_ReflectionCompression: 2
m_MixedBakeMode: 0
m_BakeBackend: 0
m_PVRSampling: 1
m_PVRDirectSampleCount: 32
m_PVRSampleCount: 500
m_PVRBounces: 2
m_PVREnvironmentSampleCount: 500
m_PVREnvironmentReferencePointCount: 2048
m_PVRFilteringMode: 0
m_PVRDenoiserTypeDirect: 0
m_PVRDenoiserTypeIndirect: 0
m_PVRDenoiserTypeAO: 0
m_PVRFilterTypeDirect: 0
m_PVRFilterTypeIndirect: 0
m_PVRFilterTypeAO: 0
m_PVREnvironmentMIS: 0
m_PVRCulling: 1
m_PVRFilteringGaussRadiusDirect: 1
m_PVRFilteringGaussRadiusIndirect: 5
m_PVRFilteringGaussRadiusAO: 2
m_PVRFilteringAtrousPositionSigmaDirect: 0.5
m_PVRFilteringAtrousPositionSigmaIndirect: 2
m_PVRFilteringAtrousPositionSigmaAO: 1
m_ExportTrainingData: 0
m_TrainingDataDestination: TrainingData
m_LightProbeSampleCountMultiplier: 4
m_LightingDataAsset: {fileID: 112000000, guid: e7b86a45dc154ae40a2f51144799b7bf,
type: 2}
m_LightingSettings: {fileID: 4890085278179872738, guid: c78b5af2c87902e4aba73014819bd1a7,
type: 2}
--- !u!1 &15
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 129}
- component: {fileID: 341}
- component: {fileID: 433}
- component: {fileID: 242}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &28
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 142}
- component: {fileID: 354}
- component: {fileID: 446}
- component: {fileID: 255}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &29
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 143}
- component: {fileID: 355}
- component: {fileID: 447}
- component: {fileID: 256}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &30
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 144}
- component: {fileID: 356}
- component: {fileID: 448}
- component: {fileID: 257}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &31
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 145}
- component: {fileID: 357}
- component: {fileID: 449}
- component: {fileID: 258}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &32
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 146}
- component: {fileID: 358}
- component: {fileID: 450}
- component: {fileID: 259}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &33
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 147}
- component: {fileID: 359}
- component: {fileID: 451}
- component: {fileID: 260}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &34
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 148}
- component: {fileID: 360}
- component: {fileID: 452}
- component: {fileID: 261}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &35
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 149}
- component: {fileID: 361}
- component: {fileID: 453}
- component: {fileID: 262}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &36
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 150}
- component: {fileID: 362}
- component: {fileID: 454}
- component: {fileID: 263}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &37
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 151}
- component: {fileID: 363}
- component: {fileID: 455}
- component: {fileID: 264}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &38
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 152}
- component: {fileID: 364}
- component: {fileID: 456}
- component: {fileID: 265}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &39
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 153}
- component: {fileID: 365}
- component: {fileID: 457}
- component: {fileID: 266}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &40
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 154}
- component: {fileID: 366}
- component: {fileID: 458}
- component: {fileID: 267}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &41
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 155}
- component: {fileID: 367}
- component: {fileID: 459}
- component: {fileID: 268}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &42
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 156}
- component: {fileID: 368}
- component: {fileID: 460}
- component: {fileID: 269}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &43
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 157}
- component: {fileID: 369}
- component: {fileID: 461}
- component: {fileID: 270}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &44
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 158}
- component: {fileID: 370}
- component: {fileID: 462}
- component: {fileID: 271}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &45
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 159}
m_Layer: 8
m_Name: Obstacles
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &46
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 160}
m_Layer: 8
m_Name: Some Cubes
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &50
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 164}
- component: {fileID: 374}
- component: {fileID: 466}
- component: {fileID: 275}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &52
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 166}
- component: {fileID: 376}
- component: {fileID: 468}
- component: {fileID: 277}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &53
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 167}
- component: {fileID: 377}
- component: {fileID: 469}
- component: {fileID: 278}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &89
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 203}
- component: {fileID: 413}
- component: {fileID: 505}
- component: {fileID: 314}
m_Layer: 8
m_Name: Cube
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!1 &108
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 222}
- component: {fileID: 234}
- component: {fileID: 525}
- component: {fileID: 508}
- component: {fileID: 110}
m_Layer: 0
m_Name: Main Camera
m_TagString: MainCamera
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 0
--- !u!1 &109
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 223}
- component: {fileID: 424}
- component: {fileID: 327}
- component: {fileID: 506}
m_Layer: 8
m_Name: Ground
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!114 &110
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 108}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: a79441f348de89743a2939f4d699eac1, type: 3}
m_Name:
m_EditorClassIdentifier:
m_RenderShadows: 1
m_RequiresDepthTextureOption: 2
m_RequiresOpaqueTextureOption: 2
m_CameraType: 0
m_Cameras: []
m_RendererIndex: -1
m_VolumeLayerMask:
serializedVersion: 2
m_Bits: 1
m_VolumeTrigger: {fileID: 0}
m_VolumeFrameworkUpdateModeOption: 2
m_RenderPostProcessing: 0
m_Antialiasing: 0
m_AntialiasingQuality: 2
m_StopNaN: 0
m_Dithering: 0
m_ClearDepth: 1
m_AllowXRRendering: 1
m_RequiresDepthTexture: 0
m_RequiresColorTexture: 0
m_Version: 2
--- !u!4 &129
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 15}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 25.79195, y: 30.101498, z: -21.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &142
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 28}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 11.79195, y: 30.101498, z: -38.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 12
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &143
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 29}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 11.79195, y: 30.101498, z: -41.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &144
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 30}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 14.79195, y: 30.101498, z: -41.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 13
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &145
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 31}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 17.79195, y: 30.101498, z: -41.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 14
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &146
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 32}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 20.79195, y: 30.101498, z: -41.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 15
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &147
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 33}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 17.79195, y: 30.101498, z: -44.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &148
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 34}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 14.79195, y: 30.101498, z: -45.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 8
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &149
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 35}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 14.79195, y: 30.101498, z: -48.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 10
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &150
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 36}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 17.79195, y: 30.101498, z: -48.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 4
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &151
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 37}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 20.79195, y: 30.101498, z: -48.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &152
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 38}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 26.79195, y: 30.101498, z: -48.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 7
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &153
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 39}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 26.79195, y: 30.101498, z: -45.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 11
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &154
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 40}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 26.79195, y: 30.101498, z: -42.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 16
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &155
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 41}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 29.79195, y: 30.101498, z: -42.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 6
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &156
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 42}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 32.79195, y: 30.101498, z: -42.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 9
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &157
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 43}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 32.79195, y: 30.101498, z: -48.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 5
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &158
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 44}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 29.79195, y: 30.101498, z: -48.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 17
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &159
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 45}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: -7.79195, y: -29.101498, z: 21.93608}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 160}
m_Father: {fileID: 517080817}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &160
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 46}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: -0.5, y: 0, z: -0.5}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 129}
- {fileID: 143}
- {fileID: 147}
- {fileID: 151}
- {fileID: 150}
- {fileID: 157}
- {fileID: 155}
- {fileID: 152}
- {fileID: 148}
- {fileID: 156}
- {fileID: 149}
- {fileID: 153}
- {fileID: 142}
- {fileID: 144}
- {fileID: 145}
- {fileID: 146}
- {fileID: 154}
- {fileID: 158}
- {fileID: 203}
- {fileID: 164}
- {fileID: 166}
- {fileID: 167}
m_Father: {fileID: 159}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &164
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 50}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 16.79195, y: 30.101498, z: -32.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 19
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &166
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 52}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 4.79195, y: 30.101498, z: -32.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 20
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &167
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 53}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 1.7919502, y: 30.101498, z: -32.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 21
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &203
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 89}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 17.79195, y: 30.397146, z: -45.93608}
m_LocalScale: {x: 3, y: 2, z: 3}
m_Children: []
m_Father: {fileID: 160}
m_RootOrder: 18
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &222
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 108}
m_LocalRotation: {x: 0.48865515, y: 0, z: 0, w: 0.87247705}
m_LocalPosition: {x: 2.1579952, y: 35.460117, z: -32.150215}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!4 &223
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 109}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 10, y: 10, z: 10}
m_Children: []
m_Father: {fileID: 517080817}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!20 &234
Camera:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 108}
m_Enabled: 1
serializedVersion: 2
m_ClearFlags: 1
m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0.019607844}
m_projectionMatrixMode: 1
m_GateFitMode: 2
m_FOVAxisMode: 0
m_SensorSize: {x: 36, y: 24}
m_LensShift: {x: 0, y: 0}
m_FocalLength: 50
m_NormalizedViewPortRect:
serializedVersion: 2
x: 0
y: 0
width: 1
height: 1
near clip plane: 0.3
far clip plane: 1000
field of view: 60
orthographic: 0
orthographic size: 100
m_Depth: -1
m_CullingMask:
serializedVersion: 2
m_Bits: 279
m_RenderingPath: -1
m_TargetTexture: {fileID: 0}
m_TargetDisplay: 0
m_TargetEye: 3
m_HDR: 0
m_AllowMSAA: 0
m_AllowDynamicResolution: 0
m_ForceIntoRT: 0
m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
--- !u!23 &242
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 15}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &255
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 28}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &256
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 29}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &257
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 30}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &258
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 31}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &259
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 32}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &260
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 33}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &261
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 34}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &262
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 35}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &263
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 36}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &264
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 37}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &265
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 38}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &266
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 39}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &267
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 40}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &268
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 41}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &269
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 42}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &270
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 43}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &271
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 44}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &275
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 50}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &277
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 52}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &278
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 53}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &314
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 89}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!23 &327
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 109}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_MotionVectors: 1
m_LightProbeUsage: 0
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 6d5adfb995cb79c438d8b1e6b5e5de91, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 0.5
m_ReceiveGI: 1
m_PreserveUVs: 0
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 0
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!33 &341
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 15}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &354
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 28}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &355
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 29}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &356
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 30}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &357
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 31}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &358
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 32}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &359
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 33}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &360
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 34}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &361
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 35}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &362
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 36}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &363
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 37}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &364
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 38}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &365
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 39}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &366
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 40}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &367
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 41}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &368
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 42}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &369
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 43}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &370
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 44}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &374
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 50}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &376
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 52}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &377
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 53}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &413
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 89}
m_Mesh: {fileID: 10202, guid: 0000000000000000e000000000000000, type: 0}
--- !u!33 &424
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 109}
m_Mesh: {fileID: 10209, guid: 0000000000000000e000000000000000, type: 0}
--- !u!65 &433
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 15}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &446
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 28}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &447
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 29}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &448
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 30}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &449
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 31}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &450
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 32}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &451
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 33}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &452
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 34}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &453
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 35}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &454
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 36}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &455
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 37}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &456
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 38}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &457
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 39}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &458
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 40}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &459
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 41}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &460
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 42}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &461
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 43}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &462
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 44}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &466
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 50}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &468
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 52}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &469
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 53}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &505
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 89}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!65 &506
BoxCollider:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 109}
m_Material: {fileID: 0}
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 10, y: 0.002, z: 10}
m_Center: {x: 0, y: 0, z: 0}
--- !u!81 &508
AudioListener:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 108}
m_Enabled: 1
--- !u!124 &525
Behaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 108}
m_Enabled: 1
--- !u!196 &536
NavMeshSettings:
serializedVersion: 2
m_ObjectHideFlags: 0
m_BuildSettings:
serializedVersion: 2
agentTypeID: 0
agentRadius: 0.5
agentHeight: 2
agentSlope: 45
agentClimb: 0.4
ledgeDropHeight: 0
maxJumpAcrossDistance: 0
minRegionArea: 2
manualCellSize: 0
cellSize: 0.16666666
manualTileSize: 0
tileSize: 256
accuratePlacement: 0
maxJobWorkers: 0
preserveTilesOutsideBounds: 0
debug:
m_Flags: 0
m_NavMeshData: {fileID: 23800000, guid: ddfe2d991620b454b97694885504c548, type: 2}
--- !u!1 &517080816
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 517080817}
- component: {fileID: 517080818}
m_Layer: 8
m_Name: World
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 4294967295
m_IsActive: 1
--- !u!4 &517080817
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 517080816}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 223}
- {fileID: 159}
m_Father: {fileID: 0}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &517080818
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 517080816}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: bb6abbfdeb65e5748bed4ac86534e3a5, type: 3}
m_Name:
m_EditorClassIdentifier:
Path: []
--- !u!1 &818345480
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 818345481}
- component: {fileID: 818345482}
m_Layer: 8
m_Name: Directional Light
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &818345481
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 818345480}
m_LocalRotation: {x: 0.505348, y: 0.5564302, z: -0.6419347, w: 0.15142253}
m_LocalPosition: {x: -20.18, y: 19.19, z: 0.4}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 60.161, y: 254.857, z: 132.307}
--- !u!108 &818345482
Light:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 818345480}
m_Enabled: 1
serializedVersion: 10
m_Type: 1
m_Shape: 0
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Intensity: 1
m_Range: 10
m_SpotAngle: 30
m_InnerSpotAngle: 21.80208
m_CookieSize: 10
m_Shadows:
m_Type: 2
m_Resolution: -1
m_CustomResolution: -1
m_Strength: 0.56
m_Bias: 1.47
m_NormalBias: 1.95
m_NearPlane: 6
m_CullingMatrixOverride:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_UseCullingMatrixOverride: 0
m_Cookie: {fileID: 0}
m_DrawHalo: 0
m_Flare: {fileID: 0}
m_RenderMode: 0
m_CullingMask:
serializedVersion: 2
m_Bits: 4294967295
m_RenderingLayerMask: 1
m_Lightmapping: 2
m_LightShadowCasterMode: 0
m_AreaSize: {x: 1, y: 1}
m_BounceIntensity: 1
m_ColorTemperature: 6570
m_UseColorTemperature: 0
m_BoundingSphereOverride: {x: 0, y: 5.8034423e+16, z: 4.5904e-41, w: 1e-45}
m_UseBoundingSphereOverride: 0
m_UseViewFrustumForShadowCasterCull: 1
m_ShadowRadius: 0
m_ShadowAngle: 0
| ET/Unity/Assets/Bundles/Scenes/Map2.unity/0 | {
"file_path": "ET/Unity/Assets/Bundles/Scenes/Map2.unity",
"repo_id": "ET",
"token_count": 31400
} | 92 |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &1386170326414932
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 224438795553994780}
- component: {fileID: 1431576037130298801}
- component: {fileID: 1431576037130298803}
- component: {fileID: 114905074804487618}
m_Layer: 5
m_Name: UILobby
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &224438795553994780
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1386170326414932}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 4771239781044397799}
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0.5, y: 0.5}
m_AnchorMax: {x: 0.5, y: 0.5}
m_AnchoredPosition: {x: 0, y: 0}
m_SizeDelta: {x: 0, y: 0}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!223 &1431576037130298801
Canvas:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1386170326414932}
m_Enabled: 1
serializedVersion: 3
m_RenderMode: 1
m_Camera: {fileID: 0}
m_PlaneDistance: 100
m_PixelPerfect: 0
m_ReceivesEvents: 1
m_OverrideSorting: 0
m_OverridePixelPerfect: 0
m_SortingBucketNormalizedSize: 0
m_AdditionalShaderChannelsFlag: 0
m_SortingLayerID: 0
m_SortingOrder: 0
m_TargetDisplay: 0
--- !u!114 &1431576037130298803
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1386170326414932}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: dc42784cf147c0c48a680349fa168899, type: 3}
m_Name:
m_EditorClassIdentifier:
m_IgnoreReversedGraphics: 1
m_BlockingObjects: 0
m_BlockingMask:
serializedVersion: 2
m_Bits: 4294967295
--- !u!114 &114905074804487618
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1386170326414932}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 502d8cafd6a5a0447ab1db9a24cdcb10, type: 3}
m_Name:
m_EditorClassIdentifier:
data:
- key: EnterMap
gameObject: {fileID: 899722670427233733}
--- !u!1 &899722670427233733
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1109878335635189875}
- component: {fileID: 1111846559939914969}
- component: {fileID: 1003519326168939849}
- component: {fileID: 1003626380862230063}
m_Layer: 5
m_Name: EnterMap
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &1109878335635189875
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 899722670427233733}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 6091551359588390577}
m_Father: {fileID: 4771239781044397799}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0.5, y: 0.5}
m_AnchorMax: {x: 0.5, y: 0.5}
m_AnchoredPosition: {x: 0.000061035, y: -31.15}
m_SizeDelta: {x: 263.5, y: 62.3}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!222 &1111846559939914969
CanvasRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 899722670427233733}
m_CullTransparentMesh: 0
--- !u!114 &1003519326168939849
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 899722670427233733}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Material: {fileID: 0}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_RaycastTarget: 1
m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0}
m_Maskable: 1
m_OnCullStateChanged:
m_PersistentCalls:
m_Calls: []
m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0}
m_Type: 1
m_PreserveAspect: 0
m_FillCenter: 1
m_FillMethod: 4
m_FillAmount: 1
m_FillClockwise: 1
m_FillOrigin: 0
m_UseSpriteMesh: 0
m_PixelsPerUnitMultiplier: 1
--- !u!114 &1003626380862230063
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 899722670427233733}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 4e29b1a8efbd4b44bb3f3716e73f07ff, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Navigation:
m_Mode: 3
m_WrapAround: 0
m_SelectOnUp: {fileID: 0}
m_SelectOnDown: {fileID: 0}
m_SelectOnLeft: {fileID: 0}
m_SelectOnRight: {fileID: 0}
m_Transition: 1
m_Colors:
m_NormalColor: {r: 1, g: 1, b: 1, a: 1}
m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1}
m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1}
m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1}
m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608}
m_ColorMultiplier: 1
m_FadeDuration: 0.1
m_SpriteState:
m_HighlightedSprite: {fileID: 0}
m_PressedSprite: {fileID: 0}
m_SelectedSprite: {fileID: 0}
m_DisabledSprite: {fileID: 0}
m_AnimationTriggers:
m_NormalTrigger: Normal
m_HighlightedTrigger: Highlighted
m_PressedTrigger: Pressed
m_SelectedTrigger: Highlighted
m_DisabledTrigger: Disabled
m_Interactable: 1
m_TargetGraphic: {fileID: 1003519326168939849}
m_OnClick:
m_PersistentCalls:
m_Calls: []
--- !u!1 &3318750498554037093
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4771239781044397799}
- component: {fileID: 7279718688677780413}
- component: {fileID: 1396409096631843897}
m_Layer: 5
m_Name: Panel
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &4771239781044397799
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 3318750498554037093}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 1109878335635189875}
m_Father: {fileID: 224438795553994780}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 1, y: 1}
m_AnchoredPosition: {x: 0, y: 0}
m_SizeDelta: {x: 0, y: 0}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!222 &7279718688677780413
CanvasRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 3318750498554037093}
m_CullTransparentMesh: 0
--- !u!114 &1396409096631843897
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 3318750498554037093}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Material: {fileID: 0}
m_Color: {r: 1, g: 1, b: 1, a: 0.392}
m_RaycastTarget: 1
m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0}
m_Maskable: 1
m_OnCullStateChanged:
m_PersistentCalls:
m_Calls: []
m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0}
m_Type: 1
m_PreserveAspect: 0
m_FillCenter: 1
m_FillMethod: 4
m_FillAmount: 1
m_FillClockwise: 1
m_FillOrigin: 0
m_UseSpriteMesh: 0
m_PixelsPerUnitMultiplier: 1
--- !u!1 &6310363376444861169
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 6091551359588390577}
- component: {fileID: 6089323556358314843}
- component: {fileID: 6197011583270449923}
m_Layer: 5
m_Name: Text
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &6091551359588390577
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6310363376444861169}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 1109878335635189875}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 1, y: 1}
m_AnchoredPosition: {x: 0, y: 0}
m_SizeDelta: {x: 0, y: 0}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!222 &6089323556358314843
CanvasRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6310363376444861169}
m_CullTransparentMesh: 0
--- !u!114 &6197011583270449923
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 6310363376444861169}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Material: {fileID: 0}
m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1}
m_RaycastTarget: 1
m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0}
m_Maskable: 1
m_OnCullStateChanged:
m_PersistentCalls:
m_Calls: []
m_FontData:
m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0}
m_FontSize: 20
m_FontStyle: 0
m_BestFit: 0
m_MinSize: 2
m_MaxSize: 40
m_Alignment: 4
m_AlignByGeometry: 0
m_RichText: 1
m_HorizontalOverflow: 0
m_VerticalOverflow: 0
m_LineSpacing: 1
m_Text: "\u8FDB\u5165"
| ET/Unity/Assets/Bundles/UI/Demo/UILobby.prefab/0 | {
"file_path": "ET/Unity/Assets/Bundles/UI/Demo/UILobby.prefab",
"repo_id": "ET",
"token_count": 5101
} | 93 |
fileFormatVersion: 2
guid: 631281e989abb6c4e80106b0502d46a8
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Config/Excel/StartConfig/Localhost/StartProcessConfig@s.xlsx.meta/0 | {
"file_path": "ET/Unity/Assets/Config/Excel/StartConfig/Localhost/StartProcessConfig@s.xlsx.meta",
"repo_id": "ET",
"token_count": 64
} | 94 |
fileFormatVersion: 2
guid: 16cd92ca656d43543947a17e27d46057
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Config/Excel/StartConfig/RouterTest/StartMachineConfig@s.xlsx.meta/0 | {
"file_path": "ET/Unity/Assets/Config/Excel/StartConfig/RouterTest/StartMachineConfig@s.xlsx.meta",
"repo_id": "ET",
"token_count": 62
} | 95 |
syntax = "proto3";
package ET;
// ResponseType G2C_Match
message C2G_Match // ISessionRequest
{
int32 RpcId = 1;
}
message G2C_Match // ISessionResponse
{
int32 RpcId = 1;
int32 Error = 2;
string Message = 3;
}
/// 匹配成功,通知客户端切换场景
message Match2G_NotifyMatchSuccess // IMessage
{
int32 RpcId = 1;
/// 房间的ActorId
ActorId ActorId = 2;
}
/// 客户端通知房间切换场景完成
message C2Room_ChangeSceneFinish // IRoomMessage
{
int64 PlayerId = 1;
}
message LockStepUnitInfo
{
int64 PlayerId = 1;
TrueSync.TSVector Position = 2;
TrueSync.TSQuaternion Rotation = 3;
}
/// 房间通知客户端进入战斗
message Room2C_Start // IMessage
{
int64 StartTime = 1;
repeated LockStepUnitInfo UnitInfo = 2;
}
message FrameMessage // IMessage
{
int32 Frame = 1;
int64 PlayerId = 2;
LSInput Input = 3;
}
message OneFrameInputs // IMessage
{
map<int64, LSInput> Inputs = 2;
}
message Room2C_AdjustUpdateTime // IMessage
{
int32 DiffTime = 1;
}
message C2Room_CheckHash // IRoomMessage
{
int64 PlayerId = 1;
int32 Frame = 2;
int64 Hash = 3;
}
message Room2C_CheckHashFail // IMessage
{
int32 Frame = 1;
bytes LSWorldBytes = 2;
}
message G2C_Reconnect // IMessage
{
int64 StartTime = 1;
repeated LockStepUnitInfo UnitInfos = 2;
int32 Frame = 3;
} | ET/Unity/Assets/Config/Proto/LockStepOuter_C_11001.proto/0 | {
"file_path": "ET/Unity/Assets/Config/Proto/LockStepOuter_C_11001.proto",
"repo_id": "ET",
"token_count": 555
} | 96 |
fileFormatVersion: 2
guid: edbdf76e36a24834fbc00ccc22cec493
folderAsset: yes
timeCreated: 1506157957
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Res/Unit/Skeleton.meta/0 | {
"file_path": "ET/Unity/Assets/Res/Unit/Skeleton.meta",
"repo_id": "ET",
"token_count": 74
} | 97 |
fileFormatVersion: 2
guid: 595f7cae6f82a6146b20ca287fe7c859
timeCreated: 1506158117
licenseType: Free
NativeFormatImporter:
mainObjectFileID: 9100000
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Res/Unit/Skeleton/SkeletonController.controller.meta/0 | {
"file_path": "ET/Unity/Assets/Res/Unit/Skeleton/SkeletonController.controller.meta",
"repo_id": "ET",
"token_count": 83
} | 98 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.